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::{PassSegment, PassTarget, ResolvedComposite, ResolvedCompositeKind, SourceContent},
41 effect_renderer::{CompositeSampleMode, EffectRenderer, RoundedCompositeMask},
42 fixed_pipeline::FixedPipeline,
43 frame::{AdmissionGate, FrameExecutor, StageSideScratch},
44 frame_graph::{
45 BufferUpload, FrameCommandRecorder, FrameCommandStats, FrameTextureDescriptor,
46 FrameUploadAllocators, UniformUpload, UploadAllocatorId, UploadAllocatorSpec,
47 WgpuFrameGraph, WgpuFrameGraphExecutor,
48 },
49 frame_packet::{CancelReason, FramePacket, FrameSceneStorage, PresentOutcome, RenderReturns},
50 geometry::{
51 DevicePixelBounds, SegmentTransform, anchored_device_rect, axis_aligned_quad_rect,
52 canonicalize_device_coordinate, canonicalized_scaled_quad, offscreen_byte_size,
53 scaled_quad, snap_delta_for_anchor, snapped_anchor_device_origin, translate_quad,
54 translation_stable_anchored_device_pixel_bounds,
55 },
56 glyph_run::{RunGlyphScratch, RunGlyphs},
57 glyph_run_arena::{GlyphRunArena, GlyphRunSpan},
58 gpu_stats::{self, gpu_stats_enabled},
59 layer_cache::LayerCache,
60 offscreen::{COMPOSITION_BYTES_PER_PIXEL, OffscreenTarget},
61 output_conversion::OutputConverter,
62 pipeline_compiler::{CompilerSend, PipelineCompilation, PipelineCompiler},
63 record_columns::record_vertex_layouts,
64 rect_to_quad,
65 rrect_shadow::{SHADOW_QUAD_CORNERS, ShadowInstance, create_rrect_shadow_pipeline},
66 run_store::{ArenaBinding, PlacementData, RunBufferMode, RunDrawCall, RunStore},
67 scene::{
68 CompositorScene, DrawOp, DrawOpKind, ImageDraw, RunDraw, ShadowDraw, SnapAnchor, TextDraw,
69 },
70 shaders,
71 shape_pipelines::{ShapePipelineFactory, ShapePipelines},
72 shared_shader::SharedShader,
73};
74const MAX_SHADOW_SURFACE_CACHE_ITEMS: usize = 512;
75const MAX_TRANSPARENT_SOURCES: usize = 16;
76const MAX_SHADOW_SURFACE_CACHE_BYTES: u64 = 384 * 1024 * 1024;
77
78static SKIP_SHADOWS: DebugToggle = DebugToggle::new("CRANPOSE_SKIP_SHADOWS");
79
80fn skip_shadow_draws() -> bool {
81 SKIP_SHADOWS.flag()
82}
83const MAX_TEXT_IMAGE_CACHE_ITEMS: usize = 1024;
84const MAX_TEXT_GLYPH_MASK_CACHE_ITEMS: usize = 8192;
85const MAX_TEXT_GLYPH_ATLAS_ITEMS: usize = 8192;
86const MIN_TEXT_GLYPH_RUN_CACHE_ITEMS: usize = 1024;
90const MAX_TEXT_GLYPH_GPU_RUN_CACHE_ITEMS: usize = 1024;
91const TEXT_GLYPH_RUN_IDLE_FRAMES: u64 = 30;
98const RETAINED_TEXT_GLYPH_RUN_MIN_QUADS: usize = 64;
102
103const TEXT_GLYPH_ATLAS_MIN_SIZE: u32 = 512;
104const TEXT_GLYPH_ATLAS_MAX_SIZE: u32 = 4096;
105const _: () = assert!(TEXT_GLYPH_ATLAS_MAX_SIZE <= u16::MAX as u32);
106const TEXT_GLYPH_ATLAS_PADDING: u32 = 1;
107const MAX_TEXT_LINE_INDEX_CACHE_ITEMS: usize = 512;
108const MIN_MULTILINE_TEXT_LINES_FOR_CLIPPED_RASTER: usize = 2;
109
110const CACHE_MISS_WARMUP_FRAMES: u8 = 1;
111pub(crate) const CLEAR_COLOR: wgpu::Color = wgpu::Color {
112 r: cranpose_render_common::FRAME_CLEAR_COLOR[0] as f64,
113 g: cranpose_render_common::FRAME_CLEAR_COLOR[1] as f64,
114 b: cranpose_render_common::FRAME_CLEAR_COLOR[2] as f64,
115 a: cranpose_render_common::FRAME_CLEAR_COLOR[3] as f64,
116};
117const MAX_TEXTURE_CACHE_ITEMS: usize = 256;
118const MAX_IMAGE_TEXTURE_CACHE_BYTES: usize = 256 * 1024 * 1024;
119
120const DEFAULT_WGPU_RENDER_STAGE_TELEMETRY_THRESHOLD_MS: f64 = 4.0;
121
122fn wgpu_render_stage_telemetry_threshold_ms() -> Option<f64> {
123 static THRESHOLD_MS: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
124 *THRESHOLD_MS.get_or_init(|| {
125 let explicit =
126 crate::debug_toggles::debug_toggle("CRANPOSE_WGPU_RENDER_STAGE_TELEMETRY_MS")
127 .and_then(|value| value.parse::<f64>().ok())
128 .filter(|value| value.is_finite() && *value >= 0.0);
129 explicit.or_else(|| {
130 std::env::var_os("CRANPOSE_WGPU_RENDER_STAGE_TELEMETRY")
131 .is_some()
132 .then_some(DEFAULT_WGPU_RENDER_STAGE_TELEMETRY_THRESHOLD_MS)
133 })
134 })
135}
136
137pub(crate) fn instant_ms(start: Instant, end: Instant) -> f64 {
138 end.duration_since(start).as_secs_f64() * 1000.0
139}
140
141pub(crate) fn should_log_wgpu_render_stage(start: Instant, end: Instant) -> Option<f64> {
142 let threshold_ms = wgpu_render_stage_telemetry_threshold_ms()?;
143 let total_ms = instant_ms(start, end);
144 (total_ms >= threshold_ms).then_some(total_ms)
145}
146
147pub static PRESENTED_FRAMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
148
149pub fn frames_presented() -> u64 {
150 PRESENTED_FRAMES.load(std::sync::atomic::Ordering::Relaxed)
151}
152
153fn text_atlas_fallback_diag_enabled() -> bool {
154 cranpose_core::env_flag!("CRANPOSE_TEXT_ATLAS_FALLBACK_DIAG")
155}
156
157#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
158struct ShadowSurfaceCacheKey {
159 content_hash: u64,
160 pixel_size: [u32; 2],
161 root_scale_bits: u32,
162 blur_radius_bits: u32,
163}
164
165struct CachedShadowSurface {
166 target: Rc<OffscreenTarget>,
167 byte_size: u64,
168}
169
170type DeviceRect4 = (f32, f32, f32, f32);
171pub(crate) type TargetRect = (u32, u32, u32, u32);
173
174pub(crate) fn clip_scissor(
181 placement: &crate::scene::Placement,
182 root_scale: f32,
183 viewport: ViewportUniformParams,
184) -> Option<TargetRect> {
185 if !viewport.transform.is_identity() {
186 return None;
187 }
188 let [x, y, width, height] = crate::run_store::device_clip(placement, root_scale)?;
189 let columns = kept_pixels(x, x + width, viewport.offset[0], viewport.width);
190 let rows = kept_pixels(y, y + height, viewport.offset[1], viewport.height);
191 Some((
192 columns.start,
193 rows.start,
194 columns.end - columns.start,
195 rows.end - rows.start,
196 ))
197}
198
199fn kept_pixels(low: f32, high: f32, offset: f32, extent: u32) -> std::ops::Range<u32> {
203 let centre = |pixel: u32| pixel as f32 + 0.5 + offset;
204 let guess = |edge: f32| (edge - offset - 0.5).ceil().clamp(0.0, extent as f32) as u32;
205 let mut start = guess(low);
206 while start > 0 && centre(start - 1) >= low {
207 start -= 1;
208 }
209 while start < extent && centre(start) < low {
210 start += 1;
211 }
212 let mut end = guess(high).max(start);
213 while end > start && centre(end - 1) > high {
214 end -= 1;
215 }
216 while end < extent && centre(end) <= high {
217 end += 1;
218 }
219 start..end
220}
221
222pub(crate) fn intersect_target_rects(a: TargetRect, b: TargetRect) -> Option<TargetRect> {
224 let left = a.0.max(b.0);
225 let top = a.1.max(b.1);
226 let right = (a.0 + a.2).min(b.0 + b.2);
227 let bottom = (a.1 + a.3).min(b.1 + b.3);
228 (right > left && bottom > top).then(|| (left, top, right - left, bottom - top))
229}
230
231pub(crate) fn bounded_scissor(
234 scissor: (u32, u32, u32, u32),
235 bound: Option<(u32, u32, u32, u32)>,
236) -> Option<(u32, u32, u32, u32)> {
237 let Some((bx, by, bw, bh)) = bound else {
238 return Some(scissor);
239 };
240 let (x, y, width, height) = scissor;
241 let left = x.max(bx);
242 let top = y.max(by);
243 let right = (x + width).min(bx + bw);
244 let bottom = (y + height).min(by + bh);
245 (right > left && bottom > top).then(|| (left, top, right - left, bottom - top))
246}
247
248fn shared_glyph_clip(
253 glyphs: &[GlyphInstance],
254 scissor: TargetRect,
255 viewport: ViewportUniformParams,
256) -> (Option<TargetRect>, TargetRect) {
257 if glyphs.is_empty() {
258 return (Some(scissor), scissor);
259 }
260 let (mut left, mut top) = (f32::INFINITY, f32::INFINITY);
261 let (mut right, mut bottom) = (f32::NEG_INFINITY, f32::NEG_INFINITY);
262 for glyph in glyphs {
263 left = left.min(glyph.rect[0]);
264 top = top.min(glyph.rect[1]);
265 right = right.max(glyph.rect[2]);
266 bottom = bottom.max(glyph.rect[3]);
267 }
268 let left = (left - viewport.offset[0]).floor().max(0.0);
269 let top = (top - viewport.offset[1]).floor().max(0.0);
270 let right = (right - viewport.offset[0]).ceil();
271 let bottom = (bottom - viewport.offset[1]).ceil();
272 let (x, y, width, height) = scissor;
273 let inside = left >= x as f32
274 && top >= y as f32
275 && right <= (x + width) as f32
276 && bottom <= (y + height) as f32;
277 if !inside || right <= left || bottom <= top {
278 return (Some(scissor), scissor);
279 }
280 let bounds = (
281 left as u32,
282 top as u32,
283 (right - left) as u32,
284 (bottom - top) as u32,
285 );
286 (None, bounds)
287}
288
289fn intersect_device_rects(a: DeviceRect4, b: DeviceRect4) -> Option<DeviceRect4> {
290 let left = a.0.max(b.0);
291 let top = a.1.max(b.1);
292 let right = (a.0 + a.2).min(b.0 + b.2);
293 let bottom = (a.1 + a.3).min(b.1 + b.3);
294 (right > left && bottom > top).then_some((left, top, right - left, bottom - top))
295}
296
297pub(crate) fn anchored_rect_to_device(
298 rect: Rect,
299 snap_anchor: Option<SnapAnchor>,
300 root_scale: f32,
301) -> DeviceRect4 {
302 let device = anchored_device_rect(rect, snap_anchor, root_scale);
303 (device.x, device.y, device.width, device.height)
304}
305
306fn mask_rect(rect: Rect) -> [f32; 4] {
307 [rect.x, rect.y, rect.width, rect.height]
308}
309
310#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
311struct TextImageCacheKey(u64);
312
313struct CachedTextImage {
314 image: ImageBitmap,
315}
316
317#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
318struct TextGlyphRunCacheKey(u64);
319
320#[derive(Clone, Copy)]
321struct CachedTextGlyphQuad {
322 x: i32,
323 y: i32,
324 width: usize,
325 height: usize,
326 color: (f32, f32, f32, f32),
327 uv: ImageUvRect,
328}
329
330struct CachedTextGlyphRun {
331 glyphs: RunGlyphs,
334 bounds: GlyphRunBounds,
335 atlas_entries: Option<Rc<[GlyphAtlasEntry]>>,
339 atlas_generation: u64,
340 last_frame: Cell<u64>,
342}
343
344#[derive(Clone, Copy)]
347struct GlyphRunQuads<'a> {
348 glyphs: &'a RunGlyphs,
349 entries: &'a [GlyphAtlasEntry],
350 atlas_size: u32,
351 bounds: GlyphRunBounds,
352}
353
354#[derive(Clone, Copy, Debug, PartialEq)]
356struct GlyphRunBounds {
357 min: [i32; 2],
358 max: [i32; 2],
359}
360
361impl GlyphRunBounds {
362 fn of(glyphs: impl IntoIterator<Item = SoftwareGlyphAtlasPlacement>) -> Self {
363 let mut bounds = Self {
364 min: [i32::MAX; 2],
365 max: [i32::MIN; 2],
366 };
367 for glyph in glyphs {
368 let width = i32::try_from(glyph.width).unwrap_or(i32::MAX);
369 let height = i32::try_from(glyph.height).unwrap_or(i32::MAX);
370 bounds.min = [bounds.min[0].min(glyph.x), bounds.min[1].min(glyph.y)];
371 bounds.max = [
372 bounds.max[0].max(glyph.x.saturating_add(width)),
373 bounds.max[1].max(glyph.y.saturating_add(height)),
374 ];
375 }
376 bounds
377 }
378
379 fn within_viewport(
382 self,
383 source_raster_rect: Rect,
384 clip: Option<Rect>,
385 viewport: ViewportUniformParams,
386 root_scale: f32,
387 ) -> bool {
388 if self.min[0] > self.max[0] || !root_scale.is_finite() || root_scale <= 0.0 {
389 return false;
390 }
391 let left = (source_raster_rect.x + self.min[0] as f32) / root_scale;
392 let top = (source_raster_rect.y + self.min[1] as f32) / root_scale;
393 let right = (source_raster_rect.x + self.max[0] as f32) / root_scale;
394 let bottom = (source_raster_rect.y + self.max[1] as f32) / root_scale;
395 let viewport_rect = viewport.scene_rect(root_scale);
396 let visible = match clip {
397 Some(clip) => clip.intersect(viewport_rect),
398 None => Some(viewport_rect),
399 };
400 visible
401 .is_some_and(|visible| visible.contains(left, top) && visible.contains(right, bottom))
402 }
403}
404
405struct TextGlyphRunLookup {
407 glyphs: RunGlyphs,
408 bounds: GlyphRunBounds,
409 cached: bool,
412 entries: Option<Rc<[GlyphAtlasEntry]>>,
414}
415
416struct TextGlyphRunDraw<'a> {
418 text_draw: &'a TextDraw,
419 raster_rect: Rect,
420 run_key: TextGlyphRunCacheKey,
421 run: TextGlyphRunLookup,
422}
423
424fn log_text_atlas_fallback(text_draw: &TextDraw) {
427 if !text_atlas_fallback_diag_enabled() {
428 return;
429 }
430 let preview: String = text_draw.text.text().chars().take(96).collect();
431 log::warn!(
432 "[text-atlas-fallback] node={:?} spans={} links={} text_len={} preview={:?} span_style={:?} paragraph_style={:?}",
433 text_draw.node_id,
434 text_draw.text.span_styles().len(),
435 text_draw.text.links().len(),
436 text_draw.text.text().len(),
437 preview,
438 text_draw.text_style.span_style,
439 text_draw.text_style.paragraph_style,
440 );
441}
442
443impl GlyphRunQuads<'_> {
444 fn len(&self) -> usize {
445 self.entries.len()
446 }
447
448 fn iter(&self) -> impl Iterator<Item = CachedTextGlyphQuad> + '_ {
449 self.glyphs
450 .iter()
451 .zip(self.entries)
452 .map(|(glyph, entry)| cached_text_glyph_quad(&glyph, *entry, self.atlas_size))
453 }
454}
455
456struct CachedGpuTextGlyphRun {
457 span: GlyphRunSpan,
458 atlas_generation: u64,
459 last_frame: Cell<u64>,
462}
463
464#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
465struct TextLineIndexCacheKey(usize);
466
467struct CachedTextLineIndex {
468 text: std::sync::Weak<cranpose_ui::text::RenderString>,
469 len: usize,
470 starts: Rc<[usize]>,
471}
472
473struct TextLineIndexCache {
474 entries: BoundedLruCache<TextLineIndexCacheKey, CachedTextLineIndex>,
475}
476
477impl TextLineIndexCache {
478 fn new(capacity: usize) -> Self {
479 Self {
480 entries: BoundedLruCache::with_capacity_at_least_one(capacity),
481 }
482 }
483
484 fn line_starts(&mut self, text: &Arc<cranpose_ui::text::RenderString>) -> Rc<[usize]> {
485 let key = TextLineIndexCacheKey(Arc::as_ptr(text) as usize);
486 if let Some(cached) = self.entries.get(&key)
487 && cached.len == text.text().len()
488 && cached
489 .text
490 .upgrade()
491 .is_some_and(|cached_text| Arc::ptr_eq(&cached_text, text))
492 {
493 return cached.starts.clone();
494 }
495
496 let starts = Rc::<[usize]>::from(line_start_offsets(text.text()));
497 self.entries.put(
498 key,
499 CachedTextLineIndex {
500 text: Arc::downgrade(text),
501 len: text.text().len(),
502 starts: starts.clone(),
503 },
504 );
505 starts
506 }
507}
508
509#[derive(Default)]
510struct DeviceErrorSentry {
511 errors: std::sync::atomic::AtomicU64,
512 poisoned: std::sync::atomic::AtomicBool,
513}
514
515impl DeviceErrorSentry {
516 fn record(&self, error: &wgpu::Error) {
517 use std::sync::atomic::Ordering;
518 self.poisoned.store(true, Ordering::Release);
519 let count = self.errors.fetch_add(1, Ordering::Relaxed) + 1;
520 if count.is_power_of_two() {
521 log::error!("[gpu-device] uncaptured wgpu error #{count}: {error}");
522 }
523 }
524
525 fn take_poison(&self) -> bool {
526 self.poisoned
527 .swap(false, std::sync::atomic::Ordering::AcqRel)
528 }
529
530 fn error_count(&self) -> u64 {
531 self.errors.load(std::sync::atomic::Ordering::Relaxed)
532 }
533}
534
535fn is_blend_mode_supported(mode: BlendMode) -> bool {
536 matches!(
537 mode,
538 BlendMode::Src | BlendMode::SrcOver | BlendMode::DstOut
539 )
540}
541
542pub(crate) fn blend_state_for_mode(mode: BlendMode) -> wgpu::BlendState {
543 match mode {
544 BlendMode::Src => wgpu::BlendState::REPLACE,
545 BlendMode::DstOut => wgpu::BlendState {
546 color: wgpu::BlendComponent {
547 src_factor: wgpu::BlendFactor::Zero,
548 dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
549 operation: wgpu::BlendOperation::Add,
550 },
551 alpha: wgpu::BlendComponent {
552 src_factor: wgpu::BlendFactor::Zero,
553 dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
554 operation: wgpu::BlendOperation::Add,
555 },
556 },
557 _ => wgpu::BlendState::ALPHA_BLENDING,
558 }
559}
560
561pub(crate) fn supported_blend_mode(mode: BlendMode) -> BlendMode {
562 if is_blend_mode_supported(mode) {
563 return mode;
564 }
565
566 BlendMode::SrcOver
567}
568
569pub(crate) fn hash_f32_for_cache<H: Hasher>(value: f32, state: &mut H) {
570 value.to_bits().hash(state);
571}
572
573fn hash_text_raster_geometry_for_cache<H: Hasher>(
574 rect: Rect,
575 static_text_motion: bool,
576 state: &mut H,
577) {
578 hash_f32_for_cache(rect.width, state);
579 hash_f32_for_cache(rect.height, state);
580 static_text_motion.hash(state);
581 if !static_text_motion {
582 hash_f32_for_cache(rect.x.fract(), state);
583 hash_f32_for_cache(rect.y.fract(), state);
584 }
585}
586
587fn hash_text_draw_for_cache<H: Hasher>(
589 text_draw: &TextDraw,
590 raster_rect: Rect,
591 text_scale: f32,
592 state: &mut H,
593) {
594 text_draw.text.render_hash().hash(state);
595 text_draw.text_style.render_hash().hash(state);
596 text_draw.color.render_hash().hash(state);
597 hash_text_gradient_phase_for_cache(text_draw, raster_rect, state);
598 text_draw.font_size.to_bits().hash(state);
599 text_scale.to_bits().hash(state);
600 text_draw.layout_options.hash(state);
601}
602
603pub(crate) fn hash_text_gradient_phase_for_cache<H: Hasher>(
604 text_draw: &TextDraw,
605 raster_rect: Rect,
606 state: &mut H,
607) {
608 if std::iter::once(&text_draw.text_style.span_style)
609 .chain(text_draw.text.span_styles().iter().map(|span| &span.item))
610 .any(|span| {
611 span.brush
612 .as_ref()
613 .is_some_and(|brush| !matches!(brush, cranpose_ui_graphics::Brush::Solid(_)))
614 })
615 {
616 for coordinate in [raster_rect.x, raster_rect.y] {
617 let phase = if coordinate >= 0.0 {
618 coordinate.rem_euclid(4.0)
619 } else {
620 coordinate
621 };
622 phase.to_bits().hash(state);
623 }
624 }
625}
626
627fn text_logical_geometry_for_draw(text_draw: &TextDraw, root_scale: f32) -> Option<(Rect, f32)> {
628 if text_draw.text.is_empty()
629 || text_draw.rect.width <= 0.0
630 || text_draw.rect.height <= 0.0
631 || !root_scale.is_finite()
632 || root_scale <= 0.0
633 {
634 return None;
635 }
636
637 let text_scale = text_draw.scale * root_scale;
638 if !text_scale.is_finite() || text_scale <= 0.0 {
639 return None;
640 }
641
642 let snap_delta = text_draw
643 .snap_anchor
644 .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
645 .unwrap_or_default();
646 let logical_rect = text_draw.rect.translate(snap_delta.x, snap_delta.y);
647 Some((logical_rect, text_scale))
648}
649
650pub(crate) fn text_raster_geometry_for_draw(
651 text_draw: &TextDraw,
652 root_scale: f32,
653) -> Option<(Rect, Rect, Option<Rect>, f32, bool)> {
654 let (logical_rect, text_scale) = text_logical_geometry_for_draw(text_draw, root_scale)?;
655 let static_text_motion = text_draw
656 .text_style
657 .paragraph_style
658 .text_motion
659 .unwrap_or(cranpose_ui::text::TextMotion::Static)
660 == cranpose_ui::text::TextMotion::Static;
661 let clip = text_draw.clip;
662 let mut raster_rect = Rect {
663 x: logical_rect.x * root_scale,
664 y: logical_rect.y * root_scale,
665 width: logical_rect.width * root_scale,
666 height: logical_rect.height * root_scale,
667 };
668 if text_draw.snap_anchor.is_some() {
669 raster_rect.x = canonicalize_device_coordinate(raster_rect.x);
670 raster_rect.y = canonicalize_device_coordinate(raster_rect.y);
671 }
672 if static_text_motion {
673 raster_rect.x = raster_rect.x.round();
674 raster_rect.y = raster_rect.y.round();
675 }
676 raster_rect.width = raster_rect.width.ceil().max(1.0);
677 raster_rect.height = raster_rect.height.ceil().max(1.0);
678 Some((
679 logical_rect,
680 raster_rect,
681 clip,
682 text_scale,
683 static_text_motion,
684 ))
685}
686
687fn text_draw_is_visible_in_viewport(
688 logical_rect: Rect,
689 clip: Option<Rect>,
690 viewport: ViewportUniformParams,
691 root_scale: f32,
692) -> bool {
693 draw_rect_is_visible_in_viewport(logical_rect, clip, viewport, root_scale)
694}
695
696fn expand_rect(rect: Rect, margin_x: f32, margin_y: f32) -> Rect {
697 Rect {
698 x: rect.x - margin_x,
699 y: rect.y - margin_y,
700 width: rect.width + margin_x * 2.0,
701 height: rect.height + margin_y * 2.0,
702 }
703}
704
705fn draw_rect_is_visible_in_viewport(
706 rect: Rect,
707 clip: Option<Rect>,
708 viewport: ViewportUniformParams,
709 root_scale: f32,
710) -> bool {
711 if !root_scale.is_finite() || root_scale <= 0.0 {
712 return false;
713 }
714 rect_is_visible_in_rect(rect, clip, viewport.scene_rect(root_scale))
715}
716
717fn rect_is_visible_in_rect(rect: Rect, clip: Option<Rect>, viewport_rect: Rect) -> bool {
718 let visible_rect = match clip {
719 Some(clip) => clip.intersect(viewport_rect),
720 None => Some(viewport_rect),
721 };
722 visible_rect.is_some_and(|visible| rect.intersect(visible).is_some())
723}
724
725fn snapped_quad_bounds(quad: [[f32; 2]; 4], anchor: Option<SnapAnchor>, root_scale: f32) -> Rect {
726 let snap_delta = anchor
727 .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
728 .unwrap_or_default();
729 quad_bounds(translate_quad(quad, snap_delta))
730}
731
732fn clipped_bounds(rect: Rect, clip: Option<Rect>) -> Option<Rect> {
735 match clip {
736 Some(clip) => rect.intersect(clip),
737 None => Some(rect),
738 }
739}
740
741pub(crate) fn text_draw_bounds(text: &TextDraw, root_scale: f32) -> Option<Rect> {
742 text_logical_geometry_for_draw(text, root_scale)
743 .and_then(|(logical_rect, _)| clipped_bounds(logical_rect, text.clip))
744}
745
746pub(crate) fn image_draw_bounds(image: &ImageDraw, root_scale: f32) -> Option<Rect> {
747 clipped_bounds(
748 snapped_quad_bounds(image.quad, image.snap_anchor, root_scale),
749 image.clip,
750 )
751}
752
753pub(crate) fn run_draw_bounds(run: &RunDraw, root_scale: f32) -> Option<Rect> {
754 let snap_delta = run
755 .placement
756 .snap_anchor
757 .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
758 .unwrap_or_default();
759 clipped_bounds(
760 run.bounds.translate(snap_delta.x, snap_delta.y),
761 run.placement.clip,
762 )
763}
764
765pub(crate) fn text_draw_is_visible_in_rect(
766 text: &TextDraw,
767 viewport_rect: Rect,
768 root_scale: f32,
769) -> bool {
770 text_draw_bounds(text, root_scale)
771 .is_some_and(|bounds| bounds.intersect(viewport_rect).is_some())
772}
773
774pub(crate) fn run_draw_is_visible_in_rect(
775 run: &RunDraw,
776 viewport_rect: Rect,
777 root_scale: f32,
778) -> bool {
779 run_draw_bounds(run, root_scale).is_some_and(|bounds| bounds.intersect(viewport_rect).is_some())
780}
781
782fn cached_text_glyph_quad(
783 glyph: &SoftwareGlyphAtlasPlacement,
784 entry: GlyphAtlasEntry,
785 atlas_size: u32,
786) -> CachedTextGlyphQuad {
787 CachedTextGlyphQuad {
788 x: glyph.x,
789 y: glyph.y,
790 width: glyph.width,
791 height: glyph.height,
792 color: (
793 glyph.color.0.clamp(0.0, 1.0),
794 glyph.color.1.clamp(0.0, 1.0),
795 glyph.color.2.clamp(0.0, 1.0),
796 glyph.color.3.clamp(0.0, 1.0),
797 ),
798 uv: glyph_atlas_uv_rect(entry, atlas_size),
799 }
800}
801
802fn cached_text_glyph_instance(
805 source_raster_rect: Rect,
806 quad: &CachedTextGlyphQuad,
807) -> Option<GlyphInstance> {
808 if quad.width == 0 || quad.height == 0 || quad.color.3 <= 0.0 {
809 return None;
810 }
811 let x0 = source_raster_rect.x + quad.x as f32;
812 let y0 = source_raster_rect.y + quad.y as f32;
813 Some(GlyphInstance {
814 rect: [x0, y0, x0 + quad.width as f32, y0 + quad.height as f32],
815 uv: [
816 quad.uv.min[0],
817 quad.uv.min[1],
818 quad.uv.max[0],
819 quad.uv.max[1],
820 ],
821 uv_bounds: quad.uv.sample_bounds,
822 color: [quad.color.0, quad.color.1, quad.color.2, quad.color.3],
823 })
824}
825
826fn cached_text_glyph_quad_logical_rect(
827 source_raster_rect: Rect,
828 quad: &CachedTextGlyphQuad,
829 root_scale: f32,
830) -> Option<Rect> {
831 if !root_scale.is_finite() || root_scale <= 0.0 {
832 return None;
833 }
834 Some(Rect {
835 x: (source_raster_rect.x + quad.x as f32) / root_scale,
836 y: (source_raster_rect.y + quad.y as f32) / root_scale,
837 width: quad.width as f32 / root_scale,
838 height: quad.height as f32 / root_scale,
839 })
840}
841
842fn cached_text_glyph_quad_is_visible_in_viewport(
843 source_raster_rect: Rect,
844 quad: &CachedTextGlyphQuad,
845 clip: Option<Rect>,
846 viewport: ViewportUniformParams,
847 root_scale: f32,
848) -> bool {
849 cached_text_glyph_quad_logical_rect(source_raster_rect, quad, root_scale)
850 .is_some_and(|rect| draw_rect_is_visible_in_viewport(rect, clip, viewport, root_scale))
851}
852
853pub(crate) fn hash_device_offset<H: Hasher>(
854 value: f32,
855 origin: f32,
856 root_scale: f32,
857 state: &mut H,
858) {
859 hash_f32_for_cache((value - origin) * root_scale, state);
860}
861
862pub(crate) fn hash_device_rect<H: Hasher>(
863 rect: Rect,
864 origin_x: f32,
865 origin_y: f32,
866 root_scale: f32,
867 state: &mut H,
868) {
869 hash_device_offset(rect.x, origin_x, root_scale, state);
870 hash_device_offset(rect.y, origin_y, root_scale, state);
871 hash_device_offset(rect.width, 0.0, root_scale, state);
872 hash_device_offset(rect.height, 0.0, root_scale, state);
873}
874
875pub(crate) fn hash_run_item_with_clip<H: Hasher>(
876 run: &RunDraw,
877 clip: Option<Rect>,
878 origin_x: f32,
879 origin_y: f32,
880 root_scale: f32,
881 state: &mut H,
882) {
883 let tables = run.tables();
884 tables.fingerprint().hash(state);
885 run.segments.start.hash(state);
886 run.segments.end.hash(state);
887 let placement = &run.placement;
888 let snap = placement
889 .snap_anchor
890 .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
891 .unwrap_or_default();
892 let offset = Point::new(placement.offset.x + snap.x, placement.offset.y + snap.y);
893 let canonicalize = placement.snap_anchor.is_some();
894 canonicalize.hash(state);
895 for segment in &tables.segments[run.segments.start as usize..run.segments.end as usize] {
896 if segment.lane != RecordLane::Shapes {
897 continue;
898 }
899 let exact_placement =
900 !canonicalize || segment.kinds & ((1u8 << FRAGMENT_KIND_ARC) | LINE_KINDS) != 0;
901 exact_placement.hash(state);
902 if exact_placement {
903 for value in [offset.x, offset.y, origin_x, origin_y, root_scale] {
904 hash_f32_for_cache(value, state);
905 }
906 continue;
907 }
908 for index in segment.start..segment.start + segment.count {
909 let record = tables
910 .shapes
911 .get(index as usize)
912 .expect("shape segment record");
913 let half_width = if record.is_stroked() {
914 record.stroke_width * 0.5
915 } else {
916 0.0
917 };
918 let [left, top, right, bottom] = crate::run_geometry::device_shape_edges(
919 record.rect,
920 half_width,
921 offset,
922 root_scale,
923 canonicalize,
924 );
925 for value in [left - origin_x, top - origin_y, right - left, bottom - top] {
926 hash_f32_for_cache(value, state);
927 }
928 }
929 }
930 let mut clipped = *placement;
931 clipped.clip = clip;
932 match crate::run_store::device_clip(&clipped, root_scale) {
933 Some([x, y, width, height]) => {
934 1u8.hash(state);
935 for value in [
936 x - origin_x,
937 y - origin_y,
938 width,
939 height,
940 placement.clip_radius * root_scale,
941 ] {
942 hash_f32_for_cache(value, state);
943 }
944 }
945 None => 0u8.hash(state),
946 }
947 if tables.segments[run.segments.start as usize..run.segments.end as usize]
948 .iter()
949 .any(|segment| segment.gradient || segment.vertex_gradient)
950 {
951 let dither = placement
952 .snap_anchor
953 .map(|anchor| snapped_anchor_device_origin(anchor, root_scale))
954 .unwrap_or_default();
955 hash_f32_for_cache(dither.x - origin_x, state);
956 hash_f32_for_cache(dither.y - origin_y, state);
957 }
958 hash_f32_for_cache(placement.alpha, state);
959 match placement.color_filter {
960 Some(filter) => {
961 1u8.hash(state);
962 filter.render_hash().hash(state);
963 }
964 None => 0u8.hash(state),
965 }
966}
967
968pub(crate) fn shadow_content_hash(shadow: &ShadowDraw, root_scale: f32) -> u64 {
969 let mut hasher = FxHasher::default();
970 let origin = shape_shadow_bounds(shadow).unwrap_or(Rect {
971 x: 0.0,
972 y: 0.0,
973 width: 0.0,
974 height: 0.0,
975 });
976 let device = anchored_device_rect(
977 origin,
978 shadow
979 .shapes
980 .as_ref()
981 .and_then(|run| run.placement.snap_anchor),
982 root_scale,
983 );
984 for run in shadow.shapes.iter().chain(&shadow.post_blur_cutouts) {
985 hash_run_item_with_clip(
986 run,
987 run.placement.clip,
988 device.x.floor(),
989 device.y.floor(),
990 root_scale,
991 &mut hasher,
992 );
993 }
994 hasher.finish()
995}
996
997fn shape_shadow_surface_cache_key(
998 shadow: &ShadowDraw,
999 device_bounds: DevicePixelBounds,
1000 pixel_radius: f32,
1001 root_scale: f32,
1002) -> Option<ShadowSurfaceCacheKey> {
1003 (root_scale.is_finite() && root_scale > 0.0).then(|| ShadowSurfaceCacheKey {
1004 content_hash: shadow_content_hash(shadow, root_scale),
1005 pixel_size: [device_bounds.width, device_bounds.height],
1006 root_scale_bits: root_scale.to_bits(),
1007 blur_radius_bits: pixel_radius.to_bits(),
1008 })
1009}
1010
1011fn shape_shadow_bounds(shadow: &ShadowDraw) -> Option<Rect> {
1012 shadow.shapes.as_ref().map(|run| run.bounds)
1013}
1014
1015pub(crate) fn shadow_draw_bounds(shadow: &ShadowDraw) -> Option<Rect> {
1016 shape_shadow_bounds(shadow)
1017 .into_iter()
1018 .chain(shadow.texts.iter().map(|text| text.rect))
1019 .reduce(|a, b| Rect {
1020 x: a.x.min(b.x),
1021 y: a.y.min(b.y),
1022 width: (a.x + a.width).max(b.x + b.width) - a.x.min(b.x),
1023 height: (a.y + a.height).max(b.y + b.height) - a.y.min(b.y),
1024 })
1025}
1026
1027fn shape_shader_source(mode: RunBufferMode) -> fn() -> Cow<'static, str> {
1029 if mode.trig_fill {
1030 || Cow::Owned(shaders::filling_shape_shader())
1031 } else if mode.storage {
1032 || Cow::Owned(shaders::storage_shape_shader())
1033 } else {
1034 || Cow::Borrowed(shaders::SHADER)
1035 }
1036}
1037
1038#[expect(clippy::too_many_arguments)]
1042pub(crate) fn create_fullscreen_strip_pipeline(
1043 device: &wgpu::Device,
1044 cache: Option<&wgpu::PipelineCache>,
1045 log_label: &str,
1046 label: &'static str,
1047 layout: &wgpu::PipelineLayout,
1048 module: &wgpu::ShaderModule,
1049 fragment_entry: &'static str,
1050 constants: &[(&str, f64)],
1051 target: wgpu::ColorTargetState,
1052) -> wgpu::RenderPipeline {
1053 create_render_pipeline_logged(
1054 device,
1055 cache,
1056 log_label,
1057 wgpu::RenderPipelineDescriptor {
1058 label: Some(label),
1059 layout: Some(layout),
1060 vertex: wgpu::VertexState {
1061 module,
1062 entry_point: Some("fullscreen_vs"),
1063 buffers: &[],
1064 compilation_options: wgpu::PipelineCompilationOptions {
1065 constants,
1066 ..wgpu::PipelineCompilationOptions::default()
1067 },
1068 },
1069 fragment: Some(wgpu::FragmentState {
1070 module,
1071 entry_point: Some(fragment_entry),
1072 targets: &[Some(target)],
1073 compilation_options: wgpu::PipelineCompilationOptions {
1074 constants,
1075 ..wgpu::PipelineCompilationOptions::default()
1076 },
1077 }),
1078 primitive: wgpu::PrimitiveState {
1079 topology: wgpu::PrimitiveTopology::TriangleStrip,
1080 strip_index_format: None,
1081 front_face: wgpu::FrontFace::Ccw,
1082 cull_mode: None,
1083 ..Default::default()
1084 },
1085 depth_stencil: None,
1086 multisample: wgpu::MultisampleState::default(),
1087 multiview_mask: None,
1088 cache: None,
1089 },
1090 )
1091}
1092
1093pub(crate) fn create_render_pipeline_logged<'a>(
1094 device: &wgpu::Device,
1095 cache: Option<&'a wgpu::PipelineCache>,
1096 tag: &str,
1097 mut descriptor: wgpu::RenderPipelineDescriptor<'a>,
1098) -> wgpu::RenderPipeline {
1099 descriptor.cache = cache;
1100 build_pipeline_logged(tag, || device.create_render_pipeline(&descriptor))
1101}
1102
1103pub(crate) fn build_pipeline_logged<T>(tag: &str, build: impl FnOnce() -> T) -> T {
1104 let started = Instant::now();
1105 let pipeline = build();
1106 log::info!(
1107 "[pipeline-create] {tag} {:.1}ms on {}",
1108 instant_ms(started, Instant::now()),
1109 std::thread::current().name().unwrap_or("unnamed thread"),
1110 );
1111 if OFF_FRAME_BUILDS.with(Cell::get) {
1112 PIPELINES_CREATED_OFF_FRAME.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1113 } else {
1114 PIPELINES_CREATED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1115 THREAD_BUILDS.with(|builds| builds.set(builds.get() + 1));
1116 }
1117 #[cfg(not(target_arch = "wasm32"))]
1118 crate::pipeline_disk_cache::note_change();
1119 pipeline
1120}
1121
1122static PIPELINES_CREATED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1131static PIPELINES_CREATED_OFF_FRAME: std::sync::atomic::AtomicU64 =
1132 std::sync::atomic::AtomicU64::new(0);
1133
1134thread_local! {
1135 static OFF_FRAME_BUILDS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1136 static THREAD_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
1138}
1139
1140#[cfg(not(target_arch = "wasm32"))]
1143fn thread_builds() -> u64 {
1144 THREAD_BUILDS.with(Cell::get)
1145}
1146
1147#[cfg(not(target_arch = "wasm32"))]
1150pub(crate) fn mark_thread_off_frame() {
1151 OFF_FRAME_BUILDS.with(|off_frame| off_frame.set(true));
1152}
1153
1154pub fn pipelines_created() -> u64 {
1155 PIPELINES_CREATED.load(std::sync::atomic::Ordering::Relaxed)
1156}
1157
1158pub fn pipelines_created_off_frame() -> u64 {
1160 PIPELINES_CREATED_OFF_FRAME.load(std::sync::atomic::Ordering::Relaxed)
1161}
1162
1163#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1164#[repr(u8)]
1165pub(crate) enum RunTier {
1166 Store = 0,
1167 Arena = 1,
1168 Either = 2,
1169}
1170
1171#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1172pub(crate) struct ShapeVariant {
1173 kinds: u8,
1174 brush: Option<u8>,
1175 solid: bool,
1176 clip: SegmentClip,
1179 interior: bool,
1180 dither: bool,
1181 ablation: ShapeAblation,
1182}
1183
1184const FLAT_FILL_ENTRIES: [[(&str, &str); 2]; 2] = [
1185 [
1186 ("vs_record_plain_fill", "fs_plain_fill"),
1187 ("vs_record_dithered_fill", "fs_dithered_fill"),
1188 ],
1189 [
1190 ("vs_record_clipped_fill", "fs_clipped_fill"),
1191 ("vs_record_solid", "fs_solid"),
1192 ],
1193];
1194
1195const SLICE_ENTRIES: [(&str, &str); 2] = [
1198 ("vs_record_slice", "fs_slice"),
1199 ("vs_record_gradient_slice", "fs_gradient_slice"),
1200];
1201
1202const ALL_SHAPE_KINDS: u8 =
1203 (1 << FRAGMENT_KIND_FILL) | (1 << FRAGMENT_KIND_STROKE) | (1 << FRAGMENT_KIND_ARC) | LINE_KINDS;
1204const LINE_KINDS: u8 = (1 << FRAGMENT_KIND_LINE) | TRAPEZOID_KIND;
1207const TRAPEZOID_KIND: u8 = 1 << FRAGMENT_KIND_TRAPEZOID;
1208
1209fn variant_kinds(kinds: u8) -> u8 {
1210 if kinds.count_ones() <= 1 {
1211 kinds
1212 } else {
1213 (ALL_SHAPE_KINDS & !LINE_KINDS) | (kinds & LINE_KINDS)
1214 }
1215}
1216
1217impl ShapeVariant {
1218 const GENERAL: Self = Self {
1221 kinds: ALL_SHAPE_KINDS & !TRAPEZOID_KIND,
1222 brush: None,
1223 solid: false,
1224 clip: SegmentClip::Tested,
1225 interior: true,
1226 dither: false,
1227 ablation: ShapeAblation {
1228 material: false,
1229 fill: false,
1230 },
1231 };
1232
1233 pub(crate) fn of_segment(
1237 segment: &RecordSegment,
1238 clip: SegmentClip,
1239 ablation: ShapeAblation,
1240 laid: bool,
1241 (flat, vertex_gradients): (bool, bool),
1242 ) -> Self {
1243 if !shape_variants_enabled() || clip == SegmentClip::Rounded {
1244 return Self {
1245 kinds: Self::GENERAL.kinds | (segment.kinds & TRAPEZOID_KIND),
1246 ablation,
1247 ..Self::GENERAL
1248 }
1249 .clipped_by(clip);
1250 }
1251 let vertex_gradients = if segment.kinds == TRAPEZOID_KIND {
1252 flat
1253 } else {
1254 vertex_gradients
1255 };
1256 let gradient = segment.gradient || (segment.vertex_gradient && !vertex_gradients);
1257 Self {
1258 kinds: variant_kinds(segment.kinds),
1259 brush: gradient
1260 .then(|| segment.uniform_brush())
1261 .flatten()
1262 .map(|brush| brush as u8),
1263 solid: !gradient,
1264 clip,
1265 interior: gradient
1266 && segment.interiors
1267 && !(laid && segment.occluders && !segment.bare_interiors),
1268 dither: segment.vertex_gradient && vertex_gradients,
1269 ablation,
1270 }
1271 }
1272
1273 fn kind(self) -> Option<u8> {
1276 (self.kinds.count_ones() == 1).then(|| match self.kinds.trailing_zeros() {
1277 FRAGMENT_KIND_TRAPEZOID => FRAGMENT_KIND_LINE as u8,
1278 kind => kind as u8,
1279 })
1280 }
1281
1282 fn entries(self, flat: bool) -> (&'static str, &'static str) {
1285 let fill = self.kind() == Some(FRAGMENT_KIND_FILL as u8);
1286 if self.rounded() {
1287 ("vs_record", "fs_main")
1288 } else if self.solid && flat && self.kinds == TRAPEZOID_KIND {
1289 SLICE_ENTRIES[usize::from(self.dither)]
1290 } else if self.solid && fill && flat {
1291 FLAT_FILL_ENTRIES[usize::from(self.clip == SegmentClip::Tested)]
1292 [usize::from(self.dither)]
1293 } else if self.solid {
1294 ("vs_record_solid", "fs_solid")
1295 } else if fill && !self.ablation.material {
1296 ("vs_record_gradient_fill", "fs_gradient_fill")
1297 } else {
1298 ("vs_record", "fs_main")
1299 }
1300 }
1301
1302 fn general(self) -> Self {
1303 Self {
1304 kinds: (ALL_SHAPE_KINDS & !LINE_KINDS) | (self.kinds & LINE_KINDS),
1305 ablation: self.ablation,
1306 ..Self::GENERAL
1307 }
1308 .clipped_by(self.clip)
1309 }
1310
1311 fn clipped_by(self, clip: SegmentClip) -> Self {
1314 if clip == SegmentClip::Rounded {
1315 Self { clip, ..self }
1316 } else {
1317 self
1318 }
1319 }
1320
1321 fn rounded(self) -> bool {
1322 self.clip == SegmentClip::Rounded
1323 }
1324
1325 fn joined(self) -> Self {
1326 if self.solid {
1327 Self {
1328 dither: true,
1329 ..self
1330 }
1331 } else {
1332 Self {
1333 interior: true,
1334 ..self
1335 }
1336 }
1337 }
1338}
1339
1340#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1344pub(crate) enum SegmentClip {
1345 Untested,
1346 Tested,
1347 Rounded,
1348}
1349
1350impl SegmentClip {
1351 pub(crate) fn of(placement: &crate::scene::Placement, scissored: bool) -> Self {
1354 if placement.clip_rounded() {
1355 Self::Rounded
1356 } else if placement.clip.is_some() && !scissored {
1357 Self::Tested
1358 } else {
1359 Self::Untested
1360 }
1361 }
1362}
1363
1364static SHAPE_VARIANTS: DebugToggle = DebugToggle::new("CRANPOSE_SHAPE_VARIANTS");
1365
1366fn shape_variants_enabled() -> bool {
1367 !SHAPE_VARIANTS.equals("0")
1368}
1369
1370#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1373pub(crate) struct PassFrame {
1374 pub(crate) size: (u32, u32),
1375 pub(crate) depth: bool,
1376}
1377
1378impl PassFrame {
1379 pub(crate) fn scissor(self, scissor: Option<(u32, u32, u32, u32)>) -> (u32, u32, u32, u32) {
1381 scissor.unwrap_or((0, 0, self.size.0, self.size.1))
1382 }
1383}
1384
1385#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1388pub(crate) enum RunStage {
1389 Interiors,
1390 Paint,
1391}
1392
1393pub(crate) const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
1395
1396#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1398pub(crate) enum ShapeDepth {
1399 Off,
1401 Tested,
1403 Interior,
1405}
1406
1407impl ShapeDepth {
1408 fn stencil_state(self) -> Option<wgpu::DepthStencilState> {
1409 let (depth_write_enabled, depth_compare) = match self {
1410 Self::Off => return None,
1411 Self::Tested => (false, wgpu::CompareFunction::Less),
1412 Self::Interior => (true, wgpu::CompareFunction::Less),
1413 };
1414 Some(wgpu::DepthStencilState {
1415 format: DEPTH_FORMAT,
1416 depth_write_enabled: Some(depth_write_enabled),
1417 depth_compare: Some(depth_compare),
1418 stencil: wgpu::StencilState::default(),
1419 bias: wgpu::DepthBiasState::default(),
1420 })
1421 }
1422}
1423
1424pub(crate) fn overlay_depth_state(depth: bool) -> Option<wgpu::DepthStencilState> {
1427 if depth {
1428 ShapeDepth::Tested.stencil_state()
1429 } else {
1430 None
1431 }
1432}
1433
1434#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1437pub(crate) enum ShapeTurns {
1438 None,
1439 All,
1440 Mixed,
1441}
1442
1443impl ShapeTurns {
1444 pub(crate) fn of(turn: SegmentTransform, mixed: bool) -> Self {
1447 if mixed {
1448 Self::Mixed
1449 } else if turn.is_identity() {
1450 Self::None
1451 } else {
1452 Self::All
1453 }
1454 }
1455
1456 fn constant(self) -> f64 {
1457 match self {
1458 Self::None => 0.0,
1459 Self::All => 1.0,
1460 Self::Mixed => 2.0,
1461 }
1462 }
1463}
1464
1465#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1466pub(crate) struct ShapePipelineKey {
1467 pub(crate) blend_mode: BlendMode,
1468 pub(crate) tier: RunTier,
1469 pub(crate) variant: ShapeVariant,
1470 pub(crate) turns: ShapeTurns,
1471 pub(crate) depth: ShapeDepth,
1472}
1473
1474#[cfg(not(target_arch = "wasm32"))]
1476#[derive(Default)]
1477struct KeyWriter {
1478 bits: u64,
1479 width: u32,
1480}
1481
1482#[cfg(not(target_arch = "wasm32"))]
1483impl KeyWriter {
1484 fn put(&mut self, value: u64, width: u32) {
1485 self.bits |= value << self.width;
1486 self.width += width;
1487 }
1488
1489 fn put_byte(&mut self, value: Option<u8>) {
1490 self.put(u64::from(value.is_some()), 1);
1491 self.put(u64::from(value.unwrap_or_default()), 8);
1492 }
1493}
1494
1495const KIND_BITS: u32 = FRAGMENT_KIND_TRAPEZOID + 1;
1498
1499struct KeyReader(u64);
1500
1501impl KeyReader {
1502 fn take(&mut self, width: u32) -> u64 {
1503 let value = self.0 & ((1 << width) - 1);
1504 self.0 >>= width;
1505 value
1506 }
1507
1508 fn take_flag(&mut self) -> bool {
1509 self.take(1) == 1
1510 }
1511
1512 fn take_byte(&mut self) -> Option<u8> {
1513 let present = self.take_flag();
1514 let value = u8::try_from(self.take(8)).ok()?;
1515 present.then_some(value)
1516 }
1517
1518 fn take_kinds(&mut self) -> Option<u8> {
1519 u8::try_from(self.take(KIND_BITS))
1520 .ok()
1521 .filter(|kinds| *kinds != 0)
1522 }
1523}
1524
1525impl ShapePipelineKey {
1526 #[cfg(not(target_arch = "wasm32"))]
1527 pub(crate) const DISK_LAYOUT: [u8; 8] = *b"CPKEY003";
1528
1529 #[cfg(not(target_arch = "wasm32"))]
1532 pub(crate) fn to_bits(self) -> u64 {
1533 let mut bits = KeyWriter::default();
1534 bits.put(self.blend_mode as u64, 5);
1535 bits.put(self.tier as u64, 2);
1536 let variant = self.variant;
1537 bits.put(u64::from(variant.kinds), KIND_BITS);
1538 bits.put_byte(variant.brush);
1539 bits.put(u64::from(variant.solid), 1);
1540 bits.put(
1541 match variant.clip {
1542 SegmentClip::Untested => 0,
1543 SegmentClip::Tested => 1,
1544 SegmentClip::Rounded => 2,
1545 },
1546 2,
1547 );
1548 bits.put(u64::from(variant.interior), 1);
1549 bits.put(u64::from(variant.dither), 1);
1550 bits.put(u64::from(variant.ablation.material), 1);
1551 bits.put(u64::from(variant.ablation.fill), 1);
1552 bits.put(
1553 match self.turns {
1554 ShapeTurns::None => 0,
1555 ShapeTurns::All => 1,
1556 ShapeTurns::Mixed => 2,
1557 },
1558 2,
1559 );
1560 bits.put(
1561 match self.depth {
1562 ShapeDepth::Off => 0,
1563 ShapeDepth::Tested => 1,
1564 ShapeDepth::Interior => 2,
1565 },
1566 2,
1567 );
1568 bits.bits
1569 }
1570
1571 pub(crate) fn from_bits(packed: u64) -> Option<Self> {
1574 let mut bits = KeyReader(packed);
1575 let blend_mode = *BlendMode::ALL.get(usize::try_from(bits.take(5)).ok()?)?;
1576 let tier = match bits.take(2) {
1577 0 => RunTier::Store,
1578 1 => RunTier::Arena,
1579 2 => RunTier::Either,
1580 _ => return None,
1581 };
1582 let kinds = bits.take_kinds()?;
1583 let brush = bits.take_byte();
1584 let solid = bits.take_flag();
1585 let clip = match bits.take(2) {
1586 0 => SegmentClip::Untested,
1587 1 => SegmentClip::Tested,
1588 2 => SegmentClip::Rounded,
1589 _ => return None,
1590 };
1591 let interior = bits.take_flag();
1592 let dither = bits.take_flag();
1593 let ablation = ShapeAblation {
1594 material: bits.take_flag(),
1595 fill: bits.take_flag(),
1596 };
1597 let turns = match bits.take(2) {
1598 0 => ShapeTurns::None,
1599 1 => ShapeTurns::All,
1600 2 => ShapeTurns::Mixed,
1601 _ => return None,
1602 };
1603 let depth = match bits.take(2) {
1604 0 => ShapeDepth::Off,
1605 1 => ShapeDepth::Tested,
1606 2 => ShapeDepth::Interior,
1607 _ => return None,
1608 };
1609 (bits.0 == 0).then_some(Self {
1610 blend_mode,
1611 tier,
1612 variant: ShapeVariant {
1613 kinds,
1614 brush,
1615 solid,
1616 clip,
1617 interior,
1618 dither,
1619 ablation,
1620 },
1621 turns,
1622 depth,
1623 })
1624 }
1625
1626 #[cfg(test)]
1627 pub(crate) fn general_for(blend_mode: BlendMode, tier: RunTier) -> Self {
1628 Self {
1629 blend_mode,
1630 tier,
1631 variant: ShapeVariant::GENERAL,
1632 turns: ShapeTurns::None,
1633 depth: ShapeDepth::Off,
1634 }
1635 }
1636
1637 pub(crate) fn interior(self) -> Option<Self> {
1642 (self.depth == ShapeDepth::Tested
1643 && !self.variant.rounded()
1644 && self.blend_mode == BlendMode::SrcOver
1645 && !self.variant.ablation.material
1646 && !self.variant.ablation.fill)
1647 .then_some(Self {
1648 variant: self.variant.general(),
1649 depth: ShapeDepth::Interior,
1650 ..self
1651 })
1652 }
1653
1654 pub(crate) fn general(self) -> Self {
1655 Self {
1656 tier: RunTier::Either,
1657 variant: self.variant.general(),
1658 ..self
1659 }
1660 }
1661
1662 pub(crate) fn is_general(self) -> bool {
1663 self.variant == self.variant.general()
1664 }
1665
1666 pub(crate) fn joined(self) -> Self {
1667 Self {
1668 variant: self.variant.joined(),
1669 ..self
1670 }
1671 }
1672}
1673
1674pub(crate) fn create_shape_pipeline(
1675 device: &wgpu::Device,
1676 cache: Option<&wgpu::PipelineCache>,
1677 surface_format: wgpu::TextureFormat,
1678 shader: &SharedShader,
1679 key: ShapePipelineKey,
1680 mode: RunBufferMode,
1681) -> wgpu::RenderPipeline {
1682 let ShapePipelineKey {
1683 blend_mode,
1684 tier,
1685 variant,
1686 turns,
1687 depth,
1688 } = key;
1689 let constants = [
1690 ("SHAPE_KIND_FIXED", variant.kind().map_or(-1.0, f64::from)),
1691 ("SHAPE_KINDS", f64::from(variant.kinds)),
1692 ("BRUSH_KIND_FIXED", variant.brush.map_or(-1.0, f64::from)),
1693 ("SHAPE_SOLID", f64::from(u8::from(variant.solid))),
1694 (
1695 "SHAPE_CLIPPED",
1696 f64::from(u8::from(variant.clip != SegmentClip::Untested)),
1697 ),
1698 ("SHAPE_ROUNDED_CLIP", f64::from(u8::from(variant.rounded()))),
1699 (
1700 "SHAPE_INTERIOR",
1701 f64::from(u8::from(variant.interior && !variant.rounded())),
1702 ),
1703 ("SHAPE_DITHER", f64::from(u8::from(variant.dither))),
1704 ("SHAPE_TURNS", turns.constant()),
1705 ("SHAPE_TIER", f64::from(tier as u8)),
1706 ("SHAPE_DEPTH", f64::from(u8::from(depth != ShapeDepth::Off))),
1707 ("SHAPE_BANDS", f64::from(u8::from(mode.storage))),
1708 ("SHAPE_TRIG_FILLED", f64::from(u8::from(mode.trig_fill))),
1709 ("SHAPE_FLAT", f64::from(u8::from(variant.ablation.material))),
1710 ("SHAPE_DISCARD", f64::from(u8::from(variant.ablation.fill))),
1711 ];
1712 let (vertex_entry, fragment_entry) = if depth == ShapeDepth::Interior {
1713 ("vs_record_interior", "fs_interior")
1714 } else {
1715 variant.entries(turns == ShapeTurns::None)
1716 };
1717 let blend = (depth != ShapeDepth::Interior).then(|| blend_state_for_mode(blend_mode));
1718 let instance_layout = record_vertex_layouts().map(Some);
1719 let module = shader.module();
1720
1721 create_render_pipeline_logged(
1722 device,
1723 cache,
1724 &format!(
1725 "shape blend={blend_mode:?} tier={tier:?} variant={variant:?} turns={turns:?} depth={depth:?}"
1726 ),
1727 wgpu::RenderPipelineDescriptor {
1728 label: Some("Shape Pipeline"),
1729 layout: Some(shader.layout()),
1730 vertex: wgpu::VertexState {
1731 module,
1732 entry_point: Some(vertex_entry),
1733 compilation_options: wgpu::PipelineCompilationOptions {
1734 constants: &constants,
1735 ..wgpu::PipelineCompilationOptions::default()
1736 },
1737 buffers: &instance_layout,
1738 },
1739 fragment: Some(wgpu::FragmentState {
1740 module,
1741 entry_point: Some(fragment_entry),
1742 compilation_options: wgpu::PipelineCompilationOptions {
1743 constants: &constants,
1744 ..wgpu::PipelineCompilationOptions::default()
1745 },
1746 targets: &[Some(wgpu::ColorTargetState {
1747 format: surface_format,
1748 blend,
1749 write_mask: wgpu::ColorWrites::ALL,
1750 })],
1751 }),
1752 primitive: wgpu::PrimitiveState {
1753 topology: wgpu::PrimitiveTopology::TriangleList,
1754 strip_index_format: None,
1755 front_face: wgpu::FrontFace::Ccw,
1756 cull_mode: None,
1757 unclipped_depth: false,
1758 polygon_mode: wgpu::PolygonMode::Fill,
1759 conservative: false,
1760 },
1761 depth_stencil: depth.stencil_state(),
1762 multisample: wgpu::MultisampleState::default(),
1763 multiview_mask: None,
1764 cache: None,
1765 },
1766 )
1767}
1768fn create_image_pipeline(
1769 device: &wgpu::Device,
1770 cache: Option<&wgpu::PipelineCache>,
1771 surface_format: wgpu::TextureFormat,
1772 shader: &SharedShader,
1773 blend_mode: BlendMode,
1774 variant: ImageVariant,
1775) -> wgpu::RenderPipeline {
1776 let module = shader.module();
1777 let ImageVariant {
1778 depth,
1779 alpha_mask,
1780 rounded,
1781 } = variant;
1782 let (vertex_entry, fragment_entry) = match (alpha_mask, rounded) {
1783 (false, false) => ("image_vs_main", "image_fs_main"),
1784 (true, false) => ("image_vs_main", "image_mask_fs_main"),
1785 (false, true) => ("image_rounded_vs_main", "image_rounded_fs_main"),
1786 (true, true) => ("image_rounded_vs_main", "image_mask_rounded_fs_main"),
1787 };
1788 let buffers = [Some(Vertex::desc()), Some(DeviceRoundedClip::desc())];
1790 create_render_pipeline_logged(
1791 device,
1792 cache,
1793 &format!(
1794 "image blend={blend_mode:?} depth={depth} alpha_mask={alpha_mask} rounded={rounded}"
1795 ),
1796 wgpu::RenderPipelineDescriptor {
1797 label: Some("Image Pipeline"),
1798 layout: Some(shader.layout()),
1799 vertex: wgpu::VertexState {
1800 module,
1801 entry_point: Some(vertex_entry),
1802 compilation_options: wgpu::PipelineCompilationOptions::default(),
1803 buffers: if rounded { &buffers } else { &buffers[..1] },
1804 },
1805 fragment: Some(wgpu::FragmentState {
1806 module,
1807 entry_point: Some(fragment_entry),
1808 compilation_options: wgpu::PipelineCompilationOptions::default(),
1809 targets: &[Some(wgpu::ColorTargetState {
1810 format: surface_format,
1811 blend: Some(blend_state_for_mode(blend_mode)),
1812 write_mask: wgpu::ColorWrites::ALL,
1813 })],
1814 }),
1815 primitive: wgpu::PrimitiveState {
1816 topology: wgpu::PrimitiveTopology::TriangleList,
1817 strip_index_format: None,
1818 front_face: wgpu::FrontFace::Ccw,
1819 cull_mode: None,
1820 unclipped_depth: false,
1821 polygon_mode: wgpu::PolygonMode::Fill,
1822 conservative: false,
1823 },
1824 depth_stencil: overlay_depth_state(depth),
1825 multisample: wgpu::MultisampleState::default(),
1826 multiview_mask: None,
1827 cache: None,
1828 },
1829 )
1830}
1831
1832fn create_glyph_atlas_pipeline(
1833 device: &wgpu::Device,
1834 cache: Option<&wgpu::PipelineCache>,
1835 surface_format: wgpu::TextureFormat,
1836 shader: &SharedShader,
1837 (depth, quads): (bool, GlyphQuads),
1838) -> wgpu::RenderPipeline {
1839 let module = shader.module();
1840 create_render_pipeline_logged(
1841 device,
1842 cache,
1843 match (depth, quads) {
1844 (false, GlyphQuads::Plain) => "glyph-atlas",
1845 (true, GlyphQuads::Plain) => "glyph-atlas depth",
1846 (false, GlyphQuads::Aligned) => "glyph-atlas aligned",
1847 (true, GlyphQuads::Aligned) => "glyph-atlas aligned depth",
1848 (false, GlyphQuads::Turned) => "glyph-atlas turned",
1849 (true, GlyphQuads::Turned) => "glyph-atlas turned depth",
1850 },
1851 wgpu::RenderPipelineDescriptor {
1852 label: Some("Glyph Atlas Pipeline"),
1853 layout: Some(shader.layout()),
1854 vertex: wgpu::VertexState {
1855 module,
1856 entry_point: Some(match quads {
1857 GlyphQuads::Plain => "glyph_atlas_vs_main",
1858 GlyphQuads::Aligned => "glyph_atlas_aligned_vs_main",
1859 GlyphQuads::Turned => "glyph_atlas_turned_vs_main",
1860 }),
1861 compilation_options: wgpu::PipelineCompilationOptions::default(),
1862 buffers: &[Some(match quads {
1863 GlyphQuads::Turned => TurnedGlyph::desc(),
1864 GlyphQuads::Plain | GlyphQuads::Aligned => GlyphInstance::desc(),
1865 })],
1866 },
1867 fragment: Some(wgpu::FragmentState {
1868 module,
1869 entry_point: Some(match quads {
1870 GlyphQuads::Aligned => "glyph_atlas_aligned_fs_main",
1871 GlyphQuads::Plain | GlyphQuads::Turned => "glyph_atlas_fs_main",
1872 }),
1873 compilation_options: wgpu::PipelineCompilationOptions::default(),
1874 targets: &[Some(wgpu::ColorTargetState {
1875 format: surface_format,
1876 blend: Some(blend_state_for_mode(BlendMode::SrcOver)),
1877 write_mask: wgpu::ColorWrites::ALL,
1878 })],
1879 }),
1880 primitive: wgpu::PrimitiveState {
1881 topology: wgpu::PrimitiveTopology::TriangleStrip,
1882 strip_index_format: None,
1883 front_face: wgpu::FrontFace::Ccw,
1884 cull_mode: None,
1885 unclipped_depth: false,
1886 polygon_mode: wgpu::PolygonMode::Fill,
1887 conservative: false,
1888 },
1889 depth_stencil: overlay_depth_state(depth),
1890 multisample: wgpu::MultisampleState::default(),
1891 multiview_mask: None,
1892 cache: None,
1893 },
1894 )
1895}
1896
1897#[repr(C)]
1898#[derive(Copy, Clone, Debug, Pod, Zeroable)]
1899pub(crate) struct Vertex {
1900 position: [f32; 2],
1901 color: [f32; 4],
1902 uv: [f32; 2],
1903 uv_bounds: [f32; 4],
1904}
1905
1906impl Vertex {
1907 const ATTRIBS: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![
1908 0 => Float32x2,
1909 1 => Float32x4,
1910 2 => Float32x2,
1911 3 => Float32x4,
1912 ];
1913
1914 fn desc() -> wgpu::VertexBufferLayout<'static> {
1915 wgpu::VertexBufferLayout {
1916 array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
1917 step_mode: wgpu::VertexStepMode::Vertex,
1918 attributes: &Self::ATTRIBS,
1919 }
1920 }
1921}
1922
1923const GLYPH_QUAD_CORNERS: u32 = 4;
1926
1927#[repr(C)]
1930#[derive(Copy, Clone, Debug, PartialEq, Pod, Zeroable)]
1931pub(crate) struct GlyphInstance {
1932 rect: [f32; 4],
1933 uv: [f32; 4],
1934 uv_bounds: [f32; 4],
1935 color: [f32; 4],
1936}
1937
1938impl GlyphInstance {
1939 const ATTRIBS: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![
1940 0 => Float32x4,
1941 1 => Float32x4,
1942 2 => Float32x4,
1943 3 => Float32x4
1944 ];
1945
1946 fn desc() -> wgpu::VertexBufferLayout<'static> {
1947 wgpu::VertexBufferLayout {
1948 array_stride: std::mem::size_of::<GlyphInstance>() as wgpu::BufferAddress,
1949 step_mode: wgpu::VertexStepMode::Instance,
1950 attributes: &Self::ATTRIBS,
1951 }
1952 }
1953
1954 pub(crate) fn clipped_to(self, edges: [f32; 4]) -> Option<Self> {
1958 let [x0, y0, x1, y1] = self.rect;
1959 let rect = [
1960 x0.max(edges[0]),
1961 y0.max(edges[1]),
1962 x1.min(edges[2]),
1963 y1.min(edges[3]),
1964 ];
1965 if rect[2] <= rect[0] || rect[3] <= rect[1] {
1966 return None;
1967 }
1968 if rect == self.rect {
1969 return Some(self);
1970 }
1971 let [u0, v0, u1, v1] = self.uv;
1972 let u = |x: f32| u0 + (x - x0) / (x1 - x0) * (u1 - u0);
1973 let v = |y: f32| v0 + (y - y0) / (y1 - y0) * (v1 - v0);
1974 Some(Self {
1975 rect,
1976 uv: [u(rect[0]), v(rect[1]), u(rect[2]), v(rect[3])],
1977 ..self
1978 })
1979 }
1980}
1981
1982#[inline]
1985fn for_each_visible_glyph(
1986 source_raster_rect: Rect,
1987 quads: GlyphRunQuads<'_>,
1988 (clip, cut): (Option<Rect>, Option<[f32; 4]>),
1989 viewport: ViewportUniformParams,
1990 root_scale: f32,
1991 mut sink: impl FnMut(GlyphInstance),
1992) {
1993 let whole_run_visible =
1994 quads
1995 .bounds
1996 .within_viewport(source_raster_rect, clip, viewport, root_scale);
1997 for quad in quads.iter() {
1998 if !whole_run_visible
1999 && !cached_text_glyph_quad_is_visible_in_viewport(
2000 source_raster_rect,
2001 &quad,
2002 clip,
2003 viewport,
2004 root_scale,
2005 )
2006 {
2007 continue;
2008 }
2009 let Some(glyph) = cached_text_glyph_instance(source_raster_rect, &quad) else {
2010 continue;
2011 };
2012 let glyph = match cut {
2013 Some(edges) => glyph.clipped_to(edges),
2014 None => Some(glyph),
2015 };
2016 if let Some(glyph) = glyph {
2017 sink(glyph);
2018 }
2019 }
2020}
2021
2022#[repr(C)]
2026#[derive(Copy, Clone, Debug, PartialEq, Pod, Zeroable)]
2027pub(crate) struct TurnedGlyph {
2028 glyph: GlyphInstance,
2029 turn: [f32; 4],
2031 translation: [f32; 4],
2033}
2034
2035impl TurnedGlyph {
2036 const ATTRIBS: [wgpu::VertexAttribute; 6] = wgpu::vertex_attr_array![
2037 0 => Float32x4,
2038 1 => Float32x4,
2039 2 => Float32x4,
2040 3 => Float32x4,
2041 4 => Float32x4,
2042 5 => Float32x4
2043 ];
2044
2045 pub(crate) fn new(glyph: GlyphInstance, turn: SegmentTransform) -> Self {
2046 let (linear, [x, y], _) = turn.uniform_parts();
2047 Self {
2048 glyph,
2049 turn: linear,
2050 translation: [x, y, 0.0, 0.0],
2051 }
2052 }
2053
2054 fn desc() -> wgpu::VertexBufferLayout<'static> {
2055 wgpu::VertexBufferLayout {
2056 array_stride: std::mem::size_of::<TurnedGlyph>() as wgpu::BufferAddress,
2057 step_mode: wgpu::VertexStepMode::Instance,
2058 attributes: &Self::ATTRIBS,
2059 }
2060 }
2061}
2062
2063#[derive(Default)]
2066pub(crate) struct GlyphInstances {
2067 pub(crate) plain: Vec<GlyphInstance>,
2068 pub(crate) turned: Vec<TurnedGlyph>,
2069}
2070
2071impl GlyphInstances {
2072 pub(crate) fn clear(&mut self) {
2073 self.plain.clear();
2074 self.turned.clear();
2075 }
2076
2077 fn lens(&self) -> (usize, usize) {
2078 (self.plain.len(), self.turned.len())
2079 }
2080
2081 fn len_of(&self, turned: bool) -> usize {
2083 if turned {
2084 self.turned.len()
2085 } else {
2086 self.plain.len()
2087 }
2088 }
2089
2090 fn draw_clip(
2093 &self,
2094 (range, turned): (std::ops::Range<usize>, bool),
2095 scissor: TargetRect,
2096 viewport: ViewportUniformParams,
2097 ) -> (Option<TargetRect>, TargetRect) {
2098 if turned {
2099 (None, scissor)
2100 } else {
2101 shared_glyph_clip(&self.plain[range], scissor, viewport)
2102 }
2103 }
2104
2105 fn truncate(&mut self, (plain, turned): (usize, usize)) {
2106 self.plain.truncate(plain);
2107 self.turned.truncate(turned);
2108 }
2109}
2110
2111fn glyph_clip_edges(clip: Rect, root_scale: f32) -> [f32; 4] {
2114 [
2115 canonicalize_device_coordinate(clip.x * root_scale),
2116 canonicalize_device_coordinate(clip.y * root_scale),
2117 canonicalize_device_coordinate((clip.x + clip.width) * root_scale),
2118 canonicalize_device_coordinate((clip.y + clip.height) * root_scale),
2119 ]
2120}
2121
2122fn glyph_cut_edges(
2131 clip: Option<Rect>,
2132 scissor: TargetRect,
2133 viewport: ViewportUniformParams,
2134 root_scale: f32,
2135) -> Option<[f32; 4]> {
2136 if !viewport.transform.is_identity() {
2137 return clip.map(|clip| glyph_clip_edges(clip, root_scale));
2138 }
2139 let (x, y, width, height) = scissor;
2140 let [offset_x, offset_y] = viewport.offset;
2141 Some([
2142 x as f32 + offset_x,
2143 y as f32 + offset_y,
2144 (x + width) as f32 + offset_x,
2145 (y + height) as f32 + offset_y,
2146 ])
2147}
2148
2149#[repr(C)]
2150#[derive(Copy, Clone, Debug, Pod, Zeroable)]
2151struct Uniforms {
2152 viewport: [f32; 2],
2153 viewport_offset: [f32; 2],
2154 transform: [f32; 4],
2155 translation: [f32; 2],
2156 reserved: [f32; 2],
2157 inverse: [f32; 4],
2158 origin: [f32; 2],
2159 origin_reserved: [f32; 2],
2160 placement: PlacementData,
2161}
2162
2163impl Uniforms {
2164 fn of(params: ViewportUniformParams, placement: PlacementData, tier: RunTier) -> Self {
2165 let (transform, translation, inverse) = params.transform.uniform_parts();
2166 Self {
2167 viewport: [params.width as f32, params.height as f32],
2168 viewport_offset: params.offset,
2169 transform,
2170 translation,
2171 reserved: [params.depth_base, f32::from(tier as u8)],
2172 inverse,
2173 origin: params.origin,
2174 origin_reserved: [0.0; 2],
2175 placement,
2176 }
2177 }
2178}
2179
2180static SURVIVE_GPU_ERRORS: DebugToggle = DebugToggle::new("CRANPOSE_SURVIVE_GPU_ERRORS");
2181
2182fn survive_gpu_errors_enabled() -> bool {
2183 !SURVIVE_GPU_ERRORS.equals("0")
2184}
2185
2186struct CachedImageTexture {
2187 alpha_mask: bool,
2188 _texture: wgpu::Texture,
2189 _view: wgpu::TextureView,
2190 nearest_bind_group: wgpu::BindGroup,
2191 linear_bind_group: wgpu::BindGroup,
2192 bytes: usize,
2193}
2194
2195impl CachedImageTexture {
2196 fn binding(&self, sampling: ImageSampling) -> ImageBinding {
2197 ImageBinding {
2198 bind_group: match sampling {
2199 ImageSampling::Nearest => self.nearest_bind_group.clone(),
2200 ImageSampling::Linear => self.linear_bind_group.clone(),
2201 },
2202 alpha_mask: self.alpha_mask,
2203 }
2204 }
2205}
2206
2207pub(crate) struct ImageBinding {
2211 bind_group: wgpu::BindGroup,
2212 alpha_mask: bool,
2213}
2214
2215#[derive(Clone, Copy)]
2216struct GlyphAtlasEntry {
2217 x: u16,
2218 y: u16,
2219 width: u16,
2220 height: u16,
2221}
2222
2223fn next_glyph_atlas_size(current: u32, max: u32) -> u32 {
2224 current.saturating_mul(2).clamp(1, max.max(1))
2225}
2226
2227#[derive(Clone, Copy)]
2230struct GlyphSamplers<'a> {
2231 nearest: &'a wgpu::Sampler,
2232 linear: &'a wgpu::Sampler,
2233}
2234
2235#[derive(Clone, Copy, PartialEq, Eq, Hash)]
2238struct GlyphAtlasSlotKey {
2239 glyph: SoftwareGlyphAtlasKey,
2240 luminance: TextLuminance,
2241}
2242
2243impl GlyphAtlasSlotKey {
2244 fn new(glyph: SoftwareGlyphAtlasKey, color: Color) -> Self {
2245 Self {
2246 glyph,
2247 luminance: TextLuminance::of_color(color),
2248 }
2249 }
2250}
2251
2252const RUN_ATLAS_ENTRY_SLOTS: usize = 64;
2254
2255struct RunAtlasEntries {
2260 slots: [Option<(GlyphAtlasSlotKey, GlyphAtlasEntry)>; RUN_ATLAS_ENTRY_SLOTS],
2261}
2262
2263impl RunAtlasEntries {
2264 fn new() -> Self {
2265 Self {
2266 slots: [None; RUN_ATLAS_ENTRY_SLOTS],
2267 }
2268 }
2269
2270 fn entry(
2273 &mut self,
2274 renderer: &mut GpuRenderer,
2275 glyph: &SoftwareGlyphAtlasPlacement,
2276 look_up: impl FnOnce(&mut GpuRenderer) -> Result<GlyphAtlasEntry, String>,
2277 ) -> Result<GlyphAtlasEntry, String> {
2278 let key = GlyphAtlasSlotKey::new(glyph.key, glyph.color);
2279 let slot = &mut self.slots[glyph.key.glyph_id as usize % RUN_ATLAS_ENTRY_SLOTS];
2280 if let Some((seen, entry)) = *slot
2281 && seen == key
2282 {
2283 renderer.frame_stats.record_text_glyph_atlas_hits(1);
2284 return Ok(entry);
2285 }
2286 let entry = look_up(renderer)?;
2287 *slot = Some((key, entry));
2288 Ok(entry)
2289 }
2290}
2291
2292struct TextGlyphAtlas {
2293 texture: wgpu::Texture,
2294 _view: wgpu::TextureView,
2295 texel_bind_group: Rc<wgpu::BindGroup>,
2296 filtered_bind_group: Rc<wgpu::BindGroup>,
2297 entries: BoundedLruCache<GlyphAtlasSlotKey, GlyphAtlasEntry>,
2298 generation: u64,
2299 size: u32,
2300 max_size: u32,
2301 cursor_x: u32,
2302 cursor_y: u32,
2303 row_height: u32,
2304 upload_scratch: Vec<u8>,
2305}
2306
2307impl TextGlyphAtlas {
2308 fn new(
2309 device: &wgpu::Device,
2310 image_layout: &wgpu::BindGroupLayout,
2311 samplers: GlyphSamplers<'_>,
2312 size: u32,
2313 ) -> Self {
2314 let max_size = TEXT_GLYPH_ATLAS_MAX_SIZE.min(device.limits().max_texture_dimension_2d);
2315 let size = size.clamp(TEXT_GLYPH_ATLAS_MIN_SIZE.min(max_size), max_size);
2316 let texture = Self::create_texture(device, size);
2317 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
2318 let bind = |label: &'static str, sampler: &wgpu::Sampler| {
2319 Rc::new(device.create_bind_group(&wgpu::BindGroupDescriptor {
2320 label: Some(label),
2321 layout: image_layout,
2322 entries: &[
2323 wgpu::BindGroupEntry {
2324 binding: 0,
2325 resource: wgpu::BindingResource::TextureView(&view),
2326 },
2327 wgpu::BindGroupEntry {
2328 binding: 1,
2329 resource: wgpu::BindingResource::Sampler(sampler),
2330 },
2331 ],
2332 }))
2333 };
2334 let texel_bind_group = bind("Text Glyph Atlas Bind Group", samplers.nearest);
2335 let filtered_bind_group = bind("Filtered Text Glyph Atlas Bind Group", samplers.linear);
2336 Self {
2337 texture,
2338 _view: view,
2339 texel_bind_group,
2340 filtered_bind_group,
2341 entries: BoundedLruCache::with_capacity_at_least_one(MAX_TEXT_GLYPH_ATLAS_ITEMS),
2342 generation: 0,
2343 size,
2344 max_size,
2345 cursor_x: TEXT_GLYPH_ATLAS_PADDING,
2346 cursor_y: TEXT_GLYPH_ATLAS_PADDING,
2347 row_height: 0,
2348 upload_scratch: Vec::new(),
2349 }
2350 }
2351
2352 fn create_texture(device: &wgpu::Device, size: u32) -> wgpu::Texture {
2353 device.create_texture(&wgpu::TextureDescriptor {
2354 label: Some("Text Glyph Atlas Texture"),
2355 size: wgpu::Extent3d {
2356 width: size,
2357 height: size,
2358 depth_or_array_layers: 1,
2359 },
2360 mip_level_count: 1,
2361 sample_count: 1,
2362 dimension: wgpu::TextureDimension::D2,
2363 format: wgpu::TextureFormat::R8Unorm,
2364 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2365 view_formats: &[],
2366 })
2367 }
2368
2369 fn reset(
2370 &mut self,
2371 device: &wgpu::Device,
2372 image_layout: &wgpu::BindGroupLayout,
2373 samplers: GlyphSamplers<'_>,
2374 ) {
2375 let generation = self.generation.wrapping_add(1);
2376 let grown = next_glyph_atlas_size(self.size, self.max_size);
2377 let mut next = Self::new(device, image_layout, samplers, grown);
2378 next.generation = generation;
2379 *self = next;
2380 }
2381
2382 fn bind_group(&self, transform: SegmentTransform) -> Rc<wgpu::BindGroup> {
2386 Rc::clone(if transform.is_identity() {
2387 &self.texel_bind_group
2388 } else {
2389 &self.filtered_bind_group
2390 })
2391 }
2392
2393 fn generation(&self) -> u64 {
2394 self.generation
2395 }
2396
2397 fn size(&self) -> u32 {
2398 self.size
2399 }
2400
2401 fn entry(&mut self, key: &GlyphAtlasSlotKey) -> Option<GlyphAtlasEntry> {
2402 self.entries.get(key).copied()
2403 }
2404
2405 fn allocate(&mut self, width: u32, height: u32) -> Option<GlyphAtlasEntry> {
2406 let max_extent = self.size.saturating_sub(TEXT_GLYPH_ATLAS_PADDING * 2);
2407 if width == 0 || height == 0 || width > max_extent || height > max_extent {
2408 return None;
2409 }
2410
2411 if self.cursor_x + width + TEXT_GLYPH_ATLAS_PADDING > self.size {
2412 self.cursor_x = TEXT_GLYPH_ATLAS_PADDING;
2413 self.cursor_y = self
2414 .cursor_y
2415 .saturating_add(self.row_height)
2416 .saturating_add(TEXT_GLYPH_ATLAS_PADDING);
2417 self.row_height = 0;
2418 }
2419 if self.cursor_y > self.size - height - TEXT_GLYPH_ATLAS_PADDING {
2420 return None;
2421 }
2422
2423 let entry = GlyphAtlasEntry {
2424 x: self.cursor_x as u16,
2425 y: self.cursor_y as u16,
2426 width: width as u16,
2427 height: height as u16,
2428 };
2429 self.cursor_x = self
2430 .cursor_x
2431 .saturating_add(width)
2432 .saturating_add(TEXT_GLYPH_ATLAS_PADDING);
2433 self.row_height = self.row_height.max(height);
2434 Some(entry)
2435 }
2436
2437 fn upload_glyph(
2438 &mut self,
2439 glyph: &SoftwareGlyphAtlasGlyph,
2440 queue: &wgpu::Queue,
2441 executor: &mut WgpuFrameGraphExecutor,
2442 frame_stats: &mut gpu_stats::FrameStats,
2443 ) -> Option<GlyphAtlasEntry> {
2444 let key = GlyphAtlasSlotKey::new(glyph.key, glyph.color);
2445 if let Some(entry) = self.entry(&key) {
2446 frame_stats.record_text_glyph_atlas_hits(1);
2447 return Some(entry);
2448 }
2449
2450 let width = u32::try_from(glyph.mask.width).ok()?;
2451 let height = u32::try_from(glyph.mask.height).ok()?;
2452 let entry = self.allocate(width, height)?;
2453 self.upload_scratch.clear();
2454 let correction = key.luminance.correction();
2455 self.upload_scratch.extend(
2456 glyph
2457 .mask
2458 .alpha
2459 .iter()
2460 .map(|&coverage| correction.apply(coverage)),
2461 );
2462
2463 let upload_stats = executor.upload_texture(
2464 queue,
2465 wgpu::TexelCopyTextureInfo {
2466 texture: &self.texture,
2467 mip_level: 0,
2468 origin: wgpu::Origin3d {
2469 x: u32::from(entry.x),
2470 y: u32::from(entry.y),
2471 z: 0,
2472 },
2473 aspect: wgpu::TextureAspect::All,
2474 },
2475 &self.upload_scratch,
2476 wgpu::TexelCopyBufferLayout {
2477 offset: 0,
2478 bytes_per_row: Some(width),
2479 rows_per_image: Some(height),
2480 },
2481 wgpu::Extent3d {
2482 width,
2483 height,
2484 depth_or_array_layers: 1,
2485 },
2486 );
2487 frame_stats.record_command_stats(upload_stats);
2488 frame_stats.record_text_glyph_atlas_miss(width, height);
2489 self.entries.put(key, entry);
2490 Some(entry)
2491 }
2492}
2493
2494#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2497pub(crate) struct ImageVariant {
2498 depth: bool,
2499 alpha_mask: bool,
2500 rounded: bool,
2501}
2502
2503pub(crate) struct ImageDrawCmd {
2504 index_start: u32,
2505 scissor: (u32, u32, u32, u32),
2506 image: ImageBinding,
2507 clip: Option<u32>,
2510}
2511
2512#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2517pub(crate) enum GlyphQuads {
2518 Plain,
2519 Aligned,
2520 Turned,
2521}
2522
2523impl GlyphQuads {
2524 fn turned(self) -> bool {
2525 self == Self::Turned
2526 }
2527
2528 fn plain(aligned: bool) -> Self {
2530 if aligned { Self::Aligned } else { Self::Plain }
2531 }
2532}
2533
2534fn glyph_rect_aligned(rect: [f32; 4], offset: [f32; 2]) -> bool {
2537 let whole = |value: f32| value.fract() == 0.0;
2538 whole(rect[0] - offset[0])
2539 && whole(rect[1] - offset[1])
2540 && whole(rect[2] - offset[0])
2541 && whole(rect[3] - offset[1])
2542}
2543
2544#[derive(Clone)]
2545enum GlyphDrawSource {
2546 Shared {
2547 instance_start: u32,
2548 instance_count: u32,
2549 quads: GlyphQuads,
2550 },
2551 Retained {
2552 run: Rc<CachedGpuTextGlyphRun>,
2553 uniform_slot: usize,
2554 aligned: bool,
2555 },
2556}
2557
2558#[derive(Clone)]
2559pub(crate) struct GlyphDrawCmd {
2560 atlas: Rc<wgpu::BindGroup>,
2561 source: GlyphDrawSource,
2562 scissor: Option<(u32, u32, u32, u32)>,
2565 bounds: (u32, u32, u32, u32),
2567}
2568
2569struct GlyphDraw<'a> {
2571 atlas: &'a Rc<wgpu::BindGroup>,
2572 scissor: Option<(u32, u32, u32, u32)>,
2573 step: GlyphDrawStep<'a>,
2574}
2575
2576enum GlyphDrawStep<'a> {
2577 Shared(std::ops::Range<u32>, GlyphQuads),
2579 Retained {
2580 run: &'a CachedGpuTextGlyphRun,
2581 uniform_slot: usize,
2582 aligned: bool,
2583 },
2584}
2585
2586struct GlyphDraws<'a> {
2590 cmds: &'a [GlyphDrawCmd],
2591}
2592
2593impl<'a> GlyphDraws<'a> {
2594 fn new(cmds: &'a [GlyphDrawCmd]) -> Self {
2595 Self { cmds }
2596 }
2597}
2598
2599impl<'a> Iterator for GlyphDraws<'a> {
2600 type Item = GlyphDraw<'a>;
2601
2602 fn next(&mut self) -> Option<Self::Item> {
2603 let (first, rest) = self.cmds.split_first()?;
2604 self.cmds = rest;
2605 let step = match &first.source {
2606 GlyphDrawSource::Retained {
2607 run,
2608 uniform_slot,
2609 aligned,
2610 } => GlyphDrawStep::Retained {
2611 run,
2612 uniform_slot: *uniform_slot,
2613 aligned: *aligned,
2614 },
2615 GlyphDrawSource::Shared {
2616 instance_start,
2617 instance_count,
2618 quads,
2619 } => {
2620 let mut end = instance_start + instance_count;
2621 while let Some((next, rest)) = self.cmds.split_first() {
2622 match next.source {
2623 GlyphDrawSource::Shared {
2624 instance_start,
2625 instance_count,
2626 quads: next_quads,
2627 } if instance_start == end
2628 && next_quads == *quads
2629 && next.scissor == first.scissor
2630 && Rc::ptr_eq(&next.atlas, &first.atlas) =>
2631 {
2632 end += instance_count;
2633 self.cmds = rest;
2634 }
2635 _ => break,
2636 }
2637 }
2638 GlyphDrawStep::Shared(*instance_start..end, *quads)
2639 }
2640 };
2641 Some(GlyphDraw {
2642 atlas: &first.atlas,
2643 scissor: first.scissor,
2644 step,
2645 })
2646 }
2647}
2648
2649impl GlyphDrawCmd {
2650 fn shared(
2651 (instances, quads): (std::ops::Range<usize>, GlyphQuads),
2652 scissor: Option<(u32, u32, u32, u32)>,
2653 bounds: (u32, u32, u32, u32),
2654 atlas: Rc<wgpu::BindGroup>,
2655 ) -> Self {
2656 let start = u32::try_from(instances.start).unwrap_or(u32::MAX);
2657 let end = u32::try_from(instances.end).unwrap_or(u32::MAX);
2658 Self {
2659 atlas,
2660 source: GlyphDrawSource::Shared {
2661 instance_start: start,
2662 instance_count: end.saturating_sub(start),
2663 quads,
2664 },
2665 scissor,
2666 bounds,
2667 }
2668 }
2669
2670 fn retained(
2671 (run, uniform_slot, aligned): (Rc<CachedGpuTextGlyphRun>, usize, bool),
2672 scissor: (u32, u32, u32, u32),
2673 atlas: Rc<wgpu::BindGroup>,
2674 ) -> Self {
2675 Self {
2676 atlas,
2677 source: GlyphDrawSource::Retained {
2678 run,
2679 uniform_slot,
2680 aligned,
2681 },
2682 scissor: Some(scissor),
2683 bounds: scissor,
2684 }
2685 }
2686
2687 pub(crate) fn bounds(&self) -> (u32, u32, u32, u32) {
2689 self.bounds
2690 }
2691
2692 fn turned(&self) -> Option<bool> {
2695 match self.source {
2696 GlyphDrawSource::Shared { quads, .. } => Some(quads.turned()),
2697 GlyphDrawSource::Retained { .. } => None,
2698 }
2699 }
2700}
2701
2702pub(crate) fn movable_glyph_kind<T>(
2709 draws: &[T],
2710 kind: impl Fn(&T) -> Option<bool>,
2711 bounds: impl Fn(&T) -> TargetRect,
2712) -> Option<bool> {
2713 let mut turned = 0;
2714 for draw in draws {
2715 turned += usize::from(kind(draw)?);
2716 }
2717 let changes = draws
2718 .windows(2)
2719 .filter(|pair| kind(&pair[0]) != kind(&pair[1]))
2720 .count();
2721 if changes < 2 {
2722 return None;
2723 }
2724 let fewer = turned * 2 < draws.len();
2725 [fewer, !fewer].into_iter().find(|&moved| {
2726 draws.iter().enumerate().all(|(index, draw)| {
2727 kind(draw) != Some(moved)
2728 || draws[index + 1..].iter().all(|later| {
2729 kind(later) == Some(moved)
2730 || !crate::draw_pass::target_rects_overlap(bounds(draw), bounds(later))
2731 })
2732 })
2733 })
2734}
2735
2736pub(crate) fn group_glyph_kinds(cmds: &mut [GlyphDrawCmd], moved: &mut Vec<GlyphDrawCmd>) {
2740 let Some(kind) = movable_glyph_kind(cmds, GlyphDrawCmd::turned, GlyphDrawCmd::bounds) else {
2741 return;
2742 };
2743 moved.clear();
2744 let mut kept = 0;
2745 for read in 0..cmds.len() {
2746 if cmds[read].turned() == Some(kind) {
2747 moved.push(cmds[read].clone());
2748 } else {
2749 cmds.swap(kept, read);
2750 kept += 1;
2751 }
2752 }
2753 for (slot, cmd) in cmds[kept..].iter_mut().zip(moved.drain(..)) {
2754 *slot = cmd;
2755 }
2756}
2757
2758#[derive(Clone, Copy, Debug, PartialEq)]
2759struct ImageUvRect {
2760 min: [f32; 2],
2761 max: [f32; 2],
2762 sample_bounds: [f32; 4],
2763}
2764
2765pub(crate) struct ImageSlot {
2769 vertices: BufferUpload,
2770 indices: BufferUpload,
2771 clips: Option<BufferUpload>,
2773}
2774
2775fn image_vertex_spec() -> UploadAllocatorSpec {
2776 UploadAllocatorSpec::vertex("Image Vertex Buffer", std::mem::size_of::<Vertex>() as u64)
2777}
2778
2779fn image_index_spec() -> UploadAllocatorSpec {
2780 UploadAllocatorSpec::index("Image Index Buffer", std::mem::size_of::<u32>() as u64)
2781}
2782
2783fn glyph_instance_spec() -> UploadAllocatorSpec {
2784 UploadAllocatorSpec::vertex(
2785 "Glyph Instance Buffer",
2786 std::mem::size_of::<GlyphInstance>() as u64,
2787 )
2788}
2789
2790fn turned_glyph_spec() -> UploadAllocatorSpec {
2791 UploadAllocatorSpec::vertex(
2792 "Turned Glyph Instance Buffer",
2793 std::mem::size_of::<TurnedGlyph>() as u64,
2794 )
2795}
2796
2797#[derive(Default)]
2798struct ViewportUniforms {
2799 uploads: FrameUploadAllocators,
2800 slots: Vec<UniformUpload>,
2801}
2802
2803impl ViewportUniforms {
2804 fn begin_frame(&mut self) {
2805 self.slots.clear();
2806 self.uploads.reset();
2807 }
2808
2809 fn claim(
2810 &mut self,
2811 device: &wgpu::Device,
2812 layout: &wgpu::BindGroupLayout,
2813 uniforms: &Uniforms,
2814 ) -> usize {
2815 let slot = self.slots.len();
2816 self.slots.push(self.uploads.upload_uniform(
2817 UploadAllocatorId::Viewport,
2818 UploadAllocatorSpec::uniform(
2819 "Viewport Uniform Buffer",
2820 "Viewport Uniform Bind Group",
2821 std::mem::size_of::<Uniforms>() as u64,
2822 ),
2823 device,
2824 layout,
2825 bytemuck::bytes_of(uniforms),
2826 ));
2827 slot
2828 }
2829
2830 fn bind(&self, pass: &mut wgpu::RenderPass<'_>, slot: usize) -> Result<(), String> {
2831 let uniform = self
2832 .slots
2833 .get(slot)
2834 .ok_or_else(|| "viewport uniform slot was never claimed this frame".to_string())?;
2835 pass.set_bind_group(0, &uniform.bind_group, &[uniform.offset]);
2836 Ok(())
2837 }
2838
2839 fn stage_pending(
2840 &mut self,
2841 device: &wgpu::Device,
2842 recorder: &mut impl FrameCommandRecorder,
2843 ) -> FrameCommandStats {
2844 self.uploads.stage_pending(|buffer, offset, bytes| {
2845 recorder.stage_frame_buffer_copy(device, buffer, offset, bytes)
2846 })
2847 }
2848}
2849
2850#[derive(Clone, Copy, Debug, PartialEq)]
2851pub(crate) struct ViewportUniformParams {
2852 pub(crate) width: u32,
2853 pub(crate) height: u32,
2854 pub(crate) offset: [f32; 2],
2855 pub(crate) transform: SegmentTransform,
2856 pub(crate) origin: [f32; 2],
2861 pub(crate) depth_base: f32,
2864}
2865
2866impl ViewportUniformParams {
2867 pub(crate) fn scene_rect(self, root_scale: f32) -> Rect {
2869 segment_scene_rect(
2870 self.transform,
2871 Rect {
2872 x: self.offset[0],
2873 y: self.offset[1],
2874 width: self.width as f32,
2875 height: self.height as f32,
2876 },
2877 root_scale,
2878 )
2879 }
2880}
2881
2882pub(crate) fn segment_scene_rect(
2886 transform: SegmentTransform,
2887 device: Rect,
2888 root_scale: f32,
2889) -> Rect {
2890 let device = if transform.is_identity() {
2891 device
2892 } else {
2893 transform.segment_bounds(device)
2894 };
2895 Rect {
2896 x: device.x / root_scale,
2897 y: device.y / root_scale,
2898 width: device.width / root_scale,
2899 height: device.height / root_scale,
2900 }
2901}
2902
2903pub(crate) struct StoreRunBatch {
2907 pub(crate) command: DrawCommandId,
2908 pub(crate) uniform_slot: usize,
2909 pub(crate) draws: SmallVec<[RunDrawCall; 8]>,
2910 pub(crate) clip: Option<TargetRect>,
2913}
2914
2915struct CompositionTarget {
2916 target: Rc<OffscreenTarget>,
2917 output_bind_group: wgpu::BindGroup,
2918}
2919
2920enum FrameRoot {
2923 Surface(Rc<OffscreenTarget>),
2924 Composition(CompositionTarget),
2925}
2926
2927impl FrameRoot {
2928 fn target(&self) -> &Rc<OffscreenTarget> {
2929 match self {
2930 Self::Surface(target) => target,
2931 Self::Composition(composition) => &composition.target,
2932 }
2933 }
2934
2935 fn output<'a>(
2938 &'a self,
2939 output_view: Option<&'a wgpu::TextureView>,
2940 screenshot_bind_group: Option<&'a wgpu::BindGroup>,
2941 ) -> Option<(&'a wgpu::TextureView, &'a wgpu::BindGroup)> {
2942 match self {
2943 Self::Surface(_) => None,
2944 Self::Composition(composition) => output_view.map(|view| {
2945 (
2946 view,
2947 screenshot_bind_group.unwrap_or(&composition.output_bind_group),
2948 )
2949 }),
2950 }
2951 }
2952}
2953
2954const DIRECT_SURFACE_ROOT_USAGES: wgpu::TextureUsages = wgpu::TextureUsages::RENDER_ATTACHMENT
2958 .union(wgpu::TextureUsages::COPY_SRC)
2959 .union(wgpu::TextureUsages::COPY_DST);
2960
2961pub fn presentable_root_usages(supported: wgpu::TextureUsages) -> wgpu::TextureUsages {
2965 wgpu::TextureUsages::RENDER_ATTACHMENT
2966 | (supported & (DIRECT_SURFACE_ROOT_USAGES | wgpu::TextureUsages::TEXTURE_BINDING))
2967}
2968
2969fn surface_is_direct_root(
2976 texture: &wgpu::Texture,
2977 composition_format: wgpu::TextureFormat,
2978 viewport: (u32, u32),
2979 reads_page: bool,
2980) -> bool {
2981 let usage = texture.usage();
2982 texture.format().remove_srgb_suffix() == composition_format
2983 && usage.contains(DIRECT_SURFACE_ROOT_USAGES)
2984 && (!reads_page || usage.contains(wgpu::TextureUsages::TEXTURE_BINDING))
2985 && (texture.width(), texture.height()) == viewport
2986}
2987
2988#[derive(Clone, Copy)]
2989enum OutputMode {
2990 Display,
2991 Screenshot,
2992}
2993
2994pub struct GpuRenderer {
2995 pub(crate) device: Arc<wgpu::Device>,
2996 pub(crate) queue: Arc<wgpu::Queue>,
2997 device_errors: Arc<DeviceErrorSentry>,
2998 renderer_epoch: u64,
2999 pub(crate) composition_format: wgpu::TextureFormat,
3000 #[cfg(not(target_arch = "wasm32"))]
3001 display_format: wgpu::TextureFormat,
3002 composition_target: Option<CompositionTarget>,
3003 output_converter: OutputConverter,
3004 screenshot_converter: OutputConverter,
3005 adapter_backend: wgpu::Backend,
3006 pipeline_cache: Option<wgpu::PipelineCache>,
3007 #[cfg(not(target_arch = "wasm32"))]
3008 _pipeline_cache_watcher: Option<crate::pipeline_disk_cache::PersistWatcher>,
3009 #[cfg(not(target_arch = "wasm32"))]
3012 recent_after_update: Option<Arc<crate::pipeline_records::PipelineRecords>>,
3013 recorder: crate::pipeline_recorder::PipelineRecorder,
3015 #[cfg(not(target_arch = "wasm32"))]
3018 landing: Option<Arc<crate::pipeline_compiler::Landing>>,
3019 #[cfg(not(target_arch = "wasm32"))]
3022 built_at_frame_start: u64,
3023 pub(crate) drew_placeholder: bool,
3026 shape_pipelines: ShapePipelines,
3027 image_pipeline: [FixedPipeline; 8],
3029 image_pipeline_dst_out: [FixedPipeline; 8],
3030 glyph_atlas_pipeline: [FixedPipeline; 6],
3032 rrect_shadow_pipeline: [FixedPipeline; 2],
3034 image_shader: SharedShader,
3035 glyph_atlas_shader: SharedShader,
3036 rrect_shadow_shader: SharedShader,
3037 depth_targets: crate::idle_pool::IdlePool<((u32, u32), wgpu::TextureView)>,
3041 pub(crate) surface_atlas_sizes: crate::frame::SurfaceAtlasSizes,
3043 uniform_bind_group_layout: wgpu::BindGroupLayout,
3044 image_bind_group_layout: wgpu::BindGroupLayout,
3045 image_nearest_sampler: wgpu::Sampler,
3046 image_linear_sampler: wgpu::Sampler,
3047 text_fonts: SoftwareTextFontSet,
3048 viewport_uniforms: ViewportUniforms,
3049 run_store: RunStore,
3050 image_texture_cache: BoundedLruCache<u64, CachedImageTexture>,
3051 image_texture_cache_bytes: usize,
3052 text_image_cache: BoundedLruCache<TextImageCacheKey, CachedTextImage>,
3053 text_glyph_atlas: TextGlyphAtlas,
3054 text_glyph_run_cache: BoundedLruCache<TextGlyphRunCacheKey, CachedTextGlyphRun>,
3055 text_glyph_gpu_run_cache: BoundedLruCache<TextGlyphRunCacheKey, Rc<CachedGpuTextGlyphRun>>,
3056 text_glyph_run_arena: GlyphRunArena,
3057 text_glyph_run_frame: u64,
3058 text_glyph_runs_drawn: usize,
3060 text_glyph_mask_cache: SoftwareGlyphRasterCache,
3061 text_line_index_cache: TextLineIndexCache,
3062 pub(crate) scratch_image_vertices: Vec<Vertex>,
3063 pub(crate) scratch_image_indices: Vec<u32>,
3064 pub(crate) scratch_glyph_instances: GlyphInstances,
3065 pub(crate) scratch_image_cmds: Vec<ImageDrawCmd>,
3066 pub(crate) scratch_image_clips: Vec<DeviceRoundedClip>,
3067 pub(crate) scratch_glyph_cmds: Vec<GlyphDrawCmd>,
3068 pub(crate) scratch_glyph_moved: Vec<GlyphDrawCmd>,
3069 pub(crate) scratch_shadow_instances: Vec<ShadowInstance>,
3070 pub(crate) scratch_arena_draws: Vec<RunDrawCall>,
3071 scratch_text_glyph_run: Vec<SoftwareGlyphAtlasRunGlyph>,
3072 scratch_text_glyph_entries: Vec<GlyphAtlasEntry>,
3073 run_glyph_scratch: RunGlyphScratch,
3074 frame_graph_executor: WgpuFrameGraphExecutor,
3075 pub(crate) stage_side_scratch: StageSideScratch,
3076 deferred_offscreen_releases: Vec<OffscreenTarget>,
3077 pub(crate) effect_renderer: EffectRenderer,
3078 pub(crate) layer_cache: LayerCache,
3079 pub(crate) ablation: Ablation,
3080 pub(crate) ablation_frames: u32,
3081 pub(crate) nesting_overflow_reported: bool,
3082 pub(crate) backdrop_gates: HashMap<NodeId, AdmissionGate>,
3083 pub(crate) fill_gates: HashMap<DrawCommandId, AdmissionGate>,
3084 pub(crate) effect_gates: HashMap<NodeId, AdmissionGate>,
3085 pub(crate) source_gates: HashMap<NodeId, AdmissionGate>,
3086 transparent_sources: HashMap<(u32, u32), Rc<OffscreenTarget>>,
3087 shadow_surface_cache: BoundedLruCache<ShadowSurfaceCacheKey, CachedShadowSurface>,
3088 shadow_surface_cache_bytes: u64,
3089 pub(crate) frame_stats: gpu_stats::FrameStats,
3090 last_frame_stats: Option<gpu_stats::FrameStatsSnapshot>,
3091 pending_frame_warmup_frames: u8,
3092 frame_count: u64,
3093 shader_warm_ups_queued: usize,
3095}
3096
3097pub fn frame_clear_color(transparent: bool) -> wgpu::Color {
3100 if transparent {
3101 wgpu::Color::TRANSPARENT
3102 } else {
3103 CLEAR_COLOR
3104 }
3105}
3106
3107fn image_sampler_descriptor(sampling: ImageSampling) -> wgpu::SamplerDescriptor<'static> {
3108 let filter = match sampling {
3109 ImageSampling::Nearest => wgpu::FilterMode::Nearest,
3110 ImageSampling::Linear => wgpu::FilterMode::Linear,
3111 };
3112 wgpu::SamplerDescriptor {
3113 label: Some(match sampling {
3114 ImageSampling::Nearest => "Nearest Image Sampler",
3115 ImageSampling::Linear => "Linear Image Sampler",
3116 }),
3117 address_mode_u: wgpu::AddressMode::ClampToEdge,
3118 address_mode_v: wgpu::AddressMode::ClampToEdge,
3119 address_mode_w: wgpu::AddressMode::ClampToEdge,
3120 mag_filter: filter,
3121 min_filter: filter,
3122 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
3123 ..Default::default()
3124 }
3125}
3126
3127pub(crate) struct GpuRendererInit {
3130 pub(crate) device: Arc<wgpu::Device>,
3131 pub(crate) queue: Arc<wgpu::Queue>,
3132 pub(crate) surface_format: wgpu::TextureFormat,
3133 pub(crate) adapter_backend: wgpu::Backend,
3134 pub(crate) adapter_downlevel: wgpu::DownlevelFlags,
3135 pub(crate) text_fonts: SoftwareTextFontSet,
3136 pub(crate) renderer_epoch: u64,
3137 pub(crate) pipeline_compilation: PipelineCompilation,
3138}
3139
3140impl GpuRenderer {
3141 pub fn new(init: GpuRendererInit) -> Self {
3142 let GpuRendererInit {
3143 device,
3144 queue,
3145 surface_format,
3146 adapter_backend,
3147 adapter_downlevel,
3148 text_fonts,
3149 renderer_epoch,
3150 pipeline_compilation,
3151 } = init;
3152 let display_format = surface_format;
3153 let construction_started = Instant::now();
3154 let device_errors = Arc::new(DeviceErrorSentry::default());
3155 if survive_gpu_errors_enabled() {
3156 let sentry = Arc::clone(&device_errors);
3157 device.on_uncaptured_error(Arc::new(move |error| sentry.record(&error)));
3158 }
3159 let composition_format = crate::offscreen::composition_format(display_format);
3160 device.set_device_lost_callback(|reason, message| {
3161 log::error!("[gpu-device] device lost ({reason:?}): {message}");
3162 });
3163 let mut run_store = RunStore::new(
3164 &device,
3165 RunBufferMode::for_device(&device, adapter_downlevel),
3166 );
3167 let uniform_bind_group_layout =
3168 device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3169 label: Some("Viewport Uniform Bind Group Layout"),
3170 entries: &[wgpu::BindGroupLayoutEntry {
3171 binding: 0,
3172 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
3173 ty: wgpu::BindingType::Buffer {
3174 ty: wgpu::BufferBindingType::Uniform,
3175 has_dynamic_offset: true,
3176 min_binding_size: wgpu::BufferSize::new(
3177 std::mem::size_of::<Uniforms>() as u64
3178 ),
3179 },
3180 count: None,
3181 }],
3182 });
3183 let image_bind_group_layout =
3184 device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3185 label: Some("Image Texture Bind Group Layout"),
3186 entries: &[
3187 wgpu::BindGroupLayoutEntry {
3188 binding: 0,
3189 visibility: wgpu::ShaderStages::FRAGMENT,
3190 ty: wgpu::BindingType::Texture {
3191 multisampled: false,
3192 view_dimension: wgpu::TextureViewDimension::D2,
3193 sample_type: wgpu::TextureSampleType::Float { filterable: true },
3194 },
3195 count: None,
3196 },
3197 wgpu::BindGroupLayoutEntry {
3198 binding: 1,
3199 visibility: wgpu::ShaderStages::FRAGMENT,
3200 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
3201 count: None,
3202 },
3203 ],
3204 });
3205 let image_nearest_sampler =
3206 device.create_sampler(&image_sampler_descriptor(ImageSampling::Nearest));
3207 let image_linear_sampler =
3208 device.create_sampler(&image_sampler_descriptor(ImageSampling::Linear));
3209 let text_glyph_atlas = TextGlyphAtlas::new(
3210 &device,
3211 &image_bind_group_layout,
3212 GlyphSamplers {
3213 nearest: &image_nearest_sampler,
3214 linear: &image_linear_sampler,
3215 },
3216 TEXT_GLYPH_ATLAS_MIN_SIZE,
3217 );
3218 let viewport_uniforms = ViewportUniforms::default();
3219
3220 static GLASS_MATERIAL_FOLDS: DebugToggle =
3221 DebugToggle::new("CRANPOSE_GLASS_MATERIAL_FOLDS");
3222 if GLASS_MATERIAL_FOLDS.equals("1") {
3223 cranpose_ui_graphics::set_glass_material_folds(true);
3224 } else if GLASS_MATERIAL_FOLDS.equals("0") {
3225 cranpose_ui_graphics::set_glass_material_folds(false);
3226 }
3227 log::info!(
3228 "[gpu-init] liquid glass material folds {}",
3229 if cranpose_ui_graphics::glass_material_folds_enabled() {
3230 "on: a pipeline per material's feature set"
3231 } else {
3232 "off: one pipeline per blend mode"
3233 }
3234 );
3235
3236 #[cfg(not(target_arch = "wasm32"))]
3237 let crate::pipeline_disk_cache::Loaded {
3238 cache: pipeline_cache,
3239 records,
3240 updated,
3241 holds_recorded,
3242 } = crate::pipeline_disk_cache::load(&device);
3243 #[cfg(not(target_arch = "wasm32"))]
3244 let first_screen: Vec<u64> = records
3245 .shapes
3246 .iter()
3247 .filter(|shape| shape.first_screen)
3248 .map(|shape| shape.entry)
3249 .collect();
3250 #[cfg(target_arch = "wasm32")]
3251 let (pipeline_cache, first_screen): (Option<wgpu::PipelineCache>, Vec<u64>) =
3252 (None, Vec::new());
3253 let recorder = crate::pipeline_recorder::PipelineRecorder::default();
3254 #[cfg(not(target_arch = "wasm32"))]
3255 let pipeline_cache_watcher = crate::pipeline_disk_cache::spawn_persist_watcher(
3256 pipeline_cache.clone(),
3257 Arc::clone(&records),
3258 recorder.clone(),
3259 );
3260
3261 let effects_started = Instant::now();
3262 let pipeline_compiler = PipelineCompiler::for_compilation(pipeline_compilation);
3263 let effect_renderer = EffectRenderer::new(
3264 &device,
3265 pipeline_compiler.clone(),
3266 pipeline_cache.clone(),
3267 composition_format,
3268 adapter_backend,
3269 recorder.clone(),
3270 );
3271 let output_converter = OutputConverter::new(&device, adapter_backend, display_format);
3272 let screenshot_converter =
3273 OutputConverter::new(&device, adapter_backend, wgpu::TextureFormat::Rgba8Unorm);
3274 let effects_ms = instant_ms(effects_started, Instant::now());
3275 let mut frame_graph_executor = WgpuFrameGraphExecutor::new();
3276 frame_graph_executor.init_pass_timing(&device, &queue);
3277 let shape_shader = SharedShader::new(
3278 &device,
3279 adapter_backend,
3280 "Shape Shader",
3281 shape_shader_source(run_store.mode()),
3282 &[Some(&uniform_bind_group_layout), Some(run_store.layout())],
3283 );
3284 if run_store.mode().trig_fill {
3285 let fill = ArcTrigFill::new(
3286 &device,
3287 adapter_backend,
3288 pipeline_cache.clone(),
3289 shape_shader.clone(),
3290 recorder.clone(),
3291 );
3292 if first_screen.contains(&crate::arc_trig_fill::FIRST_SCREEN_KEY) {
3293 fill.warm(&pipeline_compiler);
3294 }
3295 run_store.attach_trig_fill(fill);
3296 }
3297 let shape_pipelines = ShapePipelines::new(
3298 ShapePipelineFactory {
3299 device: Arc::clone(&device),
3300 cache: pipeline_cache.clone(),
3301 format: composition_format,
3302 shader: shape_shader,
3303 mode: run_store.mode(),
3304 },
3305 adapter_backend,
3306 &pipeline_compiler,
3307 first_screen
3308 .into_iter()
3309 .filter(|&bits| bits != crate::arc_trig_fill::FIRST_SCREEN_KEY)
3310 .filter_map(ShapePipelineKey::from_bits),
3311 recorder.clone(),
3312 );
3313 let image_layouts = [
3314 Some(&uniform_bind_group_layout),
3315 Some(&image_bind_group_layout),
3316 ];
3317 let image_shader = SharedShader::new(
3318 &device,
3319 adapter_backend,
3320 "Image Shader",
3321 || shaders::image_shader().into(),
3322 &image_layouts,
3323 );
3324 let glyph_atlas_shader = SharedShader::new(
3325 &device,
3326 adapter_backend,
3327 "Glyph Atlas Shader",
3328 || shaders::GLYPH_ATLAS_SHADER.into(),
3329 &image_layouts,
3330 );
3331 let rrect_shadow_shader = SharedShader::new(
3332 &device,
3333 adapter_backend,
3334 "Round Rect Shadow Shader",
3335 || shaders::RRECT_SHADOW_SHADER.into(),
3336 &[Some(&uniform_bind_group_layout)],
3337 );
3338
3339 let mut renderer = Self {
3340 device,
3341 queue,
3342 device_errors,
3343 renderer_epoch,
3344 composition_format,
3345 #[cfg(not(target_arch = "wasm32"))]
3346 display_format,
3347 composition_target: None,
3348 output_converter,
3349 screenshot_converter,
3350 adapter_backend,
3351 pipeline_cache,
3352 #[cfg(not(target_arch = "wasm32"))]
3353 _pipeline_cache_watcher: pipeline_cache_watcher,
3354 #[cfg(not(target_arch = "wasm32"))]
3355 recent_after_update: updated.then(|| Arc::clone(&records)),
3356 recorder,
3357 #[cfg(not(target_arch = "wasm32"))]
3358 landing: pipeline_compiler.landing(),
3359 #[cfg(not(target_arch = "wasm32"))]
3360 built_at_frame_start: 0,
3361 drew_placeholder: false,
3362 shape_pipelines,
3363 image_pipeline: [
3364 FixedPipeline::new("image/src-over"),
3365 FixedPipeline::new("image/src-over/depth"),
3366 FixedPipeline::new("image/src-over/alpha-mask"),
3367 FixedPipeline::new("image/src-over/alpha-mask/depth"),
3368 FixedPipeline::new("image/src-over/rounded"),
3369 FixedPipeline::new("image/src-over/rounded/depth"),
3370 FixedPipeline::new("image/src-over/alpha-mask/rounded"),
3371 FixedPipeline::new("image/src-over/alpha-mask/rounded/depth"),
3372 ],
3373 image_pipeline_dst_out: [
3374 FixedPipeline::new("image/dst-out"),
3375 FixedPipeline::new("image/dst-out/depth"),
3376 FixedPipeline::new("image/dst-out/alpha-mask"),
3377 FixedPipeline::new("image/dst-out/alpha-mask/depth"),
3378 FixedPipeline::new("image/dst-out/rounded"),
3379 FixedPipeline::new("image/dst-out/rounded/depth"),
3380 FixedPipeline::new("image/dst-out/alpha-mask/rounded"),
3381 FixedPipeline::new("image/dst-out/alpha-mask/rounded/depth"),
3382 ],
3383 glyph_atlas_pipeline: [
3384 FixedPipeline::new("glyph/atlas"),
3385 FixedPipeline::new("glyph/atlas/depth"),
3386 FixedPipeline::new("glyph/atlas/aligned"),
3387 FixedPipeline::new("glyph/atlas/aligned/depth"),
3388 FixedPipeline::new("glyph/atlas/turned"),
3389 FixedPipeline::new("glyph/atlas/turned/depth"),
3390 ],
3391 rrect_shadow_pipeline: [
3392 FixedPipeline::new("shadow/rrect"),
3393 FixedPipeline::new("shadow/rrect/depth"),
3394 ],
3395 image_shader,
3396 glyph_atlas_shader,
3397 rrect_shadow_shader,
3398 depth_targets: crate::idle_pool::IdlePool::default(),
3399 surface_atlas_sizes: crate::frame::SurfaceAtlasSizes::default(),
3400 uniform_bind_group_layout,
3401 image_bind_group_layout,
3402 image_nearest_sampler,
3403 image_linear_sampler,
3404 text_fonts,
3405 viewport_uniforms,
3406 run_store,
3407 image_texture_cache: BoundedLruCache::with_capacity_at_least_one(
3408 MAX_TEXTURE_CACHE_ITEMS,
3409 ),
3410 image_texture_cache_bytes: 0,
3411 text_image_cache: BoundedLruCache::with_capacity_at_least_one(
3412 MAX_TEXT_IMAGE_CACHE_ITEMS,
3413 ),
3414 text_glyph_atlas,
3415 text_glyph_run_cache: BoundedLruCache::with_capacity_at_least_one(
3416 MIN_TEXT_GLYPH_RUN_CACHE_ITEMS,
3417 ),
3418 text_glyph_runs_drawn: 0,
3419 text_glyph_gpu_run_cache: BoundedLruCache::with_capacity_at_least_one(
3420 MAX_TEXT_GLYPH_GPU_RUN_CACHE_ITEMS,
3421 ),
3422 text_glyph_run_arena: GlyphRunArena::default(),
3423 text_glyph_run_frame: 0,
3424 text_glyph_mask_cache: SoftwareGlyphRasterCache::with_capacity_at_least_one(
3425 MAX_TEXT_GLYPH_MASK_CACHE_ITEMS,
3426 ),
3427 text_line_index_cache: TextLineIndexCache::new(MAX_TEXT_LINE_INDEX_CACHE_ITEMS),
3428 scratch_image_vertices: Vec::new(),
3429 scratch_image_indices: Vec::new(),
3430 scratch_glyph_instances: GlyphInstances::default(),
3431 scratch_image_cmds: Vec::new(),
3432 scratch_image_clips: Vec::new(),
3433 scratch_glyph_cmds: Vec::new(),
3434 scratch_glyph_moved: Vec::new(),
3435 scratch_shadow_instances: Vec::new(),
3436 scratch_arena_draws: Vec::new(),
3437 scratch_text_glyph_run: Vec::new(),
3438 scratch_text_glyph_entries: Vec::new(),
3439 run_glyph_scratch: RunGlyphScratch::default(),
3440 frame_graph_executor,
3441 stage_side_scratch: StageSideScratch::default(),
3442 deferred_offscreen_releases: Vec::new(),
3443 effect_renderer,
3444 layer_cache: LayerCache::new(),
3445 ablation: Ablation::default(),
3446 ablation_frames: 0,
3447 nesting_overflow_reported: false,
3448 backdrop_gates: HashMap::default(),
3449 fill_gates: HashMap::default(),
3450 effect_gates: HashMap::default(),
3451 source_gates: HashMap::default(),
3452 transparent_sources: HashMap::default(),
3453 shadow_surface_cache: BoundedLruCache::with_capacity_at_least_one(
3454 MAX_SHADOW_SURFACE_CACHE_ITEMS,
3455 ),
3456 shadow_surface_cache_bytes: 0,
3457 frame_stats: gpu_stats::FrameStats::default(),
3458 last_frame_stats: None,
3459 pending_frame_warmup_frames: 0,
3460 frame_count: 0,
3461 shader_warm_ups_queued: 0,
3462 };
3463 #[cfg(not(target_arch = "wasm32"))]
3464 renderer.warm_first_screen(&records, holds_recorded);
3465 renderer.warm_requested_shaders();
3466 log::info!(
3467 "[gpu-init] {:?} renderer ready in {:.1} ms (effects {:.1} ms)",
3468 adapter_backend,
3469 instant_ms(construction_started, Instant::now()),
3470 effects_ms,
3471 );
3472 renderer
3473 }
3474
3475 #[cfg(not(target_arch = "wasm32"))]
3482 fn warm_first_screen(
3483 &mut self,
3484 records: &crate::pipeline_records::PipelineRecords,
3485 holds_recorded: bool,
3486 ) {
3487 self.warm_fixed_pipelines(&|label| {
3488 records
3489 .fixed
3490 .iter()
3491 .any(|fixed| fixed.first_screen && fixed.entry == label)
3492 });
3493 if holds_recorded {
3494 self.effect_renderer.trust_cached(records);
3495 }
3496 self.effect_renderer.warm_first_screen_shaders(
3497 records
3498 .shaders
3499 .iter()
3500 .filter(|shader| shader.first_screen)
3501 .map(|shader| &shader.entry),
3502 );
3503 }
3504
3505 fn ensure_shape_pipeline(&mut self, key: ShapePipelineKey, vertices: u64) {
3506 self.shape_pipelines.ensure(key, vertices);
3507 }
3508
3509 fn warm_requested_shaders(&mut self) {
3512 let requested = cranpose_ui_graphics::shader_warm_ups_after(self.shader_warm_ups_queued);
3513 if requested.is_empty() {
3514 return;
3515 }
3516 self.shader_warm_ups_queued += requested.len();
3517 self.effect_renderer.warm_shaders(&requested);
3518 }
3519
3520 #[cfg(not(target_arch = "wasm32"))]
3524 fn warm_recent(&mut self, records: &crate::pipeline_records::PipelineRecords) {
3525 self.warm_fixed_pipelines(&|label| records.fixed.iter().any(|fixed| fixed.entry == label));
3526 let shapes = records
3527 .shapes
3528 .iter()
3529 .map(|shape| shape.entry)
3530 .filter(|&bits| bits != crate::arc_trig_fill::FIRST_SCREEN_KEY)
3531 .filter_map(ShapePipelineKey::from_bits);
3532 for key in shapes {
3533 self.shape_pipelines.warm(key);
3534 }
3535 self.effect_renderer
3536 .warm_recorded_shaders(records.shaders.iter().map(|shader| &shader.entry));
3537 }
3538
3539 #[cfg(not(target_arch = "wasm32"))]
3541 fn warm_fixed_pipelines(&self, wanted: &dyn Fn(&str) -> bool) {
3542 self.effect_renderer.warm_fixed(&self.device, wanted);
3543 let warm =
3544 |pipeline: &FixedPipeline,
3545 job: &dyn Fn() -> Box<dyn FnOnce() -> wgpu::RenderPipeline + Send>| {
3546 if wanted(pipeline.label()) {
3547 pipeline.queue(
3548 self.effect_renderer.compiler(),
3549 crate::pipeline_compiler::CompileLane::WarmUp,
3550 self.adapter_backend,
3551 job(),
3552 );
3553 }
3554 };
3555 for depth in [false, true] {
3556 for (alpha_mask, rounded) in
3557 [(false, false), (true, false), (false, true), (true, true)]
3558 {
3559 let variant = ImageVariant {
3560 depth,
3561 alpha_mask,
3562 rounded,
3563 };
3564 for blend_mode in [BlendMode::SrcOver, BlendMode::DstOut] {
3565 warm(self.image_pipeline_resource(blend_mode, variant), &|| {
3566 Box::new(self.image_pipeline_job(blend_mode, variant))
3567 });
3568 }
3569 }
3570 for quads in [GlyphQuads::Plain, GlyphQuads::Aligned, GlyphQuads::Turned] {
3571 warm(self.glyph_atlas_pipeline_resource(depth, quads), &|| {
3572 Box::new(self.glyph_atlas_pipeline_job(depth, quads))
3573 });
3574 }
3575 warm(&self.rrect_shadow_pipeline[usize::from(depth)], &|| {
3576 Box::new(self.rrect_shadow_pipeline_job(depth))
3577 });
3578 }
3579 }
3580
3581 fn image_pipeline_resource(
3582 &self,
3583 blend_mode: BlendMode,
3584 variant: ImageVariant,
3585 ) -> &FixedPipeline {
3586 let pipelines = match blend_mode {
3587 BlendMode::DstOut => &self.image_pipeline_dst_out,
3588 _ => &self.image_pipeline,
3589 };
3590 &pipelines[usize::from(variant.depth)
3591 + 2 * usize::from(variant.alpha_mask)
3592 + 4 * usize::from(variant.rounded)]
3593 }
3594
3595 fn image_pipeline_job(
3596 &self,
3597 blend_mode: BlendMode,
3598 variant: ImageVariant,
3599 ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
3600 let device = Arc::clone(&self.device);
3601 let cache = self.pipeline_cache.clone();
3602 let format = self.composition_format;
3603 let shader = self.image_shader.clone();
3604 move || {
3605 create_image_pipeline(
3606 &device,
3607 cache.as_ref(),
3608 format,
3609 &shader,
3610 blend_mode,
3611 variant,
3612 )
3613 }
3614 }
3615
3616 pub(crate) fn image_pipeline(
3617 &self,
3618 blend_mode: BlendMode,
3619 variant: ImageVariant,
3620 ) -> &wgpu::RenderPipeline {
3621 self.image_pipeline_resource(blend_mode, variant).for_draw(
3622 &self.recorder,
3623 self.adapter_backend,
3624 || self.image_pipeline_job(blend_mode, variant)(),
3625 )
3626 }
3627
3628 fn glyph_atlas_pipeline_job(
3629 &self,
3630 depth: bool,
3631 quads: GlyphQuads,
3632 ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
3633 let device = Arc::clone(&self.device);
3634 let cache = self.pipeline_cache.clone();
3635 let format = self.composition_format;
3636 let shader = self.glyph_atlas_shader.clone();
3637 move || {
3638 create_glyph_atlas_pipeline(&device, cache.as_ref(), format, &shader, (depth, quads))
3639 }
3640 }
3641
3642 fn glyph_atlas_pipeline(&self, depth: bool, quads: GlyphQuads) -> &wgpu::RenderPipeline {
3645 self.glyph_atlas_pipeline_resource(depth, quads).for_draw(
3646 &self.recorder,
3647 self.adapter_backend,
3648 || self.glyph_atlas_pipeline_job(depth, quads)(),
3649 )
3650 }
3651
3652 fn rrect_shadow_pipeline_job(
3653 &self,
3654 depth: bool,
3655 ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
3656 let device = Arc::clone(&self.device);
3657 let cache = self.pipeline_cache.clone();
3658 let format = self.composition_format;
3659 let shader = self.rrect_shadow_shader.clone();
3660 move || create_rrect_shadow_pipeline(&device, cache.as_ref(), format, &shader, depth)
3661 }
3662
3663 pub(crate) fn draw_shadow_instances(
3666 &self,
3667 pass: &mut wgpu::RenderPass<'_>,
3668 buffer: &BufferUpload,
3669 uniform_slot: usize,
3670 instances: std::ops::Range<u32>,
3671 scissor: Option<(u32, u32, u32, u32)>,
3672 frame: PassFrame,
3673 ) -> Result<(), String> {
3674 let depth = frame.depth;
3675 let pipeline = self.rrect_shadow_pipeline[usize::from(depth)].for_draw(
3676 &self.recorder,
3677 self.adapter_backend,
3678 || self.rrect_shadow_pipeline_job(depth)(),
3679 );
3680 let (x, y, width, height) = frame.scissor(scissor);
3681 pass.set_scissor_rect(x, y, width, height);
3682 pass.set_pipeline(pipeline);
3683 self.viewport_uniforms.bind(pass, uniform_slot)?;
3684 pass.set_vertex_buffer(0, buffer.slice());
3685 pass.draw(0..SHADOW_QUAD_CORNERS, instances);
3686 self.frame_stats.add_draw_calls(1);
3687 Ok(())
3688 }
3689
3690 pub(crate) fn upload_shadow_instances<C: FrameCommandRecorder>(
3691 &self,
3692 recorder: &mut C,
3693 instances: &[ShadowInstance],
3694 ) -> BufferUpload {
3695 recorder.upload_buffer(
3696 UploadAllocatorSpec::vertex(
3697 "Shadow Instance Buffer",
3698 std::mem::size_of::<ShadowInstance>() as u64,
3699 ),
3700 &self.device,
3701 bytemuck::cast_slice(instances),
3702 )
3703 }
3704
3705 fn glyph_atlas_pipeline_resource(&self, depth: bool, quads: GlyphQuads) -> &FixedPipeline {
3706 let kind = match quads {
3707 GlyphQuads::Plain => 0,
3708 GlyphQuads::Aligned => 1,
3709 GlyphQuads::Turned => 2,
3710 };
3711 &self.glyph_atlas_pipeline[usize::from(depth) + 2 * kind]
3712 }
3713
3714 pub(crate) fn depth_target(&mut self, size: (u32, u32)) -> wgpu::TextureView {
3717 const KEPT_DEPTH_TARGETS: usize = 4;
3718 let view = match self.depth_targets.take(|(kept, _)| *kept == size) {
3719 Some((_, view)) => view,
3720 None => self.create_depth_target(size),
3721 };
3722 self.depth_targets
3723 .put((size, view.clone()), KEPT_DEPTH_TARGETS, u64::MAX, |_| 0);
3724 view
3725 }
3726
3727 fn create_depth_target(&self, size: (u32, u32)) -> wgpu::TextureView {
3728 let texture = self.device.create_texture(&wgpu::TextureDescriptor {
3729 label: Some("Opaque interior depth"),
3730 size: wgpu::Extent3d {
3731 width: size.0,
3732 height: size.1,
3733 depth_or_array_layers: 1,
3734 },
3735 mip_level_count: 1,
3736 sample_count: 1,
3737 dimension: wgpu::TextureDimension::D2,
3738 format: DEPTH_FORMAT,
3739 usage: if self.adapter_backend == wgpu::Backend::BrowserWebGpu {
3742 wgpu::TextureUsages::RENDER_ATTACHMENT
3743 } else {
3744 wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TRANSIENT_ATTACHMENT
3745 },
3746 view_formats: &[],
3747 });
3748 texture.create_view(&wgpu::TextureViewDescriptor::default())
3749 }
3750
3751 fn image_binding(
3754 &mut self,
3755 image: &ImageBitmap,
3756 sampling: ImageSampling,
3757 ) -> Result<ImageBinding, String> {
3758 if let Some(cached) = self.image_texture_cache.get(&image.id()) {
3759 return Ok(cached.binding(sampling));
3760 }
3761
3762 let size = wgpu::Extent3d {
3763 width: image.width(),
3764 height: image.height(),
3765 depth_or_array_layers: 1,
3766 };
3767
3768 let alpha_mask = matches!(
3769 image.format(),
3770 cranpose_ui_graphics::ImagePixelFormat::Alpha8 { .. }
3771 );
3772 let (format, bytes_per_pixel) = if alpha_mask {
3773 (wgpu::TextureFormat::R8Unorm, 1)
3774 } else {
3775 (wgpu::TextureFormat::Rgba8Unorm, 4)
3776 };
3777
3778 let texture = self.device.create_texture(&wgpu::TextureDescriptor {
3779 label: Some("Image Texture"),
3780 size,
3781 mip_level_count: 1,
3782 sample_count: 1,
3783 dimension: wgpu::TextureDimension::D2,
3784 format,
3785 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
3786 view_formats: &[],
3787 });
3788
3789 let upload_stats = self.frame_graph_executor.upload_texture(
3790 &self.queue,
3791 wgpu::TexelCopyTextureInfo {
3792 texture: &texture,
3793 mip_level: 0,
3794 origin: wgpu::Origin3d::ZERO,
3795 aspect: wgpu::TextureAspect::All,
3796 },
3797 image.pixels(),
3798 wgpu::TexelCopyBufferLayout {
3799 offset: 0,
3800 bytes_per_row: Some(bytes_per_pixel * image.width()),
3801 rows_per_image: Some(image.height()),
3802 },
3803 size,
3804 );
3805 self.frame_stats.record_command_stats(upload_stats);
3806
3807 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
3808 let nearest_bind_group = self.image_bind_group(&view, &self.image_nearest_sampler);
3809 let linear_bind_group = self.image_bind_group(&view, &self.image_linear_sampler);
3810
3811 let bytes = image.pixels().len();
3812 let cached = CachedImageTexture {
3813 alpha_mask,
3814 _texture: texture,
3815 _view: view,
3816 nearest_bind_group,
3817 linear_bind_group,
3818 bytes,
3819 };
3820 let binding = cached.binding(sampling);
3821 if let Some(replaced) = self.image_texture_cache.put(image.id(), cached) {
3822 self.image_texture_cache_bytes = self
3823 .image_texture_cache_bytes
3824 .saturating_sub(replaced.bytes);
3825 }
3826 self.image_texture_cache_bytes += bytes;
3827 while self.image_texture_cache_bytes > MAX_IMAGE_TEXTURE_CACHE_BYTES
3828 && self.image_texture_cache.len() > 1
3829 {
3830 let Some((_, evicted)) = self.image_texture_cache.pop_lru() else {
3831 break;
3832 };
3833 self.image_texture_cache_bytes =
3834 self.image_texture_cache_bytes.saturating_sub(evicted.bytes);
3835 }
3836 Ok(binding)
3837 }
3838
3839 fn image_bind_group(
3840 &self,
3841 view: &wgpu::TextureView,
3842 sampler: &wgpu::Sampler,
3843 ) -> wgpu::BindGroup {
3844 self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3845 label: Some("Image Texture Bind Group"),
3846 layout: &self.image_bind_group_layout,
3847 entries: &[
3848 wgpu::BindGroupEntry {
3849 binding: 0,
3850 resource: wgpu::BindingResource::TextureView(view),
3851 },
3852 wgpu::BindGroupEntry {
3853 binding: 1,
3854 resource: wgpu::BindingResource::Sampler(sampler),
3855 },
3856 ],
3857 })
3858 }
3859
3860 pub(crate) fn max_texture_dim(&self) -> u32 {
3861 self.effect_renderer.max_texture_dim()
3862 }
3863
3864 pub(crate) fn acquire_retained_surface(&mut self, width: u32, height: u32) -> OffscreenTarget {
3867 self.effect_renderer
3868 .acquire_offscreen(&self.device, width, height, Some(&self.frame_stats))
3869 }
3870
3871 fn frame_root(
3872 &mut self,
3873 output_mode: OutputMode,
3874 output_view: Option<&wgpu::TextureView>,
3875 output_texture: Option<&wgpu::Texture>,
3876 viewport: (u32, u32),
3877 reads_page: bool,
3878 ) -> FrameRoot {
3879 if let (OutputMode::Display, Some(view), Some(texture)) =
3880 (output_mode, output_view, output_texture)
3881 && surface_is_direct_root(texture, self.composition_format, viewport, reads_page)
3882 {
3883 return FrameRoot::Surface(Rc::new(OffscreenTarget::from_surface(
3884 texture.clone(),
3885 view.clone(),
3886 )));
3887 }
3888 FrameRoot::Composition(self.take_composition_target(viewport.0.max(1), viewport.1.max(1)))
3889 }
3890
3891 fn take_composition_target(&mut self, width: u32, height: u32) -> CompositionTarget {
3892 if let Some(target) = self.composition_target.take()
3893 && target.target.width == width
3894 && target.target.height == height
3895 {
3896 return target;
3897 }
3898 let target = Rc::new(OffscreenTarget::new(
3899 &self.device,
3900 self.composition_format,
3901 width,
3902 height,
3903 ));
3904 let output_bind_group = self.output_converter.bind_group(&self.device, &target.view);
3905 CompositionTarget {
3906 target,
3907 output_bind_group,
3908 }
3909 }
3910
3911 fn transient_offscreen_descriptor(
3912 &self,
3913 label: &'static str,
3914 width: u32,
3915 height: u32,
3916 ) -> FrameTextureDescriptor {
3917 let max_texture_dim = self.max_texture_dim();
3918 FrameTextureDescriptor::render_attachment(
3919 label,
3920 width.min(max_texture_dim),
3921 height.min(max_texture_dim),
3922 self.composition_format,
3923 )
3924 }
3925
3926 pub(crate) fn transparent_source<C: FrameCommandRecorder>(
3930 &mut self,
3931 recorder: &mut C,
3932 width: u32,
3933 height: u32,
3934 ) -> Rc<OffscreenTarget> {
3935 if let Some(source) = self.transparent_sources.get(&(width, height)) {
3936 return Rc::clone(source);
3937 }
3938 if self.transparent_sources.len() >= MAX_TRANSPARENT_SOURCES {
3939 for (_, source) in self.transparent_sources.drain() {
3940 if let Ok(target) = Rc::try_unwrap(source) {
3941 self.deferred_offscreen_releases.push(target);
3942 }
3943 }
3944 }
3945 let source = Rc::new(self.acquire_retained_surface(width, height));
3946 self.clear_target(
3947 recorder,
3948 &source.view,
3949 wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
3950 );
3951 self.transparent_sources
3952 .insert((width, height), Rc::clone(&source));
3953 source
3954 }
3955
3956 fn defer_offscreen_release(&mut self, target: OffscreenTarget) {
3957 self.deferred_offscreen_releases.push(target);
3958 }
3959
3960 fn flush_deferred_offscreen_releases(&mut self) {
3961 let layer_cache = &mut self.layer_cache;
3962 let mut retire = |gate: &mut AdmissionGate| {
3963 let seen = gate.end_frame();
3964 if !seen && let Some(dead) = gate.dead_entry() {
3965 layer_cache.remove(&dead);
3966 }
3967 seen
3968 };
3969 self.backdrop_gates.retain(|_, gate| retire(gate));
3970 self.fill_gates.retain(|_, gate| retire(gate));
3971 self.effect_gates.retain(|_, gate| retire(gate));
3972 self.source_gates.retain(|_, gate| retire(gate));
3973 for target in self.deferred_offscreen_releases.drain(..) {
3974 self.effect_renderer.release_offscreen(target);
3975 }
3976 self.layer_cache.end_frame();
3977 for (transient, target) in self.layer_cache.take_released() {
3978 match transient {
3979 Some(descriptor) => self
3980 .frame_graph_executor
3981 .return_cached_transient(descriptor, target),
3982 None => self.effect_renderer.release_offscreen(target),
3983 }
3984 }
3985 self.effect_renderer.end_offscreen_frame();
3986 self.frame_graph_executor.end_transient_frame();
3987 self.depth_targets.end_frame();
3988 self.surface_atlas_sizes.end_frame();
3989 }
3990
3991 fn insert_cached_shadow_surface(
3992 &mut self,
3993 key: ShadowSurfaceCacheKey,
3994 target: Rc<OffscreenTarget>,
3995 ) {
3996 let byte_size = offscreen_byte_size(target.width, target.height);
3997 while self.shadow_surface_cache_bytes + byte_size > MAX_SHADOW_SURFACE_CACHE_BYTES {
3998 let Some((_, evicted)) = self.shadow_surface_cache.pop_lru() else {
3999 break;
4000 };
4001 self.shadow_surface_cache_bytes = self
4002 .shadow_surface_cache_bytes
4003 .saturating_sub(evicted.byte_size);
4004 }
4005 let cached = CachedShadowSurface { target, byte_size };
4006 if let Some((_, replaced)) = self.shadow_surface_cache.push(key, cached) {
4007 self.shadow_surface_cache_bytes = self
4008 .shadow_surface_cache_bytes
4009 .saturating_sub(replaced.byte_size);
4010 }
4011 self.shadow_surface_cache_bytes = self.shadow_surface_cache_bytes.saturating_add(byte_size);
4012 }
4013}
4014fn frame_stats_need_warmup_frame(snapshot: &gpu_stats::FrameStatsSnapshot) -> bool {
4015 snapshot.layer_cache_misses > 0
4016 || snapshot.shadow_shape_cache_misses > 0
4017 || snapshot.text_image_cache_misses > 0
4018 || snapshot.text_glyph_atlas_misses > 0
4019}
4020
4021fn update_frame_warmup_budget(pending_frames: &mut u8, snapshot: &gpu_stats::FrameStatsSnapshot) {
4022 if *pending_frames > 0 {
4023 *pending_frames = pending_frames.saturating_sub(1);
4024 } else if frame_stats_need_warmup_frame(snapshot) {
4025 *pending_frames = CACHE_MISS_WARMUP_FRAMES;
4026 }
4027}
4028
4029impl GpuRenderer {
4030 #[expect(clippy::too_many_arguments)]
4031 pub fn render(
4032 &mut self,
4033 texture: &wgpu::Texture,
4034 view: &wgpu::TextureView,
4035 width: u32,
4036 height: u32,
4037 packet: FramePacket,
4038 surface_epoch: u64,
4039 returns: &mut RenderReturns,
4040 ) -> Result<(), String> {
4041 self.render_internal(
4042 width,
4043 height,
4044 packet,
4045 surface_epoch,
4046 returns,
4047 OutputMode::Display,
4048 Some(view),
4049 Some(texture),
4050 )
4051 }
4052
4053 #[expect(clippy::too_many_arguments)]
4054 fn render_internal(
4055 &mut self,
4056 width: u32,
4057 height: u32,
4058 packet: FramePacket,
4059 surface_epoch: u64,
4060 returns: &mut RenderReturns,
4061 output_mode: OutputMode,
4062 output_view: Option<&wgpu::TextureView>,
4063 output_texture: Option<&wgpu::Texture>,
4064 ) -> Result<(), String> {
4065 let cancel_reason = if packet.renderer_epoch != self.renderer_epoch {
4066 Some(CancelReason::RendererEpoch)
4067 } else if packet.surface_epoch != surface_epoch {
4068 Some(CancelReason::SurfaceEpoch)
4069 } else if packet.viewport != (width, height) {
4070 Some(CancelReason::Viewport)
4071 } else {
4072 None
4073 };
4074 if let Some(reason) = cancel_reason {
4075 return Self::cancel_packet(packet, reason, returns);
4076 }
4077 if self.device_errors.take_poison() {
4078 return Self::cancel_packet(packet, CancelReason::DeviceError, returns);
4079 }
4080 returns.frame_id = packet.frame_id;
4081 let render_start = Instant::now();
4082 #[cfg(not(target_arch = "wasm32"))]
4083 let builds_before = thread_builds();
4084 self.warm_requested_shaders();
4085 self.shape_pipelines.begin_frame();
4086 self.recorder.begin_frame();
4087 self.begin_placeholder_frame();
4088 self.viewport_uniforms.begin_frame();
4089 self.run_store.begin_frame(gpu_stats_enabled());
4090 self.begin_text_glyph_run_frame();
4091
4092 let text_cache_len = packet.text_cache_len;
4093 let reads_page = packet.root.contains_backdrop()
4094 || packet
4095 .overlay
4096 .as_ref()
4097 .is_some_and(LayerScene::contains_backdrop);
4098 let frame_root = self.frame_root(
4099 output_mode,
4100 output_view,
4101 output_texture,
4102 (width, height),
4103 reads_page,
4104 );
4105 let root = frame_root.target();
4106 let screenshot_bind_group = output_view.and_then(|_| {
4107 matches!(output_mode, OutputMode::Screenshot).then(|| {
4108 self.screenshot_converter
4109 .bind_group(&self.device, &root.view)
4110 })
4111 });
4112 let output = frame_root.output(output_view, screenshot_bind_group.as_ref());
4113 let result = self.render_graph(root, packet, returns, output_mode, output);
4114 #[cfg(not(target_arch = "wasm32"))]
4115 self.effect_renderer
4116 .compiler()
4117 .spread_demand(thread_builds() == builds_before);
4118 if let FrameRoot::Composition(composition) = frame_root {
4119 self.composition_target = Some(composition);
4120 }
4121 let after_graph = Instant::now();
4122 self.flush_deferred_offscreen_releases();
4123
4124 self.frame_stats
4125 .layer_cache_size
4126 .set(self.layer_cache.len() as u32);
4127 self.frame_stats
4128 .layer_cache_bytes
4129 .set(self.layer_cache.bytes());
4130 self.frame_stats.offscreen_pool_size.set(
4131 self.effect_renderer
4132 .retained_offscreen_count()
4133 .saturating_add(self.frame_graph_executor.retained_texture_count())
4134 .saturating_add(usize::from(self.composition_target.is_some())) as u32,
4135 );
4136 self.frame_stats.offscreen_pool_bytes.set(
4137 (self.effect_renderer.retained_offscreen_bytes() as u64)
4138 .saturating_add(self.frame_graph_executor.retained_texture_bytes())
4139 .saturating_add(self.composition_target.as_ref().map_or(0, |target| {
4140 u64::from(target.target.width)
4141 .saturating_mul(u64::from(target.target.height))
4142 .saturating_mul(COMPOSITION_BYTES_PER_PIXEL)
4143 })),
4144 );
4145 self.frame_stats
4146 .text_pool_size
4147 .set(self.text_image_cache.len() as u32);
4148 self.frame_stats
4149 .image_cache_size
4150 .set(self.image_texture_cache.len() as u32);
4151 self.frame_stats.text_cache_size.set(text_cache_len as u32);
4152 self.effect_renderer
4153 .merge_and_reset_debug_counters(&self.frame_stats);
4154 self.frame_graph_executor.reset_upload_allocators();
4155 let snapshot = self.frame_stats.snapshot();
4156 if crate::frame_graph::frame_graph_pass_telemetry_threshold_ms().is_some() {
4157 log::warn!(
4158 "[wgpu-render-stage:frame-stats] layer_hit={} layer_miss={} miss_px={} \
4159 offscreen_acq={} offscreen_new={} isolated={} draws={}",
4160 snapshot.layer_cache_hits,
4161 snapshot.layer_cache_misses,
4162 snapshot.layer_cache_miss_pixels,
4163 snapshot.offscreen_acquires,
4164 snapshot.offscreen_news,
4165 snapshot.isolated_layer_renders,
4166 snapshot.draw_calls,
4167 );
4168 }
4169 self.last_frame_stats = Some(snapshot);
4170 PRESENTED_FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4171 update_frame_warmup_budget(&mut self.pending_frame_warmup_frames, &snapshot);
4172 let gpu_stats_on = gpu_stats_enabled();
4173 self.frame_stats
4174 .maybe_print_snapshot(snapshot, &mut self.frame_count, gpu_stats_on);
4175 if gpu_stats_on && self.frame_count.is_multiple_of(60) {
4176 gpu_stats::print_gpu_memory_report(&self.device, self.frame_count);
4177 }
4178 self.frame_graph_executor
4179 .end_pass_timing_frame(&self.device, &self.queue);
4180 self.frame_stats.reset();
4181 let after_stats = Instant::now();
4182 if let Some(total_ms) = should_log_wgpu_render_stage(render_start, after_stats) {
4183 log::warn!(
4184 "[wgpu-render-stage:render] total_ms={total_ms:.2} graph_ms={:.2} cleanup_stats_ms={:.2}",
4185 instant_ms(render_start, after_graph),
4186 instant_ms(after_graph, after_stats),
4187 );
4188 }
4189 if result.is_ok() {
4190 returns.outcome = PresentOutcome::Presented;
4191 }
4192 result
4193 }
4194
4195 pub(crate) fn cancel_packet(
4197 packet: FramePacket,
4198 reason: CancelReason,
4199 returns: &mut RenderReturns,
4200 ) -> Result<(), String> {
4201 returns.scene = Some(FrameSceneStorage {
4202 root: packet.root,
4203 overlay: packet.overlay,
4204 });
4205 returns.frame_id = packet.frame_id;
4206 returns.outcome = PresentOutcome::Cancelled(reason);
4207 Ok(())
4208 }
4209
4210 pub fn last_frame_stats(&self) -> Option<gpu_stats::FrameStatsSnapshot> {
4211 self.last_frame_stats
4212 }
4213
4214 pub fn gpu_pass_timings(&self) -> crate::pass_timing::GpuPassTimingReport {
4215 self.frame_graph_executor.pass_timing_report()
4216 }
4217
4218 pub fn needs_frame_warmup(&self) -> bool {
4219 self.pending_frame_warmup_frames > 0 || self.placeholder_awaits_frame()
4220 }
4221
4222 fn placeholder_awaits_frame(&self) -> bool {
4226 #[cfg(not(target_arch = "wasm32"))]
4227 if let Some(landing) = &self.landing {
4228 return landing.landed() || (self.drew_placeholder && !landing.has_wake());
4229 }
4230 self.drew_placeholder
4231 }
4232
4233 fn begin_placeholder_frame(&mut self) {
4236 self.drew_placeholder = false;
4237 #[cfg(not(target_arch = "wasm32"))]
4238 if let Some(landing) = &self.landing {
4239 self.built_at_frame_start = landing.built();
4240 if landing.take_landed() {
4241 self.layer_cache.clear();
4242 }
4243 }
4244 }
4245
4246 pub(crate) fn note_placeholder(&mut self) {
4249 self.drew_placeholder = true;
4250 self.recorder.hold_first_screen();
4251 self.frame_stats
4252 .placeholder_draws
4253 .set(self.frame_stats.placeholder_draws.get() + 1);
4254 #[cfg(not(target_arch = "wasm32"))]
4255 if let Some(landing) = &self.landing {
4256 landing.await_since(self.built_at_frame_start);
4257 }
4258 }
4259
4260 #[cfg(not(target_arch = "wasm32"))]
4264 pub(crate) fn prepare_recorded(&mut self) -> bool {
4265 self.effect_renderer.warm_after_first_frame();
4266 if let Some(records) = self.recent_after_update.take() {
4267 self.warm_recent(&records);
4268 }
4269 self.compiling()
4270 }
4271
4272 #[cfg(not(target_arch = "wasm32"))]
4274 pub(crate) fn compiling(&self) -> bool {
4275 self.landing
4276 .as_ref()
4277 .is_some_and(|landing| landing.in_flight())
4278 }
4279
4280 pub(crate) fn awaits_pipelines(&self) -> bool {
4283 #[cfg(not(target_arch = "wasm32"))]
4284 if let Some(landing) = &self.landing {
4285 return self.drew_placeholder && landing.in_flight();
4286 }
4287 self.drew_placeholder
4288 }
4289
4290 #[cfg(not(target_arch = "wasm32"))]
4293 pub(crate) fn landing(&self) -> Option<Arc<crate::pipeline_compiler::Landing>> {
4294 self.landing.clone()
4295 }
4296
4297 #[cfg(not(target_arch = "wasm32"))]
4300 pub(crate) fn wake_on_landing(&self, wake: Box<dyn Fn() + Send + Sync>) {
4301 if let Some(landing) = &self.landing {
4302 landing.wake_with(wake);
4303 }
4304 }
4305
4306 pub fn debug_cpu_allocation_stats(&self) -> DebugCpuAllocationStats {
4307 DebugCpuAllocationStats {
4308 scene_graph_node_count: 0,
4309 scene_graph_heap_bytes: 0,
4310 scene_hits_len: 0,
4311 scene_hits_cap: 0,
4312 scene_node_index_len: 0,
4313 scene_node_index_cap: 0,
4314 text_renderer_pool_len: self.text_image_cache.len(),
4315 text_renderer_pool_cap: self.text_image_cache.cap().get(),
4316 image_texture_cache_len: self.image_texture_cache.len(),
4317 image_texture_cache_cap: self.image_texture_cache.cap().get(),
4318 run_arena_staging_bytes: self.run_store.arena_staging_bytes(),
4319 run_store_bytes: self.run_store.stored_bytes(),
4320 run_store_runs: self.run_store.stored_count(),
4321 scratch_image_vertices_cap: self.scratch_image_vertices.capacity(),
4322 scratch_image_indices_cap: self.scratch_image_indices.capacity(),
4323 scratch_image_cmds_cap: self.scratch_image_cmds.capacity(),
4324 scratch_glyph_instances_cap: self.scratch_glyph_instances.plain.capacity()
4325 + self.scratch_glyph_instances.turned.capacity(),
4326 layer_cache_len: self.layer_cache.len(),
4327 layer_cache_bytes: self.layer_cache.bytes(),
4328 }
4329 }
4330 pub fn render_to_rgba_pixels(
4331 &mut self,
4332 width: u32,
4333 height: u32,
4334 packet: FramePacket,
4335 surface_epoch: u64,
4336 returns: &mut RenderReturns,
4337 ) -> Result<Vec<u8>, String> {
4338 if width == 0 || height == 0 {
4339 return Err("Screenshot size must be non-zero".to_string());
4340 }
4341 let errors_before = self.device_errors.error_count();
4342
4343 let output_texture = crate::offscreen::create_2d_texture(
4344 &self.device,
4345 wgpu::TextureFormat::Rgba8Unorm,
4346 width,
4347 height,
4348 wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
4349 Some("Screenshot Output Texture"),
4350 );
4351 let output_view = output_texture.create_view(&wgpu::TextureViewDescriptor::default());
4352 self.render_internal(
4353 width,
4354 height,
4355 packet,
4356 surface_epoch,
4357 returns,
4358 OutputMode::Screenshot,
4359 Some(&output_view),
4360 None,
4361 )?;
4362 if returns.outcome != PresentOutcome::Presented {
4363 return Err(format!(
4364 "Screenshot rendering did not complete: {:?}",
4365 returns.outcome
4366 ));
4367 }
4368 self.read_screenshot_pixels(&output_texture, errors_before)
4369 }
4370
4371 fn read_screenshot_pixels(
4372 &mut self,
4373 output_texture: &wgpu::Texture,
4374 errors_before: u64,
4375 ) -> Result<Vec<u8>, String> {
4376 let width = output_texture.width();
4377 let height = output_texture.height();
4378 let bytes_per_pixel = 4u32;
4379 let unpadded_bytes_per_row = width
4380 .checked_mul(bytes_per_pixel)
4381 .ok_or_else(|| "Screenshot row byte size overflow".to_string())?;
4382 let padded_bytes_per_row =
4383 align_to(unpadded_bytes_per_row, wgpu::COPY_BYTES_PER_ROW_ALIGNMENT);
4384 let output_buffer_size = padded_bytes_per_row as u64 * height as u64;
4385
4386 let output_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
4387 label: Some("Screenshot Readback Buffer"),
4388 size: output_buffer_size,
4389 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
4390 mapped_at_creation: false,
4391 });
4392
4393 let device = self.device.clone();
4394 let queue = self.queue.clone();
4395 let mut graph = WgpuFrameGraph::new(Some("Screenshot Copy Encoder"));
4396 let source = graph.import_surface("screenshot-copy-source");
4397 graph.add_fallible_command_pass(Some("Screenshot Copy Pass"), &[source], &[], |context| {
4398 context.encoder.copy_texture_to_buffer(
4399 wgpu::TexelCopyTextureInfo {
4400 texture: output_texture,
4401 mip_level: 0,
4402 origin: wgpu::Origin3d::ZERO,
4403 aspect: wgpu::TextureAspect::All,
4404 },
4405 wgpu::TexelCopyBufferInfo {
4406 buffer: &output_buffer,
4407 layout: wgpu::TexelCopyBufferLayout {
4408 offset: 0,
4409 bytes_per_row: Some(padded_bytes_per_row),
4410 rows_per_image: Some(height),
4411 },
4412 },
4413 wgpu::Extent3d {
4414 width,
4415 height,
4416 depth_or_array_layers: 1,
4417 },
4418 );
4419 Ok(())
4420 });
4421 let mut executor = std::mem::take(&mut self.frame_graph_executor);
4422 let execution = executor.execute_recorded_graph(&device, &queue, graph);
4423 self.frame_graph_executor = executor;
4424 let execution = execution.map_err(|error| error.to_string())?;
4425 let submission_index = execution.submission;
4426 let copy_stats = execution.stats;
4427 self.last_frame_stats = self
4428 .last_frame_stats
4429 .map(|snapshot| snapshot.with_command_stats_added(copy_stats));
4430
4431 let buffer_slice = output_buffer.slice(..);
4432 let (tx, rx) = mpsc::channel();
4433 buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
4434 let _ = tx.send(result);
4435 });
4436 self.device
4437 .poll(wgpu::PollType::Wait {
4438 submission_index: Some(submission_index),
4439 timeout: None,
4440 })
4441 .map_err(|error| format!("Screenshot GPU wait failed: {error}"))?;
4442
4443 match rx.recv_timeout(Duration::from_secs(3)) {
4444 Ok(Ok(())) => {}
4445 Ok(Err(err)) => return Err(format!("Screenshot map_async failed: {err:?}")),
4446 Err(err) => return Err(format!("Screenshot readback timed out: {err}")),
4447 }
4448 if self.device_errors.error_count() != errors_before {
4449 output_buffer.unmap();
4450 return Err("GPU errors occurred while capturing the screenshot".to_string());
4451 }
4452
4453 let mapped = buffer_slice
4454 .get_mapped_range()
4455 .map_err(|err| format!("Screenshot readback could not be read: {err}"))?;
4456 let mut pixels = vec![0u8; (width as usize) * (height as usize) * 4];
4457
4458 let src_row_len = padded_bytes_per_row as usize;
4459 let dst_row_len = unpadded_bytes_per_row as usize;
4460 for row in 0..height as usize {
4461 let src_offset = row * src_row_len;
4462 let dst_offset = row * dst_row_len;
4463 pixels[dst_offset..dst_offset + dst_row_len]
4464 .copy_from_slice(&mapped[src_offset..src_offset + dst_row_len]);
4465 }
4466 drop(mapped);
4467 output_buffer.unmap();
4468
4469 self.convert_surface_pixels_to_rgba(&pixels)
4470 }
4471
4472 fn render_graph(
4473 &mut self,
4474 root_target: &Rc<OffscreenTarget>,
4475 packet: FramePacket,
4476 returns: &mut RenderReturns,
4477 output_mode: OutputMode,
4478 output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
4479 ) -> Result<(), String> {
4480 let device = self.device.clone();
4481 let queue = self.queue.clone();
4482 let graph_start = Instant::now();
4483 let FramePacket {
4484 root,
4485 overlay,
4486 root_scale,
4487 clear,
4488 ..
4489 } = packet;
4490 let page = Rc::clone(root_target);
4491
4492 #[cfg(not(target_arch = "wasm32"))]
4493 let (result, submitted) = {
4494 let mut executor = std::mem::take(&mut self.frame_graph_executor);
4495 let mut frame_graph = WgpuFrameGraph::new(Some("Renderer Frame Graph"));
4496 let surface = frame_graph.import_surface("renderer-surface");
4497 frame_graph.add_fallible_recorded_command_pass(
4498 Some("Renderer Frame Pass"),
4499 &[],
4500 &[surface],
4501 |frame_encoder| {
4502 self.encode_frame(
4503 frame_encoder,
4504 &root,
4505 overlay.as_ref(),
4506 Rc::clone(&page),
4507 root_scale,
4508 clear,
4509 output_mode,
4510 output,
4511 )
4512 },
4513 );
4514 let after_build = Instant::now();
4515 let execution = executor.execute_recorded_graph(&device, &queue, frame_graph);
4516 let after_execute = Instant::now();
4517 self.frame_graph_executor = executor;
4518 if let Some(total_ms) = should_log_wgpu_render_stage(graph_start, after_execute) {
4519 log::warn!(
4520 "[wgpu-render-stage:graph] total_ms={total_ms:.2} build_ms={:.2} execute_ms={:.2}",
4521 instant_ms(graph_start, after_build),
4522 instant_ms(after_build, after_execute),
4523 );
4524 }
4525 match execution {
4526 Ok(execution) => {
4527 if execution.stats.pass_count > 0 {
4528 self.frame_stats.record_command_stats(execution.stats);
4529 }
4530 (Ok(()), true)
4531 }
4532 Err(crate::frame_graph::FrameGraphError::NoDeclaredPasses) => (Ok(()), false),
4533 Err(error) => (Err(error.to_string()), false),
4534 }
4535 };
4536
4537 #[cfg(target_arch = "wasm32")]
4538 let (result, submitted) = {
4539 let mut executor = std::mem::take(&mut self.frame_graph_executor);
4540 let (result, execution) = {
4541 let mut frame_encoder =
4542 executor.begin(&device, &queue, Some("Renderer Frame Encoder"));
4543 let initial_pass_count = frame_encoder.recorded_pass_count();
4544 let result = self.encode_frame(
4545 &mut frame_encoder,
4546 &root,
4547 overlay.as_ref(),
4548 Rc::clone(&page),
4549 root_scale,
4550 clear,
4551 output_mode,
4552 output,
4553 );
4554 let execution =
4555 if result.is_ok() && frame_encoder.recorded_pass_count() > initial_pass_count {
4556 Some(frame_encoder.finish())
4557 } else {
4558 None
4559 };
4560 (result, execution)
4561 };
4562 let after_execute = Instant::now();
4563 self.frame_graph_executor = executor;
4564 if let Some(total_ms) = should_log_wgpu_render_stage(graph_start, after_execute) {
4565 log::warn!("[wgpu-render-stage:graph] total_ms={total_ms:.2}",);
4566 }
4567 let submitted = execution.is_some();
4568 if let Some(execution) = execution {
4569 self.frame_stats.record_command_stats(execution.stats);
4570 }
4571 (result, submitted)
4572 };
4573 #[cfg(not(target_arch = "wasm32"))]
4574 if submitted {
4575 self.recorder.note_frame_drawn();
4576 self.effect_renderer.warm_after_first_frame();
4577 if let Some(records) = self.recent_after_update.take() {
4578 self.warm_recent(&records);
4579 }
4580 }
4581 if !submitted {
4582 self.run_store.invalidate_uploads();
4583 self.text_glyph_gpu_run_cache.clear();
4584 self.text_glyph_run_arena = GlyphRunArena::default();
4585 }
4586 returns.scene = Some(FrameSceneStorage { root, overlay });
4587 result
4588 }
4589
4590 #[expect(clippy::too_many_arguments)]
4594 fn encode_frame<C: FrameCommandRecorder>(
4595 &mut self,
4596 recorder: &mut C,
4597 root: &LayerScene,
4598 overlay: Option<&LayerScene>,
4599 page: Rc<OffscreenTarget>,
4600 root_scale: f32,
4601 clear: wgpu::Color,
4602 output_mode: OutputMode,
4603 output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
4604 ) -> Result<(), String> {
4605 FrameExecutor::new(self, recorder).render_frame(
4606 root,
4607 overlay,
4608 page,
4609 root_scale,
4610 wgpu::LoadOp::Clear(clear),
4611 )?;
4612 if let Some((output_view, bind_group)) = output {
4613 match output_mode {
4614 OutputMode::Display => &self.output_converter,
4615 OutputMode::Screenshot => &self.screenshot_converter,
4616 }
4617 .encode(
4618 &self.device,
4619 recorder,
4620 output_view,
4621 bind_group,
4622 self.adapter_backend,
4623 &self.recorder,
4624 );
4625 recorder.record_pass();
4626 }
4627 self.stage_frame_uploads(recorder);
4628 self.shape_pipelines.request_wanted();
4629 self.viewport_uniforms.uploads.finish_frame();
4630 self.run_store.finish_frame();
4631 Ok(())
4632 }
4633
4634 pub(crate) fn stage_frame_uploads(&mut self, recorder: &mut impl FrameCommandRecorder) {
4635 let mut upload = self.viewport_uniforms.stage_pending(&self.device, recorder);
4636 upload += self.run_store.stage_pending(&self.device, recorder);
4637 upload += self
4638 .text_glyph_run_arena
4639 .stage_pending(&self.device, recorder);
4640 self.run_store.fill_arena_trig(&self.device, recorder);
4641 self.frame_stats.record_command_stats(upload);
4642 }
4643 pub(crate) fn claim_uniform_slot(&mut self, params: ViewportUniformParams) -> usize {
4645 let uniforms = Uniforms::of(params, PlacementData::zeroed(), RunTier::Arena);
4646 self.viewport_uniforms
4647 .claim(&self.device, &self.uniform_bind_group_layout, &uniforms)
4648 }
4649
4650 fn blurred_shadow_source<C: FrameCommandRecorder>(
4660 &mut self,
4661 recorder: &mut C,
4662 shadow: &ShadowDraw,
4663 source_device: DevicePixelBounds,
4664 pixel_radius: f32,
4665 root_scale: f32,
4666 transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
4667 ) -> Option<(Rc<OffscreenTarget>, bool, SourceContent)> {
4668 let shape_only = shadow.texts.is_empty();
4669 let key = if shape_only {
4670 shape_shadow_surface_cache_key(shadow, source_device, pixel_radius, root_scale)
4671 } else {
4672 None
4673 };
4674 let content = key.map_or(SourceContent::Transient, |key| {
4675 SourceContent::retained(&key)
4676 });
4677 if let Some(entry) = key.and_then(|key| self.shadow_surface_cache.get(&key)) {
4678 return Some((Rc::clone(&entry.target), true, content));
4679 }
4680 if !self.effect_renderer.blur_draws_now(
4682 &self.device,
4683 TileMode::Decal,
4684 (source_device.width, source_device.height),
4685 pixel_radius,
4686 pixel_radius,
4687 ) {
4688 self.note_placeholder();
4689 return None;
4690 }
4691 if !shape_only {
4692 self.frame_stats.record_shadow_text_blur_fallback();
4693 }
4694 let source = self.render_shadow_source(
4695 recorder,
4696 shadow,
4697 source_device,
4698 pixel_radius,
4699 root_scale,
4700 key.is_some(),
4701 transients,
4702 )?;
4703 if let Some(key) = key {
4704 self.frame_stats
4705 .record_shadow_shape_cache_miss(source_device.width, source_device.height);
4706 self.frame_stats.maybe_print_shadow_shape_cache_miss(
4707 source_device.width,
4708 source_device.height,
4709 key.content_hash,
4710 pixel_radius,
4711 [source_device.x, source_device.y],
4712 shadow.shapes.as_ref().map_or(0, RunDraw::record_count) as usize,
4713 shadow.clip,
4714 );
4715 self.insert_cached_shadow_surface(key, Rc::clone(&source));
4716 }
4717 Some((source, false, content))
4718 }
4719
4720 #[expect(clippy::too_many_arguments)]
4721 pub(crate) fn resolve_blurred_shadow<C: FrameCommandRecorder>(
4722 &mut self,
4723 recorder: &mut C,
4724 shadow: &ShadowDraw,
4725 z: usize,
4726 root_scale: f32,
4727 target_rect: DeviceRect4,
4728 transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
4729 resolved: &mut Vec<ResolvedComposite>,
4730 ) {
4731 if !shadow.requires_surface()
4732 || skip_shadow_draws()
4733 || !root_scale.is_finite()
4734 || root_scale <= 0.0
4735 {
4736 return;
4737 }
4738 let Some(bounds) = shadow_draw_bounds(shadow) else {
4739 return;
4740 };
4741 let margin = blur_reach(shadow.blur_radius, root_scale);
4742 let source_bounds = expand_rect(bounds, margin, margin);
4743 let mut visible = source_bounds;
4744 if let Some(clip) = shadow.clip {
4745 let Some(clipped) = visible.intersect(expand_rect(clip, margin, margin)) else {
4746 return;
4747 };
4748 visible = clipped;
4749 }
4750 let target_logical = Rect {
4751 x: target_rect.0 / root_scale,
4752 y: target_rect.1 / root_scale,
4753 width: target_rect.2 / root_scale,
4754 height: target_rect.3 / root_scale,
4755 };
4756 let Some(visible) = visible.intersect(expand_rect(target_logical, margin, margin)) else {
4757 return;
4758 };
4759 let max_texture_dim = self.max_texture_dim();
4760 let shape_only = shadow.texts.is_empty();
4761 let anchor = shadow
4762 .shapes
4763 .as_ref()
4764 .and_then(|run| run.placement.snap_anchor);
4765 let source_device = shape_only
4766 .then(|| {
4767 translation_stable_anchored_device_pixel_bounds(
4768 source_bounds,
4769 anchor,
4770 root_scale,
4771 max_texture_dim,
4772 )
4773 })
4774 .flatten()
4775 .or_else(|| device_pixel_bounds(visible, root_scale, max_texture_dim));
4776 let Some(source_device) = source_device else {
4777 return;
4778 };
4779 let pixel_radius = shadow.blur_radius * root_scale;
4780 let Some((source, hit, content)) = self.blurred_shadow_source(
4781 recorder,
4782 shadow,
4783 source_device,
4784 pixel_radius,
4785 root_scale,
4786 transients,
4787 ) else {
4788 return;
4789 };
4790 let dest = (
4791 source_device.x,
4792 source_device.y,
4793 source_device.width as f32,
4794 source_device.height as f32,
4795 );
4796 let mut coverage = intersect_device_rects(dest, target_rect);
4797 if let Some(clip) = shadow.clip {
4798 coverage = coverage.and_then(|coverage| {
4799 intersect_device_rects(coverage, anchored_rect_to_device(clip, anchor, root_scale))
4800 });
4801 }
4802 let Some(coverage) = coverage else {
4803 return;
4804 };
4805 if hit {
4806 self.frame_stats.record_shadow_shape_cache_hit(
4807 (coverage.2 as u64).saturating_mul(coverage.3 as u64),
4808 );
4809 }
4810 let rounded_mask = shadow_composite_mask(shadow, anchor, root_scale);
4811 let downscaled =
4812 (source.width, source.height) != (source_device.width, source_device.height);
4813 let (sample_mode, source_viewport) = if downscaled {
4814 (
4815 CompositeSampleMode::Linear,
4816 Some((0.0, 0.0, source.width as f32, source.height as f32)),
4817 )
4818 } else {
4819 (CompositeSampleMode::Nearest, None)
4820 };
4821 resolved.push(ResolvedComposite {
4822 z_index: z,
4823 source,
4824 content,
4825 dest,
4826 scissor: Some(coverage),
4827 kind: ResolvedCompositeKind::Blit {
4828 alpha: 1.0,
4829 blend_mode: BlendMode::SrcOver,
4830 rounded_mask,
4831 sample_mode,
4832 source_viewport,
4833 },
4834 });
4835 }
4836
4837 #[expect(clippy::too_many_arguments)]
4846 fn render_shadow_source<C: FrameCommandRecorder>(
4847 &mut self,
4848 recorder: &mut C,
4849 shadow: &ShadowDraw,
4850 bounds: DevicePixelBounds,
4851 pixel_radius: f32,
4852 root_scale: f32,
4853 retained: bool,
4854 transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
4855 ) -> Option<Rc<OffscreenTarget>> {
4856 let (width, height) = (bounds.width, bounds.height);
4857 let device = self.device.clone();
4858 let (scratch_width, scratch_height) =
4859 crate::effect_renderer::blur_scratch_size(pixel_radius, pixel_radius, width, height);
4860 let full_size_result = shadow.post_blur_cutouts.is_some()
4861 || (scratch_width, scratch_height) == (width, height);
4862 let (result_width, result_height) = if full_size_result {
4863 (width, height)
4864 } else {
4865 (scratch_width, scratch_height)
4866 };
4867 let result = if retained {
4868 Rc::new(self.acquire_retained_surface(result_width, result_height))
4869 } else {
4870 self.shadow_transient(
4871 recorder,
4872 transients,
4873 "Shadow Result",
4874 result_width,
4875 result_height,
4876 )
4877 };
4878 let source = if full_size_result {
4879 Rc::clone(&result)
4880 } else {
4881 self.shadow_transient(recorder, transients, "Shadow Source", width, height)
4882 };
4883 let offset = [bounds.x, bounds.y];
4884 let target = PassTarget {
4885 view: &source.view,
4886 width,
4887 height,
4888 };
4889 let scene = shadow_scene(
4890 shadow.shapes.as_ref(),
4891 &shadow.texts,
4892 blur_reach(shadow.blur_radius, root_scale),
4893 );
4894 let segment = PassSegment {
4895 scene: &scene,
4896 ops: &scene.draw_ops,
4897 composites: &[],
4898 offset,
4899 scissor: None,
4900 first_run_window: None,
4901 transform: SegmentTransform::IDENTITY,
4902 scale: root_scale,
4903 };
4904 let drew = self.encode_pass(
4905 recorder,
4906 target,
4907 std::slice::from_ref(&segment),
4908 wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
4909 "Shadow Source Pass",
4910 );
4911 match drew {
4912 Ok(true) => {}
4913 Ok(false) => {
4914 drop(source);
4915 if retained && let Ok(target) = Rc::try_unwrap(result) {
4916 self.defer_offscreen_release(target);
4917 }
4918 return None;
4919 }
4920 Err(error) => {
4921 log::error!("shadow source pass failed: {error}");
4922 return None;
4923 }
4924 }
4925 if pixel_radius > 0.0 {
4926 let scratch_descriptor = self.transient_offscreen_descriptor(
4927 "Shadow Blur Scratch",
4928 scratch_width,
4929 scratch_height,
4930 );
4931 let scratch = recorder.acquire_transient_offscreen(&device, scratch_descriptor);
4932 let blurred = if full_size_result && (scratch_width, scratch_height) != (width, height)
4933 {
4934 Some(self.shadow_transient(
4935 recorder,
4936 transients,
4937 "Shadow Blur Result",
4938 scratch_width,
4939 scratch_height,
4940 ))
4941 } else {
4942 None
4943 };
4944 let blur_dest = match &blurred {
4945 Some(blurred) => (&blurred.view, (scratch_width, scratch_height)),
4946 None => (&result.view, (result_width, result_height)),
4947 };
4948 let passes = self.effect_renderer.encode_blur_scissored_ping_pong_passes(
4949 recorder,
4950 &device,
4951 &source,
4952 &scratch,
4953 blur_dest,
4954 pixel_radius,
4955 pixel_radius,
4956 TileMode::Decal,
4957 None,
4958 );
4959 recorder.record_passes(passes);
4960 self.effect_renderer.record_blur_pass();
4961 recorder.release_transient_offscreen(scratch_descriptor, scratch);
4962 if let Some(blurred) = &blurred {
4963 self.effect_renderer
4964 .encode_upscale_pass(recorder, &device, blurred, &result.view);
4965 recorder.record_pass();
4966 }
4967 }
4968 if let Some(cutout_run) = &shadow.post_blur_cutouts {
4969 let cutouts = shadow_scene(Some(cutout_run), &[], 0.0);
4970 let segment = PassSegment {
4971 scene: &cutouts,
4972 ops: &cutouts.draw_ops,
4973 composites: &[],
4974 offset,
4975 scissor: None,
4976 first_run_window: None,
4977 transform: SegmentTransform::IDENTITY,
4978 scale: root_scale,
4979 };
4980 if let Err(error) = self.encode_pass(
4981 recorder,
4982 target,
4983 std::slice::from_ref(&segment),
4984 wgpu::LoadOp::Load,
4985 "Shadow Cutout Pass",
4986 ) {
4987 log::error!("shadow cutout pass failed: {error}");
4988 }
4989 }
4990 Some(result)
4991 }
4992
4993 fn shadow_transient<C: FrameCommandRecorder>(
4996 &self,
4997 recorder: &mut C,
4998 transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
4999 label: &'static str,
5000 width: u32,
5001 height: u32,
5002 ) -> Rc<OffscreenTarget> {
5003 let descriptor = self.transient_offscreen_descriptor(label, width, height);
5004 let target = Rc::new(recorder.acquire_transient_offscreen(&self.device, descriptor));
5005 transients.push((descriptor, Rc::clone(&target)));
5006 target
5007 }
5008
5009 pub(crate) fn run_is_stored(&self, run: &RunDraw) -> bool {
5011 self.run_store.is_stored(run)
5012 }
5013
5014 fn run_pipeline_key(
5018 segment: &RecordSegment,
5019 placement: &crate::scene::Placement,
5020 tier: RunTier,
5021 ablation: ShapeAblation,
5022 turns: ShapeTurns,
5023 (depth, clip): (bool, SegmentClip),
5024 viewport: ViewportUniformParams,
5025 ) -> ShapePipelineKey {
5026 let blend_mode = supported_blend_mode(segment.blend);
5027 let laid = depth
5028 && blend_mode == BlendMode::SrcOver
5029 && !placement.paints()
5030 && clip != SegmentClip::Rounded
5031 && !ablation.material
5032 && !ablation.fill;
5033 ShapePipelineKey {
5034 blend_mode,
5035 tier,
5036 variant: ShapeVariant::of_segment(
5037 segment,
5038 clip,
5039 ablation,
5040 laid,
5041 (
5042 turns == ShapeTurns::None,
5043 turns == ShapeTurns::None
5044 && placement.snap_anchor.is_some()
5045 && viewport.offset.iter().all(|value| value.fract() == 0.0),
5046 ),
5047 ),
5048 turns,
5049 depth: if depth {
5050 ShapeDepth::Tested
5051 } else {
5052 ShapeDepth::Off
5053 },
5054 }
5055 }
5056
5057 fn ensure_run_pipelines(&mut self, key: ShapePipelineKey, vertices: u64) {
5060 self.ensure_shape_pipeline(key, vertices);
5061 if let Some(interior) = key.interior() {
5062 self.ensure_shape_pipeline(interior, vertices);
5063 }
5064 }
5065
5066 pub(crate) fn prepare_store_run<C: FrameCommandRecorder>(
5069 &mut self,
5070 recorder: &mut C,
5071 run: &RunDraw,
5072 viewport: ViewportUniformParams,
5073 root_scale: f32,
5074 window: &std::ops::Range<u32>,
5075 depth: bool,
5076 ) -> StoreRunBatch {
5077 let command = run.command.expect("a stored run has a command");
5078 let placement = &run.placement;
5079 let ablation = self.ablation.shape;
5080 let turns = ShapeTurns::of(viewport.transform, false);
5081 let scissor = clip_scissor(placement, root_scale, viewport);
5082 let clip = SegmentClip::of(placement, scissor.is_some());
5083 let mut draws = SmallVec::new();
5084 self.run_store.stored_run_draws(
5085 &self.device,
5086 run,
5087 &mut |segment| {
5088 Self::run_pipeline_key(
5089 segment,
5090 placement,
5091 RunTier::Store,
5092 ablation,
5093 turns,
5094 (depth, clip),
5095 viewport,
5096 )
5097 },
5098 &mut draws,
5099 );
5100 window_draws(&mut draws, window);
5101 let upload_start = Instant::now();
5102 let (upload, fill) =
5103 self.run_store
5104 .upload_stored(&self.device, recorder, run, root_scale, window, &draws);
5105 if let Some(total_ms) = should_log_wgpu_render_stage(upload_start, Instant::now()) {
5106 log::warn!(
5107 "[wgpu-render-stage:run-upload] total_ms={total_ms:.2} bytes={} records={}",
5108 upload.upload_bytes,
5109 run.tables().shapes.len()
5110 );
5111 }
5112 self.frame_stats.record_command_stats(upload);
5113 if let Some(fill) = fill {
5114 self.frame_stats.add_shape_fill(fill);
5115 }
5116 let uniforms = Uniforms::of(
5117 viewport,
5118 PlacementData::of(&run.placement, root_scale, viewport.transform),
5119 RunTier::Store,
5120 );
5121 let uniform_slot =
5122 self.viewport_uniforms
5123 .claim(&self.device, &self.uniform_bind_group_layout, &uniforms);
5124 for draw in &draws {
5125 self.ensure_run_pipelines(
5126 draw.key,
5127 crate::run_store::draw_vertices(
5128 draw.records.end - draw.records.start,
5129 draw.band_class,
5130 ),
5131 );
5132 }
5133 StoreRunBatch {
5134 command,
5135 uniform_slot,
5136 draws,
5137 clip: scissor,
5138 }
5139 }
5140
5141 pub(crate) fn open_arena(&mut self) -> usize {
5142 self.run_store.open_arena()
5143 }
5144
5145 pub(crate) fn open_arena_records(&self) -> u32 {
5147 self.run_store.open_arena_records()
5148 }
5149
5150 pub(crate) fn arena_accepts(&self, chunk: usize, run: &RunDraw) -> bool {
5151 self.run_store.arena_accepts(chunk, run)
5152 }
5153
5154 #[expect(clippy::too_many_arguments)]
5158 pub(crate) fn append_arena_run(
5162 &mut self,
5163 chunk: usize,
5164 run: &RunDraw,
5165 window: std::ops::Range<u32>,
5166 root_scale: f32,
5167 viewport: ViewportUniformParams,
5168 mixed_turns: bool,
5169 (depth, clip): (bool, SegmentClip),
5170 ) -> u32 {
5171 let placement = &run.placement;
5172 let ablation = self.ablation.shape;
5173 let turn = viewport.transform;
5174 let turns = ShapeTurns::of(turn, mixed_turns);
5175 let mut keys: SmallVec<[(ShapePipelineKey, u64); 4]> = SmallVec::new();
5176 let taken = self.run_store.append_arena(
5177 chunk,
5178 run,
5179 window,
5180 (root_scale, turn),
5181 &mut |segment| {
5182 Self::run_pipeline_key(
5183 segment,
5184 placement,
5185 RunTier::Arena,
5186 ablation,
5187 turns,
5188 (depth, clip),
5189 viewport,
5190 )
5191 },
5192 &mut keys,
5193 );
5194 for (key, vertices) in keys {
5195 self.ensure_run_pipelines(key, vertices);
5196 }
5197 taken
5198 }
5199
5200 pub(crate) fn cut_arena(&mut self, chunk: usize, out: &mut Vec<RunDrawCall>) {
5203 self.run_store.cut_arena(&self.device, chunk, out);
5204 }
5205
5206 pub(crate) fn close_arena(&mut self, chunk: usize, out: &mut Vec<RunDrawCall>) {
5209 if let Some(fill) = self.run_store.close_arena(&self.device, chunk, out) {
5210 self.frame_stats.add_shape_fill(fill);
5211 }
5212 }
5213
5214 pub(crate) fn draw_run_calls(
5215 &self,
5216 pass: &mut wgpu::RenderPass<'_>,
5217 tables: ArenaBinding<'_>,
5218 uniform_slot: usize,
5219 draws: &[RunDrawCall],
5220 scissor: (u32, u32, u32, u32),
5221 stage: RunStage,
5222 ) -> Result<(), String> {
5223 match stage {
5224 RunStage::Paint => {
5225 if draws.is_empty() {
5226 return Ok(());
5227 }
5228 self.frame_stats.bump_shapes();
5229 self.record_run_draws(
5230 pass,
5231 tables,
5232 uniform_slot,
5233 scissor,
5234 draws.iter().map(PlannedRunDraw::paint),
5235 )
5236 }
5237 RunStage::Interiors => {
5238 let planned = interior_run_draws(draws);
5239 if planned.is_empty() {
5240 return Ok(());
5241 }
5242 self.frame_stats
5243 .shape_interior_draws
5244 .set(self.frame_stats.shape_interior_draws.get() + planned.len() as u32);
5245 self.record_run_draws(pass, tables, uniform_slot, scissor, planned.into_iter())
5246 }
5247 }
5248 }
5249
5250 fn record_run_draws(
5252 &self,
5253 pass: &mut wgpu::RenderPass<'_>,
5254 tables: ArenaBinding<'_>,
5255 uniform_slot: usize,
5256 scissor: (u32, u32, u32, u32),
5257 planned: impl ExactSizeIterator<Item = PlannedRunDraw>,
5258 ) -> Result<(), String> {
5259 self.frame_stats.add_draw_calls(planned.len() as u32);
5260 let (x, y, width, height) = scissor;
5261 pass.set_scissor_rect(x, y, width, height);
5262 self.viewport_uniforms.bind(pass, uniform_slot)?;
5263 pass.set_bind_group(1, tables.bind_group, &tables.offsets[2..]);
5264 for (slot, buffer) in tables.records.into_iter().enumerate() {
5265 pass.set_vertex_buffer(slot as u32, buffer.slice(u64::from(tables.offsets[slot])..));
5266 }
5267 let mut bound_class = None;
5268 for draw in planned {
5269 let key = draw.key;
5270 let (pipeline, fallback) = self
5271 .shape_pipelines
5272 .get(key)
5273 .ok_or_else(|| format!("shape pipeline {key:?} was not prepared"))?;
5274 if fallback {
5275 self.frame_stats
5276 .shape_pipeline_fallback_draws
5277 .set(self.frame_stats.shape_pipeline_fallback_draws.get() + 1);
5278 } else if !key.is_general() {
5279 self.frame_stats
5280 .shape_specialized_draws
5281 .set(self.frame_stats.shape_specialized_draws.get() + 1);
5282 }
5283 if bound_class != Some(draw.band_class) {
5284 pass.set_index_buffer(
5285 self.run_store.strip_index_buffer(draw.band_class).slice(..),
5286 wgpu::IndexFormat::Uint32,
5287 );
5288 bound_class = Some(draw.band_class);
5289 }
5290 pass.set_pipeline(pipeline);
5291 pass.draw_indexed(draw.indices, 0, draw.records);
5292 }
5293 Ok(())
5294 }
5295
5296 pub(crate) fn draw_store_run(
5297 &self,
5298 pass: &mut wgpu::RenderPass<'_>,
5299 batch: &StoreRunBatch,
5300 scissor: (u32, u32, u32, u32),
5301 stage: RunStage,
5302 ) -> Result<(), String> {
5303 let stored = self
5304 .run_store
5305 .stored(&batch.command)
5306 .ok_or_else(|| "a stored run left the store before its draw".to_string())?;
5307 self.draw_run_calls(
5308 pass,
5309 stored.buffers.binding(),
5310 batch.uniform_slot,
5311 &batch.draws,
5312 scissor,
5313 stage,
5314 )
5315 }
5316
5317 pub(crate) fn draw_arena(
5318 &self,
5319 pass: &mut wgpu::RenderPass<'_>,
5320 chunk: usize,
5321 uniform_slot: usize,
5322 draws: &[RunDrawCall],
5323 scissor: (u32, u32, u32, u32),
5324 stage: RunStage,
5325 ) -> Result<(), String> {
5326 self.draw_run_calls(
5327 pass,
5328 self.run_store.arena_binding(chunk),
5329 uniform_slot,
5330 draws,
5331 scissor,
5332 stage,
5333 )
5334 }
5335 #[cfg(not(target_arch = "wasm32"))]
5336 pub(crate) fn surface_format(&self) -> wgpu::TextureFormat {
5337 self.display_format
5338 }
5339
5340 pub fn device_error_count(&self) -> u64 {
5341 self.device_errors.error_count()
5342 }
5343
5344 pub(crate) fn clear_target<C: FrameCommandRecorder>(
5347 &self,
5348 recorder: &mut C,
5349 view: &wgpu::TextureView,
5350 load_op: wgpu::LoadOp<wgpu::Color>,
5351 ) {
5352 self.empty_pass(recorder, "Clear Pass", view, load_op);
5353 }
5354
5355 pub(crate) fn empty_pass<C: FrameCommandRecorder>(
5356 &self,
5357 recorder: &mut C,
5358 label: &'static str,
5359 view: &wgpu::TextureView,
5360 load_op: wgpu::LoadOp<wgpu::Color>,
5361 ) {
5362 let pass = recorder.begin_color_pass(label, view, load_op);
5363 drop(pass);
5364 recorder.record_pass();
5365 }
5366 pub(crate) fn draw_image_cmds(
5367 &self,
5368 pass: &mut wgpu::RenderPass<'_>,
5369 image_slot: &ImageSlot,
5370 uniform_slot: usize,
5371 cmds: &[ImageDrawCmd],
5372 (blend_mode, depth): (BlendMode, bool),
5373 bound: Option<(u32, u32, u32, u32)>,
5374 ) -> Result<(), String> {
5375 if cmds.is_empty() {
5376 return Ok(());
5377 }
5378 self.frame_stats.bump_images();
5379 self.frame_stats.add_draw_calls(cmds.len() as u32);
5380 let mut bound_pipeline = None;
5381 self.viewport_uniforms.bind(pass, uniform_slot)?;
5382 pass.set_index_buffer(image_slot.indices.slice(), wgpu::IndexFormat::Uint32);
5383 pass.set_vertex_buffer(0, image_slot.vertices.slice());
5384 let mut clips_bound = false;
5385 for cmd in cmds {
5386 let Some((x, y, width, height)) = bounded_scissor(cmd.scissor, bound) else {
5387 continue;
5388 };
5389 pass.set_scissor_rect(x, y, width, height);
5390 let variant = ImageVariant {
5391 depth,
5392 alpha_mask: cmd.image.alpha_mask,
5393 rounded: cmd.clip.is_some(),
5394 };
5395 if bound_pipeline != Some(variant) {
5396 pass.set_pipeline(self.image_pipeline(blend_mode, variant));
5397 bound_pipeline = Some(variant);
5398 }
5399 pass.set_bind_group(1, &cmd.image.bind_group, &[]);
5400 let instance = match cmd.clip {
5401 Some(clip) => {
5402 if !clips_bound {
5403 let clips = image_slot
5404 .clips
5405 .as_ref()
5406 .ok_or_else(|| "rounded image without clip instances".to_string())?;
5407 pass.set_vertex_buffer(1, clips.slice());
5408 clips_bound = true;
5409 }
5410 clip
5411 }
5412 None => 0,
5413 };
5414 pass.draw_indexed(
5415 cmd.index_start..(cmd.index_start + 6),
5416 0,
5417 instance..instance + 1,
5418 );
5419 }
5420 Ok(())
5421 }
5422
5423 pub(crate) fn draw_glyph_cmds(
5424 &self,
5425 pass: &mut wgpu::RenderPass<'_>,
5426 (glyph_slot, turned_slot): (Option<&BufferUpload>, Option<&BufferUpload>),
5427 uniform_slot: usize,
5428 cmds: &[GlyphDrawCmd],
5429 bound: Option<(u32, u32, u32, u32)>,
5430 frame: PassFrame,
5431 ) -> Result<(), String> {
5432 if cmds.is_empty() {
5433 return Ok(());
5434 }
5435 let whole_target = frame.scissor(bound);
5436 self.frame_stats.bump_text();
5437 let mut bound_atlas = None;
5438 let mut shared_bound: Option<bool> = None;
5441 let mut bound_pipeline: Option<GlyphQuads> = None;
5442 let mut bound_run_instances: Option<&wgpu::Buffer> = None;
5443 let mut draws = 0u32;
5444 for draw in GlyphDraws::new(cmds) {
5445 let scissor = match draw.scissor {
5446 Some(scissor) => bounded_scissor(scissor, bound),
5447 None => Some(whole_target),
5448 };
5449 let Some((x, y, width, height)) = scissor else {
5450 continue;
5451 };
5452 pass.set_scissor_rect(x, y, width, height);
5453 if !bound_atlas.is_some_and(|atlas| Rc::ptr_eq(atlas, draw.atlas)) {
5454 pass.set_bind_group(1, draw.atlas.as_ref(), &[]);
5455 bound_atlas = Some(draw.atlas);
5456 }
5457 draws += 1;
5458 match draw.step {
5459 GlyphDrawStep::Shared(instances, quads) => {
5460 if bound_pipeline != Some(quads) {
5461 pass.set_pipeline(self.glyph_atlas_pipeline(frame.depth, quads));
5462 bound_pipeline = Some(quads);
5463 }
5464 let turned = quads.turned();
5465 if shared_bound != Some(turned) {
5466 let slot =
5467 if turned { turned_slot } else { glyph_slot }.ok_or_else(|| {
5468 "shared glyph draw without glyph instances".to_string()
5469 })?;
5470 self.viewport_uniforms.bind(pass, uniform_slot)?;
5471 pass.set_vertex_buffer(0, slot.slice());
5472 shared_bound = Some(turned);
5473 bound_run_instances = None;
5474 }
5475 pass.draw(0..GLYPH_QUAD_CORNERS, instances);
5476 }
5477 GlyphDrawStep::Retained {
5478 run,
5479 uniform_slot: retained_slot,
5480 aligned,
5481 } => {
5482 let quads = GlyphQuads::plain(aligned);
5483 if bound_pipeline != Some(quads) {
5484 pass.set_pipeline(self.glyph_atlas_pipeline(frame.depth, quads));
5485 bound_pipeline = Some(quads);
5486 }
5487 shared_bound = None;
5488 self.viewport_uniforms.bind(pass, retained_slot)?;
5489 let instances = run.span.instance_buffer();
5490 if bound_run_instances != Some(instances) {
5491 pass.set_vertex_buffer(0, instances.slice(..));
5492 bound_run_instances = Some(instances);
5493 }
5494 pass.draw(0..GLYPH_QUAD_CORNERS, run.span.instances());
5495 }
5496 }
5497 }
5498 self.frame_stats.add_draw_calls(draws);
5499 Ok(())
5500 }
5501 pub(crate) fn append_image_draw_cmd(
5502 &mut self,
5503 image_draw: &ImageDraw,
5504 viewport: ViewportUniformParams,
5505 root_scale: f32,
5506 (image_vertices, image_indices): (&mut Vec<Vertex>, &mut Vec<u32>),
5507 image_clips: &mut Vec<DeviceRoundedClip>,
5508 image_cmds: &mut Vec<ImageDrawCmd>,
5509 ) -> Result<(), String> {
5510 let snap_delta = image_draw
5511 .snap_anchor
5512 .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
5513 .unwrap_or_default();
5514 let rect = image_draw.rect.translate(snap_delta.x, snap_delta.y);
5515 if rect.width <= 0.0 || rect.height <= 0.0 || image_draw.alpha <= 0.0 {
5516 return Ok(());
5517 }
5518
5519 let (mut tint, cpu_filter) = tint_for_image(image_draw.color_filter, image_draw.alpha);
5520 if tint[3] <= 0.0 {
5521 return Ok(());
5522 }
5523
5524 let filtered_image = cpu_filter
5525 .map(|filter| apply_filter_to_bitmap(&image_draw.image, filter))
5526 .transpose()?;
5527 let prepared_image = filtered_image.as_ref().unwrap_or(&image_draw.image);
5528 if let cranpose_ui_graphics::ImagePixelFormat::Alpha8 { color } = prepared_image.format() {
5529 for (channel, value) in tint[..3].iter_mut().zip(color) {
5530 *channel *= value as f32 / 255.0;
5531 }
5532 }
5533
5534 let geometry = resolve_image_geometry_with_delta(image_draw, root_scale, snap_delta);
5535 let Some(scissor) =
5536 scissor_rect_for_layer(geometry.rect, geometry.clip, root_scale, viewport)
5537 else {
5538 return Ok(());
5539 };
5540
5541 let Some(uv_rect) = image_uv_rect(&image_draw.image, image_draw.src_rect) else {
5542 return Ok(());
5543 };
5544 let device_quad = geometry.device_quad(root_scale);
5545 let index_start =
5546 push_image_quad((image_vertices, image_indices), device_quad, tint, &uv_rect);
5547 let clip = DeviceRoundedClip::of(image_draw, root_scale).map(|clip| {
5548 image_clips.push(clip);
5549 image_clips.len() as u32 - 1
5550 });
5551 image_cmds.push(ImageDrawCmd {
5552 index_start,
5553 scissor,
5554 image: self.image_binding(prepared_image, geometry.sampling)?,
5555 clip,
5556 });
5557 Ok(())
5558 }
5559
5560 pub(crate) fn upload_image_slot<C: FrameCommandRecorder>(
5562 &self,
5563 recorder: &mut C,
5564 vertices: &[Vertex],
5565 indices: &[u32],
5566 clips: &[DeviceRoundedClip],
5567 ) -> ImageSlot {
5568 ImageSlot {
5569 vertices: recorder.upload_buffer(
5570 image_vertex_spec(),
5571 &self.device,
5572 bytemuck::cast_slice(vertices),
5573 ),
5574 indices: recorder.upload_buffer(
5575 image_index_spec(),
5576 &self.device,
5577 bytemuck::cast_slice(indices),
5578 ),
5579 clips: (!clips.is_empty()).then(|| {
5580 recorder.upload_buffer(
5581 UploadAllocatorSpec::vertex(
5582 "Image Clip Buffer",
5583 std::mem::size_of::<DeviceRoundedClip>() as u64,
5584 ),
5585 &self.device,
5586 bytemuck::cast_slice(clips),
5587 )
5588 }),
5589 }
5590 }
5591
5592 pub(crate) fn upload_glyph_instances<C: FrameCommandRecorder>(
5593 &self,
5594 recorder: &mut C,
5595 instances: &[GlyphInstance],
5596 ) -> BufferUpload {
5597 recorder.upload_buffer(
5598 glyph_instance_spec(),
5599 &self.device,
5600 bytemuck::cast_slice(instances),
5601 )
5602 }
5603
5604 pub(crate) fn upload_turned_glyphs<C: FrameCommandRecorder>(
5605 &self,
5606 recorder: &mut C,
5607 glyphs: &[TurnedGlyph],
5608 ) -> BufferUpload {
5609 recorder.upload_buffer(
5610 turned_glyph_spec(),
5611 &self.device,
5612 bytemuck::cast_slice(glyphs),
5613 )
5614 }
5615
5616 fn glyph_atlas_entry_for(
5617 &mut self,
5618 glyph: &SoftwareGlyphAtlasGlyph,
5619 ) -> Result<GlyphAtlasEntry, String> {
5620 if let Some(entry) = self.text_glyph_atlas.upload_glyph(
5621 glyph,
5622 &self.queue,
5623 &mut self.frame_graph_executor,
5624 &mut self.frame_stats,
5625 ) {
5626 return Ok(entry);
5627 }
5628
5629 self.text_glyph_atlas.reset(
5630 &self.device,
5631 &self.image_bind_group_layout,
5632 GlyphSamplers {
5633 nearest: &self.image_nearest_sampler,
5634 linear: &self.image_linear_sampler,
5635 },
5636 );
5637 Err("text glyph atlas filled and was reset".to_string())
5638 }
5639
5640 fn glyph_atlas_entry_for_cached(
5641 &mut self,
5642 glyph: &SoftwareGlyphAtlasPlacement,
5643 ) -> Option<GlyphAtlasEntry> {
5644 let entry = self
5645 .text_glyph_atlas
5646 .entry(&GlyphAtlasSlotKey::new(glyph.key, glyph.color))?;
5647 self.frame_stats.record_text_glyph_atlas_hits(1);
5648 Some(entry)
5649 }
5650
5651 fn glyph_atlas_entry_for_placement(
5652 &mut self,
5653 glyph: &SoftwareGlyphAtlasPlacement,
5654 ) -> Result<GlyphAtlasEntry, String> {
5655 if let Some(entry) = self.glyph_atlas_entry_for_cached(glyph) {
5656 return Ok(entry);
5657 }
5658
5659 let Some(upload_glyph) = self.text_glyph_mask_cache.atlas_glyph_for_placement(glyph) else {
5660 return Err("text glyph placement has no retained raster mask".to_string());
5661 };
5662 self.glyph_atlas_entry_for(&upload_glyph)
5663 }
5664
5665 fn prepare_text_glyph_entries(
5669 &mut self,
5670 run_key: TextGlyphRunCacheKey,
5671 atlas_generation: u64,
5672 cached_glyph_run: Option<&RunGlyphs>,
5673 collected_run: &[SoftwareGlyphAtlasRunGlyph],
5674 entries: &mut Vec<GlyphAtlasEntry>,
5675 ) -> Result<Rc<[GlyphAtlasEntry]>, String> {
5676 entries.clear();
5677 let mut seen = RunAtlasEntries::new();
5678 if let Some(glyph_run) = cached_glyph_run {
5679 for glyph in glyph_run.iter() {
5680 entries.push(seen.entry(self, &glyph, |renderer| {
5681 renderer.glyph_atlas_entry_for_placement(&glyph)
5682 })?);
5683 }
5684 } else {
5685 for run_glyph in collected_run {
5686 entries.push(seen.entry(
5687 self,
5688 &run_glyph.placement(),
5689 |renderer| match run_glyph {
5690 SoftwareGlyphAtlasRunGlyph::Cached(placement) => {
5691 renderer.glyph_atlas_entry_for_placement(placement)
5692 }
5693 SoftwareGlyphAtlasRunGlyph::New(glyph) => {
5694 renderer.glyph_atlas_entry_for(glyph)
5695 }
5696 },
5697 )?);
5698 }
5699 }
5700
5701 let entries: Rc<[GlyphAtlasEntry]> = Rc::from(entries.as_slice());
5702 if let Some(cached) = self.text_glyph_run_cache.get_mut(&run_key) {
5703 cached.atlas_entries = Some(Rc::clone(&entries));
5704 cached.atlas_generation = atlas_generation;
5705 }
5706 Ok(entries)
5707 }
5708
5709 #[expect(clippy::too_many_arguments)]
5710 fn append_text_glyph_quad_run(
5711 &mut self,
5712 source_raster_rect: Rect,
5713 quads: GlyphRunQuads<'_>,
5714 (clip, cut): (Option<Rect>, Option<[f32; 4]>),
5715 viewport: ViewportUniformParams,
5716 root_scale: f32,
5717 glyph_instances: &mut GlyphInstances,
5718 record_cached_hits: bool,
5719 ) -> GlyphQuads {
5720 let start = glyph_instances.lens();
5721 let kind = if viewport.transform.is_identity() {
5722 let plain = &mut glyph_instances.plain;
5723 let mut aligned = true;
5724 for_each_visible_glyph(
5725 source_raster_rect,
5726 quads,
5727 (clip, cut),
5728 viewport,
5729 root_scale,
5730 |glyph| {
5731 aligned &= glyph_rect_aligned(glyph.rect, viewport.offset);
5732 plain.push(glyph);
5733 },
5734 );
5735 GlyphQuads::plain(aligned)
5736 } else {
5737 let turn = viewport.transform;
5738 let turned = &mut glyph_instances.turned;
5739 for_each_visible_glyph(
5740 source_raster_rect,
5741 quads,
5742 (clip, cut),
5743 viewport,
5744 root_scale,
5745 |glyph| turned.push(TurnedGlyph::new(glyph, turn)),
5746 );
5747 GlyphQuads::Turned
5748 };
5749 let end = glyph_instances.lens();
5750 let appended = (end.0 - start.0) + (end.1 - start.1);
5751 if record_cached_hits {
5752 self.frame_stats
5753 .record_text_glyph_atlas_hits(u32::try_from(appended).unwrap_or(u32::MAX));
5754 }
5755 kind
5756 }
5757
5758 fn retained_glyph_viewport(
5763 viewport: ViewportUniformParams,
5764 source_raster_rect: Rect,
5765 ) -> ViewportUniformParams {
5766 if !viewport.transform.is_identity() {
5767 return ViewportUniformParams {
5768 origin: [source_raster_rect.x, source_raster_rect.y],
5769 ..viewport
5770 };
5771 }
5772 ViewportUniformParams {
5773 offset: [
5774 viewport.offset[0] - source_raster_rect.x,
5775 viewport.offset[1] - source_raster_rect.y,
5776 ],
5777 ..viewport
5778 }
5779 }
5780
5781 fn retained_text_glyph_run(
5782 &mut self,
5783 cache_key: TextGlyphRunCacheKey,
5784 ) -> Option<Rc<CachedGpuTextGlyphRun>> {
5785 let atlas_generation = self.text_glyph_atlas.generation();
5786 let frame = self.text_glyph_run_frame;
5787 self.text_glyph_gpu_run_cache
5788 .get(&cache_key)
5789 .filter(|cached| cached.atlas_generation == atlas_generation)
5790 .inspect(|cached| cached.last_frame.set(frame))
5791 .cloned()
5792 }
5793
5794 fn begin_text_glyph_run_frame(&mut self) {
5798 self.text_glyph_run_frame += 1;
5799 let frame = self.text_glyph_run_frame;
5800 let demand = std::mem::take(&mut self.text_glyph_runs_drawn).saturating_mul(2);
5801 self.text_glyph_run_cache.set_cap(
5802 std::num::NonZeroUsize::new(demand.max(MIN_TEXT_GLYPH_RUN_CACHE_ITEMS))
5803 .unwrap_or(std::num::NonZeroUsize::MIN),
5804 );
5805 evict_idle(&mut self.text_glyph_gpu_run_cache, frame, |run| {
5806 run.last_frame.get()
5807 });
5808 evict_idle(&mut self.text_glyph_run_cache, frame, |run| {
5809 run.last_frame.get()
5810 });
5811 self.text_glyph_run_arena.begin_frame();
5812 }
5813
5814 fn emit_retained_text_glyph_run_if_ready(
5815 &mut self,
5816 cache_key: TextGlyphRunCacheKey,
5817 quads: GlyphRunQuads<'_>,
5818 viewport: ViewportUniformParams,
5819 source_raster_rect: Rect,
5820 scissor: (u32, u32, u32, u32),
5821 glyph_cmds: &mut Vec<GlyphDrawCmd>,
5822 ) -> bool {
5823 let Some(run) = self.retained_text_glyph_run(cache_key).or_else(|| {
5824 if self.ensure_retained_text_glyph_run(cache_key, quads) {
5825 self.retained_text_glyph_run(cache_key)
5826 } else {
5827 None
5828 }
5829 }) else {
5830 return false;
5831 };
5832 let uniform_slot =
5833 self.claim_uniform_slot(Self::retained_glyph_viewport(viewport, source_raster_rect));
5834 self.frame_stats
5835 .record_text_glyph_atlas_hits(u32::try_from(quads.len()).unwrap_or(u32::MAX));
5836 let aligned = viewport.transform.is_identity()
5838 && glyph_rect_aligned(
5839 [source_raster_rect.x, source_raster_rect.y, 0.0, 0.0],
5840 [viewport.offset[0], viewport.offset[1]],
5841 );
5842 glyph_cmds.push(GlyphDrawCmd::retained(
5843 (run, uniform_slot, aligned),
5844 scissor,
5845 self.text_glyph_atlas.bind_group(viewport.transform),
5846 ));
5847 true
5848 }
5849
5850 fn ensure_retained_text_glyph_run(
5851 &mut self,
5852 cache_key: TextGlyphRunCacheKey,
5853 quads: GlyphRunQuads<'_>,
5854 ) -> bool {
5855 let atlas_generation = self.text_glyph_atlas.generation();
5856 if self
5857 .text_glyph_gpu_run_cache
5858 .peek(&cache_key)
5859 .is_some_and(|cached| cached.atlas_generation == atlas_generation)
5860 {
5861 return true;
5862 }
5863
5864 let origin = Rect {
5865 x: 0.0,
5866 y: 0.0,
5867 width: 0.0,
5868 height: 0.0,
5869 };
5870 let Some(span) = self.text_glyph_run_arena.insert(
5871 &self.device,
5872 quads
5873 .iter()
5874 .filter_map(|quad| cached_text_glyph_instance(origin, &quad)),
5875 ) else {
5876 return false;
5877 };
5878 self.text_glyph_gpu_run_cache.put(
5879 cache_key,
5880 Rc::new(CachedGpuTextGlyphRun {
5881 span,
5882 atlas_generation,
5883 last_frame: Cell::new(self.text_glyph_run_frame),
5884 }),
5885 );
5886 true
5887 }
5888 pub(crate) fn append_text_glyph_draws(
5893 &mut self,
5894 text_draw: &TextDraw,
5895 viewport: ViewportUniformParams,
5896 root_scale: f32,
5897 glyph_instances: &mut GlyphInstances,
5898 glyph_cmds: &mut Vec<GlyphDrawCmd>,
5899 ) -> bool {
5900 let Some((logical_rect, raster_rect, clip, text_scale, static_text_motion)) =
5901 self.text_raster_geometry(text_draw, root_scale)
5902 else {
5903 return true;
5904 };
5905 if !static_text_motion {
5906 return false;
5907 }
5908 if !text_draw_is_visible_in_viewport(logical_rect, clip, viewport, root_scale) {
5909 return true;
5910 }
5911 let run_key = Self::text_glyph_run_cache_key(text_draw, raster_rect, text_scale);
5912 let mut collected_run = std::mem::take(&mut self.scratch_text_glyph_run);
5913 let mut generated_entries = std::mem::take(&mut self.scratch_text_glyph_entries);
5914 let initial_instance_len = glyph_instances.lens();
5915 let initial_cmd_len = glyph_cmds.len();
5916 let drew = self
5917 .text_glyph_run(
5918 text_draw,
5919 raster_rect,
5920 text_scale,
5921 run_key,
5922 &mut collected_run,
5923 )
5924 .is_some_and(|run| {
5925 self.append_text_glyph_run(
5926 TextGlyphRunDraw {
5927 text_draw,
5928 raster_rect,
5929 run_key,
5930 run,
5931 },
5932 (viewport, root_scale),
5933 (&collected_run, &mut generated_entries),
5934 glyph_instances,
5935 glyph_cmds,
5936 )
5937 });
5938 self.scratch_text_glyph_run = collected_run;
5939 self.scratch_text_glyph_entries = generated_entries;
5940 if !drew {
5941 glyph_instances.truncate(initial_instance_len);
5942 glyph_cmds.truncate(initial_cmd_len);
5943 }
5944 drew
5945 }
5946
5947 fn text_glyph_run(
5951 &mut self,
5952 text_draw: &TextDraw,
5953 raster_rect: Rect,
5954 text_scale: f32,
5955 run_key: TextGlyphRunCacheKey,
5956 collected_run: &mut Vec<SoftwareGlyphAtlasRunGlyph>,
5957 ) -> Option<TextGlyphRunLookup> {
5958 let atlas_generation = self.text_glyph_atlas.generation();
5959 let frame = self.text_glyph_run_frame;
5960 self.text_glyph_runs_drawn += 1;
5961 if let Some(cached) = self.text_glyph_run_cache.get(&run_key) {
5962 cached.last_frame.set(frame);
5963 return Some(TextGlyphRunLookup {
5964 glyphs: cached.glyphs.clone(),
5965 bounds: cached.bounds,
5966 cached: true,
5967 entries: (cached.atlas_generation == atlas_generation)
5968 .then(|| cached.atlas_entries.as_ref().map(Rc::clone))
5969 .flatten(),
5970 });
5971 }
5972 collected_run.clear();
5973 if collect_solid_text_atlas_run(
5974 text_draw.text.as_ref(),
5975 raster_rect,
5976 &text_draw.text_style,
5977 text_draw.color,
5978 text_draw.font_size,
5979 text_scale,
5980 &self.text_fonts,
5981 &mut self.text_glyph_mask_cache,
5982 collected_run,
5983 )
5984 .is_none()
5985 {
5986 log_text_atlas_fallback(text_draw);
5987 return None;
5988 }
5989 let Some(glyphs) = RunGlyphs::of(
5990 collected_run
5991 .iter()
5992 .map(SoftwareGlyphAtlasRunGlyph::placement),
5993 &mut self.run_glyph_scratch,
5994 ) else {
5995 log_text_atlas_fallback(text_draw);
5996 return None;
5997 };
5998 let bounds = GlyphRunBounds::of(glyphs.iter());
5999 self.frame_stats.record_text_glyph_run_collected();
6000 let cache = &mut self.text_glyph_run_cache;
6002 if cache.len() == cache.cap().get()
6003 && cache
6004 .peek_lru()
6005 .is_some_and(|(_, run)| run.last_frame.get() == frame)
6006 {
6007 cache.set_cap(cache.cap().saturating_add(cache.len()));
6008 }
6009 self.text_glyph_run_cache.put(
6010 run_key,
6011 CachedTextGlyphRun {
6012 glyphs: glyphs.clone(),
6013 bounds,
6014 atlas_entries: None,
6015 atlas_generation: 0,
6016 last_frame: Cell::new(frame),
6017 },
6018 );
6019 Some(TextGlyphRunLookup {
6020 glyphs,
6021 bounds,
6022 cached: false,
6023 entries: None,
6024 })
6025 }
6026
6027 fn append_text_glyph_run(
6031 &mut self,
6032 draw: TextGlyphRunDraw<'_>,
6033 (viewport, root_scale): (ViewportUniformParams, f32),
6034 (collected_run, generated_entries): (
6035 &[SoftwareGlyphAtlasRunGlyph],
6036 &mut Vec<GlyphAtlasEntry>,
6037 ),
6038 glyph_instances: &mut GlyphInstances,
6039 glyph_cmds: &mut Vec<GlyphDrawCmd>,
6040 ) -> bool {
6041 let TextGlyphRunDraw {
6042 text_draw,
6043 raster_rect,
6044 run_key,
6045 run,
6046 } = draw;
6047 let draw_rect = Rect {
6048 x: raster_rect.x / root_scale,
6049 y: raster_rect.y / root_scale,
6050 width: raster_rect.width / root_scale,
6051 height: raster_rect.height / root_scale,
6052 };
6053 let Some(scissor) = scissor_rect_for_layer(draw_rect, text_draw.clip, root_scale, viewport)
6054 else {
6055 return true;
6056 };
6057 let atlas_size = self.text_glyph_atlas.size();
6058
6059 let clip_needs_cut = !viewport.transform.is_identity() && text_draw.clip.is_some();
6062 if let Some(entries) = run.entries.as_ref()
6063 && entries.len() >= RETAINED_TEXT_GLYPH_RUN_MIN_QUADS
6064 && !clip_needs_cut
6065 && self.emit_retained_text_glyph_run_if_ready(
6066 run_key,
6067 GlyphRunQuads {
6068 glyphs: &run.glyphs,
6069 entries,
6070 atlas_size,
6071 bounds: run.bounds,
6072 },
6073 viewport,
6074 raster_rect,
6075 scissor,
6076 glyph_cmds,
6077 )
6078 {
6079 return true;
6080 }
6081
6082 let turned = !viewport.transform.is_identity();
6083 let instance_start = glyph_instances.len_of(turned);
6084 let (entries, entries_cached) = match run.entries {
6085 Some(entries) => (entries, true),
6086 None => {
6087 let Ok(entries) = self.prepare_text_glyph_entries(
6088 run_key,
6089 self.text_glyph_atlas.generation(),
6090 run.cached.then_some(&run.glyphs),
6091 collected_run,
6092 generated_entries,
6093 ) else {
6094 return false;
6095 };
6096 (entries, false)
6097 }
6098 };
6099 let quads = GlyphRunQuads {
6100 glyphs: &run.glyphs,
6101 entries: &entries,
6102 atlas_size: self.text_glyph_atlas.size(),
6103 bounds: run.bounds,
6104 };
6105 let cut = glyph_cut_edges(text_draw.clip, scissor, viewport, root_scale);
6106 let kind = self.append_text_glyph_quad_run(
6107 raster_rect,
6108 quads,
6109 (text_draw.clip, cut),
6110 viewport,
6111 root_scale,
6112 glyph_instances,
6113 entries_cached,
6114 );
6115 let instance_end = glyph_instances.len_of(turned);
6116 if instance_end > instance_start {
6117 let (clip, bounds) = glyph_instances.draw_clip(
6118 (instance_start..instance_end, turned),
6119 scissor,
6120 viewport,
6121 );
6122 glyph_cmds.push(GlyphDrawCmd::shared(
6123 (instance_start..instance_end, kind),
6124 clip,
6125 bounds,
6126 self.text_glyph_atlas.bind_group(viewport.transform),
6127 ));
6128 }
6129 true
6130 }
6131
6132 #[expect(clippy::too_many_arguments)]
6133 fn append_image_bitmap_draw_cmd(
6134 &mut self,
6135 image: &ImageBitmap,
6136 rect: Rect,
6137 clip: Option<Rect>,
6138 sampling: ImageSampling,
6139 viewport: ViewportUniformParams,
6140 root_scale: f32,
6141 image_vertices: &mut Vec<Vertex>,
6142 image_indices: &mut Vec<u32>,
6143 image_cmds: &mut Vec<ImageDrawCmd>,
6144 ) -> Result<(), String> {
6145 if rect.width <= 0.0 || rect.height <= 0.0 {
6146 return Ok(());
6147 }
6148
6149 let (device_quad, scissor_rect) =
6150 if sampling == ImageSampling::Nearest && root_scale.is_finite() && root_scale > 0.0 {
6151 let left_px = (rect.x * root_scale).round();
6152 let top_px = (rect.y * root_scale).round();
6153 let width_px = (rect.width * root_scale).round().max(1.0);
6154 let height_px = (rect.height * root_scale).round().max(1.0);
6155 let snapped_rect = Rect {
6156 x: left_px / root_scale,
6157 y: top_px / root_scale,
6158 width: width_px / root_scale,
6159 height: height_px / root_scale,
6160 };
6161 let right_px = left_px + width_px;
6162 let bottom_px = top_px + height_px;
6163 (
6164 [
6165 [left_px, top_px],
6166 [right_px, top_px],
6167 [left_px, bottom_px],
6168 [right_px, bottom_px],
6169 ],
6170 snapped_rect,
6171 )
6172 } else {
6173 (
6174 rect_to_quad(rect).map(|[x, y]| [x * root_scale, y * root_scale]),
6175 rect,
6176 )
6177 };
6178
6179 let Some(scissor) = scissor_rect_for_layer(scissor_rect, clip, root_scale, viewport) else {
6180 return Ok(());
6181 };
6182 let Some(uv_rect) = image_uv_rect(image, None) else {
6183 return Ok(());
6184 };
6185
6186 let index_start = push_image_quad(
6187 (image_vertices, image_indices),
6188 device_quad,
6189 [1.0, 1.0, 1.0, 1.0],
6190 &uv_rect,
6191 );
6192 image_cmds.push(ImageDrawCmd {
6193 index_start,
6194 scissor,
6195 image: self.image_binding(image, sampling)?,
6196 clip: None,
6197 });
6198 Ok(())
6199 }
6200
6201 pub(crate) fn append_text_image_draw_cmds(
6203 &mut self,
6204 text_draw: &TextDraw,
6205 viewport: ViewportUniformParams,
6206 root_scale: f32,
6207 image_vertices: &mut Vec<Vertex>,
6208 image_indices: &mut Vec<u32>,
6209 image_cmds: &mut Vec<ImageDrawCmd>,
6210 ) -> Result<(), String> {
6211 let Some((logical_rect, raster_rect, clip, text_scale, static_text_motion)) =
6212 self.text_raster_geometry(text_draw, root_scale)
6213 else {
6214 return Ok(());
6215 };
6216 if !text_draw_is_visible_in_viewport(logical_rect, clip, viewport, root_scale) {
6217 return Ok(());
6218 }
6219
6220 let raster_source = self.text_image_raster_source(
6221 text_draw,
6222 logical_rect,
6223 raster_rect,
6224 clip,
6225 root_scale,
6226 static_text_motion,
6227 );
6228 let source_draw = raster_source.draw.as_ref();
6229 let source_raster_rect = raster_source.raster_rect;
6230 let source_origin = if source_draw.text.span_styles().is_empty() {
6231 Point::new(source_raster_rect.x, source_raster_rect.y)
6232 } else {
6233 Point::new(raster_rect.x, raster_rect.y)
6234 };
6235
6236 let mut cache_key = Self::text_image_cache_key(
6237 source_draw,
6238 source_raster_rect,
6239 text_scale,
6240 static_text_motion,
6241 );
6242 if !source_draw.text.span_styles().is_empty() {
6243 let mut state = default_hash::new();
6244 cache_key.0.hash(&mut state);
6245 (source_origin.x - source_raster_rect.x)
6246 .to_bits()
6247 .hash(&mut state);
6248 (source_origin.y - source_raster_rect.y)
6249 .to_bits()
6250 .hash(&mut state);
6251 cache_key = TextImageCacheKey(state.finish());
6252 }
6253 let image = if let Some(cached) = self.text_image_cache.get(&cache_key) {
6254 self.frame_stats
6255 .record_text_image_cache_hit(cached.image.width(), cached.image.height());
6256 cached.image.clone()
6257 } else {
6258 let Some(image) = self.rasterize_text_draw_to_image(
6259 source_draw,
6260 source_raster_rect,
6261 source_origin,
6262 text_scale,
6263 ) else {
6264 return Ok(());
6265 };
6266 self.frame_stats
6267 .record_text_image_cache_miss(image.width(), image.height());
6268 self.text_image_cache.put(
6269 cache_key,
6270 CachedTextImage {
6271 image: image.clone(),
6272 },
6273 );
6274 image
6275 };
6276
6277 let draw_origin = if static_text_motion {
6278 Point::new(
6279 source_raster_rect.x / root_scale,
6280 source_raster_rect.y / root_scale,
6281 )
6282 } else {
6283 Point::new(logical_rect.x, logical_rect.y)
6284 };
6285 let draw_rect = Rect {
6286 x: draw_origin.x,
6287 y: draw_origin.y,
6288 width: image.width() as f32 / root_scale,
6289 height: image.height() as f32 / root_scale,
6290 };
6291 self.append_image_bitmap_draw_cmd(
6292 &image,
6293 draw_rect,
6294 clip,
6295 sampling_under(ImageSampling::Nearest, viewport.transform),
6296 viewport,
6297 root_scale,
6298 image_vertices,
6299 image_indices,
6300 image_cmds,
6301 )
6302 }
6303
6304 fn text_image_raster_source<'a>(
6305 &mut self,
6306 text_draw: &'a TextDraw,
6307 logical_rect: Rect,
6308 raster_rect: Rect,
6309 clip: Option<Rect>,
6310 root_scale: f32,
6311 static_text_motion: bool,
6312 ) -> TextRasterSource<'a> {
6313 let Some(clip) = clip else {
6314 return TextRasterSource {
6315 draw: Cow::Borrowed(text_draw),
6316 raster_rect,
6317 };
6318 };
6319 if !static_text_motion || text_draw.text.text().find('\n').is_none() {
6320 return TextRasterSource {
6321 draw: Cow::Borrowed(text_draw),
6322 raster_rect,
6323 };
6324 }
6325
6326 if !text_draw.text.span_styles().is_empty() {
6327 let device_clip = Rect {
6328 x: (clip.x * root_scale).floor(),
6329 y: (clip.y * root_scale).floor(),
6330 width: ((clip.x + clip.width) * root_scale).ceil() - (clip.x * root_scale).floor(),
6331 height: ((clip.y + clip.height) * root_scale).ceil()
6332 - (clip.y * root_scale).floor(),
6333 };
6334 return TextRasterSource {
6335 draw: Cow::Borrowed(text_draw),
6336 raster_rect: raster_rect.intersect(device_clip).unwrap_or(raster_rect),
6337 };
6338 }
6339
6340 let line_starts = self.text_line_index_cache.line_starts(&text_draw.text);
6341 clipped_text_raster_source_with_line_starts(
6342 text_draw,
6343 logical_rect,
6344 raster_rect,
6345 clip,
6346 root_scale,
6347 line_starts.as_ref(),
6348 )
6349 }
6350
6351 fn text_raster_geometry(
6352 &self,
6353 text_draw: &TextDraw,
6354 root_scale: f32,
6355 ) -> Option<(Rect, Rect, Option<Rect>, f32, bool)> {
6356 text_raster_geometry_for_draw(text_draw, root_scale)
6357 }
6358
6359 fn text_image_cache_key(
6360 text_draw: &TextDraw,
6361 raster_rect: Rect,
6362 text_scale: f32,
6363 static_text_motion: bool,
6364 ) -> TextImageCacheKey {
6365 let mut state = default_hash::new();
6366 hash_text_draw_for_cache(text_draw, raster_rect, text_scale, &mut state);
6367 hash_text_raster_geometry_for_cache(raster_rect, static_text_motion, &mut state);
6368 TextImageCacheKey(state.finish())
6369 }
6370
6371 fn text_glyph_run_cache_key(
6376 text_draw: &TextDraw,
6377 raster_rect: Rect,
6378 text_scale: f32,
6379 ) -> TextGlyphRunCacheKey {
6380 let mut state = default_hash::new();
6381 hash_text_draw_for_cache(text_draw, raster_rect, text_scale, &mut state);
6382 (raster_rect.width <= 0.0 || raster_rect.height <= 0.0).hash(&mut state);
6383 TextGlyphRunCacheKey(state.finish())
6384 }
6385
6386 fn rasterize_text_draw_to_image(
6387 &mut self,
6388 text_draw: &TextDraw,
6389 raster_rect: Rect,
6390 source_origin: Point,
6391 text_scale: f32,
6392 ) -> Option<ImageBitmap> {
6393 rasterize_annotated_text_region(
6394 text_draw.text.as_ref(),
6395 raster_rect,
6396 if text_draw.text.span_styles().is_empty() {
6397 Point::new(raster_rect.x, raster_rect.y)
6398 } else {
6399 source_origin
6400 },
6401 &text_draw.text_style,
6402 text_draw.color,
6403 text_draw.font_size,
6404 text_scale,
6405 &self.text_fonts,
6406 Some(&mut self.text_glyph_mask_cache),
6407 )
6408 }
6409}
6410
6411struct TextRasterSource<'a> {
6412 draw: Cow<'a, TextDraw>,
6413 raster_rect: Rect,
6414}
6415
6416fn clipped_text_raster_source_with_line_starts<'a>(
6417 text_draw: &'a TextDraw,
6418 logical_rect: Rect,
6419 raster_rect: Rect,
6420 clip: Rect,
6421 root_scale: f32,
6422 line_starts: &[usize],
6423) -> TextRasterSource<'a> {
6424 if line_starts.len() < MIN_MULTILINE_TEXT_LINES_FOR_CLIPPED_RASTER {
6425 return TextRasterSource {
6426 draw: Cow::Borrowed(text_draw),
6427 raster_rect,
6428 };
6429 }
6430
6431 let Some(visible_rect) = logical_rect.intersect(clip) else {
6432 return TextRasterSource {
6433 draw: Cow::Borrowed(text_draw),
6434 raster_rect,
6435 };
6436 };
6437
6438 let line_count = line_starts.len().max(1);
6439 let line_height = logical_rect.height / line_count as f32;
6440 if !line_height.is_finite() || line_height <= 0.0 {
6441 return TextRasterSource {
6442 draw: Cow::Borrowed(text_draw),
6443 raster_rect,
6444 };
6445 }
6446
6447 let visible_top = ((visible_rect.y - logical_rect.y) / line_height).floor() as isize;
6448 let visible_bottom =
6449 ((visible_rect.y + visible_rect.height - logical_rect.y) / line_height).ceil() as isize;
6450 let start_line = visible_top.saturating_sub(1).max(0) as usize;
6451 let end_line = (visible_bottom + 1).max(start_line as isize + 1) as usize;
6452 let end_line = end_line.min(line_count);
6453 if start_line == 0 && end_line >= line_count {
6454 return TextRasterSource {
6455 draw: Cow::Borrowed(text_draw),
6456 raster_rect,
6457 };
6458 }
6459
6460 let byte_start = line_starts[start_line];
6461 let byte_end = line_end_offset(text_draw.text.text(), line_starts, end_line - 1);
6462 if byte_start >= byte_end {
6463 return TextRasterSource {
6464 draw: Cow::Borrowed(text_draw),
6465 raster_rect,
6466 };
6467 }
6468
6469 let slice_y = logical_rect.y + start_line as f32 * line_height;
6470 let slice_height = (end_line - start_line) as f32 * line_height;
6471 let mut slice_raster_rect = Rect {
6472 x: logical_rect.x * root_scale,
6473 y: slice_y * root_scale,
6474 width: logical_rect.width * root_scale,
6475 height: slice_height * root_scale,
6476 };
6477 slice_raster_rect.x = slice_raster_rect.x.round();
6478 slice_raster_rect.y = slice_raster_rect.y.round();
6479 slice_raster_rect.width = slice_raster_rect.width.ceil().max(1.0);
6480 slice_raster_rect.height = slice_raster_rect.height.ceil().max(1.0);
6481
6482 let mut sliced_draw = text_draw.clone();
6483 sliced_draw.rect = Rect {
6484 x: logical_rect.x,
6485 y: slice_y,
6486 width: logical_rect.width,
6487 height: slice_height,
6488 };
6489 sliced_draw.text = Arc::new(text_draw.text.subsequence(byte_start..byte_end));
6490
6491 TextRasterSource {
6492 draw: Cow::Owned(sliced_draw),
6493 raster_rect: slice_raster_rect,
6494 }
6495}
6496
6497fn line_start_offsets(text: &str) -> Vec<usize> {
6498 let mut starts =
6499 Vec::with_capacity(text.as_bytes().iter().filter(|b| **b == b'\n').count() + 1);
6500 starts.push(0);
6501 starts.extend(
6502 text.char_indices()
6503 .filter_map(|(index, ch)| (ch == '\n').then_some(index + ch.len_utf8())),
6504 );
6505 starts
6506}
6507
6508fn line_end_offset(text: &str, line_starts: &[usize], line: usize) -> usize {
6509 line_starts.get(line + 1).copied().unwrap_or(text.len())
6510}
6511
6512fn align_to(value: u32, alignment: u32) -> u32 {
6513 debug_assert!(alignment > 0);
6514 value.div_ceil(alignment) * alignment
6515}
6516
6517impl GpuRenderer {
6518 fn convert_surface_pixels_to_rgba(&self, pixels: &[u8]) -> Result<Vec<u8>, String> {
6519 if !pixels.len().is_multiple_of(4) {
6520 return Err("Screenshot readback has an incomplete pixel".to_string());
6521 }
6522 Ok(pixels.to_vec())
6523 }
6524}
6525
6526pub(crate) fn scissor_rect_for_rect(
6530 rect: Rect,
6531 root_scale: f32,
6532 viewport: ViewportUniformParams,
6533) -> Option<(u32, u32, u32, u32)> {
6534 let width = viewport.width as f32;
6535 let height = viewport.height as f32;
6536 let mut left = canonicalize_device_coordinate(rect.x * root_scale);
6537 let mut top = canonicalize_device_coordinate(rect.y * root_scale);
6538 let mut right = canonicalize_device_coordinate((rect.x + rect.width) * root_scale);
6539 let mut bottom = canonicalize_device_coordinate((rect.y + rect.height) * root_scale);
6540 if !viewport.transform.is_identity() {
6541 let bounds = viewport.transform.target_bounds(Rect {
6542 x: left,
6543 y: top,
6544 width: right - left,
6545 height: bottom - top,
6546 });
6547 (left, top) = (bounds.x, bounds.y);
6548 (right, bottom) = (bounds.x + bounds.width, bounds.y + bounds.height);
6549 }
6550 let left = (left - viewport.offset[0]).clamp(0.0, width).floor();
6551 let top = (top - viewport.offset[1]).clamp(0.0, height).floor();
6552 let right = (right - viewport.offset[0]).clamp(0.0, width).ceil();
6553 let bottom = (bottom - viewport.offset[1]).clamp(0.0, height).ceil();
6554 if right <= left || bottom <= top {
6555 return None;
6556 }
6557 Some((
6558 left as u32,
6559 top as u32,
6560 (right - left) as u32,
6561 (bottom - top) as u32,
6562 ))
6563}
6564
6565fn scissor_rect_for_layer(
6566 rect: Rect,
6567 clip: Option<Rect>,
6568 root_scale: f32,
6569 viewport: ViewportUniformParams,
6570) -> Option<(u32, u32, u32, u32)> {
6571 let clipped_rect = match clip {
6572 Some(clip_rect) => rect.intersect(clip_rect)?,
6573 None => rect,
6574 };
6575 scissor_rect_for_rect(clipped_rect, root_scale, viewport)
6576}
6577fn tint_for_image(
6578 color_filter: Option<ColorFilter>,
6579 alpha: f32,
6580) -> ([f32; 4], Option<ColorFilter>) {
6581 let alpha = alpha.clamp(0.0, 1.0);
6582 match color_filter {
6583 Some(filter) if filter.supports_gpu_vertex_modulation() => {
6584 let Some(tint) = filter.gpu_vertex_tint() else {
6585 return ([1.0, 1.0, 1.0, alpha], Some(filter));
6586 };
6587 (
6588 [
6589 tint[0].clamp(0.0, 1.0),
6590 tint[1].clamp(0.0, 1.0),
6591 tint[2].clamp(0.0, 1.0),
6592 (tint[3] * alpha).clamp(0.0, 1.0),
6593 ],
6594 None,
6595 )
6596 }
6597 Some(filter) => ([1.0, 1.0, 1.0, alpha], Some(filter)),
6598 None => ([1.0, 1.0, 1.0, alpha], None),
6599 }
6600}
6601
6602#[repr(C)]
6605#[derive(Clone, Copy, Debug, Pod, Zeroable)]
6606pub(crate) struct DeviceRoundedClip {
6607 rect: [f32; 4],
6608 radius: f32,
6609}
6610
6611impl DeviceRoundedClip {
6612 const ATTRIBS: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![
6613 4 => Float32x4,
6614 5 => Float32,
6615 ];
6616
6617 fn desc() -> wgpu::VertexBufferLayout<'static> {
6618 wgpu::VertexBufferLayout {
6619 array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
6620 step_mode: wgpu::VertexStepMode::Instance,
6621 attributes: &Self::ATTRIBS,
6622 }
6623 }
6624
6625 fn of(image: &ImageDraw, root_scale: f32) -> Option<Self> {
6628 let clip = image.clip.filter(|_| image.clip_radius > 0.0)?;
6629 let device = if image.snap_anchor.is_some() {
6630 crate::geometry::canonicalized_scaled_rect(clip, root_scale)
6631 } else {
6632 Rect {
6633 x: clip.x * root_scale,
6634 y: clip.y * root_scale,
6635 width: clip.width * root_scale,
6636 height: clip.height * root_scale,
6637 }
6638 };
6639 Some(Self {
6640 rect: [device.x, device.y, device.width, device.height],
6641 radius: image.clip_radius * root_scale,
6642 })
6643 }
6644}
6645
6646fn push_image_quad(
6649 (vertices, indices): (&mut Vec<Vertex>, &mut Vec<u32>),
6650 device_quad: [[f32; 2]; 4],
6651 color: [f32; 4],
6652 uv_rect: &ImageUvRect,
6653) -> u32 {
6654 let base_vertex = vertices.len() as u32;
6655 let index_start = indices.len() as u32;
6656 indices.extend_from_slice(&[
6657 base_vertex,
6658 base_vertex + 1,
6659 base_vertex + 2,
6660 base_vertex + 2,
6661 base_vertex + 1,
6662 base_vertex + 3,
6663 ]);
6664 let corners = [
6665 [uv_rect.min[0], uv_rect.min[1]],
6666 [uv_rect.max[0], uv_rect.min[1]],
6667 [uv_rect.min[0], uv_rect.max[1]],
6668 [uv_rect.max[0], uv_rect.max[1]],
6669 ];
6670 vertices.extend(
6671 device_quad
6672 .into_iter()
6673 .zip(corners)
6674 .map(|(position, uv)| Vertex {
6675 position,
6676 color,
6677 uv,
6678 uv_bounds: uv_rect.sample_bounds,
6679 }),
6680 );
6681 index_start
6682}
6683
6684fn image_uv_rect(image: &ImageBitmap, src_rect: Option<Rect>) -> Option<ImageUvRect> {
6685 let Some(src) = src_rect else {
6686 return Some(ImageUvRect {
6687 min: [0.0, 0.0],
6688 max: [1.0, 1.0],
6689 sample_bounds: [0.0, 0.0, 1.0, 1.0],
6690 });
6691 };
6692
6693 let (u_min, u_max, u_bound_min, u_bound_max) =
6694 source_axis_uv(src.x, src.width, image.width() as f32)?;
6695 let (v_min, v_max, v_bound_min, v_bound_max) =
6696 source_axis_uv(src.y, src.height, image.height() as f32)?;
6697
6698 Some(ImageUvRect {
6699 min: [u_min, v_min],
6700 max: [u_max, v_max],
6701 sample_bounds: [u_bound_min, v_bound_min, u_bound_max, v_bound_max],
6702 })
6703}
6704
6705fn glyph_atlas_uv_rect(entry: GlyphAtlasEntry, atlas_size: u32) -> ImageUvRect {
6706 let atlas_width = atlas_size as f32;
6707 let atlas_height = atlas_size as f32;
6708 let min = [entry.x as f32 / atlas_width, entry.y as f32 / atlas_height];
6709 let max = [
6710 (entry.x + entry.width) as f32 / atlas_width,
6711 (entry.y + entry.height) as f32 / atlas_height,
6712 ];
6713 let center_min = [
6714 (entry.x as f32 + 0.5) / atlas_width,
6715 (entry.y as f32 + 0.5) / atlas_height,
6716 ];
6717 let center_max = [
6718 (entry.x as f32 + entry.width as f32 - 0.5).max(entry.x as f32 + 0.5) / atlas_width,
6719 (entry.y as f32 + entry.height as f32 - 0.5).max(entry.y as f32 + 0.5) / atlas_height,
6720 ];
6721 ImageUvRect {
6722 min,
6723 max,
6724 sample_bounds: [center_min[0], center_min[1], center_max[0], center_max[1]],
6725 }
6726}
6727
6728#[derive(Clone, Copy)]
6729pub(crate) struct ResolvedImageGeometry {
6730 pub(crate) rect: Rect,
6731 pub(crate) clip: Option<Rect>,
6732 pub(crate) sampling: ImageSampling,
6733 quad: [[f32; 2]; 4],
6734 snap_anchored: bool,
6735}
6736
6737pub(crate) fn resolve_image_geometry(image: &ImageDraw, root_scale: f32) -> ResolvedImageGeometry {
6738 let snap_delta = image
6739 .snap_anchor
6740 .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
6741 .unwrap_or_default();
6742 resolve_image_geometry_with_delta(image, root_scale, snap_delta)
6743}
6744
6745fn resolve_image_geometry_with_delta(
6746 image: &ImageDraw,
6747 root_scale: f32,
6748 snap_delta: Point,
6749) -> ResolvedImageGeometry {
6750 let mut rect = image.rect.translate(snap_delta.x, snap_delta.y);
6751 let mut quad = translate_quad(image.quad, snap_delta);
6752 snap_nearest_image_to_device_pixels(image.sampling, &mut rect, &mut quad, root_scale);
6753 ResolvedImageGeometry {
6754 rect,
6755 clip: image.clip,
6756 sampling: image.sampling,
6757 quad,
6758 snap_anchored: image.snap_anchor.is_some(),
6759 }
6760}
6761
6762impl ResolvedImageGeometry {
6763 pub(crate) fn device_quad(self, root_scale: f32) -> [[f32; 2]; 4] {
6764 nearest_image_device_quad(self.sampling, self.quad, root_scale).unwrap_or_else(|| {
6765 if self.snap_anchored {
6766 canonicalized_scaled_quad(self.quad, root_scale)
6767 } else {
6768 scaled_quad(self.quad, root_scale)
6769 }
6770 })
6771 }
6772}
6773
6774fn snap_nearest_image_to_device_pixels(
6775 sampling: ImageSampling,
6776 rect: &mut Rect,
6777 quad: &mut [[f32; 2]; 4],
6778 root_scale: f32,
6779) {
6780 if sampling != ImageSampling::Nearest || !root_scale.is_finite() || root_scale <= 0.0 {
6781 return;
6782 }
6783
6784 let Some(quad_rect) = axis_aligned_quad_rect(*quad) else {
6785 return;
6786 };
6787
6788 let left_px = (quad_rect.x * root_scale).round();
6789 let top_px = (quad_rect.y * root_scale).round();
6790 let width_px = (quad_rect.width * root_scale).round().max(1.0);
6791 let height_px = (quad_rect.height * root_scale).round().max(1.0);
6792 let snapped = Rect {
6793 x: left_px / root_scale,
6794 y: top_px / root_scale,
6795 width: width_px / root_scale,
6796 height: height_px / root_scale,
6797 };
6798
6799 *rect = snapped;
6800 *quad = crate::rect_to_quad(snapped);
6801}
6802
6803fn nearest_image_device_quad(
6804 sampling: ImageSampling,
6805 quad: [[f32; 2]; 4],
6806 root_scale: f32,
6807) -> Option<[[f32; 2]; 4]> {
6808 if sampling != ImageSampling::Nearest || !root_scale.is_finite() || root_scale <= 0.0 {
6809 return None;
6810 }
6811
6812 let rect = axis_aligned_quad_rect(quad)?;
6813 let left_px = (rect.x * root_scale).round();
6814 let top_px = (rect.y * root_scale).round();
6815 let width_px = (rect.width * root_scale).round().max(1.0);
6816 let height_px = (rect.height * root_scale).round().max(1.0);
6817 let right_px = left_px + width_px;
6818 let bottom_px = top_px + height_px;
6819 Some([
6820 [left_px, top_px],
6821 [right_px, top_px],
6822 [left_px, bottom_px],
6823 [right_px, bottom_px],
6824 ])
6825}
6826
6827fn source_axis_uv(start: f32, extent: f32, image_extent: f32) -> Option<(f32, f32, f32, f32)> {
6828 if !start.is_finite()
6829 || !extent.is_finite()
6830 || !image_extent.is_finite()
6831 || extent == 0.0
6832 || image_extent <= 0.0
6833 {
6834 return None;
6835 }
6836
6837 let end = start + extent;
6838 let edge_min = start.min(end).clamp(0.0, image_extent);
6839 let edge_max = start.max(end).clamp(0.0, image_extent);
6840 if edge_max <= edge_min {
6841 return None;
6842 }
6843
6844 let center_min = edge_min + 0.5;
6845 let center_max = edge_max - 0.5;
6846 let (bound_min, bound_max) = if center_min <= center_max {
6847 (center_min, center_max)
6848 } else {
6849 let center = (edge_min + edge_max) * 0.5;
6850 (center, center)
6851 };
6852
6853 Some((
6854 edge_min / image_extent,
6855 edge_max / image_extent,
6856 bound_min / image_extent,
6857 bound_max / image_extent,
6858 ))
6859}
6860
6861fn apply_filter_to_bitmap(image: &ImageBitmap, filter: ColorFilter) -> Result<ImageBitmap, String> {
6862 let pixel_count = image.width() as usize * image.height() as usize;
6863 let mut filtered = Vec::with_capacity(pixel_count * 4);
6864 for index in 0..pixel_count {
6865 let pixel = image.rgba8_pixel(index);
6866 let rgba = [
6867 pixel[0] as f32 / 255.0,
6868 pixel[1] as f32 / 255.0,
6869 pixel[2] as f32 / 255.0,
6870 pixel[3] as f32 / 255.0,
6871 ];
6872 let out = filter.apply_rgba(rgba);
6873 filtered.push((out[0].clamp(0.0, 1.0) * 255.0).round() as u8);
6874 filtered.push((out[1].clamp(0.0, 1.0) * 255.0).round() as u8);
6875 filtered.push((out[2].clamp(0.0, 1.0) * 255.0).round() as u8);
6876 filtered.push((out[3].clamp(0.0, 1.0) * 255.0).round() as u8);
6877 }
6878 ImageBitmap::from_rgba8(image.width(), image.height(), filtered)
6879 .map_err(|error| format!("failed to build filtered bitmap: {error}"))
6880}
6881
6882fn sampling_under(sampling: ImageSampling, transform: SegmentTransform) -> ImageSampling {
6886 if transform.is_identity() {
6887 sampling
6888 } else {
6889 ImageSampling::Linear
6890 }
6891}
6892
6893pub(crate) fn shadow_composite_mask(
6897 shadow: &ShadowDraw,
6898 snap_anchor: Option<SnapAnchor>,
6899 root_scale: f32,
6900) -> Option<RoundedCompositeMask> {
6901 inner_shadow_composite_mask(shadow, root_scale).or_else(|| {
6902 shadow.rounded_clip.map(|clip| RoundedCompositeMask {
6903 rect: mask_rect(anchored_device_rect(clip.rect, snap_anchor, root_scale)),
6904 radii: clip.radii.map(|radius| radius * root_scale),
6905 })
6906 })
6907}
6908
6909fn shadow_scene(
6913 shapes: Option<&RunDraw>,
6914 texts: &[TextDraw],
6915 input_margin: f32,
6916) -> CompositorScene {
6917 let mut scene = CompositorScene::new();
6918 if let Some(run) = shapes {
6919 scene.push_run(run.clone());
6920 }
6921 for text in texts {
6922 let z_index = scene.next_z();
6923 scene.draw_ops.push(DrawOp {
6924 z_index,
6925 kind: DrawOpKind::Text(scene.texts.len()),
6926 });
6927 let mut source_text = text.clone();
6928 source_text.clip = source_text
6929 .clip
6930 .map(|clip| expand_rect(clip, input_margin, input_margin));
6931 scene.texts.push(source_text);
6932 scene.next_z += 1;
6933 }
6934 scene
6935}
6936
6937fn device_pixel_bounds(
6940 rect: Rect,
6941 root_scale: f32,
6942 max_texture_dim: u32,
6943) -> Option<DevicePixelBounds> {
6944 let x = (rect.x * root_scale).floor();
6945 let y = (rect.y * root_scale).floor();
6946 let right = ((rect.x + rect.width) * root_scale).ceil();
6947 let bottom = ((rect.y + rect.height) * root_scale).ceil();
6948 let width = (right - x).max(0.0) as u32;
6949 let height = (bottom - y).max(0.0) as u32;
6950 if width == 0 || height == 0 || width > max_texture_dim || height > max_texture_dim {
6951 return None;
6952 }
6953 Some(DevicePixelBounds {
6954 x,
6955 y,
6956 width,
6957 height,
6958 })
6959}
6960fn inner_shadow_composite_mask(
6961 shadow: &ShadowDraw,
6962 root_scale: f32,
6963) -> Option<RoundedCompositeMask> {
6964 let run = shadow.shapes.as_ref()?;
6965 if !run
6966 .tables()
6967 .shapes
6968 .iter()
6969 .any(|record| record.blend_mode() == BlendMode::DstOut)
6970 {
6971 return None;
6972 }
6973 let fill = run.tables().shapes.get(0)?;
6974 let rect = run.placement.translated_bounds(fill.stored_rect());
6975 if rect.width <= 0.0 || rect.height <= 0.0 {
6976 return None;
6977 }
6978 let resolved =
6979 cranpose_ui_graphics::RoundedCornerShape::with_radii(cranpose_ui_graphics::CornerRadii {
6980 top_left: fill.radii[0],
6981 top_right: fill.radii[1],
6982 bottom_right: fill.radii[2],
6983 bottom_left: fill.radii[3],
6984 })
6985 .resolve(rect.width, rect.height);
6986 let radii = [
6987 resolved.top_left * root_scale,
6988 resolved.top_right * root_scale,
6989 resolved.bottom_left * root_scale,
6990 resolved.bottom_right * root_scale,
6991 ];
6992
6993 Some(RoundedCompositeMask {
6994 rect: mask_rect(anchored_device_rect(
6995 rect,
6996 run.placement.snap_anchor,
6997 root_scale,
6998 )),
6999 radii,
7000 })
7001}
7002
7003#[derive(Clone, Debug, PartialEq, Eq)]
7006pub(crate) struct PlannedRunDraw {
7007 pub(crate) key: ShapePipelineKey,
7008 pub(crate) band_class: u8,
7009 pub(crate) indices: std::ops::Range<u32>,
7010 pub(crate) records: std::ops::Range<u32>,
7011}
7012
7013impl PlannedRunDraw {
7014 fn paint(draw: &RunDrawCall) -> Self {
7016 Self {
7017 key: draw.key,
7018 band_class: draw.band_class,
7019 indices: draw.indices(),
7020 records: draw.records.clone(),
7021 }
7022 }
7023}
7024
7025pub(crate) fn interior_run_draws(draws: &[RunDrawCall]) -> SmallVec<[PlannedRunDraw; 4]> {
7033 struct Stretch {
7034 key: ShapePipelineKey,
7035 start: u32,
7036 span: Option<PlannedRunDraw>,
7037 }
7038 let mut planned: SmallVec<[PlannedRunDraw; 4]> = SmallVec::new();
7039 let mut stretch: Option<Stretch> = None;
7040 for draw in draws.iter().rev() {
7041 let Some(key) = draw.key.interior() else {
7042 planned.extend(stretch.take().and_then(|open| open.span));
7043 continue;
7044 };
7045 if stretch
7046 .as_ref()
7047 .is_some_and(|open| open.key != key || open.start != draw.records.end)
7048 {
7049 planned.extend(stretch.take().and_then(|open| open.span));
7050 }
7051 let open = stretch.get_or_insert(Stretch {
7052 key,
7053 start: draw.records.end,
7054 span: None,
7055 });
7056 open.start = draw.records.start;
7057 if !draw.occluders {
7058 continue;
7059 }
7060 match &mut open.span {
7061 Some(span) => span.records.start = draw.records.start,
7062 None => {
7063 open.span = Some(PlannedRunDraw {
7064 key,
7065 band_class: draw.band_class,
7066 indices: 0..cranpose_ui_graphics::strip_indices(1),
7067 records: draw.records.clone(),
7068 });
7069 }
7070 }
7071 }
7072 planned.extend(stretch.and_then(|open| open.span));
7073 planned
7074}
7075
7076fn evict_idle<K: Clone + Eq + std::hash::Hash, V>(
7080 cache: &mut BoundedLruCache<K, V>,
7081 frame: u64,
7082 last_frame: impl Fn(&V) -> u64,
7083) {
7084 while cache.peek_lru().is_some_and(|(_, value)| {
7085 frame.saturating_sub(last_frame(value)) > TEXT_GLYPH_RUN_IDLE_FRAMES
7086 }) {
7087 cache.pop_lru();
7088 }
7089}
7090
7091fn window_draws(draws: &mut SmallVec<[RunDrawCall; 8]>, window: &std::ops::Range<u32>) {
7092 let mut relative = 0u32;
7093 draws.retain(|draw| {
7094 let count = draw.records.end - draw.records.start;
7095 let first = relative;
7096 relative += count;
7097 let keep_start = window.start.max(first).min(first + count);
7098 let keep_end = window.end.min(first + count).max(keep_start);
7099 draw.records =
7100 draw.records.start + (keep_start - first)..draw.records.start + (keep_end - first);
7101 draw.records.start < draw.records.end
7102 });
7103}
7104
7105#[cfg(test)]
7106#[path = "tests/render_text_bounds_tests.rs"]
7107mod text_bounds_tests;
7108
7109#[cfg(test)]
7110#[path = "tests/render_retained_glyph_tests.rs"]
7111mod retained_glyph_tests;
7112
7113#[cfg(test)]
7114#[path = "tests/frame_clear_tests.rs"]
7115mod frame_clear_tests;
7116
7117#[cfg(test)]
7118#[path = "tests/render_clip_scissor_tests.rs"]
7119mod clip_scissor_tests;
7120
7121#[cfg(test)]
7122#[path = "tests/glyph_kind_tests.rs"]
7123mod glyph_kind_tests;
7124
7125#[cfg(test)]
7126#[path = "tests/glyph_run_bounds_tests.rs"]
7127mod glyph_run_bounds_tests;
7128
7129#[cfg(test)]
7130#[path = "tests/shape_variant_tests.rs"]
7131mod shape_variant_tests;