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 translated_content_offset: Point,
274 pub graphics_layer: GraphicsLayer,
275 pub clip_to_bounds: bool,
276 pub shadow_clip: Option<Rect>,
277 pub hit_test: Option<HitTestNode>,
278 pub has_hit_targets: bool,
279 pub isolation: IsolationReasons,
280 pub cache_policy: CachePolicy,
281 pub cache_hashes: LayerRasterCacheHashes,
282 pub cache_hashes_valid: bool,
283 pub children: Vec<RenderNode>,
284}
285
286impl LayerNode {
287 pub fn clip_rect(&self) -> Option<Rect> {
288 (self.clip_to_bounds || self.graphics_layer.clip).then_some(self.local_bounds)
289 }
290
291 pub fn effect(&self) -> Option<&RenderEffect> {
292 self.graphics_layer.render_effect.as_ref()
293 }
294
295 pub fn backdrop(&self) -> Option<&RenderEffect> {
296 self.graphics_layer.backdrop_effect.as_ref()
297 }
298
299 pub fn opacity(&self) -> f32 {
300 self.graphics_layer.alpha
301 }
302
303 pub fn blend_mode(&self) -> BlendMode {
304 self.graphics_layer.blend_mode
305 }
306
307 pub fn color_filter(&self) -> Option<ColorFilter> {
308 self.graphics_layer.color_filter
309 }
310
311 pub fn target_content_hash(&self) -> u64 {
312 if self.cache_hashes_valid {
313 self.cache_hashes.target_content
314 } else {
315 crate::graph_hash::layer_raster_cache_hashes(self).target_content
316 }
317 }
318
319 pub fn effect_hash(&self) -> u64 {
320 if self.cache_hashes_valid {
321 self.cache_hashes.effect
322 } else {
323 crate::graph_hash::layer_raster_cache_hashes(self).effect
324 }
325 }
326
327 pub fn recompute_raster_cache_hashes(&mut self) {
328 crate::graph_hash::recompute_layer_raster_cache_hashes(self);
329 }
330}
331
332#[derive(Clone)]
333pub enum RenderNode {
334 Primitive(PrimitiveEntry),
335 Layer(Box<LayerNode>),
336}
337
338#[derive(Clone)]
339pub struct RenderGraph {
340 pub root: LayerNode,
341}
342
343impl RenderGraph {
344 pub fn new(mut root: LayerNode) -> Self {
345 root.recompute_raster_cache_hashes();
346 Self { root }
347 }
348
349 pub fn node_count(&self) -> usize {
350 fn count_layer(layer: &LayerNode) -> usize {
351 1 + layer
352 .children
353 .iter()
354 .map(|child| match child {
355 RenderNode::Primitive(_) => 1,
356 RenderNode::Layer(child_layer) => count_layer(child_layer),
357 })
358 .sum::<usize>()
359 }
360
361 count_layer(&self.root)
362 }
363
364 pub fn heap_bytes(&self) -> usize {
365 layer_heap_bytes(&self.root)
366 }
367}
368
369fn layer_heap_bytes(layer: &LayerNode) -> usize {
370 layer.hit_test.as_ref().map_or(0, hit_test_heap_bytes)
371 + size_of::<RenderNode>() * layer.children.capacity()
372 + layer
373 .children
374 .iter()
375 .map(render_node_heap_bytes)
376 .sum::<usize>()
377}
378
379fn render_node_heap_bytes(node: &RenderNode) -> usize {
380 match node {
381 RenderNode::Primitive(entry) => primitive_entry_heap_bytes(entry),
382 RenderNode::Layer(layer) => size_of::<LayerNode>() + layer_heap_bytes(layer),
383 }
384}
385
386fn primitive_entry_heap_bytes(entry: &PrimitiveEntry) -> usize {
387 match &entry.node {
388 PrimitiveNode::Draw(draw) => draw_primitive_heap_bytes(&draw.primitive),
389 PrimitiveNode::Text(text) => {
390 size_of::<TextPrimitiveNode>() + annotated_string_heap_bytes(&text.text)
391 }
392 }
393}
394
395fn draw_primitive_heap_bytes(primitive: &DrawPrimitive) -> usize {
396 match primitive {
397 DrawPrimitive::Content | DrawPrimitive::Rect { .. } | DrawPrimitive::RoundRect { .. } => 0,
398 DrawPrimitive::Blend { primitive, .. } => {
399 size_of::<DrawPrimitive>() + draw_primitive_heap_bytes(primitive)
400 }
401 DrawPrimitive::Image { .. } => 0,
402 DrawPrimitive::Shadow(shadow) => shadow_primitive_heap_bytes(shadow),
403 }
404}
405
406fn shadow_primitive_heap_bytes(shadow: &ShadowPrimitive) -> usize {
407 match shadow {
408 ShadowPrimitive::Drop { shape, .. } => {
409 size_of::<DrawPrimitive>() + draw_primitive_heap_bytes(shape)
410 }
411 ShadowPrimitive::Inner { fill, cutout, .. } => {
412 size_of::<DrawPrimitive>() * 2
413 + draw_primitive_heap_bytes(fill)
414 + draw_primitive_heap_bytes(cutout)
415 }
416 }
417}
418
419fn annotated_string_heap_bytes(text: &AnnotatedString) -> usize {
420 text.text.capacity()
421 + text.span_styles.capacity() * size_of::<usize>() * 2
422 + text.paragraph_styles.capacity() * size_of::<usize>() * 2
423 + text.string_annotations.capacity() * size_of::<usize>() * 2
424 + text.link_annotations.capacity() * size_of::<usize>() * 2
425 + text
426 .string_annotations
427 .iter()
428 .map(|annotation| {
429 annotation.item.tag.capacity() + annotation.item.annotation.capacity()
430 })
431 .sum::<usize>()
432 + text
433 .link_annotations
434 .iter()
435 .map(|annotation| match &annotation.item {
436 cranpose_ui::text::LinkAnnotation::Url(url) => url.capacity(),
437 cranpose_ui::text::LinkAnnotation::Clickable { tag, .. } => tag.capacity(),
438 })
439 .sum::<usize>()
440}
441
442fn hit_test_heap_bytes(hit_test: &HitTestNode) -> usize {
443 hit_test.click_actions.capacity() * size_of::<Rc<dyn Fn(Point)>>()
444 + hit_test.pointer_inputs.capacity() * size_of::<Rc<dyn Fn(PointerEvent)>>()
445}
446
447pub fn quad_bounds(quad: [[f32; 2]; 4]) -> Rect {
448 let mut min_x = f32::INFINITY;
449 let mut min_y = f32::INFINITY;
450 let mut max_x = f32::NEG_INFINITY;
451 let mut max_y = f32::NEG_INFINITY;
452
453 for [x, y] in quad {
454 min_x = min_x.min(x);
455 min_y = min_y.min(y);
456 max_x = max_x.max(x);
457 max_y = max_y.max(y);
458 }
459
460 Rect {
461 x: min_x,
462 y: min_y,
463 width: (max_x - min_x).max(0.0),
464 height: (max_y - min_y).max(0.0),
465 }
466}
467
468fn multiply_matrices(lhs: [[f32; 3]; 3], rhs: [[f32; 3]; 3]) -> [[f32; 3]; 3] {
469 let mut out = [[0.0; 3]; 3];
470 for row in 0..3 {
471 for col in 0..3 {
472 out[row][col] =
473 lhs[row][0] * rhs[0][col] + lhs[row][1] * rhs[1][col] + lhs[row][2] * rhs[2][col];
474 }
475 }
476 out
477}
478
479fn solve_homography(source: [[f32; 2]; 4], target: [[f32; 2]; 4]) -> Option<[f32; 8]> {
480 let mut matrix = [[0.0f32; 9]; 8];
481 for (index, (src, dst)) in source.into_iter().zip(target).enumerate() {
482 let row = index * 2;
483 let x = src[0];
484 let y = src[1];
485 let u = dst[0];
486 let v = dst[1];
487
488 matrix[row] = [x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y, u];
489 matrix[row + 1] = [0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y, v];
490 }
491
492 for pivot in 0..8 {
493 let mut pivot_row = pivot;
494 let mut pivot_value = matrix[pivot][pivot].abs();
495 let mut candidate = pivot + 1;
496 while candidate < 8 {
497 let candidate_value = matrix[candidate][pivot].abs();
498 if candidate_value > pivot_value {
499 pivot_row = candidate;
500 pivot_value = candidate_value;
501 }
502 candidate += 1;
503 }
504
505 if pivot_value <= f32::EPSILON {
506 return None;
507 }
508
509 if pivot_row != pivot {
510 matrix.swap(pivot, pivot_row);
511 }
512
513 let divisor = matrix[pivot][pivot];
514 let mut col = pivot;
515 while col < 9 {
516 matrix[pivot][col] /= divisor;
517 col += 1;
518 }
519
520 for row in 0..8 {
521 if row == pivot {
522 continue;
523 }
524 let factor = matrix[row][pivot];
525 if factor.abs() <= f32::EPSILON {
526 continue;
527 }
528 let mut col = pivot;
529 while col < 9 {
530 matrix[row][col] -= factor * matrix[pivot][col];
531 col += 1;
532 }
533 }
534 }
535
536 let mut solution = [0.0f32; 8];
537 for index in 0..8 {
538 solution[index] = matrix[index][8];
539 }
540 Some(solution)
541}
542
543#[cfg(test)]
544mod tests {
545 use super::*;
546 use crate::raster_cache::LayerRasterCacheHashes;
547 use cranpose_ui_graphics::{Brush, Color, DrawPrimitive};
548
549 fn test_layer(local_bounds: Rect, children: Vec<RenderNode>) -> LayerNode {
550 LayerNode {
551 node_id: None,
552 local_bounds,
553 transform_to_parent: ProjectiveTransform::identity(),
554 motion_context_animated: false,
555 translated_content_context: false,
556 translated_content_offset: Point::default(),
557 graphics_layer: GraphicsLayer::default(),
558 clip_to_bounds: false,
559 shadow_clip: None,
560 hit_test: None,
561 has_hit_targets: false,
562 isolation: IsolationReasons::default(),
563 cache_policy: CachePolicy::None,
564 cache_hashes: LayerRasterCacheHashes::default(),
565 cache_hashes_valid: false,
566 children,
567 }
568 }
569
570 #[test]
571 fn projective_transform_translation_maps_points() {
572 let transform = ProjectiveTransform::translation(7.0, -3.5);
573 let mapped = transform.map_point(Point { x: 2.0, y: 4.0 });
574 assert!((mapped.x - 9.0).abs() < 1e-6);
575 assert!((mapped.y - 0.5).abs() < 1e-6);
576 }
577
578 #[test]
579 fn projective_transform_then_composes_in_parent_order() {
580 let child = ProjectiveTransform::translation(4.0, 2.0);
581 let parent = ProjectiveTransform::translation(10.0, -1.0);
582 let composed = child.then(parent);
583 let mapped = composed.map_point(Point { x: 1.0, y: 1.0 });
584 assert!((mapped.x - 15.0).abs() < 1e-6);
585 assert!((mapped.y - 2.0).abs() < 1e-6);
586 }
587
588 #[test]
589 fn homography_maps_rect_corners_to_target_quad() {
590 let rect = Rect {
591 x: 0.0,
592 y: 0.0,
593 width: 20.0,
594 height: 10.0,
595 };
596 let quad = [[5.0, 7.0], [25.0, 6.0], [7.0, 20.0], [28.0, 21.0]];
597 let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
598 let mapped = transform.map_rect(rect);
599 for (expected, actual) in quad.into_iter().zip(mapped) {
600 assert!((expected[0] - actual[0]).abs() < 1e-4);
601 assert!((expected[1] - actual[1]).abs() < 1e-4);
602 }
603 }
604
605 #[test]
606 fn axis_aligned_rect_to_quad_keeps_exact_affine_matrix() {
607 let rect = Rect {
608 x: 2.0,
609 y: 3.0,
610 width: 20.0,
611 height: 10.0,
612 };
613 let quad = [[12.0, 9.0], [32.0, 9.0], [12.0, 19.0], [32.0, 19.0]];
614 let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
615
616 assert_eq!(
617 transform.matrix(),
618 [[1.0, 0.0, 10.0], [0.0, 1.0, 6.0], [0.0, 0.0, 1.0]]
619 );
620 }
621
622 #[test]
623 fn axis_aligned_rect_to_quad_keeps_exact_axis_aligned_scale() {
624 let rect = Rect {
625 x: 4.0,
626 y: 6.0,
627 width: 10.0,
628 height: 8.0,
629 };
630 let quad = [[20.0, 18.0], [50.0, 18.0], [20.0, 42.0], [50.0, 42.0]];
631 let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
632
633 assert_eq!(
634 transform.matrix(),
635 [[3.0, 0.0, 8.0], [0.0, 3.0, 0.0], [0.0, 0.0, 1.0]]
636 );
637 }
638
639 #[test]
640 fn render_graph_new_recomputes_manual_layer_hashes() {
641 let primitive = PrimitiveEntry {
642 phase: PrimitivePhase::BeforeChildren,
643 node: PrimitiveNode::Draw(DrawPrimitiveNode {
644 primitive: DrawPrimitive::Rect {
645 rect: Rect {
646 x: 1.0,
647 y: 2.0,
648 width: 8.0,
649 height: 6.0,
650 },
651 brush: Brush::solid(Color::WHITE),
652 },
653 clip: None,
654 }),
655 };
656 let mut root = test_layer(
657 Rect {
658 x: 0.0,
659 y: 0.0,
660 width: 20.0,
661 height: 20.0,
662 },
663 vec![RenderNode::Primitive(primitive)],
664 );
665 root.graphics_layer.render_effect = Some(RenderEffect::blur(3.0));
666 let mut expected = root.clone();
667 expected.recompute_raster_cache_hashes();
668
669 let graph = RenderGraph::new(root);
670 assert_eq!(
671 graph.root.target_content_hash(),
672 expected.target_content_hash()
673 );
674 assert_eq!(graph.root.effect_hash(), expected.effect_hash());
675 }
676}