cranpose-render-common 0.25.0

Scene, renderer and hit-test contracts for Cranpose backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
#![deny(missing_docs)]
#![doc = include_str!("../README.md")]

/// Source-over blending of straight-alpha byte pixels.
pub mod byte_blend;
/// Debug switches read from environment variables, with programmatic overrides.
pub mod dev_overlay;
mod left_nodes;

/// The frame background every renderer clears to (linear values; sRGB
/// surfaces display this as rgb(75, 75, 86)). One definition so backends
/// cannot drift.
pub const FRAME_CLEAR_COLOR: [f32; 4] = [18.0 / 255.0, 18.0 / 255.0, 24.0 / 255.0, 1.0];
/// CPU sampling of brushes at a point, for the software renderers.
pub mod brush_sampling;
pub mod font_source;
/// Blur kernel and rectangle helpers shared by the renderers.
pub mod geometry;
/// Glyph masks and the cache renderers keep them in.
pub mod glyph_mask;
pub mod glyph_reach;
/// The draws a scene holds.
pub mod graph;
/// The retained scene: its records together with the hit targets built from them.
pub mod graph_scene;
/// Collecting hit targets from a scene's records.
pub mod hit_graph;
/// Pixel comparison and resampling of RGBA images, for renderer tests.
pub mod image_compare;
#[cfg(feature = "installed-fonts")]
pub mod installed_fonts;
/// Rules for when a graphics layer is drawn into its own offscreen buffer and with which alpha.
pub mod layer_composition;
pub mod layer_shadow;
/// Transform math of a graphics layer, re-exported from `cranpose_ui_graphics`.
pub mod layer_transform;
mod node_window_bounds;
/// Lowering of draw primitives to the shape, image and text draw calls of a renderer.
pub mod primitive_emit;
/// Keys of the cached rasters of layers.
pub mod raster_cache;
/// Shared cases that every renderer backend is checked against.
#[cfg(feature = "layer-tree")]
pub mod render_contract;
/// 16-bit pixels of the format most small displays take.
pub mod rgb565;
/// Building and updating the scene's records from the layout tree.
pub mod scene_builder;
/// Which mesh surface of a 3D scene a window point shows.
pub mod scene_pick;
pub mod scene_store;
pub mod shape_sdf;
/// Where a window's scenes put their 3D layers: frames, spaces, doorways
/// and what the eye sees.
pub mod space;
/// Colors, brushes and corner radii resolved against the properties of a graphics layer.
pub mod style_shared;
/// A laid-out text's glyphs placed for a renderer that draws from an atlas.
pub mod text_atlas;
/// The pixels a text's glyph masks are painted into.
pub mod text_canvas;
/// Span backgrounds and the lines under and through a text.
pub mod text_decoration;
/// The typefaces a renderer hands the app its text lays out with.
pub mod text_fonts;
/// The glyphs of a laid-out text placed on pixels with their paints.
pub mod text_glyphs;
pub mod text_mask_gamma;
pub mod text_paint;
/// A laid-out text's glyphs rasterized into pixels.
pub mod text_raster;
mod text_shadow;
mod thread_state;

#[cfg(test)]
#[path = "tests/pointer_slices.rs"]
mod pointer_slices;

use cranpose_core::MemoryApplier;
use cranpose_foundation::nodes::input::PointerEvent;
pub use cranpose_ui_graphics::Brush;
use cranpose_ui_graphics::Size;

/// What changed in a node since the scene last drew it, and so how the scene
/// updates what it drew for that node.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NodeUpdate {
    /// Its layout, children or draw commands changed: the scene records it
    /// again.
    Content,
    /// Only its draws changed: state they read, or a draw modifier updated
    /// in place, such as a background's color. Its layer keeps its children
    /// and records the node's draws again.
    Draws,
    /// Its graphics-layer properties changed and it drew the same.
    Layer,
    /// It moved in its parent and kept its size: its layer moves and keeps
    /// what it drew.
    Moved,
    /// It moved and its layer properties changed: its layer moves, takes the
    /// new properties and keeps what it drew.
    MovedLayer,
}

