- Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathgcodeplot.py
More file actions
Latest commit
executable file
·1174 lines (1026 loc) · 43.3 KB
/
Copy pathgcodeplot.py
File metadata and controls
executable file
·1174 lines (1026 loc) · 43.3 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
#!/usr/bin/python
from __future__ importprint_function
importre
importsys
importgetopt
importmath
importxml.etree.ElementTreeasET
importgcodeplotutils.annealasanneal
importsvgpath.parserasparser
importcmath
fromrandomimportsample
fromsvgpath.shaderimportShader
fromgcodeplotutils.processoffsetimportOffsetProcessor
fromgcodeplotutils.evaluateimportevaluate
SCALE_NONE=0
SCALE_DOWN_ONLY=1
SCALE_FIT=2
ALIGN_NONE=0
ALIGN_BOTTOM=1
ALIGN_TOP=2
ALIGN_LEFT=ALIGN_BOTTOM
ALIGN_RIGHT=ALIGN_TOP
ALIGN_CENTER=3
classPlotter(object):
def__init__(self, xyMin=(7,8), xyMax=(204,178),
drawSpeed=35, moveSpeed=40, zSpeed=5, workZ=14.5, liftDeltaZ=2.5, safeDeltaZ=20,
liftCommand=None, safeLiftCommand=None, downCommand=None, comment=";",
initCode="G00 S1; endstops|"
"G00 E0; no extrusion|"
"G01 S1; endstops|"
"G01 E0; no extrusion|"
"G21; millimeters|"
"G91 G0 F%.1f{{zspeed*60}} Z%.3f{{safe}}; pen park !!Zsafe|"
"G90; absolute|"
"G28 X; home|"
"G28 Y; home|"
"G28 Z; home",
endCode=None):
self.xyMin=xyMin
self.xyMax=xyMax
self.drawSpeed=drawSpeed
self.moveSpeed=moveSpeed
self.workZ=workZ
self.liftDeltaZ=liftDeltaZ
self.safeDeltaZ=safeDeltaZ
self.zSpeed=zSpeed
self.liftCommand=liftCommand
self.safeLiftCommand=safeLiftCommand
self.downCommand=downCommand
self.initCode=initCode
self.endCode=endCode
self.comment=comment
definRange(self, point):
foriinrange(2):
ifpoint[i] <self.xyMin[i]-.001orpoint[i] >self.xyMax[i]+.001:
returnFalse
returnTrue
@property
defsafeUpZ(self):
returnself.workZ+self.safeDeltaZ
@property
defpenUpZ(self):
returnself.workZ+self.liftDeltaZ
defupdateVariables(self):
self.variables= {'lift':self.liftDeltaZ, 'work':self.workZ, 'safe':self.safeDeltaZ, 'left':self.xyMin[0],
'bottom':self.xyMin[1], 'zspeed':self.zSpeed, 'movespeed':self.moveSpeed}
self.formulas= {'right':str(self.xyMax[0]), 'top':str(self.xyMax[1]), 'up':'work+lift', 'park':'work+safe', 'centerx':'(left+right)/2.', 'centery':'(top+bottom)/2.'}
defprocessCode(code):
ifnotcode:
return []
data= []
pattern=r'\{\{([^}]+)\}\}'
data=tuple( evaluate(expr, plotter.variables, plotter.formulas) forexprinre.findall(pattern, code))
formatString=re.sub(pattern, '', code.replace('|', '\n'))
return [formatString%data]
defgcodeHeader(plotter):
returnprocessCode(plotter.initCode)
defisSameColor(rgb1, rgb2):
ifrgb1isNoneorrgb2isNone:
returnrgb1isrgb2
returnmax(abs(rgb1[i]-rgb2[i]) foriinrange(3)) <0.001
classPen(object):
def__init__(self, text):
text=re.sub(r'\s+', r' ', text.strip())
self.description=text
data=text.split(' ', 4)
iflen(data) <3:
raiseValueError('Pen parsing error')
iflen(data) <4:
data.append('')
self.pen=int(data[0])
self.offset=tuple(map(float, re.sub(r'[()]',r'',data[1]).split(',')))
self.color=parser.rgbFromColor(data[2])
self.name=data[3]
classScale(object):
def__init__(self, scale=(1.,1.), offset=(0.,0.)):
self.offset=offset
self.scale=scale
defclone(self):
returnScale(scale=[self.scale[0],self.scale[1]], offset=[self.offset[0],self.offset[1]])
def__repr__(self):
returnstr(self.scale)+','+str(self.offset)
deffit(self, plotter, xyMin, xyMax):
s= [0,0]
o= [0,0]
foriinrange(2):
delta=xyMax[i]-xyMin[i]
ifdelta==0:
s[i] =1.
else:
s[i] = (plotter.xyMax[i]-plotter.xyMin[i]) /delta
self.scale= [min(s),min(s)]
self.offset=list(plotter.xyMin[i] -xyMin[i]*self.scale[i] foriinrange(2))
defalign(self, plotter, xyMin, xyMax, align):
o= [0,0]
foriinrange(2):
ifalign[i] ==ALIGN_LEFT:
o[i] =plotter.xyMin[i] -self.scale[i]*xyMin[i]
elifalign[i] ==ALIGN_RIGHT:
o[i] =plotter.xyMax[i] -self.scale[i]*xyMax[i]
elifalign[i] ==ALIGN_NONE:
o[i] =self.offset[i] # self.xyMin[i]
elifalign[i] ==ALIGN_CENTER:
o[i] =0.5* (plotter.xyMin[i] -self.scale[i]*xyMin[i] +plotter.xyMax[i] -self.scale[i]*xyMax[i])
else:
raiseValueError()
self.offset=o
defscalePoint(self, point):
return (point[0]*self.scale[0]+self.offset[0], point[1]*self.scale[1]+self.offset[1])
defcomparison(a,b):
return1ifa>belse (-1ifa<belse0)
defsafeSorted(data,comparison=comparison):
"""
A simpleminded recursive merge sort that will work even if the comparison function fails to be a partial order.
Makes (shallow) copies of the data, which uses more memory than is absolutely necessary. In the intended application,
the comparison function is very expensive but the number of data points is small.
"""
n=len(data)
ifn<=1:
returnlist(data)
d1=safeSorted(data[:n//2],comparison=comparison)
d2=safeSorted(data[n//2:],comparison=comparison)
i1=0
i2=0
out= []
whilei1<len(d1) andi2<len(d2):
ifcomparison(d1[i1], d2[i2]) <0:
out.append(d1[i1])
i1+=1
else:
out.append(d2[i2])
i2+=1
ifi1<len(d1):
out+=d1[i1:]
elifi2<len(d2):
out+=d2[i2:]
returnout
defcomparePaths(path1,path2,tolerance=0.05,pointsToCheck=3):
"""
inner paths come before outer ones
closed paths come before open ones
otherwise, average left to right movement
"""
deffixPath(path):
out= [complex(point[0],point[1]) forpointinpath]
ifout[0] !=out[-1] andabs(out[0]-out[-1]) <=tolerance:
out.append(out[0])
returnout
defclosed(path):
returnpath[-1] ==path[0]
definside(z, path):
forpinpath:
ifp==z:
returnFalse
try:
phases=sorted((cmath.phase(p-z) forpinpath))
# make a ray that is relatively far away from any points
iflen(phases) ==1:
# should not happen
bestPhase=phases[0] +math.pi
else:
bestIndex=max( (phases[i+1]-phases[i],i) foriinrange(len(phases)-1))[1]
bestPhase= (phases[bestIndex+1]+phases[bestIndex])/2.
ray=cmath.rect(1., bestPhase)
rotatedPath=tuple((p-z) /rayforpinpath)
# now we just need to check shiftedPath's intersection with the positive real line
s=0
fori,p2inenumerate(rotatedPath):
p1=rotatedPath[i-1]
ifp1.imag==p2.imag:
# horizontal lines can't intersect positive real line once phase selection was done
continue
# (1/m)y + xIntercept = x
reciprocalSlope= (p2.real-p1.real)/(p2.imag-p1.imag)
xIntercept=p2.real-reciprocalSlope*p2.imag
ifxIntercept==0:
returnFalse# on boundary
ifp1.imag*p2.imag<0andxIntercept>0:
ifp1.imag<0:
s+=1
else:
s-=1
returns!=0
exceptOverflowError:
returnFalse
defnestedPaths(path1, path2):
ifnotclosed(path2):
returnFalse
k=min(pointsToCheck, len(path1))
forpointinsample(path1, k):
ifinside(point, path2):
returnTrue
returnFalse
path1=fixPath(path1)
path2=fixPath(path2)
ifnestedPaths(path1, path2):
return-1
elifnestedPaths(path2, path1):
return1
elifclosed(path1) andnotclosed(path2):
return-1
elifclosed(path2) andnotclosed(path1):
return1
x1=sum(p.realforpinpath1) /len(path1)
x2=sum(p.realforpinpath2) /len(path2)
returncomparison(x1,x2)
defremovePenBob(data):
"""
Merge segments with same beginning and end
"""
outData= {}
forpenindata:
outSegments= []
outSegment= []
forsegmentindata[pen]:
ifnotoutSegment:
outSegment=list(segment)
elifoutSegment[-1] ==segment[0]:
outSegment+=segment[1:]
else:
outSegments.append(outSegment)
outSegment=list(segment)
ifoutSegment:
outSegments.append(outSegment)
ifoutSegments:
outData[pen] =outSegments
returnoutData
defdedup(data):
curPoint=None
defd2(a,b):
return (a[0]-b[0])**2+(a[1]-b[1])**2
newData= {}
forpenindata:
newSegments= []
newSegment= []
draws=set()
forsegmentindata[pen]:
newSegment= [segment[0]]
foriinrange(1,len(segment)):
draw= (segment[i-1], segment[i])
ifdrawindrawsor (segment[i], segment[i-1]) indraws:
iflen(newSegment)>1:
newSegments.append(newSegment)
newSegment= [segment[i]]
else:
draws.add(draw)
newSegment.append(segment[i])
ifnewSegment:
newSegments.append(newSegment)
ifnewSegments:
newData[pen] =newSegments
returnremovePenBob(newData)
defdescribePen(pens, pen):
ifpensisnotNoneandpeninpens:
returnpens[pen].description
else:
returnstr(pen)
defpenColor(pens, pen):
ifpensisnotNoneandpeninpens:
returnpens[pen].color
else:
return (0.,0.,0.)
defemitGcode(data, pens= {}, plotter=Plotter(), scalingMode=SCALE_NONE, align=None, tolerance=0, gcodePause="@pause", pauseAtStart=False, simulation=False, relCode=False, incHoming=True):
iflen(data) ==0:
returnNone
xyMin= [float("inf"),float("inf")]
xyMax= [float("-inf"),float("-inf")]
allFit=True
scale=Scale()
scale.offset= (plotter.xyMin[0],plotter.xyMin[1])
forpenindata:
forsegmentindata[pen]:
forpointinsegment:
ifnotplotter.inRange(scale.scalePoint(point)):
allFit=False
foriinrange(2):
xyMin[i] =min(xyMin[i], point[i])
xyMax[i] =max(xyMax[i], point[i])
ifscalingMode==SCALE_NONE:
ifnotallFit:
sys.stderr.write("Drawing out of range: "+str(xyMin)+" "+str(xyMax)+"\n")
returnNone
elifscalingMode!=SCALE_DOWN_ONLYornotallFit:
ifxyMin[0] >xyMax[0]:
returnNone
scale=Scale()
scale.fit(plotter, xyMin, xyMax)
ifalignisnotNone:
scale.align(plotter, xyMin, xyMax, align)
ifnotsimulation:
gcode=gcodeHeader(plotter)
else:
gcode= []
gcode.append('<?xml version="1.0" standalone="yes"?>')
gcode.append('<svg width="%.4fmm" height="%.4fmm" viewBox="%.4f %.4f %.4f %.4f" xmlns="http://www.w3.org/2000/svg" version="1.1">'% (
plotter.xyMax[0]-plotter.xyMin[0], plotter.xyMax[1]-plotter.xyMin[0], plotter.xyMin[0], plotter.xyMin[1], plotter.xyMax[0], plotter.xyMax[1]))
defpark():
ifnotsimulation:
lift=plotter.safeLiftCommandorplotter.liftCommand
iflift:
gcode.extend(processCode(lift))
else:
ifrelCode:
gcode.append('G90 ;Absolute mode for Z movement')
gcode.append('G00 F%.1f Z%.3f; pen park !!Zpark'% (plotter.zSpeed*60., plotter.safeUpZ))
ifrelCode:
gcode.append('G91 ;Relative mode for XY movement')
park()
ifrelCode:
gcode.append('G91 ;Relative mode for XY movement')
ifnotsimulation:
gcode.append('G00 F%.1f Y%.3f; !!Ybottom'% (plotter.moveSpeed*60., plotter.xyMin[1]))
gcode.append('G00 F%.1f X%.3f; !!Xleft'% (plotter.moveSpeed*60., plotter.xyMin[0]))
classState(object):
pass
state=State()
state.time= (plotter.xyMin[1]+plotter.xyMin[0]) /plotter.moveSpeed
state.curXY=plotter.xyMin
state.curZ=plotter.safeUpZ
state.penColor= (0.,0.,0.)
defdistance(a,b):
returnmath.hypot(a[0]-b[0],a[1]-b[1])
defpenUp(force=False):
ifstate.curZisNoneorstate.curZnotin (plotter.safeUpZ, plotter.penUpZ) orforce:
ifnotsimulation:
ifplotter.liftCommand:
gcode.extend(processCode(plotter.liftCommand))
else:
gcode.append('G00 F%.1f Z%.3f; pen up !!Zup'% (plotter.zSpeed*60., plotter.penUpZ))
ifstate.curZisnotNone:
state.time+=abs(plotter.penUpZ-state.curZ) /plotter.zSpeed
state.curZ=plotter.penUpZ
defpenDown(force=False):
ifstate.curZisNoneorstate.curZ!=plotter.workZorforce:
ifnotsimulation:
ifplotter.downCommand:
gcode.extend(processCode(plotter.downCommand))
else:
ifrelCode:
gcode.append('G90 ;Absolute mode for Z movement')
gcode.append('G00 F%.1f Z%.3f; pen down !!Zwork'% (plotter.zSpeed*60., plotter.workZ))
ifrelCode:
gcode.append('G91 ;Relavite mode for XY-movement')
state.time+=abs(state.curZ-plotter.workZ) /plotter.zSpeed
state.curZ=plotter.workZ
defpenMove(down, speed, p, force=False):
defflip(y):
returnplotter.xyMax[1] - (y-plotter.xyMin[1])
ifstate.curXYisNone:
d=float("inf")
else:
d=distance(state.curXY, p)
ifd>toleranceorforce:
ifdown:
penDown(force=force)
else:
penUp(force=force)
ifnotsimulation:
x=p[0]
y=p[1]
ifrelCode:
x-=state.curXY[0]
y-=state.curXY[1]
gcode.append('G0%d F%.1f X%.3f Y%.3f; %s !!Xleft+%.3f Ybottom+%.3f'% (
1ifdownelse0, speed*60., x, y, "draw"ifdownelse"move",
p[0]-plotter.xyMin[0], p[1]-plotter.xyMin[1]))
else:
start=state.curXYifstate.curXYisnotNoneelseplotter.xyMin
color= [int(math.floor(255*x+0.5)) forxin (state.penColorifdownelse (0,0.5,0))]
thickness=0.15ifdownelse0.1
end=complex(p[0], flip(p[1]))
gcode.append('<line x1="%.3f" y1="%.3f" x2="%.3f" y2="%.3f" stroke="rgb(%d,%d,%d)" stroke-width="%.2f"/>'
% (start[0], flip(start[1]), end.real, end.imag, color[0], color[1], color[2], thickness))
ray=end-complex(start[0],flip(start[1]))
ifabs(ray)>0:
ray=ray/abs(ray)
forthetain [math.pi*0.8,-math.pi*0.8]:
head=end+ray*cmath.rect(max(0.3,min(2,d*0.25)), theta)
gcode.append('<line x1="%.3f" y1="%.3f" x2="%.3f" y2="%.3f" stroke="rgb(0,128,0)" stroke-linejoin="round" stroke-width="0.1"/>'
% (end.real, end.imag, head.real, head.imag))
ifstate.curXYisnotNone:
state.time+=d/speed
state.curXY=p
forpeninsorted(data):
ifpen!=1:
state.curZ=None
state.curXY=None
state.penColor=penColor(pens, pen)
s=scale.clone()
ifpensisnotNoneandpeninpens:
s.offset= (s.offset[0]-pens[pen].offset[0],s.offset[1]-pens[pen].offset[1])
newPen=True
forsegmentindata[pen]:
penMove(False, plotter.moveSpeed, s.scalePoint(segment[0]))
ifnewPenand (pen!=1orpauseAtStart) andnotsimulation:
gcode.append( gcodePause+' load pen: '+describePen(pens,pen) )
penMove(False, plotter.moveSpeed, s.scalePoint(segment[0]), force=True)
newPen=False
foriinrange(1,len(segment)):
penMove(True, plotter.drawSpeed, s.scalePoint(segment[i]))
park()
ifsimulation:
gcode.append('</svg>')
else:
gcode.extend(processCode(plotter.endCode))
ifnotquiet:
sys.stderr.write('Estimated printing time: %dm %.1fs\n'% (state.time//60, state.time%60))
sys.stderr.flush()
returngcode
defparseHPGL(hpgl,dpi=(1016.,1016.)):
try:
scale= (25.4/dpi[0], 25.4/dpi[1])
except:
scale= (25.4/dpi, 25.4/dpi)
segment= []
pen=1
data= {pen:[]}
forcmdinre.sub(r'\s', r'', hpgl).split(';'):
ifcmd.startswith('PD'):
try:
coords=list(map(float, cmd[2:].split(',')))
foriinrange(0,len(coords),2):
segment.append((coords[i]*scale[0], coords[i+1]*scale[1]))
except:
pass
# ignore no-movement PD/PU
elifcmd.startswith('PU'):
try:
ifsegment:
data[pen].append(segment)
coords=list(map(float, cmd[2:].split(',')))
segment= [(coords[-2]*scale[0], coords[-1]*scale[1])]
except:
pass
# ignore no-movement PD/PU
elifcmd.startswith('SP'):
ifsegment:
data[pen].append(segment)
segment= []
pen=int(cmd[2:])
ifpennotindata:
data[pen] = []
elifcmd.startswith('IN'):
pass
eliflen(cmd) >0:
sys.stderr.write('Unknown command '+cmd[:2]+'\n')
ifsegment:
data[pen].append(segment)
returndata
defemitHPGL(data, pens=None):
defhpglCoordinates(offset,point):
x= (point[0]-offset[0]) *1016./25.4
y= (point[1]-offset[1]) *1016./25.4
returnstr(int(round(x)))+','+str(int(round(y)))
hpgl= []
hpgl.append('IN')
forpeninsorted(data):
ifpensisnotNoneandpeninpens:
offset=pens[pen].offset
else:
offset= (0.,0.)
hpgl.append('SP'+str(pen))
forsegmentindata[pen]:
hpgl.append('PU'+hpglCoordinates(offset,segment[0]))
foriinrange(1,len(segment)):
hpgl.append('PD'+hpglCoordinates(offset,segment[i]))
hpgl.append('PU')
hpgl.append('')
return';'.join(hpgl)
defgetPen(pens, color):
ifpensisNone:
return1
ifcolorisNone:
color= (0.,0.,0.)
bestD2=10
bestPen=1
forpinpens:
c=pens[p].color
d2= (c[0]-color[0])**2+(c[1]-color[1])**2+(c[2]-color[2])**2
ifd2<bestD2:
bestPen=p
bestD2=d2
returnbestPen
defparseSVG(svgTree, tolerance=0.05, shader=None, strokeAll=False, pens=None, extractColor=None):
data= {}
forpathinparser.getPathsFromSVG(svgTree)[0]:
lines= []
stroke=strokeAllor (path.svgState.strokeisnotNoneand (extractColorisNoneorisSameColor(path.svgState.stroke, extractColor)))
strokePen=getPen(pens, path.svgState.stroke)
ifstrokePennotindata:
data[strokePen] = []
forlineinpath.linearApproximation(error=tolerance):
ifstroke:
data[strokePen].append([(line.start.real,line.start.imag),(line.end.real,line.end.imag)])
lines.append((line.start, line.end))
ifnotdata[strokePen]:
deldata[strokePen]
ifshaderisnotNoneandshader.isActive() andpath.svgState.fillisnotNoneand (extractColorisNoneor
isSameColor(path.svgState.fill, extractColor)):
pen=getPen(pens, path.svgState.fill)
ifpennotindata:
data[pen] = []
grayscale=sum(path.svgState.fill) /3.
mode=Shader.MODE_NONZEROifpath.svgState.fillRule=='nonzero'elseShader.MODE_EVEN_ODD
ifpath.svgState.fillOpacityisnotNone:
grayscale=grayscale*path.svgState.fillOpacity+1.-path.svgState.fillOpacity# TODO: real alpha!
fillLines=shader.shade(lines, grayscale, avoidOutline=(path.svgState.strokeisNoneorstrokePen!=pen), mode=mode)
forlineinfillLines:
data[pen].append([(line[0].real,line[0].imag),(line[1].real,line[1].imag)])
ifnotdata[pen]:
deldata[pen]
returndata
defgetConfigOpts(filename):
opts= []
withopen(filename) asf:
forlineinf:
l=line.strip()
iflen(l) andl[0] !='#':
entry=l.split('=', 2)
opt=entry[0]
iflen(opt) ==1:
opt='-'+opt
elifopt[0] !='-':
opt='--'+opt
iflen(entry) >1:
arg=entry[1]
ifarg[0] in ('"', "'"):
arg=arg[1:-1]
else:
arg=None
opts.append( (opt,arg) )
returnopts
defdirectionalize(paths, angle, tolerance=1e-10):
vector= (math.cos(angle*math.pi/180.), math.sin(angle*math.pi/180.))
outPaths= []
forpathinpaths:
startIndex=0
prevPoint=path[0]
canBeForward=True
canBeReversed=True
i=1
whilei<len(path):
curVector= (path[i][0]-prevPoint[0],path[i][1]-prevPoint[1])
ifcurVector[0] orcurVector[1]:
dotProduct=curVector[0]*vector[0] +curVector[1]*vector[1]
ifdotProduct>tolerance:
ifnotcanBeForward:
outPaths.append(list(reversed(path[startIndex:i])))
startIndex=i-1
canBeForward=True
canBeReversed=False
elifdotProduct<-tolerance:
ifnotcanBeReversed:
outPaths.append(path[startIndex:i])
startIndex=i-1
canBeReversed=True
canBeForward=False
prevPoint=path[i]
i+=1
ifcanBeForward:
outPaths.append(path[startIndex:i])
else:
outPaths.append(list(reversed(path[startIndex:i])))
returnoutPaths
deffixComments(plotter, data, comment=";"):
ifcomment==";":
returndata
out= []
forcommandindata:
forlineincommand.split('\n'):
try:
ind=line.index(";")
ifind>=0:
ifnotcomment:
out.append( line[:ind].strip() )
else:
out.append( line[:ind] +comment[0] +line[ind+1:] +comment[1:] )
else:
out.append(line)
exceptValueError:
out.append(line)
returnout
if__name__=='__main__':
defhelp(error=False):
iferror:
output=sys.stderr
else:
output=sys.stdout
output.write("gcodeplot.py [options] [inputfile [> output.gcode]\n")
output.write("""
--dump-options: show current settings instead of doing anything
-h|--help: this
-r|--allow-repeats*: do not deduplicate paths
-f|--scale=mode: scaling option: none(n), fit(f), down-only(d) [default none; other options don't work with tool-offset]
-D|--input-dpi=xdpi[,ydpi]: hpgl dpi
-t|--tolerance=x: ignore (some) deviations of x millimeters or less [default 0.05]
-s|--send=port*: send gcode to serial port instead of stdout
-S|--send-speed=baud: set baud rate for sending
-x|--align-x=mode: horizontal alignment: none(n), left(l), right(r) or center(c)
-y|--align-y=mode: vertical alignment: none(n), bottom(b), top(t) or center(c)
-a|--area=x1,y1,x2,y2: gcode print area in millimeters
-Z|--lift-delta-z=z: amount to lift for pen-up (millimeters)
-z|--work-z=z: z-position for drawing (millimeters)
-F|--pen-up-speed=z: speed for moving with pen up (millimeters/second)
-f|--pen-down-speed=z: speed for moving with pen down (millimeters/second)
-u|--z-speed=s: speed for up/down movement (millimeters/second)
-H|--hpgl-out*: output is HPGL, not gcode; most options ignored [default: off]
-T|--shading-threshold=n: darkest grayscale to leave unshaded (decimal, 0. to 1.; set to 0 to turn off SVG shading) [default 1.0]
-m|--shading-lightest=x: shading spacing for lightest colors (millimeters) [default 3.0]
-M|--shading-darkest=x: shading spacing for darkest color (millimeters) [default 0.5]
-A|--shading-angle=x: shading angle (degrees) [default 45]
-X|--shading-crosshatch*: cross hatch shading
-L|--stroke-all*: stroke even regions specified by SVG to have no stroke
-O|--shading-avoid-outline*: avoid going over outline twice when shading
-o|--optimization-time=t: max time to spend optimizing (seconds; set to 0 to turn off optimization) [default 60]
-e|--direction=angle: for slanted pens: prefer to draw in given direction (degrees; 0=positive x, 90=positive y, none=no preferred direction) [default none]
-d|--sort*: sort paths from inside to outside for cutting [default off]
-c|--config-file=filename: read arguments, one per line, from filename
-w|--gcode-pause=cmd: gcode pause command [default: @pause]
-P|--pens=penfile: read output pens from penfile
-U|--pause-at-start*: pause at start (can be included without any input file to manually move stuff)
-R|--extract-color=c: extract color (specified in SVG format , e.g., rgb(1,0,0) or #ff0000 or red)
--comment-delimiters=xy: one or two characters specifying comment delimiters, e.g., ";" or "()"
--tool-offset=x: cutting tool offset (millimeters) [default 0.0]
--overcut=x: overcut (millimeters) [default 0.0]
--lift-command=gcode: gcode lift command (separate lines with |)
--down-command=gcode: gcode down command (separate lines with |)
--init-code=gcode: gcode init commands (separate lines with |)
The options with an asterisk are default off and can be turned off again by adding "no-" at the beginning to the long-form option, e.g., --no-stroke-all or --no-send.
""")
tolerance=0.05
doDedup=True
sendPort=None
sendSpeed=115200
hpglLength=279.4
scalingMode=SCALE_NONE
shader=Shader()
align= [ALIGN_NONE, ALIGN_NONE]
plotter=Plotter()
hpglOut=False
strokeAll=False
extractColor=None
gcodePause="@pause"
optimizationTime=30
dpi= (1016., 1016.)
pens= {1:Pen('1 (0.,0.) black default')}
doDump=False
penFilename=None
pauseAtStart=False
sortPaths=False
svgSimulation=False
toolOffset=0.
overcut=0.
toolMode="custom"
booleanExtractColor=False
quiet=False
comment=";"
sendAndSave=False
directionAngle=None
relCode=False
incHoming=True
defmaybeNone(a):
returnNoneifa=='none'elsea
try:
opts, args=getopt.getopt(sys.argv[1:], "e:UR:Uhdulw:P:o:Oc:LT:M:m:A:XHrf:na:D:t:s:S:x:y:z:Z:p:f:F:",
["help", "down", "up", "lower-left", "allow-repeats", "no-allow-repeats", "scale=", "config-file=",
"area=", 'align-x=', 'align-y=', 'optimization-time=', "pens=",
'input-dpi=', 'tolerance=', 'send=', 'send-speed=', 'work-z=', 'lift-delta-z=', 'safe-delta-z=',
'pen-down-speed=', 'pen-up-speed=', 'z-speed=', 'hpgl-out', 'no-hpgl-out', 'shading-threshold=',
'shading-angle=', 'shading-crosshatch', 'no-shading-crosshatch', 'shading-avoid-outline',
'pause-at-start', 'no-pause-at-start', 'min-x=', 'max-x=', 'min-y=', 'max-y=',
'no-shading-avoid-outline', 'shading-darkest=', 'shading-lightest=', 'stroke-all', 'no-stroke-all', 'gcode-pause', 'dump-options', 'tab=', 'extract-color=', 'sort', 'no-sort', 'simulation', 'no-simulation', 'tool-offset=', 'overcut=',
'boolean-shading-crosshatch=', 'boolean-sort=', 'tool-mode=', 'send-and-save=', 'direction=', 'lift-command=', 'down-command=',
'init-code=', 'comment-delimiters=', 'end-code=', 'rel-code=' ], )
iflen(args) +len(opts) ==0:
raisegetopt.GetoptError("invalid commandline")
i=0
whilei<len(opts):
opt,arg=opts[i]
ifoptin ('-r', '--allow-repeats'):
doDedup=False
elifopt=='--no-allow-repeats':
doDedup=True
elifoptin ('-w', '--gcode-pause'):
gcodePause=arg
elifoptin ('-p', '--pens'):
pens= {}
penFilename=arg
withopen(arg) asf:
forlineinf:
ifline.strip():
p=Pen(line)
pens[p.pen] =p
elifoptin ('-f', '--scale'):
arg=arg.lower()
ifarg.startswith('n'):
scalingMode=SCALE_NONE
elifarg.startswith('d'):
scalingMode=SCALE_DOWN_ONLY
elifarg.startswith('f'):
scalingMode=SCALE_FIT
elifoptin ('-x', '--align-x'):
arg=arg.lower()
ifarg.startswith('l'):
align[0] =ALIGN_LEFT
elifarg.startswith('r'):
align[0] =ALIGN_RIGHT
elifarg.startswith('c'):
align[0] =ALIGN_CENTER
elifarg.startswith('n'):
align[0] =ALIGN_NONE
else:
raiseValueError()
elifoptin ('-y', '--align-y'):
arg=arg.lower()
ifarg.startswith('b'):
align[1] =ALIGN_LEFT
elifarg.startswith('t'):
align[1] =ALIGN_RIGHT
elifarg.startswith('c'):
align[1] =ALIGN_CENTER
elifarg.startswith('n'):
align[1] =ALIGN_NONE
else:
raiseValueError()
elifoptin ('-t', '--tolerance'):
tolerance=float(arg)
elifoptin ('-s', '--send'):
sendPort=Noneiflen(arg.strip()) ==0elsearg
elifopt=='--send-and-save':
sendPort=Noneiflen(arg.strip()) ==0elsearg
ifsendPortisnotNone:
sendAndSave=True
elifopt=='--no-send':
sendPort=None
elifoptin ('-S', '--send-speed'):
sendSpeed=int(arg)
elifoptin ('-a', '--area'):
v=list(map(float, arg.split(',')))
plotter.xyMin= (v[0],v[1])
plotter.xyMax= (v[2],v[3])
elifopt=='--min-x':
plotter.xyMin= (float(arg),plotter.xyMin[1])
elifopt=='--min-y':
plotter.xyMin= (plotter.xyMin[0],float(arg))
elifopt=='--max-x':
plotter.xyMax= (float(arg),plotter.xyMax[1])
elifopt=='--max-y':
plotter.xyMax= (plotter.xyMax[0],float(arg))
elifoptin ('-D', '--input-dpi'):
v=list(map(float, arg.split(',')))
iflen(v) >1:
dpi=v[0:2]
else:
dpi= (v[0],v[0])
elifoptin ('-Z', '--lift-delta-z'):
plotter.liftDeltaZ=float(arg)
elifoptin ('-z', '--work-z'):
plotter.workZ=float(arg)
elifopt=='--tool-offset':
toolOffset=float(arg)
elifopt=='--overcut':
overcut=float(arg)
elifoptin ('-p', '--safe-delta-z'):
plotter.safeDeltaZ=float(arg)
elifoptin ('-F', '--pen-up-speed'):
plotter.moveSpeed=float(arg)
elifoptin ('-f', '--pen-down-speed'):
plotter.drawSpeed=float(arg)
elifoptin ('-u', '--z-speed'):
plotter.zSpeed=float(arg)
elifoptin ('-H', '--hpgl-out'):
hpglOut=True
elifopt=='--no-hpgl-out':
hpglOut=False
elifoptin ('-T', '--shading-threshold'):
shader.unshadedThreshold=float(arg)
elifoptin ('-m', '--shading-lightest'):
shader.lightestSpacing=float(arg)
elifoptin ('-M', '--shading-darkest'):
shader.darkestSpacing=float(arg)
elifoptin ('-A', '--shading-angle'):
shader.angle=float(arg)
elifopt=='--boolean-shading-crosshatch':
shader.crossHatch=arg.strip() !='false'
elifopt=='--boolean-sort':
sort=arg.strip() !='false'
elifoptin ('-X', '--shading-crosshatch'):
shader.crossHatch=True
elifopt=='--no-shading-crosshatch':
shader.crossHatch=False
elifoptin ('-O', '--shading-avoid-outline'):
avoidOutline=True
elifopt=='--no-shading-avoid-outline':
avoidOutline=False
elifopt=='--no-shading-crosshatch':
shader.crossHatch=False
elifopt=='--pause-at-start':
pauseAtStart=True
elifopt=='--no-pause-at-start':
pauseAtStart=False
elifoptin ('-L', '--stroke-all'):
strokeAll=True
elifopt=='--no-stroke-all':
strokeAll=False
elifoptin ('-c', '--config-file'):
configOpts=getConfigOpts(arg)
opts=opts[:i+1] +configOpts+opts[i+1:]
elifoptin ('-o', '--optimization-time'):
optimizationTime=float(arg)
ifoptimizationTime>0:
sort=False
elifoptin ('-h', '--help'):
help()
sys.exit(0)
elifopt=='--dump-options':
doDump=True
elifoptin ('-R', '--extract-color'):
arg=arg.lower()
ifarg=='all'orlen(arg.strip())==0:
extractColor=None
else:
extractColor=parser.rgbFromColor(arg)
elifoptin ('-d', '--sort'):
sortPaths=True
optimizationTime=0
elifopt=='--no-sort':
sortPaths=False
elifoptin ('U', '--simulation'):
svgSimulation=True
elifopt=='--no-simulation':
svgSimulation=False
elifopt=='--tab':
quiet=True# Inkscape
elifopt=="--tool-mode":
toolMode=arg
elifoptin ('e', '--direction'):
iflen(arg.strip()) ==0orarg=='none':
directionAngle=None
else:
directionAngle=float(arg)
elifopt=='--lift-command':
plotter.liftCommand=maybeNone(arg)
elifopt=='--down-command':
plotter.downCommand=maybeNone(arg)
elifopt=='--init-code':
plotter.initCode=maybeNone(arg)
elifopt=='--end-code':
plotter.endCode=maybeNone(arg)
elifopt=='--comment-delimiters':
plotter.comment=maybeNone(arg)
elifopt=="--rel-code":
relCode=arg=="true"
elifopt=="--inc-homing":
incHoming=arg=="true"
else:
raiseValueError("Unrecognized argument "+opt+" "+arg)
i+=1
exceptgetopt.GetoptErrorase:
sys.stderr.write(str(e)+"\n")
help(error=True)
sys.exit(2)
ifdoDump:
print('no-allow-repeats'ifdoDedupelse'allow-repeats')