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, 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}
2000
2001impl From<Quad> for Primitive {
2002 fn from(quad: Quad) -> Self {
2003 Primitive::Quad(quad)
2004 }
2005}
2006
2007pub const MAX_BACKDROP_BLUR_KERNEL_LEVELS: u32 = 5;
2010
2011const BACKDROP_BLUR_RADIUS_PER_KERNEL_LEVEL: f32 = 5.;
2014
2015#[derive(Debug, Copy, Clone)]
2021#[repr(C)]
2022#[expect(missing_docs)]
2023pub struct BackdropBlurRect {
2024 pub order: DrawOrder,
2025 pub pad: u32,
2026 pub bounds: Bounds<ScaledPixels>,
2027 pub content_mask: ContentMask<ScaledPixels>,
2028 pub corner_radii: Corners<ScaledPixels>,
2029 pub blur_radius: ScaledPixels,
2030 pub opacity: f32,
2031 pub tint: Hsla,
2032}
2033
2034impl Default for BackdropBlurRect {
2035 fn default() -> Self {
2036 Self {
2037 order: Default::default(),
2038 pad: Default::default(),
2039 bounds: Default::default(),
2040 content_mask: Default::default(),
2041 corner_radii: Default::default(),
2042 blur_radius: Default::default(),
2043 opacity: 1.,
2044 tint: Default::default(),
2045 }
2046 }
2047}
2048
2049impl BackdropBlurRect {
2050 pub fn effective_kernel_levels(&self) -> u32 {
2073 if self.blur_radius.0 <= 0. {
2074 0
2075 } else {
2076 let radius_levels = (self.blur_radius.0 / BACKDROP_BLUR_RADIUS_PER_KERNEL_LEVEL)
2077 .ceil()
2078 .max(1.) as u32;
2079 radius_levels.min(MAX_BACKDROP_BLUR_KERNEL_LEVELS)
2080 }
2081 }
2082}
2083
2084impl From<BackdropBlurRect> for Primitive {
2085 fn from(backdrop_blur_rect: BackdropBlurRect) -> Self {
2086 Primitive::BackdropBlurRect(backdrop_blur_rect)
2087 }
2088}
2089
2090pub mod effect_id {
2100 pub const FROST: u32 = 0;
2103 pub const NOISE: u32 = 1;
2105 pub const GLOW: u32 = 2;
2107 pub const COUNT: u32 = 3;
2109 pub const PUNCH: u32 = u32::MAX - 1;
2115 pub const CONTENT: u32 = u32::MAX - 2;
2120 pub const NONE: u32 = u32::MAX;
2124}
2125
2126pub const EFFECT_FLAG_NEEDS_BACKDROP: u32 = 1;
2130
2131pub const EFFECT_FLAG_NEEDS_CONTENT: u32 = 2;
2135
2136pub const EFFECT_FLAG_HISTORY: u32 = 4;
2140
2141pub const EFFECT_FLAG_HISTORY_PASS: u32 = 8;
2144
2145#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
2161#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2162pub struct TransformSpec {
2163 pub translate: (TransformLength, TransformLength),
2167 pub rotate: f32,
2170 pub scale: (f32, f32),
2172 #[serde(default)]
2176 pub shear: f32,
2177 #[serde(default)]
2181 pub translation_basis: Option<[[f32; 3]; 2]>,
2182 pub origin: (TransformLength, TransformLength),
2192}
2193
2194#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
2196#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2197pub enum TransformLength {
2198 Pixels(f32),
2200 Fraction(f32),
2204}
2205
2206impl TransformLength {
2207 pub const ZERO: Self = Self::Pixels(0.0);
2209
2210 pub fn resolve(self, own: f32) -> f32 {
2212 match self {
2213 Self::Pixels(v) => v,
2214 Self::Fraction(f) => f * own,
2215 }
2216 }
2217
2218 pub fn is_zero(self) -> bool {
2220 match self {
2221 Self::Pixels(v) | Self::Fraction(v) => v == 0.0,
2222 }
2223 }
2224
2225 pub fn interpolate(self, other: Self, t: f32) -> Self {
2233 let lerp = |a: f32, b: f32| a + (b - a) * t;
2234 match (self, other) {
2235 (Self::Pixels(a), Self::Pixels(b)) => Self::Pixels(lerp(a, b)),
2236 (Self::Fraction(a), Self::Fraction(b)) => Self::Fraction(lerp(a, b)),
2237 (a, b) if a.is_zero() => match b {
2238 Self::Pixels(v) => Self::Pixels(lerp(0.0, v)),
2239 Self::Fraction(v) => Self::Fraction(lerp(0.0, v)),
2240 },
2241 (a, b) if b.is_zero() => match a {
2242 Self::Pixels(v) => Self::Pixels(lerp(v, 0.0)),
2243 Self::Fraction(v) => Self::Fraction(lerp(v, 0.0)),
2244 },
2245 (a, b) => {
2246 if t < 0.5 {
2247 a
2248 } else {
2249 b
2250 }
2251 }
2252 }
2253 }
2254}
2255
2256impl Default for TransformSpec {
2257 fn default() -> Self {
2258 Self::IDENTITY
2259 }
2260}
2261
2262impl TransformSpec {
2263 pub const IDENTITY: Self = Self {
2265 translate: (TransformLength::ZERO, TransformLength::ZERO),
2266 rotate: 0.0,
2267 scale: (1.0, 1.0),
2268 origin: Self::CENTRE_ORIGIN,
2269 shear: 0.0,
2270 translation_basis: None,
2271 };
2272
2273 pub const CENTRE_ORIGIN: (TransformLength, TransformLength) =
2275 (TransformLength::Fraction(0.5), TransformLength::Fraction(0.5));
2276
2277 pub fn is_identity(&self) -> bool {
2283 self.rotate == 0.0
2284 && self.scale == (1.0, 1.0)
2285 && self.shear == 0.0
2286 && match self.translation_basis {
2287 Some(basis) => basis.iter().flatten().all(|v| *v == 0.0),
2288 None => self.translate.0.is_zero() && self.translate.1.is_zero(),
2289 }
2290 }
2291
2292 fn translation_coefficients(&self) -> [[f32; 3]; 2] {
2293 self.translation_basis.unwrap_or_else(|| {
2294 let x = match self.translate.0 {
2295 TransformLength::Pixels(v) => [v, 0.0, 0.0],
2296 TransformLength::Fraction(v) => [0.0, v, 0.0],
2297 };
2298 let y = match self.translate.1 {
2299 TransformLength::Pixels(v) => [v, 0.0, 0.0],
2300 TransformLength::Fraction(v) => [0.0, 0.0, v],
2301 };
2302 [x, y]
2303 })
2304 }
2305 pub fn interpolate(self, other: Self, t: f32) -> Self {
2309 let lerp = |a: f32, b: f32| a + (b - a) * t;
2310 Self {
2311 translate: (
2312 self.translate.0.interpolate(other.translate.0, t),
2313 self.translate.1.interpolate(other.translate.1, t),
2314 ),
2315 rotate: lerp(self.rotate, other.rotate),
2316 shear: lerp(self.shear, other.shear),
2317 translation_basis: if self.translation_basis.is_some() || other.translation_basis.is_some() {
2318 let a = self.translation_coefficients();
2319 let b = other.translation_coefficients();
2320 Some(std::array::from_fn(|row| std::array::from_fn(|column| lerp(a[row][column], b[row][column]))))
2321 } else { None },
2322 scale: (
2323 lerp(self.scale.0, other.scale.0),
2324 lerp(self.scale.1, other.scale.1),
2325 ),
2326 origin: (
2327 self.origin.0.interpolate(other.origin.0, t),
2328 self.origin.1.interpolate(other.origin.1, t),
2329 ),
2330 }
2331 }
2332
2333 pub fn to_matrix(self, bounds: Bounds<Pixels>, scale_factor: f32) -> TransformationMatrix {
2343 let anchor = bounds.origin
2344 + Point::new(
2345 px(self.origin.0.resolve(bounds.size.width.0)),
2346 px(self.origin.1.resolve(bounds.size.height.0)),
2347 );
2348 let coefficients = self.translation_coefficients();
2349 let resolve = |row: [f32; 3]| px(row[0] + row[1] * bounds.size.width.0 + row[2] * bounds.size.height.0);
2350 let translate = Point::new(resolve(coefficients[0]), resolve(coefficients[1]));
2351 TransformationMatrix::unit()
2352 .translate((anchor + translate).scale(scale_factor))
2353 .rotate(Radians(self.rotate))
2354 .compose(TransformationMatrix {
2355 rotation_scale: [[self.scale.0, self.shear], [0.0, self.scale.1]],
2356 translation: [0.0, 0.0],
2357 })
2358 .translate(anchor.scale(-scale_factor))
2359 }
2360}
2361
2362pub const EFFECT_PARAM_SLOTS: usize = 32;
2365
2366#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
2376#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2377pub struct EffectSpec {
2378 pub id: u32,
2380 pub flags: u32,
2382 pub length_mask: u32,
2385 pub backdrop_radius_param: Option<u8>,
2388 pub bleed_param: Option<u8>,
2391 pub animated: bool,
2394 #[serde(default)]
2397 pub animated_param: Option<u8>,
2398 pub pointer_param: Option<u8>,
2401 pub pointer_times_param: Option<u8>,
2404 pub clock_mask: u32,
2407 pub clock_window: f32,
2409 pub params: [f32; EFFECT_PARAM_SLOTS],
2411 #[serde(default)]
2414 pub textures: [Option<crate::EffectTextureParam>; crate::EFFECT_TEXTURE_SLOTS],
2415}
2416
2417impl EffectSpec {
2418 pub const NONE: EffectSpec = EffectSpec {
2421 id: effect_id::NONE,
2422 flags: 0,
2423 length_mask: 0,
2424 backdrop_radius_param: None,
2425 bleed_param: None,
2426 animated: false,
2427 animated_param: None,
2428 pointer_param: None,
2429 pointer_times_param: None,
2430 clock_mask: 0,
2431 clock_window: 0.,
2432 params: [0.; EFFECT_PARAM_SLOTS],
2433 textures: [None; crate::EFFECT_TEXTURE_SLOTS],
2434 };
2435
2436 pub fn is_some(&self) -> bool {
2438 self.id != effect_id::NONE
2439 }
2440
2441 pub fn interpolates_with(&self, other: &EffectSpec) -> bool {
2445 self.id == other.id && self.textures == other.textures
2446 }
2447
2448 pub fn follows_pointer(&self) -> bool {
2451 self.pointer_param.is_some() || self.pointer_times_param.is_some()
2452 }
2453
2454 pub fn clock_running(&self, now: f32) -> bool {
2457 if self.clock_mask == 0 {
2458 return false;
2459 }
2460 self.params
2461 .iter()
2462 .enumerate()
2463 .filter(|(slot, _)| self.clock_mask & (1 << slot) != 0)
2464 .any(|(_, start)| now < start + self.clock_window)
2465 }
2466
2467 fn param(&self, index: Option<u8>) -> f32 {
2468 index
2469 .and_then(|i| self.params.get(i as usize))
2470 .copied()
2471 .unwrap_or(0.)
2472 }
2473
2474 pub fn bleed(&self) -> f32 {
2476 self.param(self.bleed_param).max(0.)
2477 }
2478
2479 pub fn backdrop_blur_radius(&self) -> f32 {
2481 self.param(self.backdrop_radius_param).max(0.)
2482 }
2483}
2484
2485#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
2488#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2489pub struct EffectCrossFade {
2490 pub from: EffectSpec,
2492 pub progress: f32,
2494}
2495
2496#[derive(Debug, Copy, Clone, Default)]
2515#[repr(C)]
2516#[expect(missing_docs)]
2517pub struct EffectQuad {
2518 pub order: DrawOrder,
2519 pub effect_id: u32,
2521 pub bounds: Bounds<ScaledPixels>,
2523 pub content_mask: ContentMask<ScaledPixels>,
2524 pub corner_radii: Corners<ScaledPixels>,
2526 pub params: [f32; 32],
2529 pub opacity: f32,
2530 pub time: f32,
2532 pub bleed: ScaledPixels,
2534 pub backdrop_blur_radius: ScaledPixels,
2537 pub scale: f32,
2539 pub flags: u32,
2540}
2541
2542impl EffectQuad {
2543 pub fn params_from(head: &[f32]) -> [f32; EFFECT_PARAM_SLOTS] {
2545 let mut params = [0.; EFFECT_PARAM_SLOTS];
2546 params[..head.len()].copy_from_slice(head);
2547 params
2548 }
2549
2550 pub fn needs_backdrop(&self) -> bool {
2553 self.flags & EFFECT_FLAG_NEEDS_BACKDROP != 0
2554 }
2555
2556 pub fn needs_content(&self) -> bool {
2558 self.flags & EFFECT_FLAG_NEEDS_CONTENT != 0
2559 }
2560
2561 pub fn has_history(&self) -> bool {
2563 self.flags & EFFECT_FLAG_HISTORY != 0
2564 }
2565
2566 pub fn history_size(&self) -> (u32, u32) {
2568 let side = |value: f32| (value.round().max(1.)) as u32;
2569 (
2570 side(self.bounds.size.width.0),
2571 side(self.bounds.size.height.0),
2572 )
2573 }
2574
2575 pub fn history_pass(mut self) -> Self {
2577 self.flags = (self.flags & !EFFECT_FLAG_NEEDS_BACKDROP) | EFFECT_FLAG_HISTORY_PASS;
2578 self
2579 }
2580
2581 pub fn effective_kernel_levels(&self) -> u32 {
2585 if !self.needs_backdrop() || self.backdrop_blur_radius.0 <= 0. {
2586 0
2587 } else {
2588 let radius_levels = (self.backdrop_blur_radius.0
2589 / BACKDROP_BLUR_RADIUS_PER_KERNEL_LEVEL)
2590 .ceil()
2591 .max(1.) as u32;
2592 radius_levels.min(MAX_BACKDROP_BLUR_KERNEL_LEVELS)
2593 }
2594 }
2595}
2596
2597impl From<EffectQuad> for Primitive {
2598 fn from(effect_quad: EffectQuad) -> Self {
2599 Primitive::EffectQuad(effect_quad, None)
2600 }
2601}
2602
2603const _: () = assert!(std::mem::size_of::<EffectQuad>() == 224);
2604const _: () = assert!(EFFECT_PARAM_SLOTS == 32);
2605
2606const _: () = assert!(std::mem::size_of::<Quad>() == 89 * 4);
2623const _: () = assert!(std::mem::size_of::<Background>() == 57 * 4);
2624const _: () = assert!(std::mem::size_of::<Shadow>() == 42 * 4);
2625const _: () = assert!(std::mem::size_of::<Underline>() == 26 * 4);
2626const _: () = assert!(std::mem::size_of::<PolychromeSprite>() == 38 * 4);
2627const _: () = assert!(std::mem::size_of::<TransformationMatrix>() == 6 * 4);
2628
2629static EFFECT_CLOCK_ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
2630
2631pub fn effect_clock_seconds() -> f32 {
2639 EFFECT_CLOCK_ORIGIN
2640 .get_or_init(std::time::Instant::now)
2641 .elapsed()
2642 .as_secs_f32()
2643}
2644
2645pub fn set_effect_clock_origin(origin: std::time::Instant) -> bool {
2648 EFFECT_CLOCK_ORIGIN.set(origin).is_ok()
2649}
2650
2651#[derive(Debug, Copy, Clone)]
2652#[repr(C)]
2653#[expect(missing_docs)]
2654pub struct Underline {
2655 pub order: DrawOrder,
2656 pub pad: u32, pub bounds: Bounds<ScaledPixels>,
2658 pub content_mask: ContentMask<ScaledPixels>,
2659 pub color: Hsla,
2660 pub thickness: ScaledPixels,
2661 pub wavy: PaddedBool32,
2662 pub transformation: TransformationMatrix,
2665}
2666
2667impl From<Underline> for Primitive {
2668 fn from(underline: Underline) -> Self {
2669 Primitive::Underline(underline)
2670 }
2671}
2672
2673#[derive(Debug, Copy, Clone)]
2674#[repr(C)]
2675#[expect(missing_docs)]
2676pub struct Shadow {
2677 pub order: DrawOrder,
2678 pub blur_radius: ScaledPixels,
2679 pub bounds: Bounds<ScaledPixels>,
2680 pub corner_radii: Corners<ScaledPixels>,
2681 pub content_mask: ContentMask<ScaledPixels>,
2682 pub color: Hsla,
2683 pub shape_bounds: Bounds<ScaledPixels>,
2684 pub shape_corner_radii: Corners<ScaledPixels>,
2685 pub inset: u32,
2688 pub pad: u32, pub transformation: TransformationMatrix,
2693 pub element_bounds: Bounds<ScaledPixels>,
2696}
2697
2698impl From<Shadow> for Primitive {
2699 fn from(shadow: Shadow) -> Self {
2700 Primitive::Shadow(shadow)
2701 }
2702}
2703
2704#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
2706#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2707#[repr(C)]
2708pub enum BorderStyle {
2709 #[default]
2711 Solid = 0,
2712 Dashed = 1,
2714}
2715
2716#[derive(Debug, Clone, Copy, PartialEq)]
2718#[repr(C)]
2719pub struct TransformationMatrix {
2720 pub rotation_scale: [[f32; 2]; 2],
2723 pub translation: [f32; 2],
2725}
2726
2727impl Eq for TransformationMatrix {}
2728
2729impl TransformationMatrix {
2730 pub fn unit() -> Self {
2732 Self {
2733 rotation_scale: [[1.0, 0.0], [0.0, 1.0]],
2734 translation: [0.0, 0.0],
2735 }
2736 }
2737
2738 pub fn translate(self, point: Point<ScaledPixels>) -> Self {
2740 self.compose(Self {
2741 rotation_scale: [[1.0, 0.0], [0.0, 1.0]],
2742 translation: [point.x.0, point.y.0],
2743 })
2744 }
2745
2746 pub fn rotate(self, angle: Radians) -> Self {
2748 self.compose(Self {
2749 rotation_scale: [
2750 [angle.0.cos(), -angle.0.sin()],
2751 [angle.0.sin(), angle.0.cos()],
2752 ],
2753 translation: [0.0, 0.0],
2754 })
2755 }
2756
2757 pub fn scale(self, size: Size<f32>) -> Self {
2759 self.compose(Self {
2760 rotation_scale: [[size.width, 0.0], [0.0, size.height]],
2761 translation: [0.0, 0.0],
2762 })
2763 }
2764
2765 #[inline]
2769 pub fn compose(self, other: TransformationMatrix) -> TransformationMatrix {
2770 if other == Self::unit() {
2771 return self;
2772 }
2773 TransformationMatrix {
2775 rotation_scale: [
2776 [
2777 self.rotation_scale[0][0] * other.rotation_scale[0][0]
2778 + self.rotation_scale[0][1] * other.rotation_scale[1][0],
2779 self.rotation_scale[0][0] * other.rotation_scale[0][1]
2780 + self.rotation_scale[0][1] * other.rotation_scale[1][1],
2781 ],
2782 [
2783 self.rotation_scale[1][0] * other.rotation_scale[0][0]
2784 + self.rotation_scale[1][1] * other.rotation_scale[1][0],
2785 self.rotation_scale[1][0] * other.rotation_scale[0][1]
2786 + self.rotation_scale[1][1] * other.rotation_scale[1][1],
2787 ],
2788 ],
2789 translation: [
2790 self.translation[0]
2791 + self.rotation_scale[0][0] * other.translation[0]
2792 + self.rotation_scale[0][1] * other.translation[1],
2793 self.translation[1]
2794 + self.rotation_scale[1][0] * other.translation[0]
2795 + self.rotation_scale[1][1] * other.translation[1],
2796 ],
2797 }
2798 }
2799
2800 pub(crate) fn transform_bounds(&self, bounds: Bounds<ScaledPixels>) -> Bounds<ScaledPixels> {
2802 if *self == Self::unit() {
2803 return bounds;
2804 }
2805 let [[xx, xy], [yx, yy]] = self.rotation_scale;
2806 let [translate_x, translate_y] = self.translation;
2807 let corners = [
2808 bounds.origin,
2809 bounds.top_right(),
2810 bounds.bottom_left(),
2811 bounds.bottom_right(),
2812 ]
2813 .map(|corner| {
2814 Point::new(
2815 ScaledPixels(xx * corner.x.0 + xy * corner.y.0 + translate_x),
2816 ScaledPixels(yx * corner.x.0 + yy * corner.y.0 + translate_y),
2817 )
2818 });
2819 let [first, rest @ ..] = corners;
2820 let top_left = rest.iter().fold(first, |min, corner| min.min(corner));
2821 let bottom_right = rest.iter().fold(first, |max, corner| max.max(corner));
2822 Bounds::from_corners(top_left, bottom_right)
2823 }
2824
2825 pub fn apply(&self, point: Point<Pixels>) -> Point<Pixels> {
2827 let input = [point.x.0, point.y.0];
2828 let mut output = self.translation;
2829 for (i, output_cell) in output.iter_mut().enumerate() {
2830 for (k, input_cell) in input.iter().enumerate() {
2831 *output_cell += self.rotation_scale[i][k] * *input_cell;
2832 }
2833 }
2834 Point::new(output[0].into(), output[1].into())
2835 }
2836
2837 pub fn inverse(&self) -> Option<TransformationMatrix> {
2846 let [[a, b], [c, d]] = self.rotation_scale;
2847 let det = a * d - b * c;
2848 if det == 0.0 || !det.is_finite() || !(1.0 / det).is_finite() {
2852 return None;
2853 }
2854 let inv = [[d / det, -b / det], [-c / det, a / det]];
2855 let [tx, ty] = self.translation;
2856 Some(TransformationMatrix {
2857 rotation_scale: inv,
2858 translation: [
2859 -(inv[0][0] * tx + inv[0][1] * ty),
2860 -(inv[1][0] * tx + inv[1][1] * ty),
2861 ],
2862 })
2863 }
2864
2865 #[inline]
2871 pub fn is_unit(&self) -> bool {
2872 *self == Self::unit()
2873 }
2874}
2875
2876pub(crate) fn transformed_bounds(
2882 bounds: Bounds<ScaledPixels>,
2883 matrix: TransformationMatrix,
2884) -> Bounds<ScaledPixels> {
2885 matrix.transform_bounds(bounds)
2886}
2887
2888pub(crate) fn axis_aligned_through(
2896 bounds: Bounds<ScaledPixels>,
2897 matrix: TransformationMatrix,
2898) -> Option<(Bounds<ScaledPixels>, f32)> {
2899 if matrix.is_unit() {
2900 return Some((bounds, 1.0));
2901 }
2902 let [[a, b], [c, d]] = matrix.rotation_scale;
2903 const EPS: f32 = 1e-6;
2904 if b.abs() > EPS || c.abs() > EPS || a.abs() <= EPS || d.abs() <= EPS {
2905 return None;
2906 }
2907 Some((transformed_bounds(bounds, matrix), a.abs().min(d.abs())))
2908}
2909
2910impl Default for TransformationMatrix {
2911 fn default() -> Self {
2912 Self::unit()
2913 }
2914}
2915
2916#[cfg(test)]
2917mod vn_axis_aligned_tests {
2918 use super::*;
2919 use crate::{Radians, point, size};
2920
2921 fn rect(x: f32, y: f32, w: f32, h: f32) -> Bounds<ScaledPixels> {
2922 Bounds {
2923 origin: point(ScaledPixels(x), ScaledPixels(y)),
2924 size: size(ScaledPixels(w), ScaledPixels(h)),
2925 }
2926 }
2927
2928 #[test]
2929 fn a_translate_moves_the_rect_and_a_rotation_has_no_rect() {
2930 let moved =
2931 TransformationMatrix::unit().translate(point(ScaledPixels(300.), ScaledPixels(120.)));
2932 assert_eq!(
2933 axis_aligned_through(rect(0., 0., 100., 50.), moved),
2934 Some((rect(300., 120., 100., 50.), 1.0))
2935 );
2936 let zoomed = TransformationMatrix::unit()
2938 .translate(point(ScaledPixels(50.), ScaledPixels(25.)))
2939 .scale(size(0.5, 0.5))
2940 .translate(point(ScaledPixels(-50.), ScaledPixels(-25.)));
2941 assert_eq!(
2942 axis_aligned_through(rect(0., 0., 100., 50.), zoomed),
2943 Some((rect(25., 12.5, 50., 25.), 0.5))
2944 );
2945 let turned = TransformationMatrix::unit().rotate(Radians(0.3));
2946 assert_eq!(axis_aligned_through(rect(0., 0., 100., 50.), turned), None);
2947 assert_eq!(
2948 axis_aligned_through(rect(1., 2., 3., 4.), TransformationMatrix::unit()),
2949 Some((rect(1., 2., 3., 4.), 1.0))
2950 );
2951 }
2952
2953 #[test]
2955 fn a_tiny_scale_is_still_invertible() {
2956 let tiny = TransformationMatrix { rotation_scale: [[0.0003, 0.0], [0.0, 0.0003]], translation: [5.0, 7.0] };
2957 let back = tiny.inverse().expect("an inverse");
2958 assert!((back.rotation_scale[0][0] - 1.0 / 0.0003).abs() < 1.0);
2959 let flat = TransformationMatrix { rotation_scale: [[1.0, 0.0], [0.0, 0.0]], translation: [0.0, 0.0] };
2960 assert!(flat.inverse().is_none());
2961 }
2962
2963 #[test]
2966 fn a_transform_moves_a_paths_curves() {
2967 let mut builder = crate::PathBuilder::fill();
2968 builder.move_to(point(Pixels(0.), Pixels(0.)));
2969 builder.line_to(point(Pixels(10.), Pixels(0.)));
2970 builder.curve_to(point(Pixels(10.), Pixels(20.)), point(Pixels(20.), Pixels(10.)));
2971 builder.close();
2972 let path = builder.build().unwrap();
2973 let moved =
2974 TransformationMatrix::unit().translate(point(ScaledPixels(300.), ScaledPixels(-120.)));
2975 let still = path.bin(2.0).bounds();
2976 assert_eq!(
2977 path.transformed(moved, 2.0).bin(2.0).bounds(),
2978 Bounds::new(still.origin + point(ScaledPixels(300.), ScaledPixels(-120.)), still.size)
2979 );
2980 let turned = TransformationMatrix::unit().rotate(Radians(std::f32::consts::FRAC_PI_2));
2983 let turned = path.transformed(turned, 2.0).bin(2.0).bounds();
2984 assert!((turned.size.width.0 - still.size.height.0).abs() < 1e-3);
2985 assert!((turned.size.height.0 - still.size.width.0).abs() < 1e-3);
2986 }
2987}
2988
2989#[derive(Copy, Clone, Debug)]
2990#[repr(C)]
2991#[expect(missing_docs)]
2992pub struct MonochromeSprite {
2993 pub order: DrawOrder,
2994 pub raw_coverage: PaddedBool32,
2996 pub tile: AtlasTile,
2997 pub bounds: Bounds<ScaledPixels>,
2998 pub content_mask: ContentMask<ScaledPixels>,
2999 pub color: Hsla,
3000 pub transformation: TransformationMatrix,
3001 pub animation: SpriteAnimationId,
3004 pub pad: u32,
3005}
3006
3007#[derive(Copy, Clone, Debug, PartialEq, Eq)]
3012#[repr(transparent)]
3013pub struct SpriteAnimationId(u32);
3014
3015impl SpriteAnimationId {
3016 pub const NONE: Self = Self(u32::MAX);
3018}
3019
3020impl Default for SpriteAnimationId {
3021 fn default() -> Self {
3022 Self::NONE
3023 }
3024}
3025
3026#[derive(Copy, Clone, Debug)]
3029pub(crate) struct SpriteAnimation {
3030 transformation: TimedTransformation,
3031 center: Point<Pixels>,
3032 scale_factor: f32,
3033 base_color: Hsla,
3034 sprite_index: usize,
3035 outer: TransformationMatrix,
3037}
3038
3039impl SpriteAnimation {
3040 pub(crate) fn new(
3041 transformation: TimedTransformation,
3042 center: Point<Pixels>,
3043 scale_factor: f32,
3044 ) -> Self {
3045 Self {
3046 transformation,
3047 center,
3048 scale_factor,
3049 base_color: Hsla::default(),
3050 sprite_index: usize::MAX,
3051 outer: TransformationMatrix::unit(),
3052 }
3053 }
3054
3055 pub(crate) fn under(self, outer: TransformationMatrix) -> Self {
3057 Self { outer, ..self }
3058 }
3059}
3060
3061impl From<MonochromeSprite> for Primitive {
3062 fn from(sprite: MonochromeSprite) -> Self {
3063 Primitive::MonochromeSprite(sprite)
3064 }
3065}
3066
3067#[derive(Copy, Clone, Debug)]
3068#[repr(C)]
3069#[expect(missing_docs)]
3070pub struct SubpixelSprite {
3071 pub order: DrawOrder,
3072 pub pad: u32, pub tile: AtlasTile,
3074 pub bounds: Bounds<ScaledPixels>,
3075 pub content_mask: ContentMask<ScaledPixels>,
3076 pub color: Hsla,
3077 pub transformation: TransformationMatrix,
3078}
3079
3080impl From<SubpixelSprite> for Primitive {
3081 fn from(sprite: SubpixelSprite) -> Self {
3082 Primitive::SubpixelSprite(sprite)
3083 }
3084}
3085
3086#[derive(Copy, Clone, Debug)]
3087#[repr(C)]
3088#[expect(missing_docs)]
3089pub struct PolychromeSprite {
3090 pub order: DrawOrder,
3091 pub pad: u32,
3092 pub tile: AtlasTile,
3093 pub grayscale: PaddedBool32,
3094 pub opacity: f32,
3095 pub bounds: Bounds<ScaledPixels>,
3096 pub content_mask: ContentMask<ScaledPixels>,
3097 pub corner_radii: Corners<ScaledPixels>,
3098 pub transformation: TransformationMatrix,
3108 pub tint: Hsla,
3112}
3113
3114impl From<PolychromeSprite> for Primitive {
3115 fn from(sprite: PolychromeSprite) -> Self {
3116 Primitive::PolychromeSprite(sprite)
3117 }
3118}
3119
3120#[derive(Clone, Debug)]
3121#[allow(missing_docs)]
3122pub struct PaintSurface {
3123 pub order: DrawOrder,
3124 pub bounds: Bounds<ScaledPixels>,
3125 pub content_mask: ContentMask<ScaledPixels>,
3126 #[cfg(any(target_os = "macos", target_os = "ios"))]
3127 pub image_buffer: objc2_core_foundation::CFRetained<objc2_core_video::CVPixelBuffer>,
3128}
3129
3130impl From<PaintSurface> for Primitive {
3131 fn from(surface: PaintSurface) -> Self {
3132 Primitive::Surface(surface)
3133 }
3134}
3135
3136#[derive(Clone, Copy, Debug, PartialEq)]
3137#[repr(C)]
3138#[expect(missing_docs)]
3139pub struct PathCurve {
3140 pub p0: Point<f32>,
3141 pub p1: Point<f32>,
3142 pub a: Point<f32>,
3143 pub b: Point<f32>,
3144 pub sign: f32,
3145 pub pad: u32, }
3147
3148#[derive(Clone, Copy, Debug)]
3149#[repr(C)]
3150#[expect(missing_docs)]
3151pub struct PathPaint {
3152 pub bounds: Bounds<ScaledPixels>,
3154 pub content_mask: ContentMask<ScaledPixels>,
3155 pub color: Background,
3156 pub even_odd: PaddedBool32,
3157 pub pad: u32, }
3159
3160#[derive(Clone, Copy, Debug, PartialEq)]
3161#[repr(C)]
3162#[expect(missing_docs)]
3163pub struct PathTile {
3164 pub paint: u32,
3165 pub curve_start: u32,
3166 pub curve_count: u32,
3167 pub backdrop: i32,
3168 pub top_left: Point<f32>,
3169 pub bottom_right: Point<f32>,
3170 pub reference: Point<f32>,
3171 pub curves_top_left: Point<f32>,
3172 pub curves_bottom_right: Point<f32>,
3173}
3174
3175#[derive(Clone, Debug)]
3176#[expect(missing_docs)]
3177pub struct PaintedPath {
3178 order: DrawOrder,
3179 bounds: Bounds<ScaledPixels>,
3180 tiles: Rc<PathTiles>,
3181 paint: PathPaint,
3182}
3183
3184#[expect(missing_docs)]
3185impl PaintedPath {
3186 pub fn new(
3188 path: Path,
3189 scale_factor: f32,
3190 content_mask: ContentMask<Pixels>,
3191 color: Background,
3192 ) -> Self {
3193 let content_mask = content_mask.scale(scale_factor);
3194 let mut tiles = path.bin(scale_factor);
3195 tiles.retain_visible(content_mask.bounds);
3196 let paint = PathPaint {
3197 bounds: tiles.bounds(),
3198 content_mask,
3199 color,
3200 even_odd: path.even_odd().into(),
3201 pad: 0,
3202 };
3203 Self {
3204 order: 0,
3205 bounds: tiles.painted_bounds(),
3206 tiles: Rc::new(tiles),
3207 paint,
3208 }
3209 }
3210
3211 pub fn tile_count(&self) -> usize {
3212 self.tiles.tiles().len()
3213 }
3214
3215 pub fn append_to(
3216 &self,
3217 paints: &mut Vec<PathPaint>,
3218 curves: &mut Vec<PathCurve>,
3219 tiles: &mut Vec<PathTile>,
3220 ) {
3221 let paint_index = paints.len() as u32;
3222 let curve_start = curves.len() as u32;
3223 paints.push(self.paint);
3224 curves.extend_from_slice(self.tiles.curves());
3225 tiles.extend(self.tiles.tiles().iter().map(|tile| PathTile {
3226 paint: paint_index,
3227 curve_start: curve_start + tile.curve_start,
3228 ..*tile
3229 }));
3230 }
3231}
3232
3233impl From<PaintedPath> for Primitive {
3234 fn from(path: PaintedPath) -> Self {
3235 Primitive::Path(path)
3236 }
3237}
3238
3239#[cfg(test)]
3240mod tests {
3241 use super::*;
3242 use crate::{point, size};
3243
3244 fn square(x: f32) -> Bounds<ScaledPixels> {
3245 Bounds {
3246 origin: point(ScaledPixels(x), ScaledPixels(0.)),
3247 size: size(ScaledPixels(10.), ScaledPixels(10.)),
3248 }
3249 }
3250
3251 fn quad(x: f32) -> Quad {
3252 Quad {
3253 bounds: square(x),
3254 content_mask: ContentMask::rect(square(x)),
3255 ..Default::default()
3256 }
3257 }
3258
3259 fn underline(x: f32) -> Underline {
3260 Underline {
3261 order: 0,
3262 pad: 0,
3263 bounds: square(x),
3264 content_mask: ContentMask::rect(square(x)),
3265 color: Hsla::default(),
3266 thickness: ScaledPixels(1.),
3267 wavy: false.into(),
3268 transformation: TransformationMatrix::unit(),
3269 }
3270 }
3271
3272 fn batch_labels(scene: &mut Scene) -> Vec<String> {
3273 scene.finish();
3274 scene.batches().map(|batch| batch.label()).collect()
3275 }
3276
3277 #[test]
3278 fn layers_are_drawn_in_paint_order() {
3279 let mut scene = Scene::default();
3281 scene.insert_primitive(quad(0.));
3282 scene.push_layer();
3283 scene.insert_primitive(underline(0.));
3284 scene.insert_primitive(underline(5.));
3285 scene.pop_layer();
3286 scene.insert_primitive(quad(5.));
3287 assert_eq!(
3288 batch_labels(&mut scene),
3289 ["quads (1)", "underlines (2)", "quads (1)"]
3290 );
3291
3292 let mut scene = Scene::default();
3294 scene.push_layer();
3295 scene.insert_primitive(underline(0.));
3296 scene.pop_layer();
3297 scene.push_layer();
3298 scene.insert_primitive(quad(5.));
3299 scene.pop_layer();
3300 assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]);
3301 }
3302
3303 #[test]
3304 fn nested_layers_are_drawn_above_their_parents() {
3305 let mut scene = Scene::default();
3308 scene.push_layer();
3309 scene.insert_primitive(underline(0.));
3310 scene.push_layer();
3311 scene.insert_primitive(quad(5.));
3312 scene.pop_layer();
3313 scene.insert_primitive(underline(5.));
3314 scene.pop_layer();
3315 assert_eq!(batch_labels(&mut scene), ["underlines (2)", "quads (1)"]);
3316
3317 let mut scene = Scene::default();
3319 scene.push_layer();
3320 scene.insert_primitive(quad(0.));
3321 scene.push_layer();
3322 scene.insert_primitive(quad(5.));
3323 scene.pop_layer();
3324 scene.insert_primitive(quad(8.));
3325 scene.pop_layer();
3326 assert_eq!(batch_labels(&mut scene), ["quads (3)"]);
3327 assert_eq!(
3328 scene
3329 .quads
3330 .iter()
3331 .map(|quad| quad.bounds)
3332 .collect::<Vec<_>>(),
3333 [square(0.), square(8.), square(5.)]
3334 );
3335
3336 let mut scene = Scene::default();
3338 scene.push_layer();
3339 scene.push_layer();
3340 scene.insert_primitive(underline(0.));
3341 scene.pop_layer();
3342 scene.pop_layer();
3343 scene.push_layer();
3344 scene.insert_primitive(quad(5.));
3345 scene.pop_layer();
3346 assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]);
3347 }
3348}
3349
3350
3351#[cfg(test)]
3352mod vn_color_group_tests {
3353 use super::*;
3354 use crate::{VnColorMatrix, VnClipGeometry, VnFillRule, size};
3355 use std::sync::Arc;
3356
3357 fn rectangle() -> Bounds<ScaledPixels> {
3358 Bounds { origin: point(ScaledPixels(0.), ScaledPixels(0.)), size: size(ScaledPixels(100.), ScaledPixels(100.)) }
3359 }
3360
3361 fn filter(id: u64) -> VnIsolation {
3362 VnIsolation {
3363 text_paint: None,
3364 geometry: Arc::new(VnClipGeometry {
3365 fill_rule: VnFillRule::NonZero,
3366 segments: vec![[0., 0., 100., 0.], [100., 0., 100., 100.], [100., 100., 0., 100.], [0., 100., 0., 0.]],
3367 bounds: rectangle(),
3368 }),
3369 color_matrix: Some(VnColorMatrix { group_id: id, values: VnColorMatrix::IDENTITY, linear_rgb: true }),
3370 content_mask: ContentMask { bounds: rectangle(), ..Default::default() },
3371 capture: None,
3372 }
3373 }
3374
3375 fn paint(scene: &mut Scene) {
3376 scene.insert_primitive(Quad { bounds: rectangle(), content_mask: ContentMask { bounds: rectangle(), ..Default::default() }, ..Default::default() });
3377 }
3378
3379 fn text_mask(id: u64) -> VnIsolation {
3380 let mut isolation = filter(id);
3381 isolation.color_matrix = None;
3382 isolation.text_paint = Some(Arc::new(crate::VnTextPaint {
3383 fill: crate::VnTextFill { group_id: id, backgrounds: vec![crate::red().into(), crate::blue().into()] },
3384 bounds: [10., 20., 40., 30.],
3385 inverse: [0., 1., -1., 0., 50., 60.], scale_factor: 1.5,
3386 geometry: isolation.geometry.clone(), content_mask: isolation.content_mask,
3387 }));
3388 isolation
3389 }
3390
3391 #[test]
3392 fn text_glyphs_and_deferred_replay_share_one_gradient_stack_and_source() {
3393 let mut scene = Scene::default();
3394 for _ in 0..3 {
3395 scene.vn_push_isolation(text_mask(7));
3396 paint(&mut scene);
3397 scene.vn_pop_isolation();
3398 }
3399 assert_eq!(scene.vn_layers.len(), 1, "a text scope composites once, not per glyph");
3400 assert_eq!(scene.vn_groups[0].quads.len(), 3);
3401 assert_eq!(scene.vn_text_backgrounds.len(), 2, "metadata belongs to a text scope, not each glyph");
3402 assert_eq!(scene.vn_layers[0].pad, [0, 0, 2]);
3403 let brush = scene.vn_text_backgrounds[0];
3404 assert_eq!(brush.bounds.origin.x.0, 10.);
3405 assert_eq!(brush.inverse.apply(point(px(2.), px(3.))), point(px(53.), px(58.)));
3406 assert_eq!(brush.scale_factor, 1.5);
3407 let operations = 0..scene.len();
3408 scene.finish();
3409 let mut replay = Scene::default();
3410 replay.replay(operations, &scene);
3411 assert_eq!(replay.vn_layers.len(), 1);
3412 assert_eq!(replay.vn_text_backgrounds.len(), 2, "cached operations rebuild valid metadata indices");
3413 assert_eq!(replay.vn_groups[0].quads.len(), 3);
3414 replay.clear();
3415 assert!(replay.vn_text_backgrounds.is_empty());
3416 replay.vn_push_isolation(text_mask(7));
3417 paint(&mut replay);
3418 replay.vn_pop_isolation();
3419 assert_eq!(replay.vn_text_backgrounds.len(), 2);
3420 assert_eq!(replay.vn_groups[0].quads.len(), 1, "new frames cannot retain old mask coverage");
3421 }
3422
3423 #[test]
3424 fn text_and_color_filter_group_identities_do_not_alias() {
3425 let mut scene = Scene::default();
3426 scene.vn_push_isolation(filter(7));
3427 scene.vn_push_isolation(text_mask(7));
3428 paint(&mut scene);
3429 scene.vn_pop_isolation();
3430 scene.vn_pop_isolation();
3431 assert_eq!(scene.vn_groups.len(), 2);
3432 assert_eq!(scene.vn_groups[1].vn_layers.len(), 1);
3433 assert_eq!(scene.vn_layers[0].pad[0], 1);
3434 assert_eq!(scene.vn_groups[1].vn_layers[0].pad[2], 2);
3435 assert_eq!(std::mem::size_of::<VnLayer>(), 224, "keep the HLSL layer ABI");
3436 assert_eq!(std::mem::size_of::<VnTextBackground>(), 276, "match the HLSL structured buffer stride");
3437 assert_eq!(std::mem::offset_of!(VnTextBackground, bounds), 228);
3438 assert_eq!(std::mem::offset_of!(VnTextBackground, inverse), 244);
3439 assert_eq!(std::mem::offset_of!(VnTextBackground, scale_factor), 268);
3440 }
3441
3442 #[test]
3443 fn text_sources_partition_child_clip_and_filter_contexts_and_rejoin_deferred_siblings() {
3444 for matrix in [false, true] {
3445 let mut first = filter(11);
3446 let mut second = filter(12);
3447 if !matrix { first.color_matrix = None; second.color_matrix = None; }
3448 let mut scene = Scene::default();
3449 for parent in [first.clone(), second, first] {
3450 scene.vn_push_isolation(parent);
3451 scene.vn_push_isolation(text_mask(7));
3452 paint(&mut scene);
3453 scene.vn_pop_isolation();
3454 scene.vn_pop_isolation();
3455 }
3456 let masks: Vec<_> = scene.vn_groups.iter().filter(|group| !group.quads.is_empty()).collect();
3459 assert_eq!(masks.len(), 2, "text cannot be captured by the first child's clip or filter");
3460 assert_eq!(masks[0].quads.len(), 2, "deferred text in the same parent reuses its source");
3461 assert_eq!(masks[1].quads.len(), 1);
3462 assert_eq!(scene.vn_text_backgrounds.len(), 4, "two brushes per distinct isolation context");
3463 let operations = 0..scene.len();
3464 scene.finish();
3465 let mut replay = Scene::default();
3466 replay.replay(operations, &scene);
3467 assert_eq!(replay.vn_text_backgrounds.len(), 4, "paint-cache replay interns equivalent parent contexts");
3468 let masks: Vec<_> = replay.vn_groups.iter().filter(|group| !group.quads.is_empty()).collect();
3469 assert_eq!(masks.len(), 2);
3470 assert_eq!(masks[0].quads.len(), 2);
3471 }
3472 }
3473
3474 #[test]
3475 fn deferred_source_is_composited_with_its_background_before_one_color_matrix() {
3476 let mut scene = Scene::default();
3477 scene.vn_push_isolation(filter(1));
3478 paint(&mut scene);
3479 scene.vn_pop_isolation();
3480 scene.vn_push_isolation(filter(1));
3481 paint(&mut scene);
3482 scene.vn_pop_isolation();
3483 assert_eq!(scene.vn_layers.len(), 1, "one composite, not separately filtered translucent pieces");
3484 assert_eq!(scene.vn_groups.len(), 1);
3485 assert_eq!(scene.vn_groups[0].quads.len(), 2);
3486 assert!(scene.vn_groups[0].quads[1].order > scene.vn_groups[0].quads[0].order, "deferred source blends over its earlier background");
3487 let operations = 0..scene.len();
3488 scene.finish();
3489 assert_eq!(scene.vn_group_count(), 2);
3490 let mut replay = Scene::default();
3491 replay.replay(operations, &scene);
3492 assert_eq!(replay.vn_layers.len(), 1, "cached operations rebuild the same keyed source");
3493 assert_eq!(replay.vn_groups[0].quads.len(), 2);
3494 replay.clear();
3495 replay.vn_push_isolation(filter(1));
3496 paint(&mut replay);
3497 replay.vn_pop_isolation();
3498 assert_eq!(replay.vn_groups[0].quads.len(), 1, "a new frame has no old source pixels");
3499 }
3500
3501 #[test]
3502 fn an_initially_empty_filter_keeps_its_composite_for_deferred_descendants() {
3503 let mut scene = Scene::default();
3504 scene.vn_push_isolation(filter(1));
3505 scene.vn_pop_isolation();
3506 scene.vn_push_isolation(filter(1));
3507 paint(&mut scene);
3508 scene.vn_pop_isolation();
3509 assert_eq!(scene.vn_layers.len(), 1);
3510 assert_eq!(scene.vn_groups.len(), 1);
3511 assert_eq!(scene.vn_groups[0].quads.len(), 1);
3512 }
3513
3514 #[test]
3515 fn nested_filtered_sources_reopen_without_duplicate_inner_composites() {
3516 let mut scene = Scene::default();
3517 scene.vn_push_isolation(filter(1));
3518 paint(&mut scene);
3519 scene.vn_push_isolation(filter(2));
3520 paint(&mut scene);
3521 scene.vn_pop_isolation();
3522 scene.vn_pop_isolation();
3523 scene.vn_push_isolation(filter(1));
3524 scene.vn_push_isolation(filter(2));
3525 paint(&mut scene);
3526 scene.vn_pop_isolation();
3527 scene.vn_pop_isolation();
3528 assert_eq!(scene.vn_layers.len(), 1, "only the outer composite belongs to the page");
3529 assert_eq!(scene.vn_groups.len(), 2);
3530 assert_eq!(scene.vn_groups[0].quads.len(), 2, "both inner source pieces share one filter");
3531 assert_eq!(scene.vn_groups[1].vn_layers.len(), 1, "the inner filter composites once into the outer source");
3532 scene.finish();
3533 assert_eq!(scene.vn_group_count(), 3);
3534 assert_eq!(scene.vn_layers.len(), 2);
3535 }
3536
3537 #[test]
3538 fn an_in_place_snapshot_samples_through_the_captured_transform() {
3539 let mut capture = filter(0);
3540 capture.color_matrix = None;
3541 capture.capture = Some(VnCaptureInfo {
3542 id: 3,
3543 border_box: rectangle(),
3544 transform: crate::TransformationMatrix { rotation_scale: [[2., 0.], [0., 2.]], translation: [100., 5.] },
3545 });
3546 let mut scene = Scene::default();
3547 scene.vn_push_isolation(capture);
3548 paint(&mut scene);
3549 scene.vn_pop_isolation();
3550 let viewport = Bounds { origin: point(ScaledPixels(0.), ScaledPixels(0.)), size: size(ScaledPixels(400.), ScaledPixels(400.)) };
3551 scene.vn_insert_snapshot(VnSnapshotPaint {
3552 id: 3,
3553 to_unit: [0.; 6],
3554 bounds: viewport,
3555 content_mask: ContentMask { bounds: viewport, ..Default::default() },
3556 opacity: 1.,
3557 plus_lighter: false,
3558 in_place: true,
3559 });
3560 scene.finish();
3561 scene.vn_resolve_snapshots(|_| None);
3562 let layer = scene.vn_layers.iter().find(|l| l.snapshot_id() == Some(3)).copied().unwrap();
3563 assert_eq!(layer.flags, vn_layer_flags::SNAPSHOT);
3564 assert_eq!(layer.source_transform, [0.5, 0., -50., 0., 0., 0.5, -2.5, 0.]);
3565 assert_eq!(layer.bounds.origin, point(ScaledPixels(100.), ScaledPixels(5.)));
3566 assert_eq!(layer.bounds.size, size(ScaledPixels(200.), ScaledPixels(200.)));
3567 }
3568}