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
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;

/// 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, 0, 0x84),
            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)]
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,
}

/// 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));
    }

    /// 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),
                    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)
    }

    /// 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::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
}

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(features::Rect::with_center([-2.5, -2.5].into(), 5., 5.));
        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_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);
        }
    }
}