chiark / gitweb /
Added more GCode validation to GCode editor. Made temp changes to profile really...
[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 }\r
126 preferencesDefaultSettings = {\r
127         'wizardDone': 'False',\r
128         'startMode': 'Simple',\r
129         'lastFile': '',\r
130         'machine_width': '205',\r
131         'machine_depth': '205',\r
132         'machine_height': '200',\r
133         'extruder_amount': '1',\r
134         'extruder_offset_x1': '-22.0',\r
135         'extruder_offset_y1': '0.0',\r
136         'extruder_offset_x2': '0.0',\r
137         'extruder_offset_y2': '0.0',\r
138         'extruder_offset_x3': '0.0',\r
139         'extruder_offset_y3': '0.0',\r
140         'filament_density': '1300',\r
141         'steps_per_e': '0',\r
142         'serial_port': 'AUTO',\r
143         'serial_baud': '250000',\r
144         'slicer': 'Cura (Skeinforge based)',\r
145         'save_profile': 'False',\r
146         'filament_cost_kg': '0',\r
147         'filament_cost_meter': '0',\r
148         \r
149         'extruder_head_size_min_x': '70.0',\r
150         'extruder_head_size_min_y': '18.0',\r
151         'extruder_head_size_max_x': '18.0',\r
152         'extruder_head_size_max_y': '35.0',\r
153 }\r
154 \r
155 #########################################################\r
156 ## Profile and preferences functions\r
157 #########################################################\r
158 \r
159 ## Profile functions\r
160 def getDefaultProfilePath():\r
161         return os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../current_profile.ini"))\r
162 \r
163 def loadGlobalProfile(filename):\r
164         #Read a configuration file as global config\r
165         global globalProfileParser\r
166         globalProfileParser = ConfigParser.ConfigParser()\r
167         globalProfileParser.read(filename)\r
168 \r
169 def saveGlobalProfile(filename):\r
170         #Save the current profile to an ini file\r
171         globalProfileParser.write(open(filename, 'w'))\r
172 \r
173 def loadGlobalProfileFromString(options):\r
174         global globalProfileParser\r
175         globalProfileParser = ConfigParser.ConfigParser()\r
176         globalProfileParser.add_section('profile')\r
177         globalProfileParser.add_section('alterations')\r
178         options = base64.b64decode(options)\r
179         options = zlib.decompress(options)\r
180         (profileOpts, alt) = options.split('\f', 1)\r
181         for option in profileOpts.split('\b'):\r
182                 (key, value) = option.split('=', 1)\r
183                 globalProfileParser.set('profile', key, value)\r
184         for option in alt.split('\b'):\r
185                 (key, value) = option.split('=', 1)\r
186                 globalProfileParser.set('alterations', key, value)\r
187 \r
188 def getGlobalProfileString():\r
189         global globalProfileParser\r
190         if not globals().has_key('globalProfileParser'):\r
191                 loadGlobalProfile(getDefaultProfilePath())\r
192         \r
193         p = []\r
194         alt = []\r
195         tempDone = []\r
196         if globalProfileParser.has_section('profile'):\r
197                 for key in globalProfileParser.options('profile'):\r
198                         if key in tempOverride:\r
199                                 p.append(key + "=" + unicode(tempOverride[key]))\r
200                                 tempDone.append(key)\r
201                         else:\r
202                                 p.append(key + "=" + globalProfileParser.get('profile', key))\r
203         if globalProfileParser.has_section('alterations'):\r
204                 for key in globalProfileParser.options('alterations'):\r
205                         if key in tempOverride:\r
206                                 p.append(key + "=" + tempOverride[key])\r
207                                 tempDone.append(key)\r
208                         else:\r
209                                 alt.append(key + "=" + globalProfileParser.get('alterations', key))\r
210         for key in tempOverride:\r
211                 if key not in tempDone:\r
212                         p.append(key + "=" + unicode(tempOverride[key]))\r
213         ret = '\b'.join(p) + '\f' + '\b'.join(alt)\r
214         ret = base64.b64encode(zlib.compress(ret, 9))\r
215         return ret\r
216 \r
217 def getProfileSetting(name):\r
218         if name in tempOverride:\r
219                 return unicode(tempOverride[name])\r
220         #Check if we have a configuration file loaded, else load the default.\r
221         if not globals().has_key('globalProfileParser'):\r
222                 loadGlobalProfile(getDefaultProfilePath())\r
223         if not globalProfileParser.has_option('profile', name):\r
224                 if name in profileDefaultSettings:\r
225                         default = profileDefaultSettings[name]\r
226                 else:\r
227                         print "Missing default setting for: '" + name + "'"\r
228                         profileDefaultSettings[name] = ''\r
229                         default = ''\r
230                 if not globalProfileParser.has_section('profile'):\r
231                         globalProfileParser.add_section('profile')\r
232                 globalProfileParser.set('profile', name, str(default))\r
233                 #print name + " not found in profile, so using default: " + str(default)\r
234                 return default\r
235         return globalProfileParser.get('profile', name)\r
236 \r
237 def getProfileSettingFloat(name):\r
238         try:\r
239                 return float(eval(getProfileSetting(name), {}, {}))\r
240         except (ValueError, SyntaxError):\r
241                 return 0.0\r
242 \r
243 def putProfileSetting(name, value):\r
244         #Check if we have a configuration file loaded, else load the default.\r
245         if not globals().has_key('globalProfileParser'):\r
246                 loadGlobalProfile(getDefaultProfilePath())\r
247         if not globalProfileParser.has_section('profile'):\r
248                 globalProfileParser.add_section('profile')\r
249         globalProfileParser.set('profile', name, str(value))\r
250 \r
251 def isProfileSetting(name):\r
252         if name in profileDefaultSettings:\r
253                 return True\r
254         return False\r
255 \r
256 ## Preferences functions\r
257 global globalPreferenceParser\r
258 globalPreferenceParser = None\r
259 \r
260 def getPreferencePath():\r
261         return os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../preferences.ini"))\r
262 \r
263 def getPreferenceFloat(name):\r
264         try:\r
265                 return float(eval(getPreference(name), {}, {}))\r
266         except (ValueError, SyntaxError):\r
267                 return 0.0\r
268 \r
269 def getPreference(name):\r
270         if name in tempOverride:\r
271                 return unicode(tempOverride[name])\r
272         global globalPreferenceParser\r
273         if globalPreferenceParser == None:\r
274                 globalPreferenceParser = ConfigParser.ConfigParser()\r
275                 globalPreferenceParser.read(getPreferencePath())\r
276         if not globalPreferenceParser.has_option('preference', name):\r
277                 if name in preferencesDefaultSettings:\r
278                         default = preferencesDefaultSettings[name]\r
279                 else:\r
280                         print "Missing default setting for: '" + name + "'"\r
281                         preferencesDefaultSettings[name] = ''\r
282                         default = ''\r
283                 if not globalPreferenceParser.has_section('preference'):\r
284                         globalPreferenceParser.add_section('preference')\r
285                 globalPreferenceParser.set('preference', name, str(default))\r
286                 #print name + " not found in preferences, so using default: " + str(default)\r
287                 return default\r
288         return unicode(globalPreferenceParser.get('preference', name), "utf-8")\r
289 \r
290 def putPreference(name, value):\r
291         #Check if we have a configuration file loaded, else load the default.\r
292         global globalPreferenceParser\r
293         if globalPreferenceParser == None:\r
294                 globalPreferenceParser = ConfigParser.ConfigParser()\r
295                 globalPreferenceParser.read(getPreferencePath())\r
296         if not globalPreferenceParser.has_section('preference'):\r
297                 globalPreferenceParser.add_section('preference')\r
298         globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))\r
299         globalPreferenceParser.write(open(getPreferencePath(), 'w'))\r
300 \r
301 def isPreference(name):\r
302         if name in preferencesDefaultSettings:\r
303                 return True\r
304         return False\r
305 \r
306 ## Temp overrides for multi-extruder slicing and the project planner.\r
307 tempOverride = {}\r
308 def setTempOverride(name, value):\r
309         tempOverride[name] = value\r
310 def resetTempOverride():\r
311         tempOverride = {}\r
312 \r
313 #########################################################\r
314 ## Utility functions to calculate common profile values\r
315 #########################################################\r
316 def calculateEdgeWidth():\r
317         wallThickness = getProfileSettingFloat('wall_thickness')\r
318         nozzleSize = getProfileSettingFloat('nozzle_size')\r
319         \r
320         if wallThickness < nozzleSize:\r
321                 return wallThickness\r
322 \r
323         lineCount = int(wallThickness / nozzleSize)\r
324         lineWidth = wallThickness / lineCount\r
325         lineWidthAlt = wallThickness / (lineCount + 1)\r
326         if lineWidth > nozzleSize * 1.5:\r
327                 return lineWidthAlt\r
328         return lineWidth\r
329 \r
330 def calculateLineCount():\r
331         wallThickness = getProfileSettingFloat('wall_thickness')\r
332         nozzleSize = getProfileSettingFloat('nozzle_size')\r
333         \r
334         if wallThickness < nozzleSize:\r
335                 return 1\r
336 \r
337         lineCount = int(wallThickness / nozzleSize + 0.0001)\r
338         lineWidth = wallThickness / lineCount\r
339         lineWidthAlt = wallThickness / (lineCount + 1)\r
340         if lineWidth > nozzleSize * 1.5:\r
341                 return lineCount + 1\r
342         return lineCount\r
343 \r
344 def calculateSolidLayerCount():\r
345         layerHeight = getProfileSettingFloat('layer_height')\r
346         solidThickness = getProfileSettingFloat('solid_layer_thickness')\r
347         return int(math.ceil(solidThickness / layerHeight - 0.0001))\r
348 \r
349 #########################################################\r
350 ## Alteration file functions\r
351 #########################################################\r
352 def replaceTagMatch(m):\r
353         tag = m.group(0)[1:-1]\r
354         if tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:\r
355                 return str(getProfileSettingFloat(tag) * 60)\r
356         if isProfileSetting(tag):\r
357                 return str(getProfileSettingFloat(tag))\r
358         if isPreference(tag):\r
359                 return str(getProfileSettingFloat(tag))\r
360         return tag\r
361 \r
362 ### Get aleration raw contents. (Used internally in Cura)\r
363 def getAlterationFile(filename):\r
364         #Check if we have a configuration file loaded, else load the default.\r
365         if not globals().has_key('globalProfileParser'):\r
366                 loadGlobalProfile(getDefaultProfilePath())\r
367         \r
368         if not globalProfileParser.has_option('alterations', filename):\r
369                 if filename in alterationDefault:\r
370                         default = alterationDefault[filename]\r
371                 else:\r
372                         print "Missing default alteration for: '" + filename + "'"\r
373                         alterationDefault[filename] = ''\r
374                         default = ''\r
375                 if not globalProfileParser.has_section('alterations'):\r
376                         globalProfileParser.add_section('alterations')\r
377                 #print "Using default for: %s" % (filename)\r
378                 globalProfileParser.set('alterations', filename, default)\r
379         return unicode(globalProfileParser.get('alterations', filename), "utf-8")\r
380 \r
381 def setAlterationFile(filename, value):\r
382         #Check if we have a configuration file loaded, else load the default.\r
383         if not globals().has_key('globalProfileParser'):\r
384                 loadGlobalProfile(getDefaultProfilePath())\r
385         if not globalProfileParser.has_section('alterations'):\r
386                 globalProfileParser.add_section('alterations')\r
387         globalProfileParser.set('alterations', filename, value.encode("utf-8"))\r
388         saveGlobalProfile(getDefaultProfilePath())\r
389 \r
390 ### Get the alteration file for output. (Used by Skeinforge)\r
391 def getAlterationFileContents(filename):\r
392         prefix = ''\r
393         alterationContents = getAlterationFile(filename)\r
394         if filename == 'start.gcode':\r
395                 #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
396                 #We also set our steps per E here, if configured.\r
397                 eSteps = getPreferenceFloat('steps_per_e')\r
398                 if eSteps > 0:\r
399                         prefix += 'M92 E%f\n' % (eSteps)\r
400                 temp = getProfileSettingFloat('print_temperature')\r
401                 if temp > 0 and not '{print_temperature}' in alterationContents:\r
402                         prefix += 'M109 S%f\n' % (temp)\r
403         elif filename == 'replace.csv':\r
404                 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.\r
405                 prefix = 'M101\nM103\n'\r
406         \r
407         return unicode(prefix + re.sub("\{[^\}]*\}", replaceTagMatch, alterationContents).rstrip() + '\n').encode('utf-8')\r
408 \r