Sat, 04 Jun 2016 09:22:51 +0200
Code cleanup
16 | 1 | """ |
2 | Lasercutter library | |
3 | 2015/2016 by NeoSoft, Malte Bayer | |
4 | Intended to use standalone or implemented in Pronterface/Printrun | |
5 | """ | |
6 | ||
7 | """ | |
8 | LASERCUT SETTINGS | |
9 | TODO: move to printrun settings | |
10 | """ | |
19 | 11 | ENGRAVE_SPEED = 10 * 60 # mm/min |
16 | 12 | # 30mm/min works for wood (regulate the output power to something between 10-30%) |
13 | # 30mm/min for black anodized aluminum to get a light engraving @ 100% power | |
14 | # 10mm/min for black anodized aluminum to get more "silver" @ 100% power | |
15 | ||
19 | 16 | TRAVEL_SPEED = 120 * 60 |
17 | E_FACTOR = 0.5 | |
16 | 18 | |
19 | # BITMAP: | |
20 | DPI = 300 | |
21 | GREY_THRESHOLD = 0 | |
22 | CHANGE_DIRECTION = True | |
23 | INVERT_CUT = True | |
24 | ||
25 | """ | |
26 | STATIC DEFINITIONS | |
27 | DO NOT CHANGE WORLD's RULES! | |
28 | """ | |
29 | INCH = 25.4 # mm | |
30 | MM_PIXEL = round(INCH / DPI, 4) | |
31 | STEPS_PIXEL = MM_PIXEL * 80 # mine is 80 steps/mm on XY | |
32 | ||
33 | # FOR HPGL: | |
34 | SCALE_FACTOR = 1.0 / 40.0 # 40 plotter units | |
35 | ||
20 | 36 | # GENERAL HEADER AND FOOTER GCODE |
37 | GCODE_HEAD = """ | |
38 | ; GCode generated by laser.py pronterface library (marlin code flavour) | |
39 | ; 2015/2016 by NeoSoft - Malte Bayer | |
40 | ||
41 | G21 ; Metric | |
42 | ; We assume Z is in focus height and laser head is focus at bottom left of image! | |
43 | G92 X0 Y0 E0; set zero position - new origin | |
44 | G90 ; absolute positioning | |
45 | M82 ; Set extruder (laser) to absolute positioning | |
46 | M201 X1000 Y1000 E1000 ; Set acceleration | |
47 | M203 X1000 Y1000 Z4 E1000 ; Set max feedrate | |
48 | M209 S0 ; disable firmware retraction, we dont want to burn holes... | |
49 | M302 ; Allow cold extrudes - doesnt matter because we hack the extruder physically off with the M571 E mod | |
50 | M571 S1 E1 ; Activate Laser output on extrusion, but block real motor movement! | |
51 | G0 X0 Y0 F%d ; Set moving speed TRAVEL_SPEED | |
52 | G1 X0 Y0 F%d ; Set linear engraving speed ENGRAVE_SPEED | |
53 | ||
54 | """ % (TRAVEL_SPEED, ENGRAVE_SPEED) | |
55 | ||
56 | GCODE_FOOT = """M400 ; Wait for all moves to finish | |
57 | M571 S0 E0 | |
58 | M42 P28 S0 ; Force laser off! | |
59 | M501 ; undo all settings made | |
60 | """ | |
16 | 61 | |
62 | from PIL import Image | |
63 | import sys | |
64 | ||
65 | # Imports for SVG | |
66 | import xml.etree.ElementTree as ET | |
67 | import math | |
68 | from svg2gcode import shapes as shapes_pkg | |
69 | from svg2gcode.shapes import point_generator | |
70 | ||
71 | ||
72 | class Lasercutter: | |
73 | """ | |
74 | Lasercutter methods | |
20 | 75 | parameters: log = logger function (fuction has to accept a string) |
16 | 76 | """ |
77 | def __init__(self, pronterwindow = None): | |
78 | if pronterwindow: | |
79 | self.pronterwindow = pronterwindow | |
80 | self.log = pronterwindow.log | |
20 | 81 | self.pronterwindow.clear_log(None) |
16 | 82 | else: |
83 | self.pronterwindow = None | |
84 | self.log = lambda : None | |
20 | 85 | self.log("Lasercutter library initialized\n%d DPI (%f mm/pixel)" % (DPI, MM_PIXEL)) |
16 | 86 | if STEPS_PIXEL <= 5: |
87 | self.log("WARNING: STEPS PER PIXEL NEEDS TO BE > 5 (otherwise marlin joins lines): %f" % STEPS_PIXEL) | |
20 | 88 | self.log("Travel/Engrave speed: %d mm/sec, %d mm/sec" % ( |
89 | TRAVEL_SPEED / 60, ENGRAVE_SPEED / 60) ) | |
90 | self.log("") | |
16 | 91 | |
92 | ||
93 | def pixel2bit(self, pixel, threshold=128): | |
94 | """Convert the pixel value to a bit.""" | |
95 | # some really weird stuff here ;-P | |
96 | ||
97 | # RGB to greyscale | |
98 | #print pixel | |
99 | #print type(pixel) | |
100 | if isinstance(pixel, tuple): | |
101 | #rgb | |
102 | pixel = pixel[0]*0.2989 + pixel[1]*0.5870 + pixel[2]*0.1140 | |
103 | threshold = 128 | |
104 | if pixel > threshold: | |
105 | return 1 | |
106 | else: | |
107 | return 0 | |
108 | ||
109 | # color palette | |
110 | if pixel <= threshold: | |
111 | return 1 | |
112 | else: | |
113 | return 0 | |
114 | ||
115 | def image2gcode(self, filename): | |
116 | """ | |
117 | Open a image file and get the basic information about it. | |
118 | Then convert it to gcode (replacing the existing gcode buffer contents) | |
119 | """ | |
120 | try: | |
121 | im = Image.open(filename) | |
122 | except: | |
123 | self.log("Unable to open %s" % filename) | |
124 | return False | |
125 | ||
126 | self.log("Converting Image for lasercut:") | |
127 | self.log("File: %s" % filename) | |
128 | self.log("format: %s, mode: %s" % (im.format, im.mode)) | |
129 | width,height = im.size | |
130 | self.log("size: %d x %d pixels" % im.size) | |
131 | ||
132 | pix = im.load() | |
133 | ||
134 | fo = open(filename + ".g", "w") | |
20 | 135 | fo.write("; Filename: %s\n%s" % (filename, GCODE_HEAD)) |
16 | 136 | |
137 | fo.write(";Start engraving the raster image: %dx%d points @ %d DPI = %.0fx%.0f mm\n\n" % ( | |
138 | im.size[0], im.size[1], DPI, im.size[0]*MM_PIXEL, im.size[1]*MM_PIXEL) ) | |
139 | ||
140 | INVERT_Y = MM_PIXEL * (im.size[1] -1) * (-1) | |
141 | DIR = 1 | |
142 | for X in range(im.size[0]): | |
143 | fo.write("; X=%d printing row: direction %i\n" % (X, DIR)) | |
144 | fo.write("G92 E0\n") | |
145 | E = 0 | |
146 | last_bit = 1 # we engrave on black pixel = 0 | |
147 | START_Y = 0 | |
148 | if DIR > 0: | |
149 | range_start = 0 | |
150 | range_stop = im.size[1] | |
151 | else: | |
152 | range_start = im.size[1] -1 | |
153 | range_stop = -1 | |
154 | ||
155 | for Y in range(range_start, range_stop, DIR): | |
156 | YMM = abs((Y * MM_PIXEL) + INVERT_Y) | |
157 | XMM = X * MM_PIXEL | |
158 | #print "X %d Y %d" % (X, Y) | |
159 | bit = self.pixel2bit(pix[X, Y], GREY_THRESHOLD) | |
160 | if INVERT_CUT: | |
161 | if bit == 0: | |
162 | bit = 1 | |
163 | else: | |
164 | bit = 0 | |
165 | if last_bit == bit: | |
166 | if bit == 1: | |
167 | # nothing to do, | |
168 | continue | |
169 | else: | |
170 | # are we at the end of Y range? | |
171 | #print Y | |
172 | if (Y == (im.size[1] - 1)) or (Y == 0): | |
173 | # draw line | |
174 | if DIR > 0: | |
175 | E = E + MM_PIXEL * (Y - START_Y) | |
176 | else: | |
177 | E = E + MM_PIXEL * (START_Y - Y) | |
178 | fo.write("G1 X%.4f Y%.4f E%.4f\n" % (XMM, YMM, E * E_FACTOR)) | |
179 | else: | |
180 | # bit value has changed! | |
181 | if bit == 0: | |
182 | # jump to start of line to write | |
183 | START_Y = Y | |
184 | fo.write("G0 X%.4f Y%.4f\n" % (XMM, YMM)) | |
185 | else: | |
186 | # end of line to write | |
187 | if DIR > 0: | |
188 | E = E + (MM_PIXEL * (Y - START_Y)) | |
189 | else: | |
190 | E = E + (MM_PIXEL * (START_Y - Y)) | |
191 | fo.write("G1 X%.4f Y%.4f E%.4f\n" % (XMM, YMM, E * E_FACTOR)) | |
192 | last_bit = bit | |
193 | if CHANGE_DIRECTION: | |
194 | DIR = DIR * (-1) # change y direction on every X | |
195 | ||
20 | 196 | fo.write(GCODE_FOOT) |
16 | 197 | fo.close() |
198 | ||
199 | if self.pronterwindow: | |
200 | self.log("") | |
201 | self.pronterwindow.load_gcode_async(filename + '.g') | |
202 | ||
203 | def hpgl2gcode(self, filename): | |
204 | OFFSET_X = 0.0 | |
205 | OFFSET_Y = 0.0 | |
206 | ||
207 | self.log("Converting HPGL plot for lasercut:") | |
208 | self.log("File: %s" % filename) | |
209 | ||
210 | fi = open(filename, "r") | |
211 | fo = open(filename + ".g", "w") | |
20 | 212 | fo.write("; Filename: %s\n%s" % (filename, GCODE_HEAD)) |
16 | 213 | |
214 | G = "0" | |
215 | LASER_STATE = 0 | |
216 | last_coord = [0.0,0.0] | |
217 | last_cmd = "" | |
218 | ||
219 | for line in fi.readlines(): | |
220 | for action in line.split(";"): | |
221 | action = action.strip() | |
222 | if action != "": | |
223 | cmd = action[:2] | |
224 | if cmd == "PD": | |
225 | LASER_STATE = 1 | |
226 | elif cmd == "PU": | |
227 | LASER_STATE = 0 | |
228 | if last_cmd == "PD": | |
229 | OFFSET_X = coord[0] * -1 | |
230 | OFFSET_Y = coord[1] * -1 | |
231 | fo.write("; PD PU detected, set coord offset %.4f x %.4f mm\n" % (OFFSET_X, OFFSET_Y)) | |
232 | elif cmd == "PA" or cmd == "PR": | |
233 | # TODO: convert relative coordinates to absolute here! | |
234 | coord = action[2:].split(",") | |
235 | coord[0] = (float(coord[0]) + OFFSET_X) * SCALE_FACTOR | |
236 | coord[1] = (float(coord[1]) + OFFSET_Y) * SCALE_FACTOR | |
237 | if LASER_STATE: | |
238 | EN = " E%.4f F%.4f" % ( | |
239 | E_FACTOR * math.hypot(coord[0] - last_coord[0], coord[1] - last_coord[1]), | |
19 | 240 | ENGRAVE_SPEED * 0.5 ) # 1/2 engraving speed |
16 | 241 | else: |
242 | EN = " F%.4f" % TRAVEL_SPEED | |
243 | ||
244 | fo.write("G%d X%.4f Y%.4f%s\n" % ( | |
245 | LASER_STATE, coord[0], coord[1], EN) ) | |
246 | last_coord = coord | |
247 | elif cmd == "IN": | |
248 | pass | |
249 | elif cmd == "PT": | |
250 | print "Ignoring pen thickness" | |
251 | else: | |
252 | print "UNKNOWN: %s" % action | |
253 | last_cmd = cmd | |
254 | ||
20 | 255 | fo.write(GCODE_FOOT) |
16 | 256 | fi.close() |
257 | fo.close() | |
258 | ||
259 | if self.pronterwindow: | |
260 | self.log("") | |
261 | self.pronterwindow.load_gcode_async(filename + '.g') | |
262 | ||
263 | ||
19 | 264 | def svg2gcode(self, filename, bed_max_x = 50, bed_max_y = 50, smoothness = 0.2): |
16 | 265 | self.log("Generating paths from SVG...") |
266 | ||
267 | shape_preamble = "G92 E0\n" | |
19 | 268 | shape_postamble = "" |
18 | 269 | |
16 | 270 | """ |
271 | Used to control the smoothness/sharpness of the curves. | |
272 | Smaller the value greater the sharpness. Make sure the | |
273 | value is greater than 0.1 | |
274 | """ | |
275 | if smoothness < 0.1: smoothness = 0.1 | |
276 | ||
277 | svg_shapes = set(['rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'path']) | |
278 | ||
279 | tree = ET.parse(filename) | |
280 | root = tree.getroot() | |
281 | ||
282 | width = root.get('width') | |
283 | height = root.get('height') | |
284 | if width == None or height == None: | |
285 | viewbox = root.get('viewBox') | |
286 | if viewbox: | |
287 | _, _, width, height = viewbox.split() | |
288 | ||
289 | if width == None or height == None: | |
290 | self.log("Unable to get width and height for the svg!") | |
291 | return False | |
292 | ||
293 | width = float(width.replace("px", "")) | |
294 | height = float(height.replace("px", "")) | |
295 | ||
296 | scale_x = bed_max_x / max(width, height) | |
297 | scale_y = bed_max_y / max(width, height) | |
298 | ||
299 | self.log("Scaling factor: %.2f, %.2f" % (scale_x,scale_y)) | |
300 | ||
301 | fo = open(filename + ".g", "w") | |
20 | 302 | fo.write("; Filename: %s\n%s" % (filename, GCODE_HEAD)) |
16 | 303 | |
304 | for elem in root.iter(): | |
305 | try: | |
306 | _, tag_suffix = elem.tag.split('}') | |
307 | except ValueError: | |
308 | continue | |
309 | ||
310 | if tag_suffix in svg_shapes: | |
311 | shape_class = getattr(shapes_pkg, tag_suffix) | |
312 | shape_obj = shape_class(elem) | |
313 | d = shape_obj.d_path() | |
314 | m = shape_obj.transformation_matrix() | |
315 | ||
316 | if d: | |
19 | 317 | fo.write("M400 ; wait for moves finish, then printing shape: %s\n" % (tag_suffix)) |
16 | 318 | E = 0 |
319 | xo = 0 | |
320 | yo = 0 | |
321 | fo.write(shape_preamble) | |
322 | p = point_generator(d, m, smoothness) | |
323 | start = True | |
324 | for x,y,pen in p: | |
325 | y = height - y | |
326 | xs = scale_x * x | |
327 | ys = scale_y * y | |
19 | 328 | if xo == xs and yo == ys: continue |
329 | ||
16 | 330 | if not pen: start = True |
331 | if xs >= 0 and xs <= bed_max_x and ys >= 0 and ys <= bed_max_y: | |
332 | if start: | |
19 | 333 | fo.write("G0 X%0.2f Y%0.2f F%.4f ; Move to start of shape\n" % (xs, ys, TRAVEL_SPEED)) |
16 | 334 | start = False |
335 | xo = xs | |
336 | yo = ys | |
337 | else: | |
338 | e_distance = math.hypot(xs - xo, ys - yo) | |
339 | xo = xs | |
340 | yo = ys | |
19 | 341 | E = E + (e_distance) |
342 | fo.write("G1 X%0.2f Y%0.2f E%.4f F%.4f\n" % (xs, ys, E * E_FACTOR, ENGRAVE_SPEED)) | |
16 | 343 | else: |
344 | self.log("Position outside print dimension: %d, %d" % (xs, ys)) | |
345 | fo.write(shape_postamble) | |
346 | ||
20 | 347 | fo.write(GCODE_FOOT) |
348 | fo.close() | |
16 | 349 | |
350 | if self.pronterwindow: | |
351 | self.log("") | |
352 | self.pronterwindow.load_gcode_async(filename + '.g') | |
353 |