csgrs 0.20.1

Constructive solid geometry (CSG) on meshes using BSP trees in Rust
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
//! SVG input and output.

use geo::{
    BoundingRect, Coord, CoordNum, CoordsIter, LineString, MapCoords, MultiLineString, Polygon,
};
use svg::node::element::path;

use crate::float_types::Real;
use crate::sketch::Sketch;
use crate::traits::CSG;

use super::IoError;

/// A helper struct to build [`geo::MultiLineString`] from SVG Path commands.
///
/// The API aims to be compatible with the [SVG 1.1 Paths specification][svg-paths].
/// The single instance of this struct is meant to be used for building paths from a single
/// `d` attribute of an SVG `<path/>`.
///
/// In method documentation:
/// - *Current path* refers to the part of the path that was started by the most recent `M`/`m` (moveto/moveby) command
/// - *Current point* refers to the last point of the current path
/// - Method names correspond to SVG Path commands
/// - Method suffix `_to` indicates a command that uses absolute coordinates
/// - Method suffix `_by` indicates a command that uses relative coordinates
///
/// **At the moment, curves are not supported.**
/// When support for curves is implemented, the underlying data structure may change to accommodate that.
///
/// [svg-paths]: https://www.w3.org/TR/SVG11/paths.html
struct PathBuilder<F: CoordNum> {
    inner: MultiLineString<F>,
}

impl<F: CoordNum> From<PathBuilder<F>> for MultiLineString<F> {
    fn from(val: PathBuilder<F>) -> Self {
        val.inner
    }
}

impl<F: CoordNum> PathBuilder<F> {
    pub fn new() -> Self {
        Self {
            inner: MultiLineString::new(vec![]),
        }
    }

    /// Get the current position to be used for relative moves.
    fn get_pos(&self) -> Coord<F> {
        self.inner
            .0
            .last()
            .and_then(|ls| ls.0.last())
            .copied()
            .unwrap_or(Coord::zero())
    }

    /// Get a mutable reference to the current path, or an error if no path has been started.
    ///
    /// To accommodate for the semantics of [`close`], this function will automatically start a new path
    /// if the last path has 2 or more points and is closed.
    /// For this reason, using this proxy is recommended for implementing any drawing command.
    fn get_path_mut_or_fail(&mut self) -> Result<&mut LineString<F>, IoError> {
        let start_new_path = self
            .inner
            .0
            .last()
            .map(|p| p.coords_count() >= 2 && p.is_closed())
            .unwrap_or(false);

        if start_new_path {
            self.inner.0.push(LineString::new(vec![self.get_pos()]));
        }

        self.inner.0.last_mut().ok_or_else(|| {
            IoError::MalformedPath(
                "Attempted to extend the current path, but no path was started.".to_string(),
            )
        })
    }

    /// Start a new path at `point`.
    pub fn move_to(&mut self, point: Coord<F>) {
        self.inner.0.push(LineString::new(vec![point]));
    }

    /// Start a new path at `delta` relative to the last point.
    /// If and only if this is the first command, the point is treated as absolute coordinates.
    pub fn move_by(&mut self, delta: Coord<F>) {
        let pos = self.get_pos();
        self.inner.0.push(LineString::new(vec![pos + delta]));
    }

    /// Extend the current path to the `point`.
    /// Can not be the first command.
    pub fn line_to(&mut self, point: Coord<F>) -> Result<(), IoError> {
        let line = self.get_path_mut_or_fail()?;
        line.0.push(point);
        Ok(())
    }

    /// Extend the current path by `delta` relative to the current point.
    /// Can not be the first command.
    pub fn line_by(&mut self, delta: Coord<F>) -> Result<(), IoError> {
        let pos = self.get_pos();
        let line = self.get_path_mut_or_fail()?;
        line.0.push(pos + delta);
        Ok(())
    }

    /// Extend the current path with a horizontal move to `x`.
    /// Can not be the first command.
    pub fn hline_to(&mut self, x: F) -> Result<(), IoError> {
        let Coord { y, .. } = self.get_pos();
        let line = self.get_path_mut_or_fail()?;
        line.0.push(Coord { x, y });
        Ok(())
    }