impl NodeUpdate {
    /// The update a node named with both `self` and `other` needs: content
    /// wins over the others, draws with any other change need the content,
    /// and a move with a layer change moves the layer with its new
    /// properties.
    #[must_use]
    pub fn merge(self, other: Self) -> Self {
        use NodeUpdate::{Content, Draws, Layer, Moved, MovedLayer};
        match (self, other) {
            (Content, _) | (_, Content) => Content,
            (Draws, Draws) => Draws,
            (Draws, _) | (_, Draws) => Content,
            (Moved, Moved) => Moved,
            (Layer, Layer) => Layer,
            (Moved | Layer | MovedLayer, Moved | Layer | MovedLayer) => MovedLayer,
        }
    }
}

/// The nodes whose drawing changed since the last scene, each with the
/// update it needs. A node may be named more than once: its updates merge
/// (see [`NodeUpdate::merge`]).
///
/// ```
/// use cranpose_core::NodeId;
/// use cranpose_render_common::{NodeUpdate, SceneUpdates};
/// let updates: SceneUpdates<'_> = &[
///     (NodeId(1), NodeUpdate::Content),
///     (NodeId(3), NodeUpdate::Moved),
/// ];
/// assert_eq!(updates.len(), 2);
/// ```
pub type SceneUpdates<'a> = &'a [(cranpose_core::NodeId, NodeUpdate)];

/// Trait implemented by hit-test targets stored inside a [`RenderScene`].
pub trait HitTestTarget {
    /// Dispatches a pointer event to this target's handlers.
    fn dispatch(&self, event: PointerEvent);

    /// Dispatches a pointer event using the current live node state when available.
    ///
    /// Render-scene hit targets may cache closures from an older scene build. Pointer
    /// dispatch goes through this hook so implementations can resolve fresh handlers
    /// from the current applier while still using the target's geometry snapshot.
    fn dispatch_with_applier(&self, _applier: &mut MemoryApplier, event: PointerEvent) {
        self.dispatch(event);
    }

    /// Returns the NodeId associated with this hit target.
    /// Used by HitPathTracker to cache stable identity instead of geometry.
    fn node_id(&self) -> cranpose_core::NodeId;

    /// The pointer's appearance while it hovers this target, when the target
    /// names one.
    ///
    /// The shell asks the hit list top-down and applies the first answer, so
    /// the innermost region under the pointer decides the cursor.
    fn pointer_icon(&self) -> Option<cranpose_ui_graphics::PointerIcon> {
        None
    }

    /// Returns the node capture path that should stay attached to this target's gesture.
    ///
    /// The default is just this target's own node. Renderers can override this to
    /// include stable ancestor pointer-input nodes that must continue receiving
    /// Move/Up/Cancel even if the original descendant target is recycled.
    fn capture_path(&self) -> Vec<cranpose_core::NodeId> {
        vec![self.node_id()]
    }
}

/// Trait describing the minimal surface area required by the application
/// shell to process pointer events and refresh the frame graph.
pub trait RenderScene {
    /// The hit target type that hit testing returns.
    type HitTarget: HitTestTarget + Clone;

    /// Removes the scene's records and all hit targets.
    fn clear(&mut self);

    /// Performs hit testing at the given coordinates.
    /// Returns hit targets ordered by z-index (top-to-bottom).
    fn hit_test(&self, x: f32, y: f32) -> Vec<Self::HitTarget>;

    /// The one target a press reaches when it misses every target but lands
    /// inside a small target grown to the minimum touch size: the nearest such
    /// target, and none when the point is outside every grown target.
    fn hit_test_near(&self, _x: f32, _y: f32) -> Option<Self::HitTarget> {
        None
    }

    /// Returns NodeIds of all hit regions at the given coordinates.
    /// This is a convenience method equivalent to `hit_test().map(|h| h.node_id())`.
    fn hit_test_nodes(&self, x: f32, y: f32) -> Vec<cranpose_core::NodeId> {
        self.hit_test(x, y)
            .into_iter()
            .map(|h| h.node_id())
            .collect()
    }

    /// Finds a hit target by NodeId with fresh geometry from the current scene.
    ///
    /// This is the key method for HitPathTracker-style gesture handling:
    /// - On PointerDown, we cache NodeIds (not geometry)
    /// - On Move/Up/Cancel, we call this to get fresh HitTarget with current geometry
    /// - Handler closures are preserved (same Rc), so internal state survives
    ///
    /// Returns None if the node no longer exists in the scene (e.g., removed during gesture).
    fn find_target(&self, node_id: cranpose_core::NodeId) -> Option<Self::HitTarget>;

