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
extern crate conv;
extern crate geo_booleanop;
extern crate gerber_types;

use geo::{Coordinate, MultiPolygon};
use geo_booleanop::boolean::BooleanOp;
use usvg::NodeExt;

pub mod features;
use features::{Feature, InnerAtom};

mod drill;
mod gerber;
mod parser;
#[cfg(feature = "tessellate")]
mod tessellate;
#[cfg(feature = "tessellate")]
pub use tessellate::{Point as TPoint, TessellationError, VertexBuffers};

pub use parser::Err as SpecErr;

/// Alignment of multiple elements in an array.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Align {
    Start,
    Center,
    End,
}

/// PCB layers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Layer {
    FrontCopper,
    FrontMask,
    FrontLegend,
    BackCopper,
    BackMask,
    BackLegend,
}

impl Layer {
    fn color(&self) -> usvg::Color {
        match self {
            Layer::FrontCopper => usvg::Color::new(0x84, 0, 0),
            Layer::FrontMask => usvg::Color::new(0x84, 0, 0x84),
            Layer::FrontLegend => usvg::Color::new(0, 0xce, 0xde),
            Layer::BackCopper => usvg::Color::new(0, 0x84, 0),
            Layer::BackMask => usvg::Color::new(0x84, 0, 0x84),
            Layer::BackLegend => usvg::Color::new(0x4, 0, 0x84),
        }
    }
}

/// The direction in which repetitions occur.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Direction {
    Left,
    Right,
    Down,
    Up,
}

impl std::fmt::Display for Direction {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Direction::Left => write!(f, "left"),
            Direction::Right => write!(f, "right"),
            Direction::Down => write!(f, "down"),
            Direction::Up => write!(f, "up"),
        }
    }
}

impl Direction {
    pub fn offset(&self, bounds: geo::Rect<f64>) -> (f64, f64) {
        match self {
            Direction::Left => (-bounds.width(), 0.0),
            Direction::Right => (bounds.width(), 0.0),
            Direction::Down => (0.0, bounds.height()),
            Direction::Up => (0.0, -bounds.height()),
        }
    }
}

/// Failure modes when constructing or serializing geometry.
#[derive(Debug)]
pub enum Err {
    NoFeatures,
    BadEdgeGeometry(String),
    InternalGerberFailure,
    #[cfg(feature = "tessellate")]
    TessellationError(TessellationError),
}

/// Combines features into single geometry.
pub struct Panel<'a> {
    pub features: Vec<Box<dyn Feature + 'a>>,
    convex_hull: bool,
}

impl<'a> Panel<'a> {
    /// Constructs a [`Panel`].
    pub fn new() -> Self {
        let features = Vec::new();
        let convex_hull = false;
        Self {
            features,
            convex_hull,
        }
    }

    /// Constructs a [`Panel`], pre-sized to hold the given
    /// number of [`features::Feature`] objects before need an allocation.
    pub fn with_capacity(sz: usize) -> Self {
        let features = Vec::with_capacity(sz);
        let convex_hull = false;
        Self {
            features,
            convex_hull,
        }
    }

    /// Enables or disables a convex hull transform on the computed edge geometry.
    pub fn convex_hull(&mut self, convex_hull: bool) {
        self.convex_hull = convex_hull;
    }