    /// Extend the current path with a horizontal move by `dx` relative to the current point.
    /// Can not be the first command.
    pub fn hline_by(&mut self, dx: F) -> Result<(), IoError> {
        let Coord { x, y } = self.get_pos();
        let line = self.get_path_mut_or_fail()?;
        line.0.push(Coord { x: x + dx, y });
        Ok(())
    }

    /// Extend the current path with a vertical move to `y`.
    /// Can not be the first command.
    pub fn vline_to(&mut self, y: F) -> Result<(), IoError> {
        let Coord { x, .. } = self.get_pos();
        let line = self.get_path_mut_or_fail()?;
        line.0.push(Coord { x, y });
        Ok(())
    }

    /// Extend the current path with a vertical move by `dy` relative to the current point.
    /// Can not be the first command.
    pub fn vline_by(&mut self, dy: F) -> Result<(), IoError> {
        let Coord { x, y } = self.get_pos();
        let line = self.get_path_mut_or_fail()?;
        line.0.push(Coord { x, y: y + dy });
        Ok(())
    }

    /// Close the current path.
    ///
    /// In SVG, closing a path using a Close command is different from closing a path using a drawing command.
    /// Specifically, [line caps are handled differently][svg-paths-close] in such cases.
    /// For the sake of simplicity, this API *does not differentiate these cases* at the moment.
    ///
    /// To follow SVG specification:
    /// - If this is followed by a moveto/moveby command, they determine the start of the new path.
    /// - If this is followed by any other command, the new path starts at the end of the last path.
    ///
    /// Can not be the first command.
    ///
    /// [svg-paths-close]: https://www.w3.org/TR/SVG11/paths.html#PathDataClosePathCommand
    pub fn close(&mut self) -> Result<(), IoError> {
        // TODO: maybe make sure there are at least 3 points?
        let line = self.get_path_mut_or_fail()?;
        line.close();
        Ok(())
    }

    /// Extend the current path with a quadratic Bézier curve from the current point using absolute coordinates.
    ///
    /// - Using the current point as the start point
    /// - Using `control` as the control point
    /// - Using `end` as the end point
    ///
    /// Can not be the first command.
    ///
    /// **Not implemented**
    pub fn quadratic_curve_to(
        &mut self,
        _control: Coord<F>,
        _end: Coord<F>,
    ) -> Result<(), IoError> {
        Err(IoError::Unimplemented(
            "quadratic curveto (absolute quadratic Bézier curve)".to_string(),
        ))
    }

    /// Extend the current path with a quadratic Bézier curve from the current point using coordinates relative
    /// to the current point.
    ///
    /// - Using the current point as the start point
    /// - Using `control` as the control point
    /// - Using `end` as the end point
    ///
    /// Can not be the first command.
    ///
    /// **Not implemented**
    pub fn quadratic_curve_by(
        &mut self,
        _control: Coord<F>,
        _end: Coord<F>,
    ) -> Result<(), IoError> {
        Err(IoError::Unimplemented(
            "quadratic curveby (relative quadratic Bézier curve)".to_string(),
        ))
    }

    /// Extend the current path with a *smooth* quadratic Bézier curve from the current point using absolute coordinates.
    ///
    /// - Using the current point as the start point
    /// - Using a reflection of `control` of the previous command relative to the current point as the control point
    ///   - If there is no previous command, or if the previous command is not one of [`quadratic_curve_to`],
    ///     [`quadratic_curve_by`], [`quadratic_smooth_curve_to`], [`quadratic_smooth_curve_by`], current point
    ///     is used as the first control point
    /// - Using `end` as the end point
    ///
    /// Can not be the first command.
    ///
    /// **Not implemented**
    pub fn quadratic_smooth_curve_to(&mut self, _end: Coord<F>) -> Result<(), IoError> {
        Err(IoError::Unimplemented(
            "quadratic smooth curveto (absolute quadratic Bézier curve with a reflected control point)".to_string()
        ))
    }

    /// Extend the current path with a *smooth* quadratic Bézier curve from the current point using coordinates relative
    /// to the current point.
    ///
    /// - Using the current point as the start point
    /// - Using a reflection of `control` of the previous command relative to the current point as the control point
    ///   - If there is no previous command, or if the previous command is not one of [`quadratic_curve_to`],
    ///     [`quadratic_curve_by`], [`quadratic_smooth_curve_to`], [`quadratic_smooth_curve_by`], current point
    ///     is used as the first control point
    /// - Using `end` as the end point
    ///
    /// Can not be the first command.
    ///
    /// **Not implemented**
    pub fn quadratic_smooth_curve_by(&mut self, _end: Coord<F>) -> Result<(), IoError> {
        Err(IoError::Unimplemented(
            "quadratic smooth curveby (relative quadratic Bézier curve with a reflected control point)".to_string()
        ))
    }

