Skip to main content

lievisual/render/
mod.rs

1//! Rendering backend trait and default traversal logic.
2//!
3//! [`Renderer`] defines the atomic drawing methods (Canvas API style). The default
4//! method [`Renderer::render_scene`] is responsible for: sorting nodes stably by
5//! `z_index` via [`crate::scene::Scene::iter_ordered`] → applying node attributes
6//! (`visible` / `opacity` / `name` / `clip`) and `Transform` → recursing into `Group`s
7//! (internally reusing [`crate::scene::SceneNode::ordered`]). It also draws the default
8//! `nodes` layer first, then each [`crate::scene::Layer`] in order
9//! ([`Renderer::render_layer`], applying `visible` / `opacity` / `transform` / `name`
10//! to the whole layer). A backend only needs to implement the atomic methods.
11//!
12//! Convention for new primitives: every `draw_*` has a default implementation that
13//! converts the geometry into a [`kurbo::BezPath`] and delegates to [`Renderer::draw_path`],
14//! so a new backend renders correctly even without overriding them. Backends may override
15//! these to emit native markup (e.g. SVG `<ellipse>` / `<rect rx>`).
16
17use crate::geometry::{Point, Rect, Transform, Vec2};
18use crate::scene::{
19    BlendMode, Element, FillStrokeStyle, Layer, NodeKind, Scene, SceneNode, Stroke,
20};
21use kurbo::Shape;
22
23pub use svg::{SvgRenderer, SvgSizing};
24pub use vello_pixmap::VelloPixmapRenderer;
25
26mod svg;
27mod vello_pixmap;
28
29/// Build an arc path in the screen (y-down) coordinate system, geometrically identical to the
30/// SVG backend's `arc_path_d`.
31///
32/// The scene (consistent across SVG / vello) uses a y-down coordinate system: origin at the
33/// top-left, y downward, 0 angle along +x, and positive angles clockwise. kurbo::Arc, however,
34/// samples mathematically in y-up: `start=(cx+r·cos a, cy+r·sin a)` with a positive sweep being
35/// counterclockwise.
36///
37/// Here we reuse kurbo's mature Bézier arc approximation (`to_path`) and then apply a
38/// y-up → y-down coordinate mapping so the sampled arc aligns exactly with the SVG backend's
39/// `arc_path_d` formula, avoiding a vertical mirror between the two backends' arcs / pies:
40/// 1. Negate the center y and angles to construct the "to-be-flipped" arc in the math plane;
41/// 2. Apply a whole y-axis flip `Affine(1,0,0,-1)` to map math coordinates back to screen.
42pub(crate) fn arc_path_y_down(
43    center: Point,
44    radii: Vec2,
45    start_angle: f64,
46    sweep_angle: f64,
47) -> kurbo::BezPath {
48    // Scene y-down → math y-up: negate the center y and angle signs (0 angle unchanged,
49    // clockwise/counterclockwise swap).
50    let arc = kurbo::Arc::new(
51        (center.x, -center.y),
52        (radii.x, radii.y),
53        -start_angle,
54        -sweep_angle,
55        0.0,
56    )
57    .to_path(0.1);
58    // Math y-up → scene y-down: flip the whole y-axis (x unchanged).
59    let mut path = arc;
60    path.apply_affine(kurbo::Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]));
61    path
62}
63
64/// Rendering backend interface (Canvas API style).
65///
66/// Callers (liecharts / liemermaid / liepress) build a [`Scene`] and then pick a
67/// `Renderer` implementation to emit the target medium. Adding a backend does not affect
68/// the intermediate representation.
69pub trait Renderer {
70    /// Draw an axis-aligned rectangle.
71    fn draw_rect(&mut self, rect: Rect, style: &FillStrokeStyle);
72
73    /// Draw a circle.
74    fn draw_circle(&mut self, center: Point, radius: f64, style: &FillStrokeStyle);
75
76    /// Draw an ellipse (`radii` are the two semi-axis lengths, `rotation` is the angle
77    /// around the center).
78    fn draw_ellipse(&mut self, center: Point, radii: Vec2, rotation: f64, style: &FillStrokeStyle) {
79        let path =
80            kurbo::Ellipse::new((center.x, center.y), (radii.x, radii.y), rotation).to_path(0.1);
81        self.draw_path(&path, style, true);
82    }
83
84    /// Draw a rounded rectangle with a uniform corner radius.
85    fn draw_rounded_rect(&mut self, rect: Rect, radius: f64, style: &FillStrokeStyle) {
86        self.draw_rounded_rect_radii(rect, crate::scene::CornerRadii::uniform(radius), style);
87    }
88
89    /// Draw a rounded rectangle with **per-corner** radii.
90    ///
91    /// The default builds a Bézier path (kurbo `RoundedRectRadii`) and delegates to
92    /// [`Renderer::draw_path`], so any backend can render it. A backend with a native rounded-rect
93    /// tag (SVG's `<rect rx="…">`) should only use it for the *uniform* case — `<rect rx>` cannot
94    /// express four different radii — which is exactly what [`Renderer::draw_element`] arranges:
95    /// it routes a uniform `Element::RoundedRect` to [`Renderer::draw_rounded_rect`] and a
96    /// per-corner one here.
97    fn draw_rounded_rect_radii(
98        &mut self,
99        rect: Rect,
100        radii: crate::scene::CornerRadii,
101        style: &FillStrokeStyle,
102    ) {
103        let path = kurbo::RoundedRect::from_rect(rect, radii.to_kurbo()).to_path(0.1);
104        self.draw_path(&path, style, true);
105    }
106
107    /// Draw a line segment.
108    fn draw_line(&mut self, start: Point, end: Point, style: &Stroke);
109
110    /// Draw a polyline (multiple connected segments, open, stroke only).
111    fn draw_polyline(&mut self, points: &[Point], style: &Stroke);
112
113    /// Draw a polygon (closed, filled + optional stroke).
114    fn draw_polygon(&mut self, points: &[Point], style: &FillStrokeStyle) {
115        let mut path = kurbo::BezPath::new();
116        if let Some(p0) = points.first() {
117            path.move_to((p0.x, p0.y));
118            for p in &points[1..] {
119                path.line_to((p.x, p.y));
120            }
121            path.close_path();
122        }
123        self.draw_path(&path, style, false);
124    }
125
126    /// Draw an arc (open, stroke only).
127    fn draw_arc(
128        &mut self,
129        center: Point,
130        radii: Vec2,
131        start_angle: f64,
132        sweep_angle: f64,
133        style: &Stroke,
134    ) {
135        let path = crate::render::arc_path_y_down(center, radii, start_angle, sweep_angle);
136        let style = FillStrokeStyle {
137            fill: None,
138            stroke: Some(style.clone()),
139        };
140        self.draw_path(&path, &style, false);
141    }
142
143    /// Draw a pie sector (closed, including the two radius edges from the center to the
144    /// arc endpoints, filled + optional stroke).
145    fn draw_pie(
146        &mut self,
147        center: Point,
148        radius: f64,
149        start_angle: f64,
150        sweep_angle: f64,
151        style: &FillStrokeStyle,
152    ) {
153        let mut path = kurbo::BezPath::new();
154        path.move_to((center.x, center.y));
155        let arc = crate::render::arc_path_y_down(
156            center,
157            Vec2::new(radius, radius),
158            start_angle,
159            sweep_angle,
160        );
161        // The arc path starts with MoveTo(start); replace it with LineTo(start) so the whole
162        // path becomes `M center L start [arc...] end Z` -- a true pie sector (with the center
163        // vertex and the two radius edges), matching the SVG backend's `M center L start A end Z`.
164        let mut els = arc.elements().iter();
165        if let Some(kurbo::PathEl::MoveTo(p0)) = els.next() {
166            path.line_to(*p0);
167            for el in els {
168                path.push(*el);
169            }
170        } else {
171            path.extend(arc);
172        }
173        path.close_path();
174        self.draw_path(&path, style, false);
175    }
176
177    /// Draw a path (optionally closed for fill or stroke).
178    fn draw_path(&mut self, path: &kurbo::BezPath, style: &FillStrokeStyle, closed: bool);
179
180    /// Draw a path with a linear-gradient fill.
181    fn draw_gradient_path(
182        &mut self,
183        path: &kurbo::BezPath,
184        gradient: &crate::scene::LinearGradient,
185        stroke: Option<&crate::scene::Stroke>,
186    );
187
188    /// Draw text. The styled `spans` are the core content; when `layout` is provided it
189    /// takes precedence.
190    ///
191    /// Non-parley backends (e.g. SVG) should concatenate the `spans` into plain text;
192    /// `style` provides block-level placement (`align` / `baseline` / `rotation` /
193    /// `max_width`).
194    fn draw_text(
195        &mut self,
196        spans: &[crate::text::RichSpan],
197        position: Point,
198        style: &crate::text::TextStyle,
199        layout: Option<&crate::text::TextLayout>,
200    );
201
202    /// Draw an image: `image` is a self-contained RGBA8 bitmap and `frame` is the display
203    /// rectangle (pt/px coordinates).
204    ///
205    /// The backend consumes `image.pixmap` directly (already decoded, **no further
206    /// decoding needed**) and maps it onto `frame` according to `image.object_fit`.
207    /// The default implementation is empty (backends should override it to actually draw).
208    fn draw_image(&mut self, image: &crate::SceneImage, frame: Rect, opacity: f64) {
209        let _ = (image, frame, opacity);
210    }
211
212    /// Enter a transform scope (for a Group or node-local transform).
213    /// Empty by default; backends with stack-based state (vello / svg group) should
214    /// override.
215    fn push_transform(&mut self, _t: Transform) {}
216    /// Exit the scope established by [`Renderer::push_transform`].
217    fn pop_transform(&mut self) {}
218
219    /// Enter an opacity scope (for a node / subtree with `opacity < 1`). Empty by default.
220    fn push_opacity(&mut self, _opacity: f64) {}
221    /// Exit the scope established by [`Renderer::push_opacity`].
222    fn pop_opacity(&mut self) {}
223
224    /// Enter a blend-mode scope: everything drawn until [`Renderer::pop_blend`] is composited
225    /// with the backdrop using `mode`. Empty by default (backends without blend support ignore
226    /// it, degrading to [`BlendMode::Normal`]).
227    fn push_blend(&mut self, _mode: BlendMode) {}
228    /// Exit the scope established by [`Renderer::push_blend`].
229    fn pop_blend(&mut self) {}
230
231    /// Enter a mask scope: everything drawn until [`Renderer::pop_mask`] has its composited alpha
232    /// multiplied by `mask`. Empty by default (backends without mask support ignore it).
233    fn push_mask(&mut self, _mask: &crate::scene::Mask) {}
234    /// Exit the scope established by [`Renderer::push_mask`].
235    fn pop_mask(&mut self) {}
236
237    /// Enter a filter scope: everything drawn until [`Renderer::pop_filter`] is rendered into an
238    /// offscreen layer and filtered (blur / drop shadow). Empty by default.
239    fn push_filter(&mut self, _filter: &crate::scene::Filter) {}
240    /// Exit the scope established by [`Renderer::push_filter`].
241    fn pop_filter(&mut self) {}
242
243    /// Enter a named scope (for a node with `name`; emits `id` on the SVG side).
244    /// `name` is an `Option`: `None` means no `id` attribute is emitted.
245    fn push_name(&mut self, _name: Option<&str>) {}
246    /// Exit the scope established by [`Renderer::push_name`].
247    fn pop_name(&mut self) {}
248
249    /// Enter a clip scope (for a node / subtree with `clip`). Empty by default.
250    fn push_clip(&mut self, _clip: &crate::scene::Clip) {}
251    /// Exit the scope established by [`Renderer::push_clip`].
252    fn pop_clip(&mut self) {}
253
254    /// Enter a colour-matrix scope: every **paint colour** emitted until
255    /// [`Renderer::pop_color_matrix`] is transformed by `matrix`.
256    ///
257    /// Empty by default (a backend without colour support simply ignores it). Backends that
258    /// implement it accumulate the matrix down the tree with [`ColorMatrix::then`] and apply it
259    /// where paint colours are built — this is deliberately *not* an offscreen post-process; see
260    /// [`crate::scene::ColorMatrix`].
261    fn push_color_matrix(&mut self, _matrix: crate::scene::ColorMatrix) {}
262    /// Exit the scope established by [`Renderer::push_color_matrix`].
263    fn pop_color_matrix(&mut self) {}
264
265    /// Enter an anti-aliasing scope: shapes drawn until [`Renderer::pop_antialias`] use
266    /// `enabled` anti-aliasing.
267    ///
268    /// Empty by default. Backends implement it as a *draw state* (SVG `shape-rendering`, vello's
269    /// aliasing threshold) rather than a compositing layer.
270    fn push_antialias(&mut self, _enabled: bool) {}
271    /// Exit the scope established by [`Renderer::push_antialias`].
272    fn pop_antialias(&mut self) {}
273
274    /// Enter a compositing scope: stacks transform, clip, filter, opacity, blend, mask and name,
275    /// in exactly that order.
276    ///
277    /// The **single** implementation of "what does a subtree attribute scope look like", shared by
278    /// [`Renderer::push_node_scope`] (a node) and [`Renderer::render_layer`] (a layer — a named
279    /// root group). Pop order is the reverse; see [`Renderer::pop_scope`].
280    fn push_scope(&mut self, scope: &crate::scene::NodeScope) {
281        if let Some(t) = scope.transform {
282            self.push_transform(t);
283        }
284        if let Some(clip) = scope.clip {
285            self.push_clip(clip);
286        }
287        // Anti-aliasing is a draw hint, not a compositing layer: it only needs to be active while
288        // the subtree's geometry is emitted.
289        if let Some(enabled) = scope.antialias {
290            self.push_antialias(enabled);
291        }
292        // A colour matrix is *baked into the paints*, so it must be active before the subtree
293        // emits any colour — and before `filter`, which then sees the baked colours.
294        if let Some(matrix) = scope.color_matrix {
295            self.push_color_matrix(matrix);
296        }
297        // Filter is applied to the subtree's rendered content, before opacity / blend / mask
298        // (mirrors CSS `filter` → opacity → `mix-blend-mode`).
299        if let Some(filter) = scope.filter {
300            self.push_filter(filter);
301        }
302        if scope.opacity != 1.0 {
303            self.push_opacity(scope.opacity);
304        }
305        // Blend is pushed after opacity so it forms the outer compositing layer: the scope's
306        // content is first scaled by opacity, then blended with the backdrop.
307        if !scope.blend_mode.is_normal() {
308            self.push_blend(scope.blend_mode);
309        }
310        // Mask is outermost of the compositing scopes: it multiplies the final alpha of the
311        // (opacity- and blend-applied) subtree.
312        if let Some(mask) = scope.mask {
313            self.push_mask(mask);
314        }
315        if let Some(name) = scope.name {
316            self.push_name(Some(name));
317        }
318    }
319
320    /// Exit the scope established by [`Renderer::push_scope`] (pops in reverse order).
321    fn pop_scope(&mut self, scope: &crate::scene::NodeScope) {
322        if scope.name.is_some() {
323            self.pop_name();
324        }
325        if scope.mask.is_some() {
326            self.pop_mask();
327        }
328        if !scope.blend_mode.is_normal() {
329            self.pop_blend();
330        }
331        if scope.opacity != 1.0 {
332            self.pop_opacity();
333        }
334        if scope.filter.is_some() {
335            self.pop_filter();
336        }
337        if scope.color_matrix.is_some() {
338            self.pop_color_matrix();
339        }
340        if scope.antialias.is_some() {
341            self.pop_antialias();
342        }
343        if scope.clip.is_some() {
344            self.pop_clip();
345        }
346        if scope.transform.is_some() {
347            self.pop_transform();
348        }
349    }
350
351    /// Enter the node-level scope (delegates to [`Renderer::push_scope`]).
352    fn push_node_scope(&mut self, node: &SceneNode) {
353        self.push_scope(&node.scope());
354    }
355
356    /// Exit the scope established by [`Renderer::push_node_scope`].
357    fn pop_node_scope(&mut self, node: &SceneNode) {
358        self.pop_scope(&node.scope());
359    }
360
361    /// Render the whole scene: the default implementation handles sorting and recursion.
362    /// A backend may override this to capture [`Scene`] metadata (title / description /
363    /// scale), then call [`Renderer::render_scene_ordered`] to reuse the default traversal.
364    fn render_scene(&mut self, scene: &Scene) {
365        self.render_scene_ordered(scene);
366    }
367
368    /// Draw a slice of nodes in stable ascending `z_index` order.
369    ///
370    /// The single recursion shared by the default node list, [`Layer`]s and [`NodeKind::Group`]
371    /// containers: each level is sorted by `z_index`, then every node goes through
372    /// [`Renderer::render_node`] (which applies the node scope and recurses into nested groups).
373    fn render_children(&mut self, nodes: &[SceneNode]) {
374        for node in SceneNode::ordered(nodes) {
375            self.render_node(node);
376        }
377    }
378
379    /// Default traversal: draws the default `nodes` layer first (bottommost, sorted
380    /// stably by ascending `z_index`), then each [`Layer`] in array order from bottom to
381    /// top.
382    fn render_scene_ordered(&mut self, scene: &Scene) {
383        self.render_children(&scene.nodes);
384        for layer in &scene.layers {
385            self.render_layer(layer);
386        }
387    }
388
389    /// Render a single layer: apply the layer-level scope, then render each node inside the layer
390    /// stably by ascending `z_index` (including container recursion). Rarely needs to be
391    /// overridden.
392    ///
393    /// A layer is a named root group, so it reuses the very same scope path as a node
394    /// ([`Renderer::push_scope`]) instead of duplicating the push / pop sequence.
395    fn render_layer(&mut self, layer: &Layer) {
396        if !layer.visible {
397            return;
398        }
399        let scope = layer.scope();
400        self.push_scope(&scope);
401        self.render_children(&layer.nodes);
402        self.pop_scope(&scope);
403    }
404
405    /// Render a single node: enter the node's scope, draw its content (a leaf primitive, or a
406    /// container's children), then leave the scope. Rarely needs to be overridden.
407    fn render_node(&mut self, node: &SceneNode) {
408        // Skip the whole subtree for a hidden node.
409        if !node.visible {
410            return;
411        }
412        // Enter the node scope (transform + clip + compositing + name).
413        self.push_node_scope(node);
414
415        match &node.kind {
416            // A container: children are drawn stably by ascending z_index (the same recursion
417            // used by layers / the default node list).
418            NodeKind::Group(children) => self.render_children(children),
419            // A leaf: dispatch to the atomic drawing method.
420            NodeKind::Draw(element) => self.draw_element(element),
421        }
422
423        self.pop_node_scope(node);
424    }
425
426    /// Draw one leaf primitive, dispatching to the atomic `draw_*` methods.
427    ///
428    /// This is the single place that knows every [`Element`] variant; a backend (or a custom pass)
429    /// that wants to draw an element outside the standard traversal can reuse it.
430    fn draw_element(&mut self, element: &Element) {
431        match element {
432            Element::Rect { rect, style } => self.draw_rect(*rect, style),
433            Element::Circle {
434                center,
435                radius,
436                style,
437            } => self.draw_circle(*center, *radius, style),
438            Element::Ellipse {
439                center,
440                radii,
441                rotation,
442                style,
443            } => self.draw_ellipse(*center, *radii, *rotation, style),
444            // A native rounded-rect tag can only carry one radius, so a per-corner shape goes
445            // through the (path-based) radii entry point instead.
446            Element::RoundedRect { rect, radii, style } => {
447                if radii.is_uniform() {
448                    self.draw_rounded_rect(*rect, radii.uniform_value(), style);
449                } else {
450                    self.draw_rounded_rect_radii(*rect, *radii, style);
451                }
452            }
453            Element::Line { start, end, style } => self.draw_line(*start, *end, style),
454            Element::Polyline { points, style } => self.draw_polyline(points, style),
455            Element::Polygon { points, style } => self.draw_polygon(points, style),
456            Element::Arc {
457                center,
458                radii,
459                start_angle,
460                sweep_angle,
461                style,
462            } => self.draw_arc(*center, *radii, *start_angle, *sweep_angle, style),
463            Element::Pie {
464                center,
465                radius,
466                start_angle,
467                sweep_angle,
468                style,
469            } => self.draw_pie(*center, *radius, *start_angle, *sweep_angle, style),
470            Element::Path {
471                path,
472                style,
473                closed,
474            } => self.draw_path(path, style, *closed),
475            Element::Image {
476                image,
477                frame,
478                opacity,
479            } => self.draw_image(image, *frame, *opacity),
480            Element::GradientPath {
481                path,
482                gradient,
483                stroke,
484            } => self.draw_gradient_path(path, gradient, stroke.as_ref()),
485            Element::Text {
486                spans,
487                position,
488                style,
489                layout,
490            } => self.draw_text(spans, *position, style, layout.as_deref()),
491        }
492    }
493}
494
495#[cfg(test)]
496mod tests {
497    use crate::geometry::{Point, Vec2};
498
499    /// The screen (y-down) endpoint formula, identical to the SVG backend's `arc_path_d`.
500    /// start = (cx + rx·cos a, cy + ry·sin a), end = (cx + rx·cos(a+s), cy + ry·sin(a+s)).
501    fn expected_screen_points(
502        center: Point,
503        radii: Vec2,
504        start_angle: f64,
505        sweep_angle: f64,
506    ) -> (Point, Point) {
507        let start = Point::new(
508            center.x + radii.x * start_angle.cos(),
509            center.y + radii.y * start_angle.sin(),
510        );
511        let end_angle = start_angle + sweep_angle;
512        let end = Point::new(
513            center.x + radii.x * end_angle.cos(),
514            center.y + radii.y * end_angle.sin(),
515        );
516        (start, end)
517    }
518
519    /// Verify that the arc endpoints generated by the vello backend's `arc_path_y_down` match
520    /// the SVG `arc_path_d` formula, ensuring the pie/arc shapes drawn by both backends align
521    /// exactly (they were once vertically mirrored because kurbo's math coordinates were not
522    /// flipped).
523    #[test]
524    fn arc_y_down_matches_svg_geometry() {
525        let cases = [
526            (
527                Point::new(300.0, 320.0),
528                Vec2::new(70.0, 70.0),
529                0.0f64,
530                std::f64::consts::FRAC_PI_2,
531            ),
532            (
533                Point::new(300.0, 320.0),
534                Vec2::new(70.0, 70.0),
535                std::f64::consts::FRAC_PI_2,
536                std::f64::consts::FRAC_PI_2,
537            ),
538            (
539                Point::new(300.0, 320.0),
540                Vec2::new(70.0, 70.0),
541                std::f64::consts::PI,
542                -std::f64::consts::FRAC_PI_2,
543            ),
544            (Point::new(100.0, 100.0), Vec2::new(40.0, 20.0), 0.4, 2.7),
545        ];
546        for (center, radii, a, s) in cases {
547            let path = crate::render::arc_path_y_down(center, radii, a, s);
548            // Pure arc path: elements start with MoveTo(start), then CurveTo endpoints are
549            // appended in order, so pts[0] is the arc start and pts[last] is the arc end.
550            let pts: Vec<Point> = path
551                .elements()
552                .iter()
553                .filter_map(|el| match el {
554                    kurbo::PathEl::MoveTo(p)
555                    | kurbo::PathEl::LineTo(p)
556                    | kurbo::PathEl::QuadTo(_, p)
557                    | kurbo::PathEl::CurveTo(_, _, p) => Some(Point::new(p.x, p.y)),
558                    kurbo::PathEl::ClosePath => None,
559                })
560                .collect();
561            let n = pts.len();
562            assert!(n >= 2, "arc path should have at least 2 points");
563            let got_start = pts[0];
564            let got_end = pts[n - 1];
565            let (exp_start, exp_end) = expected_screen_points(center, radii, a, s);
566            let eps = 1e-6;
567            assert!(
568                (got_start.x - exp_start.x).abs() < eps && (got_start.y - exp_start.y).abs() < eps,
569                "start mismatch: got {:?} expected {:?} (center={:?} radii={:?} a={} s={})",
570                got_start,
571                exp_start,
572                center,
573                radii,
574                a,
575                s
576            );
577            assert!(
578                (got_end.x - exp_end.x).abs() < eps && (got_end.y - exp_end.y).abs() < eps,
579                "end mismatch: got {:?} expected {:?} (center={:?} radii={:?} a={} s={})",
580                got_end,
581                exp_end,
582                center,
583                radii,
584                a,
585                s
586            );
587        }
588    }
589}