cranpose_render_common/graph.rs
1use std::{ops::Range, rc::Rc};
2
3use cranpose_core::NodeId;
4use cranpose_ui::{
5 GraphicsLayer, ModifierNodeSlices, Rect, TextOverflow, TextStyle, text::RenderString,
6};
7pub use cranpose_ui_graphics::transform::{FrontPolygon, ProjectiveTransform, quad_bounds};
8use cranpose_ui_graphics::{CommandRecording, DrawPlacement, DrawPrimitive, RecordingSummary};
9
10use crate::{
11 glyph_reach::glyph_bounds,
12 text_paint::{TextPaint, TextPaintCache},
13};
14
15#[cfg(feature = "layer-tree")]
16mod inline_node;
17#[cfg(feature = "layer-tree")]
18mod layer_node;
19#[cfg(feature = "layer-tree")]
20mod layer_properties;
21#[cfg(feature = "layer-tree")]
22pub use inline_node::InlineNode;
23#[cfg(feature = "layer-tree")]
24pub use layer_node::{LayerNode, PrimitiveEntry, RenderNode, for_each_in_draw_order};
25#[cfg(feature = "layer-tree")]
26pub use layer_properties::LayerProperties;
27
28/// Reasons a layer is drawn into its own offscreen buffer instead of directly into its parent.
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub struct IsolationReasons {
31 /// The layer asked for offscreen compositing.
32 pub explicit_offscreen: bool,
33 /// The layer clips to a shape that is not a rectangle.
34 pub shape_clip: bool,
35 /// The layer applies a render effect to its content.
36 pub effect: bool,
37 /// The layer applies an effect to what lies behind it.
38 pub backdrop: bool,
39 /// The layer's alpha is below one and must apply to its content as a group.
40 pub group_opacity: bool,
41 /// The layer uses a blend mode other than source-over.
42 pub blend_mode: bool,
43}
44
45impl IsolationReasons {
46 /// Whether at least one reason requires the layer to be isolated.
47 pub fn has_any(self) -> bool {
48 self.explicit_offscreen
49 || self.shape_clip
50 || self.effect
51 || self.backdrop
52 || self.group_opacity
53 || self.blend_mode
54 }
55}
56
57// Whether graphics layers `a` and `b` read alike, `None` reading as the
58// default.
59#[inline]
60pub(crate) fn graphics_layers_read_alike(
61 a: Option<&GraphicsLayer>,
62 b: Option<&GraphicsLayer>,
63) -> bool {
64 match (a, b) {
65 (None, None) => true,
66 (a, b) => a.unwrap_or(&GraphicsLayer::DEFAULT) == b.unwrap_or(&GraphicsLayer::DEFAULT),
67 }
68}
69
70/// Whether a renderer may keep the rasterized pixels of a layer between frames.
71#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
72pub enum CachePolicy {
73 /// The layer is drawn directly each frame.
74 #[default]
75 None,
76 /// The layer is a candidate for a raster cache because it is isolated, scaled or rotated.
77 Auto,
78}
79
80/// Pointer handling attached to a layer.
81#[derive(Clone)]
82pub struct HitTestNode {
83 /// The node's modifier slices, shared rather than copied: they hold its
84 /// pointer inputs and the pointer icon it asks for while hovered. A node
85 /// that only names an icon is still a hit target, which is how a
86 /// decorative panel carries a cursor without handling clicks.
87 pub handlers: Rc<ModifierNodeSlices>,
88}
89
90/// One draw primitive together with its clip.
91#[derive(Clone, Debug, PartialEq)]
92pub struct DrawPrimitiveNode {
93 /// The shape, image or other primitive to draw.
94 pub primitive: DrawPrimitive,
95 /// Rectangle that cuts the primitive, or `None` when it is not clipped.
96 pub clip: Option<Rect>,
97}
98
99/// A run of text to draw, with the layout facts that a renderer needs.
100#[derive(Clone, Debug, PartialEq)]
101pub struct TextPrimitiveNode {
102 /// Layout node that owns the text.
103 pub node_id: NodeId,
104 /// Box of the laid-out text in logical pixels, after alignment and panning.
105 pub rect: Rect,
106 /// The string and its spans, as the renderer's draws carry them across
107 /// threads, shared with the prepared layout it came from so no frame
108 /// converts or copies it.
109 pub render_text: std::sync::Arc<RenderString>,
110 /// The lines and glyphs the text draws, from its top left corner at
111 /// `rect`'s.
112 pub layout: cranpose_text::TextLayout,
113 /// Shared so every frame's draws of this text hand over the same style
114 /// instead of copying it.
115 pub text_style: std::sync::Arc<TextStyle>,
116 /// Resolved font size in logical pixels.
117 pub font_size: f32,
118 /// How the text was laid out to handle text that does not fit.
119 pub overflow: TextOverflow,
120 /// Rectangle that cuts the glyphs: the node's box when the layout overflows it and overflow
121 /// is not visible, or when the text pans; `None` otherwise, as Compose cuts a text.
122 pub clip: Option<Rect>,
123 /// What a renderer reads of `text_style` and `render_text`'s spans to draw the
124 /// glyphs, so that drawing a plain text does not load the style.
125 pub paint: TextPaintCache,
126}
127
128impl TextPrimitiveNode {
129 /// The paint of the node's glyphs.
130 pub fn paint(&self) -> &TextPaint {
131 self.paint.get_or(|| {
132 TextPaint::of(
133 &self.text_style,
134 self.text_style.render_hash(),
135 self.render_text.span_styles(),
136 (self.font_size, &self.layout),
137 )
138 })
139 }
140
141 /// Conservative bounds for the emitted glyphs and paint: the clip, or
142 /// the layout rectangle and wherever the ink of a glyph, a stroke's
143 /// included, reaches past it. Returns `None` when an unclipped layout or
144 /// style can draw beyond both: a visible overflow, a shadow of the style
145 /// or a span, or a baseline shift.
146 pub fn draw_bounds(&self) -> Option<Rect> {
147 if let Some(clip) = self.clip {
148 return Some(clip);
149 }
150 if matches!(self.overflow, TextOverflow::Visible) {
151 return None;
152 }
153 // The paint, kept in the node, tells this without loading the style.
154 let paint = self.paint();
155 (!paint.casts_shadow && paint.baseline_shift == 0.0)
156 .then(|| glyph_bounds(self.rect, &self.layout, paint.spread))
157 }
158
159 #[cfg(feature = "window-damage")]
160 pub(crate) fn draws_within(&self, bounds: Rect) -> bool {
161 self.draw_bounds()
162 .is_some_and(|drawn| rect_within(drawn, bounds))
163 }
164}
165
166/// Whether a primitive draws before or after the children of its layer.
167#[derive(Clone, Copy, Debug, PartialEq, Eq)]
168pub enum PrimitivePhase {
169 /// Drawn under the children, like a background.
170 BeforeChildren,
171 /// Drawn over the children, like a foreground or overlay.
172 AfterChildren,
173}
174
175/// A draw or a text that a layer draws.
176#[derive(Clone, Debug, PartialEq)]
177pub enum PrimitiveNode {
178 /// A draw primitive with its clip.
179 Draw(Box<DrawPrimitiveNode>),
180 /// A text run.
181 Text(Box<TextPrimitiveNode>),
182}
183
184/// How far past its bounds a layer that draws within them may still put
185/// pixels: glyph and edge antialiasing.
186pub const CONTAINED_DRAW_SLACK: f32 = 1.0;
187
188/// Stable identity of one placement of a draw command: its layout node,
189/// command index and placement pass. A `WithContent` command shares one CPU
190/// recording between its two runs, while each placement retains independent
191/// renderer state under this identity.
192#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
193pub struct DrawCommandId {
194 /// Layout node that owns the draw command.
195 pub node_id: NodeId,
196 /// Index of the command among the draw commands of the node.
197 pub command_index: u32,
198 /// Whether the command draws behind the node's content or over it.
199 pub placement: DrawPlacement,
200}
201
202/// A run of recorded draw primitives from one draw command, kept together as one node.
203#[derive(Clone, Debug, PartialEq)]
204pub struct DrawRunNode {
205 /// Whether the run draws before or after the children of its layer.
206 pub phase: PrimitivePhase,
207 /// Which draw command recorded these primitives. `None` only for runs
208 /// with no per-command provenance (hand-built tests).
209 pub command: Option<DrawCommandId>,
210 /// The store keeps the recording when it lets go of the run, so the
211 /// command can record into its buffers on a later update. A redraw
212 /// records into it again only while the run is its one holder, which
213 /// is what makes sharing sound.
214 pub recording: Rc<CommandRecording>,
215 /// The segments of the recording this run draws: one placement's part
216 /// of a with-content command, or the whole recording.
217 pub segments: Range<u32>,
218 /// Content facts consumers keep asking per frame, answered while
219 /// recording and never by rescanning.
220 pub summary: DrawRunSummary,
221}
222
223/// What a run contains, answered while recording.
224pub type DrawRunSummary = RecordingSummary;
225
226impl DrawRunNode {
227 /// Creates a run for `primitives` that has no draw command provenance.
228 pub fn new(phase: PrimitivePhase, primitives: Vec<DrawPrimitive>) -> Self {
229 Self::for_command(phase, None, primitives)
230 }
231
232 /// Creates a run for `primitives` recorded by the draw command `command`.
233 pub fn for_command(
234 phase: PrimitivePhase,
235 command: Option<DrawCommandId>,
236 primitives: Vec<DrawPrimitive>,
237 ) -> Self {
238 let recording = CommandRecording::from_primitives(primitives);
239 let segments = recording.all_segments();
240 Self::for_command_shared(phase, command, Rc::new(recording), segments)
241 }
242
243 /// Creates a run over `segments` of an existing shared `recording`, without copying it.
244 pub fn for_command_shared(
245 phase: PrimitivePhase,
246 command: Option<DrawCommandId>,
247 recording: Rc<CommandRecording>,
248 segments: Range<u32>,
249 ) -> Self {
250 let summary = recording.summary_in(&segments);
251 Self {
252 phase,
253 command,
254 recording,
255 segments,
256 summary,
257 }
258 }
259
260 /// The run's primitives, materialised from the recording in order.
261 pub fn primitives(&self) -> impl Iterator<Item = DrawPrimitive> + '_ {
262 self.recording.primitives(self.segments.clone())
263 }
264
265 /// Runs `visit` on the run's primitives in order, as [`Self::primitives`]
266 /// yields them, without the iterator's step between segments.
267 pub fn for_each_primitive(&self, visit: impl FnMut(DrawPrimitive)) {
268 self.recording
269 .for_each_primitive(self.segments.clone(), visit);
270 }
271
272 /// The rect every entry of the run can reach.
273 pub fn coverage_rects(&self) -> impl Iterator<Item = Rect> + '_ {
274 self.recording.coverage_rects(self.segments.clone())
275 }
276
277 /// Number of primitives in the run.
278 pub fn len(&self) -> usize {
279 self.recording.len_in(&self.segments)
280 }
281
282 /// Whether the run holds no primitives.
283 pub fn is_empty(&self) -> bool {
284 self.recording.is_empty_in(&self.segments)
285 }
286
287 // Whether the run puts nothing outside `bounds` of its layer.
288 #[cfg(feature = "window-damage")]
289 pub(crate) fn draws_within(&self, bounds: Rect) -> bool {
290 !self.summary.has_shadow
291 && self
292 .recording
293 .bounds()
294 .is_none_or(|drawn| rect_within(drawn, bounds))
295 }
296}
297
298#[cfg(feature = "window-damage")]
299pub(crate) fn inflate_rect(rect: Rect, by: f32) -> Rect {
300 Rect {
301 x: rect.x - by,
302 y: rect.y - by,
303 width: rect.width + by * 2.0,
304 height: rect.height + by * 2.0,
305 }
306}
307
308#[cfg(feature = "window-damage")]
309pub(crate) fn rect_within(inner: Rect, outer: Rect) -> bool {
310 inner.x >= outer.x
311 && inner.y >= outer.y
312 && inner.x + inner.width <= outer.x + outer.width
313 && inner.y + inner.height <= outer.y + outer.height
314}
315
316#[cfg(test)]
317#[path = "tests/graph_tests.rs"]
318mod tests;