    /// Extend the current path with a cubic Bézier curve from the current point using absolute coordinates.
    ///
    /// - Using the current point as the start point
    /// - Using `control_start` as the first control point
    /// - Using `control_end` as the second control point
    /// - Using `end` as the end point
    ///
    /// Can not be the first command.
    ///
    /// **Not implemented**
    pub fn curve_to(
        &mut self,
        _control_start: Coord<F>,
        _control_end: Coord<F>,
        _end: Coord<F>,
    ) -> Result<(), IoError> {
        Err(IoError::Unimplemented(
            "curveto (absolute cubic Bézier curve)".to_string(),
        ))
    }

    /// Extend the current path with a cubic Bézier curve from the current point using coordinates relative
    /// to the current point.
    ///
    /// - Using the current point as the start point
    /// - Using `control_start` as the first control point
    /// - Using `control_end` as the second control point
    /// - Using `end` as the end point
    ///
    /// Can not be the first command.
    ///
    /// **Not implemented**
    pub fn curve_by(
        &mut self,
        _control_start: Coord<F>,
        _control_end: Coord<F>,
        _end: Coord<F>,
    ) -> Result<(), IoError> {
        Err(IoError::Unimplemented(
            "curveby (relative cubic Bézier curve)".to_string(),
        ))
    }

    /// Extend the current path with a *smooth* cubic Bézier curve from the current point using absolute coordinates.
    ///
    /// - Using the current point as the start point
    /// - Using a reflection of `control_end` of the previous command relative to the current point as the first control point
    ///   - If there is no previous command, or if the previous command is not one of [`curve_to`], [`curve_by`],
    ///     [`smooth_curve_to`], [`smooth_curve_by`], current point is used as the first control point
    /// - Using `control_end` as the second control point
    /// - Using `end` as the end point
    ///
    /// Can not be the first command.
    ///
    /// **Not implemented**
    pub fn smooth_curve_to(
        &mut self,
        _control_end: Coord<F>,
        _end: Coord<F>,
    ) -> Result<(), IoError> {
        Err(IoError::Unimplemented(
            "smooth curveto (absolute cubic Bézier curve with a reflected start control point)".to_string()
        ))
    }

    /// Extend the current path with a *smooth* cubic Bézier curve from the current point using coordinates relative
    /// to the current point.
    ///
    /// - Using the current point as the start point
    /// - Using a reflection of `control_end` of the previous command relative to the current point as the first control point
    ///   - If there is no previous command, or if the previous command is not one of [`curve_to`], [`curve_by`],
    ///     [`smooth_curve_to`], [`smooth_curve_by`], current point is used as the first control point
    /// - Using `control_end` as the second control point
    /// - Using `end` as the end point
    ///
    /// Can not be the first command.
    ///
    /// **Not implemented**
    pub fn smooth_curve_by(
        &mut self,
        _control_end: Coord<F>,
        _end: Coord<F>,
    ) -> Result<(), IoError> {
        Err(IoError::Unimplemented(
            "smooth curveby (relative cubic Bézier curve with a reflected start control point)".to_string()
        ))
    }

    /// Extend the current path with an elliptical arc from the current point using absolute coordinates.
    ///
    /// See [SVG Path Data - Elliptical Arc Curve commands][svg-arc].
    ///
    /// Can not be the first command.
    ///
    /// **Not implemented**
    ///
    /// Developers: see also [SVG Elliptical Arc Implementation Notes][svg-arc-impl-notes]
    ///
    /// [svg-arc]: https://www.w3.org/TR/SVG11/paths.html#PathDataEllipticalArcCommands
    /// [svg-arc-impl-notes]: https://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
    pub fn elliptical_arc_to(
        &mut self,
        _rx: F,
        _ry: F,
        _x_axis_rotation: F,
        _large_arc_flag: bool,
        _sweep_flag: bool,
        _end: Coord<F>,
    ) -> Result<(), IoError> {
        Err(IoError::Unimplemented("elliptical arc to".to_string()))
    }

