cranpose_render_common/lib.rs
1#![deny(missing_docs)]
2#![doc = include_str!("../README.md")]
3
4mod annotated_text;
5mod ascii_glyphs;
6/// Debug switches read from environment variables, with programmatic overrides.
7pub mod debug_toggles;
8pub mod dev_overlay;
9mod direct_mapped_cache;
10
11/// The frame background every renderer clears to (linear values; sRGB
12/// surfaces display this as rgb(75, 75, 86)). One definition so backends
13/// cannot drift.
14pub const FRAME_CLEAR_COLOR: [f32; 4] = [18.0 / 255.0, 18.0 / 255.0, 24.0 / 255.0, 1.0];
15/// CPU sampling of brushes at a point, for the software renderers.
16pub mod brush_sampling;
17mod font_features;
18/// Glyph layout and vertical metrics of a font at one pixel size.
19pub mod font_layout;
20pub mod font_source;
21mod font_tracking;
22mod full_glyph_count;
23/// Blur kernel and rectangle helpers shared by the renderers.
24pub mod geometry;
25pub mod gpos_kerning;
26/// The render graph: the layers and primitives that a scene builds for a renderer to draw.
27pub mod graph;
28mod graph_hash;
29/// The retained scene: the render graph together with the hit targets built from it.
30pub mod graph_scene;
31/// Collecting hit targets from a render graph.
32pub mod hit_graph;
33/// Pixel comparison and resampling of RGBA images, for renderer tests.
34pub mod image_compare;
35#[cfg(feature = "installed-fonts")]
36pub mod installed_fonts;
37/// Rules for when a graphics layer is drawn into its own offscreen buffer and with which alpha.
38pub mod layer_composition;
39mod layer_recycling;
40pub mod layer_shadow;
41/// Transform math of a graphics layer, re-exported from `cranpose_ui_graphics`.
42pub mod layer_transform;
43/// Lowering of draw primitives to the shape, image and text draw calls of a renderer.
44pub mod primitive_emit;
45/// Keys of the cached rasters of layers.
46pub mod raster_cache;
47/// Shared cases that every renderer backend is checked against.
48pub mod render_contract;
49/// Building and updating the render graph from the layout tree.
50pub mod scene_builder;
51/// Which mesh surface of a 3D scene a window point shows.
52pub mod scene_pick;
53pub mod shape_sdf;
54/// CPU text rasterization: fonts, glyph layout and glyph masks.
55pub mod software_text_raster;
56/// Where a window's scenes put their 3D layers: frames, spaces, doorways
57/// and what the eye sees.
58pub mod space;
59/// Colors, brushes and corner radii resolved against the properties of a graphics layer.
60pub mod style_shared;
61mod text_cache_key;
62/// Automatic hyphenation of text, using dictionaries that the app registers.
63pub mod text_hyphenation;
64pub mod text_mask_gamma;
65pub mod text_measure;
66pub mod text_paint;
67#[cfg(feature = "text-shaping")]
68mod text_shaping;
69mod thread_state;
70
71#[cfg(test)]
72#[path = "tests/pointer_slices.rs"]
73mod pointer_slices;
74
75use cranpose_core::{MemoryApplier, collections::map::HashSet};
76use cranpose_foundation::nodes::input::PointerEvent;
77use cranpose_ui::LayoutTree;
78pub use cranpose_ui_graphics::Brush;
79use cranpose_ui_graphics::Size;
80
81/// Describes scene nodes whose recorded content or layer properties changed.
82///
83/// Content updates may re-record a node's draw commands. Layer updates change
84/// graphics-layer properties while retaining those recordings. If a node
85/// appears in both slices, content dirt takes precedence.
86/// Layout, child structure, and draw-command changes belong in `content`.
87///
88/// ```
89/// use cranpose_render_common::SceneUpdates;
90/// let updates = SceneUpdates {
91/// content: &[1],
92/// layers: &[2],
93/// moved: &[3],
94/// };
95/// assert!(!updates.is_empty());
96/// ```
97#[derive(Clone, Copy, Debug, Default)]
98pub struct SceneUpdates<'a> {
99 /// Nodes whose recorded draw content must be refreshed; a node may be
100 /// named more than once.
101 pub content: &'a [cranpose_core::NodeId],
102 /// Nodes whose graphics-layer properties changed without content dirt.
103 pub layers: &'a [cranpose_core::NodeId],
104 /// Nodes that moved in their parent and kept their size: the scene moves
105 /// what it drew for them unless another list names them too.
106 pub moved: &'a [cranpose_core::NodeId],
107}
108
109impl<'a> SceneUpdates<'a> {
110 /// Creates an update containing only nodes with changed draw content.
111 pub const fn content(nodes: &'a [cranpose_core::NodeId]) -> Self {
112 Self {
113 content: nodes,
114 layers: &[],
115 moved: &[],
116 }
117 }
118
119 /// Returns whether the update contains no dirty nodes.
120 pub const fn is_empty(self) -> bool {
121 self.content.is_empty() && self.layers.is_empty() && self.moved.is_empty()
122 }
123}
124
125/// Trait implemented by hit-test targets stored inside a [`RenderScene`].
126pub trait HitTestTarget {
127 /// Dispatches a pointer event to this target's handlers.
128 fn dispatch(&self, event: PointerEvent);
129
130 /// Dispatches a pointer event using the current live node state when available.
131 ///
132 /// Render-scene hit targets may cache closures from an older scene build. Pointer
133 /// dispatch goes through this hook so implementations can resolve fresh handlers
134 /// from the current applier while still using the target's geometry snapshot.
135 fn dispatch_with_applier(&self, _applier: &mut MemoryApplier, event: PointerEvent) {
136 self.dispatch(event);
137 }
138
139 /// Returns the NodeId associated with this hit target.
140 /// Used by HitPathTracker to cache stable identity instead of geometry.
141 fn node_id(&self) -> cranpose_core::NodeId;
142
143 /// The pointer's appearance while it hovers this target, when the target
144 /// names one.
145 ///
146 /// The shell asks the hit list top-down and applies the first answer, so
147 /// the innermost region under the pointer decides the cursor.
148 fn pointer_icon(&self) -> Option<cranpose_ui_graphics::PointerIcon> {
149 None
150 }
151
152 /// Returns the node capture path that should stay attached to this target's gesture.
153 ///
154 /// The default is just this target's own node. Renderers can override this to
155 /// include stable ancestor pointer-input nodes that must continue receiving
156 /// Move/Up/Cancel even if the original descendant target is recycled.
157 fn capture_path(&self) -> Vec<cranpose_core::NodeId> {
158 vec![self.node_id()]
159 }
160}
161
162/// Trait describing the minimal surface area required by the application
163/// shell to process pointer events and refresh the frame graph.
164pub trait RenderScene {
165 /// The hit target type that hit testing returns.
166 type HitTarget: HitTestTarget + Clone;
167
168 /// Removes the render graph and all hit targets.
169 fn clear(&mut self);
170
171 /// Performs hit testing at the given coordinates.
172 /// Returns hit targets ordered by z-index (top-to-bottom).
173 fn hit_test(&self, x: f32, y: f32) -> Vec<Self::HitTarget>;
174
175 /// The one target a press reaches when it misses every target but lands
176 /// inside a small target grown to the minimum touch size: the nearest such
177 /// target, and none when the point is outside every grown target.
178 fn hit_test_near(&self, _x: f32, _y: f32) -> Option<Self::HitTarget> {
179 None
180 }
181
182 /// Returns NodeIds of all hit regions at the given coordinates.
183 /// This is a convenience method equivalent to `hit_test().map(|h| h.node_id())`.
184 fn hit_test_nodes(&self, x: f32, y: f32) -> Vec<cranpose_core::NodeId> {
185 self.hit_test(x, y)
186 .into_iter()
187 .map(|h| h.node_id())
188 .collect()
189 }
190
191 /// Finds a hit target by NodeId with fresh geometry from the current scene.
192 ///
193 /// This is the key method for HitPathTracker-style gesture handling:
194 /// - On PointerDown, we cache NodeIds (not geometry)
195 /// - On Move/Up/Cancel, we call this to get fresh HitTarget with current geometry
196 /// - Handler closures are preserved (same Rc), so internal state survives
197 ///
198 /// Returns None if the node no longer exists in the scene (e.g., removed during gesture).
199 fn find_target(&self, node_id: cranpose_core::NodeId) -> Option<Self::HitTarget>;
200
201 /// The hit targets on the mesh surfaces of the scene the node `scene`
202 /// shows that `ray` reaches, in the space the scene's eye stands in,
203 /// ordered by z-index (top-to-bottom): a controller's, a hand's or a
204 /// gaze's, which need not start at the eye.
205 fn hit_test_ray(
206 &self,
207 _scene: cranpose_core::NodeId,
208 _ray: cranpose_ui_graphics::space::Ray,
209 ) -> Vec<Self::HitTarget> {
210 Vec::new()
211 }
212
213 /// Visits each mesh surface the eyes of the window's scenes see, by its
214 /// node, with the map from its content to the window as the eye shows
215 /// it, through the doorways it lies behind: where the nodes on it show.
216 fn surface_windows(
217 &self,
218 _visit: &mut dyn FnMut(cranpose_core::NodeId, cranpose_ui_graphics::ProjectiveTransform),
219 ) {
220 }
221
222 /// Where the hit target of `node_id` shows in the window when it lies on
223 /// a mesh surface of a 3D scene: its bounds as the scene's camera shows
224 /// them, also through a doorway and for an eye that walked through one.
225 /// `None` for a flat target, a target behind the eye or no target.
226 fn surface_window_bounds(
227 &self,
228 _node_id: cranpose_core::NodeId,
229 ) -> Option<cranpose_ui_graphics::Rect> {
230 None
231 }
232
233 /// Replaces the set with retained visual observation owners, preserving its capacity.
234 /// Returns whether the scene provides this information.
235 fn collect_retained_visual_observation_nodes(
236 &self,
237 nodes: &mut HashSet<cranpose_core::NodeId>,
238 ) -> bool {
239 nodes.clear();
240 false
241 }
242}
243
244/// Abstraction implemented by concrete renderer backends.
245pub trait Renderer {
246 /// The scene type that holds the render graph and the hit targets of this renderer.
247 type Scene: RenderScene;
248 /// Error returned when the scene cannot be rebuilt or updated.
249 type Error;
250
251 /// Installs renderer-provided app services into the target AppContext.
252 ///
253 /// AppShell calls this before the first composition pass.
254 /// Renderers that provide text measurement or other per-app services should install
255 /// them here rather than as constructor side effects.
256 fn attach_app_context_services(&mut self, _app_context: &cranpose_ui::AppContext) {}
257
258 /// Takes in the fonts installed since the renderer last looked (see
259 /// `installed_fonts::install_font_file`). A renderer that installed the
260 /// app's text measurer installs one with the new faces, so text lays out
261 /// again with them.
262 ///
263 /// AppShell calls this before the layout of a frame that follows an
264 /// install.
265 fn apply_installed_fonts(&mut self, _app_context: &cranpose_ui::AppContext) {}
266
267 /// Sets how many device pixels the renderer draws for one logical unit.
268 ///
269 /// AppShell sets its primary renderer's scale to the density it lays
270 /// out with, at construction and on every density change, so a host
271 /// sets it only for the renderers of other surfaces. Renderers that take
272 /// the scale with each draw ignore it.
273 fn set_root_scale(&mut self, _scale: f32) {}
274
275 /// The scene that holds the render graph and the hit targets.
276 fn scene(&self) -> &Self::Scene;
277 /// Mutable access to the scene.
278 fn scene_mut(&mut self) -> &mut Self::Scene;
279
280 /// Rebuilds the scene from `layout_tree` for a viewport of the given size.
281 fn rebuild_scene(
282 &mut self,
283 layout_tree: &LayoutTree,
284 viewport: Size,
285 ) -> Result<(), Self::Error>;
286
287 /// Rebuilds the scene by traversing the LayoutNode tree directly via Applier.
288 ///
289 /// This is the new architecture that eliminates per-frame LayoutTree reconstruction.
290 /// Implementors must read layout state from LayoutNode.layout_state() directly.
291 fn rebuild_scene_from_applier(
292 &mut self,
293 applier: &mut cranpose_core::MemoryApplier,
294 root: cranpose_core::NodeId,
295 viewport: Size,
296 ) -> Result<(), Self::Error>;
297
298 /// Updates the scene for the nodes in `updates` and refreshes the hit targets. The default
299 /// implementation rebuilds the whole scene.
300 fn update_scene_from_applier(
301 &mut self,
302 applier: &mut cranpose_core::MemoryApplier,
303 root: cranpose_core::NodeId,
304 viewport: Size,
305 updates: SceneUpdates<'_>,
306 ) -> Result<(), Self::Error> {
307 let _ = updates;
308 self.rebuild_scene_from_applier(applier, root, viewport)
309 }
310
311 /// Updates the scene when only what is drawn changed. Hit targets are refreshed only when their
312 /// geometry changed. The default implementation calls `update_scene_from_applier`.
313 fn update_visual_scene_from_applier(
314 &mut self,
315 applier: &mut cranpose_core::MemoryApplier,
316 root: cranpose_core::NodeId,
317 viewport: Size,
318 updates: SceneUpdates<'_>,
319 ) -> Result<(), Self::Error> {
320 self.update_scene_from_applier(applier, root, viewport, updates)
321 }
322
323 /// Draw a development overlay (e.g., FPS counter) on top of the scene.
324 ///
325 /// This is called after rebuild_scene when dev options are enabled.
326 /// The text is drawn directly by the renderer without affecting composition.
327 ///
328 /// Default implementation does nothing.
329 fn draw_dev_overlay(&mut self, _text: &str, _viewport: Size) {}
330
331 /// Replaces the developer inspector graph outside the application scene.
332 ///
333 /// Passing `None` removes the inspector. Its primitives must not participate
334 /// in application hit testing, layout, or accessibility.
335 fn set_inspector_overlay(&mut self, _graph: Option<graph::RenderGraph>) {}
336
337 /// Returns whether renderer-side cache materialization needs a visible follow-up frame.
338 fn needs_frame_warmup(&self) -> bool {
339 false
340 }
341
342 /// Returns whether the last frame drew a placeholder for an effect whose
343 /// pipelines are still compiling, so its picture is not final yet; the
344 /// renderer asks for the frame that replaces it once they land.
345 fn awaits_pipelines(&self) -> bool {
346 false
347 }
348}