1#![cfg_attr(windows, allow(dead_code))]
3
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6
7use crate::{
8 AtlasTextureId, AtlasTile, Background, Bounds, ContentMask, Corners, Edges, HitboxId, Hsla,
9 NativeViewId, Path, PathTiles, Pixels, Point, Radians, ScaledPixels, Size, TimedTransformation,
10 bounds_tree::BoundsTree,
11};
12use smallvec::SmallVec;
13use std::{
14 collections::VecDeque, fmt::Debug, iter::Peekable, ops::Range, rc::Rc, slice, time::Duration,
15};
16
17#[expect(missing_docs)]
18pub type DrawOrder = u32;
19
20#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
25#[repr(transparent)]
26pub struct PaddedBool32(u32);
27
28impl From<bool> for PaddedBool32 {
29 fn from(value: bool) -> Self {
30 PaddedBool32(value as u32)
31 }
32}
33
34impl PaddedBool32 {
35 pub fn as_bool(self) -> bool {
37 self.0 != 0
38 }
39}
40
41struct Layer {
42 primitives: SmallVec<[Range<usize>; 1]>,
43 bounds: Bounds<ScaledPixels>,
44 max_kind: PrimitiveKind,
45 max_shared_kind: PrimitiveKind,
46 has_native_view: bool,
49}
50
51#[derive(Default)]
52#[expect(missing_docs)]
53pub struct Scene {
54 pub(crate) paint_operations: Vec<PaintOperation>,
55 primitive_bounds: BoundsTree<ScaledPixels>,
56 layer_stack: Vec<usize>,
57 layers: VecDeque<Layer>,
58 pub shadows: Vec<Shadow>,
59 pub quads: Vec<Quad>,
60 pub paths: Vec<PaintedPath>,
61 pub underlines: Vec<Underline>,
62 pub monochrome_sprites: Vec<MonochromeSprite>,
63 pub subpixel_sprites: Vec<SubpixelSprite>,
64 pub polychrome_sprites: Vec<PolychromeSprite>,
65 pub surfaces: Vec<PaintSurface>,
66 pub native_views: Vec<PaintNativeView>,
67 animations: Vec<SpriteAnimation>,
68}
69
70#[expect(missing_docs)]
71impl Scene {
72 pub fn clear(&mut self) {
73 self.paint_operations.clear();
74 self.primitive_bounds.clear();
75 self.layer_stack.clear();
76 self.layers.clear();
77 self.paths.clear();
78 self.shadows.clear();
79 self.quads.clear();
80 self.underlines.clear();
81 self.monochrome_sprites.clear();
82 self.subpixel_sprites.clear();
83 self.polychrome_sprites.clear();
84 self.surfaces.clear();
85 self.native_views.clear();
86 self.animations.clear();
87 }
88
89 pub(crate) fn insert_animated_sprite(
92 &mut self,
93 mut sprite: MonochromeSprite,
94 mut animation: SpriteAnimation,
95 ) {
96 sprite.animation = SpriteAnimationId(self.animations.len() as u32);
97 animation.base_color = sprite.color;
98 if self.try_insert_primitive(sprite.into()) {
99 self.animations.push(animation);
100 }
101 }
102
103 pub(crate) fn animation_frame_interval(&self) -> Option<Duration> {
107 self.animations
108 .iter()
109 .map(|animation| {
110 animation
111 .transformation
112 .min_frame_interval()
113 .unwrap_or_default()
114 })
115 .min()
116 }
117
118 pub(crate) fn advance_animations(&mut self, elapsed: Duration) {
121 for animation in &self.animations {
122 let Some(sprite) = self.monochrome_sprites.get_mut(animation.sprite_index) else {
123 continue;
124 };
125 let pose = animation.transformation.at(elapsed);
126 sprite.transformation = pose.into_matrix(animation.center, animation.scale_factor);
127 sprite.color = animation.base_color.opacity(pose.alpha_factor());
128 }
129 }
130
131 pub fn len(&self) -> usize {
132 self.paint_operations.len()
133 }
134
135 pub fn push_layer(&mut self) {
136 self.layer_stack.push(self.layers.len());
137 self.layers.push_back(Layer {
138 primitives: SmallVec::new(),
139 bounds: Bounds::default(),
140 max_kind: PrimitiveKind::Shadow,
141 max_shared_kind: PrimitiveKind::NativeView,
142 has_native_view: false,
143 });
144 self.paint_operations.push(PaintOperation::StartLayer);
145 }
146
147 pub fn pop_layer(&mut self) {
148 self.layer_stack.pop();
149 if self.layer_stack.is_empty() {
150 while let Some(layer) = self.layers.pop_front() {
151 self.insert_layer(layer);
152 }
153 }
154 self.paint_operations.push(PaintOperation::EndLayer);
155 }
156
157 fn insert_layer(&mut self, layer: Layer) {
158 if layer.primitives.is_empty() {
159 return;
160 }
161 if layer.has_native_view {
162 self.insert_layer_around_native_views(layer);
163 return;
164 }
165 let order =
166 self.primitive_bounds
167 .insert(layer.bounds, layer.max_kind, layer.max_shared_kind);
168 for index in layer.primitives.into_iter().flatten() {
169 if let PaintOperation::Primitive(primitive) = &self.paint_operations[index] {
170 let primitive = primitive.clone();
171 self.push_primitive(primitive, order);
172 }
173 }
174 }
175
176 fn insert_layer_around_native_views(&mut self, layer: Layer) {
183 let mut part = Vec::new();
184 for index in layer.primitives.into_iter().flatten() {
185 let PaintOperation::Primitive(primitive) = &self.paint_operations[index] else {
186 continue;
187 };
188 let primitive = primitive.clone();
189 if primitive.kind() == PrimitiveKind::NativeView {
190 self.insert_layer_part(std::mem::take(&mut part));
191 self.insert_layer_part(vec![primitive]);
192 } else {
193 part.push(primitive);
194 }
195 }
196 self.insert_layer_part(part);
197 }
198
199 fn insert_layer_part(&mut self, primitives: Vec<Primitive>) {
200 let Some(first) = primitives.first() else {
201 return;
202 };
203 let mut bounds = first.clipped_bounds();
204 let mut max_kind = PrimitiveKind::Shadow;
205 let mut max_shared_kind = PrimitiveKind::NativeView;
206 for primitive in &primitives {
207 let kind = primitive.kind();
208 bounds = bounds.join(&primitive.clipped_bounds());
209 max_kind = max_kind.max(kind);
210 max_shared_kind = max_shared_kind.min(kind.max_shared_kind());
211 }
212 let order = self
213 .primitive_bounds
214 .insert(bounds, max_kind, max_shared_kind);
215 for primitive in primitives {
216 self.push_primitive(primitive, order);
217 }
218 }
219
220 pub fn insert_primitive(&mut self, primitive: impl Into<Primitive>) {
221 self.try_insert_primitive(primitive.into());
222 }
223
224 fn try_insert_primitive(&mut self, primitive: Primitive) -> bool {
226 let clipped_bounds = primitive.clipped_bounds();
227 if clipped_bounds.is_empty() {
228 return false;
229 }
230
231 let kind = primitive.kind();
232 if let Some(&layer) = self.layer_stack.last()
233 && let Some(layer) = self.layers.get_mut(layer)
234 {
235 layer.bounds = layer.bounds.join(&clipped_bounds);
236 layer.max_kind = layer.max_kind.max(kind);
237 layer.max_shared_kind = layer.max_shared_kind.min(kind.max_shared_kind());
238 layer.has_native_view |= kind == PrimitiveKind::NativeView;
239 let index = self.paint_operations.len();
240 match layer.primitives.last_mut() {
241 Some(range) if range.end == index => range.end += 1,
242 _ => layer.primitives.push(index..index + 1),
243 }
244 } else {
245 let order = self
246 .primitive_bounds
247 .insert(clipped_bounds, kind, kind.max_shared_kind());
248 self.push_primitive(primitive.clone(), order);
249 }
250 self.paint_operations
251 .push(PaintOperation::Primitive(primitive));
252 true
253 }
254
255 fn push_primitive(&mut self, primitive: Primitive, order: DrawOrder) {
256 match primitive {
257 Primitive::Shadow(shadow) => self.shadows.push(Shadow { order, ..shadow }),
258 Primitive::Quad(quad) => self.quads.push(Quad { order, ..quad }),
259 Primitive::Path(mut path) => {
260 path.order = order;
261 self.paths.push(path);
262 }
263 Primitive::Underline(underline) => {
264 self.underlines.push(Underline { order, ..underline })
265 }
266 Primitive::MonochromeSprite(sprite) => self
267 .monochrome_sprites
268 .push(MonochromeSprite { order, ..sprite }),
269 Primitive::SubpixelSprite(sprite) => self
270 .subpixel_sprites
271 .push(SubpixelSprite { order, ..sprite }),
272 Primitive::PolychromeSprite(sprite) => self
273 .polychrome_sprites
274 .push(PolychromeSprite { order, ..sprite }),
275 Primitive::Surface(mut surface) => {
276 surface.order = order;
277 self.surfaces.push(surface);
278 }
279 Primitive::NativeView(native_view) => self.native_views.push(PaintNativeView {
280 order,
281 ..native_view
282 }),
283 }
284 }
285
286 pub fn replay(&mut self, range: Range<usize>, prev_scene: &Scene) {
287 for operation in &prev_scene.paint_operations[range] {
288 match operation {
289 PaintOperation::Primitive(primitive) => {
290 if let Primitive::MonochromeSprite(sprite) = primitive
292 && let Some(animation) =
293 prev_scene.animations.get(sprite.animation.0 as usize)
294 {
295 self.insert_animated_sprite(*sprite, *animation);
296 } else {
297 self.insert_primitive(primitive.clone());
298 }
299 }
300 PaintOperation::StartLayer => self.push_layer(),
301 PaintOperation::EndLayer => self.pop_layer(),
302 }
303 }
304 }
305
306 pub fn finish(&mut self) {
307 debug_assert!(self.layer_stack.is_empty(), "unbalanced scene layers");
308 let keys = &mut Vec::new();
309 sort_in_place(&mut self.shadows, keys, |shadow| (shadow.order, 0));
310 sort_in_place(&mut self.quads, keys, |quad| (quad.order, 0));
311 self.paths.sort_by_key(|path| path.order);
312 sort_in_place(&mut self.underlines, keys, |underline| (underline.order, 0));
313 sort_in_place(&mut self.monochrome_sprites, keys, |sprite| {
314 (sprite.order, sprite.tile.texture_id.index)
315 });
316 sort_in_place(&mut self.subpixel_sprites, keys, |sprite| {
317 (sprite.order, sprite.tile.texture_id.index)
318 });
319 sort_in_place(&mut self.polychrome_sprites, keys, |sprite| {
320 (sprite.order, sprite.tile.texture_id.index)
321 });
322 self.surfaces.sort_by_key(|surface| surface.order);
323 self.native_views
324 .sort_by_key(|native_view| native_view.order);
325 self.keep_first_painted_native_views();
326
327 if !self.animations.is_empty() {
329 for (index, sprite) in self.monochrome_sprites.iter().enumerate() {
330 if let Some(animation) = self.animations.get_mut(sprite.animation.0 as usize) {
331 animation.sprite_index = index;
332 }
333 }
334 }
335 }
336
337 fn keep_first_painted_native_views(&mut self) {
344 let native_views = &self.native_views;
345 let is_repeated = native_views.iter().enumerate().any(|(index, native_view)| {
346 native_views[..index]
347 .iter()
348 .any(|earlier| earlier.id == native_view.id)
349 });
350 if !is_repeated {
351 return;
352 }
353 let mut first_painted: Vec<(NativeViewId, HitboxId)> = Vec::new();
354 for operation in &self.paint_operations {
355 if let PaintOperation::Primitive(Primitive::NativeView(native_view)) = operation
356 && !first_painted.iter().any(|(id, _)| *id == native_view.id)
357 {
358 first_painted.push((native_view.id, native_view.hitbox_id));
359 }
360 }
361 self.native_views
362 .retain(|native_view| first_painted.contains(&(native_view.id, native_view.hitbox_id)));
363 }
364
365 #[cfg_attr(
366 all(
367 any(target_os = "linux", target_os = "freebsd"),
368 not(any(feature = "x11", feature = "wayland"))
369 ),
370 allow(dead_code)
371 )]
372 pub fn batches(&self) -> impl Iterator<Item = PrimitiveBatch> + '_ {
373 BatchIterator {
374 shadows_start: 0,
375 shadows_iter: self.shadows.iter().peekable(),
376 quads_start: 0,
377 quads_iter: self.quads.iter().peekable(),
378 paths_start: 0,
379 paths_iter: self.paths.iter().peekable(),
380 underlines_start: 0,
381 underlines_iter: self.underlines.iter().peekable(),
382 monochrome_sprites_start: 0,
383 monochrome_sprites_iter: self.monochrome_sprites.iter().peekable(),
384 subpixel_sprites_start: 0,
385 subpixel_sprites_iter: self.subpixel_sprites.iter().peekable(),
386 polychrome_sprites_start: 0,
387 polychrome_sprites_iter: self.polychrome_sprites.iter().peekable(),
388 surfaces_start: 0,
389 surfaces_iter: self.surfaces.iter().peekable(),
390 native_views_start: 0,
391 native_views_iter: self.native_views.iter().peekable(),
392 }
393 }
394}
395
396fn sort_in_place<T: Copy>(
401 primitives: &mut [T],
402 keys: &mut Vec<(u64, u32)>,
403 key: impl Fn(&T) -> (u32, u32),
404) {
405 if primitives.is_sorted_by_key(&key) {
406 return;
407 }
408 keys.clear();
409 keys.extend(primitives.iter().enumerate().map(|(index, primitive)| {
410 let (major, minor) = key(primitive);
411 ((major as u64) << 32 | minor as u64, index as u32)
412 }));
413 keys.sort_unstable();
414
415 for start in 0..primitives.len() {
418 if keys[start].1 as usize == start {
419 continue;
420 }
421 let displaced = primitives[start];
422 let mut target = start;
423 loop {
424 let source = keys[target].1 as usize;
425 keys[target].1 = target as u32;
426 if source == start {
427 primitives[target] = displaced;
428 break;
429 }
430 primitives[target] = primitives[source];
431 target = source;
432 }
433 }
434}
435
436pub fn quad_depth_scale(quad_count: usize) -> f32 {
438 let denominator = (quad_count.min((1 << 24) - 1) + 1).next_power_of_two();
439 1.0 / denominator as f32
440}
441
442pub fn quad_depth(quad_id: u32, scale: f32) -> f32 {
444 ((quad_id + 1) as f32 * scale).min(1.0)
445}
446
447#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Default)]
448#[cfg_attr(
449 all(
450 any(target_os = "linux", target_os = "freebsd"),
451 not(any(feature = "x11", feature = "wayland"))
452 ),
453 allow(dead_code)
454)]
455pub(crate) enum PrimitiveKind {
456 Shadow,
457 #[default]
458 Quad,
459 Path,
460 Underline,
461 MonochromeSprite,
462 SubpixelSprite,
463 PolychromeSprite,
464 Surface,
465 NativeView,
466}
467
468impl PrimitiveKind {
469 fn max_shared_kind(self) -> Self {
476 match self {
477 Self::MonochromeSprite => Self::Underline,
478 Self::SubpixelSprite => Self::MonochromeSprite,
479 Self::PolychromeSprite => Self::SubpixelSprite,
480 kind => kind,
481 }
482 }
483}
484
485pub(crate) enum PaintOperation {
486 Primitive(Primitive),
487 StartLayer,
488 EndLayer,
489}
490
491#[derive(Clone)]
492#[expect(missing_docs)]
493pub enum Primitive {
494 Shadow(Shadow),
495 Quad(Quad),
496 Path(PaintedPath),
497 Underline(Underline),
498 MonochromeSprite(MonochromeSprite),
499 SubpixelSprite(SubpixelSprite),
500 PolychromeSprite(PolychromeSprite),
501 Surface(PaintSurface),
502 NativeView(PaintNativeView),
503}
504
505#[expect(missing_docs)]
506impl Primitive {
507 pub(crate) fn kind(&self) -> PrimitiveKind {
508 match self {
509 Primitive::Shadow(_) => PrimitiveKind::Shadow,
510 Primitive::Quad(_) => PrimitiveKind::Quad,
511 Primitive::Path(_) => PrimitiveKind::Path,
512 Primitive::Underline(_) => PrimitiveKind::Underline,
513 Primitive::MonochromeSprite(_) => PrimitiveKind::MonochromeSprite,
514 Primitive::SubpixelSprite(_) => PrimitiveKind::SubpixelSprite,
515 Primitive::PolychromeSprite(_) => PrimitiveKind::PolychromeSprite,
516 Primitive::Surface(_) => PrimitiveKind::Surface,
517 Primitive::NativeView(_) => PrimitiveKind::NativeView,
518 }
519 }
520
521 pub fn bounds(&self) -> &Bounds<ScaledPixels> {
522 match self {
523 Primitive::Shadow(shadow) => &shadow.bounds,
524 Primitive::Quad(quad) => &quad.bounds,
525 Primitive::Path(path) => &path.bounds,
526 Primitive::Underline(underline) => &underline.bounds,
527 Primitive::MonochromeSprite(sprite) => &sprite.bounds,
528 Primitive::SubpixelSprite(sprite) => &sprite.bounds,
529 Primitive::PolychromeSprite(sprite) => &sprite.bounds,
530 Primitive::Surface(surface) => &surface.bounds,
531 Primitive::NativeView(native_view) => &native_view.bounds,
532 }
533 }
534
535 fn transformation(&self) -> TransformationMatrix {
536 match self {
537 Primitive::MonochromeSprite(sprite) => sprite.transformation,
538 Primitive::SubpixelSprite(sprite) => sprite.transformation,
539 _ => TransformationMatrix::unit(),
540 }
541 }
542
543 fn clipped_bounds(&self) -> Bounds<ScaledPixels> {
544 self.transformation()
545 .transform_bounds(*self.bounds())
546 .intersect(&self.content_mask().bounds)
547 }
548
549 pub fn content_mask(&self) -> &ContentMask<ScaledPixels> {
550 match self {
551 Primitive::Shadow(shadow) => &shadow.content_mask,
552 Primitive::Quad(quad) => &quad.content_mask,
553 Primitive::Path(path) => &path.paint.content_mask,
554 Primitive::Underline(underline) => &underline.content_mask,
555 Primitive::MonochromeSprite(sprite) => &sprite.content_mask,
556 Primitive::SubpixelSprite(sprite) => &sprite.content_mask,
557 Primitive::PolychromeSprite(sprite) => &sprite.content_mask,
558 Primitive::Surface(surface) => &surface.content_mask,
559 Primitive::NativeView(native_view) => &native_view.content_mask,
560 }
561 }
562}
563
564#[cfg_attr(
565 all(
566 any(target_os = "linux", target_os = "freebsd"),
567 not(any(feature = "x11", feature = "wayland"))
568 ),
569 allow(dead_code)
570)]
571struct BatchIterator<'a> {
572 shadows_start: usize,
573 shadows_iter: Peekable<slice::Iter<'a, Shadow>>,
574 quads_start: usize,
575 quads_iter: Peekable<slice::Iter<'a, Quad>>,
576 paths_start: usize,
577 paths_iter: Peekable<slice::Iter<'a, PaintedPath>>,
578 underlines_start: usize,
579 underlines_iter: Peekable<slice::Iter<'a, Underline>>,
580 monochrome_sprites_start: usize,
581 monochrome_sprites_iter: Peekable<slice::Iter<'a, MonochromeSprite>>,
582 subpixel_sprites_start: usize,
583 subpixel_sprites_iter: Peekable<slice::Iter<'a, SubpixelSprite>>,
584 polychrome_sprites_start: usize,
585 polychrome_sprites_iter: Peekable<slice::Iter<'a, PolychromeSprite>>,
586 surfaces_start: usize,
587 surfaces_iter: Peekable<slice::Iter<'a, PaintSurface>>,
588 native_views_start: usize,
589 native_views_iter: Peekable<slice::Iter<'a, PaintNativeView>>,
590}
591
592impl<'a> Iterator for BatchIterator<'a> {
593 type Item = PrimitiveBatch;
594
595 fn next(&mut self) -> Option<Self::Item> {
596 let mut orders_and_kinds = [
597 (
598 self.shadows_iter.peek().map(|s| s.order),
599 PrimitiveKind::Shadow,
600 ),
601 (self.quads_iter.peek().map(|q| q.order), PrimitiveKind::Quad),
602 (
603 self.paths_iter.peek().map(|path| path.order),
604 PrimitiveKind::Path,
605 ),
606 (
607 self.underlines_iter.peek().map(|u| u.order),
608 PrimitiveKind::Underline,
609 ),
610 (
611 self.monochrome_sprites_iter.peek().map(|s| s.order),
612 PrimitiveKind::MonochromeSprite,
613 ),
614 (
615 self.subpixel_sprites_iter.peek().map(|s| s.order),
616 PrimitiveKind::SubpixelSprite,
617 ),
618 (
619 self.polychrome_sprites_iter.peek().map(|s| s.order),
620 PrimitiveKind::PolychromeSprite,
621 ),
622 (
623 self.surfaces_iter.peek().map(|s| s.order),
624 PrimitiveKind::Surface,
625 ),
626 (
627 self.native_views_iter
628 .peek()
629 .map(|native_view| native_view.order),
630 PrimitiveKind::NativeView,
631 ),
632 ];
633 orders_and_kinds.sort_by_key(|(order, kind)| (order.unwrap_or(u32::MAX), *kind));
634
635 let first = orders_and_kinds[0];
636 let second = orders_and_kinds[1];
637 let (batch_kind, max_order_and_kind) = if first.0.is_some() {
638 (first.1, (second.0.unwrap_or(u32::MAX), second.1))
639 } else {
640 return None;
641 };
642
643 match batch_kind {
644 PrimitiveKind::Shadow => {
645 let shadows_start = self.shadows_start;
646 let mut shadows_end = shadows_start + 1;
647 self.shadows_iter.next();
648 while self
649 .shadows_iter
650 .next_if(|shadow| (shadow.order, batch_kind) < max_order_and_kind)
651 .is_some()
652 {
653 shadows_end += 1;
654 }
655 self.shadows_start = shadows_end;
656 Some(PrimitiveBatch::Shadows(shadows_start..shadows_end))
657 }
658 PrimitiveKind::Quad => {
659 let quads_start = self.quads_start;
660 let mut quads_end = quads_start + 1;
661 self.quads_iter.next();
662 while self
663 .quads_iter
664 .next_if(|quad| (quad.order, batch_kind) < max_order_and_kind)
665 .is_some()
666 {
667 quads_end += 1;
668 }
669 self.quads_start = quads_end;
670 Some(PrimitiveBatch::Quads(quads_start..quads_end))
671 }
672 PrimitiveKind::Path => {
673 let paths_start = self.paths_start;
674 let mut paths_end = paths_start + 1;
675 self.paths_iter.next();
676 while self
677 .paths_iter
678 .next_if(|path| (path.order, batch_kind) < max_order_and_kind)
679 .is_some()
680 {
681 paths_end += 1;
682 }
683 self.paths_start = paths_end;
684 Some(PrimitiveBatch::Paths(paths_start..paths_end))
685 }
686 PrimitiveKind::Underline => {
687 let underlines_start = self.underlines_start;
688 let mut underlines_end = underlines_start + 1;
689 self.underlines_iter.next();
690 while self
691 .underlines_iter
692 .next_if(|underline| (underline.order, batch_kind) < max_order_and_kind)
693 .is_some()
694 {
695 underlines_end += 1;
696 }
697 self.underlines_start = underlines_end;
698 Some(PrimitiveBatch::Underlines(underlines_start..underlines_end))
699 }
700 PrimitiveKind::MonochromeSprite => {
701 let texture_id = self.monochrome_sprites_iter.peek().unwrap().tile.texture_id;
702 let sprites_start = self.monochrome_sprites_start;
703 let mut sprites_end = sprites_start + 1;
704 self.monochrome_sprites_iter.next();
705 while self
706 .monochrome_sprites_iter
707 .next_if(|sprite| {
708 (sprite.order, batch_kind) < max_order_and_kind
709 && sprite.tile.texture_id == texture_id
710 })
711 .is_some()
712 {
713 sprites_end += 1;
714 }
715 self.monochrome_sprites_start = sprites_end;
716 Some(PrimitiveBatch::MonochromeSprites {
717 texture_id,
718 range: sprites_start..sprites_end,
719 })
720 }
721 PrimitiveKind::SubpixelSprite => {
722 let texture_id = self.subpixel_sprites_iter.peek().unwrap().tile.texture_id;
723 let sprites_start = self.subpixel_sprites_start;
724 let mut sprites_end = sprites_start + 1;
725 self.subpixel_sprites_iter.next();
726 while self
727 .subpixel_sprites_iter
728 .next_if(|sprite| {
729 (sprite.order, batch_kind) < max_order_and_kind
730 && sprite.tile.texture_id == texture_id
731 })
732 .is_some()
733 {
734 sprites_end += 1;
735 }
736 self.subpixel_sprites_start = sprites_end;
737 Some(PrimitiveBatch::SubpixelSprites {
738 texture_id,
739 range: sprites_start..sprites_end,
740 })
741 }
742 PrimitiveKind::PolychromeSprite => {
743 let texture_id = self.polychrome_sprites_iter.peek().unwrap().tile.texture_id;
744 let sprites_start = self.polychrome_sprites_start;
745 let mut sprites_end = sprites_start + 1;
746 self.polychrome_sprites_iter.next();
747 while self
748 .polychrome_sprites_iter
749 .next_if(|sprite| {
750 (sprite.order, batch_kind) < max_order_and_kind
751 && sprite.tile.texture_id == texture_id
752 })
753 .is_some()
754 {
755 sprites_end += 1;
756 }
757 self.polychrome_sprites_start = sprites_end;
758 Some(PrimitiveBatch::PolychromeSprites {
759 texture_id,
760 range: sprites_start..sprites_end,
761 })
762 }
763 PrimitiveKind::Surface => {
764 let surfaces_start = self.surfaces_start;
765 let mut surfaces_end = surfaces_start + 1;
766 self.surfaces_iter.next();
767 while self
768 .surfaces_iter
769 .next_if(|surface| (surface.order, batch_kind) < max_order_and_kind)
770 .is_some()
771 {
772 surfaces_end += 1;
773 }
774 self.surfaces_start = surfaces_end;
775 Some(PrimitiveBatch::Surfaces(surfaces_start..surfaces_end))
776 }
777 PrimitiveKind::NativeView => {
778 let native_views_start = self.native_views_start;
779 let mut native_views_end = native_views_start + 1;
780 self.native_views_iter.next();
781 while self
782 .native_views_iter
783 .next_if(|native_view| (native_view.order, batch_kind) < max_order_and_kind)
784 .is_some()
785 {
786 native_views_end += 1;
787 }
788 self.native_views_start = native_views_end;
789 Some(PrimitiveBatch::NativeViews(
790 native_views_start..native_views_end,
791 ))
792 }
793 }
794 }
795}
796
797#[derive(Debug)]
798#[cfg_attr(
799 all(
800 any(target_os = "linux", target_os = "freebsd"),
801 not(any(feature = "x11", feature = "wayland"))
802 ),
803 allow(dead_code)
804)]
805#[allow(missing_docs)]
806pub enum PrimitiveBatch {
807 Shadows(Range<usize>),
808 Quads(Range<usize>),
809 Paths(Range<usize>),
810 Underlines(Range<usize>),
811 MonochromeSprites {
812 texture_id: AtlasTextureId,
813 range: Range<usize>,
814 },
815 #[cfg_attr(target_os = "macos", allow(dead_code))]
816 SubpixelSprites {
817 texture_id: AtlasTextureId,
818 range: Range<usize>,
819 },
820 PolychromeSprites {
821 texture_id: AtlasTextureId,
822 range: Range<usize>,
823 },
824 Surfaces(Range<usize>),
825 NativeViews(Range<usize>),
826}
827
828impl PrimitiveBatch {
829 #[expect(missing_docs)]
830 pub fn label(&self) -> String {
831 match self {
832 Self::Shadows(range) => format!("shadows ({})", range.len()),
833 Self::Quads(range) => format!("quads ({})", range.len()),
834 Self::Paths(range) => format!("paths ({})", range.len()),
835 Self::Underlines(range) => format!("underlines ({})", range.len()),
836 Self::MonochromeSprites { texture_id, range } => {
837 format!(
838 "monochrome sprites ({}) on atlas {}",
839 range.len(),
840 texture_id.index
841 )
842 }
843 Self::SubpixelSprites { texture_id, range } => {
844 format!(
845 "subpixel sprites ({}) on atlas {}",
846 range.len(),
847 texture_id.index
848 )
849 }
850 Self::PolychromeSprites { texture_id, range } => {
851 format!(
852 "polychrome sprites ({}) on atlas {}",
853 range.len(),
854 texture_id.index
855 )
856 }
857 Self::Surfaces(range) => format!("surfaces ({})", range.len()),
858 Self::NativeViews(range) => format!("native views ({})", range.len()),
859 }
860 }
861}
862
863#[derive(Default, Debug, Copy, Clone)]
864#[repr(C)]
865#[expect(missing_docs)]
866pub struct Quad {
867 pub order: DrawOrder,
868 pub border_style: BorderStyle,
869 pub bounds: Bounds<ScaledPixels>,
870 pub content_mask: ContentMask<ScaledPixels>,
871 pub background: Background,
872 pub border_color: Hsla,
873 pub corner_radii: Corners<ScaledPixels>,
874 pub border_widths: Edges<ScaledPixels>,
875}
876
877impl From<Quad> for Primitive {
878 fn from(quad: Quad) -> Self {
879 Primitive::Quad(quad)
880 }
881}
882
883#[derive(Debug, Copy, Clone)]
884#[repr(C)]
885#[expect(missing_docs)]
886pub struct Underline {
887 pub order: DrawOrder,
888 pub pad: u32, pub bounds: Bounds<ScaledPixels>,
890 pub content_mask: ContentMask<ScaledPixels>,
891 pub color: Hsla,
892 pub thickness: ScaledPixels,
893 pub wavy: PaddedBool32,
894}
895
896impl From<Underline> for Primitive {
897 fn from(underline: Underline) -> Self {
898 Primitive::Underline(underline)
899 }
900}
901
902#[derive(Debug, Copy, Clone)]
903#[repr(C)]
904#[expect(missing_docs)]
905pub struct Shadow {
906 pub order: DrawOrder,
907 pub blur_radius: ScaledPixels,
908 pub bounds: Bounds<ScaledPixels>,
909 pub corner_radii: Corners<ScaledPixels>,
910 pub content_mask: ContentMask<ScaledPixels>,
911 pub color: Hsla,
912 pub shape_bounds: Bounds<ScaledPixels>,
913 pub shape_corner_radii: Corners<ScaledPixels>,
914 pub inset: PaddedBool32,
915 pub pad: u32, }
917
918impl From<Shadow> for Primitive {
919 fn from(shadow: Shadow) -> Self {
920 Primitive::Shadow(shadow)
921 }
922}
923
924#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
926#[repr(C)]
927pub enum BorderStyle {
928 #[default]
930 Solid = 0,
931 Dashed = 1,
933}
934
935#[derive(Debug, Clone, Copy, PartialEq)]
937#[repr(C)]
938pub struct TransformationMatrix {
939 pub rotation_scale: [[f32; 2]; 2],
942 pub translation: [f32; 2],
944}
945
946impl Eq for TransformationMatrix {}
947
948impl TransformationMatrix {
949 pub fn unit() -> Self {
951 Self {
952 rotation_scale: [[1.0, 0.0], [0.0, 1.0]],
953 translation: [0.0, 0.0],
954 }
955 }
956
957 pub fn translate(self, point: Point<ScaledPixels>) -> Self {
959 self.compose(Self {
960 rotation_scale: [[1.0, 0.0], [0.0, 1.0]],
961 translation: [point.x.0, point.y.0],
962 })
963 }
964
965 pub fn rotate(self, angle: Radians) -> Self {
967 self.compose(Self {
968 rotation_scale: [
969 [angle.0.cos(), -angle.0.sin()],
970 [angle.0.sin(), angle.0.cos()],
971 ],
972 translation: [0.0, 0.0],
973 })
974 }
975
976 pub fn scale(self, size: Size<f32>) -> Self {
978 self.compose(Self {
979 rotation_scale: [[size.width, 0.0], [0.0, size.height]],
980 translation: [0.0, 0.0],
981 })
982 }
983
984 #[inline]
988 pub fn compose(self, other: TransformationMatrix) -> TransformationMatrix {
989 if other == Self::unit() {
990 return self;
991 }
992 TransformationMatrix {
994 rotation_scale: [
995 [
996 self.rotation_scale[0][0] * other.rotation_scale[0][0]
997 + self.rotation_scale[0][1] * other.rotation_scale[1][0],
998 self.rotation_scale[0][0] * other.rotation_scale[0][1]
999 + self.rotation_scale[0][1] * other.rotation_scale[1][1],
1000 ],
1001 [
1002 self.rotation_scale[1][0] * other.rotation_scale[0][0]
1003 + self.rotation_scale[1][1] * other.rotation_scale[1][0],
1004 self.rotation_scale[1][0] * other.rotation_scale[0][1]
1005 + self.rotation_scale[1][1] * other.rotation_scale[1][1],
1006 ],
1007 ],
1008 translation: [
1009 self.translation[0]
1010 + self.rotation_scale[0][0] * other.translation[0]
1011 + self.rotation_scale[0][1] * other.translation[1],
1012 self.translation[1]
1013 + self.rotation_scale[1][0] * other.translation[0]
1014 + self.rotation_scale[1][1] * other.translation[1],
1015 ],
1016 }
1017 }
1018
1019 pub(crate) fn transform_bounds(&self, bounds: Bounds<ScaledPixels>) -> Bounds<ScaledPixels> {
1021 if *self == Self::unit() {
1022 return bounds;
1023 }
1024 let [[xx, xy], [yx, yy]] = self.rotation_scale;
1025 let [translate_x, translate_y] = self.translation;
1026 let corners = [
1027 bounds.origin,
1028 bounds.top_right(),
1029 bounds.bottom_left(),
1030 bounds.bottom_right(),
1031 ]
1032 .map(|corner| {
1033 Point::new(
1034 ScaledPixels(xx * corner.x.0 + xy * corner.y.0 + translate_x),
1035 ScaledPixels(yx * corner.x.0 + yy * corner.y.0 + translate_y),
1036 )
1037 });
1038 let [first, rest @ ..] = corners;
1039 let top_left = rest.iter().fold(first, |min, corner| min.min(corner));
1040 let bottom_right = rest.iter().fold(first, |max, corner| max.max(corner));
1041 Bounds::from_corners(top_left, bottom_right)
1042 }
1043
1044 pub fn apply(&self, point: Point<Pixels>) -> Point<Pixels> {
1046 let input = [point.x.0, point.y.0];
1047 let mut output = self.translation;
1048 for (i, output_cell) in output.iter_mut().enumerate() {
1049 for (k, input_cell) in input.iter().enumerate() {
1050 *output_cell += self.rotation_scale[i][k] * *input_cell;
1051 }
1052 }
1053 Point::new(output[0].into(), output[1].into())
1054 }
1055}
1056
1057impl Default for TransformationMatrix {
1058 fn default() -> Self {
1059 Self::unit()
1060 }
1061}
1062
1063#[derive(Copy, Clone, Debug)]
1064#[repr(C)]
1065#[expect(missing_docs)]
1066pub struct MonochromeSprite {
1067 pub order: DrawOrder,
1068 pub animation: SpriteAnimationId,
1069 pub tile: AtlasTile,
1070 pub bounds: Bounds<ScaledPixels>,
1071 pub content_mask: ContentMask<ScaledPixels>,
1072 pub color: Hsla,
1073 pub transformation: TransformationMatrix,
1074}
1075
1076#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1081#[repr(transparent)]
1082pub struct SpriteAnimationId(u32);
1083
1084impl SpriteAnimationId {
1085 pub const NONE: Self = Self(u32::MAX);
1087}
1088
1089impl Default for SpriteAnimationId {
1090 fn default() -> Self {
1091 Self::NONE
1092 }
1093}
1094
1095#[derive(Copy, Clone, Debug)]
1098pub(crate) struct SpriteAnimation {
1099 transformation: TimedTransformation,
1100 center: Point<Pixels>,
1101 scale_factor: f32,
1102 base_color: Hsla,
1103 sprite_index: usize,
1104}
1105
1106impl SpriteAnimation {
1107 pub(crate) fn new(
1108 transformation: TimedTransformation,
1109 center: Point<Pixels>,
1110 scale_factor: f32,
1111 ) -> Self {
1112 Self {
1113 transformation,
1114 center,
1115 scale_factor,
1116 base_color: Hsla::default(),
1117 sprite_index: usize::MAX,
1118 }
1119 }
1120}
1121
1122impl From<MonochromeSprite> for Primitive {
1123 fn from(sprite: MonochromeSprite) -> Self {
1124 Primitive::MonochromeSprite(sprite)
1125 }
1126}
1127
1128#[derive(Copy, Clone, Debug)]
1129#[repr(C)]
1130#[expect(missing_docs)]
1131pub struct SubpixelSprite {
1132 pub order: DrawOrder,
1133 pub pad: u32, pub tile: AtlasTile,
1135 pub bounds: Bounds<ScaledPixels>,
1136 pub content_mask: ContentMask<ScaledPixels>,
1137 pub color: Hsla,
1138 pub transformation: TransformationMatrix,
1139}
1140
1141impl From<SubpixelSprite> for Primitive {
1142 fn from(sprite: SubpixelSprite) -> Self {
1143 Primitive::SubpixelSprite(sprite)
1144 }
1145}
1146
1147#[derive(Copy, Clone, Debug)]
1148#[repr(C)]
1149#[expect(missing_docs)]
1150pub struct PolychromeSprite {
1151 pub order: DrawOrder,
1152 pub pad: u32,
1153 pub tile: AtlasTile,
1154 pub grayscale: PaddedBool32,
1155 pub opacity: f32,
1156 pub bounds: Bounds<ScaledPixels>,
1157 pub content_mask: ContentMask<ScaledPixels>,
1158 pub corner_radii: Corners<ScaledPixels>,
1159}
1160
1161impl From<PolychromeSprite> for Primitive {
1162 fn from(sprite: PolychromeSprite) -> Self {
1163 Primitive::PolychromeSprite(sprite)
1164 }
1165}
1166
1167#[derive(Clone, Debug)]
1168#[allow(missing_docs)]
1169pub struct PaintSurface {
1170 pub order: DrawOrder,
1171 pub bounds: Bounds<ScaledPixels>,
1172 pub content_mask: ContentMask<ScaledPixels>,
1173 #[cfg(any(target_os = "macos", target_os = "ios"))]
1174 pub image_buffer: objc2_core_foundation::CFRetained<objc2_core_video::CVPixelBuffer>,
1175}
1176
1177impl From<PaintSurface> for Primitive {
1178 fn from(surface: PaintSurface) -> Self {
1179 Primitive::Surface(surface)
1180 }
1181}
1182
1183#[derive(Clone, Copy, Debug)]
1189pub struct PaintNativeView {
1190 pub order: DrawOrder,
1192 pub id: NativeViewId,
1194 pub hitbox_id: HitboxId,
1196 pub bounds: Bounds<ScaledPixels>,
1198 pub content_mask: ContentMask<ScaledPixels>,
1200 pub background: Hsla,
1203}
1204
1205impl From<PaintNativeView> for Primitive {
1206 fn from(native_view: PaintNativeView) -> Self {
1207 Primitive::NativeView(native_view)
1208 }
1209}
1210
1211#[derive(Clone, Copy, Debug, PartialEq)]
1212#[repr(C)]
1213#[expect(missing_docs)]
1214pub struct PathCurve {
1215 pub p0: Point<f32>,
1216 pub p1: Point<f32>,
1217 pub a: Point<f32>,
1218 pub b: Point<f32>,
1219 pub sign: f32,
1220 pub pad: u32, }
1222
1223#[derive(Clone, Copy, Debug)]
1224#[repr(C)]
1225#[expect(missing_docs)]
1226pub struct PathPaint {
1227 pub bounds: Bounds<ScaledPixels>,
1229 pub content_mask: ContentMask<ScaledPixels>,
1230 pub color: Background,
1231 pub even_odd: PaddedBool32,
1232 pub pad: u32, }
1234
1235#[derive(Clone, Copy, Debug, PartialEq)]
1236#[repr(C)]
1237#[expect(missing_docs)]
1238pub struct PathTile {
1239 pub paint: u32,
1240 pub curve_start: u32,
1241 pub curve_count: u32,
1242 pub backdrop: i32,
1243 pub top_left: Point<f32>,
1244 pub bottom_right: Point<f32>,
1245 pub reference: Point<f32>,
1246 pub curves_top_left: Point<f32>,
1247 pub curves_bottom_right: Point<f32>,
1248}
1249
1250#[derive(Clone, Debug)]
1251#[expect(missing_docs)]
1252pub struct PaintedPath {
1253 order: DrawOrder,
1254 bounds: Bounds<ScaledPixels>,
1255 tiles: Rc<PathTiles>,
1256 paint: PathPaint,
1257}
1258
1259#[expect(missing_docs)]
1260impl PaintedPath {
1261 pub fn new(
1263 path: Path,
1264 scale_factor: f32,
1265 content_mask: ContentMask<Pixels>,
1266 color: Background,
1267 ) -> Self {
1268 let content_mask = content_mask.scale(scale_factor);
1269 let mut tiles = path.bin(scale_factor);
1270 tiles.retain_visible(content_mask.bounds);
1271 let paint = PathPaint {
1272 bounds: tiles.bounds(),
1273 content_mask,
1274 color,
1275 even_odd: path.even_odd().into(),
1276 pad: 0,
1277 };
1278 Self {
1279 order: 0,
1280 bounds: tiles.painted_bounds(),
1281 tiles: Rc::new(tiles),
1282 paint,
1283 }
1284 }
1285
1286 pub fn tile_count(&self) -> usize {
1287 self.tiles.tiles().len()
1288 }
1289
1290 pub fn append_to(
1291 &self,
1292 paints: &mut Vec<PathPaint>,
1293 curves: &mut Vec<PathCurve>,
1294 tiles: &mut Vec<PathTile>,
1295 ) {
1296 let paint_index = paints.len() as u32;
1297 let curve_start = curves.len() as u32;
1298 paints.push(self.paint);
1299 curves.extend_from_slice(self.tiles.curves());
1300 tiles.extend(self.tiles.tiles().iter().map(|tile| PathTile {
1301 paint: paint_index,
1302 curve_start: curve_start + tile.curve_start,
1303 ..*tile
1304 }));
1305 }
1306}
1307
1308impl From<PaintedPath> for Primitive {
1309 fn from(path: PaintedPath) -> Self {
1310 Primitive::Path(path)
1311 }
1312}
1313
1314#[cfg(test)]
1315mod tests {
1316 use super::*;
1317 use crate::{point, size};
1318
1319 fn square(x: f32) -> Bounds<ScaledPixels> {
1320 Bounds {
1321 origin: point(ScaledPixels(x), ScaledPixels(0.)),
1322 size: size(ScaledPixels(10.), ScaledPixels(10.)),
1323 }
1324 }
1325
1326 fn quad(x: f32) -> Quad {
1327 Quad {
1328 bounds: square(x),
1329 content_mask: ContentMask { bounds: square(x) },
1330 ..Default::default()
1331 }
1332 }
1333
1334 fn underline(x: f32) -> Underline {
1335 Underline {
1336 order: 0,
1337 pad: 0,
1338 bounds: square(x),
1339 content_mask: ContentMask { bounds: square(x) },
1340 color: Hsla::default(),
1341 thickness: ScaledPixels(1.),
1342 wavy: false.into(),
1343 }
1344 }
1345
1346 fn batch_labels(scene: &mut Scene) -> Vec<String> {
1347 scene.finish();
1348 scene.batches().map(|batch| batch.label()).collect()
1349 }
1350
1351 #[test]
1352 fn a_native_view_in_a_layer_is_covered_by_what_the_layer_paints_after_it() {
1353 let mut scene = Scene::default();
1354 scene.push_layer();
1355 scene.insert_primitive(quad(0.));
1356 scene.insert_primitive(PaintNativeView {
1357 order: 0,
1358 id: NativeViewId::for_test(1),
1359 hitbox_id: HitboxId::placeholder(),
1360 bounds: square(0.),
1361 content_mask: ContentMask { bounds: square(0.) },
1362 background: Hsla::default(),
1363 });
1364 scene.insert_primitive(quad(0.));
1365 scene.insert_primitive(quad(20.));
1367 scene.pop_layer();
1368 assert_eq!(
1369 batch_labels(&mut scene),
1370 ["quads (1)", "native views (1)", "quads (2)"]
1371 );
1372 }
1373
1374 #[test]
1375 fn a_native_view_painted_twice_is_kept_where_it_was_painted_first() {
1376 let native_view = |hitbox_id: HitboxId, x: f32| PaintNativeView {
1377 order: 0,
1378 id: NativeViewId::for_test(1),
1379 hitbox_id,
1380 bounds: square(x),
1381 content_mask: ContentMask { bounds: square(x) },
1382 background: Hsla::default(),
1383 };
1384 let first_hitbox = HitboxId::placeholder();
1385 let second_hitbox = first_hitbox.next();
1386 let mut scene = Scene::default();
1387 scene.insert_primitive(underline(0.));
1391 scene.insert_primitive(quad(0.));
1392 scene.insert_primitive(native_view(first_hitbox, 0.));
1393 scene.insert_primitive(native_view(second_hitbox, 20.));
1394 scene.finish();
1395
1396 let shown = scene
1397 .native_views
1398 .iter()
1399 .map(|native_view| native_view.bounds)
1400 .collect::<Vec<_>>();
1401 assert_eq!(shown, [square(0.)]);
1402 }
1403
1404 #[test]
1405 fn layers_are_drawn_in_paint_order() {
1406 let mut scene = Scene::default();
1408 scene.insert_primitive(quad(0.));
1409 scene.push_layer();
1410 scene.insert_primitive(underline(0.));
1411 scene.insert_primitive(underline(5.));
1412 scene.pop_layer();
1413 scene.insert_primitive(quad(5.));
1414 assert_eq!(
1415 batch_labels(&mut scene),
1416 ["quads (1)", "underlines (2)", "quads (1)"]
1417 );
1418
1419 let mut scene = Scene::default();
1421 scene.push_layer();
1422 scene.insert_primitive(underline(0.));
1423 scene.pop_layer();
1424 scene.push_layer();
1425 scene.insert_primitive(quad(5.));
1426 scene.pop_layer();
1427 assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]);
1428 }
1429
1430 #[test]
1431 fn nested_layers_are_drawn_above_their_parents() {
1432 let mut scene = Scene::default();
1435 scene.push_layer();
1436 scene.insert_primitive(underline(0.));
1437 scene.push_layer();
1438 scene.insert_primitive(quad(5.));
1439 scene.pop_layer();
1440 scene.insert_primitive(underline(5.));
1441 scene.pop_layer();
1442 assert_eq!(batch_labels(&mut scene), ["underlines (2)", "quads (1)"]);
1443
1444 let mut scene = Scene::default();
1446 scene.push_layer();
1447 scene.insert_primitive(quad(0.));
1448 scene.push_layer();
1449 scene.insert_primitive(quad(5.));
1450 scene.pop_layer();
1451 scene.insert_primitive(quad(8.));
1452 scene.pop_layer();
1453 assert_eq!(batch_labels(&mut scene), ["quads (3)"]);
1454 assert_eq!(
1455 scene
1456 .quads
1457 .iter()
1458 .map(|quad| quad.bounds)
1459 .collect::<Vec<_>>(),
1460 [square(0.), square(8.), square(5.)]
1461 );
1462
1463 let mut scene = Scene::default();
1465 scene.push_layer();
1466 scene.push_layer();
1467 scene.insert_primitive(underline(0.));
1468 scene.pop_layer();
1469 scene.pop_layer();
1470 scene.push_layer();
1471 scene.insert_primitive(quad(5.));
1472 scene.pop_layer();
1473 assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]);
1474 }
1475}