    /// Extend the current path with an elliptical arc from the current point using coordinates relative
    /// to the current point.
    ///
    /// See [SVG Path Data - Elliptical Arc Curve commands][svg-arc].
    ///
    /// Can not be the first command.
    ///
    /// **Not implemented**
    ///
    /// Developers: see also [SVG Elliptical Arc Implementation Notes][svg-arc-impl-notes]
    ///
    /// [svg-arc]: https://www.w3.org/TR/SVG11/paths.html#PathDataEllipticalArcCommands
    /// [svg-arc-impl-notes]: https://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
    pub fn elliptical_arc_by(
        &mut self,
        _rx: F,
        _ry: F,
        _x_axis_rotation: F,
        _large_arc_flag: bool,
        _sweep_flag: bool,
        _end: Coord<F>,
    ) -> Result<(), IoError> {
        Err(IoError::Unimplemented("elliptical arc by".to_string()))
    }
}

#[allow(unused)]
pub trait FromSVG: Sized {
    fn from_svg(doc: &str) -> Result<Self, IoError>;
}

impl FromSVG for Sketch<()> {
    fn from_svg(doc: &str) -> Result<Self, IoError> {
        use svg::node::element::tag::{self, Type::*};
        use svg::parser::Event;

        macro_rules! expect_attr {
            ($attrs:expr, $attr:literal) => {
                $attrs.get($attr).ok_or_else(|| {
                    IoError::MalformedInput(format!("Missing attribute {}", $attr))
                })
            };
        }

        macro_rules! option_attr {
            ($attrs:expr, $attr:literal) => {
                $attrs.get($attr)
            };
        }

        let mut sketch_union = Sketch::<()>::new();

        for event in svg::read(doc)? {
            match event {
                Event::Instruction(..)
                | Event::Declaration(..)
                | Event::Text(..)
                | Event::Comment(..)
                | Event::Tag(tag::SVG, ..)
                | Event::Tag(tag::Description, ..)
                | Event::Tag(tag::Text, ..)
                | Event::Tag(tag::Title, ..) => {},

                Event::Error(error) => {
                    return Err(error.into());
                },

                Event::Tag(tag::Group, ..) => {
                    // TODO: keep track of transforms
                    // TODO: keep track of style properties
                },

                Event::Tag(tag::Path, Empty, attrs) => {
                    let data = expect_attr!(attrs, "d")?;
                    let data = path::Data::parse(data)?;
                    let mls = svg_path_to_multi_line_string(data)?;

                    // TODO: This is tricky.
                    // Whether a <path/> contains lines or polygons really depends on the current stroke and fill,
                    // which requires keeping track of them by parsing `style=""` and other attributes,
                    // and pushing/popping the current "style context" on group entry and exit.
                    //
                    // On top of that, when a <path/> is a polygon, subpaths may define additional polygons OR
                    // holes in existing polygons (and how specifically, may depend on either their winding order
                    // or on the level of nestedness).
                    // Read more / see examples here: https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Attribute/fill-rule
                    //
                    // This is a bit advanced, so (for now) this code just assumes that:
                    // - every closed subpath is a polygon (as if with solid fill and zero stroke thickness)
                    // - every unclosed subpath is a line (as if with no fill)
                    //
                    // The lines are then (for now) discarded as expanding lines requires knowing current stroke-width.

                    for ls in mls.0.into_iter() {
                        if ls.is_closed() {
                            let polygon = Polygon::new(ls, vec![]);
                            let sketch = Self::from_geo(polygon.into(), None);
                            sketch_union = sketch_union.union(&sketch);
                        }
                    }
                },

                Event::Tag(tag::Circle, Empty, attrs) => {
                    let cx = expect_attr!(attrs, "cx")?.parse()?;
                    let cy = expect_attr!(attrs, "cy")?.parse()?;
                    let r: Real = expect_attr!(attrs, "r")?.parse()?;

                    // TODO: add a way for the user to configure this?
                    let segments = (r.ceil() as usize).max(6);

                    let sketch = Self::circle(r, segments, None).translate(cx, cy, 0.0);
                    sketch_union = sketch_union.union(&sketch);
                },

                Event::Tag(tag::Rectangle, Empty, attrs) => {
                    let x: Real = expect_attr!(attrs, "x")?.parse()?;
                    let y: Real = expect_attr!(attrs, "y")?.parse()?;
                    let w: Real = expect_attr!(attrs, "width")?.parse()?;
                    let h: Real = expect_attr!(attrs, "height")?.parse()?;
                    let rx: Real = option_attr!(attrs, "rx").map_or(Ok(0.0), |a| a.parse())?;
                    let ry: Real = option_attr!(attrs, "ry").map_or(Ok(0.0), |a| a.parse())?;

                    // TODO: support rx != ry
                    let r = (rx + ry) / 2.0;

                    // TODO: add a way for the user to configure this?
                    let segments = (r.ceil() as usize).max(6);

                    let sketch =
                        Self::rounded_rectangle(w, h, r, segments, None).translate(x, y, 0.0);
                    sketch_union = sketch_union.union(&sketch);
                },

                Event::Tag(tag::Ellipse, Empty, attrs) => {
                    let cx = expect_attr!(attrs, "cx")?.parse()?;
                    let cy = expect_attr!(attrs, "cy")?.parse()?;
                    let rx: Real = expect_attr!(attrs, "rx")?.parse()?;
                    let ry: Real = expect_attr!(attrs, "ry")?.parse()?;

                    // TODO: add a way for the user to configure this?
                    let segments = (rx.max(ry).ceil() as usize).max(6);

                    let sketch = Self::ellipse(rx * 2.0, ry * 2.0, segments, None)
                        .translate(cx, cy, 0.0);
                    sketch_union = sketch_union.union(&sketch);
                },

                Event::Tag(tag::Line, Empty, attrs) => {
                    let _x1 = expect_attr!(attrs, "x1")?;
                    let _y1 = expect_attr!(attrs, "y1")?;
                    let _x2 = expect_attr!(attrs, "x2")?;
                    let _y2 = expect_attr!(attrs, "y2")?;

                    // TODO: This needs knowing current stroke-width
                },

                Event::Tag(tag::Polygon, Empty, attrs) => {
                    let points = expect_attr!(attrs, "points")?;
                    let polygon = Polygon::new(svg_points_to_line_string(points)?, vec![]);
                    let sketch = Self::from_geo(polygon.into(), None);
                    sketch_union = sketch_union.union(&sketch);
                },

                Event::Tag(tag::Polyline, Empty, attrs) => {
                    let points = expect_attr!(attrs, "points")?;
                    let _ls = svg_points_to_line_string::<Real>(points)?;

                    // TODO: This needs knowing current stroke-width
                },

                tag => {
                    // TODO: Non-empty tags should also be supported

                    unimplemented!("Parsing tag {tag:?}");
                },
            }
        }

        Ok(sketch_union)
    }
}

