linnet/
drawing.rs

1#[cfg(test)]
2pub mod test {
3
4    use kurbo::{
5        simplify::{simplify_bezpath, SimplifyOptLevel, SimplifyOptions},
6        BezPath, Point, Rect, Shape, Size,
7    };
8    use std::{f64::consts::PI, fs::File, io::Write};
9
10    #[test]
11    fn helix() {
12        // Generate helix points
13        let alpha = 0.35;
14        let radius = 10.0;
15        let steps = 1000;
16        let t_range = (0.0, 46.0 * PI);
17        let step_size = (t_range.1 - t_range.0) / steps as f64;
18
19        let mut points = Vec::new();
20        for i in 0..=steps {
21            let t = t_range.0 + i as f64 * step_size;
22            let x = (alpha * t).sin() * radius + t;
23            let y = (alpha * t).cos() * radius;
24            points.push(Point::new(x, y));
25        }
26
27        // Create path
28        let mut path = BezPath::new();
29        path.move_to(points[0]);
30        for point in points.iter().skip(1) {
31            path.line_to(*point);
32        }
33        let options = SimplifyOptions::default().opt_level(SimplifyOptLevel::Optimize);
34        let simplified = simplify_bezpath(path.clone(), 1.0, &options);
35
36        // Get the bounding box of the path
37        let bbox: Rect = path.bounding_box();
38
39        // Define target SVG dimensions and padding
40        let svg_width = 800.0;
41        let svg_height = 600.0;
42        let padding = 50.0;
43
44        // Expand the bounding box by padding (to keep a margin)
45        let padded_bbox = Rect::from_origin_size(
46            Point::new(bbox.min_x() - padding, bbox.min_y() - padding),
47            Size::new(bbox.width() + 2.0 * padding, bbox.height() + 2.0 * padding),
48        );
49
50        // Create the SVG with a viewBox set to the padded bounding box.
51        let svg_string = format!(
52        "<svg width='{width}' height='{height}' viewBox='{min_x} {min_y} {vb_width} {vb_height}' xmlns='http://www.w3.org/2000/svg'>\n  \
53         <path d='{path}' stroke='#000' fill='none' stroke-width='2'/>\n</svg>",
54        width = svg_width,
55        height = svg_height,
56        min_x = padded_bbox.min_x(),
57        min_y = padded_bbox.min_y(),
58        vb_width = padded_bbox.width(),
59        vb_height = padded_bbox.height(),
60        path = simplified.to_svg(),
61    );
62
63        // Write to file
64        let mut file = File::create("output.svg").unwrap();
65        write!(file, "{}", svg_string).unwrap();
66    }
67}