Sun, 08 Nov 2015 04:18:58 +0100
infill improved movement
4 | 1 | #!/usr/bin/env python |
5 | 2 | # -*- coding: utf-8 -*- |
3 | ||
10 | 4 | import svg, sys, math |
11 | 5 | from pprint import pprint |
4 | 6 | from gcode import Gcode |
7 | from optparse import OptionParser | |
6
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
8 | from tinycss import CSS21Parser |
4 | 9 | |
11 | 10 | |
8 | 11 | from shapely.geometry import box, MultiLineString, Polygon |
5 | 12 | from shapely.affinity import rotate |
13 | from shapely import speedups | |
14 | from math import sqrt | |
11 | 15 | from functools import cmp_to_key |
5 | 16 | |
17 | # enable Shapely speedups, if possible | |
18 | if speedups.available: | |
11 | 19 | print "shapely speedups available and enabled!" |
5 | 20 | speedups.enable() |
21 | ||
22 | def hatchbox(rect, angle, spacing): | |
23 | """ | |
24 | returns a Shapely geometry (MULTILINESTRING, or more rarely, | |
25 | GEOMETRYCOLLECTION) for a simple hatched rectangle. | |
26 | ||
27 | args: | |
28 | rect - a Shapely geometry for the outer boundary of the hatch | |
29 | Likely most useful if it really is a rectangle | |
30 | ||
31 | angle - angle of hatch lines, conventional anticlockwise -ve | |
32 | ||
33 | spacing - spacing between hatch lines | |
34 | ||
35 | GEOMETRYCOLLECTION case occurs when a hatch line intersects with | |
36 | the corner of the clipping rectangle, which produces a point | |
37 | along with the usual lines. | |
38 | """ | |
39 | ||
40 | (llx, lly, urx, ury) = rect.bounds | |
41 | centre_x = (urx + llx) / 2 | |
42 | centre_y = (ury + lly) / 2 | |
43 | diagonal_length = sqrt((urx - llx) ** 2 + (ury - lly) ** 2) | |
44 | number_of_lines = 2 + int(diagonal_length / spacing) | |
45 | hatch_length = spacing * (number_of_lines - 1) | |
46 | ||
47 | # build a square (of side hatch_length) horizontal lines | |
48 | # centred on centroid of the bounding box, 'spacing' units apart | |
49 | coords = [] | |
50 | for i in range(number_of_lines): | |
51 | # alternate lines l2r and r2l to keep HP-7470A plotter happy ☺ | |
52 | if i % 2: | |
8 | 53 | coords.extend([(( |
54 | centre_x - hatch_length / 2, \ | |
55 | centre_y - hatch_length / 2 + i * spacing), ( | |
56 | centre_x + hatch_length / 2, \ | |
57 | centre_y - hatch_length / 2 + i * spacing))]) | |
5 | 58 | else: |
8 | 59 | coords.extend([(( \ |
60 | centre_x + hatch_length / 2, \ | |
61 | centre_y - hatch_length / 2 + i * spacing), ( | |
62 | centre_x - hatch_length / 2, \ | |
63 | centre_y - hatch_length / 2 + i * spacing))]) | |
5 | 64 | # turn array into Shapely object |
65 | lines = MultiLineString(coords) | |
66 | # Rotate by angle around box centre | |
67 | lines = rotate(lines, angle, origin='centroid', use_radians=False) | |
68 | # return clipped array | |
69 | return rect.intersection(lines) | |
70 | ||
6
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
71 | def parse_style(stylestr): |
10 | 72 | """ |
73 | Parse the given string containing CSS2.1 syntax | |
74 | Returns a dict with the keys/values | |
75 | """ | |
6
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
76 | if stylestr.strip() == '': |
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
77 | return None |
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
78 | parser = CSS21Parser() |
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
79 | style = parser.parse_style_attr(stylestr) |
10 | 80 | data = {} |
6
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
81 | for obj in style[0]: |
10 | 82 | data[obj.name] = obj.value[0].value |
83 | return data | |
6
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
84 | |
9 | 85 | class Image(object): |
10 | 86 | """ |
87 | SVG Image handler class | |
88 | """ | |
9 | 89 | def __init__(self, filename, options, gcoder): |
90 | self.gcoder = gcoder | |
91 | self.options = options | |
92 | self.svg = svg.parse(filename) | |
93 | self.bb1, self.bb2 = self.svg.bbox() | |
94 | self.width, self.height = self.bb2.coord() | |
95 | self.infill = None | |
8 | 96 | |
9 | 97 | self._check_dimensions() |
98 | self._generate_infill() | |
99 | ||
100 | def _check_dimensions(self): | |
10 | 101 | """ |
102 | Output image dimensions/scaling to console and gcode | |
103 | """ | |
9 | 104 | msg = "Original dimension: %.2f x %.2f" % (self.width, self.height) |
105 | print msg | |
106 | self.gcoder.comment(msg) | |
10 | 107 | self.gcoder.comment("Scale: %.2f" % (self.options.scale)) |
9 | 108 | width = self.width * self.gcoder.mm_pixel * self.options.scale |
109 | height = self.height * self.gcoder.mm_pixel * self.options.scale | |
110 | msg = "Print dimension: %.2fmm x %.2fmm" % (width, height) | |
111 | print msg | |
112 | self.gcoder.comment(msg) | |
8 | 113 | |
9 | 114 | def _generate_infill(self): |
10 | 115 | """ |
116 | Generates infill pattern image for later use | |
117 | """ | |
9 | 118 | b1x, b1y = self.bb1.coord() |
119 | b2x, b2y = self.bb2.coord() | |
120 | page = box(b1x, b1y, b2x, b2y) | |
121 | # TODO: Infill spacing needs to be calculated with proper scaling and gcode MM dimensions | |
122 | # TODO: Make infill angle 0, 45 or 90 degrees configurable to options parser (0° = X, 90° = Y, 45° = X and Y but half the speed/accel needed!) | |
123 | self.infill = hatchbox(page, 0, 2) | |
4 | 124 | |
9 | 125 | def normalize(self, coord): |
10 | 126 | """ |
127 | Normalize X / Y Axis of coordinates | |
128 | At the moment only Y gets flipped to match Reprap coordinate system (0,0 is bottom left instead top left on SVG) | |
129 | """ | |
9 | 130 | c_x = coord[0] |
131 | c_y = coord[1] | |
132 | # flip y | |
133 | c_y = (self.height - c_y) | |
134 | return (c_x, c_y) | |
4 | 135 | |
9 | 136 | def get_drawings(self): |
137 | """ | |
138 | Returns a list of all svg drawings with segments attribute | |
139 | """ | |
140 | data = [] | |
141 | for dwg in self.svg.flatten(): | |
142 | if hasattr(dwg, "segments"): | |
143 | data.append(dwg) | |
144 | return data | |
145 | ||
11 | 146 | def cmp_smallest_distance(line1, line2, coords1=None, coords2=None): |
147 | if not coords1: | |
148 | coords1 = list(line1.coords) | |
149 | if not coords2: | |
150 | coords2 = list(line2.coords) | |
151 | ||
152 | dist = [ | |
153 | abs(math.hypot(coords1[0][0] - coords2[0][0], coords1[0][1] - coords2[0][1])), | |
154 | abs(math.hypot(coords1[0][0] - coords2[1][0], coords1[0][1] - coords2[1][1])), | |
155 | abs(math.hypot(coords1[1][0] - coords2[0][0], coords1[1][1] - coords2[0][1])), | |
156 | abs(math.hypot(coords1[1][0] - coords2[1][0], coords1[1][1] - coords2[1][1])) | |
157 | ] | |
158 | ||
159 | # return the smallest distance between the two lines | |
160 | # check both start and endpoints to each other | |
161 | return sorted(dist)[0] | |
162 | ||
163 | def slow_sort_lines_by_distance(multilines): | |
164 | lines = [] | |
165 | coords = [] | |
166 | for line in multilines: | |
167 | lines.append(line) | |
168 | # coords list for brutal speedup! | |
169 | # without this it would be terrible_slow_sort_lines_by_distance() | |
170 | coords.append(list(line.coords)) | |
171 | ||
172 | data = [lines.pop(0)] | |
173 | last = coords.pop(0) | |
174 | ||
175 | def pop_nearest(line, last): | |
176 | idx = -1 | |
177 | dist = 99999999 | |
178 | for test in lines: | |
179 | idx += 1 | |
180 | tmp = cmp_smallest_distance(line, test, last, coords[idx]) | |
181 | if tmp < dist: | |
182 | dist = tmp | |
183 | dist_idx = idx | |
184 | # nearest item found | |
185 | return (lines.pop(dist_idx), coords.pop(dist_idx)) | |
186 | ||
187 | print "Optimizing infill movement, please wait..." | |
188 | while len(lines) > 0: | |
189 | tmp = len(lines) | |
190 | if not (tmp % 10): | |
191 | sys.stdout.write("\r%d " % tmp) | |
192 | sys.stdout.flush() | |
193 | tmp = pop_nearest(data[-1], last) | |
194 | data.append(tmp[0]) | |
195 | last = tmp[1] | |
196 | print "\rdone" | |
197 | return data | |
198 | ||
9 | 199 | def svg2gcode(options, gcoder): |
200 | image = Image(options.filename, options, gcoder) | |
8 | 201 | |
9 | 202 | for dwg in image.get_drawings(): |
203 | for l in dwg.segments(1): | |
204 | # THE OUTLINE | |
205 | coord = image.normalize(l[0].coord()) | |
206 | gcoder.move(coord[0], coord[1]) | |
207 | for pt in l[1:]: | |
208 | coord = image.normalize(pt.coord()) | |
209 | gcoder.engrave(coord[0], coord[1]) | |
8 | 210 | |
9 | 211 | if options.outline: |
212 | continue | |
213 | ||
214 | if isinstance(dwg, svg.Polygon) or isinstance(dwg, svg.Path): | |
215 | #check if we should infill? | |
216 | style = parse_style(dwg.style) | |
217 | if not style: | |
218 | continue | |
219 | if not 'fill' in style.keys(): | |
220 | continue | |
221 | if style['fill'] == 'none': | |
222 | continue | |
6
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
223 | |
9 | 224 | # try to generate the infill poly complex |
225 | poly = None | |
226 | for l in dwg.segments(1): | |
227 | segments = [] | |
228 | for pnt in l: | |
229 | segments.append(pnt.coord()) | |
230 | shape = Polygon(segments) | |
231 | if shape.is_valid: | |
232 | if not poly: | |
233 | poly = shape | |
234 | else: | |
235 | if shape.within(poly): | |
236 | poly = poly.difference(shape) | |
8 | 237 | else: |
9 | 238 | poly = poly.union(shape) |
8 | 239 | |
9 | 240 | lines = poly.intersection(image.infill) |
241 | if lines: | |
11 | 242 | #pprint (dir(lines)) |
9 | 243 | # THE INFILL |
10 | 244 | prev_end = None |
11 | 245 | # sort lines by nearest |
246 | lines_ordered = slow_sort_lines_by_distance(lines) | |
247 | ||
248 | ||
249 | #lines_distances = [] | |
250 | #prev_line = lines[0] | |
251 | #for line in lines: | |
252 | # lines_distances.append(cmp_smallest_distance(line, prev_line)) | |
253 | # prev_line = line | |
254 | ##lines_ordered = sorted(lines, key=cmp_to_key(cmp_smallest_distance)) | |
255 | ## decorate, sort, undecorate: | |
256 | #lines_distances, lines = zip(*sorted(zip(lines_distances, lines))) | |
257 | ||
258 | ||
259 | for line in lines_ordered: | |
10 | 260 | coords = [ |
261 | image.normalize((line.coords[0][0], line.coords[0][1])), | |
262 | image.normalize((line.coords[1][0], line.coords[1][1])) | |
263 | ] | |
264 | if prev_end: | |
265 | # calculate distances to previous end, swap if current end is nearest | |
266 | dist = [ | |
267 | abs(math.hypot(coords[0][0] - prev_end[0], coords[0][1] - prev_end[1])), | |
268 | abs(math.hypot(coords[1][0] - prev_end[0], coords[1][1] - prev_end[1])) | |
269 | ] | |
270 | if dist[0] > dist[1]: | |
271 | coords = list(reversed(coords)) | |
272 | prev_end = coords[1] | |
273 | gcoder.move(coords[0][0], coords[0][1]) | |
274 | gcoder.engrave(coords[1][0], coords[1][1]) | |
6
ff679c15cb0e
infill only on Polygon or Path which have fill style attribute
mbayer
parents:
5
diff
changeset
|
275 | |
9 | 276 | def init_options(): |
8 | 277 | parser = OptionParser() |
278 | parser.add_option("-f", "--file", dest="filename", default=None, | |
279 | help="Load SVG file", metavar="FILE") | |
280 | parser.add_option("-s", "--scale", | |
281 | dest="scale", type="float", default=1.0, | |
282 | help="set scale factor (default 1.0)") | |
283 | parser.add_option("-e", "", | |
284 | dest="engrave_speed", type="float", default=20, | |
285 | help="engrave speed mm/sec (default 20)") | |
286 | parser.add_option("-t", "", | |
287 | dest="travel_speed", type="float", default=130, | |
288 | help="travel speed mm/sec (default 130)") | |
289 | parser.add_option("-o", "--outline", action="store_true", | |
290 | dest="outline", default=False, | |
291 | help="no infill, only outlines") | |
9 | 292 | return parser.parse_args() |
7 | 293 | |
9 | 294 | if __name__ == "__main__": |
295 | (OPTIONS, ARGS) = init_options() | |
296 | if not OPTIONS.filename: | |
8 | 297 | print "no filename given!" |
298 | sys.exit(1) | |
5 | 299 | |
8 | 300 | # initialize gcode worker |
9 | 301 | GCODER = Gcode(scale=OPTIONS.scale, travel_speed=OPTIONS.travel_speed, engrave_speed=OPTIONS.engrave_speed) |
8 | 302 | |
303 | # processing | |
9 | 304 | svg2gcode(OPTIONS, GCODER) |
8 | 305 | |
306 | # write gcode file | |
9 | 307 | GCODER.write(OPTIONS.filename + ".g") |