#[allow(unused)]
pub trait ToSVG {
    fn to_svg(&self) -> String;
}

impl<S: Clone> ToSVG for Sketch<S> {
    fn to_svg(&self) -> String {
        use geo::Geometry::*;
        use svg::node::element;

        let mut g = element::Group::new();

        let make_line_string = |line_string: &geo::LineString<Real>| {
            let mut data = path::Data::new();
            let mut points = line_string.coords();

            if let Some(start) = points.next() {
                data = data.move_to(start.x_y());
            }
            for point in points {
                data = data.line_to(point.x_y());
            }

            element::Path::new()
                .set("fill", "none")
                .set("stroke", "black")
                .set("stroke-width", 1)
                .set("vector-effect", "non-scaling-stroke")
                .set("d", data)
        };

        #[allow(clippy::unnecessary_cast)]
        let make_polygon = |polygon: &geo::Polygon<Real>| {
            let mut data = path::Data::new();

            // `svg::Data` accepts a `Vec<f32>` here, so always cast to `f32`.
            let exterior = polygon.exterior();
            data = data.move_to(
                // Skip the last point because it is equal to the first one
                exterior.0[..(exterior.0.len() - 1)]
                    .iter()
                    .flat_map(|c| [c.x as f32, c.y as f32])
                    .collect::<Vec<f32>>(),
            );

            data = data.close();

            #[allow(clippy::unnecessary_cast)]
            for interior in polygon.interiors() {
                data = data.move_to(
                    // Skip the last point because it is equal to the first one
                    interior.0[..(interior.0.len() - 1)]
                        .iter()
                        .flat_map(|c| [c.x as f32, c.y as f32])
                        .collect::<Vec<f32>>(),
                );

                data = data.close();
            }

            element::Path::new()
                .set("fill", "black")
                .set("fill-rule", "evenodd")
                .set("stroke", "none")
                .set("d", data)
        };

        let bounds = self.geometry.bounding_rect().unwrap_or(geo::Rect::new(
            Coord { x: 0.0, y: 0.0 },
            Coord { x: 1.0, y: 1.0 },
        ));

        for geometry in self.geometry.iter() {
            match geometry {
                Line(line) => {
                    g = g.add(
                        element::Line::new()
                            .set("stroke", "black")
                            .set("stroke-width", 1)
                            .set("vector-effect", "non-scaling-stroke")
                            .set("x1", line.start.x)
                            .set("y1", line.start.y)
                            .set("x2", line.end.x)
                            .set("y2", line.end.y),
                    );
                },

                LineString(line_string) => {
                    g = g.add(make_line_string(line_string));
                },
                Polygon(polygon) => {
                    g = g.add(make_polygon(polygon));
                },
                MultiLineString(multi_line_string) => {
                    for line_string in multi_line_string {
                        g = g.add(make_line_string(line_string));
                    }
                },
                MultiPolygon(multi_polygon) => {
                    for polygon in multi_polygon {
                        g = g.add(make_polygon(polygon));
                    }
                },

                Rect(rect) => {
                    g = g.add(make_polygon(&rect.to_polygon()));
                },

                Triangle(triangle) => {
                    g = g.add(make_polygon(&triangle.to_polygon()));
                },

                GeometryCollection(_) => {
                    unimplemented!("Exporting nested geometry collections to SVG")
                },

                // Can't really export points to SVG
                Point(_) => {},
                MultiPoint(_) => {},
            }
        }

        let doc = svg::Document::new()
            .set(
                "viewBox",
                (
                    bounds.min().x,
                    bounds.min().y,
                    bounds.width(),
                    bounds.height(),
                ),
            )
            .add(g);

        doc.to_string()
    }
}

