Skip to main content

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