chiark / gitweb /
Update preferences to allow math expressions. Fixed #86
[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 }\r
71 alterationDefault = {\r
72 #######################################################################################\r
73         'start.gcode': """;Start GCode\r
74 G21        ;metric values\r
75 G90        ;absolute positioning\r
76 \r
77 G28 X0 Y0  ;move X/Y to min endstops\r
78 G28 Z0     ;move Z to min endstops\r
79 \r
80 ; if your prints start too high, try changing the Z0.0 below\r
81 ; to Z1.0 - the number after the Z is the actual, physical\r
82 ; height of the nozzle in mm. This can take some messing around\r
83 ; with to get just right...\r
84 G92 X0 Y0 Z0 E0         ;reset software position to front/left/z=0.0\r
85 G1 Z15.0 F{max_z_speed} ;move the platform down 15mm\r
86 G92 E0                  ;zero the extruded length\r
87 \r
88 G1 F200 E5              ;extrude 5mm of feed stock\r
89 G1 F200 E3.5            ;reverse feed stock by 1.5mm\r
90 G92 E0                  ;zero the extruded length again\r
91 \r
92 ;go to the middle of the platform, and move to Z=0 before starting the print.\r
93 G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}\r
94 G1 Z0.0 F{max_z_speed}\r
95 """,\r
96 #######################################################################################\r
97         'end.gcode': """;End GCode\r
98 M104 S0                    ;extruder heat off\r
99 G91                        ;relative positioning\r
100 G1 Z+10 E-5 F{max_z_speed} ;move Z up a bit and retract filament by 5mm\r
101 G28 X0 Y0                  ;move X/Y to min endstops, so the head is out of the way\r
102 M84                        ;steppers off\r
103 G90                        ;absolute positioning\r
104 """,\r
105 #######################################################################################\r
106         'support_start.gcode': '',\r
107         'support_end.gcode': '',\r
108         'cool_start.gcode': '',\r
109         'cool_end.gcode': '',\r
110         'replace.csv': '',\r
111 #######################################################################################\r
112         '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
113 G92 E0\r
114 G1 Z{clear_z} E-5 F{max_z_speed}\r
115 G92 E0\r
116 G1 X{machine_center_x} Y{machine_center_y} F{travel_speed}\r
117 G1 F200 E5.5\r
118 G92 E0\r
119 G1 Z0 F{max_z_speed}\r
120 """,\r
121 #######################################################################################\r
122 }\r
123 preferencesDefaultSettings = {\r
124         'wizardDone': 'False',\r
125         'startMode': 'Simple',\r
126         'lastFile': '',\r
127         'machine_width': '205',\r
128         'machine_depth': '205',\r
129         'machine_height': '200',\r
130         'extruder_amount': '1',\r
131         'extruder_offset_x1': '-22.0',\r
132         'extruder_offset_y1': '0.0',\r
133         'extruder_offset_x2': '0.0',\r
134         'extruder_offset_y2': '0.0',\r
135         'extruder_offset_x3': '0.0',\r
136         'extruder_offset_y3': '0.0',\r
137         'filament_density': '1300',\r
138         'steps_per_e': '0',\r
139         'serial_port': 'AUTO',\r
140         'serial_baud': '250000',\r
141         'slicer': 'Cura (Skeinforge based)',\r
142         'save_profile': 'False',\r
143         'filament_cost_kg': '0',\r
144         'filament_cost_meter': '0',\r
145         \r
146         'extruder_head_size_min_x': '70.0',\r
147         'extruder_head_size_min_y': '18.0',\r
148         'extruder_head_size_max_x': '18.0',\r
149         'extruder_head_size_max_y': '35.0',\r
150 }\r
151 \r
152 #########################################################\r
153 ## Profile and preferences functions\r
154 #########################################################\r
155 \r
156 def getDefaultProfilePath():\r
157         return os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../current_profile.ini"))\r
158 \r
159 def loadGlobalProfile(filename):\r
160         #Read a configuration file as global config\r
161         global globalProfileParser\r
162         globalProfileParser = ConfigParser.ConfigParser()\r
163         globalProfileParser.read(filename)\r
164 \r
165 def saveGlobalProfile(filename):\r
166         #Save the current profile to an ini file\r
167         globalProfileParser.write(open(filename, 'w'))\r
168 \r
169 def loadGlobalProfileFromString(options):\r
170         global globalProfileParser\r
171         globalProfileParser = ConfigParser.ConfigParser()\r
172         globalProfileParser.add_section('profile')\r
173         globalProfileParser.add_section('alterations')\r
174         options = base64.b64decode(options)\r
175         options = zlib.decompress(options)\r
176         (profileOpts, alt) = options.split('\f', 1)\r
177         for option in profileOpts.split('\b'):\r
178                 (key, value) = option.split('=', 1)\r
179                 globalProfileParser.set('profile', key, value)\r
180         for option in alt.split('\b'):\r
181                 (key, value) = option.split('=', 1)\r
182                 globalProfileParser.set('alterations', key, value)\r
183 \r
184 def getGlobalProfileString():\r
185         global globalProfileParser\r
186         if not globals().has_key('globalProfileParser'):\r
187                 loadGlobalProfile(getDefaultProfilePath())\r
188         \r
189         p = []\r
190         alt = []\r
191         if globalProfileParser.has_section('profile'):\r
192                 for key in globalProfileParser.options('profile'):\r
193                         p.append(key + "=" + globalProfileParser.get('profile', key))\r
194         if globalProfileParser.has_section('alterations'):\r
195                 for key in globalProfileParser.options('alterations'):\r
196                         alt.append(key + "=" + globalProfileParser.get('alterations', key))\r
197         ret = '\b'.join(p) + '\f' + '\b'.join(alt)\r
198         ret = base64.b64encode(zlib.compress(ret, 9))\r
199         return ret\r
200 \r
201 def getProfileSetting(name):\r
202         #Check if we have a configuration file loaded, else load the default.\r
203         if not globals().has_key('globalProfileParser'):\r
204                 loadGlobalProfile(getDefaultProfilePath())\r
205         if not globalProfileParser.has_option('profile', name):\r
206                 if name in profileDefaultSettings:\r
207                         default = profileDefaultSettings[name]\r
208                 else:\r
209                         print "Missing default setting for: '" + name + "'"\r
210                         profileDefaultSettings[name] = ''\r
211                         default = ''\r
212                 if not globalProfileParser.has_section('profile'):\r
213                         globalProfileParser.add_section('profile')\r
214                 globalProfileParser.set('profile', name, str(default))\r
215                 #print name + " not found in profile, so using default: " + str(default)\r
216                 return default\r
217         return globalProfileParser.get('profile', name)\r
218 \r
219 def getProfileSettingFloat(name):\r
220         try:\r
221                 return float(eval(getProfileSetting(name), {}, {}))\r
222         except (ValueError, SyntaxError):\r
223                 return 0.0\r
224 \r
225 def putProfileSetting(name, value):\r
226         #Check if we have a configuration file loaded, else load the default.\r
227         if not globals().has_key('globalProfileParser'):\r
228                 loadGlobalProfile(getDefaultProfilePath())\r
229         if not globalProfileParser.has_section('profile'):\r
230                 globalProfileParser.add_section('profile')\r
231         globalProfileParser.set('profile', name, str(value))\r
232 \r
233 global globalPreferenceParser\r
234 globalPreferenceParser = None\r
235 \r
236 def getPreferencePath():\r
237         return os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../preferences.ini"))\r
238 \r
239 def getPreferenceFloat(name):\r
240         try:\r
241                 return float(eval(getPreference(name), {}, {}))\r
242 \r
243         except (ValueError, SyntaxError):\r
244                 return 0.0\r
245 \r
246 def getPreference(name):\r
247         global globalPreferenceParser\r
248         if globalPreferenceParser == None:\r
249                 globalPreferenceParser = ConfigParser.ConfigParser()\r
250                 globalPreferenceParser.read(getPreferencePath())\r
251         if not globalPreferenceParser.has_option('preference', name):\r
252                 if name in preferencesDefaultSettings:\r
253                         default = preferencesDefaultSettings[name]\r
254                 else:\r
255                         print "Missing default setting for: '" + name + "'"\r
256                         preferencesDefaultSettings[name] = ''\r
257                         default = ''\r
258                 if not globalPreferenceParser.has_section('preference'):\r
259                         globalPreferenceParser.add_section('preference')\r
260                 globalPreferenceParser.set('preference', name, str(default))\r
261                 #print name + " not found in preferences, so using default: " + str(default)\r
262                 return default\r
263         return unicode(globalPreferenceParser.get('preference', name), "utf-8")\r
264 \r
265 def putPreference(name, value):\r
266         #Check if we have a configuration file loaded, else load the default.\r
267         global globalPreferenceParser\r
268         if globalPreferenceParser == None:\r
269                 globalPreferenceParser = ConfigParser.ConfigParser()\r
270                 globalPreferenceParser.read(getPreferencePath())\r
271         if not globalPreferenceParser.has_section('preference'):\r
272                 globalPreferenceParser.add_section('preference')\r
273         globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))\r
274         globalPreferenceParser.write(open(getPreferencePath(), 'w'))\r
275 \r
276 #########################################################\r
277 ## Utility functions to calculate common profile values\r
278 #########################################################\r
279 def calculateEdgeWidth():\r
280         wallThickness = getProfileSettingFloat('wall_thickness')\r
281         nozzleSize = getProfileSettingFloat('nozzle_size')\r
282         \r
283         if wallThickness < nozzleSize:\r
284                 return wallThickness\r
285 \r
286         lineCount = int(wallThickness / nozzleSize)\r
287         lineWidth = wallThickness / lineCount\r
288         lineWidthAlt = wallThickness / (lineCount + 1)\r
289         if lineWidth > nozzleSize * 1.5:\r
290                 return lineWidthAlt\r
291         return lineWidth\r
292 \r
293 def calculateLineCount():\r
294         wallThickness = getProfileSettingFloat('wall_thickness')\r
295         nozzleSize = getProfileSettingFloat('nozzle_size')\r
296         \r
297         if wallThickness < nozzleSize:\r
298                 return 1\r
299 \r
300         lineCount = int(wallThickness / nozzleSize + 0.0001)\r
301         lineWidth = wallThickness / lineCount\r
302         lineWidthAlt = wallThickness / (lineCount + 1)\r
303         if lineWidth > nozzleSize * 1.5:\r
304                 return lineCount + 1\r
305         return lineCount\r
306 \r
307 def calculateSolidLayerCount():\r
308         layerHeight = getProfileSettingFloat('layer_height')\r
309         solidThickness = getProfileSettingFloat('solid_layer_thickness')\r
310         return int(math.ceil(solidThickness / layerHeight - 0.0001))\r
311 \r
312 #########################################################\r
313 ## Alteration file functions\r
314 #########################################################\r
315 def replaceTagMatch(m):\r
316         tag = m.group(0)[1:-1]\r
317         if tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:\r
318                 return str(getProfileSettingFloat(tag) * 60)\r
319         return str(getProfileSettingFloat(tag))\r
320 \r
321 ### Get aleration raw contents. (Used internally in Cura)\r
322 def getAlterationFile(filename):\r
323         #Check if we have a configuration file loaded, else load the default.\r
324         if not globals().has_key('globalProfileParser'):\r
325                 loadGlobalProfile(getDefaultProfilePath())\r
326         \r
327         if not globalProfileParser.has_option('alterations', filename):\r
328                 if filename in alterationDefault:\r
329                         default = alterationDefault[filename]\r
330                 else:\r
331                         print "Missing default alteration for: '" + filename + "'"\r
332                         alterationDefault[filename] = ''\r
333                         default = ''\r
334                 if not globalProfileParser.has_section('alterations'):\r
335                         globalProfileParser.add_section('alterations')\r
336                 #print "Using default for: %s" % (filename)\r
337                 globalProfileParser.set('alterations', filename, default)\r
338         return unicode(globalProfileParser.get('alterations', filename), "utf-8")\r
339 \r
340 def setAlterationFile(filename, value):\r
341         #Check if we have a configuration file loaded, else load the default.\r
342         if not globals().has_key('globalProfileParser'):\r
343                 loadGlobalProfile(getDefaultProfilePath())\r
344         if not globalProfileParser.has_section('alterations'):\r
345                 globalProfileParser.add_section('alterations')\r
346         globalProfileParser.set('alterations', filename, value.encode("utf-8"))\r
347         saveGlobalProfile(getDefaultProfilePath())\r
348 \r
349 ### Get the alteration file for output. (Used by Skeinforge)\r
350 def getAlterationFileContents(filename):\r
351         prefix = ''\r
352         alterationContents = getAlterationFile(filename)\r
353         if filename == 'start.gcode':\r
354                 #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
355                 #We also set our steps per E here, if configured.\r
356                 eSteps = getPreferenceFloat('steps_per_e')\r
357                 if eSteps > 0:\r
358                         prefix += 'M92 E%f\n' % (eSteps)\r
359                 temp = getProfileSettingFloat('print_temperature')\r
360                 if temp > 0 and not '{print_temperature}' in alterationContents:\r
361                         prefix += 'M109 S%f\n' % (temp)\r
362         elif filename == 'replace.csv':\r
363                 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.\r
364                 prefix = 'M101\nM103\n'\r
365         \r
366         return unicode(prefix + re.sub("\{[^\}]*\}", replaceTagMatch, alterationContents).rstrip() + '\n').encode('utf-8')\r
367 \r