1use crate::geom::{
4 AreaKind, AreaShape, CoordNm, FabArea, FabLayerItems, FabStroke, Placement2D, Ring2D,
5 StrokeKind, StrokePath, fp_local_to_board_mm, mm_to_nm, pt_up,
6};
7use crate::layer_map::LayerMap;
8use cad_text_realization::{
9 StrokeTextProfile, StrokeTextRequest, TextHorizontalAlignment, TextVerticalAlignment,
10 realize_stroke_text_multiline_profile_a0,
11};
12use kicad_monkey_core::pcb::{PcbBoardText, PcbFootprint, PcbFootprintProperty, PcbFootprintText};
13use kicad_monkey_core::text_metadata::KiCadTextEffects;
14use kicad_monkey_core::text_render_cache::read_text_render_cache_a0;
15use kicad_monkey_core::{is_builtin_stroke_font_face, keep_upright_draw_angle};
16use std::collections::{BTreeSet, HashMap};
17use std::ops::Range;
18
19struct TextEmitSpec<'a> {
20 source: &'a str,
21 text: &'a str,
22 layer: &'a str,
23 x_mm: f64,
24 y_mm: f64,
25 angle_deg: f64,
26 effects: &'a KiCadTextEffects,
27 render_cache_range: Option<&'a Range<usize>>,
28 component: Option<&'a str>,
29 uuid: Option<&'a str>,
30}
31
32pub fn emit_board_text(
34 source: &str,
35 bt: &PcbBoardText,
36 layer_map: &LayerMap,
37 buckets: &mut HashMap<String, FabLayerItems>,
38) {
39 if bt.hidden || bt.effects.hidden || bt.text.trim().is_empty() {
40 return;
41 }
42 emit_text_item(
43 &TextEmitSpec {
44 source,
45 text: &bt.text,
46 layer: &bt.layer,
47 x_mm: bt.at.x,
48 y_mm: bt.at.y,
49 angle_deg: bt.angle,
50 effects: &bt.effects,
51 render_cache_range: bt.render_cache_range.as_ref(),
52 component: None,
53 uuid: bt.uuid.as_deref(),
54 },
55 layer_map,
56 buckets,
57 );
58}
59
60pub fn emit_footprint_text(
62 source: &str,
63 fp: &PcbFootprint,
64 ft: &PcbFootprintText,
65 comp_id: &str,
66 layer_map: &LayerMap,
67 buckets: &mut HashMap<String, FabLayerItems>,
68 designator_sources: &mut BTreeSet<String>,
69) {
70 if ft.hidden || ft.effects.hidden || ft.text.trim().is_empty() {
71 return;
72 }
73 let (bx, by) = fp_local_to_board_mm(
74 fp.at_x.unwrap_or(0.0),
75 fp.at_y.unwrap_or(0.0),
76 fp.angle.unwrap_or(0.0),
77 ft.at.x,
78 ft.at.y,
79 );
80 let draw_angle = if ft.unlocked {
81 ft.angle
82 } else {
83 keep_upright_draw_angle(ft.angle)
84 };
85 let is_ref = ft.kind.eq_ignore_ascii_case("reference");
86 let synthetic_uid;
87 let uuid = if is_ref {
88 if let Some(u) = ft.uuid.as_deref().filter(|s| !s.is_empty()) {
89 designator_sources.insert(u.to_owned());
90 Some(u)
91 } else {
92 synthetic_uid = format!("designator:{comp_id}:{}", ft.layer);
93 designator_sources.insert(synthetic_uid.clone());
94 Some(synthetic_uid.as_str())
95 }
96 } else {
97 ft.uuid.as_deref()
98 };
99 emit_text_item(
100 &TextEmitSpec {
101 source,
102 text: &ft.text,
103 layer: &ft.layer,
104 x_mm: bx,
105 y_mm: by,
106 angle_deg: draw_angle,
107 effects: &ft.effects,
108 render_cache_range: ft.render_cache_range.as_ref(),
109 component: Some(comp_id),
110 uuid,
111 },
112 layer_map,
113 buckets,
114 );
115}
116
117pub fn emit_footprint_property(
119 source: &str,
120 fp: &PcbFootprint,
121 prop: &PcbFootprintProperty,
122 comp_id: &str,
123 layer_map: &LayerMap,
124 buckets: &mut HashMap<String, FabLayerItems>,
125 designator_sources: &mut BTreeSet<String>,
126) {
127 if !prop.graphical || prop.hidden || prop.effects.hidden || prop.value.trim().is_empty() {
128 return;
129 }
130 let (bx, by) = fp_local_to_board_mm(
131 fp.at_x.unwrap_or(0.0),
132 fp.at_y.unwrap_or(0.0),
133 fp.angle.unwrap_or(0.0),
134 prop.at.x,
135 prop.at.y,
136 );
137 let draw_angle = if prop.unlocked {
138 prop.angle
139 } else {
140 keep_upright_draw_angle(prop.angle)
141 };
142 let is_ref = prop.name.eq_ignore_ascii_case("reference");
143 let synthetic_uid;
144 let uuid = if is_ref {
145 if let Some(u) = prop.uuid.as_deref().filter(|s| !s.is_empty()) {
146 designator_sources.insert(u.to_owned());
147 Some(u)
148 } else {
149 synthetic_uid = format!("designator:{comp_id}:{}", prop.layer);
150 designator_sources.insert(synthetic_uid.clone());
151 Some(synthetic_uid.as_str())
152 }
153 } else {
154 prop.uuid.as_deref()
155 };
156 emit_text_item(
157 &TextEmitSpec {
158 source,
159 text: &prop.value,
160 layer: &prop.layer,
161 x_mm: bx,
162 y_mm: by,
163 angle_deg: draw_angle,
164 effects: &prop.effects,
165 render_cache_range: prop.render_cache_range.as_ref(),
166 component: Some(comp_id),
167 uuid,
168 },
169 layer_map,
170 buckets,
171 );
172}
173
174#[must_use]
176pub fn realize_stroke_label(
177 text: &str,
178 center: CoordNm,
179 height_mm: f64,
180 angle_deg: f64,
181 mirrored: bool,
182 stroke_width_mm: Option<f64>,
183) -> (Vec<Vec<CoordNm>>, i64) {
184 if text.trim().is_empty() || height_mm <= 0.0 {
185 return (Vec::new(), 0);
186 }
187 let request = StrokeTextRequest {
188 text,
189 position_x_mm: center.x as f64 / 1_000_000.0,
190 position_y_mm: -(center.y as f64) / 1_000_000.0,
191 size_x_mm: height_mm,
192 size_y_mm: height_mm,
193 angle_degrees: angle_deg,
194 horizontal_alignment: TextHorizontalAlignment::Center,
195 vertical_alignment: TextVerticalAlignment::Center,
196 mirrored,
197 italic: false,
198 bold: false,
199 stroke_width_mm,
200 };
201 let Ok(output) =
202 realize_stroke_text_multiline_profile_a0(request, None, StrokeTextProfile::kicad())
203 else {
204 return (Vec::new(), 0);
205 };
206 let width_nm = mm_to_nm(output.effective_stroke_width_mm).max(15_000);
207 let polylines = output
208 .polylines
209 .into_iter()
210 .map(|pl| {
211 pl.points
212 .into_iter()
213 .map(|p| pt_up(p.x_mm, p.y_mm))
214 .collect::<Vec<_>>()
215 })
216 .filter(|pts| pts.len() >= 2)
217 .collect();
218 (polylines, width_nm)
219}
220
221fn emit_text_item(
222 spec: &TextEmitSpec<'_>,
223 layer_map: &LayerMap,
224 buckets: &mut HashMap<String, FabLayerItems>,
225) {
226 if spec.layer == "Edge.Cuts" {
227 return;
228 }
229 let Some(fab_key) = layer_map.fab_key(spec.layer) else {
230 return;
231 };
232
233 let face = spec.effects.font.face.as_deref().unwrap_or("");
234 let is_stroke_font = face.is_empty() || is_builtin_stroke_font_face(face);
235 if !is_stroke_font
236 && let Some(range) = spec.render_cache_range
237 && emit_render_cache_polygons(spec, range, fab_key, buckets)
238 {
239 return;
240 }
241
242 let font = &spec.effects.font;
243 let size_x = font.size_x;
244 let size_y = font.size_y;
245 if size_x <= 0.0 || size_y <= 0.0 {
246 return;
247 }
248 let (h_align, v_align, mirrored) = parse_justify(&spec.effects.justify);
249 let request = StrokeTextRequest {
250 text: spec.text,
251 position_x_mm: spec.x_mm,
252 position_y_mm: spec.y_mm,
253 size_x_mm: size_x,
254 size_y_mm: size_y,
255 angle_degrees: spec.angle_deg,
256 horizontal_alignment: h_align,
257 vertical_alignment: v_align,
258 mirrored,
259 italic: font.italic,
260 bold: font.bold,
261 stroke_width_mm: font.thickness.filter(|&t| t > 0.0),
262 };
263 let line_spacing = font.line_spacing.filter(|&s| s.is_finite() && s > 0.0);
264 let Ok(output) =
265 realize_stroke_text_multiline_profile_a0(request, line_spacing, StrokeTextProfile::kicad())
266 else {
267 return;
268 };
269 let stroke_w = mm_to_nm(output.effective_stroke_width_mm).max(1);
270 let kind = stroke_kind_for_layer(fab_key);
271 let bucket = buckets.entry(fab_key.to_owned()).or_default();
272 for pl in output.polylines {
273 for pair in pl.points.windows(2) {
274 let p0 = pt_up(pair[0].x_mm, pair[0].y_mm);
275 let p1 = pt_up(pair[1].x_mm, pair[1].y_mm);
276 if p0 == p1 {
277 continue;
278 }
279 bucket.push_stroke_or_dot(FabStroke {
280 kind,
281 path: StrokePath::Line { start: p0, end: p1 },
282 width: stroke_w,
283 net: None,
284 component: spec.component.map(str::to_owned),
285 source: spec.uuid.map(str::to_owned),
286 });
287 }
288 }
289}
290
291fn emit_render_cache_polygons(
292 spec: &TextEmitSpec<'_>,
293 range: &Range<usize>,
294 fab_key: &str,
295 buckets: &mut HashMap<String, FabLayerItems>,
296) -> bool {
297 let Some(slice) = spec.source.get(range.start..range.end) else {
298 return false;
299 };
300 let Ok(cache) = read_text_render_cache_a0(slice.as_bytes()) else {
301 return false;
302 };
303 if cache.polygons.is_empty() {
304 return false;
305 }
306 let kind = area_kind_for_layer(fab_key);
307 let bucket = buckets.entry(fab_key.to_owned()).or_default();
308 let mut emitted = false;
309 for poly in cache.polygons {
310 for contour in poly.contours {
311 let pts: Vec<CoordNm> = contour.points.iter().map(|p| pt_up(p.x, p.y)).collect();
312 let Some(ring) = Ring2D::from_points_oriented(&pts, true) else {
313 continue;
314 };
315 bucket.areas.push(FabArea {
316 kind,
317 shape: AreaShape::Region {
318 outer: ring,
319 holes: Vec::new(),
320 },
321 placement: Placement2D::identity(),
322 net: None,
323 component: spec.component.map(str::to_owned),
324 source: spec.uuid.map(str::to_owned),
325 });
326 emitted = true;
327 }
328 }
329 emitted
330}
331
332fn parse_justify(tokens: &[String]) -> (TextHorizontalAlignment, TextVerticalAlignment, bool) {
333 let mut h = TextHorizontalAlignment::Center;
334 let mut v = TextVerticalAlignment::Center;
335 let mut mirror = false;
336 for tok in tokens {
337 match tok.as_str() {
338 "left" => h = TextHorizontalAlignment::Left,
339 "right" => h = TextHorizontalAlignment::Right,
340 "top" => v = TextVerticalAlignment::Top,
341 "bottom" => v = TextVerticalAlignment::Bottom,
342 "mirror" => mirror = true,
343 _ => {}
344 }
345 }
346 (h, v, mirror)
347}
348
349fn stroke_kind_for_layer(fab_key: &str) -> StrokeKind {
350 match fab_key {
351 "TOPSOLDER" | "BOTTOMSOLDER" => StrokeKind::SolderMaskText,
352 "TOPPASTE" | "BOTTOMPASTE" => StrokeKind::PasteText,
353 _ => StrokeKind::TextStroke,
354 }
355}
356
357fn area_kind_for_layer(fab_key: &str) -> AreaKind {
358 match fab_key {
359 "TOPSOLDER" | "BOTTOMSOLDER" => AreaKind::SolderMaskText,
360 "TOPPASTE" | "BOTTOMPASTE" => AreaKind::PasteText,
361 _ => AreaKind::TextOutline,
362 }
363}