    /// Adds a feature to the panel.
    pub fn push<F: Feature + 'a>(&mut self, f: F) {
        self.features.push(Box::new(f));
    }

    /// Adds the feature described by the given spec to the panel.
    pub fn push_spec(&mut self, spec_str: &str) -> Result<(), SpecErr> {
        self.features.append(&mut parser::build(spec_str)?);
        Ok(())
    }

    /// Computes the outer geometry of the panel.
    pub fn edge_geometry(&self) -> Option<MultiPolygon<f64>> {
        let edge = self
            .features
            .iter()
            .map(|f| f.edge_union())
            .fold(None, |mut acc, g| {
                if let Some(poly) = g {
                    if let Some(current) = acc {
                        acc = Some(poly.union(&current));
                    } else {
                        acc = Some(poly);
                    }
                };
                acc
            });

        match (&edge, self.convex_hull) {
            (Some(edges), true) => {
                use geo::algorithm::convex_hull;
                let mut points = edges
                    .iter()
                    .map(|p| p.exterior().points_iter().collect::<Vec<_>>())
                    .flatten()
                    .map(|p| p.into())
                    .collect::<Vec<Coordinate<_>>>();

                let poly = geo::Polygon::new(
                    convex_hull::graham::graham_hull(points.as_mut_slice(), true),
                    edges
                        .iter()
                        .map(|p| p.interiors())
                        .flatten()
                        .map(|p| p.clone())
                        .collect::<Vec<_>>(),
                );

                Some((vec![poly]).into())
            }
            _ => edge,
        }
    }

    fn edge_poly(&self) -> Result<geo::Polygon<f64>, Err> {
        match self.edge_geometry() {
            Some(edges) => {
                let mut polys = edges.into_iter();
                match polys.len() {
                    0 => Err(Err::NoFeatures),
                    1 => Ok(polys.next().unwrap()),
                    _ => Err(Err::BadEdgeGeometry(
                        "multiple polygons provided for edge geometry".to_string(),
                    )),
                }
            }
            None => Err(Err::NoFeatures),
        }
    }

    /// Computes the inner geometry of the panel.
    pub fn interior_geometry(&self) -> Vec<InnerAtom> {
        self.features
            .iter()
            .map(|f| f.interior())
            .flatten()
            .collect()
    }

    /// Serializes a gerber file describing the PCB profile to the provided writer.
    pub fn serialize_gerber_edges<W: std::io::Write>(&self, w: &mut W) -> Result<(), Err> {
        let edges = self.edge_poly()?;
        let commands = gerber::serialize_edge(edges).map_err(|_| Err::InternalGerberFailure)?;
        use gerber_types::GerberCode;
        commands
            .serialize(w)
            .map_err(|_| Err::InternalGerberFailure)
    }

    /// Serializes a gerber file describing the layer (copper or soldermask) to
    /// to the provided writer.
    pub fn serialize_gerber_layer<W: std::io::Write>(
        &self,
        layer: Layer,
        w: &mut W,
    ) -> Result<(), Err> {
        let commands = gerber::serialize_layer(layer, self.interior_geometry())
            .map_err(|_| Err::InternalGerberFailure)?;
        use gerber_types::GerberCode;
        commands
            .serialize(w)
            .map_err(|_| Err::InternalGerberFailure)
    }

    /// Serializes a drill file describing drill hits to the provided writer.
    pub fn serialize_drill<W: std::io::Write>(
        &self,
        w: &mut W,
        want_plated: bool,
    ) -> Result<(), std::io::Error> {
        drill::serialize(&self.interior_geometry(), w, want_plated)
    }

    /// Computes the 2d tessellation of the panel.
    #[cfg(feature = "tessellate")]
    pub fn tessellate_2d(&self) -> Result<VertexBuffers<TPoint, u16>, Err> {
        Ok(
            tessellate::tessellate_2d(self.edge_poly()?, self.interior_geometry())
                .map_err(|e| Err::TessellationError(e))?,
        )
    }

    /// Computes the 3d tessellation of the panel.
    #[cfg(feature = "tessellate")]
    pub fn tessellate_3d(&self) -> Result<(Vec<[f64; 3]>, Vec<u16>), Err> {
        Ok(tessellate::tessellate_3d(self.tessellate_2d()?))
    }

    /// Produces an SVG tree rendering the panel.
    pub fn make_svg(&self) -> Result<usvg::Tree, Err> {
        let edges = self.edge_poly()?;
        use geo::bounding_rect::BoundingRect;
        let bounds = edges.bounding_rect().unwrap();

        let size = usvg::Size::new(bounds.width(), bounds.height()).unwrap();
        let rtree = usvg::Tree::create(usvg::Svg {
            size,
            view_box: usvg::ViewBox {
                rect: size.to_rect(0.0, 0.0),
                aspect: usvg::AspectRatio::default(),
            },
        });

        let mut path = usvg::PathData::new();
        let mut has_moved = false;
        for point in edges.exterior().points_iter() {
            if !has_moved {
                has_moved = true;
                path.push_move_to(point.x(), point.y());
            } else {
                path.push_line_to(point.x(), point.y());
            }
        }
        path.push_close_path();

        rtree.root().append_kind(usvg::NodeKind::Path(usvg::Path {
            stroke: Some(usvg::Stroke {
                paint: usvg::Paint::Color(usvg::Color::new(0, 0, 0)),
                width: usvg::StrokeWidth::new(0.1),
                ..usvg::Stroke::default()
            }),
            data: std::rc::Rc::new(path),
            ..usvg::Path::default()
        }));

        for inner in self.interior_geometry() {
            match inner {
                InnerAtom::Circle { center, radius, .. } => {
                    let p = circle(center, radius);
                    rtree.root().append_kind(usvg::NodeKind::Path(usvg::Path {
                        stroke: inner.stroke(),
                        fill: inner.fill(),
                        data: std::rc::Rc::new(p),
                        ..usvg::Path::default()
                    }));
                }
                InnerAtom::Rect {
                    rect: rect_pos,
                    layer: _,
                } => {
                    let p = rect(rect_pos);
                    rtree.root().append_kind(usvg::NodeKind::Path(usvg::Path {
                        stroke: inner.stroke(),
                        fill: inner.fill(),
                        data: std::rc::Rc::new(p),
                        ..usvg::Path::default()
                    }));
                }
                InnerAtom::Drill { center, radius, .. } => {
                    let p = circle(center, radius);
                    rtree.root().append_kind(usvg::NodeKind::Path(usvg::Path {
                        stroke: inner.stroke(),
                        fill: inner.fill(),
                        data: std::rc::Rc::new(p),
                        ..usvg::Path::default()
                    }));
                }
            }
        }

        Ok(rtree)
    }
}

