1use std::mem::size_of;
2use std::rc::Rc;
3
4use cranpose_core::NodeId;
5use cranpose_foundation::PointerEvent;
6use cranpose_ui::text::AnnotatedString;
7use cranpose_ui::{
8 GraphicsLayer, Point, Rect, RenderEffect, RoundedCornerShape, TextLayoutOptions, TextStyle,
9};
10use cranpose_ui_graphics::{BlendMode, ColorFilter, DrawPrimitive, ShadowPrimitive};
11
12use crate::raster_cache::LayerRasterCacheHashes;
13
14#[derive(Clone, Copy, Debug, PartialEq)]
15pub struct ProjectiveTransform {
16 matrix: [[f32; 3]; 3],
17}
18
19impl ProjectiveTransform {
20 pub const fn identity() -> Self {
21 Self {
22 matrix: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
23 }
24 }
25
26 pub fn translation(tx: f32, ty: f32) -> Self {
27 Self {
28 matrix: [[1.0, 0.0, tx], [0.0, 1.0, ty], [0.0, 0.0, 1.0]],
29 }
30 }
31
32 pub fn from_rect_to_quad(rect: Rect, quad: [[f32; 2]; 4]) -> Self {
33 if rect.width.abs() <= f32::EPSILON || rect.height.abs() <= f32::EPSILON {
34 return Self::translation(quad[0][0], quad[0][1]);
35 }
36
37 if let Some(axis_aligned) = axis_aligned_rect_from_quad(quad) {
38 let scale_x = axis_aligned.width / rect.width;
39 let scale_y = axis_aligned.height / rect.height;
40 return Self {
41 matrix: [
42 [scale_x, 0.0, axis_aligned.x - rect.x * scale_x],
43 [0.0, scale_y, axis_aligned.y - rect.y * scale_y],
44 [0.0, 0.0, 1.0],
45 ],
46 };
47 }
48
49 let source = [
50 [rect.x, rect.y],
51 [rect.x + rect.width, rect.y],
52 [rect.x, rect.y + rect.height],
53 [rect.x + rect.width, rect.y + rect.height],
54 ];
55 let Some(coefficients) = solve_homography(source, quad) else {
56 return Self::identity();
57 };
58
59 Self {
60 matrix: [
61 [coefficients[0], coefficients[1], coefficients[2]],
62 [coefficients[3], coefficients[4], coefficients[5]],
63 [coefficients[6], coefficients[7], 1.0],
64 ],
65 }
66 }
67
68 pub fn then(self, next: Self) -> Self {
70 Self {
71 matrix: multiply_matrices(next.matrix, self.matrix),
72 }
73 }
74
75 pub fn inverse(self) -> Option<Self> {
76 let m = self.matrix;
77 let a = m[0][0];
78 let b = m[0][1];
79 let c = m[0][2];
80 let d = m[1][0];
81 let e = m[1][1];
82 let f = m[1][2];
83 let g = m[2][0];
84 let h = m[2][1];
85 let i = m[2][2];
86
87 let cofactor00 = e * i - f * h;
88 let cofactor01 = -(d * i - f * g);
89 let cofactor02 = d * h - e * g;
90 let cofactor10 = -(b * i - c * h);
91 let cofactor11 = a * i - c * g;
92 let cofactor12 = -(a * h - b * g);
93 let cofactor20 = b * f - c * e;
94 let cofactor21 = -(a * f - c * d);
95 let cofactor22 = a * e - b * d;
96
97 let determinant = a * cofactor00 + b * cofactor01 + c * cofactor02;
98 if determinant.abs() <= f32::EPSILON {
99 return None;
100 }
101 let inverse_determinant = 1.0 / determinant;
102
103 Some(Self {
104 matrix: [
105 [
106 cofactor00 * inverse_determinant,
107 cofactor10 * inverse_determinant,
108 cofactor20 * inverse_determinant,
109 ],
110 [
111 cofactor01 * inverse_determinant,
112 cofactor11 * inverse_determinant,
113 cofactor21 * inverse_determinant,
114 ],
115 [
116 cofactor02 * inverse_determinant,
117 cofactor12 * inverse_determinant,
118 cofactor22 * inverse_determinant,
119 ],
120 ],
121 })
122 }
123
124 pub fn matrix(self) -> [[f32; 3]; 3] {
125 self.matrix
126 }
127
128 pub fn map_point(self, point: Point) -> Point {
129 let x = point.x;
130 let y = point.y;
131 let w = self.matrix[2][0] * x + self.matrix[2][1] * y + self.matrix[2][2];
132 let safe_w = if w.abs() <= f32::EPSILON { 1.0 } else { w };
133
134 Point {
135 x: (self.matrix[0][0] * x + self.matrix[0][1] * y + self.matrix[0][2]) / safe_w,
136 y: (self.matrix[1][0] * x + self.matrix[1][1] * y + self.matrix[1][2]) / safe_w,
137 }
138 }
139
140 pub fn map_rect(self, rect: Rect) -> [[f32; 2]; 4] {
141 [
142 self.map_point(Point {
143 x: rect.x,
144 y: rect.y,
145 }),
146 self.map_point(Point {
147 x: rect.x + rect.width,
148 y: rect.y,
149 }),
150 self.map_point(Point {
151 x: rect.x,
152 y: rect.y + rect.height,
153 }),
154 self.map_point(Point {
155 x: rect.x + rect.width,
156 y: rect.y + rect.height,
157 }),
158 ]
159 .map(|point| [point.x, point.y])
160 }
161
162 pub fn bounds_for_rect(self, rect: Rect) -> Rect {
163 quad_bounds(self.map_rect(rect))
164 }
165}
166
167fn axis_aligned_rect_from_quad(quad: [[f32; 2]; 4]) -> Option<Rect> {
168 let top_left = quad[0];
169 let top_right = quad[1];
170 let bottom_left = quad[2];
171 let bottom_right = quad[3];
172 let x_epsilon = 1e-4;
173 let y_epsilon = 1e-4;
174
175 if (top_left[1] - top_right[1]).abs() > y_epsilon
176 || (bottom_left[1] - bottom_right[1]).abs() > y_epsilon
177 || (top_left[0] - bottom_left[0]).abs() > x_epsilon
178 || (top_right[0] - bottom_right[0]).abs() > x_epsilon
179 {
180 return None;
181 }
182
183 Some(Rect {
184 x: top_left[0],
185 y: top_left[1],
186 width: top_right[0] - top_left[0],
187 height: bottom_left[1] - top_left[1],
188 })
189}
190
191impl Default for ProjectiveTransform {
192 fn default() -> Self {
193 Self::identity()
194 }
195}
196
197#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
198pub struct IsolationReasons {
199 pub explicit_offscreen: bool,
200 pub effect: bool,
201 pub backdrop: bool,
202 pub group_opacity: bool,
203 pub blend_mode: bool,
204}
205
206impl IsolationReasons {
207 pub fn has_any(self) -> bool {
208 self.explicit_offscreen
209 || self.effect
210 || self.backdrop
211 || self.group_opacity
212 || self.blend_mode
213 }
214}
215
216#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
217pub enum CachePolicy {
218 #[default]
219 None,
220 Auto,
221}
222
223#[derive(Clone)]
224pub struct HitTestNode {
225 pub shape: Option<RoundedCornerShape>,
226 pub click_actions: Vec<Rc<dyn Fn(Point)>>,
227 pub pointer_inputs: Vec<Rc<dyn Fn(PointerEvent)>>,
228 pub clip: Option<Rect>,
229}
230
231#[derive(Clone, Debug, PartialEq)]
232pub struct DrawPrimitiveNode {
233 pub primitive: DrawPrimitive,
234 pub clip: Option<Rect>,
235}
236
237#[derive(Clone, Debug, PartialEq)]
238pub struct TextPrimitiveNode {
239 pub node_id: NodeId,
240 pub rect: Rect,
241 pub text: AnnotatedString,
242 pub text_style: TextStyle,
243 pub font_size: f32,
244 pub layout_options: TextLayoutOptions,
245 pub clip: Option<Rect>,
246}
247
248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
249pub enum PrimitivePhase {
250 BeforeChildren,
251 AfterChildren,
252}
253
254#[derive(Clone, Debug, PartialEq)]
255pub enum PrimitiveNode {
256 Draw(DrawPrimitiveNode),
257 Text(Box<TextPrimitiveNode>),
258}
259
260#[derive(Clone, Debug, PartialEq)]
261pub struct PrimitiveEntry {
262 pub phase: PrimitivePhase,
263 pub node: PrimitiveNode,
264}
265
266#[derive(Clone)]
267pub struct LayerNode {
268 pub node_id: Option<NodeId>,
269 pub local_bounds: Rect,
270 pub transform_to_parent: ProjectiveTransform,
271 pub motion_context_animated: bool,
272 pub translated_content_context: bool,
273 pub graphics_layer: GraphicsLayer,
274 pub clip_to_bounds: bool,
275 pub shadow_clip: Option<Rect>,
276 pub hit_test: Option<HitTestNode>,
277 pub has_hit_targets: bool,
278 pub isolation: IsolationReasons,
279 pub cache_policy: CachePolicy,
280 pub cache_hashes: LayerRasterCacheHashes,
281 pub cache_hashes_valid: bool,
282 pub children: Vec<RenderNode>,
283}
284
285impl LayerNode {
286 pub fn clip_rect(&self) -> Option<Rect> {
287 (self.clip_to_bounds || self.graphics_layer.clip).then_some(self.local_bounds)
288 }
289
290 pub fn effect(&self) -> Option<&RenderEffect> {
291 self.graphics_layer.render_effect.as_ref()
292 }
293
294 pub fn backdrop(&self) -> Option<&RenderEffect> {
295 self.graphics_layer.backdrop_effect.as_ref()
296 }
297
298 pub fn opacity(&self) -> f32 {
299 self.graphics_layer.alpha
300 }
301
302 pub fn blend_mode(&self) -> BlendMode {
303 self.graphics_layer.blend_mode
304 }
305
306 pub fn color_filter(&self) -> Option<ColorFilter> {
307 self.graphics_layer.color_filter
308 }
309
310 pub fn target_content_hash(&self) -> u64 {
311 if self.cache_hashes_valid {
312 self.cache_hashes.target_content
313 } else {
314 crate::graph_hash::layer_raster_cache_hashes(self).target_content
315 }
316 }
317
318 pub fn effect_hash(&self) -> u64 {
319 if self.cache_hashes_valid {
320 self.cache_hashes.effect
321 } else {
322 crate::graph_hash::layer_raster_cache_hashes(self).effect
323 }
324 }
325
326 pub fn recompute_raster_cache_hashes(&mut self) {
327 crate::graph_hash::recompute_layer_raster_cache_hashes(self);
328 }
329}
330
331#[derive(Clone)]
332pub enum RenderNode {
333 Primitive(PrimitiveEntry),
334 Layer(Box<LayerNode>),
335}
336
337#[derive(Clone)]
338pub struct RenderGraph {
339 pub root: LayerNode,
340}
341
342impl RenderGraph {
343 pub fn new(mut root: LayerNode) -> Self {
344 root.recompute_raster_cache_hashes();
345 Self { root }
346 }
347
348 pub fn node_count(&self) -> usize {
349 fn count_layer(layer: &LayerNode) -> usize {
350 1 + layer
351 .children
352 .iter()
353 .map(|child| match child {
354 RenderNode::Primitive(_) => 1,
355 RenderNode::Layer(child_layer) => count_layer(child_layer),
356 })
357 .sum::<usize>()
358 }
359
360 count_layer(&self.root)
361 }
362
363 pub fn heap_bytes(&self) -> usize {
364 layer_heap_bytes(&self.root)
365 }
366}
367
368fn layer_heap_bytes(layer: &LayerNode) -> usize {
369 layer.hit_test.as_ref().map_or(0, hit_test_heap_bytes)
370 + size_of::<RenderNode>() * layer.children.capacity()
371 + layer
372 .children
373 .iter()
374 .map(render_node_heap_bytes)
375 .sum::<usize>()
376}
377
378fn render_node_heap_bytes(node: &RenderNode) -> usize {
379 match node {
380 RenderNode::Primitive(entry) => primitive_entry_heap_bytes(entry),
381 RenderNode::Layer(layer) => size_of::<LayerNode>() + layer_heap_bytes(layer),
382 }
383}
384
385fn primitive_entry_heap_bytes(entry: &PrimitiveEntry) -> usize {
386 match &entry.node {
387 PrimitiveNode::Draw(draw) => draw_primitive_heap_bytes(&draw.primitive),
388 PrimitiveNode::Text(text) => {
389 size_of::<TextPrimitiveNode>() + annotated_string_heap_bytes(&text.text)
390 }
391 }
392}
393
394fn draw_primitive_heap_bytes(primitive: &DrawPrimitive) -> usize {
395 match primitive {
396 DrawPrimitive::Content | DrawPrimitive::Rect { .. } | DrawPrimitive::RoundRect { .. } => 0,
397 DrawPrimitive::Blend { primitive, .. } => {
398 size_of::<DrawPrimitive>() + draw_primitive_heap_bytes(primitive)
399 }
400 DrawPrimitive::Image { .. } => 0,
401 DrawPrimitive::Shadow(shadow) => shadow_primitive_heap_bytes(shadow),
402 }
403}
404
405fn shadow_primitive_heap_bytes(shadow: &ShadowPrimitive) -> usize {
406 match shadow {
407 ShadowPrimitive::Drop { shape, .. } => {
408 size_of::<DrawPrimitive>() + draw_primitive_heap_bytes(shape)
409 }
410 ShadowPrimitive::Inner { fill, cutout, .. } => {
411 size_of::<DrawPrimitive>() * 2
412 + draw_primitive_heap_bytes(fill)
413 + draw_primitive_heap_bytes(cutout)
414 }
415 }
416}
417
418fn annotated_string_heap_bytes(text: &AnnotatedString) -> usize {
419 text.text.capacity()
420 + text.span_styles.capacity() * size_of::<usize>() * 2
421 + text.paragraph_styles.capacity() * size_of::<usize>() * 2
422 + text.string_annotations.capacity() * size_of::<usize>() * 2
423 + text.link_annotations.capacity() * size_of::<usize>() * 2
424 + text
425 .string_annotations
426 .iter()
427 .map(|annotation| {
428 annotation.item.tag.capacity() + annotation.item.annotation.capacity()
429 })
430 .sum::<usize>()
431 + text
432 .link_annotations
433 .iter()
434 .map(|annotation| match &annotation.item {
435 cranpose_ui::text::LinkAnnotation::Url(url) => url.capacity(),
436 cranpose_ui::text::LinkAnnotation::Clickable { tag, .. } => tag.capacity(),
437 })
438 .sum::<usize>()
439}
440
441fn hit_test_heap_bytes(hit_test: &HitTestNode) -> usize {
442 hit_test.click_actions.capacity() * size_of::<Rc<dyn Fn(Point)>>()
443 + hit_test.pointer_inputs.capacity() * size_of::<Rc<dyn Fn(PointerEvent)>>()
444}
445
446pub fn quad_bounds(quad: [[f32; 2]; 4]) -> Rect {
447 let mut min_x = f32::INFINITY;
448 let mut min_y = f32::INFINITY;
449 let mut max_x = f32::NEG_INFINITY;
450 let mut max_y = f32::NEG_INFINITY;
451
452 for [x, y] in quad {
453 min_x = min_x.min(x);
454 min_y = min_y.min(y);
455 max_x = max_x.max(x);
456 max_y = max_y.max(y);
457 }
458
459 Rect {
460 x: min_x,
461 y: min_y,
462 width: (max_x - min_x).max(0.0),
463 height: (max_y - min_y).max(0.0),
464 }
465}
466
467fn multiply_matrices(lhs: [[f32; 3]; 3], rhs: [[f32; 3]; 3]) -> [[f32; 3]; 3] {
468 let mut out = [[0.0; 3]; 3];
469 for row in 0..3 {
470 for col in 0..3 {
471 out[row][col] =
472 lhs[row][0] * rhs[0][col] + lhs[row][1] * rhs[1][col] + lhs[row][2] * rhs[2][col];
473 }
474 }
475 out
476}
477
478fn solve_homography(source: [[f32; 2]; 4], target: [[f32; 2]; 4]) -> Option<[f32; 8]> {
479 let mut matrix = [[0.0f32; 9]; 8];
480 for (index, (src, dst)) in source.into_iter().zip(target).enumerate() {
481 let row = index * 2;
482 let x = src[0];
483 let y = src[1];
484 let u = dst[0];
485 let v = dst[1];
486
487 matrix[row] = [x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y, u];
488 matrix[row + 1] = [0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y, v];
489 }
490
491 for pivot in 0..8 {
492 let mut pivot_row = pivot;
493 let mut pivot_value = matrix[pivot][pivot].abs();
494 let mut candidate = pivot + 1;
495 while candidate < 8 {
496 let candidate_value = matrix[candidate][pivot].abs();
497 if candidate_value > pivot_value {
498 pivot_row = candidate;
499 pivot_value = candidate_value;
500 }
501 candidate += 1;
502 }
503
504 if pivot_value <= f32::EPSILON {
505 return None;
506 }
507
508 if pivot_row != pivot {
509 matrix.swap(pivot, pivot_row);
510 }
511
512 let divisor = matrix[pivot][pivot];
513 let mut col = pivot;
514 while col < 9 {
515 matrix[pivot][col] /= divisor;
516 col += 1;
517 }
518
519 for row in 0..8 {
520 if row == pivot {
521 continue;
522 }
523 let factor = matrix[row][pivot];
524 if factor.abs() <= f32::EPSILON {
525 continue;
526 }
527 let mut col = pivot;
528 while col < 9 {
529 matrix[row][col] -= factor * matrix[pivot][col];
530 col += 1;
531 }
532 }
533 }
534
535 let mut solution = [0.0f32; 8];
536 for index in 0..8 {
537 solution[index] = matrix[index][8];
538 }
539 Some(solution)
540}
541
542#[cfg(test)]
543mod tests {
544 use super::*;
545 use crate::raster_cache::LayerRasterCacheHashes;
546 use cranpose_ui_graphics::{Brush, Color, DrawPrimitive};
547
548 fn test_layer(local_bounds: Rect, children: Vec<RenderNode>) -> LayerNode {
549 LayerNode {
550 node_id: None,
551 local_bounds,
552 transform_to_parent: ProjectiveTransform::identity(),
553 motion_context_animated: false,
554 translated_content_context: false,
555 graphics_layer: GraphicsLayer::default(),
556 clip_to_bounds: false,
557 shadow_clip: None,
558 hit_test: None,
559 has_hit_targets: false,
560 isolation: IsolationReasons::default(),
561 cache_policy: CachePolicy::None,
562 cache_hashes: LayerRasterCacheHashes::default(),
563 cache_hashes_valid: false,
564 children,
565 }
566 }
567
568 #[test]
569 fn projective_transform_translation_maps_points() {
570 let transform = ProjectiveTransform::translation(7.0, -3.5);
571 let mapped = transform.map_point(Point { x: 2.0, y: 4.0 });
572 assert!((mapped.x - 9.0).abs() < 1e-6);
573 assert!((mapped.y - 0.5).abs() < 1e-6);
574 }
575
576 #[test]
577 fn projective_transform_then_composes_in_parent_order() {
578 let child = ProjectiveTransform::translation(4.0, 2.0);
579 let parent = ProjectiveTransform::translation(10.0, -1.0);
580 let composed = child.then(parent);
581 let mapped = composed.map_point(Point { x: 1.0, y: 1.0 });
582 assert!((mapped.x - 15.0).abs() < 1e-6);
583 assert!((mapped.y - 2.0).abs() < 1e-6);
584 }
585
586 #[test]
587 fn homography_maps_rect_corners_to_target_quad() {
588 let rect = Rect {
589 x: 0.0,
590 y: 0.0,
591 width: 20.0,
592 height: 10.0,
593 };
594 let quad = [[5.0, 7.0], [25.0, 6.0], [7.0, 20.0], [28.0, 21.0]];
595 let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
596 let mapped = transform.map_rect(rect);
597 for (expected, actual) in quad.into_iter().zip(mapped) {
598 assert!((expected[0] - actual[0]).abs() < 1e-4);
599 assert!((expected[1] - actual[1]).abs() < 1e-4);
600 }
601 }
602
603 #[test]
604 fn axis_aligned_rect_to_quad_keeps_exact_affine_matrix() {
605 let rect = Rect {
606 x: 2.0,
607 y: 3.0,
608 width: 20.0,
609 height: 10.0,
610 };
611 let quad = [[12.0, 9.0], [32.0, 9.0], [12.0, 19.0], [32.0, 19.0]];
612 let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
613
614 assert_eq!(
615 transform.matrix(),
616 [[1.0, 0.0, 10.0], [0.0, 1.0, 6.0], [0.0, 0.0, 1.0]]
617 );
618 }
619
620 #[test]
621 fn axis_aligned_rect_to_quad_keeps_exact_axis_aligned_scale() {
622 let rect = Rect {
623 x: 4.0,
624 y: 6.0,
625 width: 10.0,
626 height: 8.0,
627 };
628 let quad = [[20.0, 18.0], [50.0, 18.0], [20.0, 42.0], [50.0, 42.0]];
629 let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
630
631 assert_eq!(
632 transform.matrix(),
633 [[3.0, 0.0, 8.0], [0.0, 3.0, 0.0], [0.0, 0.0, 1.0]]
634 );
635 }
636
637 #[test]
638 fn render_graph_new_recomputes_manual_layer_hashes() {
639 let primitive = PrimitiveEntry {
640 phase: PrimitivePhase::BeforeChildren,
641 node: PrimitiveNode::Draw(DrawPrimitiveNode {
642 primitive: DrawPrimitive::Rect {
643 rect: Rect {
644 x: 1.0,
645 y: 2.0,
646 width: 8.0,
647 height: 6.0,
648 },
649 brush: Brush::solid(Color::WHITE),
650 },
651 clip: None,
652 }),
653 };
654 let mut root = test_layer(
655 Rect {
656 x: 0.0,
657 y: 0.0,
658 width: 20.0,
659 height: 20.0,
660 },
661 vec![RenderNode::Primitive(primitive)],
662 );
663 root.graphics_layer.render_effect = Some(RenderEffect::blur(3.0));
664 let mut expected = root.clone();
665 expected.recompute_raster_cache_hashes();
666
667 let graph = RenderGraph::new(root);
668 assert_eq!(
669 graph.root.target_content_hash(),
670 expected.target_content_hash()
671 );
672 assert_eq!(graph.root.effect_hash(), expected.effect_hash());
673 }
674}