forked from ChrisWag91/Inkscape-Lasertools-Plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlasertools.py
1924 lines (1571 loc) · 80.2 KB
/
lasertools.py
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/env python
"""
Modified by Christoph Wagner 2017
based on gcodetools, https://github.com/cnc-club/gcodetools
based on inkscape-applytransforms, https://github.com/Klowner/inkscape-applytransforms
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
import inkex
import simplestyle
import simplepath
import cubicsuperpath
import bezmisc
import simpletransform
from simpletransform import composeTransform, fuseTransform, parseTransform, applyTransformToPath, applyTransformToPoint, formatTransform
from multiprocessing import Pool
import cProfile
import sys
sys.path.append('/usr/share/inkscape/extensions')
import os
import math
import re
import time
import datetime
import cmath
import numpy as np
import gettext
_ = gettext.gettext
if "errormsg" not in dir(inkex):
inkex.errormsg = lambda msg: sys.stderr.write(
(str(msg) + "\n").encode("UTF-8"))
################################################################################
# Styles and additional parameters
################################################################################
gcode = ""
noOfThreads = 4
csp = []
profiling = False # Disable if not debugging
debug = False # Disable if not debugging
if profiling:
import lsprofcalltree
timestamp = datetime.datetime.now()
math.pi2 = math.pi*2
tiny_infill_factor = 2 # x times the laser beam width will be removed
straight_tolerance = 0.000001
engraving_tolerance = 0.000002
options = {}
cspm = []
offset_y = 0
defaults = {
'header': """
M03 S1
G90
""",
'footer': """G00 X0 Y0
M05 S0
M02
"""
}
styles = {
"biarc_style": {
'line': simplestyle.formatStyle({'stroke': '#f88', 'fill': 'none', "marker-end": 'none', 'stroke-width': '0.1'}),
'biarc1': simplestyle.formatStyle({'stroke': '#8f8', 'fill': 'none', "marker-end": 'none', 'stroke-width': '0.5'})
}
}
################################################################################
# Cubic Super Path additional functions
################################################################################
'''
def checkIfLineInsideShape(splitted_line):
# check if the middle point of the first lines segment is inside the path.
# and remove the subline if not.
l1, l2 = splitted_line[0], splitted_line[1]
p = [(l1[0]+l2[0])/2, (l1[1]+l2[1])/2]
# check for tangential points
pMod = [(l1[0]+l2[0])/2, ((l1[1]+l2[1])/2) + 0.1]
if l1 != l2:
if point_inside_csp(p, csp):
if point_inside_csp(pMod, csp):
if len(splitted_line) == 2:
return splitted_line
else:
return [splitted_line[0], splitted_line[1]]
else:
print_debug("splitted_line removed: ", splitted_line)
return [[0, 0], [0, 0]]
else:
return [[0, 0], [0, 0]]
else:
return [[0, 0], [0, 0]]
'''
def checkIfLineInsideShape(splitted_line):
# print_("sl input", splitted_line)
# check if the middle point of the first lines segment is inside the path.
# and remove the subline if not.
l1, l2 = splitted_line[0], splitted_line[1]
if l1 == l2 and len(splitted_line) > 2:
l2 = splitted_line[2]
p = [(l1[0]+l2[0])/2, (l1[1]+l2[1])/2]
if point_inside_csp(p, csp):
if len(splitted_line) > 2:
print_debug("len splitted line > 2", splitted_line)
# if l1 == l2 and len(splitted_line) > 2:
# l2 = splitted_line[2]
if l1 != l2:
print_debug("splitted line ", [l1, l2])
return [l1, l2]
else:
return [[0, 0], [0, 0]]
else:
return [[0, 0], [0, 0]]
def csp_segment_to_bez(sp1, sp2):
return sp1[1:]+sp2[:2]
def csp_true_bounds(csp):
# Finds minx,miny,maxx,maxy of the csp and return their (x,y,i,j,t)
minx = [float("inf"), 0, 0, 0]
maxx = [float("-inf"), 0, 0, 0]
miny = [float("inf"), 0, 0, 0]
maxy = [float("-inf"), 0, 0, 0]
for i in range(len(csp)):
for j in range(1, len(csp[i])):
ax, ay, bx, by, cx, cy, x0, y0 = bezmisc.bezierparameterize(
(csp[i][j-1][1], csp[i][j-1][2], csp[i][j][0], csp[i][j][1]))
roots = cubic_solver(0, 3*ax, 2*bx, cx) + [0, 1]
for root in roots:
if type(root) is complex and abs(root.imag) < 1e-10:
root = root.real
if type(root) is not complex and 0 <= root <= 1:
y = ay*(root**3)+by*(root**2)+cy*root+y0
x = ax*(root**3)+bx*(root**2)+cx*root+x0
maxx = max([x, y, i, j, root], maxx)
minx = min([x, y, i, j, root], minx)
roots = cubic_solver(0, 3*ay, 2*by, cy) + [0, 1]
for root in roots:
if type(root) is complex and root.imag == 0:
root = root.real
if type(root) is not complex and 0 <= root <= 1:
y = ay*(root**3)+by*(root**2)+cy*root+y0
x = ax*(root**3)+bx*(root**2)+cx*root+x0
maxy = max([y, x, i, j, root], maxy)
miny = min([y, x, i, j, root], miny)
maxy[0], maxy[1] = maxy[1], maxy[0]
miny[0], miny[1] = miny[1], miny[0]
return minx, miny, maxx, maxy
def csp_at_t(sp1, sp2, t):
ax, bx, cx, dx = sp1[1][0], sp1[2][0], sp2[0][0], sp2[1][0]
ay, by, cy, dy = sp1[1][1], sp1[2][1], sp2[0][1], sp2[1][1]
x1, y1 = ax+(bx-ax)*t, ay+(by-ay)*t
x2, y2 = bx+(cx-bx)*t, by+(cy-by)*t
x3, y3 = cx+(dx-cx)*t, cy+(dy-cy)*t
x4, y4 = x1+(x2-x1)*t, y1+(y2-y1)*t
x5, y5 = x2+(x3-x2)*t, y2+(y3-y2)*t
x, y = x4+(x5-x4)*t, y4+(y5-y4)*t
return [x, y]
def cspseglength(sp1, sp2, tolerance=0.0001):
bez = (sp1[1][:], sp1[2][:], sp2[0][:], sp2[1][:])
return bezmisc.bezierlength(bez, tolerance)
def csp_line_intersection(l1, l2, sp1, sp2):
dd = l1[0]
cc = l2[0]-l1[0]
bb = l1[1]
aa = l2[1]-l1[1]
if aa == cc == 0:
return []
if aa:
coef1 = cc/aa
coef2 = 1
else:
coef1 = 1
coef2 = aa/cc
bez = (sp1[1][:], sp1[2][:], sp2[0][:], sp2[1][:])
ax, ay, bx, by, cx, cy, x0, y0 = bezmisc.bezierparameterize(bez)
a = coef1*ay-coef2*ax
b = coef1*by-coef2*bx
c = coef1*cy-coef2*cx
d = coef1*(y0-bb)-coef2*(x0-dd)
roots = cubic_solver(a, b, c, d)
retval = []
for i in roots:
if type(i) is complex and abs(i.imag) < 1e-7:
i = i.real
if type(i) is not complex and -1e-10 <= i <= 1.+1e-10:
retval.append(i)
return retval
# Return only points [ (x,y) ]
def line_line_intersection_points(p1, p2, p3, p4):
if (p1[0] == p2[0] and p1[1] == p2[1]) or (p3[0] == p4[0] and p3[1] == p4[1]):
return []
x = (p2[0]-p1[0])*(p4[1]-p3[1]) - (p2[1]-p1[1])*(p4[0]-p3[0])
if x == 0: # Lines are parallel
if (p3[0]-p1[0])*(p2[1]-p1[1]) == (p3[1]-p1[1])*(p2[0]-p1[0]):
if p3[0] != p4[0]:
t11 = (p1[0]-p3[0])/(p4[0]-p3[0])
t12 = (p2[0]-p3[0])/(p4[0]-p3[0])
t21 = (p3[0]-p1[0])/(p2[0]-p1[0])
t22 = (p4[0]-p1[0])/(p2[0]-p1[0])
else:
t11 = (p1[1]-p3[1])/(p4[1]-p3[1])
t12 = (p2[1]-p3[1])/(p4[1]-p3[1])
t21 = (p3[1]-p1[1])/(p2[1]-p1[1])
t22 = (p4[1]-p1[1])/(p2[1]-p1[1])
res = []
if (0 <= t11 <= 1 or 0 <= t12 <= 1) and (0 <= t21 <= 1 or 0 <= t22 <= 1):
if 0 <= t11 <= 1:
res += [p1]
if 0 <= t12 <= 1:
res += [p2]
if 0 <= t21 <= 1:
res += [p3]
if 0 <= t22 <= 1:
res += [p4]
return res
else:
return []
else:
t1 = ((p4[0]-p3[0])*(p1[1]-p3[1]) - (p4[1]-p3[1])*(p1[0]-p3[0]))/x
t2 = ((p2[0]-p1[0])*(p1[1]-p3[1]) - (p2[1]-p1[1])*(p1[0]-p3[0]))/x
if 0 <= t1 <= 1 and 0 <= t2 <= 1:
return [[p1[0]*(1-t1)+p2[0]*t1, p1[1]*(1-t1)+p2[1]*t1]]
else:
return []
def point_to_point_d2(a, b):
return (a[0]-b[0])**2 + (a[1]-b[1])**2
def point_to_point_d(a, b):
return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)
def csp_normalized_slope(sp1, sp2, t):
ax, ay, bx, by, cx, cy = bezmisc.bezierparameterize(
(sp1[1][:], sp1[2][:], sp2[0][:], sp2[1][:]))[0:6]
if sp1[1] == sp2[1] == sp1[2] == sp2[0]:
return [1., 0.]
f1x = 3*ax*t*t+2*bx*t+cx
f1y = 3*ay*t*t+2*by*t+cy
if abs(f1x*f1x+f1y*f1y) > 1e-20:
l = math.sqrt(f1x*f1x+f1y*f1y)
return [f1x/l, f1y/l]
if t == 0:
f1x = sp2[0][0]-sp1[1][0]
f1y = sp2[0][1]-sp1[1][1]
if abs(f1x*f1x+f1y*f1y) > 1e-20:
l = math.sqrt(f1x*f1x+f1y*f1y)
return [f1x/l, f1y/l]
else:
f1x = sp2[1][0]-sp1[1][0]
f1y = sp2[1][1]-sp1[1][1]
if f1x*f1x+f1y*f1y != 0:
l = math.sqrt(f1x*f1x+f1y*f1y)
return [f1x/l, f1y/l]
elif t == 1:
f1x = sp2[1][0]-sp1[2][0]
f1y = sp2[1][1]-sp1[2][1]
if abs(f1x*f1x+f1y*f1y) > 1e-20:
l = math.sqrt(f1x*f1x+f1y*f1y)
return [f1x/l, f1y/l]
else:
f1x = sp2[1][0]-sp1[1][0]
f1y = sp2[1][1]-sp1[1][1]
if f1x*f1x+f1y*f1y != 0:
l = math.sqrt(f1x*f1x+f1y*f1y)
return [f1x/l, f1y/l]
else:
return [1., 0.]
def csp_normalized_normal(sp1, sp2, t):
nx, ny = csp_normalized_slope(sp1, sp2, t)
return [-ny, nx]
def csp_parameterize(sp1, sp2):
return bezmisc.bezierparameterize(csp_segment_to_bez(sp1, sp2))
def csp_draw(csp, color="#05f", group=None, style="fill:none;", width=.1, comment=""):
if csp != [] and csp != [[]]:
if group == None:
group = options.doc_root
style += "stroke:"+color+";" + "stroke-width:%0.4fpx;" % width
args = {"d": cubicsuperpath.formatPath(csp), "style": style}
if comment != "":
args["comment"] = str(comment)
inkex.etree.SubElement(group, inkex.addNS('path', 'svg'), args)
def csp_subpath_line_to(subpath, points):
# Appends subpath with line or polyline.
if len(points) > 0:
if len(subpath) > 0:
subpath[-1][2] = subpath[-1][1][:]
if type(points[0]) == type([1, 1]):
for p in points:
subpath += [[p[:], p[:], p[:]]]
else:
subpath += [[points, points, points]]
return subpath
################################################################################
# Area Fill Stuff
################################################################################
def point_inside_csp(p, csp, on_the_path=True):
x, y = p
ray_intersections_count = 0
for subpath in csp:
for i in range(1, len(subpath)):
sp1, sp2 = subpath[i-1], subpath[i]
ax, bx, cx, dx = csp_parameterize(sp1, sp2)[::2]
if ax == 0 and bx == 0 and cx == 0 and dx == x:
# we've got a special case here
b = csp_true_bounds([[sp1, sp2]])
if b[1][1] <= y <= b[3][1]:
# points is on the path
return on_the_path
else:
# we can skip this segment because it wont influence the answer.
pass
else:
for t in csp_line_intersection([x, y], [x, y+5], sp1, sp2):
if t == 0 or t == 1:
# we've got another special case here
y1 = csp_at_t(sp1, sp2, t)[1]
if y1 == y:
# the point is on the path
return on_the_path
# if t == 0 we sould have considered this case previously.
if t == 1:
# we have to check the next segmant if it is on the same side of the ray
st_d = csp_normalized_slope(sp1, sp2, 1)[0]
if st_d == 0:
st_d = csp_normalized_slope(sp1, sp2, 0.99)[0]
for j in range(1, len(subpath)+1):
if (i+j) % len(subpath) == 0:
continue # skip the closing segment
sp11, sp22 = subpath[(
i-1+j) % len(subpath)], subpath[(i+j) % len(subpath)]
ax1, bx1, cx1, dx1 = csp_parameterize(
sp1, sp2)[::2]
if ax1 == 0 and bx1 == 0 and cx1 == 0 and dx1 == x:
continue # this segment parallel to the ray, so skip it
en_d = csp_normalized_slope(sp11, sp22, 0)[0]
if en_d == 0:
en_d = csp_normalized_slope(
sp11, sp22, 0.01)[0]
if st_d*en_d <= 0:
ray_intersections_count += 1
break
else:
y1 = csp_at_t(sp1, sp2, t)[1]
if y1 == y:
# the point is on the path
return on_the_path
else:
if y1 > y and 3*ax*t**2 + 2*bx*t + cx != 0: # if it's 0 the path only touches the ray
ray_intersections_count += 1
return ray_intersections_count % 2 == 1
def csp_from_polyline(line):
return [[[point[:] for _ in range(3)] for point in subline] for subline in line]
'''
def csp_close_all_subpaths(csp, tolerance=0.000001):
for i in range(len(csp)):
if point_to_point_d2(csp[i][0][1], csp[i][-1][1]) > tolerance**2:
csp[i][-1][2] = csp[i][-1][1][:]
csp[i] += [[csp[i][0][1][:] for _ in range(3)]]
else:
if csp[i][0][1] != csp[i][-1][1]:
csp[i][-1][1] = csp[i][0][1][:]
return csp
'''
################################################################################
# Some vector functions
################################################################################
def normalize(x, y):
l = math.sqrt(x**2+y**2)
if l == 0:
return [0., 0.]
else:
return [x/l, y/l]
def cross(a, b):
return a[1] * b[0] - a[0] * b[1]
def dot(a, b):
return a[0] * b[0] + a[1] * b[1]
################################################################################
# Common functions
################################################################################
def atan2(*arg):
if len(arg) == 1 and (type(arg[0]) == type([0., 0.]) or type(arg[0]) == type((0., 0.))):
return (math.pi/2 - math.atan2(arg[0][0], arg[0][1])) % math.pi2
elif len(arg) == 2:
return (math.pi/2 - math.atan2(arg[0], arg[1])) % math.pi2
else:
raise ValueError("Bad argumets for atan! (%s)" % arg)
def between(c, x, y):
return x-straight_tolerance <= c <= y+straight_tolerance or y-straight_tolerance <= c <= x+straight_tolerance
def cubic_solver(a, b, c, d):
if a != 0:
# Monics formula see http://en.wikipedia.org/wiki/Cubic_function#Monic_formula_of_roots
a, b, c = (b/a, c/a, d/a)
m = 2*a**3 - 9*a*b + 27*c
k = a**2 - 3*b
n = m**2 - 4*k**3
w1 = -.5 + .5*cmath.sqrt(3)*1j
w2 = -.5 - .5*cmath.sqrt(3)*1j
if n >= 0:
t = m+math.sqrt(n)
m1 = pow(t/2, 1./3) if t >= 0 else -pow(-t/2, 1./3)
t = m-math.sqrt(n)
n1 = pow(t/2, 1./3) if t >= 0 else -pow(-t/2, 1./3)
else:
m1 = pow(complex((m+cmath.sqrt(n))/2), 1./3)
n1 = pow(complex((m-cmath.sqrt(n))/2), 1./3)
x1 = -1./3 * (a + m1 + n1)
x2 = -1./3 * (a + w1*m1 + w2*n1)
x3 = -1./3 * (a + w2*m1 + w1*n1)
return [x1, x2, x3]
elif b != 0:
det = c**2-4*b*d
if det > 0:
return [(-c+math.sqrt(det))/(2*b), (-c-math.sqrt(det))/(2*b)]
elif d == 0:
return [-c/(b*b)]
else:
return [(-c+cmath.sqrt(det))/(2*b), (-c-cmath.sqrt(det))/(2*b)]
elif c != 0:
return [-d/c]
else:
return []
################################################################################
# print_ prints any arguments into specified log file
################################################################################
def print_(*arg):
if (os.path.isdir(options.directory)):
f = open(options.directory+"/log.txt", "a")
for s in arg:
s = str(str(s).encode('unicode_escape'))+" "
f.write(s)
f.write("\n")
f.close()
def print_debug(*arg):
if debug:
print_("DEBUG: ", *arg)
def print_time(*arg):
global timestamp
time = datetime.datetime.now() - timestamp
print_(time, " ", *arg)
timestamp = datetime.datetime.now()
################################################################################
# Point (x,y) operations
################################################################################
class P:
def __init__(self, x, y=None):
if not y == None:
self.x, self.y = float(x), float(y)
else:
self.x, self.y = float(x[0]), float(x[1])
def __add__(self, other): return P(self.x + other.x, self.y + other.y)
def __sub__(self, other): return P(self.x - other.x, self.y - other.y)
def __neg__(self): return P(-self.x, -self.y)
def __mul__(self, other):
if isinstance(other, P):
return self.x * other.x + self.y * other.y
return P(self.x * other, self.y * other)
__rmul__ = __mul__
def __div__(self, other): return P(self.x / other, self.y / other)
def mag(self): return math.hypot(self.x, self.y)
def unit(self):
h = self.mag()
if h:
return self / h
else:
return P(0, 0)
def dot(self, other): return self.x * other.x + self.y * other.y
def rot(self, theta):
c = math.cos(theta)
s = math.sin(theta)
return P(self.x * c - self.y * s, self.x * s + self.y * c)
def angle(self): return math.atan2(self.y, self.x)
def __repr__(self): return '%f,%f' % (self.x, self.y)
def pr(self): return "%.3f,%.3f" % (self.x, self.y)
def to_list(self): return [self.x, self.y]
def ccw(self): return P(-self.y, self.x)
def l2(self): return self.x*self.x + self.y*self.y
################################################################################
# Gcodetools class
################################################################################
class laser_gcode(inkex.Effect):
def export_gcode(self, gcode):
gcode_pass = gcode
for _ in range(1, self.options.passes):
gcode += "G91\n" + "\nG90\n" + gcode_pass
f = open(self.options.directory+self.options.file, "w")
f.write(self.header + "\n" + gcode + self.footer)
f.close()
def __init__(self):
inkex.Effect.__init__(self)
self.OptionParser.add_option("-d", "--directory", action="store", type="string",
dest="directory", default="/insert your target directory here", help="Output directory")
self.OptionParser.add_option("-f", "--filename", action="store", type="string",
dest="file", default="output.ngc", help="File name")
self.OptionParser.add_option("", "--add-numeric-suffix-to-filename", action="store", type="inkbool",
dest="add_numeric_suffix_to_filename", default=False, help="Add numeric suffix to file name")
self.OptionParser.add_option("", "--laser-command-perimeter", action="store", type="string",
dest="laser_command_perimeter", default="S100", help="Laser gcode command Perimeter")
self.OptionParser.add_option("", "--laser-command", action="store", type="string",
dest="laser_command", default="S100", help="Laser gcode command infill")
self.OptionParser.add_option("", "--laser-off-command", action="store", type="string",
dest="laser_off_command", default="S1", help="Laser gcode end command")
self.OptionParser.add_option("", "--laser-beam-with", action="store", type="float",
dest="laser_beam_with", default="0.3", help="Laser speed (mm/min)")
self.OptionParser.add_option("", "--laser-speed", action="store", type="int",
dest="laser_speed", default="1200", help="Laser speed for infill (mm/min)")
self.OptionParser.add_option("", "--laser-param-speed", action="store", type="int",
dest="laser_param_speed", default="700", help="Laser speed for Parameter (mm/min)")
self.OptionParser.add_option("", "--passes", action="store", type="int",
dest="passes", default="1", help="Quantity of passes")
self.OptionParser.add_option("", "--power-delay", action="store", type="string",
dest="power_delay", default="0", help="Laser power-on delay (ms)")
self.OptionParser.add_option("", "--suppress-all-messages", action="store", type="inkbool",
dest="suppress_all_messages", default=True, help="Hide messages during g-code generation")
self.OptionParser.add_option("", "--create-log", action="store", type="inkbool",
dest="log_create_log", default=True, help="Create log files")
self.OptionParser.add_option("", "--engraving-draw-calculation-paths", action="store", type="inkbool",
dest="engraving_draw_calculation_paths", default=True, help="Draw additional graphics to debug engraving path")
self.OptionParser.add_option("", "--biarc-max-split-depth", action="store", type="int", dest="biarc_max_split_depth",
default="2", help="Defines maximum depth of splitting while approximating using biarcs.")
self.OptionParser.add_option("", "--area-fill-angle", action="store", type="float", dest="area_fill_angle",
default="0", help="Fill area with lines heading this angle")
self.OptionParser.add_option("", "--engraving-newton-iterations", action="store", type="int", dest="engraving_newton_iterations",
default="20", help="Number of sample points used to calculate distance")
self.OptionParser.add_option("", "--add-contours", action="store", type="inkbool",
dest="add_contours", default=True, help="Add contour to Gcode paths")
self.OptionParser.add_option("", "--add-infill", action="store", type="inkbool",
dest="add_infill", default=True, help="Add infill to Gcode paths")
self.OptionParser.add_option("", "--remove-tiny-infill-paths", action="store", type="inkbool",
dest="remove_tiny_infill_paths", default=False, help="Remove tiny infill paths from Gcode")
self.OptionParser.add_option("", "--multi_thread", action="store", type="inkbool",
dest="multi_thread", default=True, help="Activate multithreading support")
def parse_curve(self, p, layer):
c = []
if len(p) == 0:
return []
p = self.transform_csp(p, layer)
# this code is intended to replace the code below.
# At the Moment there is a problem with muliple paths, where the fist/last path will not be generated
# TODO: Fix that
'''
print_("p_post_Trans ", p)
startPoints = np.zeros(shape=[len(p), 2])
endPoints = np.zeros(shape=[len(p), 2])
# reduce Array size
for i in range(0, len(p)):
elRed = np.array(p[i])
elRed = elRed[:, 0]
startPoints[i] = elRed[0]
endPoints[i] = elRed[-1]
print_("StartPoints", startPoints)
print_("EndPoints", endPoints)
print_("elRed", elRed)
sortedPoints = np.array(self.sort_points(
startPoints[:, 0], startPoints[:, 1], endPoints[:, 0], endPoints[:, 1]))
for point in sortedPoints:
ind = np.argwhere(startPoints == point[0])[0, 0]
elRed = np.array(p[ind])
elRed = elRed[:, 0]
c += [[[point[0], point[1]], 'move']]
for i in range(1, len(elRed)):
c += [[[elRed[i-1, 0], elRed[i-1, 1]], 'line', [elRed[i, 0], elRed[i, 1]]]]
c += [[[elRed[-1, 0], elRed[-1, 1]], 'end']]
# Sort to reduce Rapid distance
'''
k = range(1, len(p))
keys = [0]
while len(k) > 0:
end = p[keys[-1]][-1][1]
dist = None
for i in range(len(k)):
start = p[k[i]][0][1]
dist = max((-((end[0]-start[0])**2+(end[1]-start[1])**2), i), dist)
keys += [k[dist[1]]]
del k[dist[1]]
for k in keys:
subpath = p[k]
c += [[[subpath[0][1][0], subpath[0][1][1]], 'move']]
# print_([[[subpath[0][1][0], subpath[0][1][1]], 'move']])
for i in range(1, len(subpath)):
# print_("subpath: ", subpath[i-1])
sp1 = [[subpath[i-1][j][0], subpath[i-1][j][1]]
for j in range(3)]
sp2 = [[subpath[i][j][0], subpath[i][j][1]] for j in range(3)]
c += [[[sp1[0][0], sp1[0][1]], 'line', [sp2[0][0], sp2[0][1]]]]
# print_("sp1: ", sp1)
c += [[[subpath[-1][1][0], subpath[-1][1][1]], 'end']]
# print_([[[subpath[-1][1][0], subpath[-1][1][1]], 'end']])
# print_("Curve: " + str(c))
return c
def parse_curve2d(self, p, layer):
c = []
if len(p) == 0:
return []
p = self.transform_csp(p, layer)
# print_("p: ", p)
np_p = np.array(p)
# print_("len p Slice: ", len(np_p[:, 0, 0, 0]))
sortedToolpaths = self.sort_points(np_p[:, 0, 0, 0], np_p[:, 0, 0, 1], np_p[:, 1, 0, 0], np_p[:, 1, 0, 1])
for path in sortedToolpaths:
c += [[[path[0], path[1]], 'move']]
c += [[[path[0], path[1]], 'line', [path[2], path[3]]]]
c += [[[path[2], path[3]], 'end']]
return c
def sort_points(self, x1, y1, x2, y2):
sortedList = np.zeros((len(x1), 4))
xpos = np.array(x1[1:])
xposInv = np.array(x2[1:])
ypos = np.array(y1[1:])
yposInv = np.array(y2[1:])
sortedList[0] = [x1[0], y1[0], x2[0], y2[0]]
actXPos = x2[0]
actYPos = y2[0]
i = 1
while len(xpos) > 0:
xDist = np.abs(xpos - actXPos)
xDistInv = np.abs(xposInv - actXPos)
yDist = np.abs(ypos - actYPos)
yDistInv = np.abs(yposInv - actYPos)
distances = np.array([np.add(xDist, yDist), np.add(xDistInv, yDistInv)])
distances = np.abs(distances)
# print_("Distances: ", distances)
minInd = np.unravel_index(np.argmin(distances, axis=None), distances.shape)
if minInd[0] == 0:
sortedList[i] = [xpos[minInd[1]], ypos[minInd[1]], xposInv[minInd[1]], yposInv[minInd[1]]]
actXPos = xposInv[minInd[1]]
actYPos = yposInv[minInd[1]]
else:
sortedList[i] = [xposInv[minInd[1]], yposInv[minInd[1]], xpos[minInd[1]], ypos[minInd[1]]]
actXPos = xpos[minInd[1]]
actYPos = ypos[minInd[1]]
xpos = np.delete(xpos, minInd[1])
ypos = np.delete(ypos, minInd[1])
xposInv = np.delete(xposInv, minInd[1])
yposInv = np.delete(yposInv, minInd[1])
i = i+1
return sortedList
def draw_curve(self, curve, layer, group=None, style=styles["biarc_style"]):
self.get_defs()
if group == None:
group = inkex.etree.SubElement(self.layers[min(1, len(
self.layers)-1)], inkex.addNS('g', 'svg'), {"gcodetools": "Preview group"})
s = ''
a, b, c = [0., 0.], [1., 0.], [0., 1.]
a, b, c = self.transform(a, layer, True), self.transform(b, layer, True), self.transform(c, layer, True)
for si in curve:
si[0] = self.transform(si[0], layer, True)
# print_("si ", si)
if len(si) == 3:
si[2] = self.transform(si[2], layer, True)
if s != '':
if s[1] == 'line':
inkex.etree.SubElement(group, inkex.addNS('path', 'svg'),
{
'style': style['line'],
'd': 'M %s,%s L %s,%s' % (s[0][0], s[0][1], si[0][0], si[0][1]),
"gcodetools": "Preview",
}
)
s = si
def check_dir(self):
if self.options.directory[-1] not in ["/", "\\"]:
if "\\" in self.options.directory:
self.options.directory += "\\"
else:
self.options.directory += "/"
print_("Checking direcrory: '%s'" % self.options.directory)
if (os.path.isdir(self.options.directory)):
if (os.path.isfile(self.options.directory+'header')):
f = open(self.options.directory+'header', 'r')
self.header = f.read()
f.close()
else:
self.header = defaults['header']
if (os.path.isfile(self.options.directory+'footer')):
f = open(self.options.directory+'footer', 'r')
self.footer = f.read()
f.close()
else:
self.footer = defaults['footer']
self.header += "G21\n"
else:
self.error(_("Directory does not exist! Please specify existing directory at options tab!"), "error")
return False
if self.options.add_numeric_suffix_to_filename:
dir_list = os.listdir(self.options.directory)
if "." in self.options.file:
r = re.match(r"^(.*)(\..*)$", self.options.file)
ext = r.group(2)
name = r.group(1)
else:
ext = ""
name = self.options.file
max_n = 0
for s in dir_list:
r = re.match(r"^%s_0*(\d+)%s$" %
(re.escape(name), re.escape(ext)), s)
if r:
max_n = max(max_n, int(r.group(1)))
filename = name + "_" + \
("0"*(4-len(str(max_n+1))) + str(max_n+1)) + ext
self.options.file = filename
print_("Testing writing rights on '%s'" %
(self.options.directory+self.options.file))
try:
f = open(self.options.directory+self.options.file, "w")
f.close()
except:
self.error(_("Can not write to specified file!\n%s" % (self.options.directory+self.options.file)), "error")
return False
return True
################################################################################
# Generate Gcode
# Generates Gcode on given curve.
# Crve defenitnion [start point, type = {'arc','line','move','end'}, arc center, arc angle, end point, [zstart, zend]]
################################################################################
def generate_gcode(self, curve, layer, tool):
global doc_height
global offset_y
print_debug(" Laser parameters: " + str(tool))
def c(c):
c = [c[i] if i < len(c) else None for i in range(6)]
if c[5] == 0:
c[5] = None
s = [" X", " Y", " Z", " I", " J", " K"]
r = ''
for i in range(6):
if c[i] != None:
r += s[i] + ("%f" % (round(c[i], 2))).rstrip('0')
return r
try:
self.last_used_tool == None
except:
self.last_used_tool = None
# print_("Curve: " + str(curve) + "/n")
g = ""
lg, f = 'G00', "F%.1f" % tool['penetration feed']
for i in range(1, len(curve)):
# Creating Gcode for curve between s=curve[i-1] and si=curve[i] start at s[0] end at s[4]=si[0]
s, si = curve[i-1], curve[i]
si[0] = self.transform(si[0], layer, True)
# print_("si ", si)
if len(si) == 3:
si[2] = self.transform(si[2], layer, True)
s[0][1] = s[0][1] - offset_y
si[0][1] = si[0][1] - offset_y
feed = f if lg not in ['G01', 'G02', 'G03'] else ''
if s[1] == 'move':
g += "G00" + c(si[0]) + "\n" + tool['gcode before path'] + "\n"
lg = 'G00'
elif s[1] == 'line':
if lg == "G00":
g += "G01 " + feed + "\n"
g += "G01" + c(si[0]) + "\n"
lg = 'G01'
if si[1] == 'end':
g += tool['gcode after path'] + "\n"
return g
# elif s[1] == 'end':
# g += tool['gcode after path'] + "\n"
# lg = 'G00'
def get_transforms(self, g):
root = self.document.getroot()
trans = []
while (g != root):
if 'transform' in g.keys():
t = g.get('transform')
t = simpletransform.parseTransform(t)
trans = simpletransform.composeTransform(
t, trans) if trans != [] else t
g = g.getparent()
return trans
def apply_transforms(self, g, csp):
trans = self.get_transforms(g)
if trans != []:
trans[1][2] = 0
print_(' applying transformation')
# print_(trans)
simpletransform.applyTransformToPath(trans, csp)
return csp
def transform(self, source_point, layer, reverse=False):
if layer == None:
layer = self.current_layer if self.current_layer is not None else self.document.getroot()
if layer not in self.transform_matrix:
for i in range(self.layers.index(layer), -1, -1):
if self.layers[i] in self.orientation_points:
break
# print_(str(self.layers))
# print_(str("I: " + str(i)))
if self.layers[i] not in self.orientation_points:
self.error(_("Orientation points for '%s' layer have not been found! Please add orientation points using Orientation tab!") % layer.get(
inkex.addNS('label', 'inkscape')))
elif self.layers[i] in self.transform_matrix:
self.transform_matrix[layer] = self.transform_matrix[self.layers[i]]
else:
orientation_layer = self.layers[i]
if len(self.orientation_points[orientation_layer]) > 1:
self.error(_("There are more than one orientation point groups in '%s' layer") % orientation_layer.get(
inkex.addNS('label', 'inkscape')))
points = self.orientation_points[orientation_layer][0]
if len(points) == 2:
points += [[[(points[1][0][1]-points[0][0][1])+points[0][0][0], -(points[1][0][0]-points[0][0][0])+points[0][0][1]],
[-(points[1][1][1]-points[0][1][1])+points[0][1][0], points[1][1][0]-points[0][1][0]+points[0][1][1]]]]
if len(points) == 3:
# print_("Layer '%s' Orientation points: " % orientation_layer.get(inkex.addNS('label', 'inkscape')))
# for point in points:
# print_(point)
# Zcoordinates definition taken from Orientatnion point 1 and 2
self.Zcoordinates[layer] = [
max(points[0][1][2], points[1][1][2]), min(points[0][1][2], points[1][1][2])]
matrix = np.array([