1#![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, CornerShapes, 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#[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 pub fn as_bool(self) -> bool {
45 self.0 != 0
46 }
47}
48
49struct Layer {
50 primitives: SmallVec<[Range<usize>; 1]>,
51 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 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 pub vn_layers: Vec<VnLayer>,
97 pub vn_layer_effects: Vec<Option<VnEffectLayer>>,
100 pub vn_effect_draws: Vec<VnEffectDraw>,
103 pub vn_clip_segments: Vec<[f32; 4]>,
106 pub vn_text_backgrounds: Vec<VnTextBackground>,
108 vn_open: Vec<VnOpenGroup>,
111 vn_groups: Vec<VnGroupLists>,
113 vn_color_groups: HashMap<(u8, u64, usize), usize>,
116 vn_contexts: HashMap<(usize, VnIsolationIdentity), usize>,
117 vn_group_ranges: Vec<VnGroupRanges>,
120 pub vn_captures: Vec<VnCapture>,
123 animations: Vec<SpriteAnimation>,
124}
125
126#[derive(Clone, Copy, Debug, PartialEq)]
128pub struct VnCaptureInfo {
129 pub id: u64,
131 pub border_box: Bounds<ScaledPixels>,
134 pub transform: TransformationMatrix,
137}
138
139#[derive(Clone, Copy, Debug)]
143#[allow(missing_docs)]
144pub struct VnCapture {
145 pub info: VnCaptureInfo,
146 pub group: u32,
147 pub ink: Bounds<ScaledPixels>,
149}
150
151pub mod vn_layer_flags {
153 pub const SNAPSHOT: u32 = 1;
155 pub const PLUS_LIGHTER: u32 = 2;
158 pub const IN_PLACE: u32 = 4;
161}
162
163#[derive(Clone, Debug)]
166pub struct VnIsolation {
167 pub geometry: std::sync::Arc<crate::VnClipGeometry>,
169 pub color_matrix: Option<crate::VnColorMatrix>,
171 pub text_paint: Option<std::sync::Arc<crate::VnTextPaint>>,
173 pub content_mask: ContentMask<ScaledPixels>,
176 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#[derive(Clone, Copy, Debug)]
204#[repr(C)]
205pub struct VnTextBackground {
206 pub background: Background,
208 pub bounds: Bounds<ScaledPixels>,
210 pub inverse: TransformationMatrix,
212 pub scale_factor: f32,
214 pub pad: f32,
216}
217
218#[derive(Default, Debug, Copy, Clone)]
234#[repr(C)]
235#[allow(missing_docs)]
236pub struct VnLayer {
237 pub order: DrawOrder,
238 pub group: u32,
240 pub segment_start: u32,
241 pub segment_count: u32,
242 pub fill_rule: u32,
243 pub pad: [u32; 3],
244 pub color_matrix: [f32; 20],
246 pub bounds: Bounds<ScaledPixels>,
249 pub content_mask: ContentMask<ScaledPixels>,
250 pub snapshot: [u32; 2],
252 pub flags: u32,
254 pub opacity: f32,
255 pub source_rect: [f32; 4],
257 pub source_transform: [f32; 8],
260}
261
262impl VnLayer {
263 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#[derive(Clone, Copy, Debug)]
272#[allow(missing_docs)]
273pub struct VnSnapshotPaint {
274 pub id: u64,
275 pub to_unit: [f32; 6],
279 pub bounds: Bounds<ScaledPixels>,
281 pub content_mask: ContentMask<ScaledPixels>,
282 pub opacity: f32,
283 pub plus_lighter: bool,
284 pub in_place: bool,
286}
287
288#[derive(Clone, Debug)]
291#[allow(missing_docs)]
292pub struct VnEffectDraw {
293 pub quad: EffectQuad,
294 pub history: u64,
295 pub textures: Option<std::sync::Arc<crate::EffectTextureSet>>,
298}
299
300#[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 pub fn draws(&self) -> Range<usize> {
312 self.start as usize..(self.start + self.count) as usize
313 }
314}
315
316#[derive(Clone, Debug)]
319#[allow(missing_docs)]
320pub struct VnEffectPaint {
321 pub draws: Vec<VnEffectDraw>,
322 pub content: bool,
324 pub content_mask: ContentMask<ScaledPixels>,
325}
326
327#[derive(Debug)]
330pub enum VnBatch {
331 Primitives(PrimitiveBatch),
333 Layers(Range<usize>),
335}
336
337#[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#[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 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 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 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 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 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 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 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 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 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 pub fn vn_is_isolating(&self) -> bool {
663 !self.vn_open.is_empty()
664 }
665
666 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 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 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 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 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 pub fn vn_effect_layer(&self, index: usize) -> Option<VnEffectLayer> {
835 self.vn_layer_effects.get(index).copied().flatten()
836 }
837
838 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 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 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 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 pub fn vn_group_count(&self) -> usize {
955 self.vn_group_ranges.len().max(1)
956 }
957
958 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 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 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 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 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 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 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 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 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 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 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 if !self.vn_group_ranges.is_empty() {
1266 return;
1267 }
1268 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 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 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 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
1330fn 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 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
1370pub 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
1376pub 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 VnLayer,
1403}
1404
1405impl PrimitiveKind {
1406 fn max_shared_kind(self) -> Self {
1413 match self {
1414 Self::BackdropBlurRect => Self::Quad,
1417 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 VnStartIsolation(VnIsolation),
1434 VnStartEffect(VnEffectPaint),
1436 VnEndIsolation,
1438 VnSnapshot(VnSnapshotPaint),
1440 VnBeginMask(bool),
1442}
1443
1444#[derive(Clone)]
1445#[expect(missing_docs)]
1446pub enum Primitive {
1447 Shadow(Shadow),
1448 Quad(Quad),
1449 BackdropBlurRect(BackdropBlurRect),
1450 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 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 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 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 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 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 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 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 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#[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 pub transformation: TransformationMatrix,
1999 pub corner_shapes: CornerShapes,
2001}
2002
2003impl From<Quad> for Primitive {
2004 fn from(quad: Quad) -> Self {
2005 Primitive::Quad(quad)
2006 }
2007}
2008
2009pub const MAX_BACKDROP_BLUR_KERNEL_LEVELS: u32 = 5;
2012
2013const BACKDROP_BLUR_RADIUS_PER_KERNEL_LEVEL: f32 = 5.;
2016
2017#[derive(Debug, Copy, Clone)]
2023#[repr(C)]
2024#[expect(missing_docs)]
2025pub struct BackdropBlurRect {
2026 pub order: DrawOrder,
2027 pub pad: u32,
2028 pub bounds: Bounds<ScaledPixels>,
2029 pub content_mask: ContentMask<ScaledPixels>,
2030 pub corner_radii: Corners<ScaledPixels>,
2031 pub blur_radius: ScaledPixels,
2032 pub opacity: f32,
2033 pub tint: Hsla,
2034 pub corner_shapes: CornerShapes,
2035}
2036
2037impl Default for BackdropBlurRect {
2038 fn default() -> Self {
2039 Self {
2040 order: Default::default(),
2041 pad: Default::default(),
2042 bounds: Default::default(),
2043 content_mask: Default::default(),
2044 corner_radii: Default::default(),
2045 blur_radius: Default::default(),
2046 opacity: 1.,
2047 tint: Default::default(),
2048 corner_shapes: Default::default(),
2049 }
2050 }
2051}
2052
2053impl BackdropBlurRect {
2054 pub fn effective_kernel_levels(&self) -> u32 {
2077 if self.blur_radius.0 <= 0. {
2078 0
2079 } else {
2080 let radius_levels = (self.blur_radius.0 / BACKDROP_BLUR_RADIUS_PER_KERNEL_LEVEL)
2081 .ceil()
2082 .max(1.) as u32;
2083 radius_levels.min(MAX_BACKDROP_BLUR_KERNEL_LEVELS)
2084 }
2085 }
2086}
2087
2088impl From<BackdropBlurRect> for Primitive {
2089 fn from(backdrop_blur_rect: BackdropBlurRect) -> Self {
2090 Primitive::BackdropBlurRect(backdrop_blur_rect)
2091 }
2092}
2093
2094pub mod effect_id {
2104 pub const FROST: u32 = 0;
2107 pub const NOISE: u32 = 1;
2109 pub const GLOW: u32 = 2;
2111 pub const COUNT: u32 = 3;
2113 pub const PUNCH: u32 = u32::MAX - 1;
2119 pub const CONTENT: u32 = u32::MAX - 2;
2124 pub const NONE: u32 = u32::MAX;
2128}
2129
2130pub const EFFECT_FLAG_NEEDS_BACKDROP: u32 = 1;
2134
2135pub const EFFECT_FLAG_NEEDS_CONTENT: u32 = 2;
2139
2140pub const EFFECT_FLAG_HISTORY: u32 = 4;
2144
2145pub const EFFECT_FLAG_HISTORY_PASS: u32 = 8;
2148
2149#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
2165#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2166pub struct TransformSpec {
2167 pub translate: (TransformLength, TransformLength),
2171 pub rotate: f32,
2174 pub scale: (f32, f32),
2176 #[serde(default)]
2180 pub shear: f32,
2181 #[serde(default)]
2185 pub translation_basis: Option<[[f32; 3]; 2]>,
2186 pub origin: (TransformLength, TransformLength),
2196}
2197
2198#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
2200#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2201pub enum TransformLength {
2202 Pixels(f32),
2204 Fraction(f32),
2208}
2209
2210impl TransformLength {
2211 pub const ZERO: Self = Self::Pixels(0.0);
2213
2214 pub fn resolve(self, own: f32) -> f32 {
2216 match self {
2217 Self::Pixels(v) => v,
2218 Self::Fraction(f) => f * own,
2219 }
2220 }
2221
2222 pub fn is_zero(self) -> bool {
2224 match self {
2225 Self::Pixels(v) | Self::Fraction(v) => v == 0.0,
2226 }
2227 }
2228
2229 pub fn interpolate(self, other: Self, t: f32) -> Self {
2237 let lerp = |a: f32, b: f32| a + (b - a) * t;
2238 match (self, other) {
2239 (Self::Pixels(a), Self::Pixels(b)) => Self::Pixels(lerp(a, b)),
2240 (Self::Fraction(a), Self::Fraction(b)) => Self::Fraction(lerp(a, b)),
2241 (a, b) if a.is_zero() => match b {
2242 Self::Pixels(v) => Self::Pixels(lerp(0.0, v)),
2243 Self::Fraction(v) => Self::Fraction(lerp(0.0, v)),
2244 },
2245 (a, b) if b.is_zero() => match a {
2246 Self::Pixels(v) => Self::Pixels(lerp(v, 0.0)),
2247 Self::Fraction(v) => Self::Fraction(lerp(v, 0.0)),
2248 },
2249 (a, b) => {
2250 if t < 0.5 {
2251 a
2252 } else {
2253 b
2254 }
2255 }
2256 }
2257 }
2258}
2259
2260impl Default for TransformSpec {
2261 fn default() -> Self {
2262 Self::IDENTITY
2263 }
2264}
2265
2266impl TransformSpec {
2267 pub const IDENTITY: Self = Self {
2269 translate: (TransformLength::ZERO, TransformLength::ZERO),
2270 rotate: 0.0,
2271 scale: (1.0, 1.0),
2272 origin: Self::CENTRE_ORIGIN,
2273 shear: 0.0,
2274 translation_basis: None,
2275 };
2276
2277 pub const CENTRE_ORIGIN: (TransformLength, TransformLength) =
2279 (TransformLength::Fraction(0.5), TransformLength::Fraction(0.5));
2280
2281 pub fn is_identity(&self) -> bool {
2287 self.rotate == 0.0
2288 && self.scale == (1.0, 1.0)
2289 && self.shear == 0.0
2290 && match self.translation_basis {
2291 Some(basis) => basis.iter().flatten().all(|v| *v == 0.0),
2292 None => self.translate.0.is_zero() && self.translate.1.is_zero(),
2293 }
2294 }
2295
2296 fn translation_coefficients(&self) -> [[f32; 3]; 2] {
2297 self.translation_basis.unwrap_or_else(|| {
2298 let x = match self.translate.0 {
2299 TransformLength::Pixels(v) => [v, 0.0, 0.0],
2300 TransformLength::Fraction(v) => [0.0, v, 0.0],
2301 };
2302 let y = match self.translate.1 {
2303 TransformLength::Pixels(v) => [v, 0.0, 0.0],
2304 TransformLength::Fraction(v) => [0.0, 0.0, v],
2305 };
2306 [x, y]
2307 })
2308 }
2309 pub fn interpolate(self, other: Self, t: f32) -> Self {
2313 let lerp = |a: f32, b: f32| a + (b - a) * t;
2314 Self {
2315 translate: (
2316 self.translate.0.interpolate(other.translate.0, t),
2317 self.translate.1.interpolate(other.translate.1, t),
2318 ),
2319 rotate: lerp(self.rotate, other.rotate),
2320 shear: lerp(self.shear, other.shear),
2321 translation_basis: if self.translation_basis.is_some() || other.translation_basis.is_some() {
2322 let a = self.translation_coefficients();
2323 let b = other.translation_coefficients();
2324 Some(std::array::from_fn(|row| std::array::from_fn(|column| lerp(a[row][column], b[row][column]))))
2325 } else { None },
2326 scale: (
2327 lerp(self.scale.0, other.scale.0),
2328 lerp(self.scale.1, other.scale.1),
2329 ),
2330 origin: (
2331 self.origin.0.interpolate(other.origin.0, t),
2332 self.origin.1.interpolate(other.origin.1, t),
2333 ),
2334 }
2335 }
2336
2337 pub fn to_matrix(self, bounds: Bounds<Pixels>, scale_factor: f32) -> TransformationMatrix {
2347 let anchor = bounds.origin
2348 + Point::new(
2349 px(self.origin.0.resolve(bounds.size.width.0)),
2350 px(self.origin.1.resolve(bounds.size.height.0)),
2351 );
2352 let coefficients = self.translation_coefficients();
2353 let resolve = |row: [f32; 3]| px(row[0] + row[1] * bounds.size.width.0 + row[2] * bounds.size.height.0);
2354 let translate = Point::new(resolve(coefficients[0]), resolve(coefficients[1]));
2355 TransformationMatrix::unit()
2356 .translate((anchor + translate).scale(scale_factor))
2357 .rotate(Radians(self.rotate))
2358 .compose(TransformationMatrix {
2359 rotation_scale: [[self.scale.0, self.shear], [0.0, self.scale.1]],
2360 translation: [0.0, 0.0],
2361 })
2362 .translate(anchor.scale(-scale_factor))
2363 }
2364}
2365
2366pub const EFFECT_PARAM_SLOTS: usize = 32;
2369
2370#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
2380#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2381pub struct EffectSpec {
2382 pub id: u32,
2384 pub flags: u32,
2386 pub length_mask: u32,
2389 pub backdrop_radius_param: Option<u8>,
2392 pub bleed_param: Option<u8>,
2395 pub animated: bool,
2398 #[serde(default)]
2401 pub animated_param: Option<u8>,
2402 pub pointer_param: Option<u8>,
2405 pub pointer_times_param: Option<u8>,
2408 pub clock_mask: u32,
2411 pub clock_window: f32,
2413 pub params: [f32; EFFECT_PARAM_SLOTS],
2415 #[serde(default)]
2418 pub textures: [Option<crate::EffectTextureParam>; crate::EFFECT_TEXTURE_SLOTS],
2419}
2420
2421impl EffectSpec {
2422 pub const NONE: EffectSpec = EffectSpec {
2425 id: effect_id::NONE,
2426 flags: 0,
2427 length_mask: 0,
2428 backdrop_radius_param: None,
2429 bleed_param: None,
2430 animated: false,
2431 animated_param: None,
2432 pointer_param: None,
2433 pointer_times_param: None,
2434 clock_mask: 0,
2435 clock_window: 0.,
2436 params: [0.; EFFECT_PARAM_SLOTS],
2437 textures: [None; crate::EFFECT_TEXTURE_SLOTS],
2438 };
2439
2440 pub fn is_some(&self) -> bool {
2442 self.id != effect_id::NONE
2443 }
2444
2445 pub fn interpolates_with(&self, other: &EffectSpec) -> bool {
2449 self.id == other.id && self.textures == other.textures
2450 }
2451
2452 pub fn follows_pointer(&self) -> bool {
2455 self.pointer_param.is_some() || self.pointer_times_param.is_some()
2456 }
2457
2458 pub fn clock_running(&self, now: f32) -> bool {
2461 if self.clock_mask == 0 {
2462 return false;
2463 }
2464 self.params
2465 .iter()
2466 .enumerate()
2467 .filter(|(slot, _)| self.clock_mask & (1 << slot) != 0)
2468 .any(|(_, start)| now < start + self.clock_window)
2469 }
2470
2471 fn param(&self, index: Option<u8>) -> f32 {
2472 index
2473 .and_then(|i| self.params.get(i as usize))
2474 .copied()
2475 .unwrap_or(0.)
2476 }
2477
2478 pub fn bleed(&self) -> f32 {
2480 self.param(self.bleed_param).max(0.)
2481 }
2482
2483 pub fn backdrop_blur_radius(&self) -> f32 {
2485 self.param(self.backdrop_radius_param).max(0.)
2486 }
2487}
2488
2489#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
2492#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2493pub struct EffectCrossFade {
2494 pub from: EffectSpec,
2496 pub progress: f32,
2498}
2499
2500#[derive(Debug, Copy, Clone, Default)]
2519#[repr(C)]
2520#[expect(missing_docs)]
2521pub struct EffectQuad {
2522 pub order: DrawOrder,
2523 pub effect_id: u32,
2525 pub bounds: Bounds<ScaledPixels>,
2527 pub content_mask: ContentMask<ScaledPixels>,
2528 pub corner_radii: Corners<ScaledPixels>,
2530 pub params: [f32; 32],
2533 pub opacity: f32,
2534 pub time: f32,
2536 pub bleed: ScaledPixels,
2538 pub backdrop_blur_radius: ScaledPixels,
2541 pub scale: f32,
2543 pub flags: u32,
2544 pub corner_shapes: CornerShapes,
2546}
2547
2548impl EffectQuad {
2549 pub fn params_from(head: &[f32]) -> [f32; EFFECT_PARAM_SLOTS] {
2551 let mut params = [0.; EFFECT_PARAM_SLOTS];
2552 params[..head.len()].copy_from_slice(head);
2553 params
2554 }
2555
2556 pub fn needs_backdrop(&self) -> bool {
2559 self.flags & EFFECT_FLAG_NEEDS_BACKDROP != 0
2560 }
2561
2562 pub fn needs_content(&self) -> bool {
2564 self.flags & EFFECT_FLAG_NEEDS_CONTENT != 0
2565 }
2566
2567 pub fn has_history(&self) -> bool {
2569 self.flags & EFFECT_FLAG_HISTORY != 0
2570 }
2571
2572 pub fn history_size(&self) -> (u32, u32) {
2574 let side = |value: f32| (value.round().max(1.)) as u32;
2575 (
2576 side(self.bounds.size.width.0),
2577 side(self.bounds.size.height.0),
2578 )
2579 }
2580
2581 pub fn history_pass(mut self) -> Self {
2583 self.flags = (self.flags & !EFFECT_FLAG_NEEDS_BACKDROP) | EFFECT_FLAG_HISTORY_PASS;
2584 self
2585 }
2586
2587 pub fn effective_kernel_levels(&self) -> u32 {
2591 if !self.needs_backdrop() || self.backdrop_blur_radius.0 <= 0. {
2592 0
2593 } else {
2594 let radius_levels = (self.backdrop_blur_radius.0
2595 / BACKDROP_BLUR_RADIUS_PER_KERNEL_LEVEL)
2596 .ceil()
2597 .max(1.) as u32;
2598 radius_levels.min(MAX_BACKDROP_BLUR_KERNEL_LEVELS)
2599 }
2600 }
2601}
2602
2603impl From<EffectQuad> for Primitive {
2604 fn from(effect_quad: EffectQuad) -> Self {
2605 Primitive::EffectQuad(effect_quad, None)
2606 }
2607}
2608
2609const _: () = assert!(std::mem::size_of::<EffectQuad>() == 256);
2610const _: () = assert!(EFFECT_PARAM_SLOTS == 32);
2611
2612const _: () = assert!(std::mem::size_of::<Quad>() == 97 * 4);
2630const _: () = assert!(std::mem::size_of::<Background>() == 57 * 4);
2631const _: () = assert!(std::mem::size_of::<Shadow>() == 50 * 4);
2632const _: () = assert!(std::mem::size_of::<Underline>() == 30 * 4);
2633const _: () = assert!(std::mem::size_of::<PolychromeSprite>() == 46 * 4);
2634const _: () = assert!(std::mem::size_of::<TransformationMatrix>() == 6 * 4);
2635
2636static EFFECT_CLOCK_ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
2637
2638pub fn effect_clock_seconds() -> f32 {
2646 EFFECT_CLOCK_ORIGIN
2647 .get_or_init(std::time::Instant::now)
2648 .elapsed()
2649 .as_secs_f32()
2650}
2651
2652pub fn set_effect_clock_origin(origin: std::time::Instant) -> bool {
2655 EFFECT_CLOCK_ORIGIN.set(origin).is_ok()
2656}
2657
2658#[derive(Debug, Copy, Clone)]
2659#[repr(C)]
2660#[expect(missing_docs)]
2661pub struct Underline {
2662 pub order: DrawOrder,
2663 pub pad: u32, pub bounds: Bounds<ScaledPixels>,
2665 pub content_mask: ContentMask<ScaledPixels>,
2666 pub color: Hsla,
2667 pub thickness: ScaledPixels,
2668 pub wavy: PaddedBool32,
2669 pub transformation: TransformationMatrix,
2672}
2673
2674impl From<Underline> for Primitive {
2675 fn from(underline: Underline) -> Self {
2676 Primitive::Underline(underline)
2677 }
2678}
2679
2680#[derive(Debug, Copy, Clone)]
2681#[repr(C)]
2682#[expect(missing_docs)]
2683pub struct Shadow {
2684 pub order: DrawOrder,
2685 pub blur_radius: ScaledPixels,
2686 pub bounds: Bounds<ScaledPixels>,
2687 pub corner_radii: Corners<ScaledPixels>,
2688 pub content_mask: ContentMask<ScaledPixels>,
2689 pub color: Hsla,
2690 pub shape_bounds: Bounds<ScaledPixels>,
2691 pub shape_corner_radii: Corners<ScaledPixels>,
2692 pub inset: u32,
2695 pub pad: u32, pub transformation: TransformationMatrix,
2700 pub element_bounds: Bounds<ScaledPixels>,
2703 pub corner_shapes: CornerShapes,
2706}
2707
2708impl From<Shadow> for Primitive {
2709 fn from(shadow: Shadow) -> Self {
2710 Primitive::Shadow(shadow)
2711 }
2712}
2713
2714#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
2716#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2717#[repr(C)]
2718pub enum BorderStyle {
2719 #[default]
2721 Solid = 0,
2722 Dashed = 1,
2724}
2725
2726#[derive(Debug, Clone, Copy, PartialEq)]
2728#[repr(C)]
2729pub struct TransformationMatrix {
2730 pub rotation_scale: [[f32; 2]; 2],
2733 pub translation: [f32; 2],
2735}
2736
2737impl Eq for TransformationMatrix {}
2738
2739impl TransformationMatrix {
2740 pub fn unit() -> Self {
2742 Self {
2743 rotation_scale: [[1.0, 0.0], [0.0, 1.0]],
2744 translation: [0.0, 0.0],
2745 }
2746 }
2747
2748 pub fn translate(self, point: Point<ScaledPixels>) -> Self {
2750 self.compose(Self {
2751 rotation_scale: [[1.0, 0.0], [0.0, 1.0]],
2752 translation: [point.x.0, point.y.0],
2753 })
2754 }
2755
2756 pub fn rotate(self, angle: Radians) -> Self {
2758 self.compose(Self {
2759 rotation_scale: [
2760 [angle.0.cos(), -angle.0.sin()],
2761 [angle.0.sin(), angle.0.cos()],
2762 ],
2763 translation: [0.0, 0.0],
2764 })
2765 }
2766
2767 pub fn scale(self, size: Size<f32>) -> Self {
2769 self.compose(Self {
2770 rotation_scale: [[size.width, 0.0], [0.0, size.height]],
2771 translation: [0.0, 0.0],
2772 })
2773 }
2774
2775 #[inline]
2779 pub fn compose(self, other: TransformationMatrix) -> TransformationMatrix {
2780 if other == Self::unit() {
2781 return self;
2782 }
2783 TransformationMatrix {
2785 rotation_scale: [
2786 [
2787 self.rotation_scale[0][0] * other.rotation_scale[0][0]
2788 + self.rotation_scale[0][1] * other.rotation_scale[1][0],
2789 self.rotation_scale[0][0] * other.rotation_scale[0][1]
2790 + self.rotation_scale[0][1] * other.rotation_scale[1][1],
2791 ],
2792 [
2793 self.rotation_scale[1][0] * other.rotation_scale[0][0]
2794 + self.rotation_scale[1][1] * other.rotation_scale[1][0],
2795 self.rotation_scale[1][0] * other.rotation_scale[0][1]
2796 + self.rotation_scale[1][1] * other.rotation_scale[1][1],
2797 ],
2798 ],
2799 translation: [
2800 self.translation[0]
2801 + self.rotation_scale[0][0] * other.translation[0]
2802 + self.rotation_scale[0][1] * other.translation[1],
2803 self.translation[1]
2804 + self.rotation_scale[1][0] * other.translation[0]
2805 + self.rotation_scale[1][1] * other.translation[1],
2806 ],
2807 }
2808 }
2809
2810 pub(crate) fn transform_bounds(&self, bounds: Bounds<ScaledPixels>) -> Bounds<ScaledPixels> {
2812 if *self == Self::unit() {
2813 return bounds;
2814 }
2815 let [[xx, xy], [yx, yy]] = self.rotation_scale;
2816 let [translate_x, translate_y] = self.translation;
2817 let corners = [
2818 bounds.origin,
2819 bounds.top_right(),
2820 bounds.bottom_left(),
2821 bounds.bottom_right(),
2822 ]
2823 .map(|corner| {
2824 Point::new(
2825 ScaledPixels(xx * corner.x.0 + xy * corner.y.0 + translate_x),
2826 ScaledPixels(yx * corner.x.0 + yy * corner.y.0 + translate_y),
2827 )
2828 });
2829 let [first, rest @ ..] = corners;
2830 let top_left = rest.iter().fold(first, |min, corner| min.min(corner));
2831 let bottom_right = rest.iter().fold(first, |max, corner| max.max(corner));
2832 Bounds::from_corners(top_left, bottom_right)
2833 }
2834
2835 pub fn apply(&self, point: Point<Pixels>) -> Point<Pixels> {
2837 let input = [point.x.0, point.y.0];
2838 let mut output = self.translation;
2839 for (i, output_cell) in output.iter_mut().enumerate() {
2840 for (k, input_cell) in input.iter().enumerate() {
2841 *output_cell += self.rotation_scale[i][k] * *input_cell;
2842 }
2843 }
2844 Point::new(output[0].into(), output[1].into())
2845 }
2846
2847 pub fn inverse(&self) -> Option<TransformationMatrix> {
2856 let [[a, b], [c, d]] = self.rotation_scale;
2857 let det = a * d - b * c;
2858 if det == 0.0 || !det.is_finite() || !(1.0 / det).is_finite() {
2862 return None;
2863 }
2864 let inv = [[d / det, -b / det], [-c / det, a / det]];
2865 let [tx, ty] = self.translation;
2866 Some(TransformationMatrix {
2867 rotation_scale: inv,
2868 translation: [
2869 -(inv[0][0] * tx + inv[0][1] * ty),
2870 -(inv[1][0] * tx + inv[1][1] * ty),
2871 ],
2872 })
2873 }
2874
2875 #[inline]
2881 pub fn is_unit(&self) -> bool {
2882 *self == Self::unit()
2883 }
2884}
2885
2886pub(crate) fn transformed_bounds(
2892 bounds: Bounds<ScaledPixels>,
2893 matrix: TransformationMatrix,
2894) -> Bounds<ScaledPixels> {
2895 matrix.transform_bounds(bounds)
2896}
2897
2898pub(crate) fn axis_aligned_through(
2906 bounds: Bounds<ScaledPixels>,
2907 matrix: TransformationMatrix,
2908) -> Option<(Bounds<ScaledPixels>, f32)> {
2909 if matrix.is_unit() {
2910 return Some((bounds, 1.0));
2911 }
2912 let [[a, b], [c, d]] = matrix.rotation_scale;
2913 const EPS: f32 = 1e-6;
2914 if b.abs() > EPS || c.abs() > EPS || a.abs() <= EPS || d.abs() <= EPS {
2915 return None;
2916 }
2917 Some((transformed_bounds(bounds, matrix), a.abs().min(d.abs())))
2918}
2919
2920impl Default for TransformationMatrix {
2921 fn default() -> Self {
2922 Self::unit()
2923 }
2924}
2925
2926#[cfg(test)]
2927mod vn_axis_aligned_tests {
2928 use super::*;
2929 use crate::{Radians, point, size};
2930
2931 fn rect(x: f32, y: f32, w: f32, h: f32) -> Bounds<ScaledPixels> {
2932 Bounds {
2933 origin: point(ScaledPixels(x), ScaledPixels(y)),
2934 size: size(ScaledPixels(w), ScaledPixels(h)),
2935 }
2936 }
2937
2938 #[test]
2939 fn a_translate_moves_the_rect_and_a_rotation_has_no_rect() {
2940 let moved =
2941 TransformationMatrix::unit().translate(point(ScaledPixels(300.), ScaledPixels(120.)));
2942 assert_eq!(
2943 axis_aligned_through(rect(0., 0., 100., 50.), moved),
2944 Some((rect(300., 120., 100., 50.), 1.0))
2945 );
2946 let zoomed = TransformationMatrix::unit()
2948 .translate(point(ScaledPixels(50.), ScaledPixels(25.)))
2949 .scale(size(0.5, 0.5))
2950 .translate(point(ScaledPixels(-50.), ScaledPixels(-25.)));
2951 assert_eq!(
2952 axis_aligned_through(rect(0., 0., 100., 50.), zoomed),
2953 Some((rect(25., 12.5, 50., 25.), 0.5))
2954 );
2955 let turned = TransformationMatrix::unit().rotate(Radians(0.3));
2956 assert_eq!(axis_aligned_through(rect(0., 0., 100., 50.), turned), None);
2957 assert_eq!(
2958 axis_aligned_through(rect(1., 2., 3., 4.), TransformationMatrix::unit()),
2959 Some((rect(1., 2., 3., 4.), 1.0))
2960 );
2961 }
2962
2963 #[test]
2965 fn a_tiny_scale_is_still_invertible() {
2966 let tiny = TransformationMatrix { rotation_scale: [[0.0003, 0.0], [0.0, 0.0003]], translation: [5.0, 7.0] };
2967 let back = tiny.inverse().expect("an inverse");
2968 assert!((back.rotation_scale[0][0] - 1.0 / 0.0003).abs() < 1.0);
2969 let flat = TransformationMatrix { rotation_scale: [[1.0, 0.0], [0.0, 0.0]], translation: [0.0, 0.0] };
2970 assert!(flat.inverse().is_none());
2971 }
2972
2973 #[test]
2976 fn a_transform_moves_a_paths_curves() {
2977 let mut builder = crate::PathBuilder::fill();
2978 builder.move_to(point(Pixels(0.), Pixels(0.)));
2979 builder.line_to(point(Pixels(10.), Pixels(0.)));
2980 builder.curve_to(point(Pixels(10.), Pixels(20.)), point(Pixels(20.), Pixels(10.)));
2981 builder.close();
2982 let path = builder.build().unwrap();
2983 let moved =
2984 TransformationMatrix::unit().translate(point(ScaledPixels(300.), ScaledPixels(-120.)));
2985 let still = path.bin(2.0).bounds();
2986 assert_eq!(
2987 path.transformed(moved, 2.0).bin(2.0).bounds(),
2988 Bounds::new(still.origin + point(ScaledPixels(300.), ScaledPixels(-120.)), still.size)
2989 );
2990 let turned = TransformationMatrix::unit().rotate(Radians(std::f32::consts::FRAC_PI_2));
2993 let turned = path.transformed(turned, 2.0).bin(2.0).bounds();
2994 assert!((turned.size.width.0 - still.size.height.0).abs() < 1e-3);
2995 assert!((turned.size.height.0 - still.size.width.0).abs() < 1e-3);
2996 }
2997}
2998
2999#[derive(Copy, Clone, Debug)]
3000#[repr(C)]
3001#[expect(missing_docs)]
3002pub struct MonochromeSprite {
3003 pub order: DrawOrder,
3004 pub raw_coverage: PaddedBool32,
3006 pub tile: AtlasTile,
3007 pub bounds: Bounds<ScaledPixels>,
3008 pub content_mask: ContentMask<ScaledPixels>,
3009 pub color: Hsla,
3010 pub transformation: TransformationMatrix,
3011 pub animation: SpriteAnimationId,
3014 pub pad: u32,
3015}
3016
3017#[derive(Copy, Clone, Debug, PartialEq, Eq)]
3022#[repr(transparent)]
3023pub struct SpriteAnimationId(u32);
3024
3025impl SpriteAnimationId {
3026 pub const NONE: Self = Self(u32::MAX);
3028}
3029
3030impl Default for SpriteAnimationId {
3031 fn default() -> Self {
3032 Self::NONE
3033 }
3034}
3035
3036#[derive(Copy, Clone, Debug)]
3039pub(crate) struct SpriteAnimation {
3040 transformation: TimedTransformation,
3041 center: Point<Pixels>,
3042 scale_factor: f32,
3043 base_color: Hsla,
3044 sprite_index: usize,
3045 outer: TransformationMatrix,
3047}
3048
3049impl SpriteAnimation {
3050 pub(crate) fn new(
3051 transformation: TimedTransformation,
3052 center: Point<Pixels>,
3053 scale_factor: f32,
3054 ) -> Self {
3055 Self {
3056 transformation,
3057 center,
3058 scale_factor,
3059 base_color: Hsla::default(),
3060 sprite_index: usize::MAX,
3061 outer: TransformationMatrix::unit(),
3062 }
3063 }
3064
3065 pub(crate) fn under(self, outer: TransformationMatrix) -> Self {
3067 Self { outer, ..self }
3068 }
3069}
3070
3071impl From<MonochromeSprite> for Primitive {
3072 fn from(sprite: MonochromeSprite) -> Self {
3073 Primitive::MonochromeSprite(sprite)
3074 }
3075}
3076
3077#[derive(Copy, Clone, Debug)]
3078#[repr(C)]
3079#[expect(missing_docs)]
3080pub struct SubpixelSprite {
3081 pub order: DrawOrder,
3082 pub pad: u32, pub tile: AtlasTile,
3084 pub bounds: Bounds<ScaledPixels>,
3085 pub content_mask: ContentMask<ScaledPixels>,
3086 pub color: Hsla,
3087 pub transformation: TransformationMatrix,
3088}
3089
3090impl From<SubpixelSprite> for Primitive {
3091 fn from(sprite: SubpixelSprite) -> Self {
3092 Primitive::SubpixelSprite(sprite)
3093 }
3094}
3095
3096#[derive(Copy, Clone, Debug)]
3097#[repr(C)]
3098#[expect(missing_docs)]
3099pub struct PolychromeSprite {
3100 pub order: DrawOrder,
3101 pub pad: u32,
3102 pub tile: AtlasTile,
3103 pub grayscale: PaddedBool32,
3104 pub opacity: f32,
3105 pub bounds: Bounds<ScaledPixels>,
3106 pub content_mask: ContentMask<ScaledPixels>,
3107 pub corner_radii: Corners<ScaledPixels>,
3108 pub transformation: TransformationMatrix,
3118 pub tint: Hsla,
3122 pub corner_shapes: CornerShapes,
3124}
3125
3126impl From<PolychromeSprite> for Primitive {
3127 fn from(sprite: PolychromeSprite) -> Self {
3128 Primitive::PolychromeSprite(sprite)
3129 }
3130}
3131
3132#[derive(Clone, Debug)]
3133#[allow(missing_docs)]
3134pub struct PaintSurface {
3135 pub order: DrawOrder,
3136 pub bounds: Bounds<ScaledPixels>,
3137 pub content_mask: ContentMask<ScaledPixels>,
3138 #[cfg(any(target_os = "macos", target_os = "ios"))]
3139 pub image_buffer: objc2_core_foundation::CFRetained<objc2_core_video::CVPixelBuffer>,
3140}
3141
3142impl From<PaintSurface> for Primitive {
3143 fn from(surface: PaintSurface) -> Self {
3144 Primitive::Surface(surface)
3145 }
3146}
3147
3148#[derive(Clone, Copy, Debug, PartialEq)]
3149#[repr(C)]
3150#[expect(missing_docs)]
3151pub struct PathCurve {
3152 pub p0: Point<f32>,
3153 pub p1: Point<f32>,
3154 pub a: Point<f32>,
3155 pub b: Point<f32>,
3156 pub sign: f32,
3157 pub pad: u32, }
3159
3160#[derive(Clone, Copy, Debug)]
3161#[repr(C)]
3162#[expect(missing_docs)]
3163pub struct PathPaint {
3164 pub bounds: Bounds<ScaledPixels>,
3166 pub content_mask: ContentMask<ScaledPixels>,
3167 pub color: Background,
3168 pub even_odd: PaddedBool32,
3169 pub pad: u32, }
3171
3172#[derive(Clone, Copy, Debug, PartialEq)]
3173#[repr(C)]
3174#[expect(missing_docs)]
3175pub struct PathTile {
3176 pub paint: u32,
3177 pub curve_start: u32,
3178 pub curve_count: u32,
3179 pub backdrop: i32,
3180 pub top_left: Point<f32>,
3181 pub bottom_right: Point<f32>,
3182 pub reference: Point<f32>,
3183 pub curves_top_left: Point<f32>,
3184 pub curves_bottom_right: Point<f32>,
3185}
3186
3187#[derive(Clone, Debug)]
3188#[expect(missing_docs)]
3189pub struct PaintedPath {
3190 order: DrawOrder,
3191 bounds: Bounds<ScaledPixels>,
3192 tiles: Rc<PathTiles>,
3193 paint: PathPaint,
3194}
3195
3196#[expect(missing_docs)]
3197impl PaintedPath {
3198 pub fn new(
3200 path: Path,
3201 scale_factor: f32,
3202 content_mask: ContentMask<Pixels>,
3203 color: Background,
3204 ) -> Self {
3205 let content_mask = content_mask.scale(scale_factor);
3206 let mut tiles = path.bin(scale_factor);
3207 tiles.retain_visible(content_mask.bounds);
3208 let paint = PathPaint {
3209 bounds: tiles.bounds(),
3210 content_mask,
3211 color,
3212 even_odd: path.even_odd().into(),
3213 pad: 0,
3214 };
3215 Self {
3216 order: 0,
3217 bounds: tiles.painted_bounds(),
3218 tiles: Rc::new(tiles),
3219 paint,
3220 }
3221 }
3222
3223 pub fn tile_count(&self) -> usize {
3224 self.tiles.tiles().len()
3225 }
3226
3227 pub fn append_to(
3228 &self,
3229 paints: &mut Vec<PathPaint>,
3230 curves: &mut Vec<PathCurve>,
3231 tiles: &mut Vec<PathTile>,
3232 ) {
3233 let paint_index = paints.len() as u32;
3234 let curve_start = curves.len() as u32;
3235 paints.push(self.paint);
3236 curves.extend_from_slice(self.tiles.curves());
3237 tiles.extend(self.tiles.tiles().iter().map(|tile| PathTile {
3238 paint: paint_index,
3239 curve_start: curve_start + tile.curve_start,
3240 ..*tile
3241 }));
3242 }
3243}
3244
3245impl From<PaintedPath> for Primitive {
3246 fn from(path: PaintedPath) -> Self {
3247 Primitive::Path(path)
3248 }
3249}
3250
3251#[cfg(test)]
3252mod tests {
3253 use super::*;
3254 use crate::{point, size};
3255
3256 fn square(x: f32) -> Bounds<ScaledPixels> {
3257 Bounds {
3258 origin: point(ScaledPixels(x), ScaledPixels(0.)),
3259 size: size(ScaledPixels(10.), ScaledPixels(10.)),
3260 }
3261 }
3262
3263 fn quad(x: f32) -> Quad {
3264 Quad {
3265 bounds: square(x),
3266 content_mask: ContentMask::rect(square(x)),
3267 ..Default::default()
3268 }
3269 }
3270
3271 fn underline(x: f32) -> Underline {
3272 Underline {
3273 order: 0,
3274 pad: 0,
3275 bounds: square(x),
3276 content_mask: ContentMask::rect(square(x)),
3277 color: Hsla::default(),
3278 thickness: ScaledPixels(1.),
3279 wavy: false.into(),
3280 transformation: TransformationMatrix::unit(),
3281 }
3282 }
3283
3284 fn batch_labels(scene: &mut Scene) -> Vec<String> {
3285 scene.finish();
3286 scene.batches().map(|batch| batch.label()).collect()
3287 }
3288
3289 #[test]
3290 fn layers_are_drawn_in_paint_order() {
3291 let mut scene = Scene::default();
3293 scene.insert_primitive(quad(0.));
3294 scene.push_layer();
3295 scene.insert_primitive(underline(0.));
3296 scene.insert_primitive(underline(5.));
3297 scene.pop_layer();
3298 scene.insert_primitive(quad(5.));
3299 assert_eq!(
3300 batch_labels(&mut scene),
3301 ["quads (1)", "underlines (2)", "quads (1)"]
3302 );
3303
3304 let mut scene = Scene::default();
3306 scene.push_layer();
3307 scene.insert_primitive(underline(0.));
3308 scene.pop_layer();
3309 scene.push_layer();
3310 scene.insert_primitive(quad(5.));
3311 scene.pop_layer();
3312 assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]);
3313 }
3314
3315 #[test]
3316 fn nested_layers_are_drawn_above_their_parents() {
3317 let mut scene = Scene::default();
3320 scene.push_layer();
3321 scene.insert_primitive(underline(0.));
3322 scene.push_layer();
3323 scene.insert_primitive(quad(5.));
3324 scene.pop_layer();
3325 scene.insert_primitive(underline(5.));
3326 scene.pop_layer();
3327 assert_eq!(batch_labels(&mut scene), ["underlines (2)", "quads (1)"]);
3328
3329 let mut scene = Scene::default();
3331 scene.push_layer();
3332 scene.insert_primitive(quad(0.));
3333 scene.push_layer();
3334 scene.insert_primitive(quad(5.));
3335 scene.pop_layer();
3336 scene.insert_primitive(quad(8.));
3337 scene.pop_layer();
3338 assert_eq!(batch_labels(&mut scene), ["quads (3)"]);
3339 assert_eq!(
3340 scene
3341 .quads
3342 .iter()
3343 .map(|quad| quad.bounds)
3344 .collect::<Vec<_>>(),
3345 [square(0.), square(8.), square(5.)]
3346 );
3347
3348 let mut scene = Scene::default();
3350 scene.push_layer();
3351 scene.push_layer();
3352 scene.insert_primitive(underline(0.));
3353 scene.pop_layer();
3354 scene.pop_layer();
3355 scene.push_layer();
3356 scene.insert_primitive(quad(5.));
3357 scene.pop_layer();
3358 assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]);
3359 }
3360}
3361
3362
3363#[cfg(test)]
3364mod vn_color_group_tests {
3365 use super::*;
3366 use crate::{VnColorMatrix, VnClipGeometry, VnFillRule, size};
3367 use std::sync::Arc;
3368
3369 fn rectangle() -> Bounds<ScaledPixels> {
3370 Bounds { origin: point(ScaledPixels(0.), ScaledPixels(0.)), size: size(ScaledPixels(100.), ScaledPixels(100.)) }
3371 }
3372
3373 fn filter(id: u64) -> VnIsolation {
3374 VnIsolation {
3375 text_paint: None,
3376 geometry: Arc::new(VnClipGeometry {
3377 fill_rule: VnFillRule::NonZero,
3378 segments: vec![[0., 0., 100., 0.], [100., 0., 100., 100.], [100., 100., 0., 100.], [0., 100., 0., 0.]],
3379 bounds: rectangle(),
3380 }),
3381 color_matrix: Some(VnColorMatrix { group_id: id, values: VnColorMatrix::IDENTITY, linear_rgb: true }),
3382 content_mask: ContentMask { bounds: rectangle(), ..Default::default() },
3383 capture: None,
3384 }
3385 }
3386
3387 fn paint(scene: &mut Scene) {
3388 scene.insert_primitive(Quad { bounds: rectangle(), content_mask: ContentMask { bounds: rectangle(), ..Default::default() }, ..Default::default() });
3389 }
3390
3391 fn text_mask(id: u64) -> VnIsolation {
3392 let mut isolation = filter(id);
3393 isolation.color_matrix = None;
3394 isolation.text_paint = Some(Arc::new(crate::VnTextPaint {
3395 fill: crate::VnTextFill { group_id: id, backgrounds: vec![crate::red().into(), crate::blue().into()] },
3396 bounds: [10., 20., 40., 30.],
3397 inverse: [0., 1., -1., 0., 50., 60.], scale_factor: 1.5,
3398 geometry: isolation.geometry.clone(), content_mask: isolation.content_mask,
3399 }));
3400 isolation
3401 }
3402
3403 #[test]
3404 fn text_glyphs_and_deferred_replay_share_one_gradient_stack_and_source() {
3405 let mut scene = Scene::default();
3406 for _ in 0..3 {
3407 scene.vn_push_isolation(text_mask(7));
3408 paint(&mut scene);
3409 scene.vn_pop_isolation();
3410 }
3411 assert_eq!(scene.vn_layers.len(), 1, "a text scope composites once, not per glyph");
3412 assert_eq!(scene.vn_groups[0].quads.len(), 3);
3413 assert_eq!(scene.vn_text_backgrounds.len(), 2, "metadata belongs to a text scope, not each glyph");
3414 assert_eq!(scene.vn_layers[0].pad, [0, 0, 2]);
3415 let brush = scene.vn_text_backgrounds[0];
3416 assert_eq!(brush.bounds.origin.x.0, 10.);
3417 assert_eq!(brush.inverse.apply(point(px(2.), px(3.))), point(px(53.), px(58.)));
3418 assert_eq!(brush.scale_factor, 1.5);
3419 let operations = 0..scene.len();
3420 scene.finish();
3421 let mut replay = Scene::default();
3422 replay.replay(operations, &scene);
3423 assert_eq!(replay.vn_layers.len(), 1);
3424 assert_eq!(replay.vn_text_backgrounds.len(), 2, "cached operations rebuild valid metadata indices");
3425 assert_eq!(replay.vn_groups[0].quads.len(), 3);
3426 replay.clear();
3427 assert!(replay.vn_text_backgrounds.is_empty());
3428 replay.vn_push_isolation(text_mask(7));
3429 paint(&mut replay);
3430 replay.vn_pop_isolation();
3431 assert_eq!(replay.vn_text_backgrounds.len(), 2);
3432 assert_eq!(replay.vn_groups[0].quads.len(), 1, "new frames cannot retain old mask coverage");
3433 }
3434
3435 #[test]
3436 fn text_and_color_filter_group_identities_do_not_alias() {
3437 let mut scene = Scene::default();
3438 scene.vn_push_isolation(filter(7));
3439 scene.vn_push_isolation(text_mask(7));
3440 paint(&mut scene);
3441 scene.vn_pop_isolation();
3442 scene.vn_pop_isolation();
3443 assert_eq!(scene.vn_groups.len(), 2);
3444 assert_eq!(scene.vn_groups[1].vn_layers.len(), 1);
3445 assert_eq!(scene.vn_layers[0].pad[0], 1);
3446 assert_eq!(scene.vn_groups[1].vn_layers[0].pad[2], 2);
3447 assert_eq!(std::mem::size_of::<VnLayer>(), 240, "keep the HLSL layer ABI");
3448 assert_eq!(std::mem::size_of::<VnTextBackground>(), 276, "match the HLSL structured buffer stride");
3449 assert_eq!(std::mem::offset_of!(VnTextBackground, bounds), 228);
3450 assert_eq!(std::mem::offset_of!(VnTextBackground, inverse), 244);
3451 assert_eq!(std::mem::offset_of!(VnTextBackground, scale_factor), 268);
3452 }
3453
3454 #[test]
3455 fn text_sources_partition_child_clip_and_filter_contexts_and_rejoin_deferred_siblings() {
3456 for matrix in [false, true] {
3457 let mut first = filter(11);
3458 let mut second = filter(12);
3459 if !matrix { first.color_matrix = None; second.color_matrix = None; }
3460 let mut scene = Scene::default();
3461 for parent in [first.clone(), second, first] {
3462 scene.vn_push_isolation(parent);
3463 scene.vn_push_isolation(text_mask(7));
3464 paint(&mut scene);
3465 scene.vn_pop_isolation();
3466 scene.vn_pop_isolation();
3467 }
3468 let masks: Vec<_> = scene.vn_groups.iter().filter(|group| !group.quads.is_empty()).collect();
3471 assert_eq!(masks.len(), 2, "text cannot be captured by the first child's clip or filter");
3472 assert_eq!(masks[0].quads.len(), 2, "deferred text in the same parent reuses its source");
3473 assert_eq!(masks[1].quads.len(), 1);
3474 assert_eq!(scene.vn_text_backgrounds.len(), 4, "two brushes per distinct isolation context");
3475 let operations = 0..scene.len();
3476 scene.finish();
3477 let mut replay = Scene::default();
3478 replay.replay(operations, &scene);
3479 assert_eq!(replay.vn_text_backgrounds.len(), 4, "paint-cache replay interns equivalent parent contexts");
3480 let masks: Vec<_> = replay.vn_groups.iter().filter(|group| !group.quads.is_empty()).collect();
3481 assert_eq!(masks.len(), 2);
3482 assert_eq!(masks[0].quads.len(), 2);
3483 }
3484 }
3485
3486 #[test]
3487 fn deferred_source_is_composited_with_its_background_before_one_color_matrix() {
3488 let mut scene = Scene::default();
3489 scene.vn_push_isolation(filter(1));
3490 paint(&mut scene);
3491 scene.vn_pop_isolation();
3492 scene.vn_push_isolation(filter(1));
3493 paint(&mut scene);
3494 scene.vn_pop_isolation();
3495 assert_eq!(scene.vn_layers.len(), 1, "one composite, not separately filtered translucent pieces");
3496 assert_eq!(scene.vn_groups.len(), 1);
3497 assert_eq!(scene.vn_groups[0].quads.len(), 2);
3498 assert!(scene.vn_groups[0].quads[1].order > scene.vn_groups[0].quads[0].order, "deferred source blends over its earlier background");
3499 let operations = 0..scene.len();
3500 scene.finish();
3501 assert_eq!(scene.vn_group_count(), 2);
3502 let mut replay = Scene::default();
3503 replay.replay(operations, &scene);
3504 assert_eq!(replay.vn_layers.len(), 1, "cached operations rebuild the same keyed source");
3505 assert_eq!(replay.vn_groups[0].quads.len(), 2);
3506 replay.clear();
3507 replay.vn_push_isolation(filter(1));
3508 paint(&mut replay);
3509 replay.vn_pop_isolation();
3510 assert_eq!(replay.vn_groups[0].quads.len(), 1, "a new frame has no old source pixels");
3511 }
3512
3513 #[test]
3514 fn an_initially_empty_filter_keeps_its_composite_for_deferred_descendants() {
3515 let mut scene = Scene::default();
3516 scene.vn_push_isolation(filter(1));
3517 scene.vn_pop_isolation();
3518 scene.vn_push_isolation(filter(1));
3519 paint(&mut scene);
3520 scene.vn_pop_isolation();
3521 assert_eq!(scene.vn_layers.len(), 1);
3522 assert_eq!(scene.vn_groups.len(), 1);
3523 assert_eq!(scene.vn_groups[0].quads.len(), 1);
3524 }
3525
3526 #[test]
3527 fn nested_filtered_sources_reopen_without_duplicate_inner_composites() {
3528 let mut scene = Scene::default();
3529 scene.vn_push_isolation(filter(1));
3530 paint(&mut scene);
3531 scene.vn_push_isolation(filter(2));
3532 paint(&mut scene);
3533 scene.vn_pop_isolation();
3534 scene.vn_pop_isolation();
3535 scene.vn_push_isolation(filter(1));
3536 scene.vn_push_isolation(filter(2));
3537 paint(&mut scene);
3538 scene.vn_pop_isolation();
3539 scene.vn_pop_isolation();
3540 assert_eq!(scene.vn_layers.len(), 1, "only the outer composite belongs to the page");
3541 assert_eq!(scene.vn_groups.len(), 2);
3542 assert_eq!(scene.vn_groups[0].quads.len(), 2, "both inner source pieces share one filter");
3543 assert_eq!(scene.vn_groups[1].vn_layers.len(), 1, "the inner filter composites once into the outer source");
3544 scene.finish();
3545 assert_eq!(scene.vn_group_count(), 3);
3546 assert_eq!(scene.vn_layers.len(), 2);
3547 }
3548
3549 #[test]
3550 fn an_in_place_snapshot_samples_through_the_captured_transform() {
3551 let mut capture = filter(0);
3552 capture.color_matrix = None;
3553 capture.capture = Some(VnCaptureInfo {
3554 id: 3,
3555 border_box: rectangle(),
3556 transform: crate::TransformationMatrix { rotation_scale: [[2., 0.], [0., 2.]], translation: [100., 5.] },
3557 });
3558 let mut scene = Scene::default();
3559 scene.vn_push_isolation(capture);
3560 paint(&mut scene);
3561 scene.vn_pop_isolation();
3562 let viewport = Bounds { origin: point(ScaledPixels(0.), ScaledPixels(0.)), size: size(ScaledPixels(400.), ScaledPixels(400.)) };
3563 scene.vn_insert_snapshot(VnSnapshotPaint {
3564 id: 3,
3565 to_unit: [0.; 6],
3566 bounds: viewport,
3567 content_mask: ContentMask { bounds: viewport, ..Default::default() },
3568 opacity: 1.,
3569 plus_lighter: false,
3570 in_place: true,
3571 });
3572 scene.finish();
3573 scene.vn_resolve_snapshots(|_| None);
3574 let layer = scene.vn_layers.iter().find(|l| l.snapshot_id() == Some(3)).copied().unwrap();
3575 assert_eq!(layer.flags, vn_layer_flags::SNAPSHOT);
3576 assert_eq!(layer.source_transform, [0.5, 0., -50., 0., 0., 0.5, -2.5, 0.]);
3577 assert_eq!(layer.bounds.origin, point(ScaledPixels(100.), ScaledPixels(5.)));
3578 assert_eq!(layer.bounds.size, size(ScaledPixels(200.), ScaledPixels(200.)));
3579 }
3580}