Skip to main content

gpui/
scene.rs

1// todo("windows"): remove
2#![cfg_attr(windows, allow(dead_code))]
3
4#[cfg(feature = "schemars")]
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7
8use crate::{
9    AtlasTextureId, AtlasTile, Background, Bounds, ContentMask, Corners, Edges, Hsla, Path,
10    PathTiles, Pixels, Point, Radians, ScaledPixels, Size, TimedTransformation,
11    bounds_tree::BoundsTree, point, px,
12};
13use smallvec::SmallVec;
14use std::{
15    collections::{HashMap, VecDeque},
16    fmt::Debug,
17    iter::Peekable,
18    mem,
19    ops::Range,
20    rc::Rc,
21    slice,
22    time::Duration,
23};
24
25#[expect(missing_docs)]
26pub type DrawOrder = u32;
27
28/// A boolean stored as a `u32` so that GPU-facing structs contain no
29/// compiler-inserted padding bytes, which would be undefined behavior to
30/// reinterpret as `&[u8]` when writing instance buffers. Guaranteed to be
31/// `0` or `1` by construction; shaders read it as a `u32`/`uint`.
32#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
33#[repr(transparent)]
34pub struct PaddedBool32(u32);
35
36impl From<bool> for PaddedBool32 {
37    fn from(value: bool) -> Self {
38        PaddedBool32(value as u32)
39    }
40}
41
42impl PaddedBool32 {
43    /// The wrapped boolean.
44    pub fn as_bool(self) -> bool {
45        self.0 != 0
46    }
47}
48
49struct Layer {
50    primitives: SmallVec<[Range<usize>; 1]>,
51    /// vue-native fork: the indices into [`Scene::vn_layers`] of the
52    /// composites closed inside this layer, which take its order.
53    vn_composites: Vec<usize>,
54    bounds: Bounds<ScaledPixels>,
55    max_kind: PrimitiveKind,
56    max_shared_kind: PrimitiveKind,
57}
58
59impl Layer {
60    fn new() -> Self {
61        Self {
62            primitives: SmallVec::new(),
63            vn_composites: Vec::new(),
64            bounds: Bounds::default(),
65            max_kind: PrimitiveKind::Shadow,
66            max_shared_kind: PrimitiveKind::VnLayer,
67        }
68    }
69}
70
71#[derive(Default)]
72#[expect(missing_docs)]
73pub struct Scene {
74    pub(crate) paint_operations: Vec<PaintOperation>,
75    primitive_bounds: BoundsTree<ScaledPixels>,
76    layer_stack: Vec<usize>,
77    layers: VecDeque<Layer>,
78    pub shadows: Vec<Shadow>,
79    pub quads: Vec<Quad>,
80    pub backdrop_blur_rects: Vec<BackdropBlurRect>,
81    pub effect_quads: Vec<EffectQuad>,
82    /// vue-native fork: the images effect quads sample; [`EffectQuad::texture_set`]
83    /// indexes it.
84    pub effect_texture_sets: Vec<std::sync::Arc<crate::EffectTextureSet>>,
85    effect_texture_set_index: HashMap<crate::EffectTextureKey, usize>,
86    pub paths: Vec<PaintedPath>,
87    pub underlines: Vec<Underline>,
88    pub monochrome_sprites: Vec<MonochromeSprite>,
89    pub subpixel_sprites: Vec<SubpixelSprite>,
90    pub polychrome_sprites: Vec<PolychromeSprite>,
91    pub surfaces: Vec<PaintSurface>,
92    /// vue-native fork: the composites of isolated layers
93    /// ([`Scene::vn_push_isolation`]), each drawing one group through its clip
94    /// shape. After [`Scene::finish`] every vector above holds the root group
95    /// first and then each isolated group's, in [`Scene::vn_group_ranges`].
96    pub vn_layers: Vec<VnLayer>,
97    /// vue-native fork: beside each of [`Scene::vn_layers`], the effects that
98    /// composite it instead of its clip shape.
99    pub vn_layer_effects: Vec<Option<VnEffectLayer>>,
100    /// vue-native fork: the quads every [`VnEffectLayer`] draws, in no group's
101    /// order (a layer names its run).
102    pub vn_effect_draws: Vec<VnEffectDraw>,
103    /// vue-native fork: every isolated layer's clip edges, `[x0, y0, x1, y1]`
104    /// in device pixels; a [`VnLayer`] names its run.
105    pub vn_clip_segments: Vec<[f32; 4]>,
106    /// Gradient stacks used by text-mask composites, shared across source groups.
107    pub vn_text_backgrounds: Vec<VnTextBackground>,
108    /// vue-native fork: the groups still open, innermost last, each holding
109    /// the lists of the group around it while it paints.
110    vn_open: Vec<VnOpenGroup>,
111    /// vue-native fork: the closed groups, until `finish` appends them.
112    vn_groups: Vec<VnGroupLists>,
113    // Reopened deferred descendants append to one source before the matrix
114    // runs. Filtering separately changes translucent colors in linear RGB.
115    vn_color_groups: HashMap<(u8, u64, usize), usize>,
116    vn_contexts: HashMap<(usize, VnIsolationIdentity), usize>,
117    /// vue-native fork: where each group's primitives are after `finish`:
118    /// the root at 0, then the groups a [`VnLayer::group`] names.
119    vn_group_ranges: Vec<VnGroupRanges>,
120    /// vue-native fork: the groups painted for [`VnIsolation::capture`],
121    /// which the renderer draws first and keeps as snapshots.
122    pub vn_captures: Vec<VnCapture>,
123    animations: Vec<SpriteAnimation>,
124}
125
126/// vue-native fork: what a captured group knows of the element it holds.
127#[derive(Clone, Copy, Debug, PartialEq)]
128pub struct VnCaptureInfo {
129    /// The snapshot this capture writes.
130    pub id: u64,
131    /// The element's border box in device pixels, as painted inside the
132    /// capture (untransformed).
133    pub border_box: Bounds<ScaledPixels>,
134    /// The device-space transform the element had on the page, its own
135    /// included.
136    pub transform: TransformationMatrix,
137}
138
139/// vue-native fork: one capture of a finished scene. The renderer draws
140/// `group` into a cleared target and keeps the `ink` rectangle of it as the
141/// snapshot `info.id`.
142#[derive(Clone, Copy, Debug)]
143#[allow(missing_docs)]
144pub struct VnCapture {
145    pub info: VnCaptureInfo,
146    pub group: u32,
147    /// Device pixels the group painted, whole pixels; empty when nothing.
148    pub ink: Bounds<ScaledPixels>,
149}
150
151/// vue-native fork: [`VnLayer::flags`].
152pub mod vn_layer_flags {
153    /// The source is the snapshot [`super::VnLayer::snapshot`], not a group.
154    pub const SNAPSHOT: u32 = 1;
155    /// Composited with `plus-lighter` (both factors one) instead of
156    /// source-over.
157    pub const PLUS_LIGHTER: u32 = 2;
158    /// Drawn where the capture was taken; [`super::Scene::vn_resolve_snapshots`]
159    /// clears it, so no renderer sees it.
160    pub const IN_PLACE: u32 = 4;
161}
162
163/// vue-native fork: an isolated layer as it is opened: the clip it composites
164/// through, in window device pixels, and the content mask around it.
165#[derive(Clone, Debug)]
166pub struct VnIsolation {
167    /// The clip shape.
168    pub geometry: std::sync::Arc<crate::VnClipGeometry>,
169    /// A transform over the isolated source pixels before composition.
170    pub color_matrix: Option<crate::VnColorMatrix>,
171    /// A text-only alpha source, filled by this background stack.
172    pub text_paint: Option<std::sync::Arc<crate::VnTextPaint>>,
173    /// The content mask in force where the layer was opened; it cuts the
174    /// composite as it cuts any primitive.
175    pub content_mask: ContentMask<ScaledPixels>,
176    /// A captured group: it composites nowhere, the renderer keeps it as a
177    /// snapshot ([`Scene::vn_captures`]).
178    pub capture: Option<VnCaptureInfo>,
179}
180
181impl VnIsolation {
182    fn shared_key(&self, parent_context: usize) -> Option<(u8, u64, usize)> {
183        if let Some(capture) = &self.capture {
184            return Some((2, capture.id, 0));
185        }
186        if let Some(text) = &self.text_paint {
187            return Some((1, text.fill.group_id, parent_context));
188        }
189        self.color_matrix.and_then(|matrix| (matrix.group_id != 0).then_some((0, matrix.group_id, 0)))
190    }
191
192    fn identity(&self) -> VnIsolationIdentity {
193        if let Some(capture) = &self.capture { return VnIsolationIdentity::Capture(capture.id); }
194        if let Some(text) = &self.text_paint { return VnIsolationIdentity::Text(text.fill.group_id); }
195        if let Some(matrix) = self.color_matrix.filter(|matrix| matrix.group_id != 0) {
196            return VnIsolationIdentity::Matrix(matrix.group_id);
197        }
198        VnIsolationIdentity::Clip(std::sync::Arc::as_ptr(&self.geometry) as usize)
199    }
200}
201
202/// One text background and its positioning space. GPU layout matches HLSL.
203#[derive(Clone, Copy, Debug)]
204#[repr(C)]
205pub struct VnTextBackground {
206    /// Gradient/solid and its CSS size, position and repeat settings.
207    pub background: Background,
208    /// Logical CSS background box (not device-scaled).
209    pub bounds: Bounds<ScaledPixels>,
210    /// Device-space inverse transform.
211    pub inverse: TransformationMatrix,
212    /// Device pixels per CSS pixel.
213    pub scale_factor: f32,
214    /// Explicit tail padding, initialized before GPU upload.
215    pub pad: f32,
216}
217
218/// vue-native fork: the composite of one isolated layer. The renderer draws
219/// group `group` into an offscreen target the size of the window, then
220/// composites it over its parent's, multiplied by the coverage of the
221/// segments `segment_start..segment_start + segment_count` of
222/// [`Scene::vn_clip_segments`] under `fill_rule` (bit 0: 0 nonzero, 1
223/// evenodd), and by the content mask. Bits 1–2 of `fill_rule` name a mask
224/// ([`Scene::vn_begin_mask`]): 1 multiplies by the alpha, 2 by the luminance
225/// of group `group + 1`, which the renderer draws into a target of its own.
226///
227/// A snapshot composite ([`vn_layer_flags::SNAPSHOT`]) samples the snapshot
228/// instead: each device pixel maps through `source_transform` into the
229/// capture's device space, where the snapshot covers `source_rect`.
230///
231/// Keep in sync with `struct VnLayer` in `gpui_windows/src/shaders.hlsl`
232/// (56 words); the renderer uploads this vector as it is.
233#[derive(Default, Debug, Copy, Clone)]
234#[repr(C)]
235#[allow(missing_docs)]
236pub struct VnLayer {
237    pub order: DrawOrder,
238    /// The group, an index into [`Scene::vn_group_ranges`] (never 0, the root).
239    pub group: u32,
240    pub segment_start: u32,
241    pub segment_count: u32,
242    pub fill_rule: u32,
243    pub pad: [u32; 3],
244    /// Four coefficient rows and the bias column, matching the shader.
245    pub color_matrix: [f32; 20],
246    /// The device pixels the composite covers: the shape's box, out to whole
247    /// pixels and one more for the antialiased edge, cut by the mask.
248    pub bounds: Bounds<ScaledPixels>,
249    pub content_mask: ContentMask<ScaledPixels>,
250    /// The snapshot id, low and high words.
251    pub snapshot: [u32; 2],
252    /// [`vn_layer_flags`].
253    pub flags: u32,
254    pub opacity: f32,
255    /// `[x, y, width, height]` of the snapshot in capture device pixels.
256    pub source_rect: [f32; 4],
257    /// Rows `[a, b, tx, _]` and `[c, d, ty, _]`: device pixel to capture
258    /// device pixel.
259    pub source_transform: [f32; 8],
260}
261
262impl VnLayer {
263    /// The snapshot a [`vn_layer_flags::SNAPSHOT`] composite samples.
264    pub fn snapshot_id(&self) -> Option<u64> {
265        (self.flags & vn_layer_flags::SNAPSHOT != 0)
266            .then(|| self.snapshot[0] as u64 | (self.snapshot[1] as u64) << 32)
267    }
268}
269
270/// vue-native fork: a snapshot drawn into a box ([`Scene::vn_insert_snapshot`]).
271#[derive(Clone, Copy, Debug)]
272#[allow(missing_docs)]
273pub struct VnSnapshotPaint {
274    pub id: u64,
275    /// Device pixel to the box's unit square, `[a, b, tx, c, d, ty]`;
276    /// [`Scene::vn_resolve_snapshots`] maps the square onto the capture's
277    /// border box.
278    pub to_unit: [f32; 6],
279    /// The device pixels the box covers.
280    pub bounds: Bounds<ScaledPixels>,
281    pub content_mask: ContentMask<ScaledPixels>,
282    pub opacity: f32,
283    pub plus_lighter: bool,
284    /// Where the capture was taken, ignoring `to_unit`.
285    pub in_place: bool,
286}
287
288/// vue-native fork: one `--shading` quad of a [`VnEffectLayer`], with the key
289/// of its history (0 for none).
290#[derive(Clone, Debug)]
291#[allow(missing_docs)]
292pub struct VnEffectDraw {
293    pub quad: EffectQuad,
294    pub history: u64,
295    /// The images the quad samples; in [`Scene::vn_effect_draws`] they are
296    /// interned like a primitive's ([`EffectQuad::texture_set`]) and this is None.
297    pub textures: Option<std::sync::Arc<crate::EffectTextureSet>>,
298}
299
300/// vue-native fork: a [`VnLayer`] composited by its [`Scene::vn_effect_draws`]
301/// in order, each reading the layer's group (none when it is 0) as content.
302#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
303#[allow(missing_docs)]
304pub struct VnEffectLayer {
305    pub start: u32,
306    pub count: u32,
307}
308
309impl VnEffectLayer {
310    /// The indices of its draws in [`Scene::vn_effect_draws`].
311    pub fn draws(&self) -> Range<usize> {
312        self.start as usize..(self.start + self.count) as usize
313    }
314}
315
316/// vue-native fork: what [`Scene::vn_push_effect`] opens: the quads that
317/// composite what is painted until the matching [`Scene::vn_pop_isolation`].
318#[derive(Clone, Debug)]
319#[allow(missing_docs)]
320pub struct VnEffectPaint {
321    pub draws: Vec<VnEffectDraw>,
322    /// Whether the draws read what is painted inside; without, nothing is.
323    pub content: bool,
324    pub content_mask: ContentMask<ScaledPixels>,
325}
326
327/// vue-native fork: what the renderer iterates for one group: runs of
328/// primitives as before, and runs of [`VnLayer`] composites.
329#[derive(Debug)]
330pub enum VnBatch {
331    /// Primitives drawn into the group's target.
332    Primitives(PrimitiveBatch),
333    /// The composites `range` of [`Scene::vn_layers`], in order.
334    Layers(Range<usize>),
335}
336
337/// vue-native fork: one group's primitives in each of the scene's vectors.
338#[derive(Clone, Debug, Default)]
339pub struct VnGroupRanges {
340    shadows: Range<usize>,
341    quads: Range<usize>,
342    backdrop_blur_rects: Range<usize>,
343    effect_quads: Range<usize>,
344    paths: Range<usize>,
345    underlines: Range<usize>,
346    monochrome_sprites: Range<usize>,
347    subpixel_sprites: Range<usize>,
348    polychrome_sprites: Range<usize>,
349    surfaces: Range<usize>,
350    vn_layers: Range<usize>,
351}
352
353/// vue-native fork: everything a group gathers while it paints. The scene's
354/// own fields are the open group's; opening another swaps them out.
355#[derive(Default)]
356struct VnGroupLists {
357    primitive_bounds: BoundsTree<ScaledPixels>,
358    layer_stack: Vec<usize>,
359    layers: VecDeque<Layer>,
360    shadows: Vec<Shadow>,
361    quads: Vec<Quad>,
362    backdrop_blur_rects: Vec<BackdropBlurRect>,
363    effect_quads: Vec<EffectQuad>,
364    paths: Vec<PaintedPath>,
365    underlines: Vec<Underline>,
366    monochrome_sprites: Vec<MonochromeSprite>,
367    subpixel_sprites: Vec<SubpixelSprite>,
368    polychrome_sprites: Vec<PolychromeSprite>,
369    surfaces: Vec<PaintSurface>,
370    vn_layers: Vec<VnLayer>,
371    vn_layer_effects: Vec<Option<VnEffectLayer>>,
372}
373
374impl VnGroupLists {
375    fn is_empty(&self) -> bool {
376        self.shadows.is_empty()
377            && self.quads.is_empty()
378            && self.backdrop_blur_rects.is_empty()
379            && self.effect_quads.is_empty()
380            && self.paths.is_empty()
381            && self.underlines.is_empty()
382            && self.monochrome_sprites.is_empty()
383            && self.subpixel_sprites.is_empty()
384            && self.polychrome_sprites.is_empty()
385            && self.surfaces.is_empty()
386            && self.vn_layers.is_empty()
387    }
388
389    /// The device pixels everything in the group touches, before any clip of
390    /// a composite it holds.
391    fn ink(&self) -> Option<Bounds<ScaledPixels>> {
392        fn seen(
393            ink: &mut Option<Bounds<ScaledPixels>>,
394            bounds: Bounds<ScaledPixels>,
395            transform: Option<&TransformationMatrix>,
396            mask: &ContentMask<ScaledPixels>,
397        ) {
398            let bounds = match transform {
399                Some(matrix) if !matrix.is_unit() => transformed_bounds(bounds, *matrix),
400                _ => bounds,
401            }
402            .intersect(&mask.bounds);
403            if bounds.is_empty() {
404                return;
405            }
406            *ink = Some(ink.map_or(bounds, |ink| ink.union(&bounds)));
407        }
408        let mut ink = None;
409        for shadow in &self.shadows {
410            let spread = shadow.blur_radius * 2.;
411            let bounds = Bounds::from_corners(
412                point(shadow.bounds.origin.x - spread, shadow.bounds.origin.y - spread),
413                point(
414                    shadow.bounds.origin.x + shadow.bounds.size.width + spread,
415                    shadow.bounds.origin.y + shadow.bounds.size.height + spread,
416                ),
417            );
418            seen(&mut ink, bounds, Some(&shadow.transformation), &shadow.content_mask);
419        }
420        for quad in &self.quads {
421            seen(&mut ink, quad.bounds, Some(&quad.transformation), &quad.content_mask);
422        }
423        for rect in &self.backdrop_blur_rects {
424            seen(&mut ink, rect.bounds, None, &rect.content_mask);
425        }
426        for quad in &self.effect_quads {
427            seen(&mut ink, quad.bounds, None, &quad.content_mask);
428        }
429        for path in &self.paths {
430            seen(&mut ink, path.bounds, None, &path.paint.content_mask);
431        }
432        for underline in &self.underlines {
433            seen(&mut ink, underline.bounds, Some(&underline.transformation), &underline.content_mask);
434        }
435        for sprite in &self.monochrome_sprites {
436            seen(&mut ink, sprite.bounds, Some(&sprite.transformation), &sprite.content_mask);
437        }
438        for sprite in &self.subpixel_sprites {
439            seen(&mut ink, sprite.bounds, Some(&sprite.transformation), &sprite.content_mask);
440        }
441        for sprite in &self.polychrome_sprites {
442            seen(&mut ink, sprite.bounds, Some(&sprite.transformation), &sprite.content_mask);
443        }
444        for surface in &self.surfaces {
445            seen(&mut ink, surface.bounds, None, &surface.content_mask);
446        }
447        for layer in &self.vn_layers {
448            seen(&mut ink, layer.bounds, None, &layer.content_mask);
449        }
450        ink
451    }
452
453    /// The draw-order sort `Scene::finish` gives every group.
454    fn sort(&mut self) {
455        let keys = &mut Vec::new();
456        sort_in_place(&mut self.shadows, keys, |shadow| (shadow.order, 0));
457        sort_in_place(&mut self.quads, keys, |quad| (quad.order, 0));
458        sort_in_place(&mut self.backdrop_blur_rects, keys, |rect| (rect.order, 0));
459        // Secondary key `effect_id`: the batch iterator breaks a run when the
460        // id changes (each id is a different pipeline), so sorting by it keeps
461        // same-effect quads at the same draw order in ONE instanced draw. The
462        // texture set breaks a run the same way.
463        self.effect_quads.sort_by_key(|effect_quad| {
464            (
465                effect_quad.order,
466                effect_quad.effect_id,
467                effect_quad.texture_set(),
468            )
469        });
470        self.paths.sort_by_key(|path| path.order);
471        sort_in_place(&mut self.underlines, keys, |underline| (underline.order, 0));
472        sort_in_place(&mut self.monochrome_sprites, keys, |sprite| {
473            (sprite.order, sprite.tile.texture_id.index)
474        });
475        sort_in_place(&mut self.subpixel_sprites, keys, |sprite| {
476            (sprite.order, sprite.tile.texture_id.index)
477        });
478        sort_in_place(&mut self.polychrome_sprites, keys, |sprite| {
479            (sprite.order, sprite.tile.texture_id.index)
480        });
481        self.surfaces.sort_by_key(|surface| surface.order);
482        if self.vn_layer_effects.iter().any(Option::is_some) {
483            let mut layers: Vec<_> = mem::take(&mut self.vn_layers)
484                .into_iter()
485                .zip(mem::take(&mut self.vn_layer_effects))
486                .collect();
487            layers.sort_by_key(|(layer, _)| layer.order);
488            (self.vn_layers, self.vn_layer_effects) = layers.into_iter().unzip();
489        } else {
490            self.vn_layers.sort_by_key(|layer| layer.order);
491        }
492    }
493}
494
495#[derive(Clone, Copy, PartialEq, Eq, Hash)]
496enum VnIsolationIdentity {
497    Matrix(u64),
498    Text(u64),
499    Clip(usize),
500    Effect(usize),
501    Capture(u64),
502}
503
504struct VnOpenGroup {
505    /// The lists of the group around this one.
506    saved: VnGroupLists,
507    isolation: VnIsolation,
508    effect: Option<VnEffectPaint>,
509    existing_group: Option<usize>,
510    shared_key: Option<(u8, u64, usize)>,
511    context: usize,
512    /// Once the mask is painting: the group's own lists, and whether the mask
513    /// is luminance.
514    mask: Option<(VnGroupLists, bool)>,
515}
516
517#[expect(missing_docs)]
518impl Scene {
519    pub fn clear(&mut self) {
520        self.paint_operations.clear();
521        self.primitive_bounds.clear();
522        self.layer_stack.clear();
523        self.layers.clear();
524        self.paths.clear();
525        self.shadows.clear();
526        self.quads.clear();
527        self.backdrop_blur_rects.clear();
528        self.effect_quads.clear();
529        self.effect_texture_sets.clear();
530        self.effect_texture_set_index.clear();
531        self.underlines.clear();
532        self.monochrome_sprites.clear();
533        self.subpixel_sprites.clear();
534        self.polychrome_sprites.clear();
535        self.surfaces.clear();
536        self.vn_layers.clear();
537        self.vn_layer_effects.clear();
538        self.vn_effect_draws.clear();
539        self.vn_clip_segments.clear();
540        self.vn_text_backgrounds.clear();
541        self.vn_open.clear();
542        self.vn_groups.clear();
543        self.vn_color_groups.clear();
544        self.vn_contexts.clear();
545        self.vn_group_ranges.clear();
546        self.vn_captures.clear();
547        self.animations.clear();
548    }
549
550    /// vue-native fork: swaps the open group's lists with `lists`.
551    fn vn_swap_lists(&mut self, lists: &mut VnGroupLists) {
552        mem::swap(&mut self.primitive_bounds, &mut lists.primitive_bounds);
553        mem::swap(&mut self.layer_stack, &mut lists.layer_stack);
554        mem::swap(&mut self.layers, &mut lists.layers);
555        mem::swap(&mut self.shadows, &mut lists.shadows);
556        mem::swap(&mut self.quads, &mut lists.quads);
557        mem::swap(&mut self.backdrop_blur_rects, &mut lists.backdrop_blur_rects);
558        mem::swap(&mut self.effect_quads, &mut lists.effect_quads);
559        mem::swap(&mut self.paths, &mut lists.paths);
560        mem::swap(&mut self.underlines, &mut lists.underlines);
561        mem::swap(&mut self.monochrome_sprites, &mut lists.monochrome_sprites);
562        mem::swap(&mut self.subpixel_sprites, &mut lists.subpixel_sprites);
563        mem::swap(&mut self.polychrome_sprites, &mut lists.polychrome_sprites);
564        mem::swap(&mut self.surfaces, &mut lists.surfaces);
565        mem::swap(&mut self.vn_layers, &mut lists.vn_layers);
566        mem::swap(&mut self.vn_layer_effects, &mut lists.vn_layer_effects);
567    }
568
569    /// vue-native fork: opens an isolated layer. Every primitive inserted
570    /// until the matching [`Scene::vn_pop_isolation`] goes into a group of its
571    /// own, with its own draw orders: the renderer draws the group into an
572    /// offscreen target and composites it through `isolation`'s clip, at the
573    /// draw order the composite takes among its parent's primitives.
574    ///
575    /// The group is what CSS calls an isolated group: a backdrop filter in it
576    /// sees what the group painted under it, not the page (the element is a
577    /// Backdrop Root, Filter Effects 2 §3.1). The same group is where filters
578    /// on an element's own painting would apply.
579    pub fn vn_push_isolation(&mut self, isolation: VnIsolation) {
580        self.paint_operations
581            .push(PaintOperation::VnStartIsolation(isolation.clone()));
582        let mut saved = VnGroupLists::default();
583        self.vn_swap_lists(&mut saved);
584        let parent_context = self.vn_open.last().map_or(0, |group| group.context);
585        let shared_key = isolation.shared_key(parent_context);
586        let next_context = self.vn_contexts.len() + 1;
587        let context = *self.vn_contexts.entry((parent_context, isolation.identity())).or_insert(next_context);
588        let existing_group = shared_key.and_then(|key| self.vn_color_groups.get(&key).copied());
589        if let Some(index) = existing_group {
590            let mut source = mem::take(&mut self.vn_groups[index]);
591            self.vn_swap_lists(&mut source);
592        }
593        self.vn_open.push(VnOpenGroup {
594            saved,
595            isolation,
596            effect: None,
597            existing_group,
598            shared_key,
599            context,
600            mask: None,
601        });
602    }
603
604    /// vue-native fork: opens the group `effect`'s draws read as their content;
605    /// the matching [`Scene::vn_pop_isolation`] inserts them as one [`VnEffectLayer`].
606    pub fn vn_push_effect(&mut self, effect: VnEffectPaint) {
607        self.paint_operations
608            .push(PaintOperation::VnStartEffect(effect.clone()));
609        let mut saved = VnGroupLists::default();
610        self.vn_swap_lists(&mut saved);
611        let next_context = self.vn_contexts.len() + 1;
612        let parent_context = self.vn_open.last().map_or(0, |group| group.context);
613        let context = *self
614            .vn_contexts
615            .entry((parent_context, VnIsolationIdentity::Effect(next_context)))
616            .or_insert(next_context);
617        let isolation = VnIsolation {
618            geometry: std::sync::Arc::new(crate::VnClipGeometry {
619                fill_rule: crate::VnFillRule::NonZero,
620                segments: Vec::new(),
621                bounds: effect.content_mask.bounds,
622            }),
623            color_matrix: None,
624            text_paint: None,
625            content_mask: effect.content_mask,
626            capture: None,
627        };
628        self.vn_open.push(VnOpenGroup {
629            saved,
630            isolation,
631            effect: Some(effect),
632            existing_group: None,
633            shared_key: None,
634            context,
635            mask: None,
636        });
637    }
638
639    /// vue-native fork: what the innermost isolated layer paints from here to
640    /// its [`Scene::vn_pop_isolation`] is its mask: the group composites
641    /// multiplied by the mask's alpha, or its luminance.
642    pub fn vn_begin_mask(&mut self, luminance: bool) {
643        self.paint_operations.push(PaintOperation::VnBeginMask(luminance));
644        let Some(open) = self.vn_open.last() else {
645            return;
646        };
647        if open.mask.is_some()
648            || open.effect.is_some()
649            || open.existing_group.is_some()
650            || open.shared_key.is_some()
651        {
652            return;
653        }
654        let mut content = VnGroupLists::default();
655        self.vn_swap_lists(&mut content);
656        if let Some(open) = self.vn_open.last_mut() {
657            open.mask = Some((content, luminance));
658        }
659    }
660
661    /// vue-native fork: whether an isolated layer is open.
662    pub fn vn_is_isolating(&self) -> bool {
663        !self.vn_open.is_empty()
664    }
665
666    /// vue-native fork: closes the innermost isolated layer
667    /// ([`Scene::vn_push_isolation`]) and inserts its composite.
668    pub fn vn_pop_isolation(&mut self) {
669        self.paint_operations.push(PaintOperation::VnEndIsolation);
670        self.vn_close_group();
671    }
672
673    fn vn_close_group(&mut self) {
674        let Some(open) = self.vn_open.pop() else {
675            return;
676        };
677        // Layers the group left open (`finish` closing it) still paint.
678        self.layer_stack.clear();
679        self.insert_layers();
680        let mut group = open.saved;
681        self.vn_swap_lists(&mut group);
682        if let Some(effect) = open.effect {
683            self.vn_close_effect(group, effect);
684            return;
685        }
686        let (mut group, mask_group) = match open.mask {
687            Some((content, luminance)) => (content, Some((group, luminance))),
688            None => (group, None),
689        };
690        if let Some(index) = open.existing_group {
691            // Its composite was inserted on the first paint. Appending source
692            // pixels here must neither filter them alone nor composite twice.
693            self.vn_groups[index] = group;
694            return;
695        }
696        let color_group = open.shared_key;
697        if let Some(info) = open.isolation.capture {
698            if let Some(key) = color_group {
699                self.vn_color_groups.insert(key, self.vn_groups.len());
700            }
701            group.layer_stack = Vec::new();
702            self.vn_groups.push(group);
703            self.vn_captures.push(VnCapture {
704                info,
705                group: self.vn_groups.len() as u32,
706                ink: Bounds::default(),
707            });
708            return;
709        }
710        let geometry = &open.isolation.geometry;
711        let mask = open.isolation.content_mask;
712        // The antialiased edge reaches half a pixel past the shape.
713        let shape = geometry.bounds;
714        let bounds = Bounds::from_corners(
715            point(
716                ScaledPixels((shape.origin.x.0 - 1.).floor()),
717                ScaledPixels((shape.origin.y.0 - 1.).floor()),
718            ),
719            point(
720                ScaledPixels((shape.origin.x.0 + shape.size.width.0 + 1.).ceil()),
721                ScaledPixels((shape.origin.y.0 + shape.size.height.0 + 1.).ceil()),
722            ),
723        )
724        .intersect(&mask.bounds);
725        // An empty mask hides everything, as CSS's transparent black layer does.
726        let hidden = mask_group.as_ref().is_some_and(|(lists, _)| lists.is_empty());
727        if (group.is_empty() && color_group.is_none()) || hidden || geometry.segments.is_empty() || bounds.is_empty() {
728            return;
729        }
730        if color_group.is_none() { group.primitive_bounds = BoundsTree::default(); }
731        group.layer_stack = Vec::new();
732        if let Some(key) = color_group { self.vn_color_groups.insert(key, self.vn_groups.len()); }
733        self.vn_groups.push(group);
734        let mask_mode = match mask_group {
735            Some((mut lists, luminance)) => {
736                lists.primitive_bounds = BoundsTree::default();
737                lists.layer_stack = Vec::new();
738                self.vn_groups.push(lists);
739                if luminance { 2 } else { 1 }
740            }
741            None => 0,
742        };
743        let group_index = self.vn_groups.len() as u32 - u32::from(mask_mode != 0);
744        let segment_start = self.vn_clip_segments.len() as u32;
745        self.vn_clip_segments.extend_from_slice(&geometry.segments);
746        let text_start = self.vn_text_backgrounds.len() as u32;
747        if let Some(text) = &open.isolation.text_paint {
748            let m = text.inverse;
749            self.vn_text_backgrounds.extend(text.fill.backgrounds.iter().map(|background| VnTextBackground {
750                background: *background,
751                bounds: Bounds::new(
752                    point(ScaledPixels(text.bounds[0]), ScaledPixels(text.bounds[1])),
753                    crate::size(ScaledPixels(text.bounds[2]), ScaledPixels(text.bounds[3]))),
754                inverse: TransformationMatrix { rotation_scale: [[m[0], m[1]], [m[2], m[3]]], translation: [m[4], m[5]] },
755                scale_factor: text.scale_factor, pad: 0.,
756            }));
757        }
758        let text_count = self.vn_text_backgrounds.len() as u32 - text_start;
759        self.vn_layers.push(VnLayer {
760            group: group_index,
761            segment_start,
762            segment_count: geometry.segments.len() as u32,
763            fill_rule: (geometry.fill_rule == crate::VnFillRule::EvenOdd) as u32 | mask_mode << 1,
764            pad: [open.isolation.color_matrix.map_or(0, |m| if m.linear_rgb { 1 } else { 2 }), text_start, text_count],
765            color_matrix: open.isolation.color_matrix.map_or([0.; 20], |matrix| matrix.gpu_values()),
766            bounds,
767            content_mask: mask,
768            opacity: 1.,
769            ..VnLayer::default()
770        });
771        self.vn_layer_effects.push(None);
772        self.vn_place_composite(self.vn_layers.len() - 1, bounds, false);
773    }
774
775    fn vn_close_effect(&mut self, mut group: VnGroupLists, effect: VnEffectPaint) {
776        let mask = effect.content_mask;
777        let Some(reach) = effect
778            .draws
779            .iter()
780            .map(|draw| draw.quad.bounds)
781            .reduce(|union, bounds| union.union(&bounds))
782        else {
783            return;
784        };
785        let bounds = Bounds::from_corners(
786            point(
787                ScaledPixels(reach.origin.x.0.floor()),
788                ScaledPixels(reach.origin.y.0.floor()),
789            ),
790            point(
791                ScaledPixels((reach.origin.x.0 + reach.size.width.0).ceil()),
792                ScaledPixels((reach.origin.y.0 + reach.size.height.0).ceil()),
793            ),
794        )
795        .intersect(&mask.bounds);
796        if bounds.is_empty() {
797            return;
798        }
799        let group_index = if effect.content && !group.is_empty() {
800            group.primitive_bounds = BoundsTree::default();
801            group.layer_stack = Vec::new();
802            self.vn_groups.push(group);
803            self.vn_groups.len() as u32
804        } else {
805            0
806        };
807        let snapshots = effect.draws.iter().any(|draw| draw.quad.needs_backdrop());
808        let start = self.vn_effect_draws.len() as u32;
809        for draw in &effect.draws {
810            let mut quad = draw.quad;
811            self.vn_set_effect_textures(&mut quad, draw.textures.as_ref());
812            self.vn_effect_draws.push(VnEffectDraw {
813                quad,
814                history: draw.history,
815                textures: None,
816            });
817        }
818        self.vn_layers.push(VnLayer {
819            group: group_index,
820            bounds,
821            content_mask: mask,
822            opacity: 1.,
823            ..Default::default()
824        });
825        self.vn_layer_effects.push(Some(VnEffectLayer {
826            start,
827            count: effect.draws.len() as u32,
828        }));
829        self.vn_place_composite(self.vn_layers.len() - 1, bounds, snapshots);
830    }
831
832    /// vue-native fork: the [`VnEffectLayer`] that composites
833    /// [`Scene::vn_layers`]`[index]`, if effects do.
834    pub fn vn_effect_layer(&self, index: usize) -> Option<VnEffectLayer> {
835        self.vn_layer_effects.get(index).copied().flatten()
836    }
837
838    /// vue-native fork: composites the snapshot `paint.id` at the current
839    /// draw position. Its mapping is settled after `finish`
840    /// ([`Scene::vn_resolve_snapshots`]), once every capture is known.
841    pub fn vn_insert_snapshot(&mut self, paint: VnSnapshotPaint) {
842        let bounds = paint.bounds.intersect(&paint.content_mask.bounds);
843        if bounds.is_empty() || paint.opacity <= 0. {
844            return;
845        }
846        self.paint_operations.push(PaintOperation::VnSnapshot(paint));
847        let [a, b, tx, c, d, ty] = paint.to_unit;
848        self.vn_layers.push(VnLayer {
849            bounds,
850            content_mask: paint.content_mask,
851            snapshot: [paint.id as u32, (paint.id >> 32) as u32],
852            flags: vn_layer_flags::SNAPSHOT
853                | if paint.plus_lighter { vn_layer_flags::PLUS_LIGHTER } else { 0 }
854                | if paint.in_place { vn_layer_flags::IN_PLACE } else { 0 },
855            opacity: paint.opacity,
856            source_transform: [a, b, tx, 0., c, d, ty, 0.],
857            ..VnLayer::default()
858        });
859        self.vn_layer_effects.push(None);
860        self.vn_place_composite(self.vn_layers.len() - 1, bounds, false);
861    }
862
863    /// vue-native fork: maps each snapshot composite's unit square onto its
864    /// capture's border box and names the snapshot's rectangle. `known` finds
865    /// a capture of an earlier frame; one of this scene wins. A composite
866    /// whose capture is unknown draws nothing.
867    pub fn vn_resolve_snapshots(&mut self, known: impl Fn(u64) -> Option<(VnCaptureInfo, Bounds<ScaledPixels>)>) {
868        let current: HashMap<u64, (VnCaptureInfo, Bounds<ScaledPixels>)> =
869            self.vn_captures.iter().map(|c| (c.info.id, (c.info, c.ink))).collect();
870        for layer in &mut self.vn_layers {
871            let Some(id) = layer.snapshot_id() else { continue };
872            let Some((info, ink)) = current.get(&id).copied().or_else(|| known(id)) else {
873                layer.opacity = 0.;
874                continue;
875            };
876            if ink.is_empty() {
877                layer.opacity = 0.;
878                continue;
879            }
880            if layer.flags & vn_layer_flags::IN_PLACE != 0 {
881                layer.flags &= !vn_layer_flags::IN_PLACE;
882                let Some(inverse) = info.transform.inverse() else {
883                    layer.opacity = 0.;
884                    continue;
885                };
886                let [[a, b], [c, d]] = inverse.rotation_scale;
887                let [tx, ty] = inverse.translation;
888                layer.source_transform = [a, b, tx, 0., c, d, ty, 0.];
889                let drawn = transformed_bounds(ink, info.transform);
890                let drawn = Bounds::from_corners(
891                    point(ScaledPixels(drawn.origin.x.0.floor()), ScaledPixels(drawn.origin.y.0.floor())),
892                    point(
893                        ScaledPixels((drawn.origin.x.0 + drawn.size.width.0).ceil()),
894                        ScaledPixels((drawn.origin.y.0 + drawn.size.height.0).ceil()),
895                    ),
896                );
897                layer.bounds = layer.bounds.intersect(&drawn);
898            } else {
899                let bb = info.border_box;
900                let t = layer.source_transform;
901                let (w, h) = (bb.size.width.0, bb.size.height.0);
902                layer.source_transform = [
903                    t[0] * w, t[1] * w, t[2] * w + bb.origin.x.0, 0.,
904                    t[4] * h, t[5] * h, t[6] * h + bb.origin.y.0, 0.,
905                ];
906            }
907            layer.source_rect = [ink.origin.x.0, ink.origin.y.0, ink.size.width.0, ink.size.height.0];
908        }
909    }
910
911    /// vue-native fork: appends a closed group to the scene's vectors.
912    fn vn_append(&mut self, group: VnGroupLists) -> VnGroupRanges {
913        fn append<T>(into: &mut Vec<T>, from: Vec<T>) -> Range<usize> {
914            let start = into.len();
915            into.extend(from);
916            start..into.len()
917        }
918        append(&mut self.vn_layer_effects, group.vn_layer_effects);
919        VnGroupRanges {
920            shadows: append(&mut self.shadows, group.shadows),
921            quads: append(&mut self.quads, group.quads),
922            backdrop_blur_rects: append(&mut self.backdrop_blur_rects, group.backdrop_blur_rects),
923            effect_quads: append(&mut self.effect_quads, group.effect_quads),
924            paths: append(&mut self.paths, group.paths),
925            underlines: append(&mut self.underlines, group.underlines),
926            monochrome_sprites: append(&mut self.monochrome_sprites, group.monochrome_sprites),
927            subpixel_sprites: append(&mut self.subpixel_sprites, group.subpixel_sprites),
928            polychrome_sprites: append(&mut self.polychrome_sprites, group.polychrome_sprites),
929            surfaces: append(&mut self.surfaces, group.surfaces),
930            vn_layers: append(&mut self.vn_layers, group.vn_layers),
931        }
932    }
933
934    /// vue-native fork: the ranges that hold everything the vectors hold —
935    /// the root group before `finish` appended any other.
936    fn vn_whole_ranges(&self) -> VnGroupRanges {
937        VnGroupRanges {
938            shadows: 0..self.shadows.len(),
939            quads: 0..self.quads.len(),
940            backdrop_blur_rects: 0..self.backdrop_blur_rects.len(),
941            effect_quads: 0..self.effect_quads.len(),
942            paths: 0..self.paths.len(),
943            underlines: 0..self.underlines.len(),
944            monochrome_sprites: 0..self.monochrome_sprites.len(),
945            subpixel_sprites: 0..self.subpixel_sprites.len(),
946            polychrome_sprites: 0..self.polychrome_sprites.len(),
947            surfaces: 0..self.surfaces.len(),
948            vn_layers: 0..self.vn_layers.len(),
949        }
950    }
951
952    /// vue-native fork: how many groups a finished scene holds, the root
953    /// included.
954    pub fn vn_group_count(&self) -> usize {
955        self.vn_group_ranges.len().max(1)
956    }
957
958    /// vue-native fork: the batches of one group (0 is the root), with its
959    /// isolated layers' composites as [`VnBatch::Layers`]; a renderer that
960    /// isolates draws each composite's [`VnLayer::group`] through these too.
961    pub fn vn_batches(&self, group: usize) -> impl Iterator<Item = VnBatch> + '_ {
962        let ranges = self
963            .vn_group_ranges
964            .get(group)
965            .cloned()
966            .unwrap_or_else(|| if group == 0 { self.vn_whole_ranges() } else { VnGroupRanges::default() });
967        BatchIterator::new(self, ranges)
968    }
969
970    fn vn_flatten_into(&self, group: usize, depth: usize, out: &mut Vec<PrimitiveBatch>) {
971        for batch in self.vn_batches(group) {
972            match batch {
973                VnBatch::Primitives(batch) => out.push(batch),
974                VnBatch::Layers(range) => {
975                    // A cycle cannot be built, but a corrupt index must not
976                    // recurse for ever.
977                    if depth > 64 {
978                        continue;
979                    }
980                    for layer in &self.vn_layers[range] {
981                        if layer.group != 0 && layer.snapshot_id().is_none() {
982                            self.vn_flatten_into(layer.group as usize, depth + 1, out);
983                        }
984                    }
985                }
986            }
987        }
988    }
989
990    /// Inserts a sprite that [`Self::advance_animations`] keeps moving. The
991    /// sprite's color is taken as its color before the animation's alpha.
992    pub(crate) fn insert_animated_sprite(
993        &mut self,
994        mut sprite: MonochromeSprite,
995        mut animation: SpriteAnimation,
996    ) {
997        sprite.animation = SpriteAnimationId(self.animations.len() as u32);
998        animation.base_color = sprite.color;
999        if self.try_insert_primitive(sprite.into()) {
1000            self.animations.push(animation);
1001        }
1002    }
1003
1004    /// How long the window may wait between presents of this scene while only
1005    /// its animations need a frame: `None` when nothing in it animates, and
1006    /// zero when an animation wants every frame.
1007    pub(crate) fn animation_frame_interval(&self) -> Option<Duration> {
1008        self.animations
1009            .iter()
1010            .map(|animation| {
1011                animation
1012                    .transformation
1013                    .min_frame_interval()
1014                    .unwrap_or_default()
1015            })
1016            .min()
1017    }
1018
1019    /// Moves every animated sprite to its pose at `elapsed` time on the app's
1020    /// synced animation clock, without the scene being rebuilt.
1021    pub(crate) fn advance_animations(&mut self, elapsed: Duration) {
1022        for animation in &self.animations {
1023            let Some(sprite) = self.monochrome_sprites.get_mut(animation.sprite_index) else {
1024                continue;
1025            };
1026            let pose = animation.transformation.at(elapsed);
1027            sprite.transformation = animation
1028                .outer
1029                .compose(pose.into_matrix(animation.center, animation.scale_factor));
1030            sprite.color = animation.base_color.opacity(pose.alpha_factor());
1031        }
1032    }
1033
1034    pub fn len(&self) -> usize {
1035        self.paint_operations.len()
1036    }
1037
1038    pub fn push_layer(&mut self) {
1039        self.layer_stack.push(self.layers.len());
1040        self.layers.push_back(Layer::new());
1041        self.paint_operations.push(PaintOperation::StartLayer);
1042    }
1043
1044    pub fn pop_layer(&mut self) {
1045        self.layer_stack.pop();
1046        if self.layer_stack.is_empty() {
1047            self.insert_layers();
1048        }
1049        self.paint_operations.push(PaintOperation::EndLayer);
1050    }
1051
1052    fn insert_layers(&mut self) {
1053        while let Some(layer) = self.layers.pop_front() {
1054            self.insert_layer(layer);
1055        }
1056    }
1057
1058    fn insert_layer(&mut self, layer: Layer) {
1059        if layer.primitives.is_empty() && layer.vn_composites.is_empty() {
1060            return;
1061        }
1062        let order =
1063            self.primitive_bounds
1064                .insert(layer.bounds, layer.max_kind, layer.max_shared_kind);
1065        for index in layer.primitives.into_iter().flatten() {
1066            if let PaintOperation::Primitive(primitive) = &self.paint_operations[index] {
1067                let primitive = primitive.clone();
1068                self.push_primitive(primitive, order);
1069            }
1070        }
1071        for index in layer.vn_composites {
1072            self.vn_set_composite_order(index, order);
1073        }
1074    }
1075
1076    /// vue-native fork: a primitive that samples the render target draws
1077    /// after everything painted before it and before everything painted after
1078    /// it. The open layers would give it their one order, so they are inserted
1079    /// as they stand and reopened empty.
1080    fn vn_split_layers(&mut self) {
1081        let open = self.layer_stack.len();
1082        if open == 0 {
1083            return;
1084        }
1085        self.insert_layers();
1086        self.layer_stack.clear();
1087        for index in 0..open {
1088            self.layer_stack.push(index);
1089            self.layers.push_back(Layer::new());
1090        }
1091    }
1092
1093    /// vue-native fork: gives the composite [`Scene::vn_layers`]`[index]`,
1094    /// which covers `bounds`, an order: the open layer's once that is
1095    /// inserted, or one of its own.
1096    fn vn_place_composite(
1097        &mut self,
1098        index: usize,
1099        bounds: Bounds<ScaledPixels>,
1100        snapshots_backdrop: bool,
1101    ) {
1102        let kind = PrimitiveKind::VnLayer;
1103        if snapshots_backdrop {
1104            self.vn_split_layers();
1105        } else if let Some(&layer) = self.layer_stack.last()
1106            && let Some(layer) = self.layers.get_mut(layer)
1107        {
1108            layer.bounds = layer.bounds.join(&bounds);
1109            layer.max_kind = layer.max_kind.max(kind);
1110            layer.max_shared_kind = layer.max_shared_kind.min(kind.max_shared_kind());
1111            layer.vn_composites.push(index);
1112            return;
1113        }
1114        // A composite that samples its backdrop cannot share an order with
1115        // another composite: they draw in one run.
1116        let max_shared_kind = if snapshots_backdrop {
1117            PrimitiveKind::Surface
1118        } else {
1119            kind.max_shared_kind()
1120        };
1121        let order = self.primitive_bounds.insert(bounds, kind, max_shared_kind);
1122        self.vn_set_composite_order(index, order);
1123    }
1124
1125    fn vn_set_composite_order(&mut self, index: usize, order: DrawOrder) {
1126        self.vn_layers[index].order = order;
1127        if let Some(effect) = self.vn_layer_effects[index] {
1128            for draw in &mut self.vn_effect_draws[effect.draws()] {
1129                draw.quad.order = order;
1130            }
1131        }
1132    }
1133
1134    /// vue-native fork: points `quad` at `textures` in
1135    /// [`Self::effect_texture_sets`], which holds each distinct set of images once.
1136    fn vn_set_effect_textures(
1137        &mut self,
1138        quad: &mut EffectQuad,
1139        textures: Option<&std::sync::Arc<crate::EffectTextureSet>>,
1140    ) {
1141        quad.flags &= (1 << crate::EFFECT_FLAG_TEXTURE_SET_SHIFT) - 1;
1142        let Some(textures) = textures else {
1143            return;
1144        };
1145        let key = crate::effect_texture_key(textures);
1146        let index = match self.effect_texture_set_index.get(&key) {
1147            Some(index) => *index,
1148            None => {
1149                let index = self.effect_texture_sets.len();
1150                self.effect_texture_sets.push(textures.clone());
1151                self.effect_texture_set_index.insert(key, index);
1152                index
1153            }
1154        };
1155        quad.flags |= (index as u32 + 1) << crate::EFFECT_FLAG_TEXTURE_SET_SHIFT;
1156    }
1157
1158    pub fn insert_primitive(&mut self, primitive: impl Into<Primitive>) {
1159        self.try_insert_primitive(primitive.into());
1160    }
1161
1162    /// Returns whether the primitive was kept, rather than clipped away.
1163    fn try_insert_primitive(&mut self, primitive: Primitive) -> bool {
1164        let clipped_bounds = primitive.clipped_bounds();
1165        if clipped_bounds.is_empty() {
1166            return false;
1167        }
1168
1169        let kind = primitive.kind();
1170        let snapshots_backdrop = primitive.snapshots_backdrop();
1171        if snapshots_backdrop {
1172            self.vn_split_layers();
1173        }
1174        if !snapshots_backdrop
1175            && let Some(&layer) = self.layer_stack.last()
1176            && let Some(layer) = self.layers.get_mut(layer)
1177        {
1178            layer.bounds = layer.bounds.join(&clipped_bounds);
1179            layer.max_kind = layer.max_kind.max(kind);
1180            layer.max_shared_kind = layer.max_shared_kind.min(kind.max_shared_kind());
1181            let index = self.paint_operations.len();
1182            match layer.primitives.last_mut() {
1183                Some(range) if range.end == index => range.end += 1,
1184                _ => layer.primitives.push(index..index + 1),
1185            }
1186        } else {
1187            let order = self
1188                .primitive_bounds
1189                .insert(clipped_bounds, kind, kind.max_shared_kind());
1190            self.push_primitive(primitive.clone(), order);
1191        }
1192        self.paint_operations
1193            .push(PaintOperation::Primitive(primitive));
1194        true
1195    }
1196
1197    fn push_primitive(&mut self, primitive: Primitive, order: DrawOrder) {
1198        match primitive {
1199            Primitive::Shadow(shadow) => self.shadows.push(Shadow { order, ..shadow }),
1200            Primitive::Quad(quad) => self.quads.push(Quad { order, ..quad }),
1201            Primitive::BackdropBlurRect(rect) => self
1202                .backdrop_blur_rects
1203                .push(BackdropBlurRect { order, ..rect }),
1204            Primitive::EffectQuad(effect_quad, textures) => {
1205                let mut effect_quad = EffectQuad {
1206                    order,
1207                    ..effect_quad
1208                };
1209                self.vn_set_effect_textures(&mut effect_quad, textures.as_ref());
1210                self.effect_quads.push(effect_quad);
1211            }
1212            Primitive::Path(mut path) => {
1213                path.order = order;
1214                self.paths.push(path);
1215            }
1216            Primitive::Underline(underline) => {
1217                self.underlines.push(Underline { order, ..underline })
1218            }
1219            Primitive::MonochromeSprite(sprite) => self
1220                .monochrome_sprites
1221                .push(MonochromeSprite { order, ..sprite }),
1222            Primitive::SubpixelSprite(sprite) => self
1223                .subpixel_sprites
1224                .push(SubpixelSprite { order, ..sprite }),
1225            Primitive::PolychromeSprite(sprite) => self
1226                .polychrome_sprites
1227                .push(PolychromeSprite { order, ..sprite }),
1228            Primitive::Surface(mut surface) => {
1229                surface.order = order;
1230                self.surfaces.push(surface);
1231            }
1232        }
1233    }
1234
1235    pub fn replay(&mut self, range: Range<usize>, prev_scene: &Scene) {
1236        for operation in &prev_scene.paint_operations[range] {
1237            match operation {
1238                PaintOperation::Primitive(primitive) => {
1239                    // Animation ids index the scene they were inserted into.
1240                    if let Primitive::MonochromeSprite(sprite) = primitive
1241                        && let Some(animation) =
1242                            prev_scene.animations.get(sprite.animation.0 as usize)
1243                    {
1244                        self.insert_animated_sprite(*sprite, *animation);
1245                    } else {
1246                        self.insert_primitive(primitive.clone());
1247                    }
1248                }
1249                PaintOperation::StartLayer => self.push_layer(),
1250                PaintOperation::EndLayer => self.pop_layer(),
1251                PaintOperation::VnStartIsolation(isolation) => {
1252                    self.vn_push_isolation(isolation.clone())
1253                }
1254                PaintOperation::VnStartEffect(effect) => self.vn_push_effect(effect.clone()),
1255                PaintOperation::VnEndIsolation => self.vn_pop_isolation(),
1256                PaintOperation::VnSnapshot(paint) => self.vn_insert_snapshot(*paint),
1257                PaintOperation::VnBeginMask(luminance) => self.vn_begin_mask(*luminance),
1258            }
1259        }
1260    }
1261
1262    pub fn finish(&mut self) {
1263        // vue-native fork: once the groups are appended, sorting the vectors
1264        // again would mix them; a scene is finished once.
1265        if !self.vn_group_ranges.is_empty() {
1266            return;
1267        }
1268        // An isolated layer left open closes here.
1269        while !self.vn_open.is_empty() {
1270            self.vn_close_group();
1271        }
1272        self.layer_stack.clear();
1273        self.insert_layers();
1274        let mut root = VnGroupLists::default();
1275        self.vn_swap_lists(&mut root);
1276        root.sort();
1277        self.vn_swap_lists(&mut root);
1278        // Then each isolated group, sorted on its own, after the root.
1279        if self.vn_groups.is_empty() {
1280            self.vn_group_ranges.clear();
1281        } else {
1282            let mut ranges = vec![self.vn_whole_ranges()];
1283            for (index, mut group) in mem::take(&mut self.vn_groups).into_iter().enumerate() {
1284                if let Some(capture) = self.vn_captures.iter_mut().find(|c| c.group as usize == index + 1) {
1285                    capture.ink = group.ink().map_or_else(Bounds::default, |ink| {
1286                        Bounds::from_corners(
1287                            point(ScaledPixels(ink.origin.x.0.floor()), ScaledPixels(ink.origin.y.0.floor())),
1288                            point(
1289                                ScaledPixels((ink.origin.x.0 + ink.size.width.0).ceil()),
1290                                ScaledPixels((ink.origin.y.0 + ink.size.height.0).ceil()),
1291                            ),
1292                        )
1293                    });
1294                }
1295                group.sort();
1296                ranges.push(self.vn_append(group));
1297            }
1298            self.vn_group_ranges = ranges;
1299        }
1300
1301        // Sorting moved the sprites, so animations learn where theirs ended up.
1302        if !self.animations.is_empty() {
1303            for (index, sprite) in self.monochrome_sprites.iter().enumerate() {
1304                if let Some(animation) = self.animations.get_mut(sprite.animation.0 as usize) {
1305                    animation.sprite_index = index;
1306                }
1307            }
1308        }
1309    }
1310
1311    #[cfg_attr(
1312        all(
1313            any(target_os = "linux", target_os = "freebsd"),
1314            not(any(feature = "x11", feature = "wayland"))
1315        ),
1316        allow(dead_code)
1317    )]
1318    ///
1319    /// vue-native fork: an isolated layer's group comes inline where its
1320    /// composite would draw, unclipped by its shape (cut to the shape's box by
1321    /// the content mask). That is what a renderer without isolated layers
1322    /// draws; the DirectX, Metal and wgpu renderers walk [`Scene::vn_batches`].
1323    pub fn batches(&self) -> impl Iterator<Item = PrimitiveBatch> + '_ {
1324        let mut out = Vec::new();
1325        self.vn_flatten_into(0, 0, &mut out);
1326        out.into_iter()
1327    }
1328}
1329
1330/// Sorts small `(key, index)` pairs instead of the primitives themselves, then moves each
1331/// primitive into place once. Primitives are large, so a comparison sort that shuffles them
1332/// directly spends most of its time copying. Ties keep insertion order, as `sort_by_key`
1333/// does, because the index is part of what is sorted.
1334fn sort_in_place<T: Copy>(
1335    primitives: &mut [T],
1336    keys: &mut Vec<(u64, u32)>,
1337    key: impl Fn(&T) -> (u32, u32),
1338) {
1339    if primitives.is_sorted_by_key(&key) {
1340        return;
1341    }
1342    keys.clear();
1343    keys.extend(primitives.iter().enumerate().map(|(index, primitive)| {
1344        let (major, minor) = key(primitive);
1345        ((major as u64) << 32 | minor as u64, index as u32)
1346    }));
1347    keys.sort_unstable();
1348
1349    // `keys[target].1` is the source index for `target`. Follow each cycle of that
1350    // permutation, marking visited slots by pointing them at themselves.
1351    for start in 0..primitives.len() {
1352        if keys[start].1 as usize == start {
1353            continue;
1354        }
1355        let displaced = primitives[start];
1356        let mut target = start;
1357        loop {
1358            let source = keys[target].1 as usize;
1359            keys[target].1 = target as u32;
1360            if source == start {
1361                primitives[target] = displaced;
1362                break;
1363            }
1364            primitives[target] = primitives[source];
1365            target = source;
1366        }
1367    }
1368}
1369
1370/// The depth step between consecutive quads in a frame with `quad_count` quads.
1371pub fn quad_depth_scale(quad_count: usize) -> f32 {
1372    let denominator = (quad_count.min((1 << 24) - 1) + 1).next_power_of_two();
1373    1.0 / denominator as f32
1374}
1375
1376/// Maps a quad's index in [`Scene::quads`] to depth, with greater values closer.
1377pub fn quad_depth(quad_id: u32, scale: f32) -> f32 {
1378    ((quad_id + 1) as f32 * scale).min(1.0)
1379}
1380
1381#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Default)]
1382#[cfg_attr(
1383    all(
1384        any(target_os = "linux", target_os = "freebsd"),
1385        not(any(feature = "x11", feature = "wayland"))
1386    ),
1387    allow(dead_code)
1388)]
1389pub(crate) enum PrimitiveKind {
1390    Shadow,
1391    #[default]
1392    Quad,
1393    BackdropBlurRect,
1394    EffectQuad,
1395    Path,
1396    Underline,
1397    MonochromeSprite,
1398    SubpixelSprite,
1399    PolychromeSprite,
1400    Surface,
1401    /// vue-native fork: an isolated layer's composite.
1402    VnLayer,
1403}
1404
1405impl PrimitiveKind {
1406    /// We guarantee that overlapping primitives are drawn in paint order.
1407    /// But, to improve GPU draw batching, the renderer sorts primitives that
1408    /// share a draw order by kind, then by atlas texture, and only then in
1409    /// paint order. So, a primitive can only share the draw order of the
1410    /// topmost primitive it overlaps if that primitive's kind is at most the
1411    /// one returned here. Otherwise, it needs a new draw order.
1412    fn max_shared_kind(self) -> Self {
1413        match self {
1414            // vue-native fork: one batch of backdrop blurs reads one snapshot,
1415            // so a blur cannot share the order of a blur it overlaps.
1416            Self::BackdropBlurRect => Self::Quad,
1417            // vue-native fork: effect quads are sorted by effect and texture
1418            // set within an order, as sprites are by texture.
1419            Self::EffectQuad => Self::BackdropBlurRect,
1420            Self::MonochromeSprite => Self::Underline,
1421            Self::SubpixelSprite => Self::MonochromeSprite,
1422            Self::PolychromeSprite => Self::SubpixelSprite,
1423            kind => kind,
1424        }
1425    }
1426}
1427
1428pub(crate) enum PaintOperation {
1429    Primitive(Primitive),
1430    StartLayer,
1431    EndLayer,
1432    /// vue-native fork: [`Scene::vn_push_isolation`].
1433    VnStartIsolation(VnIsolation),
1434    /// vue-native fork: [`Scene::vn_push_effect`].
1435    VnStartEffect(VnEffectPaint),
1436    /// vue-native fork: [`Scene::vn_pop_isolation`].
1437    VnEndIsolation,
1438    /// vue-native fork: [`Scene::vn_insert_snapshot`].
1439    VnSnapshot(VnSnapshotPaint),
1440    /// vue-native fork: [`Scene::vn_begin_mask`].
1441    VnBeginMask(bool),
1442}
1443
1444#[derive(Clone)]
1445#[expect(missing_docs)]
1446pub enum Primitive {
1447    Shadow(Shadow),
1448    Quad(Quad),
1449    BackdropBlurRect(BackdropBlurRect),
1450    /// vue-native fork: with the images it samples.
1451    EffectQuad(EffectQuad, Option<std::sync::Arc<crate::EffectTextureSet>>),
1452    Path(PaintedPath),
1453    Underline(Underline),
1454    MonochromeSprite(MonochromeSprite),
1455    SubpixelSprite(SubpixelSprite),
1456    PolychromeSprite(PolychromeSprite),
1457    Surface(PaintSurface),
1458}
1459
1460#[expect(missing_docs)]
1461impl Primitive {
1462    pub(crate) fn kind(&self) -> PrimitiveKind {
1463        match self {
1464            Primitive::Shadow(_) => PrimitiveKind::Shadow,
1465            Primitive::Quad(_) => PrimitiveKind::Quad,
1466            Primitive::BackdropBlurRect(_) => PrimitiveKind::BackdropBlurRect,
1467            Primitive::EffectQuad(..) => PrimitiveKind::EffectQuad,
1468            Primitive::Path(_) => PrimitiveKind::Path,
1469            Primitive::Underline(_) => PrimitiveKind::Underline,
1470            Primitive::MonochromeSprite(_) => PrimitiveKind::MonochromeSprite,
1471            Primitive::SubpixelSprite(_) => PrimitiveKind::SubpixelSprite,
1472            Primitive::PolychromeSprite(_) => PrimitiveKind::PolychromeSprite,
1473            Primitive::Surface(_) => PrimitiveKind::Surface,
1474        }
1475    }
1476
1477    pub fn bounds(&self) -> &Bounds<ScaledPixels> {
1478        match self {
1479            Primitive::Shadow(shadow) => &shadow.bounds,
1480            Primitive::Quad(quad) => &quad.bounds,
1481            Primitive::BackdropBlurRect(backdrop_blur_rect) => &backdrop_blur_rect.bounds,
1482            Primitive::EffectQuad(effect_quad, _) => &effect_quad.bounds,
1483            Primitive::Path(path) => &path.bounds,
1484            Primitive::Underline(underline) => &underline.bounds,
1485            Primitive::MonochromeSprite(sprite) => &sprite.bounds,
1486            Primitive::SubpixelSprite(sprite) => &sprite.bounds,
1487            Primitive::PolychromeSprite(sprite) => &sprite.bounds,
1488            Primitive::Surface(surface) => &surface.bounds,
1489        }
1490    }
1491
1492    /// The CSS `transform` this primitive carries, if its kind has one.
1493    ///
1494    /// `bounds` is the UNTRANSFORMED rect — the shader applies the matrix — so
1495    /// anything comparing a primitive's rectangle with a window-space rect (the
1496    /// content mask, the draw-order tree) has to map it first.
1497    pub fn transformation(&self) -> Option<TransformationMatrix> {
1498        match self {
1499            Primitive::Shadow(shadow) => Some(shadow.transformation),
1500            Primitive::Quad(quad) => Some(quad.transformation),
1501            Primitive::Underline(underline) => Some(underline.transformation),
1502            Primitive::MonochromeSprite(sprite) => Some(sprite.transformation),
1503            Primitive::SubpixelSprite(sprite) => Some(sprite.transformation),
1504            Primitive::PolychromeSprite(sprite) => Some(sprite.transformation),
1505            Primitive::BackdropBlurRect(_)
1506            | Primitive::EffectQuad(..)
1507            | Primitive::Path(_)
1508            | Primitive::Surface(_) => None,
1509        }
1510    }
1511
1512    fn clipped_bounds(&self) -> Bounds<ScaledPixels> {
1513        self.transformation()
1514            .unwrap_or_default()
1515            .transform_bounds(*self.bounds())
1516            .intersect(&self.content_mask().bounds)
1517    }
1518
1519    /// vue-native fork: whether the renderer composites this primitive from a
1520    /// snapshot of the render target under it.
1521    fn snapshots_backdrop(&self) -> bool {
1522        match self {
1523            Primitive::BackdropBlurRect(_) => true,
1524            Primitive::EffectQuad(effect_quad, _) => effect_quad.needs_backdrop(),
1525            _ => false,
1526        }
1527    }
1528
1529    pub fn content_mask(&self) -> &ContentMask<ScaledPixels> {
1530        match self {
1531            Primitive::Shadow(shadow) => &shadow.content_mask,
1532            Primitive::Quad(quad) => &quad.content_mask,
1533            Primitive::BackdropBlurRect(backdrop_blur_rect) => &backdrop_blur_rect.content_mask,
1534            Primitive::EffectQuad(effect_quad, _) => &effect_quad.content_mask,
1535            Primitive::Path(path) => &path.paint.content_mask,
1536            Primitive::Underline(underline) => &underline.content_mask,
1537            Primitive::MonochromeSprite(sprite) => &sprite.content_mask,
1538            Primitive::SubpixelSprite(sprite) => &sprite.content_mask,
1539            Primitive::PolychromeSprite(sprite) => &sprite.content_mask,
1540            Primitive::Surface(surface) => &surface.content_mask,
1541        }
1542    }
1543}
1544
1545#[cfg_attr(
1546    all(
1547        any(target_os = "linux", target_os = "freebsd"),
1548        not(any(feature = "x11", feature = "wayland"))
1549    ),
1550    allow(dead_code)
1551)]
1552struct BatchIterator<'a> {
1553    shadows_start: usize,
1554    shadows_iter: Peekable<slice::Iter<'a, Shadow>>,
1555    quads_start: usize,
1556    quads_iter: Peekable<slice::Iter<'a, Quad>>,
1557    backdrop_blur_rects_start: usize,
1558    backdrop_blur_rects_iter: Peekable<slice::Iter<'a, BackdropBlurRect>>,
1559    effect_quads_start: usize,
1560    effect_quads_iter: Peekable<slice::Iter<'a, EffectQuad>>,
1561    paths_start: usize,
1562    paths_iter: Peekable<slice::Iter<'a, PaintedPath>>,
1563    underlines_start: usize,
1564    underlines_iter: Peekable<slice::Iter<'a, Underline>>,
1565    monochrome_sprites_start: usize,
1566    monochrome_sprites_iter: Peekable<slice::Iter<'a, MonochromeSprite>>,
1567    subpixel_sprites_start: usize,
1568    subpixel_sprites_iter: Peekable<slice::Iter<'a, SubpixelSprite>>,
1569    polychrome_sprites_start: usize,
1570    polychrome_sprites_iter: Peekable<slice::Iter<'a, PolychromeSprite>>,
1571    surfaces_start: usize,
1572    surfaces_iter: Peekable<slice::Iter<'a, PaintSurface>>,
1573    vn_layers_start: usize,
1574    vn_layers_iter: Peekable<slice::Iter<'a, VnLayer>>,
1575}
1576
1577impl<'a> BatchIterator<'a> {
1578    /// vue-native fork: the batches of one group's ranges of `scene`'s
1579    /// vectors. The ranges it yields index the whole vectors.
1580    fn new(scene: &'a Scene, r: VnGroupRanges) -> Self {
1581        BatchIterator {
1582            shadows_start: r.shadows.start,
1583            shadows_iter: scene.shadows[r.shadows].iter().peekable(),
1584            quads_start: r.quads.start,
1585            quads_iter: scene.quads[r.quads].iter().peekable(),
1586            backdrop_blur_rects_start: r.backdrop_blur_rects.start,
1587            backdrop_blur_rects_iter: scene.backdrop_blur_rects[r.backdrop_blur_rects]
1588                .iter()
1589                .peekable(),
1590            effect_quads_start: r.effect_quads.start,
1591            effect_quads_iter: scene.effect_quads[r.effect_quads].iter().peekable(),
1592            paths_start: r.paths.start,
1593            paths_iter: scene.paths[r.paths].iter().peekable(),
1594            underlines_start: r.underlines.start,
1595            underlines_iter: scene.underlines[r.underlines].iter().peekable(),
1596            monochrome_sprites_start: r.monochrome_sprites.start,
1597            monochrome_sprites_iter: scene.monochrome_sprites[r.monochrome_sprites]
1598                .iter()
1599                .peekable(),
1600            subpixel_sprites_start: r.subpixel_sprites.start,
1601            subpixel_sprites_iter: scene.subpixel_sprites[r.subpixel_sprites].iter().peekable(),
1602            polychrome_sprites_start: r.polychrome_sprites.start,
1603            polychrome_sprites_iter: scene.polychrome_sprites[r.polychrome_sprites]
1604                .iter()
1605                .peekable(),
1606            surfaces_start: r.surfaces.start,
1607            surfaces_iter: scene.surfaces[r.surfaces].iter().peekable(),
1608            vn_layers_start: r.vn_layers.start,
1609            vn_layers_iter: scene.vn_layers[r.vn_layers].iter().peekable(),
1610        }
1611    }
1612}
1613
1614impl<'a> Iterator for BatchIterator<'a> {
1615    type Item = VnBatch;
1616
1617    fn next(&mut self) -> Option<Self::Item> {
1618        // vue-native fork: a run of composites at the lowest order goes
1619        // first; otherwise the primitive kinds, as upstream picks them.
1620        let layer_order = self.vn_layers_iter.peek().map(|l| l.order);
1621        if let Some(layer_order) = layer_order {
1622            let lowest_primitive = [
1623                self.shadows_iter.peek().map(|s| s.order),
1624                self.quads_iter.peek().map(|q| q.order),
1625                self.backdrop_blur_rects_iter.peek().map(|b| b.order),
1626                self.effect_quads_iter.peek().map(|e| e.order),
1627                self.paths_iter.peek().map(|p| p.order),
1628                self.underlines_iter.peek().map(|u| u.order),
1629                self.monochrome_sprites_iter.peek().map(|s| s.order),
1630                self.subpixel_sprites_iter.peek().map(|s| s.order),
1631                self.polychrome_sprites_iter.peek().map(|s| s.order),
1632                self.surfaces_iter.peek().map(|s| s.order),
1633            ]
1634            .into_iter()
1635            .flatten()
1636            .min();
1637            // At equal orders the primitives go first, as `PrimitiveKind`
1638            // sorts the composite last.
1639            if lowest_primitive.is_none_or(|order| layer_order < order) {
1640                let start = self.vn_layers_start;
1641                let mut end = start + 1;
1642                self.vn_layers_iter.next();
1643                while self
1644                    .vn_layers_iter
1645                    .next_if(|layer| lowest_primitive.is_none_or(|order| layer.order < order))
1646                    .is_some()
1647                {
1648                    end += 1;
1649                }
1650                self.vn_layers_start = end;
1651                return Some(VnBatch::Layers(start..end));
1652            }
1653        }
1654        self.next_primitives(layer_order).map(VnBatch::Primitives)
1655    }
1656}
1657
1658impl<'a> BatchIterator<'a> {
1659    /// The next run of one primitive kind, which ends before `layer_order`
1660    /// (the next composite's) as before any other kind's next order.
1661    fn next_primitives(&mut self, layer_order: Option<DrawOrder>) -> Option<PrimitiveBatch> {
1662        let mut orders_and_kinds = [
1663            (
1664                self.shadows_iter.peek().map(|s| s.order),
1665                PrimitiveKind::Shadow,
1666            ),
1667            (self.quads_iter.peek().map(|q| q.order), PrimitiveKind::Quad),
1668            (
1669                self.backdrop_blur_rects_iter.peek().map(|b| b.order),
1670                PrimitiveKind::BackdropBlurRect,
1671            ),
1672            (
1673                self.effect_quads_iter.peek().map(|e| e.order),
1674                PrimitiveKind::EffectQuad,
1675            ),
1676            (
1677                self.paths_iter.peek().map(|path| path.order),
1678                PrimitiveKind::Path,
1679            ),
1680            (
1681                self.underlines_iter.peek().map(|u| u.order),
1682                PrimitiveKind::Underline,
1683            ),
1684            (
1685                self.monochrome_sprites_iter.peek().map(|s| s.order),
1686                PrimitiveKind::MonochromeSprite,
1687            ),
1688            (
1689                self.subpixel_sprites_iter.peek().map(|s| s.order),
1690                PrimitiveKind::SubpixelSprite,
1691            ),
1692            (
1693                self.polychrome_sprites_iter.peek().map(|s| s.order),
1694                PrimitiveKind::PolychromeSprite,
1695            ),
1696            (
1697                self.surfaces_iter.peek().map(|s| s.order),
1698                PrimitiveKind::Surface,
1699            ),
1700            (layer_order, PrimitiveKind::VnLayer),
1701        ];
1702        orders_and_kinds.sort_by_key(|(order, kind)| (order.unwrap_or(u32::MAX), *kind));
1703
1704        let first = orders_and_kinds[0];
1705        let second = orders_and_kinds[1];
1706        let (batch_kind, max_order_and_kind) = if first.0.is_some() {
1707            (first.1, (second.0.unwrap_or(u32::MAX), second.1))
1708        } else {
1709            return None;
1710        };
1711
1712        match batch_kind {
1713            PrimitiveKind::Shadow => {
1714                let shadows_start = self.shadows_start;
1715                let mut shadows_end = shadows_start + 1;
1716                self.shadows_iter.next();
1717                while self
1718                    .shadows_iter
1719                    .next_if(|shadow| (shadow.order, batch_kind) < max_order_and_kind)
1720                    .is_some()
1721                {
1722                    shadows_end += 1;
1723                }
1724                self.shadows_start = shadows_end;
1725                Some(PrimitiveBatch::Shadows(shadows_start..shadows_end))
1726            }
1727            PrimitiveKind::Quad => {
1728                let quads_start = self.quads_start;
1729                let mut quads_end = quads_start + 1;
1730                self.quads_iter.next();
1731                while self
1732                    .quads_iter
1733                    .next_if(|quad| (quad.order, batch_kind) < max_order_and_kind)
1734                    .is_some()
1735                {
1736                    quads_end += 1;
1737                }
1738                self.quads_start = quads_end;
1739                Some(PrimitiveBatch::Quads(quads_start..quads_end))
1740            }
1741            PrimitiveKind::BackdropBlurRect => {
1742                let backdrop_blur_rects_start = self.backdrop_blur_rects_start;
1743                let mut backdrop_blur_rects_end = backdrop_blur_rects_start + 1;
1744                self.backdrop_blur_rects_iter.next();
1745                while self
1746                    .backdrop_blur_rects_iter
1747                    .next_if(|backdrop_blur_rect| {
1748                        (backdrop_blur_rect.order, batch_kind) < max_order_and_kind
1749                    })
1750                    .is_some()
1751                {
1752                    backdrop_blur_rects_end += 1;
1753                }
1754                self.backdrop_blur_rects_start = backdrop_blur_rects_end;
1755                Some(PrimitiveBatch::BackdropBlurRects(
1756                    backdrop_blur_rects_start..backdrop_blur_rects_end,
1757                ))
1758            }
1759            PrimitiveKind::EffectQuad => {
1760                // Each `effect_id` is a different fragment pipeline, so a run
1761                // breaks when it changes — the same shape as the sprite batches
1762                // breaking on `texture_id`. Its images break it too: a batch
1763                // binds one texture set, its first quad's.
1764                let first = self.effect_quads_iter.peek().unwrap();
1765                let (effect_id, textures) = (first.effect_id, first.texture_set());
1766                let effect_quads_start = self.effect_quads_start;
1767                let mut effect_quads_end = effect_quads_start + 1;
1768                self.effect_quads_iter.next();
1769                while self
1770                    .effect_quads_iter
1771                    .next_if(|effect_quad| {
1772                        (effect_quad.order, batch_kind) < max_order_and_kind
1773                            && effect_quad.effect_id == effect_id
1774                            && effect_quad.texture_set() == textures
1775                    })
1776                    .is_some()
1777                {
1778                    effect_quads_end += 1;
1779                }
1780                self.effect_quads_start = effect_quads_end;
1781                Some(PrimitiveBatch::EffectQuads {
1782                    effect_id,
1783                    range: effect_quads_start..effect_quads_end,
1784                })
1785            }
1786            PrimitiveKind::Path => {
1787                let paths_start = self.paths_start;
1788                let mut paths_end = paths_start + 1;
1789                self.paths_iter.next();
1790                while self
1791                    .paths_iter
1792                    .next_if(|path| (path.order, batch_kind) < max_order_and_kind)
1793                    .is_some()
1794                {
1795                    paths_end += 1;
1796                }
1797                self.paths_start = paths_end;
1798                Some(PrimitiveBatch::Paths(paths_start..paths_end))
1799            }
1800            PrimitiveKind::Underline => {
1801                let underlines_start = self.underlines_start;
1802                let mut underlines_end = underlines_start + 1;
1803                self.underlines_iter.next();
1804                while self
1805                    .underlines_iter
1806                    .next_if(|underline| (underline.order, batch_kind) < max_order_and_kind)
1807                    .is_some()
1808                {
1809                    underlines_end += 1;
1810                }
1811                self.underlines_start = underlines_end;
1812                Some(PrimitiveBatch::Underlines(underlines_start..underlines_end))
1813            }
1814            PrimitiveKind::MonochromeSprite => {
1815                let texture_id = self.monochrome_sprites_iter.peek().unwrap().tile.texture_id;
1816                let sprites_start = self.monochrome_sprites_start;
1817                let mut sprites_end = sprites_start + 1;
1818                self.monochrome_sprites_iter.next();
1819                while self
1820                    .monochrome_sprites_iter
1821                    .next_if(|sprite| {
1822                        (sprite.order, batch_kind) < max_order_and_kind
1823                            && sprite.tile.texture_id == texture_id
1824                    })
1825                    .is_some()
1826                {
1827                    sprites_end += 1;
1828                }
1829                self.monochrome_sprites_start = sprites_end;
1830                Some(PrimitiveBatch::MonochromeSprites {
1831                    texture_id,
1832                    range: sprites_start..sprites_end,
1833                })
1834            }
1835            PrimitiveKind::SubpixelSprite => {
1836                let texture_id = self.subpixel_sprites_iter.peek().unwrap().tile.texture_id;
1837                let sprites_start = self.subpixel_sprites_start;
1838                let mut sprites_end = sprites_start + 1;
1839                self.subpixel_sprites_iter.next();
1840                while self
1841                    .subpixel_sprites_iter
1842                    .next_if(|sprite| {
1843                        (sprite.order, batch_kind) < max_order_and_kind
1844                            && sprite.tile.texture_id == texture_id
1845                    })
1846                    .is_some()
1847                {
1848                    sprites_end += 1;
1849                }
1850                self.subpixel_sprites_start = sprites_end;
1851                Some(PrimitiveBatch::SubpixelSprites {
1852                    texture_id,
1853                    range: sprites_start..sprites_end,
1854                })
1855            }
1856            PrimitiveKind::PolychromeSprite => {
1857                let texture_id = self.polychrome_sprites_iter.peek().unwrap().tile.texture_id;
1858                let sprites_start = self.polychrome_sprites_start;
1859                let mut sprites_end = sprites_start + 1;
1860                self.polychrome_sprites_iter.next();
1861                while self
1862                    .polychrome_sprites_iter
1863                    .next_if(|sprite| {
1864                        (sprite.order, batch_kind) < max_order_and_kind
1865                            && sprite.tile.texture_id == texture_id
1866                    })
1867                    .is_some()
1868                {
1869                    sprites_end += 1;
1870                }
1871                self.polychrome_sprites_start = sprites_end;
1872                Some(PrimitiveBatch::PolychromeSprites {
1873                    texture_id,
1874                    range: sprites_start..sprites_end,
1875                })
1876            }
1877            PrimitiveKind::Surface => {
1878                let surfaces_start = self.surfaces_start;
1879                let mut surfaces_end = surfaces_start + 1;
1880                self.surfaces_iter.next();
1881                while self
1882                    .surfaces_iter
1883                    .next_if(|surface| (surface.order, batch_kind) < max_order_and_kind)
1884                    .is_some()
1885                {
1886                    surfaces_end += 1;
1887                }
1888                self.surfaces_start = surfaces_end;
1889                Some(PrimitiveBatch::Surfaces(surfaces_start..surfaces_end))
1890            }
1891            // `next` takes a composite that comes first.
1892            PrimitiveKind::VnLayer => None,
1893        }
1894    }
1895}
1896
1897#[derive(Debug)]
1898#[cfg_attr(
1899    all(
1900        any(target_os = "linux", target_os = "freebsd"),
1901        not(any(feature = "x11", feature = "wayland"))
1902    ),
1903    allow(dead_code)
1904)]
1905#[allow(missing_docs)]
1906pub enum PrimitiveBatch {
1907    Shadows(Range<usize>),
1908    Quads(Range<usize>),
1909    BackdropBlurRects(Range<usize>),
1910    EffectQuads {
1911        effect_id: u32,
1912        range: Range<usize>,
1913    },
1914    Paths(Range<usize>),
1915    Underlines(Range<usize>),
1916    MonochromeSprites {
1917        texture_id: AtlasTextureId,
1918        range: Range<usize>,
1919    },
1920    #[cfg_attr(target_os = "macos", allow(dead_code))]
1921    SubpixelSprites {
1922        texture_id: AtlasTextureId,
1923        range: Range<usize>,
1924    },
1925    PolychromeSprites {
1926        texture_id: AtlasTextureId,
1927        range: Range<usize>,
1928    },
1929    Surfaces(Range<usize>),
1930}
1931
1932impl PrimitiveBatch {
1933    #[expect(missing_docs)]
1934    pub fn label(&self) -> String {
1935        match self {
1936            Self::Shadows(range) => format!("shadows ({})", range.len()),
1937            Self::Quads(range) => format!("quads ({})", range.len()),
1938            Self::BackdropBlurRects(range) => {
1939                format!("backdrop blur rects ({})", range.len())
1940            }
1941            Self::EffectQuads { effect_id, range } => {
1942                format!("effect quads ({}) with effect {}", range.len(), effect_id)
1943            }
1944            Self::Paths(range) => format!("paths ({})", range.len()),
1945            Self::Underlines(range) => format!("underlines ({})", range.len()),
1946            Self::MonochromeSprites { texture_id, range } => {
1947                format!(
1948                    "monochrome sprites ({}) on atlas {}",
1949                    range.len(),
1950                    texture_id.index
1951                )
1952            }
1953            Self::SubpixelSprites { texture_id, range } => {
1954                format!(
1955                    "subpixel sprites ({}) on atlas {}",
1956                    range.len(),
1957                    texture_id.index
1958                )
1959            }
1960            Self::PolychromeSprites { texture_id, range } => {
1961                format!(
1962                    "polychrome sprites ({}) on atlas {}",
1963                    range.len(),
1964                    texture_id.index
1965                )
1966            }
1967            Self::Surfaces(range) => format!("surfaces ({})", range.len()),
1968        }
1969    }
1970}
1971
1972/// Keep the field order in sync with `struct Quad` in
1973/// `gpui_windows/src/shaders.hlsl` (85 words / 340 bytes) — the DirectX
1974/// renderer uploads this straight into a `StructuredBuffer` and
1975/// `StructureByteStride` is `size_of::<Quad>()`, so the Rust layout IS the
1976/// shader layout.
1977#[derive(Default, Debug, Copy, Clone)]
1978#[repr(C)]
1979#[expect(missing_docs)]
1980pub struct Quad {
1981    pub order: DrawOrder,
1982    pub border_style: BorderStyle,
1983    pub bounds: Bounds<ScaledPixels>,
1984    pub content_mask: ContentMask<ScaledPixels>,
1985    pub background: Background,
1986    pub border_color: Hsla,
1987    pub corner_radii: Corners<ScaledPixels>,
1988    pub border_widths: Edges<ScaledPixels>,
1989    /// A paint-time transformation of the quad about its own centre — CSS
1990    /// `transform`.
1991    ///
1992    /// `bounds` stays the UNTRANSFORMED rect and is still what the scene sorts
1993    /// and culls by; the vertex shader applies this on top and the fragment
1994    /// shader keeps doing its SDF work in the untransformed local frame. That
1995    /// split is deliberate: it is what lets the rounded corners, the border
1996    /// widths and the dash phase stay correct under rotation without any of
1997    /// them learning about the matrix.
1998    pub transformation: TransformationMatrix,
1999}
2000
2001impl From<Quad> for Primitive {
2002    fn from(quad: Quad) -> Self {
2003        Primitive::Quad(quad)
2004    }
2005}
2006
2007/// Maximum number of GPU blur downsample/upsample levels a backdrop blur rect
2008/// may request.
2009pub const MAX_BACKDROP_BLUR_KERNEL_LEVELS: u32 = 5;
2010
2011/// Scaled pixels of CSS `blur()` radius covered by one Dual-Kawase pyramid
2012/// level.
2013const BACKDROP_BLUR_RADIUS_PER_KERNEL_LEVEL: f32 = 5.;
2014
2015/// A rounded rect that replaces the pixels already painted behind it with a
2016/// blurred copy of them — the primitive behind CSS `backdrop-filter: blur()`.
2017///
2018/// Keep the field order in sync with `struct BlurRect` in
2019/// `gpui_windows/src/shaders.hlsl` (20 words / 80 bytes).
2020#[derive(Debug, Copy, Clone)]
2021#[repr(C)]
2022#[expect(missing_docs)]
2023pub struct BackdropBlurRect {
2024    pub order: DrawOrder,
2025    pub pad: u32,
2026    pub bounds: Bounds<ScaledPixels>,
2027    pub content_mask: ContentMask<ScaledPixels>,
2028    pub corner_radii: Corners<ScaledPixels>,
2029    pub blur_radius: ScaledPixels,
2030    pub opacity: f32,
2031    pub tint: Hsla,
2032}
2033
2034impl Default for BackdropBlurRect {
2035    fn default() -> Self {
2036        Self {
2037            order: Default::default(),
2038            pad: Default::default(),
2039            bounds: Default::default(),
2040            content_mask: Default::default(),
2041            corner_radii: Default::default(),
2042            blur_radius: Default::default(),
2043            opacity: 1.,
2044            tint: Default::default(),
2045        }
2046    }
2047}
2048
2049impl BackdropBlurRect {
2050    /// Returns the clamped number of blur kernel levels required by this rect.
2051    ///
2052    /// # Known divergence from CSS `blur()`
2053    ///
2054    /// The radius is quantised to whole Dual-Kawase pyramid levels and then
2055    /// clamped to [`MAX_BACKDROP_BLUR_KERNEL_LEVELS`], so the mapping from CSS
2056    /// radius to visual blur **saturates**. It bites when
2057    ///
2058    /// ```text
2059    /// radius_css > MAX_BACKDROP_BLUR_KERNEL_LEVELS * BACKDROP_BLUR_RADIUS_PER_KERNEL_LEVEL / scale_factor
2060    ///            = 25px @ 100% DPI, 20px @ 125%, 16.7px @ 150%, 12.5px @ 200%
2061    /// ```
2062    ///
2063    /// Past that point `blur(30px)` and `blur(100px)` render identically, and
2064    /// below it the radius steps in 5-scaled-pixel increments rather than
2065    /// continuously. Browsers are continuous and unbounded.
2066    ///
2067    /// Fixing it properly means scaling the upsample tap offsets by the
2068    /// fractional remainder, which is a per-*group* uniform (the pyramid is
2069    /// built once per non-overlapping group) rather than a per-rect one — so it
2070    /// needs the group split to also break on fractional radius. Deferred: the
2071    /// UI range that matters (8–20px glass) is inside the linear part.
2072    pub fn effective_kernel_levels(&self) -> u32 {
2073        if self.blur_radius.0 <= 0. {
2074            0
2075        } else {
2076            let radius_levels = (self.blur_radius.0 / BACKDROP_BLUR_RADIUS_PER_KERNEL_LEVEL)
2077                .ceil()
2078                .max(1.) as u32;
2079            radius_levels.min(MAX_BACKDROP_BLUR_KERNEL_LEVELS)
2080        }
2081    }
2082}
2083
2084impl From<BackdropBlurRect> for Primitive {
2085    fn from(backdrop_blur_rect: BackdropBlurRect) -> Self {
2086        Primitive::BackdropBlurRect(backdrop_blur_rect)
2087    }
2088}
2089
2090/// The built-in effect a [`EffectQuad`] selects, and the index of its pipeline
2091/// in the renderer's effect table.
2092///
2093/// gpui deliberately does not know what these effects *do* — the shader
2094/// sources, the CSS parameter schemas and the defaults all live in
2095/// `crates/sk-effects`, which is above gpui in the dependency graph. What lives
2096/// here is only the numbering, because three separate places have to agree on
2097/// it: this enum, the pipeline table in `gpui_windows`, and the registry in
2098/// `sk-effects`.
2099pub mod effect_id {
2100    /// `frost(strength, radius?, tint?)` — blurred backdrop + crystalline
2101    /// grain + rim highlight. Reads the backdrop.
2102    pub const FROST: u32 = 0;
2103    /// `noise(amount, scale?, speed?)` — film grain over the element.
2104    pub const NOISE: u32 = 1;
2105    /// `glow(color?, radius, strength)` — soft halo around the border box.
2106    pub const GLOW: u32 = 2;
2107    /// How many built-in effects exist.
2108    pub const COUNT: u32 = 3;
2109    /// vue-native: not an effect a stylesheet can name. An [`super::EffectQuad`]
2110    /// with this id ERASES what was painted under it — its rounded rect, cut
2111    /// by its content mask, becomes transparent — so a surface composited
2112    /// under the window (an `<iframe>`'s webview) shows through there. See
2113    /// `Window::vn_paint_punch`. A renderer without it draws nothing.
2114    pub const PUNCH: u32 = u32::MAX - 1;
2115    /// vue-native: not an effect a stylesheet can name. Draws the content an
2116    /// [`super::VnEffectLayer`] reads as it is, at the quad's opacity: what
2117    /// shows of the element while its `[SkContent]` effect fades in or out,
2118    /// or when the effect cannot be drawn.
2119    pub const CONTENT: u32 = u32::MAX - 2;
2120    /// The id an [`super::EffectSpec`] carries when CSS said `--shading: none`.
2121    /// A refinement has no way to spell "explicitly nothing", so — exactly as
2122    /// `backdrop-filter: none` maps to a 0px radius — clearing is a *value*.
2123    pub const NONE: u32 = u32::MAX;
2124}
2125
2126/// Bit 0 of [`EffectQuad::flags`]: this effect samples the backdrop, so the
2127/// renderer must snapshot the render target, run the blur pyramid, bind t0/t2
2128/// and draw with blending disabled.
2129pub const EFFECT_FLAG_NEEDS_BACKDROP: u32 = 1;
2130
2131/// Bit 1 of [`EffectQuad::flags`]: the effect reads its element's painted
2132/// subtree (`[SkContent]`), so the element paints into an isolated group the
2133/// effect samples at t7 and composites in its place.
2134pub const EFFECT_FLAG_NEEDS_CONTENT: u32 = 2;
2135
2136/// Bit 2 of [`EffectQuad::flags`]: the effect keeps its own state from frame
2137/// to frame (`[SkHistory]`), at t8. A renderer clears it on a quad it has no
2138/// history for, which then reads zeros.
2139pub const EFFECT_FLAG_HISTORY: u32 = 4;
2140
2141/// Bit 3 of [`EffectQuad::flags`], set by the renderer only: this draw writes
2142/// the next history state instead of the element's pixels.
2143pub const EFFECT_FLAG_HISTORY_PASS: u32 = 8;
2144
2145/// CSS `transform`, as the cascade computed it, carried on [`crate::Style`]
2146/// and turned into a [`TransformationMatrix`] at paint time by
2147/// [`crate::Style::paint`].
2148///
2149/// Deliberately the CSS *components* rather than a finished matrix, for two
2150/// reasons. The matrix needs the element's box to know where its centre is —
2151/// CSS's initial `transform-origin: 50% 50%` — and layout only settles at
2152/// paint. And an interpolable `transform` interpolates its components (a
2153/// browser lerps `rotate(0deg)` → `rotate(90deg)` through 45°, not through the
2154/// matrix entries), so a transition wants these numbers, not their product.
2155///
2156/// The rendering rule is CSS's: a transform moves the element's **painted
2157/// output and its whole subtree**, and changes no layout at all. `translate`
2158/// here is therefore *not* the same thing as a margin offset — siblings do not
2159/// move out of the way.
2160#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
2161#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2162pub struct TransformSpec {
2163    /// `translate()`, per axis, in the unit it was authored in — see
2164    /// [`TransformLength`]. Kept unresolved because a percentage resolves
2165    /// against the element's OWN border box, which is only known at paint.
2166    pub translate: (TransformLength, TransformLength),
2167    /// `rotate()` about the element's centre, in RADIANS, clockwise — which is
2168    /// the direction a positive CSS angle turns on screen.
2169    pub rotate: f32,
2170    /// `scale()` about the element's centre. `(1.0, 1.0)` is no scale.
2171    pub scale: (f32, f32),
2172    /// Upper-right coefficient of the linear matrix before rotation:
2173    /// `R * [[scale.x, shear], [0, scale.y]]`. Unlike a tangent multiplied by
2174    /// scale.y this also represents finite rank-one/zero-scale matrices.
2175    #[serde(default)]
2176    pub shear: f32,
2177    /// Ordered transform lists can mix pixel translations with percentages of
2178    /// either box axis. When present, each row is `[pixels, width, height]`
2179    /// and replaces `translate` at paint time. Ordinary TRS lists need none.
2180    #[serde(default)]
2181    pub translation_basis: Option<[[f32; 3]; 2]>,
2182    /// `transform-origin`, per axis, relative to the element's own border box —
2183    /// the point `rotate()` and `scale()` act about. CSS's initial value is
2184    /// `50% 50%`, i.e. `(Fraction(0.5), Fraction(0.5))`, which is what
2185    /// [`TransformSpec::IDENTITY`] carries.
2186    ///
2187    /// Kept in the same authored unit as `translate` and for the same reason: a
2188    /// percentage origin resolves against the element's own box, which is only
2189    /// known at paint. Unlike `translate` it is measured from the box's
2190    /// TOP-LEFT, not from its centre, because that is how CSS writes it.
2191    pub origin: (TransformLength, TransformLength),
2192}
2193
2194/// One axis of a [`TransformSpec`]'s `translate()`.
2195#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
2196#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2197pub enum TransformLength {
2198    /// An absolute length in LOGICAL (CSS) pixels.
2199    Pixels(f32),
2200    /// A fraction of the element's own border box on this axis: `-50%` is
2201    /// `-0.5`. This is the unit `translate(-50%, -50%)` centring idiom is
2202    /// written in, and it cannot be resolved before layout.
2203    Fraction(f32),
2204}
2205
2206impl TransformLength {
2207    /// Zero, in either unit — the identity translate.
2208    pub const ZERO: Self = Self::Pixels(0.0);
2209
2210    /// Resolves against the element's own size along this axis.
2211    pub fn resolve(self, own: f32) -> f32 {
2212        match self {
2213            Self::Pixels(v) => v,
2214            Self::Fraction(f) => f * own,
2215        }
2216    }
2217
2218    /// Is this zero, whatever unit it is written in?
2219    pub fn is_zero(self) -> bool {
2220        match self {
2221            Self::Pixels(v) | Self::Fraction(v) => v == 0.0,
2222        }
2223    }
2224
2225    /// Interpolates between two authored lengths.
2226    ///
2227    /// Same units interpolate. Mixed units cannot without knowing the box, and
2228    /// CSS would produce a `calc()` there — except when one side is zero, which
2229    /// is the same length in both units and so adopts the other's. Anything
2230    /// else snaps at the halfway point, which is the discrete behaviour the
2231    /// rest of this animator already uses for uninterpolable pairs.
2232    pub fn interpolate(self, other: Self, t: f32) -> Self {
2233        let lerp = |a: f32, b: f32| a + (b - a) * t;
2234        match (self, other) {
2235            (Self::Pixels(a), Self::Pixels(b)) => Self::Pixels(lerp(a, b)),
2236            (Self::Fraction(a), Self::Fraction(b)) => Self::Fraction(lerp(a, b)),
2237            (a, b) if a.is_zero() => match b {
2238                Self::Pixels(v) => Self::Pixels(lerp(0.0, v)),
2239                Self::Fraction(v) => Self::Fraction(lerp(0.0, v)),
2240            },
2241            (a, b) if b.is_zero() => match a {
2242                Self::Pixels(v) => Self::Pixels(lerp(v, 0.0)),
2243                Self::Fraction(v) => Self::Fraction(lerp(v, 0.0)),
2244            },
2245            (a, b) => {
2246                if t < 0.5 {
2247                    a
2248                } else {
2249                    b
2250                }
2251            }
2252        }
2253    }
2254}
2255
2256impl Default for TransformSpec {
2257    fn default() -> Self {
2258        Self::IDENTITY
2259    }
2260}
2261
2262impl TransformSpec {
2263    /// `transform: none`.
2264    pub const IDENTITY: Self = Self {
2265        translate: (TransformLength::ZERO, TransformLength::ZERO),
2266        rotate: 0.0,
2267        scale: (1.0, 1.0),
2268        origin: Self::CENTRE_ORIGIN,
2269        shear: 0.0,
2270        translation_basis: None,
2271    };
2272
2273    /// CSS's initial `transform-origin: 50% 50%`.
2274    pub const CENTRE_ORIGIN: (TransformLength, TransformLength) =
2275        (TransformLength::Fraction(0.5), TransformLength::Fraction(0.5));
2276
2277    /// Is this `transform: none` — nothing to apply, nothing to pay for?
2278    ///
2279    /// `transform-origin` is deliberately NOT part of the answer: an origin on
2280    /// its own changes nothing, exactly as in CSS, and asking otherwise would
2281    /// make every element that merely declares one pay for a matrix.
2282    pub fn is_identity(&self) -> bool {
2283        self.rotate == 0.0
2284            && self.scale == (1.0, 1.0)
2285            && self.shear == 0.0
2286            && match self.translation_basis {
2287                Some(basis) => basis.iter().flatten().all(|v| *v == 0.0),
2288                None => self.translate.0.is_zero() && self.translate.1.is_zero(),
2289            }
2290    }
2291
2292    fn translation_coefficients(&self) -> [[f32; 3]; 2] {
2293        self.translation_basis.unwrap_or_else(|| {
2294            let x = match self.translate.0 {
2295                TransformLength::Pixels(v) => [v, 0.0, 0.0],
2296                TransformLength::Fraction(v) => [0.0, v, 0.0],
2297            };
2298            let y = match self.translate.1 {
2299                TransformLength::Pixels(v) => [v, 0.0, 0.0],
2300                TransformLength::Fraction(v) => [0.0, 0.0, v],
2301            };
2302            [x, y]
2303        })
2304    }
2305    /// Componentwise interpolation, which is what a browser does when both
2306    /// sides are the same function list: `rotate(0deg)` → `rotate(90deg)`
2307    /// sweeps through 45°, not through the matrix entries (which would shear).
2308    pub fn interpolate(self, other: Self, t: f32) -> Self {
2309        let lerp = |a: f32, b: f32| a + (b - a) * t;
2310        Self {
2311            translate: (
2312                self.translate.0.interpolate(other.translate.0, t),
2313                self.translate.1.interpolate(other.translate.1, t),
2314            ),
2315            rotate: lerp(self.rotate, other.rotate),
2316            shear: lerp(self.shear, other.shear),
2317            translation_basis: if self.translation_basis.is_some() || other.translation_basis.is_some() {
2318                let a = self.translation_coefficients();
2319                let b = other.translation_coefficients();
2320                Some(std::array::from_fn(|row| std::array::from_fn(|column| lerp(a[row][column], b[row][column]))))
2321            } else { None },
2322            scale: (
2323                lerp(self.scale.0, other.scale.0),
2324                lerp(self.scale.1, other.scale.1),
2325            ),
2326            origin: (
2327                self.origin.0.interpolate(other.origin.0, t),
2328                self.origin.1.interpolate(other.origin.1, t),
2329            ),
2330        }
2331    }
2332
2333    /// The device-space matrix for an element whose border box is `bounds`.
2334    ///
2335    /// Read bottom-up, as matrix products are: move the centre to the origin,
2336    /// scale, rotate, then move back — plus the translate, which rides on the
2337    /// recentring so it is applied in the element's own frame.
2338    ///
2339    /// The point rotate/scale act about is `origin`, resolved against the box
2340    /// and measured from its top-left — CSS's `transform-origin`, whose initial
2341    /// `50% 50%` lands exactly on the centre.
2342    pub fn to_matrix(self, bounds: Bounds<Pixels>, scale_factor: f32) -> TransformationMatrix {
2343        let anchor = bounds.origin
2344            + Point::new(
2345                px(self.origin.0.resolve(bounds.size.width.0)),
2346                px(self.origin.1.resolve(bounds.size.height.0)),
2347            );
2348        let coefficients = self.translation_coefficients();
2349        let resolve = |row: [f32; 3]| px(row[0] + row[1] * bounds.size.width.0 + row[2] * bounds.size.height.0);
2350        let translate = Point::new(resolve(coefficients[0]), resolve(coefficients[1]));
2351        TransformationMatrix::unit()
2352            .translate((anchor + translate).scale(scale_factor))
2353            .rotate(Radians(self.rotate))
2354            .compose(TransformationMatrix {
2355                rotation_scale: [[self.scale.0, self.shear], [0.0, self.scale.1]],
2356                translation: [0.0, 0.0],
2357            })
2358            .translate(anchor.scale(-scale_factor))
2359    }
2360}
2361
2362/// How many floats an effect's parameter block holds ([`EffectSpec::params`],
2363/// [`EffectQuad::params`]).
2364pub const EFFECT_PARAM_SLOTS: usize = 32;
2365
2366/// The `--shading` value that came out of the cascade, carried on
2367/// [`crate::Style`] and painted by [`crate::Style::paint`].
2368///
2369/// The `params` are the effect's positional CSS arguments, already
2370/// converted to floats (a colour occupies four consecutive slots), plus the
2371/// slots the host fills at paint time. Everything else is schema metadata the
2372/// *painter* needs and gpui must not have to look up: which params are lengths
2373/// (so they scale with the device factor), which one drives the backdrop blur,
2374/// which one dilates the quad, and which ones the host writes.
2375#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
2376#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2377pub struct EffectSpec {
2378    /// One of [`effect_id`].
2379    pub id: u32,
2380    /// [`EFFECT_FLAG_NEEDS_BACKDROP`], …
2381    pub flags: u32,
2382    /// Bit *i* set means `params[i]` is a length in LOGICAL pixels, to be
2383    /// multiplied by the device scale factor at paint time.
2384    pub length_mask: u32,
2385    /// `Some(i)`: `params[i]` (a logical-pixel length) is the backdrop blur
2386    /// radius. Only meaningful with [`EFFECT_FLAG_NEEDS_BACKDROP`].
2387    pub backdrop_radius_param: Option<u8>,
2388    /// `Some(i)`: `params[i]` (a logical-pixel length) dilates the painted
2389    /// quad, giving an outer glow somewhere to land.
2390    pub bleed_param: Option<u8>,
2391    /// Whether this effect's output depends on `time`, i.e. whether the window
2392    /// must keep repainting for it to animate.
2393    pub animated: bool,
2394    /// `Some(i)`: `params[i]` is a speed `time` is multiplied by, which the
2395    /// painter integrates per element so a change of it does not jump.
2396    #[serde(default)]
2397    pub animated_param: Option<u8>,
2398    /// `Some(i)`: the painter writes the pointer's position in the element's
2399    /// 0..1 box units into `params[i..i + 2]`.
2400    pub pointer_param: Option<u8>,
2401    /// `Some(i)`: the painter writes the pointer's last move, entry into the
2402    /// window and exit from it, on the effect clock, into `params[i..i + 3]`.
2403    pub pointer_times_param: Option<u8>,
2404    /// Bit *i* set means `params[i]` is a time on the effect clock; the
2405    /// element keeps repainting until `clock_window` seconds after the latest.
2406    pub clock_mask: u32,
2407    /// Seconds an effect keeps repainting after the times in `clock_mask`.
2408    pub clock_window: f32,
2409    /// The positional parameters, in schema order.
2410    pub params: [f32; EFFECT_PARAM_SLOTS],
2411    /// The `SkTexture` parameters by binding: `None` past the ones the effect
2412    /// declares.
2413    #[serde(default)]
2414    pub textures: [Option<crate::EffectTextureParam>; crate::EFFECT_TEXTURE_SLOTS],
2415}
2416
2417impl EffectSpec {
2418    /// `--shading: none` — a value that clears an effect inherited from an
2419    /// earlier rule in the cascade.
2420    pub const NONE: EffectSpec = EffectSpec {
2421        id: effect_id::NONE,
2422        flags: 0,
2423        length_mask: 0,
2424        backdrop_radius_param: None,
2425        bleed_param: None,
2426        animated: false,
2427        animated_param: None,
2428        pointer_param: None,
2429        pointer_times_param: None,
2430        clock_mask: 0,
2431        clock_window: 0.,
2432        params: [0.; EFFECT_PARAM_SLOTS],
2433        textures: [None; crate::EFFECT_TEXTURE_SLOTS],
2434    };
2435
2436    /// Whether this spec actually paints anything.
2437    pub fn is_some(&self) -> bool {
2438        self.id != effect_id::NONE
2439    }
2440
2441    /// Whether a transition can interpolate from `self` to `other` slot by
2442    /// slot: the same effect sampling the same images. Otherwise it
2443    /// cross-fades, since an image does not interpolate.
2444    pub fn interpolates_with(&self, other: &EffectSpec) -> bool {
2445        self.id == other.id && self.textures == other.textures
2446    }
2447
2448    /// Whether the painter fills a pointer parameter, so the element repaints
2449    /// when the pointer moves.
2450    pub fn follows_pointer(&self) -> bool {
2451        self.pointer_param.is_some() || self.pointer_times_param.is_some()
2452    }
2453
2454    /// Whether `now` (effect-clock seconds) is within `clock_window` of the
2455    /// latest time in a `clock_mask` slot.
2456    pub fn clock_running(&self, now: f32) -> bool {
2457        if self.clock_mask == 0 {
2458            return false;
2459        }
2460        self.params
2461            .iter()
2462            .enumerate()
2463            .filter(|(slot, _)| self.clock_mask & (1 << slot) != 0)
2464            .any(|(_, start)| now < start + self.clock_window)
2465    }
2466
2467    fn param(&self, index: Option<u8>) -> f32 {
2468        index
2469            .and_then(|i| self.params.get(i as usize))
2470            .copied()
2471            .unwrap_or(0.)
2472    }
2473
2474    /// The quad dilation in logical pixels.
2475    pub fn bleed(&self) -> f32 {
2476        self.param(self.bleed_param).max(0.)
2477    }
2478
2479    /// The backdrop blur radius in logical pixels.
2480    pub fn backdrop_blur_radius(&self) -> f32 {
2481        self.param(self.backdrop_radius_param).max(0.)
2482    }
2483}
2484
2485/// A `--shading` transition between two different effects: `from` paints at
2486/// `1 - progress` beneath the style's own effect at `progress`.
2487#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
2488#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2489pub struct EffectCrossFade {
2490    /// The effect being faded out.
2491    pub from: EffectSpec,
2492    /// 0 shows only `from`, 1 only the style's effect.
2493    pub progress: f32,
2494}
2495
2496/// A rounded rect shaded by a custom fragment pipeline — the primitive behind
2497/// the `--shading` CSS property.
2498///
2499/// Mechanically this is [`BackdropBlurRect`] with a swappable fragment shader
2500/// and a parameter block, and it reuses that primitive's whole machinery: the
2501/// render-target snapshot, the Dual-Kawase pyramid, the per-group re-snapshot,
2502/// and the "everything painted after must draw after" ordering guarantee.
2503///
2504/// `bounds`/`corner_radii` describe the *drawn* quad, which is the element's
2505/// border box dilated by `bleed`. Dilating a rounded rect is a Minkowski sum
2506/// with a disc, so the element's own SDF is exactly the drawn quad's plus
2507/// `bleed` — which is how the shader recovers one from the other with a single
2508/// add instead of a second bounds pair.
2509///
2510/// Keep the field order in sync with `struct EffectQuad` in
2511/// `gpui_windows/src/effects.hlsl` and with `struct VnEffectQuad` in the
2512/// generated wrapper (`scripts/shaders.ts`).
2513/// 56 words / 224 bytes.
2514#[derive(Debug, Copy, Clone, Default)]
2515#[repr(C)]
2516#[expect(missing_docs)]
2517pub struct EffectQuad {
2518    pub order: DrawOrder,
2519    /// Selects the pipeline; one of [`effect_id`].
2520    pub effect_id: u32,
2521    /// The element's border box, dilated by `bleed`.
2522    pub bounds: Bounds<ScaledPixels>,
2523    pub content_mask: ContentMask<ScaledPixels>,
2524    /// The element's corner radii, dilated by `bleed`.
2525    pub corner_radii: Corners<ScaledPixels>,
2526    /// The effect's parameter block, [`EFFECT_PARAM_SLOTS`] long (a literal for
2527    /// the Metal header cbindgen writes).
2528    pub params: [f32; 32],
2529    pub opacity: f32,
2530    /// Seconds on [`effect_clock_seconds`].
2531    pub time: f32,
2532    /// How far outside the element's border box this quad reaches.
2533    pub bleed: ScaledPixels,
2534    /// The blur radius applied to the backdrop before the effect sees it.
2535    /// Ignored without [`EFFECT_FLAG_NEEDS_BACKDROP`].
2536    pub backdrop_blur_radius: ScaledPixels,
2537    /// Device pixels per logical pixel.
2538    pub scale: f32,
2539    pub flags: u32,
2540}
2541
2542impl EffectQuad {
2543    /// A parameter block holding `head` in its first slots and zeros after.
2544    pub fn params_from(head: &[f32]) -> [f32; EFFECT_PARAM_SLOTS] {
2545        let mut params = [0.; EFFECT_PARAM_SLOTS];
2546        params[..head.len()].copy_from_slice(head);
2547        params
2548    }
2549
2550    /// Whether this quad reads the render-target snapshot, which decides both
2551    /// its draw ordering and whether the renderer has to break the pass.
2552    pub fn needs_backdrop(&self) -> bool {
2553        self.flags & EFFECT_FLAG_NEEDS_BACKDROP != 0
2554    }
2555
2556    /// Whether this quad reads its element's content ([`EFFECT_FLAG_NEEDS_CONTENT`]).
2557    pub fn needs_content(&self) -> bool {
2558        self.flags & EFFECT_FLAG_NEEDS_CONTENT != 0
2559    }
2560
2561    /// Whether this quad reads and steps a history ([`EFFECT_FLAG_HISTORY`]).
2562    pub fn has_history(&self) -> bool {
2563        self.flags & EFFECT_FLAG_HISTORY != 0
2564    }
2565
2566    /// The device-pixel size of this quad's history texture.
2567    pub fn history_size(&self) -> (u32, u32) {
2568        let side = |value: f32| (value.round().max(1.)) as u32;
2569        (
2570            side(self.bounds.size.width.0),
2571            side(self.bounds.size.height.0),
2572        )
2573    }
2574
2575    /// The copy a renderer draws into the history target to step it.
2576    pub fn history_pass(mut self) -> Self {
2577        self.flags = (self.flags & !EFFECT_FLAG_NEEDS_BACKDROP) | EFFECT_FLAG_HISTORY_PASS;
2578        self
2579    }
2580
2581    /// The clamped number of Dual-Kawase pyramid levels this quad's backdrop
2582    /// needs — the same quantisation (and the same saturation defect) as
2583    /// [`BackdropBlurRect::effective_kernel_levels`].
2584    pub fn effective_kernel_levels(&self) -> u32 {
2585        if !self.needs_backdrop() || self.backdrop_blur_radius.0 <= 0. {
2586            0
2587        } else {
2588            let radius_levels = (self.backdrop_blur_radius.0
2589                / BACKDROP_BLUR_RADIUS_PER_KERNEL_LEVEL)
2590                .ceil()
2591                .max(1.) as u32;
2592            radius_levels.min(MAX_BACKDROP_BLUR_KERNEL_LEVELS)
2593        }
2594    }
2595}
2596
2597impl From<EffectQuad> for Primitive {
2598    fn from(effect_quad: EffectQuad) -> Self {
2599        Primitive::EffectQuad(effect_quad, None)
2600    }
2601}
2602
2603const _: () = assert!(std::mem::size_of::<EffectQuad>() == 224);
2604const _: () = assert!(EFFECT_PARAM_SLOTS == 32);
2605
2606// The four primitives that carry a CSS `transform`. Their Rust layout IS the
2607// shader layout on every backend — the DirectX renderer uses
2608// `size_of::<T>()` as the structured buffer's `StructureByteStride`, and
2609// `gpui_wgpu/src/shaders_webgl.wgsl` hardcodes the same numbers as word
2610// strides. A field added without updating the shaders reads the next record's
2611// bytes and produces garbage rather than an error, so the sizes are asserted
2612// here where a mismatch is a compile failure.
2613//
2614// Word counts, for the shader side: 89 / 42 / 26 / 38. (vue-native fork: each
2615// grew by four, the content mask's corner radii; `PolychromeSprite` by four
2616// more, its `tint`, and `Shadow` by four more, its `element_bounds`.)
2617//
2618// `Quad` carries a `Background`, which is 57 words since it grew from a
2619// two-stop linear ramp to an eight-stop linear / radial / conic one with
2620// repeat and tiling (`color.rs`). `PathRasterizationVertex` carries one too
2621// and is asserted next to the WebGL word strides in `gpui_wgpu`.
2622const _: () = assert!(std::mem::size_of::<Quad>() == 89 * 4);
2623const _: () = assert!(std::mem::size_of::<Background>() == 57 * 4);
2624const _: () = assert!(std::mem::size_of::<Shadow>() == 42 * 4);
2625const _: () = assert!(std::mem::size_of::<Underline>() == 26 * 4);
2626const _: () = assert!(std::mem::size_of::<PolychromeSprite>() == 38 * 4);
2627const _: () = assert!(std::mem::size_of::<TransformationMatrix>() == 6 * 4);
2628
2629static EFFECT_CLOCK_ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
2630
2631/// Seconds since the effect clock's origin — the clock [`EffectQuad::time`]
2632/// carries. The origin is [`set_effect_clock_origin`]'s, or the first read.
2633///
2634/// Deliberately process-wide and monotonic rather than per-window: an f32 has
2635/// ~7 significant digits, so anchoring at zero keeps sub-millisecond precision
2636/// for the first couple of hours instead of quantising to ~64 ms the way a
2637/// UNIX-epoch value would.
2638pub fn effect_clock_seconds() -> f32 {
2639    EFFECT_CLOCK_ORIGIN
2640        .get_or_init(std::time::Instant::now)
2641        .elapsed()
2642        .as_secs_f32()
2643}
2644
2645/// Anchors the effect clock, so an embedder can make it share a zero with its
2646/// own (a JS `performance.now()`). Returns `false` once the clock has been read.
2647pub fn set_effect_clock_origin(origin: std::time::Instant) -> bool {
2648    EFFECT_CLOCK_ORIGIN.set(origin).is_ok()
2649}
2650
2651#[derive(Debug, Copy, Clone)]
2652#[repr(C)]
2653#[expect(missing_docs)]
2654pub struct Underline {
2655    pub order: DrawOrder,
2656    pub pad: u32, // align to 8 bytes
2657    pub bounds: Bounds<ScaledPixels>,
2658    pub content_mask: ContentMask<ScaledPixels>,
2659    pub color: Hsla,
2660    pub thickness: ScaledPixels,
2661    pub wavy: PaddedBool32,
2662    /// See [`Quad::transformation`]. An underline rides along with the text it
2663    /// decorates, so it takes the same ambient transform the glyph sprites do.
2664    pub transformation: TransformationMatrix,
2665}
2666
2667impl From<Underline> for Primitive {
2668    fn from(underline: Underline) -> Self {
2669        Primitive::Underline(underline)
2670    }
2671}
2672
2673#[derive(Debug, Copy, Clone)]
2674#[repr(C)]
2675#[expect(missing_docs)]
2676pub struct Shadow {
2677    pub order: DrawOrder,
2678    pub blur_radius: ScaledPixels,
2679    pub bounds: Bounds<ScaledPixels>,
2680    pub corner_radii: Corners<ScaledPixels>,
2681    pub content_mask: ContentMask<ScaledPixels>,
2682    pub color: Hsla,
2683    pub shape_bounds: Bounds<ScaledPixels>,
2684    pub shape_corner_radii: Corners<ScaledPixels>,
2685    /// vue-native fork: `SHADOW_OUTSIDE_BOX`, `SHADOW_INSET` or
2686    /// `SHADOW_UNDER_BOX` (gpui's window.rs).
2687    pub inset: u32,
2688    pub pad: u32, // align to 8 bytes
2689    /// See [`Quad::transformation`]. A shadow is part of the element's own
2690    /// painted content, so a `transform: rotate()` turns the shadow with the
2691    /// box — which is what a browser does.
2692    pub transformation: TransformationMatrix,
2693    /// vue-native fork: the element's border box, with `corner_radii`. An
2694    /// outer shadow is cut out of it; an inset one is clipped to it.
2695    pub element_bounds: Bounds<ScaledPixels>,
2696}
2697
2698impl From<Shadow> for Primitive {
2699    fn from(shadow: Shadow) -> Self {
2700        Primitive::Shadow(shadow)
2701    }
2702}
2703
2704/// The style of a border.
2705#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
2706#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2707#[repr(C)]
2708pub enum BorderStyle {
2709    /// A solid border.
2710    #[default]
2711    Solid = 0,
2712    /// A dashed border.
2713    Dashed = 1,
2714}
2715
2716/// A data type representing a 2 dimensional transformation that can be applied to an element.
2717#[derive(Debug, Clone, Copy, PartialEq)]
2718#[repr(C)]
2719pub struct TransformationMatrix {
2720    /// 2x2 matrix containing rotation and scale,
2721    /// stored row-major
2722    pub rotation_scale: [[f32; 2]; 2],
2723    /// translation vector
2724    pub translation: [f32; 2],
2725}
2726
2727impl Eq for TransformationMatrix {}
2728
2729impl TransformationMatrix {
2730    /// The unit matrix, has no effect.
2731    pub fn unit() -> Self {
2732        Self {
2733            rotation_scale: [[1.0, 0.0], [0.0, 1.0]],
2734            translation: [0.0, 0.0],
2735        }
2736    }
2737
2738    /// Move the origin by a given point
2739    pub fn translate(self, point: Point<ScaledPixels>) -> Self {
2740        self.compose(Self {
2741            rotation_scale: [[1.0, 0.0], [0.0, 1.0]],
2742            translation: [point.x.0, point.y.0],
2743        })
2744    }
2745
2746    /// Clockwise rotation in radians around the origin
2747    pub fn rotate(self, angle: Radians) -> Self {
2748        self.compose(Self {
2749            rotation_scale: [
2750                [angle.0.cos(), -angle.0.sin()],
2751                [angle.0.sin(), angle.0.cos()],
2752            ],
2753            translation: [0.0, 0.0],
2754        })
2755    }
2756
2757    /// Scale around the origin
2758    pub fn scale(self, size: Size<f32>) -> Self {
2759        self.compose(Self {
2760            rotation_scale: [[size.width, 0.0], [0.0, size.height]],
2761            translation: [0.0, 0.0],
2762        })
2763    }
2764
2765    /// Perform matrix multiplication with another transformation
2766    /// to produce a new transformation that is the result of
2767    /// applying both transformations: first, `other`, then `self`.
2768    #[inline]
2769    pub fn compose(self, other: TransformationMatrix) -> TransformationMatrix {
2770        if other == Self::unit() {
2771            return self;
2772        }
2773        // Perform matrix multiplication
2774        TransformationMatrix {
2775            rotation_scale: [
2776                [
2777                    self.rotation_scale[0][0] * other.rotation_scale[0][0]
2778                        + self.rotation_scale[0][1] * other.rotation_scale[1][0],
2779                    self.rotation_scale[0][0] * other.rotation_scale[0][1]
2780                        + self.rotation_scale[0][1] * other.rotation_scale[1][1],
2781                ],
2782                [
2783                    self.rotation_scale[1][0] * other.rotation_scale[0][0]
2784                        + self.rotation_scale[1][1] * other.rotation_scale[1][0],
2785                    self.rotation_scale[1][0] * other.rotation_scale[0][1]
2786                        + self.rotation_scale[1][1] * other.rotation_scale[1][1],
2787                ],
2788            ],
2789            translation: [
2790                self.translation[0]
2791                    + self.rotation_scale[0][0] * other.translation[0]
2792                    + self.rotation_scale[0][1] * other.translation[1],
2793                self.translation[1]
2794                    + self.rotation_scale[1][0] * other.translation[0]
2795                    + self.rotation_scale[1][1] * other.translation[1],
2796            ],
2797        }
2798    }
2799
2800    /// The smallest bounds that contain `bounds` once it is transformed.
2801    pub(crate) fn transform_bounds(&self, bounds: Bounds<ScaledPixels>) -> Bounds<ScaledPixels> {
2802        if *self == Self::unit() {
2803            return bounds;
2804        }
2805        let [[xx, xy], [yx, yy]] = self.rotation_scale;
2806        let [translate_x, translate_y] = self.translation;
2807        let corners = [
2808            bounds.origin,
2809            bounds.top_right(),
2810            bounds.bottom_left(),
2811            bounds.bottom_right(),
2812        ]
2813        .map(|corner| {
2814            Point::new(
2815                ScaledPixels(xx * corner.x.0 + xy * corner.y.0 + translate_x),
2816                ScaledPixels(yx * corner.x.0 + yy * corner.y.0 + translate_y),
2817            )
2818        });
2819        let [first, rest @ ..] = corners;
2820        let top_left = rest.iter().fold(first, |min, corner| min.min(corner));
2821        let bottom_right = rest.iter().fold(first, |max, corner| max.max(corner));
2822        Bounds::from_corners(top_left, bottom_right)
2823    }
2824
2825    /// Apply transformation to a point, mainly useful for debugging
2826    pub fn apply(&self, point: Point<Pixels>) -> Point<Pixels> {
2827        let input = [point.x.0, point.y.0];
2828        let mut output = self.translation;
2829        for (i, output_cell) in output.iter_mut().enumerate() {
2830            for (k, input_cell) in input.iter().enumerate() {
2831                *output_cell += self.rotation_scale[i][k] * *input_cell;
2832            }
2833        }
2834        Point::new(output[0].into(), output[1].into())
2835    }
2836
2837    /// The inverse transformation, or `None` when the matrix is singular
2838    /// (`scale(0)` collapses the element to nothing, and nothing has no
2839    /// interior to map a point back into).
2840    ///
2841    /// This is what hit-testing needs: a hitbox stores its untransformed
2842    /// `bounds`, so testing a pointer against a *transformed* element means
2843    /// mapping the pointer back into the element's own frame rather than
2844    /// mapping four corners forward and testing a polygon.
2845    pub fn inverse(&self) -> Option<TransformationMatrix> {
2846        let [[a, b], [c, d]] = self.rotation_scale;
2847        let det = a * d - b * c;
2848        // Zero, not "small": `scale(0.0003)` has a determinant under
2849        // `f32::EPSILON` and an inverse all the same, and an element part way
2850        // into a scale-in could not be hit.
2851        if det == 0.0 || !det.is_finite() || !(1.0 / det).is_finite() {
2852            return None;
2853        }
2854        let inv = [[d / det, -b / det], [-c / det, a / det]];
2855        let [tx, ty] = self.translation;
2856        Some(TransformationMatrix {
2857            rotation_scale: inv,
2858            translation: [
2859                -(inv[0][0] * tx + inv[0][1] * ty),
2860                -(inv[1][0] * tx + inv[1][1] * ty),
2861            ],
2862        })
2863    }
2864
2865    /// Is this the identity — i.e. is there nothing to apply?
2866    ///
2867    /// Worth asking before every push, because the whole point of the paint
2868    /// path is that an untransformed element costs exactly what it did before
2869    /// transforms existed.
2870    #[inline]
2871    pub fn is_unit(&self) -> bool {
2872        *self == Self::unit()
2873    }
2874}
2875
2876/// The axis-aligned bounding box of `bounds` after `matrix`, in the same
2877/// (device) space both are already expressed in.
2878///
2879/// Exact for a translation; a superset for a rotation or a scale, which is the
2880/// safe direction for a culling test.
2881pub(crate) fn transformed_bounds(
2882    bounds: Bounds<ScaledPixels>,
2883    matrix: TransformationMatrix,
2884) -> Bounds<ScaledPixels> {
2885    matrix.transform_bounds(bounds)
2886}
2887
2888/// vue-native fork: `bounds` carried through `matrix` EXACTLY, for the
2889/// primitives that have no `transformation` of their own and are drawn as an
2890/// axis-aligned rect — the backdrop blur and the `--shading` effect quad, which
2891/// sample the render target under that rect. A translation and an axis-aligned
2892/// scale (how every popper is positioned) fold into the rect itself; the `f32`
2893/// is the factor the corner radii scale by. `None` under a rotation or a skew,
2894/// which no axis-aligned rect can express.
2895pub(crate) fn axis_aligned_through(
2896    bounds: Bounds<ScaledPixels>,
2897    matrix: TransformationMatrix,
2898) -> Option<(Bounds<ScaledPixels>, f32)> {
2899    if matrix.is_unit() {
2900        return Some((bounds, 1.0));
2901    }
2902    let [[a, b], [c, d]] = matrix.rotation_scale;
2903    const EPS: f32 = 1e-6;
2904    if b.abs() > EPS || c.abs() > EPS || a.abs() <= EPS || d.abs() <= EPS {
2905        return None;
2906    }
2907    Some((transformed_bounds(bounds, matrix), a.abs().min(d.abs())))
2908}
2909
2910impl Default for TransformationMatrix {
2911    fn default() -> Self {
2912        Self::unit()
2913    }
2914}
2915
2916#[cfg(test)]
2917mod vn_axis_aligned_tests {
2918    use super::*;
2919    use crate::{Radians, point, size};
2920
2921    fn rect(x: f32, y: f32, w: f32, h: f32) -> Bounds<ScaledPixels> {
2922        Bounds {
2923            origin: point(ScaledPixels(x), ScaledPixels(y)),
2924            size: size(ScaledPixels(w), ScaledPixels(h)),
2925        }
2926    }
2927
2928    #[test]
2929    fn a_translate_moves_the_rect_and_a_rotation_has_no_rect() {
2930        let moved =
2931            TransformationMatrix::unit().translate(point(ScaledPixels(300.), ScaledPixels(120.)));
2932        assert_eq!(
2933            axis_aligned_through(rect(0., 0., 100., 50.), moved),
2934            Some((rect(300., 120., 100., 50.), 1.0))
2935        );
2936        // A popper's open animation: scale 0.95 about the centre.
2937        let zoomed = TransformationMatrix::unit()
2938            .translate(point(ScaledPixels(50.), ScaledPixels(25.)))
2939            .scale(size(0.5, 0.5))
2940            .translate(point(ScaledPixels(-50.), ScaledPixels(-25.)));
2941        assert_eq!(
2942            axis_aligned_through(rect(0., 0., 100., 50.), zoomed),
2943            Some((rect(25., 12.5, 50., 25.), 0.5))
2944        );
2945        let turned = TransformationMatrix::unit().rotate(Radians(0.3));
2946        assert_eq!(axis_aligned_through(rect(0., 0., 100., 50.), turned), None);
2947        assert_eq!(
2948            axis_aligned_through(rect(1., 2., 3., 4.), TransformationMatrix::unit()),
2949            Some((rect(1., 2., 3., 4.), 1.0))
2950        );
2951    }
2952
2953    /// A very small scale still has an inverse; only a flat one has none.
2954    #[test]
2955    fn a_tiny_scale_is_still_invertible() {
2956        let tiny = TransformationMatrix { rotation_scale: [[0.0003, 0.0], [0.0, 0.0003]], translation: [5.0, 7.0] };
2957        let back = tiny.inverse().expect("an inverse");
2958        assert!((back.rotation_scale[0][0] - 1.0 / 0.0003).abs() < 1.0);
2959        let flat = TransformationMatrix { rotation_scale: [[1.0, 0.0], [0.0, 0.0]], translation: [0.0, 0.0] };
2960        assert!(flat.inverse().is_none());
2961    }
2962
2963    /// A path has no transformation field, so its curves move: a chevron in a
2964    /// translated dialog is drawn where the dialog is.
2965    #[test]
2966    fn a_transform_moves_a_paths_curves() {
2967        let mut builder = crate::PathBuilder::fill();
2968        builder.move_to(point(Pixels(0.), Pixels(0.)));
2969        builder.line_to(point(Pixels(10.), Pixels(0.)));
2970        builder.curve_to(point(Pixels(10.), Pixels(20.)), point(Pixels(20.), Pixels(10.)));
2971        builder.close();
2972        let path = builder.build().unwrap();
2973        let moved =
2974            TransformationMatrix::unit().translate(point(ScaledPixels(300.), ScaledPixels(-120.)));
2975        let still = path.bin(2.0).bounds();
2976        assert_eq!(
2977            path.transformed(moved, 2.0).bin(2.0).bounds(),
2978            Bounds::new(still.origin + point(ScaledPixels(300.), ScaledPixels(-120.)), still.size)
2979        );
2980        // A quarter turn swaps the box's sides, with the curve split where it
2981        // turns back on the new axes.
2982        let turned = TransformationMatrix::unit().rotate(Radians(std::f32::consts::FRAC_PI_2));
2983        let turned = path.transformed(turned, 2.0).bin(2.0).bounds();
2984        assert!((turned.size.width.0 - still.size.height.0).abs() < 1e-3);
2985        assert!((turned.size.height.0 - still.size.width.0).abs() < 1e-3);
2986    }
2987}
2988
2989#[derive(Copy, Clone, Debug)]
2990#[repr(C)]
2991#[expect(missing_docs)]
2992pub struct MonochromeSprite {
2993    pub order: DrawOrder,
2994    /// Skips the glyph contrast and gamma correction: the tile is linear coverage (a blurred shadow).
2995    pub raw_coverage: PaddedBool32,
2996    pub tile: AtlasTile,
2997    pub bounds: Bounds<ScaledPixels>,
2998    pub content_mask: ContentMask<ScaledPixels>,
2999    pub color: Hsla,
3000    pub transformation: TransformationMatrix,
3001    /// vue-native fork: upstream keeps this in the padding word that
3002    /// `raw_coverage` holds here. Renderers ignore it.
3003    pub animation: SpriteAnimationId,
3004    pub pad: u32,
3005}
3006
3007/// Refers to an animation of the scene a sprite is inserted into.
3008///
3009/// A single `u32` so it fits the sprite's existing padding and leaves the
3010/// instance layout unchanged on every backend; renderers ignore it.
3011#[derive(Copy, Clone, Debug, PartialEq, Eq)]
3012#[repr(transparent)]
3013pub struct SpriteAnimationId(u32);
3014
3015impl SpriteAnimationId {
3016    /// No animation.
3017    pub const NONE: Self = Self(u32::MAX);
3018}
3019
3020impl Default for SpriteAnimationId {
3021    fn default() -> Self {
3022        Self::NONE
3023    }
3024}
3025
3026/// A [`TimedTransformation`] the window applies to a sprite right before
3027/// every present, so the scene can be presented again without being redrawn.
3028#[derive(Copy, Clone, Debug)]
3029pub(crate) struct SpriteAnimation {
3030    transformation: TimedTransformation,
3031    center: Point<Pixels>,
3032    scale_factor: f32,
3033    base_color: Hsla,
3034    sprite_index: usize,
3035    /// vue-native fork: the CSS `transform` the pose composes under.
3036    outer: TransformationMatrix,
3037}
3038
3039impl SpriteAnimation {
3040    pub(crate) fn new(
3041        transformation: TimedTransformation,
3042        center: Point<Pixels>,
3043        scale_factor: f32,
3044    ) -> Self {
3045        Self {
3046            transformation,
3047            center,
3048            scale_factor,
3049            base_color: Hsla::default(),
3050            sprite_index: usize::MAX,
3051            outer: TransformationMatrix::unit(),
3052        }
3053    }
3054
3055    /// vue-native fork: this animation, posed under the CSS `transform` `outer`.
3056    pub(crate) fn under(self, outer: TransformationMatrix) -> Self {
3057        Self { outer, ..self }
3058    }
3059}
3060
3061impl From<MonochromeSprite> for Primitive {
3062    fn from(sprite: MonochromeSprite) -> Self {
3063        Primitive::MonochromeSprite(sprite)
3064    }
3065}
3066
3067#[derive(Copy, Clone, Debug)]
3068#[repr(C)]
3069#[expect(missing_docs)]
3070pub struct SubpixelSprite {
3071    pub order: DrawOrder,
3072    pub pad: u32, // align to 8 bytes
3073    pub tile: AtlasTile,
3074    pub bounds: Bounds<ScaledPixels>,
3075    pub content_mask: ContentMask<ScaledPixels>,
3076    pub color: Hsla,
3077    pub transformation: TransformationMatrix,
3078}
3079
3080impl From<SubpixelSprite> for Primitive {
3081    fn from(sprite: SubpixelSprite) -> Self {
3082        Primitive::SubpixelSprite(sprite)
3083    }
3084}
3085
3086#[derive(Copy, Clone, Debug)]
3087#[repr(C)]
3088#[expect(missing_docs)]
3089pub struct PolychromeSprite {
3090    pub order: DrawOrder,
3091    pub pad: u32,
3092    pub tile: AtlasTile,
3093    pub grayscale: PaddedBool32,
3094    pub opacity: f32,
3095    pub bounds: Bounds<ScaledPixels>,
3096    pub content_mask: ContentMask<ScaledPixels>,
3097    pub corner_radii: Corners<ScaledPixels>,
3098    /// See [`Quad::transformation`]. The monochrome and subpixel sprites have
3099    /// carried one since gpui's SVG element; this is the one that was missing,
3100    /// and it is what makes an `<img>` (or a colour emoji) inside a rotated box
3101    /// rotate with it.
3102    ///
3103    /// vue-native fork: kept LAST. Upstream (zed#65814) moved `tile` up to
3104    /// offset 8 so the texture sort key sits beside `order`; every shader's
3105    /// `PolychromeSprite` mirrors this order — tile, grayscale, opacity,
3106    /// bounds, content_mask, corner_radii, transformation, tint.
3107    pub transformation: TransformationMatrix,
3108    /// vue-native fork: the colour the sprite's pixels take by its alpha,
3109    /// keeping their own alpha (`Window::with_image_tint`); transparent for
3110    /// none. After `transformation`, so every shader mirrors it last.
3111    pub tint: Hsla,
3112}
3113
3114impl From<PolychromeSprite> for Primitive {
3115    fn from(sprite: PolychromeSprite) -> Self {
3116        Primitive::PolychromeSprite(sprite)
3117    }
3118}
3119
3120#[derive(Clone, Debug)]
3121#[allow(missing_docs)]
3122pub struct PaintSurface {
3123    pub order: DrawOrder,
3124    pub bounds: Bounds<ScaledPixels>,
3125    pub content_mask: ContentMask<ScaledPixels>,
3126    #[cfg(any(target_os = "macos", target_os = "ios"))]
3127    pub image_buffer: objc2_core_foundation::CFRetained<objc2_core_video::CVPixelBuffer>,
3128}
3129
3130impl From<PaintSurface> for Primitive {
3131    fn from(surface: PaintSurface) -> Self {
3132        Primitive::Surface(surface)
3133    }
3134}
3135
3136#[derive(Clone, Copy, Debug, PartialEq)]
3137#[repr(C)]
3138#[expect(missing_docs)]
3139pub struct PathCurve {
3140    pub p0: Point<f32>,
3141    pub p1: Point<f32>,
3142    pub a: Point<f32>,
3143    pub b: Point<f32>,
3144    pub sign: f32,
3145    pub pad: u32, // align to 8 bytes
3146}
3147
3148#[derive(Clone, Copy, Debug)]
3149#[repr(C)]
3150#[expect(missing_docs)]
3151pub struct PathPaint {
3152    /// The path's bounds, in device pixels.
3153    pub bounds: Bounds<ScaledPixels>,
3154    pub content_mask: ContentMask<ScaledPixels>,
3155    pub color: Background,
3156    pub even_odd: PaddedBool32,
3157    pub pad: u32, // align to 8 bytes
3158}
3159
3160#[derive(Clone, Copy, Debug, PartialEq)]
3161#[repr(C)]
3162#[expect(missing_docs)]
3163pub struct PathTile {
3164    pub paint: u32,
3165    pub curve_start: u32,
3166    pub curve_count: u32,
3167    pub backdrop: i32,
3168    pub top_left: Point<f32>,
3169    pub bottom_right: Point<f32>,
3170    pub reference: Point<f32>,
3171    pub curves_top_left: Point<f32>,
3172    pub curves_bottom_right: Point<f32>,
3173}
3174
3175#[derive(Clone, Debug)]
3176#[expect(missing_docs)]
3177pub struct PaintedPath {
3178    order: DrawOrder,
3179    bounds: Bounds<ScaledPixels>,
3180    tiles: Rc<PathTiles>,
3181    paint: PathPaint,
3182}
3183
3184#[expect(missing_docs)]
3185impl PaintedPath {
3186    /// Bins `path` into tiles, to be filled with `color` within `content_mask`.
3187    pub fn new(
3188        path: Path,
3189        scale_factor: f32,
3190        content_mask: ContentMask<Pixels>,
3191        color: Background,
3192    ) -> Self {
3193        let content_mask = content_mask.scale(scale_factor);
3194        let mut tiles = path.bin(scale_factor);
3195        tiles.retain_visible(content_mask.bounds);
3196        let paint = PathPaint {
3197            bounds: tiles.bounds(),
3198            content_mask,
3199            color,
3200            even_odd: path.even_odd().into(),
3201            pad: 0,
3202        };
3203        Self {
3204            order: 0,
3205            bounds: tiles.painted_bounds(),
3206            tiles: Rc::new(tiles),
3207            paint,
3208        }
3209    }
3210
3211    pub fn tile_count(&self) -> usize {
3212        self.tiles.tiles().len()
3213    }
3214
3215    pub fn append_to(
3216        &self,
3217        paints: &mut Vec<PathPaint>,
3218        curves: &mut Vec<PathCurve>,
3219        tiles: &mut Vec<PathTile>,
3220    ) {
3221        let paint_index = paints.len() as u32;
3222        let curve_start = curves.len() as u32;
3223        paints.push(self.paint);
3224        curves.extend_from_slice(self.tiles.curves());
3225        tiles.extend(self.tiles.tiles().iter().map(|tile| PathTile {
3226            paint: paint_index,
3227            curve_start: curve_start + tile.curve_start,
3228            ..*tile
3229        }));
3230    }
3231}
3232
3233impl From<PaintedPath> for Primitive {
3234    fn from(path: PaintedPath) -> Self {
3235        Primitive::Path(path)
3236    }
3237}
3238
3239#[cfg(test)]
3240mod tests {
3241    use super::*;
3242    use crate::{point, size};
3243
3244    fn square(x: f32) -> Bounds<ScaledPixels> {
3245        Bounds {
3246            origin: point(ScaledPixels(x), ScaledPixels(0.)),
3247            size: size(ScaledPixels(10.), ScaledPixels(10.)),
3248        }
3249    }
3250
3251    fn quad(x: f32) -> Quad {
3252        Quad {
3253            bounds: square(x),
3254            content_mask: ContentMask::rect(square(x)),
3255            ..Default::default()
3256        }
3257    }
3258
3259    fn underline(x: f32) -> Underline {
3260        Underline {
3261            order: 0,
3262            pad: 0,
3263            bounds: square(x),
3264            content_mask: ContentMask::rect(square(x)),
3265            color: Hsla::default(),
3266            thickness: ScaledPixels(1.),
3267            wavy: false.into(),
3268            transformation: TransformationMatrix::unit(),
3269        }
3270    }
3271
3272    fn batch_labels(scene: &mut Scene) -> Vec<String> {
3273        scene.finish();
3274        scene.batches().map(|batch| batch.label()).collect()
3275    }
3276
3277    #[test]
3278    fn layers_are_drawn_in_paint_order() {
3279        // A quad painted after a layer goes above it.
3280        let mut scene = Scene::default();
3281        scene.insert_primitive(quad(0.));
3282        scene.push_layer();
3283        scene.insert_primitive(underline(0.));
3284        scene.insert_primitive(underline(5.));
3285        scene.pop_layer();
3286        scene.insert_primitive(quad(5.));
3287        assert_eq!(
3288            batch_labels(&mut scene),
3289            ["quads (1)", "underlines (2)", "quads (1)"]
3290        );
3291
3292        // A layer goes above the layer painted before it.
3293        let mut scene = Scene::default();
3294        scene.push_layer();
3295        scene.insert_primitive(underline(0.));
3296        scene.pop_layer();
3297        scene.push_layer();
3298        scene.insert_primitive(quad(5.));
3299        scene.pop_layer();
3300        assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]);
3301    }
3302
3303    #[test]
3304    fn nested_layers_are_drawn_above_their_parents() {
3305        // A layer has one draw order, so what it paints after a nested layer
3306        // still goes below that layer.
3307        let mut scene = Scene::default();
3308        scene.push_layer();
3309        scene.insert_primitive(underline(0.));
3310        scene.push_layer();
3311        scene.insert_primitive(quad(5.));
3312        scene.pop_layer();
3313        scene.insert_primitive(underline(5.));
3314        scene.pop_layer();
3315        assert_eq!(batch_labels(&mut scene), ["underlines (2)", "quads (1)"]);
3316
3317        // The same holds when the nested layer shares its parent's order.
3318        let mut scene = Scene::default();
3319        scene.push_layer();
3320        scene.insert_primitive(quad(0.));
3321        scene.push_layer();
3322        scene.insert_primitive(quad(5.));
3323        scene.pop_layer();
3324        scene.insert_primitive(quad(8.));
3325        scene.pop_layer();
3326        assert_eq!(batch_labels(&mut scene), ["quads (3)"]);
3327        assert_eq!(
3328            scene
3329                .quads
3330                .iter()
3331                .map(|quad| quad.bounds)
3332                .collect::<Vec<_>>(),
3333            [square(0.), square(8.), square(5.)]
3334        );
3335
3336        // A layer goes above the layers nested in the layer before it.
3337        let mut scene = Scene::default();
3338        scene.push_layer();
3339        scene.push_layer();
3340        scene.insert_primitive(underline(0.));
3341        scene.pop_layer();
3342        scene.pop_layer();
3343        scene.push_layer();
3344        scene.insert_primitive(quad(5.));
3345        scene.pop_layer();
3346        assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]);
3347    }
3348}
3349
3350
3351#[cfg(test)]
3352mod vn_color_group_tests {
3353    use super::*;
3354    use crate::{VnColorMatrix, VnClipGeometry, VnFillRule, size};
3355    use std::sync::Arc;
3356
3357    fn rectangle() -> Bounds<ScaledPixels> {
3358        Bounds { origin: point(ScaledPixels(0.), ScaledPixels(0.)), size: size(ScaledPixels(100.), ScaledPixels(100.)) }
3359    }
3360
3361    fn filter(id: u64) -> VnIsolation {
3362        VnIsolation {
3363            text_paint: None,
3364            geometry: Arc::new(VnClipGeometry {
3365                fill_rule: VnFillRule::NonZero,
3366                segments: vec![[0., 0., 100., 0.], [100., 0., 100., 100.], [100., 100., 0., 100.], [0., 100., 0., 0.]],
3367                bounds: rectangle(),
3368            }),
3369            color_matrix: Some(VnColorMatrix { group_id: id, values: VnColorMatrix::IDENTITY, linear_rgb: true }),
3370            content_mask: ContentMask { bounds: rectangle(), ..Default::default() },
3371            capture: None,
3372        }
3373    }
3374
3375    fn paint(scene: &mut Scene) {
3376        scene.insert_primitive(Quad { bounds: rectangle(), content_mask: ContentMask { bounds: rectangle(), ..Default::default() }, ..Default::default() });
3377    }
3378
3379    fn text_mask(id: u64) -> VnIsolation {
3380        let mut isolation = filter(id);
3381        isolation.color_matrix = None;
3382        isolation.text_paint = Some(Arc::new(crate::VnTextPaint {
3383            fill: crate::VnTextFill { group_id: id, backgrounds: vec![crate::red().into(), crate::blue().into()] },
3384            bounds: [10., 20., 40., 30.],
3385            inverse: [0., 1., -1., 0., 50., 60.], scale_factor: 1.5,
3386            geometry: isolation.geometry.clone(), content_mask: isolation.content_mask,
3387        }));
3388        isolation
3389    }
3390
3391    #[test]
3392    fn text_glyphs_and_deferred_replay_share_one_gradient_stack_and_source() {
3393        let mut scene = Scene::default();
3394        for _ in 0..3 {
3395            scene.vn_push_isolation(text_mask(7));
3396            paint(&mut scene);
3397            scene.vn_pop_isolation();
3398        }
3399        assert_eq!(scene.vn_layers.len(), 1, "a text scope composites once, not per glyph");
3400        assert_eq!(scene.vn_groups[0].quads.len(), 3);
3401        assert_eq!(scene.vn_text_backgrounds.len(), 2, "metadata belongs to a text scope, not each glyph");
3402        assert_eq!(scene.vn_layers[0].pad, [0, 0, 2]);
3403        let brush = scene.vn_text_backgrounds[0];
3404        assert_eq!(brush.bounds.origin.x.0, 10.);
3405        assert_eq!(brush.inverse.apply(point(px(2.), px(3.))), point(px(53.), px(58.)));
3406        assert_eq!(brush.scale_factor, 1.5);
3407        let operations = 0..scene.len();
3408        scene.finish();
3409        let mut replay = Scene::default();
3410        replay.replay(operations, &scene);
3411        assert_eq!(replay.vn_layers.len(), 1);
3412        assert_eq!(replay.vn_text_backgrounds.len(), 2, "cached operations rebuild valid metadata indices");
3413        assert_eq!(replay.vn_groups[0].quads.len(), 3);
3414        replay.clear();
3415        assert!(replay.vn_text_backgrounds.is_empty());
3416        replay.vn_push_isolation(text_mask(7));
3417        paint(&mut replay);
3418        replay.vn_pop_isolation();
3419        assert_eq!(replay.vn_text_backgrounds.len(), 2);
3420        assert_eq!(replay.vn_groups[0].quads.len(), 1, "new frames cannot retain old mask coverage");
3421    }
3422
3423    #[test]
3424    fn text_and_color_filter_group_identities_do_not_alias() {
3425        let mut scene = Scene::default();
3426        scene.vn_push_isolation(filter(7));
3427        scene.vn_push_isolation(text_mask(7));
3428        paint(&mut scene);
3429        scene.vn_pop_isolation();
3430        scene.vn_pop_isolation();
3431        assert_eq!(scene.vn_groups.len(), 2);
3432        assert_eq!(scene.vn_groups[1].vn_layers.len(), 1);
3433        assert_eq!(scene.vn_layers[0].pad[0], 1);
3434        assert_eq!(scene.vn_groups[1].vn_layers[0].pad[2], 2);
3435        assert_eq!(std::mem::size_of::<VnLayer>(), 224, "keep the HLSL layer ABI");
3436        assert_eq!(std::mem::size_of::<VnTextBackground>(), 276, "match the HLSL structured buffer stride");
3437        assert_eq!(std::mem::offset_of!(VnTextBackground, bounds), 228);
3438        assert_eq!(std::mem::offset_of!(VnTextBackground, inverse), 244);
3439        assert_eq!(std::mem::offset_of!(VnTextBackground, scale_factor), 268);
3440    }
3441
3442    #[test]
3443    fn text_sources_partition_child_clip_and_filter_contexts_and_rejoin_deferred_siblings() {
3444        for matrix in [false, true] {
3445            let mut first = filter(11);
3446            let mut second = filter(12);
3447            if !matrix { first.color_matrix = None; second.color_matrix = None; }
3448            let mut scene = Scene::default();
3449            for parent in [first.clone(), second, first] {
3450                scene.vn_push_isolation(parent);
3451                scene.vn_push_isolation(text_mask(7));
3452                paint(&mut scene);
3453                scene.vn_pop_isolation();
3454                scene.vn_pop_isolation();
3455            }
3456            // Clip-path groups themselves may close separately; their text
3457            // sources must still partition by stable parent geometry identity.
3458            let masks: Vec<_> = scene.vn_groups.iter().filter(|group| !group.quads.is_empty()).collect();
3459            assert_eq!(masks.len(), 2, "text cannot be captured by the first child's clip or filter");
3460            assert_eq!(masks[0].quads.len(), 2, "deferred text in the same parent reuses its source");
3461            assert_eq!(masks[1].quads.len(), 1);
3462            assert_eq!(scene.vn_text_backgrounds.len(), 4, "two brushes per distinct isolation context");
3463            let operations = 0..scene.len();
3464            scene.finish();
3465            let mut replay = Scene::default();
3466            replay.replay(operations, &scene);
3467            assert_eq!(replay.vn_text_backgrounds.len(), 4, "paint-cache replay interns equivalent parent contexts");
3468            let masks: Vec<_> = replay.vn_groups.iter().filter(|group| !group.quads.is_empty()).collect();
3469            assert_eq!(masks.len(), 2);
3470            assert_eq!(masks[0].quads.len(), 2);
3471        }
3472    }
3473
3474    #[test]
3475    fn deferred_source_is_composited_with_its_background_before_one_color_matrix() {
3476        let mut scene = Scene::default();
3477        scene.vn_push_isolation(filter(1));
3478        paint(&mut scene);
3479        scene.vn_pop_isolation();
3480        scene.vn_push_isolation(filter(1));
3481        paint(&mut scene);
3482        scene.vn_pop_isolation();
3483        assert_eq!(scene.vn_layers.len(), 1, "one composite, not separately filtered translucent pieces");
3484        assert_eq!(scene.vn_groups.len(), 1);
3485        assert_eq!(scene.vn_groups[0].quads.len(), 2);
3486        assert!(scene.vn_groups[0].quads[1].order > scene.vn_groups[0].quads[0].order, "deferred source blends over its earlier background");
3487        let operations = 0..scene.len();
3488        scene.finish();
3489        assert_eq!(scene.vn_group_count(), 2);
3490        let mut replay = Scene::default();
3491        replay.replay(operations, &scene);
3492        assert_eq!(replay.vn_layers.len(), 1, "cached operations rebuild the same keyed source");
3493        assert_eq!(replay.vn_groups[0].quads.len(), 2);
3494        replay.clear();
3495        replay.vn_push_isolation(filter(1));
3496        paint(&mut replay);
3497        replay.vn_pop_isolation();
3498        assert_eq!(replay.vn_groups[0].quads.len(), 1, "a new frame has no old source pixels");
3499    }
3500
3501    #[test]
3502    fn an_initially_empty_filter_keeps_its_composite_for_deferred_descendants() {
3503        let mut scene = Scene::default();
3504        scene.vn_push_isolation(filter(1));
3505        scene.vn_pop_isolation();
3506        scene.vn_push_isolation(filter(1));
3507        paint(&mut scene);
3508        scene.vn_pop_isolation();
3509        assert_eq!(scene.vn_layers.len(), 1);
3510        assert_eq!(scene.vn_groups.len(), 1);
3511        assert_eq!(scene.vn_groups[0].quads.len(), 1);
3512    }
3513
3514    #[test]
3515    fn nested_filtered_sources_reopen_without_duplicate_inner_composites() {
3516        let mut scene = Scene::default();
3517        scene.vn_push_isolation(filter(1));
3518        paint(&mut scene);
3519        scene.vn_push_isolation(filter(2));
3520        paint(&mut scene);
3521        scene.vn_pop_isolation();
3522        scene.vn_pop_isolation();
3523        scene.vn_push_isolation(filter(1));
3524        scene.vn_push_isolation(filter(2));
3525        paint(&mut scene);
3526        scene.vn_pop_isolation();
3527        scene.vn_pop_isolation();
3528        assert_eq!(scene.vn_layers.len(), 1, "only the outer composite belongs to the page");
3529        assert_eq!(scene.vn_groups.len(), 2);
3530        assert_eq!(scene.vn_groups[0].quads.len(), 2, "both inner source pieces share one filter");
3531        assert_eq!(scene.vn_groups[1].vn_layers.len(), 1, "the inner filter composites once into the outer source");
3532        scene.finish();
3533        assert_eq!(scene.vn_group_count(), 3);
3534        assert_eq!(scene.vn_layers.len(), 2);
3535    }
3536
3537    #[test]
3538    fn an_in_place_snapshot_samples_through_the_captured_transform() {
3539        let mut capture = filter(0);
3540        capture.color_matrix = None;
3541        capture.capture = Some(VnCaptureInfo {
3542            id: 3,
3543            border_box: rectangle(),
3544            transform: crate::TransformationMatrix { rotation_scale: [[2., 0.], [0., 2.]], translation: [100., 5.] },
3545        });
3546        let mut scene = Scene::default();
3547        scene.vn_push_isolation(capture);
3548        paint(&mut scene);
3549        scene.vn_pop_isolation();
3550        let viewport = Bounds { origin: point(ScaledPixels(0.), ScaledPixels(0.)), size: size(ScaledPixels(400.), ScaledPixels(400.)) };
3551        scene.vn_insert_snapshot(VnSnapshotPaint {
3552            id: 3,
3553            to_unit: [0.; 6],
3554            bounds: viewport,
3555            content_mask: ContentMask { bounds: viewport, ..Default::default() },
3556            opacity: 1.,
3557            plus_lighter: false,
3558            in_place: true,
3559        });
3560        scene.finish();
3561        scene.vn_resolve_snapshots(|_| None);
3562        let layer = scene.vn_layers.iter().find(|l| l.snapshot_id() == Some(3)).copied().unwrap();
3563        assert_eq!(layer.flags, vn_layer_flags::SNAPSHOT);
3564        assert_eq!(layer.source_transform, [0.5, 0., -50., 0., 0., 0.5, -2.5, 0.]);
3565        assert_eq!(layer.bounds.origin, point(ScaledPixels(100.), ScaledPixels(5.)));
3566        assert_eq!(layer.bounds.size, size(ScaledPixels(200.), ScaledPixels(200.)));
3567    }
3568}