1use crate::atlas::{AtlasKind, AtlasTile};
8use crate::shaders::ShaderId;
9use bytemuck::{Pod, Zeroable};
10use kova_native_core::{Bounds, Color, Corners, Edges, Fill, Point, Transform2D};
11use std::ops::Range;
12
13pub(crate) const KIND_QUAD: u32 = 0;
14pub(crate) const KIND_SHADOW: u32 = 1;
15pub(crate) const KIND_INSET_SHADOW: u32 = 2;
16pub(crate) const KIND_MONO_SPRITE: u32 = 3;
17pub(crate) const KIND_POLY_SPRITE: u32 = 4;
18pub(crate) const KIND_BACKDROP: u32 = 5;
19pub(crate) const KIND_LAYER: u32 = 6;
20pub(crate) const KIND_CUSTOM: u32 = 7;
21
22const FLAG_GRADIENT: u32 = 1;
23const FLAG_GRAYSCALE: u32 = 2;
24const MASK_GRADIENT: u32 = 1;
25const MASK_MONO: u32 = 2;
26const MASK_COLOR: u32 = 4;
27
28#[repr(C)]
30#[derive(Clone, Copy, Debug, Pod, Zeroable)]
31pub(crate) struct Instance {
32 pub bounds: [f32; 4],
33 pub radii: [f32; 4],
34 pub border_widths: [f32; 4],
35 pub uv: [f32; 4],
36 pub clip_bounds: [f32; 4],
37 pub clip_radii: [f32; 4],
38 pub transform: [f32; 4],
39 pub translate_params: [f32; 4],
40 pub params: [f32; 4],
41 pub color0: u32,
42 pub color1: u32,
43 pub border_color: u32,
44 pub kind: u32,
45}
46
47#[derive(Clone, Copy, Debug, PartialEq)]
49pub struct ContentMask {
50 pub bounds: Bounds,
51 pub radii: Corners<f32>,
52}
53
54impl ContentMask {
55 pub const NONE: ContentMask = ContentMask {
56 bounds: Bounds::INFINITE,
57 radii: Corners::ZERO,
58 };
59
60 pub fn new(bounds: Bounds) -> Self {
61 ContentMask {
62 bounds,
63 radii: Corners::ZERO,
64 }
65 }
66
67 pub fn rounded(bounds: Bounds, radii: Corners<f32>) -> Self {
68 ContentMask {
69 bounds,
70 radii: radii.clamp_to(bounds.size),
71 }
72 }
73
74 pub fn intersect(&self, other: &ContentMask) -> ContentMask {
77 let bounds = self.bounds.intersect(&other.bounds);
78 let self_area = self.bounds.size.width * self.bounds.size.height;
79 let other_area = other.bounds.size.width * other.bounds.size.height;
80 let radii = if other_area <= self_area {
81 other.radii
82 } else {
83 self.radii
84 };
85 ContentMask { bounds, radii }
86 }
87}
88
89#[derive(Clone, Copy, Debug, PartialEq)]
91pub struct DrawState {
92 pub transform: Transform2D,
93 pub clip: ContentMask,
94 pub opacity: f32,
95}
96
97impl Default for DrawState {
98 fn default() -> Self {
99 DrawState {
100 transform: Transform2D::IDENTITY,
101 clip: ContentMask::NONE,
102 opacity: 1.0,
103 }
104 }
105}
106
107#[derive(Clone, Copy, Debug, PartialEq)]
109pub struct Quad {
110 pub bounds: Bounds,
111 pub radii: Corners<f32>,
112 pub fill: Fill,
113 pub border_widths: Edges<f32>,
114 pub border_color: Color,
115}
116
117impl Quad {
118 pub fn filled(bounds: Bounds, fill: impl Into<Fill>) -> Self {
119 Quad {
120 bounds,
121 radii: Corners::ZERO,
122 fill: fill.into(),
123 border_widths: Edges::ZERO,
124 border_color: Color::TRANSPARENT,
125 }
126 }
127
128 pub fn radii(mut self, radii: impl Into<Corners<f32>>) -> Self {
129 self.radii = radii.into();
130 self
131 }
132
133 pub fn border(mut self, widths: impl Into<Edges<f32>>, color: Color) -> Self {
134 self.border_widths = widths.into();
135 self.border_color = color;
136 self
137 }
138}
139
140#[derive(Clone, Copy, Debug, PartialEq)]
143pub struct Shadow {
144 pub bounds: Bounds,
146 pub radii: Corners<f32>,
147 pub color: Color,
148 pub offset: Point,
149 pub blur: f32,
150 pub spread: f32,
151 pub inset: bool,
152}
153
154#[derive(Clone, Copy, Debug, PartialEq)]
156pub enum Effect {
157 CaptureBackdrop { blur: f32 },
160}
161
162#[derive(Clone, Copy, Debug, PartialEq)]
165pub enum LayerMask {
166 None,
168 LinearGradient {
172 angle: f32,
173 from: f32,
174 to: f32,
175 start: f32,
176 end: f32,
177 },
178 Tile(AtlasTile),
181}
182
183#[derive(Clone, Debug, PartialEq)]
185pub(crate) enum Op {
186 Draw {
189 instances: Range<u32>,
190 shader: Option<ShaderId>,
191 },
192 Effect(Effect),
194 PushLayer,
196 PopLayer { composite: Option<u32> },
199}
200
201#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
203pub struct SceneStats {
204 pub primitives: usize,
205 pub culled: usize,
206 pub draw_calls: usize,
207}
208
209#[derive(Default)]
211pub struct Scene {
212 pub(crate) instances: Vec<Instance>,
213 ops: Vec<Op>,
214 run_start: u32,
216 run_shader: Option<ShaderId>,
218 layer_depth: u32,
219 culled: usize,
220}
221
222fn pack(c: Color) -> u32 {
223 u32::from_le_bytes(c.to_rgba8())
224}
225
226impl Scene {
227 pub fn new() -> Self {
228 Self::default()
229 }
230
231 pub fn clear(&mut self) {
232 self.instances.clear();
233 self.ops.clear();
234 self.run_start = 0;
235 self.run_shader = None;
236 self.layer_depth = 0;
237 self.culled = 0;
238 }
239
240 pub fn layer_depth(&self) -> u32 {
242 self.layer_depth
243 }
244
245 pub fn len(&self) -> usize {
246 self.instances.len()
247 }
248
249 pub fn is_empty(&self) -> bool {
250 self.instances.is_empty()
251 }
252
253 pub fn stats(&self) -> SceneStats {
254 let draw_calls = self
255 .ops()
256 .iter()
257 .filter(|op| matches!(op, Op::Draw { .. } | Op::PopLayer { composite: Some(_) }))
258 .count();
259 SceneStats {
260 primitives: self.instances.len(),
261 culled: self.culled,
262 draw_calls,
263 }
264 }
265
266 pub(crate) fn ops(&self) -> Vec<Op> {
268 let mut ops = self.ops.clone();
269 let end = self.instances.len() as u32;
270 if end > self.run_start {
271 ops.push(Op::Draw {
272 instances: self.run_start..end,
273 shader: self.run_shader,
274 });
275 }
276 ops
277 }
278
279 fn close_run(&mut self) {
280 let end = self.instances.len() as u32;
281 if end > self.run_start {
282 self.ops.push(Op::Draw {
283 instances: self.run_start..end,
284 shader: self.run_shader,
285 });
286 }
287 self.run_start = end;
288 }
289
290 fn begin(&mut self, shader: Option<ShaderId>) {
292 if shader != self.run_shader {
293 self.close_run();
294 self.run_shader = shader;
295 }
296 }
297
298 fn push(&mut self, inst: Instance) {
299 self.begin(None);
300 self.instances.push(inst);
301 }
302
303 fn visible(&mut self, local: &Bounds, state: &DrawState) -> bool {
306 if state.opacity <= 0.0 || state.clip.bounds.is_empty() {
307 self.culled += 1;
308 return false;
309 }
310 let world = state.transform.apply_bounds(local);
311 if !world.intersects(&state.clip.bounds) {
312 self.culled += 1;
313 return false;
314 }
315 true
316 }
317
318 fn base(state: &DrawState, kind: u32) -> Instance {
319 let t = &state.transform;
320 let c = &state.clip;
321 Instance {
322 bounds: [0.0; 4],
323 radii: [0.0; 4],
324 border_widths: [0.0; 4],
325 uv: [0.0; 4],
326 clip_bounds: [
327 c.bounds.origin.x,
328 c.bounds.origin.y,
329 c.bounds.size.width,
330 c.bounds.size.height,
331 ],
332 clip_radii: [
333 c.radii.top_left,
334 c.radii.top_right,
335 c.radii.bottom_right,
336 c.radii.bottom_left,
337 ],
338 transform: [t.a, t.b, t.c, t.d],
339 translate_params: [t.tx, t.ty, 0.0, 0.0],
340 params: [0.0; 4],
341 color0: 0,
342 color1: 0,
343 border_color: 0,
344 kind,
345 }
346 }
347
348 pub fn push_quad(&mut self, quad: &Quad, state: &DrawState) {
349 if quad.bounds.is_empty() || !self.visible(&quad.bounds, state) {
350 return;
351 }
352 let border_visible = !quad.border_widths.is_zero() && !quad.border_color.is_transparent();
353 if quad.fill.is_transparent() && !border_visible {
354 return;
355 }
356 let radii = quad.radii.clamp_to(quad.bounds.size);
357 let mut inst = Self::base(state, KIND_QUAD);
358 inst.bounds = rect(&quad.bounds);
359 inst.radii = corners(&radii);
360 if border_visible {
361 let b = quad.border_widths;
362 inst.border_widths = [b.top, b.right, b.bottom, b.left];
363 inst.border_color = pack(quad.border_color.fade(state.opacity));
364 }
365 match quad.fill {
366 Fill::Solid(c) => inst.color0 = pack(c.fade(state.opacity)),
367 Fill::LinearGradient(g) => {
368 inst.kind |= FLAG_GRADIENT << 8;
369 inst.color0 = pack(g.from.color.fade(state.opacity));
370 inst.color1 = pack(g.to.color.fade(state.opacity));
371 inst.translate_params[2] = g.angle.to_radians();
372 inst.translate_params[3] = g.from.position;
373 inst.params[0] = g.to.position;
374 }
375 }
376 self.push(inst);
377 }
378
379 pub fn push_shadow(&mut self, shadow: &Shadow, state: &DrawState) {
380 if shadow.color.is_transparent() || shadow.bounds.is_empty() {
381 return;
382 }
383 let sigma = (shadow.blur * 0.5).max(0.0);
384 if shadow.inset {
385 if !self.visible(&shadow.bounds, state) {
386 return;
387 }
388 let radii = shadow.radii.clamp_to(shadow.bounds.size);
389 let hole = shadow
390 .bounds
391 .translate(shadow.offset)
392 .inflate(-shadow.spread);
393 let hole_radii = radii.map(|r| (r - shadow.spread).max(0.0));
394 let mut inst = Self::base(state, KIND_INSET_SHADOW);
395 inst.bounds = rect(&shadow.bounds);
396 inst.radii = corners(&radii);
397 inst.uv = rect(&hole);
398 inst.border_widths = corners(&hole_radii);
399 inst.translate_params[2] = sigma;
400 inst.color0 = pack(shadow.color.fade(state.opacity));
401 self.push(inst);
402 } else {
403 let shape = shadow
404 .bounds
405 .translate(shadow.offset)
406 .inflate(shadow.spread);
407 if shape.is_empty() {
408 return;
409 }
410 let radii = shadow
411 .radii
412 .clamp_to(shadow.bounds.size)
413 .map(|r| (r + shadow.spread).max(0.0));
414 if !self.visible(&shape.inflate(sigma * 3.0), state) {
415 return;
416 }
417 let mut inst = Self::base(state, KIND_SHADOW);
418 inst.bounds = rect(&shape);
419 inst.radii = corners(&radii.clamp_to(shape.size));
420 inst.translate_params[2] = sigma;
421 inst.color0 = pack(shadow.color.fade(state.opacity));
422 self.push(inst);
423 }
424 }
425
426 pub fn push_mono_sprite(
428 &mut self,
429 bounds: Bounds,
430 tile: &AtlasTile,
431 color: Color,
432 state: &DrawState,
433 ) {
434 if color.is_transparent() || !self.visible(&bounds, state) {
435 return;
436 }
437 let mut inst = Self::base(state, KIND_MONO_SPRITE | (tile.layer << 16));
438 inst.bounds = rect(&bounds);
439 inst.uv = tile.uv();
440 inst.color0 = pack(color.fade(state.opacity));
441 self.push(inst);
442 }
443
444 pub fn push_poly_sprite(
446 &mut self,
447 bounds: Bounds,
448 tile: &AtlasTile,
449 radii: Corners<f32>,
450 grayscale: bool,
451 state: &DrawState,
452 ) {
453 if !self.visible(&bounds, state) {
454 return;
455 }
456 let flags = if grayscale { FLAG_GRAYSCALE } else { 0 };
457 let mut inst = Self::base(state, KIND_POLY_SPRITE | (flags << 8) | (tile.layer << 16));
458 inst.bounds = rect(&bounds);
459 inst.radii = corners(&radii.clamp_to(bounds.size));
460 inst.uv = tile.uv();
461 inst.color0 = pack(Color::WHITE.fade(state.opacity));
462 self.push(inst);
463 }
464
465 pub fn push_backdrop_blur(
468 &mut self,
469 bounds: Bounds,
470 radii: Corners<f32>,
471 blur: f32,
472 tint: Color,
473 state: &DrawState,
474 ) {
475 if !self.visible(&bounds, state) {
476 return;
477 }
478 let effect = Effect::CaptureBackdrop {
479 blur: blur.max(0.0),
480 };
481 self.close_run();
482 if self.ops.last() != Some(&Op::Effect(effect)) {
484 self.ops.push(Op::Effect(effect));
485 }
486 let mut inst = Self::base(state, KIND_BACKDROP);
487 inst.bounds = rect(&bounds);
488 inst.radii = corners(&radii.clamp_to(bounds.size));
489 inst.color0 = pack(tint);
490 inst.params[0] = state.opacity;
491 self.push(inst);
492 }
493
494 pub fn push_layer(&mut self) {
498 self.close_run();
499 self.ops.push(Op::PushLayer);
500 self.layer_depth += 1;
501 }
502
503 pub fn pop_layer(&mut self, bounds: Bounds, mask: LayerMask, state: &DrawState) {
507 if self.layer_depth == 0 {
508 debug_assert!(false, "pop_layer without push_layer");
509 return;
510 }
511 self.layer_depth -= 1;
512 self.close_run();
513 if bounds.is_empty() || !self.visible(&bounds, state) {
514 self.ops.push(Op::PopLayer { composite: None });
515 return;
516 }
517 let (flags, layer) = match mask {
518 LayerMask::None => (0, 0),
519 LayerMask::LinearGradient { .. } => (MASK_GRADIENT, 0),
520 LayerMask::Tile(tile) => match tile.kind {
521 AtlasKind::Mono => (MASK_MONO, tile.layer),
522 AtlasKind::Color => (MASK_COLOR, tile.layer),
523 },
524 };
525 let mut inst = Self::base(state, KIND_LAYER | (flags << 8) | (layer << 16));
526 inst.bounds = rect(&bounds);
527 let opacity = state.opacity.clamp(0.0, 1.0);
528 inst.color0 = pack(Color::WHITE.with_alpha(opacity));
529 match mask {
530 LayerMask::None => {}
531 LayerMask::LinearGradient {
532 angle,
533 from,
534 to,
535 start,
536 end,
537 } => {
538 inst.color0 = pack(Color::WHITE.with_alpha(from.clamp(0.0, 1.0) * opacity));
539 inst.color1 = pack(Color::WHITE.with_alpha(to.clamp(0.0, 1.0) * opacity));
540 inst.translate_params[2] = angle.to_radians();
541 inst.translate_params[3] = start;
542 inst.params[0] = end;
543 }
544 LayerMask::Tile(tile) => inst.uv = tile.uv(),
545 }
546 let index = self.instances.len() as u32;
547 self.instances.push(inst);
548 self.run_start = self.instances.len() as u32;
549 self.ops.push(Op::PopLayer {
550 composite: Some(index),
551 });
552 }
553
554 #[allow(clippy::too_many_arguments)]
559 pub fn push_custom(
560 &mut self,
561 shader: ShaderId,
562 bounds: Bounds,
563 radii: Corners<f32>,
564 params: [f32; 8],
565 time: f32,
566 color: Color,
567 scale: f32,
568 state: &DrawState,
569 ) {
570 if bounds.is_empty() || !self.visible(&bounds, state) {
571 return;
572 }
573 let mut inst = Self::base(state, KIND_CUSTOM);
574 inst.bounds = rect(&bounds);
575 inst.radii = corners(&radii.clamp_to(bounds.size));
576 inst.uv = [params[0], params[1], params[2], params[3]];
577 inst.border_widths = [params[4], params[5], params[6], params[7]];
578 inst.translate_params[2] = time;
579 inst.translate_params[3] = scale;
580 inst.color0 = pack(Color::WHITE.with_alpha(state.opacity.clamp(0.0, 1.0)));
581 inst.color1 = pack(color);
582 self.begin(Some(shader));
583 self.instances.push(inst);
584 }
585}
586
587fn rect(b: &Bounds) -> [f32; 4] {
588 [b.origin.x, b.origin.y, b.size.width, b.size.height]
589}
590
591fn corners(c: &Corners<f32>) -> [f32; 4] {
592 [c.top_left, c.top_right, c.bottom_right, c.bottom_left]
593}
594
595#[cfg(test)]
596mod tests {
597 use super::*;
598 use kova_native_core::{bounds, rgb};
599
600 #[test]
601 fn culls_offscreen_and_clipped() {
602 let mut scene = Scene::new();
603 let state = DrawState {
604 clip: ContentMask::new(bounds(0.0, 0.0, 100.0, 100.0)),
605 ..Default::default()
606 };
607 scene.push_quad(
608 &Quad::filled(bounds(10.0, 10.0, 20.0, 20.0), rgb(0xff0000)),
609 &state,
610 );
611 scene.push_quad(
612 &Quad::filled(bounds(200.0, 10.0, 20.0, 20.0), rgb(0xff0000)),
613 &state,
614 );
615 scene.push_quad(
616 &Quad::filled(bounds(10.0, 10.0, 20.0, 20.0), Color::TRANSPARENT),
617 &state,
618 );
619 assert_eq!(scene.len(), 1);
620 assert_eq!(scene.stats().culled, 1);
621 assert_eq!(scene.stats().draw_calls, 1);
622 }
623
624 #[test]
625 fn mixed_primitives_share_one_segment() {
626 let mut scene = Scene::new();
627 let state = DrawState::default();
628 let tile = AtlasTile {
629 kind: crate::AtlasKind::Mono,
630 layer: 0,
631 x: 1,
632 y: 1,
633 width: 8,
634 height: 8,
635 origin: (0, 0),
636 };
637 for i in 0..1000 {
638 let b = bounds(i as f32, 0.0, 10.0, 10.0);
639 scene.push_quad(&Quad::filled(b, rgb(0x223344)).radii(4.0), &state);
640 scene.push_mono_sprite(b, &tile, Color::WHITE, &state);
641 }
642 assert_eq!(scene.len(), 2000);
643 assert_eq!(
644 scene.stats().draw_calls,
645 1,
646 "thousands of primitives, one draw call"
647 );
648 }
649
650 #[test]
651 fn backdrop_splits_runs() {
652 let mut scene = Scene::new();
653 let state = DrawState::default();
654 scene.push_quad(
655 &Quad::filled(bounds(0.0, 0.0, 10.0, 10.0), rgb(0x112233)),
656 &state,
657 );
658 scene.push_backdrop_blur(
659 bounds(0.0, 0.0, 10.0, 10.0),
660 Corners::all(4.0),
661 12.0,
662 Color::TRANSPARENT,
663 &state,
664 );
665 scene.push_quad(
666 &Quad::filled(bounds(0.0, 0.0, 5.0, 5.0), rgb(0x112233)),
667 &state,
668 );
669 let ops = scene.ops();
670 assert_eq!(
671 ops,
672 vec![
673 Op::Draw {
674 instances: 0..1,
675 shader: None
676 },
677 Op::Effect(Effect::CaptureBackdrop { blur: 12.0 }),
678 Op::Draw {
679 instances: 1..3,
680 shader: None
681 },
682 ]
683 );
684 assert_eq!(scene.stats().draw_calls, 2);
685 }
686
687 #[test]
688 fn layers_and_custom_shaders_split_runs() {
689 let mut scene = Scene::new();
690 let state = DrawState::default();
691 let quad = Quad::filled(bounds(0.0, 0.0, 10.0, 10.0), rgb(0x112233));
692 let shader = ShaderId::from_raw(0);
693 scene.push_quad(&quad, &state);
694 scene.push_layer();
695 scene.push_quad(&quad, &state);
696 scene.push_quad(&quad, &state);
697 scene.pop_layer(
698 bounds(0.0, 0.0, 10.0, 10.0),
699 LayerMask::LinearGradient {
700 angle: 180.0,
701 from: 1.0,
702 to: 0.0,
703 start: 0.0,
704 end: 1.0,
705 },
706 &state,
707 );
708 scene.push_custom(
709 shader,
710 bounds(0.0, 0.0, 4.0, 4.0),
711 Corners::ZERO,
712 [0.0; 8],
713 0.0,
714 Color::WHITE,
715 1.0,
716 &state,
717 );
718 scene.push_custom(
719 shader,
720 bounds(4.0, 0.0, 4.0, 4.0),
721 Corners::ZERO,
722 [0.0; 8],
723 0.0,
724 Color::WHITE,
725 1.0,
726 &state,
727 );
728 scene.push_quad(&quad, &state);
729 assert_eq!(scene.layer_depth(), 0);
730 assert_eq!(
731 scene.ops(),
732 vec![
733 Op::Draw {
734 instances: 0..1,
735 shader: None
736 },
737 Op::PushLayer,
738 Op::Draw {
739 instances: 1..3,
740 shader: None
741 },
742 Op::PopLayer { composite: Some(3) },
743 Op::Draw {
744 instances: 4..6,
745 shader: Some(shader)
746 },
747 Op::Draw {
748 instances: 6..7,
749 shader: None
750 },
751 ]
752 );
753 }
754
755 #[test]
756 fn instance_layout_is_stable() {
757 assert_eq!(std::mem::size_of::<Instance>(), 160);
758 }
759}