chiark / gitweb /
Merge branch 'master' of github.com:daid/Cura
[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.major < 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': '0',\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         'model_scale': '1.0',\r
45         'flip_x': 'False',\r
46         'flip_y': 'False',\r
47         'flip_z': 'False',\r
48         'swap_xz': 'False',\r
49         'swap_yz': 'False',\r
50         'model_rotate_base': '0',\r
51         'model_multiply_x': '1',\r
52         'model_multiply_y': '1',\r
53         'extra_base_wall_thickness': '0.0',\r
54         'sequence': 'Loops > Perimeter > Infill',\r
55         'force_first_layer_sequence': 'True',\r
56         'infill_type': 'Line',\r
57         'solid_top': 'True',\r
58         'fill_overlap': '15',\r
59         'support_rate': '50',\r
60         'support_distance': '0.5',\r
61         'joris': 'False',\r
62         'enable_skin': 'False',\r
63         'enable_raft': 'False',\r
64         'cool_min_feedrate': '5',\r
65         'bridge_speed': '100',\r
66         'raft_margin': '5',\r
67         'raft_base_material_amount': '100',\r
68         'raft_interface_material_amount': '100',\r
69         'bottom_thickness': '0.3',\r
70         \r
71         'enable_dwindle': 'False',\r
72         'dwindle_pent_up_volume': '0.4',\r
73         'dwindle_slowdown_volume': '5.0',\r
74 \r
75         'add_start_end_gcode': 'True',\r
76         'gcode_extension': 'gcode',\r
77         'alternative_center': '',\r
78         'clear_z': '0.0',\r
79         'extruder': '0',\r
80 }\r
81 alterationDefault = {\r
82 #######################################################################################\r
83         'start.gcode': """;Sliced at: {day} {date} {time}\r
84 ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}\r
85 G21        ;metric values\r
86 G90        ;absolute positioning\r
87 M107       ;start with the fan off\r
88 \r
89 G28 X0 Y0  ;move X/Y to min endstops\r
90 G28 Z0     ;move Z to min endstops\r
91 \r
92 ; if your prints start too high, try changing the Z0.0 below\r
93 ; to Z1.0 - the number after the Z is the actual, physical\r
94 ; height of the nozzle in mm. This can take some messing around\r
95 ; with to get just right...\r
96 G92 X0 Y0 Z0 E0         ;reset software position to front/left/z=0.0\r
97 G1 Z15.0 F{max_z_speed} ;move the platform down 15mm\r
98 G92 E0                  ;zero the extruded length\r
99 \r
100 G1 F200 E5              ;extrude 5mm of feed stock\r
101 G1 F200 E3.5            ;reverse feed stock by 1.5mm\r
102 G92 E0                  ;zero the extruded length again\r
103 \r
104 ;go to the middle of the platform, and move to Z=0 before starting the print.\r
105 G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}\r
106 G1 Z0.0 F{max_z_speed}\r
107 """,\r
108 #######################################################################################\r
109         'end.gcode': """;End GCode\r
110 M104 S0                    ;extruder heat off\r
111 G91                        ;relative positioning\r
112 G1 Z+10 E-5 F{max_z_speed} ;move Z up a bit and retract filament by 5mm\r
113 G28 X0 Y0                  ;move X/Y to min endstops, so the head is out of the way\r
114 M84                        ;steppers off\r
115 G90                        ;absolute positioning\r
116 """,\r
117 #######################################################################################\r
118         'support_start.gcode': '',\r
119         'support_end.gcode': '',\r
120         'cool_start.gcode': '',\r
121         'cool_end.gcode': '',\r
122         'replace.csv': '',\r
123 #######################################################################################\r
124         '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
125 G92 E0\r
126 G1 Z{clear_z} E-5 F{max_z_speed}\r
127 G92 E0\r
128 G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}\r
129 G1 F200 E5.5\r
130 G92 E0\r
131 G1 Z0 F{max_z_speed}\r
132 """,\r
133 #######################################################################################\r
134         'switchExtruder.gcode': """;Switch between the current extruder and the next extruder, when printing with multiple extruders.\r
135 G1 E-5 F5000\r
136 G92 E0\r
137 T{extruder}\r
138 G1 E5 F5000\r
139 G92 E0\r
140 """,\r
141 }\r
142 preferencesDefaultSettings = {\r
143         'wizardDone': 'False',\r
144         'startMode': 'Simple',\r
145         'lastFile': '',\r
146         'machine_width': '205',\r
147         'machine_depth': '205',\r
148         'machine_height': '200',\r
149         'extruder_amount': '1',\r
150         'extruder_offset_x1': '-22.0',\r
151         'extruder_offset_y1': '0.0',\r
152         'extruder_offset_x2': '0.0',\r
153         'extruder_offset_y2': '0.0',\r
154         'extruder_offset_x3': '0.0',\r
155         'extruder_offset_y3': '0.0',\r
156         'filament_density': '1300',\r
157         'steps_per_e': '0',\r
158         'serial_port': 'AUTO',\r
159         'serial_baud': '250000',\r
160         'slicer': 'Cura (Skeinforge based)',\r
161         'save_profile': 'False',\r
162         'filament_cost_kg': '0',\r
163         'filament_cost_meter': '0',\r
164         \r
165         'extruder_head_size_min_x': '70.0',\r
166         'extruder_head_size_min_y': '18.0',\r
167         'extruder_head_size_max_x': '18.0',\r
168         'extruder_head_size_max_y': '35.0',\r
169 }\r
170 \r
171 #########################################################\r
172 ## Profile and preferences functions\r
173 #########################################################\r
174 \r
175 ## Profile functions\r
176 def getDefaultProfilePath():\r
177         basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))\r
178         #If we have a frozen python install, we need to step out of the library.zip\r
179         if hasattr(sys, 'frozen'):\r
180                 basePath = os.path.normpath(os.path.join(basePath, ".."))\r
181         return os.path.normpath(os.path.join(basePath, "current_profile.ini"))\r
182 \r
183 def loadGlobalProfile(filename):\r
184         #Read a configuration file as global config\r
185         global globalProfileParser\r
186         globalProfileParser = ConfigParser.ConfigParser()\r
187         globalProfileParser.read(filename)\r
188 \r
189 def resetGlobalProfile():\r
190         #Read a configuration file as global config\r
191         global globalProfileParser\r
192         globalProfileParser = ConfigParser.ConfigParser()\r
193 \r
194 def saveGlobalProfile(filename):\r
195         #Save the current profile to an ini file\r
196         globalProfileParser.write(open(filename, 'w'))\r
197 \r
198 def loadGlobalProfileFromString(options):\r
199         global globalProfileParser\r
200         globalProfileParser = ConfigParser.ConfigParser()\r
201         globalProfileParser.add_section('profile')\r
202         globalProfileParser.add_section('alterations')\r
203         options = base64.b64decode(options)\r
204         options = zlib.decompress(options)\r
205         (profileOpts, alt) = options.split('\f', 1)\r
206         for option in profileOpts.split('\b'):\r
207                 if len(option) > 0:\r
208                         (key, value) = option.split('=', 1)\r
209                         globalProfileParser.set('profile', key, value)\r
210         for option in alt.split('\b'):\r
211                 if len(option) > 0:\r
212                         (key, value) = option.split('=', 1)\r
213                         globalProfileParser.set('alterations', key, value)\r
214 \r
215 def getGlobalProfileString():\r
216         global globalProfileParser\r
217         if not globals().has_key('globalProfileParser'):\r
218                 loadGlobalProfile(getDefaultProfilePath())\r
219         \r
220         p = []\r
221         alt = []\r
222         tempDone = []\r
223         if globalProfileParser.has_section('profile'):\r
224                 for key in globalProfileParser.options('profile'):\r
225                         if key in tempOverride:\r
226                                 p.append(key + "=" + unicode(tempOverride[key]))\r
227                                 tempDone.append(key)\r
228                         else:\r
229                                 p.append(key + "=" + globalProfileParser.get('profile', key))\r
230         if globalProfileParser.has_section('alterations'):\r
231                 for key in globalProfileParser.options('alterations'):\r
232                         if key in tempOverride:\r
233                                 p.append(key + "=" + tempOverride[key])\r
234                                 tempDone.append(key)\r
235                         else:\r
236                                 alt.append(key + "=" + globalProfileParser.get('alterations', key))\r
237         for key in tempOverride:\r
238                 if key not in tempDone:\r
239                         p.append(key + "=" + unicode(tempOverride[key]))\r
240         ret = '\b'.join(p) + '\f' + '\b'.join(alt)\r
241         ret = base64.b64encode(zlib.compress(ret, 9))\r
242         return ret\r
243 \r
244 def getProfileSetting(name):\r
245         if name in tempOverride:\r
246                 return unicode(tempOverride[name])\r
247         #Check if we have a configuration file loaded, else load the default.\r
248         if not globals().has_key('globalProfileParser'):\r
249                 loadGlobalProfile(getDefaultProfilePath())\r
250         if not globalProfileParser.has_option('profile', name):\r
251                 if name in profileDefaultSettings:\r
252                         default = profileDefaultSettings[name]\r
253                 else:\r
254                         print("Missing default setting for: '" + name + "'")\r
255                         profileDefaultSettings[name] = ''\r
256                         default = ''\r
257                 if not globalProfileParser.has_section('profile'):\r
258                         globalProfileParser.add_section('profile')\r
259                 globalProfileParser.set('profile', name, str(default))\r
260                 #print(name + " not found in profile, so using default: " + str(default))\r
261                 return default\r
262         return globalProfileParser.get('profile', name)\r
263 \r
264 def getProfileSettingFloat(name):\r
265         try:\r
266                 return float(eval(getProfileSetting(name), {}, {}))\r
267         except (ValueError, SyntaxError):\r
268                 return 0.0\r
269 \r
270 def putProfileSetting(name, value):\r
271         #Check if we have a configuration file loaded, else load the default.\r
272         if not globals().has_key('globalProfileParser'):\r
273                 loadGlobalProfile(getDefaultProfilePath())\r
274         if not globalProfileParser.has_section('profile'):\r
275                 globalProfileParser.add_section('profile')\r
276         globalProfileParser.set('profile', name, str(value))\r
277 \r
278 def isProfileSetting(name):\r
279         if name in profileDefaultSettings:\r
280                 return True\r
281         return False\r
282 \r
283 ## Preferences functions\r
284 global globalPreferenceParser\r
285 globalPreferenceParser = None\r
286 \r
287 def getPreferencePath():\r
288         basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))\r
289         #If we have a frozen python install, we need to step out of the library.zip\r
290         if hasattr(sys, 'frozen'):\r
291                 basePath = os.path.normpath(os.path.join(basePath, ".."))\r
292         return os.path.normpath(os.path.join(basePath, "preferences.ini"))\r
293 \r
294 def getPreferenceFloat(name):\r
295         try:\r
296                 return float(eval(getPreference(name), {}, {}))\r
297         except (ValueError, SyntaxError):\r
298                 return 0.0\r
299 \r
300 def getPreference(name):\r
301         if name in tempOverride:\r
302                 return unicode(tempOverride[name])\r
303         global globalPreferenceParser\r
304         if globalPreferenceParser == None:\r
305                 globalPreferenceParser = ConfigParser.ConfigParser()\r
306                 globalPreferenceParser.read(getPreferencePath())\r
307         if not globalPreferenceParser.has_option('preference', name):\r
308                 if name in preferencesDefaultSettings:\r
309                         default = preferencesDefaultSettings[name]\r
310                 else:\r
311                         print("Missing default setting for: '" + name + "'")\r
312                         preferencesDefaultSettings[name] = ''\r
313                         default = ''\r
314                 if not globalPreferenceParser.has_section('preference'):\r
315                         globalPreferenceParser.add_section('preference')\r
316                 globalPreferenceParser.set('preference', name, str(default))\r
317                 #print(name + " not found in preferences, so using default: " + str(default))\r
318                 return default\r
319         return unicode(globalPreferenceParser.get('preference', name), "utf-8")\r
320 \r
321 def putPreference(name, value):\r
322         #Check if we have a configuration file loaded, else load the default.\r
323         global globalPreferenceParser\r
324         if globalPreferenceParser == None:\r
325                 globalPreferenceParser = ConfigParser.ConfigParser()\r
326                 globalPreferenceParser.read(getPreferencePath())\r
327         if not globalPreferenceParser.has_section('preference'):\r
328                 globalPreferenceParser.add_section('preference')\r
329         globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))\r
330         globalPreferenceParser.write(open(getPreferencePath(), 'w'))\r
331 \r
332 def isPreference(name):\r
333         if name in preferencesDefaultSettings:\r
334                 return True\r
335         return False\r
336 \r
337 ## Temp overrides for multi-extruder slicing and the project planner.\r
338 tempOverride = {}\r
339 def setTempOverride(name, value):\r
340         tempOverride[name] = value\r
341 def resetTempOverride():\r
342         tempOverride.clear()\r
343 \r
344 #########################################################\r
345 ## Utility functions to calculate common profile values\r
346 #########################################################\r
347 def calculateEdgeWidth():\r
348         wallThickness = getProfileSettingFloat('wall_thickness')\r
349         nozzleSize = getProfileSettingFloat('nozzle_size')\r
350         \r
351         if wallThickness < nozzleSize:\r
352                 return wallThickness\r
353 \r
354         lineCount = int(wallThickness / nozzleSize)\r
355         lineWidth = wallThickness / lineCount\r
356         lineWidthAlt = wallThickness / (lineCount + 1)\r
357         if lineWidth > nozzleSize * 1.5:\r
358                 return lineWidthAlt\r
359         return lineWidth\r
360 \r
361 def calculateLineCount():\r
362         wallThickness = getProfileSettingFloat('wall_thickness')\r
363         nozzleSize = getProfileSettingFloat('nozzle_size')\r
364         \r
365         if wallThickness < nozzleSize:\r
366                 return 1\r
367 \r
368         lineCount = int(wallThickness / nozzleSize + 0.0001)\r
369         lineWidth = wallThickness / lineCount\r
370         lineWidthAlt = wallThickness / (lineCount + 1)\r
371         if lineWidth > nozzleSize * 1.5:\r
372                 return lineCount + 1\r
373         return lineCount\r
374 \r
375 def calculateSolidLayerCount():\r
376         layerHeight = getProfileSettingFloat('layer_height')\r
377         solidThickness = getProfileSettingFloat('solid_layer_thickness')\r
378         return int(math.ceil(solidThickness / layerHeight - 0.0001))\r
379 \r
380 #########################################################\r
381 ## Alteration file functions\r
382 #########################################################\r
383 def replaceTagMatch(m):\r
384         tag = m.group(0)[1:-1]\r
385         if tag == 'time':\r
386                 return time.strftime('%H:%M:%S')\r
387         if tag == 'date':\r
388                 return time.strftime('%d %b %Y')\r
389         if tag == 'day':\r
390                 return time.strftime('%a')\r
391         if tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:\r
392                 f = getProfileSettingFloat(tag) * 60\r
393         elif isProfileSetting(tag):\r
394                 f = getProfileSettingFloat(tag)\r
395         elif isPreference(tag):\r
396                 f = getProfileSettingFloat(tag)\r
397         else:\r
398                 return tag\r
399         if (f % 1) == 0:\r
400                 return str(int(f))\r
401         return str(f)\r
402 \r
403 ### Get aleration raw contents. (Used internally in Cura)\r
404 def getAlterationFile(filename):\r
405         #Check if we have a configuration file loaded, else load the default.\r
406         if not globals().has_key('globalProfileParser'):\r
407                 loadGlobalProfile(getDefaultProfilePath())\r
408         \r
409         if not globalProfileParser.has_option('alterations', filename):\r
410                 if filename in alterationDefault:\r
411                         default = alterationDefault[filename]\r
412                 else:\r
413                         print("Missing default alteration for: '" + filename + "'")\r
414                         alterationDefault[filename] = ''\r
415                         default = ''\r
416                 if not globalProfileParser.has_section('alterations'):\r
417                         globalProfileParser.add_section('alterations')\r
418                 #print("Using default for: %s" % (filename))\r
419                 globalProfileParser.set('alterations', filename, default)\r
420         return unicode(globalProfileParser.get('alterations', filename), "utf-8")\r
421 \r
422 def setAlterationFile(filename, value):\r
423         #Check if we have a configuration file loaded, else load the default.\r
424         if not globals().has_key('globalProfileParser'):\r
425                 loadGlobalProfile(getDefaultProfilePath())\r
426         if not globalProfileParser.has_section('alterations'):\r
427                 globalProfileParser.add_section('alterations')\r
428         globalProfileParser.set('alterations', filename, value.encode("utf-8"))\r
429         saveGlobalProfile(getDefaultProfilePath())\r
430 \r
431 ### Get the alteration file for output. (Used by Skeinforge)\r
432 def getAlterationFileContents(filename):\r
433         prefix = ''\r
434         alterationContents = getAlterationFile(filename)\r
435         if filename == 'start.gcode':\r
436                 #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
437                 #We also set our steps per E here, if configured.\r
438                 eSteps = getPreferenceFloat('steps_per_e')\r
439                 if eSteps > 0:\r
440                         prefix += 'M92 E%f\n' % (eSteps)\r
441                 temp = getProfileSettingFloat('print_temperature')\r
442                 if temp > 0 and not '{print_temperature}' in alterationContents:\r
443                         prefix += 'M109 S%f\n' % (temp)\r
444         elif filename == 'replace.csv':\r
445                 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.\r
446                 prefix = 'M101\nM103\n'\r
447         \r
448         return unicode(prefix + re.sub("\{[^\}]*\}", replaceTagMatch, alterationContents).rstrip() + '\n').encode('utf-8')\r
449 \r