Debian Codegraph @

bCNC/CNC.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # -*- coding: ascii -*-
2 # $Id: CNC.py,v 1.8 2014/10/15 15:03:49 bnv Exp $
3 #
4 # Author: [email protected]
5 # Date: 24-Aug-2014
6
7 from __future__ import absolute_import
8 from __future__ import print_function
9 import os
10 import re
11 import math
12 import types
13
14 import undo
15 import Unicode
16 import pickle
17 import json
18 #import binascii
19
20 from dxf import DXF
21 from bstl import Binary_STL_Writer
22 from bpath import eq,Path, Segment
23 from bmath import *
24 from copy import deepcopy
25 from svgcode import SVGcode
26 from Utils import to_zip
27
28 IDPAT = re.compile(r".*\bid:\s*(.*?)\)")
29 PARENPAT = re.compile(r"(\(.*?\))")
30 SEMIPAT = re.compile(r"(;.*)")
31 OPPAT = re.compile(r"(.*)\[(.*)\]")
32 CMDPAT = re.compile(r"([A-Za-z]+)")
33 BLOCKPAT = re.compile(r"^\(Block-([A-Za-z]+):\s*(.*)\)")
34 AUXPAT = re.compile(r"^(%[A-Za-z0-9]+)\b *(.*)$")
35
36 STOP = 0
37 SKIP = 1
38 ASK = 2
39 MSG = 3
40 WAIT = 4
41 UPDATE = 5
42
43 XY = 0
44 XZ = 1
45 YZ = 2
46
47 CW = 2
48 CCW = 3
49
50 WCS = ["G54", "G55", "G56", "G57", "G58", "G59"]
51
52 DISTANCE_MODE = { "G90" : "Absolute",
53 "G91" : "Incremental" }
54 FEED_MODE = { "G93" : "1/Time",
55 "G94" : "unit/min",
56 "G95" : "unit/rev"}
57 UNITS = { "G20" : "inch",
58 "G21" : "mm" }
59 PLANE = { "G17" : "XY",
60 "G18" : "XZ",
61 "G19" : "YZ" }
62
63 # Modal Mode from $G and variable set
64 MODAL_MODES = {
65 "G0" : "motion",
66 "G1" : "motion",
67 "G2" : "motion",
68 "G3" : "motion",
69 "G38.2" : "motion",
70 "G38.3" : "motion",
71 "G38.4" : "motion",
72 "G38.5" : "motion",
73 "G80" : "motion",
74
75 "G54" : "WCS",
76 "G55" : "WCS",
77 "G56" : "WCS",
78 "G57" : "WCS",
79 "G58" : "WCS",
80 "G59" : "WCS",
81
82 "G17" : "plane",
83 "G18" : "plane",
84 "G19" : "plane",
85
86 "G90" : "distance",
87 "G91" : "distance",
88
89 "G91.1" : "arc",
90
91 "G93" : "feedmode",
92 "G94" : "feedmode",
93 "G95" : "feedmode",
94
95 "G20" : "units",
96 "G21" : "units",
97
98 "G40" : "cutter",
99
100 "G43.1" : "tlo",
101 "G49" : "tlo",
102
103 "M0" : "program",
104 "M1" : "program",
105 "M2" : "program",
106 "M30" : "program",
107
108 "M3" : "spindle",
109 "M4" : "spindle",
110 "M5" : "spindle",
111
112 "M7" : "coolant",
113 "M8" : "coolant",
114 "M9" : "coolant",
115 }
116
117 ERROR_HANDLING = {}
118 TOLERANCE = 1e-7
119 MAXINT = 1000000000 # python3 doesn't have maxint
120
121
122 #------------------------------------------------------------------------------
123 # Return a value combined from two dictionaries new/old
124 #------------------------------------------------------------------------------
125 def getValue(name,new,old,default=0.0):
126 try:
127 return new[name]
128 except:
129 try:
130 return old[name]
131 except:
132 return default
133
134
135 #===============================================================================
136 # Probing class and linear interpolation
137 #===============================================================================
138 class Probe:
139 def __init__(self):
140 self.init()
141
142 #----------------------------------------------------------------------
143 def init(self):
144 self.filename = ""
145 self.xmin = 0.0
146 self.ymin = 0.0
147 self.zmin = -10.0
148
149 self.xmax = 10.0
150 self.ymax = 10.0
151 self.zmax = 3.0
152
153 self._xstep = 1.0
154 self._ystep = 1.0
155
156 self.xn = 5
157 self.yn = 5
158
159 self.points = [] # probe points
160 self.matrix = [] # 2D matrix with Z coordinates
161 self.zeroed = False # if probe was zeroed at any location
162 self.start = False # start collecting probes
163 self.saved = False
164
165 #----------------------------------------------------------------------
166 def clear(self):
167 del self.points[:]
168 del self.matrix[:]
169 self.zeroed = False
170 self.start = False
171 self.saved = False
172
173 #----------------------------------------------------------------------
174 def isEmpty(self): return len(self.matrix)==0
175
176 #----------------------------------------------------------------------
177 def makeMatrix(self):
178 del self.matrix[:]
179 for j in range(self.yn):
180 self.matrix.append([0.0]*(self.xn))
181
182 #----------------------------------------------------------------------
183 # Load autolevel information from file
184 #----------------------------------------------------------------------
185 def load(self, filename=None):
186 if filename is not None:
187 self.filename = filename
188 self.clear()
189 self.saved = True
190
191 def read(f):
192 while True:
193 line = f.readline()
194 assert line , "Read an empty line, please check file IO settings"
195 line = line.strip()
196 if line: return map(float, line.split())
197
198 f = open(self.filename,"r")
199 self.xmin, self.xmax, self.xn = read(f)
200 self.ymin, self.ymax, self.yn = read(f)
201 self.zmin, self.zmax, feed = read(f)
202 CNC.vars["prbfeed"] = feed
203
204 self.xn = max(2,int(self.xn))
205 self.yn = max(2,int(self.yn))
206
207 self.makeMatrix()
208 self.xstep()
209 self.ystep()
210
211 self.start = True
212 try:
213 for j in range(self.yn):
214 for i in range(self.xn):
215 self.add(*read(f))
216 except:
217 raise
218 #print "Error reading probe file",self.filename
219 f.close()
220
221 #----------------------------------------------------------------------
222 # Save level information to file
223 #----------------------------------------------------------------------
224 def save(self, filename=None):
225 if filename is None:
226 filename = self.filename
227
228 fn,ext = os.path.splitext(filename)
229 ext = ext.lower()
230
231 f = open(filename,"w")
232 if ext != '.xyz':
233 self.filename = filename
234 f.write("%g %g %d\n"%(self.xmin, self.xmax, self.xn))
235 f.write("%g %g %d\n"%(self.ymin, self.ymax, self.yn))
236 f.write("%g %g %g\n"%(self.zmin, self.zmax, CNC.vars["prbfeed"]))
237 f.write("\n\n")
238 for j in range(self.yn):
239 y = self.ymin + self._ystep*j
240 for i in range(self.xn):
241 x = self.xmin + self._xstep*i
242 f.write("%g %g %g\n"%(x,y,self.matrix[j][i]))
243 f.write("\n")
244 f.close()
245 self.saved = True
246
247 #----------------------------------------------------------------------
248 # Save level information as STL file
249 #----------------------------------------------------------------------
250 def saveAsSTL(self, filename=None):
251 if filename is not None:
252 self.filename = filename
253
254 with open(self.filename, 'wb') as fp:
255 writer = Binary_STL_Writer(fp)
256 for j in range(self.yn -1):
257 y1 = self.ymin + self._ystep*j
258 y2 = self.ymin + self._ystep*(j+1)
259 for i in range(self.xn -1):
260 x1 = self.xmin + self._xstep*i
261 x2 = self.xmin + self._xstep*(i+1)
262 v1=[x1,y1,self.matrix[j][i]]
263 v2=[x2,y1,self.matrix[j][i+1]]
264 v3=[x2,y2,self.matrix[j+1][i+1]]
265 v4=[x1,y2,self.matrix[j+1][i]]
266 writer.add_face([v1,v2,v3,v4])
267 writer.close()
268
269 #----------------------------------------------------------------------
270 # Return step
271 #----------------------------------------------------------------------
272 def xstep(self):
273 self._xstep = (self.xmax-self.xmin)/float(self.xn-1)
274 return self._xstep
275
276 #----------------------------------------------------------------------
277 def ystep(self):
278 self._ystep = (self.ymax-self.ymin)/float(self.yn-1)
279 return self._ystep
280
281 #----------------------------------------------------------------------
282 # Return the code needed to scan margins for autoleveling
283 #----------------------------------------------------------------------
284 def scanMargins(self):
285 lines = []
286 lines.append("G0 X%.4f Y%.4f"%(self.xmin, self.ymin))
287 lines.append("G0 X%.4f Y%.4f"%(self.xmin, self.ymax))
288 lines.append("G0 X%.4f Y%.4f"%(self.xmax, self.ymax))
289 lines.append("G0 X%.4f Y%.4f"%(self.xmax, self.ymin))
290 lines.append("G0 X%.4f Y%.4f"%(self.xmin, self.ymin))
291 return lines
292
293 #----------------------------------------------------------------------
294 # Return the code needed to scan for autoleveling
295 #----------------------------------------------------------------------
296 def scan(self):
297 self.clear()
298 self.start = True
299 self.makeMatrix()
300 x = self.xmin
301 xstep = self._xstep
302 lines = ["G0Z%.4f"%(CNC.vars["safe"]),
303 "G0X%.4fY%.4f"%(self.xmin, self.ymin)]
304 for j in range(self.yn):
305 y = self.ymin + self._ystep*j
306 for i in range(self.xn):
307 lines.append("G0Z%.4f"%(self.zmax))
308 lines.append("G0X%.4fY%.4f"%(x,y))
309 lines.append("%wait") # added for smoothie
310 lines.append("%sZ%.4fF%g"%(CNC.vars["prbcmd"], self.zmin, CNC.vars["prbfeed"]))
311 lines.append("%wait") # added for smoothie
312 x += xstep
313 x -= xstep
314 xstep = -xstep
315 lines.append("G0Z%.4f"%(self.zmax))
316 lines.append("G0X%.4fY%.4f"%(self.xmin,self.ymin))
317 return lines
318
319 #----------------------------------------------------------------------
320 # Add a probed point to the list and the 3D matrix
321 #----------------------------------------------------------------------
322 def add(self, x,y,z):
323 if not self.start: return
324 i = round((x-self.xmin) / self._xstep)
325 if i<0.0 or i>self.xn: return
326
327 j = round((y-self.ymin) / self._ystep)
328 if j<0.0 or j>self.yn: return
329
330 rem = abs(x - (i*self._xstep + self.xmin))
331 if rem > self._xstep/10.0: return
332
333 rem = abs(y - (j*self._ystep + self.ymin))
334 if rem > self._ystep/10.0: return
335
336 try:
337 self.matrix[int(j)][int(i)] = z
338 self.points.append([x,y,z])
339 except IndexError:
340 pass
341
342 if len(self.points) >= self.xn*self.yn:
343 self.start = False
344
345 #----------------------------------------------------------------------
346 # Make z-level relative to the location of (x,y,0)
347 #----------------------------------------------------------------------
348 def setZero(self, x, y):
349 del self.points[:]
350 if self.isEmpty():
351 self.zeroed = False
352 return
353 zero = self.interpolate(x,y)
354 self.xstep()
355 self.ystep()
356 for j,row in enumerate(self.matrix):
357 y = self.ymin + self._ystep*j
358 for i in range(len(row)):
359 x = self.xmin + self._xstep*i
360 row[i] -= zero
361 self.points.append([x,y,row[i]])
362 self.zeroed = True
363
364 #----------------------------------------------------------------------
365 def interpolate(self, x, y):
366 ix = (x-self.xmin) / self._xstep
367 jy = (y-self.ymin) / self._ystep
368 i = int(math.floor(ix))
369 j = int(math.floor(jy))
370
371 if i<0:
372 i = 0
373 elif i>=self.xn-1:
374 i = self.xn-2
375
376 if j<0:
377 j = 0
378 elif j>=self.yn-1:
379 j = self.yn-2
380
381 a = ix - i
382 b = jy - j
383 a1 = 1.0 - a
384 b1 = 1.0 - b
385
386 return a1*b1 * self.matrix[j][i] + \
387 a1*b * self.matrix[j+1][i] + \
388 a *b1 * self.matrix[j][i+1] + \
389 a *b * self.matrix[j+1][i+1]
390
391 #----------------------------------------------------------------------
392 # Split line into multiple segments correcting for Z if needed
393 # return only end points
394 #----------------------------------------------------------------------
395 def splitLine(self, x1, y1, z1, x2, y2, z2):
396 dx = x2-x1
397 dy = y2-y1
398 dz = z2-z1
399
400 if abs(dx)<1e-10: dx = 0.0
401 if abs(dy)<1e-10: dy = 0.0
402 if abs(dz)<1e-10: dz = 0.0
403
404 if dx==0.0 and dy==0.0:
405 return [(x2,y2,z2+self.interpolate(x2,y2))]
406
407 # Length along projection on X-Y plane
408 rxy = math.sqrt(dx*dx + dy*dy)
409 dx /= rxy # direction cosines along XY plane
410 dy /= rxy
411 dz /= rxy # add correction for the slope in Z, versus the travel in XY
412
413 i = int(math.floor((x1-self.xmin) / self._xstep))
414 j = int(math.floor((y1-self.ymin) / self._ystep))
415 if dx > 1e-10:
416 tx = (float(i+1)*self._xstep+self.xmin - x1)/ dx # distance to next cell
417 tdx = self._xstep / dx
418 elif dx < -1e-10:
419 tx = (float(i)*self._xstep+self.xmin - x1)/ dx # distance to next cell
420 tdx = -self._xstep / dx
421 else:
422 tx = 1e10
423 tdx = 0.0
424
425 if dy > 1e-10:
426 ty = (float(j+1)*self._ystep+self.ymin - y1)/ dy # distance to next cell
427 tdy = self._ystep / dy
428 elif dy < -1e-10:
429 ty = (float(j)*self._ystep+self.ymin - y1)/ dy # distance to next cell
430 tdy = -self._ystep / dy
431 else:
432 ty = 1e10
433 tdy = 0.0
434
435 segments = []
436 rxy *= 0.999999999 # just reduce a bit to avoid precision errors
437 while tx<rxy or ty<rxy:
438 if tx==ty:
439 t = tx
440 tx += tdx
441 ty += tdy
442 elif tx<ty:
443 t = tx
444 tx += tdx
445 else:
446 t = ty
447 ty += tdy
448 x = x1 + t*dx
449 y = y1 + t*dy
450 z = z1 + t*dz
451 segments.append((x,y,z+self.interpolate(x,y)))
452
453 segments.append((x2,y2,z2+self.interpolate(x2,y2)))
454 return segments
455
456
457 #===============================================================================
458 # contains a list of machine points vs position in the gcode
459 # calculates the transformation matrix (rotation + translation) needed
460 # to adjust the gcode to match the workpiece on the machine
461 #===============================================================================
462 class Orient:
463 #-----------------------------------------------------------------------
464 def __init__(self):
465 self.markers = [] # list of points pairs (xm, ym, x, y)
466 # xm,ym = machine x,y mpos
467 # x, y = desired or gcode location
468 self.paths = []
469 self.errors = []
470 self.filename = ""
471 self.clear()
472
473 #-----------------------------------------------------------------------
474 def clear(self, item=None):
475 if item is None:
476 self.clearPaths()
477 del self.markers[:]
478 else:
479 del self.paths[item]
480 del self.markers[item]
481
482 self.phi = 0.0
483 self.xo = 0.0
484 self.yo = 0.0
485 self.valid = False
486 self.saved = False
487
488 #-----------------------------------------------------------------------
489 def clearPaths(self):
490 del self.paths[:]
491
492 #-----------------------------------------------------------------------
493 def add(self, xm, ym, x, y):
494 self.markers.append((xm,ym,x,y))
495 self.valid = False
496 self.saved = False
497
498 #-----------------------------------------------------------------------
499 def addPath(self, path):
500 self.paths.append(path)
501
502 #-----------------------------------------------------------------------
503 def __getitem__(self, i):
504 return self.markers[i]
505
506 #-----------------------------------------------------------------------
507 def __len__(self):
508 return len(self.markers)
509
510 #-----------------------------------------------------------------------
511 # Return the rotation angle phi in radians and the offset (xo,yo)
512 # or none on failure
513 # Transformation equation is the following
514 #
515 # Xm = R * X + T
516 #
517 # Xm = [xm ym]^t
518 # X = [x y]^t
519 #
520 #
521 # / cosf -sinf \ / c -s \
522 # R = | | = | |
523 # \ sinf cosf / \ s c /
524 #
525 # Assuming that the machine is squared. We could even solve it for
526 # a skewed machine, but then the arcs have to be converted to
527 # ellipses...
528 #
529 # T = [xo yo]^t
530 #
531 # The overdetermined system (equations) to solve are the following
532 # c*x + s*(-y) + xo = xm
533 # s*x + c*y + yo = ym
534 # <=> c*y + s*y + yo = ym
535 #
536 # We are solving for the unknowns c,s,xo,yo
537 #
538 # / x1 -y1 1 0 \ / c \ / xm1 \
539 # | y1 x1 0 1 | | s | | ym1 |
540 # | x2 -y2 1 0 | | xo | | xm2 |
541 # | y2 x2 0 1 | \ yo / = | ym2 |
542 # ... ..
543 # | xn -yn 1 0 | | xmn |
544 # \ yn xn 0 1 / \ ymn /
545 #
546 # A X = B
547 #
548 # Constraints:
549 # 1. orthogonal system c^2 + s^2 = 1
550 # 2. no aspect ratio
551 #
552 #-----------------------------------------------------------------------
553 def solve(self):
554 self.valid = False
555 if len(self.markers)< 2: raise Exception("Too few markers")
556 A = []
557 B = []
558 for xm,ym,x,y in self.markers:
559 A.append([x,-y,1.0,0.0]); B.append([xm])
560 A.append([y, x,0.0,1.0]); B.append([ym])
561
562 # The solution of the overdetermined system A X = B
563 try:
564 c,s,self.xo,self.yo = solveOverDetermined(Matrix(A),Matrix(B))
565 except:
566 raise Exception("Unable to solve system")
567
568 #print "c,s,xo,yo=",c,s,xo,yo
569
570 # Normalize the coefficients
571 r = sqrt(c*c + s*s) # length should be 1.0
572 if abs(r-1.0) > 0.1:
573 raise Exception("Resulting system is too skew")
574
575 # print "r=",r
576 #xo /= r
577 #yo /= r
578 self.phi = atan2(s, c)
579
580 if abs(self.phi)<TOLERANCE: self.phi = 0.0 # rotation
581
582 self.valid = True
583 return self.phi,self.xo,self.yo
584
585 #-----------------------------------------------------------------------
586 # @return minimum, average and maximum error
587 #-----------------------------------------------------------------------
588 def error(self):
589 # Type errors
590 minerr = 1e9
591 maxerr = 0.0
592 sumerr = 0.0
593
594 c = cos(self.phi)
595 s = sin(self.phi)
596
597 del self.errors[:]
598
599 for i,(xm,ym,x,y) in enumerate(self.markers):
600 dx = c*x - s*y + self.xo - xm
601 dy = s*x + c*y + self.yo - ym
602 err = sqrt(dx**2 + dy**2)
603 self.errors.append(err)
604
605 minerr = min(minerr, err)
606 maxerr = max(maxerr, err)
607 sumerr += err
608
609 return minerr, sumerr/float(len(self.markers)), maxerr
610
611 #-----------------------------------------------------------------------
612 # Convert gcode to machine coordinates
613 #-----------------------------------------------------------------------
614 def gcode2machine(self, x, y):
615 c = cos(self.phi)
616 s = sin(self.phi)
617 return c*x - s*y + self.xo, \
618 s*x + c*y + self.yo
619
620 #-----------------------------------------------------------------------
621 # Convert machine to gcode coordinates
622 #-----------------------------------------------------------------------
623 def machine2gcode(self, x, y):
624 c = cos(self.phi)
625 s = sin(self.phi)
626 x -= self.xo
627 y -= self.yo
628 return c*x + s*y, \
629 -s*x + c*y
630
631 #----------------------------------------------------------------------
632 # Load orient information from file
633 #----------------------------------------------------------------------
634 def load(self, filename=None):
635 if filename is not None:
636 self.filename = filename
637 self.clear()
638 self.saved = True
639
640 f = open(self.filename,"r")
641 for line in f:
642 self.add(*map(float, line.split()))
643 f.close()
644
645 #----------------------------------------------------------------------
646 # Save orient information to file
647 #----------------------------------------------------------------------
648 def save(self, filename=None):
649 if filename is not None:
650 self.filename = filename
651 f = open(self.filename,"w")
652 for xm,ym,x,y in self.markers:
653 f.write("%g %g %g %g\n"%(xm,ym,x,y))
654 f.close()
655 self.saved = True
656
657
658 #===============================================================================
659 # Command operations on a CNC
660 #===============================================================================
661 class CNC:
662 inch = False
663 lasercutter = False
664 laseradaptive = False
665 acceleration_x = 25.0 # mm/s^2
666 acceleration_y = 25.0 # mm/s^2
667 acceleration_z = 25.0 # mm/s^2
668 feedmax_x = 3000
669 feedmax_y = 3000
670 feedmax_z = 2000
671 travel_x = 300
672 travel_y = 300
673 travel_z = 60
674 accuracy = 0.01 # sagitta error during arc conversion
675 digits = 4
676 startup = "G90"
677 stdexpr = False # standard way of defining expressions with []
678 comment = "" # last parsed comment
679 developer = False
680 drozeropad = 0
681 vars = {
682 "prbx" : 0.0,
683 "prby" : 0.0,
684 "prbz" : 0.0,
685 "prbcmd" : "G38.2",
686 "prbfeed" : 10.,
687 "errline" : "",
688 "wx" : 0.0,
689 "wy" : 0.0,
690 "wz" : 0.0,
691 "wa" : 0.0,
692 "wb" : 0.0,
693 "wc" : 0.0,
694 "mx" : 0.0,
695 "my" : 0.0,
696 "mz" : 0.0,
697 "ma" : 0.0,
698 "mb" : 0.0,
699 "mc" : 0.0,
700 "wcox" : 0.0,
701 "wcoy" : 0.0,
702 "wcoz" : 0.0,
703 "wcoa" : 0.0,
704 "wcob" : 0.0,
705 "wcoc" : 0.0,
706 "curfeed" : 0.0,
707 "curspindle" : 0.0,
708 "_camwx" : 0.0,
709 "_camwy" : 0.0,
710 "G" : [],
711 "TLO" : 0.0,
712 "motion" : "G0",
713 "WCS" : "G54",
714 "plane" : "G17",
715 "feedmode" : "G94",
716 "distance" : "G90",
717 "arc" : "G91.1",
718 "units" : "G20",
719 "cutter" : "",
720 "tlo" : "",
721 "program" : "M0",
722 "spindle" : "M5",
723 "coolant" : "M9",
724
725 "tool" : 0,
726 "feed" : 0.0,
727 "rpm" : 0.0,
728
729 "planner" : 0,
730 "rxbytes" : 0,
731
732 "OvFeed" : 100, # Override status
733 "OvRapid" : 100,
734 "OvSpindle" : 100,
735 "_OvChanged" : False,
736 "_OvFeed" : 100, # Override target values
737 "_OvRapid" : 100,
738 "_OvSpindle" : 100,
739
740 "diameter" : 3.175, # Tool diameter
741 "cutfeed" : 1000., # Material feed for cutting
742 "cutfeedz" : 500., # Material feed for cutting
743 "safe" : 3.,
744 "state" : "",
745 "pins" : "",
746 "msg" : "",
747 "stepz" : 1.,
748 "surface" : 0.,
749 "thickness" : 5.,
750 "stepover" : 40.,
751
752 "PRB" : None,
753 "TLO" : 0.,
754
755 "version" : "",
756 "controller" : "",
757 "running" : False,
758 #"enable6axisopt" : 0,
759 }
760
761 drillPolicy = 1 # Expand Canned cycles
762 toolPolicy = 1 # Should be in sync with ProbePage
763 # 0 - send to grbl
764 # 1 - skip those lines
765 # 2 - manual tool change (WCS)
766 # 3 - manual tool change (TLO)
767 # 4 - manual tool change (No Probe)
768
769 toolWaitAfterProbe = True # wait at tool change position after probing
770 appendFeed = False # append feed on every G1/G2/G3 commands to be used
771 # for feed override testing
772 # FIXME will not be needed after Grbl v1.0
773
774 #----------------------------------------------------------------------
775 def __init__(self):
776 self.initPath()
777 self.resetAllMargins()
778
779 #----------------------------------------------------------------------
780 # Update G variables from "G" string
781 #----------------------------------------------------------------------
782 @staticmethod
783 def updateG():
784 for g in CNC.vars["G"]:
785 if g[0] == "F":
786 CNC.vars["feed"] = float(g[1:])
787 elif g[0] == "S":
788 CNC.vars["rpm"] = float(g[1:])
789 elif g[0] == "T":
790 CNC.vars["tool"] = int(g[1:])
791 else:
792 var = MODAL_MODES.get(g)
793 if var is not None:
794 CNC.vars[var] = g
795
796 #----------------------------------------------------------------------
797 def __getitem__(self, name):
798 return CNC.vars[name]
799
800 #----------------------------------------------------------------------
801 def __setitem__(self, name, value):
802 CNC.vars[name] = value
803
804 #----------------------------------------------------------------------
805 @staticmethod
806 def loadConfig(config):
807 section = "CNC"
808 try: CNC.inch = bool(int(config.get(section, "units")))
809 except: pass
810 try: CNC.lasercutter = bool(int(config.get(section, "lasercutter")))
811 except: pass
812 try: CNC.laseradaptive = bool(int(config.get(section, "laseradaptive")))
813 except: pass
814 try: CNC.enable6axisopt = bool(int(config.get(section, "enable6axisopt")))
815 except: pass
816 try: CNC.doublesizeicon = bool(int(config.get(section, "doublesizeicon")))
817 except: pass
818 try: CNC.acceleration_x = float(config.get(section, "acceleration_x"))
819 except: pass
820 try: CNC.acceleration_y = float(config.get(section, "acceleration_y"))
821 except: pass
822 try: CNC.acceleration_z = float(config.get(section, "acceleration_z"))
823 except: pass
824 try: CNC.feedmax_x = float(config.get(section, "feedmax_x"))
825 except: pass
826 try: CNC.feedmax_y = float(config.get(section, "feedmax_y"))
827 except: pass
828 try: CNC.feedmax_z = float(config.get(section, "feedmax_z"))
829 except: pass
830 try: CNC.travel_x = float(config.get(section, "travel_x"))
831 except: pass
832 try: CNC.travel_y = float(config.get(section, "travel_y"))
833 except: pass
834 try: CNC.travel_z = float(config.get(section, "travel_z"))
835 except: pass
836 try: CNC.acceleration_a = float(config.get(section, "acceleration_a"))
837 except: pass
838 try: CNC.acceleration_b = float(config.get(section, "acceleration_b"))
839 except: pass
840 try: CNC.acceleration_c = float(config.get(section, "acceleration_c"))
841 except: pass
842 try: CNC.feedmax_a = float(config.get(section, "feedmax_a"))
843 except: pass
844 try: CNC.feedmax_b = float(config.get(section, "feedmax_b"))
845 except: pass
846 try: CNC.feedmax_c = float(config.get(section, "feedmax_c"))
847 except: pass
848 try: CNC.travel_a = float(config.get(section, "travel_a"))
849 except: pass
850 try: CNC.travel_b = float(config.get(section, "travel_b"))
851 except: pass
852 try: CNC.travel_c = float(config.get(section, "travel_c"))
853 except: pass
854 try: CNC.accuracy = float(config.get(section, "accuracy"))
855 except: pass
856 try: CNC.digits = int( config.get(section, "round"))
857 except: pass
858 try: CNC.drozeropad = int( config.get(section, "drozeropad"))
859 except: pass
860
861 try:
862 CNC.startup = config.get(section, "startup")
863 except: pass
864 try:
865 CNC.header = config.get(section, "header")
866 except: pass
867 try:
868 CNC.footer = config.get(section, "footer")
869 except: pass
870
871 if CNC.inch:
872 CNC.acceleration_x /= 25.4
873 CNC.acceleration_y /= 25.4
874 CNC.acceleration_z /= 25.4
875 CNC.feedmax_x /= 25.4
876 CNC.feedmax_y /= 25.4
877 CNC.feedmax_z /= 25.4
878 CNC.travel_x /= 25.4
879 CNC.travel_y /= 25.4
880 CNC.travel_z /= 25.4
881 # a,b,c are in degrees no conversion required
882
883 section = "Error"
884 if CNC.drillPolicy == 1:
885 ERROR_HANDLING["G98"] = 1
886 ERROR_HANDLING["G99"] = 1
887
888 for cmd,value in config.items(section):
889 try:
890 ERROR_HANDLING[cmd.upper()] = int(value)
891 except:
892 pass
893
894 #----------------------------------------------------------------------
895 @staticmethod
896 def saveConfig(config):
897 pass
898
899 #----------------------------------------------------------------------
900 def initPath(self, x=None, y=None, z=None, a=None, b=None, c=None):
901 if x is None:
902 self.x = self.xval = CNC.vars['wx'] or 0
903 else:
904 self.x = self.xval = x
905 if y is None:
906 self.y = self.yval = CNC.vars['wy'] or 0
907 else:
908 self.y = self.yval = y
909 if z is None:
910 self.z = self.zval = CNC.vars['wz'] or 0
911 else:
912 self.z = self.zval = z
913 if a is None:
914 self.a = self.aval = CNC.vars['wa'] or 0
915 else:
916 self.a = self.aval = a
917 if b is None:
918 self.b = self.bval = CNC.vars['wb'] or 0
919 else:
920 self.b = self.bval = b
921 if c is None:
922 self.c = self.cval = CNC.vars['wc'] or 0
923 else:
924 self.c = self.cval = c
925
926 self.ival = self.jval = self.kval = 0.0
927 self.uval = self.vval = self.wval = 0.0
928 self.dx = self.dy = self.dz = 0.0
929 self.di = self.dj = self.dk = 0.0
930 self.rval = 0.0
931 self.pval = 0.0
932 self.qval = 0.0
933 self.unit = 1.0
934 self.mval = 0
935 self.lval = 1
936 self.tool = 0
937 self._lastTool = None
938
939 self.absolute = True # G90/G91 absolute/relative motion
940 self.arcabsolute = False # G90.1/G91.1 absolute/relative arc
941 self.retractz = True # G98/G99 retract to Z or R
942 self.gcode = None
943 self.plane = XY
944 self.feed = 0 # Actual gcode feed rate (not to confuse with cutfeed
945 self.totalLength = 0.0
946 self.totalTime = 0.0
947
948 #----------------------------------------------------------------------
949 def resetEnableMargins(self):
950 # Selected blocks margin
951 CNC.vars["xmin"] = CNC.vars["ymin"] = CNC.vars["zmin"] = 1000000.0
952 CNC.vars["xmax"] = CNC.vars["ymax"] = CNC.vars["zmax"] = -1000000.0
953
954 #----------------------------------------------------------------------
955 def resetAllMargins(self):
956 self.resetEnableMargins()
957 # All blocks margin
958 CNC.vars["axmin"] = CNC.vars["aymin"] = CNC.vars["azmin"] = 1000000.0
959 CNC.vars["axmax"] = CNC.vars["aymax"] = CNC.vars["azmax"] = -1000000.0
960
961 #----------------------------------------------------------------------
962 @staticmethod
963 def isMarginValid():
964 return CNC.vars["xmin"] <= CNC.vars["xmax"] and \
965 CNC.vars["ymin"] <= CNC.vars["ymax"] and \
966 CNC.vars["zmin"] <= CNC.vars["zmax"]
967
968 #----------------------------------------------------------------------
969 @staticmethod
970 def isAllMarginValid():
971 return CNC.vars["axmin"] <= CNC.vars["axmax"] and \
972 CNC.vars["aymin"] <= CNC.vars["aymax"] and \
973 CNC.vars["azmin"] <= CNC.vars["azmax"]
974
975 #----------------------------------------------------------------------
976 # Number formating
977 #----------------------------------------------------------------------
978 @staticmethod
979 def fmt(c, v, d=None):
980 if d is None: d = CNC.digits
981 #Don't know why, but in some cases floats are not truncated by format string unless rounded
982 #I guess it's vital idea to round them rather than truncate anyway!
983 v = round(v, d)
984 return ("%s%*f"%(c,d,v)).rstrip("0").rstrip(".")
985
986 #----------------------------------------------------------------------
987 @staticmethod
988 def gcode(g, pairs):
989 s = "g%d"%(g)
990 for c,v in pairs:
991 s += " %c%g"%(c, round(v,CNC.digits))
992 return s
993
994 #----------------------------------------------------------------------
995 @staticmethod
996 def _gcode(g, **args):
997 s = "g%d"%(g)
998 for n,v in args.items():
999 s += ' ' + CNC.fmt(n,v)
1000 return s
1001
1002 #----------------------------------------------------------------------
1003 @staticmethod
1004 def _gotoABC(g, x=None, y=None, z=None, a=None, b=None, c=None, **args):
1005 s = "g%d"%(g)
1006 if x is not None: s += ' '+CNC.fmt('x',x)
1007 if y is not None: s += ' '+CNC.fmt('y',y)
1008 if z is not None: s += ' '+CNC.fmt('z',z)
1009 if a is not None: s += ' '+CNC.fmt('a',a)
1010 if b is not None: s += ' '+CNC.fmt('b',b)
1011 if c is not None: s += ' '+CNC.fmt('c',c)
1012 for n,v in args.items():
1013 s += ' ' + CNC.fmt(n,v)
1014 return s
1015 @staticmethod
1016 def _goto(g, x=None, y=None, z=None, **args):
1017 s = "g%d"%(g)
1018 if x is not None: s += ' '+CNC.fmt('x',x)
1019 if y is not None: s += ' '+CNC.fmt('y',y)
1020 if z is not None: s += ' '+CNC.fmt('z',z)
1021 for n,v in args.items():
1022 s += ' ' + CNC.fmt(n,v)
1023 return s
1024 #----------------------------------------------------------------------
1025 @staticmethod
1026 def grapidABC(x=None, y=None, z=None, a=None, b=None, c=None, **args):
1027 return CNC._gotoABC(0,x,y,z,a,b,c,**args)
1028 @staticmethod
1029 def grapid(x=None, y=None, z=None, **args):
1030 return CNC._goto(0,x,y,z,**args)
1031
1032 #----------------------------------------------------------------------
1033 @staticmethod
1034 def glineABC(x=None, y=None, z=None, a=None, b=None, c=None, **args):
1035 return CNC._gotoABC(1,x,y,z,a,b,c,**args)
1036 @staticmethod
1037 def gline(x=None, y=None, z=None, **args):
1038 return CNC._goto(1,x,y,z,**args)
1039
1040 #----------------------------------------------------------------------
1041 @staticmethod
1042 def glinev(g, v, feed=None):
1043 pairs = to_zip("xyz",v)
1044 if feed is not None:
1045 pairs.append(("f",feed))
1046 return CNC.gcode(g, pairs)
1047
1048 #----------------------------------------------------------------------
1049 @staticmethod
1050 def garcv(g, v, ijk):
1051 return CNC.gcode(g, to_zip("xyz",v) + to_zip("ij",ijk[:2]))
1052
1053 #----------------------------------------------------------------------
1054 @staticmethod
1055 def garc(g, x=None, y=None, z=None, i=None, j=None, k=None, **args):
1056 s = "g%d"%(g)
1057 if x is not None: s += ' '+CNC.fmt('x',x)
1058 if y is not None: s += ' '+CNC.fmt('y',y)
1059 if z is not None: s += ' '+CNC.fmt('z',z)
1060 if i is not None: s += ' '+CNC.fmt('i',i)
1061 if j is not None: s += ' '+CNC.fmt('j',j)
1062 if k is not None: s += ' '+CNC.fmt('k',k)
1063 for n,v in args.items():
1064 s += ' ' + CNC.fmt(n,v)
1065 return s
1066
1067 #----------------------------------------------------------------------
1068 # Enter to material or start the laser
1069 #----------------------------------------------------------------------
1070 @staticmethod
1071 def zenter(z, d=None):
1072 if CNC.lasercutter:
1073 if CNC.laseradaptive:
1074 return "m4"
1075 else:
1076 return "m3"
1077 else:
1078 return "g1 %s %s"%(CNC.fmt("z",z,d), CNC.fmt("f",CNC.vars["cutfeedz"]))
1079
1080 #----------------------------------------------------------------------
1081 @staticmethod
1082 def zexit(z, d=None):
1083 if CNC.lasercutter:
1084 return "m5"
1085 else:
1086 return "g0 %s"%(CNC.fmt("z",z,d))
1087
1088 #----------------------------------------------------------------------
1089 # gcode to go to z-safe
1090 # Exit from material or stop the laser
1091 #----------------------------------------------------------------------
1092 @staticmethod
1093 def zsafe():
1094 return CNC.zexit(CNC.vars["safe"])
1095
1096 #----------------------------------------------------------------------
1097 # @return line in broken a list of commands, None if empty or comment
1098 #----------------------------------------------------------------------
1099 @staticmethod
1100 def parseLine(line):
1101 # skip empty lines
1102 if len(line)==0 or line[0] in ("%","(","#",";"):
1103 return None
1104
1105 # remove comments
1106 line = PARENPAT.sub("",line)
1107 line = SEMIPAT.sub("",line)
1108
1109 # process command
1110 # strip all spaces
1111 line = line.replace(" ","")
1112
1113 # Insert space before each command
1114 line = CMDPAT.sub(r" \1",line).lstrip()
1115 return line.split()
1116
1117 # -----------------------------------------------------------------------------
1118 # @return line,comment
1119 # line broken in a list of commands,
1120 # None,"" if empty or comment
1121 # else compiled expressions,""
1122 #----------------------------------------------------------------------
1123 @staticmethod
1124 def compileLine(line, space=False):
1125 line = line.strip()
1126 if not line: return None
1127 if line[0] == "$": return line
1128
1129 # to accept #nnn variables as _nnn internally
1130 line = line.replace('#','_')
1131 CNC.comment = ""
1132
1133 # execute literally the line after the first character
1134 if line[0]=='%':
1135 # special command
1136 pat = AUXPAT.match(line.strip())
1137 if pat:
1138 cmd = pat.group(1)
1139 args = pat.group(2)
1140 else:
1141 cmd = None
1142 args = None
1143 if cmd=="%wait":
1144 return (WAIT,)
1145 elif cmd=="%msg":
1146 if not args: args = None
1147 return (MSG, args)
1148 elif cmd=="%update":
1149 return (UPDATE, args)
1150 elif line.startswith("%if running") and not CNC.vars["running"]:
1151 # ignore if running lines when not running
1152 return None
1153 else:
1154 try:
1155 return compile(line[1:],"","exec")
1156 except Exception as e:
1157 print("Compile line error: \n")
1158 print(e)
1159 return None
1160
1161 # most probably an assignment like #nnn = expr
1162 if line[0]=='_':
1163 try:
1164 return compile(line,"","exec")
1165 except:
1166 # FIXME show the error!!!!
1167 return None
1168
1169 # commented line
1170 if line[0] == ';':
1171 CNC.comment = line[1:].strip()
1172 return None
1173
1174 out = [] # output list of commands
1175 braket = 0 # bracket count []
1176 paren = 0 # parenthesis count ()
1177 expr = "" # expression string
1178 cmd = "" # cmd string
1179 inComment = False # inside inComment
1180 for i,ch in enumerate(line):
1181 if ch == '(':
1182 # comment start?
1183 paren += 1
1184 inComment = (braket==0)
1185 if not inComment:
1186 expr += ch
1187 elif ch == ')':
1188 # comment end?
1189 paren -= 1
1190 if not inComment: expr += ch
1191 if paren==0 and inComment: inComment=False
1192 elif ch == '[':
1193 # expression start?
1194 if not inComment:
1195 if CNC.stdexpr: ch='('
1196 braket += 1
1197 if braket==1:
1198 if cmd:
1199 out.append(cmd)
1200 cmd = ""
1201 else:
1202 expr += ch
1203 else:
1204 CNC.comment += ch
1205 elif ch == ']':
1206 # expression end?
1207 if not inComment:
1208 if CNC.stdexpr: ch=')'
1209 braket -= 1
1210 if braket==0:
1211 try:
1212 out.append(compile(expr,"","eval"))
1213 except:
1214 # FIXME show the error!!!!
1215 pass
1216 #out.append("<<"+expr+">>")
1217 expr = ""
1218 else:
1219 expr += ch
1220 else:
1221 CNC.comment += ch
1222 elif ch=='=':
1223 # check for assignments (FIXME very bad)
1224 if not out and braket==0 and paren==0:
1225 for i in " ()-+*/^$":
1226 if i in cmd:
1227 cmd += ch
1228 break
1229 else:
1230 try:
1231 return compile(line,"","exec")
1232 except:
1233 # FIXME show the error!!!!
1234 return None
1235 elif ch == ';':
1236 # Skip everything after the semicolon on normal lines
1237 if not inComment and paren==0 and braket==0:
1238 CNC.comment += line[i+1:]
1239 break
1240 else:
1241 expr += ch
1242
1243 elif braket>0:
1244 expr += ch
1245
1246 elif not inComment:
1247 if ch == ' ':
1248 if space:
1249 cmd += ch
1250 else:
1251 cmd += ch
1252
1253 elif inComment:
1254 CNC.comment += ch
1255
1256 if cmd: out.append(cmd)
1257
1258 # return output commands
1259 if len(out)==0:
1260 return None
1261 if len(out)>1:
1262 return out
1263 return out[0]
1264
1265 #----------------------------------------------------------------------
1266 # Break line into commands
1267 #----------------------------------------------------------------------
1268 @staticmethod
1269 def breakLine(line):
1270 if line is None: return None
1271 # Insert space before each command
1272 line = CMDPAT.sub(r" \1",line).lstrip()
1273 return line.split()
1274
1275 #----------------------------------------------------------------------
1276 # Create path for one g command
1277 #----------------------------------------------------------------------
1278 def motionStart(self, cmds):
1279 #print "\n<<<",cmds
1280 self.mval = 0 # reset m command
1281 for cmd in cmds:
1282 c = cmd[0].upper()
1283 try:
1284 value = float(cmd[1:])
1285 except:
1286 value = 0
1287
1288 if c == "X":
1289 self.xval = value*self.unit
1290 if not self.absolute:
1291 self.xval += self.x
1292 self.dx = self.xval - self.x
1293
1294 elif c == "Y":
1295 self.yval = value*self.unit
1296 if not self.absolute:
1297 self.yval += self.y
1298 self.dy = self.yval - self.y
1299
1300 elif c == "Z":
1301 self.zval = value*self.unit
1302 if not self.absolute:
1303 self.zval += self.z
1304 self.dz = self.zval - self.z
1305
1306 elif c == "A":
1307 self.aval = value*self.unit
1308
1309 elif c == "F":
1310 self.feed = value*self.unit
1311
1312 elif c == "G":
1313 gcode = int(value)
1314 decimal = int(round((value - gcode)*10))
1315
1316 # Execute immediately
1317 if gcode in (4,10,53):
1318 pass # do nothing but don't record to motion
1319 elif gcode==17:
1320 self.plane = XY
1321
1322 elif gcode==18:
1323 self.plane = XZ
1324
1325 elif gcode==19:
1326 self.plane = YZ
1327
1328 elif gcode==20: # Switch to inches
1329 if CNC.inch:
1330 self.unit = 1.0
1331 else:
1332 self.unit = 25.4
1333
1334 elif gcode==21: # Switch to mm
1335 if CNC.inch:
1336 self.unit = 1.0/25.4
1337 else:
1338 self.unit = 1.0
1339
1340 elif gcode==80:
1341 # turn off canned cycles
1342 self.gcode = None
1343 self.dz = 0
1344 self.zval = self.z
1345
1346 elif gcode==90:
1347 if decimal == 0:
1348 self.absolute = True
1349 elif decimal == 1:
1350 self.arcabsolute = True
1351
1352 elif gcode==91:
1353 if decimal == 0:
1354 self.absolute = False
1355 elif decimal == 1:
1356 self.arcabsolute = False
1357
1358 elif gcode in (93,94,95):
1359 CNC.vars["feedmode"] = gcode
1360
1361 elif gcode==98:
1362 self.retractz = True
1363
1364 elif gcode==99:
1365 self.retractz = False
1366
1367 else:
1368 self.gcode = gcode
1369
1370 elif c == "I":
1371 self.ival = value*self.unit
1372 if self.arcabsolute:
1373 self.ival -= self.x
1374
1375 elif c == "J":
1376 self.jval = value*self.unit
1377 if self.arcabsolute:
1378 self.jval -= self.y
1379
1380 elif c == "K":
1381 self.kval = value*self.unit
1382 if self.arcabsolute:
1383 self.kval -= self.z
1384
1385 elif c == "L":
1386 self.lval = int(value)
1387
1388 elif c == "M":
1389 self.mval = int(value)
1390
1391 elif c == "N":
1392 pass
1393
1394 elif c == "P":
1395 self.pval = value
1396
1397 elif c == "Q":
1398 self.qval = value*self.unit
1399
1400 elif c == "R":
1401 self.rval = value*self.unit
1402
1403 elif c == "T":
1404 self.tool = int(value)
1405
1406 elif c == "U":
1407 self.uval = value*self.unit
1408
1409 elif c == "V":
1410 self.vval = value*self.unit
1411
1412 elif c == "W":
1413 self.wval = value*self.unit
1414
1415 #----------------------------------------------------------------------
1416 # Return center x,y,z,r for arc motions 2,3 and set self.rval
1417 #----------------------------------------------------------------------
1418 def motionCenter(self):
1419 if self.rval>0.0:
1420 if self.plane == XY:
1421 x = self.x
1422 y = self.y
1423 xv = self.xval
1424 yv = self.yval
1425 elif self.plane == XZ:
1426 x = self.x
1427 y = self.z
1428 xv = self.xval
1429 yv = self.zval
1430 else:
1431 x = self.y
1432 y = self.z
1433 xv = self.yval
1434 yv = self.zval
1435
1436 ABx = xv-x
1437 ABy = yv-y
1438 Cx = 0.5*(x+xv)
1439 Cy = 0.5*(y+yv)
1440 AB = math.sqrt(ABx**2 + ABy**2)
1441 try: OC = math.sqrt(self.rval**2 - AB**2/4.0)
1442 except: OC = 0.0
1443 if self.gcode==2: OC = -OC # CW
1444 if AB != 0.0:
1445 return Cx-OC*ABy/AB, Cy + OC*ABx/AB
1446 else:
1447 # Error!!!
1448 return x,y
1449 else:
1450 # Center
1451 xc = self.x + self.ival
1452 yc = self.y + self.jval
1453 zc = self.z + self.kval
1454 self.rval = math.sqrt(self.ival**2 + self.jval**2 + self.kval**2)
1455
1456 if self.plane == XY:
1457 return xc,yc
1458 elif self.plane == XZ:
1459 return xc,zc
1460 else:
1461 return yc,zc
1462
1463 # Error checking
1464 #err = abs(self.rval - math.sqrt((self.xval-xc)**2 + (self.yval-yc)**2 + (self.zval-zc)**2))
1465 #if err/self.rval>0.001:
1466 #print "Error invalid arc", self.xval, self.yval, self.zval, err
1467 #return xc,yc,zc
1468
1469 #----------------------------------------------------------------------
1470 # Create path for one g command
1471 #----------------------------------------------------------------------
1472 def motionPath(self):
1473 xyz = []
1474
1475 # Execute g-code
1476 if self.gcode in (0,1): # fast move or line
1477 if self.xval-self.x != 0.0 or \
1478 self.yval-self.y != 0.0 or \
1479 self.zval-self.z != 0.0:
1480 xyz.append((self.x,self.y,self.z))
1481 xyz.append((self.xval,self.yval,self.zval))
1482
1483 elif self.gcode in (2,3): # CW=2,CCW=3 circle
1484 xyz.append((self.x,self.y,self.z))
1485 uc,vc = self.motionCenter()
1486
1487 gcode = self.gcode
1488 if self.plane == XY:
1489 u0 = self.x
1490 v0 = self.y
1491 w0 = self.z
1492 u1 = self.xval
1493 v1 = self.yval
1494 w1 = self.zval
1495 elif self.plane == XZ:
1496 u0 = self.x
1497 v0 = self.z
1498 w0 = self.y
1499 u1 = self.xval
1500 v1 = self.zval
1501 w1 = self.yval
1502 gcode = 5-gcode # flip 2-3 when XZ plane is used
1503 else:
1504 u0 = self.y
1505 v0 = self.z
1506 w0 = self.x
1507 u1 = self.yval
1508 v1 = self.zval
1509 w1 = self.xval
1510 phi0 = math.atan2(v0-vc, u0-uc)
1511 phi1 = math.atan2(v1-vc, u1-uc)
1512 try:
1513 sagitta = 1.0-CNC.accuracy/self.rval
1514 except ZeroDivisionError:
1515 sagitta = 0.0
1516 if sagitta>0.0:
1517 df = 2.0*math.acos(sagitta)
1518 df = min(df, math.pi/4.0)
1519 else:
1520 df = math.pi/4.0
1521
1522 if gcode==2:
1523 if phi1>=phi0-1e-10: phi1 -= 2.0*math.pi
1524 ws = (w1-w0)/(phi1-phi0)
1525 phi = phi0 - df
1526 while phi>phi1:
1527 u = uc + self.rval*math.cos(phi)
1528 v = vc + self.rval*math.sin(phi)
1529 w = w0 + (phi-phi0)*ws
1530 phi -= df
1531 if self.plane == XY:
1532 xyz.append((u,v,w))
1533 elif self.plane == XZ:
1534 xyz.append((u,w,v))
1535 else:
1536 xyz.append((w,u,v))
1537 else:
1538 if phi1<=phi0+1e-10: phi1 += 2.0*math.pi
1539 ws = (w1-w0)/(phi1-phi0)
1540 phi = phi0 + df
1541 while phi<phi1:
1542 u = uc + self.rval*math.cos(phi)
1543 v = vc + self.rval*math.sin(phi)
1544 w = w0 + (phi-phi0)*ws
1545 phi += df
1546 if self.plane == XY:
1547 xyz.append((u,v,w))
1548 elif self.plane == XZ:
1549 xyz.append((u,w,v))
1550 else:
1551 xyz.append((w,u,v))
1552
1553 xyz.append((self.xval,self.yval,self.zval))
1554
1555 elif self.gcode==4: # Dwell
1556 self.totalTime = self.pval
1557
1558 elif self.gcode in (81,82,83,85,86,89): # Canned cycles
1559 #print "x=",self.x
1560 #print "y=",self.y
1561 #print "z=",self.z
1562 #print "dx=",self.dx
1563 #print "dy=",self.dy
1564 #print "dz=",self.dz
1565 #print "abs=",self.absolute,"retract=",self.retractz
1566
1567 # FIXME Assuming only on plane XY
1568 if self.absolute:
1569 # FIXME is it correct?
1570 self.lval = 1
1571 if self.retractz:
1572 clearz = max(self.rval, self.z)
1573 else:
1574 clearz = self.rval
1575 drill = self.zval
1576 else:
1577 clearz = self.z + self.rval
1578 drill = clearz + self.dz
1579 #print "clearz=",clearz
1580 #print "drill=",drill
1581
1582 x,y,z = self.x, self.y, self.z
1583 xyz.append((x,y,z))
1584 if z != clearz:
1585 z = clearz
1586 xyz.append((x,y,z))
1587 for l in range(self.lval):
1588 # Rapid move parallel to XY
1589 x += self.dx
1590 y += self.dy
1591 xyz.append((x,y,z))
1592
1593 # Rapid move parallel to clearz
1594 if self.z > clearz:
1595 xyz.append((x,y,clearz))
1596
1597 # Drill to z
1598 xyz.append((x,y,drill))
1599
1600 # Move to original position
1601 z = clearz
1602 xyz.append((x,y,z)) # ???
1603
1604 #for a in xyz: print a
1605
1606 return xyz
1607
1608 #----------------------------------------------------------------------
1609 # move to end position
1610 #----------------------------------------------------------------------
1611 def motionEnd(self):
1612 #print "x=",self.x
1613 #print "y=",self.y
1614 #print "z=",self.z
1615 #print "dx=",self.dx
1616 #print "dy=",self.dy
1617 #print "dz=",self.dz
1618 #print "abs=",self.absolute,"retract=",self.retractz
1619
1620 if self.gcode in (0,1,2,3):
1621 self.x = self.xval
1622 self.y = self.yval
1623 self.z = self.zval
1624 self.dx = 0
1625 self.dy = 0
1626 self.dz = 0
1627
1628 if self.gcode >= 2: # reset at the end
1629 self.rval = self.ival = self.jval = self.kval = 0.0
1630
1631 elif self.gcode in (28,30,92):
1632 self.x = 0.0
1633 self.y = 0.0
1634 self.z = 0.0
1635 self.dx = 0
1636 self.dy = 0
1637 self.dz = 0
1638
1639 # FIXME L is not taken into account for repetitions!!!
1640 elif self.gcode in (81,82,83):
1641 # FIXME Assuming only on plane XY
1642 if self.absolute:
1643 self.lval = 1
1644 if self.retractz:
1645 retract = max(self.rval, self.z)
1646 else:
1647 retract = self.rval
1648 drill = self.zval
1649 else:
1650 retract = self.z + self.rval
1651 drill = retract + self.dz
1652
1653 self.x += self.dx*self.lval
1654 self.y += self.dy*self.lval
1655 self.z = retract
1656
1657 self.xval = self.x
1658 self.yval = self.y
1659 self.dx = 0
1660 self.dy = 0
1661 self.dz = drill - retract
1662
1663 #----------------------------------------------------------------------
1664 # Doesn't work correctly for G83 (peck drilling)
1665 #----------------------------------------------------------------------
1666 def pathLength(self, block, xyz):
1667 # For XY plane
1668 p = xyz[0]
1669 length = 0.0
1670 for i in xyz:
1671 length += math.sqrt((i[0]-p[0])**2 + (i[1]-p[1])**2 + (i[2]-p[2])**2)
1672 p = i
1673
1674 if self.gcode == 0:
1675 # FIXME calculate the correct time with the feed direction
1676 # and acceleration
1677 block.time += length / self.feedmax_x
1678 self.totalTime += length / self.feedmax_x
1679 block.rapid += length
1680 elif (self.gcode == 1 or self.gcode==2 or self.gcode==3) and self.feed >0 :
1681 block.time += length / self.feed
1682 self.totalTime += length / self.feed
1683 else:
1684 try:
1685 if CNC.vars["feedmode"] == 94:
1686 # Normal mode
1687 t = length / self.feed
1688 elif CNC.vars["feedmode"] == 93:
1689 # Inverse mode
1690 t = length * self.feed
1691 block.time += t
1692 self.totalTime += t
1693 except:
1694 pass
1695 block.length += length
1696
1697 self.totalLength += length
1698
1699 #----------------------------------------------------------------------
1700 def pathMargins(self, block):
1701 if block.enable:
1702 CNC.vars["xmin"] = min(CNC.vars["xmin"], block.xmin)
1703 CNC.vars["ymin"] = min(CNC.vars["ymin"], block.ymin)
1704 CNC.vars["zmin"] = min(CNC.vars["zmin"], block.zmin)
1705 CNC.vars["xmax"] = max(CNC.vars["xmax"], block.xmax)
1706 CNC.vars["ymax"] = max(CNC.vars["ymax"], block.ymax)
1707 CNC.vars["zmax"] = max(CNC.vars["zmax"], block.zmax)
1708
1709 CNC.vars["axmin"] = min(CNC.vars["axmin"], block.xmin)
1710 CNC.vars["aymin"] = min(CNC.vars["aymin"], block.ymin)
1711 CNC.vars["azmin"] = min(CNC.vars["azmin"], block.zmin)
1712 CNC.vars["axmax"] = max(CNC.vars["axmax"], block.xmax)
1713 CNC.vars["aymax"] = max(CNC.vars["aymax"], block.ymax)
1714 CNC.vars["azmax"] = max(CNC.vars["azmax"], block.zmax)
1715
1716 #----------------------------------------------------------------------
1717 # Instead of the current code, override with the custom user lines
1718 # @param program a list of lines to execute
1719 # @return the new list of lines
1720 #----------------------------------------------------------------------
1721 @staticmethod
1722 def compile(program):
1723 lines = []
1724 for j,line in enumerate(program):
1725 newcmd = []
1726 cmds = CNC.compileLine(line)
1727 if cmds is None: continue
1728 if isinstance(cmds,str):
1729 cmds = CNC.breakLine(cmds)
1730 else:
1731 # either CodeType or tuple, list[] append it as is
1732 lines.append(cmds)
1733 continue
1734
1735 for cmd in cmds:
1736 c = cmd[0]
1737 try: value = float(cmd[1:])
1738 except: value = 0.0
1739 if c.upper() in ("F","X","Y","Z","I","J","K","R","P"):
1740 cmd = CNC.fmt(c,value)
1741 else:
1742 opt = ERROR_HANDLING.get(cmd.upper(),0)
1743 if opt == SKIP: cmd = None
1744
1745 if cmd is not None:
1746 newcmd.append(cmd)
1747 lines.append("".join(newcmd))
1748 return lines
1749
1750 #----------------------------------------------------------------------
1751 # code to change manually tool
1752 #----------------------------------------------------------------------
1753 def toolChange(self, tool=None):
1754 if tool is not None:
1755 # Force a change
1756 self.tool = tool
1757 self._lastTool = None
1758
1759 # check if it is the same tool
1760 if self.tool is None or self.tool == self._lastTool: return []
1761
1762 # create the necessary code
1763 lines = []
1764 lines.append("$g") # remember state and populate variables, FIXME: move to ./controllers/_GenericController.py
1765 lines.append("m5") # stop spindle
1766 lines.append("%wait")
1767 lines.append("%_x,_y,_z = wx,wy,wz") # remember position
1768 lines.append("g53 g0 z[toolchangez]")
1769 lines.append("g53 g0 x[toolchangex] y[toolchangey]")
1770 lines.append("%wait")
1771
1772 if CNC.comment:
1773 lines.append("%%msg Tool change T%02d (%s)"%(self.tool,CNC.comment))
1774 else:
1775 lines.append("%%msg Tool change T%02d"%(self.tool))
1776 lines.append("m0") # feed hold
1777
1778 if CNC.toolPolicy < 4:
1779 lines.append("g53 g0 x[toolprobex] y[toolprobey]")
1780 lines.append("g53 g0 z[toolprobez]")
1781
1782 # fixed WCS
1783 if CNC.vars["fastprbfeed"]:
1784 prb_reverse = {"2": "4", "3": "5", "4": "2", "5": "3"}
1785 CNC.vars["prbcmdreverse"] = (CNC.vars["prbcmd"][:-1] +
1786 prb_reverse[CNC.vars["prbcmd"][-1]])
1787 currentFeedrate = CNC.vars["fastprbfeed"]
1788 while currentFeedrate > CNC.vars["prbfeed"]:
1789 lines.append("%wait")
1790 lines.append("g91 [prbcmd] %s z[toolprobez-mz-tooldistance]" \
1791 % CNC.fmt('f',currentFeedrate))
1792 lines.append("%wait")
1793 lines.append("[prbcmdreverse] %s z[toolprobez-mz]" \
1794 % CNC.fmt('f',currentFeedrate))
1795 currentFeedrate /= 10
1796 lines.append("%wait")
1797 lines.append("g91 [prbcmd] f[prbfeed] z[toolprobez-mz-tooldistance]")
1798
1799 if CNC.toolPolicy==2:
1800 # Adjust the current WCS to fit to the tool
1801 # FIXME could be done dynamically in the code
1802 p = WCS.index(CNC.vars["WCS"])+1
1803 lines.append("g10l20p%d z[toolheight]"%(p))
1804 lines.append("%wait")
1805
1806 elif CNC.toolPolicy==3:
1807 # Modify the tool length, update the TLO
1808 lines.append("g4 p1") # wait a sec to get the probe info
1809 lines.append("%wait")
1810 lines.append("%global TLO; TLO=prbz-toolmz")
1811 lines.append("g43.1z[TLO]")
1812 lines.append("%update TLO")
1813
1814 lines.append("g53 g0 z[toolchangez]")
1815 lines.append("g53 g0 x[toolchangex] y[toolchangey]")
1816
1817 if CNC.toolWaitAfterProbe:
1818 lines.append("%wait")
1819 lines.append("%msg Restart spindle")
1820 lines.append("m0") # feed hold
1821
1822 # restore state
1823 lines.append("g90") # restore mode
1824 lines.append("g0 x[_x] y[_y]") # ... x,y position
1825 lines.append("g0 z[_z]") # ... z position
1826 lines.append("f[feed] [spindle]")# ... feed and spindle
1827 lines.append("g4 p5") # wait 5s for spindle to speed up
1828
1829 # remember present tool
1830 self._lastTool = self.tool
1831 return lines
1832
1833 #----------------------------------------------------------------------
1834 # code to expand G80-G89 macro code - canned cycles
1835 # example:
1836 # code to expand G83 code - peck drilling cycle
1837 # format: (G98 / G99 opt.) G83 X~ Y~ Z~ A~ R~ L~ Q~
1838 # example: N150 G98 G83 Z-1.202 R18. Q10. F50.
1839 # ...
1840 # G80
1841 # Notes: G98, G99, Z, R, Q, F are unordered parameters
1842 #----------------------------------------------------------------------
1843 def macroGroupG8X(self):
1844 lines = []
1845
1846 #print "x=",self.x
1847 #print "y=",self.y
1848 #print "z=",self.z
1849 #print "dx=",self.dx
1850 #print "dy=",self.dy
1851 #print "dz=",self.dz
1852 #print "abs=",self.absolute,"retract=",self.retractz
1853
1854 # FIXME Assuming only on plane XY
1855 if self.absolute:
1856 # FIXME is it correct?
1857 self.lval = 1
1858 if self.retractz:
1859 clearz = max(self.rval, self.z)
1860 else:
1861 clearz = self.rval
1862 drill = self.zval
1863 retract = self.rval
1864 else:
1865 clearz = self.z + self.rval
1866 retract = clearz
1867 drill = clearz + self.dz
1868 #print "clearz=",clearz
1869 #print "drill=",drill
1870
1871 if self.gcode == 83: # peck drilling
1872 peck = self.qval
1873 else:
1874 peck = 100000.0 # a large value
1875
1876 x,y,z = self.x, self.y, self.z
1877 if z < clearz:
1878 z = clearz
1879 lines.append(CNC.grapid(z=z/self.unit))
1880
1881 for l in range(self.lval):
1882 # Rapid move parallel to XY
1883 x += self.dx
1884 y += self.dy
1885 lines.append(CNC.grapid(x/self.unit,y/self.unit))
1886
1887 # Rapid move parallel to retract
1888 zstep = max(drill, retract - peck)
1889 while z > drill:
1890 if z != retract:
1891 z = retract
1892 lines.append(CNC.grapid(z=z/self.unit))
1893
1894 z = max(drill, zstep)
1895 zstep -= peck
1896
1897 # Drill to z
1898 lines.append(CNC.gline(z=z/self.unit,f=self.feed/self.unit))
1899
1900 # 82=dwell, 86=boring-stop, 89=boring-dwell
1901 if self.gcode in (82,86,89):
1902 lines.append(CNC._gcode(4,p=self.pval))
1903
1904 if self.gcode == 86:
1905 lines.append("M5") # stop spindle???
1906
1907 # Move to original position
1908 if self.gcode in (85,89): # boring cycle
1909 z = retract
1910 lines.append(CNC.gline(z=z/self.unit,f=self.feed/self.unit))
1911
1912 z = clearz
1913 lines.append(CNC.grapid(z=z/self.unit))
1914
1915 if self.gcode == 86:
1916 lines.append("M3") # restart spindle???
1917 #print "-"*50
1918 #for a in lines: print a
1919 #print "-"*50
1920 return lines
1921
1922
1923 #===============================================================================
1924 # Block of g-code commands. A gcode file is represented as a list of blocks
1925 # - Commands are grouped as (non motion commands Mxxx)
1926 # - Basic shape from the first rapid move command to the last rapid z raise
1927 # above the working surface
1928 #
1929 # Inherits from list and contains:
1930 # - a list list of gcode lines
1931 # - (imported shape)
1932 #===============================================================================
1933 class Block(list):
1934 def __init__(self, name=None):
1935 # Copy constructor
1936 if isinstance(name, Block):
1937 self.copy(name)
1938 return
1939 self._name = name
1940 self.enable = True # Enabled/Visible in drawing
1941 self.expand = False # Expand in editor
1942 self.color = None # Custom color for path
1943 self._path = [] # canvas drawing paths
1944 self.sx = self.sy = self.sz = 0 # start coordinates
1945 # (entry point first non rapid motion)
1946 self.ex = self.ey = self.ez = 0 # ending coordinates
1947 self.resetPath()
1948
1949 #----------------------------------------------------------------------
1950 def copy(self, src):
1951 self._name = src._name
1952 self.enable = src.enable
1953 self.expand = src.expand
1954 self.color = src.color
1955 self[:] = src[:]
1956 self._path = []
1957 self.sx = src.sx
1958 self.sy = src.sy
1959 self.sz = src.sz
1960 self.ex = src.ex
1961 self.ey = src.ey
1962 self.ez = src.ez
1963
1964 #----------------------------------------------------------------------
1965 def name(self):
1966 return self._name is None and "block" or self._name
1967
1968 #----------------------------------------------------------------------
1969 # @return name without the operation
1970 #----------------------------------------------------------------------
1971 def nameNop(self):
1972 name = self.name()
1973 pat = OPPAT.match(name)
1974 if pat is None:
1975 return name
1976 else:
1977 return pat.group(1).strip()
1978
1979 #----------------------------------------------------------------------
1980 # Tests if block contains operation type
1981 #----------------------------------------------------------------------
1982 def operationTest(self, op, name=None):
1983 if name is None: name = self.name()
1984 pat = OPPAT.match(name)
1985 if pat is not None:
1986 ops = pat.group(2)
1987 ops = re.split('\W+', ops)
1988 if op in ops: return True
1989 return False
1990
1991 #----------------------------------------------------------------------
1992 # Get block operation value
1993 #----------------------------------------------------------------------
1994 def operationGet(self, op, name=None):
1995 if name is None: name = self.name()
1996 pat = OPPAT.match(name)
1997 if pat is not None:
1998 ops = pat.group(2)
1999 ops = re.split(',', ops)
2000 for opp in ops:
2001 t = re.split(':',opp)
2002 if t[0] == op: return t[1]
2003 return None
2004
2005 #----------------------------------------------------------------------
2006 # Tests if block contains operation on inside of the part (-1), outside (1), or can't decide (0)
2007 #----------------------------------------------------------------------
2008 def operationSide(self, name=None):
2009 if self.operationTest('pocket', name): return -1
2010 if self.operationTest('in', name) and not self.operationTest('out', name): return -1
2011 if self.operationTest('out', name) and not self.operationTest('in', name): return 1
2012 return 0
2013
2014 #----------------------------------------------------------------------
2015 # @return the new name with an operation (static)
2016 #----------------------------------------------------------------------
2017 @staticmethod
2018 def operationName(name, operation, remove=None):
2019 pat = OPPAT.match(name)
2020 if pat is None:
2021 return "%s [%s]"%(name,operation)
2022 else:
2023 name = pat.group(1).strip()
2024 ops = pat.group(2).split(',')
2025 if ":" in operation:
2026 oid,opt = operation.split(":")
2027 else:
2028 oid = operation
2029 opt = None
2030
2031 found = False
2032 for i,o in enumerate(ops):
2033 if ":" in o:
2034 o,c = o.split(":")
2035 try:
2036 c = int(c)
2037 except:
2038 c = 1
2039 else:
2040 c = 1
2041
2042 if remove and o in remove: ops[i]=""
2043 if not found and o==oid:
2044 if opt is not None or c is None:
2045 ops[i] = operation
2046 else:
2047 ops[i] = "%s:%d"%(oid,c+1)
2048 found = True
2049
2050 # remove all empty
2051 ops = list(filter(lambda x:x!="", ops))
2052
2053 if not found:
2054 ops.append(operation)
2055
2056 return "%s [%s]"%(name,','.join(ops))
2057
2058 #----------------------------------------------------------------------
2059 # Add a new operation to the block's name
2060 #----------------------------------------------------------------------
2061 def addOperation(self, operation, remove=None):
2062 n = self.name()
2063 self._name = Block.operationName(self.name(), operation, remove)
2064
2065 #----------------------------------------------------------------------
2066 def header(self):
2067 e = self.expand and Unicode.BLACK_DOWN_POINTING_TRIANGLE \
2068 or Unicode.BLACK_RIGHT_POINTING_TRIANGLE
2069 v = self.enable and Unicode.BALLOT_BOX_WITH_X \
2070 or Unicode.BALLOT_BOX
2071 try:
2072 return "%s %s %s - [%d]"%(e, v, self.name(), len(self))
2073 except UnicodeDecodeError:
2074 return "%s %s %s - [%d]"%(e, v, self.name().decode("ascii","replace"), len(self)) #TODO: is this OK?
2075
2076 #----------------------------------------------------------------------
2077 def write_header(self):
2078 header = ''
2079 header += "(Block-name: %s)\n"%(self.name())
2080 header += "(Block-expand: %d)\n"%(int(self.expand))
2081 header += "(Block-enable: %d)\n"%(int(self.enable))
2082 if self.color:
2083 header += "(Block-color: %s)\n"%(self.color)
2084 return header
2085
2086 def write(self, f):
2087 f.write(self.write_header())
2088 for line in self:
2089 if self.enable: f.write("%s\n"%(line))
2090 else: f.write("(Block-X: %s)\n"%(line.replace('(','[').replace(')',']')))
2091
2092 #----------------------------------------------------------------------
2093 # Return a dump object for pickler
2094 #----------------------------------------------------------------------
2095 def dump(self):
2096 return self.name(), self.enable, self.expand, self.color, self
2097
2098 #----------------------------------------------------------------------
2099 # Create a block from a dump object from unpickler
2100 #----------------------------------------------------------------------
2101 @staticmethod
2102 def load(obj):
2103 name, enable, expand, color, code = obj
2104 block = Block(name)
2105 block.enable = enable
2106 block.expand = expand
2107 block.color = color
2108 block.extend(code)
2109 return block
2110
2111 #----------------------------------------------------------------------
2112 def append(self, line):
2113 if line.startswith("(Block-"):
2114 pat = BLOCKPAT.match(line)
2115 if pat:
2116 name, value = pat.groups()
2117 value = value.strip()
2118 if name=="name":
2119 self._name = value
2120 return
2121 elif name=="expand":
2122 self.expand = bool(int(value))
2123 return
2124 elif name=="enable":
2125 self.enable = bool(int(value))
2126 return
2127 elif name=="tab":
2128 #Handled elsewhere
2129 return
2130 elif name=="color":
2131 self.color = value
2132 return
2133 elif name=="X": #uncomment
2134 list.append(self, value.replace('[','(').replace(']',')'))
2135 return
2136 if self._name is None and ("id:" in line) and ("End" not in line):
2137 pat = IDPAT.match(line)
2138 if pat: self._name = pat.group(1)
2139 list.append(self, line)
2140
2141 #----------------------------------------------------------------------
2142 def resetPath(self):
2143 del self._path[:]
2144 self.xmin = self.ymin = self.zmin = 1000000.0
2145 self.xmax = self.ymax = self.zmax = -1000000.0
2146 self.length = 0.0 # cut length
2147 self.rapid = 0.0 # rapid length
2148 self.time = 0.0
2149
2150 #----------------------------------------------------------------------
2151 def hasPath(self):
2152 return bool(self._path)
2153
2154 #----------------------------------------------------------------------
2155 def addPath(self, p):
2156 self._path.append(p)
2157
2158 #----------------------------------------------------------------------
2159 def path(self, item):
2160 try:
2161 return self._path[item]
2162 except:
2163 return None
2164
2165 #----------------------------------------------------------------------
2166 def startPath(self, x, y, z):
2167 self.sx = x
2168 self.sy = y
2169 self.sz = z
2170
2171 #----------------------------------------------------------------------
2172 def endPath(self, x, y, z):
2173 self.ex = x
2174 self.ey = y
2175 self.ez = z
2176
2177 #----------------------------------------------------------------------
2178 def pathMargins(self, xyz):
2179 self.xmin = min(self.xmin, min([i[0] for i in xyz]))
2180 self.ymin = min(self.ymin, min([i[1] for i in xyz]))
2181 self.zmin = min(self.zmin, min([i[2] for i in xyz]))
2182 self.xmax = max(self.xmax, max([i[0] for i in xyz]))
2183 self.ymax = max(self.ymax, max([i[1] for i in xyz]))
2184 self.zmax = max(self.zmax, max([i[2] for i in xyz]))
2185
2186
2187 #===============================================================================
2188 # Gcode file
2189 #===============================================================================
2190 class GCode:
2191 LOOP_MERGE = False
2192
2193 #----------------------------------------------------------------------
2194 def __init__(self):
2195 self.cnc = CNC()
2196 self.header = ""
2197 self.footer = ""
2198 self.undoredo = undo.UndoRedo()
2199 self.probe = Probe()
2200 self.orient = Orient()
2201 self.vars = {} # local variables
2202 self.init()
2203
2204 #----------------------------------------------------------------------
2205 def init(self):
2206 self.filename = ""
2207 self.blocks = [] # list of blocks
2208 self.vars.clear()
2209 self.undoredo.reset()
2210 # self.probe.init()
2211
2212 self._lastModified = 0
2213 self._modified = False
2214
2215 #----------------------------------------------------------------------
2216 # Recalculate enabled path margins
2217 #----------------------------------------------------------------------
2218 def calculateEnableMargins(self):
2219 self.cnc.resetEnableMargins()
2220 for block in self.blocks:
2221 if block.enable:
2222 CNC.vars["xmin"] = min(CNC.vars["xmin"], block.xmin)
2223 CNC.vars["ymin"] = min(CNC.vars["ymin"], block.ymin)
2224 CNC.vars["zmin"] = min(CNC.vars["zmin"], block.zmin)
2225 CNC.vars["xmax"] = max(CNC.vars["xmax"], block.xmax)
2226 CNC.vars["ymax"] = max(CNC.vars["ymax"], block.ymax)
2227 CNC.vars["zmax"] = max(CNC.vars["zmax"], block.zmax)
2228
2229 #----------------------------------------------------------------------
2230 def isModified(self): return self._modified
2231
2232 #----------------------------------------------------------------------
2233 def resetModified(self): self._modified = False
2234
2235 #----------------------------------------------------------------------
2236 def __getitem__(self, item): return self.blocks[item]
2237
2238 #----------------------------------------------------------------------
2239 def __setitem__(self, item, value): self.blocks[item] = value
2240
2241 #----------------------------------------------------------------------
2242 # Evaluate code expressions if any and return line
2243 #----------------------------------------------------------------------
2244 def evaluate(self, line, app=None):
2245 if isinstance(line,int):
2246 return None
2247
2248 elif isinstance(line,list):
2249 for i,expr in enumerate(line):
2250 if isinstance(expr, types.CodeType):
2251 result = eval(expr,CNC.vars,self.vars)
2252 if isinstance(result,float):
2253 line[i] = str(round(result,CNC.digits))
2254 else:
2255 line[i] = str(result)
2256 return "".join(line)
2257
2258 elif isinstance(line, types.CodeType):
2259 import traceback
2260 #traceback.print_stack()
2261 v = self.vars
2262 v['os'] = os
2263 v['app'] = app
2264 return eval(line,CNC.vars,self.vars)
2265
2266 else:
2267 return line
2268
2269 #----------------------------------------------------------------------
2270 # add new line to list create block if necessary
2271 #----------------------------------------------------------------------
2272 def _addLine(self, line):
2273 if line.startswith("(Block-name:"):
2274 self._blocksExist = True
2275 pat = BLOCKPAT.match(line)
2276 if pat:
2277 value = pat.group(2).strip()
2278 if not self.blocks or len(self.blocks[-1]):
2279 self.blocks.append(Block(value))
2280 else:
2281 self.blocks[-1]._name = value
2282 return
2283
2284 #FIXME: Code to import legacy tabs can be probably removed in year 2020 or so:
2285 if line.startswith("(Block-tab:"):
2286 pat = BLOCKPAT.match(line)
2287 if pat:
2288 value = pat.group(2).strip()
2289 items = map(float,value.split())
2290 tablock = Block("legacy [tab,island,minz:%f]"%(items[4]))
2291 tablock.color = "orange"
2292 tablock.extend(self.createTab(*items))
2293 self.insBlocks(-1, [tablock], "Legacy tab")
2294 print("WARNING: Converted legacy tabs loaded from file to new g-code island tabs: %s"%(tablock._name))
2295
2296 if not self.blocks:
2297 self.blocks.append(Block("Header"))
2298
2299 cmds = CNC.parseLine(line)
2300 if cmds is None:
2301 self.blocks[-1].append(line)
2302 return
2303
2304 self.cnc.motionStart(cmds)
2305
2306 # rapid move up = end of block
2307 if self._blocksExist:
2308 self.blocks[-1].append(line)
2309 elif self.cnc.gcode == 0 and self.cnc.dz > 0.0:
2310 self.blocks[-1].append(line)
2311 self.blocks.append(Block())
2312 elif self.cnc.gcode == 0 and len(self.blocks)==1:
2313 self.blocks.append(Block())
2314 self.blocks[-1].append(line)
2315 else:
2316 self.blocks[-1].append(line)
2317
2318 self.cnc.motionEnd()
2319
2320 #----------------------------------------------------------------------
2321 # Load a file into editor
2322 #----------------------------------------------------------------------
2323 def load(self, filename=None):
2324 if filename is None: filename = self.filename
2325 self.init()
2326 self.filename = filename
2327 try: f = open(self.filename,"r")
2328 except: return False
2329 self._lastModified = os.stat(self.filename).st_mtime
2330 self.cnc.initPath()
2331 self.cnc.resetAllMargins()
2332 self._blocksExist = False
2333 for line in f:
2334 self._addLine(line[:-1].replace("\x0d",""))
2335 self._trim()
2336 f.close()
2337 return True
2338
2339 #----------------------------------------------------------------------
2340 # Save to a file
2341 #----------------------------------------------------------------------
2342 def save(self, filename=None):
2343 if filename is not None: self.filename = filename
2344 try:
2345 f = open(self.filename,"w")
2346 except:
2347 return False
2348
2349 for block in self.blocks:
2350 block.write(f)
2351 f.close()
2352 self._lastModified = os.stat(self.filename).st_mtime
2353 self._modified = False
2354 return True
2355
2356 #----------------------------------------------------------------------
2357 # Save in TXT format
2358 # -Enabled Blocks only
2359 # -Cleaned from bCNC metadata and comments
2360 # -Uppercase
2361 #----------------------------------------------------------------------
2362 def saveTXT(self, filename):
2363 txt = open(filename, 'w')
2364 for block in self.blocks:
2365 if block.enable:
2366 for line in block:
2367 cmds = CNC.parseLine(line)
2368 if cmds is None: continue
2369 txt.write("%s\n"%line.upper())
2370 txt.close()
2371 return True
2372
2373 #----------------------------------------------------------------------
2374 def addBlockFromString(self, name, text):
2375 if not text: return
2376 block = Block(name)
2377 block.extend(text.splitlines())
2378 self.blocks.append(block)
2379
2380 #----------------------------------------------------------------------
2381 # If empty insert a header and a footer
2382 #----------------------------------------------------------------------
2383 def headerFooter(self):
2384 if not self.blocks:
2385 self.addBlockFromString("Header",self.header)
2386 self.addBlockFromString("Footer",self.footer)
2387 return True
2388 return False
2389
2390 #----------------------------------------------------------------------
2391 # Load DXF file into gcode
2392 #----------------------------------------------------------------------
2393 def importDXF(self, filename):
2394 try:
2395 dxf = DXF(filename,"r")
2396 except:
2397 return False
2398 self.filename = ""
2399
2400 dxf.readFile()
2401 dxf.close()
2402
2403 # prepare dxf file
2404 dxf.sort()
2405 dxf.convert2Polylines()
2406 dxf.expandBlocks()
2407
2408 #import time; start = time.time()
2409 empty = len(self.blocks)==0
2410 if empty: self.addBlockFromString("Header",self.header)
2411
2412 if CNC.inch:
2413 units = DXF.INCHES
2414 else:
2415 units = DXF.MILLIMETERS
2416
2417 undoinfo = []
2418 for name,layer in dxf.layers.items():
2419 enable = not bool(layer.isFrozen())
2420 entities = dxf.entities(name)
2421 if not entities: continue
2422 self.importEntityPoints(None, entities, name, enable, layer.color())
2423 path = Path(name)
2424 path.fromDxf(dxf, entities, units)
2425 path.removeZeroLength()
2426 if path.color is None:
2427 path.color = layer.color()
2428 if path.color == "#FFFFFF": path.color = None
2429 opath = path.split2contours(0.0001) #Lowered accuracy due to problems interfacing arcs and lines in DXF
2430 if not opath: continue
2431 while opath:
2432 li = 0
2433 llen = 0.0
2434 for i,p in enumerate(opath):
2435 if p.length()>llen:
2436 li = i
2437 llen = p.length()
2438 longest = opath.pop(li)
2439 longest.directionSet(1) #turn path to CW (conventional when milling outside)
2440
2441 # Can be time consuming
2442 if GCode.LOOP_MERGE:
2443 # print "Loop merge"
2444 longest.mergeLoops(opath)
2445
2446 undoinfo.extend(self.importPath(None, longest, None, enable))
2447 # d = longest.direction()
2448 # bid = len(self.blocks)-1
2449 # if d==0:
2450 # undoinfo.extend(self.addBlockOperationUndo(bid,"O"))
2451 # elif d==1:
2452 # undoinfo.extend(self.addBlockOperationUndo(bid,"CW"))
2453 # elif d==-1:
2454 # undoinfo.extend(self.addBlockOperationUndo(bid,"CCW"))
2455
2456 undoinfo.extend(self.importPath(None, opath, None, enable))
2457 # d = opath.direction()
2458 # bid = len(self.blocks)-1
2459 # if d==0:
2460 # undoinfo.extend(self.addBlockOperationUndo(bid,"O"))
2461 # elif d==1:
2462 # undoinfo.extend(self.addBlockOperationUndo(bid,"CW"))
2463 # elif d==-1:
2464 # undoinfo.extend(self.addBlockOperationUndo(bid,"CCW"))
2465
2466 #print "Loading time:", time.time()-start
2467 if empty: self.addBlockFromString("Footer",self.footer)
2468 #self.addUndo(undoinfo)
2469 return True
2470
2471 #----------------------------------------------------------------------
2472 # Save in DXF format
2473 #----------------------------------------------------------------------
2474 def saveDXF(self, filename):
2475 try:
2476 dxf = DXF(filename,"w")
2477 except:
2478 return False
2479 if CNC.inch:
2480 dxf.units = DXF.INCHES
2481 else:
2482 dxf.units = DXF.MILLIMETERS
2483 dxf.writeHeader()
2484 for block in self.blocks:
2485 name = block.name()
2486 if ":" in name: name = name.split(":")[0]
2487 for line in block:
2488 cmds = CNC.parseLine(line)
2489 if cmds is None: continue
2490 self.cnc.motionStart(cmds)
2491 if self.cnc.gcode == 1: # line
2492 dxf.line(self.cnc.x, self.cnc.y, self.cnc.xval, self.cnc.yval, name)
2493 elif self.cnc.gcode in (2,3): # arc
2494 xc,yc = self.cnc.motionCenter()
2495 sphi = math.atan2(self.cnc.y-yc, self.cnc.x-xc)
2496 ephi = math.atan2(self.cnc.yval-yc, self.cnc.xval-xc)
2497 if ephi<=sphi+1e-10: ephi += 2.0*math.pi
2498 if self.cnc.gcode==2:
2499 dxf.arc(xc,yc,self.cnc.rval, math.degrees(ephi), math.degrees(sphi),name)
2500 else:
2501 dxf.arc(xc,yc,self.cnc.rval, math.degrees(sphi), math.degrees(ephi),name)
2502 self.cnc.motionEnd()
2503 dxf.writeEOF()
2504 dxf.close()
2505 return True
2506
2507 #----------------------------------------------------------------------
2508 # Get scaling factor for SVG files
2509 #----------------------------------------------------------------------
2510 def SVGscale(self, dpi=96.0): #same as inkscape 0.9x (according to jscut)
2511 if CNC.inch:
2512 return 1.0 / dpi
2513 return 25.4 / dpi
2514
2515 #----------------------------------------------------------------------
2516 # Load SVG file into gcode
2517 #----------------------------------------------------------------------
2518 def importSVG(self, filename):
2519 #try:
2520 svgcode = SVGcode(filename)
2521 #except:
2522 # return False
2523
2524 empty = len(self.blocks)==0
2525 if empty: self.addBlockFromString("Header",self.header)
2526
2527 #FIXME: UI to set SVG samples_per_unit
2528 ppi = 96.0 # 96 pixels per inch.
2529 scale = self.SVGscale(ppi)
2530 samples_per_unit = 200.0
2531 for path in svgcode.get_gcode(scale, samples_per_unit, CNC.digits, ppi=ppi):
2532 self.addBlockFromString(path['id'],path['path'])
2533
2534 if empty: self.addBlockFromString("Footer",self.footer)
2535 return True
2536
2537 #----------------------------------------------------------------------
2538 # get document margins
2539 #----------------------------------------------------------------------
2540 def getMargins(self):
2541 #Get bounding box of document
2542 minx,miny,maxx,maxy = 0,0,0,0
2543 for i,block in enumerate(self.blocks):
2544 paths = self.toPath(i)
2545 for path in paths:
2546 minx2,miny2,maxx2,maxy2 = path.bbox()
2547 minx,miny,maxx,maxy = min(minx,minx2), min(miny,miny2), max(maxx,maxx2), max(maxy,maxy2)
2548 return minx,miny,maxx,maxy
2549
2550 #----------------------------------------------------------------------
2551 # Save in SVG format
2552 #----------------------------------------------------------------------
2553 def saveSVG(self, filename):
2554 try:
2555 svg = open(filename,"w")
2556 except:
2557 return False
2558
2559 padding = 10
2560 scale=self.SVGscale()
2561
2562 #Get bounding box of document
2563 minx,miny,maxx,maxy = self.getMargins()
2564 #centerx = (minx+maxx)/2
2565 #centery = (miny+maxy)/2
2566
2567 svg.write('<!-- SVG generated by bCNC: https://github.com/vlachoudis/bCNC -->\n')
2568 svg.write('<svg viewBox="%s %s %s %s">\n'%((minx*scale)-padding, (-maxy*scale)-padding, ((maxx-minx)*scale)+padding*2, ((maxy-miny)*scale)+padding*2))
2569 #svg.write('\t<path d="M %s %s L %s %s" stroke="%s" stroke-width="%s" fill="none" />\n'%(minx*scale, -miny*scale, maxx*scale, -maxy*scale, "pink", 2)) #Bounding box debug
2570
2571 def svgLine(scale, px, py, type='L'):
2572 return('\t%s %s %s\n'%(type, px*scale, py*scale))
2573
2574 def svgArc(scale, gcode, r, ax, ay, bx, by, cx, cy):
2575 sphi = math.atan2(ay-yc, ax-xc)
2576 ephi = math.atan2(by-yc, bx-xc)
2577 arcSweep = ephi - sphi
2578 arcSweep = 0 if arcSweep <= math.radians(180) else 1
2579 #Arc
2580 if gcode==2:
2581 if ephi<=sphi+1e-10: ephi += 2.0*math.pi
2582 #dxf.arc(xc,yc,self.cnc.rval, math.degrees(ephi), math.degrees(sphi),name)
2583 #return('\tM %s %s A %s %s %s %s %s %s %s\n'%(ax*scale, ay*scale, r*scale, r*scale, 0, arcSweep, 1, bx*scale, by*scale))
2584 return('\tA %s %s %s %s %s %s %s\n'%(r*scale, r*scale, 0, arcSweep, 1, bx*scale, by*scale))
2585 else:
2586 if ephi<=sphi+1e-10: ephi += 2.0*math.pi
2587 #dxf.arc(xc,yc,self.cnc.rval, math.degrees(sphi), math.degrees(ephi),name)
2588 #return('\tM %s %s A %s %s %s %s %s %s %s\n'%(ax*scale, ay*scale, r*scale, r*scale, 0, arcSweep, 0, bx*scale, by*scale))
2589 return('\tA %s %s %s %s %s %s %s\n'%(r*scale, r*scale, 0, arcSweep, 0, bx*scale, by*scale))
2590
2591
2592 for block in self.blocks:
2593
2594 name = block.name()
2595 color = block.color
2596 if color is None: color = 'black'
2597 width = 2
2598 if ":" in name: name = name.split(":")[0]
2599 svgpath = ''
2600 lastx, lasty = 0, 0
2601 firstx, firsty = None, None
2602
2603 #Write paths
2604 for line in block:
2605 cmds = CNC.parseLine(line)
2606 if cmds is None: continue
2607 self.cnc.motionStart(cmds)
2608
2609 if self.cnc.gcode == 0: # rapid line (move)
2610 svgpath += svgLine(scale, self.cnc.xval, -self.cnc.yval, 'M')
2611 else:
2612 lastx, lasty = self.cnc.xval, self.cnc.yval
2613 if firstx is None:
2614 firstx, firsty = self.cnc.x, self.cnc.y
2615
2616 if self.cnc.gcode == 1: # line
2617 svgpath += svgLine(scale, self.cnc.xval, -self.cnc.yval)
2618
2619 elif self.cnc.gcode in (2,3): # arc
2620 xc,yc = self.cnc.motionCenter()
2621
2622 #In case of full circle, we need to split circle in two arcs:
2623 midx = self.cnc.x
2624 midy = self.cnc.y
2625 if self.cnc.y==self.cnc.yval and self.cnc.x==self.cnc.xval: #is full circle?
2626 midx = self.cnc.x+(xc-self.cnc.x)*2
2627 midy = self.cnc.y+(yc-self.cnc.y)*2
2628 svgpath += svgArc(scale, self.cnc.gcode, self.cnc.rval, self.cnc.x, -self.cnc.y, midx, -midy, xc, -yc)
2629 #Finish arc
2630 svgpath += svgArc(scale, self.cnc.gcode, self.cnc.rval, midx, -midy, self.cnc.xval, -self.cnc.yval, xc, -yc)
2631 self.cnc.motionEnd()
2632
2633 if firstx == lastx and firsty == lasty:
2634 svgpath += '\tZ\n'
2635
2636 if len(svgpath) > 0:
2637 for line in block.write_header().splitlines():
2638 svg.write("\t<!-- %s -->\n"%(line))
2639 svg.write('\t<path d="\n%s\t" stroke="%s" stroke-width="%s" fill="none" />\n'%(svgpath, color, width))
2640
2641 #dxf.writeEOF()
2642 svg.write('</svg>\n')
2643 svg.close()
2644 return True
2645
2646 #----------------------------------------------------------------------
2647 # Import POINTS from entities
2648 #----------------------------------------------------------------------
2649 def importEntityPoints(self, pos, entities, name, enable=True, color=None):
2650 undoinfo = []
2651 i = 0
2652 while i<len(entities):
2653 if entities[i].type != "POINT":
2654 i += 1
2655 continue
2656
2657 block = Block("%s [P]"%(name))
2658 block.enable = enable
2659
2660 block.color = entities[i].color()
2661 if block.color is None:
2662 block.color = color
2663
2664 x,y = entities[i].start()
2665 block.append("g0 %s %s"%(self.fmt("x",x,7),self.fmt("y",y,7)))
2666 block.append(CNC.zenter(self.cnc["surface"]))
2667 block.append(CNC.zsafe())
2668 undoinfo.append(self.addBlockUndo(pos,block))
2669 if pos is not None: pos += 1
2670 del entities[i]
2671
2672 return undoinfo
2673
2674 #----------------------------------------------------------------------
2675 # convert a block to path
2676 #----------------------------------------------------------------------
2677 def toPath(self, bid):
2678 block = self.blocks[bid]
2679 paths = []
2680 path = Path(block.name())
2681 self.initPath(bid)
2682 start = Vector(self.cnc.x, self.cnc.y)
2683
2684 # get only first path that enters the surface
2685 # ignore the deeper ones
2686 passno = 0
2687 for line in block:
2688 #flatten helical paths
2689 line = re.sub(r"\s?z-?[0-9\.]+","",line)
2690
2691 #break after first depth pass
2692 if line == "( ---------- cut-here ---------- )":
2693 passno=0
2694 if path:
2695 paths.append(path)
2696 path = Path(block.name())
2697 if line[:5] == "(pass": passno+=1
2698 if passno > 1: continue
2699
2700 cmds = CNC.parseLine(line)
2701 if cmds is None: continue
2702 self.cnc.motionStart(cmds)
2703 end = Vector(self.cnc.xval, self.cnc.yval)
2704 if self.cnc.gcode == 0: # rapid move (new block)
2705 if path:
2706 paths.append(path)
2707 path = Path(block.name())
2708 elif self.cnc.gcode == 1: # line
2709 if (self.cnc.dx != 0.0 or self.cnc.dy != 0.0):
2710 path.append(Segment(1, start, end))
2711 elif self.cnc.gcode in (2,3): # arc
2712 xc,yc = self.cnc.motionCenter()
2713 center = Vector(xc,yc)
2714 path.append(Segment(self.cnc.gcode, start,end, center))
2715 self.cnc.motionEnd()
2716 start = end
2717 if path: paths.append(path)
2718 return paths
2719
2720 #----------------------------------------------------------------------
2721 # create a block from Path
2722 # @param z I ending depth
2723 # @param zstart I starting depth
2724 #----------------------------------------------------------------------
2725 def fromPath(self, path, block=None, z=None, retract=True, entry=False, exit=True, zstart=None, ramp=None, comments=True, exitpoint=None, truncate=None):
2726 #Recursion for multiple paths
2727 if not isinstance(path, Path):
2728 block = Block("new")
2729 for p in path:
2730 block.extend(self.fromPath(p, None, z, retract, entry, exit, zstart, ramp, comments, exitpoint, truncate))
2731 block.append("( ---------- cut-here ---------- )")
2732 del block[-1] #remove trailing cut-here
2733 return block
2734
2735 if z is None: z = self.cnc["surface"]
2736 if zstart is None: zstart = z
2737
2738 #Calculate helix step
2739 zstep = abs(z-zstart)
2740
2741 #Preprocess ramp
2742 if ramp is None: ramp = 0
2743 if ramp==0: ramp = path.length() #full helix (default)
2744 ramp = min(ramp, path.length()) #Never ramp longer than single pass!
2745
2746 #Calculate helical feedrate
2747 helixfeed = self.cnc["cutfeed"]
2748 if zstep > 0:
2749 #Compensate helix feed, so we never plunge too fast on short/steep paths
2750 #FIXME: Add UI to disable this feature??? Not sure if that's needed.
2751 rampratio = zstep/min(path.length(),ramp)
2752 helixfeed2 = round(self.cnc["cutfeedz"]/rampratio)
2753 helixfeed = min(self.cnc["cutfeed"], helixfeed2)
2754
2755 #
2756 if block is None:
2757 if isinstance(path, Path):
2758 block = Block(path.name)
2759 else:
2760 block = Block(path[0].name)
2761
2762 #Generate g-code for single path segment
2763 def addSegment(segment, z=None, cm=""):
2764 x,y = segment.B
2765
2766 #Generate LINE
2767 if segment.type == Segment.LINE:
2768 x,y = segment.B
2769 #rounding problem from #903 was manifesting here. Had to lower the decimal precision to CNC.digits
2770 if z is None: block.append("g1 %s %s"%(self.fmt("x",x,7),self.fmt("y",y,7))+cm)
2771 else: block.append("g1 %s %s %s"%(self.fmt("x",x,7),self.fmt("y",y,7),self.fmt("z",z,7))+cm)
2772
2773 #Generate ARCS
2774 elif segment.type in (Segment.CW, Segment.CCW):
2775 ij = segment.C - segment.A
2776 if abs(ij[0])<1e-5: ij[0] = 0.
2777 if abs(ij[1])<1e-5: ij[1] = 0.
2778 if z is None:
2779 block.append("g%d %s %s %s %s" % \
2780 (segment.type,
2781 self.fmt("x",x,7), self.fmt("y",y,7),
2782 self.fmt("i",ij[0],7),self.fmt("j",ij[1],7))+cm)
2783 else:
2784 block.append("g%d %s %s %s %s %s" % \
2785 (segment.type,
2786 self.fmt("x",x,7), self.fmt("y",y,7),
2787 self.fmt("i",ij[0],7),self.fmt("j",ij[1],7),self.fmt("z",z,7))+cm)
2788
2789 #Get island height of segment
2790 def getSegmentZTab(segment, altz=float("-inf")):
2791 if segment._inside:
2792 return max(segment._inside)
2793 else: return altz
2794
2795 #Generate block from path
2796 if isinstance(path, Path):
2797 x,y = path[0].A
2798
2799 #decide if flat or ramp/helical:
2800 if z == zstart: zh=z
2801 elif zstart is not None: zh = zstart
2802
2803 #test if not starting in tab/island!
2804 ztab = getSegmentZTab(path[0], z)
2805
2806 #Retract to zsafe
2807 if retract: block.append("g0 %s"%(self.fmt("z",CNC.vars["safe"],7)))
2808
2809 #Rapid to beginning of the path
2810 block.append("g0 %s %s"%(self.fmt("x",x,7),self.fmt("y",y,7)))
2811
2812 #Descend to pass (plunge to the beginning of path)
2813 if entry:
2814 #if entry feed to Z
2815 block.append(CNC.zenter(max(zh, ztab),7))
2816 else:
2817 #without entry just rapid to Z
2818 block.append("g0 %s"%(self.fmt("z",max(zh, ztab),7)))
2819
2820 #Begin pass
2821 #if comments: block.append("(pass %f)"%(max(zh, ztab)))
2822 if comments: block.append("(entered)")
2823
2824 #Loop over segments
2825 setfeed = True
2826 ztabprev = float("-inf");
2827 ramping = True
2828 for sid,segment in enumerate(path):
2829 zhprev = zh
2830
2831 #Ramp down
2832 zh -= (segment.length()/ramp)*zstep #ramp
2833 zh = max(zh, z) #Never cut deeper than z!
2834
2835 #Reset feedrate if not ramping anymore
2836 if zh == zhprev and ramping:
2837 helixfeed = self.cnc["cutfeed"]
2838 setfeed = True
2839 ramping = False
2840
2841 #Get tab height
2842 ztab = getSegmentZTab(segment)
2843
2844 #Retract over tabs
2845 if ztab != ztabprev: #has tab height changed? tab boundary crossed?
2846 if (ztab == float("-inf") or ztab < ztabprev) and (zh < ztabprev or zhprev < ztabprev): #if we need to enter the toolpath after done clearing the tab
2847 if comments: block.append("(tab down "+str(max(zhprev,ztab))+")")
2848 block.append(CNC.zenter(max(zhprev,ztab),7))
2849 setfeed = True
2850 elif zh < ztab or zhprev < ztab: #if we need to go higher in order to clear the tab
2851 if comments: block.append("(tab up "+str(max(zh, ztab))+")")
2852 block.append(CNC.zexit(max(zh, ztab),7))
2853 setfeed = True
2854 ztabprev = ztab
2855
2856 #Cut next segment of toolpath
2857 addSegment(segment, max(zh, ztab)) #Never cut deeper than tabs!
2858
2859 #Set feed if needed
2860 if setfeed:
2861 block[-1] += " %s"%(self.fmt("f",round(helixfeed)))
2862 setfeed = False
2863
2864 #Truncate
2865 if truncate is not None:
2866 truncate -= segment.length()
2867 if truncate <= -1e-7: break
2868
2869 #Exit toolpath
2870 if exit:
2871 if comments: block.append("(exiting)")
2872 if exitpoint is not None:
2873 block.append('g1 %s %s'%(self.fmt("x",exitpoint[0]),self.fmt("y",exitpoint[1])))
2874 block.append(CNC.zsafe())
2875
2876 return block
2877
2878 #----------------------------------------------------------------------
2879 # Import paths as block
2880 # return ids of blocks added in newblocks list if declared
2881 #----------------------------------------------------------------------
2882 def importPath(self, pos, paths, newblocks=None, enable=True, multiblock=True):
2883 undoinfo = []
2884 if isinstance(paths,Path):
2885 block = self.fromPath(paths)
2886 block.enable = enable
2887 block.color = paths.color
2888 undoinfo.append(self.addBlockUndo(pos,block))
2889 if newblocks is not None: newblocks.append(pos)
2890 else:
2891 block = None
2892 for path in paths:
2893 if block is None:
2894 block = Block(path.name)
2895 block = self.fromPath(path, block)
2896 if multiblock:
2897 block.enable = enable
2898 undoinfo.append(self.addBlockUndo(pos,block))
2899 if newblocks is not None: newblocks.append(pos)
2900 if pos is not None: pos += 1
2901 block = None
2902 if not multiblock:
2903 block.enable = enable
2904 undoinfo.append(self.addBlockUndo(pos,block))
2905 if newblocks is not None: newblocks.append(pos)
2906 return undoinfo
2907
2908 #----------------------------------------------------------------------
2909 # sync file timestamp
2910 #----------------------------------------------------------------------
2911 def syncFileTime(self):
2912 try:
2913 self._lastModified = os.stat(self.filename).st_mtime
2914 except:
2915 return False
2916
2917 #----------------------------------------------------------------------
2918 # Check if a new version exists
2919 #----------------------------------------------------------------------
2920 def checkFile(self):
2921 try:
2922 return os.stat(self.filename).st_mtime > self._lastModified
2923 except:
2924 return False
2925
2926 #----------------------------------------------------------------------
2927 def fmt(self, c, v, d=None): return self.cnc.fmt(c,v,d)
2928
2929 #----------------------------------------------------------------------
2930 def _trim(self):
2931 if not self.blocks: return
2932 # Delete last block if empty
2933 last = self.blocks[-1]
2934 if len(last)==1 and len(last[0])==0: del last[0]
2935 if len(self.blocks[-1])==0:
2936 self.blocks.pop()
2937
2938 #----------------------------------------------------------------------
2939 # Undo/Redo operations
2940 #----------------------------------------------------------------------
2941 def undo(self):
2942 #print ">u>",self.undoredo.undoText()
2943 self.undoredo.undo()
2944
2945 #----------------------------------------------------------------------
2946 def redo(self):
2947 #print ">r>",self.undoredo.redoText()
2948 self.undoredo.redo()
2949
2950 #----------------------------------------------------------------------
2951 def addUndo(self, undoinfo, msg=None):
2952 if not undoinfo: return
2953 self.undoredo.add(undoinfo, msg)
2954 self._modified = True
2955
2956 #----------------------------------------------------------------------
2957 def canUndo(self): return self.undoredo.canUndo()
2958
2959 #----------------------------------------------------------------------
2960 def canRedo(self): return self.undoredo.canRedo()
2961
2962 #----------------------------------------------------------------------
2963 # Change all lines in editor
2964 #----------------------------------------------------------------------
2965 def setLinesUndo(self, lines):
2966 undoinfo = (self.setLinesUndo, list(self.lines()))
2967 # Delete all blocks and create new ones
2968 del self.blocks[:]
2969 self.cnc.initPath()
2970 self._blocksExist = False
2971 for line in lines: self._addLine(line)
2972 self._trim()
2973 return undoinfo
2974
2975 #----------------------------------------------------------------------
2976 def setAllBlocksUndo(self, blocks=[]):
2977 undoinfo = [self.setAllBlocksUndo, self.blocks]
2978 self.blocks = blocks
2979 return undoinfo
2980
2981 #----------------------------------------------------------------------
2982 # Change a single line in a block
2983 #----------------------------------------------------------------------
2984 def setLineUndo(self, bid, lid, line):
2985 undoinfo = (self.setLineUndo, bid, lid, self.blocks[bid][lid])
2986 self.blocks[bid][lid] = line
2987 return undoinfo
2988
2989 #----------------------------------------------------------------------
2990 # Insert a new line into block
2991 #----------------------------------------------------------------------
2992 def insLineUndo(self, bid, lid, line):
2993 undoinfo = (self.delLineUndo, bid, lid)
2994 block = self.blocks[bid]
2995 if lid>=len(block):
2996 block.append(line)
2997 else:
2998 block.insert(lid, line)
2999 return undoinfo
3000
3001 #----------------------------------------------------------------------
3002 # Clone line inside a block
3003 #----------------------------------------------------------------------
3004 def cloneLineUndo(self, bid, lid):
3005 return self.insLineUndo(bid, lid, self.blocks[bid][lid])
3006
3007 #----------------------------------------------------------------------
3008 # Delete line from block
3009 #----------------------------------------------------------------------
3010 def delLineUndo(self, bid, lid):
3011 block = self.blocks[bid]
3012 undoinfo = (self.insLineUndo, bid, lid, block[lid])
3013 del block[lid]
3014 return undoinfo
3015
3016 #----------------------------------------------------------------------
3017 # Add a block
3018 #----------------------------------------------------------------------
3019 def addBlockUndo(self, bid, block):
3020 if bid is None: bid = len(self.blocks)
3021 if bid>=len(self.blocks):
3022 undoinfo = (self.delBlockUndo, len(self.blocks))
3023 self.blocks.append(block)
3024 else:
3025 undoinfo = (self.delBlockUndo, bid)
3026 self.blocks.insert(bid, block)
3027 return undoinfo
3028
3029 #----------------------------------------------------------------------
3030 # Clone a block
3031 #----------------------------------------------------------------------
3032 def cloneBlockUndo(self, bid, pos=None):
3033 if pos is None: pos = bid
3034 return self.addBlockUndo(pos, Block(self.blocks[bid]))
3035
3036 #----------------------------------------------------------------------
3037 # Delete a whole block
3038 #----------------------------------------------------------------------
3039 def delBlockUndo(self, bid):
3040 lines = [x for x in self.blocks[bid]]
3041 block = self.blocks.pop(bid)
3042 undoinfo = (self.addBlockUndo, bid, block)
3043 return undoinfo
3044
3045 #----------------------------------------------------------------------
3046 # Insert a list of other blocks from another gcode file probably
3047 #----------------------------------------------------------------------
3048 def insBlocksUndo(self, bid, blocks):
3049 if bid is None or bid >= len(self.blocks):
3050 bid = len(self.blocks)
3051 undoinfo = ("Insert blocks", self.delBlocksUndo, bid, bid+len(blocks))
3052 self.blocks[bid:bid] = blocks
3053 return undoinfo
3054
3055 #----------------------------------------------------------------------
3056 # Delete a range of blocks
3057 #----------------------------------------------------------------------
3058 def delBlocksUndo(self, from_, to_):
3059 blocks = self.blocks[from_:to_]
3060 undoinfo = ("Delete blocks", self.insBlocksUndo, from_, blocks)
3061 del self.blocks[from_:to_]
3062 return undoinfo
3063
3064 #----------------------------------------------------------------------
3065 # Insert blocks and push the undo info
3066 #----------------------------------------------------------------------
3067 def insBlocks(self, bid, blocks, msg=""):
3068 if self.headerFooter(): # just in case
3069 bid = 1
3070 self.addUndo(self.insBlocksUndo(bid, blocks), msg)
3071
3072 #----------------------------------------------------------------------
3073 # Set block expand
3074 #----------------------------------------------------------------------
3075 def setBlockExpandUndo(self, bid, expand):
3076 undoinfo = (self.setBlockExpandUndo, bid, self.blocks[bid].expand)
3077 self.blocks[bid].expand = expand
3078 return undoinfo
3079
3080 #----------------------------------------------------------------------
3081 # Set block state
3082 #----------------------------------------------------------------------
3083 def setBlockEnableUndo(self, bid, enable):
3084 undoinfo = (self.setBlockEnableUndo, bid, self.blocks[bid].enable)
3085 self.blocks[bid].enable = enable
3086 return undoinfo
3087
3088 #----------------------------------------------------------------------
3089 # Set block color
3090 #----------------------------------------------------------------------
3091 def setBlockColorUndo(self, bid, color):
3092 undoinfo = (self.setBlockColorUndo, bid, self.blocks[bid].color)
3093 self.blocks[bid].color = color
3094 return undoinfo
3095
3096 #----------------------------------------------------------------------
3097 # Swap two blocks
3098 #----------------------------------------------------------------------
3099 def swapBlockUndo(self, a, b):
3100 undoinfo = (self.swapBlockUndo, a, b)
3101 tmp = self.blocks[a]
3102 self.blocks[a] = self.blocks[b]
3103 self.blocks[b] = tmp
3104 return undoinfo
3105
3106 #----------------------------------------------------------------------
3107 # Move block from location src to location dst
3108 #----------------------------------------------------------------------
3109 def moveBlockUndo(self, src, dst):
3110 if src == dst: return None
3111 undoinfo = (self.moveBlockUndo, dst, src)
3112 if dst > src:
3113 self.blocks.insert(dst-1, self.blocks.pop(src))
3114 else:
3115 self.blocks.insert(dst, self.blocks.pop(src))
3116 return undoinfo
3117
3118 #----------------------------------------------------------------------
3119 # Invert selected blocks
3120 #----------------------------------------------------------------------
3121 def invertBlocksUndo(self, blocks):
3122 undoinfo = []
3123 first = 0
3124 last = len(blocks)-1
3125 while first < last:
3126 undoinfo.append(self.swapBlockUndo(blocks[first],blocks[last]))
3127 first += 1
3128 last -= 1
3129 return undoinfo
3130
3131 #----------------------------------------------------------------------
3132 # Move block upwards
3133 #----------------------------------------------------------------------
3134 def orderUpBlockUndo(self, bid):
3135 if bid==0: return None
3136 undoinfo = (self.orderDownBlockUndo, bid-1)
3137 # swap with the block above
3138 before = self.blocks[bid-1]
3139 self.blocks[bid-1] = self.blocks[bid]
3140 self.blocks[bid] = before
3141 return undoinfo
3142
3143 #----------------------------------------------------------------------
3144 # Move block downwards
3145 #----------------------------------------------------------------------
3146 def orderDownBlockUndo(self, bid):
3147 if bid>=len(self.blocks)-1: return None
3148 undoinfo = (self.orderUpBlockUndo, bid+1)
3149 # swap with the block below
3150 after = self[bid+1]
3151 self[bid+1] = self[bid]
3152 self[bid] = after
3153 return undoinfo
3154
3155 #----------------------------------------------------------------------
3156 # Insert block lines
3157 #----------------------------------------------------------------------
3158 def insBlockLinesUndo(self, bid, lines):
3159 undoinfo = (self.delBlockLinesUndo, bid)
3160 block = Block()
3161 for line in lines:
3162 block.append(line)
3163 self.blocks.insert(bid, block)
3164 return undoinfo
3165
3166 #----------------------------------------------------------------------
3167 # Delete a whole block lines
3168 #----------------------------------------------------------------------
3169 def delBlockLinesUndo(self, bid):
3170 lines = [x for x in self.blocks[bid]]
3171 undoinfo = (self.insBlockLinesUndo, bid, lines) #list(self.blocks[bid])[:])
3172 del self.blocks[bid]
3173 return undoinfo
3174
3175 #----------------------------------------------------------------------
3176 # Set Block name
3177 #----------------------------------------------------------------------
3178 def setBlockNameUndo(self, bid, name):
3179 undoinfo = (self.setBlockNameUndo, bid, self.blocks[bid]._name)
3180 self.blocks[bid]._name = name
3181 return undoinfo
3182
3183 #----------------------------------------------------------------------
3184 # Add an operation code in the name as [drill, cut, in/out...]
3185 #----------------------------------------------------------------------
3186 def addBlockOperationUndo(self, bid, operation, remove=None):
3187 undoinfo = (self.setBlockNameUndo, bid, self.blocks[bid]._name)
3188 self.blocks[bid].addOperation(operation, remove)
3189 return undoinfo
3190
3191 #----------------------------------------------------------------------
3192 # Replace the lines of a block
3193 #----------------------------------------------------------------------
3194 def setBlockLinesUndo(self, bid, lines):
3195 block = self.blocks[bid]
3196 undoinfo = (self.setBlockLinesUndo, bid, block[:])
3197 del block[:]
3198 block.extend(lines)
3199 return undoinfo
3200
3201 #----------------------------------------------------------------------
3202 # Move line upwards
3203 #----------------------------------------------------------------------
3204 def orderUpLineUndo(self, bid, lid):
3205 if lid==0: return None
3206 block = self.blocks[bid]
3207 undoinfo = (self.orderDownLineUndo, bid, lid-1)
3208 block.insert(lid-1, block.pop(lid))
3209 return undoinfo
3210
3211 #----------------------------------------------------------------------
3212 # Move line downwards
3213 #----------------------------------------------------------------------
3214 def orderDownLineUndo(self, bid, lid):
3215 block = self.blocks[bid]
3216 if lid>=len(block)-1: return None
3217 undoinfo = (self.orderUpLineUndo, bid, lid+1)
3218 block.insert(lid+1, block.pop(lid))
3219 return undoinfo
3220
3221 #----------------------------------------------------------------------
3222 # Expand block with autolevel information
3223 #----------------------------------------------------------------------
3224 def autolevelBlock(self, block):
3225 new = []
3226 autolevel = not self.probe.isEmpty()
3227 for line in block:
3228 newcmd = []
3229 cmds = CNC.compileLine(line)
3230 if cmds is None:
3231 new.append(line)
3232 continue
3233 elif isinstance(cmds,str):
3234 cmds = CNC.breakLine(cmds)
3235 else:
3236 new.append(line)
3237 continue
3238
3239 self.cnc.motionStart(cmds)
3240 if autolevel and self.cnc.gcode in (0,1,2,3) and self.cnc.mval==0:
3241 xyz = self.cnc.motionPath()
3242 if not xyz:
3243 # while auto-levelling, do not ignore non-movement
3244 # commands, just append the line as-is
3245 new.append(line)
3246 else:
3247 extra = ""
3248 for c in cmds:
3249 if c[0].upper() not in ('G','X','Y','Z','I','J','K','R'):
3250 extra += c
3251 x1,y1,z1 = xyz[0]
3252 if self.cnc.gcode == 0:
3253 g = 0
3254 else:
3255 g = 1
3256 for x2,y2,z2 in xyz[1:]:
3257 for x,y,z in self.probe.splitLine(x1,y1,z1,x2,y2,z2):
3258 new.append("G%d%s%s%s%s"%\
3259 (g,
3260 self.fmt('X',x/self.cnc.unit),
3261 self.fmt('Y',y/self.cnc.unit),
3262 self.fmt('Z',z/self.cnc.unit),
3263 extra))
3264 extra = ""
3265 x1,y1,z1 = x2,y2,z2
3266 self.cnc.motionEnd()
3267 else:
3268 self.cnc.motionEnd()
3269 new.append(line)
3270 return new
3271
3272 #----------------------------------------------------------------------
3273 # Execute autolevel on selected blocks
3274 #----------------------------------------------------------------------
3275 def autolevel(self, items):
3276 undoinfo = []
3277 operation = "autolevel"
3278 for bid in items:
3279 block = self.blocks[bid]
3280 if block.name() in ("Header", "Footer"): continue
3281 if not block.enable: continue
3282 lines = self.autolevelBlock(block)
3283 undoinfo.append(self.addBlockOperationUndo(bid, operation))
3284 undoinfo.append(self.setBlockLinesUndo(bid, lines))
3285 if undoinfo: self.addUndo(undoinfo)
3286
3287 #----------------------------------------------------------------------
3288 # Merge or split blocks depending on motion
3289 #
3290 # Each block should start with a rapid move and end with a rapid move
3291 #----------------------------------------------------------------------
3292 # def correctBlocks(self):
3293 # # Working in place tricky
3294 # bid = 0 # block index
3295 # while bid < len(self.blocks):
3296 # block = self.blocks[bid]
3297 # li = 0 # line index
3298 # prefix = True
3299 # suffix = False
3300 # lastg0 = None
3301 # while li < len(block):
3302 # line = block[li]
3303 # cmds = CNC.parseLine(line)
3304 # if cmds is None:
3305 # li += 1
3306 # continue
3307 #
3308 # self.cnc.motionStart(cmds)
3309 #
3310 # # move
3311 # if self.gcode in (1,2,3):
3312 # if prefix is None: prefix = li-1
3313 #
3314 # # rapid movement
3315 # elif self.gcode == 0:
3316 # lastg0 = li
3317 # if prefix is not None: suffix = li
3318 #
3319 # # moving up = end of block
3320 # if self.cnc.dz > 0.0:
3321 # if suffix:
3322 # # Move all subsequent lines to a new block
3323 # #self.blocks.append(Block())
3324 # pass
3325 # self.cnc.motionEnd()
3326
3327 #----------------------------------------------------------------------
3328 # Start a new iterator
3329 #----------------------------------------------------------------------
3330 # def __iter__(self):
3331 # self._iter = 0 #self._iter_start
3332 # self._iter_block = self.blocks[self._iter]
3333 # self._iter_block_i = 0
3334 # self._iter_end = len(self.blocks)
3335 # return self
3336 #
3337 # #----------------------------------------------------------------------
3338 # # Next iterator item
3339 # #----------------------------------------------------------------------
3340 # def next(self):
3341 # if self._iter >= self._iter_end: raise StopIteration()
3342 #
3343 # while self._iter_block_i >= len(self._iter_block):
3344 # self._iter += 1
3345 # if self._iter >= self._iter_end: raise StopIteration()
3346 # self._iter_block = self.blocks[self._iter]
3347 # self._iter_block_i = 0
3348 #
3349 # item = self._iter_block[self._iter_block_i]
3350 # self._iter_block_i += 1
3351 # return item
3352
3353 #----------------------------------------------------------------------
3354 # Return string representation of whole file
3355 #----------------------------------------------------------------------
3356 def __repr__(self):
3357 return "\n".join(list(self.lines()))
3358
3359 #----------------------------------------------------------------------
3360 # Iterate over the items
3361 #----------------------------------------------------------------------
3362 def iterate(self, items):
3363 for bid,lid in items:
3364 if lid is None:
3365 block = self.blocks[bid]
3366 for i in range(len(block)):
3367 yield bid,i
3368 else:
3369 yield bid,lid
3370
3371 #----------------------------------------------------------------------
3372 # Iterate over all lines
3373 #----------------------------------------------------------------------
3374 def lines(self):
3375 for block in self.blocks:
3376 for line in block:
3377 yield line
3378
3379 #----------------------------------------------------------------------
3380 # initialize cnc path based on block bid
3381 #----------------------------------------------------------------------
3382 def initPath(self, bid=0):
3383 if bid == 0:
3384 self.cnc.initPath()
3385 else:
3386 # Use the ending point of the previous block
3387 # since the starting (sxyz is after the rapid motion)
3388 block = self.blocks[bid-1]
3389 self.cnc.initPath(block.ex, block.ey, block.ez)
3390
3391 #----------------------------------------------------------------------
3392 # Move blocks/lines up
3393 #----------------------------------------------------------------------
3394 def orderUp(self, items):
3395 sel = [] # new selection
3396 undoinfo = []
3397 for bid,lid in items:
3398 if isinstance(lid,int):
3399 undoinfo.append(self.orderUpLineUndo(bid,lid))
3400 sel.append((bid, lid-1))
3401 elif lid is None:
3402 undoinfo.append(self.orderUpBlockUndo(bid))
3403 if bid==0:
3404 return items
3405 else:
3406 sel.append((bid-1,None))
3407 self.addUndo(undoinfo,"Move Up")
3408 return sel
3409
3410 #----------------------------------------------------------------------
3411 # Move blocks/lines down
3412 #----------------------------------------------------------------------
3413 def orderDown(self, items):
3414 sel = [] # new selection
3415 undoinfo = []
3416 for bid,lid in reversed(items):
3417 if isinstance(lid,int):
3418 undoinfo.append(self.orderDownLineUndo(bid,lid))
3419 sel.append((bid,lid+1))
3420 elif lid is None:
3421 undoinfo.append(self.orderDownBlockUndo(bid))
3422 if bid>=len(self.blocks)-1:
3423 return items
3424 else:
3425 sel.append((bid+1,None))
3426 self.addUndo(undoinfo,"Move Down")
3427 sel.reverse()
3428 return sel
3429
3430 #----------------------------------------------------------------------
3431 # Peck distance
3432 # Target depth
3433 # Depth increment
3434 # Retract height=safe height
3435 #----------------------------------------------------------------------
3436 def drill(self, items, depth=None, peck=None, dwell=None, distance=None, number=0, center=True):
3437 # find the penetration points and drill
3438 # skip all g1 movements on the horizontal plane
3439 if depth is None: depth = self.cnc["surface"]-self.cnc["thickness"]
3440 if depth < self.cnc["surface"]-self.cnc["thickness"] or depth > self.cnc["surface"]:
3441 return "ERROR: Drill depth %g outside stock surface: %g .. %g\n" \
3442 "Please change stock surface in Tools->Stock or drill depth." \
3443 %(depth, self.cnc["surface"], self.cnc["surface"]-self.cnc["thickness"])
3444 if abs(depth - (self.cnc["surface"]-self.cnc["thickness"])) < 1e-7:
3445 opname = "drill"
3446 else:
3447 opname = "drill:%g"%(depth)
3448 #Incorrect peck values can block drilling cycle calculation
3449 peck = peck or 0.0
3450 if peck == 0.0:
3451 peck = None
3452 if peck is not None:
3453 if math.copysign(1.0, depth) * math.copysign(1.0, peck) != -1:
3454 pecksignstr = "less"
3455 if math.copysign(1.0, peck) < 0:
3456 pecksignstr = "greater"
3457 return "Invalid peck depth value of %g. In this configuration, peck value should be %s than zero."%(peck, pecksignstr)
3458 #pecking value is well defined.
3459
3460 undoinfo = []
3461
3462 def drillHole(lines):
3463 # drill point
3464 if peck is None:
3465 lines.append(CNC.zenter(depth))
3466 lines.append(CNC.zsafe())
3467 else:
3468 z = self.cnc["surface"]
3469 while z>depth:
3470 z = max(z-peck, depth)
3471 lines.append(CNC.zenter(z))
3472 lines.append(CNC.zsafe())
3473 if dwell:
3474 lines.append("g4 %s"%(self.fmt("p",dwell)))
3475
3476 for bid in items:
3477 block = self.blocks[bid]
3478 if block.name() in ("Header", "Footer"): continue
3479 block.enable = True
3480
3481 # construct new name
3482 undoinfo.append(self.addBlockOperationUndo(bid, opname))
3483
3484 # 1st detect limits of first pass
3485 self.initPath(bid)
3486 self.cnc.z = self.cnc.zval = 1000.0
3487 lines = []
3488
3489 if center:
3490 #Drill in center only
3491 for path in self.toPath(bid):
3492 x,y = path.center()
3493 lines.append("g0 %s %s"%(self.fmt("x",x),self.fmt("y",y)))
3494 drillHole(lines)
3495
3496 elif distance is None and number==0:
3497 #Drill on path begining only
3498 for i,line in enumerate(block):
3499 cmds = CNC.parseLine(line)
3500 if cmds is None:
3501 lines.append(line)
3502 continue
3503 self.cnc.motionStart(cmds)
3504 if self.cnc.dz<0.0:
3505 drillHole(lines)
3506 elif self.cnc.dz>0.0:
3507 # retract
3508 pass
3509 elif self.cnc.gcode == 0:
3510 # add all rapid movements
3511 lines.append(line)
3512 elif self.cnc.gcode == 1:
3513 # ignore normal movements
3514 pass
3515 self.cnc.motionEnd()
3516 else:
3517 #Drill multiple holes along path
3518 for path in self.toPath(bid):
3519
3520 length = path.length()
3521 if number>0:
3522 distance = length / float(number)
3523 s = 0.0 # running length
3524
3525 while s < length:
3526 P = path.distPoint(s)
3527 s += distance
3528 lines.append("g0 %s %s"%(self.fmt("x",P[0]),self.fmt("y",P[1])))
3529 drillHole(lines)
3530
3531 undoinfo.append(self.setBlockLinesUndo(bid,lines))
3532 self.addUndo(undoinfo)
3533
3534 #----------------------------------------------------------------------
3535 # Perform a cut on a path an add it to block
3536 # @param newblock O block to add the cut paths
3537 # @param block I existing block
3538 # @param path I path to cut
3539 # @param z I starting z surface
3540 # @param depth I ending depth
3541 # @param stepz I stepping in z
3542 #----------------------------------------------------------------------
3543 def cutPath(self, newblock, block, path, z, depth, stepz, helix=False, helixBottom=True, ramp=0, islandPaths=[], exitpoint=None, springPass=False):
3544 closed = path.isClosed()
3545 zigzag = True #FIXME: Add UI to set this?
3546 entry = True
3547 exit = False
3548
3549 #Calculate ramp
3550 if ramp>0: ramp = abs(ramp)*CNC.vars["diameter"] #n times tool diameter
3551 if ramp<0: ramp = abs(ramp) #absolute
3552 if ramp == 0: ramp = None #No ramp
3553
3554 #Calculate exit point for thread milling
3555 centr = Vector(path.center())
3556 if exitpoint == 1:
3557 exitpoint = centr
3558 elif exitpoint == -1:
3559 exitpoint = path[-1].B+(path[-1].B-centr)
3560 else:
3561 exitpoint = None
3562
3563 #Mark in which island we are inside
3564 if islandPaths:
3565 for island in reversed(islandPaths):
3566 path.intersectPath(island)
3567 for island in reversed(islandPaths):
3568 path.markInside(island, island._inside)
3569
3570 #Decide if doing additional "appendix" passes after loop (eg.: spring pass or helixbottom)
3571 appendix = False
3572 if (springPass and closed) or (helix and helixBottom):
3573 appendix = True
3574
3575 #iterate over depth passes:
3576 retract = True
3577 while (z-depth)>1e-7:
3578 #Go one step lower
3579 z = max(z-stepz, depth)
3580
3581 #Detect last pass of loop
3582 if abs(z-depth)<1e-7 and not appendix:
3583 exit = True
3584
3585 #Flat cuts:
3586 if not helix:
3587 newblock.append("(pass %f)"%(z))
3588 if zigzag:
3589 self.fromPath(path, newblock, z, retract, True, exit, exitpoint=exitpoint)
3590 if not closed: path.invert()
3591 else:
3592 self.fromPath(path, newblock, z, True, True, exit, exitpoint=exitpoint)
3593
3594 #Helical/Ramp cuts:
3595 else:
3596 if helixBottom: exit = False
3597
3598 if closed:
3599 newblock.append("(pass %f to %f)"%(z+stepz, z))
3600 self.fromPath(path, newblock, z, retract, entry, exit, z+stepz, ramp, exitpoint=exitpoint)
3601 else:
3602 #Cut open path back and forth while descending
3603 newblock.append("(pass %f to %f)"%(z+stepz, z+stepz/2))
3604 self.fromPath(path, newblock, z+stepz/2, retract, entry, False, z+stepz, ramp, exitpoint=exitpoint)
3605 path.invert()
3606 newblock.append("(pass %f to %f)"%(z+stepz/2, z))
3607 self.fromPath(path, newblock, z, False, False, exit, z+stepz/2, ramp, exitpoint=exitpoint)
3608 path.invert()
3609
3610 retract = False
3611 entry = False
3612
3613 #Do appendix passes like spring pass or helixbottom
3614 if appendix:
3615 if (springPass and closed):
3616 ramp = None #Do not truncate pass when inverting direction
3617 path.invert()
3618 if not closed:
3619 retract = True
3620 entry = True
3621 newblock.append("(pass %f spring)"%(z))
3622 else:
3623 newblock.append("(pass %f bottom)"%(z))
3624
3625 self.fromPath(path, newblock, z, retract, entry, True, exitpoint=exitpoint, truncate=ramp)
3626
3627 return newblock
3628
3629 #----------------------------------------------------------------------
3630 # Close paths by joining end with start with a line segment
3631 #----------------------------------------------------------------------
3632 def close(self, items):
3633 undoinfo = []
3634 for bid in items:
3635 block = self.blocks[bid]
3636 if block.name() in ("Header", "Footer"): continue
3637 undoinfo.append(self.insLineUndo(bid, MAXINT,
3638 self.cnc.gline(block.sx, block.sy)))
3639 self.addUndo(undoinfo)
3640
3641 #----------------------------------------------------------------------
3642 # Create a cut my replicating the initial top-only path multiple times
3643 # until the maximum height
3644 #----------------------------------------------------------------------
3645 def cut(self, items, depth=None, stepz=None, surface=None, feed=None, feedz=None, cutFromTop=False, helix=False, helixBottom=True, ramp=0, islandsLeave=False, islandsCut=False, islandsSelectedOnly=True, exitpoint=None, springPass=False, islandsCompensate=False):
3646 if surface is None: surface = self.cnc["surface"]
3647 if stepz is None: stepz = self.cnc["stepz"]
3648 if depth is None: depth = surface - self.cnc["thickness"]
3649
3650 # override temporarily the feed if needed
3651 if feed is not None: # swap feed with cnc[cutfeed]
3652 self.cnc["cutfeed"],feed = feed, self.cnc["cutfeed"]
3653 if feedz is not None:
3654 self.cnc["cutfeedz"],feedz = feedz, self.cnc["cutfeedz"]
3655
3656 #Test if cutting within stock boundaries
3657 if surface > self.cnc["surface"]:
3658 return "ERROR: Starting cut height is higher than stock surface. " \
3659 "Please change stock surface in Tools->Stock or cut depth."
3660 if depth < self.cnc["surface"]-self.cnc["thickness"] or depth > self.cnc["surface"]:
3661 return "ERROR: Cut depth %g outside stock surface: %g .. %g\n" \
3662 "Please change stock surface in Tools->Stock or cut depth." \
3663 %(depth, self.cnc["surface"], self.cnc["surface"]-self.cnc["thickness"])
3664
3665 #Determine operation block name
3666 if abs(depth - (self.cnc["surface"]-self.cnc["thickness"])) < 1e-7:
3667 opname = "cut"
3668 if helix: opname = "helicut"
3669 else:
3670 opname = "cut:%g"%(depth)
3671 if helix: opname = "helicut:%g"%(depth)
3672
3673 stepz = abs(stepz)
3674 undoinfo = []
3675
3676 #Get list of islands and remove them from items
3677 islands = []
3678 islandPaths = []
3679 if islandsLeave:
3680 for bid,block in enumerate(self.blocks):
3681 if islandsSelectedOnly and bid not in items: continue
3682 if block.operationTest('island'):
3683 islands.append(bid)
3684 #determine island height
3685 islz = self.cnc["safe"]
3686 if block.operationGet('minz') is not None:
3687 islz = float(block.operationGet('minz'))
3688 #determine if we should offset island (tabs are always offset)
3689 isloffset=False
3690 if islandsCompensate or block.operationTest('tab'):
3691 isloffset=True
3692 #load island paths
3693 for islandPath in self.toPath(bid):
3694 #compensate for cutter diameter if needed
3695 if isloffset: islandPath = islandPath.offsetClean(CNC.vars["diameter"]/2)[0]
3696 islandPath._inside=islz
3697 islandPaths.append(islandPath)
3698
3699 #Remove islands from paths to cut if not requested
3700 #TODO: maybe also remove all islands with "tab" tag
3701 if not islandsCut and islands:
3702 for island in islands:
3703 if island in items: items.remove(island)
3704 #Check if there are any paths left
3705 if not items: return "You must select toolpaths along with islands!"
3706
3707
3708 for bid in items:
3709 block = self.blocks[bid]
3710 if block.name() in ("Header", "Footer"): continue
3711 block.enable = True
3712 newpath = []
3713 newblock = Block(block.name())
3714
3715 #Do not apply islands on islands:
3716 islandPathsClean = islandPaths
3717 if bid in items and bid in islands:
3718 islandPathsClean = []
3719
3720 for path in self.toPath(bid):
3721
3722 if cutFromTop:
3723 self.cutPath(newblock, block, path, surface + stepz, depth, stepz, helix, helixBottom, ramp, islandPathsClean, exitpoint, springPass)
3724 else:
3725 self.cutPath(newblock, block, path, surface, depth, stepz, helix, helixBottom, ramp, islandPathsClean, exitpoint, springPass)
3726 #newblock.append("( ---------- cut-here ---------- )")
3727 if newblock:
3728 #del newblock[-1] #remove trailing cut-here
3729 undoinfo.append(self.addBlockOperationUndo(bid, opname))
3730 undoinfo.append(self.setBlockLinesUndo(bid, newblock))
3731 self.addUndo(undoinfo)
3732
3733 # restore feed
3734 if feed is not None: self.cnc["cutfeed"] = feed
3735 if feedz is not None: self.cnc["cutfeedz"] = feedz
3736
3737
3738 def createTab(self, x=0, y=0, dx=0, dy=0, z=0, circ=True):
3739 path = Path("tab")
3740
3741 dx = dx/2.
3742 dy = dy/2.
3743
3744 if not circ:
3745 #Square tabs (intersect better with trochoids)
3746 A = A0 = Vector(x-dx, y-dy)
3747 B = Vector(x+dx, y-dy)
3748 path.append(Segment(Segment.LINE, A, B))
3749 A = B
3750 B = Vector(x+dx, y+dy)
3751 path.append(Segment(Segment.LINE, A, B))
3752 A = B
3753 B = Vector(x-dx, y+dy)
3754 path.append(Segment(Segment.LINE, A, B))
3755 A = B
3756 B = A0
3757 path.append(Segment(Segment.LINE, A, B))
3758 else:
3759 #Circular tabs (intersect better with angled lines)
3760 A = Vector(x-max(dx,dy), y)
3761 C = Vector(x,y)
3762 seg = Segment(Segment.CCW, A, A)
3763 seg.setCenter(C)
3764 path.append(seg)
3765
3766 #compensate for cutter radius
3767 #update: this is now done right before cutting, so no need to do it here!
3768 #path = path.offsetClean(CNC.vars["diameter"]/2)[0]
3769
3770 return self.fromPath(path, None, None, False, False, False, None, None, False)
3771
3772
3773 #----------------------------------------------------------------------
3774 # Create tabs to selected blocks
3775 # @param ntabs number of tabs
3776 # @param dtabs distance between tabs
3777 # @param dx width of tabs
3778 # @param dy depth of tabs
3779 # @param z height of tabs
3780 # @param isl create tabs in form of islands?
3781 #----------------------------------------------------------------------
3782 def createTabs(self, items, ntabs, dtabs, dx, dy, z, circ=True):
3783 msg = None
3784 undoinfo = []
3785 if ntabs==0 and dtabs==0: return
3786
3787 tablocks = []
3788 for bid in items:
3789 block = self.blocks[bid]
3790 if block.name() in ("Header", "Footer"): continue
3791
3792 #update minz for selected islands/tabs rather than doing tabs of tabs
3793 if block.operationTest('island'):
3794 block._name='%s [island,minz:%f]'%(block.nameNop(), z)
3795 continue
3796
3797 else:
3798 tablock = Block("%s [tab,island,minz:%f]"%(block.nameNop(), z))
3799 #tablock.color = "#FF0000"
3800 tablock.color = "orange"
3801 tablock.enable = False #Prevent tabs from being accidentaly cut as path
3802
3803 #Add regular tabs
3804 for path in self.toPath(bid):
3805 length = path.length()
3806 d = max(length / float(ntabs), dtabs)
3807 # running length
3808 s = d/2. # start from half distance to add first tab
3809
3810 while s <= length:
3811 P = path.distPoint(s)
3812 s += d
3813 #Make island tabs
3814 tablock.extend(self.createTab(P[0],P[1],dx,dy,z,circ))
3815 tablock.append("( ---------- cut-here ---------- )")
3816
3817 del tablock[-1] #remove last cut-here
3818 tablocks.append(tablock)
3819 self.insBlocks(bid+1, tablocks, "Tabs created")
3820 self.addUndo(undoinfo)
3821
3822 return msg
3823
3824 #----------------------------------------------------------------------
3825 # Reverse direction of cut
3826 #----------------------------------------------------------------------
3827 def reverse(self, items):
3828 undoinfo = []
3829 remove = ["cut","climb","conventional","cw","ccw","reverse"]
3830 for bid in items:
3831 operation = "reverse"
3832
3833 if self.blocks[bid].name() in ("Header", "Footer"): continue
3834 newpath = Path(self.blocks[bid].name())
3835
3836 #Not sure if this is good idea...
3837 #Might get confusing if something goes wrong, but seems to work fine
3838 if self.blocks[bid].operationTest('conventional'): operation+= ",climb"
3839 if self.blocks[bid].operationTest('climb'): operation+= ",conventional"
3840 if self.blocks[bid].operationTest('cw'): operation+= ",ccw"
3841 if self.blocks[bid].operationTest('ccw'): operation+= ",cw"
3842
3843 for path in self.toPath(bid):
3844 path.invert()
3845 newpath.extend(path)
3846 if newpath:
3847 block = self.fromPath(newpath)
3848 undoinfo.append(self.addBlockOperationUndo(bid, operation, remove))
3849 undoinfo.append(self.setBlockLinesUndo(bid, block))
3850 self.addUndo(undoinfo)
3851
3852 #----------------------------------------------------------------------
3853 # Change cut direction
3854 # 1 CW
3855 # -1 CCW
3856 # 2 Conventional = CW for inside profiles and pockets, CCW for outside profiles
3857 # -2 Climb = CCW for inside profiles and pockets, CW for outside profiles
3858 #----------------------------------------------------------------------
3859 def cutDirection(self, items, direction=-1):
3860
3861 undoinfo = []
3862 msg = None
3863
3864 remove = ["cut","reverse","climb","conventional","cw","ccw"]
3865 for bid in items:
3866 if self.blocks[bid].name() in ("Header", "Footer"): continue
3867
3868 opdir = direction
3869 operation = ""
3870
3871 #Decide conventional/climb/error:
3872 side = self.blocks[bid].operationSide()
3873 if abs(direction)>1 and side == 0:
3874 msg = "Conventional/Climb feature only works for paths with 'in/out/pocket' tags!\n"
3875 msg += "Some of the selected paths were not taged (or are both in+out). You can still use CW/CCW for them."
3876 continue
3877 if direction==2:
3878 operation = "conventional,"
3879 if side==-1: opdir=1 #inside CW
3880 if side==1: opdir=-1 #outside CCW
3881 elif direction==-2:
3882 operation = "climb,"
3883 if side==-1: opdir=-1 #inside CCW
3884 if side==1: opdir=1 #outside CW
3885
3886 #Decide CW/CCW tag
3887 if opdir==1:
3888 operation += "cw"
3889 elif opdir==-1:
3890 operation += "ccw"
3891
3892 #Process paths
3893 for path in self.toPath(bid):
3894 if not path.directionSet(opdir):
3895 msg = "Error determining direction of path!"
3896 if path:
3897 block = self.fromPath(path)
3898 undoinfo.append(self.addBlockOperationUndo(bid, operation,remove))
3899 undoinfo.append(self.setBlockLinesUndo(bid, block))
3900 self.addUndo(undoinfo)
3901
3902 return msg
3903
3904 #----------------------------------------------------------------------
3905 # Toggle or set island tag on block
3906 #----------------------------------------------------------------------
3907 def island(self, items, island=None):
3908
3909 undoinfo = []
3910 remove = ["island"]
3911 for bid in items:
3912 isl = island
3913
3914 if self.blocks[bid].name() in ("Header", "Footer"): continue
3915
3916 if isl is None: isl = not self.blocks[bid].operationTest('island')
3917 if isl:
3918 tag = 'island'
3919 self.blocks[bid].color = '#ff0000'
3920 else:
3921 tag = ''
3922 self.blocks[bid].color = None
3923
3924 undoinfo.append(self.addBlockOperationUndo(bid, tag,remove))
3925 #undoinfo.append(self.setBlockLinesUndo(bid, block))
3926
3927 self.addUndo(undoinfo)
3928
3929 #----------------------------------------------------------------------
3930 # Return information for a block
3931 # return XXX
3932 #----------------------------------------------------------------------
3933 def info(self, bid):
3934 block = self.blocks[bid]
3935 paths = self.toPath(bid)
3936 if not paths:
3937 return None, 1
3938 if len(paths)>1:
3939 closed = paths[0].isClosed()
3940 return len(paths), paths[0]._direction(closed)
3941 else:
3942 closed = paths[0].isClosed()
3943 return int(closed), paths[0]._direction(closed)
3944
3945 #----------------------------------------------------------------------
3946 # make a profile on block
3947 # offset +/- defines direction = tool/2
3948 # return new blocks inside the blocks list
3949 #----------------------------------------------------------------------
3950 def profile(self, blocks, offset, overcut=False, name=None, pocket=False):
3951 undoinfo = []
3952 msg = ""
3953 newblocks = []
3954
3955 remove = ["cut","reverse","climb","conventional","cw","ccw","in","out"]
3956
3957 for bid in reversed(blocks):
3958 if self.blocks[bid].name() in ("Header", "Footer"): continue
3959 newpath = []
3960 for path in self.toPath(bid):
3961 if name is not None:
3962 newname = Block.operationName(path.name, name)
3963 elif offset>0:
3964 newname = Block.operationName(path.name, "out,conventional,ccw", remove)
3965 path.directionSet(-1) #turn path to CCW (conventional when milling outside)
3966 else:
3967 newname = Block.operationName(path.name, "in,conventional,cw", remove)
3968 path.directionSet(1) #turn path to CW (conventional when milling inside)
3969
3970 if not path.isClosed():
3971 m = "Path: '%s' is OPEN"%(path.name)
3972 if m not in msg:
3973 if msg: msg += "\n"
3974 msg += m
3975
3976 opath = path.offsetClean(offset, overcut, newname)
3977 if opath:
3978 newpath.extend(opath)
3979 if newpath:
3980 # remember length to shift all new blocks the are inserted before
3981 before = len(newblocks)
3982 undoinfo.extend(self.importPath(bid+1, newpath, newblocks, True, False))
3983 new = len(newblocks)-before
3984 for i in range(before):
3985 newblocks[i] += new
3986 self.blocks[bid].enable = False
3987 self.addUndo(undoinfo)
3988
3989 # return new blocks inside the blocks list
3990 del blocks[:]
3991 # TODO: Not sure how to make the pocket block to cut before profile (to reduce machine load when cuting to dimension)
3992 # Idealy it should be generated as single block containing both pocket and profile
3993 if pocket: msg = msg + self.pocket(newblocks, abs(offset), CNC.vars["stepover"]/50, name, True)
3994 blocks.extend(newblocks)
3995 return msg
3996
3997 #----------------------------------------------------------------------
3998 # Generate a pocket path
3999 #----------------------------------------------------------------------
4000 def _pocket(self, path, diameter, stepover, depth):
4001 #print "_pocket",depth
4002
4003 #python's internal recursion limit hit us before bCNC's limit came to place
4004 #so i increased python's limit to bCNC's limit + 100
4005 maxdepth=10000
4006 import sys
4007 sys.setrecursionlimit(max(sys.getrecursionlimit(),maxdepth+100))
4008
4009 if depth>maxdepth: return None
4010 if depth == 0:
4011 offset = diameter / 2.0
4012 else:
4013 offset = diameter*stepover
4014
4015 opath = path.offset(offset)
4016
4017 if not opath: return None
4018
4019 opath.intersectSelf()
4020 # print
4021 # print "INTERSECT=",opath
4022 opath.removeExcluded(path, offset)
4023 opath.removeZeroLength(abs(offset)/100.)
4024 opath = opath.split2contours()
4025
4026 if not opath: return None
4027
4028 newpath = []
4029 for pout in opath:
4030 pin = self._pocket(pout, diameter, stepover, depth+1)
4031 if not pin:
4032 newpath.append(pout)
4033
4034 #else: # FIXME
4035 # 1. Find closest node that we can move with
4036 # a straight line without intersecting the path
4037 # 2. rotate the pout to start from this node
4038 # 3. join with a normal line
4039 # else
4040 # join with a rapid move as a separate path
4041 elif len(pin)==1:
4042 # FIXME maybe it is dangerous!!
4043 # Have to check before making a straight move
4044 pin[0].join(pout)
4045 newpath.append(pin[0])
4046
4047 else:
4048 # FIXME needs to check if we can go in normal move
4049 # needs to find the closest segment and rotate
4050 #pin[-1].join(pout)
4051 newpath.extend(pin)
4052 newpath.append(pout)
4053 return newpath
4054
4055 #----------------------------------------------------------------------
4056 # make a pocket on block
4057 # return new blocks inside the blocks list
4058 #----------------------------------------------------------------------
4059 def pocket(self, blocks, diameter, stepover, name, nested=False):
4060 undoinfo = []
4061 msg = ""
4062 newblocks = []
4063 for bid in reversed(blocks):
4064 if self.blocks[bid].name() in ("Header", "Footer"): continue
4065 newpath = []
4066 for path in self.toPath(bid):
4067 if not path.isClosed():
4068 m = "Path: '%s' is OPEN"%(path.name)
4069 if m not in msg:
4070 if msg: msg += "\n"
4071 msg += m
4072 path.close()
4073
4074 # Remove tiny segments
4075 path.removeZeroLength(abs(diameter)/100.)
4076 # Convert very small arcs to lines
4077 path.convert2Lines(abs(diameter)/10.)
4078
4079 path.directionSet(1) #turn path to CW (conventional when milling inside)
4080
4081 D = path.direction()
4082 if D==0: D=1
4083
4084 remove = ["cut","reverse","climb","conventional","cw","ccw","pocket"]
4085 if name is None:
4086 path.name = Block.operationName(path.name, "pocket,conventional,cw", remove)
4087 else:
4088 path.name = Block.operationName(path.name, name, remove)
4089
4090 newpath.extend(self._pocket(path, -D*diameter, stepover, 0))
4091
4092 if newpath:
4093 # remember length to shift all new blocks
4094 # the are inserted before
4095 before = len(newblocks)
4096 undoinfo.extend(self.importPath(bid+1, newpath,
4097 newblocks, True, False))
4098 new = len(newblocks)-before
4099 for i in range(before):
4100 newblocks[i] += new
4101 if not nested: self.blocks[bid].enable = False
4102 self.addUndo(undoinfo)
4103
4104 # return new blocks inside the blocks list
4105 del blocks[:]
4106 blocks.extend(newblocks)
4107 return msg
4108
4109 #----------------------------------------------------------------------
4110 # make a trochoidal profile on block
4111 # offset +/- defines direction = tool/2
4112 # return new blocks inside the blocks list
4113 #----------------------------------------------------------------------
4114 def trochprofile_cnc(self, blocks, offset, overcut=False,adaptative=True, adaptedRadius=0.0, cutDiam=0.0, tooldiameter=0.0,\
4115 targetDepth=0.0,depthIncrement=0.0, tabsnumber=0.0, tabsWidth=0.0, tabsHeight=0.0):
4116 undoinfo = []
4117 msg = ""
4118 newblocks = []
4119 for bid in reversed(blocks):
4120 if self.blocks[bid].name() in ("Header", "Footer"): continue
4121 newpath = []
4122 for path in self.toPath(bid):
4123 # if name is not None:
4124 # newname = Block.operationName(path.name, name)
4125 explain = "Tr "
4126 if offset>0:
4127 explain+="out "#n +="out "
4128 # elif offset==0:
4129 # n +=" on "
4130 elif offset<0:
4131 explain +="in "
4132 explain+= str(cutDiam)
4133 if cutDiam!= abs(2*offset):
4134 explain+=" offs "+str(abs(offset)-cutDiam/2.0)
4135 if offset<0:
4136 if adaptative:
4137 explain+=" Adapt bit "+str(tooldiameter)
4138 if overcut:
4139 explain+=" overc"
4140 newname = Block.operationName(path.name,explain)
4141
4142 if not path.isClosed():
4143 m = "Path: '%s' is OPEN"%(path.name)
4144 if m not in msg:
4145 if msg: msg += "\n"
4146 msg += m
4147
4148 # print "ORIGINAL\n",path
4149 # Remove tiny segments
4150 path.removeZeroLength(abs(offset)/100.)
4151 # Convert very small arcs to lines
4152 path.convert2Lines(abs(offset)/10.)
4153 D = path.direction()
4154 # print "Path Direction:",D
4155 if D==0: D=1
4156 # print "ZERO\n",path
4157 opath = path.offset(D*offset, newname)
4158 # print "OFFSET\n",opath
4159 if opath:
4160 opath.intersectSelf()
4161 # print "INTERSECT\n",opath
4162 opath.removeExcluded(path, D*offset)
4163 # print "EXCLUDE\n",opath
4164 opath.removeZeroLength(abs(offset)/100.)
4165 # print "REMOVE\n",opath
4166 opath = opath.split2contours()
4167 if opath:
4168 # if adaptative:
4169 # if overcut:
4170 if overcut == True or adaptative == True:
4171 for p in opath:
4172 p.trochovercut(D*offset, overcut, adaptative, adaptedRadius)
4173 newpath.extend(opath)
4174 if newpath:
4175 # remember length to shift all new blocks the are inserted before
4176 before = len(newblocks)
4177 undoinfo.extend(self.importPath(bid+1, newpath, newblocks, True, False))
4178 new = len(newblocks)-before
4179 for i in range(before):
4180 newblocks[i] += new
4181 self.blocks[bid].enable = False
4182 self.addUndo(undoinfo)
4183
4184 # return new blocks inside the blocks list
4185 del blocks[:]
4186 blocks.extend(newblocks)
4187
4188 # if tabsnumber !=0:
4189 #def createTabs(self, items, ntabs, dtabs, dx, dy, z, circ=True):
4190 # self.createTabs(reversed(blocks),1, 0, 1, 0, -1.2,1)
4191 #def cut(self, items, depth=None, stepz=None, surface=None, feed=None, feedz=None, cutFromTop=False, helix=False, helixBottom=True, ramp=0, islandsLeave=False, islandsCut=False, islandsSelectedOnly=True, exitpoint=None, springPass=False, islandsCompensate=False):
4192 self.cut(reversed(blocks), targetDepth,depthIncrement,0, 900, 120, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0)
4193 return msg
4194 #----------------------------------------------------------------------
4195 def adaptative_clearence(self, blocks, offset, overcut=False,adaptative=True, adaptedRadius=0.0, cutDiam=0.0, tooldiameter=0.0, name=None):
4196 undoinfo = []
4197 msg = ""
4198 newblocks = []
4199 for bid in reversed(blocks):
4200 if self.blocks[bid].name() in ("Header", "Footer"): continue
4201 newpath = []
4202 for path in self.toPath(bid):
4203 # if name is not None:
4204 # newname = Block.operationName(path.name, name)
4205 explain = "Clear "
4206 if offset>0:
4207 explain+="out "#n +="out "
4208 # elif offset==0:
4209 # n +=" on "
4210 elif offset<0:
4211 explain +="in "
4212 explain+= str(cutDiam)
4213 if cutDiam!= abs(2*offset):
4214 explain+=" offs "+str(abs(offset)-cutDiam/2.0)
4215 if offset<0:
4216 if adaptative:
4217 explain+=" Adapt bit "+str(tooldiameter)
4218 if overcut:
4219 explain+=" overc"
4220 newname = Block.operationName(path.name,explain)
4221
4222 if not path.isClosed():
4223 m = "Path: '%s' is OPEN"%(path.name)
4224 if m not in msg:
4225 if msg: msg += "\n"
4226 msg += m
4227
4228 # print "ORIGINAL\n",path
4229 # Remove tiny segments
4230 path.removeZeroLength(abs(offset)/100.)
4231 # Convert very small arcs to lines
4232 path.convert2Lines(abs(offset)/10.)
4233 D = path.direction()
4234 # print "Path Direction:",D
4235 if D==0: D=1
4236 # print "ZERO\n",path
4237 opath = path.offset(D*offset, newname)
4238 # print "OFFSET\n",opath
4239 if opath:
4240 opath.intersectSelf()
4241 # print "INTERSECT\n",opath
4242 opath.removeExcluded(path, D*offset)
4243 # print "EXCLUDE\n",opath
4244 opath.removeZeroLength(abs(offset)/100.)
4245 # print "REMOVE\n",opath
4246 opath = opath.split2contours()
4247 if opath:
4248 # if adaptative:
4249 # if overcut:
4250 # if overcut == True or adaptative == True:
4251 for p in opath:
4252 p.two_bit_adaptative_cut(D*offset, overcut, adaptative, adaptedRadius)
4253 newpath.extend(opath)
4254 if newpath:
4255 # remember length to shift all new blocks the are inserted before
4256 before = len(newblocks)
4257 undoinfo.extend(self.importPath(bid+1, newpath, newblocks, True, False))
4258 new = len(newblocks)-before
4259 for i in range(before):
4260 newblocks[i] += new
4261 self.blocks[bid].enable = False
4262 self.addUndo(undoinfo)
4263
4264 # return new blocks inside the blocks list
4265 # del blocks[:]
4266 blocks.extend(newblocks)
4267 return msg
4268
4269 #----------------------------------------------------------------------
4270 # draw a hole (circle with radius)
4271 #----------------------------------------------------------------------
4272 def hole(self, bid, radius):
4273 block = self.blocks[bid]
4274
4275 # Find starting location
4276 self.initPath(bid)
4277 for i,line in enumerate(block):
4278 cmds = CNC.parseLine(line)
4279 if cmds is None: continue
4280 self.cnc.motionStart(cmds)
4281 self.cnc.motionEnd()
4282
4283 # FIXME doesn't work
4284
4285 # New lines to append
4286 pos = lid+1
4287 block.insert(pos, "g0 %s"%(self.fmt("x",self.cnc.x+radius)))
4288 pos += 1
4289 block.insert(pos, "g1 %s"%(self.fmt("z",-0.001)))
4290 pos += 1
4291 block.insert(pos, "g2 %s"%(self.fmt("i",-radius)))
4292 pos += 1
4293
4294 #----------------------------------------------------------------------
4295 # Modify the lines according to the supplied function and arguments
4296 #----------------------------------------------------------------------
4297 def modify(self, items, func, tabFunc, *args):
4298 undoinfo = []
4299 old = {} # Motion commands: Last value
4300 new = {} # Motion commands: New value
4301 relative = False
4302
4303 for bid,lid in self.iterate(items):
4304 block = self.blocks[bid]
4305
4306 if isinstance(lid, int):
4307 cmds = CNC.parseLine(block[lid])
4308 if cmds is None: continue
4309 self.cnc.motionStart(cmds)
4310
4311 # Collect all values
4312 new.clear()
4313 for cmd in cmds:
4314 if cmd.upper() == 'G91': relative = True
4315 if cmd.upper() == 'G90': relative = False
4316 c = cmd[0].upper()
4317 # record only coordinates commands
4318 if c not in "XYZIJKR": continue
4319 try:
4320 new[c] = old[c] = float(cmd[1:])*self.cnc.unit
4321 except:
4322 new[c] = old[c] = 0.0
4323
4324 # Modify values with func
4325 if func(new, old, relative, *args):
4326 # Reconstruct new line
4327 newcmd = []
4328 present = ""
4329 for cmd in cmds:
4330 c = cmd[0].upper()
4331 if c in "XYZIJKR": # Coordinates
4332 newcmd.append(self.fmt(c,new[c]/self.cnc.unit))
4333 elif c == "G" and int(cmd[1:]) in (0,1,2,3): # Motion
4334 newcmd.append("G%d"%(self.cnc.gcode))
4335 else: # the rest leave unchanged
4336 newcmd.append(cmd)
4337 present += c
4338 # Append motion commands if not exist and changed
4339 check = "XYZ"
4340 if 'I' in new or 'J' in new or 'K' in new:
4341 check += "IJK"
4342 for c in check:
4343 try:
4344 if c not in present and new.get(c) != old.get(c):
4345 newcmd.append(self.fmt(c,new[c]/self.cnc.unit))
4346 except:
4347 pass
4348 undoinfo.append(self.setLineUndo(bid,lid," ".join(newcmd)))
4349 self.cnc.motionEnd()
4350 # reset arc offsets
4351 for i in "IJK":
4352 if i in old: old[i] = 0.0
4353
4354 # FIXME I should add it later, check all functions using it
4355 self.addUndo(undoinfo)
4356
4357 #----------------------------------------------------------------------
4358 # Move position by dx,dy,dz
4359 #----------------------------------------------------------------------
4360 def moveFunc(self, new, old, relative, dx, dy, dz):
4361 if relative: return False
4362 changed = False
4363 if 'X' in new:
4364 changed = True
4365 new['X'] += dx
4366 if 'Y' in new:
4367 changed = True
4368 new['Y'] += dy
4369 if 'Z' in new:
4370 changed = True
4371 new['Z'] += dz
4372 return changed
4373
4374 #----------------------------------------------------------------------
4375 def orderLines(self, items, direction):
4376 if direction == "UP":
4377 self.orderUp(items)
4378 elif direction == "DOWN":
4379 self.orderDown(items)
4380 else:
4381 pass
4382
4383 #----------------------------------------------------------------------
4384 # Move position by dx,dy,dz
4385 #----------------------------------------------------------------------
4386 def moveLines(self, items, dx, dy, dz=0.0):
4387 return self.modify(items, self.moveFunc, None, dx, dy, dz)
4388
4389 #----------------------------------------------------------------------
4390 # Rotate position by c(osine), s(ine) of an angle around center (x0,y0)
4391 #----------------------------------------------------------------------
4392 def rotateFunc(self, new, old, relative, c, s, x0, y0):
4393 if 'X' not in new and 'Y' not in new: return False
4394 x = getValue('X',new,old)
4395 y = getValue('Y',new,old)
4396 new['X'] = c*(x-x0) - s*(y-y0) + x0
4397 new['Y'] = s*(x-x0) + c*(y-y0) + y0
4398
4399 if 'I' in new or 'J' in new:
4400 i = getValue('I',new,old)
4401 j = getValue('J',new,old)
4402 if self.cnc.plane in (XY, XZ): new['I'] = c*i - s*j
4403 if self.cnc.plane in (XY, YZ): new['J'] = s*i + c*j
4404 return True
4405
4406 #----------------------------------------------------------------------
4407 # Transform (rototranslate) position with the following function:
4408 # xn = c*x - s*y + xo
4409 # yn = s*x + c*y + yo
4410 # it is like the rotate but the rotation center is not defined
4411 #----------------------------------------------------------------------
4412 def transformFunc(self, new, old, relative, c, s, xo, yo):
4413 if 'X' not in new and 'Y' not in new: return False
4414 x = getValue('X',new,old)
4415 y = getValue('Y',new,old)
4416 new['X'] = c*x - s*y + xo
4417 new['Y'] = s*x + c*y + yo
4418
4419 if 'I' in new or 'J' in new:
4420 i = getValue('I',new,old)
4421 j = getValue('J',new,old)
4422 new['I'] = c*i - s*j
4423 new['J'] = s*i + c*j
4424 return True
4425
4426 #----------------------------------------------------------------------
4427 # Rotate items around optional center (on XY plane)
4428 # ang in degrees (counter-clockwise)
4429 #----------------------------------------------------------------------
4430 def rotateLines(self, items, ang, x0=0.0, y0=0.0):
4431 a = math.radians(ang)
4432 c = math.cos(a)
4433 s = math.sin(a)
4434 if ang in (0.0,90.0,180.0,270.0,-90.0,-180.0,-270.0):
4435 c = round(c) # round numbers to avoid nasty extra digits
4436 s = round(s)
4437 return self.modify(items, self.rotateFunc, None, c, s, x0, y0)
4438
4439 #----------------------------------------------------------------------
4440 # Use the orientation information to orient selected code
4441 #----------------------------------------------------------------------
4442 def orientLines(self, items):
4443 if not self.orient.valid: return "ERROR: Orientation information is not valid"
4444 c = math.cos(self.orient.phi)
4445 s = math.sin(self.orient.phi)
4446 return self.modify(items, self.transformFunc, None, c, s,
4447 self.orient.xo, self.orient.yo)
4448
4449 #----------------------------------------------------------------------
4450 # Mirror Horizontal
4451 #----------------------------------------------------------------------
4452 def mirrorHFunc(self, new, old, relative, *kw):
4453 changed = False
4454 for axis in 'XI':
4455 if axis in new:
4456 new[axis] = -new[axis]
4457 changed = True
4458 if self.cnc.gcode in (2,3): # Change 2<->3
4459 self.cnc.gcode = 5-self.cnc.gcode
4460 changed = True
4461 return changed
4462
4463 #----------------------------------------------------------------------
4464 # Mirror Vertical
4465 #----------------------------------------------------------------------
4466 def mirrorVFunc(self, new, old, relative, *kw):
4467 changed = False
4468 for axis in 'YJ':
4469 if axis in new:
4470 new[axis] = -new[axis]
4471 changed = True
4472 if self.cnc.gcode in (2,3): # Change 2<->3
4473 self.cnc.gcode = 5-self.cnc.gcode
4474 changed = True
4475 return changed
4476
4477 #----------------------------------------------------------------------
4478 # Mirror horizontally/vertically
4479 #----------------------------------------------------------------------
4480 def mirrorHLines(self, items):
4481 return self.modify(items, self.mirrorHFunc, None)
4482
4483 #----------------------------------------------------------------------
4484 def mirrorVLines(self, items):
4485 return self.modify(items, self.mirrorVFunc, None)
4486
4487 #----------------------------------------------------------------------
4488 # Round all digits with accuracy
4489 #----------------------------------------------------------------------
4490 def roundFunc(self, new, old, relative):
4491 for name,value in new.items():
4492 new[name] = round(value,CNC.digits)
4493 return bool(new)
4494
4495 #----------------------------------------------------------------------
4496 # Round line by the amount of digits
4497 #----------------------------------------------------------------------
4498 def roundLines(self, items, acc=None):
4499 if acc is not None: CNC.digits = acc
4500 return self.modify(items, self.roundFunc, None)
4501
4502 #----------------------------------------------------------------------
4503 # Inkscape g-code tools on slice/slice it raises the tool to the
4504 # safe height then plunges again.
4505 # Comment out all these patterns
4506 #
4507 # FIXME needs re-working...
4508 #----------------------------------------------------------------------
4509 def inkscapeLines(self):
4510 undoinfo = []
4511
4512 # Loop over all blocks
4513 self.initPath()
4514 newlines = []
4515 #last = None
4516 last = -1 # line location when it was last raised with dx=dy=0.0
4517
4518 #for line in self.iterate():
4519 #for bid,block in enumerate(self.blocks):
4520 # for li,line in enumerate(block):
4521 for line in self.lines():
4522 # step id
4523 # 0 - normal cutting z<0
4524 # 1 - z>0 raised with dx=dy=0.0
4525 # 2 - z<0 plunged with dx=dy=0.0
4526 cmd = CNC.parseLine(line)
4527 if cmd is None:
4528 newlines.append(line)
4529 continue
4530 self.cnc.motionStart(cmd)
4531 xyz = self.cnc.motionPath()
4532 if self.cnc.dx==0.0 and self.cnc.dy==0.0:
4533 if self.cnc.z>0.0 and self.cnc.dz>0.0:
4534 last = len(newlines)
4535 #last = bid, li
4536
4537 #elif self.cnc.z<0.0 and self.cnc.dz<0.0 and last is not None:
4538 elif self.cnc.z<0.0 and self.cnc.dz<0.0 and last>=0:
4539 # comment out all lines from last
4540 #lb, ll = last
4541 #while bid!=lb or li!=ll:
4542 # b = self.blocks[lb]
4543 # line = b[ll]
4544 # if line and line[0] not in ("(","%"):
4545 # undoinfo.append(b.setLineUndo(ll,"(%s)"%(line)))
4546 # ll += 1
4547 # if ll>=len(b):
4548 # lb += 1
4549 # ll = 0
4550 # last = None
4551 for i in range(last,len(newlines)):
4552 s = newlines[i]
4553 if s and s[0] != '(':
4554 newlines[i] = "(%s)"%(s)
4555 last = -1
4556 else:
4557 #last = None
4558 last = -1
4559 newlines.append(line)
4560 self.cnc.motionEnd()
4561
4562 self.addUndo(self.setLinesUndo(newlines))
4563
4564 #----------------------------------------------------------------------
4565 # Remove the line number for lines
4566 #----------------------------------------------------------------------
4567 def removeNlines(self, items):
4568 pass
4569
4570 #----------------------------------------------------------------------
4571 # Re-arrange using genetic algorithms a set of blocks to minimize
4572 # rapid movements.
4573 #----------------------------------------------------------------------
4574 def optimize(self, items):
4575 n = len(items)
4576
4577 matrix = []
4578 for i in range(n):
4579 matrix.append([0.0] * n)
4580
4581 # Find distances between blocks (end to start)
4582 for i in range(n):
4583 block = self.blocks[items[i]]
4584 x1 = block.ex
4585 y1 = block.ey
4586 for j in range(n):
4587 if i==j: continue
4588 block = self.blocks[items[j]]
4589 x2 = block.sx
4590 y2 = block.sy
4591 dx = x1-x2
4592 dy = y1-y2
4593 #Compensate for machines, which have different speed of X and Y:
4594 dx/=CNC.feedmax_x
4595 dy/=CNC.feedmax_y
4596 matrix[i][j] = sqrt(dx*dx + dy*dy)
4597 #from pprint import pprint
4598 #pprint(matrix)
4599
4600 best = [0]
4601 unvisited = list(range(1,n))
4602 while unvisited:
4603 last = best[-1]
4604 row = matrix[last]
4605 # from all the unvisited places search the closest one
4606 mindist = 1e30
4607 for i,u in enumerate(unvisited):
4608 d = row[u]
4609 if d < mindist:
4610 mindist = d
4611 si = i
4612 best.append(unvisited.pop(si))
4613 #print "best=",best
4614
4615 undoinfo = []
4616 for i in range(len(best)):
4617 b = best[i]
4618 if i==b: continue
4619 ptr = best.index(i)
4620 # swap i,b in items
4621 undoinfo.append(self.swapBlockUndo(items[i], items[b]))
4622 # swap i,ptr in best
4623 best[i], best[ptr] = best[ptr], best[i]
4624 self.addUndo(undoinfo, "Optimize")
4625
4626 #----------------------------------------------------------------------
4627 # Use probe information to modify the g-code to autolevel
4628 #----------------------------------------------------------------------
4629 def compile(self, queue, stopFunc=None):
4630 #lines = [self.cnc.startup]
4631 paths = []
4632
4633 def add(line, path):
4634 if line is not None:
4635 if isinstance(line,str):
4636 queue.put(line+"\n")
4637 else:
4638 queue.put(line)
4639 paths.append(path)
4640 autolevel = not self.probe.isEmpty()
4641 self.initPath()
4642 for line in CNC.compile(self.cnc.startup.splitlines()):
4643 add(line, None)
4644
4645 every = 1
4646 for i,block in enumerate(self.blocks):
4647 if not block.enable: continue
4648 for j,line in enumerate(block):
4649 every -= 1
4650 if every<=0:
4651 if stopFunc is not None and stopFunc():
4652 return None
4653 every = 50
4654
4655 newcmd = []
4656 cmds = CNC.compileLine(line)
4657 if cmds is None:
4658 continue
4659 elif isinstance(cmds,str):
4660 cmds = CNC.breakLine(cmds)
4661 else:
4662 # either CodeType or tuple, list[] append at it as is
4663 #lines.append(cmds)
4664 if isinstance(cmds,types.CodeType) or isinstance(cmds,int):
4665 add(cmds, None)
4666 else:
4667 add(cmds, (i,j))
4668 continue
4669
4670 skip = False
4671 expand = None
4672 self.cnc.motionStart(cmds)
4673
4674 # FIXME append feed on cut commands. It will be obsolete in grbl v1.0
4675 if CNC.appendFeed and self.cnc.gcode in (1,2,3):
4676 # Check is not existing in cmds
4677 for c in cmds:
4678 if c[0] in ('f','F'):
4679 break
4680 else:
4681 cmds.append(self.fmt('F',self.cnc.feed/self.cnc.unit))
4682
4683 if autolevel and self.cnc.gcode in (0,1,2,3) and self.cnc.mval==0:
4684 xyz = self.cnc.motionPath()
4685 if not xyz:
4686 # while auto-levelling, do not ignore non-movement
4687 # commands, just append the line as-is
4688 #lines.append(line)
4689 #paths.append(None)
4690 add(line, None)
4691 else:
4692 extra = ""
4693 for c in cmds:
4694 if c[0].upper() not in ('G','X','Y','Z','I','J','K','R'):
4695 extra += c
4696 x1,y1,z1 = xyz[0]
4697 if self.cnc.gcode == 0:
4698 g = 0
4699 else:
4700 g = 1
4701 for x2,y2,z2 in xyz[1:]:
4702 for x,y,z in self.probe.splitLine(x1,y1,z1,x2,y2,z2):
4703 add("G%d%s%s%s%s"%\
4704 (g,
4705 self.fmt('X',x/self.cnc.unit),
4706 self.fmt('Y',y/self.cnc.unit),
4707 self.fmt('Z',z/self.cnc.unit),
4708 extra),
4709 (i,j))
4710 extra = ""
4711 x1,y1,z1 = x2,y2,z2
4712 self.cnc.motionEnd()
4713 continue
4714 else:
4715 # FIXME expansion policy here variable needed
4716 # Canned cycles
4717 if CNC.drillPolicy==1 and \
4718 self.cnc.gcode in (81,82,83,85,86,89):
4719 expand = self.cnc.macroGroupG8X()
4720 # Tool change
4721 elif self.cnc.mval == 6:
4722 if CNC.toolPolicy == 0:
4723 pass # send to grbl
4724 elif CNC.toolPolicy == 1:
4725 skip = True # skip whole line
4726 elif CNC.toolPolicy >= 2:
4727 expand = CNC.compile(self.cnc.toolChange())
4728 self.cnc.motionEnd()
4729
4730 if expand is not None:
4731 for line in expand:
4732 add(line, None)
4733 expand = None
4734 continue
4735 elif skip:
4736 skip = False
4737 continue
4738
4739 for cmd in cmds:
4740 c = cmd[0]
4741 try: value = float(cmd[1:])
4742 except: value = 0.0
4743 if c.upper() in ("F","X","Y","Z","I","J","K","R","P"):
4744 cmd = self.fmt(c,value)
4745 else:
4746 opt = ERROR_HANDLING.get(cmd.upper(),0)
4747 if opt == SKIP: cmd = None
4748 if cmd is not None:
4749 newcmd.append(cmd)
4750
4751 add("".join(newcmd), (i,j))
4752
4753 return paths
4754
4755 #if __name__=="__main__":
4756 # orient = Orient()
4757 # orient.add( 0, 0, 100, 50)
4758 # orient.add( 50, 10, 150, 60)
4759 # orient.add(100, 20, 200, 70)
4760 # phi,xo,yo = orient.solve()
4761 # print phi,degrees(phi),xo,yo
4762 #
4763 # orient.clear()
4764 # orient.add( 0, 0, -50, 100)
4765 # orient.add( 50, 10, -60, 150)
4766 # orient.add(100, 20, -70, 200)
4767 # phi,xo,yo = orient.solve()
4768 # print phi,degrees(phi),xo,yo
4769 #
4770 # import pdb; pdb.set_trace()
4771 # #print Block.operationName("door","in")
4772 # print Block.operationName("door [in:2,cut:0.1]","cut:0.5")
4773 # print Block.operationName("door [in:2,cut:0.1]","in")