fn svg_path_to_multi_line_string<F: CoordNum>(
    path_data: path::Data,
) -> Result<MultiLineString<F>, IoError> {
    // `svg` crate returns `f32`, so that's what is used here.
    let mut builder = PathBuilder::<f32>::new();

    for cmd in path_data.iter() {
        use svg::node::element::path::{Command::*, Position::*};

        macro_rules! ensure_param_count {
            ($count:expr, $div_by:expr) => {
                if $count % $div_by != 0 {
                    return Err(IoError::MalformedPath(format!("Expected the number of parameters {} to be divisible by {} in command {cmd:?}", $count, $div_by)));
                }
            };
        }

        let param_count = match cmd {
            Move(..) | Line(..) => 2,

            HorizontalLine(..) | VerticalLine(..) => 1,

            QuadraticCurve(..) => 4,
            SmoothQuadraticCurve(..) => 2,
            CubicCurve(..) => 6,
            SmoothCubicCurve(..) => 4,
            EllipticalArc(..) => 7,

            Close => {
                builder.close()?;
                continue;
            },
        };

        match cmd {
            Move(Absolute, params) => {
                ensure_param_count!(params.len(), param_count);
                let mut coords = params.chunks(param_count);

                if let Some(&[x, y]) = coords.next() {
                    builder.move_to(Coord { x, y });
                }

                // Follow-up coordinates for MoveTo are implicit LineTo
                while let Some(&[x, y]) = coords.next() {
                    builder.line_to(Coord { x, y })?;
                }
            },
            Move(Relative, params) => {
                ensure_param_count!(params.len(), param_count);
                let mut coords = params.chunks(param_count);

                if let Some(&[dx, dy]) = coords.next() {
                    builder.move_by(Coord { x: dx, y: dy });
                }

                // Follow-up coordinates for MoveTo are implicit LineTo
                while let Some(&[dx, dy]) = coords.next() {
                    builder.line_by(Coord { x: dx, y: dy })?;
                }
            },
            Line(Absolute, params) => {
                ensure_param_count!(params.len(), param_count);
                let mut coords = params.chunks(param_count);
                while let Some(&[x, y]) = coords.next() {
                    builder.line_to(Coord { x, y })?;
                }
            },
            Line(Relative, params) => {
                ensure_param_count!(params.len(), param_count);
                let mut coords = params.chunks(param_count);
                while let Some(&[dx, dy]) = coords.next() {
                    builder.line_by(Coord { x: dx, y: dy })?;
                }
            },
            HorizontalLine(Absolute, params) => {
                for &x in params.iter() {
                    builder.hline_to(x)?;
                }
            },
            HorizontalLine(Relative, params) => {
                for &dx in params.iter() {
                    builder.hline_by(dx)?;
                }
            },
            VerticalLine(Absolute, params) => {
                for &y in params.iter() {
                    builder.vline_to(y)?;
                }
            },
            VerticalLine(Relative, params) => {
                for &dy in params.iter() {
                    builder.vline_by(dy)?;
                }
            },

            QuadraticCurve(Absolute, params) => {
                ensure_param_count!(params.len(), param_count);
                let mut params = params.chunks(param_count);
                while let Some(&[cx, cy, x, y]) = params.next() {
                    builder.quadratic_curve_to(Coord { x: cx, y: cy }, Coord { x, y })?;
                }
            },
            QuadraticCurve(Relative, params) => {
                ensure_param_count!(params.len(), param_count);
                let mut params = params.chunks(param_count);
                while let Some(&[cx, cy, x, y]) = params.next() {
                    builder.quadratic_curve_by(Coord { x: cx, y: cy }, Coord { x, y })?;
                }
            },
            SmoothQuadraticCurve(Absolute, params) => {
                ensure_param_count!(params.len(), param_count);
                let mut params = params.chunks(param_count);
                while let Some(&[x, y]) = params.next() {
                    builder.quadratic_smooth_curve_to(Coord { x, y })?;
                }
            },
            SmoothQuadraticCurve(Relative, params) => {
                ensure_param_count!(params.len(), param_count);
                let mut params = params.chunks(param_count);
                while let Some(&[x, y]) = params.next() {
                    builder.quadratic_smooth_curve_by(Coord { x, y })?;
                }
            },

            CubicCurve(Absolute, params) => {
                ensure_param_count!(params.len(), param_count);
                let mut params = params.chunks(param_count);
                while let Some(&[c1x, c1y, c2x, c2y, x, y]) = params.next() {
                    builder.curve_to(
                        Coord { x: c1x, y: c1y },
                        Coord { x: c2x, y: c2y },
                        Coord { x, y },
                    )?;
                }
            },
            CubicCurve(Relative, params) => {
                ensure_param_count!(params.len(), param_count);
                let mut params = params.chunks(param_count);
                while let Some(&[c1x, c1y, c2x, c2y, x, y]) = params.next() {
                    builder.curve_by(
                        Coord { x: c1x, y: c1y },
                        Coord { x: c2x, y: c2y },
                        Coord { x, y },
                    )?;
                }
            },
            SmoothCubicCurve(Absolute, params) => {
                ensure_param_count!(params.len(), param_count);
                let mut params = params.chunks(param_count);
                while let Some(&[c2x, c2y, x, y]) = params.next() {
                    builder.smooth_curve_to(Coord { x: c2x, y: c2y }, Coord { x, y })?;
                }
            },
            SmoothCubicCurve(Relative, params) => {
                ensure_param_count!(params.len(), param_count);
                let mut params = params.chunks(param_count);
                while let Some(&[c2x, c2y, x, y]) = params.next() {
                    builder.smooth_curve_by(Coord { x: c2x, y: c2y }, Coord { x, y })?;
                }
            },

            EllipticalArc(Absolute, params) => {
                ensure_param_count!(params.len(), param_count);
                let mut params = params.chunks(param_count);
                while let Some(&[rx, ry, x_rot, large_arc, sweep, x, y]) = params.next() {
                    let large_arc = large_arc == 1.0;
                    let sweep = sweep == 1.0;
                    builder.elliptical_arc_to(
                        rx,
                        ry,
                        x_rot,
                        large_arc,
                        sweep,
                        Coord { x, y },
                    )?;
                }
            },
            EllipticalArc(Relative, params) => {
                ensure_param_count!(params.len(), param_count);
                let mut params = params.chunks(param_count);
                while let Some(&[rx, ry, x_rot, large_arc, sweep, x, y]) = params.next() {
                    let large_arc = large_arc == 1.0;
                    let sweep = sweep == 1.0;
                    builder.elliptical_arc_by(
                        rx,
                        ry,
                        x_rot,
                        large_arc,
                        sweep,
                        Coord { x, y },
                    )?;
                }
            },

            Close => {
                unreachable!("Expected an early continue.");
            },
        }
    }

    let mls: MultiLineString<f32> = builder.into();
    let mls = mls.map_coords(|c| Coord {
        x: F::from(c.x).unwrap(),
        y: F::from(c.y).unwrap(),
    });

    Ok(mls)
}

