-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGerberConverter.cpp
More file actions
1392 lines (1282 loc) · 53.1 KB
/
Copy pathGerberConverter.cpp
File metadata and controls
1392 lines (1282 loc) · 53.1 KB
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "GerberConverter.h"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <map>
#include <regex>
#include <set>
#include <sstream>
#include <utility>
#include <vector>
namespace {
const double PI = 3.14159265358979323846;
std::string trimWhitespace(const std::string& input) {
size_t start = 0;
while (start < input.size() && std::isspace(static_cast<unsigned char>(input[start]))) {
start++;
}
size_t end = input.size();
while (end > start && std::isspace(static_cast<unsigned char>(input[end - 1]))) {
end--;
}
return input.substr(start, end - start);
}
std::string fileNameOf(const std::string& path) {
return path.substr(path.find_last_of("/\\") + 1);
}
std::string baseNameOf(const std::string& path) {
std::string name = fileNameOf(path);
size_t dot = name.find_last_of('.');
return (dot == std::string::npos) ? name : name.substr(0, dot);
}
struct Pt {
double x;
double y;
};
Pt rotateDeg(const Pt& p, double deg) {
if (deg == 0.0) {
return p;
}
double rad = deg * PI / 180.0;
double c = std::cos(rad);
double s = std::sin(rad);
Pt r = { p.x * c - p.y * s, p.x * s + p.y * c };
return r;
}
// Collects warnings, deduplicated by key so per-flash issues are reported once.
struct WarnSink {
std::vector<std::string>& out;
std::set<std::string> seen;
explicit WarnSink(std::vector<std::string>& o) : out(o) {}
void once(const std::string& key, const std::string& msg) {
if (seen.insert(key).second) {
out.push_back(msg);
}
}
};
enum class ApType { Circle, Rect, Obround, Poly, Macro };
struct Aperture {
ApType type = ApType::Circle;
std::string macroName; // only for ApType::Macro
std::vector<double> params; // raw %ADD parameters, in file units
bool flashAsRegion = false; // geometry emitted as G36/G37 outlines
};
struct MacroDef {
std::string name;
std::vector<std::string> primitives; // '*'-separated blocks, comments stripped
};
// One fully parsed input Gerber file.
struct ParsedGerber {
std::string fileName; // display name
std::map<int, Aperture> apertures; // by local D-code
std::map<std::string, MacroDef> macros;
std::vector<std::string> commands;
int fracDigits = 6; // KiCad default: %FSLAX46Y46
double unitToMM = 1.0; // %MOMM -> 1, %MOIN -> 25.4
};
// One entry of the unified aperture wheel. Carries everything needed to
// render flashes without going back to the source file.
struct GlobalAp {
ApType type = ApType::Circle;
std::string macroName;
std::vector<double> params; // in file units of the defining file
double unitToMM = 1.0;
bool hasMacroDef = false;
MacroDef macroDef;
bool flashAsRegion = false;
bool contoursBuilt = false;
std::vector<std::vector<Pt>> contours; // flash outline(s) in mm, at origin
};
// Oval/slot hole extracted from a drill file.
struct Slot {
std::vector<Pt> pathMM; // slot centerline, in mm
double diamMM; // hole/tool diameter, in mm
};
// ---------------------------------------------------------------------------
// Aperture-macro expression evaluator: numbers, $n variables and the operators
// + - x X / (x = multiply per the Gerber macro spec). KiCad only ever emits
// simple forms like "$1+$1", but the full grammar is cheap to support.
// ---------------------------------------------------------------------------
bool evalMacroExpr(const std::string& expr, const std::vector<double>& vars, double& result) {
size_t i = 0;
const size_t n = expr.size();
bool ok = true;
auto parsePrimary = [&]() -> double {
while (i < n && std::isspace(static_cast<unsigned char>(expr[i]))) i++;
bool neg = false;
while (i < n && (expr[i] == '+' || expr[i] == '-')) {
if (expr[i] == '-') neg = !neg;
i++;
}
while (i < n && std::isspace(static_cast<unsigned char>(expr[i]))) i++;
double v = 0.0;
if (i < n && expr[i] == '$') {
i++;
size_t start = i;
while (i < n && std::isdigit(static_cast<unsigned char>(expr[i]))) i++;
if (start == i) { ok = false; return 0.0; }
int idx = std::atoi(expr.substr(start, i - start).c_str());
// Per spec, undefined variables evaluate to 0.
v = (idx >= 1 && idx <= static_cast<int>(vars.size())) ? vars[idx - 1] : 0.0;
} else {
size_t start = i;
while (i < n && (std::isdigit(static_cast<unsigned char>(expr[i])) || expr[i] == '.')) i++;
if (start == i) { ok = false; return 0.0; }
v = std::atof(expr.substr(start, i - start).c_str());
}
return neg ? -v : v;
};
double total = 0.0;
char addop = '+';
double term = parsePrimary();
while (ok) {
while (i < n && std::isspace(static_cast<unsigned char>(expr[i]))) i++;
if (i >= n) break;
char op = expr[i];
if (op == 'x' || op == 'X') {
i++;
term *= parsePrimary();
} else if (op == '/') {
i++;
double d = parsePrimary();
if (d == 0.0) { ok = false; break; }
term /= d;
} else if (op == '+' || op == '-') {
total += (addop == '+') ? term : -term;
addop = op;
i++;
term = parsePrimary();
} else {
ok = false;
break;
}
}
if (!ok) return false;
total += (addop == '+') ? term : -term;
result = total;
return true;
}
// ---------------------------------------------------------------------------
// Outline geometry helpers (all in mm). Curves are approximated by chords kept
// within ~10 um of the true arc, well below the 25.4 um resolution of the
// 2.3-inch output format.
// ---------------------------------------------------------------------------
int arcSegments(double radiusMM, double sweepDeg) {
const double tol = 0.010;
double sweepRad = std::fabs(sweepDeg) * PI / 180.0;
if (radiusMM <= tol || sweepRad <= 1e-6) return 1;
double maxStep = 2.0 * std::acos(std::max(-1.0, 1.0 - tol / radiusMM));
if (maxStep < 1e-3) maxStep = 1e-3;
int segs = static_cast<int>(std::ceil(sweepRad / maxStep));
if (segs < 2) segs = 2;
if (segs > 90) segs = 90;
return segs;
}
void appendArc(std::vector<Pt>& out, const Pt& center, double r, double a0Deg, double a1Deg) {
double sweep = a1Deg - a0Deg;
int segs = arcSegments(r, sweep);
for (int k = 0; k <= segs; ++k) {
double a = (a0Deg + sweep * k / segs) * PI / 180.0;
Pt p = { center.x + r * std::cos(a), center.y + r * std::sin(a) };
out.push_back(p);
}
}
std::vector<Pt> circleOutline(const Pt& c, double r) {
std::vector<Pt> pts;
int segs = std::max(12, arcSegments(r, 360.0));
for (int k = 0; k < segs; ++k) {
double a = 2.0 * PI * k / segs;
Pt p = { c.x + r * std::cos(a), c.y + r * std::sin(a) };
pts.push_back(p);
}
return pts;
}
std::vector<Pt> centeredRect(const Pt& c, double w, double h) {
double hw = w / 2.0;
double hh = h / 2.0;
std::vector<Pt> pts;
pts.push_back(Pt{ c.x - hw, c.y - hh });
pts.push_back(Pt{ c.x + hw, c.y - hh });
pts.push_back(Pt{ c.x + hw, c.y + hh });
pts.push_back(Pt{ c.x - hw, c.y + hh });
return pts;
}
// Rectangle swept by a thick segment (macro primitive 20: square line ends).
bool thickSegmentRect(const Pt& a, const Pt& b, double width, std::vector<Pt>& out) {
double dx = b.x - a.x;
double dy = b.y - a.y;
double len = std::sqrt(dx * dx + dy * dy);
if (len < 1e-9 || width <= 0.0) return false;
double nx = -dy / len * width / 2.0;
double ny = dx / len * width / 2.0;
out.clear();
out.push_back(Pt{ a.x + nx, a.y + ny });
out.push_back(Pt{ b.x + nx, b.y + ny });
out.push_back(Pt{ b.x - nx, b.y - ny });
out.push_back(Pt{ a.x - nx, a.y - ny });
return true;
}
std::vector<Pt> regularPolygon(const Pt& c, double outerDiameter, int nVertices, double startDeg) {
std::vector<Pt> pts;
double r = outerDiameter / 2.0;
for (int k = 0; k < nVertices; ++k) {
double a = (startDeg + 360.0 * k / nVertices) * PI / 180.0;
pts.push_back(Pt{ c.x + r * std::cos(a), c.y + r * std::sin(a) });
}
return pts;
}
// Stadium/capsule: segment a-b with round caps of diameter width (KiCad
// "HorizOval" macro, i.e. a rotated oval pad).
std::vector<Pt> capsuleOutline(const Pt& a, const Pt& b, double width) {
double r = width / 2.0;
if (std::sqrt((b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y)) < 1e-9) {
return circleOutline(a, r);
}
double ang = std::atan2(b.y - a.y, b.x - a.x) * 180.0 / PI;
std::vector<Pt> pts;
appendArc(pts, b, r, ang - 90.0, ang + 90.0);
appendArc(pts, a, r, ang + 90.0, ang + 270.0);
return pts;
}
// Convex polygon (corners in order) grown by radius r with rounded corners.
// Fed with the 4 body corners of a KiCad RoundRect this reproduces the pad
// outline exactly.
std::vector<Pt> roundedPolygonOutline(std::vector<Pt> corners, double r) {
size_t n = corners.size();
if (n < 3) return corners;
// Force counter-clockwise winding so edge normals point outwards.
double area2 = 0.0;
for (size_t i = 0; i < n; ++i) {
const Pt& p = corners[i];
const Pt& q = corners[(i + 1) % n];
area2 += p.x * q.y - q.x * p.y;
}
if (area2 < 0.0) std::reverse(corners.begin(), corners.end());
if (r <= 0.0) return corners;
// Outward normal angle of the edge from->to (CCW polygon).
auto normalAngleDeg = [](const Pt& from, const Pt& to) {
return std::atan2(-(to.x - from.x), to.y - from.y) * 180.0 / PI;
};
std::vector<Pt> pts;
for (size_t i = 0; i < n; ++i) {
const Pt& prev = corners[(i + n - 1) % n];
const Pt& cur = corners[i];
const Pt& next = corners[(i + 1) % n];
double a0 = normalAngleDeg(prev, cur);
double a1 = normalAngleDeg(cur, next);
while (a1 < a0 - 1e-9) a1 += 360.0;
if (a1 - a0 < 0.5) {
pts.push_back(Pt{ cur.x + r * std::cos(a0 * PI / 180.0),
cur.y + r * std::sin(a0 * PI / 180.0) });
} else {
appendArc(pts, cur, r, a0, a1);
}
}
return pts;
}
// ---------------------------------------------------------------------------
// Macro rendering: KiCad's known macros (RoundRect, HorizOval) get an exact
// single-outline path; everything else (RotRect, Outline4P..8P, FreePoly*,
// unknown macros) is rendered generically primitive-by-primitive. Overlapping
// dark contours are legal in Gerber and merge into the copper union.
// ---------------------------------------------------------------------------
bool renderKnownKicadMacro(const std::string& name, const std::vector<double>& p, double u,
std::vector<std::vector<Pt>>& contours) {
if (name == "RoundRect" && p.size() >= 9) {
// p: rounding radius, 4 body corners (pre-rotated by KiCad), [rotation]
double r = p[0] * u;
std::vector<Pt> corners;
for (int k = 0; k < 4; ++k) {
corners.push_back(Pt{ p[1 + 2 * k] * u, p[2 + 2 * k] * u });
}
double rot = p.size() >= 10 ? p[9] : 0.0;
if (rot != 0.0) {
for (size_t k = 0; k < corners.size(); ++k) corners[k] = rotateDeg(corners[k], rot);
}
contours.push_back(roundedPolygonOutline(corners, r));
return true;
}
if (name == "HorizOval" && p.size() >= 5) {
// p: width, first cap center (x,y), second cap center (x,y), [rotation]
double w = p[0] * u;
Pt a = { p[1] * u, p[2] * u };
Pt b = { p[3] * u, p[4] * u };
double rot = p.size() >= 6 ? p[5] : 0.0;
if (rot != 0.0) {
a = rotateDeg(a, rot);
b = rotateDeg(b, rot);
}
contours.push_back(capsuleOutline(a, b, w));
return true;
}
return false;
}
void renderMacroContours(const MacroDef& def,
const std::vector<double>& rawParams,
double u,
const std::string& apLabel,
WarnSink& warn,
std::vector<std::vector<Pt>>& contours) {
std::vector<double> vars = rawParams;
for (size_t pi = 0; pi < def.primitives.size(); ++pi) {
const std::string& prim = def.primitives[pi];
// Variable assignment block: $n=<expr>
if (!prim.empty() && prim[0] == '$') {
size_t eq = prim.find('=');
if (eq != std::string::npos) {
int idx = std::atoi(prim.substr(1, eq - 1).c_str());
double val = 0.0;
if (idx >= 1 && evalMacroExpr(prim.substr(eq + 1), vars, val)) {
if (static_cast<int>(vars.size()) < idx) vars.resize(idx, 0.0);
vars[idx - 1] = val;
}
}
continue;
}
std::vector<double> v;
bool ok = true;
{
std::stringstream ss(prim);
std::string field;
while (std::getline(ss, field, ',')) {
double val = 0.0;
if (!evalMacroExpr(trimWhitespace(field), vars, val)) { ok = false; break; }
v.push_back(val);
}
}
if (!ok || v.empty()) {
warn.once("badprim:" + def.name,
"Aperture " + apLabel + ": unparsable primitive in macro '" + def.name + "' skipped.");
continue;
}
int code = static_cast<int>(std::lround(v[0]));
if (code == 0) continue; // comment primitive
bool exposureOff = (v.size() >= 2 && v[1] == 0.0);
if (exposureOff) {
warn.once("exp0:" + def.name,
"Aperture " + apLabel + ": clear (exposure 0) primitive skipped - pad may come out slightly larger than designed.");
continue;
}
switch (code) {
case 1: { // circle: 1,exposure,diameter,cx,cy[,rot]
if (v.size() < 5) break;
double d = v[2] * u;
Pt c = rotateDeg(Pt{ v[3] * u, v[4] * u }, v.size() >= 6 ? v[5] : 0.0);
if (d > 0.0) contours.push_back(circleOutline(c, d / 2.0));
break;
}
case 2:
case 20: { // vector line: exposure,width,x1,y1,x2,y2[,rot]
if (v.size() < 7) break;
Pt a = { v[3] * u, v[4] * u };
Pt b = { v[5] * u, v[6] * u };
double rot = v.size() >= 8 ? v[7] : 0.0;
std::vector<Pt> rect;
if (thickSegmentRect(a, b, v[2] * u, rect)) {
for (size_t k = 0; k < rect.size(); ++k) rect[k] = rotateDeg(rect[k], rot);
contours.push_back(rect);
}
break;
}
case 21: { // centered rectangle: exposure,w,h,cx,cy[,rot]
if (v.size() < 6) break;
double w = v[2] * u;
double h = v[3] * u;
if (w > 0.0 && h > 0.0) {
std::vector<Pt> rect = centeredRect(Pt{ v[4] * u, v[5] * u }, w, h);
double rot = v.size() >= 7 ? v[6] : 0.0;
for (size_t k = 0; k < rect.size(); ++k) rect[k] = rotateDeg(rect[k], rot);
contours.push_back(rect);
}
break;
}
case 4: { // outline polygon: exposure,#vertices,x0,y0,...,[rot]
if (v.size() < 9) break; // at least a triangle
double rot = 0.0;
size_t coordFields = v.size() - 3;
if (coordFields % 2 == 1) { rot = v.back(); coordFields -= 1; }
size_t pairs = coordFields / 2;
std::vector<Pt> poly;
for (size_t k = 0; k < pairs; ++k) {
poly.push_back(rotateDeg(Pt{ v[3 + 2 * k] * u, v[4 + 2 * k] * u }, rot));
}
// The spec repeats the first vertex as closing point; drop it.
while (poly.size() >= 2 &&
std::fabs(poly.front().x - poly.back().x) < 1e-9 &&
std::fabs(poly.front().y - poly.back().y) < 1e-9) {
poly.pop_back();
}
if (poly.size() >= 3) contours.push_back(poly);
break;
}
case 5: { // regular polygon: exposure,#vertices,cx,cy,diameter[,rot]
if (v.size() < 6) break;
int nv = static_cast<int>(std::lround(v[2]));
if (nv >= 3 && nv <= 12) {
std::vector<Pt> poly = regularPolygon(Pt{ v[3] * u, v[4] * u }, v[5] * u, nv, 0.0);
double rot = v.size() >= 7 ? v[6] : 0.0;
for (size_t k = 0; k < poly.size(); ++k) poly[k] = rotateDeg(poly[k], rot);
contours.push_back(poly);
}
break;
}
case 6:
case 7:
warn.once("prim67:" + def.name,
"Aperture " + apLabel + ": moire/thermal primitive not supported, skipped.");
break;
default:
warn.once("primunk:" + def.name,
"Aperture " + apLabel + ": unknown macro primitive code " + std::to_string(code) + " skipped.");
break;
}
}
}
// Builds (once) the flash outline cache for a region-type wheel entry.
bool buildFlashContours(GlobalAp& ap, int globalCode, WarnSink& warn) {
if (ap.contoursBuilt) return !ap.contours.empty();
ap.contoursBuilt = true;
std::string label = "D" + std::to_string(globalCode) +
(ap.type == ApType::Macro ? " (" + ap.macroName + ")" : "");
if (ap.type == ApType::Poly) {
// Standard P aperture: outer diameter, #vertices, [rotation], [hole]
if (ap.params.size() >= 2) {
int nv = static_cast<int>(std::lround(ap.params[1]));
double rot = ap.params.size() >= 3 ? ap.params[2] : 0.0;
if (nv >= 3 && nv <= 12 && ap.params[0] > 0.0) {
ap.contours.push_back(regularPolygon(Pt{ 0.0, 0.0 }, ap.params[0] * ap.unitToMM, nv, rot));
}
}
} else if (ap.type == ApType::Macro) {
if (!renderKnownKicadMacro(ap.macroName, ap.params, ap.unitToMM, ap.contours)) {
if (!ap.hasMacroDef) {
warn.once("nomacro:" + ap.macroName,
"Macro '" + ap.macroName + "' used by " + label +
" has no %AM definition - its pads are missing from the output!");
} else {
renderMacroContours(ap.macroDef, ap.params, ap.unitToMM, label, warn, ap.contours);
}
}
}
if (ap.contours.empty()) {
warn.once("emptyflash:" + std::to_string(globalCode),
"Aperture " + label + ": no geometry could be generated - its flashes are missing from the output!");
}
return !ap.contours.empty();
}
// ---------------------------------------------------------------------------
// Gerber input parsing
// ---------------------------------------------------------------------------
bool parseAddBlock(const std::string& block, int& code, std::string& shapeName,
std::vector<double>& params) {
static const std::regex addRe(R"(^%ADD(\d+)([A-Za-z_.$][A-Za-z0-9_.$]*)(?:,([^*%]*))?\*%$)");
std::smatch m;
if (!std::regex_match(block, m, addRe)) return false;
code = std::stoi(m[1]);
shapeName = m[2];
params.clear();
if (m[3].matched) {
std::stringstream ss(m[3].str());
std::string tok;
while (std::getline(ss, tok, 'X')) {
tok = trimWhitespace(tok);
if (!tok.empty()) params.push_back(std::atof(tok.c_str()));
}
}
return true;
}
void parseMacroBlock(const std::string& block, std::map<std::string, MacroDef>& macros) {
// block: %AM<name>*<primitive>*<primitive>*...*%
std::string body = block;
if (!body.empty() && body.back() == '%') body.pop_back();
if (body.compare(0, 3, "%AM") == 0) body = body.substr(3);
std::vector<std::string> blocks;
{
std::stringstream ss(body);
std::string b;
while (std::getline(ss, b, '*')) blocks.push_back(trimWhitespace(b));
}
if (blocks.empty() || blocks[0].empty()) return;
MacroDef def;
def.name = blocks[0];
for (size_t k = 1; k < blocks.size(); ++k) {
const std::string& b = blocks[k];
if (b.empty()) continue;
if (b[0] == '0') continue; // comment primitive
def.primitives.push_back(b);
}
macros[def.name] = def;
}
bool parseGerberFile(const std::string& path, ParsedGerber& pg, WarnSink& warn, std::string& err) {
std::ifstream infile(path);
if (!infile.is_open()) {
err = "Cannot open input file: " + fileNameOf(path);
return false;
}
pg.fileName = fileNameOf(path);
bool seenFS = false;
bool seenMO = false;
std::string pctBuffer; // accumulates multi-line %...% blocks (%AM bodies)
std::string line;
while (std::getline(infile, line)) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
std::string trimmed = trimWhitespace(line);
if (trimmed.empty()) {
continue;
}
// Extended (%...%) commands, possibly spanning several lines (%AM).
if (!pctBuffer.empty() || trimmed[0] == '%') {
pctBuffer += trimmed;
if (trimmed.back() != '%') {
continue; // block not closed yet
}
std::string block = pctBuffer;
pctBuffer.clear();
if (block.compare(0, 3, "%AM") == 0) {
parseMacroBlock(block, pg.macros);
} else if (block.compare(0, 3, "%FS") == 0) {
static const std::regex fsRe(R"(^%FS([A-Z]?)([A-Z]?)X(\d)(\d)Y(\d)(\d)\*%$)");
std::smatch m;
if (std::regex_match(block, m, fsRe)) {
seenFS = true;
if (m[1].str() == "T") {
err = pg.fileName + ": trailing zero suppression (%FST...) is not supported.";
return false;
}
if (m[2].str() == "I") {
err = pg.fileName + ": incremental coordinates (%FS..I..) are not supported.";
return false;
}
pg.fracDigits = m[4].str()[0] - '0';
if (m[6].str()[0] - '0' != pg.fracDigits) {
warn.once("fsxy:" + pg.fileName,
pg.fileName + ": X and Y use different decimal counts - using the X format.");
}
} else {
warn.once("fsbad:" + pg.fileName, pg.fileName + ": unrecognized %FS line: " + block);
}
} else if (block.compare(0, 3, "%MO") == 0) {
seenMO = true;
if (block.find("IN") != std::string::npos) {
pg.unitToMM = 25.4;
} else if (block.find("MM") != std::string::npos) {
pg.unitToMM = 1.0;
} else {
warn.once("mobad:" + pg.fileName,
pg.fileName + ": unrecognized %MO unit line, assuming millimeters.");
}
} else if (block.compare(0, 4, "%LPC") == 0) {
warn.once("lpc:" + pg.fileName,
pg.fileName + ": clear polarity (%LPC) is not supported by the old format - negative objects were ignored, check the output!");
} else if (block.compare(0, 3, "%SR") == 0) {
if (block != "%SR*%") {
warn.once("sr:" + pg.fileName,
pg.fileName + ": step & repeat (%SR) is not supported - the block was NOT replicated!");
}
} else if (block.compare(0, 4, "%ADD") == 0) {
int code = 0;
std::string shapeName;
std::vector<double> params;
if (parseAddBlock(block, code, shapeName, params)) {
Aperture ap;
ap.params = params;
if (shapeName == "C") {
ap.type = ApType::Circle;
} else if (shapeName == "R") {
ap.type = ApType::Rect;
} else if (shapeName == "O") {
ap.type = ApType::Obround;
} else if (shapeName == "P") {
ap.type = ApType::Poly;
ap.flashAsRegion = true;
} else {
ap.type = ApType::Macro;
ap.macroName = shapeName;
ap.flashAsRegion = true;
}
pg.apertures[code] = ap;
} else {
warn.once("addbad:" + block,
pg.fileName + ": unparsable aperture definition ignored: " + block);
}
}
// All other % commands (%TF/%TA/%TO/%TD/%IP/%LN/%LPD...) are dropped.
continue;
}
if (trimmed.compare(0, 3, "G04") == 0) {
continue; // comment
}
pg.commands.push_back(trimmed);
}
infile.close();
if (!pctBuffer.empty()) {
warn.once("pctopen:" + pg.fileName,
pg.fileName + ": unterminated %...% block at end of file was ignored.");
}
if (!seenFS) {
warn.once("nofs:" + pg.fileName,
pg.fileName + ": no %FSLA coordinate format found - assuming KiCad default 4.6.");
}
if (!seenMO) {
warn.once("nomo:" + pg.fileName,
pg.fileName + ": no %MO unit found - assuming millimeters.");
}
return true;
}
// Assigns one global D-code (from 10 up) to every aperture of every file, in
// file order. No dedup: predictable mapping, and CircuitCAM does not mind a
// couple of same-sized entries.
void buildGlobalTable(const std::vector<ParsedGerber>& gerbers,
std::vector<GlobalAp>& table,
std::vector<std::map<int, int>>& remaps) {
int next = 10;
for (size_t f = 0; f < gerbers.size(); ++f) {
std::map<int, int> remap;
for (std::map<int, Aperture>::const_iterator it = gerbers[f].apertures.begin();
it != gerbers[f].apertures.end(); ++it) {
const Aperture& ap = it->second;
GlobalAp g;
g.type = ap.type;
g.macroName = ap.macroName;
g.params = ap.params;
g.unitToMM = gerbers[f].unitToMM;
g.flashAsRegion = ap.flashAsRegion;
if (ap.type == ApType::Macro) {
std::map<std::string, MacroDef>::const_iterator mit = gerbers[f].macros.find(ap.macroName);
if (mit != gerbers[f].macros.end()) {
g.macroDef = mit->second;
g.hasMacroDef = true;
}
}
remap[it->first] = next;
table.push_back(g);
next++;
}
remaps.push_back(remap);
}
}
// ---------------------------------------------------------------------------
// Output helpers
// ---------------------------------------------------------------------------
// Convert every X/Y/I/J number on the line from raw file units to thousandths
// of an inch (2.3 leading-suppressed). I/J arc-centre offsets share the same
// coordinate format, so they must be converted too or every arc breaks.
std::string convertCoordinates(const std::string& line, double divisor, double unitToMM) {
try {
std::string result;
std::regex coord_regex(R"(([XYIJ])([-+]?\d+))");
std::sregex_iterator iter(line.begin(), line.end(), coord_regex);
std::sregex_iterator end;
size_t last_pos = 0;
for (; iter != end; ++iter) {
try {
std::smatch match = *iter;
result += line.substr(last_pos, match.position() - last_pos);
char axis = match.str(1)[0];
long long coord = std::stoll(match.str(2));
double mm = coord / divisor * unitToMM;
double inch = mm / 25.4;
long long formatted = static_cast<long long>(std::round(inch * 1000));
result += axis + std::to_string(formatted);
last_pos = match.position() + match.length();
} catch (...) {
continue;
}
}
result += line.substr(last_pos);
return result;
} catch (...) {
return line;
}
}
long long mmToOut(double mm) {
return static_cast<long long>(std::round(mm / 25.4 * 1000.0));
}
// The Mode keyword is what CircuitCAM uses to accept/reject each wheel entry.
// Its aperture-translation templates (Ape_Templates\TutorApe.TXT, CCAM20Ape.txt)
// define exactly which Mode+Shape combinations are legal:
// Circle / Square : Draw | Flash | FlashDraw (all valid)
// Rectangle : ONLY "Flash" (NR entry, literal keyword required)
// Finger (obround): ONLY "Flash" (NO entry, literal keyword required)
// A line matching no template entry is SILENTLY IGNORED, so anything else here
// makes pads vanish. Macro/polygon apertures get a harmless placeholder circle:
// their real geometry is emitted as G36/G37 filled outlines in the .gbr, the
// wheel entry only exists so the D-code select lines resolve.
std::string formatWheelLine(int d_code, const GlobalAp& ap) {
std::string shapeName;
std::string mode;
int x_size = 0;
int y_size = 0;
switch (ap.type) {
case ApType::Circle:
shapeName = "Circle";
mode = "FlashDraw";
x_size = static_cast<int>(std::round((ap.params.empty() ? 0.0 : ap.params[0]) * ap.unitToMM * 100));
break;
case ApType::Rect:
case ApType::Obround:
shapeName = (ap.type == ApType::Rect) ? "Rectangle" : "Finger";
mode = "Flash";
x_size = static_cast<int>(std::round((ap.params.empty() ? 0.0 : ap.params[0]) * ap.unitToMM * 100));
y_size = (ap.params.size() >= 2)
? static_cast<int>(std::round(ap.params[1] * ap.unitToMM * 100))
: x_size;
break;
default: // Poly / Macro placeholder
shapeName = "Circle";
mode = "FlashDraw";
x_size = 20; // 0.2 mm, same as the smallest entry in the reference wheels
break;
}
std::string line = "D" + std::to_string(d_code) + " " + mode + " " + shapeName;
if (shapeName == "Circle") {
line += " " + std::to_string(x_size);
} else {
line += " " + std::to_string(x_size) + " " + std::to_string(y_size);
}
return line;
}
// Text mode (not binary): on Windows this emits CRLF line endings, matching
// the reference wheels CircuitCAM ships with. The old DOS-era parser can
// mishandle LF-only files.
bool writeWheelFile(const std::string& path, const std::string& title,
const std::vector<GlobalAp>& table, std::string& err) {
std::ofstream whl(path, std::ios::out);
if (!whl.is_open()) {
err = "Cannot write the .whl output file.";
return false;
}
whl << "Aperture Table for " << title << " sample files\n";
whl << "Format Unit: Inch\n";
whl << "m.n Code: 2.3\n";
whl << "Mode: absolute\n";
whl << "Zeros: leading suppressed\n\n";
whl << "Aperture unit: 1/100 mm\n";
whl << "D_Code Mode Shape X-size\tYsize\n";
for (size_t i = 0; i < table.size(); ++i) {
whl << formatWheelLine(static_cast<int>(10 + i), table[i]) << "\n";
}
whl.close();
return true;
}
// Emits one closed contour as a filled G36/G37 region, offset by the flash
// position (mm). Returns false if the contour degenerates after rounding.
bool emitRegion(std::ofstream& out, const std::vector<Pt>& poly, double oxMM, double oyMM) {
std::vector<std::pair<long long, long long> > ipts;
for (size_t k = 0; k < poly.size(); ++k) {
std::pair<long long, long long> p(mmToOut(poly[k].x + oxMM), mmToOut(poly[k].y + oyMM));
if (ipts.empty() || !(ipts.back() == p)) ipts.push_back(p);
}
while (ipts.size() > 1 && ipts.back() == ipts.front()) ipts.pop_back();
if (ipts.size() < 3) return false;
out << "G36*\n";
out << "G01*\n";
out << "X" << ipts[0].first << "Y" << ipts[0].second << "D02*\n";
for (size_t k = 1; k < ipts.size(); ++k) {
out << "X" << ipts[k].first << "Y" << ipts[k].second << "D01*\n";
}
out << "X" << ipts[0].first << "Y" << ipts[0].second << "D01*\n";
out << "G37*\n";
return true;
}
// Streams one parsed Gerber to the old format: D-codes remapped to the global
// numbering, coordinates converted, region-type flashes replaced by outlines.
bool emitConvertedGerber(const ParsedGerber& pg,
const std::map<int, int>& remap,
std::vector<GlobalAp>& table,
const std::string& outPath,
WarnSink& warn,
ConversionReport& rep,
std::string& err) {
std::ofstream out(outPath, std::ios::out);
if (!out.is_open()) {
err = "Cannot write output file: " + fileNameOf(outPath);
return false;
}
const double divisor = std::pow(10.0, pg.fracDigits);
const double rawToMM = pg.unitToMM / divisor;
static const std::regex selRe(R"(^D(\d+)\*$)");
static const std::regex coordRe(
R"(^(?:G0?([123]))?(?:X([-+]?\d+))?(?:Y([-+]?\d+))?(?:I([-+]?\d+))?(?:J([-+]?\d+))?(?:D0?([123]))?\*$)");
GlobalAp* curAp = NULL;
int curGlobal = -1;
long long modalX = 0, modalY = 0;
bool haveX = false, haveY = false;
int lastD = 2;
out << "*\n";
for (size_t ci = 0; ci < pg.commands.size(); ++ci) {
const std::string& cmd = pg.commands[ci];
std::smatch m;
// Aperture select (D-codes >= 10; D01/D02/D03 are operations).
if (std::regex_match(cmd, m, selRe)) {
int code = std::stoi(m[1]);
if (code >= 10) {
std::map<int, int>::const_iterator rit = remap.find(code);
if (rit != remap.end()) {
curGlobal = rit->second;
curAp = &table[curGlobal - 10];
} else {
curGlobal = code;
curAp = NULL;
warn.once("undef:" + pg.fileName + ":" + std::to_string(code),
pg.fileName + ": D" + std::to_string(code) +
" is selected but never defined - its objects may be wrong.");
}
out << "D" << curGlobal << "*\n";
continue;
}
}
if (cmd.find_first_of("XYIJD") != std::string::npos && std::regex_match(cmd, m, coordRe)) {
if (m[2].matched) { modalX = std::stoll(m[2]); haveX = true; }
if (m[3].matched) { modalY = std::stoll(m[3]); haveY = true; }
int d = m[6].matched ? std::stoi(m[6]) : lastD;
lastD = d;
if (d == 3 && curAp != NULL && curAp->flashAsRegion) {
if (!haveX || !haveY) {
warn.once("flashpos:" + pg.fileName,
pg.fileName + ": flash without a known X/Y position was skipped.");
continue;
}
if (buildFlashContours(*curAp, curGlobal, warn)) {
double fx = modalX * rawToMM;
double fy = modalY * rawToMM;
bool any = false;
for (size_t k = 0; k < curAp->contours.size(); ++k) {
if (emitRegion(out, curAp->contours[k], fx, fy)) any = true;
}
if (any) rep.flashesAsRegions++;
}
continue;
}
out << convertCoordinates(cmd, divisor, pg.unitToMM) << "\n";
continue;
}
// Everything else passes through (G01/G02/G03/G36/G37/G75/M02...).
if (cmd.find_first_of("XYIJ") != std::string::npos) {
out << convertCoordinates(cmd, divisor, pg.unitToMM) << "\n";
} else {
out << cmd << "\n";
}
}
out.close();
return true;
}
// ---------------------------------------------------------------------------
// Excellon drill processing: renumber tools into one global sequence (unique
// across PTH/NPTH), extract oval/slot holes (G85 or routed G00/M15..M16) for
// the separate milling gerber, pass everything else through untouched.
// ---------------------------------------------------------------------------
bool processDrillFile(const std::string& path,
const std::string& displayName,
int& nextTool,
std::vector<Slot>& slots,
std::vector<std::string>& outLines,
int& toolsDefined,
WarnSink& warn,
std::string& err) {
std::ifstream in(path);
if (!in.is_open()) {
err = "Cannot open drill file: " + displayName;
return false;
}
static const std::regex toolDefRe(R"(^T(\d+)C([0-9.]+)\s*$)");
static const std::regex toolSelRe(R"(^T(\d+)\s*$)");
static const std::regex g85Re(R"(^X([-+]?[0-9.]+)Y([-+]?[0-9.]+)G85X([-+]?[0-9.]+)Y([-+]?[0-9.]+)$)");
static const std::regex g00Re(R"(^G00X([-+]?[0-9.]+)Y([-+]?[0-9.]+)$)");
static const std::regex g01Re(R"(^G01X([-+]?[0-9.]+)Y([-+]?[0-9.]+)$)");
std::map<int, int> toolMap; // local T -> global T
std::map<int, double> toolDiamMM; // local T -> diameter in mm
double unitScale = 1.0; // METRIC -> 1, INCH -> 25.4
bool decimalWarned = false;
int curLocalTool = -1;
// Routed-slot state machine (G00 X Y / M15 / G01 X Y ... / M16).
bool routePending = false;
bool routeActive = false;
std::vector<Pt> routePts; // in file units
std::vector<std::string> routeBuffer; // original lines, flushed on abort
// KiCad's default drill format is decimal (numbers carry a dot). Without a
// dot we assume the usual 3.3 metric / 2.4 inch Excellon formats.
auto parseNum = [&](const std::string& s) -> double {
if (s.find('.') != std::string::npos) return std::atof(s.c_str());
if (!decimalWarned) {
warn.once("drlfmt:" + displayName,
displayName + ": non-decimal drill coordinates - assuming 3.3 (metric) / 2.4 (inch) format for slot extraction.");
decimalWarned = true;
}
double v = std::atof(s.c_str());
return (unitScale == 1.0) ? v / 1000.0 : v / 10000.0;
};
auto abortRoute = [&]() {
for (size_t k = 0; k < routeBuffer.size(); ++k) outLines.push_back(routeBuffer[k]);
routeBuffer.clear();
routePts.clear();
routePending = routeActive = false;
};
std::string line;