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