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