1use serde::{Deserialize, Serialize};
4use std::collections::BTreeMap;
5
6pub const MM_TO_NM: f64 = 1_000_000.0;
8
9#[must_use]
11pub fn mm_to_nm(mm: f64) -> i64 {
12 if !mm.is_finite() {
13 return 0;
14 }
15 (mm * MM_TO_NM).round() as i64
16}
17
18#[must_use]
20pub fn pt_up(x_mm: f64, y_mm: f64) -> CoordNm {
21 CoordNm {
22 x: mm_to_nm(x_mm),
23 y: -mm_to_nm(y_mm),
24 }
25}
26
27#[must_use]
29pub fn fp_local_to_board_mm(
30 fp_x: f64,
31 fp_y: f64,
32 fp_angle_deg: f64,
33 lx: f64,
34 ly: f64,
35) -> (f64, f64) {
36 let rad = fp_angle_deg.to_radians();
37 let (s, c) = rad.sin_cos();
38 (fp_x + lx * c + ly * s, fp_y - lx * s + ly * c)
39}
40
41#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize)]
43pub struct CoordNm {
44 pub x: i64,
45 pub y: i64,
46}
47
48impl CoordNm {
49 #[must_use]
50 pub const fn new(x: i64, y: i64) -> Self {
51 Self { x, y }
52 }
53}
54
55#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
57pub struct Placement2D {
58 pub tx: i64,
59 pub ty: i64,
60 pub angle_deg: f64,
62}
63
64impl Placement2D {
65 #[must_use]
66 pub const fn identity() -> Self {
67 Self {
68 tx: 0,
69 ty: 0,
70 angle_deg: 0.0,
71 }
72 }
73
74 #[must_use]
75 pub const fn translate(tx: i64, ty: i64) -> Self {
76 Self {
77 tx,
78 ty,
79 angle_deg: 0.0,
80 }
81 }
82
83 #[must_use]
84 pub const fn new(tx: i64, ty: i64, angle_deg: f64) -> Self {
85 Self { tx, ty, angle_deg }
86 }
87
88 #[must_use]
90 pub fn transform(self, lx: f64, ly: f64) -> CoordNm {
91 if self.angle_deg.abs() < 1e-9 {
92 return CoordNm::new(
93 self.tx.saturating_add(lx.round() as i64),
94 self.ty.saturating_add(ly.round() as i64),
95 );
96 }
97 let (s, c) = self.angle_deg.to_radians().sin_cos();
98 let rx = lx * c - ly * s;
99 let ry = lx * s + ly * c;
100 CoordNm::new(
101 self.tx.saturating_add(rx.round() as i64),
102 self.ty.saturating_add(ry.round() as i64),
103 )
104 }
105}
106
107#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
109pub enum RingSeg {
110 Line,
111 Arc {
112 center: CoordNm,
113 ccw: bool,
114 major: bool,
115 },
116}
117
118#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
120pub struct Ring2D {
121 pub points: Vec<CoordNm>,
122 pub segs: Vec<RingSeg>,
123}
124
125impl Ring2D {
126 #[must_use]
128 pub fn from_points_oriented(pts: &[CoordNm], ccw: bool) -> Option<Self> {
129 let mut cleaned: Vec<CoordNm> = Vec::with_capacity(pts.len());
130 for &pt in pts {
131 if cleaned.last() != Some(&pt) {
132 cleaned.push(pt);
133 }
134 }
135 if cleaned.len() > 1 && cleaned.last() == cleaned.first() {
136 cleaned.pop();
137 }
138 if cleaned.len() < 3 {
139 return None;
140 }
141 if (signed_area_2x(&cleaned) > 0.0) != ccw {
142 cleaned.reverse();
143 }
144 let n = cleaned.len();
145 Some(Self {
146 points: cleaned,
147 segs: vec![RingSeg::Line; n],
148 })
149 }
150
151 #[must_use]
153 pub fn ensure_orientation(mut self, ccw: bool) -> Self {
154 let sampled = self.flatten_polygon(32);
155 if sampled.len() < 3 {
156 return self;
157 }
158 if (signed_area_2x(&sampled) > 0.0) == ccw {
159 return self;
160 }
161 let n = self.points.len();
162 if n < 2 {
163 return self;
164 }
165 let mut rev_pts = Vec::with_capacity(n);
166 rev_pts.push(self.points[0]);
167 for idx in (1..n).rev() {
168 rev_pts.push(self.points[idx]);
169 }
170 let mut rev_segs = Vec::with_capacity(n);
171 for idx in 0..n {
172 let orig = self.segs[(n - 1 - idx) % n];
173 let flipped = match orig {
174 RingSeg::Line => RingSeg::Line,
175 RingSeg::Arc {
176 center,
177 ccw: arc_ccw,
178 major,
179 } => RingSeg::Arc {
180 center,
181 ccw: !arc_ccw,
182 major,
183 },
184 };
185 rev_segs.push(flipped);
186 }
187 self.points = rev_pts;
188 self.segs = rev_segs;
189 self
190 }
191
192 #[must_use]
194 pub fn flatten_polygon(&self, max_arc_steps: usize) -> Vec<CoordNm> {
195 let n = self.points.len();
196 if n < 2 {
197 return self.points.clone();
198 }
199 let mut out = Vec::with_capacity(n);
200 for i in 0..n {
201 let p0 = self.points[i];
202 let p1 = self.points[(i + 1) % n];
203 out.push(p0);
204 if let Some(RingSeg::Arc { center, ccw, .. }) = self.segs.get(i).copied() {
205 append_arc_interior_points(&mut out, p0, p1, center, ccw, max_arc_steps);
206 }
207 }
208 out
209 }
210
211 #[must_use]
213 pub fn signed_area(&self) -> f64 {
214 let poly = self.flatten_polygon(24);
215 0.5 * signed_area_2x(&poly)
216 }
217
218 #[must_use]
220 pub fn bounds(&self) -> Option<[i64; 4]> {
221 let poly = self.flatten_polygon(16);
222 let first = *poly.first()?;
223 let mut b = [first.x, first.y, first.x, first.y];
224 for pt in poly.iter().skip(1) {
225 b[0] = b[0].min(pt.x);
226 b[1] = b[1].min(pt.y);
227 b[2] = b[2].max(pt.x);
228 b[3] = b[3].max(pt.y);
229 }
230 Some(b)
231 }
232}
233
234#[must_use]
236pub fn signed_area_2x(pts: &[CoordNm]) -> f64 {
237 let n = pts.len();
238 if n < 3 {
239 return 0.0;
240 }
241 let mut area2 = 0.0;
242 let mut prev = pts[n - 1];
243 for &cur in pts {
244 area2 += (prev.x as f64) * (cur.y as f64) - (cur.x as f64) * (prev.y as f64);
245 prev = cur;
246 }
247 area2
248}
249
250#[must_use]
252pub fn circle_from_3pts(
253 p1: (f64, f64),
254 p2: (f64, f64),
255 p3: (f64, f64),
256) -> Option<((f64, f64), f64, bool)> {
257 let (ax, ay) = p1;
258 let (bx, by) = p2;
259 let (cx, cy) = p3;
260 let d = 2.0 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
261 if d.abs() < 1e-3 {
262 return None;
263 }
264 let a2 = ax * ax + ay * ay;
265 let b2 = bx * bx + by * by;
266 let c2 = cx * cx + cy * cy;
267 let ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / d;
268 let uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / d;
269 let r = (ax - ux).hypot(ay - uy);
270 if !r.is_finite() || r <= 0.0 {
271 return None;
272 }
273 let cross = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
274 Some(((ux, uy), r, cross > 0.0))
275}
276
277pub fn append_arc_interior_points(
279 out: &mut Vec<CoordNm>,
280 p0: CoordNm,
281 p1: CoordNm,
282 center: CoordNm,
283 ccw: bool,
284 max_steps: usize,
285) {
286 let r = ((p0.x - center.x) as f64).hypot((p0.y - center.y) as f64);
287 if r <= 1.0 {
288 return;
289 }
290 let a0 = ((p0.y - center.y) as f64).atan2((p0.x - center.x) as f64);
291 let a1 = ((p1.y - center.y) as f64).atan2((p1.x - center.x) as f64);
292 let tau = std::f64::consts::TAU;
293 let da = if ccw {
294 let raw = (a1 - a0).rem_euclid(tau);
295 if raw < 1e-9 { tau } else { raw }
296 } else {
297 let raw = (a0 - a1).rem_euclid(tau);
298 -if raw < 1e-9 { tau } else { raw }
299 };
300 let steps =
301 ((da.abs() / (std::f64::consts::PI / 16.0)).ceil() as usize).clamp(4, max_steps.max(4));
302 for step in 1..steps {
303 let ang = a0 + da * (step as f64 / steps as f64);
304 let (s, c) = ang.sin_cos();
305 out.push(CoordNm::new(
306 center.x.saturating_add((r * c).round() as i64),
307 center.y.saturating_add((r * s).round() as i64),
308 ));
309 }
310}
311
312#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize)]
314pub struct ChamferCorners {
315 pub upper_left: bool,
316 pub upper_right: bool,
317 pub lower_left: bool,
318 pub lower_right: bool,
319}
320
321impl ChamferCorners {
322 #[must_use]
323 pub const fn any(self) -> bool {
324 self.upper_left || self.upper_right || self.lower_left || self.lower_right
325 }
326}
327
328#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
330pub enum AreaShape {
331 Disk {
332 radius: i64,
333 },
334 Rect {
335 width: i64,
336 height: i64,
337 },
338 Capsule {
340 length: i64,
341 width: i64,
342 },
343 RoundedRect {
344 width: i64,
345 height: i64,
346 radius: i64,
347 },
348 ChamferedRect {
349 width: i64,
350 height: i64,
351 chamfer: i64,
352 corners: ChamferCorners,
353 },
354 Trapezoid {
355 width: i64,
356 height: i64,
357 delta_x: i64,
358 delta_y: i64,
359 },
360 Region {
361 outer: Ring2D,
362 holes: Vec<Ring2D>,
363 },
364}
365
366#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
368pub enum LandRole {
369 SmdPad,
370 PlatedPad,
371 NonPlatedPad,
372 Via,
373}
374
375#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
377pub enum LandKind {
378 PadLand,
379 ViaLand,
380 MaskLand,
381 PasteLand,
382}
383
384#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
386pub struct FabLand {
387 pub kind: LandKind,
388 pub role: LandRole,
389 pub shape: AreaShape,
390 pub placement: Placement2D,
391 pub net: Option<String>,
392 pub component: Option<String>,
393 pub pin: Option<String>,
394 pub source: Option<String>,
395}
396
397#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
399pub enum StrokeKind {
400 Route,
401 TextStroke,
402 SolderMaskText,
403 PasteText,
404 Virtual,
405}
406
407#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
409pub enum StrokePath {
410 Line {
411 start: CoordNm,
412 end: CoordNm,
413 },
414 Arc {
415 start: CoordNm,
416 end: CoordNm,
417 center: CoordNm,
418 ccw: bool,
419 major: bool,
420 },
421 FullCircle {
422 center: CoordNm,
423 radius: i64,
424 },
425}
426
427#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
429pub struct FabStroke {
430 pub kind: StrokeKind,
431 pub path: StrokePath,
432 pub width: i64,
433 pub net: Option<String>,
434 pub component: Option<String>,
435 pub source: Option<String>,
436}
437
438#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
440pub enum AreaKind {
441 PolygonCopper,
442 Region,
443 TextOutline,
444 SolderMaskText,
445 PasteText,
446 ProfileBoard,
447 ProfileCutout,
448 Virtual,
449}
450
451#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
453pub struct FabArea {
454 pub kind: AreaKind,
455 pub shape: AreaShape,
456 pub placement: Placement2D,
457 pub net: Option<String>,
458 pub component: Option<String>,
459 pub source: Option<String>,
460}
461
462#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
464pub struct FabDrillPair {
465 pub id: usize,
466 pub is_micro: bool,
467 pub start_key: String,
468 pub end_key: String,
469}
470
471#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
473pub struct FabHole {
474 pub id: String,
475 pub center: CoordNm,
476 pub diameter: i64,
477 pub plated: bool,
478 pub drill_pair: usize,
479 pub is_via: bool,
480 pub slot_rout: Option<(CoordNm, CoordNm)>,
482 pub net: Option<String>,
483 #[serde(default)]
484 pub component: Option<String>,
485 #[serde(default)]
486 pub pin: Option<String>,
487 pub source: Option<String>,
488}
489
490#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
492pub struct FabProfile {
493 pub outer: Ring2D,
494 pub cutouts: Vec<Ring2D>,
495}
496
497#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
499pub enum LayerRole {
500 Conductor,
501 SolderMask,
502 Paste,
503 Silkscreen,
504 Profile,
505 Mechanical,
506 Virtual,
507}
508
509#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
511pub enum LayerSide {
512 Top,
513 Internal,
514 Bottom,
515 None,
516}
517
518#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
520pub struct FabLayer {
521 pub key: String,
522 pub kicad_name: String,
523 pub role: LayerRole,
524 pub side: LayerSide,
525 pub positive: bool,
526 pub copper_index: Option<usize>,
527}
528
529pub const DOT_NM: f64 = 100.0;
532
533#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
535pub struct FabLayerItems {
536 pub lands: Vec<FabLand>,
537 pub strokes: Vec<FabStroke>,
538 pub areas: Vec<FabArea>,
539}
540
541impl FabLayerItems {
542 #[must_use]
543 pub fn is_empty(&self) -> bool {
544 self.lands.is_empty() && self.strokes.is_empty() && self.areas.is_empty()
545 }
546
547 pub fn push_stroke_or_dot(&mut self, stroke: FabStroke) {
550 if stroke.width <= 0 {
551 return;
552 }
553 let half = stroke.width as f64 / 2.0;
554 let dot = match stroke.path {
555 StrokePath::Line { start, end } => {
556 let dx = end.x as f64 - start.x as f64;
557 let dy = end.y as f64 - start.y as f64;
558 (dx.hypot(dy) <= DOT_NM).then(|| {
559 let mx = ((start.x as f64 + end.x as f64) * 0.5).round_ties_even() as i64;
560 let my = ((start.y as f64 + end.y as f64) * 0.5).round_ties_even() as i64;
561 (CoordNm::new(mx, my), half.round_ties_even() as i64)
562 })
563 }
564 StrokePath::Arc { start, center, .. } => {
565 let dx = start.x as f64 - center.x as f64;
566 let dy = start.y as f64 - center.y as f64;
567 let r = dx.hypot(dy);
568 (2.0 * r <= DOT_NM).then(|| (center, (r + half).round_ties_even() as i64))
569 }
570 StrokePath::FullCircle { center, radius } => {
571 if radius < 0 {
572 return;
573 }
574 let r = radius as f64;
575 (2.0 * r <= DOT_NM).then(|| (center, (r + half).round_ties_even() as i64))
576 }
577 };
578 if let Some((center, radius)) = dot {
579 if radius <= 0 {
580 return;
581 }
582 let kind = match stroke.kind {
583 StrokeKind::TextStroke => AreaKind::TextOutline,
584 StrokeKind::SolderMaskText => AreaKind::SolderMaskText,
585 StrokeKind::PasteText => AreaKind::PasteText,
586 StrokeKind::Virtual => AreaKind::Virtual,
587 StrokeKind::Route => AreaKind::Region,
588 };
589 self.areas.push(FabArea {
590 kind,
591 shape: AreaShape::Disk { radius },
592 placement: Placement2D::translate(center.x, center.y),
593 net: stroke.net,
594 component: stroke.component,
595 source: stroke.source,
596 });
597 return;
598 }
599 self.strokes.push(stroke);
600 }
601}
602
603#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
605pub struct FabComponent {
606 pub id: String,
607 pub designator: String,
608 pub value: String,
609 pub footprint: String,
610 pub description: String,
611 pub side: LayerSide,
612 pub center: CoordNm,
613 pub rotation_deg: f64,
614 pub fitted: bool,
615 pub exclude_from_bom: bool,
616 pub exclude_from_pos: bool,
617 pub board_only: bool,
618 #[serde(default)]
620 pub pins: Vec<String>,
621 #[serde(default)]
623 pub parameters: BTreeMap<String, String>,
624}
625
626#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
628pub struct FabStackRow {
629 pub name: String,
630 pub kind: String,
631 pub layer_key: Option<String>,
632 pub thickness_nm: i64,
633 pub material: String,
634}