/// Parse contents of the SVG <polyline/> and <polygon/> attribute [`points`][points] into a `LineString`.
///
/// [points]: https://www.w3.org/TR/SVG11/shapes.html#PointsBNF
fn svg_points_to_line_string<F: CoordNum>(points: &str) -> Result<LineString<F>, IoError> {
    use nom::IResult;
    use nom::Parser;
    use nom::branch::alt;
    use nom::character::complete::{char, multispace0, multispace1};
    use nom::combinator::opt;
    use nom::multi::separated_list1;
    use nom::number::complete::float;
    use nom::sequence::{delimited, pair, separated_pair, tuple};

    fn comma_wsp(i: &str) -> IResult<&str, ()> {
        let (i, _) = alt((
            tuple((multispace1, opt(char(',')), multispace0)).map(|_| ()),
            pair(char(','), multispace0).map(|_| ()),
        ))(i)?;
        Ok((i, ()))
    }

    fn point<F: CoordNum>(i: &str) -> IResult<&str, Coord<F>> {
        let (i, (x, y)) = separated_pair(float, comma_wsp, float)(i)?;
        Ok((
            i,
            Coord {
                x: F::from(x).unwrap(),
                y: F::from(y).unwrap(),
            },
        ))
    }

    fn all_points<F: CoordNum>(i: &str) -> IResult<&str, Vec<Coord<F>>> {
        delimited(multispace0, separated_list1(comma_wsp, point), multispace0)(i)
    }

    match all_points(points) {
        Ok(("", points)) => Ok(LineString::new(points)),
        Ok(_) => Err(IoError::MalformedInput(format!(
            "Could not parse the list of points: {points}"
        ))),
        Err(err) => Err(IoError::MalformedInput(format!(
            "Could not parse the list of points ({err}): {points}"
        ))),
    }
}