fn circle(center: Coordinate<f64>, radius: f64) -> usvg::PathData {
    let mut p = usvg::PathData::with_capacity(6);
    p.push_move_to(center.x + radius, center.y);
    p.push_arc_to(
        radius,
        radius,
        0.0,
        false,
        true,
        center.x,
        center.y + radius,
    );
    p.push_arc_to(
        radius,
        radius,
        0.0,
        false,
        true,
        center.x - radius,
        center.y,
    );
    p.push_arc_to(
        radius,
        radius,
        0.0,
        false,
        true,
        center.x,
        center.y - radius,
    );
    p.push_arc_to(
        radius,
        radius,
        0.0,
        false,
        true,
        center.x + radius,
        center.y,
    );
    p.push_close_path();
    p
}

fn rect(rect: geo::Rect<f64>) -> usvg::PathData {
    let mut p = usvg::PathData::with_capacity(5);
    p.push_move_to(rect.min().x, rect.min().y);
    p.push_line_to(rect.max().x, rect.min().y);
    p.push_line_to(rect.max().x, rect.max().y);
    p.push_line_to(rect.min().x, rect.max().y);
    p.push_line_to(rect.min().x, rect.min().y);
    p.push_close_path();
    p
}

impl std::fmt::Display for Panel<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "panel(")?;
        for feature in &self.features {
            feature.fmt(f)?;
            write!(f, " ")?;
        }
        write!(f, ")")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_overlapping_rects() {
        let mut panel = Panel::new();
        panel.push_spec("R<@(-2.5, -2.5), 5>(h3)").unwrap();
        panel.push(features::Rect::new([-0., -1.].into(), [5., 3.].into()));

        assert_eq!(
            panel.edge_geometry().unwrap(),
            geo::MultiPolygon(vec![geo::Polygon::new(
                geo::LineString(vec![
                    geo::Coordinate { x: -5.0, y: -5.0 },
                    geo::Coordinate { x: 0.0, y: -5.0 },
                    geo::Coordinate { x: 0.0, y: -1.0 },
                    geo::Coordinate { x: 5.0, y: -1.0 },
                    geo::Coordinate { x: 5.0, y: 3.0 },
                    geo::Coordinate { x: -0.0, y: 3.0 },
                    geo::Coordinate { x: 0.0, y: 0.0 },
                    geo::Coordinate { x: -5.0, y: 0.0 },
                    geo::Coordinate { x: -5.0, y: -5.0 }
                ]),
                vec![],
            )]),
        );
    }

    #[test]
    fn test_rect_inner() {
        let mut panel = Panel::new();
        panel.push_spec("R<@(2.5, -2.5), 5>(h3)").unwrap();

        // eprintln!("{:?}", panel.interior_geometry());
        for i in 0..5 {
            assert!(panel.interior_geometry()[i].bounds().center().x > 2.49);
            assert!(panel.interior_geometry()[i].bounds().center().x < 2.51);
            assert!(panel.interior_geometry()[i].bounds().center().y < -2.49);
            assert!(panel.interior_geometry()[i].bounds().center().y > -2.51);
        }
    }

    #[test]
    fn test_array_inner() {
        let mut panel = Panel::new();
        panel.push_spec("[5]R<5>(h3)").unwrap();
        assert_eq!(panel.interior_geometry().len(), 25);

        use geo::bounding_rect::BoundingRect;
        let bounds = panel.edge_geometry().unwrap().bounding_rect().unwrap();
        assert!(bounds.width() > 24.99 && bounds.width() < 25.01);
        assert!(bounds.height() > 4.99 && bounds.height() < 5.01);
    }

    #[test]
    fn test_column_down() {
        let mut panel = Panel::new();
        panel
            .push_spec("column left { R<5,5>(h) R<3>(h) } ")
            .unwrap();

        use geo::bounding_rect::BoundingRect;
        let bounds = panel.edge_geometry().unwrap().bounding_rect().unwrap();
        eprintln!("{:?}\n\n{:?}", panel.features, bounds);
        assert!(bounds.width() > 4.99 && bounds.width() < 5.01);
        assert!(bounds.height() > 7.99 && bounds.height() < 8.01);
    }

    #[test]
    fn test_circ_inner() {
        let mut panel = Panel::new();
        panel.push_spec("C<5>(h2)").unwrap();

        for i in 0..5 {
            assert!(panel.interior_geometry()[i].bounds().center().x > -0.01);
            assert!(panel.interior_geometry()[i].bounds().center().x < 0.01);
            assert!(panel.interior_geometry()[i].bounds().center().y < 0.01);
            assert!(panel.interior_geometry()[i].bounds().center().y > -0.01);
        }

        let mut panel = Panel::new();
        panel.push_spec("C<@(1, 1), 1>(h2)").unwrap();
        // eprintln!("{:?}", panel.interior_geometry());
        for i in 0..5 {
            assert!(panel.interior_geometry()[i].bounds().center().x > 0.99);
            assert!(panel.interior_geometry()[i].bounds().center().x < 1.01);
            assert!(panel.interior_geometry()[i].bounds().center().y < 1.01);
            assert!(panel.interior_geometry()[i].bounds().center().y > 0.99);
        }
    }

    #[test]
    fn test_atpos_xends() {
        let mut panel = Panel::new();
        panel.push(features::AtPos::x_ends(
            features::Rect::with_center([4., 2.].into(), 2., 3.),
            Some(features::Circle::wrap_with_radius(
                features::ScrewHole::with_diameter(1.),
                2.,
            )),
            Some(features::Circle::wrap_with_radius(
                features::ScrewHole::with_diameter(1.),
                2.,
            )),
        ));

        for i in 0..5 {
            assert!(panel.interior_geometry()[i].bounds().center().x < 3.01);
            assert!(panel.interior_geometry()[i].bounds().center().x > 2.99);
            assert!(panel.interior_geometry()[i].bounds().center().y < 2.01);
            assert!(panel.interior_geometry()[i].bounds().center().y > -2.01);
        }
        for i in 5..10 {
            assert!(panel.interior_geometry()[i].bounds().center().x < 5.01);
            assert!(panel.interior_geometry()[i].bounds().center().x > 4.99);
            assert!(panel.interior_geometry()[i].bounds().center().y < 2.01);
            assert!(panel.interior_geometry()[i].bounds().center().y > -2.01);
        }
    }
}