chiark / gitweb /
ea269d785a245b34472e7a1b9f5afeafbcc46ba0
[cura.git] / Cura / util / profile.py
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
4 import __init__\r
5 \r
6 import os, traceback, math, re, zlib, base64, time, sys\r
7 if sys.version_info[0] < 3:\r
8         import ConfigParser\r
9 else:\r
10         import configparser as ConfigParser\r
11 \r
12 #########################################################\r
13 ## Default settings when none are found.\r
14 #########################################################\r
15 \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
24         'skirt_gap': '3.0',\r
25         'print_speed': '50',\r
26         'print_temperature': '220',\r
27         'print_bed_temperature': '70',\r
28         'support': 'None',\r
29         'filament_diameter': '2.89',\r
30         'filament_density': '1.00',\r
31         'machine_center_x': '100',\r
32         'machine_center_y': '100',\r
33         'retraction_min_travel': '5.0',\r
34         'retraction_enable': 'False',\r
35         'retraction_speed': '40.0',\r
36         'retraction_amount': '4.5',\r
37         'retraction_extra': '0.0',\r
38         'retract_on_jumps_only': 'True',\r
39         'travel_speed': '150',\r
40         'max_z_speed': '3.0',\r
41         'bottom_layer_speed': '20',\r
42         'cool_min_layer_time': '10',\r
43         'fan_enabled': 'True',\r
44         'fan_layer': '1',\r
45         'fan_speed': '100',\r
46         'fan_speed_max': '100',\r
47         'model_scale': '1.0',\r
48         'flip_x': 'False',\r
49         'flip_y': 'False',\r
50         'flip_z': 'False',\r
51         'swap_xz': 'False',\r
52         'swap_yz': 'False',\r
53         'model_rotate_base': '0',\r
54         'model_multiply_x': '1',\r
55         'model_multiply_y': '1',\r
56         'extra_base_wall_thickness': '0.0',\r
57         'sequence': 'Loops > Perimeter > Infill',\r
58         'force_first_layer_sequence': 'True',\r
59         'infill_type': 'Line',\r
60         'solid_top': 'True',\r
61         'fill_overlap': '15',\r
62         'support_rate': '50',\r
63         'support_distance': '0.5',\r
64         'support_dual_extrusion': 'False',\r
65         'joris': 'False',\r
66         'enable_skin': 'False',\r
67         'enable_raft': 'False',\r
68         'cool_min_feedrate': '10',\r
69         'bridge_speed': '100',\r
70         'raft_margin': '5',\r
71         'raft_base_material_amount': '100',\r
72         'raft_interface_material_amount': '100',\r
73         'bottom_thickness': '0.3',\r
74         \r
75         'add_start_end_gcode': 'True',\r
76         'gcode_extension': 'gcode',\r
77         'alternative_center': '',\r
78         'clear_z': '0.0',\r
79         'extruder': '0',\r
80 }\r
81 alterationDefault = {\r
82 #######################################################################################\r
83         'start.gcode': """;Sliced {filename} at: {day} {date} {time}\r
84 ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}\r
85 ;Print time: {print_time}\r
86 ;Filament used: {filament_amount}m {filament_weight}g\r
87 ;Filament cost: {filament_cost}\r
88 G21        ;metric values\r
89 G90        ;absolute positioning\r
90 M107       ;start with the fan off\r
91 \r
92 G28 X0 Y0  ;move X/Y to min endstops\r
93 G28 Z0     ;move Z to min endstops\r
94 G92 X0 Y0 Z0 E0         ;reset software position to front/left/z=0.0\r
95 \r
96 G1 Z15.0 F{max_z_speed} ;move the platform down 15mm\r
97 \r
98 G92 E0                  ;zero the extruded length\r
99 G1 F200 E3              ;extrude 3mm of feed stock\r
100 G92 E0                  ;zero the extruded length again\r
101 \r
102 ;go to the middle of the platform (disabled, as there is no need to go to the center)\r
103 ;G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}\r
104 G1 F{travel_speed}\r
105 """,\r
106 #######################################################################################\r
107         'end.gcode': """;End GCode\r
108 M104 S0                     ;extruder heater off\r
109 M140 S0                     ;heated bed heater off (if you have it)\r
110 \r
111 G91                                    ;relative positioning\r
112 G1 E-1 F300                            ;retract the filament a bit before lifting the nozzle, to release some of the pressure\r
113 G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more\r
114 G28 X0 Y0                              ;move X/Y to min endstops, so the head is out of the way\r
115 \r
116 M84                         ;steppers off\r
117 G90                         ;absolute positioning\r
118 """,\r
119 #######################################################################################\r
120         'support_start.gcode': '',\r
121         'support_end.gcode': '',\r
122         'cool_start.gcode': '',\r
123         'cool_end.gcode': '',\r
124         'replace.csv': '',\r
125 #######################################################################################\r
126         '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
127 G92 E0\r
128 \r
129 G91                                    ;relative positioning\r
130 G1 E-1 F300                            ;retract the filament a bit before lifting the nozzle, to release some of the pressure\r
131 G1 Z+0.5 E-5 F{travel_speed}           ;move Z up a bit and retract filament even more\r
132 G90                                    ;absolute positioning\r
133 \r
134 G1 Z{clear_z} F{max_z_speed}\r
135 G92 E0\r
136 G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}\r
137 G1 F200 E5\r
138 G92 E0\r
139 """,\r
140 #######################################################################################\r
141         'switchExtruder.gcode': """;Switch between the current extruder and the next extruder, when printing with multiple extruders.\r
142 G1 E-5 F5000\r
143 G92 E0\r
144 T{extruder}\r
145 G1 E5 F5000\r
146 G92 E0\r
147 """,\r
148 }\r
149 preferencesDefaultSettings = {\r
150         'wizardDone': 'False',\r
151         'startMode': 'Simple',\r
152         'lastFile': os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'example', 'UltimakerRobot_support.stl')),\r
153         'machine_width': '205',\r
154         'machine_depth': '205',\r
155         'machine_height': '200',\r
156         'machine_type': 'unknown',\r
157         'has_heated_bed': 'False',\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_port_auto': '',\r
169         'serial_baud': 'AUTO',\r
170         'serial_baud_auto': '',\r
171         'slicer': 'Cura (Skeinforge based)',\r
172         'save_profile': 'False',\r
173         'filament_cost_kg': '0',\r
174         'filament_cost_meter': '0',\r
175         'sdpath': '',\r
176         'sdshortnames': 'True',\r
177         \r
178         'extruder_head_size_min_x': '70.0',\r
179         'extruder_head_size_min_y': '18.0',\r
180         'extruder_head_size_max_x': '18.0',\r
181         'extruder_head_size_max_y': '35.0',\r
182         'extruder_head_size_height': '80.0',\r
183         \r
184         'model_colour': '#FFCC99',\r
185         'model_colour2': '#33FF1A',\r
186         'model_colour3': '#FF331A',\r
187         'model_colour4': '#1A33FF',\r
188 }\r
189 \r
190 #########################################################\r
191 ## Profile and preferences functions\r
192 #########################################################\r
193 \r
194 ## Profile functions\r
195 def getDefaultProfilePath():\r
196         basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))\r
197         #If we have a frozen python install, we need to step out of the library.zip\r
198         if hasattr(sys, 'frozen'):\r
199                 basePath = os.path.normpath(os.path.join(basePath, ".."))\r
200         return os.path.normpath(os.path.join(basePath, "current_profile.ini"))\r
201 \r
202 def loadGlobalProfile(filename):\r
203         #Read a configuration file as global config\r
204         global globalProfileParser\r
205         globalProfileParser = ConfigParser.ConfigParser()\r
206         globalProfileParser.read(filename)\r
207 \r
208 def resetGlobalProfile():\r
209         #Read a configuration file as global config\r
210         global globalProfileParser\r
211         globalProfileParser = ConfigParser.ConfigParser()\r
212 \r
213 def saveGlobalProfile(filename):\r
214         #Save the current profile to an ini file\r
215         globalProfileParser.write(open(filename, 'w'))\r
216 \r
217 def loadGlobalProfileFromString(options):\r
218         global globalProfileParser\r
219         globalProfileParser = ConfigParser.ConfigParser()\r
220         globalProfileParser.add_section('profile')\r
221         globalProfileParser.add_section('alterations')\r
222         options = base64.b64decode(options)\r
223         options = zlib.decompress(options)\r
224         (profileOpts, alt) = options.split('\f', 1)\r
225         for option in profileOpts.split('\b'):\r
226                 if len(option) > 0:\r
227                         (key, value) = option.split('=', 1)\r
228                         globalProfileParser.set('profile', key, value)\r
229         for option in alt.split('\b'):\r
230                 if len(option) > 0:\r
231                         (key, value) = option.split('=', 1)\r
232                         globalProfileParser.set('alterations', key, value)\r
233 \r
234 def getGlobalProfileString():\r
235         global globalProfileParser\r
236         if not globals().has_key('globalProfileParser'):\r
237                 loadGlobalProfile(getDefaultProfilePath())\r
238         \r
239         p = []\r
240         alt = []\r
241         tempDone = []\r
242         if globalProfileParser.has_section('profile'):\r
243                 for key in globalProfileParser.options('profile'):\r
244                         if key in tempOverride:\r
245                                 p.append(key + "=" + tempOverride[key])\r
246                                 tempDone.append(key)\r
247                         else:\r
248                                 p.append(key + "=" + globalProfileParser.get('profile', key))\r
249         if globalProfileParser.has_section('alterations'):\r
250                 for key in globalProfileParser.options('alterations'):\r
251                         if key in tempOverride:\r
252                                 p.append(key + "=" + tempOverride[key])\r
253                                 tempDone.append(key)\r
254                         else:\r
255                                 alt.append(key + "=" + globalProfileParser.get('alterations', key))\r
256         for key in tempOverride:\r
257                 if key not in tempDone:\r
258                         p.append(key + "=" + tempOverride[key])\r
259         ret = '\b'.join(p) + '\f' + '\b'.join(alt)\r
260         ret = base64.b64encode(zlib.compress(ret, 9))\r
261         return ret\r
262 \r
263 def getProfileSetting(name):\r
264         if name in tempOverride:\r
265                 return unicode(tempOverride[name], "utf-8")\r
266         #Check if we have a configuration file loaded, else load the default.\r
267         if not globals().has_key('globalProfileParser'):\r
268                 loadGlobalProfile(getDefaultProfilePath())\r
269         if not globalProfileParser.has_option('profile', name):\r
270                 if name in profileDefaultSettings:\r
271                         default = profileDefaultSettings[name]\r
272                 else:\r
273                         print("Missing default setting for: '" + name + "'")\r
274                         profileDefaultSettings[name] = ''\r
275                         default = ''\r
276                 if not globalProfileParser.has_section('profile'):\r
277                         globalProfileParser.add_section('profile')\r
278                 globalProfileParser.set('profile', name, str(default))\r
279                 #print(name + " not found in profile, so using default: " + str(default))\r
280                 return default\r
281         return globalProfileParser.get('profile', name)\r
282 \r
283 def getProfileSettingFloat(name):\r
284         try:\r
285                 setting = getProfileSetting(name).replace(',', '.')\r
286                 return float(eval(setting, {}, {}))\r
287         except (ValueError, SyntaxError, TypeError):\r
288                 return 0.0\r
289 \r
290 def putProfileSetting(name, value):\r
291         #Check if we have a configuration file loaded, else load the default.\r
292         if not globals().has_key('globalProfileParser'):\r
293                 loadGlobalProfile(getDefaultProfilePath())\r
294         if not globalProfileParser.has_section('profile'):\r
295                 globalProfileParser.add_section('profile')\r
296         globalProfileParser.set('profile', name, str(value))\r
297 \r
298 def isProfileSetting(name):\r
299         if name in profileDefaultSettings:\r
300                 return True\r
301         return False\r
302 \r
303 ## Preferences functions\r
304 global globalPreferenceParser\r
305 globalPreferenceParser = None\r
306 \r
307 def getPreferencePath():\r
308         basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))\r
309         #If we have a frozen python install, we need to step out of the library.zip\r
310         if hasattr(sys, 'frozen'):\r
311                 basePath = os.path.normpath(os.path.join(basePath, ".."))\r
312         return os.path.normpath(os.path.join(basePath, "preferences.ini"))\r
313 \r
314 def getPreferenceFloat(name):\r
315         try:\r
316                 setting = getPreference(name).replace(',', '.')\r
317                 return float(eval(setting, {}, {}))\r
318         except (ValueError, SyntaxError, TypeError):\r
319                 return 0.0\r
320 \r
321 def getPreferenceColour(name):\r
322         colorString = getPreference(name)\r
323         return [float(int(colorString[1:3], 16)) / 255, float(int(colorString[3:5], 16)) / 255, float(int(colorString[5:7], 16)) / 255, 1.0]\r
324 \r
325 def getPreference(name):\r
326         if name in tempOverride:\r
327                 return unicode(tempOverride[name])\r
328         global globalPreferenceParser\r
329         if globalPreferenceParser == None:\r
330                 globalPreferenceParser = ConfigParser.ConfigParser()\r
331                 globalPreferenceParser.read(getPreferencePath())\r
332         if not globalPreferenceParser.has_option('preference', name):\r
333                 if name in preferencesDefaultSettings:\r
334                         default = preferencesDefaultSettings[name]\r
335                 else:\r
336                         print("Missing default setting for: '" + name + "'")\r
337                         preferencesDefaultSettings[name] = ''\r
338                         default = ''\r
339                 if not globalPreferenceParser.has_section('preference'):\r
340                         globalPreferenceParser.add_section('preference')\r
341                 globalPreferenceParser.set('preference', name, str(default))\r
342                 #print(name + " not found in preferences, so using default: " + str(default))\r
343                 return default\r
344         return unicode(globalPreferenceParser.get('preference', name), "utf-8")\r
345 \r
346 def putPreference(name, value):\r
347         #Check if we have a configuration file loaded, else load the default.\r
348         global globalPreferenceParser\r
349         if globalPreferenceParser == None:\r
350                 globalPreferenceParser = ConfigParser.ConfigParser()\r
351                 globalPreferenceParser.read(getPreferencePath())\r
352         if not globalPreferenceParser.has_section('preference'):\r
353                 globalPreferenceParser.add_section('preference')\r
354         globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))\r
355         globalPreferenceParser.write(open(getPreferencePath(), 'w'))\r
356 \r
357 def isPreference(name):\r
358         if name in preferencesDefaultSettings:\r
359                 return True\r
360         return False\r
361 \r
362 ## Temp overrides for multi-extruder slicing and the project planner.\r
363 tempOverride = {}\r
364 def setTempOverride(name, value):\r
365         tempOverride[name] = unicode(value).encode("utf-8")\r
366 def clearTempOverride(name):\r
367         del tempOverride[name]\r
368 def resetTempOverride():\r
369         tempOverride.clear()\r
370 \r
371 #########################################################\r
372 ## Utility functions to calculate common profile values\r
373 #########################################################\r
374 def calculateEdgeWidth():\r
375         wallThickness = getProfileSettingFloat('wall_thickness')\r
376         nozzleSize = getProfileSettingFloat('nozzle_size')\r
377         \r
378         if wallThickness < nozzleSize:\r
379                 return wallThickness\r
380 \r
381         lineCount = int(wallThickness / nozzleSize)\r
382         lineWidth = wallThickness / lineCount\r
383         lineWidthAlt = wallThickness / (lineCount + 1)\r
384         if lineWidth > nozzleSize * 1.5:\r
385                 return lineWidthAlt\r
386         return lineWidth\r
387 \r
388 def calculateLineCount():\r
389         wallThickness = getProfileSettingFloat('wall_thickness')\r
390         nozzleSize = getProfileSettingFloat('nozzle_size')\r
391         \r
392         if wallThickness < nozzleSize:\r
393                 return 1\r
394 \r
395         lineCount = int(wallThickness / nozzleSize + 0.0001)\r
396         lineWidth = wallThickness / lineCount\r
397         lineWidthAlt = wallThickness / (lineCount + 1)\r
398         if lineWidth > nozzleSize * 1.5:\r
399                 return lineCount + 1\r
400         return lineCount\r
401 \r
402 def calculateSolidLayerCount():\r
403         layerHeight = getProfileSettingFloat('layer_height')\r
404         solidThickness = getProfileSettingFloat('solid_layer_thickness')\r
405         return int(math.ceil(solidThickness / layerHeight - 0.0001))\r
406 \r
407 #########################################################\r
408 ## Alteration file functions\r
409 #########################################################\r
410 def replaceTagMatch(m):\r
411         pre = m.group(1)\r
412         tag = m.group(2)\r
413         if tag == 'time':\r
414                 return pre + time.strftime('%H:%M:%S')\r
415         if tag == 'date':\r
416                 return pre + time.strftime('%d %b %Y')\r
417         if tag == 'day':\r
418                 return pre + time.strftime('%a')\r
419         if tag == 'print_time':\r
420                 return pre + '#P_TIME#'\r
421         if tag == 'filament_amount':\r
422                 return pre + '#F_AMNT#'\r
423         if tag == 'filament_weight':\r
424                 return pre + '#F_WGHT#'\r
425         if tag == 'filament_cost':\r
426                 return pre + '#F_COST#'\r
427         if pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:\r
428                 f = getProfileSettingFloat(tag) * 60\r
429         elif isProfileSetting(tag):\r
430                 f = getProfileSettingFloat(tag)\r
431         elif isPreference(tag):\r
432                 f = getProfileSettingFloat(tag)\r
433         else:\r
434                 return '%s?%s?' % (pre, tag)\r
435         if (f % 1) == 0:\r
436                 return pre + str(int(f))\r
437         return pre + str(f)\r
438 \r
439 def replaceGCodeTags(filename, gcodeInt):\r
440         f = open(filename, 'r+')\r
441         data = f.read(2048)\r
442         data = data.replace('#P_TIME#', ('%5d:%02d' % (int(gcodeInt.totalMoveTimeMinute / 60), int(gcodeInt.totalMoveTimeMinute % 60)))[-8:])\r
443         data = data.replace('#F_AMNT#', ('%8.2f' % (gcodeInt.extrusionAmount / 1000))[-8:])\r
444         data = data.replace('#F_WGHT#', ('%8.2f' % (gcodeInt.calculateWeight() * 1000))[-8:])\r
445         cost = gcodeInt.calculateCost()\r
446         if cost == False:\r
447                 cost = 'Unknown'\r
448         data = data.replace('#F_COST#', ('%8s' % (cost.split(' ')[0]))[-8:])\r
449         f.seek(0)\r
450         f.write(data)\r
451         f.close()\r
452 \r
453 ### Get aleration raw contents. (Used internally in Cura)\r
454 def getAlterationFile(filename):\r
455         #Check if we have a configuration file loaded, else load the default.\r
456         if not globals().has_key('globalProfileParser'):\r
457                 loadGlobalProfile(getDefaultProfilePath())\r
458         \r
459         if not globalProfileParser.has_option('alterations', filename):\r
460                 if filename in alterationDefault:\r
461                         default = alterationDefault[filename]\r
462                 else:\r
463                         print("Missing default alteration for: '" + filename + "'")\r
464                         alterationDefault[filename] = ''\r
465                         default = ''\r
466                 if not globalProfileParser.has_section('alterations'):\r
467                         globalProfileParser.add_section('alterations')\r
468                 #print("Using default for: %s" % (filename))\r
469                 globalProfileParser.set('alterations', filename, default)\r
470         return unicode(globalProfileParser.get('alterations', filename), "utf-8")\r
471 \r
472 def setAlterationFile(filename, value):\r
473         #Check if we have a configuration file loaded, else load the default.\r
474         if not globals().has_key('globalProfileParser'):\r
475                 loadGlobalProfile(getDefaultProfilePath())\r
476         if not globalProfileParser.has_section('alterations'):\r
477                 globalProfileParser.add_section('alterations')\r
478         globalProfileParser.set('alterations', filename, value.encode("utf-8"))\r
479         saveGlobalProfile(getDefaultProfilePath())\r
480 \r
481 ### Get the alteration file for output. (Used by Skeinforge)\r
482 def getAlterationFileContents(filename):\r
483         prefix = ''\r
484         postfix = ''\r
485         alterationContents = getAlterationFile(filename)\r
486         if filename == 'start.gcode':\r
487                 #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
488                 #We also set our steps per E here, if configured.\r
489                 eSteps = getPreferenceFloat('steps_per_e')\r
490                 if eSteps > 0:\r
491                         prefix += 'M92 E%f\n' % (eSteps)\r
492                 temp = getProfileSettingFloat('print_temperature')\r
493                 bedTemp = 0\r
494                 if getPreference('has_heated_bed') == 'True':\r
495                         bedTemp = getProfileSettingFloat('print_bed_temperature')\r
496                 \r
497                 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:\r
498                         prefix += 'M140 S%f\n' % (bedTemp)\r
499                 if temp > 0 and not '{print_temperature}' in alterationContents:\r
500                         prefix += 'M109 S%f\n' % (temp)\r
501                 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:\r
502                         prefix += 'M190 S%f\n' % (bedTemp)\r
503         elif filename == 'end.gcode':\r
504                 #Append the profile string to the end of the GCode, so we can load it from the GCode file later.\r
505                 postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())\r
506         elif filename == 'replace.csv':\r
507                 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.\r
508                 prefix = 'M101\nM103\n'\r
509         elif filename == 'support_start.gcode' or filename == 'support_end.gcode':\r
510                 #Add support start/end code \r
511                 if getProfileSetting('support_dual_extrusion') == 'True' and int(getPreference('extruder_amount')) > 1:\r
512                         if filename == 'support_start.gcode':\r
513                                 setTempOverride('extruder', '1')\r
514                         else:\r
515                                 setTempOverride('extruder', '0')\r
516                         alterationContents = getAlterationFileContents('switchExtruder.gcode')\r
517                         clearTempOverride('extruder')\r
518                 else:\r
519                         alterationContents = ''\r
520         return unicode(prefix + re.sub("(.)\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).encode('utf-8')\r
521 \r