chiark / gitweb /
Added feature #201 - fixed #201
[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': os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'example', 'UltimakerRobotCourseMesh.stl')),\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_port_auto': '',\r
171         'serial_baud': 'AUTO',\r
172         'serial_baud_auto': '',\r
173         'slicer': 'Cura (Skeinforge based)',\r
174         'save_profile': 'False',\r
175         'filament_cost_kg': '0',\r
176         'filament_cost_meter': '0',\r
177         'sdpath': '',\r
178         'sdshortnames': 'True',\r
179         \r
180         'extruder_head_size_min_x': '70.0',\r
181         'extruder_head_size_min_y': '18.0',\r
182         'extruder_head_size_max_x': '18.0',\r
183         'extruder_head_size_max_y': '35.0',\r
184         'extruder_head_size_height': '80.0',\r
185         \r
186         'model_colour': '#FFCC99',\r
187         'model_colour2': '#33FF1A',\r
188         'model_colour3': '#FF331A',\r
189         'model_colour4': '#1A33FF',\r
190 }\r
191 \r
192 #########################################################\r
193 ## Profile and preferences functions\r
194 #########################################################\r
195 \r
196 ## Profile functions\r
197 def getDefaultProfilePath():\r
198         basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))\r
199         #If we have a frozen python install, we need to step out of the library.zip\r
200         if hasattr(sys, 'frozen'):\r
201                 basePath = os.path.normpath(os.path.join(basePath, ".."))\r
202         return os.path.normpath(os.path.join(basePath, "current_profile.ini"))\r
203 \r
204 def loadGlobalProfile(filename):\r
205         #Read a configuration file as global config\r
206         global globalProfileParser\r
207         globalProfileParser = ConfigParser.ConfigParser()\r
208         globalProfileParser.read(filename)\r
209 \r
210 def resetGlobalProfile():\r
211         #Read a configuration file as global config\r
212         global globalProfileParser\r
213         globalProfileParser = ConfigParser.ConfigParser()\r
214 \r
215 def saveGlobalProfile(filename):\r
216         #Save the current profile to an ini file\r
217         globalProfileParser.write(open(filename, 'w'))\r
218 \r
219 def loadGlobalProfileFromString(options):\r
220         global globalProfileParser\r
221         globalProfileParser = ConfigParser.ConfigParser()\r
222         globalProfileParser.add_section('profile')\r
223         globalProfileParser.add_section('alterations')\r
224         options = base64.b64decode(options)\r
225         options = zlib.decompress(options)\r
226         (profileOpts, alt) = options.split('\f', 1)\r
227         for option in profileOpts.split('\b'):\r
228                 if len(option) > 0:\r
229                         (key, value) = option.split('=', 1)\r
230                         globalProfileParser.set('profile', key, value)\r
231         for option in alt.split('\b'):\r
232                 if len(option) > 0:\r
233                         (key, value) = option.split('=', 1)\r
234                         globalProfileParser.set('alterations', key, value)\r
235 \r
236 def getGlobalProfileString():\r
237         global globalProfileParser\r
238         if not globals().has_key('globalProfileParser'):\r
239                 loadGlobalProfile(getDefaultProfilePath())\r
240         \r
241         p = []\r
242         alt = []\r
243         tempDone = []\r
244         if globalProfileParser.has_section('profile'):\r
245                 for key in globalProfileParser.options('profile'):\r
246                         if key in tempOverride:\r
247                                 p.append(key + "=" + tempOverride[key])\r
248                                 tempDone.append(key)\r
249                         else:\r
250                                 p.append(key + "=" + globalProfileParser.get('profile', key))\r
251         if globalProfileParser.has_section('alterations'):\r
252                 for key in globalProfileParser.options('alterations'):\r
253                         if key in tempOverride:\r
254                                 p.append(key + "=" + tempOverride[key])\r
255                                 tempDone.append(key)\r
256                         else:\r
257                                 alt.append(key + "=" + globalProfileParser.get('alterations', key))\r
258         for key in tempOverride:\r
259                 if key not in tempDone:\r
260                         p.append(key + "=" + tempOverride[key])\r
261         ret = '\b'.join(p) + '\f' + '\b'.join(alt)\r
262         ret = base64.b64encode(zlib.compress(ret, 9))\r
263         return ret\r
264 \r
265 def getProfileSetting(name):\r
266         if name in tempOverride:\r
267                 return unicode(tempOverride[name], "utf-8")\r
268         #Check if we have a configuration file loaded, else load the default.\r
269         if not globals().has_key('globalProfileParser'):\r
270                 loadGlobalProfile(getDefaultProfilePath())\r
271         if not globalProfileParser.has_option('profile', name):\r
272                 if name in profileDefaultSettings:\r
273                         default = profileDefaultSettings[name]\r
274                 else:\r
275                         print("Missing default setting for: '" + name + "'")\r
276                         profileDefaultSettings[name] = ''\r
277                         default = ''\r
278                 if not globalProfileParser.has_section('profile'):\r
279                         globalProfileParser.add_section('profile')\r
280                 globalProfileParser.set('profile', name, str(default))\r
281                 #print(name + " not found in profile, so using default: " + str(default))\r
282                 return default\r
283         return globalProfileParser.get('profile', name)\r
284 \r
285 def getProfileSettingFloat(name):\r
286         try:\r
287                 setting = getProfileSetting(name).replace(',', '.')\r
288                 return float(eval(setting, {}, {}))\r
289         except (ValueError, SyntaxError, TypeError):\r
290                 return 0.0\r
291 \r
292 def putProfileSetting(name, value):\r
293         #Check if we have a configuration file loaded, else load the default.\r
294         if not globals().has_key('globalProfileParser'):\r
295                 loadGlobalProfile(getDefaultProfilePath())\r
296         if not globalProfileParser.has_section('profile'):\r
297                 globalProfileParser.add_section('profile')\r
298         globalProfileParser.set('profile', name, str(value))\r
299 \r
300 def isProfileSetting(name):\r
301         if name in profileDefaultSettings:\r
302                 return True\r
303         return False\r
304 \r
305 ## Preferences functions\r
306 global globalPreferenceParser\r
307 globalPreferenceParser = None\r
308 \r
309 def getPreferencePath():\r
310         basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))\r
311         #If we have a frozen python install, we need to step out of the library.zip\r
312         if hasattr(sys, 'frozen'):\r
313                 basePath = os.path.normpath(os.path.join(basePath, ".."))\r
314         return os.path.normpath(os.path.join(basePath, "preferences.ini"))\r
315 \r
316 def getPreferenceFloat(name):\r
317         try:\r
318                 setting = getPreference(name).replace(',', '.')\r
319                 return float(eval(setting, {}, {}))\r
320         except (ValueError, SyntaxError, TypeError):\r
321                 return 0.0\r
322 \r
323 def getPreferenceColour(name):\r
324         colorString = getPreference(name)\r
325         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
326 \r
327 def getPreference(name):\r
328         if name in tempOverride:\r
329                 return unicode(tempOverride[name])\r
330         global globalPreferenceParser\r
331         if globalPreferenceParser == None:\r
332                 globalPreferenceParser = ConfigParser.ConfigParser()\r
333                 globalPreferenceParser.read(getPreferencePath())\r
334         if not globalPreferenceParser.has_option('preference', name):\r
335                 if name in preferencesDefaultSettings:\r
336                         default = preferencesDefaultSettings[name]\r
337                 else:\r
338                         print("Missing default setting for: '" + name + "'")\r
339                         preferencesDefaultSettings[name] = ''\r
340                         default = ''\r
341                 if not globalPreferenceParser.has_section('preference'):\r
342                         globalPreferenceParser.add_section('preference')\r
343                 globalPreferenceParser.set('preference', name, str(default))\r
344                 #print(name + " not found in preferences, so using default: " + str(default))\r
345                 return default\r
346         return unicode(globalPreferenceParser.get('preference', name), "utf-8")\r
347 \r
348 def putPreference(name, value):\r
349         #Check if we have a configuration file loaded, else load the default.\r
350         global globalPreferenceParser\r
351         if globalPreferenceParser == None:\r
352                 globalPreferenceParser = ConfigParser.ConfigParser()\r
353                 globalPreferenceParser.read(getPreferencePath())\r
354         if not globalPreferenceParser.has_section('preference'):\r
355                 globalPreferenceParser.add_section('preference')\r
356         globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))\r
357         globalPreferenceParser.write(open(getPreferencePath(), 'w'))\r
358 \r
359 def isPreference(name):\r
360         if name in preferencesDefaultSettings:\r
361                 return True\r
362         return False\r
363 \r
364 ## Temp overrides for multi-extruder slicing and the project planner.\r
365 tempOverride = {}\r
366 def setTempOverride(name, value):\r
367         tempOverride[name] = unicode(value).encode("utf-8")\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                         \r
504         elif filename == 'end.gcode':\r
505                 #Append the profile string to the end of the GCode, so we can load it from the GCode file later.\r
506                 postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())\r
507         elif filename == 'replace.csv':\r
508                 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.\r
509                 prefix = 'M101\nM103\n'\r
510         \r
511         return unicode(prefix + re.sub("(.)\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).encode('utf-8')\r
512 \r