    /// The hit targets on the mesh surfaces of the scene the node `scene`
    /// shows that `ray` reaches, in the space the scene's eye stands in,
    /// ordered by z-index (top-to-bottom): a controller's, a hand's or a
    /// gaze's, which need not start at the eye.
    fn hit_test_ray(
        &self,
        _scene: cranpose_core::NodeId,
        _ray: cranpose_ui_graphics::space::Ray,
    ) -> Vec<Self::HitTarget> {
        Vec::new()
    }

    /// Visits each mesh surface the eyes of the window's scenes see, by its
    /// node, with the map from its content to the window as the eye shows
    /// it, through the doorways it lies behind: where the nodes on it show.
    fn surface_windows(
        &self,
        _visit: &mut dyn FnMut(cranpose_core::NodeId, cranpose_ui_graphics::ProjectiveTransform),
    ) {
    }

    /// Where the hit target of `node_id` shows in the window when it lies on
    /// a mesh surface of a 3D scene: its bounds as the scene's camera shows
    /// them, also through a doorway and for an eye that walked through one.
    /// `None` for a flat target, a target behind the eye or no target.
    fn surface_window_bounds(
        &self,
        _node_id: cranpose_core::NodeId,
    ) -> Option<cranpose_ui_graphics::Rect> {
        None
    }

    /// Visits each layout node the scene draws with the bounds of its rect
    /// in the window, through the graphics layers above it and its own, and
    /// on a mesh surface as the scene's camera shows it: where it shows.
    fn node_window_bounds(
        &self,
        _visit: &mut dyn FnMut(cranpose_core::NodeId, cranpose_ui_graphics::Rect),
    ) {
    }

    /// A count that grows when an update moves a layer in its parent without a layout pass, as
    /// an animated graphics layer or `offset_with` does: what read [`Self::node_window_bounds`]
    /// reads them again when it changes.
    fn layer_moves(&self) -> u64 {
        0
    }

    /// Gives back the room the scene's storage holds past what it draws. Its
    /// owner calls it at rest, when no frame waits. Returns whether the scene
    /// let every record go to give that room back: the owner builds it anew
    /// before anything reads it.
    fn trim(&mut self) -> bool {
        false
    }

    /// Whether the scene draws `node`. A scene that keeps no record of the nodes it draws says
    /// it does.
    fn draws(&self, _node: cranpose_core::NodeId) -> bool {
        true
    }

    /// The node whose record holds what the scene draws for `node`: the node the scene draws
    /// again for `node` to leave it. `None` when the scene draws no record for `node`, or that
    /// record is its root.
    fn drawn_parent(&self, _node: cranpose_core::NodeId) -> Option<cranpose_core::NodeId> {
        None
    }

    /// Adds to `left` the layout nodes whose records the scene dropped since the last call; a
    /// node may draw through another record since, as [`Self::draws`] tells. Returns whether the
    /// scene can tell: a scene handed a store built from scratch since cannot, and the caller
    /// asks [`Self::draws`] of every node instead.
    fn read_left_nodes(&mut self, _left: &mut Vec<cranpose_core::NodeId>) -> bool {
        true
    }
}

/// Abstraction implemented by concrete renderer backends.
pub trait Renderer {
    /// The scene type that holds the records and the hit targets of this renderer.
    type Scene: RenderScene;
    /// Error returned when the scene cannot be rebuilt or updated.
    type Error;

    /// Installs renderer-provided app services into the target AppContext.
    ///
    /// AppShell calls this before the first composition pass.
    /// Renderers that provide text measurement or other per-app services should install
    /// them here rather than as constructor side effects.
    fn attach_app_context_services(&mut self, _app_context: &cranpose_ui::AppContext) {}

    /// Gives back the room the renderer's storage holds past what it draws,
    /// beside its scene's. AppShell calls it at rest, when no frame waits.
    fn trim(&mut self) {}

    /// Takes in the fonts installed since the renderer last looked (see
    /// `installed_fonts::install_font_file`). A renderer that installed the
    /// app's text measurer installs one with the new faces, so text lays out
    /// again with them.
    ///
    /// AppShell calls this before the layout of a frame that follows an
    /// install.
    fn apply_installed_fonts(&mut self, _app_context: &cranpose_ui::AppContext) {}

