forked from swannman/pdf2gerb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdf2gerb.pl
executable file
·2016 lines (1804 loc) · 118 KB
/
pdf2gerb.pl
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
#!/usr/bin/perl
#
# pdf2gerb 1.6
#
# (c) 2010 Matthew M. Swann, [email protected] - initial versions
# (c) 2012 [email protected] (1.5 + 1.6) - I offer up these enhancements to our Grand Designer, and hoping to make it easier for other hobbyists to create PCBs.
#
# Recent rev history:
# Version Date Who What
# 1.4 7/2011 MS last public version from Matt
# 1.5a 4/7/12 DJ add support for PDF 1.4 compression (flate decode)
# 1.5b 4/9/12 DJ handle scale transform (was giving incorrect dimensions), warn about file too big and use consts (seems safer)
# 1.5c 4/10/12 DJ fix filled circles, change drill fmt to 2.4 (drill coords were interpreted as 10x)
# 1.5d 4/11/12 DJ set origin to lower left corner of PCB, draw large circles on silk screen using line segments
# 1.5e 4/12/12 DJ use rectangular apertures for square/rectangular pads, accept multiple files (top + bottom + silk screen) and concatenate to look like 1 file with multiple layers, update usage message
# 1.5f 4/14/12 DJ fix "." and \s in regex, added G04 for easier debug, add inverted/filled areas (layer polarity), placeholders for top + bottom solder masks
# 1.5g 4/20/12 DJ restructured drawing loop to handle multiple stoke vs. fill commands (to support thermal pads, ground planes, solder masks), restructured main line code, only emit tool commands when needed, turned on strict + warnings, explicitly declare locals/globals ("my", "our")
# 1.5h 4/24/12 DJ map scaled aperture and trace sizes to standard values, consolidate hole lists to minimize drill tool swapping, change aperture lists to use hash (faster lookups), undo larger holes if smaller hole found in same location
# 1.5i 4/25/12 DJ generate solder masks (invert + enlarge all pads, no holes)
# 1.5j 4/28/12 DJ added polygon fill (needed for ground plane and no-fill areas), allow metric units for non-US people
# 1.5k 5/1/12 DJ added panelization; fixed polygon fill (nudge edges for more accurate edges); generate separate outline layer
# 1.6 5/5/12 DJ misc fixes, released for testing
# 1.6a 5/6/12 DJ trim panel overhangs even with 1 x 1 (by default), added some pad/hole sizes, allow rotated PDFs (landscape prints), allow x + y pad around panelization
# 1.6b 5/21/12 DJ pre-scan multiple layers for PCB outline, don't use clip rect for outline, generate drill file on any layer (for Matt's test file)
# 1.6c 1/7/13 DJ initialize visibility to Tristate value so both holes + pads will be recognized if no fill/stroke color set in PDF, treat singleton layer as copper, not silk
# 1.6d 1/30/13 DJ insert dummy G54D10 command at start, in case there are no traces (avoids ViewPlot D00 message for outline file)
# 1.6e 2/1/13 DJ added DRILL_FMT to allow 2.3 or 2.4 drill format, show version# in output files
# 1.6f 3/21/13 DJ made \n after "stream" optional (newer PDFCreator omits it?); default WANT_STREAMS to FALSE; extract max 100 streams (for safety); use REDUCE_TOLERANCE const for adjustable tolerance on reduce logic
# 1.6g 3/28/13 GDM/DJ implement gray space drawing attr; change "\1" to "$1" to prevent perl warning; substitute circles for clip rects (SUBST_CIRCLE_CLIPRECT)
# 1.6h 4/11/13 DJ allow \r\n between "<<" and "/FlateDecode"; make \n optional between commands; join commands that are split across lines; added more debug; force input to Unicode
# 1.6i 7/14/14 DJ avoid /0 error for nudge line segment or polygon edge, avoid infinite loops for outline/fill unknown shapes, fix handling of 2 adjacent polygon edges parallel (shouldn't happen, though)
# 1.6j 9/30/15 DJ fix an additional subscript error; perl short-circuit IF doesn't seem to be working
# 1.6k 1/2/16 DJ undo attempt to compensate for Unicode; broke parser logic
# 1.6L 1/24/16 DJ handle "re W" on same line, draw/fill bezier curves on silk screen (fill requires additional module), allow stand-alone line fill, add placeholder for curve offset
#
# TODO maybe:
# -elliptical pads? (draw short line seg using round aperture)
# -use G02/03/75 circular commands instead of drawing circles with line segments?
# -use hollow apertures? (pads are currently solid circles and hole is in center; this seems okay)
# -make it run faster? (not too bad now)
# -add command-line parameters instead of editing config constants?
# -exclude selected layers?
#
# Notes/Current limitations:
# - PCB outline is assumed to be rectangular
# - Holes in PDFs must be white circles; copper areas any color except white
# - Some CAD packages have origin in top left, but PDF is bottom left
# - Polygons and larger pads are filled with .001" lines; for non-rectangular ground planes, any points and intersections will be at least this wide (even if source CAD software shows them as points).
# - Polygons (ground planes) where the edges define internal "cut-out" areas will be treated as such, even if the CAD software fills them.
# - Larger pads that are filled will not have a solder mask opening (we don't want a solder mask opening on ground planes, for example).
# - Panelization will squash text or other display elements outside the PCB border to avoid interference with adjacent panels (by design).
#
# Helpful background links:
# (Gerber)
# Gerber intro: http://www.apcircuits.com/resources/information/gerber_data.html
# G-codes + D-codes: http://www.artwork.com/gerber/appl2.htm
# 274X format: http://www.artwork.com/gerber/274x/rs274x.htm
# KiCAD Gerbers: http://www.kxcad.net/visualcam/visualcam/tutorials/gerber_for_beginners.htm
# Excellon (drill file): http://www.excellon.com/manuals/program.htm
# Creating Gerbers: http://www.sparkfun.com/tutorials/109
# Gerbv (viewer): http://gerbv.gpleda.org/index.html
# Viewplot (viewer): http://www.viewplot.com
# Pdf2Gerb: http://swannman.github.com/pdf2gerb/
# (Other)
# Cubic Bezier curves for circles: http://www.tinaja.com/glib/ellipse4.pdf
# Polygon fill algorithm: http://alienryderflex.com/polygon_fill/
# Point-in-polygon algoritm: http://alienryderflex.com/polygon/
# Perl help: http://www.perlmonks.org
# PDFCreator 1.3.2 (CAREFUL: TURN OFF SPYWARE DURING INSTALL): http://sourceforge.net/projects/pdfcreator/
# Strawberry Perl (for Windows): http://www.strawberryperl.com
#
# More information about this work can be found at the following URL:
# http://swannman.github.com/pdf2gerb/
#
# This work is released under the terms and conditions set forth under
# the GNU General Public License 3.0. For more details, see the following:
# http://www.gnu.org/licenses/gpl-3.0.txt
#
###########################################################################
use strict; #trap undef vars, etc (easier debug)
use warnings; #other useful info (easier debug)
use Cwd; #gets current directory
use Compress::Zlib; #needed for PDF1.4 decompression
use File::Spec; #Path::Class; #for folder name manipulation
use Time::HiRes qw(time); #for elapsed time calculation
use List::Util qw[min max];
use Encode; #::Detect::Detector; #for detecting charset encoding
#use Math::Bezier; #http://search.cpan.org/~abw/Math-Bezier-0.01/Bezier.pm
#are fwd defs needed?
#sub inches; #ToInches;
#sub inchesX;
#sub inchesY;
#sub ToDrillInches;
#sub GetAperture;
#sub GetDrillAperture;
#sub ComputeBezier;
#sub DebugPrint;
#sub FillRect;
#sub SetPolarity;
##sub min;
##sub max;
use constant VERSION => '1.6L';
#just a little warning; set realistic expectations:
printf "Pdf2Gerb.pl %s\nThis is EXPERIMENTAL software. \nGerber files MAY CONTAIN ERRORS. Please CHECK them before fabrication!\n\n", VERSION;
#Perl constants can supposedly be optimized at compile time, so here are some:
use constant { TRUE => 1, FALSE => 0, MAYBE => 2 }; #tri-state values
use constant { MININT => - 2 ** 31 - 1, MAXINT => 2 ** 31 - 1}; #big enough for simple arithmetic purposes
use constant { K => 1024, M => 1024 * 1024 }; #used for more concise display of numbers
use constant PI => 4 * atan2(1, 1); #used for circumference calculations
use constant METRIC => FALSE; #set to TRUE for metric units (only affect final numbers in output files, not internal arithmetic)
use constant APERTURE_LIMIT => 0; #34; #generate warnings if too many apertures are used (0 to not check)
use constant DRILL_FMT => '2.4'; #'2.3'; #'2.4' is the default for PCB fab; change to '2.3' for CNC
use constant WANT_DEBUG => 0; #10; #level of debug wanted; higher == more, lower == less, 0 == none
use constant GERBER_DEBUG => 0; #level of debug to include in Gerber file; DON'T USE FOR FABRICATION
use constant WANT_STREAMS => FALSE; #TRUE; #save decompressed streams to files (for debug)
use constant WANT_ALLINPUT => FALSE; #TRUE; #save entire input stream (for debug ONLY)
DebugPrint(sprintf("DEBUG: stdout %d, gerber %d, want streams? %d, all input? %d, O/S: $^O, Perl: $]\n", WANT_DEBUG, GERBER_DEBUG, WANT_STREAMS, WANT_ALLINPUT), 1);
#DebugPrint(sprintf("max int = %d, min int = %d\n", MAXINT, MININT), 1);
#define standard trace and pad sizes to reduce scaling or PDF rendering errors:
#This avoids weird aperture settings and replaces them with more standardized values.
#(I'm not sure how photoplotters handle strange sizes).
#Fewer choices here gives more accurate mapping in the final Gerber files.
#units are in inches
use constant TOOL_SIZES => #add more as desired
(
#round or square pads (> 0) and drills (< 0):
.031, -.014, #used for vias
.041, -.020, #smallest non-filled plated hole
.051, -.025,
.056, -.029, #useful for IC pins
.070, -.033,
.075, -.040, #heavier leads
# .090, -.043, #NOTE: 600 dpi is not high enough resolution to reliably distinguish between .043" and .046", so choose 1 of the 2
.100, -.046,
.115, -.052,
.130, -.061,
.140, -.067,
.150, -.079,
.175, -.088,
.190, -.093,
.200, -.100,
.220, -.110,
.160, -.125, #useful for mounting holes
#some additional pad sizes without holes (repeat a previous hole size if you just want the pad size):
.090, -.040, #want a .090 pad option, but use dummy hole size
.065, -.040, #.035 x .065 rect pad
.035, -.040, #.035 x .065 rect pad
#traces:
.001, #too thin for real traces; use only for board outlines
.006, #minimum real trace width; mainly used for text
.008, #mainly used for mid-sized text, not traces
.010, #minimum recommended trace width for low-current signals
.012,
.015, #moderate low-voltage current
.020, #heavier trace for power, ground (even if a lighter one is adequate)
.025,
.030, #heavy-current traces; be careful with these ones!
.040,
.050,
.060,
.080,
.100,
.120,
);
#Areas larger than the values below will be filled with parallel lines:
#This cuts down on the number of aperture sizes used.
#Set to 0 to always use an aperture or drill, regardless of size.
use constant { MAX_APERTURE => max((TOOL_SIZES)) + .004, MAX_DRILL => -min((TOOL_SIZES)) + .004 }; #max aperture and drill sizes (plus a little tolerance)
DebugPrint(sprintf("using %d standard tool sizes: %s, max aper %.3f, max drill %.3f\n", scalar((TOOL_SIZES)), join(", ", (TOOL_SIZES)), MAX_APERTURE, MAX_DRILL), 1);
#NOTE: Compare the PDF to the original CAD file to check the accuracy of the PDF rendering and parsing!
#for example, the CAD software I used generated the following circles for holes:
#CAD hole size: parsed PDF diameter: error:
# .014 .016 +.002
# .020 .02267 +.00267
# .025 .026 +.001
# .029 .03167 +.00267
# .033 .036 +.003
# .040 .04267 +.00267
#This was usually ~ .002" - .003" too big compared to the hole as displayed in the CAD software.
#To compensate for PDF rendering errors (either during CAD Print function or PDF parsing logic), adjust the values below as needed.
#units are pixels; for example, a value of 2.4 at 600 dpi = .004 inch, 2 at 600 dpi = .0033"
use constant
{
HOLE_ADJUST => -2.6, #holes seemed to be slightly oversized (by .002" - .004"), so shrink them a little
RNDPAD_ADJUST => -2, #-2.4, #round pads seemed to be slightly oversized, so shrink them a little
SQRPAD_ADJUST => +.5, #square pads are sometimes too small by .00067, so bump them up a little
RECTPAD_ADJUST => 0, #rectangular pads seem to be okay; actually, i didn't test them much :(
TRACE_ADJUST => 0, #traces seemed to be okay
REDUCE_TOLERANCE => .001, #allow this much variation when reducing circles and rects
};
#Also, my CAD's Print function or the PDF print driver I used was a little off for circles, so define some additional adjustment values here:
#Values are added to X/Y coordinates; units are pixels; for example, a value of 1 at 600 dpi would be ~= .002 inch
use constant
{
CIRCLE_ADJUST_MINX => 0,
CIRCLE_ADJUST_MINY => -1, #circles were a little too high, so nudge them a little lower
CIRCLE_ADJUST_MAXX => +1, #circles were a little too far to the left, so nudge them a little to the right
CIRCLE_ADJUST_MAXY => 0,
SUBST_CIRCLE_CLIPRECT => TRUE #FALSE, #generate circle and substitute for clip rects (to compensate for the way some CAD software draws circles)
};
#allow .012 clearance around pads for solder mask:
#This value effectively adjusts pad sizes in the TOOL_SIZES list above (only for solder mask layers).
use constant SOLDER_MARGIN => +.012; #units are inches
#panelization:
#This will repeat the entire body the number of times indicated along the X or Y axes (files grow accordingly).
#Display elements that overhang PCB boundary can be squashed or left as-is (typically text or other silk screen markings).
#Set "overhangs" TRUE to allow over hangs, FALSE to truncate them.
#xpad and ypad allow margins to be added around outer edge of panelized PCB.
use constant PANELIZE => {'x' => 1, 'y' => 1, 'xpad' => 0, 'ypad' => 0, 'overhangs' => TRUE}; #number of times to repeat in X and Y directions
# Set this to 1 if you need TurboCAD support.
#$turboCAD = FALSE; #is this still needed as an option?
#PDF uses "points", each point = 1/72 inch
#combined with a PDF scale factor of .12, this gives 600 dpi resolution (1/72 * .12 = 600 dpi)
use constant INCHES_PER_POINT => 1/72; #0.0138888889; #multiply point-size by this to get inches
# The precision used when computing a bezier curve. Higher numbers are more precise but slower (and generate larger files).
#$bezierPrecision = 100;
use constant BEZIER_PRECISION => 36; #100; #use const; reduced for faster rendering (mainly used for silk screen and thermal pads)
# Ground planes and silk screen or larger copper rectangles or circles are filled line-by-line using this resolution.
use constant FILL_WIDTH => .01; #fill at most 0.01 inch at a time
# The max number of characters to read into memory
use constant MAX_BYTES => 10 * M; #bumped up to 10 MB, use const
my $runtime = time(); #Time::HiRes::gettimeofday(); #measure my execution time
###########################################################################
#Start of main logic:
###########################################################################
if ((scalar(@ARGV) < 1) || (scalar(@ARGV) > 3)) #allow up to 3 pdfs to define multiple layers in separate files
{
my ($os, $prefix) = ($^O, ""); #$OSNAME
if ($os =~ m/Win/) { $prefix = "perl"; } #bash-ify may not work on Windows (ie, without CygWin)
print "Usage: $prefix pdf2gerb.pl <top-copper.pdf> [<bottom-copper.pdf>] [<top-silk.pdf>]\n";
if ($prefix ne "") { print "On Windows, you may need to put \"perl\" at the start.\n"; }
print "Output files will be placed in the current working folder.\n";
exit;
}
# Used by the main routine to store layer names
our @layerTitles = ();
#moved up here so it's only done once:
# Which layer we're on
our $currentLayer = 0;
#keep track of overall board dimensions and origin:
our %pcbLayout = ();
#summary stats:
our ($numfiles, $totalLines, $warnings) = (0, 0, 0); #globals
our ($did_drill, $did_outline) = (FALSE, FALSE);
getfiles(); #read all input files
my $pdfContents = our $multiContents;
#debug input stream:
if (WANT_ALLINPUT) #save entire input stream (for debug ONLY)
{
our $outputDir;
my $filename = "all_input.txt";
open my $outstream, ">$outputDir$filename";
print $outstream $pdfContents;
close $outstream;
mywarn("[DEBUG] input stream saved to $outputDir$filename\n");
}
#pre-scan all layers to determine PCB size and origin (outline might not be on the first layer)
if (scalar(@layerTitles) > 1)
{
our @lines = ();
while ($pdfContents =~ m/BDC(.*?)EMC/gs)
{
my @morelines = split /\n/, $1;
our $rot = shift(@morelines); #pull off rotation
push(@lines, @morelines);
}
boundingRect(); #get pcb size and origin
# Reset the match position to the beginning
pos($pdfContents) = 0; #is this still needed?
}
# Break the file into layers (BDC...EMC)
while ($pdfContents =~ m/BDC(.*?)EMC/gs)
{
# Break the layer into separate lines
our @lines = split /\n/, $1;
our $rot = shift(@lines); #pull off rotation
# Make up a layer title if there wasn't one defined in the file
if (scalar(@layerTitles) <= $currentLayer) { push(@layerTitles, "pdf2gerb"); } #layer type suffix will be added later
DebugPrint("starting layer# $currentLayer $layerTitles[$currentLayer], rot $rot\n", 1);
#moved down to here so it can be reset for each layer
# Used by GetAperture as well as the main routine to store aperture defn's
our %apertures = (); #changed to hash
# Used by GetDrillAperture
our %drillApertures = (); #changed to hash
# Multiply value in points by this to get value in inches
our $scaleFactor = INCHES_PER_POINT; #0.0138888889; #use const
our ($offsetX, $offsetY) = (0, 0); #note: default PDF coordinate space has origin at lower left
our $lastAperture = "";
our $currentDrillAperture = "";
our $lastStrokeWeight = 1; #default to 1 point
#remember stroke vs. fill colors separately:
# our %visibleFillColor = ('f' => TRUE, 's' => TRUE); #0 == white (hidden), !0 == !white (visible)
our %visibleFillColor = ('f' => MAYBE, 's' => TRUE); #0 == white (hidden), !0 == !white (visible)
our $layerPolarity = TRUE; #remember last LPD/LPC emitted; initial default = visible
our ($startPositionX, $startPositionY) = (0, 0); #remember subpath start in case path needs to be closed again later (sometimes needed)
our ($currentX, $currentY) = (0, 0); #current location in subpath
my $currentLine = 0; #helpful for debug
our @drawPath = (); #drawing path
our %holes = (); #used for overlapped hole detection
our %masks = (); #solder masks for each pad
our $body = ""; # list of commands generated for current layer
our %drillBody = (); #list of holes for each drill tool size; changed to hash
#SetAperture(1); #xform scale factor not set yet
boundingRect(); #get/check pcb size and origin
foreach our $line (@lines) #main loop to process PDF drawing commands
{
++$currentLine; #not too useful since it's relative to embedded PDF stream, but track it anyway for debug
DebugPrint("line $currentLine: \"$line\"\n", 19);
#process various types of PDF commands:
if (ignore()) { next; }
if (transforms()) { next; }
if (drawingAttrs()) { next; }
if (subpaths()) { next; }
if (drawshapes()) { next; }
#contact the authors if any others are important for your PCB
mywarn(sprintf("ignored: line# $currentLine/%d", scalar(@lines)) . "$line\n");
}
$totalLines += $currentLine;
refillholes(); #undo unneeded holes
DebugPrint(sprintf("body length: %.0fK, drill body len: %.0fK\n", length($body)/K, length(join("", values %drillBody))/K), 2);
#generate output files:
# if ($currentLayer + 1 == scalar(@layerTitles)) { copper("silk"); } #assume LAST layer is silk screen
if ($currentLayer && ($currentLayer + 1 == scalar(@layerTitles))) { copper("silk"); } #assume LAST layer is silk screen if not also first layer
else #top and bottom copper
{
copper("copper");
solder();
}
#only need one drill or outline file (should be the same for top + bottom); create for FIRST layer only:
drill();
edges();
# Increment our layer counter
DebugPrint("DONE with layer# $currentLayer $layerTitles[$currentLayer]\n", 1);
++$currentLayer;
#print $header . $body . "M02*\n";
}
$runtime -= time(); #Time::HiRes::gettimeofday();
DebugPrint(sprintf("files processed: %d, layers: $currentLayer, src lines: $totalLines, warnings: $warnings\n", $numfiles), 0);
if ($numfiles) #show PCB sizes
{
printf "pcb size is %5.3f x %5.3f, origin at (%5.3f, %5.3f) %s\n", inchesX($pcbLayout{'xmax'}), inchesY($pcbLayout{'ymax'}), inchesX($pcbLayout{'xmin'}), inchesY($pcbLayout{'ymin'}), METRIC? "mm": "inches";
if (PANELIZE->{'x'} * PANELIZE->{'y'} > 1) { printf "panelized size is %5.3f x %5.3f %s\n", PANELIZE->{'x'} * inchesX($pcbLayout{'xmax'}), PANELIZE->{'y'} * inchesY($pcbLayout{'ymax'}), METRIC? "mm": "inches"; }
}
printf "total input stream size: %.0fK, processing time: %.2f sec\n-end-\n", length($pdfContents)/K, -$runtime; #time() - $^T; #$BASETIME
###########################################################################
#Input file parsing:
###########################################################################
#concatenate all input files:
#This is an alternative to defining multiple layers in a single PDF file.
#parameters: none (uses globals)
#return value: none (uses globals)
sub getfiles
{
our ($numfiles, $multiContents, $outputDir, $grab_streams) = (0, "", "", 0); #initialize globals
foreach my $pdfFilePath (@ARGV) #added outer loop
{
++$numfiles;
DebugPrint("processing file#$numfiles: $pdfFilePath ...\n", 0);
# Calculate the output dir from the input file path
#$pdfFilePath =~ m/^(.+)\/.+$/;
if ($outputDir eq "") #set output dir first time only, then place all output files there
{
my ($vol, $dir, $filename) = File::Spec->splitpath($pdfFilePath);
#just place output files into current directory (better for separation):
##$dir =~ s/\.\.\\//g; #place output in subfolder even if source files are in parent
#$outputDir = $vol . $dir;
if ($outputDir eq "") { $outputDir = cwd() . "/"; } #default to current directory
DebugPrint("vol $vol, dir $dir, file $filename, outdir $outputDir\n", 5);
}
# Open the file for reading
#added file size warning:
unless (-e $pdfFilePath) { --$numfiles; mywarn("file missing: $pdfFilePath"); next; }
my $filesize = -s $pdfFilePath;
my $sizewarn = ($filesize > MAX_BYTES)? sprintf("TOO BIG (> %dMB)", MAX_BYTES / 1024 / 1024): "ok";
DebugPrint("opening file $pdfFilePath, size $filesize $sizewarn ...\n", 1);
open my $pdfFile, "< $pdfFilePath";
binmode $pdfFile; #PDF 1.4 flate coding is binary, not ascii
# Read in up to MAXBYTES
read $pdfFile, my $rawPdfContents, MAX_BYTES;
close $pdfFile; #close file after reading
# $rawPdfContents = decode_utf8($rawPdfContents);
#NO $rawPdfContents = Encode::decode('iso-8859-1', $rawPdfContents); #convert to Unicode
# my $enctype = Encode::Detect::Detector::detect($rawPdfContents);
DebugPrint(sprintf("got %d chars from input file $pdfFilePath\n", length($rawPdfContents)), 2);
# Fix a problem where content lines end in \r (0x0D) and are unprintable
#@rawLines = split /(\r\n|\n\r|\n|\r)/, $rawPdfContents;
my @rawLines = split /(\r\n|\n\r|\n|\r)/, decompress($rawPdfContents, $pdfFilePath); #PDF 1.4 requires decompress
chomp(@rawLines);
my $pdfContents = join("\n", @rawLines);
$pdfContents =~ s/\r//gs; #remove DOS carriage returns
$pdfContents =~ s/\n\n/\n/gs; #remove blank lines
# $pdfContents =~ s/\n(W\*? n)/ \1/gs; #join clip command with prev line to avoid confusion with regular rects
$pdfContents =~ s/\n(W\*? n)/ $1/gs; #join clip command with prev line to avoid confusion with regular rects
#some PDF editors join/split commands on a line, which makes parsing more complicated
#try to fix it here:
$pdfContents =~ s/(-?\d+\.?\d*)\s*\n\s*(c|-?\d+\.?\d*)\s+/$1 $2 /gs; #join c or other commands that are split across lines
$pdfContents =~ s/(-?\d+\.?\d*\s+)(c|m)\s+(-?\d+\.?\d*)/$1$2\n$3/gs; #split c and m commands if on same line
$pdfContents =~ s/(re|c|m|l)\s+(f|h|S|W)/$1\n$2/gs; #split re/c/m/l and f/h/S commands if on same line; also W
# open my $outstream, ">$outputDir" . "pdfdebug.txt";
# print $outstream $pdfContents;
# close $outstream;
# printf "wrote pdf contents to pdfdebug.txt\n";
#silk screen layer seems to have a lot of independent strokes
#string them together to cut down on silk layer size:
my $svlen = length($pdfContents);
for (;;) #remove redundant l/m commands; loop handles overlapping matches
{
my $svbuf = $pdfContents;
$pdfContents =~ s/\n(-?\d+\s-?\d+\s)l\nS\n\1m\n/\n$1l\n/gs; #merge redundant l + m commands
if ($pdfContents eq $svbuf) { last; } #nothing merged this time, so exit
}
DebugPrint(sprintf("reduced stroke chains by %d bytes (%d%%)\n", $svlen - length($pdfContents), 100 * ($svlen - length($pdfContents))/$svlen), 8);
# Get the layer titles
my $numtitles = 0;
while ($pdfContents =~ m/\/Title\((.+?)\)/gs)
{
#print "title: $1\n";
push(@layerTitles, $1);
++$numtitles;
}
DebugPrint("titles found: $numtitles\n", 5);
if ($numtitles <= 1) #use file name in place of title unless file contains multiple layers
{
my ($vol, $dir, $filename) = File::Spec->splitpath($pdfFilePath);
$filename =~ s/\.pdf$//i; #drop file extension
if ($filename !~ m/(^|\W)(top|bottom|silk)$/i) #add descriptive suffix to layer/file name
{ $filename .= ("-top", "-bottom", "-silk")[$numfiles - 1]; }
DebugPrint("using title '$filename'\n", 5);
if (!$numtitles) { push(@layerTitles, $filename); } #add new layer name
else { $layerTitles[-1] = $filename; } #replace existing layer name
}
# Does BDC occur in this file? (It will not if the file is a single layer)
if ($pdfContents !~ m/BDC/gs)
{
# No, so -- as a hack -- let's convert "stream" -> "BDC" and "endstream" -> "EMC"
$pdfContents =~ s/endstream/EMC/gs;
$pdfContents =~ s/stream/BDC/gs;
}
#check for page rotation:
my $rot = ($pdfContents =~ m/\/Rotate (\d+)/)? $1: 0;
if ($rot) { DebugPrint("page is rotated $rot deg\n", 3); }
$pdfContents =~ s/BDC/BDC$rot\n/gs; #kludge: add rotation onto layer delimiter since the layer itself doesn't have a place for that info
DebugPrint(sprintf("now have %d chars from input file $pdfFilePath\n", length($pdfContents)), 2);
$multiContents .= $pdfContents;
}
#at this point all files have been concatenated to look like multiple layers within in a single file
$multiContents =~ s/^s$/h\nS/gs; #s = h + S; replace with equivalent PDF commands
$multiContents =~ s/^b$/h\nB/gs; #b = h + B; replace with equivalent PDF commands
$multiContents =~ s/^b\*$/h\nB\*/gs; #b* = h + B*; replace with equivalent PDF commands
}
#pre-scan to find layer origin and size (bounding rect):
#This assumes that the rect or lines that define the PCB edges are outside of a transformed area,
#which seems to be the case. (transforms seem to only apply to traces/pads).
#parameters: none (uses globals)
#return value: none (uses globals)
sub boundingRect
{
our (@lines, $rot, $currentLayer, %pcbLayout, %clipRect); #globals
#For rectangular PCB, the longest horizontal and vertical lines are used to determine the PCB origin and size.
#These could be individual line segments or a rectangle.
#Curves and shorter lines are likely text, so they are ignored.
my ($minX, $minY, $maxX, $maxY) = (0, 0, 0, 0); #set initial values to force first values to be captured
my ($numlines, $srclineX, $srclineY) = (0, "?", "?"); #remember where origin/size was defined for error reporting
my ($prevx, $prevy, $prevlineX, $prevlineY) = ("", "", "", "");
foreach my $brline (@lines)
{
++$numlines;
if ($brline =~ m/(-?\d+\.?\d*)\s(-?\d+\.?\d*)\sm$/) #move; position is only used to define start of next line segment
{
($prevx, $prevy, $prevlineX, $prevlineY) = ($1, $2, "'$brline'", "'$brline'");
next;
}
if ($brline =~ m/(-?\d+\.?\d*)\s(-?\d+\.?\d*)\sl$/) #line segment
{
if (($2 eq $prevy) && (abs($1 - $prevx) > $maxX - $minX)) { ($minX, $maxX, $srclineX) = (min($1, $prevx), max($1, $prevx), "$prevlineX + '$brline' at line#$numlines"); }
if (($1 eq $prevx) && (abs($2 - $prevy) > $maxY - $minY)) { ($minY, $maxY, $srclineY) = (min($2, $prevy), max($2, $prevy), "$prevlineY + '$brline' at line#$numlines"); }
#DebugPrint("line: line $numlines, \"$minX $minY\" .. \"$maxX, $maxY\"\n", 2);
($prevx, $prevy, $prevlineX, $prevlineY) = ($1, $2, "'$brline'", "'$brline'");
next;
}
if ($brline =~ m/(-?\d+\.?\d*)\s(-?\d+\.?\d*)\s(-?\d+\.?\d*)\s(-?\d+\.?\d*)\sre$/) #rect
{
if (abs($3) > $maxX - $minX) { ($minX, $maxX, $srclineX) = (min($1, $1 + $3), max($1, $1 + $3), "'$brline' at line#$numlines"); }
if (abs($4) > $maxY - $minY) { ($minY, $maxY, $srclineY) = (min($2, $2 + $4), max($2, $2 + $4), "'$brline' at line#$numlines"); }
#DebugPrint("rect: line $numlines, \"$minX $minY\" .. \"$maxX, $maxY\"\n", 2);
next;
}
}
DebugPrint("layer#$currentLayer bounding rect: \"$minX $minY\" .. \"$maxX, $maxY\"\n", 2);
DebugPrint("bounding rect: used $srclineX for X\n", 4);
DebugPrint("bounding rect: used $srclineY for Y\n", 4);
#apply rotation to bounding box before saving it:
#This needs to be outside the above loop since max values aren't known until the end.
if (($rot == 90) || ($rot == 270)) { ($minX, $minY, $maxX, $maxY) = ($minY, $minX, $maxY, $maxX); }
if (!scalar(%pcbLayout)) #use first layer to define overall pcb size
{ %pcbLayout = ('xmin' => $minX, 'ymin' => $minY, 'xmax' => $maxX, 'ymax' => $maxY, 'srcX' => $srclineX, 'srcY' => $srclineY); }
elsif (($minX != $pcbLayout{'xmin'}) || ($minY != $pcbLayout{'ymin'})) #consistency check between layers
{
mywarn("layer#$currentLayer origin ($minX, $minY) doesn't match layer#0 ($pcbLayout{'xmin'}, $pcbLayout{'ymin'})");
DebugPrint("layer#$currentLayer origin ($minX, $minY) from lines $srclineX, $srclineY\n", 3);
DebugPrint("layer#0 origin ($pcbLayout{'xmin'}, $pcbLayout{'ymin'}) from lines $pcbLayout{'srcX'}, $pcbLayout{'srcY'}", 3);
}
elsif (($maxX != $pcbLayout{'xmax'}) || ($maxY != $pcbLayout{'ymax'})) #consistency check between layers
{
mywarn("layer#$currentLayer size ($maxX, $maxY) doesn't match layer#0 size ($pcbLayout{'xmax'}, $pcbLayout{'ymax'})");
DebugPrint("layer#$currentLayer size ($maxX, $maxY) from lines $srclineX, $srclineY\n", 3);
DebugPrint("layer#0 size ($pcbLayout{'xmax'}, $pcbLayout{'ymax'}) from lines $pcbLayout{'srcX'}, $pcbLayout{'srcY'}", 3);
}
%clipRect = (%pcbLayout); #set initial clipping rect to entire "page" (pcb)
unshift(@lines, "1 0 0 1 0 0 cm"); #insert a transform to recalculate origin
}
#ignore PDF commands that don't affect PCB rendering:
#parameters: none (uses globals)
#return value: true/false indicating whether the line was processed
sub ignore
{
our ($line); #globals
if ($line =~ m/^\s*$/) { return TRUE; } #empty line
#these seem to be safe to ignore:
if ($line =~ m/\d+\si$/) { return TRUE; } #flatness tolerance
if ($line =~ m/\d+\sj$/i) { return TRUE; } #line join + cap styles
if ($line =~ m/\sgs$/i) { return TRUE; } #graphics state dictionary
if ($line =~ m/Q$/i) { return TRUE; } #save/restore graphics state
return FALSE; #check for other commands
}
#handle transforms:
#NOTE: junk at start of line is ignored
#parameters: none (uses globals)
#return value: true/false indicating whether the line was processed
sub transforms
{
our ($line, $offsetX, $offsetY, $scaleFactor, %pcbLayout); #globals
if ($line =~ m/1 0 0 1 (-?\d+\.?\d*)\s(-?\d+\.?\d*)\scm$/) #transformation matrix (translation)
{
# Lines ending in cm define a transformation matrix...
# 1 0 0 1 X Y means offset all values by X and Y.
($offsetX, $offsetY) = (tenths($1) - $pcbLayout{'xmin'}, tenths($2) - $pcbLayout{'ymin'}); #set origin to lower left corner
#print "offset:" . $1 . " " . $2 . "\n";
DebugPrint(sprintf("xform offset ($1, $2) => adj ofs ($offsetX, $offsetY), pcb layout (%5.5f, %5.5f) .. (%5.5f, %5.5f)\n", inchesX($pcbLayout{'xmin'}), inchesY($pcbLayout{'ymin'}), inchesX($pcbLayout{'xmax'}), inchesY($pcbLayout{'ymax'})), 10);
return TRUE;
}
if ($line =~ m/(-?\d+\.?\d*)\s0 0 (-?\d+\.?\d*)\s0 0 cm$/) #transformation matrix (scaling)
{
#size + coords were incorrect, so this is needed
#other useful info at: http://www.asppdf.com/manual_04.html
# [sx 0 0 sy 0 0] = scaled; this is the one I am seeing
if ($1 != $2) { mywarn("non-proportional scaling transform ($1 vs. $2) not implemented"); }
$scaleFactor *= $1; # a value of .12 * 1/72 gives 1/600, which gives 600 dpi resolution
DebugPrint(sprintf("xform scale: ($1, $2) => factor %5.5f, pcb layout (%5.5f, %5.5f) .. (%5.5f, %5.5f)\n", $scaleFactor, inchesX($pcbLayout{'xmin'}), inchesY($pcbLayout{'ymin'}), inchesX($pcbLayout{'xmax'}), inchesY($pcbLayout{'ymax'})), 10);
return TRUE;
}
return FALSE; #xform not found, check for other commands
}
#handle drawing attrs:
#NOTE: junk at start of line is ignored
#parameters: none (uses globals)
#return value: true/false indicating whether the line was processed
sub drawingAttrs
{
our ($line, %visibleFillColor, $lastStrokeWeight); #globals
if ($line =~ m/(\d+\.?\d*)\s(g)$/i) #Gray Space
{
my $which = ($2 eq "g")? 'f': 's'; #stroke vs. fill (upper vs lower case command)
#One number followed by g define the current fill color in Gray Space
#We want to ignore anything drawn in white
$visibleFillColor{$which} = ($1 == 1)? FALSE: TRUE; # This changes color to white, which makes things invisible
#print "fill color:" . $1 . " " . $ 1 . " " . $1 . "\n";
DebugPrint("$which color rgb $1 $1 $1 => vis-$which $visibleFillColor{$which}\n", 5);
return TRUE;
}
if ($line =~ m/(\d+\.?\d*)\s(\d+\.?\d*)\s(\d+\.?\d*)\s(rg)$/i) #RGB color; distinguish stroke vs. fill
{
my $which = ($4 eq "rg")? 'f': 's'; #stroke vs. fill (upper vs. lower case command)
# Three numbers followed by rg define the current fill color in RGB
# We want to ignore anything drawn in white
$visibleFillColor{$which} = (($1 == 1) && ($2 == 1) && ($3 == 1))? FALSE: TRUE; # This changes color to white, which makes things invisible
#print "fill color:" . $1 . " " . $2 . " " . $3 . "\n";
DebugPrint("$which color rgb $1 $2 $3 => vis-$which $visibleFillColor{$which}\n", 5);
return TRUE;
}
if ($line =~ m/(\d+\.?\d*)\s(\d+\.?\d*)\s(\d+\.?\d*)\s(\d+\.?\d*)\s(k)$/i) #CYMK color; distinguish stroke vs. fill
{
my $which = ($5 eq "k")? 'f': 's'; #stroke vs. fill (upper vs. lower case command)
# Four numbers followed by k define the current fill color in CMYK
# We want to ignore anything drawn in white
$visibleFillColor{$which} = (($1 == 0) && ($2 == 0) && ($3 == 0) && ($4 == 0))? FALSE: TRUE; # This changes color to white, which makes things invisible
#print "fill color:" . $1 . " " . $2 . " " . $3 . "\n";
DebugPrint("$which color cmyk $1 $2 $3 => vis-$which $visibleFillColor{$which}\n", 10);
return TRUE;
}
if ($line =~ m/(\d+\.?\d*)\sw/) #stroke weight (in points)
{
# Number followed by w is a stroke weight
#print "weight:" . $1 . "\n";
DebugPrint(sprintf("weight: %5.5f \"$1\"\n", inches($1)), 10);
$lastStrokeWeight = $1;
#defer aperture selection until needed:
return TRUE;
}
return FALSE; #drawing attr not found, check for other commands
}
#drawing subpaths:
#This will save line segments and arcs, or other elements in the drawing path until the next fill or stroke command.
#NOTE: junk at start of line is ignored for MOST commands.
#parameters: none (uses globals)
#return value: true/false indicating whether the line was processed
sub subpaths
{
our ($line, @drawPath, $startPositionX, $startPositionY, $startXY, $currentX, $currentY, $curXY, %visibleFillColor, $lastStrokeWeight); #globals
if ($line =~ m/(-?\d+\.?\d*)\s(-?\d+\.?\d*)\s(-?\d+\.?\d*)\s(-?\d+\.?\d*)\sre$/) #rect
{
# Lines ending in re define a rectangle, often followed
# by W n to define the clipping rect
my ($startx, $starty) = rotate($1, $2);
my ($endx, $endy) = rotate(tenths($1 + $3), tenths($2 + $4)); #convert w, h to max x, y
push(@drawPath, (min($startx, $endx), min($starty, $endy), max($startx, $endx), max($starty, $endy), 1, "rect")); #add rect to draw path; NOTE: rotation might have reversed coords, so check min/max again
DebugPrint(sprintf("rect: (%5.5f, %5.5f) .. (%5.5f, %5.5f) \"$1 $2 +$3 +$4\", vis-f $visibleFillColor{'f'}, weight $lastStrokeWeight\n", inchesX($drawPath[-6]), inchesY($drawPath[-5]), inchesX($drawPath[-4]), inchesY($drawPath[-3])), 10);
($startPositionX, $startPositionY, $startXY) = (0, 0, "0 0"); #rect closes current subpath
($currentX, $currentY, $curXY) = (0, 0, "0 0"); #rect closes current subpath
return TRUE;
}
if ($line =~ m/(-?\d+\.?\d*)\s(-?\d+\.?\d*)\sm$/) #start new subpath
{
# Lines ending in m mean move to a position, which can be used
# to close a path later on
($startPositionX, $startPositionY, $startXY) = (rotate(tenths($1), tenths($2)), "$1 $2"); #keep start position of drawing subpath
($currentX, $currentY, $curXY) = ($startPositionX, $startPositionY, "$1 $2"); #keep last position in drawing subpath
DebugPrint(sprintf("move \"$curXY\" & ($currentX, $currentY) = (%5.5f, %5.5f)", inchesX($currentX), inchesY($currentY)), 5);
return TRUE;
}
if ($line =~ m/(-?\d+\.?\d*)\s(-?\d+\.?\d*)\sl$/) #line segment
{
# Lines ending in l mean draw a straight line to this position
my ($endx, $endy) = rotate($1, $2);
push(@drawPath, ($currentX, $currentY, $endx, $endy, numshapes("line") + 1, "line"));
DebugPrint(sprintf("line: from (%5.5f, %5.5f) \"$curXY\" to (%5.5f, %5.5f) \"$1 $2\" \"$line\", vis-s $visibleFillColor{'s'}, weight %5.5f \"$lastStrokeWeight\"\n", inchesX($drawPath[-6]), inchesY($drawPath[-5]), inchesX($drawPath[-4]), inchesY($drawPath[-3]), inches($lastStrokeWeight)), 5);
($currentX, $currentY, $curXY) = ($endx, $endy, "$1 $2"); #remember last position in drawing subpath
return TRUE;
}
if ($line =~ m/^h$/) #close subpath
{
# h means draw a straight line back to the first point
#not sure we want to do this:
# if (($currentX == $startPositionX) && ($currentY == $startPositionY)) #skip this subpath (prevents circle reduction, which doesn't allow it to be a round pad or drill hole)
# {
# DebugPrint(sprintf("close: ignoring benign (%5.5f, %5.5f) \"$curXY\" back to self, vis-s $visibleFillColor{'s'}, weight $lastStrokeWeight\n", inchesX($currentX), inchesY($currentY)), 10);
# return TRUE;
# }
push(@drawPath, ($currentX, $currentY, $startPositionX, $startPositionY, numshapes("line") + 1, "line"));
DebugPrint(sprintf("close: from (%5.5f, %5.5f) \"$curXY\" back to (%5.5f, %5.5f) \"$drawPath[-4] $drawPath[-3]\", vis-s $visibleFillColor{'s'}, weight $lastStrokeWeight\n", inchesX($drawPath[-6]), inchesY($drawPath[-5]), inchesX($drawPath[-4]), inchesY($drawPath[-3])), 10);
($startPositionX, $startPositionY, $startXY) = (0, 0, "0 0"); #close current subpath
($currentX, $currentY, $curXY) = (0, 0, "0 0"); #close current subpath
return TRUE;
}
if ($line =~ m/(-?\d+\.?\d*)\s(-?\d+\.?\d*)\s(-?\d+\.?\d*)\s(-?\d+\.?\d*)\s(-?\d+\.?\d*)\s(-?\d+\.?\d*)\sc$/) #cubic bezier (3 points)
{
# Lines ending in c mean draw a bezier path to this point (x1 y1 x2 y2 x3 y3)
# x1 y1 x2 y2 x3 y3
# The curve extends from the current point to the point (x3, y3),
# using (x1, y1) and (x2, y2) as the Bezier control points.
# The new current point is (x3, y3).
my ($endx, $endy) = rotate($5, $6);
push(@drawPath, ($currentX, $currentY, rotate($1, $2), rotate($3, $4), $endx, $endy, numshapes("curve") + 1, "curve"));
DebugPrint(sprintf("curve-c: from (%5.5f, %5.5f) \"$curXY\" thru (%5.5f, %5.5f) \"$1 $2\" and (%5.5f, %5.5f) \"$3 $4\" to (%5.5f, %5.5f) \"$5 $6\", vis-s $visibleFillColor{'s'}, weight %5.5f \"$lastStrokeWeight\"\n", inchesX($drawPath[-10]), inchesY($drawPath[-9]), inchesX($drawPath[-8]), inchesY($drawPath[-7]), inchesX($drawPath[-6]), inchesY($drawPath[-5]), inchesX($drawPath[-4]), inchesY($drawPath[-3]), inches($lastStrokeWeight)), 5);
($currentX, $currentY, $curXY) = ($endx, $endy, "$5 $6"); #remember last position in subpath
return TRUE;
}
if ($line =~ m/(-?\d+\.?\d*)\s(-?\d+\.?\d*)\s(-?\d+\.?\d*)\s(-?\d+\.?\d*)\sv$/) #cubic bezier (2 points)
{
# Lines ending in v mean draw a bezier curve (x2 y2 x3 y3)
# x2 y2 x3 y3.
# The curve extends from the current point to the point (x3, y3),
# using the current point and (x2, y2) as the Bezier control points.
# The new current point is (x3, y3).
my ($endx, $endy) = rotate($3, $4);
push(@drawPath, ($currentX, $currentY, $currentX, $currentY, rotate($1, $2), $endx, $endy, numshapes("curve") + 1, "curve"));
DebugPrint(sprintf("curve-v: from (%5.5f, %5.5f) \"$curXY\" thru (%5.5f, %5.5f) \"$1 $2\" to (%5.5f, %5.5f) \"$3 $4\", vis-s $visibleFillColor{'s'}, weight $lastStrokeWeight\n", inchesX($drawPath[-10]), inchesY($drawPath[-9]), inchesX($drawPath[-6]), inchesY($drawPath[-5]), inchesX($drawPath[-4]), inchesY($drawPath[-3])), 5);
($currentX, $currentY, $curXY) = ($endx, $endy, "$3 $4"); #remember last position in subpath
return TRUE;
}
if ($line =~ m/(-?\d+\.?\d*)\s(-?\d+\.?\d*)\s(-?\d+\.?\d*)\s(-?\d+\.?\d*)\sy$/) #cubic bezier (2 points)
{
# Lines ending in y mean draw a bezier curve (x1 y1 x3 y3)
# x1 y1 x3 y3.
# The curve extends from the current point to the point (x3, y3),
# using (x1, y1) and (x3, y3) as the Bezier control points.
# The new current point is (x3, y3).
my ($endx, $endy) = rotate($3, $4);
push(@drawPath, ($currentX, $currentY, rotate($1, $2), $endx, $endy, $endx, $endy, numshapes("curve") + 1, "curve"));
DebugPrint(sprintf("curve-y: from (%5.5f, %5.5f) \"$curXY\" thru (%5.5f, %5.5f) \"$1 $2\" to (%5.5f, %5.5f) \"$3 $4\", vis-s $visibleFillColor{'s'}, weight $lastStrokeWeight\n", inchesX($drawPath[-10]), inchesY($drawPath[-9]), inchesX($drawPath[-8]), inchesY($drawPath[-7]), inchesX($drawPath[-4]), inchesY($drawPath[-3])), 5);
($currentX, $currentY, $curXY) = ($endx, $endy, "$3 $4"); #keep last position in subpath
return TRUE;
}
return FALSE; #subpath not found, check for other commands
}
#apply stroke or fill to subpaths:
#This is the main function to draw pads, holes, traces, and ground planes.
#parameters: none (uses globals)
#return value: true/false indicating whether the line was processed
sub drawshapes
{
our ($line, @drawPath, %clipRect, $lastStrokeWeight, %visibleFillColor); #globals
if ($line =~ m/W\*? n$/) #clip rect
{
# W n makes the prev re command set the clipping rect
#NOTE: this ignores winding + even-odd rules
#ignore clip rect for now; not used anywhere
#reduceRect(); #check if last 3 or 4 line segments in drawing path make a rect
#if ($drawPath[-1] eq "rect") #intersect clipping rect with drawing path to get new clip rect
#{
# ($clipRect{'xmin'}, $clipRect{'ymin'}) = (max($clipRect{'xmin'}, $drawPath[-6]), max($clipRect{'ymin'}, $drawPath[-5]));
# ($clipRect{'xmax'}, $clipRect{'ymax'}) = (min($clipRect{'xmax'}, $drawPath[-4]), min($clipRect{'ymax'}, $drawPath[-3]));
# DebugPrint(sprintf("new clip rect: (%5.5f, %5.5f) .. (%5.5f, %5.5f)\n", inchesX($clipRect{'xmin'}), inchesY($clipRect{'ymin'}), inchesX($clipRect{'xmax'}), inchesY($clipRect{'ymax'})), 8);
#}
#else { mywarn("clip region $drawPath[-1] not implemented"); }
#popshape();
#most CAD software does not seem to need clip rects, so they can be safely ignored
#however, this behavior can be overridden using the SUBST_CIRCLE_CLIPRECT option, as a work-around for CAD software that uses clip rects along with other, unrecognized drawing commands
if (!SUBST_CIRCLE_CLIPRECT) { return TRUE; }
reduceRect(); #check if last 3 or 4 line segments in drawing path make a rect
if (scalar(@drawPath) < 2) { mywarn(sprintf("not a rect: %d", scalar(@drawPath))); }
elsif ($drawPath[-1] eq "rect") #intersect clipping rect with drawing path to get new clip rect
{
my ($minX, $minY, $maxX, $maxY) = ($drawPath[-6], $drawPath[-5], $drawPath[-4], $drawPath[-3]);
DebugPrint(sprintf("clip rect: (%5.5f, %5.5f) .. (%5.5f, %5.5f) replaced with circle\n", inchesX($minX), inchesY($minY), inchesX($maxX), inchesY($maxY)), 8);
popshape();
push(@drawPath, (($minX + $maxX)/2, ($minY + $maxY)/2, $maxX - $minX, 1, "circle")); #replace clip rect with circle
}
else { mywarn("clip region $drawPath[-2] $drawPath[-1] not implemented"); }
return TRUE;
}
if ($line =~ m/^n$/) #noop (discard path)
{
DebugPrint("noop: shape $drawPath[-1]\n", 5);
popshape();
return TRUE;
}
if ($line =~ m/^S$/) #stroke: draw current path
{
# S means stroke what we just drew - only supported for circles
# as a workaround for TurboCAD, which can't fill circles (!)
#this now handles lines and curves
SetPolarity('s');
SetAperture('t', $lastStrokeWeight + TRACE_ADJUST);
# DebugPrint(sprintf("path waiting for stroke: %d, stroke weight: $lastStrokeWeight, polarity $visibleFillColor{'s'}\n", scalar(@drawPath)), 5);
while (scalar(@drawPath)) #draw all subpaths that are waiting
{
outline();
if (popshape()) { next; }
DebugPrint("failed to outline subpath\n", 5);
@drawPath = ();
}
return TRUE;
}
if ($line =~ m/^f\*?$/) #fill; small rect or circles are treated as pads; small white filled circles are treated as holes
{
#NOTE: this ignores PDF winding + even-odd rules
#NOTE: "*" is for odd-even fill path rule; rule is ignored
reduceRect(); #check if last 4 line segments in drawing path make a rect
reduceCircle(); #check if last 4 curves in drawing path make a circle
# DebugPrint(sprintf("path waiting for fill: %d, polarity $visibleFillColor{'f'}\n", scalar(@drawPath)), 5);
while (scalar(@drawPath)) #fill all subpaths that are waiting
{
fill();
if (popshape()) { next; }
DebugPrint("failed to fill subpath\n", 5);
@drawPath = ();
}
return TRUE;
}
return FALSE; #shape not found, check for other commands
}
#draw outline for next shape in path:
#This function generates traces and text.
#Also used around line-filled areas to give a smoother edge.
#parameters: none (uses globals)
#return value: none (uses globals)
sub outline
{
our (@drawPath, %visibleFillColor, $lastStrokeWeight, $lastAperture, $body); #globals
my ($ofs) = scalar(@_)? @_: (0); #offset toward center
if ($drawPath[-1] eq "rect") #draw rect edges
{
if ($ofs) #nudge toward center of rect (gives more accurate outline on filled rect)
{
$drawPath[-6] += $ofs; #minX is known to be < centerX
$drawPath[-5] += $ofs; #minY is known to be < centerY
$drawPath[-4] -= $ofs; #maxX is known to be > centerX
$drawPath[-3] -= $ofs; #maxY is known to be > centerY
}
DebugPrint(sprintf("stroke rect: (%5.5f, %5.5f) .. (%5.5f, %5.5f), vis-s $visibleFillColor{'s'}, weight $lastStrokeWeight, aper $lastAperture\n", inchesX($drawPath[-6]), inchesY($drawPath[-5]), inchesX($drawPath[-4]), inchesY($drawPath[-3])), 8);
$body .= sprintf("X%sY%sD02*\n", inchesX($drawPath[-6], FALSE), inchesY($drawPath[-5], FALSE)); #move to lower left corner
$body .= sprintf("Y%sD01*\n", inchesY($drawPath[-3], FALSE)); #draw to upper left corner
$body .= sprintf("X%sD01*\n", inchesX($drawPath[-4], FALSE)); #draw to upper right corner
$body .= sprintf("Y%sD01*\n", inchesY($drawPath[-5], FALSE)); #draw to lower right corner
$body .= sprintf("X%sD01*\n", inchesX($drawPath[-6], FALSE)); #draw to lower left corner again
return TRUE;
}
if ($drawPath[-1] eq "line") #line segment or polygon
{
if ($ofs) #nudge edges "inward" (gives more accurate outline because it compensates for line width)
{
#for each edge, determine which direction is toward "inside" of polygon:
my %inside = ();
for (my $j = -6 * $drawPath[-2]; $j < 0; $j += 6)
{
my ($midX, $midY, $deltaX, $deltaY) = (($drawPath[$j + 0] + $drawPath[$j + 2])/2, ($drawPath[$j + 1] + $drawPath[$j + 3])/2, $drawPath[$j + 2] - $drawPath[$j + 0], $drawPath[$j + 3] - $drawPath[$j + 1]);
# my $slope = $deltaX? $deltaY/$deltaX: MAXINT;
#first pick a test point near the center of but not on this edge:
my $edgelen = sqrt($deltaX **2 + $deltaY **2);
if ($edgelen < 0.00001) { DebugPrint(sprintf("no edge delta? (%5.5f, %5.5f) - (%5.5f, %5.5f)", $drawPath[$j + 0], $drawPath[$j + 2], $drawPath[$j + 1], $drawPath[$j + 3]), 5); next; }
my ($testX, $testY) = ($midX - $deltaY * $ofs / $edgelen, $midY + $deltaX * $ofs / $edgelen); #move a short distance perpendicular to center of polygon's edge
#then check whether test point is inside or outside the polygon:
#The code below is based on the point-in-polygon algorithm described at http://alienryderflex.com/polygon/
$inside{$j} = +$ofs; #assume outside for now; <0 => inside, >0 => outside
for (my $i = -6 * $drawPath[-2]; $i < 0; $i += 6)
{
if ((min($drawPath[$i + 1], $drawPath[$i + 3]) >= $testY) || (max($drawPath[$i + 1], $drawPath[$i + 3]) < $testY)) { next; } #polygon side doesn't cross test point
#? if (($drawPath[$i + 0] > $testX) && ($drawPath[$i + 2] > $testX)) { next; } #only need to check edges to one side of test point
my $x = $drawPath[$i] + ($testY - $drawPath[$i + 1]) / ($drawPath[$i + 3] - $drawPath[$i + 1]) * ($drawPath[$i + 2] - $drawPath[$i + 0]); #intersection of test line with edge
DebugPrint(sprintf("polygon edge %d intersects at X= %5.5f, this is %s test point X\n", -$i/6, inchesX($x), ($x < $testX)? "<": ($x > $testX)? ">": "="), 5);
if ($testX <= $x) { next; } #test point lies to the left of polygon edge
$inside{$j} = -$inside{$j}; #track inside/outside parity
}
DebugPrint(sprintf("polygon edge %d check: (%5.5f, %5.5f) .. (%5.5f, %5.5f), test point %s%s (%5.5f, %5.5f) inside? %d\n", -$j/6, inchesX($drawPath[$j + 0]), inchesY($drawPath[$j + 1]), inchesX($drawPath[$j + 2]), inchesY($drawPath[$j + 3]), ($testX < $midX)? "-": ($testX > $midX)? "+": "=", ($testY < $midY)? "-": ($testY > $midY)? "+": "=", inchesX($testX), inchesY($testY), $inside{$j}), 5);
}
#now move the polygon edge toward the "inside" of the polygon:
#NOTE: "inward" may mean toward or away from the center of the polygon, depending on orientation of polygon edges
for (my $i = -6 * $drawPath[-2]; $i < 0; $i += 6)
{
my ($svx0, $svy0, $svx1, $svy1) = ($drawPath[$i + 0], $drawPath[$i + 1], $drawPath[$i + 2], $drawPath[$i + 3]);
my ($deltaX, $deltaY) = ($drawPath[$i + 2] - $drawPath[$i + 0], $drawPath[$i + 3] - $drawPath[$i + 1]);
my $edgelen = sqrt($deltaX **2 + $deltaY **2);
if ($edgelen < 0.00001) { next; }
#move edge toward or away from test point, based on whether it was inside or outside the polygon:
($drawPath[$i + 0], $drawPath[$i + 1]) = ($drawPath[$i + 0] + $inside{$i} * $deltaY / $edgelen, $drawPath[$i + 1] - $inside{$i} * $deltaX / $edgelen);
($drawPath[$i + 2], $drawPath[$i + 3]) = ($drawPath[$i + 2] + $inside{$i} * $deltaY / $edgelen, $drawPath[$i + 3] - $inside{$i} * $deltaX / $edgelen);
DebugPrint(sprintf("polygon edge %d nudge: (%5.5f, %5.5f) .. (%5.5f, %5.5f), test pt inside poly? %d, new edge: (%5.5f, %5.5f) .. (%5.5f, %5.5f)\n", -$i/6, inchesX($svx0), inchesY($svy0), inchesX($svx1), inchesY($svy1), $inside{$i}, inchesX($drawPath[$i + 0]), inchesY($drawPath[$i + 1]), inchesX($drawPath[$i + 2]), inchesY($drawPath[$i + 3])), 5);
}
#lastly, lengthen or shorten the polygon edges so the corners touch again (so polygon can be filled):
#This is done by finding the intersection of the pair of equations through each corner.
#There's probably a more efficient way, but this works and it isn't executed frequently.
for (my ($i, $previ) = (-6 * $drawPath[-2], -6); $i < 0; $previ = $i, $i += 6)
{
#given 2 points on a line, the line's equation is: y = (Y2 - Y1)/(X2 - X1)(x - X1) + Y1, or just x = X1 if the line is vertical
my ($deltaX, $deltaY) = ($drawPath[$i + 2] - $drawPath[$i + 0], $drawPath[$i + 3] - $drawPath[$i + 1]);
my ($prevdeltaX, $prevdeltaY) = ($drawPath[$previ + 2] - $drawPath[$previ + 0], $drawPath[$previ + 3] - $drawPath[$previ + 1]);
my ($cornerX, $cornerY) = ($drawPath[$i + 0], $drawPath[$i + 1]);
if (!$deltaX) #special case: current edge is a vertical line
{
if (!$prevdeltaX) { mywarn("2 adjacent polygon edges are vertical?"); } #shouldn't happen (2 adjacent edges should not be parallel)
else { $cornerY = $prevdeltaY/$prevdeltaX * ($cornerX - $drawPath[$previ + 0]) + $drawPath[$previ + 1]; }
# DebugPrint(sprintf("corner-vert-now = (%5.5f, %5.5f), prev delta (%5.5f, %5.5f)\n", inchesX($cornerX), inchesY($cornerY), inchesX($prevdeltaX), inchesY($prevdeltaY)), 60);
}
elsif (!$prevdeltaX) #special case: previous edge was a vertical line
{
$cornerX = $drawPath[$previ + 2];
$cornerY = $deltaY/$deltaX * ($cornerX - $drawPath[$i + 0]) + $drawPath[$i + 1];
# DebugPrint(sprintf("corner-vert-prev = (%5.5f, %5.5f), cur delta (%5.5f, %5.5f)\n", inchesX($cornerX), inchesY($cornerY), inchesX($deltaX), inchesY($deltaY)), 60);
}
elsif (abs($deltaY/$deltaX - $prevdeltaY/$prevdeltaX) < .0001) { mywarn(sprintf("2 adjacent polygon edges are parallel: edge[%d] (%5.5f, %5.5f) - (%5.5f, %5.5f) and edge[%d] (%5.5f, %5.5f) - (%5.5f, %5.5f)", -$i/6, inchesX($drawPath[$i + 0]), inchesY($drawPath[$i + 1]), inchesX($drawPath[$i + 2]), inchesY($drawPath[$i + 3]), -$previ/6, inchesX($drawPath[$previ + 0]), inchesY($drawPath[$previ + 1]), inchesX($drawPath[$previ + 2]), inchesY($drawPath[$previ + 3]))); } #shouldn't happen (2 adjacent edges should not be parallel)
else #neither edge is vertical, solve for x then y
{
if ($deltaY/$deltaX == $prevdeltaY/$prevdeltaX) { mywarn("2 adjacent polygon edges are parallel?"); } #shouldn't happen (2 adjacent edges should not be parallel)
$cornerX = $deltaY/$deltaX * $cornerX - $prevdeltaY/$prevdeltaX * $drawPath[$previ + 2] + $drawPath[$previ + 3] - $cornerY;
$cornerX /= $deltaY/$deltaX - $prevdeltaY/$prevdeltaX;
$cornerY = $deltaY/$deltaX * ($cornerX - $drawPath[$i + 2]) + $drawPath[$i + 3];
# DebugPrint(sprintf("corner-non-vert = (%5.5f, %5.5f), cur delta (%5.5f, %5.5f), prev delta (%5.5f, %5.5f)\n", inchesX($cornerX), inchesY($cornerY), inchesX($deltaX), inchesY($deltaY), inchesX($prevdeltaX), inchesY($prevdeltaY)), 60);
# if (($cornerX > 10000) || ($cornerY > 10000)) { DebugPrint("WHOOPS\n"); }
}
DebugPrint(sprintf("polygon corner %d: moved from (%5.5f, %5.5f) to (%5.5f, %5.5f)\n", -$i/6, inchesX($drawPath[$i + 0]), inchesY($drawPath[$i + 1]), inchesX($cornerX), inchesY($cornerY)), 5);
($drawPath[$i + 0], $drawPath[$i + 1]) = ($cornerX, $cornerY);
($drawPath[$previ + 2], $drawPath[$previ + 3]) = ($cornerX, $cornerY); #update both copies of the corner
}
}
#draw polygon edges:
for (my ($i, $first) = (-6 * $drawPath[-2], TRUE); $i < 0; $i += 6, $first = FALSE)
{
if ($first) { $body .= sprintf("X%sY%sD02*\n", inchesX($drawPath[$i + 0], FALSE), inchesY($drawPath[$i + 1], FALSE)); } #move to first corner
$body .= sprintf("X%sY%sD01*\n", inchesX($drawPath[$i + 2], FALSE), inchesY($drawPath[$i + 3], FALSE)); #line to next corner
DebugPrint(sprintf("poly outline %d: (%5.5f, %5.5f) .. (%5.5f, %5.5f)\n", -$i/6, inchesX($drawPath[$i + 0]), inchesY($drawPath[$i + 1]), inchesX($drawPath[$i + 2]), inchesY($drawPath[$i + 3])), 8);
}
if ($drawPath[-2] > 1) { DebugPrint("polygon: drew outline using $drawPath[-2] line segs, aper $lastAperture\n", 5); }
return TRUE;
}
if ($drawPath[-1] eq "curve") #arc (bezier curve); arc or part of a circle, not a full circle
{