def generate_gcode(): svg_shapes = set(['rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'path']) tree = ET.parse(sys.stdin) root = tree.getroot() width = float(root.get('width')) height = float(root.get('height')) scale_x = bed_max_x / max(width, height) scale_y = bed_max_y / max(width, height) print preamble for elem in root.iter(): try: _, tag_suffix = elem.tag.split('}') except ValueError: continue if tag_suffix in svg_shapes: shape_class = getattr(shapes_pkg, tag_suffix) shape_obj = shape_class(elem) d = shape_obj.d_path() if d: print shape_preamble p = point_generator(d, smoothness) for x,y in p: print "G1 X%0.1f Y%0.1f" % (scale_x*x, scale_y*y) print shape_postamble print postamble
def generate_gcode(): svg_shapes = set( ['rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'path']) tree = ET.parse(sys.stdin) root = tree.getroot() width = root.get('width') height = root.get('height') if width == None or height == None: viewbox = root.get('viewBox') if viewbox: _, _, width, height = viewbox.split() if width == None or height == None: print "Unable to get width and height for the svg" sys.exit(1) width = float(width) height = float(height) scale_x = bed_max_x / max(width, height) scale_y = bed_max_y / max(width, height) print preamble for elem in root.iter(): try: _, tag_suffix = elem.tag.split('}') except ValueError: continue if tag_suffix in svg_shapes: shape_class = getattr(shapes_pkg, tag_suffix) shape_obj = shape_class(elem) d = shape_obj.d_path() m = shape_obj.transformation_matrix() if d: print shape_preamble p = point_generator(d, m, smoothness) feed = 0 for x, y in p: if x > 0 and x < bed_max_x and y > 0 and y < bed_max_y: print "G%d X%0.1f Y%0.1f" % (feed, scale_x * x, scale_y * y) feed = 1 print shape_postamble print postamble
def generate_gcode(): dom = minidom.parse(sys.stdin) print "G28\n\n G1 Z5.0\n\n" for svg_shape in svg_shapes: shapes = dom.getElementsByTagName(svg_shape) for shape in shapes: shape_class = getattr(shapes_pkg, shape.nodeName) shape_obj = shape_class(shape.toxml()) print "G4 P200" p = point_generator(shape_obj.d_path()) for x, y in p: print "G1 X%0.1f Y%0.1f" % (x, y) print "G28" dom.unlink()
def generate_gcode(): svg_shapes = set(['rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'path']) tree = ET.parse(sys.stdin) root = tree.getroot() width = root.get('width') height = root.get('height') if width == None or height == None: viewbox = root.get('viewBox') if viewbox: _, _, width, height = viewbox.split() if width == None or height == None: print "Unable to get width and height for the svg" sys.exit(1) width = float(width) height = float(height) scale_x = bed_max_x / max(width, height) scale_y = bed_max_y / max(width, height) print preamble for elem in root.iter(): try: _, tag_suffix = elem.tag.split('}') except ValueError: continue if tag_suffix in svg_shapes: shape_class = getattr(shapes_pkg, tag_suffix) shape_obj = shape_class(elem) d = shape_obj.d_path() m = shape_obj.transformation_matrix() if d: print shape_preamble p = point_generator(d, m, smoothness) for x,y in p: if x > 0 and x < bed_max_x and y > 0 and y < bed_max_y: print "G1 X%0.1f Y%0.1f" % (scale_x*x, scale_y*y) print shape_postamble print postamble
def generate_points(svg_path, smoothness=0.2): svg_shapes = set( ['rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'path']) tree = ET.parse(svg_path) root = tree.getroot() for elem in root.iter(): try: _, tag_suffix = elem.tag.split('}') except ValueError: continue if tag_suffix in svg_shapes: shape_class = getattr(shapes_pkg, tag_suffix) shape_obj = shape_class(elem) d = shape_obj.d_path() m = shape_obj.transformation_matrix() if d: p = point_generator(d, m, smoothness) yield p
def generate_gcode(filename): ''' The main method that converts svg files into gcode files. Still incomplete. See tests/start.svg''' # Check File Validity if not os.path.isfile(filename): raise ValueError("File \"" + filename + "\" not found.") if not filename.endswith('.svg'): raise ValueError("File \"" + filename + "\" is not an SVG file.") # Define the Output # ASSUMING LINUX / OSX FOLDER NAMING STYLE log = "" log += debug_log("Input File: " + filename) file = filename.split('/')[-1] dirlist = filename.split('/')[:-1] dir_string = "" for folder in dirlist: dir_string += folder + '/' # Make Output File outdir = dir_string + "gcode_output/" if not os.path.exists(outdir): os.makedirs(outdir) outfile = outdir + file.split(".svg")[0] + '.gcode' log += debug_log("Output File: " + outfile) # Make Debug File debugdir = dir_string + "log/" if not os.path.exists(debugdir): os.makedirs(debugdir) debug_file = debugdir + file.split(".svg")[0] + '.log' log += debug_log("Log File: " + debug_file + "\n") # Get the SVG Input File file = open(filename, 'r') tree = ET.parse(file) root = tree.getroot() file.close() # Get the Height and Width from the parent svg tag width = root.get('width') height = root.get('height') if width == None or height == None: viewbox = root.get('viewBox') if viewbox: _, _, width, height = viewbox.split() if width == None or height == None: # raise ValueError("Unable to get width or height for the svg") print "Unable to get width and height for the svg" sys.exit(1) # Scale the file appropriately # (Will never distort image - always scales evenly) # ASSUMES: Y ASIX IS LONG AXIS # X AXIS IS SHORT AXIS # i.e. laser cutter is in "portrait" scale_x = bed_max_x / float(width) scale_y = bed_max_y / float(height) scale = min(scale_x, scale_y) if scale > 1: scale = 1 log += debug_log("wdth: " + str(width)) log += debug_log("hght: " + str(height)) log += debug_log("scale: " + str(scale)) log += debug_log("x%: " + str(scale_x)) log += debug_log("y%: " + str(scale_y)) # CREATE OUTPUT VARIABLE gcode = "" # Write Initial G-Codes gcode += preamble + "\n" # Iterate through svg elements for elem in root.iter(): log += debug_log("--Found Elem: " + str(elem)) new_shape = True try: tag_suffix = elem.tag.split("}")[-1] except: print "Error reading tag value:", tag_suffix continue # Checks element is valid SVG shape if tag_suffix in SVG: log += debug_log(" --Name: " + str(tag_suffix)) # Get corresponding class object from 'shapes.py' shape_class = getattr(shapes_pkg, tag_suffix) shape_obj = shape_class(elem) log += debug_log("\tClass : " + str(shape_class)) log += debug_log("\tObject: " + str(shape_obj)) log += debug_log("\tAttrs : " + str(elem.items())) log += debug_log("\tTransform: " + str(elem.get('transform'))) ############ HERE'S THE MEAT!!! ############# # Gets the Object path info in one of 2 ways: # 1. Reads the <tag>'s 'd' attribute. # 2. Reads the SVG and generates the path itself. d = shape_obj.d_path() log += debug_log("\td: " + str(d)) # The *Transformation Matrix* # # Specifies something about how curves are approximated # Non-essential - a default is used if the method below # returns None. m = shape_obj.transformation_matrix() log += debug_log("\tm: " + str(m)) if d: log += debug_log("\td is GOOD!") gcode += shape_preamble + "\n" points = point_generator(d, m, smoothness) log += debug_log("\tPoints: " + str(points)) for x, y in points: #log += debug_log("\t pt: "+str((x,y))) x = scale * x y = bed_max_y - scale * y log += debug_log("\t pt: " + str((x, y))) if x >= 0 and x <= bed_max_x and y >= 0 and y <= bed_max_y: if new_shape: gcode += ("G0 X%0.1f Y%0.1f\n" % (x, y)) gcode += "M03\n" new_shape = False else: gcode += ("G0 X%0.1f Y%0.1f\n" % (x, y)) log += debug_log("\t --Point printed") else: log += debug_log("\t --POINT NOT PRINTED (" + str(bed_max_x) + "," + str(bed_max_y) + ")") gcode += shape_postamble + "\n" else: log += debug_log("\tNO PATH INSTRUCTIONS FOUND!!") else: log += debug_log(" --No Name: " + tag_suffix) gcode += postamble + "\n" # Write the Result ofile = open(outfile, 'w+') ofile.write(gcode) ofile.close() # Write Debugging if DEBUGGING: dfile = open(debug_file, 'w+') dfile.write(log) dfile.close()
def generate_gcode(filename): ''' The main method that converts svg files into gcode files. Still incomplete. See tests/start.svg''' # Check File Validity if not os.path.isfile(filename): raise ValueError("File \"" + filename + "\" not found.") if not filename.endswith('.svg'): raise ValueError("File \"" + filename + "\" is not an SVG file.") # Define the Output # ASSUMING LINUX / OSX FOLDER NAMING STYLE log = "" log += debug_log("Input File: " + filename) file = filename.split('/')[-1] dirlist = filename.split('/')[:-1] dir_string = "" # for folder in dirlist: # dir_string += folder + '/' # Make Output File outdir = dir_string + "gcode_output/" if not os.path.exists(outdir): os.makedirs(outdir) outfile = outdir + file.split(".svg")[0] + '.gcode' log += debug_log("Output File: " + outfile) # Make Debug File debugdir = dir_string + "log/" if not os.path.exists(debugdir): os.makedirs(debugdir) debug_file = debugdir + file.split(".svg")[0] + '.log' log += debug_log("Log File: " + debug_file + "\n") # Get the SVG Input File file = open(filename, 'r') tree = ET.parse(file) root = tree.getroot() file.close() # Get the Height and Width from the parent svg tag width = root.get('width') height = root.get('height') if width == None or height == None: viewbox = root.get('viewBox') if viewbox: _, _, width, height = viewbox.split() if width == None or height == None: # raise ValueError("Unable to get width or height for the svg") print("Unable to get width and height for the svg") sys.exit(1) if "mm" in width: width = width[:-2] if "mm" in height: height = height[:-2] # Scale the file appropriately # (Will never distort image - always scales evenly) # ASSUMES: Y ASIX IS LONG AXIS # X AXIS IS SHORT AXIS # i.e. laser cutter is in "portrait" scale_x = bed_max_x / float(width) scale_y = bed_max_y / float(height) scale = min(scale_x, scale_y) if scale > 1: scale = 1 log += debug_log("wdth: " + str(width)) log += debug_log("hght: " + str(height)) log += debug_log("scale: " + str(scale)) log += debug_log("x%: " + str(scale_x)) log += debug_log("y%: " + str(scale_y)) # CREATE OUTPUT VARIABLE gcode = "" # Write Initial G-Codes gcode += preamble + "\n" # Iterate through svg elements prev_tool_num = -1 for elem in root.iter(): log += debug_log("--Found Elem: " + str(elem)) new_shape = True try: tag_suffix = elem.tag.split("}")[-1] except: print("Error reading tag value:", tag_suffix) continue # Checks element is valid SVG shape if tag_suffix in svg_keywords: #### change tool fill_color = elem.get("fill") stroke_color = elem.get("stroke") stroke_width = 0 style = elem.get("style") info_dict = {} if style: for info in style.split(';'): splited_data = info.split(":") if splited_data[0] == "fill": fill_color = splited_data[1] elif splited_data[0] == "stroke": stroke_color = splited_data[1] elif splited_data[0] == "stroke-width": stroke_width = splited_data[1] info_dict["stroke-width"] = splited_data[1] if fill_color: if fill_color[0] == '#': fill_color = fill_color[1:] log += "color in HEX" + str(fill_color) fill_RGB = tuple( int(fill_color[i:i + 2], 16) for i in (0, 2, 4)) log += "color in RGB" + str(fill_RGB) closest_colors = sorted( avilable_colors_RGB, key=lambda color: distance(color, fill_RGB)) info_dict["fill"] = color_dict[closest_colors[0]] else: if fill_color in color_dict: info_dict["fill"] = color_dict[fill_color] elif fill_color == "none": pass else: info_dict["fill"] = 4 if stroke_color: if stroke_color[0] == '#': stroke_color = stroke_color[1:] stroke_RGB = tuple( int(stroke_color[i:i + 2], 16) for i in (0, 2, 4)) closest_colors = sorted( avilable_colors_RGB, key=lambda color: distance(color, stroke_RGB)) info_dict["stroke"] = color_dict[closest_colors[0]] else: if stroke_color in color_dict: info_dict["stroke"] = color_dict[stroke_color] else: info_dict["stroke"] = 4 tool_num = 4 if "fill" in info_dict: tool_num = info_dict["fill"] if "stroke" in info_dict: tool_num = info_dict["stroke"] if prev_tool_num != tool_num: gcode += shape_postamble + "G4 S0.5\n" for i in range(8): gcode += "M280 P0 S" + str(tool_num) + "\n" gcode += "G4 S0.01\n" prev_tool_num = tool_num ##end of change tool log += debug_log(" --Name: " + str(tag_suffix)) # Get corresponding class object from 'shapes.py' shape_class = getattr(shapes_pkg, tag_suffix) shape_obj = shape_class(elem) log += debug_log("\tClass : " + str(shape_class)) log += debug_log("\tObject: " + str(shape_obj)) log += debug_log("\tAttrs : " + str(elem.items())) log += debug_log("\tTransform: " + str(elem.get('transform'))) ############ HERE'S THE MEAT!!! ############# # Gets the Object path info in one of 2 ways: # 1. Reads the <tag>'s 'd' attribute. # 2. Reads the SVG and generates the path itself. d = shape_obj.d_path() log += debug_log("\td: " + str(d)) # The *Transformation Matrix* # # Specifies something about how curves are approximated # Non-essential - a default is used if the method below # returns None. m = shape_obj.transformation_matrix() log += debug_log("\tm: " + str(m)) if d: log += debug_log("\td is GOOD!") points = point_generator(d, m, smoothness) log += debug_log("\tPoints: " + str(points)) prev_x = 0 prev_y = 0 prev_flag = False for x, y in points: log += debug_log("\t pt: " + str((x, y))) x = scale * x y = bed_max_y - scale * y log += debug_log("\t pt: " + str((x, y))) if x >= 0 and x <= bed_max_x and y >= 0 and y <= bed_max_y: if new_shape: gcode += ("G0 X%0.1f Y%0.1f\n" % (x, y)) gcode += shape_preamble prev_x = x prev_y = y new_shape = False else: if round(prev_x, 2) == round(x, 2) and round( prev_y, 2) == round(y, 2): prev_x = x prev_y = y gcode += shape_postamble prev_flag = True else: gcode += ("G0 X%0.1f Y%0.1f\n" % (x, y)) prev_x = x prev_y = y if prev_flag == True: gcode += shape_preamble prev_flag = False log += debug_log("\t --Point printed") else: log += debug_log("\t --POINT NOT PRINTED (" + str(bed_max_x) + "," + str(bed_max_y) + ")") pass gcode += shape_postamble + "\n" else: log += debug_log("\tNO PATH INSTRUCTIONS FOUND!!") else: log += debug_log(" --No Name: " + tag_suffix) gcode += postamble + "\n" # Write the Result ofile = open(outfile, 'w+') ofile.write(gcode) ofile.close()
def generate_gcode(filename, outputfile_name, use_printheight_placeholder=True): svg_shapes = set(['rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'path']) tree = ET.parse(filename) root = tree.getroot() width = root.get('width') height = root.get('height') traveled_way = 0 x_old = None y_old = None if width == None or height == None: viewbox = root.get('viewBox') if viewbox: _, _, width, height = viewbox.split() if width == None or height == None: print "Unable to get width and height for the svg" sys.exit(1) width = checkAndReturnMeasurementInMillimeter(width) height = checkAndReturnMeasurementInMillimeter(height) output_file = open(outputfile_name, "w") write_gcodeline(output_file, preamble) shape_counter = 0 z_position_plotting = z_position_plotting_start if use_printheight_placeholder: gcode_line_zposition_plotting = "G1 Z%s" % (z_position_placeholder) else: gcode_line_zposition_plotting = "G1 Z%0.1f" % (z_position_plotting) for elem in root.iter(): try: _, tag_suffix = elem.tag.split('}') except ValueError: continue if tag_suffix in svg_shapes: shape_class = getattr(shapes_pkg, tag_suffix) shape_obj = shape_class(elem) d = shape_obj.d_path() m = shape_obj.transformation_matrix() if d: write_gcodeline(output_file, shape_preamble) p = point_generator(d, m, smoothness) move_to_startposition_shape_done = False for x,y in p: distance_from_previous_point = 0 gcode_line = "G1 X%0.1f Y%0.1f" % (x, y) if x_old and y_old and move_to_startposition_shape_done: distance_from_previous_point = calculateDistance(x_old, y_old, x, y) if distance_from_previous_point > 3: write_gcodeline(output_file, "G1 Z%s" % (z_movement_placeholder)) write_gcodeline(output_file, gcode_line, traveled_way, elem.attrib["id"], distance_from_previous_point) write_gcodeline(output_file, gcode_line_zposition_plotting) else: traveled_way = traveled_way + distance_from_previous_point write_gcodeline(output_file, gcode_line, traveled_way, elem.attrib["id"], distance_from_previous_point) x_old = x y_old = y if not move_to_startposition_shape_done: write_gcodeline(output_file, gcode_line_zposition_plotting) move_to_startposition_shape_done = True if use_printheight_placeholder: write_gcodeline(output_file, "G1 Z%s" % (z_movement_placeholder)) write_gcodeline(output_file, shape_postamble) if not use_printheight_placeholder: shape_counter = shape_counter + 1 if shape_counter % z_correction_every_nth_shape == 0: z_position_plotting = z_position_plotting - retract_pencil if z_position_plotting < 0.4: pause_printer_for_pencil_retraction() gcode_line_zposition_plotting = "G1 Z%0.1f" % (z_position_plotting_start) write_gcodeline(output_file, gcode_line_zposition_plotting) write_gcodeline(output_file, "M25") z_position_plotting = z_position_plotting_start write_gcodeline(output_file, postamble)
def generate_gcode(filename): ''' The main method that converts svg files into gcode files. Still incomplete. See tests/start.svg''' # Check File Validity if not os.path.isfile(filename): raise ValueError("File " + filename + " not found.") if not filename.endswith('.svg'): raise ValueError("File " + filename + " is not an SVG file.") # Define the Output # ASSUMING LINUX / OSX FOLDER NAMING STYLE log = "" log += debug_log("Input File: " + filename) log += debug_log("Debug resides in: " + str(debug_log.__module__)) #Define the file/folder paths to work with file = os.path.split(filename)[-1] dirlist = os.path.split(filename)[0] dir_string = dirlist # Make Output File outdir = os.path.abspath(os.path.join(dirlist, "..", "TuotetutNCTiedostot")) #outdir = os.path.join(dirlist,"gcode_output") if not os.path.exists(outdir): os.makedirs(outdir) outfile = os.path.join(outdir, file.split(".svg")[0] + '.nc') log += debug_log("Output File: " + outfile) # Make Debug File #debugdir = os.path.join(dir_string, "log") debugdir = os.path.join(dirlist, "..", "log") if not os.path.exists(debugdir): os.makedirs(debugdir) debug_file = os.path.join(debugdir, file.split(".svg")[0] + '.log') log += debug_log("Log File: " + debug_file + "\n") # Get the SVG Input File file = open(filename, 'r') tree = ET.parse(file) root = tree.getroot() print(dir(root)) #print("Tree.getroot(): "+str(tree.getroot()+"\n")) file.close() # Get the Height and Width from the parent svg tag width = root.get('width') height = root.get('height') if width == None or height == None: viewbox = root.get('viewBox') if viewbox: _, _, width, height = viewbox.split() if width == None or height == None: # raise ValueError("Unable to get width or height for the svg") print("Unable to get width and height for the svg") sys.exit(1) #print(type(width)) # Scale the file appropriately # (Will never distort image - always scales evenly) # ASSUMES: Y ASIX IS LONG AXIS # X AXIS IS SHORT AXIS # i.e. laser cutter is in "portrait" #Remove units so float conversion does not fail scale_x = bed_max_x / float(width.replace("mm", "")) scale_y = bed_max_y / float(height.replace("mm", "")) scale = min(scale_x, scale_y) if scale > 1: scale = 0.6 log += debug_log("wdth: " + str(width)) log += debug_log("hght: " + str(height)) log += debug_log("scale: " + str(scale)) log += debug_log("x%: " + str(scale_x)) log += debug_log("y%: " + str(scale_y)) # CREATE OUTPUT VARIABLE gcode = "" # Write Initial G-Codes gcode += preamble + "\n" # Iterate through svg elements commandStock = [] for elem in root.iter(): #gcode += "NIRNAR\n" log += debug_log("--Found Elem: " + str(elem)) #new_shape = True try: tag_suffix = elem.tag.split("}")[-1] except: print("Error reading tag value:", tag_suffix) continue # Checks element is valid SVG shape if tag_suffix in SVG: log += debug_log(" --Name: " + str(tag_suffix)) # Get corresponding class object from 'shapes.py' shape_class = getattr(shapes_pkg, tag_suffix) shape_obj = shape_class(elem) log += debug_log("\tClass : " + str(shape_class)) log += debug_log("\tObject: " + str(shape_obj)) log += debug_log("\tAttrs : " + str(list(elem.items()))) log += debug_log("\tTransform: " + str(elem.get('transform'))) ############ HERE'S THE MEAT!!! ############# # Gets the Object path info in one of 2 ways: # 1. Reads the <tag>'s 'd' attribute. # 2. Reads the SVG and generates the path itself. d = shape_obj.d_path() log += debug_log("\td: " + str(d)) # The *Transformation Matrix* # # Specifies something about how curves are approximated # Non-essential - a default is used if the method below # returns None. m = shape_obj.transformation_matrix() log += debug_log("\tm: " + str(m)) if d: #print("type(d): "+str(type(d))) qir = str(d) highest_x = 0 lowest_x = 0 highest_y = 0 lowest_y = 0 #Split the chain of commands #where z appears, leaving the last #empty list out qirSplit = qir.split("z")[:-1] #print("root.iter(): "+str(root.iter())) log += debug_log("\td is GOOD!") #gcode += shape_preamble + "\n" chkPoints = point_generator(d, m, smoothness) #Run a preliminary check of minimum and maximum #coordinates, then adjust accordingly to make #the lower left corner of the drawing #process be near the zero coordinates of #the drawing machine for x, y, cmdType in chkPoints: #log += debug_log("\t pt: "+str((x,y))) #x = bed_max_x/2.0 - scale*x #y = bed_max_y/2.0 - scale*y x = scale * x y = scale * y #y = bed_max_y - scale*y if x > highest_x: highest_x = x if x < lowest_x: lowest_x = x if y > highest_y: highest_y = y if y < lowest_y: lowest_y = y #Store all bezier curve commands #for counting and ending the #drawing correctly commandStock.append(cmdType) #Count the number of Z-commands zCounter = commandStock.count("Z") xAdj = 0 yAdj = 0 if lowest_x < 0: xAdj = -lowest_x + 50 if lowest_y < 0: yAdj = -lowest_y + 30 points = point_generator(d, m, smoothness) log += debug_log("\tPoints: " + str(points)) #Generate the G-code new_shape = True #move_between_shapes = False #Count the finished shapes finishCounter = 0 skipCounter = 0 commandCount = 0 for x, y, cmdType in points: #log += debug_log("\t pt: "+str((x,y))) x = scale * x + xAdj y = scale * y + yAdj log += debug_log("\t pt: " + str((x, y))) #Check that the drawing board limits are not exceeded if x >= 0 and x <= bed_max_x and y >= 0 and y <= bed_max_y: #If the Z command is reached, increment the counter #and close the shape with the point from which it was #started if cmdType == 'Z' and finishCounter < zCounter: gcode += startPointStorage new_shape = True skipCounter = 3 finishCounter += 1 #If the number of commands matches the amount of commands #given per shape, if the end is reached, lift the tool if new_shape: skipCounter -= 1 if skipCounter <= 0: gcode += "M51\n" startPointStorage = ("G00 X%0.1f Y%0.1f\n" % (x, y)) gcode += startPointStorage gcode += "M52\n" new_shape = False else: gcode += ("G00 X%0.1f Y%0.1f\n" % (x, y)) commandCount += 1 log += debug_log("\t --Point printed") else: log += debug_log("\t --POINT NOT PRINTED (" + str(bed_max_x) + "," + str(bed_max_y) + ")") gcode += shape_postamble + "\n" else: log += debug_log("\tNO PATH INSTRUCTIONS FOUND!!") else: log += debug_log(" --No Name: " + tag_suffix) gcode += postamble + "\n" #nuuh() #print("highest_x: "+str(highest_x), "lowest_x: "+str(lowest_y), # "highest_y: "+str(highest_y), "lowest_y: "+str(lowest_y)) # Write the Result ofile = open(outfile, 'w+') ofile.write(gcode) ofile.close() # Write Debugging if DEBUGGING: dfile = open(debug_file, 'w+') dfile.write(log) dfile.close()
def generate_gcode(): svg_shapes = set( ['rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'path']) if os.path.exists(sys.argv[1]): tree = ET.parse(sys.argv[1]) else: print "Error: Could not open file '%s'" % sys.argv[1] if os.path.exists(sys.argv[2]): os.unlink(sys.argv[2]) root = tree.getroot() width = root.get('width') height = root.get('height') if width == None or height == None: print "Error: Unable to get width and height for the svg" sys.exit(1) else: width = float(width.rstrip('mm')) height = float(height.rstrip('mm')) viewbox = root.get('viewBox') if viewbox: _, _, ww, hh = viewbox.split() print "ViewBox w=%s h=%s" % (ww, hh) ww = float(ww) hh = float(hh) else: print "Error: Unable to get viewbox for the svg" sys.exit(1) # Inkscape scale: http://wiki.inkscape.org/wiki/index.php/Units_In_Inkscape dpi = 96.0 scale_x = width / ww scale_y = height / hh if scale_x != scale_y: print "Warning: width and height scale factors are not equal!" print "Info: Document scale factor is %0.1f %0.1f" % (scale_x, scale_y) if width > bed_max_x or height > bed_max_y: print "Info: Document area larger than print bed, extra scaling needed!" scale_x = (bed_max_x / max(width, height)) * scale_x scale_y = (bed_max_y / max(width, height)) * scale_y print "Info: New scale factor is %0.1f %0.1f" % (scale_x, scale_y) write_gcode(preamble) first = True maxX = None minX = None maxY = None minY = None for elem in root.iter(): try: _, tag_suffix = elem.tag.split('}') except ValueError: continue if tag_suffix in svg_shapes: shape_class = getattr(shapes_pkg, tag_suffix) shape_obj = shape_class(elem) d = shape_obj.d_path() m = shape_obj.transformation_matrix() if d: write_gcode(shape_preamble) p = point_generator(d, m, smoothness) for x, y in p: xs = scale_x * x ys = scale_y * y if flipX: xs = -xs + bed_max_x if flipY: ys = -ys + bed_max_y xs += offset_x ys += offset_y if not maxX: maxX = xs elif xs > maxX: maxX = xs if not minX: minX = xs elif xs < minX: minX = xs if not maxY: maxY = ys elif ys > maxY: maxY = ys if not minY: minY = ys elif ys < minY: minY = ys if xs > bed_min_x and xs < bed_max_x and ys > bed_min_y and ys < bed_max_y: if first: write_gcode("G1 X%0.1f Y%0.1f" % (xs, ys)) write_gcode(after_move) first = False write_gcode("G1 X%0.1f Y%0.1f" % (xs, ys)) else: print "Error: out of bounds! (X%0.1f Y%0.1f)" % (xs, ys) first = True write_gcode(before_move) #print shape_postamble write_gcode(postamble) print "Min X = %0.1fmm" % minX print "Max X = %0.1fmm" % maxX print "Min Y = %0.1fmm" % minY print "Max Y = %0.1fmm" % maxY print "DeltaX = %0.1fmm" % (maxX - minX) print "DeltaY = %0.1fmm" % (maxY - minY)
def generate_gcode(self, svg): now = datetime.now() # current date and time now_time = now.strftime("%m-%d-%Y-%H:%M:%S") gcode_file = os.path.join(os.path.expanduser('~'), self.options.gcode_file + now_time + ".gcode") try: os.remove(gcode_file) except OSError: pass pen_up = self.options.pen_up pen_down = self.options.pen_down feed_rate_up = self.options.feed_rate_up feed_rate_down = self.options.feed_rate_down pen_rate = self.options.pen_rate does_dip = self.options.does_dip dip_when = self.options.dip_when dip_count = dip_when width = svg.get('width') height = svg.get('height') inkex.debug(width) width = self.unittouu(width) height = self.unittouu(height) # if width > bed_width or height > bed_height: # raise ValueError(('The document size (%d x %d) is greater than the bedsize' % # (round(width, 1), round(height, 1)))) with open(gcode_file, 'w') as gcode: gcode.write(self.options.preamble + '\n') gcode.write("G00 Z%0.1f(Pen up)\n" % (pen_up)) svg_shapes = set(['rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'path']) for elem in svg.iter(): inkex.debug(elem) inkex.debug(elem.tag) try: _, tag_suffix = elem.tag.split('}') except ValueError: continue if tag_suffix in svg_shapes: shape_class = getattr(shapes_pkg, tag_suffix) shape_obj = shape_class(elem) d = shape_obj.d_path() m = shape_obj.transformation_matrix() if d: p = point_generator(d, m, 0.05) preamble = True # hack!! first = True if does_dip and dip_count == dip_when: gcode.write('G00 X100.0 Y0.0 F3200.0(Go to paint)\n') gcode.write('G01 Z0.0 F3200.0(Pen down in paint)\n') gcode.write('G00 X105.0 Y5.0 F1200.0(Move in paint)\n') gcode.write("G00 Z%0.1f F3200.0(Pen up in paint)\n" % (pen_up)) dip_count = 0 else: dip_count = dip_count + 1 for x,y in p: if preamble: gcode.write("G00 X%0.1f Y%0.1f F%0.1f(New shape)\n" % (x, y, feed_rate_up)) gcode.write("G01 Z%0.1f F%0.1f(Pen down)\n" % (pen_down, pen_rate)) preamble = False else: if first: gcode.write("G01 X%0.1f Y%0.1f Z%0.1f F%0.1f\n" % (x, y, pen_down, feed_rate_down)) first = False else: gcode.write("G01 X%0.1f Y%0.1f Z%0.1f\n" % (x, y, pen_down)) gcode.write("G01 Z%0.1f F%0.1f(Pen up)\n" % (pen_up, pen_rate)) # gcode.write(self.options.shape_postamble + '\n') gcode.write('G00 X0.0 Y0.0 F3200.0(Go home)\n') gcode.write('G01 Z0.0 F3200.0(Pen down)\n')
def generate_gcode(): svg_shapes = set(['rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'path']) if os.path.exists(sys.argv[1]): tree = ET.parse(sys.argv[1]) else: print "Error: Could not open file '%s'" % sys.argv[1] if os.path.exists(sys.argv[2]): os.unlink(sys.argv[2]) root = tree.getroot() width = root.get('width') height = root.get('height') if width == None or height == None: print "Error: Unable to get width and height for the svg" sys.exit(1) else: width = float(width.rstrip('mm')) height = float(height.rstrip('mm')) viewbox = root.get('viewBox') if viewbox: _, _, ww, hh = viewbox.split() print "ViewBox w=%s h=%s" % (ww, hh) ww = float(ww) hh = float(hh) else: print "Error: Unable to get viewbox for the svg" sys.exit(1) # Inkscape scale: http://wiki.inkscape.org/wiki/index.php/Units_In_Inkscape dpi = 96.0 scale_x = width / ww scale_y = height / hh if scale_x != scale_y: print "Warning: width and height scale factors are not equal!" print "Info: Document scale factor is %0.1f %0.1f" % (scale_x, scale_y) if width > bed_max_x or height > bed_max_y: print "Info: Document area larger than print bed, extra scaling needed!" scale_x = (bed_max_x / max(width, height)) * scale_x scale_y = (bed_max_y / max(width, height)) * scale_y print "Info: New scale factor is %0.1f %0.1f" % (scale_x, scale_y) write_gcode(preamble) first = True maxX = None minX = None maxY = None minY = None for elem in root.iter(): try: _, tag_suffix = elem.tag.split('}') except ValueError: continue if tag_suffix in svg_shapes: shape_class = getattr(shapes_pkg, tag_suffix) shape_obj = shape_class(elem) d = shape_obj.d_path() m = shape_obj.transformation_matrix() if d: write_gcode(shape_preamble) p = point_generator(d, m, smoothness) for x,y in p: xs = scale_x*x ys = scale_y*y if flipX: xs = -xs + bed_max_x if flipY: ys = -ys + bed_max_y xs += offset_x ys += offset_y if not maxX: maxX = xs elif xs > maxX: maxX = xs if not minX: minX = xs elif xs < minX: minX = xs if not maxY: maxY = ys elif ys > maxY: maxY = ys if not minY: minY = ys elif ys < minY: minY = ys if xs > bed_min_x and xs < bed_max_x and ys > bed_min_y and ys < bed_max_y: if first: write_gcode("G1 X%0.1f Y%0.1f" % (xs, ys)) write_gcode(after_move) first = False write_gcode("G1 X%0.1f Y%0.1f" % (xs, ys)) else: print "Error: out of bounds! (X%0.1f Y%0.1f)" % (xs, ys) first = True write_gcode(before_move) #print shape_postamble write_gcode(postamble) print "Min X = %0.1fmm" % minX print "Max X = %0.1fmm" % maxX print "Min Y = %0.1fmm" % minY print "Max Y = %0.1fmm" % maxY print "DeltaX = %0.1fmm" % (maxX - minX) print "DeltaY = %0.1fmm" % (maxY - minY)
def get_shapes(path, auto_scale=True): t1 = dt.now() svg_shapes = set( ['rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'path']) shapes = [] tree = ET.parse(path) root = tree.getroot() pointRatio = 0.352778 width = root.get('width') height = root.get('height') if width is None or height is None: viewbox = root.get('viewBox') if viewbox: _, _, width, height = viewbox.split() if width is None or height is None: print("Unable to get width and height for the svg") sys.exit(1) # width = float(re.sub("[^0-9]", "", width)) # height = float(re.sub("[^0-9]", "", height)) width = float(re.findall(r"[-+]?\d*\.\d+|\d+", width)[0]) height = float(re.findall(r"[-+]?\d*\.\d+|\d+", height)[0]) print("width / height ", width, height) if units == "points": width *= pointRatio height *= pointRatio if auto_scale: print("\nauto scaling") scale_x = bed_max_x / max(width, height) scale_y = bed_max_y / max(width, height) scale_x = min(scale_x, scale_y) scale_y = scale_x print("width / height ", width, height) print("scale factor ", scale_x, "\n") for elem in root.iter(): try: _, tag_suffix = elem.tag.split('}') except ValueError: continue if tag_suffix in svg_shapes: shape_class = getattr(shapes_pkg, tag_suffix) shape_obj = shape_class(elem) d = shape_obj.d_path() m = shape_obj.transformation_matrix( ) # todo work out what d and m are coords = [] if d: # begin shape processing p = point_generator(d, m, smoothness) # tuples of x y coords first = True for x, y in p: # todo sort out this nightmare if units == "points": x *= pointRatio y *= pointRatio y = -y + height if auto_scale: x *= scale_x y *= scale_y if first: #coords.append((x, -y + height)) coords.append((x, y)) else: if not (x, y) == coords[-1]: #coords.append((x, -y + height)) coords.append((x, y)) if first: first = False shapes.append(coords) timer(t1, "parsing gcode ") return shapes