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: Vec<((u32, u32), wgpu::TextureView)>,
3040 uniform_bind_group_layout: wgpu::BindGroupLayout,
3041 image_bind_group_layout: wgpu::BindGroupLayout,
3042 image_nearest_sampler: wgpu::Sampler,
3043 image_linear_sampler: wgpu::Sampler,
3044 text_fonts: SoftwareTextFontSet,
3045 viewport_uniforms: ViewportUniforms,
3046 run_store: RunStore,
3047 image_texture_cache: BoundedLruCache<u64, CachedImageTexture>,
3048 image_texture_cache_bytes: usize,
3049 text_image_cache: BoundedLruCache<TextImageCacheKey, CachedTextImage>,
3050 text_glyph_atlas: TextGlyphAtlas,
3051 text_glyph_run_cache: BoundedLruCache<TextGlyphRunCacheKey, CachedTextGlyphRun>,
3052 text_glyph_gpu_run_cache: BoundedLruCache<TextGlyphRunCacheKey, Rc<CachedGpuTextGlyphRun>>,
3053 text_glyph_run_arena: GlyphRunArena,
3054 text_glyph_run_frame: u64,
3055 text_glyph_runs_drawn: usize,
3057 text_glyph_mask_cache: SoftwareGlyphRasterCache,
3058 text_line_index_cache: TextLineIndexCache,
3059 pub(crate) scratch_image_vertices: Vec<Vertex>,
3060 pub(crate) scratch_image_indices: Vec<u32>,
3061 pub(crate) scratch_glyph_instances: GlyphInstances,
3062 pub(crate) scratch_image_cmds: Vec<ImageDrawCmd>,
3063 pub(crate) scratch_image_clips: Vec<DeviceRoundedClip>,
3064 pub(crate) scratch_glyph_cmds: Vec<GlyphDrawCmd>,
3065 pub(crate) scratch_glyph_moved: Vec<GlyphDrawCmd>,
3066 pub(crate) scratch_shadow_instances: Vec<ShadowInstance>,
3067 pub(crate) scratch_arena_draws: Vec<RunDrawCall>,
3068 scratch_text_glyph_run: Vec<SoftwareGlyphAtlasRunGlyph>,
3069 scratch_text_glyph_entries: Vec<GlyphAtlasEntry>,
3070 run_glyph_scratch: RunGlyphScratch,
3071 frame_graph_executor: WgpuFrameGraphExecutor,
3072 pub(crate) stage_side_scratch: StageSideScratch,
3073 deferred_offscreen_releases: Vec<OffscreenTarget>,
3074 pub(crate) effect_renderer: EffectRenderer,
3075 pub(crate) layer_cache: LayerCache,
3076 pub(crate) ablation: Ablation,
3077 pub(crate) ablation_frames: u32,
3078 pub(crate) nesting_overflow_reported: bool,
3079 pub(crate) backdrop_gates: HashMap<NodeId, AdmissionGate>,
3080 pub(crate) fill_gates: HashMap<DrawCommandId, AdmissionGate>,
3081 pub(crate) effect_gates: HashMap<NodeId, AdmissionGate>,
3082 pub(crate) source_gates: HashMap<NodeId, AdmissionGate>,
3083 transparent_sources: HashMap<(u32, u32), Rc<OffscreenTarget>>,
3084 shadow_surface_cache: BoundedLruCache<ShadowSurfaceCacheKey, CachedShadowSurface>,
3085 shadow_surface_cache_bytes: u64,
3086 pub(crate) frame_stats: gpu_stats::FrameStats,
3087 last_frame_stats: Option<gpu_stats::FrameStatsSnapshot>,
3088 pending_frame_warmup_frames: u8,
3089 frame_count: u64,
3090 shader_warm_ups_queued: usize,
3092}
3093
3094pub fn frame_clear_color(transparent: bool) -> wgpu::Color {
3097 if transparent {
3098 wgpu::Color::TRANSPARENT
3099 } else {
3100 CLEAR_COLOR
3101 }
3102}
3103
3104fn image_sampler_descriptor(sampling: ImageSampling) -> wgpu::SamplerDescriptor<'static> {
3105 let filter = match sampling {
3106 ImageSampling::Nearest => wgpu::FilterMode::Nearest,
3107 ImageSampling::Linear => wgpu::FilterMode::Linear,
3108 };
3109 wgpu::SamplerDescriptor {
3110 label: Some(match sampling {
3111 ImageSampling::Nearest => "Nearest Image Sampler",
3112 ImageSampling::Linear => "Linear Image Sampler",
3113 }),
3114 address_mode_u: wgpu::AddressMode::ClampToEdge,
3115 address_mode_v: wgpu::AddressMode::ClampToEdge,
3116 address_mode_w: wgpu::AddressMode::ClampToEdge,
3117 mag_filter: filter,
3118 min_filter: filter,
3119 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
3120 ..Default::default()
3121 }
3122}
3123
3124pub(crate) struct GpuRendererInit {
3127 pub(crate) device: Arc<wgpu::Device>,
3128 pub(crate) queue: Arc<wgpu::Queue>,
3129 pub(crate) surface_format: wgpu::TextureFormat,
3130 pub(crate) adapter_backend: wgpu::Backend,
3131 pub(crate) adapter_downlevel: wgpu::DownlevelFlags,
3132 pub(crate) text_fonts: SoftwareTextFontSet,
3133 pub(crate) renderer_epoch: u64,
3134 pub(crate) pipeline_compilation: PipelineCompilation,
3135}
3136
3137impl GpuRenderer {
3138 pub fn new(init: GpuRendererInit) -> Self {
3139 let GpuRendererInit {
3140 device,
3141 queue,
3142 surface_format,
3143 adapter_backend,
3144 adapter_downlevel,
3145 text_fonts,
3146 renderer_epoch,
3147 pipeline_compilation,
3148 } = init;
3149 let display_format = surface_format;
3150 let construction_started = Instant::now();
3151 let device_errors = Arc::new(DeviceErrorSentry::default());
3152 if survive_gpu_errors_enabled() {
3153 let sentry = Arc::clone(&device_errors);
3154 device.on_uncaptured_error(Arc::new(move |error| sentry.record(&error)));
3155 }
3156 let composition_format = crate::offscreen::composition_format(display_format);
3157 device.set_device_lost_callback(|reason, message| {
3158 log::error!("[gpu-device] device lost ({reason:?}): {message}");
3159 });
3160 let mut run_store = RunStore::new(
3161 &device,
3162 RunBufferMode::for_device(&device, adapter_downlevel),
3163 );
3164 let uniform_bind_group_layout =
3165 device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3166 label: Some("Viewport Uniform Bind Group Layout"),
3167 entries: &[wgpu::BindGroupLayoutEntry {
3168 binding: 0,
3169 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
3170 ty: wgpu::BindingType::Buffer {
3171 ty: wgpu::BufferBindingType::Uniform,
3172 has_dynamic_offset: true,
3173 min_binding_size: wgpu::BufferSize::new(
3174 std::mem::size_of::<Uniforms>() as u64
3175 ),
3176 },
3177 count: None,
3178 }],
3179 });
3180 let image_bind_group_layout =
3181 device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3182 label: Some("Image Texture Bind Group Layout"),
3183 entries: &[
3184 wgpu::BindGroupLayoutEntry {
3185 binding: 0,
3186 visibility: wgpu::ShaderStages::FRAGMENT,
3187 ty: wgpu::BindingType::Texture {
3188 multisampled: false,
3189 view_dimension: wgpu::TextureViewDimension::D2,
3190 sample_type: wgpu::TextureSampleType::Float { filterable: true },
3191 },
3192 count: None,
3193 },
3194 wgpu::BindGroupLayoutEntry {
3195 binding: 1,
3196 visibility: wgpu::ShaderStages::FRAGMENT,
3197 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
3198 count: None,
3199 },
3200 ],
3201 });
3202 let image_nearest_sampler =
3203 device.create_sampler(&image_sampler_descriptor(ImageSampling::Nearest));
3204 let image_linear_sampler =
3205 device.create_sampler(&image_sampler_descriptor(ImageSampling::Linear));
3206 let text_glyph_atlas = TextGlyphAtlas::new(
3207 &device,
3208 &image_bind_group_layout,
3209 GlyphSamplers {
3210 nearest: &image_nearest_sampler,
3211 linear: &image_linear_sampler,
3212 },
3213 TEXT_GLYPH_ATLAS_MIN_SIZE,
3214 );
3215 let viewport_uniforms = ViewportUniforms::default();
3216
3217 static GLASS_MATERIAL_FOLDS: DebugToggle =
3218 DebugToggle::new("CRANPOSE_GLASS_MATERIAL_FOLDS");
3219 if GLASS_MATERIAL_FOLDS.equals("1") {
3220 cranpose_ui_graphics::set_glass_material_folds(true);
3221 } else if GLASS_MATERIAL_FOLDS.equals("0") {
3222 cranpose_ui_graphics::set_glass_material_folds(false);
3223 }
3224 log::info!(
3225 "[gpu-init] liquid glass material folds {}",
3226 if cranpose_ui_graphics::glass_material_folds_enabled() {
3227 "on: a pipeline per material's feature set"
3228 } else {
3229 "off: one pipeline per blend mode"
3230 }
3231 );
3232
3233 #[cfg(not(target_arch = "wasm32"))]
3234 let crate::pipeline_disk_cache::Loaded {
3235 cache: pipeline_cache,
3236 records,
3237 updated,
3238 holds_recorded,
3239 } = crate::pipeline_disk_cache::load(&device);
3240 #[cfg(not(target_arch = "wasm32"))]
3241 let first_screen: Vec<u64> = records
3242 .shapes
3243 .iter()
3244 .filter(|shape| shape.first_screen)
3245 .map(|shape| shape.entry)
3246 .collect();
3247 #[cfg(target_arch = "wasm32")]
3248 let (pipeline_cache, first_screen): (Option<wgpu::PipelineCache>, Vec<u64>) =
3249 (None, Vec::new());
3250 let recorder = crate::pipeline_recorder::PipelineRecorder::default();
3251 #[cfg(not(target_arch = "wasm32"))]
3252 let pipeline_cache_watcher = crate::pipeline_disk_cache::spawn_persist_watcher(
3253 pipeline_cache.clone(),
3254 Arc::clone(&records),
3255 recorder.clone(),
3256 );
3257
3258 let effects_started = Instant::now();
3259 let pipeline_compiler = PipelineCompiler::for_compilation(pipeline_compilation);
3260 let effect_renderer = EffectRenderer::new(
3261 &device,
3262 pipeline_compiler.clone(),
3263 pipeline_cache.clone(),
3264 composition_format,
3265 adapter_backend,
3266 recorder.clone(),
3267 );
3268 let output_converter = OutputConverter::new(&device, adapter_backend, display_format);
3269 let screenshot_converter =
3270 OutputConverter::new(&device, adapter_backend, wgpu::TextureFormat::Rgba8Unorm);
3271 let effects_ms = instant_ms(effects_started, Instant::now());
3272 let mut frame_graph_executor = WgpuFrameGraphExecutor::new();
3273 frame_graph_executor.init_pass_timing(&device, &queue);
3274 let shape_shader = SharedShader::new(
3275 &device,
3276 adapter_backend,
3277 "Shape Shader",
3278 shape_shader_source(run_store.mode()),
3279 &[Some(&uniform_bind_group_layout), Some(run_store.layout())],
3280 );
3281 if run_store.mode().trig_fill {
3282 let fill = ArcTrigFill::new(
3283 &device,
3284 adapter_backend,
3285 pipeline_cache.clone(),
3286 shape_shader.clone(),
3287 recorder.clone(),
3288 );
3289 if first_screen.contains(&crate::arc_trig_fill::FIRST_SCREEN_KEY) {
3290 fill.warm(&pipeline_compiler);
3291 }
3292 run_store.attach_trig_fill(fill);
3293 }
3294 let shape_pipelines = ShapePipelines::new(
3295 ShapePipelineFactory {
3296 device: Arc::clone(&device),
3297 cache: pipeline_cache.clone(),
3298 format: composition_format,
3299 shader: shape_shader,
3300 mode: run_store.mode(),
3301 },
3302 adapter_backend,
3303 &pipeline_compiler,
3304 first_screen
3305 .into_iter()
3306 .filter(|&bits| bits != crate::arc_trig_fill::FIRST_SCREEN_KEY)
3307 .filter_map(ShapePipelineKey::from_bits),
3308 recorder.clone(),
3309 );
3310 let image_layouts = [
3311 Some(&uniform_bind_group_layout),
3312 Some(&image_bind_group_layout),
3313 ];
3314 let image_shader = SharedShader::new(
3315 &device,
3316 adapter_backend,
3317 "Image Shader",
3318 || shaders::image_shader().into(),
3319 &image_layouts,
3320 );
3321 let glyph_atlas_shader = SharedShader::new(
3322 &device,
3323 adapter_backend,
3324 "Glyph Atlas Shader",
3325 || shaders::GLYPH_ATLAS_SHADER.into(),
3326 &image_layouts,
3327 );
3328 let rrect_shadow_shader = SharedShader::new(
3329 &device,
3330 adapter_backend,
3331 "Round Rect Shadow Shader",
3332 || shaders::RRECT_SHADOW_SHADER.into(),
3333 &[Some(&uniform_bind_group_layout)],
3334 );
3335
3336 let mut renderer = Self {
3337 device,
3338 queue,
3339 device_errors,
3340 renderer_epoch,
3341 composition_format,
3342 #[cfg(not(target_arch = "wasm32"))]
3343 display_format,
3344 composition_target: None,
3345 output_converter,
3346 screenshot_converter,
3347 adapter_backend,
3348 pipeline_cache,
3349 #[cfg(not(target_arch = "wasm32"))]
3350 _pipeline_cache_watcher: pipeline_cache_watcher,
3351 #[cfg(not(target_arch = "wasm32"))]
3352 recent_after_update: updated.then(|| Arc::clone(&records)),
3353 recorder,
3354 #[cfg(not(target_arch = "wasm32"))]
3355 landing: pipeline_compiler.landing(),
3356 #[cfg(not(target_arch = "wasm32"))]
3357 built_at_frame_start: 0,
3358 drew_placeholder: false,
3359 shape_pipelines,
3360 image_pipeline: [
3361 FixedPipeline::new("image/src-over"),
3362 FixedPipeline::new("image/src-over/depth"),
3363 FixedPipeline::new("image/src-over/alpha-mask"),
3364 FixedPipeline::new("image/src-over/alpha-mask/depth"),
3365 FixedPipeline::new("image/src-over/rounded"),
3366 FixedPipeline::new("image/src-over/rounded/depth"),
3367 FixedPipeline::new("image/src-over/alpha-mask/rounded"),
3368 FixedPipeline::new("image/src-over/alpha-mask/rounded/depth"),
3369 ],
3370 image_pipeline_dst_out: [
3371 FixedPipeline::new("image/dst-out"),
3372 FixedPipeline::new("image/dst-out/depth"),
3373 FixedPipeline::new("image/dst-out/alpha-mask"),
3374 FixedPipeline::new("image/dst-out/alpha-mask/depth"),
3375 FixedPipeline::new("image/dst-out/rounded"),
3376 FixedPipeline::new("image/dst-out/rounded/depth"),
3377 FixedPipeline::new("image/dst-out/alpha-mask/rounded"),
3378 FixedPipeline::new("image/dst-out/alpha-mask/rounded/depth"),
3379 ],
3380 glyph_atlas_pipeline: [
3381 FixedPipeline::new("glyph/atlas"),
3382 FixedPipeline::new("glyph/atlas/depth"),
3383 FixedPipeline::new("glyph/atlas/aligned"),
3384 FixedPipeline::new("glyph/atlas/aligned/depth"),
3385 FixedPipeline::new("glyph/atlas/turned"),
3386 FixedPipeline::new("glyph/atlas/turned/depth"),
3387 ],
3388 rrect_shadow_pipeline: [
3389 FixedPipeline::new("shadow/rrect"),
3390 FixedPipeline::new("shadow/rrect/depth"),
3391 ],
3392 image_shader,
3393 glyph_atlas_shader,
3394 rrect_shadow_shader,
3395 depth_targets: Vec::new(),
3396 uniform_bind_group_layout,
3397 image_bind_group_layout,
3398 image_nearest_sampler,
3399 image_linear_sampler,
3400 text_fonts,
3401 viewport_uniforms,
3402 run_store,
3403 image_texture_cache: BoundedLruCache::with_capacity_at_least_one(
3404 MAX_TEXTURE_CACHE_ITEMS,
3405 ),
3406 image_texture_cache_bytes: 0,
3407 text_image_cache: BoundedLruCache::with_capacity_at_least_one(
3408 MAX_TEXT_IMAGE_CACHE_ITEMS,
3409 ),
3410 text_glyph_atlas,
3411 text_glyph_run_cache: BoundedLruCache::with_capacity_at_least_one(
3412 MIN_TEXT_GLYPH_RUN_CACHE_ITEMS,
3413 ),
3414 text_glyph_runs_drawn: 0,
3415 text_glyph_gpu_run_cache: BoundedLruCache::with_capacity_at_least_one(
3416 MAX_TEXT_GLYPH_GPU_RUN_CACHE_ITEMS,
3417 ),
3418 text_glyph_run_arena: GlyphRunArena::default(),
3419 text_glyph_run_frame: 0,
3420 text_glyph_mask_cache: SoftwareGlyphRasterCache::with_capacity_at_least_one(
3421 MAX_TEXT_GLYPH_MASK_CACHE_ITEMS,
3422 ),
3423 text_line_index_cache: TextLineIndexCache::new(MAX_TEXT_LINE_INDEX_CACHE_ITEMS),
3424 scratch_image_vertices: Vec::new(),
3425 scratch_image_indices: Vec::new(),
3426 scratch_glyph_instances: GlyphInstances::default(),
3427 scratch_image_cmds: Vec::new(),
3428 scratch_image_clips: Vec::new(),
3429 scratch_glyph_cmds: Vec::new(),
3430 scratch_glyph_moved: Vec::new(),
3431 scratch_shadow_instances: Vec::new(),
3432 scratch_arena_draws: Vec::new(),
3433 scratch_text_glyph_run: Vec::new(),
3434 scratch_text_glyph_entries: Vec::new(),
3435 run_glyph_scratch: RunGlyphScratch::default(),
3436 frame_graph_executor,
3437 stage_side_scratch: StageSideScratch::default(),
3438 deferred_offscreen_releases: Vec::new(),
3439 effect_renderer,
3440 layer_cache: LayerCache::new(),
3441 ablation: Ablation::default(),
3442 ablation_frames: 0,
3443 nesting_overflow_reported: false,
3444 backdrop_gates: HashMap::default(),
3445 fill_gates: HashMap::default(),
3446 effect_gates: HashMap::default(),
3447 source_gates: HashMap::default(),
3448 transparent_sources: HashMap::default(),
3449 shadow_surface_cache: BoundedLruCache::with_capacity_at_least_one(
3450 MAX_SHADOW_SURFACE_CACHE_ITEMS,
3451 ),
3452 shadow_surface_cache_bytes: 0,
3453 frame_stats: gpu_stats::FrameStats::default(),
3454 last_frame_stats: None,
3455 pending_frame_warmup_frames: 0,
3456 frame_count: 0,
3457 shader_warm_ups_queued: 0,
3458 };
3459 #[cfg(not(target_arch = "wasm32"))]
3460 renderer.warm_first_screen(&records, holds_recorded);
3461 renderer.warm_requested_shaders();
3462 log::info!(
3463 "[gpu-init] {:?} renderer ready in {:.1} ms (effects {:.1} ms)",
3464 adapter_backend,
3465 instant_ms(construction_started, Instant::now()),
3466 effects_ms,
3467 );
3468 renderer
3469 }
3470
3471 #[cfg(not(target_arch = "wasm32"))]
3478 fn warm_first_screen(
3479 &mut self,
3480 records: &crate::pipeline_records::PipelineRecords,
3481 holds_recorded: bool,
3482 ) {
3483 self.warm_fixed_pipelines(&|label| {
3484 records
3485 .fixed
3486 .iter()
3487 .any(|fixed| fixed.first_screen && fixed.entry == label)
3488 });
3489 if holds_recorded {
3490 self.effect_renderer.trust_cached(records);
3491 }
3492 self.effect_renderer.warm_first_screen_shaders(
3493 records
3494 .shaders
3495 .iter()
3496 .filter(|shader| shader.first_screen)
3497 .map(|shader| &shader.entry),
3498 );
3499 }
3500
3501 fn ensure_shape_pipeline(&mut self, key: ShapePipelineKey, vertices: u64) {
3502 self.shape_pipelines.ensure(key, vertices);
3503 }
3504
3505 fn warm_requested_shaders(&mut self) {
3508 let requested = cranpose_ui_graphics::shader_warm_ups_after(self.shader_warm_ups_queued);
3509 if requested.is_empty() {
3510 return;
3511 }
3512 self.shader_warm_ups_queued += requested.len();
3513 self.effect_renderer.warm_shaders(&requested);
3514 }
3515
3516 #[cfg(not(target_arch = "wasm32"))]
3520 fn warm_recent(&mut self, records: &crate::pipeline_records::PipelineRecords) {
3521 self.warm_fixed_pipelines(&|label| records.fixed.iter().any(|fixed| fixed.entry == label));
3522 let shapes = records
3523 .shapes
3524 .iter()
3525 .map(|shape| shape.entry)
3526 .filter(|&bits| bits != crate::arc_trig_fill::FIRST_SCREEN_KEY)
3527 .filter_map(ShapePipelineKey::from_bits);
3528 for key in shapes {
3529 self.shape_pipelines.warm(key);
3530 }
3531 self.effect_renderer
3532 .warm_recorded_shaders(records.shaders.iter().map(|shader| &shader.entry));
3533 }
3534
3535 #[cfg(not(target_arch = "wasm32"))]
3537 fn warm_fixed_pipelines(&self, wanted: &dyn Fn(&str) -> bool) {
3538 self.effect_renderer.warm_fixed(&self.device, wanted);
3539 let warm =
3540 |pipeline: &FixedPipeline,
3541 job: &dyn Fn() -> Box<dyn FnOnce() -> wgpu::RenderPipeline + Send>| {
3542 if wanted(pipeline.label()) {
3543 pipeline.queue(
3544 self.effect_renderer.compiler(),
3545 crate::pipeline_compiler::CompileLane::WarmUp,
3546 self.adapter_backend,
3547 job(),
3548 );
3549 }
3550 };
3551 for depth in [false, true] {
3552 for (alpha_mask, rounded) in
3553 [(false, false), (true, false), (false, true), (true, true)]
3554 {
3555 let variant = ImageVariant {
3556 depth,
3557 alpha_mask,
3558 rounded,
3559 };
3560 for blend_mode in [BlendMode::SrcOver, BlendMode::DstOut] {
3561 warm(self.image_pipeline_resource(blend_mode, variant), &|| {
3562 Box::new(self.image_pipeline_job(blend_mode, variant))
3563 });
3564 }
3565 }
3566 for quads in [GlyphQuads::Plain, GlyphQuads::Aligned, GlyphQuads::Turned] {
3567 warm(self.glyph_atlas_pipeline_resource(depth, quads), &|| {
3568 Box::new(self.glyph_atlas_pipeline_job(depth, quads))
3569 });
3570 }
3571 warm(&self.rrect_shadow_pipeline[usize::from(depth)], &|| {
3572 Box::new(self.rrect_shadow_pipeline_job(depth))
3573 });
3574 }
3575 }
3576
3577 fn image_pipeline_resource(
3578 &self,
3579 blend_mode: BlendMode,
3580 variant: ImageVariant,
3581 ) -> &FixedPipeline {
3582 let pipelines = match blend_mode {
3583 BlendMode::DstOut => &self.image_pipeline_dst_out,
3584 _ => &self.image_pipeline,
3585 };
3586 &pipelines[usize::from(variant.depth)
3587 + 2 * usize::from(variant.alpha_mask)
3588 + 4 * usize::from(variant.rounded)]
3589 }
3590
3591 fn image_pipeline_job(
3592 &self,
3593 blend_mode: BlendMode,
3594 variant: ImageVariant,
3595 ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
3596 let device = Arc::clone(&self.device);
3597 let cache = self.pipeline_cache.clone();
3598 let format = self.composition_format;
3599 let shader = self.image_shader.clone();
3600 move || {
3601 create_image_pipeline(
3602 &device,
3603 cache.as_ref(),
3604 format,
3605 &shader,
3606 blend_mode,
3607 variant,
3608 )
3609 }
3610 }
3611
3612 pub(crate) fn image_pipeline(
3613 &self,
3614 blend_mode: BlendMode,
3615 variant: ImageVariant,
3616 ) -> &wgpu::RenderPipeline {
3617 self.image_pipeline_resource(blend_mode, variant).for_draw(
3618 &self.recorder,
3619 self.adapter_backend,
3620 || self.image_pipeline_job(blend_mode, variant)(),
3621 )
3622 }
3623
3624 fn glyph_atlas_pipeline_job(
3625 &self,
3626 depth: bool,
3627 quads: GlyphQuads,
3628 ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
3629 let device = Arc::clone(&self.device);
3630 let cache = self.pipeline_cache.clone();
3631 let format = self.composition_format;
3632 let shader = self.glyph_atlas_shader.clone();
3633 move || {
3634 create_glyph_atlas_pipeline(&device, cache.as_ref(), format, &shader, (depth, quads))
3635 }
3636 }
3637
3638 fn glyph_atlas_pipeline(&self, depth: bool, quads: GlyphQuads) -> &wgpu::RenderPipeline {
3641 self.glyph_atlas_pipeline_resource(depth, quads).for_draw(
3642 &self.recorder,
3643 self.adapter_backend,
3644 || self.glyph_atlas_pipeline_job(depth, quads)(),
3645 )
3646 }
3647
3648 fn rrect_shadow_pipeline_job(
3649 &self,
3650 depth: bool,
3651 ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
3652 let device = Arc::clone(&self.device);
3653 let cache = self.pipeline_cache.clone();
3654 let format = self.composition_format;
3655 let shader = self.rrect_shadow_shader.clone();
3656 move || create_rrect_shadow_pipeline(&device, cache.as_ref(), format, &shader, depth)
3657 }
3658
3659 pub(crate) fn draw_shadow_instances(
3662 &self,
3663 pass: &mut wgpu::RenderPass<'_>,
3664 buffer: &BufferUpload,
3665 uniform_slot: usize,
3666 instances: std::ops::Range<u32>,
3667 scissor: Option<(u32, u32, u32, u32)>,
3668 frame: PassFrame,
3669 ) -> Result<(), String> {
3670 let depth = frame.depth;
3671 let pipeline = self.rrect_shadow_pipeline[usize::from(depth)].for_draw(
3672 &self.recorder,
3673 self.adapter_backend,
3674 || self.rrect_shadow_pipeline_job(depth)(),
3675 );
3676 let (x, y, width, height) = frame.scissor(scissor);
3677 pass.set_scissor_rect(x, y, width, height);
3678 pass.set_pipeline(pipeline);
3679 self.viewport_uniforms.bind(pass, uniform_slot)?;
3680 pass.set_vertex_buffer(0, buffer.slice());
3681 pass.draw(0..SHADOW_QUAD_CORNERS, instances);
3682 self.frame_stats.add_draw_calls(1);
3683 Ok(())
3684 }
3685
3686 pub(crate) fn upload_shadow_instances<C: FrameCommandRecorder>(
3687 &self,
3688 recorder: &mut C,
3689 instances: &[ShadowInstance],
3690 ) -> BufferUpload {
3691 recorder.upload_buffer(
3692 UploadAllocatorSpec::vertex(
3693 "Shadow Instance Buffer",
3694 std::mem::size_of::<ShadowInstance>() as u64,
3695 ),
3696 &self.device,
3697 bytemuck::cast_slice(instances),
3698 )
3699 }
3700
3701 fn glyph_atlas_pipeline_resource(&self, depth: bool, quads: GlyphQuads) -> &FixedPipeline {
3702 let kind = match quads {
3703 GlyphQuads::Plain => 0,
3704 GlyphQuads::Aligned => 1,
3705 GlyphQuads::Turned => 2,
3706 };
3707 &self.glyph_atlas_pipeline[usize::from(depth) + 2 * kind]
3708 }
3709
3710 pub(crate) fn depth_target(&mut self, size: (u32, u32)) -> wgpu::TextureView {
3713 const KEPT_DEPTH_TARGETS: usize = 4;
3714 if let Some(index) = self
3715 .depth_targets
3716 .iter()
3717 .position(|(kept, _)| *kept == size)
3718 {
3719 let entry = self.depth_targets.remove(index);
3720 let view = entry.1.clone();
3721 self.depth_targets.insert(0, entry);
3722 return view;
3723 }
3724 let texture = self.device.create_texture(&wgpu::TextureDescriptor {
3725 label: Some("Opaque interior depth"),
3726 size: wgpu::Extent3d {
3727 width: size.0,
3728 height: size.1,
3729 depth_or_array_layers: 1,
3730 },
3731 mip_level_count: 1,
3732 sample_count: 1,
3733 dimension: wgpu::TextureDimension::D2,
3734 format: DEPTH_FORMAT,
3735 usage: if self.adapter_backend == wgpu::Backend::BrowserWebGpu {
3738 wgpu::TextureUsages::RENDER_ATTACHMENT
3739 } else {
3740 wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TRANSIENT_ATTACHMENT
3741 },
3742 view_formats: &[],
3743 });
3744 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
3745 self.depth_targets.insert(0, (size, view.clone()));
3746 self.depth_targets.truncate(KEPT_DEPTH_TARGETS);
3747 view
3748 }
3749
3750 fn image_binding(
3753 &mut self,
3754 image: &ImageBitmap,
3755 sampling: ImageSampling,
3756 ) -> Result<ImageBinding, String> {
3757 if let Some(cached) = self.image_texture_cache.get(&image.id()) {
3758 return Ok(cached.binding(sampling));
3759 }
3760
3761 let size = wgpu::Extent3d {
3762 width: image.width(),
3763 height: image.height(),
3764 depth_or_array_layers: 1,
3765 };
3766
3767 let alpha_mask = matches!(
3768 image.format(),
3769 cranpose_ui_graphics::ImagePixelFormat::Alpha8 { .. }
3770 );
3771 let (format, bytes_per_pixel) = if alpha_mask {
3772 (wgpu::TextureFormat::R8Unorm, 1)
3773 } else {
3774 (wgpu::TextureFormat::Rgba8Unorm, 4)
3775 };
3776
3777 let texture = self.device.create_texture(&wgpu::TextureDescriptor {
3778 label: Some("Image Texture"),
3779 size,
3780 mip_level_count: 1,
3781 sample_count: 1,
3782 dimension: wgpu::TextureDimension::D2,
3783 format,
3784 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
3785 view_formats: &[],
3786 });
3787
3788 let upload_stats = self.frame_graph_executor.upload_texture(
3789 &self.queue,
3790 wgpu::TexelCopyTextureInfo {
3791 texture: &texture,
3792 mip_level: 0,
3793 origin: wgpu::Origin3d::ZERO,
3794 aspect: wgpu::TextureAspect::All,
3795 },
3796 image.pixels(),
3797 wgpu::TexelCopyBufferLayout {
3798 offset: 0,
3799 bytes_per_row: Some(bytes_per_pixel * image.width()),
3800 rows_per_image: Some(image.height()),
3801 },
3802 size,
3803 );
3804 self.frame_stats.record_command_stats(upload_stats);
3805
3806 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
3807 let nearest_bind_group = self.image_bind_group(&view, &self.image_nearest_sampler);
3808 let linear_bind_group = self.image_bind_group(&view, &self.image_linear_sampler);
3809
3810 let bytes = image.pixels().len();
3811 let cached = CachedImageTexture {
3812 alpha_mask,
3813 _texture: texture,
3814 _view: view,
3815 nearest_bind_group,
3816 linear_bind_group,
3817 bytes,
3818 };
3819 let binding = cached.binding(sampling);
3820 if let Some(replaced) = self.image_texture_cache.put(image.id(), cached) {
3821 self.image_texture_cache_bytes = self
3822 .image_texture_cache_bytes
3823 .saturating_sub(replaced.bytes);
3824 }
3825 self.image_texture_cache_bytes += bytes;
3826 while self.image_texture_cache_bytes > MAX_IMAGE_TEXTURE_CACHE_BYTES
3827 && self.image_texture_cache.len() > 1
3828 {
3829 let Some((_, evicted)) = self.image_texture_cache.pop_lru() else {
3830 break;
3831 };
3832 self.image_texture_cache_bytes =
3833 self.image_texture_cache_bytes.saturating_sub(evicted.bytes);
3834 }
3835 Ok(binding)
3836 }
3837
3838 fn image_bind_group(
3839 &self,
3840 view: &wgpu::TextureView,
3841 sampler: &wgpu::Sampler,
3842 ) -> wgpu::BindGroup {
3843 self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3844 label: Some("Image Texture Bind Group"),
3845 layout: &self.image_bind_group_layout,
3846 entries: &[
3847 wgpu::BindGroupEntry {
3848 binding: 0,
3849 resource: wgpu::BindingResource::TextureView(view),
3850 },
3851 wgpu::BindGroupEntry {
3852 binding: 1,
3853 resource: wgpu::BindingResource::Sampler(sampler),
3854 },
3855 ],
3856 })
3857 }
3858
3859 pub(crate) fn max_texture_dim(&self) -> u32 {
3860 self.effect_renderer.max_texture_dim()
3861 }
3862
3863 pub(crate) fn acquire_retained_surface(&mut self, width: u32, height: u32) -> OffscreenTarget {
3866 self.effect_renderer
3867 .acquire_offscreen(&self.device, width, height, Some(&self.frame_stats))
3868 }
3869
3870 fn frame_root(
3871 &mut self,
3872 output_mode: OutputMode,
3873 output_view: Option<&wgpu::TextureView>,
3874 output_texture: Option<&wgpu::Texture>,
3875 viewport: (u32, u32),
3876 reads_page: bool,
3877 ) -> FrameRoot {
3878 if let (OutputMode::Display, Some(view), Some(texture)) =
3879 (output_mode, output_view, output_texture)
3880 && surface_is_direct_root(texture, self.composition_format, viewport, reads_page)
3881 {
3882 return FrameRoot::Surface(Rc::new(OffscreenTarget::from_surface(
3883 texture.clone(),
3884 view.clone(),
3885 )));
3886 }
3887 FrameRoot::Composition(self.take_composition_target(viewport.0.max(1), viewport.1.max(1)))
3888 }
3889
3890 fn take_composition_target(&mut self, width: u32, height: u32) -> CompositionTarget {
3891 if let Some(target) = self.composition_target.take()
3892 && target.target.width == width
3893 && target.target.height == height
3894 {
3895 return target;
3896 }
3897 let target = Rc::new(OffscreenTarget::new(
3898 &self.device,
3899 self.composition_format,
3900 width,
3901 height,
3902 ));
3903 let output_bind_group = self.output_converter.bind_group(&self.device, &target.view);
3904 CompositionTarget {
3905 target,
3906 output_bind_group,
3907 }
3908 }
3909
3910 fn transient_offscreen_descriptor(
3911 &self,
3912 label: &'static str,
3913 width: u32,
3914 height: u32,
3915 ) -> FrameTextureDescriptor {
3916 let max_texture_dim = self.max_texture_dim();
3917 FrameTextureDescriptor::render_attachment(
3918 label,
3919 width.min(max_texture_dim),
3920 height.min(max_texture_dim),
3921 self.composition_format,
3922 )
3923 }
3924
3925 pub(crate) fn transparent_source<C: FrameCommandRecorder>(
3929 &mut self,
3930 recorder: &mut C,
3931 width: u32,
3932 height: u32,
3933 ) -> Rc<OffscreenTarget> {
3934 if let Some(source) = self.transparent_sources.get(&(width, height)) {
3935 return Rc::clone(source);
3936 }
3937 if self.transparent_sources.len() >= MAX_TRANSPARENT_SOURCES {
3938 for (_, source) in self.transparent_sources.drain() {
3939 if let Ok(target) = Rc::try_unwrap(source) {
3940 self.deferred_offscreen_releases.push(target);
3941 }
3942 }
3943 }
3944 let source = Rc::new(self.acquire_retained_surface(width, height));
3945 self.clear_target(
3946 recorder,
3947 &source.view,
3948 wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
3949 );
3950 self.transparent_sources
3951 .insert((width, height), Rc::clone(&source));
3952 source
3953 }
3954
3955 fn defer_offscreen_release(&mut self, target: OffscreenTarget) {
3956 self.deferred_offscreen_releases.push(target);
3957 }
3958
3959 fn flush_deferred_offscreen_releases(&mut self) {
3960 let layer_cache = &mut self.layer_cache;
3961 let mut retire = |gate: &mut AdmissionGate| {
3962 let seen = gate.end_frame();
3963 if !seen && let Some(dead) = gate.dead_entry() {
3964 layer_cache.remove(&dead);
3965 }
3966 seen
3967 };
3968 self.backdrop_gates.retain(|_, gate| retire(gate));
3969 self.fill_gates.retain(|_, gate| retire(gate));
3970 self.effect_gates.retain(|_, gate| retire(gate));
3971 self.source_gates.retain(|_, gate| retire(gate));
3972 for target in self.deferred_offscreen_releases.drain(..) {
3973 self.effect_renderer.release_offscreen(target);
3974 }
3975 self.layer_cache.end_frame();
3976 for (transient, target) in self.layer_cache.take_released() {
3977 match transient {
3978 Some(descriptor) => self
3979 .frame_graph_executor
3980 .return_cached_transient(descriptor, target),
3981 None => self.effect_renderer.release_offscreen(target),
3982 }
3983 }
3984 self.effect_renderer.end_offscreen_frame();
3985 self.frame_graph_executor.end_transient_frame();
3986 }
3987
3988 fn insert_cached_shadow_surface(
3989 &mut self,
3990 key: ShadowSurfaceCacheKey,
3991 target: Rc<OffscreenTarget>,
3992 ) {
3993 let byte_size = offscreen_byte_size(target.width, target.height);
3994 while self.shadow_surface_cache_bytes + byte_size > MAX_SHADOW_SURFACE_CACHE_BYTES {
3995 let Some((_, evicted)) = self.shadow_surface_cache.pop_lru() else {
3996 break;
3997 };
3998 self.shadow_surface_cache_bytes = self
3999 .shadow_surface_cache_bytes
4000 .saturating_sub(evicted.byte_size);
4001 }
4002 let cached = CachedShadowSurface { target, byte_size };
4003 if let Some((_, replaced)) = self.shadow_surface_cache.push(key, cached) {
4004 self.shadow_surface_cache_bytes = self
4005 .shadow_surface_cache_bytes
4006 .saturating_sub(replaced.byte_size);
4007 }
4008 self.shadow_surface_cache_bytes = self.shadow_surface_cache_bytes.saturating_add(byte_size);
4009 }
4010}
4011fn frame_stats_need_warmup_frame(snapshot: &gpu_stats::FrameStatsSnapshot) -> bool {
4012 snapshot.layer_cache_misses > 0
4013 || snapshot.shadow_shape_cache_misses > 0
4014 || snapshot.text_image_cache_misses > 0
4015 || snapshot.text_glyph_atlas_misses > 0
4016}
4017
4018fn update_frame_warmup_budget(pending_frames: &mut u8, snapshot: &gpu_stats::FrameStatsSnapshot) {
4019 if *pending_frames > 0 {
4020 *pending_frames = pending_frames.saturating_sub(1);
4021 } else if frame_stats_need_warmup_frame(snapshot) {
4022 *pending_frames = CACHE_MISS_WARMUP_FRAMES;
4023 }
4024}
4025
4026impl GpuRenderer {
4027 #[expect(clippy::too_many_arguments)]
4028 pub fn render(
4029 &mut self,
4030 texture: &wgpu::Texture,
4031 view: &wgpu::TextureView,
4032 width: u32,
4033 height: u32,
4034 packet: FramePacket,
4035 surface_epoch: u64,
4036 returns: &mut RenderReturns,
4037 ) -> Result<(), String> {
4038 self.render_internal(
4039 width,
4040 height,
4041 packet,
4042 surface_epoch,
4043 returns,
4044 OutputMode::Display,
4045 Some(view),
4046 Some(texture),
4047 )
4048 }
4049
4050 #[expect(clippy::too_many_arguments)]
4051 fn render_internal(
4052 &mut self,
4053 width: u32,
4054 height: u32,
4055 packet: FramePacket,
4056 surface_epoch: u64,
4057 returns: &mut RenderReturns,
4058 output_mode: OutputMode,
4059 output_view: Option<&wgpu::TextureView>,
4060 output_texture: Option<&wgpu::Texture>,
4061 ) -> Result<(), String> {
4062 let cancel_reason = if packet.renderer_epoch != self.renderer_epoch {
4063 Some(CancelReason::RendererEpoch)
4064 } else if packet.surface_epoch != surface_epoch {
4065 Some(CancelReason::SurfaceEpoch)
4066 } else if packet.viewport != (width, height) {
4067 Some(CancelReason::Viewport)
4068 } else {
4069 None
4070 };
4071 if let Some(reason) = cancel_reason {
4072 return Self::cancel_packet(packet, reason, returns);
4073 }
4074 if self.device_errors.take_poison() {
4075 return Self::cancel_packet(packet, CancelReason::DeviceError, returns);
4076 }
4077 returns.frame_id = packet.frame_id;
4078 let render_start = Instant::now();
4079 #[cfg(not(target_arch = "wasm32"))]
4080 let builds_before = thread_builds();
4081 self.warm_requested_shaders();
4082 self.shape_pipelines.begin_frame();
4083 self.recorder.begin_frame();
4084 self.begin_placeholder_frame();
4085 self.viewport_uniforms.begin_frame();
4086 self.run_store.begin_frame(gpu_stats_enabled());
4087 self.begin_text_glyph_run_frame();
4088
4089 let text_cache_len = packet.text_cache_len;
4090 let reads_page = packet.root.contains_backdrop()
4091 || packet
4092 .overlay
4093 .as_ref()
4094 .is_some_and(LayerScene::contains_backdrop);
4095 let frame_root = self.frame_root(
4096 output_mode,
4097 output_view,
4098 output_texture,
4099 (width, height),
4100 reads_page,
4101 );
4102 let root = frame_root.target();
4103 let screenshot_bind_group = output_view.and_then(|_| {
4104 matches!(output_mode, OutputMode::Screenshot).then(|| {
4105 self.screenshot_converter
4106 .bind_group(&self.device, &root.view)
4107 })
4108 });
4109 let output = frame_root.output(output_view, screenshot_bind_group.as_ref());
4110 let result = self.render_graph(root, packet, returns, output_mode, output);
4111 #[cfg(not(target_arch = "wasm32"))]
4112 self.effect_renderer
4113 .compiler()
4114 .spread_demand(thread_builds() == builds_before);
4115 if let FrameRoot::Composition(composition) = frame_root {
4116 self.composition_target = Some(composition);
4117 }
4118 let after_graph = Instant::now();
4119 self.flush_deferred_offscreen_releases();
4120
4121 self.frame_stats
4122 .layer_cache_size
4123 .set(self.layer_cache.len() as u32);
4124 self.frame_stats
4125 .layer_cache_bytes
4126 .set(self.layer_cache.bytes());
4127 self.frame_stats.offscreen_pool_size.set(
4128 self.effect_renderer
4129 .retained_offscreen_count()
4130 .saturating_add(self.frame_graph_executor.retained_texture_count())
4131 .saturating_add(usize::from(self.composition_target.is_some())) as u32,
4132 );
4133 self.frame_stats.offscreen_pool_bytes.set(
4134 (self.effect_renderer.retained_offscreen_bytes() as u64)
4135 .saturating_add(self.frame_graph_executor.retained_texture_bytes())
4136 .saturating_add(self.composition_target.as_ref().map_or(0, |target| {
4137 u64::from(target.target.width)
4138 .saturating_mul(u64::from(target.target.height))
4139 .saturating_mul(COMPOSITION_BYTES_PER_PIXEL)
4140 })),
4141 );
4142 self.frame_stats
4143 .text_pool_size
4144 .set(self.text_image_cache.len() as u32);
4145 self.frame_stats
4146 .image_cache_size
4147 .set(self.image_texture_cache.len() as u32);
4148 self.frame_stats.text_cache_size.set(text_cache_len as u32);
4149 self.effect_renderer
4150 .merge_and_reset_debug_counters(&self.frame_stats);
4151 self.frame_graph_executor.reset_upload_allocators();
4152 let snapshot = self.frame_stats.snapshot();
4153 if crate::frame_graph::frame_graph_pass_telemetry_threshold_ms().is_some() {
4154 log::warn!(
4155 "[wgpu-render-stage:frame-stats] layer_hit={} layer_miss={} miss_px={} \
4156 offscreen_acq={} offscreen_new={} isolated={} draws={}",
4157 snapshot.layer_cache_hits,
4158 snapshot.layer_cache_misses,
4159 snapshot.layer_cache_miss_pixels,
4160 snapshot.offscreen_acquires,
4161 snapshot.offscreen_news,
4162 snapshot.isolated_layer_renders,
4163 snapshot.draw_calls,
4164 );
4165 }
4166 self.last_frame_stats = Some(snapshot);
4167 PRESENTED_FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4168 update_frame_warmup_budget(&mut self.pending_frame_warmup_frames, &snapshot);
4169 let gpu_stats_on = gpu_stats_enabled();
4170 self.frame_stats
4171 .maybe_print_snapshot(snapshot, &mut self.frame_count, gpu_stats_on);
4172 if gpu_stats_on && self.frame_count.is_multiple_of(60) {
4173 gpu_stats::print_gpu_memory_report(&self.device, self.frame_count);
4174 }
4175 self.frame_graph_executor
4176 .end_pass_timing_frame(&self.device, &self.queue);
4177 self.frame_stats.reset();
4178 let after_stats = Instant::now();
4179 if let Some(total_ms) = should_log_wgpu_render_stage(render_start, after_stats) {
4180 log::warn!(
4181 "[wgpu-render-stage:render] total_ms={total_ms:.2} graph_ms={:.2} cleanup_stats_ms={:.2}",
4182 instant_ms(render_start, after_graph),
4183 instant_ms(after_graph, after_stats),
4184 );
4185 }
4186 if result.is_ok() {
4187 returns.outcome = PresentOutcome::Presented;
4188 }
4189 result
4190 }
4191
4192 pub(crate) fn cancel_packet(
4194 packet: FramePacket,
4195 reason: CancelReason,
4196 returns: &mut RenderReturns,
4197 ) -> Result<(), String> {
4198 returns.scene = Some(FrameSceneStorage {
4199 root: packet.root,
4200 overlay: packet.overlay,
4201 });
4202 returns.frame_id = packet.frame_id;
4203 returns.outcome = PresentOutcome::Cancelled(reason);
4204 Ok(())
4205 }
4206
4207 pub fn last_frame_stats(&self) -> Option<gpu_stats::FrameStatsSnapshot> {
4208 self.last_frame_stats
4209 }
4210
4211 pub fn gpu_pass_timings(&self) -> crate::pass_timing::GpuPassTimingReport {
4212 self.frame_graph_executor.pass_timing_report()
4213 }
4214
4215 pub fn needs_frame_warmup(&self) -> bool {
4216 self.pending_frame_warmup_frames > 0 || self.placeholder_awaits_frame()
4217 }
4218
4219 fn placeholder_awaits_frame(&self) -> bool {
4223 #[cfg(not(target_arch = "wasm32"))]
4224 if let Some(landing) = &self.landing {
4225 return landing.landed() || (self.drew_placeholder && !landing.has_wake());
4226 }
4227 self.drew_placeholder
4228 }
4229
4230 fn begin_placeholder_frame(&mut self) {
4233 self.drew_placeholder = false;
4234 #[cfg(not(target_arch = "wasm32"))]
4235 if let Some(landing) = &self.landing {
4236 self.built_at_frame_start = landing.built();
4237 if landing.take_landed() {
4238 self.layer_cache.clear();
4239 }
4240 }
4241 }
4242
4243 pub(crate) fn note_placeholder(&mut self) {
4246 self.drew_placeholder = true;
4247 self.recorder.hold_first_screen();
4248 self.frame_stats
4249 .placeholder_draws
4250 .set(self.frame_stats.placeholder_draws.get() + 1);
4251 #[cfg(not(target_arch = "wasm32"))]
4252 if let Some(landing) = &self.landing {
4253 landing.await_since(self.built_at_frame_start);
4254 }
4255 }
4256
4257 #[cfg(not(target_arch = "wasm32"))]
4261 pub(crate) fn prepare_recorded(&mut self) -> bool {
4262 self.effect_renderer.warm_after_first_frame();
4263 if let Some(records) = self.recent_after_update.take() {
4264 self.warm_recent(&records);
4265 }
4266 self.compiling()
4267 }
4268
4269 #[cfg(not(target_arch = "wasm32"))]
4271 pub(crate) fn compiling(&self) -> bool {
4272 self.landing
4273 .as_ref()
4274 .is_some_and(|landing| landing.in_flight())
4275 }
4276
4277 pub(crate) fn awaits_pipelines(&self) -> bool {
4280 #[cfg(not(target_arch = "wasm32"))]
4281 if let Some(landing) = &self.landing {
4282 return self.drew_placeholder && landing.in_flight();
4283 }
4284 self.drew_placeholder
4285 }
4286
4287 #[cfg(not(target_arch = "wasm32"))]
4290 pub(crate) fn landing(&self) -> Option<Arc<crate::pipeline_compiler::Landing>> {
4291 self.landing.clone()
4292 }
4293
4294 #[cfg(not(target_arch = "wasm32"))]
4297 pub(crate) fn wake_on_landing(&self, wake: Box<dyn Fn() + Send + Sync>) {
4298 if let Some(landing) = &self.landing {
4299 landing.wake_with(wake);
4300 }
4301 }
4302
4303 pub fn debug_cpu_allocation_stats(&self) -> DebugCpuAllocationStats {
4304 DebugCpuAllocationStats {
4305 scene_graph_node_count: 0,
4306 scene_graph_heap_bytes: 0,
4307 scene_hits_len: 0,
4308 scene_hits_cap: 0,
4309 scene_node_index_len: 0,
4310 scene_node_index_cap: 0,
4311 text_renderer_pool_len: self.text_image_cache.len(),
4312 text_renderer_pool_cap: self.text_image_cache.cap().get(),
4313 image_texture_cache_len: self.image_texture_cache.len(),
4314 image_texture_cache_cap: self.image_texture_cache.cap().get(),
4315 run_arena_staging_bytes: self.run_store.arena_staging_bytes(),
4316 run_store_bytes: self.run_store.stored_bytes(),
4317 run_store_runs: self.run_store.stored_count(),
4318 scratch_image_vertices_cap: self.scratch_image_vertices.capacity(),
4319 scratch_image_indices_cap: self.scratch_image_indices.capacity(),
4320 scratch_image_cmds_cap: self.scratch_image_cmds.capacity(),
4321 scratch_glyph_instances_cap: self.scratch_glyph_instances.plain.capacity()
4322 + self.scratch_glyph_instances.turned.capacity(),
4323 layer_cache_len: self.layer_cache.len(),
4324 layer_cache_bytes: self.layer_cache.bytes(),
4325 }
4326 }
4327 pub fn render_to_rgba_pixels(
4328 &mut self,
4329 width: u32,
4330 height: u32,
4331 packet: FramePacket,
4332 surface_epoch: u64,
4333 returns: &mut RenderReturns,
4334 ) -> Result<Vec<u8>, String> {
4335 if width == 0 || height == 0 {
4336 return Err("Screenshot size must be non-zero".to_string());
4337 }
4338 let errors_before = self.device_errors.error_count();
4339
4340 let output_texture = crate::offscreen::create_2d_texture(
4341 &self.device,
4342 wgpu::TextureFormat::Rgba8Unorm,
4343 width,
4344 height,
4345 wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
4346 Some("Screenshot Output Texture"),
4347 );
4348 let output_view = output_texture.create_view(&wgpu::TextureViewDescriptor::default());
4349 self.render_internal(
4350 width,
4351 height,
4352 packet,
4353 surface_epoch,
4354 returns,
4355 OutputMode::Screenshot,
4356 Some(&output_view),
4357 None,
4358 )?;
4359 if returns.outcome != PresentOutcome::Presented {
4360 return Err(format!(
4361 "Screenshot rendering did not complete: {:?}",
4362 returns.outcome
4363 ));
4364 }
4365 self.read_screenshot_pixels(&output_texture, errors_before)
4366 }
4367
4368 fn read_screenshot_pixels(
4369 &mut self,
4370 output_texture: &wgpu::Texture,
4371 errors_before: u64,
4372 ) -> Result<Vec<u8>, String> {
4373 let width = output_texture.width();
4374 let height = output_texture.height();
4375 let bytes_per_pixel = 4u32;
4376 let unpadded_bytes_per_row = width
4377 .checked_mul(bytes_per_pixel)
4378 .ok_or_else(|| "Screenshot row byte size overflow".to_string())?;
4379 let padded_bytes_per_row =
4380 align_to(unpadded_bytes_per_row, wgpu::COPY_BYTES_PER_ROW_ALIGNMENT);
4381 let output_buffer_size = padded_bytes_per_row as u64 * height as u64;
4382
4383 let output_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
4384 label: Some("Screenshot Readback Buffer"),
4385 size: output_buffer_size,
4386 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
4387 mapped_at_creation: false,
4388 });
4389
4390 let device = self.device.clone();
4391 let queue = self.queue.clone();
4392 let mut graph = WgpuFrameGraph::new(Some("Screenshot Copy Encoder"));
4393 let source = graph.import_surface("screenshot-copy-source");
4394 graph.add_fallible_command_pass(Some("Screenshot Copy Pass"), &[source], &[], |context| {
4395 context.encoder.copy_texture_to_buffer(
4396 wgpu::TexelCopyTextureInfo {
4397 texture: output_texture,
4398 mip_level: 0,
4399 origin: wgpu::Origin3d::ZERO,
4400 aspect: wgpu::TextureAspect::All,
4401 },
4402 wgpu::TexelCopyBufferInfo {
4403 buffer: &output_buffer,
4404 layout: wgpu::TexelCopyBufferLayout {
4405 offset: 0,
4406 bytes_per_row: Some(padded_bytes_per_row),
4407 rows_per_image: Some(height),
4408 },
4409 },
4410 wgpu::Extent3d {
4411 width,
4412 height,
4413 depth_or_array_layers: 1,
4414 },
4415 );
4416 Ok(())
4417 });
4418 let mut executor = std::mem::take(&mut self.frame_graph_executor);
4419 let execution = executor.execute_recorded_graph(&device, &queue, graph);
4420 self.frame_graph_executor = executor;
4421 let execution = execution.map_err(|error| error.to_string())?;
4422 let submission_index = execution.submission;
4423 let copy_stats = execution.stats;
4424 self.last_frame_stats = self
4425 .last_frame_stats
4426 .map(|snapshot| snapshot.with_command_stats_added(copy_stats));
4427
4428 let buffer_slice = output_buffer.slice(..);
4429 let (tx, rx) = mpsc::channel();
4430 buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
4431 let _ = tx.send(result);
4432 });
4433 self.device
4434 .poll(wgpu::PollType::Wait {
4435 submission_index: Some(submission_index),
4436 timeout: None,
4437 })
4438 .map_err(|error| format!("Screenshot GPU wait failed: {error}"))?;
4439
4440 match rx.recv_timeout(Duration::from_secs(3)) {
4441 Ok(Ok(())) => {}
4442 Ok(Err(err)) => return Err(format!("Screenshot map_async failed: {err:?}")),
4443 Err(err) => return Err(format!("Screenshot readback timed out: {err}")),
4444 }
4445 if self.device_errors.error_count() != errors_before {
4446 output_buffer.unmap();
4447 return Err("GPU errors occurred while capturing the screenshot".to_string());
4448 }
4449
4450 let mapped = buffer_slice
4451 .get_mapped_range()
4452 .map_err(|err| format!("Screenshot readback could not be read: {err}"))?;
4453 let mut pixels = vec![0u8; (width as usize) * (height as usize) * 4];
4454
4455 let src_row_len = padded_bytes_per_row as usize;
4456 let dst_row_len = unpadded_bytes_per_row as usize;
4457 for row in 0..height as usize {
4458 let src_offset = row * src_row_len;
4459 let dst_offset = row * dst_row_len;
4460 pixels[dst_offset..dst_offset + dst_row_len]
4461 .copy_from_slice(&mapped[src_offset..src_offset + dst_row_len]);
4462 }
4463 drop(mapped);
4464 output_buffer.unmap();
4465
4466 self.convert_surface_pixels_to_rgba(&pixels)
4467 }
4468
4469 fn render_graph(
4470 &mut self,
4471 root_target: &Rc<OffscreenTarget>,
4472 packet: FramePacket,
4473 returns: &mut RenderReturns,
4474 output_mode: OutputMode,
4475 output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
4476 ) -> Result<(), String> {
4477 let device = self.device.clone();
4478 let queue = self.queue.clone();
4479 let graph_start = Instant::now();
4480 let FramePacket {
4481 root,
4482 overlay,
4483 root_scale,
4484 clear,
4485 ..
4486 } = packet;
4487 let page = Rc::clone(root_target);
4488
4489 #[cfg(not(target_arch = "wasm32"))]
4490 let (result, submitted) = {
4491 let mut executor = std::mem::take(&mut self.frame_graph_executor);
4492 let mut frame_graph = WgpuFrameGraph::new(Some("Renderer Frame Graph"));
4493 let surface = frame_graph.import_surface("renderer-surface");
4494 frame_graph.add_fallible_recorded_command_pass(
4495 Some("Renderer Frame Pass"),
4496 &[],
4497 &[surface],
4498 |frame_encoder| {
4499 self.encode_frame(
4500 frame_encoder,
4501 &root,
4502 overlay.as_ref(),
4503 Rc::clone(&page),
4504 root_scale,
4505 clear,
4506 output_mode,
4507 output,
4508 )
4509 },
4510 );
4511 let after_build = Instant::now();
4512 let execution = executor.execute_recorded_graph(&device, &queue, frame_graph);
4513 let after_execute = Instant::now();
4514 self.frame_graph_executor = executor;
4515 if let Some(total_ms) = should_log_wgpu_render_stage(graph_start, after_execute) {
4516 log::warn!(
4517 "[wgpu-render-stage:graph] total_ms={total_ms:.2} build_ms={:.2} execute_ms={:.2}",
4518 instant_ms(graph_start, after_build),
4519 instant_ms(after_build, after_execute),
4520 );
4521 }
4522 match execution {
4523 Ok(execution) => {
4524 if execution.stats.pass_count > 0 {
4525 self.frame_stats.record_command_stats(execution.stats);
4526 }
4527 (Ok(()), true)
4528 }
4529 Err(crate::frame_graph::FrameGraphError::NoDeclaredPasses) => (Ok(()), false),
4530 Err(error) => (Err(error.to_string()), false),
4531 }
4532 };
4533
4534 #[cfg(target_arch = "wasm32")]
4535 let (result, submitted) = {
4536 let mut executor = std::mem::take(&mut self.frame_graph_executor);
4537 let (result, execution) = {
4538 let mut frame_encoder =
4539 executor.begin(&device, &queue, Some("Renderer Frame Encoder"));
4540 let initial_pass_count = frame_encoder.recorded_pass_count();
4541 let result = self.encode_frame(
4542 &mut frame_encoder,
4543 &root,
4544 overlay.as_ref(),
4545 Rc::clone(&page),
4546 root_scale,
4547 clear,
4548 output_mode,
4549 output,
4550 );
4551 let execution =
4552 if result.is_ok() && frame_encoder.recorded_pass_count() > initial_pass_count {
4553 Some(frame_encoder.finish())
4554 } else {
4555 None
4556 };
4557 (result, execution)
4558 };
4559 let after_execute = Instant::now();
4560 self.frame_graph_executor = executor;
4561 if let Some(total_ms) = should_log_wgpu_render_stage(graph_start, after_execute) {
4562 log::warn!("[wgpu-render-stage:graph] total_ms={total_ms:.2}",);
4563 }
4564 let submitted = execution.is_some();
4565 if let Some(execution) = execution {
4566 self.frame_stats.record_command_stats(execution.stats);
4567 }
4568 (result, submitted)
4569 };
4570 #[cfg(not(target_arch = "wasm32"))]
4571 if submitted {
4572 self.recorder.note_frame_drawn();
4573 self.effect_renderer.warm_after_first_frame();
4574 if let Some(records) = self.recent_after_update.take() {
4575 self.warm_recent(&records);
4576 }
4577 }
4578 if !submitted {
4579 self.run_store.invalidate_uploads();
4580 self.text_glyph_gpu_run_cache.clear();
4581 self.text_glyph_run_arena = GlyphRunArena::default();
4582 }
4583 returns.scene = Some(FrameSceneStorage { root, overlay });
4584 result
4585 }
4586
4587 #[expect(clippy::too_many_arguments)]
4591 fn encode_frame<C: FrameCommandRecorder>(
4592 &mut self,
4593 recorder: &mut C,
4594 root: &LayerScene,
4595 overlay: Option<&LayerScene>,
4596 page: Rc<OffscreenTarget>,
4597 root_scale: f32,
4598 clear: wgpu::Color,
4599 output_mode: OutputMode,
4600 output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
4601 ) -> Result<(), String> {
4602 FrameExecutor::new(self, recorder).render_frame(
4603 root,
4604 overlay,
4605 page,
4606 root_scale,
4607 wgpu::LoadOp::Clear(clear),
4608 )?;
4609 if let Some((output_view, bind_group)) = output {
4610 match output_mode {
4611 OutputMode::Display => &self.output_converter,
4612 OutputMode::Screenshot => &self.screenshot_converter,
4613 }
4614 .encode(
4615 &self.device,
4616 recorder,
4617 output_view,
4618 bind_group,
4619 self.adapter_backend,
4620 &self.recorder,
4621 );
4622 recorder.record_pass();
4623 }
4624 self.stage_frame_uploads(recorder);
4625 self.shape_pipelines.request_wanted();
4626 self.viewport_uniforms.uploads.finish_frame();
4627 self.run_store.finish_frame();
4628 Ok(())
4629 }
4630
4631 pub(crate) fn stage_frame_uploads(&mut self, recorder: &mut impl FrameCommandRecorder) {
4632 let mut upload = self.viewport_uniforms.stage_pending(&self.device, recorder);
4633 upload += self.run_store.stage_pending(&self.device, recorder);
4634 upload += self
4635 .text_glyph_run_arena
4636 .stage_pending(&self.device, recorder);
4637 self.run_store.fill_arena_trig(&self.device, recorder);
4638 self.frame_stats.record_command_stats(upload);
4639 }
4640 pub(crate) fn claim_uniform_slot(&mut self, params: ViewportUniformParams) -> usize {
4642 let uniforms = Uniforms::of(params, PlacementData::zeroed(), RunTier::Arena);
4643 self.viewport_uniforms
4644 .claim(&self.device, &self.uniform_bind_group_layout, &uniforms)
4645 }
4646
4647 fn blurred_shadow_source<C: FrameCommandRecorder>(
4657 &mut self,
4658 recorder: &mut C,
4659 shadow: &ShadowDraw,
4660 source_device: DevicePixelBounds,
4661 pixel_radius: f32,
4662 root_scale: f32,
4663 transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
4664 ) -> Option<(Rc<OffscreenTarget>, bool, SourceContent)> {
4665 let shape_only = shadow.texts.is_empty();
4666 let key = if shape_only {
4667 shape_shadow_surface_cache_key(shadow, source_device, pixel_radius, root_scale)
4668 } else {
4669 None
4670 };
4671 let content = key.map_or(SourceContent::Transient, |key| {
4672 SourceContent::retained(&key)
4673 });
4674 if let Some(entry) = key.and_then(|key| self.shadow_surface_cache.get(&key)) {
4675 return Some((Rc::clone(&entry.target), true, content));
4676 }
4677 if !self.effect_renderer.blur_draws_now(
4679 &self.device,
4680 TileMode::Decal,
4681 (source_device.width, source_device.height),
4682 pixel_radius,
4683 pixel_radius,
4684 ) {
4685 self.note_placeholder();
4686 return None;
4687 }
4688 if !shape_only {
4689 self.frame_stats.record_shadow_text_blur_fallback();
4690 }
4691 let source = self.render_shadow_source(
4692 recorder,
4693 shadow,
4694 source_device,
4695 pixel_radius,
4696 root_scale,
4697 key.is_some(),
4698 transients,
4699 )?;
4700 if let Some(key) = key {
4701 self.frame_stats
4702 .record_shadow_shape_cache_miss(source_device.width, source_device.height);
4703 self.frame_stats.maybe_print_shadow_shape_cache_miss(
4704 source_device.width,
4705 source_device.height,
4706 key.content_hash,
4707 pixel_radius,
4708 [source_device.x, source_device.y],
4709 shadow.shapes.as_ref().map_or(0, RunDraw::record_count) as usize,
4710 shadow.clip,
4711 );
4712 self.insert_cached_shadow_surface(key, Rc::clone(&source));
4713 }
4714 Some((source, false, content))
4715 }
4716
4717 #[expect(clippy::too_many_arguments)]
4718 pub(crate) fn resolve_blurred_shadow<C: FrameCommandRecorder>(
4719 &mut self,
4720 recorder: &mut C,
4721 shadow: &ShadowDraw,
4722 z: usize,
4723 root_scale: f32,
4724 target_rect: DeviceRect4,
4725 transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
4726 resolved: &mut Vec<ResolvedComposite>,
4727 ) {
4728 if !shadow.requires_surface()
4729 || skip_shadow_draws()
4730 || !root_scale.is_finite()
4731 || root_scale <= 0.0
4732 {
4733 return;
4734 }
4735 let Some(bounds) = shadow_draw_bounds(shadow) else {
4736 return;
4737 };
4738 let margin = blur_reach(shadow.blur_radius, root_scale);
4739 let source_bounds = expand_rect(bounds, margin, margin);
4740 let mut visible = source_bounds;
4741 if let Some(clip) = shadow.clip {
4742 let Some(clipped) = visible.intersect(expand_rect(clip, margin, margin)) else {
4743 return;
4744 };
4745 visible = clipped;
4746 }
4747 let target_logical = Rect {
4748 x: target_rect.0 / root_scale,
4749 y: target_rect.1 / root_scale,
4750 width: target_rect.2 / root_scale,
4751 height: target_rect.3 / root_scale,
4752 };
4753 let Some(visible) = visible.intersect(expand_rect(target_logical, margin, margin)) else {
4754 return;
4755 };
4756 let max_texture_dim = self.max_texture_dim();
4757 let shape_only = shadow.texts.is_empty();
4758 let anchor = shadow
4759 .shapes
4760 .as_ref()
4761 .and_then(|run| run.placement.snap_anchor);
4762 let source_device = shape_only
4763 .then(|| {
4764 translation_stable_anchored_device_pixel_bounds(
4765 source_bounds,
4766 anchor,
4767 root_scale,
4768 max_texture_dim,
4769 )
4770 })
4771 .flatten()
4772 .or_else(|| device_pixel_bounds(visible, root_scale, max_texture_dim));
4773 let Some(source_device) = source_device else {
4774 return;
4775 };
4776 let pixel_radius = shadow.blur_radius * root_scale;
4777 let Some((source, hit, content)) = self.blurred_shadow_source(
4778 recorder,
4779 shadow,
4780 source_device,
4781 pixel_radius,
4782 root_scale,
4783 transients,
4784 ) else {
4785 return;
4786 };
4787 let dest = (
4788 source_device.x,
4789 source_device.y,
4790 source_device.width as f32,
4791 source_device.height as f32,
4792 );
4793 let mut coverage = intersect_device_rects(dest, target_rect);
4794 if let Some(clip) = shadow.clip {
4795 coverage = coverage.and_then(|coverage| {
4796 intersect_device_rects(coverage, anchored_rect_to_device(clip, anchor, root_scale))
4797 });
4798 }
4799 let Some(coverage) = coverage else {
4800 return;
4801 };
4802 if hit {
4803 self.frame_stats.record_shadow_shape_cache_hit(
4804 (coverage.2 as u64).saturating_mul(coverage.3 as u64),
4805 );
4806 }
4807 let rounded_mask = shadow_composite_mask(shadow, anchor, root_scale);
4808 let downscaled =
4809 (source.width, source.height) != (source_device.width, source_device.height);
4810 let (sample_mode, source_viewport) = if downscaled {
4811 (
4812 CompositeSampleMode::Linear,
4813 Some((0.0, 0.0, source.width as f32, source.height as f32)),
4814 )
4815 } else {
4816 (CompositeSampleMode::Nearest, None)
4817 };
4818 resolved.push(ResolvedComposite {
4819 z_index: z,
4820 source,
4821 content,
4822 dest,
4823 scissor: Some(coverage),
4824 kind: ResolvedCompositeKind::Blit {
4825 alpha: 1.0,
4826 blend_mode: BlendMode::SrcOver,
4827 rounded_mask,
4828 sample_mode,
4829 source_viewport,
4830 },
4831 });
4832 }
4833
4834 #[expect(clippy::too_many_arguments)]
4843 fn render_shadow_source<C: FrameCommandRecorder>(
4844 &mut self,
4845 recorder: &mut C,
4846 shadow: &ShadowDraw,
4847 bounds: DevicePixelBounds,
4848 pixel_radius: f32,
4849 root_scale: f32,
4850 retained: bool,
4851 transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
4852 ) -> Option<Rc<OffscreenTarget>> {
4853 let (width, height) = (bounds.width, bounds.height);
4854 let device = self.device.clone();
4855 let (scratch_width, scratch_height) =
4856 crate::effect_renderer::blur_scratch_size(pixel_radius, pixel_radius, width, height);
4857 let full_size_result = shadow.post_blur_cutouts.is_some()
4858 || (scratch_width, scratch_height) == (width, height);
4859 let (result_width, result_height) = if full_size_result {
4860 (width, height)
4861 } else {
4862 (scratch_width, scratch_height)
4863 };
4864 let result = if retained {
4865 Rc::new(self.acquire_retained_surface(result_width, result_height))
4866 } else {
4867 self.shadow_transient(
4868 recorder,
4869 transients,
4870 "Shadow Result",
4871 result_width,
4872 result_height,
4873 )
4874 };
4875 let source = if full_size_result {
4876 Rc::clone(&result)
4877 } else {
4878 self.shadow_transient(recorder, transients, "Shadow Source", width, height)
4879 };
4880 let offset = [bounds.x, bounds.y];
4881 let target = PassTarget {
4882 view: &source.view,
4883 width,
4884 height,
4885 };
4886 let scene = shadow_scene(
4887 shadow.shapes.as_ref(),
4888 &shadow.texts,
4889 blur_reach(shadow.blur_radius, root_scale),
4890 );
4891 let segment = PassSegment {
4892 scene: &scene,
4893 ops: &scene.draw_ops,
4894 composites: &[],
4895 offset,
4896 scissor: None,
4897 first_run_window: None,
4898 transform: SegmentTransform::IDENTITY,
4899 scale: root_scale,
4900 };
4901 let drew = self.encode_pass(
4902 recorder,
4903 target,
4904 std::slice::from_ref(&segment),
4905 wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
4906 "Shadow Source Pass",
4907 );
4908 match drew {
4909 Ok(true) => {}
4910 Ok(false) => {
4911 drop(source);
4912 if retained && let Ok(target) = Rc::try_unwrap(result) {
4913 self.defer_offscreen_release(target);
4914 }
4915 return None;
4916 }
4917 Err(error) => {
4918 log::error!("shadow source pass failed: {error}");
4919 return None;
4920 }
4921 }
4922 if pixel_radius > 0.0 {
4923 let scratch_descriptor = self.transient_offscreen_descriptor(
4924 "Shadow Blur Scratch",
4925 scratch_width,
4926 scratch_height,
4927 );
4928 let scratch = recorder.acquire_transient_offscreen(&device, scratch_descriptor);
4929 let blurred = if full_size_result && (scratch_width, scratch_height) != (width, height)
4930 {
4931 Some(self.shadow_transient(
4932 recorder,
4933 transients,
4934 "Shadow Blur Result",
4935 scratch_width,
4936 scratch_height,
4937 ))
4938 } else {
4939 None
4940 };
4941 let blur_dest = match &blurred {
4942 Some(blurred) => (&blurred.view, (scratch_width, scratch_height)),
4943 None => (&result.view, (result_width, result_height)),
4944 };
4945 let passes = self.effect_renderer.encode_blur_scissored_ping_pong_passes(
4946 recorder,
4947 &device,
4948 &source,
4949 &scratch,
4950 blur_dest,
4951 pixel_radius,
4952 pixel_radius,
4953 TileMode::Decal,
4954 None,
4955 );
4956 recorder.record_passes(passes);
4957 self.effect_renderer.record_blur_pass();
4958 recorder.release_transient_offscreen(scratch_descriptor, scratch);
4959 if let Some(blurred) = &blurred {
4960 self.effect_renderer
4961 .encode_upscale_pass(recorder, &device, blurred, &result.view);
4962 recorder.record_pass();
4963 }
4964 }
4965 if let Some(cutout_run) = &shadow.post_blur_cutouts {
4966 let cutouts = shadow_scene(Some(cutout_run), &[], 0.0);
4967 let segment = PassSegment {
4968 scene: &cutouts,
4969 ops: &cutouts.draw_ops,
4970 composites: &[],
4971 offset,
4972 scissor: None,
4973 first_run_window: None,
4974 transform: SegmentTransform::IDENTITY,
4975 scale: root_scale,
4976 };
4977 if let Err(error) = self.encode_pass(
4978 recorder,
4979 target,
4980 std::slice::from_ref(&segment),
4981 wgpu::LoadOp::Load,
4982 "Shadow Cutout Pass",
4983 ) {
4984 log::error!("shadow cutout pass failed: {error}");
4985 }
4986 }
4987 Some(result)
4988 }
4989
4990 fn shadow_transient<C: FrameCommandRecorder>(
4993 &self,
4994 recorder: &mut C,
4995 transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
4996 label: &'static str,
4997 width: u32,
4998 height: u32,
4999 ) -> Rc<OffscreenTarget> {
5000 let descriptor = self.transient_offscreen_descriptor(label, width, height);
5001 let target = Rc::new(recorder.acquire_transient_offscreen(&self.device, descriptor));
5002 transients.push((descriptor, Rc::clone(&target)));
5003 target
5004 }
5005
5006 pub(crate) fn run_is_stored(&self, run: &RunDraw) -> bool {
5008 self.run_store.is_stored(run)
5009 }
5010
5011 fn run_pipeline_key(
5015 segment: &RecordSegment,
5016 placement: &crate::scene::Placement,
5017 tier: RunTier,
5018 ablation: ShapeAblation,
5019 turns: ShapeTurns,
5020 (depth, clip): (bool, SegmentClip),
5021 viewport: ViewportUniformParams,
5022 ) -> ShapePipelineKey {
5023 let blend_mode = supported_blend_mode(segment.blend);
5024 let laid = depth
5025 && blend_mode == BlendMode::SrcOver
5026 && !placement.paints()
5027 && clip != SegmentClip::Rounded
5028 && !ablation.material
5029 && !ablation.fill;
5030 ShapePipelineKey {
5031 blend_mode,
5032 tier,
5033 variant: ShapeVariant::of_segment(
5034 segment,
5035 clip,
5036 ablation,
5037 laid,
5038 (
5039 turns == ShapeTurns::None,
5040 turns == ShapeTurns::None
5041 && placement.snap_anchor.is_some()
5042 && viewport.offset.iter().all(|value| value.fract() == 0.0),
5043 ),
5044 ),
5045 turns,
5046 depth: if depth {
5047 ShapeDepth::Tested
5048 } else {
5049 ShapeDepth::Off
5050 },
5051 }
5052 }
5053
5054 fn ensure_run_pipelines(&mut self, key: ShapePipelineKey, vertices: u64) {
5057 self.ensure_shape_pipeline(key, vertices);
5058 if let Some(interior) = key.interior() {
5059 self.ensure_shape_pipeline(interior, vertices);
5060 }
5061 }
5062
5063 pub(crate) fn prepare_store_run<C: FrameCommandRecorder>(
5066 &mut self,
5067 recorder: &mut C,
5068 run: &RunDraw,
5069 viewport: ViewportUniformParams,
5070 root_scale: f32,
5071 window: &std::ops::Range<u32>,
5072 depth: bool,
5073 ) -> StoreRunBatch {
5074 let command = run.command.expect("a stored run has a command");
5075 let placement = &run.placement;
5076 let ablation = self.ablation.shape;
5077 let turns = ShapeTurns::of(viewport.transform, false);
5078 let scissor = clip_scissor(placement, root_scale, viewport);
5079 let clip = SegmentClip::of(placement, scissor.is_some());
5080 let mut draws = SmallVec::new();
5081 self.run_store.stored_run_draws(
5082 &self.device,
5083 run,
5084 &mut |segment| {
5085 Self::run_pipeline_key(
5086 segment,
5087 placement,
5088 RunTier::Store,
5089 ablation,
5090 turns,
5091 (depth, clip),
5092 viewport,
5093 )
5094 },
5095 &mut draws,
5096 );
5097 window_draws(&mut draws, window);
5098 let upload_start = Instant::now();
5099 let (upload, fill) =
5100 self.run_store
5101 .upload_stored(&self.device, recorder, run, root_scale, window, &draws);
5102 if let Some(total_ms) = should_log_wgpu_render_stage(upload_start, Instant::now()) {
5103 log::warn!(
5104 "[wgpu-render-stage:run-upload] total_ms={total_ms:.2} bytes={} records={}",
5105 upload.upload_bytes,
5106 run.tables().shapes.len()
5107 );
5108 }
5109 self.frame_stats.record_command_stats(upload);
5110 if let Some(fill) = fill {
5111 self.frame_stats.add_shape_fill(fill);
5112 }
5113 let uniforms = Uniforms::of(
5114 viewport,
5115 PlacementData::of(&run.placement, root_scale, viewport.transform),
5116 RunTier::Store,
5117 );
5118 let uniform_slot =
5119 self.viewport_uniforms
5120 .claim(&self.device, &self.uniform_bind_group_layout, &uniforms);
5121 for draw in &draws {
5122 self.ensure_run_pipelines(
5123 draw.key,
5124 crate::run_store::draw_vertices(
5125 draw.records.end - draw.records.start,
5126 draw.band_class,
5127 ),
5128 );
5129 }
5130 StoreRunBatch {
5131 command,
5132 uniform_slot,
5133 draws,
5134 clip: scissor,
5135 }
5136 }
5137
5138 pub(crate) fn open_arena(&mut self) -> usize {
5139 self.run_store.open_arena()
5140 }
5141
5142 pub(crate) fn open_arena_records(&self) -> u32 {
5144 self.run_store.open_arena_records()
5145 }
5146
5147 pub(crate) fn arena_accepts(&self, chunk: usize, run: &RunDraw) -> bool {
5148 self.run_store.arena_accepts(chunk, run)
5149 }
5150
5151 #[expect(clippy::too_many_arguments)]
5155 pub(crate) fn append_arena_run(
5159 &mut self,
5160 chunk: usize,
5161 run: &RunDraw,
5162 window: std::ops::Range<u32>,
5163 root_scale: f32,
5164 viewport: ViewportUniformParams,
5165 mixed_turns: bool,
5166 (depth, clip): (bool, SegmentClip),
5167 ) -> u32 {
5168 let placement = &run.placement;
5169 let ablation = self.ablation.shape;
5170 let turn = viewport.transform;
5171 let turns = ShapeTurns::of(turn, mixed_turns);
5172 let mut keys: SmallVec<[(ShapePipelineKey, u64); 4]> = SmallVec::new();
5173 let taken = self.run_store.append_arena(
5174 chunk,
5175 run,
5176 window,
5177 (root_scale, turn),
5178 &mut |segment| {
5179 Self::run_pipeline_key(
5180 segment,
5181 placement,
5182 RunTier::Arena,
5183 ablation,
5184 turns,
5185 (depth, clip),
5186 viewport,
5187 )
5188 },
5189 &mut keys,
5190 );
5191 for (key, vertices) in keys {
5192 self.ensure_run_pipelines(key, vertices);
5193 }
5194 taken
5195 }
5196
5197 pub(crate) fn cut_arena(&mut self, chunk: usize, out: &mut Vec<RunDrawCall>) {
5200 self.run_store.cut_arena(&self.device, chunk, out);
5201 }
5202
5203 pub(crate) fn close_arena(&mut self, chunk: usize, out: &mut Vec<RunDrawCall>) {
5206 if let Some(fill) = self.run_store.close_arena(&self.device, chunk, out) {
5207 self.frame_stats.add_shape_fill(fill);
5208 }
5209 }
5210
5211 pub(crate) fn draw_run_calls(
5212 &self,
5213 pass: &mut wgpu::RenderPass<'_>,
5214 tables: ArenaBinding<'_>,
5215 uniform_slot: usize,
5216 draws: &[RunDrawCall],
5217 scissor: (u32, u32, u32, u32),
5218 stage: RunStage,
5219 ) -> Result<(), String> {
5220 match stage {
5221 RunStage::Paint => {
5222 if draws.is_empty() {
5223 return Ok(());
5224 }
5225 self.frame_stats.bump_shapes();
5226 self.record_run_draws(
5227 pass,
5228 tables,
5229 uniform_slot,
5230 scissor,
5231 draws.iter().map(PlannedRunDraw::paint),
5232 )
5233 }
5234 RunStage::Interiors => {
5235 let planned = interior_run_draws(draws);
5236 if planned.is_empty() {
5237 return Ok(());
5238 }
5239 self.frame_stats
5240 .shape_interior_draws
5241 .set(self.frame_stats.shape_interior_draws.get() + planned.len() as u32);
5242 self.record_run_draws(pass, tables, uniform_slot, scissor, planned.into_iter())
5243 }
5244 }
5245 }
5246
5247 fn record_run_draws(
5249 &self,
5250 pass: &mut wgpu::RenderPass<'_>,
5251 tables: ArenaBinding<'_>,
5252 uniform_slot: usize,
5253 scissor: (u32, u32, u32, u32),
5254 planned: impl ExactSizeIterator<Item = PlannedRunDraw>,
5255 ) -> Result<(), String> {
5256 self.frame_stats.add_draw_calls(planned.len() as u32);
5257 let (x, y, width, height) = scissor;
5258 pass.set_scissor_rect(x, y, width, height);
5259 self.viewport_uniforms.bind(pass, uniform_slot)?;
5260 pass.set_bind_group(1, tables.bind_group, &tables.offsets[2..]);
5261 for (slot, buffer) in tables.records.into_iter().enumerate() {
5262 pass.set_vertex_buffer(slot as u32, buffer.slice(u64::from(tables.offsets[slot])..));
5263 }
5264 let mut bound_class = None;
5265 for draw in planned {
5266 let key = draw.key;
5267 let (pipeline, fallback) = self
5268 .shape_pipelines
5269 .get(key)
5270 .ok_or_else(|| format!("shape pipeline {key:?} was not prepared"))?;
5271 if fallback {
5272 self.frame_stats
5273 .shape_pipeline_fallback_draws
5274 .set(self.frame_stats.shape_pipeline_fallback_draws.get() + 1);
5275 } else if !key.is_general() {
5276 self.frame_stats
5277 .shape_specialized_draws
5278 .set(self.frame_stats.shape_specialized_draws.get() + 1);
5279 }
5280 if bound_class != Some(draw.band_class) {
5281 pass.set_index_buffer(
5282 self.run_store.strip_index_buffer(draw.band_class).slice(..),
5283 wgpu::IndexFormat::Uint32,
5284 );
5285 bound_class = Some(draw.band_class);
5286 }
5287 pass.set_pipeline(pipeline);
5288 pass.draw_indexed(draw.indices, 0, draw.records);
5289 }
5290 Ok(())
5291 }
5292
5293 pub(crate) fn draw_store_run(
5294 &self,
5295 pass: &mut wgpu::RenderPass<'_>,
5296 batch: &StoreRunBatch,
5297 scissor: (u32, u32, u32, u32),
5298 stage: RunStage,
5299 ) -> Result<(), String> {
5300 let stored = self
5301 .run_store
5302 .stored(&batch.command)
5303 .ok_or_else(|| "a stored run left the store before its draw".to_string())?;
5304 self.draw_run_calls(
5305 pass,
5306 stored.buffers.binding(),
5307 batch.uniform_slot,
5308 &batch.draws,
5309 scissor,
5310 stage,
5311 )
5312 }
5313
5314 pub(crate) fn draw_arena(
5315 &self,
5316 pass: &mut wgpu::RenderPass<'_>,
5317 chunk: usize,
5318 uniform_slot: usize,
5319 draws: &[RunDrawCall],
5320 scissor: (u32, u32, u32, u32),
5321 stage: RunStage,
5322 ) -> Result<(), String> {
5323 self.draw_run_calls(
5324 pass,
5325 self.run_store.arena_binding(chunk),
5326 uniform_slot,
5327 draws,
5328 scissor,
5329 stage,
5330 )
5331 }
5332 #[cfg(not(target_arch = "wasm32"))]
5333 pub(crate) fn surface_format(&self) -> wgpu::TextureFormat {
5334 self.display_format
5335 }
5336
5337 pub fn device_error_count(&self) -> u64 {
5338 self.device_errors.error_count()
5339 }
5340
5341 pub(crate) fn clear_target<C: FrameCommandRecorder>(
5344 &self,
5345 recorder: &mut C,
5346 view: &wgpu::TextureView,
5347 load_op: wgpu::LoadOp<wgpu::Color>,
5348 ) {
5349 self.empty_pass(recorder, "Clear Pass", view, load_op);
5350 }
5351
5352 pub(crate) fn empty_pass<C: FrameCommandRecorder>(
5353 &self,
5354 recorder: &mut C,
5355 label: &'static str,
5356 view: &wgpu::TextureView,
5357 load_op: wgpu::LoadOp<wgpu::Color>,
5358 ) {
5359 let pass = recorder.begin_color_pass(label, view, load_op);
5360 drop(pass);
5361 recorder.record_pass();
5362 }
5363 pub(crate) fn draw_image_cmds(
5364 &self,
5365 pass: &mut wgpu::RenderPass<'_>,
5366 image_slot: &ImageSlot,
5367 uniform_slot: usize,
5368 cmds: &[ImageDrawCmd],
5369 (blend_mode, depth): (BlendMode, bool),
5370 bound: Option<(u32, u32, u32, u32)>,
5371 ) -> Result<(), String> {
5372 if cmds.is_empty() {
5373 return Ok(());
5374 }
5375 self.frame_stats.bump_images();
5376 self.frame_stats.add_draw_calls(cmds.len() as u32);
5377 let mut bound_pipeline = None;
5378 self.viewport_uniforms.bind(pass, uniform_slot)?;
5379 pass.set_index_buffer(image_slot.indices.slice(), wgpu::IndexFormat::Uint32);
5380 pass.set_vertex_buffer(0, image_slot.vertices.slice());
5381 let mut clips_bound = false;
5382 for cmd in cmds {
5383 let Some((x, y, width, height)) = bounded_scissor(cmd.scissor, bound) else {
5384 continue;
5385 };
5386 pass.set_scissor_rect(x, y, width, height);
5387 let variant = ImageVariant {
5388 depth,
5389 alpha_mask: cmd.image.alpha_mask,
5390 rounded: cmd.clip.is_some(),
5391 };
5392 if bound_pipeline != Some(variant) {
5393 pass.set_pipeline(self.image_pipeline(blend_mode, variant));
5394 bound_pipeline = Some(variant);
5395 }
5396 pass.set_bind_group(1, &cmd.image.bind_group, &[]);
5397 let instance = match cmd.clip {
5398 Some(clip) => {
5399 if !clips_bound {
5400 let clips = image_slot
5401 .clips
5402 .as_ref()
5403 .ok_or_else(|| "rounded image without clip instances".to_string())?;
5404 pass.set_vertex_buffer(1, clips.slice());
5405 clips_bound = true;
5406 }
5407 clip
5408 }
5409 None => 0,
5410 };
5411 pass.draw_indexed(
5412 cmd.index_start..(cmd.index_start + 6),
5413 0,
5414 instance..instance + 1,
5415 );
5416 }
5417 Ok(())
5418 }
5419
5420 pub(crate) fn draw_glyph_cmds(
5421 &self,
5422 pass: &mut wgpu::RenderPass<'_>,
5423 (glyph_slot, turned_slot): (Option<&BufferUpload>, Option<&BufferUpload>),
5424 uniform_slot: usize,
5425 cmds: &[GlyphDrawCmd],
5426 bound: Option<(u32, u32, u32, u32)>,
5427 frame: PassFrame,
5428 ) -> Result<(), String> {
5429 if cmds.is_empty() {
5430 return Ok(());
5431 }
5432 let whole_target = frame.scissor(bound);
5433 self.frame_stats.bump_text();
5434 let mut bound_atlas = None;
5435 let mut shared_bound: Option<bool> = None;
5438 let mut bound_pipeline: Option<GlyphQuads> = None;
5439 let mut bound_run_instances: Option<&wgpu::Buffer> = None;
5440 let mut draws = 0u32;
5441 for draw in GlyphDraws::new(cmds) {
5442 let scissor = match draw.scissor {
5443 Some(scissor) => bounded_scissor(scissor, bound),
5444 None => Some(whole_target),
5445 };
5446 let Some((x, y, width, height)) = scissor else {
5447 continue;
5448 };
5449 pass.set_scissor_rect(x, y, width, height);
5450 if !bound_atlas.is_some_and(|atlas| Rc::ptr_eq(atlas, draw.atlas)) {
5451 pass.set_bind_group(1, draw.atlas.as_ref(), &[]);
5452 bound_atlas = Some(draw.atlas);
5453 }
5454 draws += 1;
5455 match draw.step {
5456 GlyphDrawStep::Shared(instances, quads) => {
5457 if bound_pipeline != Some(quads) {
5458 pass.set_pipeline(self.glyph_atlas_pipeline(frame.depth, quads));
5459 bound_pipeline = Some(quads);
5460 }
5461 let turned = quads.turned();
5462 if shared_bound != Some(turned) {
5463 let slot =
5464 if turned { turned_slot } else { glyph_slot }.ok_or_else(|| {
5465 "shared glyph draw without glyph instances".to_string()
5466 })?;
5467 self.viewport_uniforms.bind(pass, uniform_slot)?;
5468 pass.set_vertex_buffer(0, slot.slice());
5469 shared_bound = Some(turned);
5470 bound_run_instances = None;
5471 }
5472 pass.draw(0..GLYPH_QUAD_CORNERS, instances);
5473 }
5474 GlyphDrawStep::Retained {
5475 run,
5476 uniform_slot: retained_slot,
5477 aligned,
5478 } => {
5479 let quads = GlyphQuads::plain(aligned);
5480 if bound_pipeline != Some(quads) {
5481 pass.set_pipeline(self.glyph_atlas_pipeline(frame.depth, quads));
5482 bound_pipeline = Some(quads);
5483 }
5484 shared_bound = None;
5485 self.viewport_uniforms.bind(pass, retained_slot)?;
5486 let instances = run.span.instance_buffer();
5487 if bound_run_instances != Some(instances) {
5488 pass.set_vertex_buffer(0, instances.slice(..));
5489 bound_run_instances = Some(instances);
5490 }
5491 pass.draw(0..GLYPH_QUAD_CORNERS, run.span.instances());
5492 }
5493 }
5494 }
5495 self.frame_stats.add_draw_calls(draws);
5496 Ok(())
5497 }
5498 pub(crate) fn append_image_draw_cmd(
5499 &mut self,
5500 image_draw: &ImageDraw,
5501 viewport: ViewportUniformParams,
5502 root_scale: f32,
5503 (image_vertices, image_indices): (&mut Vec<Vertex>, &mut Vec<u32>),
5504 image_clips: &mut Vec<DeviceRoundedClip>,
5505 image_cmds: &mut Vec<ImageDrawCmd>,
5506 ) -> Result<(), String> {
5507 let snap_delta = image_draw
5508 .snap_anchor
5509 .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
5510 .unwrap_or_default();
5511 let rect = image_draw.rect.translate(snap_delta.x, snap_delta.y);
5512 if rect.width <= 0.0 || rect.height <= 0.0 || image_draw.alpha <= 0.0 {
5513 return Ok(());
5514 }
5515
5516 let (mut tint, cpu_filter) = tint_for_image(image_draw.color_filter, image_draw.alpha);
5517 if tint[3] <= 0.0 {
5518 return Ok(());
5519 }
5520
5521 let filtered_image = cpu_filter
5522 .map(|filter| apply_filter_to_bitmap(&image_draw.image, filter))
5523 .transpose()?;
5524 let prepared_image = filtered_image.as_ref().unwrap_or(&image_draw.image);
5525 if let cranpose_ui_graphics::ImagePixelFormat::Alpha8 { color } = prepared_image.format() {
5526 for (channel, value) in tint[..3].iter_mut().zip(color) {
5527 *channel *= value as f32 / 255.0;
5528 }
5529 }
5530
5531 let geometry = resolve_image_geometry_with_delta(image_draw, root_scale, snap_delta);
5532 let Some(scissor) =
5533 scissor_rect_for_layer(geometry.rect, geometry.clip, root_scale, viewport)
5534 else {
5535 return Ok(());
5536 };
5537
5538 let Some(uv_rect) = image_uv_rect(&image_draw.image, image_draw.src_rect) else {
5539 return Ok(());
5540 };
5541 let device_quad = geometry.device_quad(root_scale);
5542 let index_start =
5543 push_image_quad((image_vertices, image_indices), device_quad, tint, &uv_rect);
5544 let clip = DeviceRoundedClip::of(image_draw, root_scale).map(|clip| {
5545 image_clips.push(clip);
5546 image_clips.len() as u32 - 1
5547 });
5548 image_cmds.push(ImageDrawCmd {
5549 index_start,
5550 scissor,
5551 image: self.image_binding(prepared_image, geometry.sampling)?,
5552 clip,
5553 });
5554 Ok(())
5555 }
5556
5557 pub(crate) fn upload_image_slot<C: FrameCommandRecorder>(
5559 &self,
5560 recorder: &mut C,
5561 vertices: &[Vertex],
5562 indices: &[u32],
5563 clips: &[DeviceRoundedClip],
5564 ) -> ImageSlot {
5565 ImageSlot {
5566 vertices: recorder.upload_buffer(
5567 image_vertex_spec(),
5568 &self.device,
5569 bytemuck::cast_slice(vertices),
5570 ),
5571 indices: recorder.upload_buffer(
5572 image_index_spec(),
5573 &self.device,
5574 bytemuck::cast_slice(indices),
5575 ),
5576 clips: (!clips.is_empty()).then(|| {
5577 recorder.upload_buffer(
5578 UploadAllocatorSpec::vertex(
5579 "Image Clip Buffer",
5580 std::mem::size_of::<DeviceRoundedClip>() as u64,
5581 ),
5582 &self.device,
5583 bytemuck::cast_slice(clips),
5584 )
5585 }),
5586 }
5587 }
5588
5589 pub(crate) fn upload_glyph_instances<C: FrameCommandRecorder>(
5590 &self,
5591 recorder: &mut C,
5592 instances: &[GlyphInstance],
5593 ) -> BufferUpload {
5594 recorder.upload_buffer(
5595 glyph_instance_spec(),
5596 &self.device,
5597 bytemuck::cast_slice(instances),
5598 )
5599 }
5600
5601 pub(crate) fn upload_turned_glyphs<C: FrameCommandRecorder>(
5602 &self,
5603 recorder: &mut C,
5604 glyphs: &[TurnedGlyph],
5605 ) -> BufferUpload {
5606 recorder.upload_buffer(
5607 turned_glyph_spec(),
5608 &self.device,
5609 bytemuck::cast_slice(glyphs),
5610 )
5611 }
5612
5613 fn glyph_atlas_entry_for(
5614 &mut self,
5615 glyph: &SoftwareGlyphAtlasGlyph,
5616 ) -> Result<GlyphAtlasEntry, String> {
5617 if let Some(entry) = self.text_glyph_atlas.upload_glyph(
5618 glyph,
5619 &self.queue,
5620 &mut self.frame_graph_executor,
5621 &mut self.frame_stats,
5622 ) {
5623 return Ok(entry);
5624 }
5625
5626 self.text_glyph_atlas.reset(
5627 &self.device,
5628 &self.image_bind_group_layout,
5629 GlyphSamplers {
5630 nearest: &self.image_nearest_sampler,
5631 linear: &self.image_linear_sampler,
5632 },
5633 );
5634 Err("text glyph atlas filled and was reset".to_string())
5635 }
5636
5637 fn glyph_atlas_entry_for_cached(
5638 &mut self,
5639 glyph: &SoftwareGlyphAtlasPlacement,
5640 ) -> Option<GlyphAtlasEntry> {
5641 let entry = self
5642 .text_glyph_atlas
5643 .entry(&GlyphAtlasSlotKey::new(glyph.key, glyph.color))?;
5644 self.frame_stats.record_text_glyph_atlas_hits(1);
5645 Some(entry)
5646 }
5647
5648 fn glyph_atlas_entry_for_placement(
5649 &mut self,
5650 glyph: &SoftwareGlyphAtlasPlacement,
5651 ) -> Result<GlyphAtlasEntry, String> {
5652 if let Some(entry) = self.glyph_atlas_entry_for_cached(glyph) {
5653 return Ok(entry);
5654 }
5655
5656 let Some(upload_glyph) = self.text_glyph_mask_cache.atlas_glyph_for_placement(glyph) else {
5657 return Err("text glyph placement has no retained raster mask".to_string());
5658 };
5659 self.glyph_atlas_entry_for(&upload_glyph)
5660 }
5661
5662 fn prepare_text_glyph_entries(
5666 &mut self,
5667 run_key: TextGlyphRunCacheKey,
5668 atlas_generation: u64,
5669 cached_glyph_run: Option<&RunGlyphs>,
5670 collected_run: &[SoftwareGlyphAtlasRunGlyph],
5671 entries: &mut Vec<GlyphAtlasEntry>,
5672 ) -> Result<Rc<[GlyphAtlasEntry]>, String> {
5673 entries.clear();
5674 let mut seen = RunAtlasEntries::new();
5675 if let Some(glyph_run) = cached_glyph_run {
5676 for glyph in glyph_run.iter() {
5677 entries.push(seen.entry(self, &glyph, |renderer| {
5678 renderer.glyph_atlas_entry_for_placement(&glyph)
5679 })?);
5680 }
5681 } else {
5682 for run_glyph in collected_run {
5683 entries.push(seen.entry(
5684 self,
5685 &run_glyph.placement(),
5686 |renderer| match run_glyph {
5687 SoftwareGlyphAtlasRunGlyph::Cached(placement) => {
5688 renderer.glyph_atlas_entry_for_placement(placement)
5689 }
5690 SoftwareGlyphAtlasRunGlyph::New(glyph) => {
5691 renderer.glyph_atlas_entry_for(glyph)
5692 }
5693 },
5694 )?);
5695 }
5696 }
5697
5698 let entries: Rc<[GlyphAtlasEntry]> = Rc::from(entries.as_slice());
5699 if let Some(cached) = self.text_glyph_run_cache.get_mut(&run_key) {
5700 cached.atlas_entries = Some(Rc::clone(&entries));
5701 cached.atlas_generation = atlas_generation;
5702 }
5703 Ok(entries)
5704 }
5705
5706 #[expect(clippy::too_many_arguments)]
5707 fn append_text_glyph_quad_run(
5708 &mut self,
5709 source_raster_rect: Rect,
5710 quads: GlyphRunQuads<'_>,
5711 (clip, cut): (Option<Rect>, Option<[f32; 4]>),
5712 viewport: ViewportUniformParams,
5713 root_scale: f32,
5714 glyph_instances: &mut GlyphInstances,
5715 record_cached_hits: bool,
5716 ) -> GlyphQuads {
5717 let start = glyph_instances.lens();
5718 let kind = if viewport.transform.is_identity() {
5719 let plain = &mut glyph_instances.plain;
5720 let mut aligned = true;
5721 for_each_visible_glyph(
5722 source_raster_rect,
5723 quads,
5724 (clip, cut),
5725 viewport,
5726 root_scale,
5727 |glyph| {
5728 aligned &= glyph_rect_aligned(glyph.rect, viewport.offset);
5729 plain.push(glyph);
5730 },
5731 );
5732 GlyphQuads::plain(aligned)
5733 } else {
5734 let turn = viewport.transform;
5735 let turned = &mut glyph_instances.turned;
5736 for_each_visible_glyph(
5737 source_raster_rect,
5738 quads,
5739 (clip, cut),
5740 viewport,
5741 root_scale,
5742 |glyph| turned.push(TurnedGlyph::new(glyph, turn)),
5743 );
5744 GlyphQuads::Turned
5745 };
5746 let end = glyph_instances.lens();
5747 let appended = (end.0 - start.0) + (end.1 - start.1);
5748 if record_cached_hits {
5749 self.frame_stats
5750 .record_text_glyph_atlas_hits(u32::try_from(appended).unwrap_or(u32::MAX));
5751 }
5752 kind
5753 }
5754
5755 fn retained_glyph_viewport(
5760 viewport: ViewportUniformParams,
5761 source_raster_rect: Rect,
5762 ) -> ViewportUniformParams {
5763 if !viewport.transform.is_identity() {
5764 return ViewportUniformParams {
5765 origin: [source_raster_rect.x, source_raster_rect.y],
5766 ..viewport
5767 };
5768 }
5769 ViewportUniformParams {
5770 offset: [
5771 viewport.offset[0] - source_raster_rect.x,
5772 viewport.offset[1] - source_raster_rect.y,
5773 ],
5774 ..viewport
5775 }
5776 }
5777
5778 fn retained_text_glyph_run(
5779 &mut self,
5780 cache_key: TextGlyphRunCacheKey,
5781 ) -> Option<Rc<CachedGpuTextGlyphRun>> {
5782 let atlas_generation = self.text_glyph_atlas.generation();
5783 let frame = self.text_glyph_run_frame;
5784 self.text_glyph_gpu_run_cache
5785 .get(&cache_key)
5786 .filter(|cached| cached.atlas_generation == atlas_generation)
5787 .inspect(|cached| cached.last_frame.set(frame))
5788 .cloned()
5789 }
5790
5791 fn begin_text_glyph_run_frame(&mut self) {
5795 self.text_glyph_run_frame += 1;
5796 let frame = self.text_glyph_run_frame;
5797 let demand = std::mem::take(&mut self.text_glyph_runs_drawn).saturating_mul(2);
5798 self.text_glyph_run_cache.set_cap(
5799 std::num::NonZeroUsize::new(demand.max(MIN_TEXT_GLYPH_RUN_CACHE_ITEMS))
5800 .unwrap_or(std::num::NonZeroUsize::MIN),
5801 );
5802 evict_idle(&mut self.text_glyph_gpu_run_cache, frame, |run| {
5803 run.last_frame.get()
5804 });
5805 evict_idle(&mut self.text_glyph_run_cache, frame, |run| {
5806 run.last_frame.get()
5807 });
5808 self.text_glyph_run_arena.begin_frame();
5809 }
5810
5811 fn emit_retained_text_glyph_run_if_ready(
5812 &mut self,
5813 cache_key: TextGlyphRunCacheKey,
5814 quads: GlyphRunQuads<'_>,
5815 viewport: ViewportUniformParams,
5816 source_raster_rect: Rect,
5817 scissor: (u32, u32, u32, u32),
5818 glyph_cmds: &mut Vec<GlyphDrawCmd>,
5819 ) -> bool {
5820 let Some(run) = self.retained_text_glyph_run(cache_key).or_else(|| {
5821 if self.ensure_retained_text_glyph_run(cache_key, quads) {
5822 self.retained_text_glyph_run(cache_key)
5823 } else {
5824 None
5825 }
5826 }) else {
5827 return false;
5828 };
5829 let uniform_slot =
5830 self.claim_uniform_slot(Self::retained_glyph_viewport(viewport, source_raster_rect));
5831 self.frame_stats
5832 .record_text_glyph_atlas_hits(u32::try_from(quads.len()).unwrap_or(u32::MAX));
5833 let aligned = viewport.transform.is_identity()
5835 && glyph_rect_aligned(
5836 [source_raster_rect.x, source_raster_rect.y, 0.0, 0.0],
5837 [viewport.offset[0], viewport.offset[1]],
5838 );
5839 glyph_cmds.push(GlyphDrawCmd::retained(
5840 (run, uniform_slot, aligned),
5841 scissor,
5842 self.text_glyph_atlas.bind_group(viewport.transform),
5843 ));
5844 true
5845 }
5846
5847 fn ensure_retained_text_glyph_run(
5848 &mut self,
5849 cache_key: TextGlyphRunCacheKey,
5850 quads: GlyphRunQuads<'_>,
5851 ) -> bool {
5852 let atlas_generation = self.text_glyph_atlas.generation();
5853 if self
5854 .text_glyph_gpu_run_cache
5855 .peek(&cache_key)
5856 .is_some_and(|cached| cached.atlas_generation == atlas_generation)
5857 {
5858 return true;
5859 }
5860
5861 let origin = Rect {
5862 x: 0.0,
5863 y: 0.0,
5864 width: 0.0,
5865 height: 0.0,
5866 };
5867 let Some(span) = self.text_glyph_run_arena.insert(
5868 &self.device,
5869 quads
5870 .iter()
5871 .filter_map(|quad| cached_text_glyph_instance(origin, &quad)),
5872 ) else {
5873 return false;
5874 };
5875 self.text_glyph_gpu_run_cache.put(
5876 cache_key,
5877 Rc::new(CachedGpuTextGlyphRun {
5878 span,
5879 atlas_generation,
5880 last_frame: Cell::new(self.text_glyph_run_frame),
5881 }),
5882 );
5883 true
5884 }
5885 pub(crate) fn append_text_glyph_draws(
5890 &mut self,
5891 text_draw: &TextDraw,
5892 viewport: ViewportUniformParams,
5893 root_scale: f32,
5894 glyph_instances: &mut GlyphInstances,
5895 glyph_cmds: &mut Vec<GlyphDrawCmd>,
5896 ) -> bool {
5897 let Some((logical_rect, raster_rect, clip, text_scale, static_text_motion)) =
5898 self.text_raster_geometry(text_draw, root_scale)
5899 else {
5900 return true;
5901 };
5902 if !static_text_motion {
5903 return false;
5904 }
5905 if !text_draw_is_visible_in_viewport(logical_rect, clip, viewport, root_scale) {
5906 return true;
5907 }
5908 let run_key = Self::text_glyph_run_cache_key(text_draw, raster_rect, text_scale);
5909 let mut collected_run = std::mem::take(&mut self.scratch_text_glyph_run);
5910 let mut generated_entries = std::mem::take(&mut self.scratch_text_glyph_entries);
5911 let initial_instance_len = glyph_instances.lens();
5912 let initial_cmd_len = glyph_cmds.len();
5913 let drew = self
5914 .text_glyph_run(
5915 text_draw,
5916 raster_rect,
5917 text_scale,
5918 run_key,
5919 &mut collected_run,
5920 )
5921 .is_some_and(|run| {
5922 self.append_text_glyph_run(
5923 TextGlyphRunDraw {
5924 text_draw,
5925 raster_rect,
5926 run_key,
5927 run,
5928 },
5929 (viewport, root_scale),
5930 (&collected_run, &mut generated_entries),
5931 glyph_instances,
5932 glyph_cmds,
5933 )
5934 });
5935 self.scratch_text_glyph_run = collected_run;
5936 self.scratch_text_glyph_entries = generated_entries;
5937 if !drew {
5938 glyph_instances.truncate(initial_instance_len);
5939 glyph_cmds.truncate(initial_cmd_len);
5940 }
5941 drew
5942 }
5943
5944 fn text_glyph_run(
5948 &mut self,
5949 text_draw: &TextDraw,
5950 raster_rect: Rect,
5951 text_scale: f32,
5952 run_key: TextGlyphRunCacheKey,
5953 collected_run: &mut Vec<SoftwareGlyphAtlasRunGlyph>,
5954 ) -> Option<TextGlyphRunLookup> {
5955 let atlas_generation = self.text_glyph_atlas.generation();
5956 let frame = self.text_glyph_run_frame;
5957 self.text_glyph_runs_drawn += 1;
5958 if let Some(cached) = self.text_glyph_run_cache.get(&run_key) {
5959 cached.last_frame.set(frame);
5960 return Some(TextGlyphRunLookup {
5961 glyphs: cached.glyphs.clone(),
5962 bounds: cached.bounds,
5963 cached: true,
5964 entries: (cached.atlas_generation == atlas_generation)
5965 .then(|| cached.atlas_entries.as_ref().map(Rc::clone))
5966 .flatten(),
5967 });
5968 }
5969 collected_run.clear();
5970 if collect_solid_text_atlas_run(
5971 text_draw.text.as_ref(),
5972 raster_rect,
5973 &text_draw.text_style,
5974 text_draw.color,
5975 text_draw.font_size,
5976 text_scale,
5977 &self.text_fonts,
5978 &mut self.text_glyph_mask_cache,
5979 collected_run,
5980 )
5981 .is_none()
5982 {
5983 log_text_atlas_fallback(text_draw);
5984 return None;
5985 }
5986 let Some(glyphs) = RunGlyphs::of(
5987 collected_run
5988 .iter()
5989 .map(SoftwareGlyphAtlasRunGlyph::placement),
5990 &mut self.run_glyph_scratch,
5991 ) else {
5992 log_text_atlas_fallback(text_draw);
5993 return None;
5994 };
5995 let bounds = GlyphRunBounds::of(glyphs.iter());
5996 self.frame_stats.record_text_glyph_run_collected();
5997 let cache = &mut self.text_glyph_run_cache;
5999 if cache.len() == cache.cap().get()
6000 && cache
6001 .peek_lru()
6002 .is_some_and(|(_, run)| run.last_frame.get() == frame)
6003 {
6004 cache.set_cap(cache.cap().saturating_add(cache.len()));
6005 }
6006 self.text_glyph_run_cache.put(
6007 run_key,
6008 CachedTextGlyphRun {
6009 glyphs: glyphs.clone(),
6010 bounds,
6011 atlas_entries: None,
6012 atlas_generation: 0,
6013 last_frame: Cell::new(frame),
6014 },
6015 );
6016 Some(TextGlyphRunLookup {
6017 glyphs,
6018 bounds,
6019 cached: false,
6020 entries: None,
6021 })
6022 }
6023
6024 fn append_text_glyph_run(
6028 &mut self,
6029 draw: TextGlyphRunDraw<'_>,
6030 (viewport, root_scale): (ViewportUniformParams, f32),
6031 (collected_run, generated_entries): (
6032 &[SoftwareGlyphAtlasRunGlyph],
6033 &mut Vec<GlyphAtlasEntry>,
6034 ),
6035 glyph_instances: &mut GlyphInstances,
6036 glyph_cmds: &mut Vec<GlyphDrawCmd>,
6037 ) -> bool {
6038 let TextGlyphRunDraw {
6039 text_draw,
6040 raster_rect,
6041 run_key,
6042 run,
6043 } = draw;
6044 let draw_rect = Rect {
6045 x: raster_rect.x / root_scale,
6046 y: raster_rect.y / root_scale,
6047 width: raster_rect.width / root_scale,
6048 height: raster_rect.height / root_scale,
6049 };
6050 let Some(scissor) = scissor_rect_for_layer(draw_rect, text_draw.clip, root_scale, viewport)
6051 else {
6052 return true;
6053 };
6054 let atlas_size = self.text_glyph_atlas.size();
6055
6056 let clip_needs_cut = !viewport.transform.is_identity() && text_draw.clip.is_some();
6059 if let Some(entries) = run.entries.as_ref()
6060 && entries.len() >= RETAINED_TEXT_GLYPH_RUN_MIN_QUADS
6061 && !clip_needs_cut
6062 && self.emit_retained_text_glyph_run_if_ready(
6063 run_key,
6064 GlyphRunQuads {
6065 glyphs: &run.glyphs,
6066 entries,
6067 atlas_size,
6068 bounds: run.bounds,
6069 },
6070 viewport,
6071 raster_rect,
6072 scissor,
6073 glyph_cmds,
6074 )
6075 {
6076 return true;
6077 }
6078
6079 let turned = !viewport.transform.is_identity();
6080 let instance_start = glyph_instances.len_of(turned);
6081 let (entries, entries_cached) = match run.entries {
6082 Some(entries) => (entries, true),
6083 None => {
6084 let Ok(entries) = self.prepare_text_glyph_entries(
6085 run_key,
6086 self.text_glyph_atlas.generation(),
6087 run.cached.then_some(&run.glyphs),
6088 collected_run,
6089 generated_entries,
6090 ) else {
6091 return false;
6092 };
6093 (entries, false)
6094 }
6095 };
6096 let quads = GlyphRunQuads {
6097 glyphs: &run.glyphs,
6098 entries: &entries,
6099 atlas_size: self.text_glyph_atlas.size(),
6100 bounds: run.bounds,
6101 };
6102 let cut = glyph_cut_edges(text_draw.clip, scissor, viewport, root_scale);
6103 let kind = self.append_text_glyph_quad_run(
6104 raster_rect,
6105 quads,
6106 (text_draw.clip, cut),
6107 viewport,
6108 root_scale,
6109 glyph_instances,
6110 entries_cached,
6111 );
6112 let instance_end = glyph_instances.len_of(turned);
6113 if instance_end > instance_start {
6114 let (clip, bounds) = glyph_instances.draw_clip(
6115 (instance_start..instance_end, turned),
6116 scissor,
6117 viewport,
6118 );
6119 glyph_cmds.push(GlyphDrawCmd::shared(
6120 (instance_start..instance_end, kind),
6121 clip,
6122 bounds,
6123 self.text_glyph_atlas.bind_group(viewport.transform),
6124 ));
6125 }
6126 true
6127 }
6128
6129 #[expect(clippy::too_many_arguments)]
6130 fn append_image_bitmap_draw_cmd(
6131 &mut self,
6132 image: &ImageBitmap,
6133 rect: Rect,
6134 clip: Option<Rect>,
6135 sampling: ImageSampling,
6136 viewport: ViewportUniformParams,
6137 root_scale: f32,
6138 image_vertices: &mut Vec<Vertex>,
6139 image_indices: &mut Vec<u32>,
6140 image_cmds: &mut Vec<ImageDrawCmd>,
6141 ) -> Result<(), String> {
6142 if rect.width <= 0.0 || rect.height <= 0.0 {
6143 return Ok(());
6144 }
6145
6146 let (device_quad, scissor_rect) =
6147 if sampling == ImageSampling::Nearest && root_scale.is_finite() && root_scale > 0.0 {
6148 let left_px = (rect.x * root_scale).round();
6149 let top_px = (rect.y * root_scale).round();
6150 let width_px = (rect.width * root_scale).round().max(1.0);
6151 let height_px = (rect.height * root_scale).round().max(1.0);
6152 let snapped_rect = Rect {
6153 x: left_px / root_scale,
6154 y: top_px / root_scale,
6155 width: width_px / root_scale,
6156 height: height_px / root_scale,
6157 };
6158 let right_px = left_px + width_px;
6159 let bottom_px = top_px + height_px;
6160 (
6161 [
6162 [left_px, top_px],
6163 [right_px, top_px],
6164 [left_px, bottom_px],
6165 [right_px, bottom_px],
6166 ],
6167 snapped_rect,
6168 )
6169 } else {
6170 (
6171 rect_to_quad(rect).map(|[x, y]| [x * root_scale, y * root_scale]),
6172 rect,
6173 )
6174 };
6175
6176 let Some(scissor) = scissor_rect_for_layer(scissor_rect, clip, root_scale, viewport) else {
6177 return Ok(());
6178 };
6179 let Some(uv_rect) = image_uv_rect(image, None) else {
6180 return Ok(());
6181 };
6182
6183 let index_start = push_image_quad(
6184 (image_vertices, image_indices),
6185 device_quad,
6186 [1.0, 1.0, 1.0, 1.0],
6187 &uv_rect,
6188 );
6189 image_cmds.push(ImageDrawCmd {
6190 index_start,
6191 scissor,
6192 image: self.image_binding(image, sampling)?,
6193 clip: None,
6194 });
6195 Ok(())
6196 }
6197
6198 pub(crate) fn append_text_image_draw_cmds(
6200 &mut self,
6201 text_draw: &TextDraw,
6202 viewport: ViewportUniformParams,
6203 root_scale: f32,
6204 image_vertices: &mut Vec<Vertex>,
6205 image_indices: &mut Vec<u32>,
6206 image_cmds: &mut Vec<ImageDrawCmd>,
6207 ) -> Result<(), String> {
6208 let Some((logical_rect, raster_rect, clip, text_scale, static_text_motion)) =
6209 self.text_raster_geometry(text_draw, root_scale)
6210 else {
6211 return Ok(());
6212 };
6213 if !text_draw_is_visible_in_viewport(logical_rect, clip, viewport, root_scale) {
6214 return Ok(());
6215 }
6216
6217 let raster_source = self.text_image_raster_source(
6218 text_draw,
6219 logical_rect,
6220 raster_rect,
6221 clip,
6222 root_scale,
6223 static_text_motion,
6224 );
6225 let source_draw = raster_source.draw.as_ref();
6226 let source_raster_rect = raster_source.raster_rect;
6227 let source_origin = if source_draw.text.span_styles().is_empty() {
6228 Point::new(source_raster_rect.x, source_raster_rect.y)
6229 } else {
6230 Point::new(raster_rect.x, raster_rect.y)
6231 };
6232
6233 let mut cache_key = Self::text_image_cache_key(
6234 source_draw,
6235 source_raster_rect,
6236 text_scale,
6237 static_text_motion,
6238 );
6239 if !source_draw.text.span_styles().is_empty() {
6240 let mut state = default_hash::new();
6241 cache_key.0.hash(&mut state);
6242 (source_origin.x - source_raster_rect.x)
6243 .to_bits()
6244 .hash(&mut state);
6245 (source_origin.y - source_raster_rect.y)
6246 .to_bits()
6247 .hash(&mut state);
6248 cache_key = TextImageCacheKey(state.finish());
6249 }
6250 let image = if let Some(cached) = self.text_image_cache.get(&cache_key) {
6251 self.frame_stats
6252 .record_text_image_cache_hit(cached.image.width(), cached.image.height());
6253 cached.image.clone()
6254 } else {
6255 let Some(image) = self.rasterize_text_draw_to_image(
6256 source_draw,
6257 source_raster_rect,
6258 source_origin,
6259 text_scale,
6260 ) else {
6261 return Ok(());
6262 };
6263 self.frame_stats
6264 .record_text_image_cache_miss(image.width(), image.height());
6265 self.text_image_cache.put(
6266 cache_key,
6267 CachedTextImage {
6268 image: image.clone(),
6269 },
6270 );
6271 image
6272 };
6273
6274 let draw_origin = if static_text_motion {
6275 Point::new(
6276 source_raster_rect.x / root_scale,
6277 source_raster_rect.y / root_scale,
6278 )
6279 } else {
6280 Point::new(logical_rect.x, logical_rect.y)
6281 };
6282 let draw_rect = Rect {
6283 x: draw_origin.x,
6284 y: draw_origin.y,
6285 width: image.width() as f32 / root_scale,
6286 height: image.height() as f32 / root_scale,
6287 };
6288 self.append_image_bitmap_draw_cmd(
6289 &image,
6290 draw_rect,
6291 clip,
6292 sampling_under(ImageSampling::Nearest, viewport.transform),
6293 viewport,
6294 root_scale,
6295 image_vertices,
6296 image_indices,
6297 image_cmds,
6298 )
6299 }
6300
6301 fn text_image_raster_source<'a>(
6302 &mut self,
6303 text_draw: &'a TextDraw,
6304 logical_rect: Rect,
6305 raster_rect: Rect,
6306 clip: Option<Rect>,
6307 root_scale: f32,
6308 static_text_motion: bool,
6309 ) -> TextRasterSource<'a> {
6310 let Some(clip) = clip else {
6311 return TextRasterSource {
6312 draw: Cow::Borrowed(text_draw),
6313 raster_rect,
6314 };
6315 };
6316 if !static_text_motion || text_draw.text.text().find('\n').is_none() {
6317 return TextRasterSource {
6318 draw: Cow::Borrowed(text_draw),
6319 raster_rect,
6320 };
6321 }
6322
6323 if !text_draw.text.span_styles().is_empty() {
6324 let device_clip = Rect {
6325 x: (clip.x * root_scale).floor(),
6326 y: (clip.y * root_scale).floor(),
6327 width: ((clip.x + clip.width) * root_scale).ceil() - (clip.x * root_scale).floor(),
6328 height: ((clip.y + clip.height) * root_scale).ceil()
6329 - (clip.y * root_scale).floor(),
6330 };
6331 return TextRasterSource {
6332 draw: Cow::Borrowed(text_draw),
6333 raster_rect: raster_rect.intersect(device_clip).unwrap_or(raster_rect),
6334 };
6335 }
6336
6337 let line_starts = self.text_line_index_cache.line_starts(&text_draw.text);
6338 clipped_text_raster_source_with_line_starts(
6339 text_draw,
6340 logical_rect,
6341 raster_rect,
6342 clip,
6343 root_scale,
6344 line_starts.as_ref(),
6345 )
6346 }
6347
6348 fn text_raster_geometry(
6349 &self,
6350 text_draw: &TextDraw,
6351 root_scale: f32,
6352 ) -> Option<(Rect, Rect, Option<Rect>, f32, bool)> {
6353 text_raster_geometry_for_draw(text_draw, root_scale)
6354 }
6355
6356 fn text_image_cache_key(
6357 text_draw: &TextDraw,
6358 raster_rect: Rect,
6359 text_scale: f32,
6360 static_text_motion: bool,
6361 ) -> TextImageCacheKey {
6362 let mut state = default_hash::new();
6363 hash_text_draw_for_cache(text_draw, raster_rect, text_scale, &mut state);
6364 hash_text_raster_geometry_for_cache(raster_rect, static_text_motion, &mut state);
6365 TextImageCacheKey(state.finish())
6366 }
6367
6368 fn text_glyph_run_cache_key(
6373 text_draw: &TextDraw,
6374 raster_rect: Rect,
6375 text_scale: f32,
6376 ) -> TextGlyphRunCacheKey {
6377 let mut state = default_hash::new();
6378 hash_text_draw_for_cache(text_draw, raster_rect, text_scale, &mut state);
6379 (raster_rect.width <= 0.0 || raster_rect.height <= 0.0).hash(&mut state);
6380 TextGlyphRunCacheKey(state.finish())
6381 }
6382
6383 fn rasterize_text_draw_to_image(
6384 &mut self,
6385 text_draw: &TextDraw,
6386 raster_rect: Rect,
6387 source_origin: Point,
6388 text_scale: f32,
6389 ) -> Option<ImageBitmap> {
6390 rasterize_annotated_text_region(
6391 text_draw.text.as_ref(),
6392 raster_rect,
6393 if text_draw.text.span_styles().is_empty() {
6394 Point::new(raster_rect.x, raster_rect.y)
6395 } else {
6396 source_origin
6397 },
6398 &text_draw.text_style,
6399 text_draw.color,
6400 text_draw.font_size,
6401 text_scale,
6402 &self.text_fonts,
6403 Some(&mut self.text_glyph_mask_cache),
6404 )
6405 }
6406}
6407
6408struct TextRasterSource<'a> {
6409 draw: Cow<'a, TextDraw>,
6410 raster_rect: Rect,
6411}
6412
6413fn clipped_text_raster_source_with_line_starts<'a>(
6414 text_draw: &'a TextDraw,
6415 logical_rect: Rect,
6416 raster_rect: Rect,
6417 clip: Rect,
6418 root_scale: f32,
6419 line_starts: &[usize],
6420) -> TextRasterSource<'a> {
6421 if line_starts.len() < MIN_MULTILINE_TEXT_LINES_FOR_CLIPPED_RASTER {
6422 return TextRasterSource {
6423 draw: Cow::Borrowed(text_draw),
6424 raster_rect,
6425 };
6426 }
6427
6428 let Some(visible_rect) = logical_rect.intersect(clip) else {
6429 return TextRasterSource {
6430 draw: Cow::Borrowed(text_draw),
6431 raster_rect,
6432 };
6433 };
6434
6435 let line_count = line_starts.len().max(1);
6436 let line_height = logical_rect.height / line_count as f32;
6437 if !line_height.is_finite() || line_height <= 0.0 {
6438 return TextRasterSource {
6439 draw: Cow::Borrowed(text_draw),
6440 raster_rect,
6441 };
6442 }
6443
6444 let visible_top = ((visible_rect.y - logical_rect.y) / line_height).floor() as isize;
6445 let visible_bottom =
6446 ((visible_rect.y + visible_rect.height - logical_rect.y) / line_height).ceil() as isize;
6447 let start_line = visible_top.saturating_sub(1).max(0) as usize;
6448 let end_line = (visible_bottom + 1).max(start_line as isize + 1) as usize;
6449 let end_line = end_line.min(line_count);
6450 if start_line == 0 && end_line >= line_count {
6451 return TextRasterSource {
6452 draw: Cow::Borrowed(text_draw),
6453 raster_rect,
6454 };
6455 }
6456
6457 let byte_start = line_starts[start_line];
6458 let byte_end = line_end_offset(text_draw.text.text(), line_starts, end_line - 1);
6459 if byte_start >= byte_end {
6460 return TextRasterSource {
6461 draw: Cow::Borrowed(text_draw),
6462 raster_rect,
6463 };
6464 }
6465
6466 let slice_y = logical_rect.y + start_line as f32 * line_height;
6467 let slice_height = (end_line - start_line) as f32 * line_height;
6468 let mut slice_raster_rect = Rect {
6469 x: logical_rect.x * root_scale,
6470 y: slice_y * root_scale,
6471 width: logical_rect.width * root_scale,
6472 height: slice_height * root_scale,
6473 };
6474 slice_raster_rect.x = slice_raster_rect.x.round();
6475 slice_raster_rect.y = slice_raster_rect.y.round();
6476 slice_raster_rect.width = slice_raster_rect.width.ceil().max(1.0);
6477 slice_raster_rect.height = slice_raster_rect.height.ceil().max(1.0);
6478
6479 let mut sliced_draw = text_draw.clone();
6480 sliced_draw.rect = Rect {
6481 x: logical_rect.x,
6482 y: slice_y,
6483 width: logical_rect.width,
6484 height: slice_height,
6485 };
6486 sliced_draw.text = Arc::new(text_draw.text.subsequence(byte_start..byte_end));
6487
6488 TextRasterSource {
6489 draw: Cow::Owned(sliced_draw),
6490 raster_rect: slice_raster_rect,
6491 }
6492}
6493
6494fn line_start_offsets(text: &str) -> Vec<usize> {
6495 let mut starts =
6496 Vec::with_capacity(text.as_bytes().iter().filter(|b| **b == b'\n').count() + 1);
6497 starts.push(0);
6498 starts.extend(
6499 text.char_indices()
6500 .filter_map(|(index, ch)| (ch == '\n').then_some(index + ch.len_utf8())),
6501 );
6502 starts
6503}
6504
6505fn line_end_offset(text: &str, line_starts: &[usize], line: usize) -> usize {
6506 line_starts.get(line + 1).copied().unwrap_or(text.len())
6507}
6508
6509fn align_to(value: u32, alignment: u32) -> u32 {
6510 debug_assert!(alignment > 0);
6511 value.div_ceil(alignment) * alignment
6512}
6513
6514impl GpuRenderer {
6515 fn convert_surface_pixels_to_rgba(&self, pixels: &[u8]) -> Result<Vec<u8>, String> {
6516 if !pixels.len().is_multiple_of(4) {
6517 return Err("Screenshot readback has an incomplete pixel".to_string());
6518 }
6519 Ok(pixels.to_vec())
6520 }
6521}
6522
6523pub(crate) fn scissor_rect_for_rect(
6527 rect: Rect,
6528 root_scale: f32,
6529 viewport: ViewportUniformParams,
6530) -> Option<(u32, u32, u32, u32)> {
6531 let width = viewport.width as f32;
6532 let height = viewport.height as f32;
6533 let mut left = canonicalize_device_coordinate(rect.x * root_scale);
6534 let mut top = canonicalize_device_coordinate(rect.y * root_scale);
6535 let mut right = canonicalize_device_coordinate((rect.x + rect.width) * root_scale);
6536 let mut bottom = canonicalize_device_coordinate((rect.y + rect.height) * root_scale);
6537 if !viewport.transform.is_identity() {
6538 let bounds = viewport.transform.target_bounds(Rect {
6539 x: left,
6540 y: top,
6541 width: right - left,
6542 height: bottom - top,
6543 });
6544 (left, top) = (bounds.x, bounds.y);
6545 (right, bottom) = (bounds.x + bounds.width, bounds.y + bounds.height);
6546 }
6547 let left = (left - viewport.offset[0]).clamp(0.0, width).floor();
6548 let top = (top - viewport.offset[1]).clamp(0.0, height).floor();
6549 let right = (right - viewport.offset[0]).clamp(0.0, width).ceil();
6550 let bottom = (bottom - viewport.offset[1]).clamp(0.0, height).ceil();
6551 if right <= left || bottom <= top {
6552 return None;
6553 }
6554 Some((
6555 left as u32,
6556 top as u32,
6557 (right - left) as u32,
6558 (bottom - top) as u32,
6559 ))
6560}
6561
6562fn scissor_rect_for_layer(
6563 rect: Rect,
6564 clip: Option<Rect>,
6565 root_scale: f32,
6566 viewport: ViewportUniformParams,
6567) -> Option<(u32, u32, u32, u32)> {
6568 let clipped_rect = match clip {
6569 Some(clip_rect) => rect.intersect(clip_rect)?,
6570 None => rect,
6571 };
6572 scissor_rect_for_rect(clipped_rect, root_scale, viewport)
6573}
6574fn tint_for_image(
6575 color_filter: Option<ColorFilter>,
6576 alpha: f32,
6577) -> ([f32; 4], Option<ColorFilter>) {
6578 let alpha = alpha.clamp(0.0, 1.0);
6579 match color_filter {
6580 Some(filter) if filter.supports_gpu_vertex_modulation() => {
6581 let Some(tint) = filter.gpu_vertex_tint() else {
6582 return ([1.0, 1.0, 1.0, alpha], Some(filter));
6583 };
6584 (
6585 [
6586 tint[0].clamp(0.0, 1.0),
6587 tint[1].clamp(0.0, 1.0),
6588 tint[2].clamp(0.0, 1.0),
6589 (tint[3] * alpha).clamp(0.0, 1.0),
6590 ],
6591 None,
6592 )
6593 }
6594 Some(filter) => ([1.0, 1.0, 1.0, alpha], Some(filter)),
6595 None => ([1.0, 1.0, 1.0, alpha], None),
6596 }
6597}
6598
6599#[repr(C)]
6602#[derive(Clone, Copy, Debug, Pod, Zeroable)]
6603pub(crate) struct DeviceRoundedClip {
6604 rect: [f32; 4],
6605 radius: f32,
6606}
6607
6608impl DeviceRoundedClip {
6609 const ATTRIBS: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![
6610 4 => Float32x4,
6611 5 => Float32,
6612 ];
6613
6614 fn desc() -> wgpu::VertexBufferLayout<'static> {
6615 wgpu::VertexBufferLayout {
6616 array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
6617 step_mode: wgpu::VertexStepMode::Instance,
6618 attributes: &Self::ATTRIBS,
6619 }
6620 }
6621
6622 fn of(image: &ImageDraw, root_scale: f32) -> Option<Self> {
6625 let clip = image.clip.filter(|_| image.clip_radius > 0.0)?;
6626 let device = if image.snap_anchor.is_some() {
6627 crate::geometry::canonicalized_scaled_rect(clip, root_scale)
6628 } else {
6629 Rect {
6630 x: clip.x * root_scale,
6631 y: clip.y * root_scale,
6632 width: clip.width * root_scale,
6633 height: clip.height * root_scale,
6634 }
6635 };
6636 Some(Self {
6637 rect: [device.x, device.y, device.width, device.height],
6638 radius: image.clip_radius * root_scale,
6639 })
6640 }
6641}
6642
6643fn push_image_quad(
6646 (vertices, indices): (&mut Vec<Vertex>, &mut Vec<u32>),
6647 device_quad: [[f32; 2]; 4],
6648 color: [f32; 4],
6649 uv_rect: &ImageUvRect,
6650) -> u32 {
6651 let base_vertex = vertices.len() as u32;
6652 let index_start = indices.len() as u32;
6653 indices.extend_from_slice(&[
6654 base_vertex,
6655 base_vertex + 1,
6656 base_vertex + 2,
6657 base_vertex + 2,
6658 base_vertex + 1,
6659 base_vertex + 3,
6660 ]);
6661 let corners = [
6662 [uv_rect.min[0], uv_rect.min[1]],
6663 [uv_rect.max[0], uv_rect.min[1]],
6664 [uv_rect.min[0], uv_rect.max[1]],
6665 [uv_rect.max[0], uv_rect.max[1]],
6666 ];
6667 vertices.extend(
6668 device_quad
6669 .into_iter()
6670 .zip(corners)
6671 .map(|(position, uv)| Vertex {
6672 position,
6673 color,
6674 uv,
6675 uv_bounds: uv_rect.sample_bounds,
6676 }),
6677 );
6678 index_start
6679}
6680
6681fn image_uv_rect(image: &ImageBitmap, src_rect: Option<Rect>) -> Option<ImageUvRect> {
6682 let Some(src) = src_rect else {
6683 return Some(ImageUvRect {
6684 min: [0.0, 0.0],
6685 max: [1.0, 1.0],
6686 sample_bounds: [0.0, 0.0, 1.0, 1.0],
6687 });
6688 };
6689
6690 let (u_min, u_max, u_bound_min, u_bound_max) =
6691 source_axis_uv(src.x, src.width, image.width() as f32)?;
6692 let (v_min, v_max, v_bound_min, v_bound_max) =
6693 source_axis_uv(src.y, src.height, image.height() as f32)?;
6694
6695 Some(ImageUvRect {
6696 min: [u_min, v_min],
6697 max: [u_max, v_max],
6698 sample_bounds: [u_bound_min, v_bound_min, u_bound_max, v_bound_max],
6699 })
6700}
6701
6702fn glyph_atlas_uv_rect(entry: GlyphAtlasEntry, atlas_size: u32) -> ImageUvRect {
6703 let atlas_width = atlas_size as f32;
6704 let atlas_height = atlas_size as f32;
6705 let min = [entry.x as f32 / atlas_width, entry.y as f32 / atlas_height];
6706 let max = [
6707 (entry.x + entry.width) as f32 / atlas_width,
6708 (entry.y + entry.height) as f32 / atlas_height,
6709 ];
6710 let center_min = [
6711 (entry.x as f32 + 0.5) / atlas_width,
6712 (entry.y as f32 + 0.5) / atlas_height,
6713 ];
6714 let center_max = [
6715 (entry.x as f32 + entry.width as f32 - 0.5).max(entry.x as f32 + 0.5) / atlas_width,
6716 (entry.y as f32 + entry.height as f32 - 0.5).max(entry.y as f32 + 0.5) / atlas_height,
6717 ];
6718 ImageUvRect {
6719 min,
6720 max,
6721 sample_bounds: [center_min[0], center_min[1], center_max[0], center_max[1]],
6722 }
6723}
6724
6725#[derive(Clone, Copy)]
6726pub(crate) struct ResolvedImageGeometry {
6727 pub(crate) rect: Rect,
6728 pub(crate) clip: Option<Rect>,
6729 pub(crate) sampling: ImageSampling,
6730 quad: [[f32; 2]; 4],
6731 snap_anchored: bool,
6732}
6733
6734pub(crate) fn resolve_image_geometry(image: &ImageDraw, root_scale: f32) -> ResolvedImageGeometry {
6735 let snap_delta = image
6736 .snap_anchor
6737 .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
6738 .unwrap_or_default();
6739 resolve_image_geometry_with_delta(image, root_scale, snap_delta)
6740}
6741
6742fn resolve_image_geometry_with_delta(
6743 image: &ImageDraw,
6744 root_scale: f32,
6745 snap_delta: Point,
6746) -> ResolvedImageGeometry {
6747 let mut rect = image.rect.translate(snap_delta.x, snap_delta.y);
6748 let mut quad = translate_quad(image.quad, snap_delta);
6749 snap_nearest_image_to_device_pixels(image.sampling, &mut rect, &mut quad, root_scale);
6750 ResolvedImageGeometry {
6751 rect,
6752 clip: image.clip,
6753 sampling: image.sampling,
6754 quad,
6755 snap_anchored: image.snap_anchor.is_some(),
6756 }
6757}
6758
6759impl ResolvedImageGeometry {
6760 pub(crate) fn device_quad(self, root_scale: f32) -> [[f32; 2]; 4] {
6761 nearest_image_device_quad(self.sampling, self.quad, root_scale).unwrap_or_else(|| {
6762 if self.snap_anchored {
6763 canonicalized_scaled_quad(self.quad, root_scale)
6764 } else {
6765 scaled_quad(self.quad, root_scale)
6766 }
6767 })
6768 }
6769}
6770
6771fn snap_nearest_image_to_device_pixels(
6772 sampling: ImageSampling,
6773 rect: &mut Rect,
6774 quad: &mut [[f32; 2]; 4],
6775 root_scale: f32,
6776) {
6777 if sampling != ImageSampling::Nearest || !root_scale.is_finite() || root_scale <= 0.0 {
6778 return;
6779 }
6780
6781 let Some(quad_rect) = axis_aligned_quad_rect(*quad) else {
6782 return;
6783 };
6784
6785 let left_px = (quad_rect.x * root_scale).round();
6786 let top_px = (quad_rect.y * root_scale).round();
6787 let width_px = (quad_rect.width * root_scale).round().max(1.0);
6788 let height_px = (quad_rect.height * root_scale).round().max(1.0);
6789 let snapped = Rect {
6790 x: left_px / root_scale,
6791 y: top_px / root_scale,
6792 width: width_px / root_scale,
6793 height: height_px / root_scale,
6794 };
6795
6796 *rect = snapped;
6797 *quad = crate::rect_to_quad(snapped);
6798}
6799
6800fn nearest_image_device_quad(
6801 sampling: ImageSampling,
6802 quad: [[f32; 2]; 4],
6803 root_scale: f32,
6804) -> Option<[[f32; 2]; 4]> {
6805 if sampling != ImageSampling::Nearest || !root_scale.is_finite() || root_scale <= 0.0 {
6806 return None;
6807 }
6808
6809 let rect = axis_aligned_quad_rect(quad)?;
6810 let left_px = (rect.x * root_scale).round();
6811 let top_px = (rect.y * root_scale).round();
6812 let width_px = (rect.width * root_scale).round().max(1.0);
6813 let height_px = (rect.height * root_scale).round().max(1.0);
6814 let right_px = left_px + width_px;
6815 let bottom_px = top_px + height_px;
6816 Some([
6817 [left_px, top_px],
6818 [right_px, top_px],
6819 [left_px, bottom_px],
6820 [right_px, bottom_px],
6821 ])
6822}
6823
6824fn source_axis_uv(start: f32, extent: f32, image_extent: f32) -> Option<(f32, f32, f32, f32)> {
6825 if !start.is_finite()
6826 || !extent.is_finite()
6827 || !image_extent.is_finite()
6828 || extent == 0.0
6829 || image_extent <= 0.0
6830 {
6831 return None;
6832 }
6833
6834 let end = start + extent;
6835 let edge_min = start.min(end).clamp(0.0, image_extent);
6836 let edge_max = start.max(end).clamp(0.0, image_extent);
6837 if edge_max <= edge_min {
6838 return None;
6839 }
6840
6841 let center_min = edge_min + 0.5;
6842 let center_max = edge_max - 0.5;
6843 let (bound_min, bound_max) = if center_min <= center_max {
6844 (center_min, center_max)
6845 } else {
6846 let center = (edge_min + edge_max) * 0.5;
6847 (center, center)
6848 };
6849
6850 Some((
6851 edge_min / image_extent,
6852 edge_max / image_extent,
6853 bound_min / image_extent,
6854 bound_max / image_extent,
6855 ))
6856}
6857
6858fn apply_filter_to_bitmap(image: &ImageBitmap, filter: ColorFilter) -> Result<ImageBitmap, String> {
6859 let pixel_count = image.width() as usize * image.height() as usize;
6860 let mut filtered = Vec::with_capacity(pixel_count * 4);
6861 for index in 0..pixel_count {
6862 let pixel = image.rgba8_pixel(index);
6863 let rgba = [
6864 pixel[0] as f32 / 255.0,
6865 pixel[1] as f32 / 255.0,
6866 pixel[2] as f32 / 255.0,
6867 pixel[3] as f32 / 255.0,
6868 ];
6869 let out = filter.apply_rgba(rgba);
6870 filtered.push((out[0].clamp(0.0, 1.0) * 255.0).round() as u8);
6871 filtered.push((out[1].clamp(0.0, 1.0) * 255.0).round() as u8);
6872 filtered.push((out[2].clamp(0.0, 1.0) * 255.0).round() as u8);
6873 filtered.push((out[3].clamp(0.0, 1.0) * 255.0).round() as u8);
6874 }
6875 ImageBitmap::from_rgba8(image.width(), image.height(), filtered)
6876 .map_err(|error| format!("failed to build filtered bitmap: {error}"))
6877}
6878
6879fn sampling_under(sampling: ImageSampling, transform: SegmentTransform) -> ImageSampling {
6883 if transform.is_identity() {
6884 sampling
6885 } else {
6886 ImageSampling::Linear
6887 }
6888}
6889
6890pub(crate) fn shadow_composite_mask(
6894 shadow: &ShadowDraw,
6895 snap_anchor: Option<SnapAnchor>,
6896 root_scale: f32,
6897) -> Option<RoundedCompositeMask> {
6898 inner_shadow_composite_mask(shadow, root_scale).or_else(|| {
6899 shadow.rounded_clip.map(|clip| RoundedCompositeMask {
6900 rect: mask_rect(anchored_device_rect(clip.rect, snap_anchor, root_scale)),
6901 radii: clip.radii.map(|radius| radius * root_scale),
6902 })
6903 })
6904}
6905
6906fn shadow_scene(
6910 shapes: Option<&RunDraw>,
6911 texts: &[TextDraw],
6912 input_margin: f32,
6913) -> CompositorScene {
6914 let mut scene = CompositorScene::new();
6915 if let Some(run) = shapes {
6916 scene.push_run(run.clone());
6917 }
6918 for text in texts {
6919 let z_index = scene.next_z();
6920 scene.draw_ops.push(DrawOp {
6921 z_index,
6922 kind: DrawOpKind::Text(scene.texts.len()),
6923 });
6924 let mut source_text = text.clone();
6925 source_text.clip = source_text
6926 .clip
6927 .map(|clip| expand_rect(clip, input_margin, input_margin));
6928 scene.texts.push(source_text);
6929 scene.next_z += 1;
6930 }
6931 scene
6932}
6933
6934fn device_pixel_bounds(
6937 rect: Rect,
6938 root_scale: f32,
6939 max_texture_dim: u32,
6940) -> Option<DevicePixelBounds> {
6941 let x = (rect.x * root_scale).floor();
6942 let y = (rect.y * root_scale).floor();
6943 let right = ((rect.x + rect.width) * root_scale).ceil();
6944 let bottom = ((rect.y + rect.height) * root_scale).ceil();
6945 let width = (right - x).max(0.0) as u32;
6946 let height = (bottom - y).max(0.0) as u32;
6947 if width == 0 || height == 0 || width > max_texture_dim || height > max_texture_dim {
6948 return None;
6949 }
6950 Some(DevicePixelBounds {
6951 x,
6952 y,
6953 width,
6954 height,
6955 })
6956}
6957fn inner_shadow_composite_mask(
6958 shadow: &ShadowDraw,
6959 root_scale: f32,
6960) -> Option<RoundedCompositeMask> {
6961 let run = shadow.shapes.as_ref()?;
6962 if !run
6963 .tables()
6964 .shapes
6965 .iter()
6966 .any(|record| record.blend_mode() == BlendMode::DstOut)
6967 {
6968 return None;
6969 }
6970 let fill = run.tables().shapes.get(0)?;
6971 let rect = run.placement.translated_bounds(fill.stored_rect());
6972 if rect.width <= 0.0 || rect.height <= 0.0 {
6973 return None;
6974 }
6975 let resolved =
6976 cranpose_ui_graphics::RoundedCornerShape::with_radii(cranpose_ui_graphics::CornerRadii {
6977 top_left: fill.radii[0],
6978 top_right: fill.radii[1],
6979 bottom_right: fill.radii[2],
6980 bottom_left: fill.radii[3],
6981 })
6982 .resolve(rect.width, rect.height);
6983 let radii = [
6984 resolved.top_left * root_scale,
6985 resolved.top_right * root_scale,
6986 resolved.bottom_left * root_scale,
6987 resolved.bottom_right * root_scale,
6988 ];
6989
6990 Some(RoundedCompositeMask {
6991 rect: mask_rect(anchored_device_rect(
6992 rect,
6993 run.placement.snap_anchor,
6994 root_scale,
6995 )),
6996 radii,
6997 })
6998}
6999
7000#[derive(Clone, Debug, PartialEq, Eq)]
7003pub(crate) struct PlannedRunDraw {
7004 pub(crate) key: ShapePipelineKey,
7005 pub(crate) band_class: u8,
7006 pub(crate) indices: std::ops::Range<u32>,
7007 pub(crate) records: std::ops::Range<u32>,
7008}
7009
7010impl PlannedRunDraw {
7011 fn paint(draw: &RunDrawCall) -> Self {
7013 Self {
7014 key: draw.key,
7015 band_class: draw.band_class,
7016 indices: draw.indices(),
7017 records: draw.records.clone(),
7018 }
7019 }
7020}
7021
7022pub(crate) fn interior_run_draws(draws: &[RunDrawCall]) -> SmallVec<[PlannedRunDraw; 4]> {
7030 struct Stretch {
7031 key: ShapePipelineKey,
7032 start: u32,
7033 span: Option<PlannedRunDraw>,
7034 }
7035 let mut planned: SmallVec<[PlannedRunDraw; 4]> = SmallVec::new();
7036 let mut stretch: Option<Stretch> = None;
7037 for draw in draws.iter().rev() {
7038 let Some(key) = draw.key.interior() else {
7039 planned.extend(stretch.take().and_then(|open| open.span));
7040 continue;
7041 };
7042 if stretch
7043 .as_ref()
7044 .is_some_and(|open| open.key != key || open.start != draw.records.end)
7045 {
7046 planned.extend(stretch.take().and_then(|open| open.span));
7047 }
7048 let open = stretch.get_or_insert(Stretch {
7049 key,
7050 start: draw.records.end,
7051 span: None,
7052 });
7053 open.start = draw.records.start;
7054 if !draw.occluders {
7055 continue;
7056 }
7057 match &mut open.span {
7058 Some(span) => span.records.start = draw.records.start,
7059 None => {
7060 open.span = Some(PlannedRunDraw {
7061 key,
7062 band_class: draw.band_class,
7063 indices: 0..cranpose_ui_graphics::strip_indices(1),
7064 records: draw.records.clone(),
7065 });
7066 }
7067 }
7068 }
7069 planned.extend(stretch.and_then(|open| open.span));
7070 planned
7071}
7072
7073fn evict_idle<K: Clone + Eq + std::hash::Hash, V>(
7077 cache: &mut BoundedLruCache<K, V>,
7078 frame: u64,
7079 last_frame: impl Fn(&V) -> u64,
7080) {
7081 while cache.peek_lru().is_some_and(|(_, value)| {
7082 frame.saturating_sub(last_frame(value)) > TEXT_GLYPH_RUN_IDLE_FRAMES
7083 }) {
7084 cache.pop_lru();
7085 }
7086}
7087
7088fn window_draws(draws: &mut SmallVec<[RunDrawCall; 8]>, window: &std::ops::Range<u32>) {
7089 let mut relative = 0u32;
7090 draws.retain(|draw| {
7091 let count = draw.records.end - draw.records.start;
7092 let first = relative;
7093 relative += count;
7094 let keep_start = window.start.max(first).min(first + count);
7095 let keep_end = window.end.min(first + count).max(keep_start);
7096 draw.records =
7097 draw.records.start + (keep_start - first)..draw.records.start + (keep_end - first);
7098 draw.records.start < draw.records.end
7099 });
7100}
7101
7102#[cfg(test)]
7103#[path = "tests/render_text_bounds_tests.rs"]
7104mod text_bounds_tests;
7105
7106#[cfg(test)]
7107#[path = "tests/render_retained_glyph_tests.rs"]
7108mod retained_glyph_tests;
7109
7110#[cfg(test)]
7111#[path = "tests/frame_clear_tests.rs"]
7112mod frame_clear_tests;
7113
7114#[cfg(test)]
7115#[path = "tests/render_clip_scissor_tests.rs"]
7116mod clip_scissor_tests;
7117
7118#[cfg(test)]
7119#[path = "tests/glyph_kind_tests.rs"]
7120mod glyph_kind_tests;
7121
7122#[cfg(test)]
7123#[path = "tests/glyph_run_bounds_tests.rs"]
7124mod glyph_run_bounds_tests;
7125
7126#[cfg(test)]
7127#[path = "tests/shape_variant_tests.rs"]
7128mod shape_variant_tests;