Skip to main content

usvg/parser/
shapes.rs

1// Copyright 2018 the Resvg Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use std::sync::Arc;
5
6use svgtypes::Length;
7use tiny_skia_path::Path;
8
9use super::svgtree::{AId, EId, SvgNode};
10use super::{converter, units};
11use crate::{ApproxEqUlps, IsValidLength, Rect};
12
13pub(crate) fn convert(node: SvgNode, state: &converter::State) -> Option<Arc<Path>> {
14    match node.tag_name()? {
15        EId::Rect => convert_rect(node, state),
16        EId::Circle => convert_circle(node, state),
17        EId::Ellipse => convert_ellipse(node, state),
18        EId::Line => convert_line(node, state),
19        EId::Polyline => convert_polyline(node),
20        EId::Polygon => convert_polygon(node),
21        EId::Path => convert_path(node),
22        _ => None,
23    }
24}
25
26pub(crate) fn convert_path(node: SvgNode) -> Option<Arc<Path>> {
27    let value: &str = node.attribute(AId::D)?;
28    convert_path_data(value)
29}
30
31pub(crate) fn convert_path_data(value: &str) -> Option<Arc<Path>> {
32    let mut builder = tiny_skia_path::PathBuilder::new();
33    for segment in svgtypes::SimplifyingPathParser::from(value) {
34        let segment = match segment {
35            Ok(v) => v,
36            Err(e) => {
37                log::warn!("Error during path parsing: {e}");
38                break;
39            }
40        };
41
42        match segment {
43            svgtypes::SimplePathSegment::MoveTo { x, y } => {
44                builder.move_to(x as f32, y as f32);
45            }
46            svgtypes::SimplePathSegment::LineTo { x, y } => {
47                builder.line_to(x as f32, y as f32);
48            }
49            svgtypes::SimplePathSegment::Quadratic { x1, y1, x, y } => {
50                builder.quad_to(x1 as f32, y1 as f32, x as f32, y as f32);
51            }
52            svgtypes::SimplePathSegment::CurveTo {
53                x1,
54                y1,
55                x2,
56                y2,
57                x,
58                y,
59            } => {
60                builder.cubic_to(
61                    x1 as f32, y1 as f32, x2 as f32, y2 as f32, x as f32, y as f32,
62                );
63            }
64            svgtypes::SimplePathSegment::ClosePath => {
65                builder.close();
66            }
67        }
68    }
69
70    builder.finish().map(Arc::new)
71}
72
73fn convert_rect(node: SvgNode, state: &converter::State) -> Option<Arc<Path>> {
74    // 'width' and 'height' attributes must be positive and non-zero.
75    let width = node.convert_user_length(AId::Width, state, Length::zero());
76    let height = node.convert_user_length(AId::Height, state, Length::zero());
77    if !width.is_valid_length() {
78        log::warn!(
79            "Rect '{}' has an invalid 'width' value. Skipped.",
80            node.element_id()
81        );
82        return None;
83    }
84    if !height.is_valid_length() {
85        log::warn!(
86            "Rect '{}' has an invalid 'height' value. Skipped.",
87            node.element_id()
88        );
89        return None;
90    }
91
92    let x = node.convert_user_length(AId::X, state, Length::zero());
93    let y = node.convert_user_length(AId::Y, state, Length::zero());
94
95    let (mut rx, mut ry) = resolve_rx_ry(node, state);
96
97    // Clamp rx/ry to the half of the width/height.
98    //
99    // Should be done only after resolving.
100    if rx > width / 2.0 {
101        rx = width / 2.0;
102    }
103    if ry > height / 2.0 {
104        ry = height / 2.0;
105    }
106
107    // Conversion according to https://www.w3.org/TR/SVG11/shapes.html#RectElement
108    let path = if rx.approx_eq_ulps(&0.0, 4) {
109        tiny_skia_path::PathBuilder::from_rect(Rect::from_xywh(x, y, width, height)?)
110    } else {
111        let mut builder = tiny_skia_path::PathBuilder::new();
112        builder.move_to(x + rx, y);
113
114        builder.line_to(x + width - rx, y);
115        builder.arc_to(rx, ry, 0.0, false, true, x + width, y + ry);
116
117        builder.line_to(x + width, y + height - ry);
118        builder.arc_to(rx, ry, 0.0, false, true, x + width - rx, y + height);
119
120        builder.line_to(x + rx, y + height);
121        builder.arc_to(rx, ry, 0.0, false, true, x, y + height - ry);
122
123        builder.line_to(x, y + ry);
124        builder.arc_to(rx, ry, 0.0, false, true, x + rx, y);
125
126        builder.close();
127
128        builder.finish()?
129    };
130
131    Some(Arc::new(path))
132}
133
134fn resolve_rx_ry(node: SvgNode, state: &converter::State) -> (f32, f32) {
135    let mut rx_opt = node.attribute::<Length>(AId::Rx);
136    let mut ry_opt = node.attribute::<Length>(AId::Ry);
137
138    // Remove negative values first.
139    if let Some(v) = rx_opt {
140        if v.number.is_sign_negative() {
141            rx_opt = None;
142        }
143    }
144    if let Some(v) = ry_opt {
145        if v.number.is_sign_negative() {
146            ry_opt = None;
147        }
148    }
149
150    // Resolve.
151    match (rx_opt, ry_opt) {
152        (None, None) => (0.0, 0.0),
153        (Some(rx), None) => {
154            let rx = units::convert_user_length(rx, node, AId::Rx, state);
155            (rx, rx)
156        }
157        (None, Some(ry)) => {
158            let ry = units::convert_user_length(ry, node, AId::Ry, state);
159            (ry, ry)
160        }
161        (Some(rx), Some(ry)) => {
162            let rx = units::convert_user_length(rx, node, AId::Rx, state);
163            let ry = units::convert_user_length(ry, node, AId::Ry, state);
164            (rx, ry)
165        }
166    }
167}
168
169fn convert_line(node: SvgNode, state: &converter::State) -> Option<Arc<Path>> {
170    let x1 = node.convert_user_length(AId::X1, state, Length::zero());
171    let y1 = node.convert_user_length(AId::Y1, state, Length::zero());
172    let x2 = node.convert_user_length(AId::X2, state, Length::zero());
173    let y2 = node.convert_user_length(AId::Y2, state, Length::zero());
174
175    let mut builder = tiny_skia_path::PathBuilder::new();
176    builder.move_to(x1, y1);
177    builder.line_to(x2, y2);
178    builder.finish().map(Arc::new)
179}
180
181fn convert_polyline(node: SvgNode) -> Option<Arc<Path>> {
182    let builder = points_to_path(node, "Polyline")?;
183    builder.finish().map(Arc::new)
184}
185
186fn convert_polygon(node: SvgNode) -> Option<Arc<Path>> {
187    let mut builder = points_to_path(node, "Polygon")?;
188    builder.close();
189    builder.finish().map(Arc::new)
190}
191
192fn points_to_path(node: SvgNode, eid: &str) -> Option<tiny_skia_path::PathBuilder> {
193    use svgtypes::PointsParser;
194
195    let mut builder = tiny_skia_path::PathBuilder::new();
196    match node.attribute::<&str>(AId::Points) {
197        Some(text) => {
198            for (x, y) in PointsParser::from(text) {
199                if builder.is_empty() {
200                    builder.move_to(x as f32, y as f32);
201                } else {
202                    builder.line_to(x as f32, y as f32);
203                }
204            }
205        }
206        _ => {
207            log::warn!(
208                "{} '{}' has an invalid 'points' value. Skipped.",
209                eid,
210                node.element_id()
211            );
212            return None;
213        }
214    };
215
216    // 'polyline' and 'polygon' elements must contain at least 2 points.
217    if builder.len() < 2 {
218        log::warn!(
219            "{} '{}' has less than 2 points. Skipped.",
220            eid,
221            node.element_id()
222        );
223        return None;
224    }
225
226    Some(builder)
227}
228
229fn convert_circle(node: SvgNode, state: &converter::State) -> Option<Arc<Path>> {
230    let cx = node.convert_user_length(AId::Cx, state, Length::zero());
231    let cy = node.convert_user_length(AId::Cy, state, Length::zero());
232    let r = node.convert_user_length(AId::R, state, Length::zero());
233
234    if !r.is_valid_length() {
235        log::warn!(
236            "Circle '{}' has an invalid 'r' value. Skipped.",
237            node.element_id()
238        );
239        return None;
240    }
241
242    ellipse_to_path(cx, cy, r, r)
243}
244
245fn convert_ellipse(node: SvgNode, state: &converter::State) -> Option<Arc<Path>> {
246    let cx = node.convert_user_length(AId::Cx, state, Length::zero());
247    let cy = node.convert_user_length(AId::Cy, state, Length::zero());
248    let (rx, ry) = resolve_rx_ry(node, state);
249
250    if !rx.is_valid_length() {
251        log::warn!(
252            "Ellipse '{}' has an invalid 'rx' value. Skipped.",
253            node.element_id()
254        );
255        return None;
256    }
257
258    if !ry.is_valid_length() {
259        log::warn!(
260            "Ellipse '{}' has an invalid 'ry' value. Skipped.",
261            node.element_id()
262        );
263        return None;
264    }
265
266    ellipse_to_path(cx, cy, rx, ry)
267}
268
269fn ellipse_to_path(cx: f32, cy: f32, rx: f32, ry: f32) -> Option<Arc<Path>> {
270    let mut builder = tiny_skia_path::PathBuilder::new();
271    builder.move_to(cx + rx, cy);
272    builder.arc_to(rx, ry, 0.0, false, true, cx, cy + ry);
273    builder.arc_to(rx, ry, 0.0, false, true, cx - rx, cy);
274    builder.arc_to(rx, ry, 0.0, false, true, cx, cy - ry);
275    builder.arc_to(rx, ry, 0.0, false, true, cx + rx, cy);
276    builder.close();
277    builder.finish().map(Arc::new)
278}
279
280trait PathBuilderExt {
281    fn arc_to(
282        &mut self,
283        rx: f32,
284        ry: f32,
285        x_axis_rotation: f32,
286        large_arc: bool,
287        sweep: bool,
288        x: f32,
289        y: f32,
290    );
291}
292
293impl PathBuilderExt for tiny_skia_path::PathBuilder {
294    fn arc_to(
295        &mut self,
296        rx: f32,
297        ry: f32,
298        x_axis_rotation: f32,
299        large_arc: bool,
300        sweep: bool,
301        x: f32,
302        y: f32,
303    ) {
304        let prev = match self.last_point() {
305            Some(v) => v,
306            None => return,
307        };
308
309        let svg_arc = kurbo::SvgArc {
310            from: kurbo::Point::new(prev.x as f64, prev.y as f64),
311            to: kurbo::Point::new(x as f64, y as f64),
312            radii: kurbo::Vec2::new(rx as f64, ry as f64),
313            x_rotation: (x_axis_rotation as f64).to_radians(),
314            large_arc,
315            sweep,
316        };
317
318        match kurbo::Arc::from_svg_arc(&svg_arc) {
319            Some(arc) => {
320                arc.to_cubic_beziers(0.1, |p1, p2, p| {
321                    self.cubic_to(
322                        p1.x as f32,
323                        p1.y as f32,
324                        p2.x as f32,
325                        p2.y as f32,
326                        p.x as f32,
327                        p.y as f32,
328                    );
329                });
330            }
331            None => {
332                self.line_to(x, y);
333            }
334        }
335    }
336}