#[cfg(test)]
mod tests {
    use geo::line_string;

    use super::*;

    #[test]
    fn basic_svg_io() {
        let svg_in = r#"
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<g>
<path d="M0,0,100,0,100,100 z" fill="black" fill-rule="evenodd" stroke="none"/>
</g>
</svg>
        "#;

        let sketch = Sketch::from_svg(svg_in).unwrap();
        let svg_out = sketch.to_svg();

        assert_eq!(svg_in.trim(), svg_out.trim());
    }

    #[test]
    fn svg_points_parsing() {
        let expected = line_string![
            (x: 350.0, y:  75.0),
            (x: 379.0, y: 161.0),
            (x: 469.0, y: 161.0),
            (x: 397.0, y: 215.0),
            (x: 423.0, y: 301.0),
            (x: 350.0, y: 250.0),
            (x: 277.0, y: 301.0),
            (x: 303.0, y: 215.0),
            (x: 231.0, y: 161.0),
            (x: 321.0, y: 161.0),
        ];

        let points = "
            350,75  379,161 469,161 397,215
            423,301 350,250 277,301 303,215
            231,161 321,161
        ";
        let points = svg_points_to_line_string(points).unwrap();
        assert_eq!(points, expected);

        let points = "
            350 75  379 161 469 161 397 215
            423 301 350 250 277 301 303 215
            231 161 321 161
        ";
        let points = svg_points_to_line_string(points).unwrap();
        assert_eq!(points, expected);

        let points = "
            350,75,379,161,469,161,397,215,
            423,301,350,250,277,301,303,215,
            231,161,321,161
        ";
        let points = svg_points_to_line_string(points).unwrap();
        assert_eq!(points, expected);

        let points = "
            350 , 75 , 379 , 161 , 469 , 161 , 397 , 215 ,
            423 ,301, 350 ,250, 277 ,301, 303 ,215,
            231    161    321    161
        ";
        let points = svg_points_to_line_string(points).unwrap();
        assert_eq!(points, expected);
    }
}