1use crate::geom::{
4 AreaKind, AreaShape, CoordNm, FabArea, FabLayerItems, FabStroke, Placement2D, Ring2D,
5 StrokeKind, StrokePath, circle_from_3pts, fp_local_to_board_mm, mm_to_nm, pt_up,
6};
7use crate::layer_map::LayerMap;
8use crate::view::pads::swept_arc_path;
9use kicad_monkey_core::pcb::{PcbFootprint, PcbGraphic, PcbGraphicKind, PcbPolygonPoint};
10use std::collections::HashMap;
11
12pub fn emit_graphic(
14 graphic: &PcbGraphic,
15 fp: Option<&PcbFootprint>,
16 comp_id: Option<&str>,
17 layer_map: &LayerMap,
18 buckets: &mut HashMap<String, FabLayerItems>,
19) {
20 let klayers = graphic_concrete_layers(graphic, layer_map);
21 if klayers.is_empty() {
22 return;
23 }
24 let xform = |x: f64, y: f64| -> CoordNm {
25 match fp {
26 Some(owner) => {
27 let (bx, by) = fp_local_to_board_mm(
28 owner.at_x.unwrap_or(0.0),
29 owner.at_y.unwrap_or(0.0),
30 owner.angle.unwrap_or(0.0),
31 x,
32 y,
33 );
34 pt_up(bx, by)
35 }
36 None => pt_up(x, y),
37 }
38 };
39 match graphic.kind {
40 PcbGraphicKind::Line => emit_line(graphic, &klayers, &xform, comp_id, layer_map, buckets),
41 PcbGraphicKind::Arc => emit_arc(graphic, &klayers, &xform, comp_id, layer_map, buckets),
42 PcbGraphicKind::Circle => {
43 emit_circle(graphic, &klayers, &xform, comp_id, layer_map, buckets);
44 }
45 PcbGraphicKind::Rect => emit_rect(graphic, &klayers, &xform, comp_id, layer_map, buckets),
46 PcbGraphicKind::Poly => emit_poly(graphic, &klayers, &xform, comp_id, layer_map, buckets),
47 _ => {}
48 }
49}
50
51fn graphic_concrete_layers(graphic: &PcbGraphic, layer_map: &LayerMap) -> Vec<String> {
52 if let Some(plural) = graphic.layers.as_ref()
53 && !plural.is_empty()
54 {
55 return layer_map
56 .expand_layers(plural)
57 .into_iter()
58 .filter(|l| l != "Edge.Cuts")
59 .collect();
60 }
61 match graphic.layer.as_deref() {
62 Some(l) if !l.is_empty() && l != "Edge.Cuts" => vec![l.to_owned()],
63 _ => Vec::new(),
64 }
65}
66
67fn is_filled(graphic: &PcbGraphic, klayer: &str) -> bool {
68 !matches!(
69 graphic.effective_fill_for_layer(klayer),
70 "none" | "no" | "false" | "0"
71 )
72}
73
74fn emit_line(
75 graphic: &PcbGraphic,
76 klayers: &[String],
77 xform: &impl Fn(f64, f64) -> CoordNm,
78 comp_id: Option<&str>,
79 layer_map: &LayerMap,
80 buckets: &mut HashMap<String, FabLayerItems>,
81) {
82 let (Some(start), Some(end)) = (graphic.start, graphic.end) else {
83 return;
84 };
85 let path = StrokePath::Line {
86 start: xform(start.x, start.y),
87 end: xform(end.x, end.y),
88 };
89 for kl in klayers {
90 let Some(fk) = layer_map.fab_key(kl) else {
91 continue;
92 };
93 let w = mm_to_nm(graphic.effective_stroke_width_for_layer(kl)).max(0);
94 buckets
95 .entry(fk.to_owned())
96 .or_default()
97 .push_stroke_or_dot(FabStroke {
98 kind: StrokeKind::Route,
99 path: path.clone(),
100 width: w,
101 net: None,
102 component: comp_id.map(str::to_owned),
103 source: graphic.uuid.clone(),
104 });
105 }
106}
107
108fn emit_arc(
109 graphic: &PcbGraphic,
110 klayers: &[String],
111 xform: &impl Fn(f64, f64) -> CoordNm,
112 comp_id: Option<&str>,
113 layer_map: &LayerMap,
114 buckets: &mut HashMap<String, FabLayerItems>,
115) {
116 let (Some(start), Some(mid), Some(end)) = (graphic.start, graphic.mid, graphic.end) else {
117 return;
118 };
119 let path = swept_arc_path(
120 xform(start.x, start.y),
121 xform(mid.x, mid.y),
122 xform(end.x, end.y),
123 );
124 for kl in klayers {
125 let Some(fk) = layer_map.fab_key(kl) else {
126 continue;
127 };
128 let w = mm_to_nm(graphic.effective_stroke_width_for_layer(kl)).max(0);
129 buckets
130 .entry(fk.to_owned())
131 .or_default()
132 .push_stroke_or_dot(FabStroke {
133 kind: StrokeKind::Route,
134 path: path.clone(),
135 width: w,
136 net: None,
137 component: comp_id.map(str::to_owned),
138 source: graphic.uuid.clone(),
139 });
140 }
141}
142
143fn emit_circle(
144 graphic: &PcbGraphic,
145 klayers: &[String],
146 xform: &impl Fn(f64, f64) -> CoordNm,
147 comp_id: Option<&str>,
148 layer_map: &LayerMap,
149 buckets: &mut HashMap<String, FabLayerItems>,
150) {
151 let (Some(center), Some(end)) = (graphic.center, graphic.end) else {
152 return;
153 };
154 let c = xform(center.x, center.y);
155 let e = xform(end.x, end.y);
156 let r = ((e.x - c.x) as f64).hypot((e.y - c.y) as f64).round() as i64;
157 if r <= 0 {
158 return;
159 }
160 for kl in klayers {
161 let Some(fk) = layer_map.fab_key(kl) else {
162 continue;
163 };
164 let bucket = buckets.entry(fk.to_owned()).or_default();
165 if is_filled(graphic, kl) {
166 bucket.areas.push(FabArea {
167 kind: AreaKind::Region,
168 shape: AreaShape::Disk { radius: r },
169 placement: Placement2D::translate(c.x, c.y),
170 net: None,
171 component: comp_id.map(str::to_owned),
172 source: graphic.uuid.clone(),
173 });
174 } else {
175 let w = mm_to_nm(graphic.effective_stroke_width_for_layer(kl)).max(0);
176 bucket.push_stroke_or_dot(FabStroke {
177 kind: StrokeKind::Route,
178 path: StrokePath::FullCircle {
179 center: c,
180 radius: r,
181 },
182 width: w,
183 net: None,
184 component: comp_id.map(str::to_owned),
185 source: graphic.uuid.clone(),
186 });
187 }
188 }
189}
190
191fn emit_rect(
192 graphic: &PcbGraphic,
193 klayers: &[String],
194 xform: &impl Fn(f64, f64) -> CoordNm,
195 comp_id: Option<&str>,
196 layer_map: &LayerMap,
197 buckets: &mut HashMap<String, FabLayerItems>,
198) {
199 let (Some(start), Some(end)) = (graphic.start, graphic.end) else {
200 return;
201 };
202 let corners = [
203 xform(start.x, start.y),
204 xform(end.x, start.y),
205 xform(end.x, end.y),
206 xform(start.x, end.y),
207 ];
208 for kl in klayers {
209 let Some(fk) = layer_map.fab_key(kl) else {
210 continue;
211 };
212 let bucket = buckets.entry(fk.to_owned()).or_default();
213 if is_filled(graphic, kl) {
214 if let Some(ring) = Ring2D::from_points_oriented(&corners, true) {
215 bucket.areas.push(FabArea {
216 kind: AreaKind::Region,
217 shape: AreaShape::Region {
218 outer: ring,
219 holes: Vec::new(),
220 },
221 placement: Placement2D::identity(),
222 net: None,
223 component: comp_id.map(str::to_owned),
224 source: graphic.uuid.clone(),
225 });
226 }
227 } else {
228 let w = mm_to_nm(graphic.effective_stroke_width_for_layer(kl)).max(0);
229 for idx in 0..4 {
230 bucket.push_stroke_or_dot(FabStroke {
231 kind: StrokeKind::Route,
232 path: StrokePath::Line {
233 start: corners[idx],
234 end: corners[(idx + 1) % 4],
235 },
236 width: w,
237 net: None,
238 component: comp_id.map(str::to_owned),
239 source: graphic.uuid.clone(),
240 });
241 }
242 }
243 }
244}
245
246fn emit_poly(
247 graphic: &PcbGraphic,
248 klayers: &[String],
249 xform: &impl Fn(f64, f64) -> CoordNm,
250 comp_id: Option<&str>,
251 layer_map: &LayerMap,
252 buckets: &mut HashMap<String, FabLayerItems>,
253) {
254 let mut pts: Vec<CoordNm> =
255 Vec::with_capacity(graphic.polygon_points.len().max(graphic.points.len()));
256 if !graphic.polygon_points.is_empty() {
257 for item in &graphic.polygon_points {
258 match item {
259 PcbPolygonPoint::Xy(p) => pts.push(xform(p.x, p.y)),
260 PcbPolygonPoint::Arc { start, mid, end } => {
261 let p0 = xform(start.x, start.y);
262 let pm = xform(mid.x, mid.y);
263 let p1 = xform(end.x, end.y);
264 pts.push(p0);
265 if let Some(((cx, cy), _, ccw)) = circle_from_3pts(
266 (p0.x as f64, p0.y as f64),
267 (pm.x as f64, pm.y as f64),
268 (p1.x as f64, p1.y as f64),
269 ) {
270 crate::geom::append_arc_interior_points(
271 &mut pts,
272 p0,
273 p1,
274 CoordNm::new(cx.round() as i64, cy.round() as i64),
275 ccw,
276 24,
277 );
278 }
279 pts.push(p1);
280 }
281 }
282 }
283 } else {
284 pts.extend(graphic.points.iter().map(|p| xform(p.x, p.y)));
285 }
286 if pts.len() < 3 {
287 return;
288 }
289 for kl in klayers {
290 let Some(fk) = layer_map.fab_key(kl) else {
291 continue;
292 };
293 let bucket = buckets.entry(fk.to_owned()).or_default();
294 if is_filled(graphic, kl) {
295 if let Some(ring) = Ring2D::from_points_oriented(&pts, true) {
296 bucket.areas.push(FabArea {
297 kind: AreaKind::Region,
298 shape: AreaShape::Region {
299 outer: ring,
300 holes: Vec::new(),
301 },
302 placement: Placement2D::identity(),
303 net: None,
304 component: comp_id.map(str::to_owned),
305 source: graphic.uuid.clone(),
306 });
307 }
308 } else {
309 let w = mm_to_nm(graphic.effective_stroke_width_for_layer(kl)).max(0);
310 for idx in 0..pts.len() {
311 bucket.push_stroke_or_dot(FabStroke {
312 kind: StrokeKind::Route,
313 path: StrokePath::Line {
314 start: pts[idx],
315 end: pts[(idx + 1) % pts.len()],
316 },
317 width: w,
318 net: None,
319 component: comp_id.map(str::to_owned),
320 source: graphic.uuid.clone(),
321 });
322 }
323 }
324 }
325}