cranpose_render_common/lib.rs
1#![deny(missing_docs)]
2#![doc = include_str!("../README.md")]
3
4/// Source-over blending of straight-alpha byte pixels.
5pub mod byte_blend;
6/// Debug switches read from environment variables, with programmatic overrides.
7pub mod dev_overlay;
8mod left_nodes;
9
10/// The frame background every renderer clears to (linear values; sRGB
11/// surfaces display this as rgb(75, 75, 86)). One definition so backends
12/// cannot drift.
13pub const FRAME_CLEAR_COLOR: [f32; 4] = [18.0 / 255.0, 18.0 / 255.0, 24.0 / 255.0, 1.0];
14/// CPU sampling of brushes at a point, for the software renderers.
15pub mod brush_sampling;
16pub mod font_source;
17/// Blur kernel and rectangle helpers shared by the renderers.
18pub mod geometry;
19/// Glyph masks and the cache renderers keep them in.
20pub mod glyph_mask;
21pub mod glyph_reach;
22/// The draws a scene holds.
23pub mod graph;
24/// The retained scene: its records together with the hit targets built from them.
25pub mod graph_scene;
26/// Collecting hit targets from a scene's records.
27pub mod hit_graph;
28/// Pixel comparison and resampling of RGBA images, for renderer tests.
29pub mod image_compare;
30#[cfg(feature = "installed-fonts")]
31pub mod installed_fonts;
32/// Rules for when a graphics layer is drawn into its own offscreen buffer and with which alpha.
33pub mod layer_composition;
34pub mod layer_shadow;
35/// Transform math of a graphics layer, re-exported from `cranpose_ui_graphics`.
36pub mod layer_transform;
37mod node_window_bounds;
38/// Lowering of draw primitives to the shape, image and text draw calls of a renderer.
39pub mod primitive_emit;
40/// Keys of the cached rasters of layers.
41pub mod raster_cache;
42/// Shared cases that every renderer backend is checked against.
43#[cfg(feature = "layer-tree")]
44pub mod render_contract;
45/// 16-bit pixels of the format most small displays take.
46pub mod rgb565;
47/// Building and updating the scene's records from the layout tree.
48pub mod scene_builder;
49/// Which mesh surface of a 3D scene a window point shows.
50pub mod scene_pick;
51pub mod scene_store;
52pub mod shape_sdf;
53/// Where a window's scenes put their 3D layers: frames, spaces, doorways
54/// and what the eye sees.
55pub mod space;
56/// Colors, brushes and corner radii resolved against the properties of a graphics layer.
57pub mod style_shared;
58/// A laid-out text's glyphs placed for a renderer that draws from an atlas.
59pub mod text_atlas;
60/// The pixels a text's glyph masks are painted into.
61pub mod text_canvas;
62/// Span backgrounds and the lines under and through a text.
63pub mod text_decoration;
64/// The typefaces a renderer hands the app its text lays out with.
65pub mod text_fonts;
66/// The glyphs of a laid-out text placed on pixels with their paints.
67pub mod text_glyphs;
68pub mod text_mask_gamma;
69pub mod text_paint;
70/// A laid-out text's glyphs rasterized into pixels.
71pub mod text_raster;
72mod text_shadow;
73mod thread_state;
74
75#[cfg(test)]
76#[path = "tests/pointer_slices.rs"]
77mod pointer_slices;
78
79use cranpose_core::MemoryApplier;
80use cranpose_foundation::nodes::input::PointerEvent;
81pub use cranpose_ui_graphics::Brush;
82use cranpose_ui_graphics::Size;
83
84/// What changed in a node since the scene last drew it, and so how the scene
85/// updates what it drew for that node.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub enum NodeUpdate {
88 /// Its layout, children or draw commands changed: the scene records it
89 /// again.
90 Content,
91 /// Only its draws changed: state they read, or a draw modifier updated
92 /// in place, such as a background's color. Its layer keeps its children
93 /// and records the node's draws again.
94 Draws,
95 /// Its graphics-layer properties changed and it drew the same.
96 Layer,
97 /// It moved in its parent and kept its size: its layer moves and keeps
98 /// what it drew.
99 Moved,
100 /// It moved and its layer properties changed: its layer moves, takes the
101 /// new properties and keeps what it drew.
102 MovedLayer,
103}
104
105impl NodeUpdate {
106 /// The update a node named with both `self` and `other` needs: content
107 /// wins over the others, draws with any other change need the content,
108 /// and a move with a layer change moves the layer with its new
109 /// properties.
110 #[must_use]
111 pub fn merge(self, other: Self) -> Self {
112 use NodeUpdate::{Content, Draws, Layer, Moved, MovedLayer};
113 match (self, other) {
114 (Content, _) | (_, Content) => Content,
115 (Draws, Draws) => Draws,
116 (Draws, _) | (_, Draws) => Content,
117 (Moved, Moved) => Moved,
118 (Layer, Layer) => Layer,
119 (Moved | Layer | MovedLayer, Moved | Layer | MovedLayer) => MovedLayer,
120 }
121 }
122}
123
124/// The nodes whose drawing changed since the last scene, each with the
125/// update it needs. A node may be named more than once: its updates merge
126/// (see [`NodeUpdate::merge`]).
127///
128/// ```
129/// use cranpose_core::NodeId;
130/// use cranpose_render_common::{NodeUpdate, SceneUpdates};
131/// let updates: SceneUpdates<'_> = &[
132/// (NodeId(1), NodeUpdate::Content),
133/// (NodeId(3), NodeUpdate::Moved),
134/// ];
135/// assert_eq!(updates.len(), 2);
136/// ```
137pub type SceneUpdates<'a> = &'a [(cranpose_core::NodeId, NodeUpdate)];
138
139/// Trait implemented by hit-test targets stored inside a [`RenderScene`].
140pub trait HitTestTarget {
141 /// Dispatches a pointer event to this target's handlers.
142 fn dispatch(&self, event: PointerEvent);
143
144 /// Dispatches a pointer event using the current live node state when available.
145 ///
146 /// Render-scene hit targets may cache closures from an older scene build. Pointer
147 /// dispatch goes through this hook so implementations can resolve fresh handlers
148 /// from the current applier while still using the target's geometry snapshot.
149 fn dispatch_with_applier(&self, _applier: &mut MemoryApplier, event: PointerEvent) {
150 self.dispatch(event);
151 }
152
153 /// Returns the NodeId associated with this hit target.
154 /// Used by HitPathTracker to cache stable identity instead of geometry.
155 fn node_id(&self) -> cranpose_core::NodeId;
156
157 /// The pointer's appearance while it hovers this target, when the target
158 /// names one.
159 ///
160 /// The shell asks the hit list top-down and applies the first answer, so
161 /// the innermost region under the pointer decides the cursor.
162 fn pointer_icon(&self) -> Option<cranpose_ui_graphics::PointerIcon> {
163 None
164 }
165
166 /// Returns the node capture path that should stay attached to this target's gesture.
167 ///
168 /// The default is just this target's own node. Renderers can override this to
169 /// include stable ancestor pointer-input nodes that must continue receiving
170 /// Move/Up/Cancel even if the original descendant target is recycled.
171 fn capture_path(&self) -> Vec<cranpose_core::NodeId> {
172 vec![self.node_id()]
173 }
174}
175
176/// Trait describing the minimal surface area required by the application
177/// shell to process pointer events and refresh the frame graph.
178pub trait RenderScene {
179 /// The hit target type that hit testing returns.
180 type HitTarget: HitTestTarget + Clone;
181
182 /// Removes the scene's records and all hit targets.
183 fn clear(&mut self);
184
185 /// Performs hit testing at the given coordinates.
186 /// Returns hit targets ordered by z-index (top-to-bottom).
187 fn hit_test(&self, x: f32, y: f32) -> Vec<Self::HitTarget>;
188
189 /// The one target a press reaches when it misses every target but lands
190 /// inside a small target grown to the minimum touch size: the nearest such
191 /// target, and none when the point is outside every grown target.
192 fn hit_test_near(&self, _x: f32, _y: f32) -> Option<Self::HitTarget> {
193 None
194 }
195
196 /// Returns NodeIds of all hit regions at the given coordinates.
197 /// This is a convenience method equivalent to `hit_test().map(|h| h.node_id())`.
198 fn hit_test_nodes(&self, x: f32, y: f32) -> Vec<cranpose_core::NodeId> {
199 self.hit_test(x, y)
200 .into_iter()
201 .map(|h| h.node_id())
202 .collect()
203 }
204
205 /// Finds a hit target by NodeId with fresh geometry from the current scene.
206 ///
207 /// This is the key method for HitPathTracker-style gesture handling:
208 /// - On PointerDown, we cache NodeIds (not geometry)
209 /// - On Move/Up/Cancel, we call this to get fresh HitTarget with current geometry
210 /// - Handler closures are preserved (same Rc), so internal state survives
211 ///
212 /// Returns None if the node no longer exists in the scene (e.g., removed during gesture).
213 fn find_target(&self, node_id: cranpose_core::NodeId) -> Option<Self::HitTarget>;
214
215 /// The hit targets on the mesh surfaces of the scene the node `scene`
216 /// shows that `ray` reaches, in the space the scene's eye stands in,
217 /// ordered by z-index (top-to-bottom): a controller's, a hand's or a
218 /// gaze's, which need not start at the eye.
219 fn hit_test_ray(
220 &self,
221 _scene: cranpose_core::NodeId,
222 _ray: cranpose_ui_graphics::space::Ray,
223 ) -> Vec<Self::HitTarget> {
224 Vec::new()
225 }
226
227 /// Visits each mesh surface the eyes of the window's scenes see, by its
228 /// node, with the map from its content to the window as the eye shows
229 /// it, through the doorways it lies behind: where the nodes on it show.
230 fn surface_windows(
231 &self,
232 _visit: &mut dyn FnMut(cranpose_core::NodeId, cranpose_ui_graphics::ProjectiveTransform),
233 ) {
234 }
235
236 /// Where the hit target of `node_id` shows in the window when it lies on
237 /// a mesh surface of a 3D scene: its bounds as the scene's camera shows
238 /// them, also through a doorway and for an eye that walked through one.
239 /// `None` for a flat target, a target behind the eye or no target.
240 fn surface_window_bounds(
241 &self,
242 _node_id: cranpose_core::NodeId,
243 ) -> Option<cranpose_ui_graphics::Rect> {
244 None
245 }
246
247 /// Visits each layout node the scene draws with the bounds of its rect
248 /// in the window, through the graphics layers above it and its own, and
249 /// on a mesh surface as the scene's camera shows it: where it shows.
250 fn node_window_bounds(
251 &self,
252 _visit: &mut dyn FnMut(cranpose_core::NodeId, cranpose_ui_graphics::Rect),
253 ) {
254 }
255
256 /// A count that grows when an update moves a layer in its parent without a layout pass, as
257 /// an animated graphics layer or `offset_with` does: what read [`Self::node_window_bounds`]
258 /// reads them again when it changes.
259 fn layer_moves(&self) -> u64 {
260 0
261 }
262
263 /// Gives back the room the scene's storage holds past what it draws. Its
264 /// owner calls it at rest, when no frame waits. Returns whether the scene
265 /// let every record go to give that room back: the owner builds it anew
266 /// before anything reads it.
267 fn trim(&mut self) -> bool {
268 false
269 }
270
271 /// Whether the scene draws `node`. A scene that keeps no record of the nodes it draws says
272 /// it does.
273 fn draws(&self, _node: cranpose_core::NodeId) -> bool {
274 true
275 }
276
277 /// The node whose record holds what the scene draws for `node`: the node the scene draws
278 /// again for `node` to leave it. `None` when the scene draws no record for `node`, or that
279 /// record is its root.
280 fn drawn_parent(&self, _node: cranpose_core::NodeId) -> Option<cranpose_core::NodeId> {
281 None
282 }
283
284 /// Adds to `left` the layout nodes whose records the scene dropped since the last call; a
285 /// node may draw through another record since, as [`Self::draws`] tells. Returns whether the
286 /// scene can tell: a scene handed a store built from scratch since cannot, and the caller
287 /// asks [`Self::draws`] of every node instead.
288 fn read_left_nodes(&mut self, _left: &mut Vec<cranpose_core::NodeId>) -> bool {
289 true
290 }
291}
292
293/// Abstraction implemented by concrete renderer backends.
294pub trait Renderer {
295 /// The scene type that holds the records and the hit targets of this renderer.
296 type Scene: RenderScene;
297 /// Error returned when the scene cannot be rebuilt or updated.
298 type Error;
299
300 /// Installs renderer-provided app services into the target AppContext.
301 ///
302 /// AppShell calls this before the first composition pass.
303 /// Renderers that provide text measurement or other per-app services should install
304 /// them here rather than as constructor side effects.
305 fn attach_app_context_services(&mut self, _app_context: &cranpose_ui::AppContext) {}
306
307 /// Gives back the room the renderer's storage holds past what it draws,
308 /// beside its scene's. AppShell calls it at rest, when no frame waits.
309 fn trim(&mut self) {}
310
311 /// Takes in the fonts installed since the renderer last looked (see
312 /// `installed_fonts::install_font_file`). A renderer that installed the
313 /// app's text measurer installs one with the new faces, so text lays out
314 /// again with them.
315 ///
316 /// AppShell calls this before the layout of a frame that follows an
317 /// install.
318 fn apply_installed_fonts(&mut self, _app_context: &cranpose_ui::AppContext) {}
319
320 /// Sets how many device pixels the renderer draws for one logical unit.
321 ///
322 /// AppShell sets its primary renderer's scale to the density it lays
323 /// out with, at construction and on every density change, so a host
324 /// sets it only for the renderers of other surfaces. Renderers that take
325 /// the scale with each draw ignore it.
326 fn set_root_scale(&mut self, _scale: f32) {}
327
328 /// The scene that holds the records and the hit targets.
329 fn scene(&self) -> &Self::Scene;
330 /// Mutable access to the scene.
331 fn scene_mut(&mut self) -> &mut Self::Scene;
332
333 /// Rebuilds the scene by traversing the LayoutNode tree directly via Applier.
334 ///
335 /// This is the new architecture that eliminates per-frame LayoutTree reconstruction.
336 /// Implementors must read layout state from LayoutNode.layout_state() directly.
337 fn rebuild_scene_from_applier(
338 &mut self,
339 applier: &mut MemoryApplier,
340 root: cranpose_core::NodeId,
341 viewport: Size,
342 ) -> Result<(), Self::Error>;
343
344 /// Updates the scene for the nodes in `updates`, and the hit targets when the update changed
345 /// one or the geometry above one. The default implementation rebuilds the whole scene.
346 fn update_scene_from_applier(
347 &mut self,
348 applier: &mut MemoryApplier,
349 root: cranpose_core::NodeId,
350 viewport: Size,
351 updates: SceneUpdates<'_>,
352 ) -> Result<(), Self::Error> {
353 let _ = updates;
354 self.rebuild_scene_from_applier(applier, root, viewport)
355 }
356
357 /// Updates the scene when only what is drawn changed: nothing was composed or laid out. The
358 /// default implementation calls `update_scene_from_applier`.
359 fn update_visual_scene_from_applier(
360 &mut self,
361 applier: &mut MemoryApplier,
362 root: cranpose_core::NodeId,
363 viewport: Size,
364 updates: SceneUpdates<'_>,
365 ) -> Result<(), Self::Error> {
366 self.update_scene_from_applier(applier, root, viewport, updates)
367 }
368
369 /// Draw a development overlay (e.g., FPS counter) on top of the scene.
370 ///
371 /// This is called after the scene is built when dev options are enabled.
372 /// The text, laid out in `overlay`, is drawn directly by the renderer
373 /// without affecting composition.
374 ///
375 /// Default implementation does nothing.
376 fn draw_dev_overlay(&mut self, _overlay: &cranpose_ui::PreparedTextLayout, _viewport: Size) {}
377
378 /// Replaces the developer inspector layer drawn over the application scene.
379 ///
380 /// Passing `None` removes the inspector. Its primitives must not participate
381 /// in application hit testing, layout, or accessibility.
382 fn set_inspector_overlay(&mut self, _overlay: Option<scene_store::OverlayLayer>) {}
383
384 /// Replaces the overlay with the layer tree `overlay` describes, as a
385 /// renderer's tests describe an overlay by hand.
386 ///
387 /// Passing `None` removes the overlay. Default implementation does nothing.
388 #[cfg(feature = "layer-tree")]
389 fn set_overlay_tree(&mut self, _overlay: Option<graph::LayerNode>) {}
390
391 /// Tells the renderer that its app held still between the last frame and the next one: the
392 /// shell asked the platform for no frame and no update. A renderer that compares frames to
393 /// draw only what changed counts the frames on either side of the pause apart.
394 ///
395 /// AppShell calls this before the first frame after such a pause.
396 fn note_held_still(&mut self) {}
397
398 /// Tells the renderer that a pointer is held on the app's controls for the coming frame: the
399 /// user may move it at any moment, so the frame is not one to spend on work that holds the
400 /// frames after it back, such as a WebGL program link.
401 ///
402 /// AppShell calls this before each frame drawn while a pointer is held.
403 fn note_pointer_held(&mut self) {}
404
405 /// Runs one step of the pipeline builds that wait for a frame, where frames run them (a WebGL
406 /// page links one program at a frame's end), while the app draws none: a page that stands
407 /// still still builds what its next touch draws. Returns whether builds still wait.
408 ///
409 /// The platform calls this in its idle periods while it has no frame to draw.
410 fn build_while_idle(&mut self) -> bool {
411 false
412 }
413
414 /// Returns whether renderer-side cache materialization needs a visible follow-up frame.
415 fn needs_frame_warmup(&self) -> bool {
416 false
417 }
418
419 /// Returns whether the last frame drew a placeholder for an effect whose
420 /// pipelines are still compiling, so its picture is not final yet; the
421 /// renderer asks for the frame that replaces it once they land.
422 fn awaits_pipelines(&self) -> bool {
423 false
424 }
425}