    /// Sets how many device pixels the renderer draws for one logical unit.
    ///
    /// AppShell sets its primary renderer's scale to the density it lays
    /// out with, at construction and on every density change, so a host
    /// sets it only for the renderers of other surfaces. Renderers that take
    /// the scale with each draw ignore it.
    fn set_root_scale(&mut self, _scale: f32) {}

    /// The scene that holds the records and the hit targets.
    fn scene(&self) -> &Self::Scene;
    /// Mutable access to the scene.
    fn scene_mut(&mut self) -> &mut Self::Scene;

    /// Rebuilds the scene by traversing the LayoutNode tree directly via Applier.
    ///
    /// This is the new architecture that eliminates per-frame LayoutTree reconstruction.
    /// Implementors must read layout state from LayoutNode.layout_state() directly.
    fn rebuild_scene_from_applier(
        &mut self,
        applier: &mut MemoryApplier,
        root: cranpose_core::NodeId,
        viewport: Size,
    ) -> Result<(), Self::Error>;

    /// Updates the scene for the nodes in `updates`, and the hit targets when the update changed
    /// one or the geometry above one. The default implementation rebuilds the whole scene.
    fn update_scene_from_applier(
        &mut self,
        applier: &mut MemoryApplier,
        root: cranpose_core::NodeId,
        viewport: Size,
        updates: SceneUpdates<'_>,
    ) -> Result<(), Self::Error> {
        let _ = updates;
        self.rebuild_scene_from_applier(applier, root, viewport)
    }

    /// Updates the scene when only what is drawn changed: nothing was composed or laid out. The
    /// default implementation calls `update_scene_from_applier`.
    fn update_visual_scene_from_applier(
        &mut self,
        applier: &mut MemoryApplier,
        root: cranpose_core::NodeId,
        viewport: Size,
        updates: SceneUpdates<'_>,
    ) -> Result<(), Self::Error> {
        self.update_scene_from_applier(applier, root, viewport, updates)
    }

    /// Draw a development overlay (e.g., FPS counter) on top of the scene.
    ///
    /// This is called after the scene is built when dev options are enabled.
    /// The text, laid out in `overlay`, is drawn directly by the renderer
    /// without affecting composition.
    ///
    /// Default implementation does nothing.
    fn draw_dev_overlay(&mut self, _overlay: &cranpose_ui::PreparedTextLayout, _viewport: Size) {}

    /// Replaces the developer inspector layer drawn over the application scene.
    ///
    /// Passing `None` removes the inspector. Its primitives must not participate
    /// in application hit testing, layout, or accessibility.
    fn set_inspector_overlay(&mut self, _overlay: Option<scene_store::OverlayLayer>) {}

    /// Replaces the overlay with the layer tree `overlay` describes, as a
    /// renderer's tests describe an overlay by hand.
    ///
    /// Passing `None` removes the overlay. Default implementation does nothing.
    #[cfg(feature = "layer-tree")]
    fn set_overlay_tree(&mut self, _overlay: Option<graph::LayerNode>) {}

    /// Tells the renderer that its app held still between the last frame and the next one: the
    /// shell asked the platform for no frame and no update. A renderer that compares frames to
    /// draw only what changed counts the frames on either side of the pause apart.
    ///
    /// AppShell calls this before the first frame after such a pause.
    fn note_held_still(&mut self) {}

    /// Tells the renderer that a pointer is held on the app's controls for the coming frame: the
    /// user may move it at any moment, so the frame is not one to spend on work that holds the
    /// frames after it back, such as a WebGL program link.
    ///
    /// AppShell calls this before each frame drawn while a pointer is held.
    fn note_pointer_held(&mut self) {}

    /// Runs one step of the pipeline builds that wait for a frame, where frames run them (a WebGL
    /// page links one program at a frame's end), while the app draws none: a page that stands
    /// still still builds what its next touch draws. Returns whether builds still wait.
    ///
    /// The platform calls this in its idle periods while it has no frame to draw.
    fn build_while_idle(&mut self) -> bool {
        false
    }

    /// Returns whether renderer-side cache materialization needs a visible follow-up frame.
    fn needs_frame_warmup(&self) -> bool {
        false
    }

    /// Returns whether the last frame drew a placeholder for an effect whose
    /// pipelines are still compiling, so its picture is not final yet; the
    /// renderer asks for the frame that replaces it once they land.
    fn awaits_pipelines(&self) -> bool {
        false
    }
}