chiark / gitweb /
Added support for comma in numbers instead of a dot.
[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                 setting = getProfileSetting(name).replace(',', '.')\r
278                 return float(eval(setting, {}, {}))\r
279         except (ValueError, SyntaxError, TypeError):\r
280                 return 0.0\r
281 \r
282 def putProfileSetting(name, value):\r
283         #Check if we have a configuration file loaded, else load the default.\r
284         if not globals().has_key('globalProfileParser'):\r
285                 loadGlobalProfile(getDefaultProfilePath())\r
286         if not globalProfileParser.has_section('profile'):\r
287                 globalProfileParser.add_section('profile')\r
288         globalProfileParser.set('profile', name, str(value))\r
289 \r
290 def isProfileSetting(name):\r
291         if name in profileDefaultSettings:\r
292                 return True\r
293         return False\r
294 \r
295 ## Preferences functions\r
296 global globalPreferenceParser\r
297 globalPreferenceParser = None\r
298 \r
299 def getPreferencePath():\r
300         basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))\r
301         #If we have a frozen python install, we need to step out of the library.zip\r
302         if hasattr(sys, 'frozen'):\r
303                 basePath = os.path.normpath(os.path.join(basePath, ".."))\r
304         return os.path.normpath(os.path.join(basePath, "preferences.ini"))\r
305 \r
306 def getPreferenceFloat(name):\r
307         try:\r
308                 setting = getPreference(name).replace(',', '.')\r
309                 return float(eval(setting, {}, {}))\r
310         except (ValueError, SyntaxError, TypeError):\r
311                 return 0.0\r
312 \r
313 def getPreference(name):\r
314         if name in tempOverride:\r
315                 return unicode(tempOverride[name])\r
316         global globalPreferenceParser\r
317         if globalPreferenceParser == None:\r
318                 globalPreferenceParser = ConfigParser.ConfigParser()\r
319                 globalPreferenceParser.read(getPreferencePath())\r
320         if not globalPreferenceParser.has_option('preference', name):\r
321                 if name in preferencesDefaultSettings:\r
322                         default = preferencesDefaultSettings[name]\r
323                 else:\r
324                         print("Missing default setting for: '" + name + "'")\r
325                         preferencesDefaultSettings[name] = ''\r
326                         default = ''\r
327                 if not globalPreferenceParser.has_section('preference'):\r
328                         globalPreferenceParser.add_section('preference')\r
329                 globalPreferenceParser.set('preference', name, str(default))\r
330                 #print(name + " not found in preferences, so using default: " + str(default))\r
331                 return default\r
332         return unicode(globalPreferenceParser.get('preference', name), "utf-8")\r
333 \r
334 def putPreference(name, value):\r
335         #Check if we have a configuration file loaded, else load the default.\r
336         global globalPreferenceParser\r
337         if globalPreferenceParser == None:\r
338                 globalPreferenceParser = ConfigParser.ConfigParser()\r
339                 globalPreferenceParser.read(getPreferencePath())\r
340         if not globalPreferenceParser.has_section('preference'):\r
341                 globalPreferenceParser.add_section('preference')\r
342         globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))\r
343         globalPreferenceParser.write(open(getPreferencePath(), 'w'))\r
344 \r
345 def isPreference(name):\r
346         if name in preferencesDefaultSettings:\r
347                 return True\r
348         return False\r
349 \r
350 ## Temp overrides for multi-extruder slicing and the project planner.\r
351 tempOverride = {}\r
352 def setTempOverride(name, value):\r
353         tempOverride[name] = value\r
354 def resetTempOverride():\r
355         tempOverride.clear()\r
356 \r
357 #########################################################\r
358 ## Utility functions to calculate common profile values\r
359 #########################################################\r
360 def calculateEdgeWidth():\r
361         wallThickness = getProfileSettingFloat('wall_thickness')\r
362         nozzleSize = getProfileSettingFloat('nozzle_size')\r
363         \r
364         if wallThickness < nozzleSize:\r
365                 return wallThickness\r
366 \r
367         lineCount = int(wallThickness / nozzleSize)\r
368         lineWidth = wallThickness / lineCount\r
369         lineWidthAlt = wallThickness / (lineCount + 1)\r
370         if lineWidth > nozzleSize * 1.5:\r
371                 return lineWidthAlt\r
372         return lineWidth\r
373 \r
374 def calculateLineCount():\r
375         wallThickness = getProfileSettingFloat('wall_thickness')\r
376         nozzleSize = getProfileSettingFloat('nozzle_size')\r
377         \r
378         if wallThickness < nozzleSize:\r
379                 return 1\r
380 \r
381         lineCount = int(wallThickness / nozzleSize + 0.0001)\r
382         lineWidth = wallThickness / lineCount\r
383         lineWidthAlt = wallThickness / (lineCount + 1)\r
384         if lineWidth > nozzleSize * 1.5:\r
385                 return lineCount + 1\r
386         return lineCount\r
387 \r
388 def calculateSolidLayerCount():\r
389         layerHeight = getProfileSettingFloat('layer_height')\r
390         solidThickness = getProfileSettingFloat('solid_layer_thickness')\r
391         return int(math.ceil(solidThickness / layerHeight - 0.0001))\r
392 \r
393 #########################################################\r
394 ## Alteration file functions\r
395 #########################################################\r
396 def replaceTagMatch(m):\r
397         pre = m.group(1)\r
398         tag = m.group(2)\r
399         if tag == 'time':\r
400                 return pre + time.strftime('%H:%M:%S')\r
401         if tag == 'date':\r
402                 return pre + time.strftime('%d %b %Y')\r
403         if tag == 'day':\r
404                 return pre + time.strftime('%a')\r
405         if tag == 'print_time':\r
406                 return pre + '#P_TIME#'\r
407         if tag == 'filament_amount':\r
408                 return pre + '#F_AMNT#'\r
409         if tag == 'filament_weight':\r
410                 return pre + '#F_WGHT#'\r
411         if tag == 'filament_cost':\r
412                 return pre + '#F_COST#'\r
413         if pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:\r
414                 f = getProfileSettingFloat(tag) * 60\r
415         elif isProfileSetting(tag):\r
416                 f = getProfileSettingFloat(tag)\r
417         elif isPreference(tag):\r
418                 f = getProfileSettingFloat(tag)\r
419         else:\r
420                 return '%s?%s?' % (pre, tag)\r
421         if (f % 1) == 0:\r
422                 return pre + str(int(f))\r
423         return pre + str(f)\r
424 \r
425 def replaceGCodeTags(filename, gcodeInt):\r
426         f = open(filename, 'r+')\r
427         data = f.read(2048)\r
428         data = data.replace('#P_TIME#', ('%5d:%02d' % (int(gcodeInt.totalMoveTimeMinute / 60), int(gcodeInt.totalMoveTimeMinute % 60)))[-8:])\r
429         data = data.replace('#F_AMNT#', ('%8.2f' % (gcodeInt.extrusionAmount / 1000))[-8:])\r
430         data = data.replace('#F_WGHT#', ('%8.2f' % (gcodeInt.calculateWeight() * 1000))[-8:])\r
431         cost = gcodeInt.calculateCost()\r
432         if cost == False:\r
433                 cost = 'Unknown'\r
434         data = data.replace('#F_COST#', ('%8s' % (cost.split(' ')[0]))[-8:])\r
435         f.seek(0)\r
436         f.write(data)\r
437         f.close()\r
438 \r
439 ### Get aleration raw contents. (Used internally in Cura)\r
440 def getAlterationFile(filename):\r
441         #Check if we have a configuration file loaded, else load the default.\r
442         if not globals().has_key('globalProfileParser'):\r
443                 loadGlobalProfile(getDefaultProfilePath())\r
444         \r
445         if not globalProfileParser.has_option('alterations', filename):\r
446                 if filename in alterationDefault:\r
447                         default = alterationDefault[filename]\r
448                 else:\r
449                         print("Missing default alteration for: '" + filename + "'")\r
450                         alterationDefault[filename] = ''\r
451                         default = ''\r
452                 if not globalProfileParser.has_section('alterations'):\r
453                         globalProfileParser.add_section('alterations')\r
454                 #print("Using default for: %s" % (filename))\r
455                 globalProfileParser.set('alterations', filename, default)\r
456         return unicode(globalProfileParser.get('alterations', filename), "utf-8")\r
457 \r
458 def setAlterationFile(filename, value):\r
459         #Check if we have a configuration file loaded, else load the default.\r
460         if not globals().has_key('globalProfileParser'):\r
461                 loadGlobalProfile(getDefaultProfilePath())\r
462         if not globalProfileParser.has_section('alterations'):\r
463                 globalProfileParser.add_section('alterations')\r
464         globalProfileParser.set('alterations', filename, value.encode("utf-8"))\r
465         saveGlobalProfile(getDefaultProfilePath())\r
466 \r
467 ### Get the alteration file for output. (Used by Skeinforge)\r
468 def getAlterationFileContents(filename):\r
469         prefix = ''\r
470         postfix = ''\r
471         alterationContents = getAlterationFile(filename)\r
472         if filename == 'start.gcode':\r
473                 #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
474                 #We also set our steps per E here, if configured.\r
475                 eSteps = getPreferenceFloat('steps_per_e')\r
476                 if eSteps > 0:\r
477                         prefix += 'M92 E%f\n' % (eSteps)\r
478                 temp = getProfileSettingFloat('print_temperature')\r
479                 if temp > 0 and not '{print_temperature}' in alterationContents:\r
480                         prefix += 'M109 S%f\n' % (temp)\r
481         elif filename == 'end.gcode':\r
482                 #Append the profile string to the end of the GCode, so we can load it from the GCode file later.\r
483                 postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())\r
484         elif filename == 'replace.csv':\r
485                 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.\r
486                 prefix = 'M101\nM103\n'\r
487         \r
488         return unicode(prefix + re.sub("(.)\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).encode('utf-8')\r
489 \r