chiark / gitweb /
#169 - Set the temperature for the next object when using the project planner. Also...
[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         'support': 'None',\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
42         'fan_layer': '1',\r
43         'fan_speed': '100',\r
44         'fan_speed_max': '100',\r
45         'model_scale': '1.0',\r
46         'flip_x': 'False',\r
47         'flip_y': 'False',\r
48         'flip_z': 'False',\r
49         'swap_xz': 'False',\r
50         'swap_yz': 'False',\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
62         'joris': 'False',\r
63         'enable_skin': 'False',\r
64         'enable_raft': 'False',\r
65         'cool_min_feedrate': '5',\r
66         'bridge_speed': '100',\r
67         'raft_margin': '5',\r
68         'raft_base_material_amount': '100',\r
69         'raft_interface_material_amount': '100',\r
70         'bottom_thickness': '0.3',\r
71         \r
72         'enable_dwindle': 'False',\r
73         'dwindle_pent_up_volume': '0.4',\r
74         'dwindle_slowdown_volume': '5.0',\r
75 \r
76         'add_start_end_gcode': 'True',\r
77         'gcode_extension': 'gcode',\r
78         'alternative_center': '',\r
79         'clear_z': '0.0',\r
80         'extruder': '0',\r
81 }\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
89 G21        ;metric values\r
90 G90        ;absolute positioning\r
91 M107       ;start with the fan off\r
92 \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
96 \r
97 G1 Z15.0 F{max_z_speed} ;move the platform down 15mm\r
98 \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
102 \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
105 G1 F{travel_speed}\r
106 """,\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
111 \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
116 \r
117 M84                         ;steppers off\r
118 G90                         ;absolute positioning\r
119 """,\r
120 #######################################################################################\r
121         'support_start.gcode': '',\r
122         'support_end.gcode': '',\r
123         'cool_start.gcode': '',\r
124         'cool_end.gcode': '',\r
125         'replace.csv': '',\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
128 G92 E0\r
129 \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
134 \r
135 G1 Z{clear_z} F{max_z_speed}\r
136 G92 E0\r
137 G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}\r
138 G1 F200 E5\r
139 G92 E0\r
140 """,\r
141 #######################################################################################\r
142         'switchExtruder.gcode': """;Switch between the current extruder and the next extruder, when printing with multiple extruders.\r
143 G1 E-5 F5000\r
144 G92 E0\r
145 T{extruder}\r
146 G1 E5 F5000\r
147 G92 E0\r
148 """,\r
149 }\r
150 preferencesDefaultSettings = {\r
151         'wizardDone': 'False',\r
152         'startMode': 'Simple',\r
153         'lastFile': '',\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
173         'sdpath': '',\r
174         'sdshortnames': 'True',\r
175         \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 }\r
181 \r
182 #########################################################\r
183 ## Profile and preferences functions\r
184 #########################################################\r
185 \r
186 ## Profile functions\r
187 def getDefaultProfilePath():\r
188         basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))\r
189         #If we have a frozen python install, we need to step out of the library.zip\r
190         if hasattr(sys, 'frozen'):\r
191                 basePath = os.path.normpath(os.path.join(basePath, ".."))\r
192         return os.path.normpath(os.path.join(basePath, "current_profile.ini"))\r
193 \r
194 def loadGlobalProfile(filename):\r
195         #Read a configuration file as global config\r
196         global globalProfileParser\r
197         globalProfileParser = ConfigParser.ConfigParser()\r
198         globalProfileParser.read(filename)\r
199 \r
200 def resetGlobalProfile():\r
201         #Read a configuration file as global config\r
202         global globalProfileParser\r
203         globalProfileParser = ConfigParser.ConfigParser()\r
204 \r
205 def saveGlobalProfile(filename):\r
206         #Save the current profile to an ini file\r
207         globalProfileParser.write(open(filename, 'w'))\r
208 \r
209 def loadGlobalProfileFromString(options):\r
210         global globalProfileParser\r
211         globalProfileParser = ConfigParser.ConfigParser()\r
212         globalProfileParser.add_section('profile')\r
213         globalProfileParser.add_section('alterations')\r
214         options = base64.b64decode(options)\r
215         options = zlib.decompress(options)\r
216         (profileOpts, alt) = options.split('\f', 1)\r
217         for option in profileOpts.split('\b'):\r
218                 if len(option) > 0:\r
219                         (key, value) = option.split('=', 1)\r
220                         globalProfileParser.set('profile', key, value)\r
221         for option in alt.split('\b'):\r
222                 if len(option) > 0:\r
223                         (key, value) = option.split('=', 1)\r
224                         globalProfileParser.set('alterations', key, value)\r
225 \r
226 def getGlobalProfileString():\r
227         global globalProfileParser\r
228         if not globals().has_key('globalProfileParser'):\r
229                 loadGlobalProfile(getDefaultProfilePath())\r
230         \r
231         p = []\r
232         alt = []\r
233         tempDone = []\r
234         if globalProfileParser.has_section('profile'):\r
235                 for key in globalProfileParser.options('profile'):\r
236                         if key in tempOverride:\r
237                                 p.append(key + "=" + unicode(tempOverride[key]))\r
238                                 tempDone.append(key)\r
239                         else:\r
240                                 p.append(key + "=" + globalProfileParser.get('profile', key))\r
241         if globalProfileParser.has_section('alterations'):\r
242                 for key in globalProfileParser.options('alterations'):\r
243                         if key in tempOverride:\r
244                                 p.append(key + "=" + tempOverride[key])\r
245                                 tempDone.append(key)\r
246                         else:\r
247                                 alt.append(key + "=" + globalProfileParser.get('alterations', key))\r
248         for key in tempOverride:\r
249                 if key not in tempDone:\r
250                         p.append(key + "=" + unicode(tempOverride[key]))\r
251         ret = '\b'.join(p) + '\f' + '\b'.join(alt)\r
252         ret = base64.b64encode(zlib.compress(ret, 9))\r
253         return ret\r
254 \r
255 def getProfileSetting(name):\r
256         if name in tempOverride:\r
257                 return unicode(tempOverride[name])\r
258         #Check if we have a configuration file loaded, else load the default.\r
259         if not globals().has_key('globalProfileParser'):\r
260                 loadGlobalProfile(getDefaultProfilePath())\r
261         if not globalProfileParser.has_option('profile', name):\r
262                 if name in profileDefaultSettings:\r
263                         default = profileDefaultSettings[name]\r
264                 else:\r
265                         print("Missing default setting for: '" + name + "'")\r
266                         profileDefaultSettings[name] = ''\r
267                         default = ''\r
268                 if not globalProfileParser.has_section('profile'):\r
269                         globalProfileParser.add_section('profile')\r
270                 globalProfileParser.set('profile', name, str(default))\r
271                 #print(name + " not found in profile, so using default: " + str(default))\r
272                 return default\r
273         return globalProfileParser.get('profile', name)\r
274 \r
275 def getProfileSettingFloat(name):\r
276         try:\r
277                 return float(eval(getProfileSetting(name), {}, {}))\r
278         except (ValueError, SyntaxError, TypeError):\r
279                 return 0.0\r
280 \r
281 def putProfileSetting(name, value):\r
282         #Check if we have a configuration file loaded, else load the default.\r
283         if not globals().has_key('globalProfileParser'):\r
284                 loadGlobalProfile(getDefaultProfilePath())\r
285         if not globalProfileParser.has_section('profile'):\r
286                 globalProfileParser.add_section('profile')\r
287         globalProfileParser.set('profile', name, str(value))\r
288 \r
289 def isProfileSetting(name):\r
290         if name in profileDefaultSettings:\r
291                 return True\r
292         return False\r
293 \r
294 ## Preferences functions\r
295 global globalPreferenceParser\r
296 globalPreferenceParser = None\r
297 \r
298 def getPreferencePath():\r
299         basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))\r
300         #If we have a frozen python install, we need to step out of the library.zip\r
301         if hasattr(sys, 'frozen'):\r
302                 basePath = os.path.normpath(os.path.join(basePath, ".."))\r
303         return os.path.normpath(os.path.join(basePath, "preferences.ini"))\r
304 \r
305 def getPreferenceFloat(name):\r
306         try:\r
307                 return float(eval(getPreference(name), {}, {}))\r
308         except (ValueError, SyntaxError, TypeError):\r
309                 return 0.0\r
310 \r
311 def getPreference(name):\r
312         if name in tempOverride:\r
313                 return unicode(tempOverride[name])\r
314         global globalPreferenceParser\r
315         if globalPreferenceParser == None:\r
316                 globalPreferenceParser = ConfigParser.ConfigParser()\r
317                 globalPreferenceParser.read(getPreferencePath())\r
318         if not globalPreferenceParser.has_option('preference', name):\r
319                 if name in preferencesDefaultSettings:\r
320                         default = preferencesDefaultSettings[name]\r
321                 else:\r
322                         print("Missing default setting for: '" + name + "'")\r
323                         preferencesDefaultSettings[name] = ''\r
324                         default = ''\r
325                 if not globalPreferenceParser.has_section('preference'):\r
326                         globalPreferenceParser.add_section('preference')\r
327                 globalPreferenceParser.set('preference', name, str(default))\r
328                 #print(name + " not found in preferences, so using default: " + str(default))\r
329                 return default\r
330         return unicode(globalPreferenceParser.get('preference', name), "utf-8")\r
331 \r
332 def putPreference(name, value):\r
333         #Check if we have a configuration file loaded, else load the default.\r
334         global globalPreferenceParser\r
335         if globalPreferenceParser == None:\r
336                 globalPreferenceParser = ConfigParser.ConfigParser()\r
337                 globalPreferenceParser.read(getPreferencePath())\r
338         if not globalPreferenceParser.has_section('preference'):\r
339                 globalPreferenceParser.add_section('preference')\r
340         globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))\r
341         globalPreferenceParser.write(open(getPreferencePath(), 'w'))\r
342 \r
343 def isPreference(name):\r
344         if name in preferencesDefaultSettings:\r
345                 return True\r
346         return False\r
347 \r
348 ## Temp overrides for multi-extruder slicing and the project planner.\r
349 tempOverride = {}\r
350 def setTempOverride(name, value):\r
351         tempOverride[name] = value\r
352 def resetTempOverride():\r
353         tempOverride.clear()\r
354 \r
355 #########################################################\r
356 ## Utility functions to calculate common profile values\r
357 #########################################################\r
358 def calculateEdgeWidth():\r
359         wallThickness = getProfileSettingFloat('wall_thickness')\r
360         nozzleSize = getProfileSettingFloat('nozzle_size')\r
361         \r
362         if wallThickness < nozzleSize:\r
363                 return wallThickness\r
364 \r
365         lineCount = int(wallThickness / nozzleSize)\r
366         lineWidth = wallThickness / lineCount\r
367         lineWidthAlt = wallThickness / (lineCount + 1)\r
368         if lineWidth > nozzleSize * 1.5:\r
369                 return lineWidthAlt\r
370         return lineWidth\r
371 \r
372 def calculateLineCount():\r
373         wallThickness = getProfileSettingFloat('wall_thickness')\r
374         nozzleSize = getProfileSettingFloat('nozzle_size')\r
375         \r
376         if wallThickness < nozzleSize:\r
377                 return 1\r
378 \r
379         lineCount = int(wallThickness / nozzleSize + 0.0001)\r
380         lineWidth = wallThickness / lineCount\r
381         lineWidthAlt = wallThickness / (lineCount + 1)\r
382         if lineWidth > nozzleSize * 1.5:\r
383                 return lineCount + 1\r
384         return lineCount\r
385 \r
386 def calculateSolidLayerCount():\r
387         layerHeight = getProfileSettingFloat('layer_height')\r
388         solidThickness = getProfileSettingFloat('solid_layer_thickness')\r
389         return int(math.ceil(solidThickness / layerHeight - 0.0001))\r
390 \r
391 #########################################################\r
392 ## Alteration file functions\r
393 #########################################################\r
394 def replaceTagMatch(m):\r
395         pre = m.group(1)\r
396         tag = m.group(2)\r
397         if tag == 'time':\r
398                 return pre + time.strftime('%H:%M:%S')\r
399         if tag == 'date':\r
400                 return pre + time.strftime('%d %b %Y')\r
401         if tag == 'day':\r
402                 return pre + time.strftime('%a')\r
403         if tag == 'print_time':\r
404                 return pre + '#P_TIME#'\r
405         if tag == 'filament_amount':\r
406                 return pre + '#F_AMNT#'\r
407         if tag == 'filament_weight':\r
408                 return pre + '#F_WGHT#'\r
409         if tag == 'filament_cost':\r
410                 return pre + '#F_COST#'\r
411         if pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:\r
412                 f = getProfileSettingFloat(tag) * 60\r
413         elif isProfileSetting(tag):\r
414                 f = getProfileSettingFloat(tag)\r
415         elif isPreference(tag):\r
416                 f = getProfileSettingFloat(tag)\r
417         else:\r
418                 return '%s?%s?' % (pre, tag)\r
419         if (f % 1) == 0:\r
420                 return pre + str(int(f))\r
421         return pre + str(f)\r
422 \r
423 def replaceGCodeTags(filename, gcodeInt):\r
424         f = open(filename, 'r+')\r
425         data = f.read(2048)\r
426         data = data.replace('#P_TIME#', ('%5d:%02d' % (int(gcodeInt.totalMoveTimeMinute / 60), int(gcodeInt.totalMoveTimeMinute % 60)))[-8:])\r
427         data = data.replace('#F_AMNT#', ('%8.2f' % (gcodeInt.extrusionAmount / 1000))[-8:])\r
428         data = data.replace('#F_WGHT#', ('%8.2f' % (gcodeInt.calculateWeight() * 1000))[-8:])\r
429         cost = gcodeInt.calculateCost()\r
430         if cost == False:\r
431                 cost = 'Unknown'\r
432         data = data.replace('#F_COST#', ('%8s' % (cost.split(' ')[0]))[-8:])\r
433         f.seek(0)\r
434         f.write(data)\r
435         f.close()\r
436 \r
437 ### Get aleration raw contents. (Used internally in Cura)\r
438 def getAlterationFile(filename):\r
439         #Check if we have a configuration file loaded, else load the default.\r
440         if not globals().has_key('globalProfileParser'):\r
441                 loadGlobalProfile(getDefaultProfilePath())\r
442         \r
443         if not globalProfileParser.has_option('alterations', filename):\r
444                 if filename in alterationDefault:\r
445                         default = alterationDefault[filename]\r
446                 else:\r
447                         print("Missing default alteration for: '" + filename + "'")\r
448                         alterationDefault[filename] = ''\r
449                         default = ''\r
450                 if not globalProfileParser.has_section('alterations'):\r
451                         globalProfileParser.add_section('alterations')\r
452                 #print("Using default for: %s" % (filename))\r
453                 globalProfileParser.set('alterations', filename, default)\r
454         return unicode(globalProfileParser.get('alterations', filename), "utf-8")\r
455 \r
456 def setAlterationFile(filename, value):\r
457         #Check if we have a configuration file loaded, else load the default.\r
458         if not globals().has_key('globalProfileParser'):\r
459                 loadGlobalProfile(getDefaultProfilePath())\r
460         if not globalProfileParser.has_section('alterations'):\r
461                 globalProfileParser.add_section('alterations')\r
462         globalProfileParser.set('alterations', filename, value.encode("utf-8"))\r
463         saveGlobalProfile(getDefaultProfilePath())\r
464 \r
465 ### Get the alteration file for output. (Used by Skeinforge)\r
466 def getAlterationFileContents(filename):\r
467         prefix = ''\r
468         postfix = ''\r
469         alterationContents = getAlterationFile(filename)\r
470         if filename == 'start.gcode':\r
471                 #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
472                 #We also set our steps per E here, if configured.\r
473                 eSteps = getPreferenceFloat('steps_per_e')\r
474                 if eSteps > 0:\r
475                         prefix += 'M92 E%f\n' % (eSteps)\r
476                 temp = getProfileSettingFloat('print_temperature')\r
477                 if temp > 0 and not '{print_temperature}' in alterationContents:\r
478                         prefix += 'M109 S%f\n' % (temp)\r
479         elif filename == 'end.gcode':\r
480                 #Append the profile string to the end of the GCode, so we can load it from the GCode file later.\r
481                 postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())\r
482         elif filename == 'replace.csv':\r
483                 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.\r
484                 prefix = 'M101\nM103\n'\r
485         \r
486         return unicode(prefix + re.sub("(.)\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).encode('utf-8')\r
487 \r