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