Skip to main content

sui_render_wgpu/
lib.rs

1#![deny(unsafe_code)]
2#![allow(clippy::too_many_arguments)]
3
4mod feathering;
5mod gpu;
6mod retained;
7mod scene;
8mod text;
9
10use std::{
11    collections::{HashMap, HashSet, hash_map::Entry},
12    fmt,
13    hash::{DefaultHasher, Hash, Hasher},
14    sync::{
15        Arc, Condvar, Mutex,
16        atomic::{AtomicU64, Ordering},
17    },
18    time::Duration,
19};
20
21use bytemuck::{Pod, Zeroable};
22use half::f16;
23use lyon_path::{Path as LyonPath, builder::PathBuilder as LyonPathBuilder, math::point};
24use lyon_tessellation::{
25    BuffersBuilder, FillOptions, FillTessellator, FillVertex, FillVertexConstructor, StrokeVertex,
26    StrokeVertexConstructor, VertexBuffers,
27};
28use sui_core::{
29    Color, ColorSpace, Error, ImageHandle, Path as ScenePath, PathElement, Point, Rect, Result,
30    Size, Transform, Vector, WindowId,
31};
32pub use sui_scene::TextSubpixelOrder;
33use sui_scene::{
34    Brush, ImageSampling, RegisteredExternalImage, RegisteredImage, RegisteredImageFormat, Scene,
35    SceneCommand, SceneFrame, SceneLayer, SceneLayerId, SceneLayerUpdateKind, StrokeStyle,
36    TextRenderCoveragePolicy, TextRenderHinting, TextRenderPolicy, TextRenderStemDarkening,
37};
38use sui_text::{
39    FontRegistry, ResolvedTextFace, ShapedGlyph as SceneShapedGlyph, ShapedText, TextLayout,
40    TextLayoutCacheSnapshot, TextRun, TextStyle, TextSystem,
41};
42use swash::{
43    FontRef as SwashFontRef,
44    scale::{
45        Render as SwashRender, ScaleContext as SwashScaleContext, Source as SwashSource,
46        StrikeWith as SwashStrikeWith, image::Content as SwashImageContent,
47    },
48    zeno::Format as SwashFormat,
49};
50#[cfg(test)]
51use tiny_skia::PathBuilder as TinySkiaPathBuilder;
52use web_time::Instant;
53use wgpu::util::DeviceExt;
54use winit::window::Window;
55
56use gpu::*;
57use retained::*;
58use scene::*;
59use text::*;
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct RendererCapabilities {
63    pub supports_color_management: bool,
64    pub supports_offscreen_surfaces: bool,
65}
66
67impl Default for RendererCapabilities {
68    fn default() -> Self {
69        Self {
70            supports_color_management: true,
71            supports_offscreen_surfaces: true,
72        }
73    }
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
77pub enum DisplayColorPrimaries {
78    #[default]
79    Srgb,
80    DisplayP3,
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
84pub enum DynamicRangeMode {
85    #[default]
86    StandardDynamicRange,
87    HighDynamicRange,
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
91pub enum DisplayTransferFunction {
92    #[default]
93    Srgb,
94    LinearExtended,
95    Pq,
96    Hlg,
97}
98
99#[derive(Debug, Clone, PartialEq)]
100pub struct DisplayCapabilities {
101    pub supports_wide_gamut: bool,
102    pub supports_hdr: bool,
103    pub preferred_primaries: DisplayColorPrimaries,
104    pub preferred_dynamic_range: DynamicRangeMode,
105    pub max_luminance_nits: Option<f32>,
106    pub sdr_white_nits: Option<f32>,
107    pub max_content_headroom: Option<f32>,
108    pub native_hdr_presentation_supported: bool,
109    pub notes: String,
110}
111
112impl Default for DisplayCapabilities {
113    fn default() -> Self {
114        Self {
115            supports_wide_gamut: false,
116            supports_hdr: false,
117            preferred_primaries: DisplayColorPrimaries::Srgb,
118            preferred_dynamic_range: DynamicRangeMode::StandardDynamicRange,
119            max_luminance_nits: None,
120            sdr_white_nits: None,
121            max_content_headroom: None,
122            native_hdr_presentation_supported: false,
123            notes: "Default SDR capability profile".to_string(),
124        }
125    }
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
129pub enum RequestedOutputColorPrimaries {
130    #[default]
131    Automatic,
132    Srgb,
133    DisplayP3,
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
137pub enum RequestedDynamicRangeMode {
138    #[default]
139    Automatic,
140    StandardDynamicRange,
141    HighDynamicRange,
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
145pub enum RequestedColorManagementMode {
146    #[default]
147    Automatic,
148    ForceSdr,
149    PreferWideGamut,
150    PreferHdr,
151}
152
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
154pub enum RequestedToneMappingMode {
155    #[default]
156    Automatic,
157    Clamp,
158    Reinhard,
159}
160
161pub const DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS: f32 = 203.0;
162const SCRGB_REFERENCE_WHITE_NITS: f32 = 80.0;
163
164#[derive(Debug, Clone, Copy, PartialEq)]
165pub struct ColorManagementMode {
166    pub mode: RequestedColorManagementMode,
167    pub output_primaries: RequestedOutputColorPrimaries,
168    pub dynamic_range: RequestedDynamicRangeMode,
169    pub tone_mapping: RequestedToneMappingMode,
170    pub sdr_content_brightness_nits: f32,
171}
172
173impl Default for ColorManagementMode {
174    fn default() -> Self {
175        Self {
176            mode: RequestedColorManagementMode::Automatic,
177            output_primaries: RequestedOutputColorPrimaries::Automatic,
178            dynamic_range: RequestedDynamicRangeMode::Automatic,
179            tone_mapping: RequestedToneMappingMode::Automatic,
180            sdr_content_brightness_nits: DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS,
181        }
182    }
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub enum OutputStrategy {
187    SdrSurface {
188        format: wgpu::TextureFormat,
189    },
190    WideGamutSurface {
191        format: wgpu::TextureFormat,
192        primaries: DisplayColorPrimaries,
193    },
194    HdrNativeSurface {
195        format: wgpu::TextureFormat,
196        primaries: DisplayColorPrimaries,
197        transfer: DisplayTransferFunction,
198    },
199    /// Debug/offscreen-only path for inspecting HDR scene values on SDR outputs.
200    ///
201    /// Normal presentation should choose native HDR when the environment can present
202    /// HDR end-to-end; otherwise it should render SDR instead of tone mapping HDR.
203    HdrIntermediateThenToneMap {
204        intermediate_format: wgpu::TextureFormat,
205        surface_format: wgpu::TextureFormat,
206        primaries: DisplayColorPrimaries,
207    },
208}
209
210impl OutputStrategy {
211    pub const fn surface_format(self) -> wgpu::TextureFormat {
212        match self {
213            Self::SdrSurface { format }
214            | Self::WideGamutSurface { format, .. }
215            | Self::HdrNativeSurface { format, .. } => format,
216            Self::HdrIntermediateThenToneMap { surface_format, .. } => surface_format,
217        }
218    }
219}
220
221#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
222pub enum DebugCaptureStage {
223    HdrIntermediate,
224    #[default]
225    FinalComposed,
226}
227
228impl DebugCaptureStage {
229    pub const fn is_hdr_capable(self) -> bool {
230        matches!(self, Self::HdrIntermediate)
231    }
232
233    pub const fn uses_hdr_intermediate(self) -> bool {
234        matches!(self, Self::HdrIntermediate)
235    }
236}
237
238#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
239pub enum DebugSdrVisualization {
240    #[default]
241    ToneMappedColor,
242    LuminanceHeatmap,
243    HeadroomHeatmap,
244    ClipMask,
245}
246
247#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
248pub enum DebugCaptureEncoding {
249    Exr,
250    #[default]
251    Png,
252}
253
254#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
255pub struct DebugCaptureRequest {
256    pub stage: DebugCaptureStage,
257    pub encoding: DebugCaptureEncoding,
258    pub sdr_visualization: DebugSdrVisualization,
259}
260
261#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
262pub struct RendererInterop {
263    pub raw_wgpu_enabled: bool,
264}
265
266/// Cloneable access to the renderer-owned WGPU device and queue.
267///
268/// The handles refer to the exact device used by SUI. Applications can use
269/// them to populate textures or run conversion passes, then register the
270/// resulting sampled texture through [`WgpuExternalTextureRegistry`].
271#[derive(Debug, Clone)]
272pub struct WgpuExternalTextureContext {
273    device: wgpu::Device,
274    queue: wgpu::Queue,
275}
276
277impl WgpuExternalTextureContext {
278    pub fn device(&self) -> &wgpu::Device {
279        &self.device
280    }
281
282    pub fn queue(&self) -> &wgpu::Queue {
283        &self.queue
284    }
285}
286
287#[derive(Debug, Clone)]
288struct WgpuExternalTextureEntry {
289    texture: wgpu::Texture,
290    view: wgpu::TextureView,
291    descriptor: RegisteredExternalImage,
292    binding_revision: u64,
293    content_revision: Option<u64>,
294}
295
296#[derive(Default)]
297struct WgpuExternalTextureRegistryInner {
298    context: Mutex<Option<WgpuExternalTextureContext>>,
299    context_ready: Condvar,
300    textures: Mutex<HashMap<ImageHandle, WgpuExternalTextureEntry>>,
301    next_binding_revision: AtomicU64,
302}
303
304/// Shared registry for app-owned textures sampled by SUI's normal image draw
305/// path.
306///
307/// This contract is intentionally media-agnostic. The application owns the
308/// producer, update cadence, pixel conversion, and texture contents. SUI owns
309/// only the renderer device handoff and sampled-texture lifetime needed to
310/// compose the resource with ordinary scene transforms and clips.
311#[derive(Clone, Default)]
312pub struct WgpuExternalTextureRegistry {
313    inner: Arc<WgpuExternalTextureRegistryInner>,
314}
315
316impl fmt::Debug for WgpuExternalTextureRegistry {
317    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
318        formatter
319            .debug_struct("WgpuExternalTextureRegistry")
320            .field("attached", &self.context().is_some())
321            .field("len", &self.len())
322            .finish()
323    }
324}
325
326impl WgpuExternalTextureRegistry {
327    pub fn new() -> Self {
328        Self::default()
329    }
330
331    /// Returns the renderer device once the first render target initializes.
332    pub fn context(&self) -> Option<WgpuExternalTextureContext> {
333        self.inner
334            .context
335            .lock()
336            .unwrap_or_else(|poisoned| poisoned.into_inner())
337            .clone()
338    }
339
340    /// Wait for renderer initialization without tying the registry to a
341    /// platform event-loop type.
342    pub fn wait_for_context(&self, timeout: Duration) -> Option<WgpuExternalTextureContext> {
343        let context = self
344            .inner
345            .context
346            .lock()
347            .unwrap_or_else(|poisoned| poisoned.into_inner());
348        let (context, _) = self
349            .inner
350            .context_ready
351            .wait_timeout_while(context, timeout, |context| context.is_none())
352            .unwrap_or_else(|poisoned| poisoned.into_inner());
353        context.clone()
354    }
355
356    /// Upload tightly packed sRGB RGBA8 pixels into a persistent texture.
357    /// Reusing `handle` and dimensions updates the existing allocation.
358    pub fn upload_rgba8(
359        &self,
360        handle: ImageHandle,
361        width: u32,
362        height: u32,
363        pixels: Arc<[u8]>,
364        revision: u64,
365    ) -> Result<RegisteredExternalImage> {
366        let context = self.context().ok_or_else(|| {
367            Error::new("external texture registry is not attached to an initialized renderer")
368        })?;
369        let descriptor = RegisteredExternalImage::new(width, height)?;
370        let row_bytes = width
371            .checked_mul(4)
372            .ok_or_else(|| Error::new("external RGBA8 image row size overflow"))?;
373        let expected_len = row_bytes
374            .checked_mul(height)
375            .map(|len| len as usize)
376            .ok_or_else(|| Error::new("external RGBA8 image byte size overflow"))?;
377        if pixels.len() != expected_len {
378            return Err(Error::new(format!(
379                "external RGBA8 image data length {} does not match expected size {} for a {}x{} image",
380                pixels.len(),
381                expected_len,
382                width,
383                height
384            )));
385        }
386
387        let mut textures = self
388            .inner
389            .textures
390            .lock()
391            .unwrap_or_else(|poisoned| poisoned.into_inner());
392        let reusable = textures.get_mut(&handle).filter(|entry| {
393            entry.descriptor == descriptor
394                && entry.texture.format() == wgpu::TextureFormat::Rgba8UnormSrgb
395                && entry
396                    .texture
397                    .usage()
398                    .contains(wgpu::TextureUsages::COPY_DST)
399        });
400        if let Some(entry) = reusable {
401            if entry.content_revision == Some(revision) {
402                return Ok(entry.descriptor);
403            }
404            Self::write_rgba8(&context.queue, &entry.texture, width, height, &pixels);
405            entry.content_revision = Some(revision);
406            return Ok(entry.descriptor);
407        }
408
409        let texture = context.device.create_texture(&wgpu::TextureDescriptor {
410            label: Some("SUI external RGBA8 texture"),
411            size: wgpu::Extent3d {
412                width,
413                height,
414                depth_or_array_layers: 1,
415            },
416            mip_level_count: 1,
417            sample_count: 1,
418            dimension: wgpu::TextureDimension::D2,
419            format: wgpu::TextureFormat::Rgba8UnormSrgb,
420            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
421            view_formats: &[],
422        });
423        Self::write_rgba8(&context.queue, &texture, width, height, &pixels);
424        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
425        let binding_revision = self.next_binding_revision();
426        textures.insert(
427            handle,
428            WgpuExternalTextureEntry {
429                texture,
430                view,
431                descriptor,
432                binding_revision,
433                content_revision: Some(revision),
434            },
435        );
436        Ok(descriptor)
437    }
438
439    /// Register a sampled texture created from this registry's renderer
440    /// context. This supports app-owned GPU conversion/render passes without
441    /// exposing backend-native shared-handle policy in SUI.
442    pub fn register_texture(
443        &self,
444        handle: ImageHandle,
445        texture: wgpu::Texture,
446    ) -> Result<RegisteredExternalImage> {
447        let context = self.context().ok_or_else(|| {
448            Error::new("external texture registry is not attached to an initialized renderer")
449        })?;
450        if texture.dimension() != wgpu::TextureDimension::D2
451            || texture.depth_or_array_layers() != 1
452            || texture.sample_count() != 1
453        {
454            return Err(Error::new(
455                "external texture must be a single-sampled two-dimensional texture",
456            ));
457        }
458        if !texture
459            .usage()
460            .contains(wgpu::TextureUsages::TEXTURE_BINDING)
461        {
462            return Err(Error::new(
463                "external texture must include TEXTURE_BINDING usage",
464            ));
465        }
466        if texture.format().sample_type(
467            Some(wgpu::TextureAspect::All),
468            Some(context.device.features()),
469        ) != Some(wgpu::TextureSampleType::Float { filterable: true })
470        {
471            return Err(Error::new(
472                "external texture format must support filterable float sampling",
473            ));
474        }
475
476        let descriptor = RegisteredExternalImage::new(texture.width(), texture.height())?;
477        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
478        let entry = WgpuExternalTextureEntry {
479            texture,
480            view,
481            descriptor,
482            binding_revision: self.next_binding_revision(),
483            content_revision: None,
484        };
485        self.inner
486            .textures
487            .lock()
488            .unwrap_or_else(|poisoned| poisoned.into_inner())
489            .insert(handle, entry);
490        Ok(descriptor)
491    }
492
493    pub fn unregister(&self, handle: ImageHandle) -> bool {
494        self.inner
495            .textures
496            .lock()
497            .unwrap_or_else(|poisoned| poisoned.into_inner())
498            .remove(&handle)
499            .is_some()
500    }
501
502    pub fn contains(&self, handle: ImageHandle) -> bool {
503        self.inner
504            .textures
505            .lock()
506            .unwrap_or_else(|poisoned| poisoned.into_inner())
507            .contains_key(&handle)
508    }
509
510    pub fn len(&self) -> usize {
511        self.inner
512            .textures
513            .lock()
514            .unwrap_or_else(|poisoned| poisoned.into_inner())
515            .len()
516    }
517
518    pub fn is_empty(&self) -> bool {
519        self.len() == 0
520    }
521
522    fn attach(&self, device: wgpu::Device, queue: wgpu::Queue) {
523        let mut context = self
524            .inner
525            .context
526            .lock()
527            .unwrap_or_else(|poisoned| poisoned.into_inner());
528        if context.is_none() {
529            *context = Some(WgpuExternalTextureContext { device, queue });
530            self.inner.context_ready.notify_all();
531        }
532    }
533
534    fn resolve(&self, handle: ImageHandle) -> Option<WgpuExternalTextureEntry> {
535        self.inner
536            .textures
537            .lock()
538            .unwrap_or_else(|poisoned| poisoned.into_inner())
539            .get(&handle)
540            .cloned()
541    }
542
543    fn next_binding_revision(&self) -> u64 {
544        self.inner
545            .next_binding_revision
546            .fetch_add(1, Ordering::Relaxed)
547            .wrapping_add(1)
548    }
549
550    fn write_rgba8(
551        queue: &wgpu::Queue,
552        texture: &wgpu::Texture,
553        width: u32,
554        height: u32,
555        pixels: &[u8],
556    ) {
557        queue.write_texture(
558            wgpu::TexelCopyTextureInfo {
559                texture,
560                mip_level: 0,
561                origin: wgpu::Origin3d::ZERO,
562                aspect: wgpu::TextureAspect::All,
563            },
564            pixels,
565            wgpu::TexelCopyBufferLayout {
566                offset: 0,
567                bytes_per_row: Some(width * 4),
568                rows_per_image: Some(height),
569            },
570            wgpu::Extent3d {
571                width,
572                height,
573                depth_or_array_layers: 1,
574            },
575        );
576    }
577}
578
579#[derive(Debug, Clone, Copy, PartialEq)]
580pub struct FeatheringOptions {
581    pub enabled: bool,
582    pub width: f32,
583}
584
585impl FeatheringOptions {
586    pub const fn new(enabled: bool, width: f32) -> Self {
587        Self { enabled, width }
588    }
589
590    pub fn clamped(self) -> Self {
591        Self {
592            enabled: self.enabled,
593            width: self.width.max(0.0),
594        }
595    }
596
597    pub fn effective_width(self) -> f32 {
598        if self.enabled {
599            self.width.max(0.0)
600        } else {
601            0.0
602        }
603    }
604}
605
606#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
607pub enum TextRenderMode {
608    #[default]
609    Grayscale,
610    LcdSubpixel,
611}
612
613#[derive(Debug, Clone, Copy, PartialEq)]
614pub enum TextHinting {
615    None,
616    Slight { max_ppem: f32 },
617}
618
619const DEFAULT_TEXT_HINTING_MAX_PPEM: f32 = 96.0;
620
621impl Default for TextHinting {
622    fn default() -> Self {
623        Self::Slight {
624            max_ppem: DEFAULT_TEXT_HINTING_MAX_PPEM,
625        }
626    }
627}
628
629impl TextHinting {
630    pub fn normalized(self) -> Self {
631        match self {
632            Self::None => Self::None,
633            Self::Slight { max_ppem } if max_ppem.is_finite() && max_ppem > 0.0 => {
634                Self::Slight { max_ppem }
635            }
636            Self::Slight { .. } => Self::None,
637        }
638    }
639
640    pub fn should_hint(self, ppem: f32) -> bool {
641        match self.normalized() {
642            Self::None => false,
643            Self::Slight { max_ppem } => ppem.is_finite() && ppem <= max_ppem,
644        }
645    }
646}
647
648#[derive(Debug, Clone, Copy, PartialEq, Default)]
649pub enum StemDarkening {
650    #[default]
651    None,
652    Enabled {
653        max_ppem: f32,
654        amount: f32,
655    },
656}
657
658impl StemDarkening {
659    pub fn normalized(self) -> Self {
660        match self {
661            Self::None => Self::None,
662            Self::Enabled { max_ppem, amount }
663                if max_ppem.is_finite() && max_ppem > 0.0 && amount.is_finite() && amount > 0.0 =>
664            {
665                Self::Enabled {
666                    max_ppem,
667                    amount: amount.clamp(0.0, 1.0),
668                }
669            }
670            Self::Enabled { .. } => Self::None,
671        }
672    }
673
674    pub fn effective_amount(self, ppem: f32) -> f32 {
675        match self.normalized() {
676            Self::None => 0.0,
677            Self::Enabled { max_ppem, amount } if ppem.is_finite() && ppem <= max_ppem => amount,
678            Self::Enabled { .. } => 0.0,
679        }
680    }
681}
682
683#[derive(Debug, Clone, Copy, PartialEq, Default)]
684pub enum TextCoveragePolicy {
685    #[default]
686    Perceptual,
687    Linear,
688    Gamma(f32),
689    CoverageBoost(f32),
690    TwoCoverageMinusCoverageSq,
691}
692
693impl TextCoveragePolicy {
694    pub fn normalized(self) -> Self {
695        match self {
696            Self::Perceptual => Self::Perceptual,
697            Self::Linear => Self::Linear,
698            Self::Gamma(gamma) if gamma.is_finite() && gamma > 0.0 => Self::Gamma(gamma),
699            Self::Gamma(_) => Self::Linear,
700            Self::CoverageBoost(amount) if amount.is_finite() && amount > 0.0 => {
701                Self::CoverageBoost(amount.clamp(0.0, 1.0))
702            }
703            Self::CoverageBoost(_) => Self::Linear,
704            Self::TwoCoverageMinusCoverageSq => Self::TwoCoverageMinusCoverageSq,
705        }
706    }
707
708    pub fn resolved_for_text_color(self, color: Color) -> Self {
709        match self.normalized() {
710            Self::Perceptual => Self::CoverageBoost(perceptual_text_coverage_boost(color)),
711            policy => policy,
712        }
713    }
714
715    pub fn apply(self, coverage: f32) -> f32 {
716        let coverage = coverage.clamp(0.0, 1.0);
717        match self.normalized() {
718            Self::Perceptual => {
719                apply_coverage_boost(coverage, perceptual_text_coverage_boost(Color::BLACK))
720            }
721            Self::Linear => coverage,
722            Self::Gamma(gamma) => coverage.powf(gamma),
723            Self::CoverageBoost(amount) => apply_coverage_boost(coverage, amount),
724            Self::TwoCoverageMinusCoverageSq => (2.0 * coverage) - (coverage * coverage),
725        }
726    }
727}
728
729fn perceptual_text_coverage_boost(color: Color) -> f32 {
730    let luminance = encoded_srgb_luminance(color);
731    (1.0 - luminance).clamp(0.45, 0.92)
732}
733
734fn apply_coverage_boost(coverage: f32, amount: f32) -> f32 {
735    coverage + (coverage * (1.0 - coverage) * amount.clamp(0.0, 1.0))
736}
737
738fn encoded_srgb_luminance(color: Color) -> f32 {
739    let linear = color.to_linear_srgb();
740    let red = linear_srgb_to_encoded_unit(linear.red);
741    let green = linear_srgb_to_encoded_unit(linear.green);
742    let blue = linear_srgb_to_encoded_unit(linear.blue);
743    ((0.2126 * red) + (0.7152 * green) + (0.0722 * blue)).clamp(0.0, 1.0)
744}
745
746fn linear_srgb_to_encoded_unit(channel: f32) -> f32 {
747    let value = channel.clamp(0.0, 1.0);
748    if value <= 0.003_130_8 {
749        value * 12.92
750    } else {
751        (1.055 * value.powf(1.0 / 2.4)) - 0.055
752    }
753}
754
755#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
756pub struct GlyphCacheSnapshot {
757    pub entries: usize,
758    pub hits: usize,
759    pub misses: usize,
760}
761
762impl GlyphCacheSnapshot {
763    pub const fn requests(self) -> usize {
764        self.hits + self.misses
765    }
766
767    pub fn hit_rate(self) -> f64 {
768        let requests = self.requests();
769        if requests == 0 {
770            0.0
771        } else {
772            self.hits as f64 / requests as f64
773        }
774    }
775}
776
777#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
778pub struct RendererTextCacheSnapshot {
779    pub layout: TextLayoutCacheSnapshot,
780    pub glyph: GlyphCacheSnapshot,
781    pub path: GlyphCacheSnapshot,
782}
783
784#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
785struct TextFrameStats {
786    glyph_instances: usize,
787    glyph_upload_bytes: u64,
788    atlas_miss_count: usize,
789    atlas_miss_time_us: u64,
790}
791
792const TEXT_ATLAS_WIDTH: usize = 2048;
793const TEXT_ATLAS_HEIGHT: usize = 2048;
794const TEXT_ATLAS_PADDING: usize = 2;
795/// Maximum number of atlas pages (texture-array layers) before whole-page LRU eviction kicks in.
796/// Each page is TEXT_ATLAS_WIDTH x TEXT_ATLAS_HEIGHT x 4 bytes (~16 MB); 4 pages -> ~64 MB.
797const TEXT_ATLAS_MAX_PAGES: usize = 4;
798
799#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
800pub struct RetainedPacketRebuildStats {
801    pub new_count: usize,
802    pub coordinate_space_count: usize,
803    pub signature_count: usize,
804    pub scene_count: usize,
805    pub state_count: usize,
806}
807
808#[derive(Debug, Clone, Copy, PartialEq, Eq)]
809enum PacketRebuildReason {
810    NewPacket,
811    CoordinateSpace,
812    Signature,
813    Scene,
814    State,
815}
816
817impl RetainedPacketRebuildStats {
818    pub const fn new(
819        new_count: usize,
820        coordinate_space_count: usize,
821        signature_count: usize,
822        scene_count: usize,
823        state_count: usize,
824    ) -> Self {
825        Self {
826            new_count,
827            coordinate_space_count,
828            signature_count,
829            scene_count,
830            state_count,
831        }
832    }
833
834    fn record_reason(&mut self, reason: PacketRebuildReason) {
835        match reason {
836            PacketRebuildReason::NewPacket => self.new_count += 1,
837            PacketRebuildReason::CoordinateSpace => self.coordinate_space_count += 1,
838            PacketRebuildReason::Signature => self.signature_count += 1,
839            PacketRebuildReason::Scene => self.scene_count += 1,
840            PacketRebuildReason::State => self.state_count += 1,
841        }
842    }
843
844    pub const fn total_count(&self) -> usize {
845        self.new_count
846            + self.coordinate_space_count
847            + self.signature_count
848            + self.scene_count
849            + self.state_count
850    }
851}
852
853#[derive(Debug, Clone, PartialEq, Eq, Default)]
854pub struct RendererFrameStats {
855    pub pass_count: usize,
856    pub draw_count: usize,
857    pub uploaded_vertex_bytes: u64,
858    pub text_glyph_instance_count: usize,
859    pub text_vertex_bytes: u64,
860    pub visible_layer_count: usize,
861    pub direct_packet_count: usize,
862    pub retained_state_update_time_us: u64,
863    pub composition_time_us: u64,
864    pub retained_scene_traversal_time_us: u64,
865    pub retained_packet_build_time_us: u64,
866    pub retained_packet_build_count: usize,
867    pub retained_packet_rebuilds: RetainedPacketRebuildStats,
868    pub retained_packet_normalize_time_us: u64,
869    pub retained_packet_signature_time_us: u64,
870    pub retained_packet_raster_state_init_time_us: u64,
871    pub retained_packet_scene_build_time_us: u64,
872    pub retained_packet_command_count: usize,
873    pub retained_packet_text_command_count: usize,
874    pub retained_packet_path_command_count: usize,
875    pub retained_packet_clip_path_command_count: usize,
876    pub retained_packet_image_command_count: usize,
877    pub retained_packet_rect_command_count: usize,
878    pub retained_packet_text_command_time_us: u64,
879    pub retained_packet_path_command_time_us: u64,
880    pub retained_packet_clip_path_command_time_us: u64,
881    pub retained_packet_image_command_time_us: u64,
882    pub retained_packet_rect_command_time_us: u64,
883    pub text_atlas_miss_count: usize,
884    pub text_atlas_miss_time_us: u64,
885    pub surface_acquire_time_us: u64,
886    pub resource_collection_time_us: u64,
887    pub bind_group_prepare_time_us: u64,
888    pub image_bind_group_time_us: u64,
889    pub analytic_path_bind_group_time_us: u64,
890    pub analytic_path_bind_group_miss_count: usize,
891    pub analytic_path_bind_group_upload_bytes: u64,
892    pub text_atlas_bind_group_time_us: u64,
893    pub text_atlas_upload_copy_time_us: u64,
894    pub text_atlas_upload_write_time_us: u64,
895    pub text_atlas_upload_bytes: u64,
896    pub batch_prepare_time_us: u64,
897    pub gpu_upload_time_us: u64,
898    pub pass_encode_time_us: u64,
899    pub queue_submit_time_us: u64,
900    pub surface_present_time_us: u64,
901    pub retained_packet_hotspot: Option<RendererPacketHotspot>,
902}
903
904#[derive(Debug, Clone, PartialEq, Eq)]
905pub struct RendererPacketHotspot {
906    pub container_layer_id: Option<u64>,
907    pub owner_widget_id: Option<u64>,
908    pub segment_index: u32,
909    pub total_time_us: u64,
910    pub scene_build_time_us: u64,
911    pub command_count: usize,
912    pub text_command_count: usize,
913    pub path_command_count: usize,
914    pub rect_command_count: usize,
915    pub text_command_time_us: u64,
916    pub path_command_time_us: u64,
917    pub rect_command_time_us: u64,
918    pub text_sample: Option<String>,
919}
920
921impl RendererFrameStats {
922    #[cfg(test)]
923    fn from_prepared_frame(prepared: &PreparedFrameBatches) -> Self {
924        Self::from_prepared_counts(
925            prepared.passes.len().max(1),
926            prepared
927                .passes
928                .iter()
929                .map(|pass| pass.clip_paths.len() + pass.draws.len())
930                .sum(),
931            (prepared.scene_vertices.len() as u64 + prepared.clip_vertices.len() as u64)
932                * VERTEX_SIZE
933                + prepared.text_instances.len() as u64 * TEXT_ATLAS_INSTANCE_SIZE,
934        )
935    }
936
937    fn from_prepared_counts(
938        pass_count: usize,
939        draw_count: usize,
940        uploaded_vertex_bytes: u64,
941    ) -> Self {
942        Self {
943            pass_count,
944            draw_count,
945            uploaded_vertex_bytes,
946            text_glyph_instance_count: 0,
947            text_vertex_bytes: 0,
948            visible_layer_count: 0,
949            direct_packet_count: 0,
950            retained_state_update_time_us: 0,
951            composition_time_us: 0,
952            retained_scene_traversal_time_us: 0,
953            retained_packet_build_time_us: 0,
954            retained_packet_build_count: 0,
955            retained_packet_rebuilds: RetainedPacketRebuildStats::default(),
956            retained_packet_normalize_time_us: 0,
957            retained_packet_signature_time_us: 0,
958            retained_packet_raster_state_init_time_us: 0,
959            retained_packet_scene_build_time_us: 0,
960            retained_packet_command_count: 0,
961            retained_packet_text_command_count: 0,
962            retained_packet_path_command_count: 0,
963            retained_packet_clip_path_command_count: 0,
964            retained_packet_image_command_count: 0,
965            retained_packet_rect_command_count: 0,
966            retained_packet_text_command_time_us: 0,
967            retained_packet_path_command_time_us: 0,
968            retained_packet_clip_path_command_time_us: 0,
969            retained_packet_image_command_time_us: 0,
970            retained_packet_rect_command_time_us: 0,
971            text_atlas_miss_count: 0,
972            text_atlas_miss_time_us: 0,
973            surface_acquire_time_us: 0,
974            resource_collection_time_us: 0,
975            bind_group_prepare_time_us: 0,
976            image_bind_group_time_us: 0,
977            analytic_path_bind_group_time_us: 0,
978            analytic_path_bind_group_miss_count: 0,
979            analytic_path_bind_group_upload_bytes: 0,
980            text_atlas_bind_group_time_us: 0,
981            text_atlas_upload_copy_time_us: 0,
982            text_atlas_upload_write_time_us: 0,
983            text_atlas_upload_bytes: 0,
984            batch_prepare_time_us: 0,
985            gpu_upload_time_us: 0,
986            pass_encode_time_us: 0,
987            queue_submit_time_us: 0,
988            surface_present_time_us: 0,
989            retained_packet_hotspot: None,
990        }
991    }
992
993    fn with_compositor_stats(mut self, stats: RetainedCompositorFrameStats) -> Self {
994        self.visible_layer_count = stats.visible_layers;
995        self.direct_packet_count = stats.direct_packets;
996        self.retained_state_update_time_us = (stats.state_update_time_ms * 1000.0).round() as u64;
997        self.composition_time_us = (stats.composition_time_ms * 1000.0).round() as u64;
998        self.retained_scene_traversal_time_us =
999            (stats.scene_traversal_time_ms * 1000.0).round() as u64;
1000        self.retained_packet_build_time_us = (stats.packet_build_time_ms * 1000.0).round() as u64;
1001        self.retained_packet_build_count = stats.packet_build_count;
1002        self.retained_packet_rebuilds = stats.packet_rebuilds;
1003        self.retained_packet_normalize_time_us =
1004            (stats.packet_normalize_time_ms * 1000.0).round() as u64;
1005        self.retained_packet_signature_time_us =
1006            (stats.packet_signature_time_ms * 1000.0).round() as u64;
1007        self.retained_packet_raster_state_init_time_us =
1008            (stats.packet_raster_state_init_time_ms * 1000.0).round() as u64;
1009        self.retained_packet_scene_build_time_us =
1010            (stats.packet_scene_build_time_ms * 1000.0).round() as u64;
1011        self.retained_packet_command_count = stats.packet_command_count;
1012        self.retained_packet_text_command_count = stats.packet_text_command_count;
1013        self.retained_packet_path_command_count = stats.packet_path_command_count;
1014        self.retained_packet_clip_path_command_count = stats.packet_clip_path_command_count;
1015        self.retained_packet_image_command_count = stats.packet_image_command_count;
1016        self.retained_packet_rect_command_count = stats.packet_rect_command_count;
1017        self.retained_packet_text_command_time_us =
1018            (stats.packet_text_command_time_ms * 1000.0).round() as u64;
1019        self.retained_packet_path_command_time_us =
1020            (stats.packet_path_command_time_ms * 1000.0).round() as u64;
1021        self.retained_packet_clip_path_command_time_us =
1022            (stats.packet_clip_path_command_time_ms * 1000.0).round() as u64;
1023        self.retained_packet_image_command_time_us =
1024            (stats.packet_image_command_time_ms * 1000.0).round() as u64;
1025        self.retained_packet_rect_command_time_us =
1026            (stats.packet_rect_command_time_ms * 1000.0).round() as u64;
1027        self.retained_packet_hotspot =
1028            stats
1029                .slowest_packet_build
1030                .map(|hotspot| RendererPacketHotspot {
1031                    container_layer_id: hotspot.container_layer_id,
1032                    owner_widget_id: hotspot.owner_widget_id,
1033                    segment_index: hotspot.segment_index,
1034                    total_time_us: (hotspot.total_time_ms * 1000.0).round() as u64,
1035                    scene_build_time_us: (hotspot.scene_build_time_ms * 1000.0).round() as u64,
1036                    command_count: hotspot.command_count,
1037                    text_command_count: hotspot.text_command_count,
1038                    path_command_count: hotspot.path_command_count,
1039                    rect_command_count: hotspot.rect_command_count,
1040                    text_command_time_us: (hotspot.text_command_time_ms * 1000.0).round() as u64,
1041                    path_command_time_us: (hotspot.path_command_time_ms * 1000.0).round() as u64,
1042                    rect_command_time_us: (hotspot.rect_command_time_ms * 1000.0).round() as u64,
1043                    text_sample: hotspot.text_sample,
1044                });
1045        self
1046    }
1047
1048    fn with_text_stats(mut self, stats: TextFrameStats) -> Self {
1049        self.text_glyph_instance_count = stats.glyph_instances;
1050        self.text_vertex_bytes = stats.glyph_upload_bytes;
1051        self.text_atlas_miss_count = stats.atlas_miss_count;
1052        self.text_atlas_miss_time_us = stats.atlas_miss_time_us;
1053        self
1054    }
1055}
1056
1057pub struct WgpuRenderer {
1058    instance: wgpu::Instance,
1059    feathering_enabled: bool,
1060    feather_width: f32,
1061    text_render_mode: TextRenderMode,
1062    text_subpixel_order: TextSubpixelOrder,
1063    text_hinting: TextHinting,
1064    stem_darkening: StemDarkening,
1065    text_coverage_policy: TextCoveragePolicy,
1066    vsync_enabled: bool,
1067    runtime_feathering_override: Option<FeatheringOptions>,
1068    runtime_text_subpixel_order_override: Option<TextSubpixelOrder>,
1069    runtime_text_hinting_override: Option<TextHinting>,
1070    runtime_stem_darkening_override: Option<StemDarkening>,
1071    runtime_text_coverage_policy_override: Option<TextCoveragePolicy>,
1072    runtime_diagnostics_enabled: bool,
1073    frames_rendered: usize,
1074    capabilities: RendererCapabilities,
1075    last_frames: HashMap<WindowId, SceneFrame>,
1076    last_frame_stats: HashMap<WindowId, RendererFrameStats>,
1077    shared: Option<SharedRenderer>,
1078    text_engine: Option<TextEngine>,
1079    image_cache: HashMap<ImageTextureCacheKey, CachedImageTexture>,
1080    external_texture_registry: Option<WgpuExternalTextureRegistry>,
1081    external_image_cache: HashMap<ImageHandle, CachedExternalTextureBindGroup>,
1082    text_atlas_array: Option<CachedTextAtlasTexture>,
1083    analytic_path_cache: HashMap<u64, CachedAnalyticPathGpu>,
1084    compositors: HashMap<WindowId, RetainedCompositorState>,
1085    surfaces: HashMap<WindowId, SurfaceState>,
1086    offscreen_targets: HashMap<WindowId, OffscreenTarget>,
1087    intermediate_targets: HashMap<WindowId, OffscreenTarget>,
1088    frame_resources: FrameResources,
1089}
1090
1091#[derive(Default)]
1092struct FrameResources {
1093    stencil: Option<StencilTarget>,
1094    analytic_path_arena: AnalyticPathArena,
1095}
1096
1097#[derive(Default)]
1098struct AnalyticPathArena {
1099    bind_group: Option<wgpu::BindGroup>,
1100    meta_buffer: Option<wgpu::Buffer>,
1101    contour_buffer: Option<wgpu::Buffer>,
1102    point_buffer: Option<wgpu::Buffer>,
1103    meta_capacity: usize,
1104    contour_capacity: usize,
1105    point_capacity: usize,
1106    used_slots: usize,
1107    used_contours: usize,
1108    used_points: usize,
1109}
1110
1111struct StencilTarget {
1112    texture: wgpu::Texture,
1113    view: wgpu::TextureView,
1114    size: (u32, u32),
1115}
1116
1117#[derive(Debug, Clone, PartialEq, Eq)]
1118pub struct RgbaImage {
1119    width: u32,
1120    height: u32,
1121    pixels: Vec<u8>,
1122}
1123
1124#[derive(Debug, Clone, PartialEq)]
1125pub struct HdrRgbaImage {
1126    width: u32,
1127    height: u32,
1128    pixels: Vec<f32>,
1129}
1130
1131#[derive(Debug, Clone, PartialEq)]
1132pub enum DebugCaptureArtifact {
1133    SdrRgba8(RgbaImage),
1134    HdrLinearRgbaF32(HdrRgbaImage),
1135}
1136
1137#[repr(C)]
1138#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
1139struct OutputTransformUniform {
1140    tone_mapping_mode: u32,
1141    encode_srgb: u32,
1142    output_primaries: u32,
1143    _padding0: u32,
1144    sdr_content_scale: f32,
1145    _padding1: [u32; 3],
1146}
1147
1148impl OutputTransformUniform {
1149    const fn new(
1150        tone_mapping_mode: u32,
1151        encode_srgb: bool,
1152        output_primaries: DisplayColorPrimaries,
1153        sdr_content_scale: f32,
1154    ) -> Self {
1155        Self {
1156            tone_mapping_mode,
1157            encode_srgb: encode_srgb as u32,
1158            output_primaries: match output_primaries {
1159                DisplayColorPrimaries::Srgb => 0,
1160                DisplayColorPrimaries::DisplayP3 => 1,
1161            },
1162            _padding0: 0,
1163            sdr_content_scale,
1164            _padding1: [0; 3],
1165        }
1166    }
1167}
1168
1169impl RgbaImage {
1170    pub fn new(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self> {
1171        let expected_len = width as usize * height as usize * 4;
1172        if pixels.len() != expected_len {
1173            return Err(Error::new(format!(
1174                "RGBA image pixel buffer length {} does not match {}x{} image size",
1175                pixels.len(),
1176                width,
1177                height
1178            )));
1179        }
1180
1181        Ok(Self {
1182            width,
1183            height,
1184            pixels,
1185        })
1186    }
1187
1188    pub const fn width(&self) -> u32 {
1189        self.width
1190    }
1191
1192    pub const fn height(&self) -> u32 {
1193        self.height
1194    }
1195
1196    pub fn pixels(&self) -> &[u8] {
1197        &self.pixels
1198    }
1199
1200    pub fn into_pixels(self) -> Vec<u8> {
1201        self.pixels
1202    }
1203}
1204
1205impl HdrRgbaImage {
1206    pub fn new(width: u32, height: u32, pixels: Vec<f32>) -> Result<Self> {
1207        let expected_len = width as usize * height as usize * 4;
1208        if pixels.len() != expected_len {
1209            return Err(Error::new(format!(
1210                "HDR RGBA image pixel buffer length {} does not match {}x{} image size",
1211                pixels.len(),
1212                width,
1213                height
1214            )));
1215        }
1216
1217        Ok(Self {
1218            width,
1219            height,
1220            pixels,
1221        })
1222    }
1223
1224    pub const fn width(&self) -> u32 {
1225        self.width
1226    }
1227
1228    pub const fn height(&self) -> u32 {
1229        self.height
1230    }
1231
1232    pub fn pixels(&self) -> &[f32] {
1233        &self.pixels
1234    }
1235
1236    pub fn into_pixels(self) -> Vec<f32> {
1237        self.pixels
1238    }
1239}
1240
1241const STENCIL_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24PlusStencil8;
1242const DEFAULT_FEATHER_WIDTH: f32 = 0.0;
1243
1244struct ImageMipLevel {
1245    width: u32,
1246    height: u32,
1247    pixels: Vec<u8>,
1248}
1249
1250fn image_mip_level_count(width: u32, height: u32) -> u32 {
1251    width.max(height).max(1).ilog2() + 1
1252}
1253
1254fn image_mip_chain(image: &RegisteredImage, mipmapped: bool) -> Vec<ImageMipLevel> {
1255    let mut levels = vec![ImageMipLevel {
1256        width: image.width(),
1257        height: image.height(),
1258        pixels: image.bytes().to_vec(),
1259    }];
1260    if !mipmapped {
1261        return levels;
1262    }
1263
1264    while let Some(previous) = levels.last() {
1265        if previous.width == 1 && previous.height == 1 {
1266            break;
1267        }
1268        levels.push(downsample_rgba8_srgb(previous));
1269    }
1270    levels
1271}
1272
1273fn downsample_rgba8_srgb(source: &ImageMipLevel) -> ImageMipLevel {
1274    let width = (source.width / 2).max(1);
1275    let height = (source.height / 2).max(1);
1276    let mut pixels = vec![0; width as usize * height as usize * 4];
1277
1278    for y in 0..height {
1279        for x in 0..width {
1280            let mut premultiplied = [0.0f32; 3];
1281            let mut alpha_sum = 0.0f32;
1282            let mut sample_count = 0.0f32;
1283            let source_y_start = y * source.height / height;
1284            let source_y_end = ((y + 1) * source.height / height).max(source_y_start + 1);
1285            let source_x_start = x * source.width / width;
1286            let source_x_end = ((x + 1) * source.width / width).max(source_x_start + 1);
1287            for source_y in source_y_start..source_y_end {
1288                for source_x in source_x_start..source_x_end {
1289                    let offset = ((source_y * source.width + source_x) * 4) as usize;
1290                    let alpha = source.pixels[offset + 3] as f32 / 255.0;
1291                    for (channel, premultiplied_channel) in premultiplied.iter_mut().enumerate() {
1292                        *premultiplied_channel +=
1293                            srgb_u8_to_linear(source.pixels[offset + channel]) * alpha;
1294                    }
1295                    alpha_sum += alpha;
1296                    sample_count += 1.0;
1297                }
1298            }
1299
1300            let output = ((y * width + x) * 4) as usize;
1301            let alpha = alpha_sum / sample_count.max(1.0);
1302            if alpha_sum > f32::EPSILON {
1303                for (channel, premultiplied_channel) in premultiplied.iter().enumerate() {
1304                    pixels[output + channel] =
1305                        linear_to_srgb_u8(*premultiplied_channel / alpha_sum);
1306                }
1307            }
1308            pixels[output + 3] = (alpha * 255.0).round().clamp(0.0, 255.0) as u8;
1309        }
1310    }
1311
1312    ImageMipLevel {
1313        width,
1314        height,
1315        pixels,
1316    }
1317}
1318
1319fn srgb_u8_to_linear(value: u8) -> f32 {
1320    let value = value as f32 / 255.0;
1321    if value <= 0.04045 {
1322        value / 12.92
1323    } else {
1324        ((value + 0.055) / 1.055).powf(2.4)
1325    }
1326}
1327
1328fn linear_to_srgb_u8(value: f32) -> u8 {
1329    let value = value.clamp(0.0, 1.0);
1330    let encoded = if value <= 0.003_130_8 {
1331        value * 12.92
1332    } else {
1333        1.055 * value.powf(1.0 / 2.4) - 0.055
1334    };
1335    (encoded * 255.0).round().clamp(0.0, 255.0) as u8
1336}
1337
1338/// Bind group layout for the multi-page glyph atlas: a filtering sampler plus a
1339/// `texture_2d_array` (one layer per atlas page). Distinct from the image layout, which is `D2`.
1340fn create_text_atlas_array_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
1341    device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1342        label: Some("SUI text atlas array bind group layout"),
1343        entries: &[
1344            wgpu::BindGroupLayoutEntry {
1345                binding: 0,
1346                visibility: wgpu::ShaderStages::FRAGMENT,
1347                ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
1348                count: None,
1349            },
1350            wgpu::BindGroupLayoutEntry {
1351                binding: 1,
1352                visibility: wgpu::ShaderStages::FRAGMENT,
1353                ty: wgpu::BindingType::Texture {
1354                    sample_type: wgpu::TextureSampleType::Float { filterable: true },
1355                    view_dimension: wgpu::TextureViewDimension::D2Array,
1356                    multisampled: false,
1357                },
1358                count: None,
1359            },
1360        ],
1361    })
1362}
1363
1364fn strip_padded_readback_rows(
1365    mapped: &[u8],
1366    bytes_per_row: usize,
1367    padded_bytes_per_row: usize,
1368    rows: usize,
1369) -> Vec<u8> {
1370    let mut tightly_packed = Vec::with_capacity(bytes_per_row * rows);
1371    for row in 0..rows {
1372        let start = row * padded_bytes_per_row;
1373        tightly_packed.extend_from_slice(&mapped[start..start + bytes_per_row]);
1374    }
1375    tightly_packed
1376}
1377
1378fn decode_rgba16f_pixels(raw: &[u8]) -> Vec<f32> {
1379    let mut pixels = Vec::with_capacity(raw.len() / 2);
1380    for chunk in raw.chunks_exact(2) {
1381        pixels.push(f16::from_bits(u16::from_le_bytes([chunk[0], chunk[1]])).to_f32());
1382    }
1383    pixels
1384}
1385
1386fn hdr_image_to_sdr_rgba(
1387    image: &HdrRgbaImage,
1388    visualization: DebugSdrVisualization,
1389    reference_white: f32,
1390    output_primaries: DisplayColorPrimaries,
1391) -> Result<RgbaImage> {
1392    let reference_white = if reference_white.is_finite() && reference_white > 0.0 {
1393        reference_white
1394    } else {
1395        1.0
1396    };
1397    let mut pixels = Vec::with_capacity((image.width() * image.height() * 4) as usize);
1398    for rgba in image.pixels().chunks_exact(4) {
1399        let normalized = linear_output_primaries_to_srgb(
1400            [
1401                rgba[0] / reference_white,
1402                rgba[1] / reference_white,
1403                rgba[2] / reference_white,
1404            ],
1405            output_primaries,
1406        );
1407        match visualization {
1408            DebugSdrVisualization::ToneMappedColor => {
1409                // Native HDR final targets store SDR white above 1.0. Divide that
1410                // headroom back out, convert the output primaries to linear sRGB,
1411                // then clamp during sRGB encoding. SDR-authored sRGB colors round
1412                // back to their original PNG bytes; HDR values overflow to white.
1413                pixels.extend_from_slice(&[
1414                    linear_to_srgb_capture_u8(normalized[0]),
1415                    linear_to_srgb_capture_u8(normalized[1]),
1416                    linear_to_srgb_capture_u8(normalized[2]),
1417                    linear_alpha_to_capture_u8(rgba[3]),
1418                ]);
1419            }
1420            DebugSdrVisualization::LuminanceHeatmap => {
1421                let luminance =
1422                    (normalized[0] * 0.2126 + normalized[1] * 0.7152 + normalized[2] * 0.0722)
1423                        .max(0.0);
1424                let normalized = (luminance / (1.0 + luminance)).clamp(0.0, 1.0);
1425                let value = (normalized * 255.0).round() as u8;
1426                pixels.extend_from_slice(&[value, value, value, 255]);
1427            }
1428            DebugSdrVisualization::HeadroomHeatmap => {
1429                let headroom = normalized[0].max(normalized[1]).max(normalized[2]).max(0.0);
1430                let normalized = (headroom / (1.0 + headroom)).clamp(0.0, 1.0);
1431                let red = (normalized * 255.0).round() as u8;
1432                let blue = ((1.0 - normalized) * 96.0).round() as u8;
1433                pixels.extend_from_slice(&[red, 32, blue, 255]);
1434            }
1435            DebugSdrVisualization::ClipMask => {
1436                let clipped = normalized[0].max(normalized[1]).max(normalized[2]) > 1.0;
1437                if clipped {
1438                    pixels.extend_from_slice(&[255, 64, 64, 255]);
1439                } else {
1440                    pixels.extend_from_slice(&[0, 0, 0, 255]);
1441                }
1442            }
1443        }
1444    }
1445    RgbaImage::new(image.width(), image.height(), pixels)
1446}
1447
1448fn linear_output_primaries_to_srgb(
1449    color: [f32; 3],
1450    output_primaries: DisplayColorPrimaries,
1451) -> [f32; 3] {
1452    match output_primaries {
1453        DisplayColorPrimaries::Srgb => color,
1454        DisplayColorPrimaries::DisplayP3 => {
1455            let det = (0.822_461_96 * 0.966_805_76) - (0.177_538_02 * 0.033_194_2);
1456            let red = (0.966_805_76 * color[0] - 0.177_538_02 * color[1]) / det;
1457            let green = (-0.033_194_2 * color[0] + 0.822_461_96 * color[1]) / det;
1458            let blue = (color[2] - (0.017_082_63 * red) - (0.072_397_43 * green)) / 0.910_519_96;
1459            [red, green, blue]
1460        }
1461    }
1462}
1463
1464fn encode_hdr_debug_artifact(
1465    image: HdrRgbaImage,
1466    request: DebugCaptureRequest,
1467    sdr_reference_white: f32,
1468    output_primaries: DisplayColorPrimaries,
1469) -> Result<DebugCaptureArtifact> {
1470    match request.encoding {
1471        DebugCaptureEncoding::Exr => Ok(DebugCaptureArtifact::HdrLinearRgbaF32(image)),
1472        DebugCaptureEncoding::Png => hdr_image_to_sdr_rgba(
1473            &image,
1474            request.sdr_visualization,
1475            sdr_reference_white,
1476            output_primaries,
1477        )
1478        .map(DebugCaptureArtifact::SdrRgba8),
1479    }
1480}
1481
1482fn linear_to_srgb_capture_u8(channel: f32) -> u8 {
1483    let value = channel.clamp(0.0, 1.0);
1484    let encoded = if value <= 0.003_130_8 {
1485        value * 12.92
1486    } else {
1487        (1.055 * value.powf(1.0 / 2.4)) - 0.055
1488    };
1489    (encoded.clamp(0.0, 1.0) * 255.0).round() as u8
1490}
1491
1492fn linear_alpha_to_capture_u8(alpha: f32) -> u8 {
1493    (alpha.clamp(0.0, 1.0) * 255.0).round() as u8
1494}
1495
1496fn optional_renderer_features(adapter: &wgpu::Adapter) -> wgpu::Features {
1497    let mut features = wgpu::Features::empty();
1498    if adapter
1499        .features()
1500        .contains(wgpu::Features::DUAL_SOURCE_BLENDING)
1501    {
1502        features |= wgpu::Features::DUAL_SOURCE_BLENDING;
1503    }
1504    features
1505}
1506
1507impl WgpuRenderer {
1508    pub fn new() -> Self {
1509        Self::default()
1510    }
1511
1512    pub fn with_feathering(mut self, feathering: FeatheringOptions) -> Self {
1513        self.set_feathering(feathering);
1514        self
1515    }
1516
1517    pub fn with_feathering_enabled(mut self, enabled: bool) -> Self {
1518        self.set_feathering_enabled(enabled);
1519        self
1520    }
1521
1522    pub fn with_text_coverage_policy(mut self, policy: TextCoveragePolicy) -> Self {
1523        self.set_text_coverage_policy(policy);
1524        self
1525    }
1526
1527    pub fn with_text_render_mode(mut self, mode: TextRenderMode) -> Self {
1528        self.set_text_render_mode(mode);
1529        self
1530    }
1531
1532    pub fn with_text_subpixel_order(mut self, order: TextSubpixelOrder) -> Self {
1533        self.set_text_subpixel_order(order);
1534        self
1535    }
1536
1537    pub fn with_text_hinting(mut self, hinting: TextHinting) -> Self {
1538        self.set_text_hinting(hinting);
1539        self
1540    }
1541
1542    pub fn with_stem_darkening(mut self, darkening: StemDarkening) -> Self {
1543        self.set_stem_darkening(darkening);
1544        self
1545    }
1546
1547    pub fn with_feather_width(mut self, feather_width: f32) -> Self {
1548        self.set_feather_width(feather_width);
1549        self
1550    }
1551
1552    pub fn with_vsync_enabled(mut self, enabled: bool) -> Self {
1553        self.set_vsync_enabled(enabled);
1554        self
1555    }
1556
1557    pub fn with_external_texture_registry(mut self, registry: WgpuExternalTextureRegistry) -> Self {
1558        self.set_external_texture_registry(registry);
1559        self
1560    }
1561
1562    pub fn feathering(&self) -> FeatheringOptions {
1563        FeatheringOptions::new(self.feathering_enabled, self.feather_width)
1564    }
1565
1566    pub fn feathering_enabled(&self) -> bool {
1567        self.feathering_enabled
1568    }
1569
1570    pub fn feather_width(&self) -> f32 {
1571        self.feather_width
1572    }
1573
1574    pub fn vsync_enabled(&self) -> bool {
1575        self.vsync_enabled
1576    }
1577
1578    pub fn external_texture_registry(&self) -> Option<&WgpuExternalTextureRegistry> {
1579        self.external_texture_registry.as_ref()
1580    }
1581
1582    pub fn set_external_texture_registry(&mut self, registry: WgpuExternalTextureRegistry) {
1583        if let Some(shared) = &self.shared {
1584            registry.attach(shared.device.clone(), shared.queue.clone());
1585        }
1586        self.external_texture_registry = Some(registry);
1587        self.external_image_cache.clear();
1588    }
1589
1590    pub fn text_coverage_policy(&self) -> TextCoveragePolicy {
1591        self.text_coverage_policy
1592    }
1593
1594    pub fn text_render_mode(&self) -> TextRenderMode {
1595        self.text_render_mode
1596    }
1597
1598    pub fn text_subpixel_order(&self) -> TextSubpixelOrder {
1599        self.text_subpixel_order
1600    }
1601
1602    pub fn text_hinting(&self) -> TextHinting {
1603        self.text_hinting
1604    }
1605
1606    pub fn stem_darkening(&self) -> StemDarkening {
1607        self.stem_darkening
1608    }
1609
1610    pub fn set_feathering(&mut self, feathering: FeatheringOptions) {
1611        let feathering = feathering.clamped();
1612        self.feathering_enabled = feathering.enabled;
1613        self.feather_width = feathering.width;
1614    }
1615
1616    pub fn set_feathering_enabled(&mut self, enabled: bool) {
1617        self.feathering_enabled = enabled;
1618    }
1619
1620    pub fn set_text_coverage_policy(&mut self, policy: TextCoveragePolicy) {
1621        let policy = policy.normalized();
1622        if self.text_coverage_policy == policy {
1623            return;
1624        }
1625
1626        self.text_coverage_policy = policy;
1627        if let Some(text_engine) = self.text_engine.as_mut() {
1628            text_engine.set_text_coverage_policy(policy);
1629        }
1630        self.invalidate_text_render_state();
1631    }
1632
1633    pub fn set_text_render_mode(&mut self, mode: TextRenderMode) {
1634        if self.text_render_mode == mode {
1635            return;
1636        }
1637
1638        self.text_render_mode = mode;
1639        if let Some(text_engine) = self.text_engine.as_mut() {
1640            text_engine.set_text_render_mode(mode);
1641        }
1642        self.invalidate_text_render_state();
1643    }
1644
1645    pub fn set_text_subpixel_order(&mut self, order: TextSubpixelOrder) {
1646        if self.text_subpixel_order == order {
1647            return;
1648        }
1649
1650        self.text_subpixel_order = order;
1651        if let Some(text_engine) = self.text_engine.as_mut() {
1652            text_engine.set_text_subpixel_order(order);
1653        }
1654        self.invalidate_text_render_state();
1655    }
1656
1657    pub fn set_text_hinting(&mut self, hinting: TextHinting) {
1658        let hinting = hinting.normalized();
1659        if self.text_hinting == hinting {
1660            return;
1661        }
1662
1663        self.text_hinting = hinting;
1664        if let Some(text_engine) = self.text_engine.as_mut() {
1665            text_engine.set_text_hinting(hinting);
1666        }
1667    }
1668
1669    pub fn set_stem_darkening(&mut self, darkening: StemDarkening) {
1670        let darkening = darkening.normalized();
1671        if self.stem_darkening == darkening {
1672            return;
1673        }
1674
1675        self.stem_darkening = darkening;
1676        if let Some(text_engine) = self.text_engine.as_mut() {
1677            text_engine.set_stem_darkening(darkening);
1678        }
1679    }
1680
1681    pub fn set_feather_width(&mut self, feather_width: f32) {
1682        self.feather_width = feather_width.max(0.0);
1683    }
1684
1685    pub fn set_vsync_enabled(&mut self, enabled: bool) {
1686        self.vsync_enabled = enabled;
1687    }
1688
1689    pub fn set_window_display_capabilities(
1690        &mut self,
1691        window_id: WindowId,
1692        capabilities: DisplayCapabilities,
1693    ) -> Result<()> {
1694        if let Some(surface) = self.surfaces.get_mut(&window_id) {
1695            if surface.display_capabilities == capabilities {
1696                return Ok(());
1697            }
1698            surface.display_capabilities = capabilities;
1699        }
1700        self.configure_existing_surface(window_id)
1701    }
1702
1703    pub fn window_display_capabilities(&self, window_id: WindowId) -> Option<DisplayCapabilities> {
1704        self.surfaces
1705            .get(&window_id)
1706            .map(|surface| surface.display_capabilities.clone())
1707    }
1708
1709    pub fn set_window_color_management(
1710        &mut self,
1711        window_id: WindowId,
1712        color_management: ColorManagementMode,
1713    ) -> Result<()> {
1714        if let Some(surface) = self.surfaces.get_mut(&window_id) {
1715            if surface.color_management == color_management {
1716                return Ok(());
1717            }
1718            surface.color_management = color_management;
1719        }
1720        self.configure_existing_surface(window_id)
1721    }
1722
1723    pub fn window_output_strategy(&self, window_id: WindowId) -> Option<OutputStrategy> {
1724        self.surfaces
1725            .get(&window_id)
1726            .map(|surface| surface.output_strategy)
1727    }
1728
1729    pub fn window_surface_formats(&self, window_id: WindowId) -> Option<Vec<wgpu::TextureFormat>> {
1730        self.surfaces
1731            .get(&window_id)
1732            .map(|surface| surface.available_surface_formats.clone())
1733    }
1734
1735    pub fn set_runtime_feathering_override(&mut self, feathering: Option<FeatheringOptions>) {
1736        self.runtime_feathering_override = feathering.map(FeatheringOptions::clamped);
1737    }
1738
1739    pub fn set_runtime_text_subpixel_order_override(&mut self, order: Option<TextSubpixelOrder>) {
1740        self.runtime_text_subpixel_order_override = order;
1741    }
1742
1743    pub fn set_runtime_text_hinting_override(&mut self, hinting: Option<TextHinting>) {
1744        self.runtime_text_hinting_override = hinting.map(TextHinting::normalized);
1745    }
1746
1747    pub fn set_runtime_stem_darkening_override(&mut self, darkening: Option<StemDarkening>) {
1748        self.runtime_stem_darkening_override = darkening.map(StemDarkening::normalized);
1749    }
1750
1751    pub fn set_runtime_text_coverage_policy_override(
1752        &mut self,
1753        policy: Option<TextCoveragePolicy>,
1754    ) {
1755        self.runtime_text_coverage_policy_override = policy.map(TextCoveragePolicy::normalized);
1756    }
1757
1758    pub fn set_runtime_diagnostics_enabled(&mut self, enabled: bool) {
1759        self.runtime_diagnostics_enabled = enabled;
1760        if let Some(text_engine) = self.text_engine.as_mut() {
1761            text_engine.set_diagnostics_enabled(enabled);
1762        }
1763        for compositor in self.compositors.values_mut() {
1764            compositor.set_diagnostics_enabled(enabled);
1765        }
1766    }
1767
1768    fn active_feather_width(&self) -> f32 {
1769        self.runtime_feathering_override
1770            .unwrap_or_else(|| self.feathering())
1771            .effective_width()
1772    }
1773
1774    fn active_text_hinting(&self) -> TextHinting {
1775        self.runtime_text_hinting_override
1776            .unwrap_or(self.text_hinting)
1777            .normalized()
1778    }
1779
1780    fn active_text_subpixel_order(&self) -> TextSubpixelOrder {
1781        self.runtime_text_subpixel_order_override
1782            .unwrap_or(self.text_subpixel_order)
1783    }
1784
1785    fn active_stem_darkening(&self) -> StemDarkening {
1786        self.runtime_stem_darkening_override
1787            .unwrap_or(self.stem_darkening)
1788            .normalized()
1789    }
1790
1791    fn active_text_coverage_policy(&self) -> TextCoveragePolicy {
1792        self.runtime_text_coverage_policy_override
1793            .unwrap_or(self.text_coverage_policy)
1794            .normalized()
1795    }
1796
1797    fn invalidate_text_render_state(&mut self) {
1798        self.text_engine = None;
1799        self.text_atlas_array = None;
1800        self.compositors.clear();
1801        self.last_frames.clear();
1802        self.last_frame_stats.clear();
1803    }
1804
1805    pub fn register_window(&mut self, window_id: WindowId, window: Arc<Window>) -> Result<()> {
1806        let physical_size = window.inner_size();
1807        let size = normalize_surface_size(physical_size.width, physical_size.height);
1808        let state = self.create_surface_state(window, size)?;
1809
1810        self.surfaces.insert(window_id, state);
1811        self.offscreen_targets.remove(&window_id);
1812        self.intermediate_targets.remove(&window_id);
1813        Ok(())
1814    }
1815
1816    pub fn remove_window(&mut self, window_id: WindowId) {
1817        self.surfaces.remove(&window_id);
1818        self.offscreen_targets.remove(&window_id);
1819        self.intermediate_targets.remove(&window_id);
1820        self.last_frames.remove(&window_id);
1821        self.last_frame_stats.remove(&window_id);
1822        self.compositors.remove(&window_id);
1823    }
1824
1825    pub fn render(&mut self, frame: &SceneFrame) -> Result<()> {
1826        let viewport = normalize_framebuffer_size(frame.surface_size);
1827        let mut frame_stats = RendererFrameStats::default();
1828
1829        if let Some(size) = viewport {
1830            if self.surfaces.contains_key(&frame.window_id) {
1831                frame_stats = self.render_surface(frame, size)?;
1832            } else {
1833                frame_stats = self.render_offscreen(frame, size)?;
1834            }
1835        }
1836
1837        self.frames_rendered += 1;
1838        self.last_frames.insert(frame.window_id, frame.clone());
1839        self.last_frame_stats.insert(frame.window_id, frame_stats);
1840        self.analytic_path_cache
1841            .retain(|_, entry| self.frames_rendered.saturating_sub(entry.last_used_frame) <= 120);
1842        self.image_cache
1843            .retain(|_, entry| self.frames_rendered.saturating_sub(entry.last_used_frame) <= 120);
1844        Ok(())
1845    }
1846
1847    pub fn capabilities(&self) -> RendererCapabilities {
1848        self.capabilities
1849    }
1850
1851    pub fn frames_rendered(&self) -> usize {
1852        self.frames_rendered
1853    }
1854
1855    pub fn last_frame(&self, window_id: WindowId) -> Option<&SceneFrame> {
1856        self.last_frames.get(&window_id)
1857    }
1858
1859    pub fn last_frame_stats(&self, window_id: WindowId) -> Option<RendererFrameStats> {
1860        self.last_frame_stats.get(&window_id).cloned()
1861    }
1862
1863    pub fn text_cache_snapshot(&self, window_id: WindowId) -> RendererTextCacheSnapshot {
1864        let mut snapshot = self
1865            .text_engine
1866            .as_ref()
1867            .map(TextEngine::cache_snapshot)
1868            .unwrap_or_default();
1869        snapshot.path = self
1870            .compositors
1871            .get(&window_id)
1872            .map(|compositor| compositor.path_cache.snapshot())
1873            .unwrap_or_default();
1874        snapshot
1875    }
1876
1877    pub fn capture_last_frame_rgba(&mut self, window_id: WindowId) -> Result<RgbaImage> {
1878        match self.capture_last_frame_debug(window_id, DebugCaptureRequest::default())? {
1879            DebugCaptureArtifact::SdrRgba8(image) => Ok(image),
1880            DebugCaptureArtifact::HdrLinearRgbaF32(_) => Err(Error::new(format!(
1881                "window {} returned an HDR debug artifact when SDR RGBA capture was requested",
1882                window_id.get()
1883            ))),
1884        }
1885    }
1886
1887    pub fn capture_last_frame_debug(
1888        &mut self,
1889        window_id: WindowId,
1890        request: DebugCaptureRequest,
1891    ) -> Result<DebugCaptureArtifact> {
1892        let frame = self.last_frames.get(&window_id).cloned().ok_or_else(|| {
1893            Error::new(format!(
1894                "window {} does not have a previously rendered frame available for capture",
1895                window_id.get()
1896            ))
1897        })?;
1898
1899        let size = normalize_framebuffer_size(frame.surface_size).ok_or_else(|| {
1900            Error::new(format!(
1901                "window {} last rendered frame has an invalid framebuffer size",
1902                window_id.get()
1903            ))
1904        })?;
1905
1906        self.render_debug_capture_stage(&frame, size, request)?;
1907        self.capture_debug_frame(window_id, request)
1908    }
1909
1910    pub fn capture_debug_frame(
1911        &self,
1912        window_id: WindowId,
1913        request: DebugCaptureRequest,
1914    ) -> Result<DebugCaptureArtifact> {
1915        match request.stage {
1916            DebugCaptureStage::FinalComposed => {
1917                self.capture_final_composed_debug_artifact(window_id, request)
1918            }
1919            DebugCaptureStage::HdrIntermediate => {
1920                let image = self.capture_hdr_intermediate_rgba_f32(window_id)?;
1921                encode_hdr_debug_artifact(image, request, 1.0, DisplayColorPrimaries::Srgb)
1922            }
1923        }
1924    }
1925
1926    pub fn capture_rgba(&self, window_id: WindowId) -> Result<RgbaImage> {
1927        let target = self.offscreen_targets.get(&window_id).ok_or_else(|| {
1928            Error::new(format!(
1929                "window {} does not have an offscreen render target available for screenshot capture",
1930                window_id.get()
1931            ))
1932        })?;
1933        let raw = self.readback_target_bytes(
1934            &target.texture,
1935            target.size,
1936            4,
1937            "SUI screenshot readback",
1938            "SUI screenshot readback encoder",
1939        )?;
1940
1941        let mut pixels = Vec::with_capacity((target.size.0 * target.size.1 * 4) as usize);
1942        for chunk in raw.chunks_exact(4) {
1943            pixels.extend_from_slice(&[chunk[2], chunk[1], chunk[0], chunk[3]]);
1944        }
1945
1946        RgbaImage::new(target.size.0, target.size.1, pixels)
1947    }
1948
1949    pub fn capture_hdr_intermediate_rgba_f32(&self, window_id: WindowId) -> Result<HdrRgbaImage> {
1950        let target = self.intermediate_targets.get(&window_id).ok_or_else(|| {
1951            Error::new(format!(
1952                "window {} does not have an HDR intermediate target available for debug capture",
1953                window_id.get()
1954            ))
1955        })?;
1956        let raw = self.readback_target_bytes(
1957            &target.texture,
1958            target.size,
1959            8,
1960            "SUI HDR intermediate readback",
1961            "SUI HDR intermediate readback encoder",
1962        )?;
1963        let pixels = decode_rgba16f_pixels(&raw);
1964        HdrRgbaImage::new(target.size.0, target.size.1, pixels)
1965    }
1966
1967    fn capture_final_composed_debug_artifact(
1968        &self,
1969        window_id: WindowId,
1970        request: DebugCaptureRequest,
1971    ) -> Result<DebugCaptureArtifact> {
1972        let target = self.offscreen_targets.get(&window_id).ok_or_else(|| {
1973            Error::new(format!(
1974                "window {} does not have an offscreen target available for final composed debug capture",
1975                window_id.get()
1976            ))
1977        })?;
1978
1979        match target.format {
1980            wgpu::TextureFormat::Bgra8UnormSrgb => self
1981                .capture_rgba(window_id)
1982                .map(DebugCaptureArtifact::SdrRgba8),
1983            wgpu::TextureFormat::Rgba16Float => {
1984                let image = self.capture_hdr_offscreen_rgba_f32(window_id)?;
1985                encode_hdr_debug_artifact(
1986                    image,
1987                    request,
1988                    self.final_composed_sdr_reference_white(window_id),
1989                    self.final_composed_output_primaries(window_id),
1990                )
1991            }
1992            other => Err(Error::new(format!(
1993                "window {} uses unsupported final composed debug capture format {other:?}",
1994                window_id.get()
1995            ))),
1996        }
1997    }
1998
1999    fn capture_hdr_offscreen_rgba_f32(&self, window_id: WindowId) -> Result<HdrRgbaImage> {
2000        let target = self.offscreen_targets.get(&window_id).ok_or_else(|| {
2001            Error::new(format!(
2002                "window {} does not have an offscreen HDR target available for debug capture",
2003                window_id.get()
2004            ))
2005        })?;
2006        let raw = self.readback_target_bytes(
2007            &target.texture,
2008            target.size,
2009            8,
2010            "SUI HDR final readback",
2011            "SUI HDR final readback encoder",
2012        )?;
2013        let pixels = decode_rgba16f_pixels(&raw);
2014        HdrRgbaImage::new(target.size.0, target.size.1, pixels)
2015    }
2016
2017    fn final_composed_sdr_reference_white(&self, window_id: WindowId) -> f32 {
2018        self.surfaces
2019            .get(&window_id)
2020            .map(|surface| {
2021                scene::output_sdr_content_scale(
2022                    surface.output_strategy,
2023                    surface.color_management.sdr_content_brightness_nits,
2024                    surface.display_capabilities.sdr_white_nits,
2025                )
2026            })
2027            .filter(|scale| scale.is_finite() && *scale > 0.0)
2028            .unwrap_or(1.0)
2029    }
2030
2031    fn final_composed_output_primaries(&self, window_id: WindowId) -> DisplayColorPrimaries {
2032        self.surfaces
2033            .get(&window_id)
2034            .map(|surface| scene::output_primaries(surface.output_strategy))
2035            .unwrap_or(DisplayColorPrimaries::Srgb)
2036    }
2037
2038    fn readback_target_bytes(
2039        &self,
2040        texture: &wgpu::Texture,
2041        size: (u32, u32),
2042        bytes_per_pixel: u32,
2043        buffer_label: &'static str,
2044        encoder_label: &'static str,
2045    ) -> Result<Vec<u8>> {
2046        let shared = self
2047            .shared
2048            .as_ref()
2049            .ok_or_else(|| Error::new("renderer has not initialized a wgpu device yet"))?;
2050        let bytes_per_row = size.0 * bytes_per_pixel;
2051        let padded_bytes_per_row = bytes_per_row.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
2052            * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
2053        let buffer_size = padded_bytes_per_row as u64 * size.1 as u64;
2054        let buffer = shared.device.create_buffer(&wgpu::BufferDescriptor {
2055            label: Some(buffer_label),
2056            size: buffer_size,
2057            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
2058            mapped_at_creation: false,
2059        });
2060
2061        let mut encoder = shared
2062            .device
2063            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
2064                label: Some(encoder_label),
2065            });
2066        encoder.copy_texture_to_buffer(
2067            wgpu::TexelCopyTextureInfo {
2068                texture,
2069                mip_level: 0,
2070                origin: wgpu::Origin3d::ZERO,
2071                aspect: wgpu::TextureAspect::All,
2072            },
2073            wgpu::TexelCopyBufferInfo {
2074                buffer: &buffer,
2075                layout: wgpu::TexelCopyBufferLayout {
2076                    offset: 0,
2077                    bytes_per_row: Some(padded_bytes_per_row),
2078                    rows_per_image: Some(size.1),
2079                },
2080            },
2081            wgpu::Extent3d {
2082                width: size.0,
2083                height: size.1,
2084                depth_or_array_layers: 1,
2085            },
2086        );
2087        shared.queue.submit([encoder.finish()]);
2088
2089        let (sender, receiver) = std::sync::mpsc::channel();
2090        let slice = buffer.slice(..);
2091        slice.map_async(wgpu::MapMode::Read, move |result| {
2092            let _ = sender.send(result);
2093        });
2094        shared
2095            .device
2096            .poll(wgpu::PollType::wait_indefinitely())
2097            .map_err(|error| {
2098                Error::new(format!(
2099                    "failed to poll device for screenshot capture: {error}"
2100                ))
2101            })?;
2102        receiver
2103            .recv()
2104            .map_err(|error| {
2105                Error::new(format!(
2106                    "failed to receive screenshot readback completion: {error}"
2107                ))
2108            })?
2109            .map_err(|error| {
2110                Error::new(format!("failed to map screenshot readback buffer: {error}"))
2111            })?;
2112
2113        let mapped = slice.get_mapped_range().map_err(|error| {
2114            Error::new(format!(
2115                "failed to access mapped screenshot readback buffer: {error}"
2116            ))
2117        })?;
2118        let tightly_packed = strip_padded_readback_rows(
2119            &mapped,
2120            bytes_per_row as usize,
2121            padded_bytes_per_row as usize,
2122            size.1 as usize,
2123        );
2124        drop(mapped);
2125        buffer.unmap();
2126        Ok(tightly_packed)
2127    }
2128
2129    fn ensure_shared(&mut self, compatible_surface: Option<&wgpu::Surface<'_>>) -> Result<()> {
2130        if self.shared.is_some() {
2131            return Ok(());
2132        }
2133
2134        let adapter =
2135            pollster::block_on(self.instance.request_adapter(&wgpu::RequestAdapterOptions {
2136                power_preference: wgpu::PowerPreference::HighPerformance,
2137                force_fallback_adapter: false,
2138                compatible_surface,
2139                apply_limit_buckets: false,
2140            }))
2141            .map_err(|error| Error::new(format!("failed to acquire wgpu adapter: {error}")))?;
2142
2143        let required_features = optional_renderer_features(&adapter);
2144        let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
2145            label: Some("SUI renderer device"),
2146            required_features,
2147            ..Default::default()
2148        }))
2149        .map_err(|error| Error::new(format!("failed to create wgpu device: {error}")))?;
2150
2151        let image_bind_group_layout =
2152            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2153                label: Some("SUI image bind group layout"),
2154                entries: &[
2155                    wgpu::BindGroupLayoutEntry {
2156                        binding: 0,
2157                        visibility: wgpu::ShaderStages::FRAGMENT,
2158                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
2159                        count: None,
2160                    },
2161                    wgpu::BindGroupLayoutEntry {
2162                        binding: 1,
2163                        visibility: wgpu::ShaderStages::FRAGMENT,
2164                        ty: wgpu::BindingType::Texture {
2165                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
2166                            view_dimension: wgpu::TextureViewDimension::D2,
2167                            multisampled: false,
2168                        },
2169                        count: None,
2170                    },
2171                ],
2172            });
2173        let text_atlas_array_bind_group_layout = create_text_atlas_array_bind_group_layout(&device);
2174        let image_linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2175            label: Some("SUI linear image sampler"),
2176            mag_filter: wgpu::FilterMode::Linear,
2177            min_filter: wgpu::FilterMode::Linear,
2178            mipmap_filter: wgpu::MipmapFilterMode::Linear,
2179            ..Default::default()
2180        });
2181        let image_nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2182            label: Some("SUI nearest image sampler"),
2183            mag_filter: wgpu::FilterMode::Nearest,
2184            min_filter: wgpu::FilterMode::Nearest,
2185            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
2186            lod_max_clamp: 0.0,
2187            ..Default::default()
2188        });
2189        let text_atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2190            label: Some("SUI text atlas sampler"),
2191            mag_filter: wgpu::FilterMode::Linear,
2192            min_filter: wgpu::FilterMode::Linear,
2193            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
2194            ..Default::default()
2195        });
2196        let text_quad_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
2197            label: Some("SUI text atlas quad"),
2198            contents: bytemuck::cast_slice(&TextAtlasQuadVertex::unit_quad()),
2199            usage: wgpu::BufferUsages::VERTEX,
2200        });
2201        let analytic_path_bind_group_layout =
2202            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2203                label: Some("SUI analytic path bind group layout"),
2204                entries: &[
2205                    wgpu::BindGroupLayoutEntry {
2206                        binding: 0,
2207                        visibility: wgpu::ShaderStages::FRAGMENT,
2208                        ty: wgpu::BindingType::Buffer {
2209                            ty: wgpu::BufferBindingType::Storage { read_only: true },
2210                            has_dynamic_offset: false,
2211                            min_binding_size: None,
2212                        },
2213                        count: None,
2214                    },
2215                    wgpu::BindGroupLayoutEntry {
2216                        binding: 1,
2217                        visibility: wgpu::ShaderStages::FRAGMENT,
2218                        ty: wgpu::BindingType::Buffer {
2219                            ty: wgpu::BufferBindingType::Storage { read_only: true },
2220                            has_dynamic_offset: false,
2221                            min_binding_size: None,
2222                        },
2223                        count: None,
2224                    },
2225                    wgpu::BindGroupLayoutEntry {
2226                        binding: 2,
2227                        visibility: wgpu::ShaderStages::FRAGMENT,
2228                        ty: wgpu::BindingType::Buffer {
2229                            ty: wgpu::BufferBindingType::Storage { read_only: true },
2230                            has_dynamic_offset: false,
2231                            min_binding_size: None,
2232                        },
2233                        count: None,
2234                    },
2235                ],
2236            });
2237        let output_transform_bind_group_layout =
2238            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2239                label: Some("SUI output transform bind group layout"),
2240                entries: &[
2241                    wgpu::BindGroupLayoutEntry {
2242                        binding: 0,
2243                        visibility: wgpu::ShaderStages::FRAGMENT,
2244                        ty: wgpu::BindingType::Texture {
2245                            sample_type: wgpu::TextureSampleType::Float { filterable: false },
2246                            view_dimension: wgpu::TextureViewDimension::D2,
2247                            multisampled: false,
2248                        },
2249                        count: None,
2250                    },
2251                    wgpu::BindGroupLayoutEntry {
2252                        binding: 1,
2253                        visibility: wgpu::ShaderStages::FRAGMENT,
2254                        ty: wgpu::BindingType::Buffer {
2255                            ty: wgpu::BufferBindingType::Uniform,
2256                            has_dynamic_offset: false,
2257                            min_binding_size: None,
2258                        },
2259                        count: None,
2260                    },
2261                ],
2262            });
2263
2264        let dual_source_blending_enabled = device
2265            .features()
2266            .contains(wgpu::Features::DUAL_SOURCE_BLENDING);
2267
2268        self.shared = Some(SharedRenderer {
2269            adapter,
2270            device,
2271            queue,
2272            pipelines: HashMap::new(),
2273            image_bind_group_layout,
2274            text_atlas_array_bind_group_layout,
2275            analytic_path_bind_group_layout,
2276            output_transform_bind_group_layout,
2277            image_linear_sampler,
2278            image_nearest_sampler,
2279            text_atlas_sampler,
2280            text_quad_buffer,
2281            dual_source_blending_enabled,
2282        });
2283        if let (Some(registry), Some(shared)) = (&self.external_texture_registry, &self.shared) {
2284            registry.attach(shared.device.clone(), shared.queue.clone());
2285        }
2286
2287        Ok(())
2288    }
2289
2290    #[cfg(target_arch = "wasm32")]
2291    pub async fn initialize_async(
2292        &mut self,
2293        compatible_surface: Option<&wgpu::Surface<'_>>,
2294    ) -> Result<()> {
2295        if self.shared.is_some() {
2296            return Ok(());
2297        }
2298
2299        let adapter = self
2300            .instance
2301            .request_adapter(&wgpu::RequestAdapterOptions {
2302                power_preference: wgpu::PowerPreference::None,
2303                force_fallback_adapter: false,
2304                compatible_surface,
2305                apply_limit_buckets: false,
2306            })
2307            .await
2308            .map_err(|error| Error::new(format!("failed to acquire wgpu adapter: {error}")))?;
2309
2310        let required_features = optional_renderer_features(&adapter);
2311        let (device, queue) = adapter
2312            .request_device(&wgpu::DeviceDescriptor {
2313                label: Some("SUI renderer device"),
2314                required_features,
2315                ..Default::default()
2316            })
2317            .await
2318            .map_err(|error| Error::new(format!("failed to create wgpu device: {error}")))?;
2319
2320        let image_bind_group_layout =
2321            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2322                label: Some("SUI image bind group layout"),
2323                entries: &[
2324                    wgpu::BindGroupLayoutEntry {
2325                        binding: 0,
2326                        visibility: wgpu::ShaderStages::FRAGMENT,
2327                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
2328                        count: None,
2329                    },
2330                    wgpu::BindGroupLayoutEntry {
2331                        binding: 1,
2332                        visibility: wgpu::ShaderStages::FRAGMENT,
2333                        ty: wgpu::BindingType::Texture {
2334                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
2335                            view_dimension: wgpu::TextureViewDimension::D2,
2336                            multisampled: false,
2337                        },
2338                        count: None,
2339                    },
2340                ],
2341            });
2342        let text_atlas_array_bind_group_layout = create_text_atlas_array_bind_group_layout(&device);
2343        let image_linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2344            label: Some("SUI linear image sampler"),
2345            mag_filter: wgpu::FilterMode::Linear,
2346            min_filter: wgpu::FilterMode::Linear,
2347            mipmap_filter: wgpu::MipmapFilterMode::Linear,
2348            ..Default::default()
2349        });
2350        let image_nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2351            label: Some("SUI nearest image sampler"),
2352            mag_filter: wgpu::FilterMode::Nearest,
2353            min_filter: wgpu::FilterMode::Nearest,
2354            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
2355            lod_max_clamp: 0.0,
2356            ..Default::default()
2357        });
2358        let text_atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
2359            label: Some("SUI text atlas sampler"),
2360            mag_filter: wgpu::FilterMode::Linear,
2361            min_filter: wgpu::FilterMode::Linear,
2362            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
2363            ..Default::default()
2364        });
2365        let text_quad_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
2366            label: Some("SUI text atlas quad"),
2367            contents: bytemuck::cast_slice(&TextAtlasQuadVertex::unit_quad()),
2368            usage: wgpu::BufferUsages::VERTEX,
2369        });
2370        let analytic_path_bind_group_layout =
2371            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2372                label: Some("SUI analytic path bind group layout"),
2373                entries: &[
2374                    wgpu::BindGroupLayoutEntry {
2375                        binding: 0,
2376                        visibility: wgpu::ShaderStages::FRAGMENT,
2377                        ty: wgpu::BindingType::Buffer {
2378                            ty: wgpu::BufferBindingType::Storage { read_only: true },
2379                            has_dynamic_offset: false,
2380                            min_binding_size: None,
2381                        },
2382                        count: None,
2383                    },
2384                    wgpu::BindGroupLayoutEntry {
2385                        binding: 1,
2386                        visibility: wgpu::ShaderStages::FRAGMENT,
2387                        ty: wgpu::BindingType::Buffer {
2388                            ty: wgpu::BufferBindingType::Storage { read_only: true },
2389                            has_dynamic_offset: false,
2390                            min_binding_size: None,
2391                        },
2392                        count: None,
2393                    },
2394                    wgpu::BindGroupLayoutEntry {
2395                        binding: 2,
2396                        visibility: wgpu::ShaderStages::FRAGMENT,
2397                        ty: wgpu::BindingType::Buffer {
2398                            ty: wgpu::BufferBindingType::Storage { read_only: true },
2399                            has_dynamic_offset: false,
2400                            min_binding_size: None,
2401                        },
2402                        count: None,
2403                    },
2404                ],
2405            });
2406        let output_transform_bind_group_layout =
2407            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
2408                label: Some("SUI output transform bind group layout"),
2409                entries: &[
2410                    wgpu::BindGroupLayoutEntry {
2411                        binding: 0,
2412                        visibility: wgpu::ShaderStages::FRAGMENT,
2413                        ty: wgpu::BindingType::Texture {
2414                            sample_type: wgpu::TextureSampleType::Float { filterable: false },
2415                            view_dimension: wgpu::TextureViewDimension::D2,
2416                            multisampled: false,
2417                        },
2418                        count: None,
2419                    },
2420                    wgpu::BindGroupLayoutEntry {
2421                        binding: 1,
2422                        visibility: wgpu::ShaderStages::FRAGMENT,
2423                        ty: wgpu::BindingType::Buffer {
2424                            ty: wgpu::BufferBindingType::Uniform,
2425                            has_dynamic_offset: false,
2426                            min_binding_size: None,
2427                        },
2428                        count: None,
2429                    },
2430                ],
2431            });
2432
2433        let dual_source_blending_enabled = device
2434            .features()
2435            .contains(wgpu::Features::DUAL_SOURCE_BLENDING);
2436
2437        self.shared = Some(SharedRenderer {
2438            adapter,
2439            device,
2440            queue,
2441            pipelines: HashMap::new(),
2442            image_bind_group_layout,
2443            text_atlas_array_bind_group_layout,
2444            analytic_path_bind_group_layout,
2445            output_transform_bind_group_layout,
2446            image_linear_sampler,
2447            image_nearest_sampler,
2448            text_atlas_sampler,
2449            text_quad_buffer,
2450            dual_source_blending_enabled,
2451        });
2452        if let (Some(registry), Some(shared)) = (&self.external_texture_registry, &self.shared) {
2453            registry.attach(shared.device.clone(), shared.queue.clone());
2454        }
2455
2456        Ok(())
2457    }
2458
2459    fn render_surface(
2460        &mut self,
2461        frame: &SceneFrame,
2462        size: (u32, u32),
2463    ) -> Result<RendererFrameStats> {
2464        self.ensure_shared(None)?;
2465        self.resize_surface(frame.window_id, size)?;
2466
2467        let prepared = self.prepare_scene_submission(frame)?;
2468
2469        let Some((frame_texture, suboptimal, surface_acquire_time_us)) =
2470            self.acquire_surface_texture(frame.window_id, size)?
2471        else {
2472            return Ok(RendererFrameStats::default());
2473        };
2474
2475        let (format, strategy, tone_mapping, sdr_content_brightness_nits, display_sdr_white_nits) = {
2476            let surface = self.surfaces.get(&frame.window_id).ok_or_else(|| {
2477                Error::new(format!(
2478                    "missing surface for window {}",
2479                    frame.window_id.get()
2480                ))
2481            })?;
2482            (
2483                surface.config.format,
2484                surface.output_strategy,
2485                surface.color_management.tone_mapping,
2486                surface.color_management.sdr_content_brightness_nits,
2487                surface.display_capabilities.sdr_white_nits,
2488            )
2489        };
2490        let view = frame_texture
2491            .texture
2492            .create_view(&wgpu::TextureViewDescriptor::default());
2493
2494        let mut frame_stats = if output_transform_requires_intermediate(strategy) {
2495            let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
2496            let intermediate_format = self
2497                .intermediate_targets
2498                .get(&frame.window_id)
2499                .map(|target| target.format)
2500                .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
2501            let mut frame_stats =
2502                self.submit_prepared_scene(prepared, intermediate_format, &intermediate_view)?;
2503            self.submit_output_transform_pass(
2504                &intermediate_view,
2505                &view,
2506                format,
2507                strategy,
2508                tone_mapping,
2509                sdr_content_brightness_nits,
2510                display_sdr_white_nits,
2511                &mut frame_stats,
2512            )?;
2513            frame_stats
2514        } else {
2515            self.submit_prepared_scene(prepared, format, &view)?
2516        };
2517        frame_stats.surface_acquire_time_us = surface_acquire_time_us;
2518        let surface_present_started = self.runtime_diagnostics_enabled.then(Instant::now);
2519        self.shared
2520            .as_ref()
2521            .expect("renderer shared state initialized")
2522            .queue
2523            .present(frame_texture);
2524        frame_stats.surface_present_time_us = surface_present_started
2525            .map(|started| started.elapsed().as_micros() as u64)
2526            .unwrap_or(0);
2527
2528        if suboptimal {
2529            self.configure_surface(frame.window_id, size)?;
2530        }
2531
2532        Ok(frame_stats)
2533    }
2534
2535    fn acquire_surface_texture(
2536        &mut self,
2537        window_id: WindowId,
2538        size: (u32, u32),
2539    ) -> Result<Option<(wgpu::SurfaceTexture, bool, u64)>> {
2540        let surface_acquire_started = self.runtime_diagnostics_enabled.then(Instant::now);
2541        let (frame_texture, suboptimal) = loop {
2542            let result = {
2543                let surface = self.surfaces.get(&window_id).ok_or_else(|| {
2544                    Error::new(format!("missing surface for window {}", window_id.get()))
2545                })?;
2546                surface.surface.get_current_texture()
2547            };
2548
2549            match result {
2550                wgpu::CurrentSurfaceTexture::Success(texture) => break (texture, false),
2551                wgpu::CurrentSurfaceTexture::Suboptimal(texture) => break (texture, true),
2552                wgpu::CurrentSurfaceTexture::Outdated => {
2553                    self.configure_surface(window_id, size)?;
2554                }
2555                wgpu::CurrentSurfaceTexture::Lost => {
2556                    self.recreate_surface(window_id, size)?;
2557                }
2558                wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
2559                    return Ok(None);
2560                }
2561                wgpu::CurrentSurfaceTexture::Validation => {
2562                    return Err(Error::new(
2563                        "wgpu surface acquisition triggered a validation error",
2564                    ));
2565                }
2566            }
2567        };
2568        let surface_acquire_time_us = surface_acquire_started
2569            .map(|started| started.elapsed().as_micros() as u64)
2570            .unwrap_or(0);
2571
2572        Ok(Some((frame_texture, suboptimal, surface_acquire_time_us)))
2573    }
2574
2575    fn render_debug_capture_stage(
2576        &mut self,
2577        frame: &SceneFrame,
2578        size: (u32, u32),
2579        request: DebugCaptureRequest,
2580    ) -> Result<RendererFrameStats> {
2581        match request.stage {
2582            DebugCaptureStage::HdrIntermediate => self.render_offscreen(frame, size),
2583            DebugCaptureStage::FinalComposed
2584                if request.encoding == DebugCaptureEncoding::Png
2585                    && request.sdr_visualization == DebugSdrVisualization::ToneMappedColor =>
2586            {
2587                self.render_offscreen(frame, size)
2588            }
2589            DebugCaptureStage::FinalComposed => self.render_final_composed_offscreen(frame, size),
2590        }
2591    }
2592
2593    fn render_final_composed_offscreen(
2594        &mut self,
2595        frame: &SceneFrame,
2596        size: (u32, u32),
2597    ) -> Result<RendererFrameStats> {
2598        self.ensure_shared(None)?;
2599
2600        let Some(surface_state) = self.surfaces.get(&frame.window_id) else {
2601            return self.render_offscreen(frame, size);
2602        };
2603        let strategy = surface_state.output_strategy;
2604        let requested_tone_mapping = surface_state.color_management.tone_mapping;
2605        let sdr_content_brightness_nits =
2606            surface_state.color_management.sdr_content_brightness_nits;
2607        let display_sdr_white_nits = surface_state.display_capabilities.sdr_white_nits;
2608        let final_format = strategy.surface_format();
2609        let final_view = self.ensure_offscreen_target(frame.window_id, size, final_format)?;
2610        let prepared = self.prepare_scene_submission(frame)?;
2611
2612        if output_transform_requires_intermediate(strategy) {
2613            let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
2614            let intermediate_format = self
2615                .intermediate_targets
2616                .get(&frame.window_id)
2617                .map(|target| target.format)
2618                .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
2619            let mut frame_stats =
2620                self.submit_prepared_scene(prepared, intermediate_format, &intermediate_view)?;
2621            self.submit_output_transform_pass(
2622                &intermediate_view,
2623                &final_view,
2624                final_format,
2625                strategy,
2626                requested_tone_mapping,
2627                sdr_content_brightness_nits,
2628                display_sdr_white_nits,
2629                &mut frame_stats,
2630            )?;
2631            Ok(frame_stats)
2632        } else {
2633            self.submit_prepared_scene(prepared, final_format, &final_view)
2634        }
2635    }
2636
2637    fn render_offscreen(
2638        &mut self,
2639        frame: &SceneFrame,
2640        size: (u32, u32),
2641    ) -> Result<RendererFrameStats> {
2642        self.ensure_shared(None)?;
2643
2644        let final_format = wgpu::TextureFormat::Bgra8UnormSrgb;
2645        let final_view = self.ensure_offscreen_target(frame.window_id, size, final_format)?;
2646        let prepared = self.prepare_scene_submission(frame)?;
2647        let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
2648        let intermediate_format = self
2649            .intermediate_targets
2650            .get(&frame.window_id)
2651            .map(|target| target.format)
2652            .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
2653        let mut frame_stats =
2654            self.submit_prepared_scene(prepared, intermediate_format, &intermediate_view)?;
2655        self.submit_output_transform_pass(
2656            &intermediate_view,
2657            &final_view,
2658            final_format,
2659            OutputStrategy::SdrSurface {
2660                format: final_format,
2661            },
2662            RequestedToneMappingMode::Clamp,
2663            ColorManagementMode::default().sdr_content_brightness_nits,
2664            None,
2665            &mut frame_stats,
2666        )?;
2667        Ok(frame_stats)
2668    }
2669
2670    fn ensure_offscreen_target(
2671        &mut self,
2672        window_id: WindowId,
2673        size: (u32, u32),
2674        format: wgpu::TextureFormat,
2675    ) -> Result<wgpu::TextureView> {
2676        let recreate = self
2677            .offscreen_targets
2678            .get(&window_id)
2679            .is_none_or(|target| target.size != size || target.format != format);
2680        if recreate {
2681            let shared = self
2682                .shared
2683                .as_ref()
2684                .expect("renderer shared state initialized");
2685            let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
2686                label: Some("SUI offscreen frame"),
2687                size: wgpu::Extent3d {
2688                    width: size.0,
2689                    height: size.1,
2690                    depth_or_array_layers: 1,
2691                },
2692                mip_level_count: 1,
2693                sample_count: 1,
2694                dimension: wgpu::TextureDimension::D2,
2695                format,
2696                usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
2697                view_formats: &[],
2698            });
2699            self.offscreen_targets.insert(
2700                window_id,
2701                OffscreenTarget {
2702                    texture,
2703                    format,
2704                    size,
2705                },
2706            );
2707        }
2708        self.offscreen_targets
2709            .get(&window_id)
2710            .map(|target| {
2711                target
2712                    .texture
2713                    .create_view(&wgpu::TextureViewDescriptor::default())
2714            })
2715            .ok_or_else(|| Error::new(format!("missing target for window {}", window_id.get())))
2716    }
2717
2718    fn ensure_intermediate_target(
2719        &mut self,
2720        window_id: WindowId,
2721        size: (u32, u32),
2722    ) -> Result<wgpu::TextureView> {
2723        let format = wgpu::TextureFormat::Rgba16Float;
2724        let recreate = self
2725            .intermediate_targets
2726            .get(&window_id)
2727            .is_none_or(|target| target.size != size || target.format != format);
2728        if recreate {
2729            let shared = self
2730                .shared
2731                .as_ref()
2732                .expect("renderer shared state initialized");
2733            let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
2734                label: Some("SUI HDR intermediate frame"),
2735                size: wgpu::Extent3d {
2736                    width: size.0,
2737                    height: size.1,
2738                    depth_or_array_layers: 1,
2739                },
2740                mip_level_count: 1,
2741                sample_count: 1,
2742                dimension: wgpu::TextureDimension::D2,
2743                format,
2744                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
2745                    | wgpu::TextureUsages::TEXTURE_BINDING
2746                    | wgpu::TextureUsages::COPY_SRC,
2747                view_formats: &[],
2748            });
2749            self.intermediate_targets.insert(
2750                window_id,
2751                OffscreenTarget {
2752                    texture,
2753                    format,
2754                    size,
2755                },
2756            );
2757        }
2758        self.intermediate_targets
2759            .get(&window_id)
2760            .map(|target| {
2761                target
2762                    .texture
2763                    .create_view(&wgpu::TextureViewDescriptor::default())
2764            })
2765            .ok_or_else(|| Error::new(format!("missing target for window {}", window_id.get())))
2766    }
2767
2768    fn submit_output_transform_pass(
2769        &mut self,
2770        source_view: &wgpu::TextureView,
2771        destination_view: &wgpu::TextureView,
2772        destination_format: wgpu::TextureFormat,
2773        strategy: OutputStrategy,
2774        requested_tone_mapping: RequestedToneMappingMode,
2775        sdr_content_brightness_nits: f32,
2776        display_sdr_white_nits: Option<f32>,
2777        frame_stats: &mut RendererFrameStats,
2778    ) -> Result<()> {
2779        let resolved_tone_mapping = match strategy {
2780            OutputStrategy::HdrNativeSurface { .. } => 0,
2781            _ => match requested_tone_mapping {
2782                RequestedToneMappingMode::Automatic => 1,
2783                RequestedToneMappingMode::Clamp => 1,
2784                RequestedToneMappingMode::Reinhard => 2,
2785            },
2786        };
2787        let shared = self
2788            .shared
2789            .as_mut()
2790            .expect("renderer shared state initialized");
2791        let sdr_content_scale = scene::output_sdr_content_scale(
2792            strategy,
2793            sdr_content_brightness_nits,
2794            display_sdr_white_nits,
2795        );
2796        let encode_srgb = matches!(
2797            destination_format,
2798            wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm
2799        ) || matches!(
2800            strategy,
2801            OutputStrategy::HdrNativeSurface {
2802                transfer: DisplayTransferFunction::Srgb,
2803                ..
2804            }
2805        );
2806        let uniform = OutputTransformUniform::new(
2807            resolved_tone_mapping,
2808            encode_srgb,
2809            scene::output_primaries(strategy),
2810            sdr_content_scale,
2811        );
2812        let uniform_buffer = shared
2813            .device
2814            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
2815                label: Some("SUI output transform uniform"),
2816                contents: bytemuck::bytes_of(&uniform),
2817                usage: wgpu::BufferUsages::UNIFORM,
2818            });
2819        let bind_group = shared.device.create_bind_group(&wgpu::BindGroupDescriptor {
2820            label: Some("SUI output transform bind group"),
2821            layout: &shared.output_transform_bind_group_layout,
2822            entries: &[
2823                wgpu::BindGroupEntry {
2824                    binding: 0,
2825                    resource: wgpu::BindingResource::TextureView(source_view),
2826                },
2827                wgpu::BindGroupEntry {
2828                    binding: 1,
2829                    resource: uniform_buffer.as_entire_binding(),
2830                },
2831            ],
2832        });
2833        let mut encoder = shared
2834            .device
2835            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
2836                label: Some("SUI output transform encoder"),
2837            });
2838        {
2839            let pipeline = shared.output_transform_pipeline(destination_format);
2840            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
2841                label: Some("SUI output transform pass"),
2842                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
2843                    view: destination_view,
2844                    depth_slice: None,
2845                    resolve_target: None,
2846                    ops: wgpu::Operations {
2847                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
2848                        store: wgpu::StoreOp::Store,
2849                    },
2850                })],
2851                depth_stencil_attachment: None,
2852                occlusion_query_set: None,
2853                timestamp_writes: None,
2854                multiview_mask: None,
2855            });
2856            pass.set_pipeline(pipeline);
2857            pass.set_bind_group(0, &bind_group, &[]);
2858            pass.draw(0..3, 0..1);
2859        }
2860        shared.queue.submit([encoder.finish()]);
2861        frame_stats.pass_count += 1;
2862        Ok(())
2863    }
2864
2865    fn resize_surface(&mut self, window_id: WindowId, size: (u32, u32)) -> Result<()> {
2866        let surface = self
2867            .surfaces
2868            .get(&window_id)
2869            .ok_or_else(|| Error::new(format!("missing surface for window {}", window_id.get())))?;
2870
2871        if surface.config.width == size.0 && surface.config.height == size.1 {
2872            return Ok(());
2873        }
2874
2875        self.configure_surface(window_id, size)
2876    }
2877
2878    fn configure_existing_surface(&mut self, window_id: WindowId) -> Result<()> {
2879        let size = {
2880            let surface = self.surfaces.get(&window_id).ok_or_else(|| {
2881                Error::new(format!("missing surface for window {}", window_id.get()))
2882            })?;
2883            (surface.config.width.max(1), surface.config.height.max(1))
2884        };
2885        self.configure_surface(window_id, size)
2886    }
2887
2888    fn configure_surface(&mut self, window_id: WindowId, size: (u32, u32)) -> Result<()> {
2889        let shared = self
2890            .shared
2891            .as_ref()
2892            .expect("renderer shared state initialized");
2893        let surface = self
2894            .surfaces
2895            .get_mut(&window_id)
2896            .ok_or_else(|| Error::new(format!("missing surface for window {}", window_id.get())))?;
2897
2898        let available_surface_formats = surface.surface.get_capabilities(&shared.adapter).formats;
2899        let (config, output_strategy) = configure_surface(
2900            &surface.surface,
2901            &shared.adapter,
2902            &shared.device,
2903            size,
2904            self.vsync_enabled,
2905            surface.display_capabilities.clone(),
2906            surface.color_management,
2907        )?;
2908        surface.config = config;
2909        surface.output_strategy = output_strategy;
2910        surface.available_surface_formats = available_surface_formats;
2911        Ok(())
2912    }
2913
2914    fn recreate_surface(&mut self, window_id: WindowId, size: (u32, u32)) -> Result<()> {
2915        let window = self
2916            .surfaces
2917            .get(&window_id)
2918            .ok_or_else(|| Error::new(format!("missing surface for window {}", window_id.get())))?
2919            .window
2920            .clone();
2921        let state = self.create_surface_state(window, size)?;
2922        self.surfaces.insert(window_id, state);
2923        Ok(())
2924    }
2925
2926    fn prepare_scene_submission(&mut self, frame: &SceneFrame) -> Result<PreparedSceneSubmission> {
2927        let diagnostics_enabled = self.runtime_diagnostics_enabled;
2928        let feather_width = self.active_feather_width();
2929        let text_render_mode = self.text_render_mode();
2930        let text_subpixel_order = self.active_text_subpixel_order();
2931        let text_hinting = self.active_text_hinting();
2932        let stem_darkening = self.active_stem_darkening();
2933        let text_coverage_policy = self.active_text_coverage_policy();
2934        if self.text_engine.is_none() {
2935            self.text_engine = Some(TextEngine::new()?);
2936        }
2937        // The multi-page atlas grows and evicts on demand, so a glyph that cannot be placed is
2938        // simply dropped for the frame -- there is no longer an "atlas full" error to recover
2939        // from, hence no retry loop.
2940        let (submission, compositor_stats, text_frame_stats) = {
2941            let text_engine = self
2942                .text_engine
2943                .as_mut()
2944                .expect("text engine initialized before draw-op construction");
2945            text_engine.set_text_render_mode(text_render_mode);
2946            text_engine.set_text_subpixel_order(text_subpixel_order);
2947            text_engine.set_text_hinting(text_hinting);
2948            text_engine.set_stem_darkening(stem_darkening);
2949            text_engine.set_text_coverage_policy(text_coverage_policy);
2950            text_engine.set_diagnostics_enabled(diagnostics_enabled);
2951            text_engine.begin_frame();
2952            let compositor = self.compositors.entry(frame.window_id).or_default();
2953            compositor.set_diagnostics_enabled(diagnostics_enabled);
2954            let submission =
2955                compositor.prepare_frame_submission(frame, text_engine, feather_width)?;
2956            let compositor_stats = compositor.last_frame_stats.clone();
2957            let text_frame_stats = if diagnostics_enabled {
2958                text_engine.frame_stats()
2959            } else {
2960                TextFrameStats::default()
2961            };
2962            (submission, compositor_stats, text_frame_stats)
2963        };
2964        let framebuffer_size = normalize_framebuffer_size(frame.surface_size).unwrap_or((1, 1));
2965        let mut analytic_paths = HashMap::new();
2966        let mut image_resources = HashSet::new();
2967        let mut uses_text_atlas = false;
2968        let resource_collection_started = diagnostics_enabled.then(Instant::now);
2969        for fragment in &submission.fragments {
2970            let RetainedFrameFragment::Transient(draw_ops) = fragment;
2971            uses_text_atlas |=
2972                collect_draw_op_resources(draw_ops, &mut analytic_paths, &mut image_resources);
2973        }
2974        let resource_collection_time_us = resource_collection_started
2975            .map(|started| started.elapsed().as_micros() as u64)
2976            .unwrap_or(0);
2977
2978        let bind_group_prepare_started = diagnostics_enabled.then(Instant::now);
2979        let (analytic_path_resources, analytic_path_stats) =
2980            self.prepare_analytic_path_resources(analytic_paths, diagnostics_enabled)?;
2981        let analytic_path_bind_group_time_us = analytic_path_stats.total_time_us;
2982        let analytic_path_bind_group_miss_count = analytic_path_stats.miss_count;
2983        let analytic_path_bind_group_upload_bytes = analytic_path_stats.upload_bytes;
2984
2985        let image_bind_group_started = diagnostics_enabled.then(Instant::now);
2986        let mut image_bind_groups = HashMap::new();
2987        for key in image_resources {
2988            let bind_group = if let Some(image) = frame.image_registry.get_external(key.handle) {
2989                self.ensure_external_image_bind_group(key.handle, key.sampling, *image)?
2990            } else {
2991                let image = frame.image_registry.get(key.handle).ok_or_else(|| {
2992                    Error::new(format!(
2993                        "image handle {} is not registered",
2994                        key.handle.get()
2995                    ))
2996                })?;
2997                self.ensure_image_bind_group(key, image)?
2998            };
2999            image_bind_groups.insert(key, bind_group);
3000        }
3001        let image_bind_group_time_us = image_bind_group_started
3002            .map(|started| started.elapsed().as_micros() as u64)
3003            .unwrap_or(0);
3004        let mut text_atlas_bind_group_time_us = 0u64;
3005        let mut text_atlas_upload_copy_time_us = 0u64;
3006        let mut text_atlas_upload_write_time_us = 0u64;
3007        let mut text_atlas_upload_bytes = 0u64;
3008        let text_atlas_bind_group = if uses_text_atlas {
3009            let mut text_engine = self
3010                .text_engine
3011                .take()
3012                .expect("text engine initialized before text atlas upload");
3013            let (bind_group, stats) =
3014                self.ensure_text_atlas_bind_group(&mut text_engine, diagnostics_enabled)?;
3015            self.text_engine = Some(text_engine);
3016            text_atlas_bind_group_time_us = stats.total_time_us;
3017            text_atlas_upload_copy_time_us = stats.upload_copy_time_us;
3018            text_atlas_upload_write_time_us = stats.upload_write_time_us;
3019            text_atlas_upload_bytes = stats.upload_bytes;
3020            Some(bind_group)
3021        } else {
3022            None
3023        };
3024        let bind_group_prepare_time_us = bind_group_prepare_started
3025            .map(|started| started.elapsed().as_micros() as u64)
3026            .unwrap_or(0);
3027        let mut prepared_fragments = Vec::new();
3028        let mut draw_count = 0usize;
3029        let mut uploaded_vertex_bytes = 0u64;
3030        let mut needs_stencil = false;
3031        let mut batch_prepare_time_us = 0u64;
3032        let mut gpu_upload_time_us = 0u64;
3033
3034        for fragment in submission.fragments {
3035            let RetainedFrameFragment::Transient(draw_ops) = fragment;
3036            let batch_prepare_started = diagnostics_enabled.then(Instant::now);
3037            let mut prepared = prepare_frame_batches(draw_ops, frame.viewport, framebuffer_size);
3038            stamp_analytic_path_slots(
3039                &mut prepared.scene_vertices,
3040                &prepared.passes,
3041                analytic_path_resources.as_ref(),
3042            );
3043            if let Some(started) = batch_prepare_started {
3044                batch_prepare_time_us += started.elapsed().as_micros() as u64;
3045            }
3046            if diagnostics_enabled {
3047                let (_, fragment_draw_count) = prepared_batch_counts(&prepared.passes);
3048                draw_count += fragment_draw_count;
3049                uploaded_vertex_bytes += (prepared.scene_vertices.len() as u64
3050                    + prepared.clip_vertices.len() as u64)
3051                    * VERTEX_SIZE
3052                    + prepared.text_instances.len() as u64 * TEXT_ATLAS_INSTANCE_SIZE;
3053            }
3054
3055            if prepared.passes.is_empty() {
3056                continue;
3057            }
3058
3059            let shared = self
3060                .shared
3061                .as_ref()
3062                .expect("renderer shared state initialized");
3063            needs_stencil |= prepared
3064                .passes
3065                .iter()
3066                .any(|pass| !pass.clip_paths.is_empty());
3067            let gpu_upload_started = diagnostics_enabled.then(Instant::now);
3068            prepared_fragments.push(PreparedFragmentSubmission {
3069                passes: prepared.passes,
3070                scene_buffer: create_static_vertex_buffer(
3071                    &shared.device,
3072                    "SUI transient fragment scene",
3073                    &prepared.scene_vertices,
3074                ),
3075                clip_buffer: create_static_vertex_buffer(
3076                    &shared.device,
3077                    "SUI transient fragment clip",
3078                    &prepared.clip_vertices,
3079                ),
3080                text_instance_buffer: create_static_text_instance_buffer(
3081                    &shared.device,
3082                    "SUI transient fragment text instances",
3083                    &prepared.text_instances,
3084                ),
3085                translation: Vector::ZERO,
3086            });
3087            if let Some(started) = gpu_upload_started {
3088                gpu_upload_time_us += started.elapsed().as_micros() as u64;
3089            }
3090        }
3091
3092        if needs_stencil {
3093            let shared = self
3094                .shared
3095                .as_ref()
3096                .expect("renderer shared state initialized");
3097            let gpu_upload_started = diagnostics_enabled.then(Instant::now);
3098            self.frame_resources
3099                .ensure_stencil(&shared.device, framebuffer_size);
3100            if let Some(started) = gpu_upload_started {
3101                gpu_upload_time_us += started.elapsed().as_micros() as u64;
3102            }
3103        }
3104
3105        let batch_prepare_started = diagnostics_enabled.then(Instant::now);
3106        let encodable_passes = flatten_fragment_passes(&prepared_fragments);
3107        if let Some(started) = batch_prepare_started {
3108            batch_prepare_time_us += started.elapsed().as_micros() as u64;
3109        }
3110        let mut frame_stats = if diagnostics_enabled {
3111            RendererFrameStats::from_prepared_counts(0, draw_count, uploaded_vertex_bytes)
3112                .with_text_stats(text_frame_stats)
3113                .with_compositor_stats(compositor_stats)
3114        } else {
3115            RendererFrameStats::default()
3116        };
3117        frame_stats.resource_collection_time_us = resource_collection_time_us;
3118        frame_stats.bind_group_prepare_time_us = bind_group_prepare_time_us;
3119        frame_stats.image_bind_group_time_us = image_bind_group_time_us;
3120        frame_stats.analytic_path_bind_group_time_us = analytic_path_bind_group_time_us;
3121        frame_stats.analytic_path_bind_group_miss_count = analytic_path_bind_group_miss_count;
3122        frame_stats.analytic_path_bind_group_upload_bytes = analytic_path_bind_group_upload_bytes;
3123        frame_stats.text_atlas_bind_group_time_us = text_atlas_bind_group_time_us;
3124        frame_stats.text_atlas_upload_copy_time_us = text_atlas_upload_copy_time_us;
3125        frame_stats.text_atlas_upload_write_time_us = text_atlas_upload_write_time_us;
3126        frame_stats.text_atlas_upload_bytes = text_atlas_upload_bytes;
3127        frame_stats.batch_prepare_time_us = batch_prepare_time_us;
3128        frame_stats.gpu_upload_time_us = gpu_upload_time_us;
3129        Ok(PreparedSceneSubmission {
3130            viewport: frame.viewport,
3131            framebuffer_size,
3132            encodable_passes,
3133            image_bind_groups,
3134            text_atlas_bind_group,
3135            analytic_path_resources,
3136            frame_stats,
3137        })
3138    }
3139
3140    fn submit_prepared_scene(
3141        &mut self,
3142        prepared: PreparedSceneSubmission,
3143        target_format: wgpu::TextureFormat,
3144        view: &wgpu::TextureView,
3145    ) -> Result<RendererFrameStats> {
3146        let mut encoder = {
3147            let shared = self
3148                .shared
3149                .as_ref()
3150                .expect("renderer shared state initialized");
3151            shared
3152                .device
3153                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
3154                    label: Some("SUI scene encoder"),
3155                })
3156        };
3157
3158        let pass_encode_started = self.runtime_diagnostics_enabled.then(Instant::now);
3159        let pass_count = if prepared.encodable_passes.is_empty() {
3160            let _ = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
3161                label: Some("SUI scene clear pass"),
3162                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
3163                    view,
3164                    depth_slice: None,
3165                    resolve_target: None,
3166                    ops: wgpu::Operations {
3167                        load: wgpu::LoadOp::Clear(wgpu::Color {
3168                            r: 0.0,
3169                            g: 0.0,
3170                            b: 0.0,
3171                            a: 0.0,
3172                        }),
3173                        store: wgpu::StoreOp::Store,
3174                    },
3175                })],
3176                depth_stencil_attachment: None,
3177                occlusion_query_set: None,
3178                timestamp_writes: None,
3179                multiview_mask: None,
3180            });
3181            1
3182        } else {
3183            let shared = self
3184                .shared
3185                .as_mut()
3186                .expect("renderer shared state initialized");
3187            let stencil_view = self.frame_resources.stencil.as_ref().map(|target| {
3188                let _ = &target.texture;
3189                &target.view
3190            });
3191            encode_fragment_passes(
3192                shared,
3193                &mut encoder,
3194                view,
3195                target_format,
3196                prepared.viewport,
3197                prepared.framebuffer_size,
3198                &prepared.encodable_passes,
3199                stencil_view,
3200                &prepared.image_bind_groups,
3201                prepared.text_atlas_bind_group.as_ref(),
3202                prepared.analytic_path_resources.as_ref(),
3203            )?
3204        };
3205        let pass_encode_time_us = pass_encode_started
3206            .map(|started| started.elapsed().as_micros() as u64)
3207            .unwrap_or(0);
3208
3209        let queue_submit_started = self.runtime_diagnostics_enabled.then(Instant::now);
3210        self.shared
3211            .as_ref()
3212            .expect("renderer shared state initialized")
3213            .queue
3214            .submit([encoder.finish()]);
3215        let queue_submit_time_us = queue_submit_started
3216            .map(|started| started.elapsed().as_micros() as u64)
3217            .unwrap_or(0);
3218
3219        let mut frame_stats = prepared.frame_stats;
3220        frame_stats.pass_encode_time_us = pass_encode_time_us;
3221        frame_stats.queue_submit_time_us = queue_submit_time_us;
3222        frame_stats.pass_count = pass_count.max(1);
3223        Ok(frame_stats)
3224    }
3225
3226    fn registered_image_data_identity_eq(left: &RegisteredImage, right: &RegisteredImage) -> bool {
3227        left.width() == right.width()
3228            && left.height() == right.height()
3229            && left.format() == right.format()
3230            && left.bytes().len() == right.bytes().len()
3231            && std::ptr::addr_eq(left.bytes().as_ptr(), right.bytes().as_ptr())
3232    }
3233
3234    fn write_registered_image_texture(
3235        queue: &wgpu::Queue,
3236        texture: &wgpu::Texture,
3237        image: &RegisteredImage,
3238        mipmapped: bool,
3239    ) {
3240        if !mipmapped {
3241            queue.write_texture(
3242                wgpu::TexelCopyTextureInfo {
3243                    texture,
3244                    mip_level: 0,
3245                    origin: wgpu::Origin3d::ZERO,
3246                    aspect: wgpu::TextureAspect::All,
3247                },
3248                image.bytes(),
3249                wgpu::TexelCopyBufferLayout {
3250                    offset: 0,
3251                    bytes_per_row: Some(image.width() * 4),
3252                    rows_per_image: Some(image.height()),
3253                },
3254                wgpu::Extent3d {
3255                    width: image.width(),
3256                    height: image.height(),
3257                    depth_or_array_layers: 1,
3258                },
3259            );
3260            return;
3261        }
3262
3263        let mip_chain = image_mip_chain(image, mipmapped);
3264        for (mip_level, level) in mip_chain.iter().enumerate() {
3265            queue.write_texture(
3266                wgpu::TexelCopyTextureInfo {
3267                    texture,
3268                    mip_level: mip_level as u32,
3269                    origin: wgpu::Origin3d::ZERO,
3270                    aspect: wgpu::TextureAspect::All,
3271                },
3272                &level.pixels,
3273                wgpu::TexelCopyBufferLayout {
3274                    offset: 0,
3275                    bytes_per_row: Some(level.width * 4),
3276                    rows_per_image: Some(level.height),
3277                },
3278                wgpu::Extent3d {
3279                    width: level.width,
3280                    height: level.height,
3281                    depth_or_array_layers: 1,
3282                },
3283            );
3284        }
3285    }
3286
3287    fn ensure_image_bind_group(
3288        &mut self,
3289        key: ImageBindGroupKey,
3290        image: &RegisteredImage,
3291    ) -> Result<wgpu::BindGroup> {
3292        let mipmapped = !image.is_svg() && image.mipmaps_enabled();
3293        let texture_key = ImageTextureCacheKey {
3294            handle: key.handle,
3295            raster_size: image.is_svg().then_some(key.raster_size),
3296            mipmapped,
3297        };
3298        if let Some(cached) = self.image_cache.get_mut(&texture_key) {
3299            cached.last_used_frame = self.frames_rendered;
3300            if Self::registered_image_data_identity_eq(&cached.image, image) {
3301                return Ok(Self::image_bind_group_for_sampling(cached, key.sampling));
3302            }
3303        }
3304
3305        let rasterized;
3306        let upload_image = if image.is_svg() {
3307            rasterized = image
3308                .rasterize_svg_at_size(key.raster_size.width, key.raster_size.height)?
3309                .ok_or_else(|| Error::new("registered SVG lost its retained vector source"))?;
3310            &rasterized
3311        } else {
3312            image
3313        };
3314
3315        if let Some(cached) = self.image_cache.get_mut(&texture_key)
3316            && cached.texture.width() == upload_image.width()
3317            && cached.texture.height() == upload_image.height()
3318            && cached.image.format() == image.format()
3319        {
3320            let shared = self
3321                .shared
3322                .as_ref()
3323                .expect("renderer shared state initialized");
3324            Self::write_registered_image_texture(
3325                &shared.queue,
3326                &cached.texture,
3327                upload_image,
3328                mipmapped,
3329            );
3330            cached.image = image.clone();
3331            return Ok(Self::image_bind_group_for_sampling(cached, key.sampling));
3332        }
3333
3334        let shared = self
3335            .shared
3336            .as_ref()
3337            .expect("renderer shared state initialized");
3338        let texture_format = match upload_image.format() {
3339            RegisteredImageFormat::Rgba8 => wgpu::TextureFormat::Rgba8UnormSrgb,
3340        };
3341        let mip_level_count = if mipmapped {
3342            image_mip_level_count(upload_image.width(), upload_image.height())
3343        } else {
3344            1
3345        };
3346        let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
3347            label: Some("SUI image texture"),
3348            size: wgpu::Extent3d {
3349                width: upload_image.width(),
3350                height: upload_image.height(),
3351                depth_or_array_layers: 1,
3352            },
3353            mip_level_count,
3354            sample_count: 1,
3355            dimension: wgpu::TextureDimension::D2,
3356            format: texture_format,
3357            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
3358            view_formats: &[],
3359        });
3360        Self::write_registered_image_texture(&shared.queue, &texture, upload_image, mipmapped);
3361        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
3362        let linear_bind_group =
3363            Self::create_image_bind_group(shared, &view, &shared.image_linear_sampler);
3364        let nearest_bind_group =
3365            Self::create_image_bind_group(shared, &view, &shared.image_nearest_sampler);
3366        let bind_group = match key.sampling {
3367            ImageSampling::Nearest => nearest_bind_group.clone(),
3368            ImageSampling::Linear => linear_bind_group.clone(),
3369        };
3370
3371        self.image_cache.insert(
3372            texture_key,
3373            CachedImageTexture {
3374                texture,
3375                _view: view,
3376                linear_bind_group,
3377                nearest_bind_group,
3378                image: image.clone(),
3379                last_used_frame: self.frames_rendered,
3380            },
3381        );
3382
3383        Ok(bind_group)
3384    }
3385
3386    fn ensure_external_image_bind_group(
3387        &mut self,
3388        handle: ImageHandle,
3389        sampling: ImageSampling,
3390        descriptor: RegisteredExternalImage,
3391    ) -> Result<wgpu::BindGroup> {
3392        let entry = self
3393            .external_texture_registry
3394            .as_ref()
3395            .and_then(|registry| registry.resolve(handle))
3396            .ok_or_else(|| {
3397                Error::new(format!(
3398                    "external image handle {} has no WGPU texture registered",
3399                    handle.get()
3400                ))
3401            })?;
3402        if entry.descriptor != descriptor {
3403            return Err(Error::new(format!(
3404                "external image handle {} scene dimensions {}x{} do not match registered texture dimensions {}x{}",
3405                handle.get(),
3406                descriptor.width(),
3407                descriptor.height(),
3408                entry.descriptor.width(),
3409                entry.descriptor.height()
3410            )));
3411        }
3412
3413        if let Some(cached) = self.external_image_cache.get(&handle)
3414            && cached.binding_revision == entry.binding_revision
3415        {
3416            return Ok(Self::external_image_bind_group_for_sampling(
3417                cached, sampling,
3418            ));
3419        }
3420
3421        let shared = self
3422            .shared
3423            .as_ref()
3424            .expect("renderer shared state initialized");
3425        let linear_bind_group =
3426            Self::create_image_bind_group(shared, &entry.view, &shared.image_linear_sampler);
3427        let nearest_bind_group =
3428            Self::create_image_bind_group(shared, &entry.view, &shared.image_nearest_sampler);
3429        let bind_group = match sampling {
3430            ImageSampling::Nearest => nearest_bind_group.clone(),
3431            ImageSampling::Linear => linear_bind_group.clone(),
3432        };
3433        self.external_image_cache.insert(
3434            handle,
3435            CachedExternalTextureBindGroup {
3436                binding_revision: entry.binding_revision,
3437                linear_bind_group,
3438                nearest_bind_group,
3439            },
3440        );
3441        Ok(bind_group)
3442    }
3443
3444    fn image_bind_group_for_sampling(
3445        cached: &CachedImageTexture,
3446        sampling: ImageSampling,
3447    ) -> wgpu::BindGroup {
3448        match sampling {
3449            ImageSampling::Nearest => cached.nearest_bind_group.clone(),
3450            ImageSampling::Linear => cached.linear_bind_group.clone(),
3451        }
3452    }
3453
3454    fn external_image_bind_group_for_sampling(
3455        cached: &CachedExternalTextureBindGroup,
3456        sampling: ImageSampling,
3457    ) -> wgpu::BindGroup {
3458        match sampling {
3459            ImageSampling::Nearest => cached.nearest_bind_group.clone(),
3460            ImageSampling::Linear => cached.linear_bind_group.clone(),
3461        }
3462    }
3463
3464    fn create_image_bind_group(
3465        shared: &SharedRenderer,
3466        view: &wgpu::TextureView,
3467        sampler: &wgpu::Sampler,
3468    ) -> wgpu::BindGroup {
3469        shared.device.create_bind_group(&wgpu::BindGroupDescriptor {
3470            label: Some("SUI image bind group"),
3471            layout: &shared.image_bind_group_layout,
3472            entries: &[
3473                wgpu::BindGroupEntry {
3474                    binding: 0,
3475                    resource: wgpu::BindingResource::Sampler(sampler),
3476                },
3477                wgpu::BindGroupEntry {
3478                    binding: 1,
3479                    resource: wgpu::BindingResource::TextureView(view),
3480                },
3481            ],
3482        })
3483    }
3484
3485    fn ensure_text_atlas_bind_group(
3486        &mut self,
3487        text_engine: &mut TextEngine,
3488        collect_stats: bool,
3489    ) -> Result<(wgpu::BindGroup, TextAtlasBindGroupStats)> {
3490        let total_started = collect_stats.then(Instant::now);
3491        let upload_copy_started = collect_stats.then(Instant::now);
3492        let uploads = text_engine.take_atlas_uploads();
3493        let page_size = text_engine.atlas.page_size();
3494        let page_count = text_engine.atlas.page_count() as u32;
3495        let mut stats = TextAtlasBindGroupStats {
3496            upload_copy_time_us: upload_copy_started
3497                .map(|started| started.elapsed().as_micros() as u64)
3498                .unwrap_or(0),
3499            upload_bytes: if collect_stats {
3500                uploads
3501                    .iter()
3502                    .map(|(_, upload)| upload.pixels.len() as u64)
3503                    .sum()
3504            } else {
3505                0
3506            },
3507            ..TextAtlasBindGroupStats::default()
3508        };
3509
3510        // One persistent texture array; each atlas page is a layer. Dirty rects are written
3511        // directly to their layer -- no ring rotation, no full-texture forward-copy.
3512        self.ensure_text_atlas_array(page_size, page_count)?;
3513
3514        if !uploads.is_empty() {
3515            let shared = self
3516                .shared
3517                .as_ref()
3518                .expect("renderer shared state initialized");
3519            let cached = self
3520                .text_atlas_array
3521                .as_ref()
3522                .expect("text atlas array created above");
3523            let upload_write_started = collect_stats.then(Instant::now);
3524            for (page_index, upload) in &uploads {
3525                shared.queue.write_texture(
3526                    wgpu::TexelCopyTextureInfo {
3527                        texture: &cached.texture,
3528                        mip_level: 0,
3529                        origin: wgpu::Origin3d {
3530                            x: upload.offset.0,
3531                            y: upload.offset.1,
3532                            z: *page_index as u32,
3533                        },
3534                        aspect: wgpu::TextureAspect::All,
3535                    },
3536                    &upload.pixels,
3537                    wgpu::TexelCopyBufferLayout {
3538                        offset: 0,
3539                        bytes_per_row: Some(upload.extent.0 * 4),
3540                        rows_per_image: Some(upload.extent.1),
3541                    },
3542                    wgpu::Extent3d {
3543                        width: upload.extent.0,
3544                        height: upload.extent.1,
3545                        depth_or_array_layers: 1,
3546                    },
3547                );
3548            }
3549            stats.upload_write_time_us = upload_write_started
3550                .map(|started| started.elapsed().as_micros() as u64)
3551                .unwrap_or(0);
3552        }
3553
3554        let bind_group = self
3555            .text_atlas_array
3556            .as_ref()
3557            .map(|cached| cached.bind_group.clone())
3558            .ok_or_else(|| Error::new("text atlas bind group requested before any atlas upload"))?;
3559        stats.total_time_us = total_started
3560            .map(|started| started.elapsed().as_micros() as u64)
3561            .unwrap_or(0);
3562        Ok((bind_group, stats))
3563    }
3564
3565    fn ensure_text_atlas_array(
3566        &mut self,
3567        page_size: (u32, u32),
3568        required_layers: u32,
3569    ) -> Result<()> {
3570        // Allocate only as many layers as there are live pages, growing on demand up to the page
3571        // budget. This keeps the common single-page case at one 16 MB layer instead of committing
3572        // the whole budget up front.
3573        let required_layers = required_layers.clamp(1, TEXT_ATLAS_MAX_PAGES as u32);
3574        if self
3575            .text_atlas_array
3576            .as_ref()
3577            .is_some_and(|cached| cached.size == page_size && cached.layers >= required_layers)
3578        {
3579            return Ok(());
3580        }
3581
3582        let shared = self
3583            .shared
3584            .as_ref()
3585            .expect("renderer shared state initialized before text atlas texture setup");
3586
3587        let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
3588            label: Some("SUI text atlas array texture"),
3589            size: wgpu::Extent3d {
3590                width: page_size.0,
3591                height: page_size.1,
3592                depth_or_array_layers: required_layers,
3593            },
3594            mip_level_count: 1,
3595            sample_count: 1,
3596            dimension: wgpu::TextureDimension::D2,
3597            format: wgpu::TextureFormat::Rgba8Unorm,
3598            usage: wgpu::TextureUsages::TEXTURE_BINDING
3599                | wgpu::TextureUsages::COPY_DST
3600                | wgpu::TextureUsages::COPY_SRC,
3601            view_formats: &[],
3602        });
3603        let view = texture.create_view(&wgpu::TextureViewDescriptor {
3604            dimension: Some(wgpu::TextureViewDimension::D2Array),
3605            ..Default::default()
3606        });
3607        let bind_group = shared.device.create_bind_group(&wgpu::BindGroupDescriptor {
3608            label: Some("SUI text atlas array bind group"),
3609            layout: &shared.text_atlas_array_bind_group_layout,
3610            entries: &[
3611                wgpu::BindGroupEntry {
3612                    binding: 0,
3613                    resource: wgpu::BindingResource::Sampler(&shared.text_atlas_sampler),
3614                },
3615                wgpu::BindGroupEntry {
3616                    binding: 1,
3617                    resource: wgpu::BindingResource::TextureView(&view),
3618                },
3619            ],
3620        });
3621
3622        // Growing an existing array of the same page size: copy the already-populated layers
3623        // forward so their glyphs survive (their CPU dirty state was cleared after first upload).
3624        if let Some(old) = self.text_atlas_array.as_ref()
3625            && old.size == page_size
3626        {
3627            let mut encoder =
3628                shared
3629                    .device
3630                    .create_command_encoder(&wgpu::CommandEncoderDescriptor {
3631                        label: Some("SUI text atlas array grow copy"),
3632                    });
3633            encoder.copy_texture_to_texture(
3634                wgpu::TexelCopyTextureInfo {
3635                    texture: &old.texture,
3636                    mip_level: 0,
3637                    origin: wgpu::Origin3d::ZERO,
3638                    aspect: wgpu::TextureAspect::All,
3639                },
3640                wgpu::TexelCopyTextureInfo {
3641                    texture: &texture,
3642                    mip_level: 0,
3643                    origin: wgpu::Origin3d::ZERO,
3644                    aspect: wgpu::TextureAspect::All,
3645                },
3646                wgpu::Extent3d {
3647                    width: page_size.0,
3648                    height: page_size.1,
3649                    depth_or_array_layers: old.layers,
3650                },
3651            );
3652            shared.queue.submit([encoder.finish()]);
3653        }
3654
3655        self.text_atlas_array = Some(CachedTextAtlasTexture {
3656            texture,
3657            _view: view,
3658            bind_group,
3659            size: page_size,
3660            layers: required_layers,
3661        });
3662
3663        Ok(())
3664    }
3665
3666    fn prepare_analytic_path_resources(
3667        &mut self,
3668        analytic_paths: HashMap<u64, Arc<AnalyticPathCpuData>>,
3669        collect_stats: bool,
3670    ) -> Result<(
3671        Option<PreparedAnalyticPathResources>,
3672        AnalyticPathBindGroupStats,
3673    )> {
3674        if analytic_paths.is_empty() {
3675            return Ok((None, AnalyticPathBindGroupStats::default()));
3676        }
3677
3678        let total_started = collect_stats.then(Instant::now);
3679        let shared = self
3680            .shared
3681            .as_ref()
3682            .expect("renderer shared state initialized");
3683        let mut slots = HashMap::with_capacity(analytic_paths.len());
3684        let mut pending = Vec::new();
3685        let mut visible_signatures = Vec::with_capacity(analytic_paths.len());
3686        let mut sorted_paths: Vec<_> = analytic_paths.into_iter().collect();
3687        sorted_paths.sort_unstable_by_key(|(signature, _)| *signature);
3688
3689        for (signature, path) in sorted_paths {
3690            visible_signatures.push(signature);
3691            if let Some(cached) = self.analytic_path_cache.get_mut(&signature) {
3692                cached.last_used_frame = self.frames_rendered;
3693                slots.insert(signature, cached.slot);
3694            } else {
3695                pending.push((signature, path));
3696            }
3697        }
3698
3699        let mut stats = AnalyticPathBindGroupStats {
3700            miss_count: if collect_stats { pending.len() } else { 0 },
3701            ..AnalyticPathBindGroupStats::default()
3702        };
3703        let needs_rebuild = if self
3704            .frame_resources
3705            .analytic_path_arena
3706            .bind_group
3707            .is_none()
3708        {
3709            true
3710        } else if pending.is_empty() {
3711            false
3712        } else {
3713            let required_slots =
3714                self.frame_resources.analytic_path_arena.used_slots + pending.len();
3715            let required_contours = self.frame_resources.analytic_path_arena.used_contours
3716                + pending
3717                    .iter()
3718                    .map(|(_, path)| path.contours.len())
3719                    .sum::<usize>();
3720            let required_points = self.frame_resources.analytic_path_arena.used_points
3721                + pending
3722                    .iter()
3723                    .map(|(_, path)| path.points.len())
3724                    .sum::<usize>();
3725            !self.frame_resources.analytic_path_arena.has_capacity(
3726                required_slots,
3727                required_contours,
3728                required_points,
3729            )
3730        };
3731
3732        if needs_rebuild {
3733            let mut cached_entries: Vec<_> = self
3734                .analytic_path_cache
3735                .iter()
3736                .map(|(signature, entry)| {
3737                    (
3738                        *signature,
3739                        entry.slot,
3740                        entry.last_used_frame,
3741                        entry.data.clone(),
3742                    )
3743                })
3744                .collect();
3745            cached_entries.sort_unstable_by_key(|(_, slot, _, _)| *slot);
3746
3747            let total_slots = cached_entries.len() + pending.len();
3748            let total_contours = cached_entries
3749                .iter()
3750                .map(|(_, _, _, data)| data.contours.len())
3751                .sum::<usize>()
3752                + pending
3753                    .iter()
3754                    .map(|(_, data)| data.contours.len())
3755                    .sum::<usize>();
3756            let total_points = cached_entries
3757                .iter()
3758                .map(|(_, _, _, data)| data.points.len())
3759                .sum::<usize>()
3760                + pending
3761                    .iter()
3762                    .map(|(_, data)| data.points.len())
3763                    .sum::<usize>();
3764
3765            self.frame_resources.analytic_path_arena.ensure_capacity(
3766                &shared.device,
3767                &shared.analytic_path_bind_group_layout,
3768                total_slots,
3769                total_contours,
3770                total_points,
3771            );
3772
3773            let mut meta_data = Vec::with_capacity(total_slots);
3774            let mut contour_data = Vec::with_capacity(total_contours);
3775            let mut point_data = Vec::with_capacity(total_points);
3776            let mut rebuilt_cache = HashMap::with_capacity(total_slots);
3777
3778            for (signature, _, last_used_frame, data) in cached_entries {
3779                let slot = meta_data.len() as u32;
3780                let contour_start = contour_data.len() as u32;
3781                let point_start = point_data.len() as u32;
3782                meta_data.push(data.meta(contour_start, point_start));
3783                contour_data.extend_from_slice(&data.contours);
3784                point_data.extend_from_slice(&data.points);
3785                rebuilt_cache.insert(
3786                    signature,
3787                    CachedAnalyticPathGpu {
3788                        data,
3789                        slot,
3790                        last_used_frame,
3791                    },
3792                );
3793            }
3794
3795            for (signature, data) in pending {
3796                let slot = meta_data.len() as u32;
3797                let contour_start = contour_data.len() as u32;
3798                let point_start = point_data.len() as u32;
3799                meta_data.push(data.meta(contour_start, point_start));
3800                contour_data.extend_from_slice(&data.contours);
3801                point_data.extend_from_slice(&data.points);
3802                rebuilt_cache.insert(
3803                    signature,
3804                    CachedAnalyticPathGpu {
3805                        data,
3806                        slot,
3807                        last_used_frame: self.frames_rendered,
3808                    },
3809                );
3810            }
3811
3812            let meta_buffer = self
3813                .frame_resources
3814                .analytic_path_arena
3815                .meta_buffer
3816                .as_ref()
3817                .expect("analytic path arena metadata buffer initialized");
3818            let contour_buffer = self
3819                .frame_resources
3820                .analytic_path_arena
3821                .contour_buffer
3822                .as_ref()
3823                .expect("analytic path arena contour buffer initialized");
3824            let point_buffer = self
3825                .frame_resources
3826                .analytic_path_arena
3827                .point_buffer
3828                .as_ref()
3829                .expect("analytic path arena point buffer initialized");
3830            if !meta_data.is_empty() {
3831                shared
3832                    .queue
3833                    .write_buffer(meta_buffer, 0, bytemuck::cast_slice(&meta_data));
3834            }
3835            if !contour_data.is_empty() {
3836                shared
3837                    .queue
3838                    .write_buffer(contour_buffer, 0, bytemuck::cast_slice(&contour_data));
3839            }
3840            if !point_data.is_empty() {
3841                shared
3842                    .queue
3843                    .write_buffer(point_buffer, 0, bytemuck::cast_slice(&point_data));
3844            }
3845
3846            if collect_stats {
3847                stats.upload_bytes = (meta_data.len() * std::mem::size_of::<AnalyticPathMetaGpu>()
3848                    + contour_data.len() * std::mem::size_of::<AnalyticContourGpu>()
3849                    + point_data.len() * std::mem::size_of::<AnalyticPointGpu>())
3850                    as u64;
3851            }
3852
3853            self.analytic_path_cache = rebuilt_cache;
3854            self.frame_resources.analytic_path_arena.used_slots = meta_data.len();
3855            self.frame_resources.analytic_path_arena.used_contours = contour_data.len();
3856            self.frame_resources.analytic_path_arena.used_points = point_data.len();
3857
3858            for signature in visible_signatures {
3859                let slot = self
3860                    .analytic_path_cache
3861                    .get(&signature)
3862                    .expect("visible analytic path cached after arena rebuild")
3863                    .slot;
3864                slots.insert(signature, slot);
3865            }
3866        } else if !pending.is_empty() {
3867            let meta_buffer = self
3868                .frame_resources
3869                .analytic_path_arena
3870                .meta_buffer
3871                .as_ref()
3872                .expect("analytic path arena metadata buffer initialized");
3873            let contour_buffer = self
3874                .frame_resources
3875                .analytic_path_arena
3876                .contour_buffer
3877                .as_ref()
3878                .expect("analytic path arena contour buffer initialized");
3879            let point_buffer = self
3880                .frame_resources
3881                .analytic_path_arena
3882                .point_buffer
3883                .as_ref()
3884                .expect("analytic path arena point buffer initialized");
3885            let base_slot = self.frame_resources.analytic_path_arena.used_slots as u32;
3886            let base_contour = self.frame_resources.analytic_path_arena.used_contours as u32;
3887            let base_point = self.frame_resources.analytic_path_arena.used_points as u32;
3888            let total_contours = pending
3889                .iter()
3890                .map(|(_, data)| data.contours.len())
3891                .sum::<usize>();
3892            let total_points = pending
3893                .iter()
3894                .map(|(_, data)| data.points.len())
3895                .sum::<usize>();
3896            let mut meta_data = Vec::with_capacity(pending.len());
3897            let mut contour_data = Vec::with_capacity(total_contours);
3898            let mut point_data = Vec::with_capacity(total_points);
3899
3900            for (signature, data) in pending {
3901                let slot = base_slot + meta_data.len() as u32;
3902                let contour_start = base_contour + contour_data.len() as u32;
3903                let point_start = base_point + point_data.len() as u32;
3904                meta_data.push(data.meta(contour_start, point_start));
3905                contour_data.extend_from_slice(&data.contours);
3906                point_data.extend_from_slice(&data.points);
3907                if collect_stats {
3908                    stats.upload_bytes += data.byte_size() as u64;
3909                }
3910                slots.insert(signature, slot);
3911                self.analytic_path_cache.insert(
3912                    signature,
3913                    CachedAnalyticPathGpu {
3914                        data,
3915                        slot,
3916                        last_used_frame: self.frames_rendered,
3917                    },
3918                );
3919            }
3920
3921            if !meta_data.is_empty() {
3922                let meta_offset =
3923                    base_slot as u64 * std::mem::size_of::<AnalyticPathMetaGpu>() as u64;
3924                shared.queue.write_buffer(
3925                    meta_buffer,
3926                    meta_offset,
3927                    bytemuck::cast_slice(&meta_data),
3928                );
3929            }
3930            if !contour_data.is_empty() {
3931                let contour_offset =
3932                    base_contour as u64 * std::mem::size_of::<AnalyticContourGpu>() as u64;
3933                shared.queue.write_buffer(
3934                    contour_buffer,
3935                    contour_offset,
3936                    bytemuck::cast_slice(&contour_data),
3937                );
3938            }
3939            if !point_data.is_empty() {
3940                let point_offset =
3941                    base_point as u64 * std::mem::size_of::<AnalyticPointGpu>() as u64;
3942                shared.queue.write_buffer(
3943                    point_buffer,
3944                    point_offset,
3945                    bytemuck::cast_slice(&point_data),
3946                );
3947            }
3948
3949            self.frame_resources.analytic_path_arena.used_slots += meta_data.len();
3950            self.frame_resources.analytic_path_arena.used_contours += contour_data.len();
3951            self.frame_resources.analytic_path_arena.used_points += point_data.len();
3952        }
3953
3954        let bind_group = self
3955            .frame_resources
3956            .analytic_path_arena
3957            .bind_group
3958            .as_ref()
3959            .expect("analytic path arena bind group initialized")
3960            .clone();
3961        stats.total_time_us = total_started
3962            .map(|started| started.elapsed().as_micros() as u64)
3963            .unwrap_or(0);
3964        Ok((
3965            Some(PreparedAnalyticPathResources { bind_group, slots }),
3966            stats,
3967        ))
3968    }
3969
3970    fn create_surface_state(
3971        &mut self,
3972        window: Arc<Window>,
3973        size: (u32, u32),
3974    ) -> Result<SurfaceState> {
3975        let surface = self
3976            .instance
3977            .create_surface(Arc::clone(&window))
3978            .map_err(|error| Error::new(format!("failed to create wgpu surface: {error}")))?;
3979        self.ensure_shared(Some(&surface))?;
3980
3981        let shared = self
3982            .shared
3983            .as_ref()
3984            .expect("renderer shared state initialized");
3985        let default_capabilities = DisplayCapabilities::default();
3986        let default_color_management = ColorManagementMode::default();
3987        let available_surface_formats = surface.get_capabilities(&shared.adapter).formats;
3988        let (config, output_strategy) = configure_surface(
3989            &surface,
3990            &shared.adapter,
3991            &shared.device,
3992            size,
3993            self.vsync_enabled,
3994            default_capabilities.clone(),
3995            default_color_management,
3996        )?;
3997
3998        Ok(SurfaceState {
3999            window,
4000            surface,
4001            config,
4002            display_capabilities: default_capabilities,
4003            color_management: default_color_management,
4004            output_strategy,
4005            available_surface_formats,
4006        })
4007    }
4008}
4009
4010/// Build the renderer's wgpu instance with the GL backend left out unless the
4011/// environment explicitly asks for it (`WGPU_BACKEND=gl`).
4012///
4013/// Initializing the GL/WGL backend spins up a device thread per instance, and
4014/// concurrent initialization — one renderer per test in the headless harness —
4015/// deadlocks inside some Windows OpenGL drivers (observed as all test threads
4016/// parked on `wgl::create_instance_device` results while the creator threads
4017/// sat inside `nvoglv64.dll`; the same churn also produces access-violation
4018/// crashes). The primary native backends (Vulkan/Metal/DX12) cover every
4019/// platform SUI supports, so GL is opt-in rather than eagerly probed.
4020fn default_wgpu_instance() -> wgpu::Instance {
4021    let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle_from_env();
4022    if std::env::var_os("WGPU_BACKEND").is_none() {
4023        descriptor.backends -= wgpu::Backends::GL;
4024    }
4025    wgpu::Instance::new(descriptor)
4026}
4027
4028impl Default for WgpuRenderer {
4029    fn default() -> Self {
4030        Self {
4031            instance: default_wgpu_instance(),
4032            feathering_enabled: false,
4033            feather_width: DEFAULT_FEATHER_WIDTH,
4034            text_render_mode: TextRenderMode::default(),
4035            text_subpixel_order: TextSubpixelOrder::default(),
4036            text_hinting: TextHinting::default(),
4037            stem_darkening: StemDarkening::default(),
4038            text_coverage_policy: TextCoveragePolicy::default(),
4039            vsync_enabled: true,
4040            runtime_feathering_override: None,
4041            runtime_text_subpixel_order_override: None,
4042            runtime_text_hinting_override: None,
4043            runtime_stem_darkening_override: None,
4044            runtime_text_coverage_policy_override: None,
4045            runtime_diagnostics_enabled: true,
4046            frames_rendered: 0,
4047            capabilities: RendererCapabilities::default(),
4048            last_frames: HashMap::new(),
4049            last_frame_stats: HashMap::new(),
4050            shared: None,
4051            text_engine: None,
4052            image_cache: HashMap::new(),
4053            external_texture_registry: None,
4054            external_image_cache: HashMap::new(),
4055            text_atlas_array: None,
4056            analytic_path_cache: HashMap::new(),
4057            compositors: HashMap::new(),
4058            surfaces: HashMap::new(),
4059            offscreen_targets: HashMap::new(),
4060            intermediate_targets: HashMap::new(),
4061            frame_resources: FrameResources::default(),
4062        }
4063    }
4064}
4065
4066impl fmt::Debug for WgpuRenderer {
4067    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4068        f.debug_struct("WgpuRenderer")
4069            .field("feathering_enabled", &self.feathering_enabled)
4070            .field("feather_width", &self.feather_width)
4071            .field("text_coverage_policy", &self.text_coverage_policy)
4072            .field("frames_rendered", &self.frames_rendered)
4073            .field("capabilities", &self.capabilities)
4074            .field("last_frame_count", &self.last_frames.len())
4075            .field("last_frame_stats_count", &self.last_frame_stats.len())
4076            .field("has_device", &self.shared.is_some())
4077            .field("surface_count", &self.surfaces.len())
4078            .finish()
4079    }
4080}
4081
4082impl FrameResources {
4083    fn ensure_stencil(&mut self, device: &wgpu::Device, size: (u32, u32)) {
4084        let needs_recreate = self
4085            .stencil
4086            .as_ref()
4087            .is_none_or(|target| target.size != size);
4088        if !needs_recreate {
4089            return;
4090        }
4091
4092        let texture = device.create_texture(&wgpu::TextureDescriptor {
4093            label: Some("SUI scene stencil"),
4094            size: wgpu::Extent3d {
4095                width: size.0,
4096                height: size.1,
4097                depth_or_array_layers: 1,
4098            },
4099            mip_level_count: 1,
4100            sample_count: 1,
4101            dimension: wgpu::TextureDimension::D2,
4102            format: STENCIL_FORMAT,
4103            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
4104            view_formats: &[],
4105        });
4106        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
4107        self.stencil = Some(StencilTarget {
4108            texture,
4109            view,
4110            size,
4111        });
4112    }
4113}
4114
4115impl AnalyticPathArena {
4116    fn has_capacity(&self, meta_count: usize, contour_count: usize, point_count: usize) -> bool {
4117        self.bind_group.is_some()
4118            && self.meta_capacity >= meta_count
4119            && self.contour_capacity >= contour_count
4120            && self.point_capacity >= point_count
4121    }
4122
4123    fn ensure_capacity(
4124        &mut self,
4125        device: &wgpu::Device,
4126        layout: &wgpu::BindGroupLayout,
4127        meta_count: usize,
4128        contour_count: usize,
4129        point_count: usize,
4130    ) {
4131        if self.has_capacity(meta_count, contour_count, point_count) {
4132            return;
4133        }
4134
4135        let meta_capacity = grow_analytic_path_capacity(self.meta_capacity, meta_count);
4136        let contour_capacity = grow_analytic_path_capacity(self.contour_capacity, contour_count);
4137        let point_capacity = grow_analytic_path_capacity(self.point_capacity, point_count);
4138
4139        let meta_buffer = device.create_buffer(&wgpu::BufferDescriptor {
4140            label: Some("SUI analytic path metadata arena"),
4141            size: analytic_path_buffer_size::<AnalyticPathMetaGpu>(meta_capacity),
4142            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
4143            mapped_at_creation: false,
4144        });
4145        let contour_buffer = device.create_buffer(&wgpu::BufferDescriptor {
4146            label: Some("SUI analytic path contour arena"),
4147            size: analytic_path_buffer_size::<AnalyticContourGpu>(contour_capacity),
4148            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
4149            mapped_at_creation: false,
4150        });
4151        let point_buffer = device.create_buffer(&wgpu::BufferDescriptor {
4152            label: Some("SUI analytic path point arena"),
4153            size: analytic_path_buffer_size::<AnalyticPointGpu>(point_capacity),
4154            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
4155            mapped_at_creation: false,
4156        });
4157        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
4158            label: Some("SUI analytic path arena bind group"),
4159            layout,
4160            entries: &[
4161                wgpu::BindGroupEntry {
4162                    binding: 0,
4163                    resource: meta_buffer.as_entire_binding(),
4164                },
4165                wgpu::BindGroupEntry {
4166                    binding: 1,
4167                    resource: contour_buffer.as_entire_binding(),
4168                },
4169                wgpu::BindGroupEntry {
4170                    binding: 2,
4171                    resource: point_buffer.as_entire_binding(),
4172                },
4173            ],
4174        });
4175
4176        self.bind_group = Some(bind_group);
4177        self.meta_buffer = Some(meta_buffer);
4178        self.contour_buffer = Some(contour_buffer);
4179        self.point_buffer = Some(point_buffer);
4180        self.meta_capacity = meta_capacity;
4181        self.contour_capacity = contour_capacity;
4182        self.point_capacity = point_capacity;
4183    }
4184}
4185
4186const SHADER_SOURCE: &str = r#"
4187struct VsOut {
4188    @builtin(position) position: vec4<f32>,
4189    @location(0) color: vec4<f32>,
4190    @location(1) local_position: vec2<f32>,
4191    @location(2) rect_params: vec4<f32>,
4192};
4193
4194@vertex
4195fn vs_main(
4196    @location(0) position: vec2<f32>,
4197    @location(1) color: vec4<f32>,
4198    @location(2) tex_coords: vec2<f32>,
4199    @location(3) shader_params: vec4<f32>,
4200) -> VsOut {
4201    var out: VsOut;
4202    out.position = vec4<f32>(position, 0.0, 1.0);
4203    out.color = color;
4204    out.local_position = tex_coords;
4205    out.rect_params = shader_params;
4206    return out;
4207}
4208
4209@fragment
4210fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
4211    let feather_width = in.rect_params.z;
4212    let p = in.local_position;
4213    let derivative_width = length(vec2<f32>(fwidth(p.x), fwidth(p.y)));
4214    if feather_width > 0.0 {
4215        let size = max(in.rect_params.xy, vec2<f32>(0.0));
4216        let outside_distance = max(
4217            max(-p.x, p.x - size.x),
4218            max(-p.y, p.y - size.y),
4219        );
4220        let feather = max(feather_width, derivative_width);
4221        let coverage = select(
4222            clamp(1.0 - (outside_distance / max(feather, 1e-4)), 0.0, 1.0),
4223            1.0,
4224            outside_distance <= 0.0,
4225        );
4226        return vec4<f32>(in.color.rgb, in.color.a * coverage);
4227    }
4228    return in.color;
4229}
4230"#;
4231
4232const TEXTURED_SHADER_SOURCE: &str = r#"
4233struct VsOut {
4234    @builtin(position) position: vec4<f32>,
4235    @location(0) color: vec4<f32>,
4236    @location(1) tex_coords: vec2<f32>,
4237};
4238
4239@group(0) @binding(0)
4240var image_sampler: sampler;
4241
4242@group(0) @binding(1)
4243var image_texture: texture_2d<f32>;
4244
4245@vertex
4246fn vs_main(
4247    @location(0) position: vec2<f32>,
4248    @location(1) color: vec4<f32>,
4249    @location(2) tex_coords: vec2<f32>,
4250) -> VsOut {
4251    var out: VsOut;
4252    out.position = vec4<f32>(position, 0.0, 1.0);
4253    out.color = color;
4254    out.tex_coords = tex_coords;
4255    return out;
4256}
4257
4258@fragment
4259fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
4260    return textureSample(image_texture, image_sampler, in.tex_coords) * in.color;
4261}
4262"#;
4263
4264const WIDGET_SHADER_SOURCE: &str = r#"
4265struct VsOut {
4266    @builtin(position) position: vec4<f32>,
4267    @location(0) metadata: vec4<f32>,
4268    @location(1) uv: vec2<f32>,
4269    @location(2) params: vec4<f32>,
4270};
4271
4272const KIND_COLOR_WHEEL: u32 = 0u;
4273const KIND_HUE_BAR: u32 = 1u;
4274const KIND_SATURATION_VALUE_PLANE: u32 = 2u;
4275const KIND_SATURATION_BAR: u32 = 3u;
4276const KIND_VALUE_BAR: u32 = 4u;
4277const KIND_ALPHA_BAR: u32 = 5u;
4278const KIND_RGB_CHANNEL_BAR: u32 = 6u;
4279const TAU: f32 = 6.283185307179586;
4280const COLOR_SPACE_LINEAR_SRGB: u32 = 1u;
4281const COLOR_SPACE_DISPLAY_P3: u32 = 2u;
4282const COLOR_SPACE_LINEAR_DISPLAY_P3: u32 = 3u;
4283
4284@vertex
4285fn vs_main(
4286    @location(0) position: vec2<f32>,
4287    @location(1) metadata: vec4<f32>,
4288    @location(2) uv: vec2<f32>,
4289    @location(3) params: vec4<f32>,
4290) -> VsOut {
4291    var out: VsOut;
4292    out.position = vec4<f32>(position, 0.0, 1.0);
4293    out.metadata = metadata;
4294    out.uv = uv;
4295    out.params = params;
4296    return out;
4297}
4298
4299fn srgb_transfer_to_linear(channel: f32) -> f32 {
4300    if channel <= 0.04045 {
4301        return channel / 12.92;
4302    }
4303    return pow((channel + 0.055) / 1.055, 2.4);
4304}
4305
4306fn color_space_index(space: f32) -> u32 {
4307    return u32(space + 0.5);
4308}
4309
4310fn to_linear_srgb(rgb: vec3<f32>, space: f32) -> vec3<f32> {
4311    let index = color_space_index(space);
4312    var linear = rgb;
4313    if index != COLOR_SPACE_LINEAR_SRGB && index != COLOR_SPACE_LINEAR_DISPLAY_P3 {
4314        linear = vec3<f32>(
4315            srgb_transfer_to_linear(rgb.r),
4316            srgb_transfer_to_linear(rgb.g),
4317            srgb_transfer_to_linear(rgb.b),
4318        );
4319    }
4320    if index == COLOR_SPACE_DISPLAY_P3 || index == COLOR_SPACE_LINEAR_DISPLAY_P3 {
4321        return vec3<f32>(
4322            1.2249402 * linear.r - 0.22494018 * linear.g,
4323            -0.042056955 * linear.r + 1.042057 * linear.g,
4324            -0.019637555 * linear.r - 0.07863604 * linear.g + 1.0982736 * linear.b,
4325        );
4326    }
4327    return linear;
4328}
4329
4330fn hsv_to_rgb(hue_value: f32, saturation: f32, value: f32) -> vec3<f32> {
4331    let hue = fract(hue_value) * 6.0;
4332    let sector = floor(hue);
4333    let fraction = hue - sector;
4334    let p = value * (1.0 - saturation);
4335    let q = value * (1.0 - fraction * saturation);
4336    let t = value * (1.0 - (1.0 - fraction) * saturation);
4337    if sector < 1.0 {
4338        return vec3<f32>(value, t, p);
4339    }
4340    if sector < 2.0 {
4341        return vec3<f32>(q, value, p);
4342    }
4343    if sector < 3.0 {
4344        return vec3<f32>(p, value, t);
4345    }
4346    if sector < 4.0 {
4347        return vec3<f32>(p, q, value);
4348    }
4349    if sector < 5.0 {
4350        return vec3<f32>(t, p, value);
4351    }
4352    return vec3<f32>(value, p, q);
4353}
4354
4355fn hsv_to_linear_color(space: f32, hue: f32, saturation: f32, value: f32, alpha: f32) -> vec4<f32> {
4356    return vec4<f32>(to_linear_srgb(hsv_to_rgb(hue, saturation, value), space), clamp(alpha, 0.0, 1.0));
4357}
4358
4359fn hdr_slider_to_value(t: f32, max_value: f32) -> f32 {
4360    if max_value <= 1.0001 {
4361        return t;
4362    }
4363    if t <= 0.5 {
4364        return t * 2.0;
4365    }
4366    return pow(max(max_value, 1.0001), (t - 0.5) / 0.5);
4367}
4368
4369@fragment
4370fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
4371    let kind = u32(in.metadata.x + 0.5);
4372    let space = in.metadata.y;
4373    let u = clamp(in.uv.x, 0.0, 1.0);
4374    let v = clamp(in.uv.y, 0.0, 1.0);
4375
4376    if kind == KIND_COLOR_WHEEL {
4377        let centered = vec2<f32>(u * 2.0 - 1.0, v * 2.0 - 1.0);
4378        let distance = length(centered);
4379        let edge = 0.01;
4380        let alpha = smoothstep(0.55, 0.55 + edge, distance) * (1.0 - smoothstep(1.0 - edge, 1.0, distance));
4381        let hue = fract((atan2(centered.y, centered.x) / TAU) + 1.0);
4382        let color = hsv_to_linear_color(0.0, hue, 1.0, 1.0, alpha);
4383        return color;
4384    }
4385
4386    if kind == KIND_HUE_BAR {
4387        return hsv_to_linear_color(0.0, u, 1.0, 1.0, 1.0);
4388    }
4389
4390    if kind == KIND_SATURATION_VALUE_PLANE {
4391        let hue = in.metadata.z;
4392        let max_value = in.metadata.w;
4393        let value = hdr_slider_to_value(1.0 - v, max_value);
4394        return hsv_to_linear_color(space, hue, u, value, 1.0);
4395    }
4396
4397    if kind == KIND_SATURATION_BAR {
4398        let hue = in.metadata.z;
4399        let value = in.metadata.w;
4400        return hsv_to_linear_color(space, hue, u, value, 1.0);
4401    }
4402
4403    if kind == KIND_VALUE_BAR {
4404        let hue = in.metadata.z;
4405        let saturation = in.metadata.w;
4406        let value = hdr_slider_to_value(u, in.params.x);
4407        return hsv_to_linear_color(space, hue, saturation, value, 1.0);
4408    }
4409
4410    if kind == KIND_ALPHA_BAR {
4411        let alpha = u;
4412        return vec4<f32>(to_linear_srgb(in.params.rgb, space), alpha);
4413    }
4414
4415    if kind == KIND_RGB_CHANNEL_BAR {
4416        let channel = u32(in.metadata.z + 0.5);
4417        let max_value = in.metadata.w;
4418        var rgb = in.params.rgb;
4419        if channel == 0u {
4420            rgb.r = max_value * u;
4421        } else if channel == 1u {
4422            rgb.g = max_value * u;
4423        } else {
4424            rgb.b = max_value * u;
4425        }
4426        return vec4<f32>(to_linear_srgb(rgb, space), 1.0);
4427    }
4428
4429    return vec4<f32>(0.0, 0.0, 0.0, 0.0);
4430}
4431"#;
4432
4433const ROUNDED_RECT_SHADER_SOURCE: &str = r#"
4434const RR_MODE_FILL: f32 = 0.0;
4435const RR_MODE_SHADOW: f32 = 1.0;
4436struct VsOut {
4437    @builtin(position) position: vec4<f32>,
4438    @location(0) color: vec4<f32>, @location(1) local: vec2<f32>,
4439    @location(2) p0: vec4<f32>, @location(3) radii: vec4<f32>,
4440    @location(4) p2: vec4<f32>, @location(5) border_color: vec4<f32>,
4441};
4442@vertex
4443fn vs_main(@location(0) position: vec2<f32>, @location(1) color: vec4<f32>,
4444    @location(2) local: vec2<f32>, @location(3) p0: vec4<f32>, @location(4) radii: vec4<f32>,
4445    @location(5) p2: vec4<f32>, @location(6) border_color: vec4<f32>) -> VsOut {
4446    var out: VsOut; out.position = vec4<f32>(position, 0.0, 1.0);
4447    out.color = color; out.local = local; out.p0 = p0; out.radii = radii; out.p2 = p2; out.border_color = border_color;
4448    return out;
4449}
4450fn sd_round_box(p: vec2<f32>, b: vec2<f32>, r: vec4<f32>) -> f32 {
4451    let rt = select(r.x, r.y, p.x > 0.0);
4452    let rb = select(r.w, r.z, p.x > 0.0);
4453    let rr = select(rt, rb, p.y > 0.0);
4454    let q = abs(p) - b + vec2<f32>(rr, rr);
4455    return min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0))) - rr;
4456}
4457fn gaussian_box_coverage(p: vec2<f32>, b: vec2<f32>, r: vec4<f32>, sigma: f32) -> f32 {
4458    let s = max(sigma, 1e-3); let d = sd_round_box(p, b, r); let edge = 1.4142136 * s;
4459    return 1.0 - smoothstep(-edge, edge, d);
4460}
4461@fragment
4462fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
4463    let half = max(in.p0.xy, vec2<f32>(0.0));
4464    let mode = in.p0.z; let feather = in.p0.w;
4465    let radii = clamp(in.radii, vec4<f32>(0.0), vec4<f32>(min(half.x, half.y)));
4466    let p = in.local;
4467    // Derivatives must execute in uniform control flow on WebGPU. Compute the
4468    // fill edge before selecting the shadow path; the shadow branch simply
4469    // leaves the derivative result unused.
4470    let d = sd_round_box(p, half, radii);
4471    let aa = max(feather, fwidth(d));
4472    if (mode == RR_MODE_SHADOW) {
4473        let sigma = in.p2.y;
4474        let pp = p - vec2<f32>(in.p2.z, in.p2.w);
4475        let cov = gaussian_box_coverage(pp, half, radii, sigma);
4476        return vec4<f32>(in.color.rgb, in.color.a * cov);
4477    }
4478    let fill_cov = clamp(0.5 - d / max(aa, 1e-4), 0.0, 1.0);
4479    let bw = in.p2.x;
4480    if (bw > 0.0) {
4481        let inner_cov = clamp(0.5 - (d + bw) / max(aa, 1e-4), 0.0, 1.0);
4482        let ring = clamp(fill_cov - inner_cov, 0.0, 1.0);
4483        let interior = inner_cov;
4484        let a = in.border_color.a * ring + in.color.a * interior;
4485        if (a <= 0.0) { return vec4<f32>(0.0); }
4486        let rgb = in.border_color.rgb * (in.border_color.a * ring) + in.color.rgb * (in.color.a * interior);
4487        return vec4<f32>(rgb / a, a);
4488    }
4489    return vec4<f32>(in.color.rgb, in.color.a * fill_cov);
4490}
4491"#;
4492
4493// Linear-gradient brush. The gradient is packed entirely into vertex attributes
4494// (bind-group-free, like the rounded-rect pipeline): two stops carried in `color`
4495// (stop 0, linear) and `border_color` (stop 1, linear); the gradient axis end-points
4496// (rect-local) in p2 = [start.x, start.y, end.x, end.y]. Coverage reuses the rounded
4497// rect SDF so the same pipeline fills both sharp FillRect (radii = 0) and rounded fills.
4498const GRADIENT_RECT_SHADER_SOURCE: &str = r#"
4499struct VsOut {
4500    @builtin(position) position: vec4<f32>,
4501    @location(0) stop0: vec4<f32>, @location(1) local: vec2<f32>,
4502    @location(2) p0: vec4<f32>, @location(3) radii: vec4<f32>,
4503    @location(4) axis: vec4<f32>, @location(5) stop1: vec4<f32>,
4504};
4505@vertex
4506fn vs_main(@location(0) position: vec2<f32>, @location(1) stop0: vec4<f32>,
4507    @location(2) local: vec2<f32>, @location(3) p0: vec4<f32>, @location(4) radii: vec4<f32>,
4508    @location(5) axis: vec4<f32>, @location(6) stop1: vec4<f32>) -> VsOut {
4509    var out: VsOut; out.position = vec4<f32>(position, 0.0, 1.0);
4510    out.stop0 = stop0; out.local = local; out.p0 = p0; out.radii = radii; out.axis = axis; out.stop1 = stop1;
4511    return out;
4512}
4513fn sd_round_box(p: vec2<f32>, b: vec2<f32>, r: vec4<f32>) -> f32 {
4514    let rt = select(r.x, r.y, p.x > 0.0);
4515    let rb = select(r.w, r.z, p.x > 0.0);
4516    let rr = select(rt, rb, p.y > 0.0);
4517    let q = abs(p) - b + vec2<f32>(rr, rr);
4518    return min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0))) - rr;
4519}
4520@fragment
4521fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
4522    let half = max(in.p0.xy, vec2<f32>(0.0));
4523    let feather = in.p0.w;
4524    let radii = clamp(in.radii, vec4<f32>(0.0), vec4<f32>(min(half.x, half.y)));
4525    let p = in.local; let d = sd_round_box(p, half, radii);
4526    let aa = max(feather, fwidth(d));
4527    let fill_cov = clamp(0.5 - d / max(aa, 1e-4), 0.0, 1.0);
4528    let a = in.axis.xy; let b = in.axis.zw;
4529    let ab = b - a; let denom = max(dot(ab, ab), 1e-6);
4530    let t = clamp(dot(in.local - a, ab) / denom, 0.0, 1.0);
4531    let col = mix(in.stop0, in.stop1, t);
4532    return vec4<f32>(col.rgb, col.a * fill_cov);
4533}
4534"#;
4535
4536const TEXT_ATLAS_SHADER_SOURCE: &str = r#"
4537struct VsOut {
4538    @builtin(position) position: vec4<f32>,
4539    @location(0) color: vec4<f32>,
4540    @location(1) tex_coords: vec2<f32>,
4541    @location(2) metadata: vec4<f32>,
4542    @location(3) @interpolate(flat) layer: u32,
4543    @location(4) uv_min: vec2<f32>,
4544    @location(5) uv_max: vec2<f32>,
4545};
4546
4547@group(0) @binding(0)
4548var text_atlas_sampler: sampler;
4549
4550@group(0) @binding(1)
4551var text_atlas_texture: texture_2d_array<f32>;
4552
4553@vertex
4554fn vs_main(
4555    @location(0) local_pos: vec2<f32>,
4556    @location(1) top_left: vec2<f32>,
4557    @location(2) x_axis: vec2<f32>,
4558    @location(3) y_axis: vec2<f32>,
4559    @location(4) uv_min: vec2<f32>,
4560    @location(5) uv_max: vec2<f32>,
4561    @location(6) color: vec4<f32>,
4562    @location(7) metadata: vec4<f32>,
4563    @location(8) layer: u32,
4564) -> VsOut {
4565    var out: VsOut;
4566    out.position = vec4<f32>(top_left + local_pos.x * x_axis + local_pos.y * y_axis, 0.0, 1.0);
4567    out.color = color;
4568    out.tex_coords = uv_min + local_pos * (uv_max - uv_min);
4569    out.metadata = metadata;
4570    out.layer = layer;
4571    out.uv_min = uv_min;
4572    out.uv_max = uv_max;
4573    return out;
4574}
4575
4576fn srgb_to_linear(color: vec3<f32>) -> vec3<f32> {
4577    let low = color / 12.92;
4578    let high = pow((color + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4));
4579    return select(high, low, color <= vec3<f32>(0.04045));
4580}
4581
4582fn apply_text_coverage(coverage: f32, policy: f32, parameter: f32) -> f32 {
4583    let c = clamp(coverage, 0.0, 1.0);
4584    if policy < 0.5 {
4585        return c;
4586    }
4587    if policy < 1.5 {
4588        return pow(c, max(parameter, 1e-4));
4589    }
4590    if policy < 2.5 {
4591        let amount = clamp(parameter, 0.0, 1.0);
4592        return c + (c * (1.0 - c) * amount);
4593    }
4594    if policy < 3.5 {
4595        return (2.0 * c) - (c * c);
4596    }
4597    return c;
4598}
4599
4600@fragment
4601fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
4602    // Clamp the sample point to the glyph's half-texel-inset UV rect so bilinear taps at the quad
4603    // edges can't reach into neighbouring glyphs (or the padding) at non-integer scales.
4604    let atlas_half_texel = 0.5 / vec2<f32>(textureDimensions(text_atlas_texture));
4605    let clamped_uv = clamp(in.tex_coords, in.uv_min + atlas_half_texel, in.uv_max - atlas_half_texel);
4606    let sampled = textureSample(text_atlas_texture, text_atlas_sampler, clamped_uv, i32(in.layer));
4607    if in.color.a < 0.0 {
4608        let opacity = -in.color.a;
4609        let alpha = sampled.a * opacity;
4610        // Color/bitmap emoji glyphs carry their own RGB. Linearize the stored sRGB and premultiply.
4611        return vec4<f32>(srgb_to_linear(sampled.rgb) * alpha, alpha);
4612    }
4613
4614    if in.metadata.x > 0.5 {
4615        let coverage = vec3<f32>(
4616            apply_text_coverage(sampled.r, in.metadata.z, in.metadata.w),
4617            apply_text_coverage(sampled.g, in.metadata.z, in.metadata.w),
4618            apply_text_coverage(sampled.b, in.metadata.z, in.metadata.w),
4619        );
4620        let max_coverage = max(max(coverage.r, coverage.g), coverage.b);
4621        let premul = in.color.rgb * coverage * in.color.a;
4622        return vec4<f32>(premul, in.color.a * max_coverage);
4623    }
4624
4625    if in.metadata.y > 0.5 {
4626        let coverage = apply_text_coverage(
4627            (sampled.r + sampled.g + sampled.b) / 3.0,
4628            in.metadata.z,
4629            in.metadata.w,
4630        );
4631        let alpha = in.color.a * coverage;
4632        return vec4<f32>(in.color.rgb * alpha, alpha);
4633    }
4634
4635    let coverage = apply_text_coverage(sampled.a, in.metadata.z, in.metadata.w);
4636    let alpha = in.color.a * coverage;
4637    return vec4<f32>(in.color.rgb * alpha, alpha);
4638}
4639"#;
4640
4641const TEXT_ATLAS_DUAL_SOURCE_SHADER_SOURCE: &str = r#"
4642enable dual_source_blending;
4643
4644struct VsOut {
4645    @builtin(position) position: vec4<f32>,
4646    @location(0) color: vec4<f32>,
4647    @location(1) tex_coords: vec2<f32>,
4648    @location(2) metadata: vec4<f32>,
4649    @location(3) @interpolate(flat) layer: u32,
4650    @location(4) uv_min: vec2<f32>,
4651    @location(5) uv_max: vec2<f32>,
4652};
4653
4654struct FragmentOutput {
4655    @location(0) @blend_src(0) foreground: vec4<f32>,
4656    @location(0) @blend_src(1) alpha: vec4<f32>,
4657};
4658
4659@group(0) @binding(0)
4660var text_atlas_sampler: sampler;
4661
4662@group(0) @binding(1)
4663var text_atlas_texture: texture_2d_array<f32>;
4664
4665@vertex
4666fn vs_main(
4667    @location(0) local_pos: vec2<f32>,
4668    @location(1) top_left: vec2<f32>,
4669    @location(2) x_axis: vec2<f32>,
4670    @location(3) y_axis: vec2<f32>,
4671    @location(4) uv_min: vec2<f32>,
4672    @location(5) uv_max: vec2<f32>,
4673    @location(6) color: vec4<f32>,
4674    @location(7) metadata: vec4<f32>,
4675    @location(8) layer: u32,
4676) -> VsOut {
4677    var out: VsOut;
4678    out.position = vec4<f32>(top_left + local_pos.x * x_axis + local_pos.y * y_axis, 0.0, 1.0);
4679    out.color = color;
4680    out.tex_coords = uv_min + local_pos * (uv_max - uv_min);
4681    out.metadata = metadata;
4682    out.layer = layer;
4683    out.uv_min = uv_min;
4684    out.uv_max = uv_max;
4685    return out;
4686}
4687
4688fn srgb_to_linear(color: vec3<f32>) -> vec3<f32> {
4689    let low = color / 12.92;
4690    let high = pow((color + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4));
4691    return select(high, low, color <= vec3<f32>(0.04045));
4692}
4693
4694fn apply_text_coverage(coverage: f32, policy: f32, parameter: f32) -> f32 {
4695    let c = clamp(coverage, 0.0, 1.0);
4696    if policy < 0.5 {
4697        return c;
4698    }
4699    if policy < 1.5 {
4700        return pow(c, max(parameter, 1e-4));
4701    }
4702    if policy < 2.5 {
4703        let amount = clamp(parameter, 0.0, 1.0);
4704        return c + (c * (1.0 - c) * amount);
4705    }
4706    if policy < 3.5 {
4707        return (2.0 * c) - (c * c);
4708    }
4709    return c;
4710}
4711
4712fn dual_source(foreground: vec3<f32>, alpha: vec3<f32>) -> FragmentOutput {
4713    var out: FragmentOutput;
4714    let source_alpha = max(max(alpha.r, alpha.g), alpha.b);
4715    out.foreground = vec4<f32>(foreground, source_alpha);
4716    out.alpha = vec4<f32>(alpha, 1.0);
4717    return out;
4718}
4719
4720@fragment
4721fn fs_main(in: VsOut) -> FragmentOutput {
4722    // Clamp the sample point to the glyph's half-texel-inset UV rect so bilinear taps at the quad
4723    // edges can't reach into neighbouring glyphs (or the padding) at non-integer scales.
4724    let atlas_half_texel = 0.5 / vec2<f32>(textureDimensions(text_atlas_texture));
4725    let clamped_uv = clamp(in.tex_coords, in.uv_min + atlas_half_texel, in.uv_max - atlas_half_texel);
4726    let sampled = textureSample(text_atlas_texture, text_atlas_sampler, clamped_uv, i32(in.layer));
4727    if in.color.a < 0.0 {
4728        let opacity = -in.color.a;
4729        // Color/bitmap emoji glyphs carry their own RGB. Linearize the stored sRGB before
4730        // premultiplying.
4731        return dual_source(srgb_to_linear(sampled.rgb), vec3<f32>(sampled.a * opacity));
4732    }
4733
4734    if in.metadata.x > 0.5 {
4735        let coverage = vec3<f32>(
4736            apply_text_coverage(sampled.r, in.metadata.z, in.metadata.w),
4737            apply_text_coverage(sampled.g, in.metadata.z, in.metadata.w),
4738            apply_text_coverage(sampled.b, in.metadata.z, in.metadata.w),
4739        );
4740        return dual_source(in.color.rgb, coverage * in.color.a);
4741    }
4742
4743    if in.metadata.y > 0.5 {
4744        let coverage = apply_text_coverage(
4745            (sampled.r + sampled.g + sampled.b) / 3.0,
4746            in.metadata.z,
4747            in.metadata.w,
4748        );
4749        return dual_source(in.color.rgb, vec3<f32>(coverage * in.color.a));
4750    }
4751
4752    let coverage = apply_text_coverage(sampled.a, in.metadata.z, in.metadata.w);
4753    return dual_source(in.color.rgb, vec3<f32>(coverage * in.color.a));
4754}
4755"#;
4756
4757const ANALYTIC_PATH_SHADER_SOURCE: &str = r#"
4758struct VsOut {
4759    @builtin(position) position: vec4<f32>,
4760    @location(0) color: vec4<f32>,
4761    @location(1) scene_position: vec2<f32>,
4762    @location(2) @interpolate(flat) path_index: u32,
4763};
4764
4765struct AnalyticPathMeta {
4766    contour_start: u32,
4767    contour_count: u32,
4768    point_start: u32,
4769    mode: u32,
4770    feather_width: f32,
4771    stroke_width: f32,
4772    _pad0: vec2<f32>,
4773};
4774
4775struct AnalyticContour {
4776    start: u32,
4777    len: u32,
4778    flags: u32,
4779    _pad0: u32,
4780};
4781
4782const ANALYTIC_CONTOUR_FLAG_CLOSED: u32 = 1u;
4783const ANALYTIC_PATH_MODE_FILL: u32 = 0u;
4784const ANALYTIC_PATH_MODE_STROKE: u32 = 1u;
4785
4786struct AnalyticPoint {
4787    position: vec2<f32>,
4788    _pad: vec2<f32>,
4789};
4790
4791@group(0) @binding(0)
4792var<storage, read> path_metas: array<AnalyticPathMeta>;
4793
4794@group(0) @binding(1)
4795var<storage, read> contours: array<AnalyticContour>;
4796
4797@group(0) @binding(2)
4798var<storage, read> points: array<AnalyticPoint>;
4799
4800@vertex
4801fn vs_main(
4802    @location(0) position: vec2<f32>,
4803    @location(1) color: vec4<f32>,
4804    @location(2) scene_position: vec2<f32>,
4805    @location(3) shader_params: vec4<f32>,
4806) -> VsOut {
4807    var out: VsOut;
4808    out.position = vec4<f32>(position, 0.0, 1.0);
4809    out.color = color;
4810    out.scene_position = scene_position;
4811    out.path_index = u32(shader_params.x + 0.5);
4812    return out;
4813}
4814
4815fn segment_distance(point: vec2<f32>, a: vec2<f32>, b: vec2<f32>) -> f32 {
4816    let ab = b - a;
4817    let denom = max(dot(ab, ab), 1e-5);
4818    let t = clamp(dot(point - a, ab) / denom, 0.0, 1.0);
4819    return length(point - (a + (ab * t)));
4820}
4821
4822@fragment
4823fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
4824    // Derivatives must be evaluated before path-indexed storage-buffer access introduces
4825    // potentially non-uniform control flow. The larger scene-space pixel axis gives a stable
4826    // one-physical-pixel coverage transition without the sqrt(2) over-blur of combining axes.
4827    let scene_dx = dpdx(in.scene_position);
4828    let scene_dy = dpdy(in.scene_position);
4829    let derivative_width = max(max(length(scene_dx), length(scene_dy)), 1e-4);
4830
4831    let path_meta = path_metas[in.path_index];
4832    if path_meta.contour_count == 0u {
4833        return vec4<f32>(0.0, 0.0, 0.0, 0.0);
4834    }
4835
4836    let point = in.scene_position;
4837    var inside = false;
4838    var min_distance = 1e9;
4839
4840    for (var contour_index = 0u; contour_index < path_meta.contour_count; contour_index = contour_index + 1u) {
4841        let contour = contours[path_meta.contour_start + contour_index];
4842        if contour.len < 2u {
4843            continue;
4844        }
4845
4846        let closed = (contour.flags & ANALYTIC_CONTOUR_FLAG_CLOSED) != 0u;
4847        let point_start = path_meta.point_start + contour.start;
4848        var previous = select(
4849            points[point_start].position,
4850            points[point_start + contour.len - 1u].position,
4851            closed,
4852        );
4853        var start_index = select(1u, 0u, closed);
4854        for (var point_index = start_index; point_index < contour.len; point_index = point_index + 1u) {
4855            let current = points[point_start + point_index].position;
4856                let denom = previous.y - current.y;
4857                let safe_denom = select(
4858                    denom,
4859                    select(-1e-5, 1e-5, denom >= 0.0),
4860                    abs(denom) < 1e-5,
4861                );
4862            let intersects = ((current.y > point.y) != (previous.y > point.y))
4863                && (point.x < (((previous.x - current.x) * (point.y - current.y))
4864                / safe_denom) + current.x);
4865            if intersects {
4866                inside = !inside;
4867            }
4868
4869            min_distance = min(min_distance, segment_distance(point, previous, current));
4870            previous = current;
4871        }
4872    }
4873
4874    let feather = max(path_meta.feather_width, derivative_width);
4875    var coverage = 0.0;
4876
4877    if path_meta.mode == ANALYTIC_PATH_MODE_FILL {
4878        let signed_distance = select(min_distance, -min_distance, inside);
4879        coverage = clamp(0.5 - (signed_distance / max(feather, 1e-4)), 0.0, 1.0);
4880    } else {
4881        let half_width = max(0.0, 0.5 * path_meta.stroke_width);
4882        let edge_distance = min_distance - half_width;
4883        coverage = clamp(0.5 - (edge_distance / max(feather, 1e-4)), 0.0, 1.0);
4884    }
4885
4886    return vec4<f32>(in.color.rgb, in.color.a * coverage);
4887}
4888"#;
4889
4890const OUTPUT_TRANSFORM_SHADER_SOURCE: &str = r#"
4891struct VsOut {
4892    @builtin(position) position: vec4<f32>,
4893}
4894
4895struct OutputUniform {
4896    tone_mapping_mode: u32,
4897    encode_srgb: u32,
4898    output_primaries: u32,
4899    _padding2: u32,
4900    sdr_content_scale: f32,
4901    _padding3: u32,
4902    _padding4: u32,
4903    _padding5: u32,
4904}
4905
4906@group(0) @binding(0)
4907var scene_texture: texture_2d<f32>;
4908
4909@group(0) @binding(1)
4910var<uniform> output_uniform: OutputUniform;
4911
4912@vertex
4913fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VsOut {
4914    var positions = array<vec2<f32>, 3>(
4915        vec2<f32>(-1.0, -3.0),
4916        vec2<f32>(-1.0, 1.0),
4917        vec2<f32>(3.0, 1.0),
4918    );
4919    var out: VsOut;
4920    out.position = vec4<f32>(positions[vertex_index], 0.0, 1.0);
4921    return out;
4922}
4923
4924fn tone_map(color: vec3<f32>) -> vec3<f32> {
4925    let scaled = max(color, vec3<f32>(0.0)) * output_uniform.sdr_content_scale;
4926    switch output_uniform.tone_mapping_mode {
4927        case 0u: {
4928            return scaled;
4929        }
4930        case 2u: {
4931            return scaled / (vec3<f32>(1.0) + scaled);
4932        }
4933        default: {
4934            return clamp(scaled, vec3<f32>(0.0), vec3<f32>(1.0));
4935        }
4936    }
4937}
4938
4939fn linear_srgb_to_output_primaries(color: vec3<f32>) -> vec3<f32> {
4940    if output_uniform.output_primaries == 1u {
4941        return vec3<f32>(
4942            0.82246196 * color.r + 0.17753802 * color.g,
4943            0.0331942 * color.r + 0.96680576 * color.g,
4944            0.01708263 * color.r + 0.07239743 * color.g + 0.91051996 * color.b,
4945        );
4946    }
4947    return color;
4948}
4949
4950fn linear_to_srgb_channel(channel: f32) -> f32 {
4951    let value = max(channel, 0.0);
4952    if value <= 0.0031308 {
4953        return value * 12.92;
4954    }
4955    return (1.055 * pow(value, 1.0 / 2.4)) - 0.055;
4956}
4957
4958fn encode_for_output(color: vec3<f32>) -> vec3<f32> {
4959    if output_uniform.encode_srgb == 0u {
4960        return color;
4961    }
4962    return vec3<f32>(
4963        linear_to_srgb_channel(color.r),
4964        linear_to_srgb_channel(color.g),
4965        linear_to_srgb_channel(color.b),
4966    );
4967}
4968
4969@fragment
4970fn fs_main(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
4971    let dims = textureDimensions(scene_texture);
4972    let max_coord = vec2<i32>(max(vec2<u32>(1u), dims) - vec2<u32>(1u));
4973    let coords = clamp(vec2<i32>(position.xy), vec2<i32>(0), max_coord);
4974    let color = textureLoad(scene_texture, coords, 0);
4975    return vec4<f32>(
4976        encode_for_output(linear_srgb_to_output_primaries(tone_map(color.rgb))),
4977        clamp(color.a, 0.0, 1.0),
4978    );
4979}
4980"#;
4981
4982#[cfg(test)]
4983mod tests {
4984    use super::{
4985        ANALYTIC_PATH_SHADER_SOURCE, CachedGlyphAtlas, CachedGlyphMesh, ClipState,
4986        ColorManagementMode, CompositionContainerId, DEFAULT_FEATHER_WIDTH, DebugCaptureArtifact,
4987        DebugCaptureEncoding, DebugCaptureRequest, DebugCaptureStage, DebugSdrVisualization,
4988        DisplayCapabilities, DisplayColorPrimaries, DisplayTransferFunction, DrawOp, DrawOpArena,
4989        DrawOpKind, DynamicRangeMode, GlyphCacheKey, GlyphFaceCacheKey, GlyphSubpixelOffsetKey,
4990        HdrRgbaImage, OutputStrategy, PacketRebuildReason, PreparedClipPath, PreparedDrawBatch,
4991        PreparedDrawKind, PreparedFrameBatches, PreparedPassBatch, PreparedVertices,
4992        RendererFrameStats, RequestedColorManagementMode, RequestedDynamicRangeMode,
4993        RequestedOutputColorPrimaries, RequestedToneMappingMode, RetainedCompositorFrameStats,
4994        RetainedCompositorState, RetainedPacketId, RetainedPacketRebuildStats, RgbaImage,
4995        ScissorRect, StemDarkening, SwashImageContent, SwashSource, SwashStrikeWith,
4996        TEXT_ATLAS_DUAL_SOURCE_SHADER_SOURCE, TEXT_ATLAS_SHADER_SOURCE, TextAtlasColorMode,
4997        TextAtlasPages, TextCoveragePolicy, TextEngine, TextHinting, TextRenderMode,
4998        TextSubpixelOrder, VERTEX_SIZE, Vertex, WgpuExternalTextureRegistry, WgpuRenderer,
4999        append_cached_path_mesh, batch_draw_ops, build_vertices, decode_rgba16f_pixels,
5000        encode_hdr_debug_artifact, hdr_image_to_sdr_rgba, image_mip_chain, image_mip_level_count,
5001        prepare_frame_batches,
5002        scene::{
5003            CachedDrawBatch, CachedPassBatch, allows_lcd_text, append_cached_glyph_atlas,
5004            apply_output_transform_for_testing, apply_stem_darkening_to_coverage,
5005            convert_subpixel_texel_for_mode, glyph_raster_offset, glyph_subpixel_offset,
5006            output_transform_requires_intermediate, prepare_cached_passes, select_output_strategy,
5007            swash_image_to_rgba, tone_map_linear_color,
5008        },
5009        shader_color, strip_padded_readback_rows, to_ndc,
5010    };
5011    use std::sync::Arc;
5012    use sui_core::{
5013        Color, FontHandle, ImageHandle, Path, PathBuilder, Point, Rect, Size, Transform, Vector,
5014        WidgetId, WindowId,
5015    };
5016    use sui_scene::{
5017        Border, Brush, GradientStop, ImageRegistry, ImageSampling, ImageSource,
5018        LayerCompositionMode, RegisteredImage, Scene, SceneCommand, SceneFrame, SceneLayer,
5019        SceneLayerDescriptor, SceneLayerId, SceneLayerUpdate, SceneLayerUpdateKind, ShadowParams,
5020        StrokeStyle, TextRenderCoveragePolicy, TextRenderPolicy, WidgetShader,
5021    };
5022    use sui_text::{
5023        FontRegistry, RegisteredFont, ShapedGlyph, ShapedText, ShapedTextWindow,
5024        TextLayoutRegistry, TextRun, TextStyle, TextSystem,
5025    };
5026
5027    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
5028    enum LayerCachePolicy {
5029        Auto,
5030        Direct,
5031        Cached,
5032    }
5033
5034    trait TestSceneLayerDescriptorExt {
5035        fn with_cache_policy(self, _cache_policy: LayerCachePolicy) -> Self;
5036    }
5037
5038    impl TestSceneLayerDescriptorExt for SceneLayerDescriptor {
5039        fn with_cache_policy(self, _cache_policy: LayerCachePolicy) -> Self {
5040            self
5041        }
5042    }
5043
5044    #[test]
5045    fn retained_packet_rebuild_stats_record_each_reason_and_preserve_grouping() {
5046        let mut rebuilds = RetainedPacketRebuildStats::default();
5047
5048        rebuilds.record_reason(PacketRebuildReason::NewPacket);
5049        rebuilds.record_reason(PacketRebuildReason::CoordinateSpace);
5050        rebuilds.record_reason(PacketRebuildReason::Signature);
5051        rebuilds.record_reason(PacketRebuildReason::Scene);
5052        rebuilds.record_reason(PacketRebuildReason::State);
5053
5054        assert_eq!(rebuilds, RetainedPacketRebuildStats::new(1, 1, 1, 1, 1));
5055        assert_eq!(rebuilds.total_count(), 5);
5056    }
5057
5058    #[test]
5059    fn bitmap_mip_chain_reaches_one_pixel_and_preserves_transparent_edge_color() {
5060        let image = RegisteredImage::from_rgba8(
5061            2,
5062            2,
5063            vec![255, 0, 0, 255, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0],
5064        )
5065        .unwrap();
5066
5067        assert_eq!(image_mip_level_count(8, 4), 4);
5068        let levels = image_mip_chain(&image, true);
5069        assert_eq!(levels.len(), 2);
5070        assert_eq!((levels[1].width, levels[1].height), (1, 1));
5071        assert_eq!(&levels[1].pixels[0..3], &[255, 0, 0]);
5072        assert_eq!(levels[1].pixels[3], 64);
5073        assert_eq!(image_mip_chain(&image, false).len(), 1);
5074    }
5075
5076    #[test]
5077    fn renderer_frame_stats_with_compositor_stats_preserves_grouped_packet_rebuilds() {
5078        let stats = RendererFrameStats::from_prepared_counts(1, 2, 3).with_compositor_stats(
5079            RetainedCompositorFrameStats {
5080                packet_rebuilds: RetainedPacketRebuildStats::new(2, 3, 5, 7, 11),
5081                ..Default::default()
5082            },
5083        );
5084
5085        assert_eq!(
5086            stats.retained_packet_rebuilds,
5087            RetainedPacketRebuildStats::new(2, 3, 5, 7, 11)
5088        );
5089    }
5090
5091    #[test]
5092    fn debug_capture_stage_helpers_classify_hdr_and_final_outputs() {
5093        assert!(DebugCaptureStage::HdrIntermediate.is_hdr_capable());
5094        assert!(DebugCaptureStage::HdrIntermediate.uses_hdr_intermediate());
5095        assert!(!DebugCaptureStage::FinalComposed.is_hdr_capable());
5096        assert!(!DebugCaptureStage::FinalComposed.uses_hdr_intermediate());
5097
5098        assert_eq!(
5099            DebugCaptureStage::default(),
5100            DebugCaptureStage::FinalComposed
5101        );
5102        assert_eq!(DebugCaptureEncoding::default(), DebugCaptureEncoding::Png);
5103        assert_eq!(
5104            DebugSdrVisualization::default(),
5105            DebugSdrVisualization::ToneMappedColor
5106        );
5107        assert_eq!(
5108            DebugCaptureRequest::default(),
5109            DebugCaptureRequest {
5110                stage: DebugCaptureStage::FinalComposed,
5111                encoding: DebugCaptureEncoding::Png,
5112                sdr_visualization: DebugSdrVisualization::ToneMappedColor,
5113            }
5114        );
5115    }
5116
5117    #[test]
5118    fn strip_padded_float_readback_rows_preserves_pixel_order() {
5119        let mapped = vec![1u8, 2, 3, 4, 9, 9, 9, 9, 5, 6, 7, 8, 8, 8, 8, 8];
5120        let stripped = strip_padded_readback_rows(&mapped, 4, 8, 2);
5121        assert_eq!(stripped, vec![1u8, 2, 3, 4, 5, 6, 7, 8]);
5122    }
5123
5124    #[test]
5125    fn decode_rgba16f_pixels_converts_half_float_channels_to_f32() {
5126        let samples = [0.0f32, 1.0, 2.0, 0.5, 4.0, 8.0, 0.25, 1.0];
5127        let mut raw = Vec::new();
5128        for sample in samples {
5129            raw.extend_from_slice(&half::f16::from_f32(sample).to_bits().to_le_bytes());
5130        }
5131        let decoded = decode_rgba16f_pixels(&raw);
5132        assert_eq!(decoded.len(), 8);
5133        for (actual, expected) in decoded.into_iter().zip(samples) {
5134            assert!(
5135                (actual - expected).abs() < 0.001,
5136                "expected {expected}, got {actual}"
5137            );
5138        }
5139    }
5140
5141    #[test]
5142    fn hdr_png_capture_normalizes_native_hdr_reference_white() {
5143        let image = HdrRgbaImage::new(
5144            3,
5145            1,
5146            vec![
5147                2.5, 2.5, 2.5, 1.0, //
5148                1.25, 1.25, 1.25, 0.5, //
5149                5.0, 0.0, 0.0, 1.0,
5150            ],
5151        )
5152        .unwrap();
5153
5154        let sdr = hdr_image_to_sdr_rgba(
5155            &image,
5156            DebugSdrVisualization::ToneMappedColor,
5157            2.5,
5158            DisplayColorPrimaries::Srgb,
5159        )
5160        .unwrap();
5161
5162        assert_rgba_channels_near(
5163            &sdr.pixels()[0..4],
5164            [255, 255, 255, 255],
5165            RGBA_CHANNEL_TOLERANCE,
5166        );
5167        assert!(sdr.pixels()[4] < 255);
5168        assert!(
5169            sdr.pixels()[4].abs_diff(sdr.pixels()[5]) <= RGBA_CHANNEL_TOLERANCE,
5170            "normalized grayscale channels differed by more than {RGBA_CHANNEL_TOLERANCE}: got {} and {}",
5171            sdr.pixels()[4],
5172            sdr.pixels()[5]
5173        );
5174        assert!(
5175            sdr.pixels()[7].abs_diff(128) <= RGBA_CHANNEL_TOLERANCE,
5176            "alpha channel differed by more than {RGBA_CHANNEL_TOLERANCE}: got {}, expected 128",
5177            sdr.pixels()[7]
5178        );
5179        assert_rgba_channels_near(
5180            &sdr.pixels()[8..12],
5181            [255, 0, 0, 255],
5182            RGBA_CHANNEL_TOLERANCE,
5183        );
5184    }
5185
5186    #[test]
5187    fn hdr_png_capture_preserves_srgb_bytes_after_hdr_scale_and_half_readback() {
5188        let reference_white = 203.0 / 80.0;
5189        let mut pixels = Vec::with_capacity(256 * 4);
5190        let mut expected = Vec::with_capacity(256 * 4);
5191
5192        for value in 0..=255u8 {
5193            let encoded = value as f32 / 255.0;
5194            let linear = shader_color(Color::srgba(encoded, encoded, encoded, 1.0));
5195            let captured = half::f16::from_f32(linear[0] * reference_white).to_f32();
5196            pixels.extend_from_slice(&[captured, captured, captured, 1.0]);
5197            expected.extend_from_slice(&[value, value, value, 255]);
5198        }
5199
5200        let image = HdrRgbaImage::new(256, 1, pixels).unwrap();
5201        let sdr = hdr_image_to_sdr_rgba(
5202            &image,
5203            DebugSdrVisualization::ToneMappedColor,
5204            reference_white,
5205            DisplayColorPrimaries::Srgb,
5206        )
5207        .unwrap();
5208
5209        assert_rgba_pixels_near(sdr.pixels(), expected.as_slice(), RGBA_CHANNEL_TOLERANCE);
5210    }
5211
5212    #[test]
5213    fn sdr_png_capture_transform_preserves_srgb_bytes_regardless_of_sdr_brightness() {
5214        let strategy = OutputStrategy::SdrSurface {
5215            format: wgpu::TextureFormat::Bgra8UnormSrgb,
5216        };
5217
5218        for value in 0..=255u8 {
5219            let encoded = value as f32 / 255.0;
5220            let transformed = apply_output_transform_for_testing(
5221                shader_color(Color::srgba(encoded, encoded, encoded, 1.0)),
5222                strategy,
5223                RequestedToneMappingMode::Clamp,
5224                10_000.0,
5225                None,
5226            );
5227            let captured = super::linear_to_srgb_capture_u8(transformed[0]);
5228            assert_eq!(captured, value, "sRGB byte {value} should round-trip");
5229        }
5230
5231        let clipped = apply_output_transform_for_testing(
5232            [4.0, 2.0, 0.5, 1.0],
5233            strategy,
5234            RequestedToneMappingMode::Clamp,
5235            10_000.0,
5236            None,
5237        );
5238        assert_eq!(super::linear_to_srgb_capture_u8(clipped[0]), 255);
5239        assert_eq!(super::linear_to_srgb_capture_u8(clipped[1]), 255);
5240        assert_eq!(super::linear_to_srgb_capture_u8(clipped[2]), 188);
5241    }
5242
5243    #[test]
5244    fn sdr_png_capture_readback_preserves_srgb_bytes_and_clips_hdr() {
5245        let window_id = WindowId::new(4520);
5246        let viewport = Size::new(32.0, 16.0);
5247        let mut scene = Scene::new();
5248        scene.push(SceneCommand::Clear(Color::srgba(0.0, 0.0, 0.0, 1.0)));
5249        scene.push(SceneCommand::FillRect {
5250            rect: Rect::new(0.0, 0.0, 16.0, 16.0),
5251            brush: Color::srgba(66.0 / 255.0, 42.0 / 255.0, 213.0 / 255.0, 1.0).into(),
5252        });
5253        scene.push(SceneCommand::FillRect {
5254            rect: Rect::new(16.0, 0.0, 16.0, 16.0),
5255            brush: Color::linear_rgba(4.0, 2.0, 0.5, 1.0).into(),
5256        });
5257
5258        let frame = SceneFrame {
5259            window_id,
5260            viewport,
5261            surface_size: viewport,
5262            scale_factor: 1.0,
5263            dirty_regions: Vec::new(),
5264            layer_updates: Vec::new(),
5265            scene,
5266            font_registry: Arc::new(FontRegistry::new()),
5267            image_registry: Arc::new(ImageRegistry::new()),
5268            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
5269        };
5270
5271        let mut renderer = WgpuRenderer::new();
5272        renderer.render(&frame).unwrap();
5273        let image = renderer.capture_last_frame_rgba(window_id).unwrap();
5274
5275        assert_rgba_pixel_near(&image, 8, 8, [66, 42, 213, 255], RGBA_CHANNEL_TOLERANCE);
5276        assert_rgba_pixel_near(
5277            &image,
5278            24,
5279            8,
5280            [255, 255, super::linear_to_srgb_capture_u8(0.5), 255],
5281            RGBA_CHANNEL_TOLERANCE,
5282        );
5283    }
5284
5285    #[test]
5286    fn headless_intermediate_accepts_stencil_clip_mask_pipeline() {
5287        let window_id = WindowId::new(4521);
5288        let viewport = Size::new(32.0, 24.0);
5289        let mut scene = Scene::new();
5290        scene.push(SceneCommand::Clear(Color::BLACK));
5291        scene.push(SceneCommand::PushClipPath {
5292            path: Path::rounded_rect(Rect::new(4.0, 4.0, 24.0, 16.0), 6.0),
5293        });
5294        scene.push(SceneCommand::FillRect {
5295            rect: Rect::new(0.0, 0.0, 32.0, 24.0),
5296            brush: Color::WHITE.into(),
5297        });
5298        scene.push(SceneCommand::PopClip);
5299
5300        let frame = SceneFrame {
5301            window_id,
5302            viewport,
5303            surface_size: viewport,
5304            scale_factor: 1.0,
5305            dirty_regions: Vec::new(),
5306            layer_updates: Vec::new(),
5307            scene,
5308            font_registry: Arc::new(FontRegistry::new()),
5309            image_registry: Arc::new(ImageRegistry::new()),
5310            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
5311        };
5312
5313        let mut renderer = WgpuRenderer::new();
5314        renderer.render(&frame).unwrap();
5315        let image = renderer.capture_last_frame_rgba(window_id).unwrap();
5316        assert_rgba_pixel_near(&image, 16, 12, [255, 255, 255, 255], RGBA_CHANNEL_TOLERANCE);
5317        assert_rgba_pixel_near(&image, 0, 0, [0, 0, 0, 255], RGBA_CHANNEL_TOLERANCE);
5318    }
5319
5320    #[test]
5321    fn hdr_png_capture_converts_display_p3_final_output_back_to_srgb() {
5322        let color = Color::srgba(66.0 / 255.0, 42.0 / 255.0, 213.0 / 255.0, 1.0);
5323        let strategy = OutputStrategy::HdrNativeSurface {
5324            format: wgpu::TextureFormat::Rgba16Float,
5325            primaries: DisplayColorPrimaries::DisplayP3,
5326            transfer: DisplayTransferFunction::LinearExtended,
5327        };
5328        let transformed = apply_output_transform_for_testing(
5329            shader_color(color),
5330            strategy,
5331            RequestedToneMappingMode::Automatic,
5332            203.0,
5333            None,
5334        );
5335        let image = HdrRgbaImage::new(
5336            1,
5337            1,
5338            vec![
5339                transformed[0],
5340                transformed[1],
5341                transformed[2],
5342                transformed[3],
5343            ],
5344        )
5345        .unwrap();
5346
5347        let sdr = hdr_image_to_sdr_rgba(
5348            &image,
5349            DebugSdrVisualization::ToneMappedColor,
5350            203.0 / 80.0,
5351            DisplayColorPrimaries::DisplayP3,
5352        )
5353        .unwrap();
5354
5355        assert_rgba_channels_near(
5356            &sdr.pixels()[0..4],
5357            [66, 42, 213, 255],
5358            RGBA_CHANNEL_TOLERANCE,
5359        );
5360    }
5361
5362    #[test]
5363    fn hdr_png_capture_visualizations_use_sdr_reference_white() {
5364        let image = HdrRgbaImage::new(
5365            2,
5366            1,
5367            vec![
5368                2.0, 2.0, 2.0, 1.0, //
5369                2.01, 0.0, 0.0, 1.0,
5370            ],
5371        )
5372        .unwrap();
5373
5374        let mask = hdr_image_to_sdr_rgba(
5375            &image,
5376            DebugSdrVisualization::ClipMask,
5377            2.0,
5378            DisplayColorPrimaries::Srgb,
5379        )
5380        .unwrap();
5381        assert_rgba_channels_near(&mask.pixels()[0..4], [0, 0, 0, 255], RGBA_CHANNEL_TOLERANCE);
5382        assert_rgba_channels_near(
5383            &mask.pixels()[4..8],
5384            [255, 64, 64, 255],
5385            RGBA_CHANNEL_TOLERANCE,
5386        );
5387
5388        let heatmap = hdr_image_to_sdr_rgba(
5389            &image,
5390            DebugSdrVisualization::HeadroomHeatmap,
5391            2.0,
5392            DisplayColorPrimaries::Srgb,
5393        )
5394        .unwrap();
5395        assert!(heatmap.pixels()[4] >= heatmap.pixels()[0]);
5396        assert!(
5397            heatmap.pixels()[7].abs_diff(255) <= RGBA_CHANNEL_TOLERANCE,
5398            "heatmap alpha channel differed by more than {RGBA_CHANNEL_TOLERANCE}: got {}, expected 255",
5399            heatmap.pixels()[7]
5400        );
5401    }
5402
5403    #[test]
5404    fn hdr_debug_artifact_encoding_preserves_exr_and_maps_png_to_sdr() {
5405        let image = HdrRgbaImage::new(1, 1, vec![2.5, 1.25, 0.0, 1.0]).unwrap();
5406
5407        let png = encode_hdr_debug_artifact(
5408            image.clone(),
5409            DebugCaptureRequest {
5410                stage: DebugCaptureStage::FinalComposed,
5411                encoding: DebugCaptureEncoding::Png,
5412                sdr_visualization: DebugSdrVisualization::ToneMappedColor,
5413            },
5414            2.5,
5415            DisplayColorPrimaries::Srgb,
5416        )
5417        .unwrap();
5418        let DebugCaptureArtifact::SdrRgba8(png) = png else {
5419            panic!("PNG HDR debug capture should be converted to SDR RGBA");
5420        };
5421        assert!(
5422            png.pixels()[0].abs_diff(255) <= RGBA_CHANNEL_TOLERANCE,
5423            "PNG red channel differed by more than {RGBA_CHANNEL_TOLERANCE}: got {}, expected 255",
5424            png.pixels()[0]
5425        );
5426        assert!(png.pixels()[1] < 255);
5427
5428        let exr = encode_hdr_debug_artifact(
5429            image,
5430            DebugCaptureRequest {
5431                stage: DebugCaptureStage::FinalComposed,
5432                encoding: DebugCaptureEncoding::Exr,
5433                sdr_visualization: DebugSdrVisualization::ToneMappedColor,
5434            },
5435            2.5,
5436            DisplayColorPrimaries::Srgb,
5437        )
5438        .unwrap();
5439        let DebugCaptureArtifact::HdrLinearRgbaF32(exr) = exr else {
5440            panic!("EXR HDR debug capture should preserve HDR linear RGBA");
5441        };
5442        assert_eq!(exr.pixels()[0], 2.5);
5443    }
5444
5445    fn load_test_font() -> RegisteredFont {
5446        let mut font_db = fontdb::Database::new();
5447        font_db.load_system_fonts();
5448        let families = [fontdb::Family::SansSerif];
5449        let font_id = font_db
5450            .query(&fontdb::Query {
5451                families: &families,
5452                weight: fontdb::Weight::NORMAL,
5453                stretch: fontdb::Stretch::Normal,
5454                style: fontdb::Style::Normal,
5455            })
5456            .or_else(|| font_db.faces().next().map(|face| face.id))
5457            .expect("system font available for renderer tests");
5458
5459        font_db
5460            .with_face_data(font_id, |font_data, face_index| {
5461                RegisteredFont::from_bytes(font_data.to_vec()).with_face_index(face_index)
5462            })
5463            .expect("font data should be readable from system font database")
5464    }
5465
5466    fn content_update(widget_id: WidgetId) -> SceneLayerUpdate {
5467        SceneLayerUpdate::from_descriptor(
5468            SceneLayerUpdateKind::Content,
5469            SceneLayerDescriptor::new(SceneLayerId::from_widget(widget_id), widget_id, Rect::ZERO),
5470        )
5471        .with_damage(Rect::ZERO)
5472    }
5473
5474    fn content_updates<const N: usize>(widget_ids: [WidgetId; N]) -> Vec<SceneLayerUpdate> {
5475        widget_ids.into_iter().map(content_update).collect()
5476    }
5477
5478    fn prepare_with_compositor(
5479        frame: &SceneFrame,
5480        text_engine: &mut TextEngine,
5481        compositor: &mut RetainedCompositorState,
5482    ) -> sui_core::Result<DrawOpArena> {
5483        compositor.prepare_frame(frame, text_engine, DEFAULT_FEATHER_WIDTH)
5484    }
5485
5486    fn packet_signature(
5487        compositor: &RetainedCompositorState,
5488        container: CompositionContainerId,
5489    ) -> u64 {
5490        compositor.packets[&RetainedPacketId {
5491            container,
5492            segment_index: 0,
5493        }]
5494            .signature
5495    }
5496
5497    const RGBA_CHANNEL_TOLERANCE: u8 = 1;
5498
5499    fn rgba_channels_match_with_tolerance(left: &[u8], right: &[u8], tolerance: u8) -> bool {
5500        left.iter()
5501            .zip(right.iter())
5502            .all(|(left, right)| left.abs_diff(*right) <= tolerance)
5503    }
5504
5505    fn assert_rgba_images_match(left: &super::RgbaImage, right: &super::RgbaImage) {
5506        assert_eq!(left.width(), right.width(), "image widths differ");
5507        assert_eq!(left.height(), right.height(), "image heights differ");
5508
5509        let mut diff_count = 0usize;
5510        let mut diff_bounds: Option<(u32, u32, u32, u32)> = None;
5511        let mut max_channel_diff = 0u8;
5512        let width = left.width();
5513        for (index, (left_px, right_px)) in left
5514            .pixels()
5515            .chunks_exact(4)
5516            .zip(right.pixels().chunks_exact(4))
5517            .enumerate()
5518        {
5519            let pixel_max_channel_diff = left_px
5520                .iter()
5521                .zip(right_px.iter())
5522                .map(|(left, right)| left.abs_diff(*right))
5523                .max()
5524                .unwrap_or(0);
5525            max_channel_diff = max_channel_diff.max(pixel_max_channel_diff);
5526            if pixel_max_channel_diff > RGBA_CHANNEL_TOLERANCE {
5527                diff_count += 1;
5528                let x = (index as u32) % width;
5529                let y = (index as u32) / width;
5530                diff_bounds = Some(match diff_bounds {
5531                    Some((min_x, min_y, max_x, max_y)) => {
5532                        (min_x.min(x), min_y.min(y), max_x.max(x), max_y.max(y))
5533                    }
5534                    None => (x, y, x, y),
5535                });
5536            }
5537        }
5538
5539        if diff_count != 0 {
5540            let (min_x, min_y, max_x, max_y) = diff_bounds.expect("diff bounds present");
5541            panic!(
5542                "images differ beyond {RGBA_CHANNEL_TOLERANCE} channel value at {} pixels within bounds ({}, {})..({}, {}); max channel diff {}",
5543                diff_count, min_x, min_y, max_x, max_y, max_channel_diff
5544            );
5545        }
5546    }
5547
5548    fn rgba_image_diff_count(left: &super::RgbaImage, right: &super::RgbaImage) -> usize {
5549        assert_eq!(left.width(), right.width(), "image widths differ");
5550        assert_eq!(left.height(), right.height(), "image heights differ");
5551
5552        left.pixels()
5553            .chunks_exact(4)
5554            .zip(right.pixels().chunks_exact(4))
5555            .filter(|(left_px, right_px)| {
5556                !rgba_channels_match_with_tolerance(left_px, right_px, RGBA_CHANNEL_TOLERANCE)
5557            })
5558            .count()
5559    }
5560
5561    fn ink_pixel_count(image: &super::RgbaImage, rect: Rect) -> usize {
5562        let min_x = rect.x().floor().max(0.0) as u32;
5563        let min_y = rect.y().floor().max(0.0) as u32;
5564        let max_x = rect.max_x().ceil().min(image.width() as f32) as u32;
5565        let max_y = rect.max_y().ceil().min(image.height() as f32) as u32;
5566        let pixels = image.pixels();
5567        let width = image.width() as usize;
5568
5569        let mut count = 0usize;
5570        for y in min_y..max_y {
5571            for x in min_x..max_x {
5572                let index = ((y as usize * width) + x as usize) * 4;
5573                let red = pixels[index] as i32;
5574                let green = pixels[index + 1] as i32;
5575                let blue = pixels[index + 2] as i32;
5576                let alpha = pixels[index + 3] as i32;
5577                if alpha > 0 && (red + green + blue) < 680 {
5578                    count += 1;
5579                }
5580            }
5581        }
5582        count
5583    }
5584
5585    fn non_white_pixel_count(image: &super::RgbaImage, rect: Rect) -> usize {
5586        let min_x = rect.x().floor().max(0.0) as u32;
5587        let min_y = rect.y().floor().max(0.0) as u32;
5588        let max_x = rect.max_x().ceil().min(image.width() as f32) as u32;
5589        let max_y = rect.max_y().ceil().min(image.height() as f32) as u32;
5590        let pixels = image.pixels();
5591        let width = image.width() as usize;
5592
5593        let mut count = 0usize;
5594        for y in min_y..max_y {
5595            for x in min_x..max_x {
5596                let index = ((y as usize * width) + x as usize) * 4;
5597                if !rgba_channels_match_with_tolerance(
5598                    &pixels[index..index + 4],
5599                    &[255, 255, 255, 255],
5600                    RGBA_CHANNEL_TOLERANCE,
5601                ) {
5602                    count += 1;
5603                }
5604            }
5605        }
5606        count
5607    }
5608
5609    fn non_white_row_count(image: &super::RgbaImage, rect: Rect) -> usize {
5610        let min_x = rect.x().floor().max(0.0) as u32;
5611        let min_y = rect.y().floor().max(0.0) as u32;
5612        let max_x = rect.max_x().ceil().min(image.width() as f32) as u32;
5613        let max_y = rect.max_y().ceil().min(image.height() as f32) as u32;
5614        let pixels = image.pixels();
5615        let width = image.width() as usize;
5616
5617        let mut rows = 0usize;
5618        for y in min_y..max_y {
5619            let mut row_has_ink = false;
5620            for x in min_x..max_x {
5621                let index = ((y as usize * width) + x as usize) * 4;
5622                if !rgba_channels_match_with_tolerance(
5623                    &pixels[index..index + 4],
5624                    &[255, 255, 255, 255],
5625                    RGBA_CHANNEL_TOLERANCE,
5626                ) {
5627                    row_has_ink = true;
5628                    break;
5629                }
5630            }
5631            rows += row_has_ink as usize;
5632        }
5633        rows
5634    }
5635
5636    fn rgba_pixel(image: &super::RgbaImage, x: u32, y: u32) -> [u8; 4] {
5637        let width = image.width() as usize;
5638        let index = ((y as usize * width) + x as usize) * 4;
5639        let pixels = image.pixels();
5640        [
5641            pixels[index],
5642            pixels[index + 1],
5643            pixels[index + 2],
5644            pixels[index + 3],
5645        ]
5646    }
5647
5648    fn assert_rgba_pixel_near(
5649        image: &super::RgbaImage,
5650        x: u32,
5651        y: u32,
5652        expected: [u8; 4],
5653        tolerance: u8,
5654    ) {
5655        let actual = rgba_pixel(image, x, y);
5656        for channel in 0..4 {
5657            assert!(
5658                actual[channel].abs_diff(expected[channel]) <= tolerance,
5659                "pixel ({x}, {y}) channel {channel} differed by more than {tolerance}: got {}, expected {}",
5660                actual[channel],
5661                expected[channel]
5662            );
5663        }
5664    }
5665
5666    fn assert_rgba_channels_near(actual: &[u8], expected: [u8; 4], tolerance: u8) {
5667        assert_eq!(
5668            actual.len(),
5669            4,
5670            "expected exactly one RGBA pixel, got {} channels",
5671            actual.len()
5672        );
5673        for channel in 0..4 {
5674            assert!(
5675                actual[channel].abs_diff(expected[channel]) <= tolerance,
5676                "channel {channel} differed by more than {tolerance}: got {}, expected {}",
5677                actual[channel],
5678                expected[channel]
5679            );
5680        }
5681    }
5682
5683    fn assert_rgba_pixels_near(actual: &[u8], expected: &[u8], tolerance: u8) {
5684        assert_eq!(
5685            actual.len(),
5686            expected.len(),
5687            "RGBA buffer length mismatch: got {}, expected {}",
5688            actual.len(),
5689            expected.len()
5690        );
5691        assert_eq!(
5692            actual.len() % 4,
5693            0,
5694            "RGBA buffer length must be divisible by 4"
5695        );
5696
5697        for (pixel_index, (actual_pixel, expected_pixel)) in actual
5698            .chunks_exact(4)
5699            .zip(expected.chunks_exact(4))
5700            .enumerate()
5701        {
5702            for channel in 0..4 {
5703                assert!(
5704                    actual_pixel[channel].abs_diff(expected_pixel[channel]) <= tolerance,
5705                    "pixel {pixel_index} channel {channel} differed by more than {tolerance}: got {}, expected {}",
5706                    actual_pixel[channel],
5707                    expected_pixel[channel]
5708                );
5709            }
5710        }
5711    }
5712
5713    #[test]
5714    fn renderer_draws_widget_shader_rect_gradient() {
5715        let mut scene = Scene::new();
5716        scene.push(SceneCommand::DrawShaderRect {
5717            rect: Rect::new(0.0, 0.0, 96.0, 24.0),
5718            shader: WidgetShader::ColorPickerHueBar,
5719        });
5720
5721        let frame = SceneFrame {
5722            window_id: WindowId::new(240),
5723            viewport: Size::new(96.0, 24.0),
5724            surface_size: Size::new(96.0, 24.0),
5725            scale_factor: 1.0,
5726            dirty_regions: Vec::new(),
5727            layer_updates: Vec::new(),
5728            scene,
5729            font_registry: Arc::new(FontRegistry::new()),
5730            image_registry: Arc::new(ImageRegistry::new()),
5731            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
5732        };
5733
5734        let mut renderer = WgpuRenderer::default();
5735        renderer.render(&frame).unwrap();
5736        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
5737        let left = rgba_pixel(&pixels, 4, 12);
5738        let right = rgba_pixel(&pixels, 72, 12);
5739
5740        assert!(left[3] > 200);
5741        assert!(right[3] > 200);
5742        assert_ne!(left, right);
5743    }
5744
5745    fn build_translucent_scroll_child_frame(
5746        window_id: WindowId,
5747        scroll_cache_policy: LayerCachePolicy,
5748        child_cache_policy: LayerCachePolicy,
5749        child_y: f32,
5750        update_kind: SceneLayerUpdateKind,
5751    ) -> SceneFrame {
5752        let shell_id = WidgetId::new(210);
5753        let scroll_id = WidgetId::new(211);
5754        let child_id = WidgetId::new(212);
5755        let scroll_bounds = Rect::new(24.0, 24.0, 382.0, 292.0);
5756        let child_bounds = Rect::new(42.0, child_y, 360.0, 220.0);
5757        let selected_row = Rect::new(42.0, child_y + 32.0, 360.0, 28.0);
5758        let thumb = Rect::new(396.0, child_y + 14.0, 4.0, 58.0);
5759
5760        let shell_descriptor = SceneLayerDescriptor::new(
5761            SceneLayerId::from_widget(shell_id),
5762            shell_id,
5763            Rect::new(0.0, 0.0, 430.0, 360.0),
5764        )
5765        .with_content_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
5766        .with_paint_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
5767        .with_cache_policy(LayerCachePolicy::Direct);
5768
5769        let scroll_descriptor = SceneLayerDescriptor::new(
5770            SceneLayerId::from_widget(scroll_id),
5771            scroll_id,
5772            scroll_bounds,
5773        )
5774        .with_content_bounds(scroll_bounds)
5775        .with_paint_bounds(scroll_bounds)
5776        .with_cache_policy(scroll_cache_policy)
5777        .with_composition_mode(LayerCompositionMode::Scroll);
5778
5779        let child_descriptor =
5780            SceneLayerDescriptor::new(SceneLayerId::from_widget(child_id), child_id, child_bounds)
5781                .with_content_bounds(child_bounds)
5782                .with_paint_bounds(child_bounds)
5783                .with_cache_policy(child_cache_policy);
5784
5785        let mut child_scene = Scene::new();
5786        child_scene.push(SceneCommand::FillRect {
5787            rect: child_bounds,
5788            brush: Color::rgba(0.985, 0.99, 1.0, 1.0).into(),
5789        });
5790        child_scene.push(SceneCommand::PushClip { rect: child_bounds });
5791        child_scene.push(SceneCommand::FillPath {
5792            path: Path::rounded_rect(selected_row, 6.0),
5793            brush: Color::rgba(0.09, 0.40, 0.92, 0.14).into(),
5794        });
5795        child_scene.push(SceneCommand::FillRect {
5796            rect: Rect::new(58.0, child_y + 40.0, 172.0, 12.0),
5797            brush: Color::rgba(0.17, 0.21, 0.29, 1.0).into(),
5798        });
5799        child_scene.push(SceneCommand::FillRect {
5800            rect: Rect::new(58.0, child_y + 64.0, 140.0, 10.0),
5801            brush: Color::rgba(0.45, 0.52, 0.61, 1.0).into(),
5802        });
5803        child_scene.push(SceneCommand::PopClip);
5804        child_scene.push(SceneCommand::FillPath {
5805            path: Path::rounded_rect(thumb, 2.0),
5806            brush: Color::rgba(0.54, 0.60, 0.68, 0.75).into(),
5807        });
5808
5809        let mut scroll_scene = Scene::new();
5810        scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
5811            child_descriptor.clone(),
5812            child_scene,
5813        )));
5814
5815        let mut shell_scene = Scene::new();
5816        shell_scene.push(SceneCommand::FillRect {
5817            rect: Rect::new(0.0, 0.0, 430.0, 360.0),
5818            brush: Color::rgba(0.95, 0.97, 0.99, 1.0).into(),
5819        });
5820        shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
5821            scroll_descriptor.clone(),
5822            scroll_scene,
5823        )));
5824
5825        let mut scene = Scene::new();
5826        scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
5827            shell_descriptor,
5828            shell_scene,
5829        )));
5830
5831        let update_damage = if update_kind == SceneLayerUpdateKind::Transform {
5832            Rect::new(42.0, 0.0, 360.0, 320.0)
5833        } else {
5834            child_bounds
5835        };
5836
5837        SceneFrame {
5838            window_id,
5839            viewport: Size::new(430.0, 360.0),
5840            surface_size: Size::new(430.0, 360.0),
5841            scale_factor: 1.0,
5842            dirty_regions: Vec::new(),
5843            layer_updates: vec![
5844                SceneLayerUpdate::from_descriptor(update_kind, child_descriptor)
5845                    .with_damage(update_damage),
5846            ],
5847            scene,
5848            font_registry: Arc::new(FontRegistry::new()),
5849            image_registry: Arc::new(ImageRegistry::new()),
5850            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
5851        }
5852    }
5853
5854    fn logical_x_from_ndc(ndc_x: f32, viewport: Size) -> f32 {
5855        ((ndc_x + 1.0) * 0.5) * viewport.width
5856    }
5857
5858    fn logical_y_from_ndc(ndc_y: f32, viewport: Size) -> f32 {
5859        ((1.0 - ndc_y) * 0.5) * viewport.height
5860    }
5861
5862    const PHYSICAL_PIXEL_ALIGNMENT_EPSILON: f32 = 0.005;
5863
5864    fn is_physically_pixel_aligned(value: f32, scale_factor: f32) -> bool {
5865        let physical = value * scale_factor;
5866        (physical - physical.round()).abs() <= PHYSICAL_PIXEL_ALIGNMENT_EPSILON
5867    }
5868
5869    #[test]
5870    fn build_vertices_applies_clip_and_transform_to_fill_rects() {
5871        let mut scene = Scene::new();
5872        scene.push(SceneCommand::PushTransform {
5873            transform: Transform::translation(10.0, 5.0),
5874        });
5875        scene.push(SceneCommand::PushClip {
5876            rect: Rect::new(0.0, 0.0, 16.0, 12.0),
5877        });
5878        scene.push(SceneCommand::FillRect {
5879            rect: Rect::new(4.0, 3.0, 20.0, 10.0),
5880            brush: Color::WHITE.into(),
5881        });
5882
5883        let mut text_engine = TextEngine::new().unwrap();
5884        let vertices = build_vertices(
5885            &SceneFrame {
5886                window_id: WindowId::new(1),
5887                viewport: Size::new(100.0, 100.0),
5888                surface_size: Size::new(100.0, 100.0),
5889                scale_factor: 1.0,
5890                dirty_regions: Vec::new(),
5891                layer_updates: Vec::new(),
5892                scene,
5893                font_registry: Arc::new(FontRegistry::new()),
5894                image_registry: Arc::new(ImageRegistry::new()),
5895                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
5896            },
5897            &mut text_engine,
5898        )
5899        .unwrap();
5900
5901        let expected_min = to_ndc(13.0, 7.0, Size::new(100.0, 100.0));
5902        let expected_max = to_ndc(26.0, 17.0, Size::new(100.0, 100.0));
5903
5904        assert_eq!(vertices.len(), 6);
5905        assert!(
5906            vertices
5907                .iter()
5908                .any(|vertex| vertex.position == expected_min)
5909        );
5910        assert!(
5911            vertices
5912                .iter()
5913                .any(|vertex| vertex.position == expected_max)
5914        );
5915        assert!(
5916            vertices
5917                .iter()
5918                .all(|vertex| vertex.shader_params == [10.0, 5.0, 0.0, DEFAULT_FEATHER_WIDTH])
5919        );
5920        assert!(
5921            vertices
5922                .iter()
5923                .any(|vertex| vertex.tex_coords == [-11.0, -6.0])
5924        );
5925        assert!(
5926            vertices
5927                .iter()
5928                .any(|vertex| vertex.tex_coords == [2.0, 4.0])
5929        );
5930    }
5931
5932    #[test]
5933    fn build_vertices_supports_text_and_stroke_primitives() {
5934        let mut scene = Scene::new();
5935        scene.push(SceneCommand::DrawText(TextRun {
5936            rect: Rect::new(4.0, 6.0, 80.0, 24.0),
5937            text: "scene".to_string(),
5938            style: TextStyle::new(Color::WHITE),
5939        }));
5940        scene.push(SceneCommand::StrokeRect {
5941            rect: Rect::new(2.0, 2.0, 20.0, 10.0),
5942            brush: Color::rgba(1.0, 0.0, 0.0, 1.0).into(),
5943            stroke: StrokeStyle::new(2.0),
5944        });
5945
5946        let mut text_engine = TextEngine::new().unwrap();
5947        let vertices = build_vertices(
5948            &SceneFrame {
5949                window_id: WindowId::new(2),
5950                viewport: Size::new(100.0, 80.0),
5951                surface_size: Size::new(100.0, 80.0),
5952                scale_factor: 1.0,
5953                dirty_regions: Vec::new(),
5954                layer_updates: Vec::new(),
5955                scene,
5956                font_registry: Arc::new(FontRegistry::new()),
5957                image_registry: Arc::new(ImageRegistry::new()),
5958                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
5959            },
5960            &mut text_engine,
5961        )
5962        .unwrap();
5963
5964        assert!(!vertices.is_empty());
5965        assert!(vertices.len() >= 30);
5966    }
5967
5968    #[test]
5969    fn build_vertices_supports_non_rect_paths() {
5970        let mut triangle = Path::builder();
5971        triangle
5972            .move_to(Point::new(10.0, 10.0))
5973            .line_to(Point::new(40.0, 10.0))
5974            .line_to(Point::new(24.0, 36.0))
5975            .close();
5976
5977        let mut curve = Path::builder();
5978        curve
5979            .move_to(Point::new(8.0, 44.0))
5980            .quad_to(Point::new(24.0, 24.0), Point::new(48.0, 44.0));
5981
5982        let mut scene = Scene::new();
5983        scene.push(SceneCommand::FillPath {
5984            path: triangle.build(),
5985            brush: Color::rgba(0.2, 0.8, 0.4, 1.0).into(),
5986        });
5987        scene.push(SceneCommand::StrokePath {
5988            path: curve.build(),
5989            brush: Color::rgba(0.9, 0.4, 0.2, 1.0).into(),
5990            stroke: StrokeStyle::new(3.0),
5991        });
5992
5993        let mut text_engine = TextEngine::new().unwrap();
5994        let vertices = build_vertices(
5995            &SceneFrame {
5996                window_id: WindowId::new(5),
5997                viewport: Size::new(80.0, 60.0),
5998                surface_size: Size::new(80.0, 60.0),
5999                scale_factor: 1.0,
6000                dirty_regions: Vec::new(),
6001                layer_updates: Vec::new(),
6002                scene,
6003                font_registry: Arc::new(FontRegistry::new()),
6004                image_registry: Arc::new(ImageRegistry::new()),
6005                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
6006            },
6007            &mut text_engine,
6008        )
6009        .unwrap();
6010
6011        assert!(!vertices.is_empty());
6012        assert!(vertices.len() >= 12);
6013    }
6014
6015    #[test]
6016    fn shader_color_linearizes_srgb_inputs() {
6017        let rgba = shader_color(Color::srgba(66.0 / 255.0, 42.0 / 255.0, 213.0 / 255.0, 1.0));
6018
6019        assert!((rgba[0] - 0.05448).abs() < 0.0001);
6020        assert!((rgba[1] - 0.02315).abs() < 0.0001);
6021        assert!((rgba[2] - 0.66539).abs() < 0.0001);
6022        assert_eq!(rgba[3], 1.0);
6023    }
6024
6025    #[test]
6026    fn shader_color_converts_display_p3_primaries_into_linear_srgb_working_space() {
6027        let rgba = shader_color(Color::display_p3(1.0, 0.0, 0.0, 1.0));
6028
6029        assert!((rgba[0] - 1.22494).abs() < 0.0001);
6030        assert!((rgba[1] + 0.04205).abs() < 0.0001);
6031        assert!((rgba[2] + 0.01963).abs() < 0.0001);
6032        assert_eq!(rgba[3], 1.0);
6033    }
6034
6035    #[test]
6036    fn shader_color_preserves_extended_linear_srgb_values_for_hdr_content() {
6037        let rgba = shader_color(Color::linear_rgba(2.0, 4.0, 8.0, 1.0));
6038
6039        assert_eq!(rgba, [2.0, 4.0, 8.0, 1.0]);
6040    }
6041
6042    #[test]
6043    fn select_output_strategy_prefers_wide_gamut_when_requested_and_supported() {
6044        let strategy = select_output_strategy(
6045            &[wgpu::TextureFormat::Bgra8UnormSrgb],
6046            DisplayCapabilities {
6047                supports_wide_gamut: true,
6048                preferred_primaries: DisplayColorPrimaries::DisplayP3,
6049                ..DisplayCapabilities::default()
6050            },
6051            ColorManagementMode {
6052                mode: RequestedColorManagementMode::PreferWideGamut,
6053                output_primaries: RequestedOutputColorPrimaries::DisplayP3,
6054                dynamic_range: RequestedDynamicRangeMode::Automatic,
6055                tone_mapping: RequestedToneMappingMode::Automatic,
6056                ..ColorManagementMode::default()
6057            },
6058        );
6059
6060        assert_eq!(
6061            strategy,
6062            OutputStrategy::WideGamutSurface {
6063                format: wgpu::TextureFormat::Bgra8UnormSrgb,
6064                primaries: DisplayColorPrimaries::DisplayP3,
6065            }
6066        );
6067    }
6068
6069    #[test]
6070    fn select_output_strategy_automatic_uses_wide_gamut_when_supported() {
6071        let strategy = select_output_strategy(
6072            &[wgpu::TextureFormat::Bgra8UnormSrgb],
6073            DisplayCapabilities {
6074                supports_wide_gamut: true,
6075                preferred_primaries: DisplayColorPrimaries::DisplayP3,
6076                ..DisplayCapabilities::default()
6077            },
6078            ColorManagementMode::default(),
6079        );
6080
6081        assert_eq!(
6082            strategy,
6083            OutputStrategy::WideGamutSurface {
6084                format: wgpu::TextureFormat::Bgra8UnormSrgb,
6085                primaries: DisplayColorPrimaries::DisplayP3,
6086            }
6087        );
6088    }
6089
6090    #[test]
6091    fn select_output_strategy_automatic_uses_native_hdr_when_supported() {
6092        let strategy = select_output_strategy(
6093            &[
6094                wgpu::TextureFormat::Rgba16Float,
6095                wgpu::TextureFormat::Bgra8UnormSrgb,
6096            ],
6097            DisplayCapabilities {
6098                supports_wide_gamut: true,
6099                supports_hdr: true,
6100                preferred_primaries: DisplayColorPrimaries::Srgb,
6101                preferred_dynamic_range: DynamicRangeMode::HighDynamicRange,
6102                native_hdr_presentation_supported: true,
6103                ..DisplayCapabilities::default()
6104            },
6105            ColorManagementMode::default(),
6106        );
6107
6108        assert_eq!(
6109            strategy,
6110            OutputStrategy::HdrNativeSurface {
6111                format: wgpu::TextureFormat::Rgba16Float,
6112                primaries: DisplayColorPrimaries::Srgb,
6113                transfer: DisplayTransferFunction::LinearExtended,
6114            }
6115        );
6116    }
6117
6118    #[test]
6119    fn select_output_strategy_automatic_ignores_float16_without_native_hdr_support() {
6120        let strategy = select_output_strategy(
6121            &[
6122                wgpu::TextureFormat::Rgba16Float,
6123                wgpu::TextureFormat::Bgra8UnormSrgb,
6124            ],
6125            DisplayCapabilities {
6126                supports_wide_gamut: true,
6127                supports_hdr: false,
6128                preferred_primaries: DisplayColorPrimaries::DisplayP3,
6129                preferred_dynamic_range: DynamicRangeMode::StandardDynamicRange,
6130                native_hdr_presentation_supported: false,
6131                ..DisplayCapabilities::default()
6132            },
6133            ColorManagementMode::default(),
6134        );
6135
6136        assert_eq!(
6137            strategy,
6138            OutputStrategy::WideGamutSurface {
6139                format: wgpu::TextureFormat::Bgra8UnormSrgb,
6140                primaries: DisplayColorPrimaries::DisplayP3,
6141            }
6142        );
6143    }
6144
6145    #[test]
6146    fn select_output_strategy_hdr_support_without_native_uses_sdr_despite_float16() {
6147        let strategy = select_output_strategy(
6148            &[
6149                wgpu::TextureFormat::Rgba16Float,
6150                wgpu::TextureFormat::Bgra8UnormSrgb,
6151            ],
6152            DisplayCapabilities {
6153                supports_wide_gamut: true,
6154                supports_hdr: true,
6155                preferred_primaries: DisplayColorPrimaries::Srgb,
6156                preferred_dynamic_range: DynamicRangeMode::HighDynamicRange,
6157                native_hdr_presentation_supported: false,
6158                ..DisplayCapabilities::default()
6159            },
6160            ColorManagementMode::default(),
6161        );
6162
6163        assert_eq!(
6164            strategy,
6165            OutputStrategy::SdrSurface {
6166                format: wgpu::TextureFormat::Bgra8UnormSrgb,
6167            }
6168        );
6169    }
6170
6171    #[test]
6172    fn select_output_strategy_automatic_hdr_falls_back_to_sdr_without_native_hdr() {
6173        let strategy = select_output_strategy(
6174            &[wgpu::TextureFormat::Bgra8UnormSrgb],
6175            DisplayCapabilities {
6176                supports_wide_gamut: true,
6177                supports_hdr: true,
6178                preferred_primaries: DisplayColorPrimaries::DisplayP3,
6179                preferred_dynamic_range: DynamicRangeMode::HighDynamicRange,
6180                native_hdr_presentation_supported: false,
6181                ..DisplayCapabilities::default()
6182            },
6183            ColorManagementMode::default(),
6184        );
6185
6186        assert_eq!(
6187            strategy,
6188            OutputStrategy::SdrSurface {
6189                format: wgpu::TextureFormat::Bgra8UnormSrgb,
6190            }
6191        );
6192    }
6193
6194    #[test]
6195    fn select_output_strategy_explicit_sdr_disables_automatic_hdr() {
6196        let strategy = select_output_strategy(
6197            &[
6198                wgpu::TextureFormat::Rgba16Float,
6199                wgpu::TextureFormat::Bgra8UnormSrgb,
6200            ],
6201            DisplayCapabilities {
6202                supports_wide_gamut: true,
6203                supports_hdr: true,
6204                preferred_primaries: DisplayColorPrimaries::DisplayP3,
6205                preferred_dynamic_range: DynamicRangeMode::HighDynamicRange,
6206                native_hdr_presentation_supported: false,
6207                ..DisplayCapabilities::default()
6208            },
6209            ColorManagementMode {
6210                dynamic_range: RequestedDynamicRangeMode::StandardDynamicRange,
6211                ..ColorManagementMode::default()
6212            },
6213        );
6214
6215        assert_eq!(
6216            strategy,
6217            OutputStrategy::WideGamutSurface {
6218                format: wgpu::TextureFormat::Bgra8UnormSrgb,
6219                primaries: DisplayColorPrimaries::DisplayP3,
6220            }
6221        );
6222    }
6223
6224    #[test]
6225    fn select_output_strategy_uses_sdr_when_hdr_is_requested_without_native_support() {
6226        let strategy = select_output_strategy(
6227            &[wgpu::TextureFormat::Bgra8UnormSrgb],
6228            DisplayCapabilities {
6229                supports_wide_gamut: true,
6230                supports_hdr: true,
6231                preferred_primaries: DisplayColorPrimaries::DisplayP3,
6232                preferred_dynamic_range: DynamicRangeMode::HighDynamicRange,
6233                native_hdr_presentation_supported: false,
6234                ..DisplayCapabilities::default()
6235            },
6236            ColorManagementMode {
6237                mode: RequestedColorManagementMode::PreferHdr,
6238                output_primaries: RequestedOutputColorPrimaries::DisplayP3,
6239                dynamic_range: RequestedDynamicRangeMode::HighDynamicRange,
6240                tone_mapping: RequestedToneMappingMode::Automatic,
6241                ..ColorManagementMode::default()
6242            },
6243        );
6244
6245        assert_eq!(
6246            strategy,
6247            OutputStrategy::SdrSurface {
6248                format: wgpu::TextureFormat::Bgra8UnormSrgb,
6249            }
6250        );
6251    }
6252
6253    #[test]
6254    fn select_output_strategy_uses_native_hdr_scrgb_surface_when_supported() {
6255        let strategy = select_output_strategy(
6256            &[
6257                wgpu::TextureFormat::Rgba16Float,
6258                wgpu::TextureFormat::Bgra8UnormSrgb,
6259            ],
6260            DisplayCapabilities {
6261                supports_wide_gamut: true,
6262                supports_hdr: true,
6263                preferred_primaries: DisplayColorPrimaries::Srgb,
6264                preferred_dynamic_range: DynamicRangeMode::HighDynamicRange,
6265                native_hdr_presentation_supported: true,
6266                ..DisplayCapabilities::default()
6267            },
6268            ColorManagementMode {
6269                mode: RequestedColorManagementMode::PreferHdr,
6270                output_primaries: RequestedOutputColorPrimaries::DisplayP3,
6271                dynamic_range: RequestedDynamicRangeMode::HighDynamicRange,
6272                tone_mapping: RequestedToneMappingMode::Automatic,
6273                ..ColorManagementMode::default()
6274            },
6275        );
6276
6277        assert_eq!(
6278            strategy,
6279            OutputStrategy::HdrNativeSurface {
6280                format: wgpu::TextureFormat::Rgba16Float,
6281                primaries: DisplayColorPrimaries::Srgb,
6282                transfer: DisplayTransferFunction::LinearExtended,
6283            }
6284        );
6285    }
6286
6287    #[test]
6288    fn hdr_output_transform_requires_intermediate_for_hdr_strategies() {
6289        assert!(output_transform_requires_intermediate(
6290            OutputStrategy::HdrIntermediateThenToneMap {
6291                intermediate_format: wgpu::TextureFormat::Rgba16Float,
6292                surface_format: wgpu::TextureFormat::Bgra8UnormSrgb,
6293                primaries: DisplayColorPrimaries::DisplayP3,
6294            }
6295        ));
6296        assert!(output_transform_requires_intermediate(
6297            OutputStrategy::HdrNativeSurface {
6298                format: wgpu::TextureFormat::Rgba16Float,
6299                primaries: DisplayColorPrimaries::DisplayP3,
6300                transfer: DisplayTransferFunction::LinearExtended,
6301            }
6302        ));
6303        assert!(!output_transform_requires_intermediate(
6304            OutputStrategy::SdrSurface {
6305                format: wgpu::TextureFormat::Bgra8UnormSrgb,
6306            }
6307        ));
6308    }
6309
6310    #[test]
6311    fn wide_gamut_output_transform_runs_even_for_srgb_surface_formats() {
6312        assert!(output_transform_requires_intermediate(
6313            OutputStrategy::WideGamutSurface {
6314                format: wgpu::TextureFormat::Bgra8UnormSrgb,
6315                primaries: DisplayColorPrimaries::DisplayP3,
6316            }
6317        ));
6318    }
6319
6320    #[test]
6321    fn reinhard_tone_mapping_compresses_extended_linear_values() {
6322        let transformed =
6323            tone_map_linear_color([4.0, 1.0, 0.5, 1.0], RequestedToneMappingMode::Reinhard);
6324
6325        assert!(transformed[0] < 1.0);
6326        assert!(transformed[0] > transformed[1]);
6327        assert_eq!(transformed[3], 1.0);
6328    }
6329
6330    #[test]
6331    fn clamp_tone_mapping_limits_linear_values_to_sdr_range() {
6332        let transformed =
6333            tone_map_linear_color([2.5, 1.25, 0.5, 1.0], RequestedToneMappingMode::Clamp);
6334
6335        assert_eq!(transformed, [1.0, 1.0, 0.5, 1.0]);
6336    }
6337
6338    #[test]
6339    fn hdr_output_transform_scales_reference_white_to_requested_sdr_content_brightness() {
6340        let transformed = apply_output_transform_for_testing(
6341            [1.0, 1.0, 1.0, 1.0],
6342            OutputStrategy::HdrNativeSurface {
6343                format: wgpu::TextureFormat::Rgba16Float,
6344                primaries: DisplayColorPrimaries::Srgb,
6345                transfer: DisplayTransferFunction::LinearExtended,
6346            },
6347            RequestedToneMappingMode::Automatic,
6348            203.0,
6349            None,
6350        );
6351
6352        let expected = 203.0 / 80.0;
6353        assert!((transformed[0] - expected).abs() < 0.0001);
6354        assert!((transformed[1] - expected).abs() < 0.0001);
6355        assert!((transformed[2] - expected).abs() < 0.0001);
6356        assert_eq!(transformed[3], 1.0);
6357    }
6358
6359    #[test]
6360    fn native_hdr_output_preserves_requested_reference_white_even_with_manual_tone_mapping_modes() {
6361        let strategy = OutputStrategy::HdrNativeSurface {
6362            format: wgpu::TextureFormat::Rgba16Float,
6363            primaries: DisplayColorPrimaries::Srgb,
6364            transfer: DisplayTransferFunction::LinearExtended,
6365        };
6366        let expected = 203.0 / 80.0;
6367
6368        for mode in [
6369            RequestedToneMappingMode::Automatic,
6370            RequestedToneMappingMode::Clamp,
6371            RequestedToneMappingMode::Reinhard,
6372        ] {
6373            let transformed = apply_output_transform_for_testing(
6374                [1.0, 1.0, 1.0, 1.0],
6375                strategy,
6376                mode,
6377                203.0,
6378                None,
6379            );
6380            assert!((transformed[0] - expected).abs() < 0.0001, "mode={mode:?}");
6381            assert!((transformed[1] - expected).abs() < 0.0001, "mode={mode:?}");
6382            assert!((transformed[2] - expected).abs() < 0.0001, "mode={mode:?}");
6383            assert_eq!(transformed[3], 1.0, "mode={mode:?}");
6384        }
6385    }
6386
6387    #[test]
6388    fn native_hdr_output_uses_sc_rgb_reference_white_when_display_sdr_white_is_reported() {
6389        let strategy = OutputStrategy::HdrNativeSurface {
6390            format: wgpu::TextureFormat::Rgba16Float,
6391            primaries: DisplayColorPrimaries::DisplayP3,
6392            transfer: DisplayTransferFunction::LinearExtended,
6393        };
6394        let transformed = apply_output_transform_for_testing(
6395            [1.0, 1.0, 1.0, 1.0],
6396            strategy,
6397            RequestedToneMappingMode::Automatic,
6398            101.5,
6399            Some(203.0),
6400        );
6401
6402        let expected = 101.5 / 80.0;
6403        assert!((transformed[0] - expected).abs() < 0.0001);
6404        assert!((transformed[1] - expected).abs() < 0.0001);
6405        assert!((transformed[2] - expected).abs() < 0.0001);
6406        assert_eq!(transformed[3], 1.0);
6407    }
6408
6409    #[test]
6410    fn output_transform_maps_linear_srgb_to_display_p3_canvas_primaries() {
6411        let transformed = apply_output_transform_for_testing(
6412            [1.0, 0.55, 0.18, 1.0],
6413            OutputStrategy::HdrNativeSurface {
6414                format: wgpu::TextureFormat::Rgba16Float,
6415                primaries: DisplayColorPrimaries::DisplayP3,
6416                transfer: DisplayTransferFunction::Srgb,
6417            },
6418            RequestedToneMappingMode::Automatic,
6419            80.0,
6420            None,
6421        );
6422
6423        assert!((transformed[0] - 0.920_107_84).abs() < 0.0001);
6424        assert!((transformed[1] - 0.564_937_35).abs() < 0.0001);
6425        assert!((transformed[2] - 0.220_794_81).abs() < 0.0001);
6426        assert_eq!(transformed[3], 1.0);
6427    }
6428
6429    #[test]
6430    fn hdr_tone_mapped_output_preserves_sdr_reference_white_by_default() {
6431        let transformed = apply_output_transform_for_testing(
6432            [1.0, 1.0, 1.0, 1.0],
6433            OutputStrategy::HdrIntermediateThenToneMap {
6434                intermediate_format: wgpu::TextureFormat::Rgba16Float,
6435                surface_format: wgpu::TextureFormat::Bgra8UnormSrgb,
6436                primaries: DisplayColorPrimaries::DisplayP3,
6437            },
6438            RequestedToneMappingMode::Automatic,
6439            203.0,
6440            None,
6441        );
6442
6443        assert!((transformed[0] - 1.0).abs() < 0.0001);
6444        assert!((transformed[1] - 1.0).abs() < 0.0001);
6445        assert!((transformed[2] - 1.0).abs() < 0.0001);
6446        assert_eq!(transformed[3], 1.0);
6447    }
6448
6449    #[test]
6450    fn hdr_tone_mapped_output_keeps_reinhard_as_explicit_opt_in() {
6451        let transformed = apply_output_transform_for_testing(
6452            [1.0, 1.0, 1.0, 1.0],
6453            OutputStrategy::HdrIntermediateThenToneMap {
6454                intermediate_format: wgpu::TextureFormat::Rgba16Float,
6455                surface_format: wgpu::TextureFormat::Bgra8UnormSrgb,
6456                primaries: DisplayColorPrimaries::Srgb,
6457            },
6458            RequestedToneMappingMode::Reinhard,
6459            203.0,
6460            None,
6461        );
6462
6463        let expected = 0.5;
6464        assert!((transformed[0] - expected).abs() < 0.0001);
6465        assert!((transformed[1] - expected).abs() < 0.0001);
6466        assert!((transformed[2] - expected).abs() < 0.0001);
6467        assert_eq!(transformed[3], 1.0);
6468    }
6469
6470    #[test]
6471    fn shader_color_preserves_linear_display_p3_channels_before_gamut_conversion() {
6472        let encoded = shader_color(Color::display_p3(0.5, 0.25, 0.75, 1.0));
6473        let linear = shader_color(Color::linear_display_p3(
6474            0.21404114, 0.05087609, 0.52252156, 1.0,
6475        ));
6476
6477        for index in 0..3 {
6478            assert!((encoded[index] - linear[index]).abs() < 0.0001);
6479        }
6480        assert_eq!(linear[3], 1.0);
6481    }
6482
6483    #[test]
6484    fn cached_path_mesh_linearizes_srgb_inputs() {
6485        let mut mesh = CachedGlyphMesh::default();
6486        let a = mesh.push_vertex(Point::new(0.0, 0.0), 1.0);
6487        let b = mesh.push_vertex(Point::new(10.0, 0.0), 1.0);
6488        let c = mesh.push_vertex(Point::new(0.0, 10.0), 1.0);
6489        mesh.add_triangle(a, b, c);
6490
6491        let color = Color::srgba(66.0 / 255.0, 42.0 / 255.0, 213.0 / 255.0, 1.0);
6492        let mut vertices = Vec::new();
6493        append_cached_path_mesh(&mut vertices, &mesh, color, Size::new(32.0, 32.0));
6494
6495        assert_eq!(vertices.len(), 3);
6496        let expected = shader_color(color);
6497        for vertex in vertices {
6498            assert!((vertex.color[0] - expected[0]).abs() < 0.0001);
6499            assert!((vertex.color[1] - expected[1]).abs() < 0.0001);
6500            assert!((vertex.color[2] - expected[2]).abs() < 0.0001);
6501            assert_eq!(vertex.color[3], 1.0);
6502        }
6503    }
6504
6505    #[test]
6506    fn cached_glyph_atlas_linearizes_srgb_inputs() {
6507        let atlas = CachedGlyphAtlas {
6508            scale: 12.0,
6509            offset: Vector::new(1.0, 2.0),
6510            size: Size::new(8.0, 10.0),
6511            uv_min: [0.25, 0.5],
6512            uv_max: [0.5, 0.75],
6513            color_mode: TextAtlasColorMode::Grayscale,
6514            is_color: false,
6515            page_index: 0,
6516        };
6517        let glyph = ShapedGlyph {
6518            glyph_id: 42,
6519            cluster: 0,
6520            span_id: sui_text::TextSpanId {
6521                paragraph_index: 0,
6522                span_index: 0,
6523            },
6524            run_index: 0,
6525            line_index: 0,
6526            face_index: 0,
6527            origin_x: 12.0,
6528            origin_y: 20.0,
6529            advance: Vector::new(8.0, 0.0),
6530            scale: 12.0,
6531            bounds: Some(Rect::new(13.0, 22.0, 8.0, 10.0)),
6532        };
6533
6534        let color = Color::srgba(66.0 / 255.0, 42.0 / 255.0, 213.0 / 255.0, 0.75);
6535        let mut vertices = Vec::new();
6536        append_cached_glyph_atlas(
6537            &mut vertices,
6538            &atlas,
6539            &glyph,
6540            color,
6541            Transform::IDENTITY,
6542            Size::new(64.0, 64.0),
6543            1.0,
6544        );
6545
6546        assert_eq!(vertices.len(), 6);
6547        let expected = shader_color(color);
6548        for vertex in vertices {
6549            assert!((vertex.color[0] - expected[0]).abs() < 0.0001);
6550            assert!((vertex.color[1] - expected[1]).abs() < 0.0001);
6551            assert!((vertex.color[2] - expected[2]).abs() < 0.0001);
6552            assert!((vertex.color[3] - expected[3]).abs() < 0.0001);
6553        }
6554    }
6555
6556    #[test]
6557    fn cached_glyph_atlas_places_quad_from_subpixel_phase_integer() {
6558        let atlas = CachedGlyphAtlas {
6559            scale: 12.0,
6560            offset: Vector::ZERO,
6561            size: Size::new(8.0, 10.0),
6562            uv_min: [0.25, 0.5],
6563            uv_max: [0.5, 0.75],
6564            color_mode: TextAtlasColorMode::Grayscale,
6565            is_color: false,
6566            page_index: 0,
6567        };
6568        let glyph = ShapedGlyph {
6569            glyph_id: 42,
6570            cluster: 0,
6571            span_id: sui_text::TextSpanId {
6572                paragraph_index: 0,
6573                span_index: 0,
6574            },
6575            run_index: 0,
6576            line_index: 0,
6577            face_index: 0,
6578            origin_x: 10.75,
6579            origin_y: 20.0,
6580            advance: Vector::new(8.0, 0.0),
6581            scale: 12.0,
6582            bounds: None,
6583        };
6584        let viewport = Size::new(64.0, 64.0);
6585        let mut vertices = Vec::new();
6586        append_cached_glyph_atlas(
6587            &mut vertices,
6588            &atlas,
6589            &glyph,
6590            Color::WHITE,
6591            Transform::IDENTITY,
6592            viewport,
6593            1.0,
6594        );
6595
6596        assert_eq!(vertices.len(), 6);
6597        let left = logical_x_from_ndc(vertices[0].position[0], viewport);
6598        assert!((left - 10.0).abs() < 0.0001);
6599    }
6600
6601    #[test]
6602    fn swash_placement_offsets_are_converted_to_screen_space() {
6603        let offset = glyph_raster_offset(
6604            &swash::zeno::Placement {
6605                left: 6,
6606                top: 10,
6607                width: 12,
6608                height: 14,
6609            },
6610            2.0,
6611        );
6612
6613        assert_eq!(offset, Vector::new(3.0, -5.0));
6614    }
6615
6616    #[test]
6617    fn cached_color_glyph_atlas_uses_opacity_sentinel() {
6618        let atlas = CachedGlyphAtlas {
6619            scale: 12.0,
6620            offset: Vector::new(1.0, 2.0),
6621            size: Size::new(8.0, 10.0),
6622            uv_min: [0.25, 0.5],
6623            uv_max: [0.5, 0.75],
6624            color_mode: TextAtlasColorMode::Grayscale,
6625            is_color: true,
6626            page_index: 0,
6627        };
6628        let glyph = ShapedGlyph {
6629            glyph_id: 42,
6630            cluster: 0,
6631            span_id: sui_text::TextSpanId {
6632                paragraph_index: 0,
6633                span_index: 0,
6634            },
6635            run_index: 0,
6636            line_index: 0,
6637            face_index: 0,
6638            origin_x: 12.0,
6639            origin_y: 20.0,
6640            advance: Vector::new(8.0, 0.0),
6641            scale: 12.0,
6642            bounds: Some(Rect::new(13.0, 22.0, 8.0, 10.0)),
6643        };
6644
6645        let mut vertices = Vec::new();
6646        append_cached_glyph_atlas(
6647            &mut vertices,
6648            &atlas,
6649            &glyph,
6650            Color::srgba(0.2, 0.4, 0.6, 0.75),
6651            Transform::IDENTITY,
6652            Size::new(64.0, 64.0),
6653            1.0,
6654        );
6655
6656        assert_eq!(vertices.len(), 6);
6657        for vertex in vertices {
6658            assert_eq!(vertex.color[0], 1.0);
6659            assert_eq!(vertex.color[1], 1.0);
6660            assert_eq!(vertex.color[2], 1.0);
6661            assert_eq!(vertex.color[3], -0.75);
6662        }
6663    }
6664
6665    #[test]
6666    fn swash_color_glyph_images_store_srgb_for_text_atlas() {
6667        let image = swash::scale::image::Image {
6668            source: SwashSource::ColorBitmap(SwashStrikeWith::BestFit),
6669            content: SwashImageContent::Color,
6670            placement: swash::zeno::Placement {
6671                left: 0,
6672                top: 0,
6673                width: 1,
6674                height: 1,
6675            },
6676            data: vec![66, 42, 213, 128],
6677        };
6678
6679        let rasterized = swash_image_to_rgba(
6680            &image,
6681            14.0,
6682            TextRenderMode::Grayscale,
6683            TextSubpixelOrder::None,
6684            StemDarkening::None,
6685        )
6686        .expect("color glyph should convert into atlas pixels");
6687
6688        assert!(rasterized.is_color);
6689        // The atlas stores sRGB verbatim; the fragment shader linearizes at sample time.
6690        assert_rgba_pixels_near(
6691            &rasterized.pixels,
6692            &[66, 42, 213, 128],
6693            RGBA_CHANNEL_TOLERANCE,
6694        );
6695    }
6696
6697    #[test]
6698    fn text_atlas_shader_outputs_premultiplied_alpha() {
6699        let color = shader_color(Color::srgba(
6700            66.0 / 255.0,
6701            42.0 / 255.0,
6702            213.0 / 255.0,
6703            0.75,
6704        ));
6705        let coverage = 0.5;
6706        let alpha = color[3] * coverage;
6707        let premultiplied = [color[0] * alpha, color[1] * alpha, color[2] * alpha, alpha];
6708
6709        assert!((premultiplied[0] - 0.02043).abs() < 0.0001);
6710        assert!((premultiplied[1] - 0.00868).abs() < 0.0001);
6711        assert!((premultiplied[2] - 0.24952).abs() < 0.0001);
6712        assert!((premultiplied[3] - 0.375).abs() < 0.0001);
6713    }
6714
6715    #[test]
6716    fn color_text_atlas_shader_outputs_sampled_premultiplied_alpha() {
6717        // The atlas now holds sRGB; the shader linearizes the sampled color before premultiplying.
6718        fn srgb_to_linear(channel: f32) -> f32 {
6719            if channel <= 0.04045 {
6720                channel / 12.92
6721            } else {
6722                ((channel + 0.055) / 1.055).powf(2.4)
6723            }
6724        }
6725        let sampled_srgb = [66.0 / 255.0, 42.0 / 255.0, 213.0 / 255.0];
6726        let linear = [
6727            srgb_to_linear(sampled_srgb[0]),
6728            srgb_to_linear(sampled_srgb[1]),
6729            srgb_to_linear(sampled_srgb[2]),
6730        ];
6731        let sampled_alpha = 0.5;
6732        let opacity = 0.75;
6733        let alpha = sampled_alpha * opacity;
6734        let premultiplied = [
6735            linear[0] * alpha,
6736            linear[1] * alpha,
6737            linear[2] * alpha,
6738            alpha,
6739        ];
6740
6741        assert!((premultiplied[0] - linear[0] * 0.375).abs() < 0.0001);
6742        assert!((premultiplied[1] - linear[1] * 0.375).abs() < 0.0001);
6743        assert!((premultiplied[2] - linear[2] * 0.375).abs() < 0.0001);
6744        assert!((premultiplied[3] - 0.375).abs() < 0.0001);
6745    }
6746
6747    #[test]
6748    fn text_coverage_policy_matches_egui_reference_formulas() {
6749        assert!((TextCoveragePolicy::Linear.apply(0.5) - 0.5).abs() < 0.0001);
6750        assert!((TextCoveragePolicy::Gamma(2.0).apply(0.5) - 0.25).abs() < 0.0001);
6751        assert!((TextCoveragePolicy::CoverageBoost(0.5).apply(0.5) - 0.625).abs() < 0.0001);
6752        assert!((TextCoveragePolicy::TwoCoverageMinusCoverageSq.apply(0.5) - 0.75).abs() < 0.0001);
6753    }
6754
6755    #[test]
6756    fn text_coverage_policy_defaults_to_perceptual_luminance_curve() {
6757        assert_eq!(
6758            TextCoveragePolicy::default(),
6759            TextCoveragePolicy::Perceptual
6760        );
6761
6762        let TextCoveragePolicy::CoverageBoost(black_boost) =
6763            TextCoveragePolicy::default().resolved_for_text_color(Color::BLACK)
6764        else {
6765            panic!("perceptual coverage should resolve to a coverage boost policy");
6766        };
6767        let TextCoveragePolicy::CoverageBoost(white_boost) =
6768            TextCoveragePolicy::default().resolved_for_text_color(Color::WHITE)
6769        else {
6770            panic!("perceptual coverage should resolve to a coverage boost policy");
6771        };
6772
6773        assert!((black_boost - 0.92).abs() < 0.0001);
6774        assert!((white_boost - 0.45).abs() < 0.0001);
6775        assert!(black_boost > white_boost);
6776    }
6777
6778    #[test]
6779    fn text_render_mode_defaults_to_grayscale() {
6780        assert_eq!(TextRenderMode::default(), TextRenderMode::Grayscale);
6781    }
6782
6783    #[test]
6784    fn text_subpixel_order_defaults_to_none() {
6785        assert_eq!(TextSubpixelOrder::default(), TextSubpixelOrder::None);
6786        assert_eq!(
6787            WgpuRenderer::new().text_subpixel_order(),
6788            TextSubpixelOrder::None
6789        );
6790    }
6791
6792    #[test]
6793    fn slight_hinting_enables_below_threshold() {
6794        let config = TextHinting::Slight { max_ppem: 18.0 };
6795        assert!(config.should_hint(14.0));
6796        assert!(!config.should_hint(24.0));
6797    }
6798
6799    #[test]
6800    fn stem_darkening_applies_only_below_threshold() {
6801        let config = StemDarkening::Enabled {
6802            max_ppem: 18.0,
6803            amount: 0.08,
6804        };
6805        assert!(config.effective_amount(14.0) > 0.0);
6806        assert_eq!(config.effective_amount(24.0), 0.0);
6807    }
6808
6809    #[test]
6810    fn stem_darkening_boosts_partial_coverage() {
6811        let darkened = apply_stem_darkening_to_coverage(128, 0.1);
6812        assert!(darkened > 128);
6813    }
6814
6815    #[test]
6816    fn stem_darkening_preserves_transparent_and_opaque_endpoints() {
6817        // A transparent pixel must stay transparent — otherwise every glyph cell's background
6818        // gets lifted to `amount` opacity, painting a gray box behind each glyph. A fully
6819        // opaque pixel must stay opaque. This must hold even at a large darkening amount.
6820        for amount in [0.1, 0.5, 0.6, 1.0] {
6821            assert_eq!(apply_stem_darkening_to_coverage(0, amount), 0);
6822            assert_eq!(apply_stem_darkening_to_coverage(255, amount), 255);
6823        }
6824    }
6825
6826    #[test]
6827    fn lcd_text_render_mode_has_distinct_cache_identity() {
6828        assert_ne!(
6829            TextAtlasColorMode::from(TextRenderMode::Grayscale),
6830            TextAtlasColorMode::from(TextRenderMode::LcdSubpixel),
6831        );
6832    }
6833
6834    #[test]
6835    fn subpixel_mask_preserves_distinct_rgb_channels_in_lcd_mode() {
6836        let converted = convert_subpixel_texel_for_mode(
6837            [255, 128, 32, 255],
6838            TextRenderMode::LcdSubpixel,
6839            TextSubpixelOrder::Rgb,
6840            0.0,
6841        );
6842        assert_rgba_channels_near(&converted, [32, 128, 255, 255], RGBA_CHANNEL_TOLERANCE);
6843    }
6844
6845    #[test]
6846    fn subpixel_mask_can_reverse_physical_order_for_bgr_lcd() {
6847        let converted = convert_subpixel_texel_for_mode(
6848            [255, 128, 32, 255],
6849            TextRenderMode::LcdSubpixel,
6850            TextSubpixelOrder::Bgr,
6851            0.0,
6852        );
6853        assert_rgba_channels_near(&converted, [255, 128, 32, 255], RGBA_CHANNEL_TOLERANCE);
6854    }
6855
6856    #[test]
6857    fn subpixel_mask_uses_grayscale_when_subpixel_order_is_none() {
6858        let converted = convert_subpixel_texel_for_mode(
6859            [255, 128, 32, 255],
6860            TextRenderMode::LcdSubpixel,
6861            TextSubpixelOrder::None,
6862            0.0,
6863        );
6864        assert_rgba_channels_near(&converted, [255, 255, 255, 138], RGBA_CHANNEL_TOLERANCE);
6865    }
6866
6867    #[test]
6868    fn glyph_subpixel_offset_tracks_quarter_pixel_phase() {
6869        let glyph = ShapedGlyph {
6870            glyph_id: 42,
6871            cluster: 0,
6872            span_id: sui_text::TextSpanId {
6873                paragraph_index: 0,
6874                span_index: 0,
6875            },
6876            run_index: 0,
6877            line_index: 0,
6878            face_index: 0,
6879            origin_x: 10.25,
6880            origin_y: 20.0,
6881            advance: Vector::new(8.0, 0.0),
6882            scale: 12.0,
6883            bounds: None,
6884        };
6885
6886        assert_eq!(
6887            glyph_subpixel_offset(Transform::IDENTITY, Vector::ZERO, &glyph, 1.0),
6888            GlyphSubpixelOffsetKey::new(1, 0)
6889        );
6890        assert_eq!(
6891            glyph_subpixel_offset(Transform::IDENTITY, Vector::ZERO, &glyph, 2.0),
6892            GlyphSubpixelOffsetKey::new(2, 0)
6893        );
6894        assert_eq!(
6895            glyph_subpixel_offset(Transform::rotation(0.25), Vector::ZERO, &glyph, 1.0),
6896            GlyphSubpixelOffsetKey::default()
6897        );
6898    }
6899
6900    #[test]
6901    fn glyph_subpixel_offset_includes_layer_pixel_snap_phase() {
6902        let glyph = ShapedGlyph {
6903            glyph_id: 42,
6904            cluster: 0,
6905            span_id: sui_text::TextSpanId {
6906                paragraph_index: 0,
6907                span_index: 0,
6908            },
6909            run_index: 0,
6910            line_index: 0,
6911            face_index: 0,
6912            origin_x: 14.0,
6913            origin_y: 20.0,
6914            advance: Vector::new(8.0, 0.0),
6915            scale: 12.0,
6916            bounds: None,
6917        };
6918
6919        assert_eq!(
6920            glyph_subpixel_offset(
6921                Transform::IDENTITY,
6922                Vector::new(1.0 / 3.0, 0.0),
6923                &glyph,
6924                1.5
6925            ),
6926            GlyphSubpixelOffsetKey::new(2, 0)
6927        );
6928    }
6929
6930    #[test]
6931    fn glyph_cache_key_includes_subpixel_offset() {
6932        let face = GlyphFaceCacheKey {
6933            data_ptr: 0x1000,
6934            data_len: 128,
6935            face_index: 0,
6936        };
6937        let first = GlyphCacheKey::new(
6938            face,
6939            7,
6940            1024,
6941            GlyphSubpixelOffsetKey::new(0, 0),
6942            TextRenderMode::Grayscale,
6943            TextSubpixelOrder::None,
6944            TextHinting::None,
6945            StemDarkening::None,
6946            400,
6947        );
6948        let second = GlyphCacheKey::new(
6949            face,
6950            7,
6951            1024,
6952            GlyphSubpixelOffsetKey::new(1, 0),
6953            TextRenderMode::Grayscale,
6954            TextSubpixelOrder::None,
6955            TextHinting::None,
6956            StemDarkening::None,
6957            400,
6958        );
6959        assert_ne!(first, second);
6960    }
6961
6962    #[test]
6963    fn glyph_cache_key_includes_weight() {
6964        let face = GlyphFaceCacheKey {
6965            data_ptr: 0x1000,
6966            data_len: 128,
6967            face_index: 0,
6968        };
6969        let key = |weight| {
6970            GlyphCacheKey::new(
6971                face,
6972                7,
6973                1024,
6974                GlyphSubpixelOffsetKey::new(0, 0),
6975                TextRenderMode::Grayscale,
6976                TextSubpixelOrder::None,
6977                TextHinting::None,
6978                StemDarkening::None,
6979                weight,
6980            )
6981        };
6982        // Different weights of a variable font rasterize differently -> distinct cache entries.
6983        assert_ne!(key(400), key(700));
6984        assert_eq!(key(700), key(700));
6985    }
6986
6987    #[test]
6988    fn glyph_cache_key_includes_subpixel_order() {
6989        let face = GlyphFaceCacheKey {
6990            data_ptr: 0x1000,
6991            data_len: 128,
6992            face_index: 0,
6993        };
6994        let key = |order| {
6995            GlyphCacheKey::new(
6996                face,
6997                7,
6998                1024,
6999                GlyphSubpixelOffsetKey::new(0, 0),
7000                TextRenderMode::LcdSubpixel,
7001                order,
7002                TextHinting::None,
7003                StemDarkening::None,
7004                400,
7005            )
7006        };
7007        assert_ne!(key(TextSubpixelOrder::Rgb), key(TextSubpixelOrder::Bgr));
7008        assert_eq!(key(TextSubpixelOrder::None), key(TextSubpixelOrder::None));
7009    }
7010
7011    #[test]
7012    fn text_atlas_shaders_use_sampled_coverage_and_dual_source_blending() {
7013        assert!(TEXT_ATLAS_SHADER_SOURCE.contains("fn apply_text_coverage"));
7014        assert!(TEXT_ATLAS_SHADER_SOURCE.contains("apply_text_coverage(sampled.a"));
7015        assert!(!TEXT_ATLAS_SHADER_SOURCE.contains("TEXT_COVERAGE_GAMMA"));
7016        assert!(TEXT_ATLAS_DUAL_SOURCE_SHADER_SOURCE.contains("@blend_src(0)"));
7017        assert!(TEXT_ATLAS_DUAL_SOURCE_SHADER_SOURCE.contains("@blend_src(1)"));
7018        assert!(TEXT_ATLAS_DUAL_SOURCE_SHADER_SOURCE.contains("fn apply_text_coverage"));
7019        assert!(TEXT_ATLAS_DUAL_SOURCE_SHADER_SOURCE.contains("apply_text_coverage(sampled.a"));
7020        assert!(!TEXT_ATLAS_DUAL_SOURCE_SHADER_SOURCE.contains("TEXT_COVERAGE_GAMMA"));
7021    }
7022
7023    #[test]
7024    fn lcd_text_requires_axis_aligned_pixel_snapped_path() {
7025        assert!(allows_lcd_text(Transform::IDENTITY));
7026        assert!(!allows_lcd_text(Transform::rotation(
7027            std::f32::consts::FRAC_PI_4
7028        )));
7029        assert!(!allows_lcd_text(Transform::scale(-1.0, 1.0)));
7030        assert!(!allows_lcd_text(Transform::rotation(std::f32::consts::PI)));
7031    }
7032
7033    #[test]
7034    fn analytic_path_fill_shader_uses_symmetric_signed_distance() {
7035        assert!(ANALYTIC_PATH_SHADER_SOURCE.contains("let signed_distance"));
7036        assert!(ANALYTIC_PATH_SHADER_SOURCE.contains("0.5 - (signed_distance"));
7037        let derivative = ANALYTIC_PATH_SHADER_SOURCE
7038            .find("let scene_dx = dpdx(in.scene_position)")
7039            .expect("analytic shader should derive AA width from scene position");
7040        let path_lookup = ANALYTIC_PATH_SHADER_SOURCE
7041            .find("let path_meta = path_metas[in.path_index]")
7042            .expect("analytic shader should load path metadata");
7043        assert!(
7044            derivative < path_lookup,
7045            "derivatives must precede path-indexed non-uniform control flow"
7046        );
7047        assert!(ANALYTIC_PATH_SHADER_SOURCE.contains("let scene_dy = dpdy(in.scene_position)"));
7048        assert!(!ANALYTIC_PATH_SHADER_SOURCE.contains("dpdx(min_distance)"));
7049        assert!(!ANALYTIC_PATH_SHADER_SOURCE.contains("dpdy(min_distance)"));
7050        assert!(!ANALYTIC_PATH_SHADER_SOURCE.contains("fwidth(point.x)"));
7051        assert!(!ANALYTIC_PATH_SHADER_SOURCE.contains("1.0 - (min_distance"));
7052    }
7053
7054    #[test]
7055    fn analytic_path_shader_passes_wgsl_uniformity_validation() {
7056        let module = naga::front::wgsl::parse_str(ANALYTIC_PATH_SHADER_SOURCE)
7057            .expect("analytic path WGSL should parse");
7058        naga::valid::Validator::new(
7059            naga::valid::ValidationFlags::all(),
7060            naga::valid::Capabilities::all(),
7061        )
7062        .validate(&module)
7063        .expect("analytic path WGSL should satisfy uniform-control-flow validation");
7064    }
7065
7066    #[test]
7067    fn atlas_text_snaps_repeated_stems_to_physical_pixels() {
7068        let handle = FontHandle::new(31);
7069        let mut fonts = FontRegistry::new();
7070        fonts.insert(handle, load_test_font());
7071
7072        let viewport = Size::new(260.0, 52.0);
7073        let frame = SceneFrame {
7074            window_id: WindowId::new(98),
7075            viewport,
7076            surface_size: Size::new(390.0, 78.0),
7077            scale_factor: 1.5,
7078            dirty_regions: Vec::new(),
7079            layer_updates: Vec::new(),
7080            scene: {
7081                let mut scene = Scene::new();
7082                scene.push(SceneCommand::DrawText(TextRun {
7083                    rect: Rect::new(8.0, 10.0, 220.0, 24.0),
7084                    text: "scroll".to_string(),
7085                    style: TextStyle {
7086                        font: Some(handle),
7087                        font_size: 14.0,
7088                        line_height: 18.0,
7089                        color: Color::rgba(0.12, 0.16, 0.22, 1.0),
7090                        ..TextStyle::default()
7091                    },
7092                }));
7093                scene
7094            },
7095            font_registry: Arc::new(fonts),
7096            image_registry: Arc::new(ImageRegistry::new()),
7097            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7098        };
7099
7100        let mut text_engine = TextEngine::new().unwrap();
7101        let vertices = build_vertices(&frame, &mut text_engine).unwrap();
7102
7103        assert!(
7104            vertices.len() >= 12,
7105            "expected atlas vertices for repeated l glyphs"
7106        );
7107
7108        let first_l_left = logical_x_from_ndc(vertices[24].position[0], viewport);
7109        let second_l_left = logical_x_from_ndc(vertices[30].position[0], viewport);
7110
7111        assert!(
7112            is_physically_pixel_aligned(first_l_left, frame.scale_factor),
7113            "first l did not snap to the physical pixel grid: x={first_l_left}"
7114        );
7115        assert!(
7116            is_physically_pixel_aligned(second_l_left, frame.scale_factor),
7117            "second l did not snap to the physical pixel grid: x={second_l_left}"
7118        );
7119    }
7120
7121    #[test]
7122    fn atlas_text_is_position_invariant_at_matching_fractional_dpi_phase() {
7123        let handle = FontHandle::new(311);
7124        let mut fonts = FontRegistry::new();
7125        fonts.insert(handle, load_test_font());
7126
7127        let viewport = Size::new(260.0, 140.0);
7128        let outer_origin = Point::new(39.0, 2.3333333);
7129        let inner_origin = Point::new(58.333332, 97.666664);
7130        let delta = inner_origin - outer_origin;
7131        let frame = SceneFrame {
7132            window_id: WindowId::new(99),
7133            viewport,
7134            surface_size: Size::new(390.0, 210.0),
7135            scale_factor: 1.5,
7136            dirty_regions: Vec::new(),
7137            layer_updates: Vec::new(),
7138            scene: {
7139                let mut scene = Scene::new();
7140                for origin in [outer_origin, inner_origin] {
7141                    scene.push(SceneCommand::DrawText(TextRun {
7142                        rect: Rect::new(origin.x, origin.y, 180.0, 22.0),
7143                        text: "Light preview live updates".to_string(),
7144                        style: TextStyle {
7145                            font: Some(handle),
7146                            font_size: 14.0,
7147                            line_height: 20.0,
7148                            color: Color::rgba(0.12, 0.16, 0.22, 1.0),
7149                            ..TextStyle::default()
7150                        },
7151                    }));
7152                }
7153                scene
7154            },
7155            font_registry: Arc::new(fonts),
7156            image_registry: Arc::new(ImageRegistry::new()),
7157            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7158        };
7159
7160        let mut text_engine = TextEngine::new().unwrap();
7161        let vertices = build_vertices(&frame, &mut text_engine).unwrap();
7162
7163        assert_eq!(
7164            vertices.len() % 2,
7165            0,
7166            "expected identical text runs to produce an even vertex count"
7167        );
7168
7169        let split = vertices.len() / 2;
7170        let (outer_vertices, inner_vertices) = vertices.split_at(split);
7171        assert_eq!(outer_vertices.len(), inner_vertices.len());
7172
7173        for (index, (outer, inner)) in outer_vertices.iter().zip(inner_vertices.iter()).enumerate()
7174        {
7175            let outer_x = logical_x_from_ndc(outer.position[0], viewport);
7176            let outer_y = logical_y_from_ndc(outer.position[1], viewport);
7177            let inner_x = logical_x_from_ndc(inner.position[0], viewport);
7178            let inner_y = logical_y_from_ndc(inner.position[1], viewport);
7179            let normalized_inner_x = inner_x - delta.x;
7180            let normalized_inner_y = inner_y - delta.y;
7181
7182            assert!(
7183                (outer_x - normalized_inner_x).abs() < 0.0001,
7184                "vertex {index} changed x after translation normalization: outer={outer_x}, inner={inner_x}, delta_x={} ",
7185                delta.x,
7186            );
7187            assert!(
7188                (outer_y - normalized_inner_y).abs() < 0.0001,
7189                "vertex {index} changed y after translation normalization: outer={outer_y}, inner={inner_y}, delta_y={} ",
7190                delta.y,
7191            );
7192            assert_eq!(
7193                outer.tex_coords, inner.tex_coords,
7194                "vertex {index} UVs differ"
7195            );
7196            assert_eq!(outer.color, inner.color, "vertex {index} colors differ");
7197        }
7198    }
7199
7200    #[test]
7201    fn renderer_text_coverage_policy_shares_glyph_cache_entries_for_explicit_policies() {
7202        let handle = FontHandle::new(33);
7203        let mut fonts = FontRegistry::new();
7204        fonts.insert(handle, load_test_font());
7205
7206        let frame = SceneFrame {
7207            window_id: WindowId::new(201),
7208            viewport: Size::new(320.0, 84.0),
7209            surface_size: Size::new(320.0, 84.0),
7210            scale_factor: 1.25,
7211            dirty_regions: Vec::new(),
7212            layer_updates: Vec::new(),
7213            scene: {
7214                let mut scene = Scene::new();
7215                scene.push(SceneCommand::FillRect {
7216                    rect: Rect::new(0.0, 0.0, 320.0, 84.0),
7217                    brush: Color::BLACK.into(),
7218                });
7219                scene.push(SceneCommand::DrawText(TextRun {
7220                    rect: Rect::new(12.0, 8.0, 296.0, 64.0),
7221                    text: "Reusable".to_string(),
7222                    style: TextStyle {
7223                        font: Some(handle),
7224                        font_size: 55.5,
7225                        line_height: 59.5,
7226                        color: Color::WHITE,
7227                        ..TextStyle::default()
7228                    },
7229                }));
7230                scene
7231            },
7232            font_registry: Arc::new(fonts),
7233            image_registry: Arc::new(ImageRegistry::new()),
7234            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7235        };
7236
7237        let mut text_engine = TextEngine::new().unwrap();
7238        text_engine.set_text_coverage_policy(TextCoveragePolicy::Linear);
7239        let _ = build_vertices(&frame, &mut text_engine).unwrap();
7240        let linear_stats = text_engine.glyph_cache_stats();
7241
7242        text_engine.set_text_coverage_policy(TextCoveragePolicy::TwoCoverageMinusCoverageSq);
7243        let _ = build_vertices(&frame, &mut text_engine).unwrap();
7244        let dark_stats = text_engine.glyph_cache_stats();
7245
7246        assert!(
7247            linear_stats.0 > 0,
7248            "linear policy should populate the glyph cache"
7249        );
7250        assert!(
7251            linear_stats.2 > 0,
7252            "first pass should record glyph cache misses"
7253        );
7254        assert!(
7255            dark_stats.1 > linear_stats.1,
7256            "switching policy should reuse existing glyph cache entries"
7257        );
7258        assert_eq!(dark_stats.0, linear_stats.0);
7259        assert_eq!(dark_stats.2, linear_stats.2);
7260    }
7261
7262    #[test]
7263    fn text_render_policy_scope_overrides_and_restores_glyph_cache_policy() {
7264        let handle = FontHandle::new(36);
7265        let mut fonts = FontRegistry::new();
7266        fonts.insert(handle, load_test_font());
7267        let text_style = TextStyle {
7268            font: Some(handle),
7269            font_size: 24.0,
7270            line_height: 28.0,
7271            color: Color::WHITE,
7272            ..TextStyle::default()
7273        };
7274
7275        let frame = SceneFrame {
7276            window_id: WindowId::new(204),
7277            viewport: Size::new(120.0, 120.0),
7278            surface_size: Size::new(120.0, 120.0),
7279            scale_factor: 1.0,
7280            dirty_regions: Vec::new(),
7281            layer_updates: Vec::new(),
7282            scene: {
7283                let mut scene = Scene::new();
7284                scene.push(SceneCommand::DrawText(TextRun {
7285                    rect: Rect::new(8.0, 8.0, 80.0, 28.0),
7286                    text: "I".to_string(),
7287                    style: text_style.clone(),
7288                }));
7289                scene.push(SceneCommand::PushTextRenderPolicy {
7290                    policy: TextRenderPolicy::new()
7291                        .with_coverage_policy(TextRenderCoveragePolicy::TwoCoverageMinusCoverageSq),
7292                });
7293                scene.push(SceneCommand::DrawText(TextRun {
7294                    rect: Rect::new(8.0, 44.0, 80.0, 28.0),
7295                    text: "I".to_string(),
7296                    style: text_style.clone(),
7297                }));
7298                scene.push(SceneCommand::PopTextRenderPolicy);
7299                scene.push(SceneCommand::DrawText(TextRun {
7300                    rect: Rect::new(8.0, 80.0, 80.0, 28.0),
7301                    text: "I".to_string(),
7302                    style: text_style,
7303                }));
7304                scene
7305            },
7306            font_registry: Arc::new(fonts),
7307            image_registry: Arc::new(ImageRegistry::new()),
7308            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7309        };
7310
7311        let mut text_engine = TextEngine::new().unwrap();
7312        text_engine.set_text_coverage_policy(TextCoveragePolicy::Linear);
7313        let _ = build_vertices(&frame, &mut text_engine).unwrap();
7314
7315        assert_eq!(text_engine.glyph_cache_stats(), (1, 2, 1));
7316    }
7317
7318    #[test]
7319    fn text_render_policy_scope_overrides_and_restores_render_mode() {
7320        let handle = FontHandle::new(37);
7321        let mut fonts = FontRegistry::new();
7322        fonts.insert(handle, load_test_font());
7323        let text_style = TextStyle {
7324            font: Some(handle),
7325            font_size: 24.0,
7326            line_height: 28.0,
7327            color: Color::WHITE,
7328            ..TextStyle::default()
7329        };
7330
7331        let frame = SceneFrame {
7332            window_id: WindowId::new(205),
7333            viewport: Size::new(120.0, 120.0),
7334            surface_size: Size::new(120.0, 120.0),
7335            scale_factor: 1.0,
7336            dirty_regions: Vec::new(),
7337            layer_updates: Vec::new(),
7338            scene: {
7339                let mut scene = Scene::new();
7340                scene.push(SceneCommand::DrawText(TextRun {
7341                    rect: Rect::new(8.0, 8.0, 80.0, 28.0),
7342                    text: "I".to_string(),
7343                    style: text_style.clone(),
7344                }));
7345                scene.push(SceneCommand::PushTextRenderPolicy {
7346                    policy: TextRenderPolicy::new()
7347                        .with_render_mode(sui_scene::TextRenderMode::LcdSubpixel)
7348                        .with_subpixel_order(TextSubpixelOrder::Rgb),
7349                });
7350                scene.push(SceneCommand::DrawText(TextRun {
7351                    rect: Rect::new(8.0, 44.0, 80.0, 28.0),
7352                    text: "I".to_string(),
7353                    style: text_style.clone(),
7354                }));
7355                scene.push(SceneCommand::PopTextRenderPolicy);
7356                scene.push(SceneCommand::DrawText(TextRun {
7357                    rect: Rect::new(8.0, 80.0, 80.0, 28.0),
7358                    text: "I".to_string(),
7359                    style: text_style,
7360                }));
7361                scene
7362            },
7363            font_registry: Arc::new(fonts),
7364            image_registry: Arc::new(ImageRegistry::new()),
7365            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7366        };
7367
7368        let mut text_engine = TextEngine::new().unwrap();
7369        text_engine.set_text_render_mode(TextRenderMode::Grayscale);
7370        let _ = build_vertices(&frame, &mut text_engine).unwrap();
7371
7372        assert_eq!(text_engine.glyph_cache_stats(), (2, 1, 2));
7373    }
7374
7375    #[test]
7376    fn unsafe_lcd_text_transform_uses_grayscale_glyph_cache_entry() {
7377        let handle = FontHandle::new(38);
7378        let mut fonts = FontRegistry::new();
7379        fonts.insert(handle, load_test_font());
7380        let text_style = TextStyle {
7381            font: Some(handle),
7382            font_size: 24.0,
7383            line_height: 28.0,
7384            color: Color::WHITE,
7385            ..TextStyle::default()
7386        };
7387
7388        let frame = SceneFrame {
7389            window_id: WindowId::new(206),
7390            viewport: Size::new(160.0, 120.0),
7391            surface_size: Size::new(160.0, 120.0),
7392            scale_factor: 1.0,
7393            dirty_regions: Vec::new(),
7394            layer_updates: Vec::new(),
7395            scene: {
7396                let mut scene = Scene::new();
7397                scene.push(SceneCommand::DrawText(TextRun {
7398                    rect: Rect::new(8.0, 8.0, 80.0, 28.0),
7399                    text: "I".to_string(),
7400                    style: text_style.clone(),
7401                }));
7402                scene.push(SceneCommand::PushTextRenderPolicy {
7403                    policy: TextRenderPolicy::new()
7404                        .with_render_mode(sui_scene::TextRenderMode::LcdSubpixel)
7405                        .with_subpixel_order(TextSubpixelOrder::Rgb),
7406                });
7407                scene.push(SceneCommand::PushTransform {
7408                    transform: Transform::rotation(0.25),
7409                });
7410                scene.push(SceneCommand::DrawText(TextRun {
7411                    rect: Rect::new(20.0, 20.0, 80.0, 28.0),
7412                    text: "I".to_string(),
7413                    style: text_style,
7414                }));
7415                scene.push(SceneCommand::PopTransform);
7416                scene.push(SceneCommand::PopTextRenderPolicy);
7417                scene
7418            },
7419            font_registry: Arc::new(fonts),
7420            image_registry: Arc::new(ImageRegistry::new()),
7421            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7422        };
7423
7424        let mut text_engine = TextEngine::new().unwrap();
7425        text_engine.set_text_render_mode(TextRenderMode::Grayscale);
7426        let _ = build_vertices(&frame, &mut text_engine).unwrap();
7427
7428        assert_eq!(text_engine.glyph_cache_stats(), (1, 1, 1));
7429    }
7430
7431    #[test]
7432    fn linear_text_coverage_policy_shares_glyph_cache_entries_for_light_and_dark_text() {
7433        let handle = FontHandle::new(34);
7434        let mut fonts = FontRegistry::new();
7435        fonts.insert(handle, load_test_font());
7436
7437        let frame = SceneFrame {
7438            window_id: WindowId::new(202),
7439            viewport: Size::new(240.0, 96.0),
7440            surface_size: Size::new(240.0, 96.0),
7441            scale_factor: 1.0,
7442            dirty_regions: Vec::new(),
7443            layer_updates: Vec::new(),
7444            scene: {
7445                let mut scene = Scene::new();
7446                scene.push(SceneCommand::DrawText(TextRun {
7447                    rect: Rect::new(8.0, 8.0, 100.0, 32.0),
7448                    text: "I".to_string(),
7449                    style: TextStyle {
7450                        font: Some(handle),
7451                        font_size: 24.0,
7452                        line_height: 28.0,
7453                        color: Color::BLACK,
7454                        ..TextStyle::default()
7455                    },
7456                }));
7457                scene.push(SceneCommand::DrawText(TextRun {
7458                    rect: Rect::new(8.0, 48.0, 100.0, 32.0),
7459                    text: "I".to_string(),
7460                    style: TextStyle {
7461                        font: Some(handle),
7462                        font_size: 24.0,
7463                        line_height: 28.0,
7464                        color: Color::WHITE,
7465                        ..TextStyle::default()
7466                    },
7467                }));
7468                scene
7469            },
7470            font_registry: Arc::new(fonts),
7471            image_registry: Arc::new(ImageRegistry::new()),
7472            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7473        };
7474
7475        let mut text_engine = TextEngine::new().unwrap();
7476        text_engine.set_text_coverage_policy(TextCoveragePolicy::Linear);
7477        let _ = build_vertices(&frame, &mut text_engine).unwrap();
7478
7479        assert_eq!(text_engine.glyph_cache_stats(), (1, 1, 1));
7480    }
7481
7482    #[test]
7483    fn default_text_coverage_policy_shares_glyph_cache_entries_across_text_colors() {
7484        let handle = FontHandle::new(35);
7485        let mut fonts = FontRegistry::new();
7486        fonts.insert(handle, load_test_font());
7487
7488        let frame = SceneFrame {
7489            window_id: WindowId::new(203),
7490            viewport: Size::new(240.0, 96.0),
7491            surface_size: Size::new(240.0, 96.0),
7492            scale_factor: 1.0,
7493            dirty_regions: Vec::new(),
7494            layer_updates: Vec::new(),
7495            scene: {
7496                let mut scene = Scene::new();
7497                scene.push(SceneCommand::DrawText(TextRun {
7498                    rect: Rect::new(8.0, 8.0, 100.0, 32.0),
7499                    text: "I".to_string(),
7500                    style: TextStyle {
7501                        font: Some(handle),
7502                        font_size: 24.0,
7503                        line_height: 28.0,
7504                        color: Color::BLACK,
7505                        ..TextStyle::default()
7506                    },
7507                }));
7508                scene.push(SceneCommand::DrawText(TextRun {
7509                    rect: Rect::new(8.0, 48.0, 100.0, 32.0),
7510                    text: "I".to_string(),
7511                    style: TextStyle {
7512                        font: Some(handle),
7513                        font_size: 24.0,
7514                        line_height: 28.0,
7515                        color: Color::WHITE,
7516                        ..TextStyle::default()
7517                    },
7518                }));
7519                scene
7520            },
7521            font_registry: Arc::new(fonts),
7522            image_registry: Arc::new(ImageRegistry::new()),
7523            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7524        };
7525
7526        let mut text_engine = TextEngine::new().unwrap();
7527        let _ = build_vertices(&frame, &mut text_engine).unwrap();
7528
7529        assert_eq!(text_engine.glyph_cache_stats(), (1, 1, 1));
7530    }
7531
7532    #[test]
7533    fn retained_compositor_carries_active_path_clips() {
7534        let mut clip = Path::builder();
7535        clip.move_to(Point::new(8.0, 8.0))
7536            .line_to(Point::new(32.0, 8.0))
7537            .line_to(Point::new(20.0, 28.0))
7538            .close();
7539
7540        let mut scene = Scene::new();
7541        scene.push(SceneCommand::PushClipPath { path: clip.build() });
7542        scene.push(SceneCommand::FillRect {
7543            rect: Rect::new(0.0, 0.0, 40.0, 40.0),
7544            brush: Color::WHITE.into(),
7545        });
7546
7547        let mut text_engine = TextEngine::new().unwrap();
7548        let mut compositor = RetainedCompositorState::default();
7549        let ops = prepare_with_compositor(
7550            &SceneFrame {
7551                window_id: WindowId::new(6),
7552                viewport: Size::new(64.0, 64.0),
7553                surface_size: Size::new(64.0, 64.0),
7554                scale_factor: 1.0,
7555                dirty_regions: Vec::new(),
7556                layer_updates: Vec::new(),
7557                scene,
7558                font_registry: Arc::new(FontRegistry::new()),
7559                image_registry: Arc::new(ImageRegistry::new()),
7560                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
7561            },
7562            &mut text_engine,
7563            &mut compositor,
7564        )
7565        .unwrap();
7566
7567        assert_eq!(ops.draw_ops.len(), 1);
7568        let op = &ops.draw_ops[0];
7569        let clip_state = &ops.clip_states[op.clip_state_index];
7570        assert!(op.clip_state_index > 0);
7571        assert_eq!(clip_state.clip_paths.len(), 1);
7572        assert!(clip_state.clip_paths[0].len > 0);
7573        assert_eq!(op.clip_rect, Some(Rect::new(8.0, 8.0, 24.0, 20.0)));
7574    }
7575
7576    #[test]
7577    fn batch_draw_ops_merges_consecutive_matching_state() {
7578        let passes = batch_draw_ops(
7579            &DrawOpArena {
7580                scene_vertices: vec![
7581                    Vertex::basic(
7582                        [0.0, 0.0],
7583                        [1.0, 1.0, 1.0, 1.0],
7584                        [0.0, 0.0],
7585                        [0.0; 4],
7586                    );
7587                    6
7588                ],
7589                clip_vertices: Vec::new(),
7590                text_instances: Vec::new(),
7591                clip_states: vec![ClipState {
7592                    clip_paths: Vec::new(),
7593                }],
7594                draw_ops: vec![
7595                    DrawOp {
7596                        kind: DrawOpKind::Solid,
7597                        vertices: PreparedVertices { start: 0, len: 3 },
7598                        clip_rect: Some(Rect::new(2.0, 4.0, 20.0, 10.0)),
7599                        clip_state_index: 0,
7600                        image: None,
7601                    },
7602                    DrawOp {
7603                        kind: DrawOpKind::Solid,
7604                        vertices: PreparedVertices { start: 3, len: 3 },
7605                        clip_rect: Some(Rect::new(2.0, 4.0, 20.0, 10.0)),
7606                        clip_state_index: 0,
7607                        image: None,
7608                    },
7609                ],
7610                analytic_paths: std::collections::HashMap::new(),
7611                next_analytic_path_id: 0,
7612            },
7613            Size::new(50.0, 40.0),
7614            (100, 80),
7615        );
7616
7617        assert_eq!(passes.len(), 1);
7618        assert_eq!(passes[0].draws.len(), 1);
7619        assert_eq!(passes[0].draws[0].vertices.len, 6);
7620    }
7621
7622    #[test]
7623    fn prepare_frame_batches_converts_clip_rects_to_scissors() {
7624        let prepared = prepare_frame_batches(
7625            DrawOpArena {
7626                scene_vertices: vec![
7627                    Vertex::basic(
7628                        [0.0, 0.0],
7629                        [1.0, 1.0, 1.0, 1.0],
7630                        [0.0, 0.0],
7631                        [0.0; 4],
7632                    );
7633                    6
7634                ],
7635                clip_vertices: Vec::new(),
7636                text_instances: Vec::new(),
7637                clip_states: vec![ClipState {
7638                    clip_paths: Vec::new(),
7639                }],
7640                draw_ops: vec![DrawOp {
7641                    kind: DrawOpKind::Solid,
7642                    clip_rect: Some(Rect::new(5.0, 8.0, 20.0, 10.0)),
7643                    vertices: PreparedVertices { start: 0, len: 6 },
7644                    clip_state_index: 0,
7645                    image: None,
7646                }],
7647                analytic_paths: std::collections::HashMap::new(),
7648                next_analytic_path_id: 0,
7649            },
7650            Size::new(50.0, 40.0),
7651            (100, 80),
7652        );
7653
7654        assert_eq!(prepared.passes.len(), 1);
7655        assert_eq!(
7656            prepared.passes[0].draws[0].clip_rect,
7657            Some(ScissorRect {
7658                x: 10,
7659                y: 16,
7660                width: 40,
7661                height: 20,
7662            })
7663        );
7664    }
7665
7666    #[test]
7667    fn prepare_cached_passes_snap_translated_adjacent_clip_edges_without_overlap() {
7668        let passes = prepare_cached_passes(
7669            &[
7670                CachedPassBatch {
7671                    clip_paths: Vec::new(),
7672                    draws: vec![CachedDrawBatch {
7673                        kind: PreparedDrawKind::Solid,
7674                        clip_rect: Some(Rect::new(0.0, 0.0, 384.0, 128.0)),
7675                        vertices: PreparedVertices { start: 0, len: 6 },
7676                    }],
7677                },
7678                CachedPassBatch {
7679                    clip_paths: Vec::new(),
7680                    draws: vec![CachedDrawBatch {
7681                        kind: PreparedDrawKind::Solid,
7682                        clip_rect: Some(Rect::new(384.0, 0.0, 128.0, 128.0)),
7683                        vertices: PreparedVertices { start: 6, len: 6 },
7684                    }],
7685                },
7686            ],
7687            Size::new(512.0, 128.0),
7688            (768, 192),
7689            Vector::new(0.25, 0.0),
7690            None,
7691            0,
7692            0,
7693            0,
7694        );
7695
7696        let first = passes[0].draws[0].clip_rect.expect("first scissor");
7697        let second = passes[1].draws[0].clip_rect.expect("second scissor");
7698
7699        assert_eq!(first.x + first.width, second.x);
7700        assert!(first.x + first.width <= second.x);
7701    }
7702
7703    #[test]
7704    fn prepare_cached_passes_uses_external_clip_for_unclipped_draws() {
7705        let passes = prepare_cached_passes(
7706            &[CachedPassBatch {
7707                clip_paths: Vec::new(),
7708                draws: vec![CachedDrawBatch {
7709                    kind: PreparedDrawKind::Image {
7710                        handle: ImageHandle::new(99),
7711                        sampling: ImageSampling::Linear,
7712                        raster_size: crate::scene::ImageRasterSize {
7713                            width: 1,
7714                            height: 1,
7715                        },
7716                    },
7717                    clip_rect: None,
7718                    vertices: PreparedVertices { start: 0, len: 6 },
7719                }],
7720            }],
7721            Size::new(100.0, 100.0),
7722            (100, 100),
7723            Vector::ZERO,
7724            Some(Rect::new(20.0, 30.0, 40.0, 50.0)),
7725            0,
7726            0,
7727            0,
7728        );
7729
7730        assert_eq!(passes.len(), 1);
7731        assert_eq!(passes[0].draws.len(), 1);
7732        assert_eq!(
7733            passes[0].draws[0].clip_rect,
7734            Some(ScissorRect {
7735                x: 20,
7736                y: 30,
7737                width: 40,
7738                height: 50,
7739            })
7740        );
7741    }
7742
7743    #[test]
7744    fn prepare_cached_passes_drops_draws_fully_outside_external_clip() {
7745        let passes = prepare_cached_passes(
7746            &[CachedPassBatch {
7747                clip_paths: Vec::new(),
7748                draws: vec![CachedDrawBatch {
7749                    kind: PreparedDrawKind::Image {
7750                        handle: ImageHandle::new(100),
7751                        sampling: ImageSampling::Linear,
7752                        raster_size: crate::scene::ImageRasterSize {
7753                            width: 1,
7754                            height: 1,
7755                        },
7756                    },
7757                    clip_rect: Some(Rect::new(70.0, 70.0, 20.0, 20.0)),
7758                    vertices: PreparedVertices { start: 0, len: 6 },
7759                }],
7760            }],
7761            Size::new(100.0, 100.0),
7762            (100, 100),
7763            Vector::ZERO,
7764            Some(Rect::new(0.0, 0.0, 20.0, 20.0)),
7765            0,
7766            0,
7767            0,
7768        );
7769
7770        assert_eq!(passes.len(), 1);
7771        assert!(passes[0].draws.is_empty());
7772    }
7773
7774    #[test]
7775    fn renderer_frame_stats_count_passes_draws_and_uploaded_vertices() {
7776        let vertex = Vertex::basic([0.0, 0.0], [1.0, 1.0, 1.0, 1.0], [0.0, 0.0], [0.0; 4]);
7777        let prepared = PreparedFrameBatches {
7778            scene_vertices: vec![vertex; 9],
7779            clip_vertices: vec![vertex; 6],
7780            text_instances: Vec::new(),
7781            passes: vec![
7782                PreparedPassBatch {
7783                    clip_paths: vec![PreparedClipPath {
7784                        vertices: PreparedVertices { start: 0, len: 6 },
7785                    }],
7786                    draws: vec![
7787                        PreparedDrawBatch {
7788                            kind: PreparedDrawKind::Solid,
7789                            clip_rect: None,
7790                            vertices: PreparedVertices { start: 0, len: 3 },
7791                        },
7792                        PreparedDrawBatch {
7793                            kind: PreparedDrawKind::Solid,
7794                            clip_rect: Some(ScissorRect {
7795                                x: 0,
7796                                y: 0,
7797                                width: 10,
7798                                height: 10,
7799                            }),
7800                            vertices: PreparedVertices { start: 3, len: 6 },
7801                        },
7802                    ],
7803                },
7804                PreparedPassBatch {
7805                    clip_paths: Vec::new(),
7806                    draws: vec![PreparedDrawBatch {
7807                        kind: PreparedDrawKind::Image {
7808                            handle: ImageHandle::new(1),
7809                            sampling: ImageSampling::Linear,
7810                            raster_size: crate::scene::ImageRasterSize {
7811                                width: 1,
7812                                height: 1,
7813                            },
7814                        },
7815                        clip_rect: None,
7816                        vertices: PreparedVertices { start: 0, len: 3 },
7817                    }],
7818                },
7819            ],
7820        };
7821
7822        let stats = RendererFrameStats::from_prepared_frame(&prepared);
7823
7824        assert_eq!(stats.pass_count, 2);
7825        assert_eq!(stats.draw_count, 4);
7826        assert_eq!(stats.uploaded_vertex_bytes, 15 * VERTEX_SIZE);
7827        assert_eq!(stats.visible_layer_count, 0);
7828        assert_eq!(stats.retained_state_update_time_us, 0);
7829    }
7830
7831    #[test]
7832    fn text_engine_shapes_text_with_font_metrics() {
7833        let text = TextRun {
7834            rect: Rect::new(8.0, 10.0, 160.0, 32.0),
7835            text: "office".to_string(),
7836            style: TextStyle::new(Color::WHITE),
7837        };
7838
7839        let text_engine = TextEngine::new().unwrap();
7840        let layout = text_engine
7841            .shape_text_run(&text, &FontRegistry::new())
7842            .unwrap();
7843
7844        assert!(!layout.glyphs().is_empty());
7845        assert!(layout.measurement().width > 0.0);
7846        assert!(layout.measurement().height >= text.style.font_size);
7847    }
7848
7849    #[test]
7850    fn build_vertices_supports_pre_shaped_text() {
7851        let text_system = TextSystem::new();
7852        let layout = text_system
7853            .shape_text_persistent(
7854                None,
7855                "scene",
7856                Size::new(80.0, 24.0),
7857                TextStyle::new(Color::WHITE),
7858                &FontRegistry::new(),
7859            )
7860            .unwrap();
7861
7862        let mut scene = Scene::new();
7863        scene.push(SceneCommand::DrawShapedText(ShapedText::new(
7864            Point::new(4.0, 6.0),
7865            &layout,
7866        )));
7867
7868        let mut text_engine = TextEngine::new().unwrap();
7869        let vertices = build_vertices(
7870            &SceneFrame {
7871                window_id: WindowId::new(11),
7872                viewport: Size::new(100.0, 80.0),
7873                surface_size: Size::new(100.0, 80.0),
7874                scale_factor: 1.0,
7875                dirty_regions: Vec::new(),
7876                layer_updates: Vec::new(),
7877                scene,
7878                font_registry: Arc::new(FontRegistry::new()),
7879                image_registry: Arc::new(ImageRegistry::new()),
7880                text_layout_registry: text_system.text_layout_registry(),
7881            },
7882            &mut text_engine,
7883        )
7884        .unwrap();
7885
7886        assert!(!vertices.is_empty());
7887    }
7888
7889    #[test]
7890    fn shaped_text_color_override_paints_cached_layout_without_changing_style() {
7891        let text_system = TextSystem::new();
7892        let layout_color = Color::rgba(0.92, 0.18, 0.16, 1.0);
7893        let paint_color = Color::rgba(0.12, 0.48, 0.86, 1.0);
7894        let layout = text_system
7895            .shape_text_persistent(
7896                None,
7897                "state",
7898                Size::new(96.0, 24.0),
7899                TextStyle::new(layout_color),
7900                &FontRegistry::new(),
7901            )
7902            .unwrap();
7903
7904        let mut scene = Scene::new();
7905        scene.push(SceneCommand::DrawShapedText(
7906            ShapedText::new(Point::new(4.0, 6.0), &layout).with_color(paint_color),
7907        ));
7908
7909        let mut text_engine = TextEngine::new().unwrap();
7910        let vertices = build_vertices(
7911            &SceneFrame {
7912                window_id: WindowId::new(311),
7913                viewport: Size::new(120.0, 80.0),
7914                surface_size: Size::new(120.0, 80.0),
7915                scale_factor: 1.0,
7916                dirty_regions: Vec::new(),
7917                layer_updates: Vec::new(),
7918                scene,
7919                font_registry: Arc::new(FontRegistry::new()),
7920                image_registry: Arc::new(ImageRegistry::new()),
7921                text_layout_registry: text_system.text_layout_registry(),
7922            },
7923            &mut text_engine,
7924        )
7925        .unwrap();
7926
7927        assert_eq!(layout.style().color, layout_color);
7928        assert!(!vertices.is_empty());
7929        assert_eq!(vertices[0].color, shader_color(paint_color));
7930    }
7931
7932    #[test]
7933    fn shaped_text_from_runtime_draw_text_snaps_to_physical_pixels_at_fractional_dpi() {
7934        let handle = FontHandle::new(312);
7935        let mut fonts = FontRegistry::new();
7936        fonts.insert(handle, load_test_font());
7937        let text_system = TextSystem::new();
7938        let layout = text_system
7939            .shape_text_persistent(
7940                None,
7941                "Widget text",
7942                Size::new(132.0, 24.0),
7943                TextStyle {
7944                    font: Some(handle),
7945                    font_size: 14.0,
7946                    line_height: 19.0,
7947                    color: Color::rgba(0.12, 0.16, 0.22, 1.0),
7948                    ..TextStyle::default()
7949                },
7950                &fonts,
7951            )
7952            .unwrap();
7953        let viewport = Size::new(220.0, 72.0);
7954        let origin = Point::new(18.333_332, 10.666_667);
7955        let mut scene = Scene::new();
7956        scene.push(SceneCommand::DrawShapedText(ShapedText::new(
7957            origin, &layout,
7958        )));
7959
7960        let frame = SceneFrame {
7961            window_id: WindowId::new(312),
7962            viewport,
7963            surface_size: Size::new(330.0, 108.0),
7964            scale_factor: 1.5,
7965            dirty_regions: Vec::new(),
7966            layer_updates: Vec::new(),
7967            scene,
7968            font_registry: Arc::new(fonts),
7969            image_registry: Arc::new(ImageRegistry::new()),
7970            text_layout_registry: text_system.text_layout_registry(),
7971        };
7972
7973        let mut text_engine = TextEngine::new().unwrap();
7974        let mut compositor = RetainedCompositorState::default();
7975        let draw_ops = prepare_with_compositor(&frame, &mut text_engine, &mut compositor)
7976            .expect("shaped text frame should prepare");
7977        let text_op = draw_ops
7978            .draw_ops
7979            .iter()
7980            .find(|op| matches!(op.kind, DrawOpKind::TextAtlas))
7981            .expect("shaped text should emit atlas instances");
7982        let start = text_op.vertices.start as usize;
7983        let end = start + text_op.vertices.len as usize;
7984        let instances = &draw_ops.text_instances[start..end];
7985        assert!(!instances.is_empty());
7986        for (index, instance) in instances.iter().enumerate() {
7987            let x = logical_x_from_ndc(instance.top_left[0], viewport);
7988            let y = logical_y_from_ndc(instance.top_left[1], viewport);
7989            assert!(
7990                is_physically_pixel_aligned(x, frame.scale_factor),
7991                "shaped text instance {index} x was not physically aligned: {x}"
7992            );
7993            assert!(
7994                is_physically_pixel_aligned(y, frame.scale_factor),
7995                "shaped text instance {index} y was not physically aligned: {y}"
7996            );
7997        }
7998    }
7999
8000    #[test]
8001    fn shaped_text_window_snaps_to_physical_pixels_at_fractional_dpi() {
8002        let handle = FontHandle::new(313);
8003        let mut fonts = FontRegistry::new();
8004        fonts.insert(handle, load_test_font());
8005        let text_system = TextSystem::new();
8006        let layout = text_system
8007            .shape_text_persistent(
8008                None,
8009                "First line wraps into a second visible line",
8010                Size::new(84.0, 72.0),
8011                TextStyle {
8012                    font: Some(handle),
8013                    font_size: 14.0,
8014                    line_height: 19.0,
8015                    color: Color::rgba(0.12, 0.16, 0.22, 1.0),
8016                    ..TextStyle::default()
8017                },
8018                &fonts,
8019            )
8020            .unwrap();
8021        assert!(
8022            layout.lines().len() > 1,
8023            "test layout must produce a non-empty line window"
8024        );
8025        assert!(
8026            layout.line_window(1..2).glyph_instances().len() > 0,
8027            "test layout line window must contain glyphs"
8028        );
8029        let viewport = Size::new(220.0, 96.0);
8030        let origin = Point::new(18.333_332, 10.666_667);
8031        let mut scene = Scene::new();
8032        scene.push(SceneCommand::DrawShapedTextWindow(ShapedTextWindow::new(
8033            origin,
8034            &layout,
8035            1..2,
8036        )));
8037
8038        let frame = SceneFrame {
8039            window_id: WindowId::new(313),
8040            viewport,
8041            surface_size: Size::new(330.0, 144.0),
8042            scale_factor: 1.5,
8043            dirty_regions: Vec::new(),
8044            layer_updates: Vec::new(),
8045            scene,
8046            font_registry: Arc::new(fonts),
8047            image_registry: Arc::new(ImageRegistry::new()),
8048            text_layout_registry: text_system.text_layout_registry(),
8049        };
8050
8051        let mut text_engine = TextEngine::new().unwrap();
8052        let mut compositor = RetainedCompositorState::default();
8053        let draw_ops = prepare_with_compositor(&frame, &mut text_engine, &mut compositor)
8054            .expect("windowed shaped text frame should prepare");
8055        let text_op = draw_ops
8056            .draw_ops
8057            .iter()
8058            .find(|op| matches!(op.kind, DrawOpKind::TextAtlas))
8059            .expect("windowed shaped text should emit atlas instances");
8060        let start = text_op.vertices.start as usize;
8061        let end = start + text_op.vertices.len as usize;
8062        let instances = &draw_ops.text_instances[start..end];
8063        assert!(!instances.is_empty());
8064        for (index, instance) in instances.iter().enumerate() {
8065            let x = logical_x_from_ndc(instance.top_left[0], viewport);
8066            let y = logical_y_from_ndc(instance.top_left[1], viewport);
8067            assert!(
8068                is_physically_pixel_aligned(x, frame.scale_factor),
8069                "windowed shaped text instance {index} x was not physically aligned: {x}"
8070            );
8071            assert!(
8072                is_physically_pixel_aligned(y, frame.scale_factor),
8073                "windowed shaped text instance {index} y was not physically aligned: {y}"
8074            );
8075        }
8076    }
8077
8078    #[test]
8079    fn text_engine_reuses_cached_glyph_atlas_entries_across_repeated_builds() {
8080        let mut scene = Scene::new();
8081        scene.push(SceneCommand::DrawText(TextRun {
8082            rect: Rect::new(4.0, 6.0, 120.0, 28.0),
8083            text: "abc".to_string(),
8084            style: TextStyle::new(Color::WHITE),
8085        }));
8086
8087        let frame = SceneFrame {
8088            window_id: WindowId::new(12),
8089            viewport: Size::new(160.0, 60.0),
8090            surface_size: Size::new(160.0, 60.0),
8091            scale_factor: 1.0,
8092            dirty_regions: Vec::new(),
8093            layer_updates: Vec::new(),
8094            scene,
8095            font_registry: Arc::new(FontRegistry::new()),
8096            image_registry: Arc::new(ImageRegistry::new()),
8097            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8098        };
8099
8100        let mut text_engine = TextEngine::new().unwrap();
8101        let first = build_vertices(&frame, &mut text_engine).unwrap();
8102        assert!(!first.is_empty());
8103        assert_eq!(first.len(), 18);
8104        assert!(first.iter().any(|vertex| vertex.tex_coords != [0.0, 0.0]));
8105        assert_eq!(text_engine.glyph_cache_stats(), (3, 0, 3));
8106
8107        let second = build_vertices(&frame, &mut text_engine).unwrap();
8108        assert_eq!(first.len(), second.len());
8109        assert!(first.iter().zip(&second).all(|(left, right)| {
8110            left.position == right.position
8111                && left.color == right.color
8112                && left.tex_coords == right.tex_coords
8113        }));
8114        assert_eq!(text_engine.glyph_cache_stats(), (3, 3, 3));
8115    }
8116
8117    #[test]
8118    fn text_engine_parses_swash_face_once_per_text_run_when_glyphs_miss() {
8119        let mut scene = Scene::new();
8120        scene.push(SceneCommand::DrawText(TextRun {
8121            rect: Rect::new(4.0, 6.0, 120.0, 28.0),
8122            text: "abc".to_string(),
8123            style: TextStyle::new(Color::WHITE),
8124        }));
8125
8126        let frame = SceneFrame {
8127            window_id: WindowId::new(15),
8128            viewport: Size::new(160.0, 60.0),
8129            surface_size: Size::new(160.0, 60.0),
8130            scale_factor: 1.0,
8131            dirty_regions: Vec::new(),
8132            layer_updates: Vec::new(),
8133            scene,
8134            font_registry: Arc::new(FontRegistry::new()),
8135            image_registry: Arc::new(ImageRegistry::new()),
8136            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8137        };
8138
8139        let mut text_engine = TextEngine::new().unwrap();
8140        let first = build_vertices(&frame, &mut text_engine).unwrap();
8141        assert!(!first.is_empty());
8142        assert_eq!(text_engine.glyph_cache_stats(), (3, 0, 3));
8143        assert_eq!(text_engine.swash_face_parse_count(), 1);
8144
8145        let second = build_vertices(&frame, &mut text_engine).unwrap();
8146        assert_eq!(first.len(), second.len());
8147        assert_eq!(text_engine.glyph_cache_stats(), (3, 3, 3));
8148        assert_eq!(text_engine.swash_face_parse_count(), 1);
8149    }
8150
8151    #[test]
8152    fn text_engine_buckets_cached_glyph_atlas_entries_by_scale() {
8153        let mut scene = Scene::new();
8154        scene.push(SceneCommand::DrawText(TextRun {
8155            rect: Rect::new(4.0, 6.0, 120.0, 28.0),
8156            text: "abc".to_string(),
8157            style: TextStyle::new(Color::WHITE),
8158        }));
8159
8160        let base_frame = SceneFrame {
8161            window_id: WindowId::new(13),
8162            viewport: Size::new(160.0, 60.0),
8163            surface_size: Size::new(160.0, 60.0),
8164            scale_factor: 1.0,
8165            dirty_regions: Vec::new(),
8166            layer_updates: Vec::new(),
8167            scene,
8168            font_registry: Arc::new(FontRegistry::new()),
8169            image_registry: Arc::new(ImageRegistry::new()),
8170            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8171        };
8172
8173        let mut scaled_scene = Scene::new();
8174        scaled_scene.push(SceneCommand::DrawText(TextRun {
8175            rect: Rect::new(4.0, 6.0, 120.0, 56.0),
8176            text: "abc".to_string(),
8177            style: TextStyle {
8178                font_size: 28.0,
8179                line_height: 32.0,
8180                ..TextStyle::new(Color::WHITE)
8181            },
8182        }));
8183
8184        let scaled_frame = SceneFrame {
8185            window_id: WindowId::new(14),
8186            viewport: Size::new(160.0, 80.0),
8187            surface_size: Size::new(160.0, 80.0),
8188            scale_factor: 1.0,
8189            dirty_regions: Vec::new(),
8190            layer_updates: Vec::new(),
8191            scene: scaled_scene,
8192            font_registry: Arc::new(FontRegistry::new()),
8193            image_registry: Arc::new(ImageRegistry::new()),
8194            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8195        };
8196
8197        let mut text_engine = TextEngine::new().unwrap();
8198        let first = build_vertices(&base_frame, &mut text_engine).unwrap();
8199        assert!(!first.is_empty());
8200        assert_eq!(text_engine.glyph_cache_stats(), (3, 0, 3));
8201
8202        let second = build_vertices(&scaled_frame, &mut text_engine).unwrap();
8203        assert!(!second.is_empty());
8204        assert_eq!(text_engine.glyph_cache_stats(), (6, 0, 6));
8205    }
8206
8207    #[test]
8208    fn retained_compositor_reuses_cached_path_meshes_across_retained_packets() {
8209        let layer_id = WidgetId::new(70);
8210        let descriptor = SceneLayerDescriptor::new(
8211            SceneLayerId::from_widget(layer_id),
8212            layer_id,
8213            Rect::new(0.0, 0.0, 512.0, 128.0),
8214        )
8215        .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
8216        .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
8217        .with_cache_policy(LayerCachePolicy::Cached);
8218
8219        let mut layer_scene = Scene::new();
8220        layer_scene.push(SceneCommand::FillPath {
8221            path: Path::rect(Rect::new(0.0, 0.0, 512.0, 128.0)),
8222            brush: Color::rgba(0.24, 0.48, 0.72, 1.0).into(),
8223        });
8224
8225        let mut scene = Scene::new();
8226        scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8227            descriptor.clone(),
8228            layer_scene,
8229        )));
8230
8231        let frame = SceneFrame {
8232            window_id: WindowId::new(30),
8233            viewport: Size::new(512.0, 128.0),
8234            surface_size: Size::new(512.0, 128.0),
8235            scale_factor: 1.0,
8236            dirty_regions: Vec::new(),
8237            layer_updates: vec![
8238                SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
8239                    .with_damage(Rect::new(0.0, 0.0, 512.0, 128.0)),
8240            ],
8241            scene,
8242            font_registry: Arc::new(FontRegistry::new()),
8243            image_registry: Arc::new(ImageRegistry::new()),
8244            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8245        };
8246
8247        let mut text_engine = TextEngine::new().unwrap();
8248        let mut compositor = RetainedCompositorState::default();
8249        let draw_ops = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8250
8251        assert!(!draw_ops.draw_ops.is_empty());
8252        assert_eq!(compositor.path_cache.stats(), (0, 0, 0));
8253        assert_eq!(draw_ops.analytic_paths.len(), 1);
8254        assert!(
8255            draw_ops
8256                .draw_ops
8257                .iter()
8258                .any(|draw| matches!(draw.kind, DrawOpKind::AnalyticPath { .. }))
8259        );
8260    }
8261
8262    #[test]
8263    fn retained_compositor_uses_analytic_stroke_paths_across_retained_packets() {
8264        let layer_id = WidgetId::new(71);
8265        let descriptor = SceneLayerDescriptor::new(
8266            SceneLayerId::from_widget(layer_id),
8267            layer_id,
8268            Rect::new(0.0, 0.0, 512.0, 128.0),
8269        )
8270        .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
8271        .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
8272        .with_cache_policy(LayerCachePolicy::Cached);
8273
8274        let mut stroke_path = Path::builder();
8275        stroke_path
8276            .move_to(Point::new(8.0, 24.0))
8277            .line_to(Point::new(180.0, 92.0))
8278            .line_to(Point::new(340.0, 20.0))
8279            .line_to(Point::new(500.0, 92.0));
8280
8281        let mut layer_scene = Scene::new();
8282        layer_scene.push(SceneCommand::StrokePath {
8283            path: stroke_path.build(),
8284            brush: Color::rgba(0.92, 0.46, 0.18, 1.0).into(),
8285            stroke: StrokeStyle::new(12.0),
8286        });
8287
8288        let mut scene = Scene::new();
8289        scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8290            descriptor.clone(),
8291            layer_scene,
8292        )));
8293
8294        let frame = SceneFrame {
8295            window_id: WindowId::new(31),
8296            viewport: Size::new(512.0, 128.0),
8297            surface_size: Size::new(512.0, 128.0),
8298            scale_factor: 1.0,
8299            dirty_regions: Vec::new(),
8300            layer_updates: vec![
8301                SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
8302                    .with_damage(Rect::new(0.0, 0.0, 512.0, 128.0)),
8303            ],
8304            scene,
8305            font_registry: Arc::new(FontRegistry::new()),
8306            image_registry: Arc::new(ImageRegistry::new()),
8307            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8308        };
8309
8310        let mut text_engine = TextEngine::new().unwrap();
8311        let mut compositor = RetainedCompositorState::default();
8312        let draw_ops = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8313
8314        assert!(!draw_ops.draw_ops.is_empty());
8315        assert_eq!(compositor.path_cache.stats(), (0, 0, 0));
8316        assert_eq!(draw_ops.analytic_paths.len(), 1);
8317        assert!(
8318            draw_ops
8319                .draw_ops
8320                .iter()
8321                .any(|draw| matches!(draw.kind, DrawOpKind::AnalyticPath { .. }))
8322        );
8323    }
8324
8325    #[test]
8326    fn retained_compositor_reuses_layer_packets_until_content_changes() {
8327        let layer_id = WidgetId::new(41);
8328        let mut child_scene = Scene::new();
8329        child_scene.push(SceneCommand::FillRect {
8330            rect: Rect::new(4.0, 6.0, 32.0, 24.0),
8331            brush: Color::rgba(1.0, 0.0, 0.0, 1.0).into(),
8332        });
8333
8334        let mut scene = Scene::new();
8335        scene.push(SceneCommand::Clear(Color::BLACK));
8336        scene.push(SceneCommand::Layer(SceneLayer::new(
8337            layer_id,
8338            Rect::new(4.0, 6.0, 32.0, 24.0),
8339            child_scene,
8340        )));
8341
8342        let mut frame = SceneFrame {
8343            window_id: WindowId::new(21),
8344            viewport: Size::new(96.0, 64.0),
8345            surface_size: Size::new(96.0, 64.0),
8346            scale_factor: 1.0,
8347            dirty_regions: Vec::new(),
8348            layer_updates: content_updates([layer_id]),
8349            scene,
8350            font_registry: Arc::new(FontRegistry::new()),
8351            image_registry: Arc::new(ImageRegistry::new()),
8352            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8353        };
8354
8355        let mut text_engine = TextEngine::new().unwrap();
8356        let mut compositor = RetainedCompositorState::default();
8357        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8358        assert!(compositor.last_frame_stats.packet_build_count > 0);
8359        let layer_container = CompositionContainerId::Layer(SceneLayerId::from_widget(layer_id));
8360        let first_signature = packet_signature(&compositor, layer_container);
8361        let first_content_version =
8362            compositor.layers[&SceneLayerId::from_widget(layer_id)].content_version;
8363
8364        frame.layer_updates.clear();
8365        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8366        assert_eq!(compositor.last_frame_stats.packet_build_count, 0);
8367        assert_eq!(first.scene_vertices, second.scene_vertices);
8368        assert_eq!(
8369            first_signature,
8370            packet_signature(&compositor, layer_container)
8371        );
8372
8373        frame.layer_updates = content_updates([layer_id]);
8374        let mut updated_child_scene = Scene::new();
8375        updated_child_scene.push(SceneCommand::FillRect {
8376            rect: Rect::new(4.0, 6.0, 32.0, 24.0),
8377            brush: Color::rgba(1.0, 0.0, 0.0, 1.0).into(),
8378        });
8379        updated_child_scene.push(SceneCommand::FillRect {
8380            rect: Rect::new(12.0, 10.0, 8.0, 8.0),
8381            brush: Color::rgba(0.0, 1.0, 0.0, 1.0).into(),
8382        });
8383        assert!(frame.scene.replace_layer(
8384            layer_id,
8385            SceneLayer::new(
8386                layer_id,
8387                Rect::new(4.0, 6.0, 32.0, 24.0),
8388                updated_child_scene
8389            ),
8390        ));
8391        let third = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8392        assert!(compositor.last_frame_stats.packet_build_count > 0);
8393        let third_signature = packet_signature(&compositor, layer_container);
8394        let third_content_version =
8395            compositor.layers[&SceneLayerId::from_widget(layer_id)].content_version;
8396
8397        assert!(third_content_version > first_content_version);
8398        assert_ne!(first_signature, third_signature);
8399        assert_ne!(first.scene_vertices, third.scene_vertices);
8400    }
8401
8402    #[test]
8403    fn retained_compositor_skips_packet_rebuild_for_unchanged_content_updates() {
8404        let layer_id = WidgetId::new(411);
8405        let mut child_scene = Scene::new();
8406        child_scene.push(SceneCommand::FillRect {
8407            rect: Rect::new(4.0, 6.0, 32.0, 24.0),
8408            brush: Color::rgba(1.0, 0.0, 0.0, 1.0).into(),
8409        });
8410
8411        let mut scene = Scene::new();
8412        scene.push(SceneCommand::Layer(SceneLayer::new(
8413            layer_id,
8414            Rect::new(4.0, 6.0, 32.0, 24.0),
8415            child_scene,
8416        )));
8417
8418        let mut frame = SceneFrame {
8419            window_id: WindowId::new(211),
8420            viewport: Size::new(96.0, 64.0),
8421            surface_size: Size::new(96.0, 64.0),
8422            scale_factor: 1.0,
8423            dirty_regions: Vec::new(),
8424            layer_updates: content_updates([layer_id]),
8425            scene,
8426            font_registry: Arc::new(FontRegistry::new()),
8427            image_registry: Arc::new(ImageRegistry::new()),
8428            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8429        };
8430
8431        let mut text_engine = TextEngine::new().unwrap();
8432        let mut compositor = RetainedCompositorState::default();
8433        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8434        assert!(compositor.last_frame_stats.packet_build_count > 0);
8435        let layer_container = CompositionContainerId::Layer(SceneLayerId::from_widget(layer_id));
8436        let first_signature = packet_signature(&compositor, layer_container);
8437
8438        frame.layer_updates = content_updates([layer_id]);
8439        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8440
8441        assert_eq!(compositor.last_frame_stats.packet_build_count, 0);
8442        assert_eq!(
8443            first_signature,
8444            packet_signature(&compositor, layer_container)
8445        );
8446        assert_eq!(first.scene_vertices, second.scene_vertices);
8447    }
8448
8449    #[test]
8450    fn retained_compositor_reuses_parent_packets_when_only_child_content_changes() {
8451        let parent_id = WidgetId::new(51);
8452        let child_id = WidgetId::new(52);
8453
8454        let mut child_scene = Scene::new();
8455        child_scene.push(SceneCommand::FillRect {
8456            rect: Rect::new(8.0, 8.0, 10.0, 10.0),
8457            brush: Color::rgba(1.0, 0.0, 0.0, 1.0).into(),
8458        });
8459
8460        let mut parent_scene = Scene::new();
8461        parent_scene.push(SceneCommand::FillRect {
8462            rect: Rect::new(4.0, 4.0, 24.0, 24.0),
8463            brush: Color::rgba(0.1, 0.1, 0.1, 1.0).into(),
8464        });
8465        parent_scene.push(SceneCommand::Layer(SceneLayer::new(
8466            child_id,
8467            Rect::new(8.0, 8.0, 10.0, 10.0),
8468            child_scene,
8469        )));
8470
8471        let mut scene = Scene::new();
8472        scene.push(SceneCommand::Layer(SceneLayer::new(
8473            parent_id,
8474            Rect::new(4.0, 4.0, 24.0, 24.0),
8475            parent_scene,
8476        )));
8477
8478        let mut frame = SceneFrame {
8479            window_id: WindowId::new(22),
8480            viewport: Size::new(64.0, 64.0),
8481            surface_size: Size::new(64.0, 64.0),
8482            scale_factor: 1.0,
8483            dirty_regions: Vec::new(),
8484            layer_updates: content_updates([parent_id, child_id]),
8485            scene,
8486            font_registry: Arc::new(FontRegistry::new()),
8487            image_registry: Arc::new(ImageRegistry::new()),
8488            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8489        };
8490
8491        let mut text_engine = TextEngine::new().unwrap();
8492        let mut compositor = RetainedCompositorState::default();
8493        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8494        let parent_container = CompositionContainerId::Layer(SceneLayerId::from_widget(parent_id));
8495        let child_container = CompositionContainerId::Layer(SceneLayerId::from_widget(child_id));
8496        let parent_signature = packet_signature(&compositor, parent_container);
8497        let child_signature = packet_signature(&compositor, child_container);
8498
8499        frame.layer_updates.clear();
8500        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8501        assert_eq!(first.scene_vertices, second.scene_vertices);
8502        assert_eq!(
8503            parent_signature,
8504            packet_signature(&compositor, parent_container)
8505        );
8506        assert_eq!(
8507            child_signature,
8508            packet_signature(&compositor, child_container)
8509        );
8510
8511        let mut updated_child_scene = Scene::new();
8512        updated_child_scene.push(SceneCommand::FillRect {
8513            rect: Rect::new(8.0, 8.0, 10.0, 10.0),
8514            brush: Color::rgba(0.0, 1.0, 0.0, 1.0).into(),
8515        });
8516
8517        let mut updated_parent_scene = Scene::new();
8518        updated_parent_scene.push(SceneCommand::FillRect {
8519            rect: Rect::new(4.0, 4.0, 24.0, 24.0),
8520            brush: Color::rgba(0.1, 0.1, 0.1, 1.0).into(),
8521        });
8522        updated_parent_scene.push(SceneCommand::Layer(SceneLayer::new(
8523            child_id,
8524            Rect::new(8.0, 8.0, 10.0, 10.0),
8525            updated_child_scene,
8526        )));
8527        assert!(frame.scene.replace_layer(
8528            parent_id,
8529            SceneLayer::new(
8530                parent_id,
8531                Rect::new(4.0, 4.0, 24.0, 24.0),
8532                updated_parent_scene
8533            ),
8534        ));
8535
8536        frame.layer_updates = content_updates([child_id]);
8537        let third = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8538
8539        assert_eq!(
8540            parent_signature,
8541            packet_signature(&compositor, parent_container)
8542        );
8543        assert_ne!(
8544            child_signature,
8545            packet_signature(&compositor, child_container)
8546        );
8547        assert_ne!(first.scene_vertices, third.scene_vertices);
8548    }
8549
8550    #[test]
8551    fn retained_compositor_reuses_direct_packets_across_layer_translation() {
8552        let layer_id = WidgetId::new(53);
8553
8554        let build_layer = |x: f32| {
8555            let descriptor = SceneLayerDescriptor::new(
8556                SceneLayerId::from_widget(layer_id),
8557                layer_id,
8558                Rect::new(x, 10.0, 80.0, 36.0),
8559            )
8560            .with_content_bounds(Rect::new(x, 10.0, 80.0, 36.0))
8561            .with_paint_bounds(Rect::new(x, 10.0, 80.0, 36.0))
8562            .with_cache_policy(LayerCachePolicy::Direct);
8563
8564            let mut layer_scene = Scene::new();
8565            layer_scene.push(SceneCommand::FillRect {
8566                rect: Rect::new(x, 10.0, 80.0, 36.0),
8567                brush: Color::rgba(0.82, 0.36, 0.18, 1.0).into(),
8568            });
8569
8570            SceneLayer::from_descriptor(descriptor, layer_scene)
8571        };
8572
8573        let mut scene = Scene::new();
8574        scene.push(SceneCommand::Layer(build_layer(8.0)));
8575
8576        let mut frame = SceneFrame {
8577            window_id: WindowId::new(24),
8578            viewport: Size::new(160.0, 80.0),
8579            surface_size: Size::new(160.0, 80.0),
8580            scale_factor: 1.0,
8581            dirty_regions: Vec::new(),
8582            layer_updates: content_updates([layer_id]),
8583            scene,
8584            font_registry: Arc::new(FontRegistry::new()),
8585            image_registry: Arc::new(ImageRegistry::new()),
8586            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8587        };
8588
8589        let mut text_engine = TextEngine::new().unwrap();
8590        let mut compositor = RetainedCompositorState::default();
8591        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8592        assert!(compositor.last_frame_stats.packet_build_count > 0);
8593        let layer_container = CompositionContainerId::Layer(SceneLayerId::from_widget(layer_id));
8594        let first_signature = packet_signature(&compositor, layer_container);
8595        let first_content_version =
8596            compositor.layers[&SceneLayerId::from_widget(layer_id)].content_version;
8597
8598        frame.scene = {
8599            let mut next = Scene::new();
8600            next.push(SceneCommand::Layer(build_layer(44.0)));
8601            next
8602        };
8603        frame.layer_updates = vec![SceneLayerUpdate::from_descriptor(
8604            SceneLayerUpdateKind::Transform,
8605            SceneLayerDescriptor::new(
8606                SceneLayerId::from_widget(layer_id),
8607                layer_id,
8608                Rect::new(44.0, 10.0, 80.0, 36.0),
8609            )
8610            .with_content_bounds(Rect::new(44.0, 10.0, 80.0, 36.0))
8611            .with_paint_bounds(Rect::new(44.0, 10.0, 80.0, 36.0))
8612            .with_cache_policy(LayerCachePolicy::Direct),
8613        )];
8614
8615        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8616        let second_signature = packet_signature(&compositor, layer_container);
8617        let second_content_version =
8618            compositor.layers[&SceneLayerId::from_widget(layer_id)].content_version;
8619
8620        assert_eq!(first_signature, second_signature);
8621        assert_eq!(first_content_version, second_content_version);
8622        assert_eq!(compositor.last_frame_stats.direct_packets, 1);
8623        assert_eq!(compositor.last_frame_stats.packet_build_count, 0);
8624        assert_ne!(first.scene_vertices, second.scene_vertices);
8625    }
8626
8627    #[test]
8628    fn retained_compositor_reuses_direct_packets_across_clip_only_updates() {
8629        let layer_id = WidgetId::new(54);
8630        let descriptor = SceneLayerDescriptor::new(
8631            SceneLayerId::from_widget(layer_id),
8632            layer_id,
8633            Rect::new(8.0, 8.0, 96.0, 48.0),
8634        )
8635        .with_content_bounds(Rect::new(8.0, 8.0, 96.0, 48.0))
8636        .with_paint_bounds(Rect::new(8.0, 8.0, 96.0, 48.0))
8637        .with_cache_policy(LayerCachePolicy::Direct);
8638
8639        let build_layer = || {
8640            let mut layer_scene = Scene::new();
8641            layer_scene.push(SceneCommand::FillRect {
8642                rect: Rect::new(8.0, 8.0, 96.0, 48.0),
8643                brush: Color::rgba(0.16, 0.52, 0.84, 1.0).into(),
8644            });
8645            SceneLayer::from_descriptor(descriptor.clone(), layer_scene)
8646        };
8647
8648        let build_scene = |clip: Rect| {
8649            let mut scene = Scene::new();
8650            scene.push(SceneCommand::PushClip { rect: clip });
8651            scene.push(SceneCommand::Layer(build_layer()));
8652            scene.push(SceneCommand::PopClip);
8653            scene
8654        };
8655
8656        let mut frame = SceneFrame {
8657            window_id: WindowId::new(25),
8658            viewport: Size::new(160.0, 96.0),
8659            surface_size: Size::new(160.0, 96.0),
8660            scale_factor: 1.0,
8661            dirty_regions: Vec::new(),
8662            layer_updates: content_updates([layer_id]),
8663            scene: build_scene(Rect::new(0.0, 0.0, 160.0, 96.0)),
8664            font_registry: Arc::new(FontRegistry::new()),
8665            image_registry: Arc::new(ImageRegistry::new()),
8666            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8667        };
8668
8669        let mut text_engine = TextEngine::new().unwrap();
8670        let mut compositor = RetainedCompositorState::default();
8671        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8672        let layer_container = CompositionContainerId::Layer(SceneLayerId::from_widget(layer_id));
8673        let first_signature = packet_signature(&compositor, layer_container);
8674        let first_content_version =
8675            compositor.layers[&SceneLayerId::from_widget(layer_id)].content_version;
8676        let first_clip_rects = first
8677            .draw_ops
8678            .iter()
8679            .map(|draw_op| draw_op.clip_rect)
8680            .collect::<Vec<_>>();
8681
8682        frame.scene = build_scene(Rect::new(24.0, 8.0, 64.0, 48.0));
8683        frame.layer_updates = vec![SceneLayerUpdate::from_descriptor(
8684            SceneLayerUpdateKind::Clip,
8685            descriptor.clone(),
8686        )];
8687
8688        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8689        let second_signature = packet_signature(&compositor, layer_container);
8690        let second_content_version =
8691            compositor.layers[&SceneLayerId::from_widget(layer_id)].content_version;
8692        let second_clip_rects = second
8693            .draw_ops
8694            .iter()
8695            .map(|draw_op| draw_op.clip_rect)
8696            .collect::<Vec<_>>();
8697
8698        assert_eq!(first_signature, second_signature);
8699        assert_eq!(first_content_version, second_content_version);
8700        assert_eq!(compositor.last_frame_stats.direct_packets, 1);
8701        assert_eq!(first.scene_vertices, second.scene_vertices);
8702        assert_ne!(first_clip_rects, second_clip_rects);
8703    }
8704
8705    #[test]
8706    fn retained_compositor_rebuilds_retained_packets_across_ancestor_clip_updates() {
8707        let shell_id = WidgetId::new(55);
8708        let scroll_id = WidgetId::new(56);
8709        let content_id = WidgetId::new(57);
8710
8711        let shell_descriptor = SceneLayerDescriptor::new(
8712            SceneLayerId::from_widget(shell_id),
8713            shell_id,
8714            Rect::new(0.0, 0.0, 220.0, 180.0),
8715        )
8716        .with_content_bounds(Rect::new(0.0, 0.0, 220.0, 180.0))
8717        .with_paint_bounds(Rect::new(0.0, 0.0, 220.0, 180.0))
8718        .with_cache_policy(LayerCachePolicy::Direct);
8719
8720        let scroll_descriptor = SceneLayerDescriptor::new(
8721            SceneLayerId::from_widget(scroll_id),
8722            scroll_id,
8723            Rect::new(0.0, 0.0, 220.0, 360.0),
8724        )
8725        .with_content_bounds(Rect::new(0.0, 0.0, 220.0, 360.0))
8726        .with_paint_bounds(Rect::new(0.0, 0.0, 220.0, 360.0))
8727        .with_cache_policy(LayerCachePolicy::Cached)
8728        .with_composition_mode(LayerCompositionMode::Scroll);
8729
8730        let content_descriptor = SceneLayerDescriptor::new(
8731            SceneLayerId::from_widget(content_id),
8732            content_id,
8733            Rect::new(0.0, 0.0, 220.0, 360.0),
8734        )
8735        .with_content_bounds(Rect::new(0.0, 0.0, 220.0, 360.0))
8736        .with_paint_bounds(Rect::new(0.0, 0.0, 220.0, 360.0))
8737        .with_cache_policy(LayerCachePolicy::Direct);
8738
8739        let build_scene = |clip: Rect| {
8740            let mut content_scene = Scene::new();
8741            content_scene.push(SceneCommand::FillRect {
8742                rect: Rect::new(0.0, 0.0, 220.0, 360.0),
8743                brush: Color::WHITE.into(),
8744            });
8745            content_scene.push(SceneCommand::FillRect {
8746                rect: Rect::new(16.0, 16.0, 188.0, 120.0),
8747                brush: Color::rgba(0.28, 0.20, 0.86, 1.0).into(),
8748            });
8749            content_scene.push(SceneCommand::FillRect {
8750                rect: Rect::new(16.0, 220.0, 188.0, 120.0),
8751                brush: Color::rgba(0.14, 0.55, 0.82, 1.0).into(),
8752            });
8753
8754            let mut scroll_scene = Scene::new();
8755            scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8756                content_descriptor.clone(),
8757                content_scene,
8758            )));
8759
8760            let mut shell_scene = Scene::new();
8761            shell_scene.push(SceneCommand::PushClip { rect: clip });
8762            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8763                scroll_descriptor.clone(),
8764                scroll_scene,
8765            )));
8766            shell_scene.push(SceneCommand::PopClip);
8767
8768            let mut scene = Scene::new();
8769            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8770                shell_descriptor.clone(),
8771                shell_scene,
8772            )));
8773            scene
8774        };
8775
8776        let mut frame = SceneFrame {
8777            window_id: WindowId::new(26),
8778            viewport: Size::new(220.0, 180.0),
8779            surface_size: Size::new(220.0, 180.0),
8780            scale_factor: 1.0,
8781            dirty_regions: Vec::new(),
8782            layer_updates: vec![
8783                SceneLayerUpdate::from_descriptor(
8784                    SceneLayerUpdateKind::Content,
8785                    scroll_descriptor.clone(),
8786                )
8787                .with_damage(scroll_descriptor.paint_bounds),
8788            ],
8789            scene: build_scene(Rect::new(0.0, 0.0, 220.0, 180.0)),
8790            font_registry: Arc::new(FontRegistry::new()),
8791            image_registry: Arc::new(ImageRegistry::new()),
8792            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8793        };
8794
8795        let mut text_engine = TextEngine::new().unwrap();
8796        let mut compositor = RetainedCompositorState::default();
8797        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8798        let first_clip_rects = first
8799            .draw_ops
8800            .iter()
8801            .map(|draw_op| draw_op.clip_rect)
8802            .collect::<Vec<_>>();
8803
8804        frame.scene = build_scene(Rect::new(0.0, 0.0, 220.0, 96.0));
8805        frame.layer_updates = vec![
8806            SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Clip, shell_descriptor.clone())
8807                .with_damage(shell_descriptor.paint_bounds),
8808        ];
8809
8810        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8811        let second_clip_rects = second
8812            .draw_ops
8813            .iter()
8814            .map(|draw_op| draw_op.clip_rect)
8815            .collect::<Vec<_>>();
8816
8817        assert_ne!(first_clip_rects, second_clip_rects);
8818    }
8819
8820    #[test]
8821    fn retained_compositor_prunes_removed_layers_and_packets() {
8822        let removed_id = WidgetId::new(61);
8823        let replacement_id = WidgetId::new(62);
8824
8825        let mut first_scene = Scene::new();
8826        first_scene.push(SceneCommand::Layer(SceneLayer::new(
8827            removed_id,
8828            Rect::new(0.0, 0.0, 24.0, 24.0),
8829            {
8830                let mut scene = Scene::new();
8831                scene.push(SceneCommand::FillRect {
8832                    rect: Rect::new(0.0, 0.0, 24.0, 24.0),
8833                    brush: Color::rgba(1.0, 0.0, 0.0, 1.0).into(),
8834                });
8835                scene
8836            },
8837        )));
8838
8839        let mut frame = SceneFrame {
8840            window_id: WindowId::new(23),
8841            viewport: Size::new(64.0, 64.0),
8842            surface_size: Size::new(64.0, 64.0),
8843            scale_factor: 1.0,
8844            dirty_regions: Vec::new(),
8845            layer_updates: content_updates([removed_id]),
8846            scene: first_scene,
8847            font_registry: Arc::new(FontRegistry::new()),
8848            image_registry: Arc::new(ImageRegistry::new()),
8849            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8850        };
8851
8852        let mut text_engine = TextEngine::new().unwrap();
8853        let mut compositor = RetainedCompositorState::default();
8854        let _ = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8855        let removed_layer_id = SceneLayerId::from_widget(removed_id);
8856        let replacement_layer_id = SceneLayerId::from_widget(replacement_id);
8857        let removed_packet_id = RetainedPacketId {
8858            container: CompositionContainerId::Layer(removed_layer_id),
8859            segment_index: 0,
8860        };
8861        assert!(compositor.layers.contains_key(&removed_layer_id));
8862        assert!(compositor.packets.contains_key(&removed_packet_id));
8863
8864        let mut second_scene = Scene::new();
8865        second_scene.push(SceneCommand::Layer(SceneLayer::new(
8866            replacement_id,
8867            Rect::new(8.0, 8.0, 24.0, 24.0),
8868            {
8869                let mut scene = Scene::new();
8870                scene.push(SceneCommand::FillRect {
8871                    rect: Rect::new(8.0, 8.0, 24.0, 24.0),
8872                    brush: Color::rgba(0.0, 1.0, 0.0, 1.0).into(),
8873                });
8874                scene
8875            },
8876        )));
8877        frame.scene = second_scene;
8878        frame.layer_updates = content_updates([replacement_id]);
8879
8880        let _ = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
8881
8882        assert!(!compositor.layers.contains_key(&removed_layer_id));
8883        assert!(!compositor.packets.contains_key(&removed_packet_id));
8884        assert!(compositor.layers.contains_key(&replacement_layer_id));
8885        assert!(compositor.packets.contains_key(&RetainedPacketId {
8886            container: CompositionContainerId::Layer(replacement_layer_id),
8887            segment_index: 0,
8888        }));
8889    }
8890
8891    #[test]
8892    fn overlay_layers_paint_above_later_normal_siblings() {
8893        let normal_id = WidgetId::new(205);
8894        let overlay_id = WidgetId::new(206);
8895
8896        let build_frame = || {
8897            let normal_descriptor = SceneLayerDescriptor::new(
8898                SceneLayerId::from_widget(normal_id),
8899                normal_id,
8900                Rect::new(32.0, 12.0, 72.0, 48.0),
8901            )
8902            .with_content_bounds(Rect::new(32.0, 12.0, 72.0, 48.0))
8903            .with_paint_bounds(Rect::new(32.0, 12.0, 72.0, 48.0))
8904            .with_cache_policy(LayerCachePolicy::Direct);
8905            let overlay_descriptor = SceneLayerDescriptor::new(
8906                SceneLayerId::from_widget(overlay_id),
8907                overlay_id,
8908                Rect::new(12.0, 12.0, 72.0, 48.0),
8909            )
8910            .with_content_bounds(Rect::new(12.0, 12.0, 72.0, 48.0))
8911            .with_paint_bounds(Rect::new(12.0, 12.0, 72.0, 48.0))
8912            .with_cache_policy(LayerCachePolicy::Direct)
8913            .with_composition_mode(LayerCompositionMode::Overlay);
8914
8915            let mut overlay_scene = Scene::new();
8916            overlay_scene.push(SceneCommand::FillRect {
8917                rect: overlay_descriptor.bounds,
8918                brush: Color::rgba(0.90, 0.16, 0.16, 1.0).into(),
8919            });
8920
8921            let mut normal_scene = Scene::new();
8922            normal_scene.push(SceneCommand::FillRect {
8923                rect: normal_descriptor.bounds,
8924                brush: Color::rgba(0.16, 0.72, 0.24, 1.0).into(),
8925            });
8926
8927            let mut scene = Scene::new();
8928            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8929                overlay_descriptor.clone(),
8930                overlay_scene,
8931            )));
8932            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
8933                normal_descriptor.clone(),
8934                normal_scene,
8935            )));
8936
8937            SceneFrame {
8938                window_id: WindowId::new(143),
8939                viewport: Size::new(128.0, 80.0),
8940                surface_size: Size::new(128.0, 80.0),
8941                scale_factor: 1.0,
8942                dirty_regions: Vec::new(),
8943                layer_updates: vec![
8944                    SceneLayerUpdate::from_descriptor(
8945                        SceneLayerUpdateKind::Content,
8946                        overlay_descriptor,
8947                    )
8948                    .with_damage(Rect::new(12.0, 12.0, 72.0, 48.0)),
8949                    SceneLayerUpdate::from_descriptor(
8950                        SceneLayerUpdateKind::Content,
8951                        normal_descriptor,
8952                    )
8953                    .with_damage(Rect::new(32.0, 12.0, 72.0, 48.0)),
8954                ],
8955                scene,
8956                font_registry: Arc::new(FontRegistry::new()),
8957                image_registry: Arc::new(ImageRegistry::new()),
8958                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
8959            }
8960        };
8961
8962        let mut renderer = WgpuRenderer::default();
8963        let frame = build_frame();
8964        renderer.render(&frame).unwrap();
8965        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
8966        let overlap = rgba_pixel(&pixels, 48, 24);
8967
8968        assert!(
8969            overlap[0] > overlap[1],
8970            "expected overlay pixel to dominate overlap, got rgba={overlap:?}"
8971        );
8972    }
8973
8974    #[test]
8975    fn nested_overlay_layers_paint_above_later_root_normal_siblings() {
8976        let shell_id = WidgetId::new(207);
8977        let nested_overlay_id = WidgetId::new(208);
8978        let blocker_id = WidgetId::new(209);
8979
8980        let build_frame = || {
8981            let shell_descriptor = SceneLayerDescriptor::new(
8982                SceneLayerId::from_widget(shell_id),
8983                shell_id,
8984                Rect::new(0.0, 0.0, 128.0, 80.0),
8985            )
8986            .with_content_bounds(Rect::new(0.0, 0.0, 128.0, 80.0))
8987            .with_paint_bounds(Rect::new(0.0, 0.0, 128.0, 80.0))
8988            .with_cache_policy(LayerCachePolicy::Direct);
8989            let nested_overlay_descriptor = SceneLayerDescriptor::new(
8990                SceneLayerId::from_widget(nested_overlay_id),
8991                nested_overlay_id,
8992                Rect::new(12.0, 12.0, 72.0, 48.0),
8993            )
8994            .with_content_bounds(Rect::new(12.0, 12.0, 72.0, 48.0))
8995            .with_paint_bounds(Rect::new(12.0, 12.0, 72.0, 48.0))
8996            .with_cache_policy(LayerCachePolicy::Direct)
8997            .with_composition_mode(LayerCompositionMode::Overlay);
8998            let blocker_descriptor = SceneLayerDescriptor::new(
8999                SceneLayerId::from_widget(blocker_id),
9000                blocker_id,
9001                Rect::new(32.0, 12.0, 72.0, 48.0),
9002            )
9003            .with_content_bounds(Rect::new(32.0, 12.0, 72.0, 48.0))
9004            .with_paint_bounds(Rect::new(32.0, 12.0, 72.0, 48.0))
9005            .with_cache_policy(LayerCachePolicy::Direct);
9006
9007            let mut nested_overlay_scene = Scene::new();
9008            nested_overlay_scene.push(SceneCommand::FillRect {
9009                rect: nested_overlay_descriptor.bounds,
9010                brush: Color::rgba(0.90, 0.16, 0.16, 1.0).into(),
9011            });
9012
9013            let mut shell_scene = Scene::new();
9014            shell_scene.push(SceneCommand::FillRect {
9015                rect: shell_descriptor.bounds,
9016                brush: Color::rgba(0.97, 0.98, 1.0, 1.0).into(),
9017            });
9018            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9019                nested_overlay_descriptor.clone(),
9020                nested_overlay_scene,
9021            )));
9022
9023            let mut blocker_scene = Scene::new();
9024            blocker_scene.push(SceneCommand::FillRect {
9025                rect: blocker_descriptor.bounds,
9026                brush: Color::rgba(0.16, 0.72, 0.24, 1.0).into(),
9027            });
9028
9029            let mut scene = Scene::new();
9030            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9031                shell_descriptor.clone(),
9032                shell_scene,
9033            )));
9034            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9035                blocker_descriptor.clone(),
9036                blocker_scene,
9037            )));
9038
9039            SceneFrame {
9040                window_id: WindowId::new(144),
9041                viewport: Size::new(128.0, 80.0),
9042                surface_size: Size::new(128.0, 80.0),
9043                scale_factor: 1.0,
9044                dirty_regions: Vec::new(),
9045                layer_updates: vec![
9046                    SceneLayerUpdate::from_descriptor(
9047                        SceneLayerUpdateKind::Content,
9048                        shell_descriptor,
9049                    )
9050                    .with_damage(Rect::new(0.0, 0.0, 128.0, 80.0)),
9051                    SceneLayerUpdate::from_descriptor(
9052                        SceneLayerUpdateKind::Content,
9053                        nested_overlay_descriptor,
9054                    )
9055                    .with_damage(Rect::new(12.0, 12.0, 72.0, 48.0)),
9056                    SceneLayerUpdate::from_descriptor(
9057                        SceneLayerUpdateKind::Content,
9058                        blocker_descriptor,
9059                    )
9060                    .with_damage(Rect::new(32.0, 12.0, 72.0, 48.0)),
9061                ],
9062                scene,
9063                font_registry: Arc::new(FontRegistry::new()),
9064                image_registry: Arc::new(ImageRegistry::new()),
9065                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9066            }
9067        };
9068
9069        let mut renderer = WgpuRenderer::default();
9070        let frame = build_frame();
9071        renderer.render(&frame).unwrap();
9072        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
9073        let overlap = rgba_pixel(&pixels, 48, 24);
9074
9075        assert!(
9076            overlap[0] > overlap[1],
9077            "expected nested overlay pixel to dominate overlap, got rgba={overlap:?}"
9078        );
9079    }
9080
9081    #[test]
9082    fn cached_ancestor_overlay_layers_paint_above_later_root_normal_siblings() {
9083        let shell_id = WidgetId::new(210);
9084        let nested_overlay_id = WidgetId::new(211);
9085        let blocker_id = WidgetId::new(212);
9086
9087        let build_frame = || {
9088            let shell_descriptor = SceneLayerDescriptor::new(
9089                SceneLayerId::from_widget(shell_id),
9090                shell_id,
9091                Rect::new(0.0, 0.0, 512.0, 120.0),
9092            )
9093            .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 120.0))
9094            .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 120.0))
9095            .with_cache_policy(LayerCachePolicy::Cached);
9096            let nested_overlay_descriptor = SceneLayerDescriptor::new(
9097                SceneLayerId::from_widget(nested_overlay_id),
9098                nested_overlay_id,
9099                Rect::new(12.0, 12.0, 180.0, 80.0),
9100            )
9101            .with_content_bounds(Rect::new(12.0, 12.0, 180.0, 80.0))
9102            .with_paint_bounds(Rect::new(12.0, 12.0, 180.0, 80.0))
9103            .with_cache_policy(LayerCachePolicy::Direct)
9104            .with_composition_mode(LayerCompositionMode::Overlay);
9105            let blocker_descriptor = SceneLayerDescriptor::new(
9106                SceneLayerId::from_widget(blocker_id),
9107                blocker_id,
9108                Rect::new(96.0, 40.0, 220.0, 44.0),
9109            )
9110            .with_content_bounds(Rect::new(96.0, 40.0, 220.0, 44.0))
9111            .with_paint_bounds(Rect::new(96.0, 40.0, 220.0, 44.0))
9112            .with_cache_policy(LayerCachePolicy::Direct);
9113
9114            let mut nested_overlay_scene = Scene::new();
9115            nested_overlay_scene.push(SceneCommand::FillRect {
9116                rect: nested_overlay_descriptor.bounds,
9117                brush: Color::rgba(0.90, 0.16, 0.16, 1.0).into(),
9118            });
9119
9120            let mut shell_scene = Scene::new();
9121            shell_scene.push(SceneCommand::FillRect {
9122                rect: shell_descriptor.bounds,
9123                brush: Color::rgba(0.97, 0.98, 1.0, 1.0).into(),
9124            });
9125            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9126                nested_overlay_descriptor.clone(),
9127                nested_overlay_scene,
9128            )));
9129
9130            let mut blocker_scene = Scene::new();
9131            blocker_scene.push(SceneCommand::FillRect {
9132                rect: blocker_descriptor.bounds,
9133                brush: Color::rgba(0.16, 0.72, 0.24, 1.0).into(),
9134            });
9135
9136            let mut scene = Scene::new();
9137            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9138                shell_descriptor.clone(),
9139                shell_scene,
9140            )));
9141            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9142                blocker_descriptor.clone(),
9143                blocker_scene,
9144            )));
9145
9146            SceneFrame {
9147                window_id: WindowId::new(145),
9148                viewport: Size::new(512.0, 120.0),
9149                surface_size: Size::new(512.0, 120.0),
9150                scale_factor: 1.0,
9151                dirty_regions: Vec::new(),
9152                layer_updates: vec![
9153                    SceneLayerUpdate::from_descriptor(
9154                        SceneLayerUpdateKind::Content,
9155                        shell_descriptor,
9156                    )
9157                    .with_damage(Rect::new(0.0, 0.0, 512.0, 120.0)),
9158                    SceneLayerUpdate::from_descriptor(
9159                        SceneLayerUpdateKind::Content,
9160                        nested_overlay_descriptor,
9161                    )
9162                    .with_damage(Rect::new(12.0, 12.0, 180.0, 80.0)),
9163                    SceneLayerUpdate::from_descriptor(
9164                        SceneLayerUpdateKind::Content,
9165                        blocker_descriptor,
9166                    )
9167                    .with_damage(Rect::new(96.0, 40.0, 220.0, 44.0)),
9168                ],
9169                scene,
9170                font_registry: Arc::new(FontRegistry::new()),
9171                image_registry: Arc::new(ImageRegistry::new()),
9172                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9173            }
9174        };
9175
9176        let mut renderer = WgpuRenderer::default();
9177        let frame = build_frame();
9178        renderer.render(&frame).unwrap();
9179        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
9180        let overlap = rgba_pixel(&pixels, 120, 52);
9181
9182        assert!(
9183            overlap[0] > overlap[1],
9184            "expected cached-ancestor overlay pixel to dominate overlap, got rgba={overlap:?}"
9185        );
9186    }
9187
9188    #[test]
9189    fn retained_compositor_routes_descendant_damage_into_cached_parent_packets() {
9190        let parent_id = WidgetId::new(81);
9191        let child_id = WidgetId::new(82);
9192
9193        let parent_descriptor = SceneLayerDescriptor::new(
9194            SceneLayerId::from_widget(parent_id),
9195            parent_id,
9196            Rect::new(0.0, 0.0, 512.0, 128.0),
9197        )
9198        .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
9199        .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
9200        .with_cache_policy(LayerCachePolicy::Cached);
9201        let child_descriptor = SceneLayerDescriptor::new(
9202            SceneLayerId::from_widget(child_id),
9203            child_id,
9204            Rect::new(300.0, 24.0, 48.0, 48.0),
9205        );
9206
9207        let build_parent_scene = |child_brush: Color| {
9208            let mut child_scene = Scene::new();
9209            child_scene.push(SceneCommand::FillRect {
9210                rect: Rect::new(300.0, 24.0, 48.0, 48.0),
9211                brush: child_brush.into(),
9212            });
9213
9214            let mut parent_scene = Scene::new();
9215            parent_scene.push(SceneCommand::FillRect {
9216                rect: Rect::new(0.0, 0.0, 512.0, 128.0),
9217                brush: Color::rgba(0.1, 0.1, 0.1, 1.0).into(),
9218            });
9219            parent_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9220                child_descriptor.clone(),
9221                child_scene,
9222            )));
9223            parent_scene
9224        };
9225
9226        let mut scene = Scene::new();
9227        scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9228            parent_descriptor.clone(),
9229            build_parent_scene(Color::rgba(1.0, 0.0, 0.0, 1.0)),
9230        )));
9231
9232        let mut frame = SceneFrame {
9233            window_id: WindowId::new(32),
9234            viewport: Size::new(512.0, 128.0),
9235            surface_size: Size::new(512.0, 128.0),
9236            scale_factor: 1.0,
9237            dirty_regions: Vec::new(),
9238            layer_updates: vec![
9239                SceneLayerUpdate::from_descriptor(
9240                    SceneLayerUpdateKind::Content,
9241                    parent_descriptor.clone(),
9242                )
9243                .with_damage(Rect::new(0.0, 0.0, 512.0, 128.0)),
9244                SceneLayerUpdate::from_descriptor(
9245                    SceneLayerUpdateKind::Content,
9246                    child_descriptor.clone(),
9247                )
9248                .with_damage(Rect::new(300.0, 24.0, 48.0, 48.0)),
9249            ],
9250            scene,
9251            font_registry: Arc::new(FontRegistry::new()),
9252            image_registry: Arc::new(ImageRegistry::new()),
9253            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9254        };
9255
9256        let mut text_engine = TextEngine::new().unwrap();
9257        let mut compositor = RetainedCompositorState::default();
9258        let _ = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9259
9260        assert!(frame.scene.replace_layer(
9261            parent_id,
9262            SceneLayer::from_descriptor(
9263                parent_descriptor.clone(),
9264                build_parent_scene(Color::rgba(0.0, 1.0, 0.0, 1.0)),
9265            ),
9266        ));
9267        frame.layer_updates = vec![
9268            SceneLayerUpdate::from_descriptor(
9269                SceneLayerUpdateKind::Content,
9270                child_descriptor.clone(),
9271            )
9272            .with_damage(Rect::new(300.0, 24.0, 48.0, 48.0)),
9273        ];
9274
9275        let _ = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9276    }
9277
9278    #[test]
9279    fn retained_compositor_routes_descendant_transform_into_cached_parent_packets() {
9280        let parent_id = WidgetId::new(181);
9281        let child_id = WidgetId::new(182);
9282
9283        let parent_descriptor = SceneLayerDescriptor::new(
9284            SceneLayerId::from_widget(parent_id),
9285            parent_id,
9286            Rect::new(0.0, 0.0, 512.0, 128.0),
9287        )
9288        .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
9289        .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
9290        .with_cache_policy(LayerCachePolicy::Cached);
9291
9292        let child_descriptor = |x: f32| {
9293            SceneLayerDescriptor::new(
9294                SceneLayerId::from_widget(child_id),
9295                child_id,
9296                Rect::new(x, 24.0, 48.0, 48.0),
9297            )
9298            .with_content_bounds(Rect::new(x, 24.0, 48.0, 48.0))
9299            .with_paint_bounds(Rect::new(x, 24.0, 48.0, 48.0))
9300            .with_cache_policy(LayerCachePolicy::Direct)
9301        };
9302
9303        let build_parent_scene = |child_x: f32| {
9304            let mut child_scene = Scene::new();
9305            child_scene.push(SceneCommand::FillRect {
9306                rect: Rect::new(child_x, 24.0, 48.0, 48.0),
9307                brush: Color::rgba(0.84, 0.32, 0.18, 1.0).into(),
9308            });
9309
9310            let mut parent_scene = Scene::new();
9311            parent_scene.push(SceneCommand::FillRect {
9312                rect: Rect::new(0.0, 0.0, 512.0, 128.0),
9313                brush: Color::rgba(0.1, 0.1, 0.1, 1.0).into(),
9314            });
9315            parent_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9316                child_descriptor(child_x),
9317                child_scene,
9318            )));
9319            parent_scene
9320        };
9321
9322        let mut scene = Scene::new();
9323        scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9324            parent_descriptor.clone(),
9325            build_parent_scene(300.0),
9326        )));
9327
9328        let mut frame = SceneFrame {
9329            window_id: WindowId::new(132),
9330            viewport: Size::new(512.0, 128.0),
9331            surface_size: Size::new(512.0, 128.0),
9332            scale_factor: 1.0,
9333            dirty_regions: Vec::new(),
9334            layer_updates: vec![
9335                SceneLayerUpdate::from_descriptor(
9336                    SceneLayerUpdateKind::Content,
9337                    parent_descriptor.clone(),
9338                )
9339                .with_damage(Rect::new(0.0, 0.0, 512.0, 128.0)),
9340                SceneLayerUpdate::from_descriptor(
9341                    SceneLayerUpdateKind::Content,
9342                    child_descriptor(300.0),
9343                )
9344                .with_damage(Rect::new(300.0, 24.0, 48.0, 48.0)),
9345            ],
9346            scene,
9347            font_registry: Arc::new(FontRegistry::new()),
9348            image_registry: Arc::new(ImageRegistry::new()),
9349            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9350        };
9351
9352        let mut text_engine = TextEngine::new().unwrap();
9353        let mut compositor = RetainedCompositorState::default();
9354        let _ = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9355
9356        assert!(frame.scene.replace_layer(
9357            parent_id,
9358            SceneLayer::from_descriptor(parent_descriptor.clone(), build_parent_scene(340.0)),
9359        ));
9360        frame.layer_updates = vec![
9361            SceneLayerUpdate::from_descriptor(
9362                SceneLayerUpdateKind::Transform,
9363                child_descriptor(340.0),
9364            )
9365            .with_damage(Rect::new(300.0, 24.0, 88.0, 48.0)),
9366        ];
9367
9368        let _ = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9369    }
9370
9371    #[test]
9372    fn retained_compositor_updates_nested_retained_scroll_layer_after_child_transform() {
9373        let shell_id = WidgetId::new(191);
9374        let scroll_id = WidgetId::new(192);
9375        let content_id = WidgetId::new(193);
9376        let first_id = WidgetId::new(194);
9377        let second_id = WidgetId::new(195);
9378        let third_id = WidgetId::new(196);
9379
9380        let shell_descriptor = SceneLayerDescriptor::new(
9381            SceneLayerId::from_widget(shell_id),
9382            shell_id,
9383            Rect::new(0.0, 0.0, 360.0, 220.0),
9384        )
9385        .with_content_bounds(Rect::new(0.0, 0.0, 360.0, 220.0))
9386        .with_paint_bounds(Rect::new(0.0, 0.0, 360.0, 220.0))
9387        .with_cache_policy(LayerCachePolicy::Direct);
9388
9389        let scroll_descriptor = SceneLayerDescriptor::new(
9390            SceneLayerId::from_widget(scroll_id),
9391            scroll_id,
9392            Rect::new(0.0, 0.0, 240.0, 220.0),
9393        )
9394        .with_content_bounds(Rect::new(0.0, 0.0, 240.0, 220.0))
9395        .with_paint_bounds(Rect::new(0.0, 0.0, 240.0, 220.0))
9396        .with_cache_policy(LayerCachePolicy::Cached)
9397        .with_composition_mode(LayerCompositionMode::Scroll);
9398
9399        let content_descriptor = |y: f32| {
9400            SceneLayerDescriptor::new(
9401                SceneLayerId::from_widget(content_id),
9402                content_id,
9403                Rect::new(0.0, y, 360.0, 360.0),
9404            )
9405            .with_content_bounds(Rect::new(0.0, y, 220.0, 360.0))
9406            .with_paint_bounds(Rect::new(0.0, y, 220.0, 360.0))
9407            .with_cache_policy(LayerCachePolicy::Direct)
9408        };
9409
9410        let child_layer = |id: WidgetId, y: f32, brush: Color| {
9411            let mut scene = Scene::new();
9412            scene.push(SceneCommand::FillRect {
9413                rect: Rect::new(0.0, y, 220.0, 120.0),
9414                brush: brush.into(),
9415            });
9416            SceneLayer::from_descriptor(
9417                SceneLayerDescriptor::new(
9418                    SceneLayerId::from_widget(id),
9419                    id,
9420                    Rect::new(0.0, y, 220.0, 120.0),
9421                )
9422                .with_content_bounds(Rect::new(0.0, y, 220.0, 120.0))
9423                .with_paint_bounds(Rect::new(0.0, y, 220.0, 120.0))
9424                .with_cache_policy(LayerCachePolicy::Direct),
9425                scene,
9426            )
9427        };
9428
9429        let build_content_scene = |y: f32| {
9430            let mut scene = Scene::new();
9431            scene.push(SceneCommand::Layer(child_layer(
9432                first_id,
9433                y,
9434                Color::rgba(0.82, 0.36, 0.18, 1.0),
9435            )));
9436            scene.push(SceneCommand::Layer(child_layer(
9437                second_id,
9438                y + 120.0,
9439                Color::rgba(0.18, 0.54, 0.82, 1.0),
9440            )));
9441            scene.push(SceneCommand::Layer(child_layer(
9442                third_id,
9443                y + 240.0,
9444                Color::rgba(0.24, 0.72, 0.36, 1.0),
9445            )));
9446            scene
9447        };
9448
9449        let build_shell_scene = |content_y: f32| {
9450            let mut scroll_scene = Scene::new();
9451            scroll_scene.push(SceneCommand::PushClip {
9452                rect: Rect::new(0.0, 0.0, 230.0, 220.0),
9453            });
9454            scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9455                content_descriptor(content_y),
9456                build_content_scene(content_y),
9457            )));
9458            scroll_scene.push(SceneCommand::PopClip);
9459
9460            let mut shell_scene = Scene::new();
9461            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9462                scroll_descriptor.clone(),
9463                scroll_scene,
9464            )));
9465            shell_scene.push(SceneCommand::FillRect {
9466                rect: Rect::new(240.0, 0.0, 120.0, 220.0),
9467                brush: Color::rgba(0.94, 0.95, 0.97, 1.0).into(),
9468            });
9469            shell_scene
9470        };
9471
9472        let mut scene = Scene::new();
9473        scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9474            shell_descriptor.clone(),
9475            build_shell_scene(0.0),
9476        )));
9477
9478        let mut frame = SceneFrame {
9479            window_id: WindowId::new(142),
9480            viewport: Size::new(360.0, 220.0),
9481            surface_size: Size::new(360.0, 220.0),
9482            scale_factor: 1.0,
9483            dirty_regions: Vec::new(),
9484            layer_updates: vec![
9485                SceneLayerUpdate::from_descriptor(
9486                    SceneLayerUpdateKind::Content,
9487                    scroll_descriptor.clone(),
9488                )
9489                .with_damage(scroll_descriptor.paint_bounds),
9490                SceneLayerUpdate::from_descriptor(
9491                    SceneLayerUpdateKind::Content,
9492                    content_descriptor(0.0),
9493                )
9494                .with_damage(Rect::new(0.0, 0.0, 220.0, 360.0)),
9495            ],
9496            scene,
9497            font_registry: Arc::new(FontRegistry::new()),
9498            image_registry: Arc::new(ImageRegistry::new()),
9499            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9500        };
9501
9502        let mut text_engine = TextEngine::new().unwrap();
9503        let mut compositor = RetainedCompositorState::default();
9504        let first_frame = frame.clone();
9505        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9506
9507        assert!(
9508            frame
9509                .scene
9510                .translate_layer(content_id, Vector::new(0.0, -72.0))
9511        );
9512        frame.layer_updates = vec![
9513            SceneLayerUpdate::from_descriptor(
9514                SceneLayerUpdateKind::Transform,
9515                content_descriptor(-72.0),
9516            )
9517            .with_damage(Rect::new(0.0, -72.0, 220.0, 432.0)),
9518            SceneLayerUpdate::from_descriptor(
9519                SceneLayerUpdateKind::Transform,
9520                scroll_descriptor.clone(),
9521            )
9522            .with_damage(Rect::new(0.0, 0.0, 220.0, 360.0)),
9523        ];
9524
9525        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9526
9527        assert_ne!(first.scene_vertices, second.scene_vertices);
9528        let mut renderer = WgpuRenderer::default();
9529        renderer.render(&first_frame).unwrap();
9530        let before = renderer
9531            .capture_last_frame_rgba(first_frame.window_id)
9532            .unwrap();
9533        renderer.render(&frame).unwrap();
9534        let after = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
9535
9536        assert!(
9537            rgba_image_diff_count(&before, &after) > 0,
9538            "translated retained layer did not change the captured image beyond {RGBA_CHANNEL_TOLERANCE} channel value"
9539        );
9540    }
9541
9542    #[test]
9543    fn retained_compositor_routes_nested_cached_descendant_damage_into_packet_owner() {
9544        let outer_id = WidgetId::new(83);
9545        let inner_id = WidgetId::new(84);
9546        let leaf_id = WidgetId::new(85);
9547
9548        let outer_descriptor = SceneLayerDescriptor::new(
9549            SceneLayerId::from_widget(outer_id),
9550            outer_id,
9551            Rect::new(0.0, 0.0, 512.0, 128.0),
9552        )
9553        .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
9554        .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 128.0))
9555        .with_cache_policy(LayerCachePolicy::Cached);
9556        let inner_descriptor = SceneLayerDescriptor::new(
9557            SceneLayerId::from_widget(inner_id),
9558            inner_id,
9559            Rect::new(256.0, 0.0, 256.0, 128.0),
9560        )
9561        .with_content_bounds(Rect::new(256.0, 0.0, 256.0, 128.0))
9562        .with_paint_bounds(Rect::new(256.0, 0.0, 256.0, 128.0))
9563        .with_cache_policy(LayerCachePolicy::Cached);
9564        let leaf_descriptor = SceneLayerDescriptor::new(
9565            SceneLayerId::from_widget(leaf_id),
9566            leaf_id,
9567            Rect::new(300.0, 24.0, 48.0, 48.0),
9568        )
9569        .with_content_bounds(Rect::new(300.0, 24.0, 48.0, 48.0))
9570        .with_paint_bounds(Rect::new(300.0, 24.0, 48.0, 48.0));
9571
9572        let build_scene = |leaf_brush: Color| {
9573            let mut leaf_scene = Scene::new();
9574            leaf_scene.push(SceneCommand::FillRect {
9575                rect: leaf_descriptor.bounds,
9576                brush: leaf_brush.into(),
9577            });
9578
9579            let mut inner_scene = Scene::new();
9580            inner_scene.push(SceneCommand::FillRect {
9581                rect: inner_descriptor.bounds,
9582                brush: Color::rgba(0.12, 0.12, 0.16, 1.0).into(),
9583            });
9584            inner_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9585                leaf_descriptor.clone(),
9586                leaf_scene,
9587            )));
9588
9589            let mut outer_scene = Scene::new();
9590            outer_scene.push(SceneCommand::FillRect {
9591                rect: outer_descriptor.bounds,
9592                brush: Color::rgba(0.08, 0.08, 0.10, 1.0).into(),
9593            });
9594            outer_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9595                inner_descriptor.clone(),
9596                inner_scene,
9597            )));
9598
9599            let mut scene = Scene::new();
9600            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9601                outer_descriptor.clone(),
9602                outer_scene,
9603            )));
9604            scene
9605        };
9606
9607        let mut frame = SceneFrame {
9608            window_id: WindowId::new(36),
9609            viewport: Size::new(512.0, 128.0),
9610            surface_size: Size::new(512.0, 128.0),
9611            scale_factor: 1.0,
9612            dirty_regions: Vec::new(),
9613            layer_updates: vec![
9614                SceneLayerUpdate::from_descriptor(
9615                    SceneLayerUpdateKind::Content,
9616                    outer_descriptor.clone(),
9617                )
9618                .with_damage(outer_descriptor.paint_bounds),
9619                SceneLayerUpdate::from_descriptor(
9620                    SceneLayerUpdateKind::Content,
9621                    inner_descriptor.clone(),
9622                )
9623                .with_damage(inner_descriptor.paint_bounds),
9624                SceneLayerUpdate::from_descriptor(
9625                    SceneLayerUpdateKind::Content,
9626                    leaf_descriptor.clone(),
9627                )
9628                .with_damage(leaf_descriptor.paint_bounds),
9629            ],
9630            scene: build_scene(Color::rgba(1.0, 0.0, 0.0, 1.0)),
9631            font_registry: Arc::new(FontRegistry::new()),
9632            image_registry: Arc::new(ImageRegistry::new()),
9633            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9634        };
9635
9636        let mut text_engine = TextEngine::new().unwrap();
9637        let mut compositor = RetainedCompositorState::default();
9638        let first = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9639
9640        frame.scene = build_scene(Color::rgba(0.0, 1.0, 0.0, 1.0));
9641        frame.layer_updates = vec![
9642            SceneLayerUpdate::from_descriptor(
9643                SceneLayerUpdateKind::Content,
9644                leaf_descriptor.clone(),
9645            )
9646            .with_damage(leaf_descriptor.paint_bounds),
9647        ];
9648
9649        let second = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
9650
9651        assert_ne!(first.scene_vertices, second.scene_vertices);
9652    }
9653
9654    #[test]
9655    fn retained_packets_match_direct_text_across_packet_boundaries() {
9656        let handle = FontHandle::new(27);
9657        let mut fonts = FontRegistry::new();
9658        fonts.insert(handle, load_test_font());
9659
9660        let layer_id = WidgetId::new(92);
9661        let build_frame = |cache_policy| {
9662            let descriptor = SceneLayerDescriptor::new(
9663                SceneLayerId::from_widget(layer_id),
9664                layer_id,
9665                Rect::new(0.0, 0.0, 512.0, 72.0),
9666            )
9667            .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 72.0))
9668            .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 72.0))
9669            .with_cache_policy(cache_policy);
9670
9671            let mut layer_scene = Scene::new();
9672            layer_scene.push(SceneCommand::FillRect {
9673                rect: Rect::new(0.0, 0.0, 512.0, 72.0),
9674                brush: Color::rgba(0.08, 0.09, 0.11, 1.0).into(),
9675            });
9676            layer_scene.push(SceneCommand::DrawText(TextRun {
9677                rect: Rect::new(332.0, 18.0, 156.0, 28.0),
9678                text: "boundary glyph sample".to_string(),
9679                style: TextStyle {
9680                    font: Some(handle),
9681                    ..TextStyle::new(Color::WHITE)
9682                },
9683            }));
9684
9685            let mut scene = Scene::new();
9686            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9687                descriptor.clone(),
9688                layer_scene,
9689            )));
9690
9691            SceneFrame {
9692                window_id: WindowId::new(92),
9693                viewport: Size::new(512.0, 72.0),
9694                surface_size: Size::new(512.0, 72.0),
9695                scale_factor: 1.0,
9696                dirty_regions: Vec::new(),
9697                layer_updates: vec![
9698                    SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
9699                        .with_damage(Rect::new(0.0, 0.0, 512.0, 72.0)),
9700                ],
9701                scene,
9702                font_registry: Arc::new(fonts.clone()),
9703                image_registry: Arc::new(ImageRegistry::new()),
9704                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9705            }
9706        };
9707
9708        let mut renderer = WgpuRenderer::default();
9709        let direct = build_frame(LayerCachePolicy::Direct);
9710        renderer.render(&direct).unwrap();
9711        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
9712
9713        let cached = build_frame(LayerCachePolicy::Cached);
9714        renderer.render(&cached).unwrap();
9715        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
9716
9717        assert_rgba_images_match(&direct_pixels, &cached_pixels);
9718    }
9719
9720    #[test]
9721    fn retained_layer_local_text_snaps_after_fractional_origin_composition() {
9722        let handle = FontHandle::new(127);
9723        let mut fonts = FontRegistry::new();
9724        fonts.insert(handle, load_test_font());
9725        let viewport = Size::new(240.0, 92.0);
9726        let layer_id = WidgetId::new(127);
9727        let layer_bounds = Rect::new(58.333_332, 18.333_334, 158.0, 54.0);
9728        let text_rect = Rect::new(
9729            layer_bounds.x() + 14.0,
9730            layer_bounds.y() + 14.0,
9731            132.0,
9732            24.0,
9733        );
9734        let text_style = TextStyle {
9735            font: Some(handle),
9736            font_size: 14.0,
9737            line_height: 19.0,
9738            color: Color::rgba(0.92, 0.94, 0.98, 1.0),
9739            ..TextStyle::default()
9740        };
9741        let text = "Popup text snaps".to_string();
9742
9743        let descriptor =
9744            SceneLayerDescriptor::new(SceneLayerId::from_widget(layer_id), layer_id, layer_bounds)
9745                .with_content_bounds(layer_bounds)
9746                .with_paint_bounds(layer_bounds);
9747        let mut layer_scene = Scene::new();
9748        layer_scene.push(SceneCommand::FillRect {
9749            rect: layer_bounds,
9750            brush: Color::rgba(0.12, 0.15, 0.20, 1.0).into(),
9751        });
9752        layer_scene.push(SceneCommand::DrawText(TextRun {
9753            rect: text_rect,
9754            text,
9755            style: text_style,
9756        }));
9757        let mut retained_scene = Scene::new();
9758        retained_scene.push(SceneCommand::FillRect {
9759            rect: Rect::new(0.0, 0.0, viewport.width, viewport.height),
9760            brush: Color::rgba(0.06, 0.07, 0.09, 1.0).into(),
9761        });
9762        retained_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9763            descriptor.clone(),
9764            layer_scene,
9765        )));
9766
9767        let retained = SceneFrame {
9768            window_id: WindowId::new(128),
9769            viewport,
9770            surface_size: Size::new(360.0, 138.0),
9771            scale_factor: 1.5,
9772            dirty_regions: Vec::new(),
9773            layer_updates: vec![
9774                SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
9775                    .with_damage(layer_bounds),
9776            ],
9777            scene: retained_scene,
9778            font_registry: Arc::new(fonts),
9779            image_registry: Arc::new(ImageRegistry::new()),
9780            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9781        };
9782
9783        let mut text_engine = TextEngine::new().unwrap();
9784        let mut compositor = RetainedCompositorState::default();
9785        let draw_ops = prepare_with_compositor(&retained, &mut text_engine, &mut compositor)
9786            .expect("retained frame should prepare");
9787        let text_op = draw_ops
9788            .draw_ops
9789            .iter()
9790            .find(|op| matches!(op.kind, DrawOpKind::TextAtlas))
9791            .expect("retained layer should emit atlas text");
9792        let start = text_op.vertices.start as usize;
9793        let end = start + text_op.vertices.len as usize;
9794        let instances = &draw_ops.text_instances[start..end];
9795        assert!(!instances.is_empty());
9796        for (index, instance) in instances.iter().enumerate() {
9797            let x = logical_x_from_ndc(instance.top_left[0], viewport);
9798            let y = logical_y_from_ndc(instance.top_left[1], viewport);
9799            assert!(
9800                is_physically_pixel_aligned(x, retained.scale_factor),
9801                "text instance {index} x was not aligned after layer composition: {x}"
9802            );
9803            assert!(
9804                is_physically_pixel_aligned(y, retained.scale_factor),
9805                "text instance {index} y was not aligned after layer composition: {y}"
9806            );
9807        }
9808    }
9809
9810    #[test]
9811    fn retained_ancestors_match_direct_for_child_layer_text_across_packet_boundaries() {
9812        let handle = FontHandle::new(28);
9813        let mut fonts = FontRegistry::new();
9814        fonts.insert(handle, load_test_font());
9815
9816        let shell_id = WidgetId::new(93);
9817        let child_id = WidgetId::new(94);
9818        let build_frame = |shell_cache_policy| {
9819            let shell_descriptor = SceneLayerDescriptor::new(
9820                SceneLayerId::from_widget(shell_id),
9821                shell_id,
9822                Rect::new(0.0, 0.0, 512.0, 84.0),
9823            )
9824            .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 84.0))
9825            .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 84.0))
9826            .with_cache_policy(shell_cache_policy);
9827
9828            let child_descriptor = SceneLayerDescriptor::new(
9829                SceneLayerId::from_widget(child_id),
9830                child_id,
9831                Rect::new(0.0, 0.0, 512.0, 84.0),
9832            )
9833            .with_content_bounds(Rect::new(0.0, 0.0, 512.0, 84.0))
9834            .with_paint_bounds(Rect::new(0.0, 0.0, 512.0, 84.0))
9835            .with_cache_policy(LayerCachePolicy::Direct);
9836
9837            let mut child_scene = Scene::new();
9838            child_scene.push(SceneCommand::FillRect {
9839                rect: Rect::new(0.0, 0.0, 512.0, 84.0),
9840                brush: Color::rgba(0.08, 0.09, 0.11, 1.0).into(),
9841            });
9842            child_scene.push(SceneCommand::DrawText(TextRun {
9843                rect: Rect::new(326.0, 22.0, 164.0, 28.0),
9844                text: "tab boundary sample".to_string(),
9845                style: TextStyle {
9846                    font: Some(handle),
9847                    ..TextStyle::new(Color::WHITE)
9848                },
9849            }));
9850
9851            let mut shell_scene = Scene::new();
9852            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9853                child_descriptor.clone(),
9854                child_scene,
9855            )));
9856
9857            let mut scene = Scene::new();
9858            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
9859                shell_descriptor.clone(),
9860                shell_scene,
9861            )));
9862
9863            SceneFrame {
9864                window_id: WindowId::new(93),
9865                viewport: Size::new(512.0, 84.0),
9866                surface_size: Size::new(512.0, 84.0),
9867                scale_factor: 1.0,
9868                dirty_regions: Vec::new(),
9869                layer_updates: vec![
9870                    SceneLayerUpdate::from_descriptor(
9871                        SceneLayerUpdateKind::Content,
9872                        shell_descriptor,
9873                    )
9874                    .with_damage(Rect::new(0.0, 0.0, 512.0, 84.0)),
9875                    SceneLayerUpdate::from_descriptor(
9876                        SceneLayerUpdateKind::Content,
9877                        child_descriptor,
9878                    )
9879                    .with_damage(Rect::new(0.0, 0.0, 512.0, 84.0)),
9880                ],
9881                scene,
9882                font_registry: Arc::new(fonts.clone()),
9883                image_registry: Arc::new(ImageRegistry::new()),
9884                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
9885            }
9886        };
9887
9888        let mut renderer = WgpuRenderer::default();
9889        let direct = build_frame(LayerCachePolicy::Direct);
9890        renderer.render(&direct).unwrap();
9891        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
9892
9893        let cached = build_frame(LayerCachePolicy::Cached);
9894        renderer.render(&cached).unwrap();
9895        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
9896
9897        assert_rgba_images_match(&direct_pixels, &cached_pixels);
9898    }
9899
9900    #[test]
9901    fn retained_packets_match_direct_for_theme_preview_style_cards() {
9902        let handle = FontHandle::new(151);
9903        let mut fonts = FontRegistry::new();
9904        fonts.insert(handle, load_test_font());
9905
9906        let widget_id = WidgetId::new(152);
9907        let build_frame = |window_id, cache_policy| {
9908            let descriptor = SceneLayerDescriptor::new(
9909                SceneLayerId::from_widget(widget_id),
9910                widget_id,
9911                Rect::new(0.0, 0.0, 640.0, 220.0),
9912            )
9913            .with_content_bounds(Rect::new(0.0, 0.0, 640.0, 220.0))
9914            .with_paint_bounds(Rect::new(0.0, 0.0, 640.0, 220.0))
9915            .with_cache_policy(cache_policy)
9916            .with_composition_mode(LayerCompositionMode::Scroll);
9917
9918            let mut layer_scene = Scene::new();
9919            layer_scene.push(SceneCommand::FillRect {
9920                rect: Rect::new(0.0, 0.0, 640.0, 220.0),
9921                brush: Color::rgba(0.94, 0.95, 0.98, 1.0).into(),
9922            });
9923
9924            let card_specs = [
9925                (
9926                    56.0,
9927                    Color::rgba(0.99, 0.99, 1.0, 1.0),
9928                    Color::rgba(0.19, 0.46, 0.91, 1.0),
9929                    Color::rgba(0.15, 0.73, 0.70, 1.0),
9930                    Color::rgba(0.10, 0.13, 0.19, 1.0),
9931                    Color::rgba(0.39, 0.45, 0.54, 1.0),
9932                    Color::rgba(0.82, 0.85, 0.91, 1.0),
9933                    "Light theme",
9934                ),
9935                (
9936                    344.0,
9937                    Color::rgba(0.14, 0.16, 0.21, 1.0),
9938                    Color::rgba(0.45, 0.60, 0.98, 1.0),
9939                    Color::rgba(0.96, 0.54, 0.31, 1.0),
9940                    Color::rgba(0.94, 0.95, 0.98, 1.0),
9941                    Color::rgba(0.68, 0.72, 0.80, 1.0),
9942                    Color::rgba(0.28, 0.31, 0.38, 1.0),
9943                    "Dark theme",
9944                ),
9945            ];
9946
9947            for (card_x, surface, accent, secondary, text_color, subtle_text, border, title) in
9948                card_specs
9949            {
9950                let card_rect = Rect::new(card_x, 24.0, 240.0, 172.0);
9951                layer_scene.push(SceneCommand::FillPath {
9952                    path: Path::rounded_rect(card_rect, 18.0),
9953                    brush: surface.into(),
9954                });
9955                layer_scene.push(SceneCommand::StrokePath {
9956                    path: Path::rounded_rect(card_rect, 18.0),
9957                    brush: border.into(),
9958                    stroke: StrokeStyle::new(1.0),
9959                });
9960                layer_scene.push(SceneCommand::DrawText(TextRun {
9961                    rect: Rect::new(card_x + 20.0, 44.0, 172.0, 24.0),
9962                    text: title.to_string(),
9963                    style: TextStyle {
9964                        font: Some(handle),
9965                        font_size: 18.0,
9966                        line_height: 22.0,
9967                        color: text_color,
9968                        ..Default::default()
9969                    },
9970                }));
9971                layer_scene.push(SceneCommand::DrawText(TextRun {
9972                    rect: Rect::new(card_x + 20.0, 76.0, 188.0, 20.0),
9973                    text: "Retained packets must match direct".to_string(),
9974                    style: TextStyle {
9975                        font: Some(handle),
9976                        font_size: 13.0,
9977                        line_height: 18.0,
9978                        color: subtle_text,
9979                        ..Default::default()
9980                    },
9981                }));
9982
9983                let swatch_colors = [Color::rgba(0.84, 0.87, 0.92, 1.0), accent, secondary];
9984                for (index, swatch_color) in swatch_colors.into_iter().enumerate() {
9985                    let swatch_rect =
9986                        Rect::new(card_x + 24.0 + (index as f32 * 72.0), 124.0, 60.0, 32.0);
9987                    layer_scene.push(SceneCommand::FillPath {
9988                        path: Path::rounded_rect(swatch_rect, 10.0),
9989                        brush: swatch_color.into(),
9990                    });
9991                    layer_scene.push(SceneCommand::StrokePath {
9992                        path: Path::rounded_rect(swatch_rect, 10.0),
9993                        brush: border.into(),
9994                        stroke: StrokeStyle::new(1.0),
9995                    });
9996                }
9997            }
9998
9999            let mut scene = Scene::new();
10000            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10001                descriptor.clone(),
10002                layer_scene,
10003            )));
10004
10005            SceneFrame {
10006                window_id,
10007                viewport: Size::new(640.0, 220.0),
10008                surface_size: Size::new(640.0, 220.0),
10009                scale_factor: 1.0,
10010                dirty_regions: Vec::new(),
10011                layer_updates: vec![
10012                    SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
10013                        .with_damage(Rect::new(0.0, 0.0, 640.0, 220.0)),
10014                ],
10015                scene,
10016                font_registry: Arc::new(fonts.clone()),
10017                image_registry: Arc::new(ImageRegistry::new()),
10018                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
10019            }
10020        };
10021
10022        let mut renderer = WgpuRenderer::default();
10023        let direct = build_frame(WindowId::new(152), LayerCachePolicy::Direct);
10024        renderer.render(&direct).unwrap();
10025        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
10026
10027        let cached = build_frame(WindowId::new(153), LayerCachePolicy::Cached);
10028        renderer.render(&cached).unwrap();
10029        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
10030
10031        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10032    }
10033
10034    #[test]
10035    fn retained_scroll_layer_matches_direct_at_fractional_packet_boundaries() {
10036        let widget_id = WidgetId::new(95);
10037        let build_frame = |window_id, cache_policy| {
10038            let descriptor = SceneLayerDescriptor::new(
10039                SceneLayerId::from_widget(widget_id),
10040                widget_id,
10041                Rect::new(0.0, -150.5, 420.0, 700.0),
10042            )
10043            .with_content_bounds(Rect::new(0.0, -150.5, 420.0, 700.0))
10044            .with_paint_bounds(Rect::new(0.0, -150.5, 420.0, 700.0))
10045            .with_cache_policy(cache_policy)
10046            .with_composition_mode(LayerCompositionMode::Scroll);
10047
10048            let mut layer_scene = Scene::new();
10049            layer_scene.push(SceneCommand::FillRect {
10050                rect: Rect::new(0.0, -150.5, 420.0, 700.0),
10051                brush: Color::WHITE.into(),
10052            });
10053            layer_scene.push(SceneCommand::FillRect {
10054                rect: Rect::new(32.0, 372.0, 340.0, 18.0),
10055                brush: Color::rgba(0.18, 0.24, 0.34, 1.0).into(),
10056            });
10057            layer_scene.push(SceneCommand::FillRect {
10058                rect: Rect::new(350.0, 356.0, 44.0, 58.0),
10059                brush: Color::rgba(0.12, 0.35, 0.78, 1.0).into(),
10060            });
10061            layer_scene.push(SceneCommand::FillRect {
10062                rect: Rect::new(334.0, 392.0, 64.0, 16.0),
10063                brush: Color::rgba(0.88, 0.52, 0.18, 1.0).into(),
10064            });
10065
10066            let mut scene = Scene::new();
10067            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10068                descriptor.clone(),
10069                layer_scene,
10070            )));
10071
10072            SceneFrame {
10073                window_id,
10074                viewport: Size::new(420.0, 240.0),
10075                surface_size: Size::new(420.0, 240.0),
10076                scale_factor: 1.0,
10077                dirty_regions: Vec::new(),
10078                layer_updates: vec![
10079                    SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
10080                        .with_damage(Rect::new(0.0, -150.5, 420.0, 700.0)),
10081                ],
10082                scene,
10083                font_registry: Arc::new(FontRegistry::new()),
10084                image_registry: Arc::new(ImageRegistry::new()),
10085                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
10086            }
10087        };
10088
10089        let mut renderer = WgpuRenderer::default();
10090        let direct = build_frame(WindowId::new(94), LayerCachePolicy::Direct);
10091        renderer.render(&direct).unwrap();
10092        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
10093
10094        let cached = build_frame(WindowId::new(95), LayerCachePolicy::Cached);
10095        renderer.render(&cached).unwrap();
10096        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
10097
10098        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10099    }
10100
10101    #[test]
10102    fn retained_scroll_layer_matches_direct_for_clipped_rows_across_packet_boundary() {
10103        let widget_id = WidgetId::new(96);
10104        let clip_rect = Rect::new(42.0, 628.0, 360.0, 220.0);
10105        let build_frame = |window_id, cache_policy| {
10106            let descriptor = SceneLayerDescriptor::new(
10107                SceneLayerId::from_widget(widget_id),
10108                widget_id,
10109                Rect::new(24.0, -478.0, 1232.0, 2046.0),
10110            )
10111            .with_content_bounds(Rect::new(24.0, -478.0, 1232.0, 2046.0))
10112            .with_paint_bounds(Rect::new(24.0, -478.0, 1232.0, 2046.0))
10113            .with_cache_policy(cache_policy)
10114            .with_composition_mode(LayerCompositionMode::Scroll);
10115
10116            let mut layer_scene = Scene::new();
10117            layer_scene.push(SceneCommand::FillRect {
10118                rect: Rect::new(24.0, -478.0, 1232.0, 2046.0),
10119                brush: Color::WHITE.into(),
10120            });
10121            layer_scene.push(SceneCommand::PushClip { rect: clip_rect });
10122            for (index, y) in [636.0, 668.0, 700.0, 732.0].into_iter().enumerate() {
10123                let brush = if index == 1 {
10124                    Color::rgba(0.79, 0.86, 0.98, 1.0)
10125                } else {
10126                    Color::rgba(0.90, 0.93, 0.97, 1.0)
10127                };
10128                layer_scene.push(SceneCommand::FillRect {
10129                    rect: Rect::new(42.0, y, 360.0, 28.0),
10130                    brush: brush.into(),
10131                });
10132                layer_scene.push(SceneCommand::FillRect {
10133                    rect: Rect::new(58.0, y + 8.0, 172.0, 12.0),
10134                    brush: Color::rgba(0.17, 0.21, 0.29, 1.0).into(),
10135                });
10136                layer_scene.push(SceneCommand::FillRect {
10137                    rect: Rect::new(248.0, y + 8.0, 96.0, 12.0),
10138                    brush: Color::rgba(0.41, 0.48, 0.58, 1.0).into(),
10139                });
10140            }
10141            layer_scene.push(SceneCommand::PopClip);
10142
10143            let mut scene = Scene::new();
10144            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10145                descriptor.clone(),
10146                layer_scene,
10147            )));
10148
10149            SceneFrame {
10150                window_id,
10151                viewport: Size::new(430.0, 900.0),
10152                surface_size: Size::new(430.0, 900.0),
10153                scale_factor: 1.0,
10154                dirty_regions: Vec::new(),
10155                layer_updates: vec![
10156                    SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
10157                        .with_damage(Rect::new(24.0, -478.0, 1232.0, 2046.0)),
10158                ],
10159                scene,
10160                font_registry: Arc::new(FontRegistry::new()),
10161                image_registry: Arc::new(ImageRegistry::new()),
10162                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
10163            }
10164        };
10165
10166        let mut renderer = WgpuRenderer::default();
10167        let direct = build_frame(WindowId::new(96), LayerCachePolicy::Direct);
10168        renderer.render(&direct).unwrap();
10169        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
10170
10171        let cached = build_frame(WindowId::new(97), LayerCachePolicy::Cached);
10172        renderer.render(&cached).unwrap();
10173        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
10174
10175        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10176    }
10177
10178    #[test]
10179    fn retained_scroll_layer_clips_direct_packet_after_child_layer_boundary() {
10180        let scroll_id = WidgetId::new(209);
10181        let child_id = WidgetId::new(210);
10182        let scroll_bounds = Rect::new(0.0, 0.0, 200.0, 160.0);
10183        let internal_clip = Rect::new(20.0, 24.0, 120.0, 80.0);
10184        let scroll_descriptor = SceneLayerDescriptor::new(
10185            SceneLayerId::from_widget(scroll_id),
10186            scroll_id,
10187            scroll_bounds,
10188        )
10189        .with_content_bounds(scroll_bounds)
10190        .with_paint_bounds(scroll_bounds)
10191        .with_composition_mode(LayerCompositionMode::Scroll);
10192        let child_descriptor = SceneLayerDescriptor::new(
10193            SceneLayerId::from_widget(child_id),
10194            child_id,
10195            Rect::new(32.0, 36.0, 48.0, 36.0),
10196        )
10197        .with_content_bounds(Rect::new(32.0, 36.0, 48.0, 36.0))
10198        .with_paint_bounds(Rect::new(32.0, 36.0, 48.0, 36.0));
10199
10200        let mut child_scene = Scene::new();
10201        child_scene.push(SceneCommand::FillRect {
10202            rect: Rect::new(32.0, 36.0, 48.0, 36.0),
10203            brush: Color::rgba(0.0, 0.0, 1.0, 1.0).into(),
10204        });
10205
10206        let mut scroll_scene = Scene::new();
10207        scroll_scene.push(SceneCommand::FillRect {
10208            rect: scroll_bounds,
10209            brush: Color::WHITE.into(),
10210        });
10211        scroll_scene.push(SceneCommand::PushClip {
10212            rect: internal_clip,
10213        });
10214        scroll_scene.push(SceneCommand::FillRect {
10215            rect: Rect::new(28.0, 36.0, 52.0, 20.0),
10216            brush: Color::rgba(0.90, 0.94, 0.98, 1.0).into(),
10217        });
10218        scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10219            child_descriptor.clone(),
10220            child_scene,
10221        )));
10222        scroll_scene.push(SceneCommand::FillRect {
10223            rect: Rect::new(28.0, 12.0, 96.0, 40.0),
10224            brush: Color::rgba(1.0, 0.0, 0.0, 1.0).into(),
10225        });
10226        scroll_scene.push(SceneCommand::PopClip);
10227
10228        let mut scene = Scene::new();
10229        scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10230            scroll_descriptor.clone(),
10231            scroll_scene,
10232        )));
10233
10234        let frame = SceneFrame {
10235            window_id: WindowId::new(209),
10236            viewport: Size::new(200.0, 160.0),
10237            surface_size: Size::new(200.0, 160.0),
10238            scale_factor: 1.0,
10239            dirty_regions: Vec::new(),
10240            layer_updates: vec![
10241                SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, scroll_descriptor)
10242                    .with_damage(scroll_bounds),
10243                SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, child_descriptor),
10244            ],
10245            scene,
10246            font_registry: Arc::new(FontRegistry::new()),
10247            image_registry: Arc::new(ImageRegistry::new()),
10248            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
10249        };
10250
10251        let mut renderer = WgpuRenderer::default();
10252        renderer.render(&frame).unwrap();
10253        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
10254
10255        assert_rgba_pixel_near(&pixels, 32, 18, [255, 255, 255, 255], 2);
10256        assert_rgba_pixel_near(&pixels, 32, 30, [255, 0, 0, 255], 2);
10257    }
10258
10259    #[test]
10260    fn cached_scroll_ancestor_matches_direct_for_clipped_child_layer_rows() {
10261        let shell_id = WidgetId::new(97);
10262        let child_id = WidgetId::new(98);
10263        let clip_rect = Rect::new(42.0, 628.0, 360.0, 220.0);
10264        let build_frame = |window_id, shell_cache_policy| {
10265            let shell_descriptor = SceneLayerDescriptor::new(
10266                SceneLayerId::from_widget(shell_id),
10267                shell_id,
10268                Rect::new(24.0, -478.0, 1232.0, 2046.0),
10269            )
10270            .with_content_bounds(Rect::new(24.0, -478.0, 1232.0, 2046.0))
10271            .with_paint_bounds(Rect::new(24.0, -478.0, 1232.0, 2046.0))
10272            .with_cache_policy(shell_cache_policy)
10273            .with_composition_mode(LayerCompositionMode::Scroll);
10274
10275            let child_descriptor = SceneLayerDescriptor::new(
10276                SceneLayerId::from_widget(child_id),
10277                child_id,
10278                Rect::new(41.5, 627.5, 361.0, 221.0),
10279            )
10280            .with_content_bounds(Rect::new(41.5, 627.5, 361.0, 221.0))
10281            .with_paint_bounds(Rect::new(41.5, 627.5, 361.0, 221.0))
10282            .with_cache_policy(LayerCachePolicy::Direct);
10283
10284            let mut child_scene = Scene::new();
10285            child_scene.push(SceneCommand::FillRect {
10286                rect: Rect::new(41.5, 627.5, 361.0, 221.0),
10287                brush: Color::WHITE.into(),
10288            });
10289            child_scene.push(SceneCommand::PushClip { rect: clip_rect });
10290            for (index, y) in [636.0, 668.0, 700.0, 732.0].into_iter().enumerate() {
10291                let brush = if index == 1 {
10292                    Color::rgba(0.79, 0.86, 0.98, 1.0)
10293                } else {
10294                    Color::rgba(0.90, 0.93, 0.97, 1.0)
10295                };
10296                child_scene.push(SceneCommand::FillRect {
10297                    rect: Rect::new(42.0, y, 360.0, 28.0),
10298                    brush: brush.into(),
10299                });
10300                child_scene.push(SceneCommand::FillRect {
10301                    rect: Rect::new(58.0, y + 8.0, 172.0, 12.0),
10302                    brush: Color::rgba(0.17, 0.21, 0.29, 1.0).into(),
10303                });
10304                child_scene.push(SceneCommand::FillRect {
10305                    rect: Rect::new(248.0, y + 8.0, 96.0, 12.0),
10306                    brush: Color::rgba(0.41, 0.48, 0.58, 1.0).into(),
10307                });
10308            }
10309            child_scene.push(SceneCommand::PopClip);
10310
10311            let mut shell_scene = Scene::new();
10312            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10313                child_descriptor.clone(),
10314                child_scene,
10315            )));
10316
10317            let mut scene = Scene::new();
10318            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10319                shell_descriptor.clone(),
10320                shell_scene,
10321            )));
10322
10323            SceneFrame {
10324                window_id,
10325                viewport: Size::new(430.0, 900.0),
10326                surface_size: Size::new(430.0, 900.0),
10327                scale_factor: 1.0,
10328                dirty_regions: Vec::new(),
10329                layer_updates: vec![
10330                    SceneLayerUpdate::from_descriptor(
10331                        SceneLayerUpdateKind::Content,
10332                        shell_descriptor,
10333                    )
10334                    .with_damage(Rect::new(24.0, -478.0, 1232.0, 2046.0)),
10335                    SceneLayerUpdate::from_descriptor(
10336                        SceneLayerUpdateKind::Content,
10337                        child_descriptor,
10338                    )
10339                    .with_damage(Rect::new(41.5, 627.5, 361.0, 221.0)),
10340                ],
10341                scene,
10342                font_registry: Arc::new(FontRegistry::new()),
10343                image_registry: Arc::new(ImageRegistry::new()),
10344                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
10345            }
10346        };
10347
10348        let mut renderer = WgpuRenderer::default();
10349        let direct = build_frame(WindowId::new(98), LayerCachePolicy::Direct);
10350        renderer.render(&direct).unwrap();
10351        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
10352
10353        let cached = build_frame(WindowId::new(99), LayerCachePolicy::Cached);
10354        renderer.render(&cached).unwrap();
10355        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
10356
10357        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10358    }
10359
10360    #[test]
10361    fn cached_scroll_ancestor_clips_fully_outside_child_layer() {
10362        let shell_id = WidgetId::new(100);
10363        let child_id = WidgetId::new(101);
10364        let clip_rect = Rect::new(42.0, 628.0, 360.0, 220.0);
10365        let build_frame = |window_id, shell_cache_policy| {
10366            let shell_descriptor = SceneLayerDescriptor::new(
10367                SceneLayerId::from_widget(shell_id),
10368                shell_id,
10369                Rect::new(24.0, -478.0, 1232.0, 2046.0),
10370            )
10371            .with_content_bounds(Rect::new(24.0, -478.0, 1232.0, 2046.0))
10372            .with_paint_bounds(Rect::new(24.0, -478.0, 1232.0, 2046.0))
10373            .with_cache_policy(shell_cache_policy)
10374            .with_composition_mode(LayerCompositionMode::Scroll);
10375
10376            let child_descriptor = SceneLayerDescriptor::new(
10377                SceneLayerId::from_widget(child_id),
10378                child_id,
10379                Rect::new(96.0, 904.0, 180.0, 96.0),
10380            )
10381            .with_content_bounds(Rect::new(96.0, 904.0, 180.0, 96.0))
10382            .with_paint_bounds(Rect::new(96.0, 904.0, 180.0, 96.0))
10383            .with_cache_policy(LayerCachePolicy::Direct);
10384
10385            let mut child_scene = Scene::new();
10386            child_scene.push(SceneCommand::FillRect {
10387                rect: Rect::new(96.0, 904.0, 180.0, 96.0),
10388                brush: Color::rgba(0.82, 0.16, 0.18, 1.0).into(),
10389            });
10390
10391            let mut shell_scene = Scene::new();
10392            shell_scene.push(SceneCommand::FillRect {
10393                rect: Rect::new(24.0, -478.0, 1232.0, 2046.0),
10394                brush: Color::WHITE.into(),
10395            });
10396            shell_scene.push(SceneCommand::PushClip { rect: clip_rect });
10397            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10398                child_descriptor.clone(),
10399                child_scene,
10400            )));
10401            shell_scene.push(SceneCommand::PopClip);
10402
10403            let mut scene = Scene::new();
10404            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10405                shell_descriptor.clone(),
10406                shell_scene,
10407            )));
10408
10409            SceneFrame {
10410                window_id,
10411                viewport: Size::new(430.0, 900.0),
10412                surface_size: Size::new(430.0, 900.0),
10413                scale_factor: 1.0,
10414                dirty_regions: Vec::new(),
10415                layer_updates: vec![
10416                    SceneLayerUpdate::from_descriptor(
10417                        SceneLayerUpdateKind::Content,
10418                        shell_descriptor,
10419                    )
10420                    .with_damage(Rect::new(24.0, -478.0, 1232.0, 2046.0)),
10421                    SceneLayerUpdate::from_descriptor(
10422                        SceneLayerUpdateKind::Content,
10423                        child_descriptor,
10424                    )
10425                    .with_damage(Rect::new(96.0, 904.0, 180.0, 96.0)),
10426                ],
10427                scene,
10428                font_registry: Arc::new(FontRegistry::new()),
10429                image_registry: Arc::new(ImageRegistry::new()),
10430                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
10431            }
10432        };
10433
10434        let mut renderer = WgpuRenderer::default();
10435        let direct = build_frame(WindowId::new(100), LayerCachePolicy::Direct);
10436        renderer.render(&direct).unwrap();
10437        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
10438
10439        let cached = build_frame(WindowId::new(101), LayerCachePolicy::Cached);
10440        renderer.render(&cached).unwrap();
10441        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
10442
10443        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10444    }
10445
10446    #[test]
10447    fn cached_scroll_ancestor_matches_direct_after_child_translation() {
10448        let shell_id = WidgetId::new(102);
10449        let scroll_id = WidgetId::new(103);
10450        let content_id = WidgetId::new(104);
10451        let first_id = WidgetId::new(105);
10452        let second_id = WidgetId::new(106);
10453        let third_id = WidgetId::new(107);
10454        let clip_rect = Rect::new(42.0, 60.0, 360.0, 220.0);
10455
10456        let content_descriptor = |y: f32| {
10457            SceneLayerDescriptor::new(
10458                SceneLayerId::from_widget(content_id),
10459                content_id,
10460                Rect::new(42.0, y, 360.0, 360.0),
10461            )
10462            .with_content_bounds(Rect::new(42.0, y, 360.0, 360.0))
10463            .with_paint_bounds(Rect::new(42.0, y, 360.0, 360.0))
10464            .with_cache_policy(LayerCachePolicy::Direct)
10465        };
10466
10467        let child_layer = |id: WidgetId, y: f32, brush: Color| {
10468            let mut scene = Scene::new();
10469            scene.push(SceneCommand::FillRect {
10470                rect: Rect::new(42.0, y, 360.0, 96.0),
10471                brush: brush.into(),
10472            });
10473            SceneLayer::from_descriptor(
10474                SceneLayerDescriptor::new(
10475                    SceneLayerId::from_widget(id),
10476                    id,
10477                    Rect::new(42.0, y, 360.0, 96.0),
10478                )
10479                .with_content_bounds(Rect::new(42.0, y, 360.0, 96.0))
10480                .with_paint_bounds(Rect::new(42.0, y, 360.0, 96.0))
10481                .with_cache_policy(LayerCachePolicy::Direct),
10482                scene,
10483            )
10484        };
10485
10486        let build_content_scene = |y: f32| {
10487            let mut scene = Scene::new();
10488            scene.push(SceneCommand::Layer(child_layer(
10489                first_id,
10490                y,
10491                Color::rgba(0.82, 0.36, 0.18, 1.0),
10492            )));
10493            scene.push(SceneCommand::Layer(child_layer(
10494                second_id,
10495                y + 120.0,
10496                Color::rgba(0.18, 0.54, 0.82, 1.0),
10497            )));
10498            scene.push(SceneCommand::Layer(child_layer(
10499                third_id,
10500                y + 240.0,
10501                Color::rgba(0.24, 0.72, 0.36, 1.0),
10502            )));
10503            scene
10504        };
10505
10506        let build_frame = |window_id, scroll_cache_policy, content_y: f32, update_kind| {
10507            let shell_descriptor = SceneLayerDescriptor::new(
10508                SceneLayerId::from_widget(shell_id),
10509                shell_id,
10510                Rect::new(0.0, 0.0, 430.0, 360.0),
10511            )
10512            .with_content_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
10513            .with_paint_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
10514            .with_cache_policy(LayerCachePolicy::Direct);
10515
10516            let scroll_descriptor = SceneLayerDescriptor::new(
10517                SceneLayerId::from_widget(scroll_id),
10518                scroll_id,
10519                Rect::new(24.0, 24.0, 382.0, 292.0),
10520            )
10521            .with_content_bounds(Rect::new(24.0, 24.0, 382.0, 292.0))
10522            .with_paint_bounds(Rect::new(24.0, 24.0, 382.0, 292.0))
10523            .with_cache_policy(scroll_cache_policy)
10524            .with_composition_mode(LayerCompositionMode::Scroll);
10525
10526            let mut scroll_scene = Scene::new();
10527            scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10528                content_descriptor(content_y),
10529                build_content_scene(content_y),
10530            )));
10531
10532            let mut shell_scene = Scene::new();
10533            shell_scene.push(SceneCommand::FillRect {
10534                rect: Rect::new(0.0, 0.0, 430.0, 360.0),
10535                brush: Color::rgba(0.95, 0.97, 0.99, 1.0).into(),
10536            });
10537            shell_scene.push(SceneCommand::PushClip { rect: clip_rect });
10538            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10539                scroll_descriptor.clone(),
10540                scroll_scene,
10541            )));
10542            shell_scene.push(SceneCommand::PopClip);
10543
10544            let mut scene = Scene::new();
10545            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10546                shell_descriptor.clone(),
10547                shell_scene,
10548            )));
10549
10550            let update = if update_kind == SceneLayerUpdateKind::Content {
10551                SceneLayerUpdate::from_descriptor(update_kind, content_descriptor(content_y))
10552                    .with_damage(Rect::new(42.0, content_y, 360.0, 360.0))
10553            } else {
10554                SceneLayerUpdate::from_descriptor(update_kind, content_descriptor(content_y))
10555                    .with_damage(Rect::new(42.0, 0.0, 360.0, 432.0))
10556            };
10557
10558            SceneFrame {
10559                window_id,
10560                viewport: Size::new(430.0, 360.0),
10561                surface_size: Size::new(430.0, 360.0),
10562                scale_factor: 1.0,
10563                dirty_regions: Vec::new(),
10564                layer_updates: vec![update],
10565                scene,
10566                font_registry: Arc::new(FontRegistry::new()),
10567                image_registry: Arc::new(ImageRegistry::new()),
10568                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
10569            }
10570        };
10571
10572        let mut renderer = WgpuRenderer::default();
10573
10574        let direct_initial = build_frame(
10575            WindowId::new(110),
10576            LayerCachePolicy::Direct,
10577            0.0,
10578            SceneLayerUpdateKind::Content,
10579        );
10580        renderer.render(&direct_initial).unwrap();
10581        let direct_updated = build_frame(
10582            WindowId::new(110),
10583            LayerCachePolicy::Direct,
10584            72.0,
10585            SceneLayerUpdateKind::Transform,
10586        );
10587        renderer.render(&direct_updated).unwrap();
10588        let direct_pixels = renderer
10589            .capture_last_frame_rgba(direct_updated.window_id)
10590            .unwrap();
10591
10592        let cached_initial = build_frame(
10593            WindowId::new(111),
10594            LayerCachePolicy::Cached,
10595            0.0,
10596            SceneLayerUpdateKind::Content,
10597        );
10598        renderer.render(&cached_initial).unwrap();
10599        let cached_updated = build_frame(
10600            WindowId::new(111),
10601            LayerCachePolicy::Cached,
10602            72.0,
10603            SceneLayerUpdateKind::Transform,
10604        );
10605        renderer.render(&cached_updated).unwrap();
10606        let cached_pixels = renderer
10607            .capture_last_frame_rgba(cached_updated.window_id)
10608            .unwrap();
10609
10610        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10611    }
10612
10613    #[test]
10614    fn cached_scroll_internal_clip_matches_direct_after_child_translation() {
10615        let shell_id = WidgetId::new(108);
10616        let scroll_id = WidgetId::new(109);
10617        let content_id = WidgetId::new(110);
10618        let first_id = WidgetId::new(111);
10619        let second_id = WidgetId::new(112);
10620        let third_id = WidgetId::new(113);
10621        let clip_rect = Rect::new(42.0, 60.0, 360.0, 220.0);
10622
10623        let content_descriptor = |y: f32| {
10624            SceneLayerDescriptor::new(
10625                SceneLayerId::from_widget(content_id),
10626                content_id,
10627                Rect::new(42.0, y, 360.0, 360.0),
10628            )
10629            .with_content_bounds(Rect::new(42.0, y, 360.0, 360.0))
10630            .with_paint_bounds(Rect::new(42.0, y, 360.0, 360.0))
10631            .with_cache_policy(LayerCachePolicy::Direct)
10632        };
10633
10634        let child_layer = |id: WidgetId, y: f32, brush: Color| {
10635            let mut scene = Scene::new();
10636            scene.push(SceneCommand::FillRect {
10637                rect: Rect::new(42.0, y, 360.0, 96.0),
10638                brush: brush.into(),
10639            });
10640            SceneLayer::from_descriptor(
10641                SceneLayerDescriptor::new(
10642                    SceneLayerId::from_widget(id),
10643                    id,
10644                    Rect::new(42.0, y, 360.0, 96.0),
10645                )
10646                .with_content_bounds(Rect::new(42.0, y, 360.0, 96.0))
10647                .with_paint_bounds(Rect::new(42.0, y, 360.0, 96.0))
10648                .with_cache_policy(LayerCachePolicy::Direct),
10649                scene,
10650            )
10651        };
10652
10653        let build_content_scene = |y: f32| {
10654            let mut scene = Scene::new();
10655            scene.push(SceneCommand::Layer(child_layer(
10656                first_id,
10657                y,
10658                Color::rgba(0.82, 0.36, 0.18, 1.0),
10659            )));
10660            scene.push(SceneCommand::Layer(child_layer(
10661                second_id,
10662                y + 120.0,
10663                Color::rgba(0.18, 0.54, 0.82, 1.0),
10664            )));
10665            scene.push(SceneCommand::Layer(child_layer(
10666                third_id,
10667                y + 240.0,
10668                Color::rgba(0.24, 0.72, 0.36, 1.0),
10669            )));
10670            scene
10671        };
10672
10673        let build_frame = |window_id, scroll_cache_policy, content_y: f32, update_kind| {
10674            let shell_descriptor = SceneLayerDescriptor::new(
10675                SceneLayerId::from_widget(shell_id),
10676                shell_id,
10677                Rect::new(0.0, 0.0, 430.0, 360.0),
10678            )
10679            .with_content_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
10680            .with_paint_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
10681            .with_cache_policy(LayerCachePolicy::Direct);
10682
10683            let scroll_descriptor = SceneLayerDescriptor::new(
10684                SceneLayerId::from_widget(scroll_id),
10685                scroll_id,
10686                Rect::new(24.0, 24.0, 382.0, 292.0),
10687            )
10688            .with_content_bounds(Rect::new(24.0, 24.0, 382.0, 292.0))
10689            .with_paint_bounds(Rect::new(24.0, 24.0, 382.0, 292.0))
10690            .with_cache_policy(scroll_cache_policy)
10691            .with_composition_mode(LayerCompositionMode::Scroll);
10692
10693            let mut scroll_scene = Scene::new();
10694            scroll_scene.push(SceneCommand::PushClip { rect: clip_rect });
10695            scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10696                content_descriptor(content_y),
10697                build_content_scene(content_y),
10698            )));
10699            scroll_scene.push(SceneCommand::PopClip);
10700
10701            let mut shell_scene = Scene::new();
10702            shell_scene.push(SceneCommand::FillRect {
10703                rect: Rect::new(0.0, 0.0, 430.0, 360.0),
10704                brush: Color::rgba(0.95, 0.97, 0.99, 1.0).into(),
10705            });
10706            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10707                scroll_descriptor.clone(),
10708                scroll_scene,
10709            )));
10710
10711            let mut scene = Scene::new();
10712            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10713                shell_descriptor.clone(),
10714                shell_scene,
10715            )));
10716
10717            let update = if update_kind == SceneLayerUpdateKind::Content {
10718                SceneLayerUpdate::from_descriptor(update_kind, content_descriptor(content_y))
10719                    .with_damage(Rect::new(42.0, content_y, 360.0, 360.0))
10720            } else {
10721                SceneLayerUpdate::from_descriptor(update_kind, content_descriptor(content_y))
10722                    .with_damage(Rect::new(42.0, 0.0, 360.0, 432.0))
10723            };
10724
10725            SceneFrame {
10726                window_id,
10727                viewport: Size::new(430.0, 360.0),
10728                surface_size: Size::new(430.0, 360.0),
10729                scale_factor: 1.0,
10730                dirty_regions: Vec::new(),
10731                layer_updates: vec![update],
10732                scene,
10733                font_registry: Arc::new(FontRegistry::new()),
10734                image_registry: Arc::new(ImageRegistry::new()),
10735                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
10736            }
10737        };
10738
10739        let mut renderer = WgpuRenderer::default();
10740
10741        let direct_initial = build_frame(
10742            WindowId::new(112),
10743            LayerCachePolicy::Direct,
10744            0.0,
10745            SceneLayerUpdateKind::Content,
10746        );
10747        renderer.render(&direct_initial).unwrap();
10748        let direct_updated = build_frame(
10749            WindowId::new(112),
10750            LayerCachePolicy::Direct,
10751            72.0,
10752            SceneLayerUpdateKind::Transform,
10753        );
10754        renderer.render(&direct_updated).unwrap();
10755        let direct_pixels = renderer
10756            .capture_last_frame_rgba(direct_updated.window_id)
10757            .unwrap();
10758
10759        let cached_initial = build_frame(
10760            WindowId::new(113),
10761            LayerCachePolicy::Cached,
10762            0.0,
10763            SceneLayerUpdateKind::Content,
10764        );
10765        renderer.render(&cached_initial).unwrap();
10766        let cached_updated = build_frame(
10767            WindowId::new(113),
10768            LayerCachePolicy::Cached,
10769            72.0,
10770            SceneLayerUpdateKind::Transform,
10771        );
10772        renderer.render(&cached_updated).unwrap();
10773        let cached_pixels = renderer
10774            .capture_last_frame_rgba(cached_updated.window_id)
10775            .unwrap();
10776
10777        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10778    }
10779
10780    #[test]
10781    fn cached_scroll_translucent_auto_child_matches_direct_after_translation() {
10782        let mut renderer = WgpuRenderer::default();
10783
10784        let direct_initial = build_translucent_scroll_child_frame(
10785            WindowId::new(214),
10786            LayerCachePolicy::Direct,
10787            LayerCachePolicy::Direct,
10788            60.0,
10789            SceneLayerUpdateKind::Content,
10790        );
10791        renderer.render(&direct_initial).unwrap();
10792        let direct_updated = build_translucent_scroll_child_frame(
10793            WindowId::new(214),
10794            LayerCachePolicy::Direct,
10795            LayerCachePolicy::Direct,
10796            132.0,
10797            SceneLayerUpdateKind::Transform,
10798        );
10799        renderer.render(&direct_updated).unwrap();
10800        let direct_pixels = renderer
10801            .capture_last_frame_rgba(direct_updated.window_id)
10802            .unwrap();
10803
10804        let cached_initial = build_translucent_scroll_child_frame(
10805            WindowId::new(215),
10806            LayerCachePolicy::Cached,
10807            LayerCachePolicy::Auto,
10808            60.0,
10809            SceneLayerUpdateKind::Content,
10810        );
10811        renderer.render(&cached_initial).unwrap();
10812        let cached_updated = build_translucent_scroll_child_frame(
10813            WindowId::new(215),
10814            LayerCachePolicy::Cached,
10815            LayerCachePolicy::Auto,
10816            132.0,
10817            SceneLayerUpdateKind::Transform,
10818        );
10819        renderer.render(&cached_updated).unwrap();
10820        let cached_pixels = renderer
10821            .capture_last_frame_rgba(cached_updated.window_id)
10822            .unwrap();
10823
10824        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10825    }
10826
10827    #[test]
10828    fn cached_scroll_translucent_direct_child_matches_direct_after_translation() {
10829        let mut renderer = WgpuRenderer::default();
10830
10831        let direct_initial = build_translucent_scroll_child_frame(
10832            WindowId::new(216),
10833            LayerCachePolicy::Direct,
10834            LayerCachePolicy::Direct,
10835            60.0,
10836            SceneLayerUpdateKind::Content,
10837        );
10838        renderer.render(&direct_initial).unwrap();
10839        let direct_updated = build_translucent_scroll_child_frame(
10840            WindowId::new(216),
10841            LayerCachePolicy::Direct,
10842            LayerCachePolicy::Direct,
10843            132.0,
10844            SceneLayerUpdateKind::Transform,
10845        );
10846        renderer.render(&direct_updated).unwrap();
10847        let direct_pixels = renderer
10848            .capture_last_frame_rgba(direct_updated.window_id)
10849            .unwrap();
10850
10851        let cached_initial = build_translucent_scroll_child_frame(
10852            WindowId::new(217),
10853            LayerCachePolicy::Cached,
10854            LayerCachePolicy::Direct,
10855            60.0,
10856            SceneLayerUpdateKind::Content,
10857        );
10858        renderer.render(&cached_initial).unwrap();
10859        let cached_updated = build_translucent_scroll_child_frame(
10860            WindowId::new(217),
10861            LayerCachePolicy::Cached,
10862            LayerCachePolicy::Direct,
10863            132.0,
10864            SceneLayerUpdateKind::Transform,
10865        );
10866        renderer.render(&cached_updated).unwrap();
10867        let cached_pixels = renderer
10868            .capture_last_frame_rgba(cached_updated.window_id)
10869            .unwrap();
10870
10871        assert_rgba_images_match(&direct_pixels, &cached_pixels);
10872    }
10873
10874    #[test]
10875    fn cached_scroll_internal_clip_image_matches_direct_after_child_translation() {
10876        let shell_id = WidgetId::new(114);
10877        let scroll_id = WidgetId::new(115);
10878        let content_id = WidgetId::new(116);
10879        let image_layer_id = WidgetId::new(117);
10880        let filler_id = WidgetId::new(118);
10881        let image_handle = ImageHandle::new(41);
10882        let clip_rect = Rect::new(42.0, 60.0, 360.0, 220.0);
10883
10884        let mut images = ImageRegistry::new();
10885        images.insert(
10886            image_handle,
10887            RegisteredImage::from_rgba8(
10888                2,
10889                2,
10890                vec![
10891                    220, 232, 246, 255, 64, 156, 232, 255, 64, 156, 232, 255, 255, 175, 64, 255,
10892                ],
10893            )
10894            .unwrap(),
10895        );
10896        let images = Arc::new(images);
10897
10898        let content_descriptor = |y: f32| {
10899            SceneLayerDescriptor::new(
10900                SceneLayerId::from_widget(content_id),
10901                content_id,
10902                Rect::new(42.0, y, 360.0, 360.0),
10903            )
10904            .with_content_bounds(Rect::new(42.0, y, 360.0, 360.0))
10905            .with_paint_bounds(Rect::new(42.0, y, 360.0, 360.0))
10906            .with_cache_policy(LayerCachePolicy::Direct)
10907        };
10908
10909        let image_layer = |y: f32| {
10910            let mut scene = Scene::new();
10911            scene.push(SceneCommand::DrawImage {
10912                rect: Rect::new(42.0, y, 220.0, 220.0),
10913                source: ImageSource::new(image_handle),
10914            });
10915            SceneLayer::from_descriptor(
10916                SceneLayerDescriptor::new(
10917                    SceneLayerId::from_widget(image_layer_id),
10918                    image_layer_id,
10919                    Rect::new(42.0, y, 220.0, 220.0),
10920                )
10921                .with_content_bounds(Rect::new(42.0, y, 220.0, 220.0))
10922                .with_paint_bounds(Rect::new(42.0, y, 220.0, 220.0))
10923                .with_cache_policy(LayerCachePolicy::Direct),
10924                scene,
10925            )
10926        };
10927
10928        let filler_layer = |y: f32| {
10929            let mut scene = Scene::new();
10930            scene.push(SceneCommand::FillRect {
10931                rect: Rect::new(42.0, y, 360.0, 96.0),
10932                brush: Color::rgba(0.24, 0.72, 0.36, 1.0).into(),
10933            });
10934            SceneLayer::from_descriptor(
10935                SceneLayerDescriptor::new(
10936                    SceneLayerId::from_widget(filler_id),
10937                    filler_id,
10938                    Rect::new(42.0, y, 360.0, 96.0),
10939                )
10940                .with_content_bounds(Rect::new(42.0, y, 360.0, 96.0))
10941                .with_paint_bounds(Rect::new(42.0, y, 360.0, 96.0))
10942                .with_cache_policy(LayerCachePolicy::Direct),
10943                scene,
10944            )
10945        };
10946
10947        let build_content_scene = |y: f32| {
10948            let mut scene = Scene::new();
10949            scene.push(SceneCommand::Layer(image_layer(y)));
10950            scene.push(SceneCommand::Layer(filler_layer(y + 240.0)));
10951            scene
10952        };
10953
10954        let build_frame = |window_id, scroll_cache_policy, content_y: f32, update_kind| {
10955            let shell_descriptor = SceneLayerDescriptor::new(
10956                SceneLayerId::from_widget(shell_id),
10957                shell_id,
10958                Rect::new(0.0, 0.0, 430.0, 360.0),
10959            )
10960            .with_content_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
10961            .with_paint_bounds(Rect::new(0.0, 0.0, 430.0, 360.0))
10962            .with_cache_policy(LayerCachePolicy::Direct);
10963
10964            let scroll_descriptor = SceneLayerDescriptor::new(
10965                SceneLayerId::from_widget(scroll_id),
10966                scroll_id,
10967                Rect::new(24.0, 24.0, 382.0, 292.0),
10968            )
10969            .with_content_bounds(Rect::new(24.0, 24.0, 382.0, 292.0))
10970            .with_paint_bounds(Rect::new(24.0, 24.0, 382.0, 292.0))
10971            .with_cache_policy(scroll_cache_policy)
10972            .with_composition_mode(LayerCompositionMode::Scroll);
10973
10974            let mut scroll_scene = Scene::new();
10975            scroll_scene.push(SceneCommand::PushClip { rect: clip_rect });
10976            scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10977                content_descriptor(content_y),
10978                build_content_scene(content_y),
10979            )));
10980            scroll_scene.push(SceneCommand::PopClip);
10981
10982            let mut shell_scene = Scene::new();
10983            shell_scene.push(SceneCommand::FillRect {
10984                rect: Rect::new(0.0, 0.0, 430.0, 360.0),
10985                brush: Color::rgba(0.95, 0.97, 0.99, 1.0).into(),
10986            });
10987            shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10988                scroll_descriptor.clone(),
10989                scroll_scene,
10990            )));
10991
10992            let mut scene = Scene::new();
10993            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
10994                shell_descriptor.clone(),
10995                shell_scene,
10996            )));
10997
10998            let update = if update_kind == SceneLayerUpdateKind::Content {
10999                SceneLayerUpdate::from_descriptor(update_kind, content_descriptor(content_y))
11000                    .with_damage(Rect::new(42.0, content_y, 360.0, 360.0))
11001            } else {
11002                SceneLayerUpdate::from_descriptor(update_kind, content_descriptor(content_y))
11003                    .with_damage(Rect::new(42.0, 0.0, 360.0, 460.0))
11004            };
11005
11006            SceneFrame {
11007                window_id,
11008                viewport: Size::new(430.0, 360.0),
11009                surface_size: Size::new(430.0, 360.0),
11010                scale_factor: 1.0,
11011                dirty_regions: Vec::new(),
11012                layer_updates: vec![update],
11013                scene,
11014                font_registry: Arc::new(FontRegistry::new()),
11015                image_registry: Arc::clone(&images),
11016                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
11017            }
11018        };
11019
11020        let mut renderer = WgpuRenderer::default();
11021
11022        let direct_initial = build_frame(
11023            WindowId::new(114),
11024            LayerCachePolicy::Direct,
11025            0.0,
11026            SceneLayerUpdateKind::Content,
11027        );
11028        renderer.render(&direct_initial).unwrap();
11029        let direct_updated = build_frame(
11030            WindowId::new(114),
11031            LayerCachePolicy::Direct,
11032            72.0,
11033            SceneLayerUpdateKind::Transform,
11034        );
11035        renderer.render(&direct_updated).unwrap();
11036        let direct_pixels = renderer
11037            .capture_last_frame_rgba(direct_updated.window_id)
11038            .unwrap();
11039
11040        let cached_initial = build_frame(
11041            WindowId::new(115),
11042            LayerCachePolicy::Cached,
11043            0.0,
11044            SceneLayerUpdateKind::Content,
11045        );
11046        renderer.render(&cached_initial).unwrap();
11047        let cached_updated = build_frame(
11048            WindowId::new(115),
11049            LayerCachePolicy::Cached,
11050            72.0,
11051            SceneLayerUpdateKind::Transform,
11052        );
11053        renderer.render(&cached_updated).unwrap();
11054        let cached_pixels = renderer
11055            .capture_last_frame_rgba(cached_updated.window_id)
11056            .unwrap();
11057
11058        assert_rgba_images_match(&direct_pixels, &cached_pixels);
11059    }
11060
11061    #[test]
11062    fn nested_cached_scroll_image_outside_parent_bounds_matches_direct_render() {
11063        let shell_id = WidgetId::new(119);
11064        let outer_scroll_id = WidgetId::new(120);
11065        let inner_scroll_id = WidgetId::new(121);
11066        let image_layer_id = WidgetId::new(122);
11067        let image_handle = ImageHandle::new(42);
11068
11069        let mut images = ImageRegistry::new();
11070        images.insert(
11071            image_handle,
11072            RegisteredImage::from_rgba8(
11073                2,
11074                2,
11075                vec![
11076                    220, 232, 246, 255, 64, 156, 232, 255, 64, 156, 232, 255, 255, 175, 64, 255,
11077                ],
11078            )
11079            .unwrap(),
11080        );
11081        let images = Arc::new(images);
11082
11083        let build_frame = |window_id, inner_cache_policy| {
11084            let shell_descriptor = SceneLayerDescriptor::new(
11085                SceneLayerId::from_widget(shell_id),
11086                shell_id,
11087                Rect::new(0.0, 0.0, 1280.0, 720.0),
11088            )
11089            .with_content_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11090            .with_paint_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11091            .with_cache_policy(LayerCachePolicy::Direct);
11092
11093            let outer_scroll_descriptor = SceneLayerDescriptor::new(
11094                SceneLayerId::from_widget(outer_scroll_id),
11095                outer_scroll_id,
11096                Rect::new(320.0, 28.0, 428.0, 336.0),
11097            )
11098            .with_content_bounds(Rect::new(320.0, 28.0, 428.0, 336.0))
11099            .with_paint_bounds(Rect::new(320.0, 28.0, 428.0, 336.0))
11100            .with_cache_policy(LayerCachePolicy::Direct)
11101            .with_composition_mode(LayerCompositionMode::Scroll);
11102
11103            let inner_scroll_descriptor = SceneLayerDescriptor::new(
11104                SceneLayerId::from_widget(inner_scroll_id),
11105                inner_scroll_id,
11106                Rect::new(321.0, 60.0, 426.0, 303.0),
11107            )
11108            .with_content_bounds(Rect::new(321.0, 60.0, 426.0, 303.0))
11109            .with_paint_bounds(Rect::new(321.0, 60.0, 426.0, 303.0))
11110            .with_cache_policy(inner_cache_policy)
11111            .with_composition_mode(LayerCompositionMode::Scroll)
11112            .with_is_stack_surface(true);
11113
11114            let mut image_scene = Scene::new();
11115            image_scene.push(SceneCommand::DrawImage {
11116                rect: Rect::new(363.0, 376.0, 220.0, 220.0),
11117                source: ImageSource::new(image_handle),
11118            });
11119            let image_layer = SceneLayer::from_descriptor(
11120                SceneLayerDescriptor::new(
11121                    SceneLayerId::from_widget(image_layer_id),
11122                    image_layer_id,
11123                    Rect::new(363.0, 376.0, 220.0, 220.0),
11124                )
11125                .with_content_bounds(Rect::new(363.0, 376.0, 220.0, 220.0))
11126                .with_paint_bounds(Rect::new(363.0, 376.0, 220.0, 220.0))
11127                .with_cache_policy(LayerCachePolicy::Direct),
11128                image_scene,
11129            );
11130
11131            let mut inner_scroll_scene = Scene::new();
11132            inner_scroll_scene.push(SceneCommand::FillRect {
11133                rect: Rect::new(321.0, 60.0, 426.0, 303.0),
11134                brush: Color::rgba(0.96, 0.97, 0.99, 1.0).into(),
11135            });
11136            inner_scroll_scene.push(SceneCommand::Layer(image_layer));
11137
11138            let mut outer_scroll_scene = Scene::new();
11139            outer_scroll_scene.push(SceneCommand::FillRect {
11140                rect: Rect::new(320.0, 28.0, 428.0, 336.0),
11141                brush: Color::rgba(0.96, 0.97, 0.99, 1.0).into(),
11142            });
11143            outer_scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11144                inner_scroll_descriptor,
11145                inner_scroll_scene,
11146            )));
11147
11148            let mut scene = Scene::new();
11149            scene.push(SceneCommand::FillRect {
11150                rect: Rect::new(0.0, 0.0, 1280.0, 720.0),
11151                brush: Color::rgba(0.92, 0.94, 0.97, 1.0).into(),
11152            });
11153            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11154                shell_descriptor,
11155                {
11156                    let mut shell_scene = Scene::new();
11157                    shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11158                        outer_scroll_descriptor,
11159                        outer_scroll_scene,
11160                    )));
11161                    shell_scene
11162                },
11163            )));
11164
11165            SceneFrame {
11166                window_id,
11167                viewport: Size::new(1280.0, 720.0),
11168                surface_size: Size::new(1280.0, 720.0),
11169                scale_factor: 1.0,
11170                dirty_regions: Vec::new(),
11171                layer_updates: vec![SceneLayerUpdate::from_descriptor(
11172                    SceneLayerUpdateKind::Content,
11173                    SceneLayerDescriptor::new(
11174                        SceneLayerId::from_widget(image_layer_id),
11175                        image_layer_id,
11176                        Rect::new(363.0, 376.0, 220.0, 220.0),
11177                    )
11178                    .with_content_bounds(Rect::new(363.0, 376.0, 220.0, 220.0))
11179                    .with_paint_bounds(Rect::new(363.0, 376.0, 220.0, 220.0))
11180                    .with_cache_policy(LayerCachePolicy::Direct),
11181                )],
11182                scene,
11183                font_registry: Arc::new(FontRegistry::new()),
11184                image_registry: Arc::clone(&images),
11185                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
11186            }
11187        };
11188
11189        let mut renderer = WgpuRenderer::default();
11190
11191        let direct_frame = build_frame(WindowId::new(116), LayerCachePolicy::Direct);
11192        renderer.render(&direct_frame).unwrap();
11193        let direct_pixels = renderer
11194            .capture_last_frame_rgba(direct_frame.window_id)
11195            .unwrap();
11196
11197        let cached_frame = build_frame(WindowId::new(117), LayerCachePolicy::Cached);
11198        renderer.render(&cached_frame).unwrap();
11199        let cached_pixels = renderer
11200            .capture_last_frame_rgba(cached_frame.window_id)
11201            .unwrap();
11202
11203        assert_rgba_images_match(&direct_pixels, &cached_pixels);
11204    }
11205
11206    #[test]
11207    fn nested_cached_scroll_large_paint_bounds_image_matches_direct_render() {
11208        let shell_id = WidgetId::new(123);
11209        let outer_scroll_id = WidgetId::new(124);
11210        let inner_scroll_id = WidgetId::new(125);
11211        let image_layer_id = WidgetId::new(126);
11212        let image_handle = ImageHandle::new(43);
11213
11214        let mut images = ImageRegistry::new();
11215        images.insert(
11216            image_handle,
11217            RegisteredImage::from_rgba8(
11218                2,
11219                2,
11220                vec![
11221                    220, 232, 246, 255, 64, 156, 232, 255, 64, 156, 232, 255, 255, 175, 64, 255,
11222                ],
11223            )
11224            .unwrap(),
11225        );
11226        let images = Arc::new(images);
11227
11228        let build_frame = |window_id, inner_cache_policy| {
11229            let shell_descriptor = SceneLayerDescriptor::new(
11230                SceneLayerId::from_widget(shell_id),
11231                shell_id,
11232                Rect::new(0.0, 0.0, 1280.0, 720.0),
11233            )
11234            .with_content_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11235            .with_paint_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11236            .with_cache_policy(LayerCachePolicy::Direct);
11237
11238            let outer_scroll_descriptor = SceneLayerDescriptor::new(
11239                SceneLayerId::from_widget(outer_scroll_id),
11240                outer_scroll_id,
11241                Rect::new(320.0, 28.0, 428.0, 336.0),
11242            )
11243            .with_content_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11244            .with_paint_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11245            .with_cache_policy(LayerCachePolicy::Direct)
11246            .with_composition_mode(LayerCompositionMode::Scroll);
11247
11248            let inner_scroll_descriptor = SceneLayerDescriptor::new(
11249                SceneLayerId::from_widget(inner_scroll_id),
11250                inner_scroll_id,
11251                Rect::new(321.0, 60.0, 426.0, 303.0),
11252            )
11253            .with_content_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11254            .with_paint_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11255            .with_cache_policy(inner_cache_policy)
11256            .with_composition_mode(LayerCompositionMode::Scroll)
11257            .with_is_stack_surface(true);
11258
11259            let mut image_scene = Scene::new();
11260            image_scene.push(SceneCommand::DrawImage {
11261                rect: Rect::new(363.0, 376.0, 220.0, 220.0),
11262                source: ImageSource::new(image_handle),
11263            });
11264            let image_layer = SceneLayer::from_descriptor(
11265                SceneLayerDescriptor::new(
11266                    SceneLayerId::from_widget(image_layer_id),
11267                    image_layer_id,
11268                    Rect::new(363.0, 376.0, 220.0, 220.0),
11269                )
11270                .with_content_bounds(Rect::new(362.5, 375.5, 221.0, 221.0))
11271                .with_paint_bounds(Rect::new(362.5, 375.5, 221.0, 221.0))
11272                .with_cache_policy(LayerCachePolicy::Direct),
11273                image_scene,
11274            );
11275
11276            let mut inner_scroll_scene = Scene::new();
11277            inner_scroll_scene.push(SceneCommand::Layer(image_layer));
11278
11279            let mut outer_scroll_scene = Scene::new();
11280            outer_scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11281                inner_scroll_descriptor,
11282                inner_scroll_scene,
11283            )));
11284
11285            let mut scene = Scene::new();
11286            scene.push(SceneCommand::FillRect {
11287                rect: Rect::new(0.0, 0.0, 1280.0, 720.0),
11288                brush: Color::rgba(0.92, 0.94, 0.97, 1.0).into(),
11289            });
11290            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11291                shell_descriptor,
11292                {
11293                    let mut shell_scene = Scene::new();
11294                    shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11295                        outer_scroll_descriptor,
11296                        outer_scroll_scene,
11297                    )));
11298                    shell_scene
11299                },
11300            )));
11301
11302            SceneFrame {
11303                window_id,
11304                viewport: Size::new(1280.0, 720.0),
11305                surface_size: Size::new(1280.0, 720.0),
11306                scale_factor: 1.0,
11307                dirty_regions: Vec::new(),
11308                layer_updates: vec![SceneLayerUpdate::from_descriptor(
11309                    SceneLayerUpdateKind::Content,
11310                    SceneLayerDescriptor::new(
11311                        SceneLayerId::from_widget(image_layer_id),
11312                        image_layer_id,
11313                        Rect::new(363.0, 376.0, 220.0, 220.0),
11314                    )
11315                    .with_content_bounds(Rect::new(362.5, 375.5, 221.0, 221.0))
11316                    .with_paint_bounds(Rect::new(362.5, 375.5, 221.0, 221.0))
11317                    .with_cache_policy(LayerCachePolicy::Direct),
11318                )],
11319                scene,
11320                font_registry: Arc::new(FontRegistry::new()),
11321                image_registry: Arc::clone(&images),
11322                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
11323            }
11324        };
11325
11326        let mut renderer = WgpuRenderer::default();
11327
11328        let direct_frame = build_frame(WindowId::new(118), LayerCachePolicy::Direct);
11329        renderer.render(&direct_frame).unwrap();
11330        let direct_pixels = renderer
11331            .capture_last_frame_rgba(direct_frame.window_id)
11332            .unwrap();
11333
11334        let cached_frame = build_frame(WindowId::new(119), LayerCachePolicy::Cached);
11335        renderer.render(&cached_frame).unwrap();
11336        let cached_pixels = renderer
11337            .capture_last_frame_rgba(cached_frame.window_id)
11338            .unwrap();
11339
11340        assert_rgba_images_match(&direct_pixels, &cached_pixels);
11341    }
11342
11343    #[test]
11344    fn nested_cached_scroll_internal_clip_matches_direct_after_image_scroll() {
11345        let shell_id = WidgetId::new(127);
11346        let outer_scroll_id = WidgetId::new(128);
11347        let inner_scroll_id = WidgetId::new(129);
11348        let image_layer_id = WidgetId::new(130);
11349        let image_handle = ImageHandle::new(44);
11350
11351        let mut images = ImageRegistry::new();
11352        images.insert(
11353            image_handle,
11354            RegisteredImage::from_rgba8(
11355                2,
11356                2,
11357                vec![
11358                    220, 232, 246, 255, 64, 156, 232, 255, 64, 156, 232, 255, 255, 175, 64, 255,
11359                ],
11360            )
11361            .unwrap(),
11362        );
11363        let images = Arc::new(images);
11364
11365        let build_frame = |window_id, inner_cache_policy, image_y, update_kind| {
11366            let shell_descriptor = SceneLayerDescriptor::new(
11367                SceneLayerId::from_widget(shell_id),
11368                shell_id,
11369                Rect::new(0.0, 0.0, 1280.0, 720.0),
11370            )
11371            .with_content_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11372            .with_paint_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11373            .with_cache_policy(LayerCachePolicy::Direct);
11374
11375            let outer_scroll_descriptor = SceneLayerDescriptor::new(
11376                SceneLayerId::from_widget(outer_scroll_id),
11377                outer_scroll_id,
11378                Rect::new(320.0, 28.0, 428.0, 336.0),
11379            )
11380            .with_content_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11381            .with_paint_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11382            .with_cache_policy(LayerCachePolicy::Direct)
11383            .with_composition_mode(LayerCompositionMode::Scroll);
11384
11385            let inner_scroll_descriptor = SceneLayerDescriptor::new(
11386                SceneLayerId::from_widget(inner_scroll_id),
11387                inner_scroll_id,
11388                Rect::new(321.0, 60.0, 426.0, 303.0),
11389            )
11390            .with_content_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11391            .with_paint_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11392            .with_cache_policy(inner_cache_policy)
11393            .with_composition_mode(LayerCompositionMode::Scroll)
11394            .with_is_stack_surface(true);
11395
11396            let image_descriptor = SceneLayerDescriptor::new(
11397                SceneLayerId::from_widget(image_layer_id),
11398                image_layer_id,
11399                Rect::new(363.0, image_y, 220.0, 220.0),
11400            )
11401            .with_content_bounds(Rect::new(362.5, image_y - 0.5, 221.0, 221.0))
11402            .with_paint_bounds(Rect::new(362.5, image_y - 0.5, 221.0, 221.0))
11403            .with_cache_policy(LayerCachePolicy::Direct);
11404
11405            let mut image_scene = Scene::new();
11406            image_scene.push(SceneCommand::FillPath {
11407                path: Path::rounded_rect(Rect::new(363.0, image_y, 220.0, 220.0), 12.0),
11408                brush: Color::rgba(0.965, 0.975, 0.99, 1.0).into(),
11409            });
11410            image_scene.push(SceneCommand::PushClip {
11411                rect: Rect::new(363.0, image_y, 220.0, 220.0),
11412            });
11413            image_scene.push(SceneCommand::DrawImage {
11414                rect: Rect::new(363.0, image_y, 220.0, 220.0),
11415                source: ImageSource::new(image_handle),
11416            });
11417            image_scene.push(SceneCommand::PopClip);
11418            image_scene.push(SceneCommand::StrokePath {
11419                path: Path::rounded_rect(Rect::new(363.0, image_y, 220.0, 220.0), 12.0),
11420                brush: Color::rgba(0.8335978, 0.8335974, 0.835042, 1.0).into(),
11421                stroke: StrokeStyle::new(1.0),
11422            });
11423            let image_layer = SceneLayer::from_descriptor(image_descriptor.clone(), image_scene);
11424
11425            let mut inner_scroll_scene = Scene::new();
11426            inner_scroll_scene.push(SceneCommand::PushClip {
11427                rect: Rect::new(321.0, 60.0, 426.0, 303.0),
11428            });
11429            inner_scroll_scene.push(SceneCommand::Layer(image_layer));
11430            inner_scroll_scene.push(SceneCommand::PopClip);
11431
11432            let mut outer_scroll_scene = Scene::new();
11433            outer_scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11434                inner_scroll_descriptor,
11435                inner_scroll_scene,
11436            )));
11437
11438            let mut scene = Scene::new();
11439            scene.push(SceneCommand::FillRect {
11440                rect: Rect::new(0.0, 0.0, 1280.0, 720.0),
11441                brush: Color::rgba(0.92, 0.94, 0.97, 1.0).into(),
11442            });
11443            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11444                shell_descriptor,
11445                {
11446                    let mut shell_scene = Scene::new();
11447                    shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11448                        outer_scroll_descriptor,
11449                        outer_scroll_scene,
11450                    )));
11451                    shell_scene
11452                },
11453            )));
11454
11455            let update = SceneLayerUpdate::from_descriptor(update_kind, image_descriptor.clone())
11456                .with_damage(Rect::new(362.5, 139.5, 221.0, 457.0));
11457
11458            SceneFrame {
11459                window_id,
11460                viewport: Size::new(1280.0, 720.0),
11461                surface_size: Size::new(1280.0, 720.0),
11462                scale_factor: 1.0,
11463                dirty_regions: Vec::new(),
11464                layer_updates: vec![update],
11465                scene,
11466                font_registry: Arc::new(FontRegistry::new()),
11467                image_registry: Arc::clone(&images),
11468                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
11469            }
11470        };
11471
11472        let mut renderer = WgpuRenderer::default();
11473
11474        let direct_initial = build_frame(
11475            WindowId::new(120),
11476            LayerCachePolicy::Direct,
11477            140.0,
11478            SceneLayerUpdateKind::Content,
11479        );
11480        renderer.render(&direct_initial).unwrap();
11481        let direct_updated = build_frame(
11482            WindowId::new(120),
11483            LayerCachePolicy::Direct,
11484            376.0,
11485            SceneLayerUpdateKind::Transform,
11486        );
11487        renderer.render(&direct_updated).unwrap();
11488        let direct_pixels = renderer
11489            .capture_last_frame_rgba(direct_updated.window_id)
11490            .unwrap();
11491
11492        let cached_initial = build_frame(
11493            WindowId::new(121),
11494            LayerCachePolicy::Cached,
11495            140.0,
11496            SceneLayerUpdateKind::Content,
11497        );
11498        renderer.render(&cached_initial).unwrap();
11499        let cached_updated = build_frame(
11500            WindowId::new(121),
11501            LayerCachePolicy::Cached,
11502            376.0,
11503            SceneLayerUpdateKind::Transform,
11504        );
11505        renderer.render(&cached_updated).unwrap();
11506        let cached_pixels = renderer
11507            .capture_last_frame_rgba(cached_updated.window_id)
11508            .unwrap();
11509
11510        assert_rgba_images_match(&direct_pixels, &cached_pixels);
11511    }
11512
11513    #[test]
11514    fn nested_cached_scroll_sibling_transforms_match_direct_after_image_scroll() {
11515        let shell_id = WidgetId::new(131);
11516        let outer_scroll_id = WidgetId::new(132);
11517        let inner_scroll_id = WidgetId::new(133);
11518        let top_section_id = WidgetId::new(134);
11519        let bottom_section_id = WidgetId::new(135);
11520        let image_layer_id = WidgetId::new(136);
11521        let image_handle = ImageHandle::new(45);
11522
11523        let mut images = ImageRegistry::new();
11524        images.insert(
11525            image_handle,
11526            RegisteredImage::from_rgba8(
11527                2,
11528                2,
11529                vec![
11530                    220, 232, 246, 255, 64, 156, 232, 255, 64, 156, 232, 255, 255, 175, 64, 255,
11531                ],
11532            )
11533            .unwrap(),
11534        );
11535        let images = Arc::new(images);
11536
11537        let build_frame = |window_id, inner_cache_policy, top_y, bottom_y, update_kind| {
11538            let shell_descriptor = SceneLayerDescriptor::new(
11539                SceneLayerId::from_widget(shell_id),
11540                shell_id,
11541                Rect::new(0.0, 0.0, 1280.0, 720.0),
11542            )
11543            .with_content_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11544            .with_paint_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11545            .with_cache_policy(LayerCachePolicy::Direct);
11546
11547            let outer_scroll_descriptor = SceneLayerDescriptor::new(
11548                SceneLayerId::from_widget(outer_scroll_id),
11549                outer_scroll_id,
11550                Rect::new(320.0, 28.0, 428.0, 336.0),
11551            )
11552            .with_content_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11553            .with_paint_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11554            .with_cache_policy(LayerCachePolicy::Direct)
11555            .with_composition_mode(LayerCompositionMode::Scroll);
11556
11557            let inner_scroll_descriptor = SceneLayerDescriptor::new(
11558                SceneLayerId::from_widget(inner_scroll_id),
11559                inner_scroll_id,
11560                Rect::new(321.0, 60.0, 426.0, 303.0),
11561            )
11562            .with_content_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11563            .with_paint_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11564            .with_cache_policy(inner_cache_policy)
11565            .with_composition_mode(LayerCompositionMode::Scroll)
11566            .with_is_stack_surface(true);
11567
11568            let mut top_scene = Scene::new();
11569            top_scene.push(SceneCommand::FillRect {
11570                rect: Rect::new(345.0, top_y, 378.0, 379.0),
11571                brush: Color::rgba(0.985, 0.99, 1.0, 1.0).into(),
11572            });
11573            top_scene.push(SceneCommand::FillRect {
11574                rect: Rect::new(363.0, top_y + 81.0, 440.2, 240.0),
11575                brush: Color::rgba(0.97, 0.981, 0.992, 1.0).into(),
11576            });
11577            let top_layer = SceneLayer::from_descriptor(
11578                SceneLayerDescriptor::new(
11579                    SceneLayerId::from_widget(top_section_id),
11580                    top_section_id,
11581                    Rect::new(345.0, top_y, 378.0, 379.0),
11582                )
11583                .with_content_bounds(Rect::new(345.0, top_y, 1172.2, 379.0))
11584                .with_paint_bounds(Rect::new(345.0, top_y, 1172.2, 379.0))
11585                .with_cache_policy(LayerCachePolicy::Direct),
11586                top_scene,
11587            );
11588
11589            let image_y = bottom_y + 133.0;
11590            let mut image_scene = Scene::new();
11591            image_scene.push(SceneCommand::FillPath {
11592                path: Path::rounded_rect(Rect::new(363.0, image_y, 220.0, 220.0), 12.0),
11593                brush: Color::rgba(0.965, 0.975, 0.99, 1.0).into(),
11594            });
11595            image_scene.push(SceneCommand::PushClip {
11596                rect: Rect::new(363.0, image_y, 220.0, 220.0),
11597            });
11598            image_scene.push(SceneCommand::DrawImage {
11599                rect: Rect::new(363.0, image_y, 220.0, 220.0),
11600                source: ImageSource::new(image_handle),
11601            });
11602            image_scene.push(SceneCommand::PopClip);
11603            let image_layer = SceneLayer::from_descriptor(
11604                SceneLayerDescriptor::new(
11605                    SceneLayerId::from_widget(image_layer_id),
11606                    image_layer_id,
11607                    Rect::new(363.0, image_y, 220.0, 220.0),
11608                )
11609                .with_content_bounds(Rect::new(362.5, image_y - 0.5, 221.0, 221.0))
11610                .with_paint_bounds(Rect::new(362.5, image_y - 0.5, 221.0, 221.0))
11611                .with_cache_policy(LayerCachePolicy::Direct),
11612                image_scene,
11613            );
11614
11615            let mut bottom_scene = Scene::new();
11616            bottom_scene.push(SceneCommand::FillRect {
11617                rect: Rect::new(345.0, bottom_y, 378.0, 371.0),
11618                brush: Color::rgba(0.985, 0.99, 1.0, 1.0).into(),
11619            });
11620            bottom_scene.push(SceneCommand::Layer(image_layer));
11621            let bottom_layer = SceneLayer::from_descriptor(
11622                SceneLayerDescriptor::new(
11623                    SceneLayerId::from_widget(bottom_section_id),
11624                    bottom_section_id,
11625                    Rect::new(345.0, bottom_y, 378.0, 371.0),
11626                )
11627                .with_content_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0))
11628                .with_paint_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0))
11629                .with_cache_policy(LayerCachePolicy::Direct),
11630                bottom_scene,
11631            );
11632
11633            let mut inner_scroll_scene = Scene::new();
11634            inner_scroll_scene.push(SceneCommand::PushClip {
11635                rect: Rect::new(321.0, 60.0, 426.0, 303.0),
11636            });
11637            inner_scroll_scene.push(SceneCommand::Layer(top_layer));
11638            inner_scroll_scene.push(SceneCommand::Layer(bottom_layer));
11639            inner_scroll_scene.push(SceneCommand::PopClip);
11640
11641            let mut outer_scroll_scene = Scene::new();
11642            outer_scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11643                inner_scroll_descriptor,
11644                inner_scroll_scene,
11645            )));
11646
11647            let mut scene = Scene::new();
11648            scene.push(SceneCommand::FillRect {
11649                rect: Rect::new(0.0, 0.0, 1280.0, 720.0),
11650                brush: Color::rgba(0.92, 0.94, 0.97, 1.0).into(),
11651            });
11652            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11653                shell_descriptor,
11654                {
11655                    let mut shell_scene = Scene::new();
11656                    shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11657                        outer_scroll_descriptor,
11658                        outer_scroll_scene,
11659                    )));
11660                    shell_scene
11661                },
11662            )));
11663
11664            SceneFrame {
11665                window_id,
11666                viewport: Size::new(1280.0, 720.0),
11667                surface_size: Size::new(1280.0, 720.0),
11668                scale_factor: 1.0,
11669                dirty_regions: Vec::new(),
11670                layer_updates: vec![
11671                    SceneLayerUpdate::from_descriptor(
11672                        update_kind,
11673                        SceneLayerDescriptor::new(
11674                            SceneLayerId::from_widget(top_section_id),
11675                            top_section_id,
11676                            Rect::new(345.0, top_y, 378.0, 379.0),
11677                        )
11678                        .with_content_bounds(Rect::new(345.0, top_y, 1172.2, 379.0))
11679                        .with_paint_bounds(Rect::new(345.0, top_y, 1172.2, 379.0))
11680                        .with_cache_policy(LayerCachePolicy::Direct),
11681                    )
11682                    .with_damage(Rect::new(345.0, -178.0, 1172.2, 403.0)),
11683                    SceneLayerUpdate::from_descriptor(
11684                        update_kind,
11685                        SceneLayerDescriptor::new(
11686                            SceneLayerId::from_widget(bottom_section_id),
11687                            bottom_section_id,
11688                            Rect::new(345.0, bottom_y, 378.0, 371.0),
11689                        )
11690                        .with_content_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0))
11691                        .with_paint_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0))
11692                        .with_cache_policy(LayerCachePolicy::Direct),
11693                    )
11694                    .with_damage(Rect::new(345.0, 219.0, 378.0, 395.0)),
11695                ],
11696                scene,
11697                font_registry: Arc::new(FontRegistry::new()),
11698                image_registry: Arc::clone(&images),
11699                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
11700            }
11701        };
11702
11703        let mut renderer = WgpuRenderer::default();
11704
11705        let direct_initial = build_frame(
11706            WindowId::new(122),
11707            LayerCachePolicy::Direct,
11708            -178.0,
11709            219.0,
11710            SceneLayerUpdateKind::Content,
11711        );
11712        renderer.render(&direct_initial).unwrap();
11713        let direct_updated = build_frame(
11714            WindowId::new(122),
11715            LayerCachePolicy::Direct,
11716            -154.0,
11717            243.0,
11718            SceneLayerUpdateKind::Transform,
11719        );
11720        renderer.render(&direct_updated).unwrap();
11721        let direct_pixels = renderer
11722            .capture_last_frame_rgba(direct_updated.window_id)
11723            .unwrap();
11724
11725        let cached_initial = build_frame(
11726            WindowId::new(123),
11727            LayerCachePolicy::Cached,
11728            -178.0,
11729            219.0,
11730            SceneLayerUpdateKind::Content,
11731        );
11732        renderer.render(&cached_initial).unwrap();
11733        let cached_updated = build_frame(
11734            WindowId::new(123),
11735            LayerCachePolicy::Cached,
11736            -154.0,
11737            243.0,
11738            SceneLayerUpdateKind::Transform,
11739        );
11740        renderer.render(&cached_updated).unwrap();
11741        let cached_pixels = renderer
11742            .capture_last_frame_rgba(cached_updated.window_id)
11743            .unwrap();
11744
11745        assert_rgba_images_match(&direct_pixels, &cached_pixels);
11746    }
11747
11748    #[test]
11749    fn nested_cached_scroll_auto_sibling_transforms_match_direct_after_image_scroll() {
11750        let shell_id = WidgetId::new(137);
11751        let outer_scroll_id = WidgetId::new(138);
11752        let inner_scroll_id = WidgetId::new(139);
11753        let top_section_id = WidgetId::new(140);
11754        let bottom_section_id = WidgetId::new(141);
11755        let image_layer_id = WidgetId::new(142);
11756        let image_handle = ImageHandle::new(46);
11757
11758        let mut images = ImageRegistry::new();
11759        images.insert(
11760            image_handle,
11761            RegisteredImage::from_rgba8(
11762                2,
11763                2,
11764                vec![
11765                    220, 232, 246, 255, 64, 156, 232, 255, 64, 156, 232, 255, 255, 175, 64, 255,
11766                ],
11767            )
11768            .unwrap(),
11769        );
11770        let images = Arc::new(images);
11771
11772        let build_frame = |window_id, inner_cache_policy, top_y, bottom_y, update_kind| {
11773            let shell_descriptor = SceneLayerDescriptor::new(
11774                SceneLayerId::from_widget(shell_id),
11775                shell_id,
11776                Rect::new(0.0, 0.0, 1280.0, 720.0),
11777            )
11778            .with_content_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11779            .with_paint_bounds(Rect::new(0.0, 0.0, 1280.0, 720.0))
11780            .with_cache_policy(LayerCachePolicy::Direct);
11781
11782            let outer_scroll_descriptor = SceneLayerDescriptor::new(
11783                SceneLayerId::from_widget(outer_scroll_id),
11784                outer_scroll_id,
11785                Rect::new(320.0, 28.0, 428.0, 336.0),
11786            )
11787            .with_content_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11788            .with_paint_bounds(Rect::new(345.0, 84.0, 378.0, 781.0))
11789            .with_cache_policy(LayerCachePolicy::Direct)
11790            .with_composition_mode(LayerCompositionMode::Scroll);
11791
11792            let inner_scroll_descriptor = SceneLayerDescriptor::new(
11793                SceneLayerId::from_widget(inner_scroll_id),
11794                inner_scroll_id,
11795                Rect::new(321.0, 60.0, 426.0, 303.0),
11796            )
11797            .with_content_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11798            .with_paint_bounds(Rect::new(345.0, -130.0, 1172.2, 768.0))
11799            .with_cache_policy(inner_cache_policy)
11800            .with_composition_mode(LayerCompositionMode::Scroll)
11801            .with_is_stack_surface(true);
11802
11803            let mut top_scene = Scene::new();
11804            top_scene.push(SceneCommand::FillRect {
11805                rect: Rect::new(345.0, top_y, 378.0, 379.0),
11806                brush: Color::rgba(0.985, 0.99, 1.0, 1.0).into(),
11807            });
11808            top_scene.push(SceneCommand::FillRect {
11809                rect: Rect::new(363.0, top_y + 81.0, 440.2, 240.0),
11810                brush: Color::rgba(0.97, 0.981, 0.992, 1.0).into(),
11811            });
11812            let top_layer = SceneLayer::from_descriptor(
11813                SceneLayerDescriptor::new(
11814                    SceneLayerId::from_widget(top_section_id),
11815                    top_section_id,
11816                    Rect::new(345.0, top_y, 378.0, 379.0),
11817                )
11818                .with_content_bounds(Rect::new(345.0, top_y, 1172.2, 379.0))
11819                .with_paint_bounds(Rect::new(345.0, top_y, 1172.2, 379.0)),
11820                top_scene,
11821            );
11822
11823            let image_y = bottom_y + 133.0;
11824            let mut image_scene = Scene::new();
11825            image_scene.push(SceneCommand::FillPath {
11826                path: Path::rounded_rect(Rect::new(363.0, image_y, 220.0, 220.0), 12.0),
11827                brush: Color::rgba(0.965, 0.975, 0.99, 1.0).into(),
11828            });
11829            image_scene.push(SceneCommand::PushClip {
11830                rect: Rect::new(363.0, image_y, 220.0, 220.0),
11831            });
11832            image_scene.push(SceneCommand::DrawImage {
11833                rect: Rect::new(363.0, image_y, 220.0, 220.0),
11834                source: ImageSource::new(image_handle),
11835            });
11836            image_scene.push(SceneCommand::PopClip);
11837            let image_layer = SceneLayer::from_descriptor(
11838                SceneLayerDescriptor::new(
11839                    SceneLayerId::from_widget(image_layer_id),
11840                    image_layer_id,
11841                    Rect::new(363.0, image_y, 220.0, 220.0),
11842                )
11843                .with_content_bounds(Rect::new(362.5, image_y - 0.5, 221.0, 221.0))
11844                .with_paint_bounds(Rect::new(362.5, image_y - 0.5, 221.0, 221.0)),
11845                image_scene,
11846            );
11847
11848            let mut bottom_scene = Scene::new();
11849            bottom_scene.push(SceneCommand::FillRect {
11850                rect: Rect::new(345.0, bottom_y, 378.0, 371.0),
11851                brush: Color::rgba(0.985, 0.99, 1.0, 1.0).into(),
11852            });
11853            bottom_scene.push(SceneCommand::Layer(image_layer));
11854            let bottom_layer = SceneLayer::from_descriptor(
11855                SceneLayerDescriptor::new(
11856                    SceneLayerId::from_widget(bottom_section_id),
11857                    bottom_section_id,
11858                    Rect::new(345.0, bottom_y, 378.0, 371.0),
11859                )
11860                .with_content_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0))
11861                .with_paint_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0)),
11862                bottom_scene,
11863            );
11864
11865            let mut inner_scroll_scene = Scene::new();
11866            inner_scroll_scene.push(SceneCommand::PushClip {
11867                rect: Rect::new(321.0, 60.0, 426.0, 303.0),
11868            });
11869            inner_scroll_scene.push(SceneCommand::Layer(top_layer));
11870            inner_scroll_scene.push(SceneCommand::Layer(bottom_layer));
11871            inner_scroll_scene.push(SceneCommand::PopClip);
11872
11873            let mut outer_scroll_scene = Scene::new();
11874            outer_scroll_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11875                inner_scroll_descriptor,
11876                inner_scroll_scene,
11877            )));
11878
11879            let mut scene = Scene::new();
11880            scene.push(SceneCommand::FillRect {
11881                rect: Rect::new(0.0, 0.0, 1280.0, 720.0),
11882                brush: Color::rgba(0.92, 0.94, 0.97, 1.0).into(),
11883            });
11884            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11885                shell_descriptor,
11886                {
11887                    let mut shell_scene = Scene::new();
11888                    shell_scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
11889                        outer_scroll_descriptor,
11890                        outer_scroll_scene,
11891                    )));
11892                    shell_scene
11893                },
11894            )));
11895
11896            SceneFrame {
11897                window_id,
11898                viewport: Size::new(1280.0, 720.0),
11899                surface_size: Size::new(1280.0, 720.0),
11900                scale_factor: 1.0,
11901                dirty_regions: Vec::new(),
11902                layer_updates: vec![
11903                    SceneLayerUpdate::from_descriptor(
11904                        update_kind,
11905                        SceneLayerDescriptor::new(
11906                            SceneLayerId::from_widget(top_section_id),
11907                            top_section_id,
11908                            Rect::new(345.0, top_y, 378.0, 379.0),
11909                        )
11910                        .with_content_bounds(Rect::new(345.0, top_y, 1172.2, 379.0))
11911                        .with_paint_bounds(Rect::new(345.0, top_y, 1172.2, 379.0)),
11912                    )
11913                    .with_damage(Rect::new(345.0, -178.0, 1172.2, 403.0)),
11914                    SceneLayerUpdate::from_descriptor(
11915                        update_kind,
11916                        SceneLayerDescriptor::new(
11917                            SceneLayerId::from_widget(bottom_section_id),
11918                            bottom_section_id,
11919                            Rect::new(345.0, bottom_y, 378.0, 371.0),
11920                        )
11921                        .with_content_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0))
11922                        .with_paint_bounds(Rect::new(345.0, bottom_y, 378.0, 371.0)),
11923                    )
11924                    .with_damage(Rect::new(345.0, 219.0, 378.0, 395.0)),
11925                ],
11926                scene,
11927                font_registry: Arc::new(FontRegistry::new()),
11928                image_registry: Arc::clone(&images),
11929                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
11930            }
11931        };
11932
11933        let mut renderer = WgpuRenderer::default();
11934
11935        let direct_initial = build_frame(
11936            WindowId::new(124),
11937            LayerCachePolicy::Direct,
11938            -178.0,
11939            219.0,
11940            SceneLayerUpdateKind::Content,
11941        );
11942        renderer.render(&direct_initial).unwrap();
11943        let direct_updated = build_frame(
11944            WindowId::new(124),
11945            LayerCachePolicy::Direct,
11946            -154.0,
11947            243.0,
11948            SceneLayerUpdateKind::Transform,
11949        );
11950        renderer.render(&direct_updated).unwrap();
11951        let direct_pixels = renderer
11952            .capture_last_frame_rgba(direct_updated.window_id)
11953            .unwrap();
11954
11955        let cached_initial = build_frame(
11956            WindowId::new(125),
11957            LayerCachePolicy::Cached,
11958            -178.0,
11959            219.0,
11960            SceneLayerUpdateKind::Content,
11961        );
11962        renderer.render(&cached_initial).unwrap();
11963        let cached_updated = build_frame(
11964            WindowId::new(125),
11965            LayerCachePolicy::Cached,
11966            -154.0,
11967            243.0,
11968            SceneLayerUpdateKind::Transform,
11969        );
11970        renderer.render(&cached_updated).unwrap();
11971        let cached_pixels = renderer
11972            .capture_last_frame_rgba(cached_updated.window_id)
11973            .unwrap();
11974
11975        assert_rgba_images_match(&direct_pixels, &cached_pixels);
11976    }
11977
11978    #[test]
11979    fn glyph_raster_bounds_expand_fractional_edges() {
11980        let mut builder = super::TinySkiaPathBuilder::new();
11981        builder.move_to(0.6, -0.2);
11982        builder.line_to(10.2, -0.2);
11983        builder.line_to(10.2, 4.4);
11984        builder.line_to(0.6, 4.4);
11985        builder.close();
11986        let path = builder.finish().expect("fractional rectangle path");
11987
11988        let bounds = super::glyph_raster_bounds(&path).expect("bounds for fractional rectangle");
11989
11990        assert!((bounds.logical_min_x - 0.6).abs() < 0.0001);
11991        assert!((bounds.logical_min_y + 0.2).abs() < 0.0001);
11992        assert!((bounds.logical_width - 9.6).abs() < 0.0001);
11993        assert!((bounds.logical_height - 4.6).abs() < 0.0001);
11994        assert_eq!(bounds.raster_min_x, 0.0);
11995        assert_eq!(bounds.raster_min_y, -1.0);
11996        assert_eq!(bounds.raster_width, 11);
11997        assert_eq!(bounds.raster_height, 6);
11998    }
11999
12000    #[test]
12001    fn atlas_text_keeps_terminal_glyphs_at_fractional_scale() {
12002        let handle = FontHandle::new(30);
12003        let mut fonts = FontRegistry::new();
12004        fonts.insert(handle, load_test_font());
12005
12006        let build_frame = |text: &str| SceneFrame {
12007            window_id: WindowId::new(96),
12008            viewport: Size::new(260.0, 52.0),
12009            surface_size: Size::new(390.0, 78.0),
12010            scale_factor: 1.5,
12011            dirty_regions: Vec::new(),
12012            layer_updates: Vec::new(),
12013            scene: {
12014                let mut scene = Scene::new();
12015                scene.push(SceneCommand::FillRect {
12016                    rect: Rect::new(0.0, 0.0, 260.0, 52.0),
12017                    brush: Color::WHITE.into(),
12018                });
12019                scene.push(SceneCommand::DrawText(TextRun {
12020                    rect: Rect::new(8.0, 10.0, 220.0, 24.0),
12021                    text: text.to_string(),
12022                    style: TextStyle {
12023                        font: Some(handle),
12024                        font_size: 14.0,
12025                        line_height: 18.0,
12026                        color: Color::rgba(0.12, 0.16, 0.22, 1.0),
12027                        ..TextStyle::default()
12028                    },
12029                }));
12030                scene
12031            },
12032            font_registry: Arc::new(fonts.clone()),
12033            image_registry: Arc::new(ImageRegistry::new()),
12034            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12035        };
12036
12037        let mut renderer = WgpuRenderer::default();
12038        let without_terminal = build_frame("inspecto");
12039        renderer.render(&without_terminal).unwrap();
12040        let without_terminal_pixels = renderer
12041            .capture_last_frame_rgba(without_terminal.window_id)
12042            .unwrap();
12043
12044        let with_terminal = build_frame("inspector");
12045        renderer.render(&with_terminal).unwrap();
12046        let with_terminal_pixels = renderer
12047            .capture_last_frame_rgba(with_terminal.window_id)
12048            .unwrap();
12049
12050        let diff_count = rgba_image_diff_count(&without_terminal_pixels, &with_terminal_pixels);
12051
12052        assert!(
12053            diff_count > 0,
12054            "terminal glyph vanished at fractional scale (diff_count={diff_count})"
12055        );
12056    }
12057
12058    #[test]
12059    fn analytic_stroke_rect_renders_at_fractional_scale() {
12060        let frame = SceneFrame {
12061            window_id: WindowId::new(97),
12062            viewport: Size::new(220.0, 64.0),
12063            surface_size: Size::new(330.0, 96.0),
12064            scale_factor: 1.5,
12065            dirty_regions: Vec::new(),
12066            layer_updates: Vec::new(),
12067            scene: {
12068                let mut scene = Scene::new();
12069                scene.push(SceneCommand::FillRect {
12070                    rect: Rect::new(0.0, 0.0, 220.0, 64.0),
12071                    brush: Color::WHITE.into(),
12072                });
12073                scene.push(SceneCommand::StrokeRect {
12074                    rect: Rect::new(12.0, 12.0, 180.0, 32.0),
12075                    brush: Color::rgba(0.18, 0.33, 0.85, 1.0).into(),
12076                    stroke: StrokeStyle::new(1.0),
12077                });
12078                scene
12079            },
12080            font_registry: Arc::new(FontRegistry::new()),
12081            image_registry: Arc::new(ImageRegistry::new()),
12082            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12083        };
12084
12085        let mut renderer = WgpuRenderer::default();
12086        renderer.render(&frame).unwrap();
12087        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
12088
12089        let changed_pixels = pixels
12090            .pixels()
12091            .chunks_exact(4)
12092            .filter(|pixel| {
12093                !rgba_channels_match_with_tolerance(
12094                    pixel,
12095                    &[255, 255, 255, 255],
12096                    RGBA_CHANNEL_TOLERANCE,
12097                )
12098            })
12099            .count();
12100
12101        assert!(
12102            changed_pixels > 500,
12103            "analytic stroke rect disappeared at fractional scale (changed_pixels={changed_pixels})"
12104        );
12105    }
12106
12107    #[test]
12108    fn analytic_stroke_path_keeps_nominal_line_thickness() {
12109        let mut builder = PathBuilder::new();
12110        builder
12111            .move_to(Point::new(24.0, 32.0))
12112            .line_to(Point::new(196.0, 32.0));
12113
12114        let frame = SceneFrame {
12115            window_id: WindowId::new(98),
12116            viewport: Size::new(220.0, 64.0),
12117            surface_size: Size::new(220.0, 64.0),
12118            scale_factor: 1.0,
12119            dirty_regions: Vec::new(),
12120            layer_updates: Vec::new(),
12121            scene: {
12122                let mut scene = Scene::new();
12123                scene.push(SceneCommand::FillRect {
12124                    rect: Rect::new(0.0, 0.0, 220.0, 64.0),
12125                    brush: Color::WHITE.into(),
12126                });
12127                scene.push(SceneCommand::StrokePath {
12128                    path: builder.build(),
12129                    brush: Color::BLACK.into(),
12130                    stroke: StrokeStyle::new(1.0),
12131                });
12132                scene
12133            },
12134            font_registry: Arc::new(FontRegistry::new()),
12135            image_registry: Arc::new(ImageRegistry::new()),
12136            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12137        };
12138
12139        let mut renderer = WgpuRenderer::default();
12140        renderer.render(&frame).unwrap();
12141        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
12142        let visible_rows = non_white_row_count(&pixels, Rect::new(20.0, 26.0, 180.0, 12.0));
12143
12144        assert!(
12145            visible_rows <= 3,
12146            "analytic one-pixel stroke expanded across too many rows (visible_rows={visible_rows})"
12147        );
12148    }
12149
12150    #[test]
12151    fn round_stroke_path_uses_analytic_antialiasing() {
12152        let mut builder = PathBuilder::new();
12153        builder
12154            .move_to(Point::new(6.0, 25.0))
12155            .line_to(Point::new(25.0, 6.0));
12156
12157        let frame = SceneFrame {
12158            window_id: WindowId::new(9901),
12159            viewport: Size::new(32.0, 32.0),
12160            surface_size: Size::new(32.0, 32.0),
12161            scale_factor: 1.0,
12162            dirty_regions: Vec::new(),
12163            layer_updates: Vec::new(),
12164            scene: {
12165                let mut scene = Scene::new();
12166                scene.push(SceneCommand::StrokePath {
12167                    path: builder.build(),
12168                    brush: Color::WHITE.into(),
12169                    stroke: StrokeStyle::new(2.0)
12170                        .with_cap(sui_scene::StrokeCap::Round)
12171                        .with_join(sui_scene::StrokeJoin::Round),
12172                });
12173                scene
12174            },
12175            font_registry: Arc::new(FontRegistry::new()),
12176            image_registry: Arc::new(ImageRegistry::new()),
12177            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12178        };
12179
12180        let mut text_engine = TextEngine::new().unwrap();
12181        let mut compositor = RetainedCompositorState::default();
12182        let draw_ops = prepare_with_compositor(&frame, &mut text_engine, &mut compositor).unwrap();
12183        assert_eq!(draw_ops.analytic_paths.len(), 1);
12184        assert_eq!(compositor.path_cache.stats(), (0, 0, 0));
12185        assert!(
12186            draw_ops
12187                .draw_ops
12188                .iter()
12189                .any(|draw| matches!(draw.kind, DrawOpKind::AnalyticPath { .. }))
12190        );
12191
12192        let mut renderer = WgpuRenderer::default();
12193        renderer.render(&frame).unwrap();
12194        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
12195        let partial_coverage = pixels
12196            .pixels()
12197            .chunks_exact(4)
12198            .filter(|pixel| pixel[3] > 0 && pixel[3] < 255)
12199            .count();
12200        let opaque_coverage = pixels
12201            .pixels()
12202            .chunks_exact(4)
12203            .filter(|pixel| pixel[3] == 255)
12204            .count();
12205
12206        assert!(
12207            partial_coverage > 0,
12208            "round stroke edges should contain partial alpha coverage"
12209        );
12210        assert!(
12211            opaque_coverage > 0,
12212            "round stroke center should retain fully covered pixels"
12213        );
12214    }
12215
12216    #[test]
12217    fn soft_rounded_border_retains_most_ink_when_feathering_is_enabled() {
12218        let build_frame = || {
12219            let mut scene = Scene::new();
12220            scene.push(SceneCommand::FillRect {
12221                rect: Rect::new(0.0, 0.0, 240.0, 72.0),
12222                brush: Color::WHITE.into(),
12223            });
12224            scene.push(SceneCommand::FillPath {
12225                path: Path::rounded_rect(Rect::new(12.0, 16.0, 196.0, 36.0), 8.0),
12226                brush: Color::rgba(1.0, 1.0, 1.0, 1.0).into(),
12227            });
12228            scene.push(SceneCommand::StrokePath {
12229                path: Path::rounded_rect(Rect::new(12.0, 16.0, 196.0, 36.0), 8.0),
12230                brush: Color::rgba(0.18, 0.33, 0.85, 1.0).into(),
12231                stroke: StrokeStyle::new(1.0 / 1.5),
12232            });
12233
12234            SceneFrame {
12235                window_id: WindowId::new(99),
12236                viewport: Size::new(240.0, 72.0),
12237                surface_size: Size::new(360.0, 108.0),
12238                scale_factor: 1.5,
12239                dirty_regions: Vec::new(),
12240                layer_updates: Vec::new(),
12241                scene,
12242                font_registry: Arc::new(FontRegistry::new()),
12243                image_registry: Arc::new(ImageRegistry::new()),
12244                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12245            }
12246        };
12247
12248        let frame = build_frame();
12249
12250        let mut feathered = WgpuRenderer::default()
12251            .with_feathering_enabled(true)
12252            .with_feather_width(1.0);
12253        feathered.render(&frame).unwrap();
12254        let feathered_pixels = feathered.capture_last_frame_rgba(frame.window_id).unwrap();
12255
12256        let mut hard = WgpuRenderer::default().with_feathering_enabled(false);
12257        hard.render(&frame).unwrap();
12258        let hard_pixels = hard.capture_last_frame_rgba(frame.window_id).unwrap();
12259
12260        let crop = Rect::new(10.0, 14.0, 200.0, 40.0);
12261        let feathered_ink = ink_pixel_count(&feathered_pixels, crop);
12262        let hard_ink = ink_pixel_count(&hard_pixels, crop);
12263
12264        assert!(
12265            feathered_ink * 5 >= hard_ink * 4,
12266            "feathered rounded border lost too much ink at fractional scale (feathered_ink={feathered_ink}, hard_ink={hard_ink})"
12267        );
12268    }
12269
12270    #[test]
12271    fn soft_control_border_and_chevrons_retain_visible_ink_when_feathering_is_enabled() {
12272        fn line_path(start: Point, end: Point) -> Path {
12273            let mut builder = PathBuilder::new();
12274            builder.move_to(start).line_to(end);
12275            builder.build()
12276        }
12277
12278        fn chevron_path(bounds: Rect, direction: f32) -> Path {
12279            let center = Point::new(
12280                bounds.x() + (bounds.width() * 0.5),
12281                bounds.y() + (bounds.height() * 0.5),
12282            );
12283            let mut builder = PathBuilder::new();
12284            if direction.is_sign_positive() {
12285                builder
12286                    .move_to(Point::new(bounds.x(), bounds.y() + (bounds.height() * 0.3)))
12287                    .line_to(Point::new(
12288                        center.x,
12289                        bounds.max_y() - (bounds.height() * 0.3),
12290                    ))
12291                    .line_to(Point::new(
12292                        bounds.max_x(),
12293                        bounds.y() + (bounds.height() * 0.3),
12294                    ));
12295            } else {
12296                builder
12297                    .move_to(Point::new(
12298                        bounds.x(),
12299                        bounds.max_y() - (bounds.height() * 0.3),
12300                    ))
12301                    .line_to(Point::new(center.x, bounds.y() + (bounds.height() * 0.3)))
12302                    .line_to(Point::new(
12303                        bounds.max_x(),
12304                        bounds.max_y() - (bounds.height() * 0.3),
12305                    ));
12306            }
12307            builder.build()
12308        }
12309
12310        let build_frame = || {
12311            let mut scene = Scene::new();
12312            scene.push(SceneCommand::FillRect {
12313                rect: Rect::new(0.0, 0.0, 220.0, 72.0),
12314                brush: Color::WHITE.into(),
12315            });
12316            scene.push(SceneCommand::StrokePath {
12317                path: Path::rounded_rect(Rect::new(10.0, 16.0, 170.0, 40.0), 6.0),
12318                brush: Color::rgba(0.47, 0.49, 0.53, 1.0).into(),
12319                stroke: StrokeStyle::new(1.0),
12320            });
12321            scene.push(SceneCommand::StrokePath {
12322                path: line_path(Point::new(154.0, 22.0), Point::new(154.0, 50.0)),
12323                brush: Color::rgba(0.73, 0.73, 0.75, 1.0).into(),
12324                stroke: StrokeStyle::new(1.0),
12325            });
12326            scene.push(SceneCommand::StrokePath {
12327                path: chevron_path(Rect::new(156.0, 18.0, 16.0, 14.0), -1.0),
12328                brush: Color::rgba(0.12, 0.12, 0.12, 1.0).into(),
12329                stroke: StrokeStyle::new(1.8),
12330            });
12331            scene.push(SceneCommand::StrokePath {
12332                path: chevron_path(Rect::new(156.0, 40.0, 16.0, 14.0), 1.0),
12333                brush: Color::rgba(0.12, 0.12, 0.12, 1.0).into(),
12334                stroke: StrokeStyle::new(1.8),
12335            });
12336            scene.push(SceneCommand::StrokePath {
12337                path: Path::rounded_rect(Rect::new(10.0, 16.0, 196.0, 40.0), 6.0),
12338                brush: Color::rgba(0.73, 0.73, 0.75, 1.0).into(),
12339                stroke: StrokeStyle::new(1.0),
12340            });
12341            scene.push(SceneCommand::StrokePath {
12342                path: chevron_path(Rect::new(178.0, 27.0, 18.0, 18.0), 1.0),
12343                brush: Color::rgba(0.12, 0.12, 0.12, 1.0).into(),
12344                stroke: StrokeStyle::new(1.8),
12345            });
12346
12347            SceneFrame {
12348                window_id: WindowId::new(102),
12349                viewport: Size::new(220.0, 72.0),
12350                surface_size: Size::new(220.0, 72.0),
12351                scale_factor: 1.0,
12352                dirty_regions: Vec::new(),
12353                layer_updates: Vec::new(),
12354                scene,
12355                font_registry: Arc::new(FontRegistry::new()),
12356                image_registry: Arc::new(ImageRegistry::new()),
12357                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12358            }
12359        };
12360
12361        let frame = build_frame();
12362
12363        let mut feathered = WgpuRenderer::default()
12364            .with_feathering_enabled(true)
12365            .with_feather_width(1.0);
12366        feathered.render(&frame).unwrap();
12367        let feathered_pixels = feathered.capture_last_frame_rgba(frame.window_id).unwrap();
12368
12369        let mut hard = WgpuRenderer::default().with_feathering_enabled(false);
12370        hard.render(&frame).unwrap();
12371        let hard_pixels = hard.capture_last_frame_rgba(frame.window_id).unwrap();
12372
12373        let number_input_crop = Rect::new(8.0, 14.0, 172.0, 44.0);
12374        let select_crop = Rect::new(8.0, 14.0, 200.0, 44.0);
12375        let feathered_number_input_ink = ink_pixel_count(&feathered_pixels, number_input_crop);
12376        let hard_number_input_ink = ink_pixel_count(&hard_pixels, number_input_crop);
12377        let feathered_select_ink = ink_pixel_count(&feathered_pixels, select_crop);
12378        let hard_select_ink = ink_pixel_count(&hard_pixels, select_crop);
12379
12380        assert!(
12381            feathered_number_input_ink * 3 >= hard_number_input_ink,
12382            "feathered number-input border or chevrons lost too much ink (feathered={feathered_number_input_ink}, hard={hard_number_input_ink})"
12383        );
12384        assert!(
12385            feathered_select_ink * 3 >= hard_select_ink,
12386            "feathered select border or chevron lost too much ink (feathered={feathered_select_ink}, hard={hard_select_ink})"
12387        );
12388    }
12389
12390    #[test]
12391    fn analytic_splitter_rects_stay_at_divider_location() {
12392        let divider = Rect::new(140.0, 10.0, 12.0, 84.0);
12393        let handle = Rect::new(144.0, 38.0, 4.0, 28.0);
12394        let mut scene = Scene::new();
12395        scene.push(SceneCommand::FillRect {
12396            rect: Rect::new(0.0, 0.0, 220.0, 108.0),
12397            brush: Color::WHITE.into(),
12398        });
12399        scene.push(SceneCommand::FillRect {
12400            rect: divider,
12401            brush: Color::rgba(0.94, 0.955, 0.975, 1.0).into(),
12402        });
12403        scene.push(SceneCommand::StrokeRect {
12404            rect: divider,
12405            brush: Color::rgba(0.58, 0.62, 0.68, 1.0).into(),
12406            stroke: StrokeStyle::new(1.0),
12407        });
12408        scene.push(SceneCommand::FillRect {
12409            rect: handle,
12410            brush: Color::rgba(0.58, 0.62, 0.68, 0.9).into(),
12411        });
12412
12413        let frame = SceneFrame {
12414            window_id: WindowId::new(103),
12415            viewport: Size::new(220.0, 108.0),
12416            surface_size: Size::new(220.0, 108.0),
12417            scale_factor: 1.0,
12418            dirty_regions: Vec::new(),
12419            layer_updates: Vec::new(),
12420            scene,
12421            font_registry: Arc::new(FontRegistry::new()),
12422            image_registry: Arc::new(ImageRegistry::new()),
12423            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12424        };
12425
12426        let mut renderer = WgpuRenderer::default();
12427        renderer.render(&frame).unwrap();
12428        let pixels = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
12429
12430        let misplaced_left_pixels =
12431            non_white_pixel_count(&pixels, Rect::new(0.0, 0.0, 100.0, 108.0));
12432        let divider_pixels = non_white_pixel_count(&pixels, Rect::new(138.0, 8.0, 18.0, 88.0));
12433
12434        assert_eq!(
12435            misplaced_left_pixels, 0,
12436            "splitter coverage rendered away from the divider"
12437        );
12438        assert!(
12439            divider_pixels > 250,
12440            "splitter divider did not render enough visible pixels at its expected location (divider_pixels={divider_pixels})"
12441        );
12442    }
12443
12444    #[test]
12445    fn transformed_layer_keeps_analytic_path_at_translated_location() {
12446        let layer_id = WidgetId::new(104);
12447        let window_id = WindowId::new(104);
12448        let build_layer = |x: f32| {
12449            let bounds = Rect::new(x, 12.0, 72.0, 52.0);
12450            let descriptor =
12451                SceneLayerDescriptor::new(SceneLayerId::from_widget(layer_id), layer_id, bounds)
12452                    .with_content_bounds(bounds)
12453                    .with_paint_bounds(bounds)
12454                    .with_cache_policy(LayerCachePolicy::Direct);
12455
12456            let mut layer_scene = Scene::new();
12457            layer_scene.push(SceneCommand::FillPath {
12458                path: Path::rounded_rect(Rect::new(x + 14.0, 24.0, 44.0, 24.0), 7.0),
12459                brush: Color::rgba(0.18, 0.32, 0.86, 1.0).into(),
12460            });
12461
12462            (
12463                descriptor.clone(),
12464                SceneLayer::from_descriptor(descriptor, layer_scene),
12465            )
12466        };
12467
12468        let build_frame = |descriptor: SceneLayerDescriptor, layer: SceneLayer, update_kind| {
12469            let mut scene = Scene::new();
12470            scene.push(SceneCommand::FillRect {
12471                rect: Rect::new(0.0, 0.0, 240.0, 92.0),
12472                brush: Color::WHITE.into(),
12473            });
12474            scene.push(SceneCommand::Layer(layer));
12475
12476            SceneFrame {
12477                window_id,
12478                viewport: Size::new(240.0, 92.0),
12479                surface_size: Size::new(240.0, 92.0),
12480                scale_factor: 1.0,
12481                dirty_regions: Vec::new(),
12482                layer_updates: vec![SceneLayerUpdate::from_descriptor(update_kind, descriptor)],
12483                scene,
12484                font_registry: Arc::new(FontRegistry::new()),
12485                image_registry: Arc::new(ImageRegistry::new()),
12486                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12487            }
12488        };
12489
12490        let (initial_descriptor, initial_layer) = build_layer(28.0);
12491        let (moved_descriptor, moved_layer) = build_layer(136.0);
12492
12493        let mut renderer = WgpuRenderer::default();
12494        let first = build_frame(
12495            initial_descriptor,
12496            initial_layer,
12497            SceneLayerUpdateKind::Content,
12498        );
12499        renderer.render(&first).unwrap();
12500
12501        let second = build_frame(
12502            moved_descriptor,
12503            moved_layer,
12504            SceneLayerUpdateKind::Transform,
12505        );
12506        renderer.render(&second).unwrap();
12507        let pixels = renderer.capture_last_frame_rgba(window_id).unwrap();
12508
12509        let old_location_pixels = non_white_pixel_count(&pixels, Rect::new(34.0, 18.0, 60.0, 40.0));
12510        let moved_location_pixels =
12511            non_white_pixel_count(&pixels, Rect::new(142.0, 18.0, 60.0, 40.0));
12512
12513        assert_eq!(
12514            old_location_pixels, 0,
12515            "translated feathered path left pixels at its previous layer location"
12516        );
12517        assert!(
12518            moved_location_pixels > 400,
12519            "translated feathered path did not render at its moved layer location (moved_location_pixels={moved_location_pixels})"
12520        );
12521    }
12522
12523    #[test]
12524    fn cached_layer_matches_direct_for_tight_rounded_border_at_fractional_scale() {
12525        let widget_id = WidgetId::new(100);
12526        let build_frame = |cache_policy| {
12527            let descriptor = SceneLayerDescriptor::new(
12528                SceneLayerId::from_widget(widget_id),
12529                widget_id,
12530                Rect::new(0.0, 0.0, 220.0, 64.0),
12531            )
12532            .with_content_bounds(Rect::new(0.0, 0.0, 220.0, 64.0))
12533            .with_paint_bounds(Rect::new(0.0, 0.0, 220.0, 64.0))
12534            .with_cache_policy(cache_policy);
12535
12536            let mut layer_scene = Scene::new();
12537            layer_scene.push(SceneCommand::FillRect {
12538                rect: Rect::new(0.0, 0.0, 220.0, 64.0),
12539                brush: Color::WHITE.into(),
12540            });
12541            layer_scene.push(SceneCommand::StrokePath {
12542                path: Path::rounded_rect(Rect::new(0.0, 0.0, 220.0, 64.0), 10.0),
12543                brush: Color::rgba(0.18, 0.33, 0.85, 1.0).into(),
12544                stroke: StrokeStyle::new(1.0 / 1.5),
12545            });
12546
12547            let mut scene = Scene::new();
12548            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
12549                descriptor.clone(),
12550                layer_scene,
12551            )));
12552
12553            SceneFrame {
12554                window_id: WindowId::new(100),
12555                viewport: Size::new(220.0, 64.0),
12556                surface_size: Size::new(330.0, 96.0),
12557                scale_factor: 1.5,
12558                dirty_regions: Vec::new(),
12559                layer_updates: vec![
12560                    SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
12561                        .with_damage(Rect::new(0.0, 0.0, 220.0, 64.0)),
12562                ],
12563                scene,
12564                font_registry: Arc::new(FontRegistry::new()),
12565                image_registry: Arc::new(ImageRegistry::new()),
12566                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12567            }
12568        };
12569
12570        let mut renderer = WgpuRenderer::default();
12571        let direct = build_frame(LayerCachePolicy::Direct);
12572        renderer.render(&direct).unwrap();
12573        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
12574
12575        let cached = build_frame(LayerCachePolicy::Cached);
12576        renderer.render(&cached).unwrap();
12577        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
12578
12579        assert_rgba_images_match(&direct_pixels, &cached_pixels);
12580    }
12581
12582    #[test]
12583    fn retained_packets_match_direct_for_theme_preview_style_cards_at_fractional_scale() {
12584        let handle = FontHandle::new(153);
12585        let mut fonts = FontRegistry::new();
12586        fonts.insert(handle, load_test_font());
12587
12588        let widget_id = WidgetId::new(154);
12589        let build_frame = |window_id, cache_policy| {
12590            let descriptor = SceneLayerDescriptor::new(
12591                SceneLayerId::from_widget(widget_id),
12592                widget_id,
12593                Rect::new(0.0, 0.0, 640.0, 220.0),
12594            )
12595            .with_content_bounds(Rect::new(0.0, 0.0, 640.0, 220.0))
12596            .with_paint_bounds(Rect::new(0.0, 0.0, 640.0, 220.0))
12597            .with_cache_policy(cache_policy)
12598            .with_composition_mode(LayerCompositionMode::Scroll);
12599
12600            let mut layer_scene = Scene::new();
12601            layer_scene.push(SceneCommand::FillRect {
12602                rect: Rect::new(0.0, 0.0, 640.0, 220.0),
12603                brush: Color::rgba(0.94, 0.95, 0.98, 1.0).into(),
12604            });
12605
12606            let card_specs = [
12607                (
12608                    56.0,
12609                    Color::rgba(0.99, 0.99, 1.0, 1.0),
12610                    Color::rgba(0.19, 0.46, 0.91, 1.0),
12611                    Color::rgba(0.15, 0.73, 0.70, 1.0),
12612                    Color::rgba(0.10, 0.13, 0.19, 1.0),
12613                    Color::rgba(0.39, 0.45, 0.54, 1.0),
12614                    Color::rgba(0.82, 0.85, 0.91, 1.0),
12615                    "Light theme",
12616                ),
12617                (
12618                    344.0,
12619                    Color::rgba(0.14, 0.16, 0.21, 1.0),
12620                    Color::rgba(0.45, 0.60, 0.98, 1.0),
12621                    Color::rgba(0.96, 0.54, 0.31, 1.0),
12622                    Color::rgba(0.94, 0.95, 0.98, 1.0),
12623                    Color::rgba(0.68, 0.72, 0.80, 1.0),
12624                    Color::rgba(0.28, 0.31, 0.38, 1.0),
12625                    "Dark theme",
12626                ),
12627            ];
12628
12629            for (card_x, surface, accent, secondary, text_color, subtle_text, border, title) in
12630                card_specs
12631            {
12632                let card_rect = Rect::new(card_x, 24.0, 240.0, 172.0);
12633                layer_scene.push(SceneCommand::FillPath {
12634                    path: Path::rounded_rect(card_rect, 18.0),
12635                    brush: surface.into(),
12636                });
12637                layer_scene.push(SceneCommand::StrokePath {
12638                    path: Path::rounded_rect(card_rect, 18.0),
12639                    brush: border.into(),
12640                    stroke: StrokeStyle::new(1.0),
12641                });
12642                layer_scene.push(SceneCommand::DrawText(TextRun {
12643                    rect: Rect::new(card_x + 20.0, 44.0, 172.0, 24.0),
12644                    text: title.to_string(),
12645                    style: TextStyle {
12646                        font: Some(handle),
12647                        font_size: 18.0,
12648                        line_height: 22.0,
12649                        color: text_color,
12650                        ..Default::default()
12651                    },
12652                }));
12653                layer_scene.push(SceneCommand::DrawText(TextRun {
12654                    rect: Rect::new(card_x + 20.0, 76.0, 188.0, 20.0),
12655                    text: format!(
12656                        "{} base surface with {} accent for primary actions.",
12657                        title.split_whitespace().next().unwrap().to_lowercase(),
12658                        title.split_whitespace().next().unwrap().to_lowercase(),
12659                    ),
12660                    style: TextStyle {
12661                        font: Some(handle),
12662                        font_size: 13.0,
12663                        line_height: 18.0,
12664                        color: subtle_text,
12665                        ..Default::default()
12666                    },
12667                }));
12668                layer_scene.push(SceneCommand::FillPath {
12669                    path: Path::rounded_rect(Rect::new(card_x + 20.0, 108.0, 220.0, 36.0), 10.0),
12670                    brush: surface.into(),
12671                });
12672                layer_scene.push(SceneCommand::StrokePath {
12673                    path: Path::rounded_rect(Rect::new(card_x + 20.0, 108.0, 220.0, 36.0), 10.0),
12674                    brush: border.into(),
12675                    stroke: StrokeStyle::new(1.0),
12676                });
12677                layer_scene.push(SceneCommand::DrawText(TextRun {
12678                    rect: Rect::new(card_x + 36.0, 118.0, 172.0, 16.0),
12679                    text: "Find layer, panel, or asset".to_string(),
12680                    style: TextStyle {
12681                        font: Some(handle),
12682                        font_size: 13.0,
12683                        line_height: 18.0,
12684                        color: subtle_text,
12685                        ..Default::default()
12686                    },
12687                }));
12688                layer_scene.push(SceneCommand::FillPath {
12689                    path: Path::rounded_rect(Rect::new(card_x + 20.0, 156.0, 86.0, 28.0), 14.0),
12690                    brush: accent.into(),
12691                });
12692                layer_scene.push(SceneCommand::DrawText(TextRun {
12693                    rect: Rect::new(card_x + 38.0, 163.0, 48.0, 16.0),
12694                    text: "Inspect".to_string(),
12695                    style: TextStyle {
12696                        font: Some(handle),
12697                        font_size: 13.0,
12698                        line_height: 18.0,
12699                        color: Color::rgba(1.0, 1.0, 1.0, 1.0),
12700                        ..Default::default()
12701                    },
12702                }));
12703                layer_scene.push(SceneCommand::FillRect {
12704                    rect: Rect::new(card_x + 128.0, 160.0, 28.0, 16.0),
12705                    brush: secondary.into(),
12706                });
12707                layer_scene.push(SceneCommand::DrawText(TextRun {
12708                    rect: Rect::new(card_x + 164.0, 158.33333, 68.0, 20.0),
12709                    text: "Live updates".to_string(),
12710                    style: TextStyle {
12711                        font: Some(handle),
12712                        font_size: 14.0,
12713                        line_height: 20.0,
12714                        color: text_color,
12715                        ..Default::default()
12716                    },
12717                }));
12718            }
12719
12720            let mut scene = Scene::new();
12721            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
12722                descriptor.clone(),
12723                layer_scene,
12724            )));
12725
12726            SceneFrame {
12727                window_id,
12728                viewport: Size::new(640.0, 220.0),
12729                surface_size: Size::new(960.0, 330.0),
12730                scale_factor: 1.5,
12731                dirty_regions: Vec::new(),
12732                layer_updates: vec![
12733                    SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
12734                        .with_damage(Rect::new(0.0, 0.0, 640.0, 220.0)),
12735                ],
12736                scene,
12737                font_registry: Arc::new(fonts.clone()),
12738                image_registry: Arc::new(ImageRegistry::new()),
12739                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12740            }
12741        };
12742
12743        let mut renderer = WgpuRenderer::default();
12744        let direct = build_frame(WindowId::new(153), LayerCachePolicy::Direct);
12745        renderer.render(&direct).unwrap();
12746        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
12747
12748        let cached = build_frame(WindowId::new(154), LayerCachePolicy::Cached);
12749        renderer.render(&cached).unwrap();
12750        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
12751
12752        assert_rgba_images_match(&direct_pixels, &cached_pixels);
12753    }
12754
12755    #[test]
12756    fn cached_layer_matches_direct_for_tight_tab_text_at_fractional_scale() {
12757        let handle = FontHandle::new(30);
12758        let mut fonts = FontRegistry::new();
12759        fonts.insert(handle, load_test_font());
12760
12761        let widget_id = WidgetId::new(101);
12762        let build_frame = |cache_policy| {
12763            let descriptor = SceneLayerDescriptor::new(
12764                SceneLayerId::from_widget(widget_id),
12765                widget_id,
12766                Rect::new(0.0, 0.0, 236.0, 44.0),
12767            )
12768            .with_content_bounds(Rect::new(0.0, 0.0, 236.0, 44.0))
12769            .with_paint_bounds(Rect::new(0.0, 0.0, 236.0, 44.0))
12770            .with_cache_policy(cache_policy);
12771
12772            let mut layer_scene = Scene::new();
12773            layer_scene.push(SceneCommand::FillRect {
12774                rect: Rect::new(0.0, 0.0, 236.0, 44.0),
12775                brush: Color::rgba(0.96, 0.97, 0.99, 1.0).into(),
12776            });
12777            layer_scene.push(SceneCommand::DrawText(TextRun {
12778                rect: Rect::new(10.0, 10.0, 216.0, 20.0),
12779                text: "Inspector".to_string(),
12780                style: TextStyle {
12781                    font: Some(handle),
12782                    font_size: 12.0,
12783                    line_height: 16.0,
12784                    color: Color::rgba(0.15, 0.19, 0.26, 1.0),
12785                    ..TextStyle::default()
12786                },
12787            }));
12788
12789            let mut scene = Scene::new();
12790            scene.push(SceneCommand::Layer(SceneLayer::from_descriptor(
12791                descriptor.clone(),
12792                layer_scene,
12793            )));
12794
12795            SceneFrame {
12796                window_id: WindowId::new(101),
12797                viewport: Size::new(236.0, 44.0),
12798                surface_size: Size::new(354.0, 66.0),
12799                scale_factor: 1.5,
12800                dirty_regions: Vec::new(),
12801                layer_updates: vec![
12802                    SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Content, descriptor)
12803                        .with_damage(Rect::new(0.0, 0.0, 236.0, 44.0)),
12804                ],
12805                scene,
12806                font_registry: Arc::new(fonts.clone()),
12807                image_registry: Arc::new(ImageRegistry::new()),
12808                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12809            }
12810        };
12811
12812        let mut renderer = WgpuRenderer::default();
12813        let direct = build_frame(LayerCachePolicy::Direct);
12814        renderer.render(&direct).unwrap();
12815        let direct_pixels = renderer.capture_last_frame_rgba(direct.window_id).unwrap();
12816
12817        let cached = build_frame(LayerCachePolicy::Cached);
12818        renderer.render(&cached).unwrap();
12819        let cached_pixels = renderer.capture_last_frame_rgba(cached.window_id).unwrap();
12820
12821        assert_rgba_images_match(&direct_pixels, &cached_pixels);
12822    }
12823
12824    #[test]
12825    fn build_vertices_uses_registered_font_handle() {
12826        let handle = FontHandle::new(17);
12827        let mut fonts = FontRegistry::new();
12828        fonts.insert(handle, load_test_font());
12829
12830        let mut scene = Scene::new();
12831        scene.push(SceneCommand::DrawText(TextRun {
12832            rect: Rect::new(4.0, 6.0, 120.0, 28.0),
12833            text: "registered".to_string(),
12834            style: TextStyle {
12835                font: Some(handle),
12836                ..TextStyle::new(Color::WHITE)
12837            },
12838        }));
12839
12840        let mut text_engine = TextEngine::new().unwrap();
12841        let vertices = build_vertices(
12842            &SceneFrame {
12843                window_id: WindowId::new(3),
12844                viewport: Size::new(160.0, 60.0),
12845                surface_size: Size::new(160.0, 60.0),
12846                scale_factor: 1.0,
12847                dirty_regions: Vec::new(),
12848                layer_updates: Vec::new(),
12849                scene,
12850                font_registry: Arc::new(fonts),
12851                image_registry: Arc::new(ImageRegistry::new()),
12852                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12853            },
12854            &mut text_engine,
12855        )
12856        .unwrap();
12857
12858        assert!(!vertices.is_empty());
12859    }
12860
12861    #[test]
12862    fn build_vertices_errors_for_unregistered_font_handle() {
12863        let mut scene = Scene::new();
12864        scene.push(SceneCommand::DrawText(TextRun {
12865            rect: Rect::new(4.0, 6.0, 120.0, 28.0),
12866            text: "missing".to_string(),
12867            style: TextStyle {
12868                font: Some(FontHandle::new(404)),
12869                ..TextStyle::new(Color::WHITE)
12870            },
12871        }));
12872
12873        let mut text_engine = TextEngine::new().unwrap();
12874        let error = match build_vertices(
12875            &SceneFrame {
12876                window_id: WindowId::new(4),
12877                viewport: Size::new(160.0, 60.0),
12878                surface_size: Size::new(160.0, 60.0),
12879                scale_factor: 1.0,
12880                dirty_regions: Vec::new(),
12881                layer_updates: Vec::new(),
12882                scene,
12883                font_registry: Arc::new(FontRegistry::new()),
12884                image_registry: Arc::new(ImageRegistry::new()),
12885                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12886            },
12887            &mut text_engine,
12888        ) {
12889            Ok(_) => panic!("expected missing font handle to fail during shaping"),
12890            Err(error) => error,
12891        };
12892
12893        assert!(
12894            error
12895                .to_string()
12896                .contains("font handle 404 is not registered")
12897        );
12898    }
12899
12900    #[test]
12901    fn renderer_grows_atlas_pages_when_text_atlas_fills_mid_frame() {
12902        let mut scene = Scene::new();
12903        let text: String = (33u8..=126).map(char::from).collect();
12904        scene.push(SceneCommand::DrawText(TextRun {
12905            rect: Rect::new(4.0, 6.0, 1800.0, 32.0),
12906            text,
12907            style: TextStyle {
12908                font_size: 18.0,
12909                line_height: 22.0,
12910                ..TextStyle::new(Color::WHITE)
12911            },
12912        }));
12913
12914        let frame = SceneFrame {
12915            window_id: WindowId::new(16),
12916            viewport: Size::new(1800.0, 64.0),
12917            surface_size: Size::new(1800.0, 64.0),
12918            scale_factor: 1.0,
12919            dirty_regions: Vec::new(),
12920            layer_updates: Vec::new(),
12921            scene,
12922            font_registry: Arc::new(FontRegistry::new()),
12923            image_registry: Arc::new(ImageRegistry::new()),
12924            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12925        };
12926
12927        let mut renderer = WgpuRenderer::new();
12928        let mut text_engine = TextEngine::new().unwrap();
12929        // Tiny pages with room for several layers: the printable-ASCII run overflows the first
12930        // page, so the atlas must grow onto additional texture-array layers rather than reset.
12931        text_engine.atlas = TextAtlasPages::new(96, 96, 4);
12932        renderer.text_engine = Some(text_engine);
12933
12934        renderer.render(&frame).unwrap();
12935
12936        let active_text_engine = renderer
12937            .text_engine
12938            .as_ref()
12939            .expect("renderer keeps the same text engine -- no nuclear reset");
12940        // The engine was NOT replaced: it still has the small page size we configured (a reset
12941        // would have rebuilt it at the default page size).
12942        assert_eq!(active_text_engine.atlas.page_size(), (96, 96));
12943        // Overflowing one page grew the atlas onto more pages instead of resetting.
12944        assert!(
12945            active_text_engine.atlas.page_count() >= 2,
12946            "atlas should have grown onto multiple pages"
12947        );
12948        assert!(active_text_engine.glyph_cache_stats().0 > 32);
12949
12950        let stats = renderer
12951            .last_frame_stats(frame.window_id)
12952            .expect("renderer should record frame stats");
12953        assert!(stats.text_glyph_instance_count > 0);
12954
12955        let image = renderer.capture_last_frame_rgba(frame.window_id).unwrap();
12956        assert!(
12957            image
12958                .pixels()
12959                .chunks_exact(4)
12960                .any(|pixel| pixel[3] > RGBA_CHANNEL_TOLERANCE),
12961            "frame should render visible text across atlas pages"
12962        );
12963    }
12964
12965    #[test]
12966    fn multi_page_atlas_is_stable_across_frames() {
12967        // Rendering the same overflowing scene twice must not re-rasterize glyphs or churn pages.
12968        // This is the property that replaces the old "atlas full -> full reset every frame"
12969        // stutter: once warm, repeat frames are pure cache hits.
12970        let text: String = (33u8..=126).map(char::from).collect();
12971        let make_frame = || {
12972            let mut scene = Scene::new();
12973            scene.push(SceneCommand::DrawText(TextRun {
12974                rect: Rect::new(4.0, 6.0, 1800.0, 32.0),
12975                text: text.clone(),
12976                style: TextStyle {
12977                    font_size: 18.0,
12978                    line_height: 22.0,
12979                    ..TextStyle::new(Color::WHITE)
12980                },
12981            }));
12982            SceneFrame {
12983                window_id: WindowId::new(17),
12984                viewport: Size::new(1800.0, 64.0),
12985                surface_size: Size::new(1800.0, 64.0),
12986                scale_factor: 1.0,
12987                dirty_regions: Vec::new(),
12988                layer_updates: Vec::new(),
12989                scene,
12990                font_registry: Arc::new(FontRegistry::new()),
12991                image_registry: Arc::new(ImageRegistry::new()),
12992                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
12993            }
12994        };
12995
12996        let mut renderer = WgpuRenderer::new();
12997        let mut text_engine = TextEngine::new().unwrap();
12998        text_engine.atlas = TextAtlasPages::new(96, 96, 4);
12999        renderer.text_engine = Some(text_engine);
13000
13001        renderer.render(&make_frame()).unwrap();
13002        let (entries_after_first, pages_after_first) = {
13003            let text_engine = renderer.text_engine.as_ref().unwrap();
13004            (
13005                text_engine.glyph_cache_stats().0,
13006                text_engine.atlas.page_count(),
13007            )
13008        };
13009        assert!(pages_after_first >= 2, "glyphs should span multiple pages");
13010
13011        renderer.render(&make_frame()).unwrap();
13012        let text_engine = renderer.text_engine.as_ref().unwrap();
13013        assert_eq!(
13014            text_engine.atlas.page_count(),
13015            pages_after_first,
13016            "page count must be stable across frames (no growth/thrash)"
13017        );
13018        assert_eq!(
13019            text_engine.atlas.page_size(),
13020            (96, 96),
13021            "engine must not have been reset"
13022        );
13023        assert_eq!(
13024            text_engine.glyph_cache_stats().0,
13025            entries_after_first,
13026            "no glyphs should be re-rasterized on the second frame"
13027        );
13028
13029        let image = renderer.capture_last_frame_rgba(WindowId::new(17)).unwrap();
13030        assert!(
13031            image
13032                .pixels()
13033                .chunks_exact(4)
13034                .any(|pixel| pixel[3] > RGBA_CHANNEL_TOLERANCE)
13035        );
13036    }
13037
13038    #[test]
13039    fn multi_page_atlas_evicts_without_corruption_under_pressure() {
13040        // A tight 2-page budget with a rotating glyph set forces LRU eviction across frames. The
13041        // atlas must never exceed its budget, the glyph cache must never dangle past the live
13042        // pages (coupled entries are dropped on eviction), and rendering must keep working.
13043        let texts = [
13044            "the quick brown fox",
13045            "JUMPS OVER THE LAZY",
13046            "0123456789 !?#@&*()",
13047            "Pack my box w/ jugs",
13048            "Sphinx of black quartz",
13049        ];
13050
13051        let mut renderer = WgpuRenderer::new();
13052        let mut text_engine = TextEngine::new().unwrap();
13053        text_engine.atlas = TextAtlasPages::new(64, 64, 2);
13054        renderer.text_engine = Some(text_engine);
13055
13056        for label in texts {
13057            let mut scene = Scene::new();
13058            scene.push(SceneCommand::DrawText(TextRun {
13059                rect: Rect::new(4.0, 6.0, 600.0, 28.0),
13060                text: label.to_string(),
13061                style: TextStyle {
13062                    font_size: 18.0,
13063                    line_height: 22.0,
13064                    ..TextStyle::new(Color::WHITE)
13065                },
13066            }));
13067            let frame = SceneFrame {
13068                window_id: WindowId::new(21),
13069                viewport: Size::new(600.0, 40.0),
13070                surface_size: Size::new(600.0, 40.0),
13071                scale_factor: 1.0,
13072                dirty_regions: Vec::new(),
13073                layer_updates: Vec::new(),
13074                scene,
13075                font_registry: Arc::new(FontRegistry::new()),
13076                image_registry: Arc::new(ImageRegistry::new()),
13077                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
13078            };
13079
13080            renderer.render(&frame).unwrap();
13081
13082            let text_engine = renderer.text_engine.as_ref().unwrap();
13083            let pages = text_engine.atlas.page_count();
13084            assert!(pages <= 2, "atlas must respect the page budget");
13085            assert!(
13086                text_engine
13087                    .glyph_cache
13088                    .values()
13089                    .all(|cached| cached.page_index < pages),
13090                "every cached glyph must reference a live page after eviction"
13091            );
13092        }
13093
13094        let image = renderer.capture_last_frame_rgba(WindowId::new(21)).unwrap();
13095        assert!(
13096            image
13097                .pixels()
13098                .chunks_exact(4)
13099                .any(|pixel| pixel[3] > RGBA_CHANNEL_TOLERANCE)
13100        );
13101    }
13102
13103    #[test]
13104    fn retained_compositor_uses_registered_image_handle() {
13105        let handle = ImageHandle::new(23);
13106        let mut images = ImageRegistry::new();
13107        images.insert(
13108            handle,
13109            RegisteredImage::from_rgba8(
13110                2,
13111                2,
13112                vec![
13113                    255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
13114                ],
13115            )
13116            .unwrap(),
13117        );
13118
13119        let mut scene = Scene::new();
13120        scene.push(SceneCommand::DrawImage {
13121            rect: Rect::new(4.0, 6.0, 32.0, 24.0),
13122            source: ImageSource::new(handle),
13123        });
13124
13125        let mut text_engine = TextEngine::new().unwrap();
13126        let mut compositor = RetainedCompositorState::default();
13127        let ops = prepare_with_compositor(
13128            &SceneFrame {
13129                window_id: WindowId::new(7),
13130                viewport: Size::new(96.0, 64.0),
13131                surface_size: Size::new(96.0, 64.0),
13132                scale_factor: 1.0,
13133                dirty_regions: Vec::new(),
13134                layer_updates: Vec::new(),
13135                scene,
13136                font_registry: Arc::new(FontRegistry::new()),
13137                image_registry: Arc::new(images),
13138                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
13139            },
13140            &mut text_engine,
13141            &mut compositor,
13142        )
13143        .unwrap();
13144
13145        assert_eq!(ops.draw_ops.len(), 1);
13146        let op = &ops.draw_ops[0];
13147        assert!(
13148            matches!(op.kind, DrawOpKind::Image { handle: value, sampling: ImageSampling::Linear, .. } if value == handle)
13149        );
13150        assert_eq!(op.vertices.len, 6);
13151    }
13152
13153    #[test]
13154    fn retained_svg_draws_track_physical_size_and_snap_after_dpi_changes() {
13155        let handle = ImageHandle::new(24);
13156        let svg = br##"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4" viewBox="0 0 4 4"><path d="M0 0h4v4H0z" fill="#fff"/></svg>"##;
13157        let mut images = ImageRegistry::new();
13158        images.insert(handle, RegisteredImage::from_svg(svg).unwrap());
13159        let images = Arc::new(images);
13160
13161        let mut scene = Scene::new();
13162        scene.push(SceneCommand::DrawImage {
13163            rect: Rect::new(10.2, 5.3, 14.0, 12.0),
13164            source: ImageSource::new(handle),
13165        });
13166
13167        let mut text_engine = TextEngine::new().unwrap();
13168        let mut compositor = RetainedCompositorState::default();
13169        let make_frame = |surface_size| SceneFrame {
13170            window_id: WindowId::new(8),
13171            viewport: Size::new(100.0, 100.0),
13172            surface_size,
13173            scale_factor: surface_size.width / 100.0,
13174            dirty_regions: Vec::new(),
13175            layer_updates: Vec::new(),
13176            scene: scene.clone(),
13177            font_registry: Arc::new(FontRegistry::new()),
13178            image_registry: Arc::clone(&images),
13179            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
13180        };
13181
13182        let one_x = prepare_with_compositor(
13183            &make_frame(Size::new(100.0, 100.0)),
13184            &mut text_engine,
13185            &mut compositor,
13186        )
13187        .unwrap();
13188        let DrawOpKind::Image {
13189            raster_size: one_x_raster,
13190            ..
13191        } = one_x.draw_ops[0].kind
13192        else {
13193            panic!("expected image draw op");
13194        };
13195        assert_eq!((one_x_raster.width, one_x_raster.height), (14, 12));
13196
13197        let two_x = prepare_with_compositor(
13198            &make_frame(Size::new(200.0, 200.0)),
13199            &mut text_engine,
13200            &mut compositor,
13201        )
13202        .unwrap();
13203        let op = &two_x.draw_ops[0];
13204        let DrawOpKind::Image { raster_size, .. } = op.kind else {
13205            panic!("expected image draw op");
13206        };
13207        assert_eq!((raster_size.width, raster_size.height), (28, 24));
13208        assert_eq!(
13209            op.image.expect("image metadata").bounds,
13210            Rect::new(10.0, 5.5, 14.0, 12.0)
13211        );
13212    }
13213
13214    #[test]
13215    fn renderer_caches_physical_svg_variants_and_bitmap_mip_levels() {
13216        let svg_handle = ImageHandle::new(25);
13217        let bitmap_handle = ImageHandle::new(26);
13218        let dynamic_bitmap_handle = ImageHandle::new(27);
13219        let mut images = ImageRegistry::new();
13220        images.insert(
13221            svg_handle,
13222            RegisteredImage::from_svg(
13223                br##"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4" viewBox="0 0 4 4"><circle cx="2" cy="2" r="2" fill="#fff"/></svg>"##,
13224            )
13225            .unwrap(),
13226        );
13227        images.insert(
13228            bitmap_handle,
13229            RegisteredImage::from_rgba8(8, 4, vec![255; 8 * 4 * 4]).unwrap(),
13230        );
13231        images.insert(
13232            dynamic_bitmap_handle,
13233            RegisteredImage::from_rgba8(8, 4, vec![255; 8 * 4 * 4])
13234                .unwrap()
13235                .without_mipmaps(),
13236        );
13237
13238        let mut scene = Scene::new();
13239        scene.push(SceneCommand::DrawImage {
13240            rect: Rect::new(2.0, 2.0, 14.0, 12.0),
13241            source: ImageSource::new(svg_handle),
13242        });
13243        scene.push(SceneCommand::DrawImage {
13244            rect: Rect::new(20.0, 2.0, 8.0, 4.0),
13245            source: ImageSource::new(bitmap_handle),
13246        });
13247        scene.push(SceneCommand::DrawImage {
13248            rect: Rect::new(30.0, 2.0, 8.0, 4.0),
13249            source: ImageSource::new(dynamic_bitmap_handle),
13250        });
13251        let frame = SceneFrame {
13252            window_id: WindowId::new(9),
13253            viewport: Size::new(50.0, 30.0),
13254            surface_size: Size::new(100.0, 60.0),
13255            scale_factor: 2.0,
13256            dirty_regions: Vec::new(),
13257            layer_updates: Vec::new(),
13258            scene,
13259            font_registry: Arc::new(FontRegistry::new()),
13260            image_registry: Arc::new(images),
13261            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
13262        };
13263
13264        let mut renderer = WgpuRenderer::new();
13265        renderer.render(&frame).unwrap();
13266
13267        let (svg_key, svg_texture) = renderer
13268            .image_cache
13269            .iter()
13270            .find(|(key, _)| key.handle == svg_handle)
13271            .expect("physical SVG texture cached");
13272        let svg_size = svg_key.raster_size.expect("SVG cache key has raster size");
13273        assert_eq!((svg_size.width, svg_size.height), (28, 24));
13274        assert_eq!(
13275            (svg_texture.texture.width(), svg_texture.texture.height()),
13276            (28, 24)
13277        );
13278        assert_eq!(svg_texture.texture.mip_level_count(), 1);
13279
13280        let (bitmap_key, bitmap_texture) = renderer
13281            .image_cache
13282            .iter()
13283            .find(|(key, _)| key.handle == bitmap_handle)
13284            .expect("bitmap texture cached");
13285        assert_eq!(bitmap_key.raster_size, None);
13286        assert!(bitmap_key.mipmapped);
13287        assert_eq!(bitmap_texture.texture.mip_level_count(), 4);
13288
13289        let (dynamic_bitmap_key, dynamic_bitmap_texture) = renderer
13290            .image_cache
13291            .iter()
13292            .find(|(key, _)| key.handle == dynamic_bitmap_handle)
13293            .expect("dynamic bitmap texture cached");
13294        assert_eq!(dynamic_bitmap_key.raster_size, None);
13295        assert!(!dynamic_bitmap_key.mipmapped);
13296        assert_eq!(dynamic_bitmap_texture.texture.mip_level_count(), 1);
13297    }
13298
13299    #[test]
13300    fn renderer_samples_persistent_external_texture_updates() {
13301        let handle = ImageHandle::new(2301);
13302        let window_id = WindowId::new(2301);
13303        let viewport = Size::new(16.0, 16.0);
13304        let registry = WgpuExternalTextureRegistry::new();
13305        let mut renderer = WgpuRenderer::new().with_external_texture_registry(registry.clone());
13306
13307        // The first target initialization publishes the renderer-owned device
13308        // and queue to the shared registry.
13309        renderer
13310            .render(&SceneFrame::new(window_id, viewport))
13311            .unwrap();
13312        let context = registry.context().expect("renderer context attached");
13313
13314        let direct_handle = ImageHandle::new(2302);
13315        let direct_texture = context.device().create_texture(&wgpu::TextureDescriptor {
13316            label: Some("SUI direct external texture test"),
13317            size: wgpu::Extent3d {
13318                width: 4,
13319                height: 3,
13320                depth_or_array_layers: 1,
13321            },
13322            mip_level_count: 1,
13323            sample_count: 1,
13324            dimension: wgpu::TextureDimension::D2,
13325            format: wgpu::TextureFormat::Rgba8UnormSrgb,
13326            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
13327            view_formats: &[],
13328        });
13329        let direct_descriptor = registry
13330            .register_texture(direct_handle, direct_texture)
13331            .unwrap();
13332        assert_eq!(
13333            (direct_descriptor.width(), direct_descriptor.height()),
13334            (4, 3)
13335        );
13336        assert!(registry.unregister(direct_handle));
13337
13338        let red = Arc::<[u8]>::from(
13339            [255, 0, 0, 255]
13340                .into_iter()
13341                .cycle()
13342                .take(2 * 2 * 4)
13343                .collect::<Vec<_>>(),
13344        );
13345        let descriptor = registry.upload_rgba8(handle, 2, 2, red, 1).unwrap();
13346        let first_binding_revision = registry.resolve(handle).unwrap().binding_revision;
13347        let mut images = ImageRegistry::new();
13348        images.insert_external(handle, descriptor);
13349
13350        let mut scene = Scene::new();
13351        scene.push(SceneCommand::Clear(Color::BLACK));
13352        scene.push(SceneCommand::DrawImage {
13353            rect: Rect::new(0.0, 0.0, viewport.width, viewport.height),
13354            source: ImageSource::new(handle),
13355        });
13356        let mut frame = SceneFrame::new(window_id, viewport);
13357        frame.scene = scene;
13358        frame.image_registry = Arc::new(images);
13359
13360        renderer.render(&frame).unwrap();
13361        let first = renderer.capture_last_frame_rgba(window_id).unwrap();
13362        assert_rgba_pixel_near(&first, 8, 8, [255, 0, 0, 255], RGBA_CHANNEL_TOLERANCE);
13363
13364        let green = Arc::<[u8]>::from(
13365            [0, 255, 0, 255]
13366                .into_iter()
13367                .cycle()
13368                .take(2 * 2 * 4)
13369                .collect::<Vec<_>>(),
13370        );
13371        assert_eq!(
13372            registry.upload_rgba8(handle, 2, 2, green, 2).unwrap(),
13373            descriptor
13374        );
13375        assert_eq!(
13376            registry.resolve(handle).unwrap().binding_revision,
13377            first_binding_revision,
13378            "same-size updates must reuse the persistent GPU allocation"
13379        );
13380
13381        // The retained scene is unchanged; rendering again samples the newly
13382        // uploaded contents through the same image handle and bind group.
13383        renderer.render(&frame).unwrap();
13384        let second = renderer.capture_last_frame_rgba(window_id).unwrap();
13385        assert_rgba_pixel_near(&second, 8, 8, [0, 255, 0, 255], RGBA_CHANNEL_TOLERANCE);
13386    }
13387
13388    #[test]
13389    fn retained_compositor_preserves_transformed_image_quad() {
13390        let handle = ImageHandle::new(24);
13391        let mut images = ImageRegistry::new();
13392        images.insert(
13393            handle,
13394            RegisteredImage::from_rgba8(
13395                2,
13396                2,
13397                vec![
13398                    255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
13399                ],
13400            )
13401            .unwrap(),
13402        );
13403
13404        let rect = Rect::new(4.0, 6.0, 32.0, 24.0);
13405        let transform = Transform::translation(40.0, 10.0).then(Transform::rotation(0.35));
13406        let mut scene = Scene::new();
13407        scene.push(SceneCommand::PushTransform { transform });
13408        scene.push(SceneCommand::DrawImage {
13409            rect,
13410            source: ImageSource::new(handle),
13411        });
13412        scene.push(SceneCommand::PopTransform);
13413
13414        let mut text_engine = TextEngine::new().unwrap();
13415        let vertices = build_vertices(
13416            &SceneFrame {
13417                window_id: WindowId::new(7),
13418                viewport: Size::new(128.0, 96.0),
13419                surface_size: Size::new(128.0, 96.0),
13420                scale_factor: 1.0,
13421                dirty_regions: Vec::new(),
13422                layer_updates: Vec::new(),
13423                scene,
13424                font_registry: Arc::new(FontRegistry::new()),
13425                image_registry: Arc::new(images),
13426                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
13427            },
13428            &mut text_engine,
13429        )
13430        .unwrap();
13431
13432        let expected = transform.transform_point(rect.origin);
13433        let expected = to_ndc(expected.x, expected.y, Size::new(128.0, 96.0));
13434        assert!((vertices[0].position[0] - expected[0]).abs() < 0.001);
13435        assert!((vertices[0].position[1] - expected[1]).abs() < 0.001);
13436    }
13437
13438    #[test]
13439    fn retained_compositor_errors_for_unregistered_image_handle() {
13440        let mut scene = Scene::new();
13441        scene.push(SceneCommand::DrawImage {
13442            rect: Rect::new(4.0, 6.0, 32.0, 24.0),
13443            source: ImageSource::new(ImageHandle::new(88)),
13444        });
13445
13446        let mut text_engine = TextEngine::new().unwrap();
13447        let mut compositor = RetainedCompositorState::default();
13448        let error = prepare_with_compositor(
13449            &SceneFrame {
13450                window_id: WindowId::new(8),
13451                viewport: Size::new(96.0, 64.0),
13452                surface_size: Size::new(96.0, 64.0),
13453                scale_factor: 1.0,
13454                dirty_regions: Vec::new(),
13455                layer_updates: Vec::new(),
13456                scene,
13457                font_registry: Arc::new(FontRegistry::new()),
13458                image_registry: Arc::new(ImageRegistry::new()),
13459                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
13460            },
13461            &mut text_engine,
13462            &mut compositor,
13463        )
13464        .unwrap_err();
13465
13466        assert!(
13467            error
13468                .to_string()
13469                .contains("image handle 88 is not registered")
13470        );
13471    }
13472
13473    #[test]
13474    fn renderer_feather_width_is_configurable() {
13475        let mut renderer = WgpuRenderer::new().with_feather_width(2.5);
13476
13477        assert_eq!(renderer.feather_width(), 2.5);
13478        assert!(!renderer.feathering_enabled());
13479
13480        renderer.set_feathering_enabled(true);
13481
13482        assert!(renderer.feathering_enabled());
13483
13484        renderer.set_feather_width(-3.0);
13485
13486        assert_eq!(renderer.feather_width(), 0.0);
13487
13488        renderer.set_feathering_enabled(false);
13489
13490        assert!(!renderer.feathering_enabled());
13491    }
13492
13493    /// Minimal RGBA8 PNG encoder using a single zlib "stored" (uncompressed) block, so the
13494    /// capture test can persist a screenshot without pulling in an image/png dependency.
13495    fn encode_png_rgba8(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
13496        fn crc32(bytes: &[u8]) -> u32 {
13497            let mut crc: u32 = 0xFFFF_FFFF;
13498            for &byte in bytes {
13499                crc ^= byte as u32;
13500                for _ in 0..8 {
13501                    let mask = (crc & 1).wrapping_neg();
13502                    crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
13503                }
13504            }
13505            !crc
13506        }
13507
13508        fn adler32(bytes: &[u8]) -> u32 {
13509            let mut a: u32 = 1;
13510            let mut b: u32 = 0;
13511            for &byte in bytes {
13512                a = (a + byte as u32) % 65521;
13513                b = (b + a) % 65521;
13514            }
13515            (b << 16) | a
13516        }
13517
13518        fn write_chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
13519            out.extend_from_slice(&(data.len() as u32).to_be_bytes());
13520            let mut crc_input = Vec::with_capacity(4 + data.len());
13521            crc_input.extend_from_slice(kind);
13522            crc_input.extend_from_slice(data);
13523            out.extend_from_slice(&crc_input);
13524            out.extend_from_slice(&crc32(&crc_input).to_be_bytes());
13525        }
13526
13527        // Raw image data: one filter byte (0 = None) per scanline, then RGBA pixels.
13528        let stride = width as usize * 4;
13529        let mut raw = Vec::with_capacity((stride + 1) * height as usize);
13530        for row in 0..height as usize {
13531            raw.push(0);
13532            raw.extend_from_slice(&rgba[row * stride..(row + 1) * stride]);
13533        }
13534
13535        // zlib stream: 0x78 0x01 header, stored deflate blocks, adler32 trailer.
13536        let mut zlib = vec![0x78, 0x01];
13537        let mut offset = 0;
13538        while offset < raw.len() {
13539            let block = (raw.len() - offset).min(0xFFFF);
13540            let last = offset + block >= raw.len();
13541            zlib.push(if last { 1 } else { 0 });
13542            zlib.extend_from_slice(&(block as u16).to_le_bytes());
13543            zlib.extend_from_slice(&(!(block as u16)).to_le_bytes());
13544            zlib.extend_from_slice(&raw[offset..offset + block]);
13545            offset += block;
13546        }
13547        zlib.extend_from_slice(&adler32(&raw).to_be_bytes());
13548
13549        let mut png = Vec::new();
13550        png.extend_from_slice(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]);
13551        let mut ihdr = Vec::with_capacity(13);
13552        ihdr.extend_from_slice(&width.to_be_bytes());
13553        ihdr.extend_from_slice(&height.to_be_bytes());
13554        ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); // bit depth 8, color type 6 (RGBA)
13555        write_chunk(&mut png, b"IHDR", &ihdr);
13556        write_chunk(&mut png, b"IDAT", &zlib);
13557        write_chunk(&mut png, b"IEND", &[]);
13558        png
13559    }
13560
13561    #[test]
13562    fn rounded_rect_primitives_render_to_png_capture() {
13563        // Exercises the new rounded-rect (per-corner radii + border + soft shadow) and the
13564        // linear-gradient brush end to end: build a scene, render headless, persist a PNG.
13565        let window_id = WindowId::new(4242);
13566        let viewport = Size::new(320.0, 240.0);
13567
13568        let mut scene = Scene::new();
13569        scene.push(SceneCommand::Clear(Color::rgba(0.12, 0.13, 0.16, 1.0)));
13570
13571        // A shadowed, bordered rounded card inside a larger clip. The clip is wide enough
13572        // that the soft shadow remains visible around the card.
13573        scene.push(SceneCommand::PushClip {
13574            rect: Rect::new(16.0, 16.0, 180.0, 150.0),
13575        });
13576        scene.push(SceneCommand::FillRoundedRect {
13577            rect: Rect::new(40.0, 44.0, 120.0, 84.0),
13578            radii: [16.0; 4],
13579            brush: Brush::Solid(Color::rgba(0.20, 0.55, 0.95, 1.0)),
13580            border: Some(Border {
13581                width: 3.0,
13582                color: Color::rgba(0.95, 0.97, 1.0, 1.0),
13583            }),
13584            shadow: Some(ShadowParams {
13585                offset_x: 0.0,
13586                offset_y: 6.0,
13587                blur: 8.0,
13588                spread: 1.0,
13589                color: Color::rgba(0.0, 0.0, 0.0, 0.55),
13590            }),
13591        });
13592        scene.push(SceneCommand::PopClip);
13593
13594        // A per-corner-radii rounded rect (sharp tl/br, round tr/bl).
13595        scene.push(SceneCommand::FillRoundedRect {
13596            rect: Rect::new(210.0, 30.0, 90.0, 70.0),
13597            radii: [2.0, 20.0, 2.0, 20.0],
13598            brush: Brush::Solid(Color::rgba(0.95, 0.45, 0.30, 1.0)),
13599            border: None,
13600            shadow: None,
13601        });
13602
13603        // A horizontal linear-gradient rounded rect.
13604        scene.push(SceneCommand::FillRoundedRect {
13605            rect: Rect::new(40.0, 160.0, 240.0, 56.0),
13606            radii: [10.0; 4],
13607            brush: Brush::LinearGradient {
13608                start: Point::new(40.0, 188.0),
13609                end: Point::new(280.0, 188.0),
13610                stops: vec![
13611                    GradientStop {
13612                        offset: 0.0,
13613                        color: Color::rgba(0.10, 0.80, 0.55, 1.0),
13614                    },
13615                    GradientStop {
13616                        offset: 1.0,
13617                        color: Color::rgba(0.55, 0.20, 0.85, 1.0),
13618                    },
13619                ],
13620            },
13621            border: None,
13622            shadow: None,
13623        });
13624
13625        let frame = SceneFrame {
13626            window_id,
13627            viewport,
13628            surface_size: viewport,
13629            scale_factor: 1.0,
13630            dirty_regions: Vec::new(),
13631            layer_updates: Vec::new(),
13632            scene,
13633            font_registry: Arc::new(FontRegistry::new()),
13634            image_registry: Arc::new(ImageRegistry::new()),
13635            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
13636        };
13637
13638        let mut renderer = WgpuRenderer::new();
13639        renderer
13640            .render(&frame)
13641            .expect("headless render of rounded-rect primitives should succeed");
13642
13643        let image = renderer
13644            .capture_last_frame_rgba(window_id)
13645            .expect("capture of rendered frame should succeed");
13646
13647        // The frame must contain visibly painted content (the clear color is opaque, so we
13648        // additionally check that some pixels differ from the background).
13649        let bg = [
13650            (0.12_f32.powf(1.0 / 2.2) * 255.0) as u8,
13651            (0.13_f32.powf(1.0 / 2.2) * 255.0) as u8,
13652            (0.16_f32.powf(1.0 / 2.2) * 255.0) as u8,
13653        ];
13654        let non_background = image.pixels().chunks_exact(4).any(|pixel| {
13655            (pixel[0] as i32 - bg[0] as i32).abs()
13656                + (pixel[1] as i32 - bg[1] as i32).abs()
13657                + (pixel[2] as i32 - bg[2] as i32).abs()
13658                > 24
13659        });
13660        assert!(
13661            non_background,
13662            "rendered frame should contain the painted primitives"
13663        );
13664
13665        let png = encode_png_rgba8(image.width(), image.height(), image.pixels());
13666        let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
13667        path.push("../../target");
13668        let _ = std::fs::create_dir_all(&path);
13669        path.push("rounded_rect_primitives_capture.png");
13670        std::fs::write(&path, &png).expect("writing capture PNG should succeed");
13671        eprintln!("wrote capture PNG to {}", path.display());
13672    }
13673
13674    /// Diagnostic microbenchmark for text policy cache behavior. It measures CPU-side scene
13675    /// preparation through the real text engine and reports cache behavior across coverage,
13676    /// color, LCD, and unsafe-LCD fallback scenarios. Run with `--ignored --nocapture`.
13677    #[test]
13678    #[ignore = "diagnostic benchmark for text render policy cache and atlas behavior"]
13679    fn text_render_policy_cache_benchmark() {
13680        let handle = FontHandle::new(7101);
13681        let mut fonts = FontRegistry::new();
13682        fonts.insert(handle, load_test_font());
13683        let fonts = Arc::new(fonts);
13684        let images = Arc::new(ImageRegistry::new());
13685        let layouts = Arc::new(TextLayoutRegistry::default());
13686        let viewport = Size::new(640.0, 760.0);
13687
13688        let frame = |window_id: u64,
13689                     policy: TextRenderPolicy,
13690                     color: Color,
13691                     transform: Option<Transform>|
13692         -> SceneFrame {
13693            let mut scene = Scene::new();
13694            scene.push(SceneCommand::PushTextRenderPolicy { policy });
13695            if let Some(transform) = transform {
13696                scene.push(SceneCommand::PushTransform { transform });
13697            }
13698            for row in 0..44 {
13699                scene.push(SceneCommand::DrawText(TextRun {
13700                    rect: Rect::new(18.0, 12.0 + row as f32 * 16.0, 600.0, 17.0),
13701                    text: format!(
13702                        "Atlas policy benchmark row {row:02}: minimum ill glyphs 1234567890"
13703                    ),
13704                    style: TextStyle {
13705                        font: Some(handle),
13706                        font_size: 12.0,
13707                        line_height: 16.0,
13708                        color,
13709                        ..TextStyle::default()
13710                    },
13711                }));
13712            }
13713            if transform.is_some() {
13714                scene.push(SceneCommand::PopTransform);
13715            }
13716            scene.push(SceneCommand::PopTextRenderPolicy);
13717            SceneFrame {
13718                window_id: WindowId::new(window_id),
13719                viewport,
13720                surface_size: viewport,
13721                scale_factor: 1.0,
13722                dirty_regions: Vec::new(),
13723                layer_updates: Vec::new(),
13724                scene,
13725                font_registry: Arc::clone(&fonts),
13726                image_registry: Arc::clone(&images),
13727                text_layout_registry: Arc::clone(&layouts),
13728            }
13729        };
13730
13731        let scenarios = [
13732            (
13733                "grayscale-perceptual",
13734                frame(
13735                    7201,
13736                    TextRenderPolicy::new()
13737                        .with_coverage_policy(TextRenderCoveragePolicy::Perceptual),
13738                    Color::rgba(0.08, 0.10, 0.14, 1.0),
13739                    None,
13740                ),
13741            ),
13742            (
13743                "coverage-linear",
13744                frame(
13745                    7202,
13746                    TextRenderPolicy::new().with_coverage_policy(TextRenderCoveragePolicy::Linear),
13747                    Color::rgba(0.08, 0.10, 0.14, 1.0),
13748                    None,
13749                ),
13750            ),
13751            (
13752                "coverage-boost",
13753                frame(
13754                    7203,
13755                    TextRenderPolicy::new()
13756                        .with_coverage_policy(TextRenderCoveragePolicy::CoverageBoost(0.55)),
13757                    Color::rgba(0.08, 0.10, 0.14, 1.0),
13758                    None,
13759                ),
13760            ),
13761            (
13762                "coverage-gamma",
13763                frame(
13764                    7204,
13765                    TextRenderPolicy::new()
13766                        .with_coverage_policy(TextRenderCoveragePolicy::Gamma(1.8)),
13767                    Color::rgba(0.08, 0.10, 0.14, 1.0),
13768                    None,
13769                ),
13770            ),
13771            (
13772                "color-churn-light",
13773                frame(
13774                    7205,
13775                    TextRenderPolicy::new()
13776                        .with_coverage_policy(TextRenderCoveragePolicy::Perceptual),
13777                    Color::rgba(0.88, 0.90, 0.94, 1.0),
13778                    None,
13779                ),
13780            ),
13781            (
13782                "lcd-rgb",
13783                frame(
13784                    7206,
13785                    TextRenderPolicy::new()
13786                        .with_render_mode(sui_scene::TextRenderMode::LcdSubpixel)
13787                        .with_subpixel_order(TextSubpixelOrder::Rgb)
13788                        .with_coverage_policy(TextRenderCoveragePolicy::Perceptual),
13789                    Color::rgba(0.08, 0.10, 0.14, 1.0),
13790                    None,
13791                ),
13792            ),
13793            (
13794                "grayscale-rotated",
13795                frame(
13796                    7207,
13797                    TextRenderPolicy::new()
13798                        .with_coverage_policy(TextRenderCoveragePolicy::Perceptual),
13799                    Color::rgba(0.08, 0.10, 0.14, 1.0),
13800                    Some(Transform::rotation(0.08)),
13801                ),
13802            ),
13803            (
13804                "unsafe-lcd-fallback",
13805                frame(
13806                    7208,
13807                    TextRenderPolicy::new()
13808                        .with_render_mode(sui_scene::TextRenderMode::LcdSubpixel)
13809                        .with_subpixel_order(TextSubpixelOrder::Rgb)
13810                        .with_coverage_policy(TextRenderCoveragePolicy::Perceptual),
13811                    Color::rgba(0.08, 0.10, 0.14, 1.0),
13812                    Some(Transform::rotation(0.08)),
13813                ),
13814            ),
13815        ];
13816
13817        let mut text_engine = TextEngine::new().expect("text engine should initialize");
13818        println!("\n=== Text Render Policy Cache Benchmark ===");
13819        for (name, frame) in scenarios {
13820            let before = text_engine.glyph_cache_stats();
13821            let first_start = std::time::Instant::now();
13822            let vertices = build_vertices(&frame, &mut text_engine)
13823                .expect("benchmark frame should build")
13824                .len();
13825            let first_us = first_start.elapsed().as_secs_f64() * 1_000_000.0;
13826            let after_first = text_engine.glyph_cache_stats();
13827
13828            let warm_repeats = 12usize;
13829            let warm_start = std::time::Instant::now();
13830            for _ in 0..warm_repeats {
13831                let _ = build_vertices(&frame, &mut text_engine)
13832                    .expect("warm benchmark frame should build");
13833            }
13834            let warm_avg_us =
13835                warm_start.elapsed().as_secs_f64() * 1_000_000.0 / warm_repeats as f64;
13836            let after_warm = text_engine.glyph_cache_stats();
13837
13838            println!(
13839                "{name:22} first={first_us:8.1}us warm_avg={warm_avg_us:8.1}us vertices={vertices:5} entries={} (+{}) hits=+{} misses=+{} first_misses=+{}",
13840                after_warm.0,
13841                after_warm.0.saturating_sub(before.0),
13842                after_warm.1.saturating_sub(before.1),
13843                after_warm.2.saturating_sub(before.2),
13844                after_first.2.saturating_sub(before.2),
13845            );
13846        }
13847        println!("==========================================\n");
13848    }
13849
13850    /// Renders a body-text + small-label sample across DPR, light/dark surfaces, and coverage
13851    /// policies. The validation reports core stem luma plus an edge-coverage ratio instead of raw
13852    /// pixel diffs, because small-text quality changes are perceptual and do not track total
13853    /// changed-pixel percentages well.
13854    #[test]
13855    fn text_coverage_quality_matrix_capture() {
13856        let handle = FontHandle::new(7001);
13857        let mut fonts = FontRegistry::new();
13858        fonts.insert(handle, load_test_font());
13859        let fonts = Arc::new(fonts);
13860
13861        // Body paragraph + a couple of small UI labels.
13862        let lines: [(&str, f32, f32); 5] = [
13863            ("The quick brown fox jumps over the lazy dog.", 20.0, 16.0),
13864            ("Pack my box with five dozen liquor jugs.", 20.0, 44.0),
13865            (
13866                "Body text at a typical reading size, 1234567890.",
13867                16.0,
13868                72.0,
13869            ),
13870            ("Small UI label", 12.0, 98.0),
13871            ("settings  ·  profile  ·  sign out", 11.0, 118.0),
13872        ];
13873
13874        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
13875        enum MatrixPolicy {
13876            Linear,
13877            Perceptual,
13878            LcdRgb,
13879        }
13880
13881        impl MatrixPolicy {
13882            fn name(self) -> &'static str {
13883                match self {
13884                    Self::Linear => "linear",
13885                    Self::Perceptual => "perceptual",
13886                    Self::LcdRgb => "lcd-rgb",
13887                }
13888            }
13889
13890            fn configure(self, renderer: &mut WgpuRenderer) {
13891                match self {
13892                    Self::Linear => {
13893                        renderer.set_text_render_mode(TextRenderMode::Grayscale);
13894                        renderer.set_text_subpixel_order(TextSubpixelOrder::None);
13895                        renderer.set_text_coverage_policy(TextCoveragePolicy::Linear);
13896                    }
13897                    Self::Perceptual => {
13898                        renderer.set_text_render_mode(TextRenderMode::Grayscale);
13899                        renderer.set_text_subpixel_order(TextSubpixelOrder::None);
13900                        renderer.set_text_coverage_policy(TextCoveragePolicy::Perceptual);
13901                    }
13902                    Self::LcdRgb => {
13903                        renderer.set_text_render_mode(TextRenderMode::LcdSubpixel);
13904                        renderer.set_text_subpixel_order(TextSubpixelOrder::Rgb);
13905                        renderer.set_text_coverage_policy(TextCoveragePolicy::Perceptual);
13906                    }
13907                }
13908            }
13909        }
13910
13911        let render_sample = |policy: MatrixPolicy, scale: f32, bg: Color, fg: Color| -> RgbaImage {
13912            let policy_id = match policy {
13913                MatrixPolicy::Linear => 1,
13914                MatrixPolicy::Perceptual => 2,
13915                MatrixPolicy::LcdRgb => 3,
13916            };
13917            let window_id = WindowId::new(7100 + policy_id + (scale * 10.0) as u64);
13918            let viewport = Size::new(420.0, 140.0);
13919            let mut scene = Scene::new();
13920            scene.push(SceneCommand::Clear(bg));
13921            for (text, size, y) in lines {
13922                scene.push(SceneCommand::DrawText(TextRun {
13923                    rect: Rect::new(12.0, y, 400.0, size + 8.0),
13924                    text: text.to_string(),
13925                    style: TextStyle {
13926                        font: Some(handle),
13927                        font_size: size,
13928                        line_height: size + 6.0,
13929                        color: fg,
13930                        ..TextStyle::default()
13931                    },
13932                }));
13933            }
13934            let frame = SceneFrame {
13935                window_id,
13936                viewport,
13937                surface_size: Size::new(viewport.width * scale, viewport.height * scale),
13938                scale_factor: scale,
13939                dirty_regions: Vec::new(),
13940                layer_updates: Vec::new(),
13941                scene,
13942                font_registry: Arc::clone(&fonts),
13943                image_registry: Arc::new(ImageRegistry::new()),
13944                text_layout_registry: Arc::new(TextLayoutRegistry::default()),
13945            };
13946            let mut renderer = WgpuRenderer::new();
13947            policy.configure(&mut renderer);
13948            renderer
13949                .render(&frame)
13950                .expect("headless text render should succeed");
13951            renderer
13952                .capture_last_frame_rgba(window_id)
13953                .expect("capture of rendered text frame should succeed")
13954        };
13955
13956        #[derive(Debug, Clone, Copy)]
13957        struct InkStats {
13958            mean_luma: f32,
13959            core_luma: f32,
13960            foreground_weight: f32,
13961            edge_ratio: f32,
13962            inked_pixels: u64,
13963        }
13964
13965        fn luma(rgb: [u8; 3]) -> f32 {
13966            0.2126 * rgb[0] as f32 + 0.7152 * rgb[1] as f32 + 0.0722 * rgb[2] as f32
13967        }
13968
13969        fn ink_stats(image: &RgbaImage, bg: [u8; 3], fg: [u8; 3], dark_text: bool) -> InkStats {
13970            let bg_luma = luma(bg);
13971            let fg_luma = luma(fg);
13972            let contrast = (fg_luma - bg_luma).abs().max(1.0);
13973            let mut lumas: Vec<f32> = Vec::new();
13974            let mut edge_pixels = 0u64;
13975            let mut core_pixels = 0u64;
13976            for px in image.pixels().chunks_exact(4) {
13977                let d = (px[0] as i32 - bg[0] as i32).abs()
13978                    + (px[1] as i32 - bg[1] as i32).abs()
13979                    + (px[2] as i32 - bg[2] as i32).abs();
13980                if d > 10 {
13981                    let pixel_luma = luma([px[0], px[1], px[2]]);
13982                    let coverage = ((pixel_luma - bg_luma).abs() / contrast).clamp(0.0, 1.0);
13983                    if coverage >= 0.85 {
13984                        core_pixels += 1;
13985                    } else if coverage >= 0.10 {
13986                        edge_pixels += 1;
13987                    }
13988                    lumas.push(pixel_luma);
13989                }
13990            }
13991            let count = lumas.len() as u64;
13992            if count == 0 {
13993                return InkStats {
13994                    mean_luma: 0.0,
13995                    core_luma: 0.0,
13996                    foreground_weight: 0.0,
13997                    edge_ratio: 0.0,
13998                    inked_pixels: 0,
13999                };
14000            }
14001            let mean = lumas.iter().sum::<f32>() / count as f32;
14002            if dark_text {
14003                lumas.sort_by(|a, b| a.partial_cmp(b).unwrap());
14004            } else {
14005                lumas.sort_by(|a, b| b.partial_cmp(a).unwrap());
14006            }
14007            let q = (lumas.len() / 4).max(1);
14008            let core = lumas[..q].iter().sum::<f32>() / q as f32;
14009            let foreground_weight = if dark_text {
14010                bg_luma - core
14011            } else {
14012                core - bg_luma
14013            };
14014            InkStats {
14015                mean_luma: mean,
14016                core_luma: core,
14017                foreground_weight,
14018                edge_ratio: edge_pixels as f32 / core_pixels.max(1) as f32,
14019                inked_pixels: count,
14020            }
14021        }
14022
14023        let light_bg = Color::rgba(0.98, 0.98, 0.99, 1.0);
14024        let dark_bg = Color::rgba(0.08, 0.09, 0.11, 1.0);
14025        let light_bg8 = [250u8, 250, 252];
14026        let dark_bg8 = [22u8, 24, 28];
14027        let light_fg = Color::rgba(0.05, 0.05, 0.06, 1.0);
14028        let dark_fg = Color::rgba(0.95, 0.95, 0.96, 1.0);
14029        let light_fg8 = [13u8, 13, 15];
14030        let dark_fg8 = [242u8, 242, 245];
14031        let policies = [
14032            MatrixPolicy::Linear,
14033            MatrixPolicy::Perceptual,
14034            MatrixPolicy::LcdRgb,
14035        ];
14036        let scales = [1.0f32, 1.5, 2.0];
14037        let mut write_dir = None;
14038        if std::env::var_os("SUI_TEXT_COVERAGE_WRITE_PNGS").is_some() {
14039            let mut dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
14040            dir.push("../../target/text-coverage-matrix");
14041            std::fs::create_dir_all(&dir).expect("creating text coverage capture dir should work");
14042            write_dir = Some(dir);
14043        }
14044
14045        for scale in scales {
14046            let mut linear_light_weight = None;
14047            let mut perceptual_light_weight = None;
14048            let mut linear_dark_weight = None;
14049            let mut perceptual_dark_weight = None;
14050
14051            for policy in policies {
14052                let light = render_sample(policy, scale, light_bg, light_fg);
14053                let dark = render_sample(policy, scale, dark_bg, dark_fg);
14054                let light_stats = ink_stats(&light, light_bg8, light_fg8, true);
14055                let dark_stats = ink_stats(&dark, dark_bg8, dark_fg8, false);
14056                assert!(light_stats.inked_pixels > 200);
14057                assert!(dark_stats.inked_pixels > 200);
14058                assert!(light_stats.edge_ratio.is_finite());
14059                assert!(dark_stats.edge_ratio.is_finite());
14060
14061                eprintln!(
14062                    "[text-quality {policy} @{scale:.1}x light] mean={:.1} core={:.1} weight={:.1} edge/core={:.2} n={}",
14063                    light_stats.mean_luma,
14064                    light_stats.core_luma,
14065                    light_stats.foreground_weight,
14066                    light_stats.edge_ratio,
14067                    light_stats.inked_pixels,
14068                    policy = policy.name(),
14069                );
14070                eprintln!(
14071                    "[text-quality {policy} @{scale:.1}x dark] mean={:.1} core={:.1} weight={:.1} edge/core={:.2} n={}",
14072                    dark_stats.mean_luma,
14073                    dark_stats.core_luma,
14074                    dark_stats.foreground_weight,
14075                    dark_stats.edge_ratio,
14076                    dark_stats.inked_pixels,
14077                    policy = policy.name(),
14078                );
14079
14080                match policy {
14081                    MatrixPolicy::Linear => {
14082                        linear_light_weight = Some(light_stats.foreground_weight);
14083                        linear_dark_weight = Some(dark_stats.foreground_weight);
14084                    }
14085                    MatrixPolicy::Perceptual => {
14086                        perceptual_light_weight = Some(light_stats.foreground_weight);
14087                        perceptual_dark_weight = Some(dark_stats.foreground_weight);
14088                    }
14089                    MatrixPolicy::LcdRgb => {}
14090                }
14091
14092                if let Some(dir) = write_dir.as_ref() {
14093                    for (image, surface) in [(&light, "light"), (&dark, "dark")] {
14094                        let png = encode_png_rgba8(image.width(), image.height(), image.pixels());
14095                        let mut path = dir.clone();
14096                        path.push(format!("text-{surface}-{}-{scale:.1}x.png", policy.name()));
14097                        std::fs::write(&path, &png)
14098                            .expect("writing text capture PNG should succeed");
14099                    }
14100                }
14101            }
14102
14103            assert!(
14104                perceptual_light_weight.expect("perceptual light stats")
14105                    >= linear_light_weight.expect("linear light stats") * 0.98
14106            );
14107            assert!(
14108                perceptual_dark_weight.expect("perceptual dark stats")
14109                    >= linear_dark_weight.expect("linear dark stats") * 0.98
14110            );
14111        }
14112    }
14113}