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