chiark / gitweb /
Add support for heated bed temperature setting.
[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': '230',\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_speed': '40.0',\r
35         'retraction_amount': '0.0',\r
36         'retraction_extra': '0.0',\r
37         'retract_on_jumps_only': 'True',\r
38         'travel_speed': '150',\r
39         'max_z_speed': '3.0',\r
40         'bottom_layer_speed': '20',\r
41         'cool_min_layer_time': '10',\r
42         'fan_enabled': 'True',\r
43         'fan_layer': '1',\r
44         'fan_speed': '100',\r
45         'fan_speed_max': '100',\r
46         'model_scale': '1.0',\r
47         'flip_x': 'False',\r
48         'flip_y': 'False',\r
49         'flip_z': 'False',\r
50         'swap_xz': 'False',\r
51         'swap_yz': 'False',\r
52         'model_rotate_base': '0',\r
53         'model_multiply_x': '1',\r
54         'model_multiply_y': '1',\r
55         'extra_base_wall_thickness': '0.0',\r
56         'sequence': 'Loops > Perimeter > Infill',\r
57         'force_first_layer_sequence': 'True',\r
58         'infill_type': 'Line',\r
59         'solid_top': 'True',\r
60         'fill_overlap': '15',\r
61         'support_rate': '50',\r
62         'support_distance': '0.5',\r
63         'joris': 'False',\r
64         'enable_skin': 'False',\r
65         'enable_raft': 'False',\r
66         'cool_min_feedrate': '10',\r
67         'bridge_speed': '100',\r
68         'raft_margin': '5',\r
69         'raft_base_material_amount': '100',\r
70         'raft_interface_material_amount': '100',\r
71         'bottom_thickness': '0.3',\r
72         \r
73         'enable_dwindle': 'False',\r
74         'dwindle_pent_up_volume': '0.4',\r
75         'dwindle_slowdown_volume': '5.0',\r
76 \r
77         'add_start_end_gcode': 'True',\r
78         'gcode_extension': 'gcode',\r
79         'alternative_center': '',\r
80         'clear_z': '0.0',\r
81         'extruder': '0',\r
82 }\r
83 alterationDefault = {\r
84 #######################################################################################\r
85         'start.gcode': """;Sliced {filename} at: {day} {date} {time}\r
86 ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}\r
87 ;Print time: {print_time}\r
88 ;Filament used: {filament_amount}m {filament_weight}g\r
89 ;Filament cost: {filament_cost}\r
90 G21        ;metric values\r
91 G90        ;absolute positioning\r
92 M107       ;start with the fan off\r
93 \r
94 G28 X0 Y0  ;move X/Y to min endstops\r
95 G28 Z0     ;move Z to min endstops\r
96 G92 X0 Y0 Z0 E0         ;reset software position to front/left/z=0.0\r
97 \r
98 G1 Z15.0 F{max_z_speed} ;move the platform down 15mm\r
99 \r
100 G92 E0                  ;zero the extruded length\r
101 G1 F200 E3              ;extrude 3mm of feed stock\r
102 G92 E0                  ;zero the extruded length again\r
103 \r
104 ;go to the middle of the platform (disabled, as there is no need to go to the center)\r
105 ;G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}\r
106 G1 F{travel_speed}\r
107 """,\r
108 #######################################################################################\r
109         'end.gcode': """;End GCode\r
110 M104 S0                     ;extruder heater off\r
111 M140 S0                     ;heated bed heater off (if you have it)\r
112 \r
113 G91                                    ;relative positioning\r
114 G1 E-1 F300                            ;retract the filament a bit before lifting the nozzle, to release some of the pressure\r
115 G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more\r
116 G28 X0 Y0                              ;move X/Y to min endstops, so the head is out of the way\r
117 \r
118 M84                         ;steppers off\r
119 G90                         ;absolute positioning\r
120 """,\r
121 #######################################################################################\r
122         'support_start.gcode': '',\r
123         'support_end.gcode': '',\r
124         'cool_start.gcode': '',\r
125         'cool_end.gcode': '',\r
126         'replace.csv': '',\r
127 #######################################################################################\r
128         '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
129 G92 E0\r
130 \r
131 G91                                    ;relative positioning\r
132 G1 E-1 F300                            ;retract the filament a bit before lifting the nozzle, to release some of the pressure\r
133 G1 Z+0.5 E-5 F{travel_speed}           ;move Z up a bit and retract filament even more\r
134 G90                                    ;absolute positioning\r
135 \r
136 G1 Z{clear_z} F{max_z_speed}\r
137 G92 E0\r
138 G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}\r
139 G1 F200 E5\r
140 G92 E0\r
141 """,\r
142 #######################################################################################\r
143         'switchExtruder.gcode': """;Switch between the current extruder and the next extruder, when printing with multiple extruders.\r
144 G1 E-5 F5000\r
145 G92 E0\r
146 T{extruder}\r
147 G1 E5 F5000\r
148 G92 E0\r
149 """,\r
150 }\r
151 preferencesDefaultSettings = {\r
152         'wizardDone': 'False',\r
153         'startMode': 'Simple',\r
154         'lastFile': '',\r
155         'machine_width': '205',\r
156         'machine_depth': '205',\r
157         'machine_height': '200',\r
158         'machine_type': 'unknown',\r
159         'has_heated_bed': 'False',\r
160         'extruder_amount': '1',\r
161         'extruder_offset_x1': '-22.0',\r
162         'extruder_offset_y1': '0.0',\r
163         'extruder_offset_x2': '0.0',\r
164         'extruder_offset_y2': '0.0',\r
165         'extruder_offset_x3': '0.0',\r
166         'extruder_offset_y3': '0.0',\r
167         'filament_density': '1300',\r
168         'steps_per_e': '0',\r
169         'serial_port': '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 + "=" + unicode(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 + "=" + unicode(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])\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] = value\r
366 def resetTempOverride():\r
367         tempOverride.clear()\r
368 \r
369 #########################################################\r
370 ## Utility functions to calculate common profile values\r
371 #########################################################\r
372 def calculateEdgeWidth():\r
373         wallThickness = getProfileSettingFloat('wall_thickness')\r
374         nozzleSize = getProfileSettingFloat('nozzle_size')\r
375         \r
376         if wallThickness < nozzleSize:\r
377                 return wallThickness\r
378 \r
379         lineCount = int(wallThickness / nozzleSize)\r
380         lineWidth = wallThickness / lineCount\r
381         lineWidthAlt = wallThickness / (lineCount + 1)\r
382         if lineWidth > nozzleSize * 1.5:\r
383                 return lineWidthAlt\r
384         return lineWidth\r
385 \r
386 def calculateLineCount():\r
387         wallThickness = getProfileSettingFloat('wall_thickness')\r
388         nozzleSize = getProfileSettingFloat('nozzle_size')\r
389         \r
390         if wallThickness < nozzleSize:\r
391                 return 1\r
392 \r
393         lineCount = int(wallThickness / nozzleSize + 0.0001)\r
394         lineWidth = wallThickness / lineCount\r
395         lineWidthAlt = wallThickness / (lineCount + 1)\r
396         if lineWidth > nozzleSize * 1.5:\r
397                 return lineCount + 1\r
398         return lineCount\r
399 \r
400 def calculateSolidLayerCount():\r
401         layerHeight = getProfileSettingFloat('layer_height')\r
402         solidThickness = getProfileSettingFloat('solid_layer_thickness')\r
403         return int(math.ceil(solidThickness / layerHeight - 0.0001))\r
404 \r
405 #########################################################\r
406 ## Alteration file functions\r
407 #########################################################\r
408 def replaceTagMatch(m):\r
409         pre = m.group(1)\r
410         tag = m.group(2)\r
411         if tag == 'time':\r
412                 return pre + time.strftime('%H:%M:%S')\r
413         if tag == 'date':\r
414                 return pre + time.strftime('%d %b %Y')\r
415         if tag == 'day':\r
416                 return pre + time.strftime('%a')\r
417         if tag == 'print_time':\r
418                 return pre + '#P_TIME#'\r
419         if tag == 'filament_amount':\r
420                 return pre + '#F_AMNT#'\r
421         if tag == 'filament_weight':\r
422                 return pre + '#F_WGHT#'\r
423         if tag == 'filament_cost':\r
424                 return pre + '#F_COST#'\r
425         if pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:\r
426                 f = getProfileSettingFloat(tag) * 60\r
427         elif isProfileSetting(tag):\r
428                 f = getProfileSettingFloat(tag)\r
429         elif isPreference(tag):\r
430                 f = getProfileSettingFloat(tag)\r
431         else:\r
432                 return '%s?%s?' % (pre, tag)\r
433         if (f % 1) == 0:\r
434                 return pre + str(int(f))\r
435         return pre + str(f)\r
436 \r
437 def replaceGCodeTags(filename, gcodeInt):\r
438         f = open(filename, 'r+')\r
439         data = f.read(2048)\r
440         data = data.replace('#P_TIME#', ('%5d:%02d' % (int(gcodeInt.totalMoveTimeMinute / 60), int(gcodeInt.totalMoveTimeMinute % 60)))[-8:])\r
441         data = data.replace('#F_AMNT#', ('%8.2f' % (gcodeInt.extrusionAmount / 1000))[-8:])\r
442         data = data.replace('#F_WGHT#', ('%8.2f' % (gcodeInt.calculateWeight() * 1000))[-8:])\r
443         cost = gcodeInt.calculateCost()\r
444         if cost == False:\r
445                 cost = 'Unknown'\r
446         data = data.replace('#F_COST#', ('%8s' % (cost.split(' ')[0]))[-8:])\r
447         f.seek(0)\r
448         f.write(data)\r
449         f.close()\r
450 \r
451 ### Get aleration raw contents. (Used internally in Cura)\r
452 def getAlterationFile(filename):\r
453         #Check if we have a configuration file loaded, else load the default.\r
454         if not globals().has_key('globalProfileParser'):\r
455                 loadGlobalProfile(getDefaultProfilePath())\r
456         \r
457         if not globalProfileParser.has_option('alterations', filename):\r
458                 if filename in alterationDefault:\r
459                         default = alterationDefault[filename]\r
460                 else:\r
461                         print("Missing default alteration for: '" + filename + "'")\r
462                         alterationDefault[filename] = ''\r
463                         default = ''\r
464                 if not globalProfileParser.has_section('alterations'):\r
465                         globalProfileParser.add_section('alterations')\r
466                 #print("Using default for: %s" % (filename))\r
467                 globalProfileParser.set('alterations', filename, default)\r
468         return unicode(globalProfileParser.get('alterations', filename), "utf-8")\r
469 \r
470 def setAlterationFile(filename, value):\r
471         #Check if we have a configuration file loaded, else load the default.\r
472         if not globals().has_key('globalProfileParser'):\r
473                 loadGlobalProfile(getDefaultProfilePath())\r
474         if not globalProfileParser.has_section('alterations'):\r
475                 globalProfileParser.add_section('alterations')\r
476         globalProfileParser.set('alterations', filename, value.encode("utf-8"))\r
477         saveGlobalProfile(getDefaultProfilePath())\r
478 \r
479 ### Get the alteration file for output. (Used by Skeinforge)\r
480 def getAlterationFileContents(filename):\r
481         prefix = ''\r
482         postfix = ''\r
483         alterationContents = getAlterationFile(filename)\r
484         if filename == 'start.gcode':\r
485                 #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
486                 #We also set our steps per E here, if configured.\r
487                 eSteps = getPreferenceFloat('steps_per_e')\r
488                 if eSteps > 0:\r
489                         prefix += 'M92 E%f\n' % (eSteps)\r
490                 temp = getProfileSettingFloat('print_temperature')\r
491                 bedTemp = 0\r
492                 if getPreference('has_heated_bed') == 'True':\r
493                         bedTemp = getProfileSettingFloat('print_bed_temperature')\r
494                 \r
495                 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:\r
496                         prefix += 'M140 S%f\n' % (bedTemp)\r
497                 if temp > 0 and not '{print_temperature}' in alterationContents:\r
498                         prefix += 'M109 S%f\n' % (temp)\r
499                 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:\r
500                         prefix += 'M190 S%f\n' % (bedTemp)\r
501                         \r
502         elif filename == 'end.gcode':\r
503                 #Append the profile string to the end of the GCode, so we can load it from the GCode file later.\r
504                 postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())\r
505         elif filename == 'replace.csv':\r
506                 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.\r
507                 prefix = 'M101\nM103\n'\r
508         \r
509         return unicode(prefix + re.sub("(.)\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).encode('utf-8')\r
510 \r