1 from __future__ import absolute_import
\r
2 from __future__ import division
\r
3 #Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
\r
6 import os, traceback, math, re, zlib, base64, time, sys
\r
7 if sys.version_info[0] < 3:
\r
10 import configparser as ConfigParser
\r
12 #########################################################
\r
13 ## Default settings when none are found.
\r
14 #########################################################
\r
16 #Single place to store the defaults, so we have a consistent set of default settings.
\r
17 profileDefaultSettings = {
\r
18 'nozzle_size': '0.4',
\r
19 'layer_height': '0.2',
\r
20 'wall_thickness': '0.8',
\r
21 'solid_layer_thickness': '0.6',
\r
22 'fill_density': '20',
\r
23 'skirt_line_count': '1',
\r
25 'print_speed': '50',
\r
26 'print_temperature': '230',
\r
28 'filament_diameter': '2.89',
\r
29 'filament_density': '1.00',
\r
30 'machine_center_x': '100',
\r
31 'machine_center_y': '100',
\r
32 'retraction_min_travel': '5.0',
\r
33 'retraction_speed': '40.0',
\r
34 'retraction_amount': '0.0',
\r
35 'retraction_extra': '0.0',
\r
36 'retract_on_jumps_only': 'True',
\r
37 'travel_speed': '150',
\r
38 'max_z_speed': '3.0',
\r
39 'bottom_layer_speed': '20',
\r
40 'cool_min_layer_time': '10',
\r
41 'fan_enabled': 'True',
\r
44 'fan_speed_max': '100',
\r
45 'model_scale': '1.0',
\r
51 'model_rotate_base': '0',
\r
52 'model_multiply_x': '1',
\r
53 'model_multiply_y': '1',
\r
54 'extra_base_wall_thickness': '0.0',
\r
55 'sequence': 'Loops > Perimeter > Infill',
\r
56 'force_first_layer_sequence': 'True',
\r
57 'infill_type': 'Line',
\r
58 'solid_top': 'True',
\r
59 'fill_overlap': '15',
\r
60 'support_rate': '50',
\r
61 'support_distance': '0.5',
\r
63 'enable_skin': 'False',
\r
64 'enable_raft': 'False',
\r
65 'cool_min_feedrate': '5',
\r
66 'bridge_speed': '100',
\r
68 'raft_base_material_amount': '100',
\r
69 'raft_interface_material_amount': '100',
\r
70 'bottom_thickness': '0.3',
\r
72 'enable_dwindle': 'False',
\r
73 'dwindle_pent_up_volume': '0.4',
\r
74 'dwindle_slowdown_volume': '5.0',
\r
76 'add_start_end_gcode': 'True',
\r
77 'gcode_extension': 'gcode',
\r
78 'alternative_center': '',
\r
82 alterationDefault = {
\r
83 #######################################################################################
\r
84 'start.gcode': """;Sliced {filename} at: {day} {date} {time}
\r
85 ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
\r
86 ;Print time: {print_time}
\r
87 ;Filament used: {filament_amount}m {filament_weight}g
\r
88 ;Filament cost: {filament_cost}
\r
90 G90 ;absolute positioning
\r
91 M107 ;start with the fan off
\r
93 G28 X0 Y0 ;move X/Y to min endstops
\r
94 G28 Z0 ;move Z to min endstops
\r
95 G92 X0 Y0 Z0 E0 ;reset software position to front/left/z=0.0
\r
97 G1 Z15.0 F{max_z_speed} ;move the platform down 15mm
\r
99 G92 E0 ;zero the extruded length
\r
100 G1 F200 E3 ;extrude 3mm of feed stock
\r
101 G92 E0 ;zero the extruded length again
\r
103 ;go to the middle of the platform (disabled, as there is no need to go to the center)
\r
104 ;G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}
\r
107 #######################################################################################
\r
108 'end.gcode': """;End GCode
\r
109 M104 S0 ;extruder heater off
\r
110 M140 S0 ;heated bed heater off (if you have it)
\r
112 G91 ;relative positioning
\r
113 G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
\r
114 G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
\r
115 G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
\r
118 G90 ;absolute positioning
\r
120 #######################################################################################
\r
121 'support_start.gcode': '',
\r
122 'support_end.gcode': '',
\r
123 'cool_start.gcode': '',
\r
124 'cool_end.gcode': '',
\r
126 #######################################################################################
\r
127 'nextobject.gcode': """;Move to next object on the platform. clear_z is the minimal z height we need to make sure we do not hit any objects.
\r
130 G91 ;relative positioning
\r
131 G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
\r
132 G1 Z+0.5 E-5 F{travel_speed} ;move Z up a bit and retract filament even more
\r
133 G90 ;absolute positioning
\r
135 G1 Z{clear_z} F{max_z_speed}
\r
137 G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}
\r
141 #######################################################################################
\r
142 'switchExtruder.gcode': """;Switch between the current extruder and the next extruder, when printing with multiple extruders.
\r
150 preferencesDefaultSettings = {
\r
151 'wizardDone': 'False',
\r
152 'startMode': 'Simple',
\r
154 'machine_width': '205',
\r
155 'machine_depth': '205',
\r
156 'machine_height': '200',
\r
157 'machine_type': 'unknown',
\r
158 'extruder_amount': '1',
\r
159 'extruder_offset_x1': '-22.0',
\r
160 'extruder_offset_y1': '0.0',
\r
161 'extruder_offset_x2': '0.0',
\r
162 'extruder_offset_y2': '0.0',
\r
163 'extruder_offset_x3': '0.0',
\r
164 'extruder_offset_y3': '0.0',
\r
165 'filament_density': '1300',
\r
166 'steps_per_e': '0',
\r
167 'serial_port': 'AUTO',
\r
168 'serial_baud': 'AUTO',
\r
169 'slicer': 'Cura (Skeinforge based)',
\r
170 'save_profile': 'False',
\r
171 'filament_cost_kg': '0',
\r
172 'filament_cost_meter': '0',
\r
174 'sdshortnames': 'True',
\r
176 'extruder_head_size_min_x': '70.0',
\r
177 'extruder_head_size_min_y': '18.0',
\r
178 'extruder_head_size_max_x': '18.0',
\r
179 'extruder_head_size_max_y': '35.0',
\r
180 'extruder_head_size_height': '80.0',
\r
183 #########################################################
\r
184 ## Profile and preferences functions
\r
185 #########################################################
\r
187 ## Profile functions
\r
188 def getDefaultProfilePath():
\r
189 basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
\r
190 #If we have a frozen python install, we need to step out of the library.zip
\r
191 if hasattr(sys, 'frozen'):
\r
192 basePath = os.path.normpath(os.path.join(basePath, ".."))
\r
193 return os.path.normpath(os.path.join(basePath, "current_profile.ini"))
\r
195 def loadGlobalProfile(filename):
\r
196 #Read a configuration file as global config
\r
197 global globalProfileParser
\r
198 globalProfileParser = ConfigParser.ConfigParser()
\r
199 globalProfileParser.read(filename)
\r
201 def resetGlobalProfile():
\r
202 #Read a configuration file as global config
\r
203 global globalProfileParser
\r
204 globalProfileParser = ConfigParser.ConfigParser()
\r
206 def saveGlobalProfile(filename):
\r
207 #Save the current profile to an ini file
\r
208 globalProfileParser.write(open(filename, 'w'))
\r
210 def loadGlobalProfileFromString(options):
\r
211 global globalProfileParser
\r
212 globalProfileParser = ConfigParser.ConfigParser()
\r
213 globalProfileParser.add_section('profile')
\r
214 globalProfileParser.add_section('alterations')
\r
215 options = base64.b64decode(options)
\r
216 options = zlib.decompress(options)
\r
217 (profileOpts, alt) = options.split('\f', 1)
\r
218 for option in profileOpts.split('\b'):
\r
219 if len(option) > 0:
\r
220 (key, value) = option.split('=', 1)
\r
221 globalProfileParser.set('profile', key, value)
\r
222 for option in alt.split('\b'):
\r
223 if len(option) > 0:
\r
224 (key, value) = option.split('=', 1)
\r
225 globalProfileParser.set('alterations', key, value)
\r
227 def getGlobalProfileString():
\r
228 global globalProfileParser
\r
229 if not globals().has_key('globalProfileParser'):
\r
230 loadGlobalProfile(getDefaultProfilePath())
\r
235 if globalProfileParser.has_section('profile'):
\r
236 for key in globalProfileParser.options('profile'):
\r
237 if key in tempOverride:
\r
238 p.append(key + "=" + unicode(tempOverride[key]))
\r
239 tempDone.append(key)
\r
241 p.append(key + "=" + globalProfileParser.get('profile', key))
\r
242 if globalProfileParser.has_section('alterations'):
\r
243 for key in globalProfileParser.options('alterations'):
\r
244 if key in tempOverride:
\r
245 p.append(key + "=" + tempOverride[key])
\r
246 tempDone.append(key)
\r
248 alt.append(key + "=" + globalProfileParser.get('alterations', key))
\r
249 for key in tempOverride:
\r
250 if key not in tempDone:
\r
251 p.append(key + "=" + unicode(tempOverride[key]))
\r
252 ret = '\b'.join(p) + '\f' + '\b'.join(alt)
\r
253 ret = base64.b64encode(zlib.compress(ret, 9))
\r
256 def getProfileSetting(name):
\r
257 if name in tempOverride:
\r
258 return unicode(tempOverride[name])
\r
259 #Check if we have a configuration file loaded, else load the default.
\r
260 if not globals().has_key('globalProfileParser'):
\r
261 loadGlobalProfile(getDefaultProfilePath())
\r
262 if not globalProfileParser.has_option('profile', name):
\r
263 if name in profileDefaultSettings:
\r
264 default = profileDefaultSettings[name]
\r
266 print("Missing default setting for: '" + name + "'")
\r
267 profileDefaultSettings[name] = ''
\r
269 if not globalProfileParser.has_section('profile'):
\r
270 globalProfileParser.add_section('profile')
\r
271 globalProfileParser.set('profile', name, str(default))
\r
272 #print(name + " not found in profile, so using default: " + str(default))
\r
274 return globalProfileParser.get('profile', name)
\r
276 def getProfileSettingFloat(name):
\r
278 setting = getProfileSetting(name).replace(',', '.')
\r
279 return float(eval(setting, {}, {}))
\r
280 except (ValueError, SyntaxError, TypeError):
\r
283 def putProfileSetting(name, value):
\r
284 #Check if we have a configuration file loaded, else load the default.
\r
285 if not globals().has_key('globalProfileParser'):
\r
286 loadGlobalProfile(getDefaultProfilePath())
\r
287 if not globalProfileParser.has_section('profile'):
\r
288 globalProfileParser.add_section('profile')
\r
289 globalProfileParser.set('profile', name, str(value))
\r
291 def isProfileSetting(name):
\r
292 if name in profileDefaultSettings:
\r
296 ## Preferences functions
\r
297 global globalPreferenceParser
\r
298 globalPreferenceParser = None
\r
300 def getPreferencePath():
\r
301 basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
\r
302 #If we have a frozen python install, we need to step out of the library.zip
\r
303 if hasattr(sys, 'frozen'):
\r
304 basePath = os.path.normpath(os.path.join(basePath, ".."))
\r
305 return os.path.normpath(os.path.join(basePath, "preferences.ini"))
\r
307 def getPreferenceFloat(name):
\r
309 setting = getPreference(name).replace(',', '.')
\r
310 return float(eval(setting, {}, {}))
\r
311 except (ValueError, SyntaxError, TypeError):
\r
314 def getPreference(name):
\r
315 if name in tempOverride:
\r
316 return unicode(tempOverride[name])
\r
317 global globalPreferenceParser
\r
318 if globalPreferenceParser == None:
\r
319 globalPreferenceParser = ConfigParser.ConfigParser()
\r
320 globalPreferenceParser.read(getPreferencePath())
\r
321 if not globalPreferenceParser.has_option('preference', name):
\r
322 if name in preferencesDefaultSettings:
\r
323 default = preferencesDefaultSettings[name]
\r
325 print("Missing default setting for: '" + name + "'")
\r
326 preferencesDefaultSettings[name] = ''
\r
328 if not globalPreferenceParser.has_section('preference'):
\r
329 globalPreferenceParser.add_section('preference')
\r
330 globalPreferenceParser.set('preference', name, str(default))
\r
331 #print(name + " not found in preferences, so using default: " + str(default))
\r
333 return unicode(globalPreferenceParser.get('preference', name), "utf-8")
\r
335 def putPreference(name, value):
\r
336 #Check if we have a configuration file loaded, else load the default.
\r
337 global globalPreferenceParser
\r
338 if globalPreferenceParser == None:
\r
339 globalPreferenceParser = ConfigParser.ConfigParser()
\r
340 globalPreferenceParser.read(getPreferencePath())
\r
341 if not globalPreferenceParser.has_section('preference'):
\r
342 globalPreferenceParser.add_section('preference')
\r
343 globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))
\r
344 globalPreferenceParser.write(open(getPreferencePath(), 'w'))
\r
346 def isPreference(name):
\r
347 if name in preferencesDefaultSettings:
\r
351 ## Temp overrides for multi-extruder slicing and the project planner.
\r
353 def setTempOverride(name, value):
\r
354 tempOverride[name] = value
\r
355 def resetTempOverride():
\r
356 tempOverride.clear()
\r
358 #########################################################
\r
359 ## Utility functions to calculate common profile values
\r
360 #########################################################
\r
361 def calculateEdgeWidth():
\r
362 wallThickness = getProfileSettingFloat('wall_thickness')
\r
363 nozzleSize = getProfileSettingFloat('nozzle_size')
\r
365 if wallThickness < nozzleSize:
\r
366 return wallThickness
\r
368 lineCount = int(wallThickness / nozzleSize)
\r
369 lineWidth = wallThickness / lineCount
\r
370 lineWidthAlt = wallThickness / (lineCount + 1)
\r
371 if lineWidth > nozzleSize * 1.5:
\r
372 return lineWidthAlt
\r
375 def calculateLineCount():
\r
376 wallThickness = getProfileSettingFloat('wall_thickness')
\r
377 nozzleSize = getProfileSettingFloat('nozzle_size')
\r
379 if wallThickness < nozzleSize:
\r
382 lineCount = int(wallThickness / nozzleSize + 0.0001)
\r
383 lineWidth = wallThickness / lineCount
\r
384 lineWidthAlt = wallThickness / (lineCount + 1)
\r
385 if lineWidth > nozzleSize * 1.5:
\r
386 return lineCount + 1
\r
389 def calculateSolidLayerCount():
\r
390 layerHeight = getProfileSettingFloat('layer_height')
\r
391 solidThickness = getProfileSettingFloat('solid_layer_thickness')
\r
392 return int(math.ceil(solidThickness / layerHeight - 0.0001))
\r
394 #########################################################
\r
395 ## Alteration file functions
\r
396 #########################################################
\r
397 def replaceTagMatch(m):
\r
401 return pre + time.strftime('%H:%M:%S')
\r
403 return pre + time.strftime('%d %b %Y')
\r
405 return pre + time.strftime('%a')
\r
406 if tag == 'print_time':
\r
407 return pre + '#P_TIME#'
\r
408 if tag == 'filament_amount':
\r
409 return pre + '#F_AMNT#'
\r
410 if tag == 'filament_weight':
\r
411 return pre + '#F_WGHT#'
\r
412 if tag == 'filament_cost':
\r
413 return pre + '#F_COST#'
\r
414 if pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:
\r
415 f = getProfileSettingFloat(tag) * 60
\r
416 elif isProfileSetting(tag):
\r
417 f = getProfileSettingFloat(tag)
\r
418 elif isPreference(tag):
\r
419 f = getProfileSettingFloat(tag)
\r
421 return '%s?%s?' % (pre, tag)
\r
423 return pre + str(int(f))
\r
424 return pre + str(f)
\r
426 def replaceGCodeTags(filename, gcodeInt):
\r
427 f = open(filename, 'r+')
\r
428 data = f.read(2048)
\r
429 data = data.replace('#P_TIME#', ('%5d:%02d' % (int(gcodeInt.totalMoveTimeMinute / 60), int(gcodeInt.totalMoveTimeMinute % 60)))[-8:])
\r
430 data = data.replace('#F_AMNT#', ('%8.2f' % (gcodeInt.extrusionAmount / 1000))[-8:])
\r
431 data = data.replace('#F_WGHT#', ('%8.2f' % (gcodeInt.calculateWeight() * 1000))[-8:])
\r
432 cost = gcodeInt.calculateCost()
\r
435 data = data.replace('#F_COST#', ('%8s' % (cost.split(' ')[0]))[-8:])
\r
440 ### Get aleration raw contents. (Used internally in Cura)
\r
441 def getAlterationFile(filename):
\r
442 #Check if we have a configuration file loaded, else load the default.
\r
443 if not globals().has_key('globalProfileParser'):
\r
444 loadGlobalProfile(getDefaultProfilePath())
\r
446 if not globalProfileParser.has_option('alterations', filename):
\r
447 if filename in alterationDefault:
\r
448 default = alterationDefault[filename]
\r
450 print("Missing default alteration for: '" + filename + "'")
\r
451 alterationDefault[filename] = ''
\r
453 if not globalProfileParser.has_section('alterations'):
\r
454 globalProfileParser.add_section('alterations')
\r
455 #print("Using default for: %s" % (filename))
\r
456 globalProfileParser.set('alterations', filename, default)
\r
457 return unicode(globalProfileParser.get('alterations', filename), "utf-8")
\r
459 def setAlterationFile(filename, value):
\r
460 #Check if we have a configuration file loaded, else load the default.
\r
461 if not globals().has_key('globalProfileParser'):
\r
462 loadGlobalProfile(getDefaultProfilePath())
\r
463 if not globalProfileParser.has_section('alterations'):
\r
464 globalProfileParser.add_section('alterations')
\r
465 globalProfileParser.set('alterations', filename, value.encode("utf-8"))
\r
466 saveGlobalProfile(getDefaultProfilePath())
\r
468 ### Get the alteration file for output. (Used by Skeinforge)
\r
469 def getAlterationFileContents(filename):
\r
472 alterationContents = getAlterationFile(filename)
\r
473 if filename == 'start.gcode':
\r
474 #For the start code, hack the temperature and the steps per E value into it. So the temperature is reached before the start code extrusion.
\r
475 #We also set our steps per E here, if configured.
\r
476 eSteps = getPreferenceFloat('steps_per_e')
\r
478 prefix += 'M92 E%f\n' % (eSteps)
\r
479 temp = getProfileSettingFloat('print_temperature')
\r
480 if temp > 0 and not '{print_temperature}' in alterationContents:
\r
481 prefix += 'M109 S%f\n' % (temp)
\r
482 elif filename == 'end.gcode':
\r
483 #Append the profile string to the end of the GCode, so we can load it from the GCode file later.
\r
484 postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())
\r
485 elif filename == 'replace.csv':
\r
486 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.
\r
487 prefix = 'M101\nM103\n'
\r
489 return unicode(prefix + re.sub("(.)\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).encode('utf-8')
\r