1 from __future__ import absolute_import
2 from __future__ import division
4 import os, traceback, math, re, zlib, base64, time, sys, platform, glob, string, stat
5 import cPickle as pickle
6 if sys.version_info[0] < 3:
9 import configparser as ConfigParser
11 from Cura.util import resources
12 from Cura.util import version
14 #########################################################
15 ## Default settings when none are found.
16 #########################################################
18 #Single place to store the defaults, so we have a consistent set of default settings.
19 profileDefaultSettings = {
21 'layer_height': '0.2',
22 'wall_thickness': '0.8',
23 'solid_layer_thickness': '0.6',
25 'skirt_line_count': '1',
28 'print_temperature': '220',
29 'print_bed_temperature': '70',
31 'filament_diameter': '2.89',
32 'filament_density': '1.00',
33 'retraction_min_travel': '5.0',
34 'retraction_enable': 'False',
35 'retraction_speed': '40.0',
36 'retraction_amount': '4.5',
37 'retraction_extra': '0.0',
38 'retract_on_jumps_only': 'True',
39 'travel_speed': '150',
41 'bottom_layer_speed': '20',
42 'cool_min_layer_time': '5',
43 'fan_enabled': 'True',
46 'fan_speed_max': '100',
47 'model_matrix': '1,0,0,0,1,0,0,0,1',
48 'extra_base_wall_thickness': '0.0',
49 'sequence': 'Loops > Perimeter > Infill',
50 'force_first_layer_sequence': 'True',
51 'infill_type': 'Line',
55 'support_distance': '0.5',
56 'support_dual_extrusion': 'False',
58 'enable_skin': 'False',
59 'enable_raft': 'False',
60 'cool_min_feedrate': '10',
61 'bridge_speed': '100',
63 'raft_base_material_amount': '100',
64 'raft_interface_material_amount': '100',
65 'bottom_thickness': '0.3',
66 'hop_on_move': 'False',
68 'object_center_x': '-1',
69 'object_center_y': '-1',
72 'gcode_extension': 'gcode',
73 'alternative_center': '',
78 #######################################################################################
79 'start.gcode': """;Sliced {filename} at: {day} {date} {time}
80 ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
81 ;Print time: {print_time}
82 ;Filament used: {filament_amount}m {filament_weight}g
83 ;Filament cost: {filament_cost}
85 G90 ;absolute positioning
86 M107 ;start with the fan off
88 G28 X0 Y0 ;move X/Y to min endstops
89 G28 Z0 ;move Z to min endstops
90 G92 X0 Y0 Z0 E0 ;reset software position to front/left/z=0.0
92 G1 Z15.0 F{max_z_speed} ;move the platform down 15mm
94 G92 E0 ;zero the extruded length
95 G1 F200 E3 ;extrude 3mm of feed stock
96 G92 E0 ;zero the extruded length again
99 #######################################################################################
100 'end.gcode': """;End GCode
101 M104 S0 ;extruder heater off
102 M140 S0 ;heated bed heater off (if you have it)
104 G91 ;relative positioning
105 G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
106 G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
107 G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
110 G90 ;absolute positioning
112 #######################################################################################
113 'support_start.gcode': '',
114 'support_end.gcode': '',
115 'cool_start.gcode': '',
116 'cool_end.gcode': '',
118 #######################################################################################
119 '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.
122 G91 ;relative positioning
123 G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
124 G1 Z+0.5 E-5 F{travel_speed} ;move Z up a bit and retract filament even more
125 G90 ;absolute positioning
127 G1 Z{clear_z} F{max_z_speed}
129 G1 X{object_center_x} Y{object_center_x} F{travel_speed}
133 #######################################################################################
134 'switchExtruder.gcode': """;Switch between the current extruder and the next extruder, when printing with multiple extruders.
143 preferencesDefaultSettings = {
144 'startMode': 'Simple',
145 'lastFile': os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'resources', 'example', 'UltimakerRobot_support.stl')),
146 'machine_width': '205',
147 'machine_depth': '205',
148 'machine_height': '200',
149 'machine_type': 'unknown',
150 'machine_center_is_zero': 'False',
151 'ultimaker_extruder_upgrade': 'False',
152 'has_heated_bed': 'False',
153 'reprap_name': 'RepRap',
154 'extruder_amount': '1',
155 'extruder_offset_x1': '-22.0',
156 'extruder_offset_y1': '0.0',
157 'extruder_offset_x2': '0.0',
158 'extruder_offset_y2': '0.0',
159 'extruder_offset_x3': '0.0',
160 'extruder_offset_y3': '0.0',
161 'filament_density': '1300',
163 'serial_port': 'AUTO',
164 'serial_port_auto': '',
165 'serial_baud': 'AUTO',
166 'serial_baud_auto': '',
167 'slicer': 'Cura (Skeinforge based)',
168 'save_profile': 'False',
169 'filament_cost_kg': '0',
170 'filament_cost_meter': '0',
172 'sdshortnames': 'False',
173 'check_for_updates': 'True',
174 'submit_slice_information': 'False',
176 'planner_always_autoplace': 'True',
177 'extruder_head_size_min_x': '75.0',
178 'extruder_head_size_min_y': '18.0',
179 'extruder_head_size_max_x': '18.0',
180 'extruder_head_size_max_y': '35.0',
181 'extruder_head_size_height': '60.0',
183 'model_colour': '#72CB30',
184 'model_colour2': '#CB3030',
185 'model_colour3': '#DDD93C',
186 'model_colour4': '#4550D3',
188 'window_maximized': 'False',
189 'window_pos_x': '-1',
190 'window_pos_y': '-1',
191 'window_width': '-1',
192 'window_height': '-1',
193 'window_normal_sash': '320',
196 #########################################################
197 ## Profile and preferences functions
198 #########################################################
202 if platform.system() == "Windows":
203 basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
204 #If we have a frozen python install, we need to step out of the library.zip
205 if hasattr(sys, 'frozen'):
206 basePath = os.path.normpath(os.path.join(basePath, ".."))
208 basePath = os.path.expanduser('~/.cura/%s' % version.getVersion(False))
209 if not os.path.isdir(basePath):
210 os.makedirs(basePath)
213 def getDefaultProfilePath():
214 return os.path.join(getBasePath(), 'current_profile.ini')
216 def loadGlobalProfile(filename):
217 #Read a configuration file as global config
218 global globalProfileParser
219 globalProfileParser = ConfigParser.ConfigParser()
221 globalProfileParser.read(filename)
222 except ConfigParser.ParsingError:
225 def resetGlobalProfile():
226 #Read a configuration file as global config
227 global globalProfileParser
228 globalProfileParser = ConfigParser.ConfigParser()
230 if getPreference('machine_type') == 'ultimaker':
231 putProfileSetting('nozzle_size', '0.4')
232 if getPreference('ultimaker_extruder_upgrade') == 'True':
233 putProfileSetting('retraction_enable', 'True')
235 putProfileSetting('nozzle_size', '0.5')
237 def saveGlobalProfile(filename):
238 #Save the current profile to an ini file
239 globalProfileParser.write(open(filename, 'w'))
241 def loadGlobalProfileFromString(options):
242 global globalProfileParser
243 globalProfileParser = ConfigParser.ConfigParser()
244 globalProfileParser.add_section('profile')
245 globalProfileParser.add_section('alterations')
246 options = base64.b64decode(options)
247 options = zlib.decompress(options)
248 (profileOpts, alt) = options.split('\f', 1)
249 for option in profileOpts.split('\b'):
251 (key, value) = option.split('=', 1)
252 globalProfileParser.set('profile', key, value)
253 for option in alt.split('\b'):
255 (key, value) = option.split('=', 1)
256 globalProfileParser.set('alterations', key, value)
258 def getGlobalProfileString():
259 global globalProfileParser
260 if not globals().has_key('globalProfileParser'):
261 loadGlobalProfile(getDefaultProfilePath())
266 if globalProfileParser.has_section('profile'):
267 for key in globalProfileParser.options('profile'):
268 if key in tempOverride:
269 p.append(key + "=" + tempOverride[key])
272 p.append(key + "=" + globalProfileParser.get('profile', key))
273 if globalProfileParser.has_section('alterations'):
274 for key in globalProfileParser.options('alterations'):
275 if key in tempOverride:
276 p.append(key + "=" + tempOverride[key])
279 alt.append(key + "=" + globalProfileParser.get('alterations', key))
280 for key in tempOverride:
281 if key not in tempDone:
282 p.append(key + "=" + tempOverride[key])
283 ret = '\b'.join(p) + '\f' + '\b'.join(alt)
284 ret = base64.b64encode(zlib.compress(ret, 9))
287 def getProfileSetting(name):
288 if name in tempOverride:
289 return unicode(tempOverride[name], "utf-8")
290 #Check if we have a configuration file loaded, else load the default.
291 if not globals().has_key('globalProfileParser'):
292 loadGlobalProfile(getDefaultProfilePath())
293 if not globalProfileParser.has_option('profile', name):
294 if name in profileDefaultSettings:
295 default = profileDefaultSettings[name]
297 print("Missing default setting for: '" + name + "'")
298 profileDefaultSettings[name] = ''
300 if not globalProfileParser.has_section('profile'):
301 globalProfileParser.add_section('profile')
302 globalProfileParser.set('profile', name, str(default))
303 #print(name + " not found in profile, so using default: " + str(default))
305 return globalProfileParser.get('profile', name)
307 def getProfileSettingFloat(name):
309 setting = getProfileSetting(name).replace(',', '.')
310 return float(eval(setting, {}, {}))
311 except (ValueError, SyntaxError, TypeError):
314 def putProfileSetting(name, value):
315 #Check if we have a configuration file loaded, else load the default.
316 if not globals().has_key('globalProfileParser'):
317 loadGlobalProfile(getDefaultProfilePath())
318 if not globalProfileParser.has_section('profile'):
319 globalProfileParser.add_section('profile')
320 globalProfileParser.set('profile', name, str(value))
322 def isProfileSetting(name):
323 if name in profileDefaultSettings:
327 ## Preferences functions
328 global globalPreferenceParser
329 globalPreferenceParser = None
331 def getPreferencePath():
332 return os.path.join(getBasePath(), 'preferences.ini')
334 def getPreferenceFloat(name):
336 setting = getPreference(name).replace(',', '.')
337 return float(eval(setting, {}, {}))
338 except (ValueError, SyntaxError, TypeError):
341 def getPreferenceColour(name):
342 colorString = getPreference(name)
343 return [float(int(colorString[1:3], 16)) / 255, float(int(colorString[3:5], 16)) / 255, float(int(colorString[5:7], 16)) / 255, 1.0]
345 def getPreference(name):
346 if name in tempOverride:
347 return unicode(tempOverride[name])
348 global globalPreferenceParser
349 if globalPreferenceParser is None:
350 globalPreferenceParser = ConfigParser.ConfigParser()
352 globalPreferenceParser.read(getPreferencePath())
353 except ConfigParser.ParsingError:
355 if not globalPreferenceParser.has_option('preference', name):
356 if name in preferencesDefaultSettings:
357 default = preferencesDefaultSettings[name]
359 print("Missing default setting for: '" + name + "'")
360 preferencesDefaultSettings[name] = ''
362 if not globalPreferenceParser.has_section('preference'):
363 globalPreferenceParser.add_section('preference')
364 globalPreferenceParser.set('preference', name, str(default))
365 #print(name + " not found in preferences, so using default: " + str(default))
367 return unicode(globalPreferenceParser.get('preference', name), "utf-8")
369 def putPreference(name, value):
370 #Check if we have a configuration file loaded, else load the default.
371 global globalPreferenceParser
372 if globalPreferenceParser == None:
373 globalPreferenceParser = ConfigParser.ConfigParser()
375 globalPreferenceParser.read(getPreferencePath())
376 except ConfigParser.ParsingError:
378 if not globalPreferenceParser.has_section('preference'):
379 globalPreferenceParser.add_section('preference')
380 globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))
381 globalPreferenceParser.write(open(getPreferencePath(), 'w'))
383 def isPreference(name):
384 if name in preferencesDefaultSettings:
388 ## Temp overrides for multi-extruder slicing and the project planner.
390 def setTempOverride(name, value):
391 tempOverride[name] = unicode(value).encode("utf-8")
392 def clearTempOverride(name):
393 del tempOverride[name]
394 def resetTempOverride():
397 #########################################################
398 ## Utility functions to calculate common profile values
399 #########################################################
400 def calculateEdgeWidth():
401 wallThickness = getProfileSettingFloat('wall_thickness')
402 nozzleSize = getProfileSettingFloat('nozzle_size')
404 if wallThickness < nozzleSize:
407 lineCount = int(wallThickness / nozzleSize + 0.0001)
408 lineWidth = wallThickness / lineCount
409 lineWidthAlt = wallThickness / (lineCount + 1)
410 if lineWidth > nozzleSize * 1.5:
414 def calculateLineCount():
415 wallThickness = getProfileSettingFloat('wall_thickness')
416 nozzleSize = getProfileSettingFloat('nozzle_size')
418 if wallThickness < nozzleSize:
421 lineCount = int(wallThickness / nozzleSize + 0.0001)
422 lineWidth = wallThickness / lineCount
423 lineWidthAlt = wallThickness / (lineCount + 1)
424 if lineWidth > nozzleSize * 1.5:
428 def calculateSolidLayerCount():
429 layerHeight = getProfileSettingFloat('layer_height')
430 solidThickness = getProfileSettingFloat('solid_layer_thickness')
431 return int(math.ceil(solidThickness / layerHeight - 0.0001))
433 def getMachineCenterCoords():
434 if getPreference('machine_center_is_zero') == 'True':
436 return [getPreferenceFloat('machine_width') / 2, getPreferenceFloat('machine_depth') / 2]
438 def getObjectMatrix():
440 return map(float, getProfileSetting('model_matrix').split(','))
442 return [1,0,0, 0,1,0, 0,0,1]
445 #########################################################
446 ## Alteration file functions
447 #########################################################
448 def replaceTagMatch(m):
452 return pre + time.strftime('%H:%M:%S').encode('utf-8', 'replace')
454 return pre + time.strftime('%d %b %Y').encode('utf-8', 'replace')
456 return pre + time.strftime('%a').encode('utf-8', 'replace')
457 if tag == 'print_time':
458 return pre + '#P_TIME#'
459 if tag == 'filament_amount':
460 return pre + '#F_AMNT#'
461 if tag == 'filament_weight':
462 return pre + '#F_WGHT#'
463 if tag == 'filament_cost':
464 return pre + '#F_COST#'
465 if pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:
466 f = getProfileSettingFloat(tag) * 60
467 elif isProfileSetting(tag):
468 f = getProfileSettingFloat(tag)
469 elif isPreference(tag):
470 f = getProfileSettingFloat(tag)
472 return '%s?%s?' % (pre, tag)
474 return pre + str(int(f))
477 def replaceGCodeTags(filename, gcodeInt):
478 f = open(filename, 'r+')
480 data = data.replace('#P_TIME#', ('%5d:%02d' % (int(gcodeInt.totalMoveTimeMinute / 60), int(gcodeInt.totalMoveTimeMinute % 60)))[-8:])
481 data = data.replace('#F_AMNT#', ('%8.2f' % (gcodeInt.extrusionAmount / 1000))[-8:])
482 data = data.replace('#F_WGHT#', ('%8.2f' % (gcodeInt.calculateWeight() * 1000))[-8:])
483 cost = gcodeInt.calculateCost()
486 data = data.replace('#F_COST#', ('%8s' % (cost.split(' ')[0]))[-8:])
491 ### Get aleration raw contents. (Used internally in Cura)
492 def getAlterationFile(filename):
493 #Check if we have a configuration file loaded, else load the default.
494 if not globals().has_key('globalProfileParser'):
495 loadGlobalProfile(getDefaultProfilePath())
497 if not globalProfileParser.has_option('alterations', filename):
498 if filename in alterationDefault:
499 default = alterationDefault[filename]
501 print("Missing default alteration for: '" + filename + "'")
502 alterationDefault[filename] = ''
504 if not globalProfileParser.has_section('alterations'):
505 globalProfileParser.add_section('alterations')
506 #print("Using default for: %s" % (filename))
507 globalProfileParser.set('alterations', filename, default)
508 return unicode(globalProfileParser.get('alterations', filename), "utf-8")
510 def setAlterationFile(filename, value):
511 #Check if we have a configuration file loaded, else load the default.
512 if not globals().has_key('globalProfileParser'):
513 loadGlobalProfile(getDefaultProfilePath())
514 if not globalProfileParser.has_section('alterations'):
515 globalProfileParser.add_section('alterations')
516 globalProfileParser.set('alterations', filename, value.encode("utf-8"))
517 saveGlobalProfile(getDefaultProfilePath())
519 ### Get the alteration file for output. (Used by Skeinforge)
520 def getAlterationFileContents(filename):
523 alterationContents = getAlterationFile(filename)
524 if filename == 'start.gcode':
525 #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.
526 #We also set our steps per E here, if configured.
527 eSteps = getPreferenceFloat('steps_per_e')
529 prefix += 'M92 E%f\n' % (eSteps)
530 temp = getProfileSettingFloat('print_temperature')
532 if getPreference('has_heated_bed') == 'True':
533 bedTemp = getProfileSettingFloat('print_bed_temperature')
535 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
536 prefix += 'M140 S%f\n' % (bedTemp)
537 if temp > 0 and not '{print_temperature}' in alterationContents:
538 prefix += 'M109 S%f\n' % (temp)
539 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
540 prefix += 'M190 S%f\n' % (bedTemp)
541 elif filename == 'end.gcode':
542 #Append the profile string to the end of the GCode, so we can load it from the GCode file later.
543 postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())
544 elif filename == 'replace.csv':
545 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.
546 prefix = 'M101\nM103\n'
547 elif filename == 'support_start.gcode' or filename == 'support_end.gcode':
548 #Add support start/end code
549 if getProfileSetting('support_dual_extrusion') == 'True' and int(getPreference('extruder_amount')) > 1:
550 if filename == 'support_start.gcode':
551 setTempOverride('extruder', '1')
553 setTempOverride('extruder', '0')
554 alterationContents = getAlterationFileContents('switchExtruder.gcode')
555 clearTempOverride('extruder')
557 alterationContents = ''
558 return unicode(prefix + re.sub("(.)\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
562 def getPluginConfig():
564 return pickle.loads(getProfileSetting('plugin_config'))
568 def setPluginConfig(config):
569 putProfileSetting('plugin_config', pickle.dumps(config))
571 def getPluginBasePaths():
573 if platform.system() != "Windows":
574 ret.append(os.path.expanduser('~/.cura/plugins/'))
575 if platform.system() == "Darwin" and hasattr(sys, 'frozen'):
576 ret.append(os.path.normpath(os.path.join(resources.resourceBasePath, "Cura/plugins")))
578 ret.append(os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'plugins')))
583 for basePath in getPluginBasePaths():
584 for filename in glob.glob(os.path.join(basePath, '*.py')):
585 filename = os.path.basename(filename)
586 if filename.startswith('_'):
588 with open(os.path.join(basePath, filename), "r") as f:
589 item = {'filename': filename, 'name': None, 'info': None, 'type': None, 'params': []}
592 if not line.startswith('#'):
594 line = line[1:].split(':', 1)
597 if line[0].upper() == 'NAME':
598 item['name'] = line[1].strip()
599 elif line[0].upper() == 'INFO':
600 item['info'] = line[1].strip()
601 elif line[0].upper() == 'TYPE':
602 item['type'] = line[1].strip()
603 elif line[0].upper() == 'DEPEND':
605 elif line[0].upper() == 'PARAM':
606 m = re.match('([a-zA-Z][a-zA-Z0-9_]*)\(([a-zA-Z_]*)(?::([^\)]*))?\) +(.*)', line[1].strip())
608 item['params'].append({'name': m.group(1), 'type': m.group(2), 'default': m.group(3), 'description': m.group(4)})
610 print "Unknown item in effect meta data: %s %s" % (line[0], line[1])
611 if item['name'] != None and item['type'] == 'postprocess':
615 def runPostProcessingPlugins(gcodefilename):
616 pluginConfigList = getPluginConfig()
617 pluginList = getPluginList()
619 for pluginConfig in pluginConfigList:
621 for pluginTest in pluginList:
622 if pluginTest['filename'] == pluginConfig['filename']:
628 for basePath in getPluginBasePaths():
629 testFilename = os.path.join(basePath, pluginConfig['filename'])
630 if os.path.isfile(testFilename):
631 pythonFile = testFilename
632 if pythonFile is None:
635 locals = {'filename': gcodefilename}
636 for param in plugin['params']:
637 value = param['default']
638 if param['name'] in pluginConfig['params']:
639 value = pluginConfig['params'][param['name']]
641 if param['type'] == 'float':
645 value = float(param['default'])
647 locals[param['name']] = value
649 execfile(pythonFile, locals)
651 locationInfo = traceback.extract_tb(sys.exc_info()[2])[-1]
652 return "%s: '%s' @ %s:%s:%d" % (str(sys.exc_info()[0].__name__), str(sys.exc_info()[1]), os.path.basename(locationInfo[0]), locationInfo[2], locationInfo[1])
655 def getSDcardDrives():
657 if platform.system() == "Windows":
658 from ctypes import windll
659 bitmask = windll.kernel32.GetLogicalDrives()
660 for letter in string.uppercase:
662 drives.append(letter + ':/')
664 if platform.system() == "Darwin":
666 for volume in glob.glob('/Volumes/*'):
667 if stat.S_ISLNK(os.lstat(volume).st_mode):
669 drives.append(volume)