chiark / gitweb /
Copyright message needs to be after the __future__ imports.
[cura.git] / Cura / util / gcodeInterpreter.py
1 from __future__ import absolute_import
2 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
3
4 import sys
5 import math
6 import os
7 import time
8 import numpy
9
10 from Cura.util import profile
11
12 #class gcodePath(object):
13 #       def __init__(self, newType, pathType, layerThickness, startPoint):
14 #               self.type = newType
15 #               self.pathType = pathType
16 #               self.layerThickness = layerThickness
17 #               self.points = [startPoint]
18 #               self.extrusion = [0.0]
19 def gcodePath(newType, pathType, layerThickness, startPoint):
20         return {'type': newType,
21                         'pathType': pathType,
22                         'layerThickness': layerThickness,
23                         'points': [startPoint],
24                         'extrusion': [0.0]}
25
26 class gcode(object):
27         def __init__(self):
28                 self.regMatch = {}
29                 self.layerList = []
30                 self.extrusionAmount = 0
31                 self.totalMoveTimeMinute = 0
32                 self.filename = None
33                 self.progressCallback = None
34         
35         def load(self, filename):
36                 if os.path.isfile(filename):
37                         self.filename = filename
38                         self._fileSize = os.stat(filename).st_size
39                         gcodeFile = open(filename, 'r')
40                         self._load(gcodeFile)
41                         gcodeFile.close()
42         
43         def loadList(self, l):
44                 self.filename = None
45                 self._load(l)
46         
47         def calculateWeight(self):
48                 #Calculates the weight of the filament in kg
49                 radius = float(profile.getProfileSetting('filament_diameter')) / 2
50                 volumeM3 = (self.extrusionAmount * (math.pi * radius * radius)) / (1000*1000*1000)
51                 return volumeM3 * profile.getPreferenceFloat('filament_physical_density')
52         
53         def calculateCost(self):
54                 cost_kg = profile.getPreferenceFloat('filament_cost_kg')
55                 cost_meter = profile.getPreferenceFloat('filament_cost_meter')
56                 if cost_kg > 0.0 and cost_meter > 0.0:
57                         return "%.2f / %.2f" % (self.calculateWeight() * cost_kg, self.extrusionAmount / 1000 * cost_meter)
58                 elif cost_kg > 0.0:
59                         return "%.2f" % (self.calculateWeight() * cost_kg)
60                 elif cost_meter > 0.0:
61                         return "%.2f" % (self.extrusionAmount / 1000 * cost_meter)
62                 return None
63         
64         def _load(self, gcodeFile):
65                 pos = [0.0, 0.0, 0.0]
66                 posOffset = [0.0, 0.0, 0.0]
67                 currentE = 0.0
68                 totalExtrusion = 0.0
69                 maxExtrusion = 0.0
70                 currentExtruder = 0
71                 extrudeAmountMultiply = 1.0
72                 totalMoveTimeMinute = 0.0
73                 absoluteE = True
74                 scale = 1.0
75                 posAbs = True
76                 feedRate = 3600.0
77                 layerThickness = 0.1
78                 pathType = 'CUSTOM';
79                 currentLayer = []
80                 currentPath = gcodePath('move', pathType, layerThickness, pos[:])
81                 currentPath['extruder'] = currentExtruder
82
83                 currentLayer.append(currentPath)
84                 for line in gcodeFile:
85                         if type(line) is tuple:
86                                 line = line[0]
87
88                         #Parse Cura_SF comments
89                         if line.startswith(';TYPE:'):
90                                 pathType = line[6:].strip()
91
92                         if ';' in line:
93                                 #Slic3r GCode comment parser
94                                 comment = line[line.find(';')+1:].strip()
95                                 if comment == 'fill':
96                                         pathType = 'FILL'
97                                 elif comment == 'perimeter':
98                                         pathType = 'WALL-INNER'
99                                 elif comment == 'skirt':
100                                         pathType = 'SKIRT'
101                                 if comment.startswith('LAYER:'):
102                                         currentPath = gcodePath(moveType, pathType, layerThickness, currentPath['points'][-1])
103                                         currentPath['extruder'] = currentExtruder
104                                         for path in currentLayer:
105                                                 path['points'] = numpy.array(path['points'], numpy.float32)
106                                                 path['extrusion'] = numpy.array(path['extrusion'], numpy.float32)
107                                         self.layerList.append(currentLayer)
108                                         if self.progressCallback is not None:
109                                                 if self.progressCallback(float(gcodeFile.tell()) / float(self._fileSize)):
110                                                         #Abort the loading, we can safely return as the results here will be discarded
111                                                         gcodeFile.close()
112                                                         return
113                                         currentLayer = [currentPath]
114                                 line = line[0:line.find(';')]
115                         T = getCodeInt(line, 'T')
116                         if T is not None:
117                                 if currentExtruder > 0:
118                                         posOffset[0] -= profile.getPreferenceFloat('extruder_offset_x%d' % (currentExtruder))
119                                         posOffset[1] -= profile.getPreferenceFloat('extruder_offset_y%d' % (currentExtruder))
120                                 currentExtruder = T
121                                 if currentExtruder > 0:
122                                         posOffset[0] += profile.getPreferenceFloat('extruder_offset_x%d' % (currentExtruder))
123                                         posOffset[1] += profile.getPreferenceFloat('extruder_offset_y%d' % (currentExtruder))
124                         
125                         G = getCodeInt(line, 'G')
126                         if G is not None:
127                                 if G == 0 or G == 1:    #Move
128                                         x = getCodeFloat(line, 'X')
129                                         y = getCodeFloat(line, 'Y')
130                                         z = getCodeFloat(line, 'Z')
131                                         e = getCodeFloat(line, 'E')
132                                         #f = getCodeFloat(line, 'F')
133                                         oldPos = pos[:]
134                                         if posAbs:
135                                                 if x is not None:
136                                                         pos[0] = x * scale + posOffset[0]
137                                                 if y is not None:
138                                                         pos[1] = y * scale + posOffset[1]
139                                                 if z is not None:
140                                                         pos[2] = z * scale + posOffset[2]
141                                         else:
142                                                 if x is not None:
143                                                         pos[0] += x * scale
144                                                 if y is not None:
145                                                         pos[1] += y * scale
146                                                 if z is not None:
147                                                         pos[2] += z * scale
148                                         #if f is not None:
149                                         #       feedRate = f
150                                         #if x is not None or y is not None or z is not None:
151                                         #       diffX = oldPos[0] - pos[0]
152                                         #       diffY = oldPos[1] - pos[1]
153                                         #       totalMoveTimeMinute += math.sqrt(diffX * diffX + diffY * diffY) / feedRate
154                                         moveType = 'move'
155                                         if e is not None:
156                                                 if absoluteE:
157                                                         e -= currentE
158                                                 if e > 0.0:
159                                                         moveType = 'extrude'
160                                                 if e < 0.0:
161                                                         moveType = 'retract'
162                                                 totalExtrusion += e
163                                                 currentE += e
164                                                 if totalExtrusion > maxExtrusion:
165                                                         maxExtrusion = totalExtrusion
166                                         else:
167                                                 e = 0.0
168                                         if moveType == 'move' and oldPos[2] != pos[2]:
169                                                 if oldPos[2] > pos[2] and abs(oldPos[2] - pos[2]) > 5.0 and pos[2] < 1.0:
170                                                         oldPos[2] = 0.0
171                                                 layerThickness = abs(oldPos[2] - pos[2])
172                                         if currentPath['type'] != moveType or currentPath['pathType'] != pathType:
173                                                 currentPath = gcodePath(moveType, pathType, layerThickness, currentPath['points'][-1])
174                                                 currentPath['extruder'] = currentExtruder
175                                                 currentLayer.append(currentPath)
176
177                                         currentPath['points'].append(pos[:])
178                                         currentPath['extrusion'].append(e * extrudeAmountMultiply)
179                                 elif G == 4:    #Delay
180                                         S = getCodeFloat(line, 'S')
181                                         if S is not None:
182                                                 totalMoveTimeMinute += S / 60.0
183                                         P = getCodeFloat(line, 'P')
184                                         if P is not None:
185                                                 totalMoveTimeMinute += P / 60.0 / 1000.0
186                                 elif G == 20:   #Units are inches
187                                         scale = 25.4
188                                 elif G == 21:   #Units are mm
189                                         scale = 1.0
190                                 elif G == 28:   #Home
191                                         x = getCodeFloat(line, 'X')
192                                         y = getCodeFloat(line, 'Y')
193                                         z = getCodeFloat(line, 'Z')
194                                         if x is None and y is None and z is None:
195                                                 pos = [0.0,0.0,0.0]
196                                         else:
197                                                 if x is not None:
198                                                         pos[0] = 0.0
199                                                 if y is not None:
200                                                         pos[0] = 0.0
201                                                 if z is not None:
202                                                         pos[0] = 0.0
203                                 elif G == 90:   #Absolute position
204                                         posAbs = True
205                                 elif G == 91:   #Relative position
206                                         posAbs = False
207                                 elif G == 92:
208                                         x = getCodeFloat(line, 'X')
209                                         y = getCodeFloat(line, 'Y')
210                                         z = getCodeFloat(line, 'Z')
211                                         e = getCodeFloat(line, 'E')
212                                         if e is not None:
213                                                 currentE = e
214                                         if x is not None:
215                                                 posOffset[0] = pos[0] - x
216                                         if y is not None:
217                                                 posOffset[1] = pos[1] - y
218                                         if z is not None:
219                                                 posOffset[2] = pos[2] - z
220                                 else:
221                                         print "Unknown G code:" + str(G)
222                         else:
223                                 M = getCodeInt(line, 'M')
224                                 if M is not None:
225                                         if M == 0:      #Message with possible wait (ignored)
226                                                 pass
227                                         elif M == 1:    #Message with possible wait (ignored)
228                                                 pass
229                                         elif M == 80:   #Enable power supply
230                                                 pass
231                                         elif M == 81:   #Suicide/disable power supply
232                                                 pass
233                                         elif M == 82:   #Absolute E
234                                                 absoluteE = True
235                                         elif M == 83:   #Relative E
236                                                 absoluteE = False
237                                         elif M == 84:   #Disable step drivers
238                                                 pass
239                                         elif M == 92:   #Set steps per unit
240                                                 pass
241                                         elif M == 101:  #Enable extruder
242                                                 pass
243                                         elif M == 103:  #Disable extruder
244                                                 pass
245                                         elif M == 104:  #Set temperature, no wait
246                                                 pass
247                                         elif M == 105:  #Get temperature
248                                                 pass
249                                         elif M == 106:  #Enable fan
250                                                 pass
251                                         elif M == 107:  #Disable fan
252                                                 pass
253                                         elif M == 108:  #Extruder RPM (these should not be in the final GCode, but they are)
254                                                 pass
255                                         elif M == 109:  #Set temperature, wait
256                                                 pass
257                                         elif M == 110:  #Reset N counter
258                                                 pass
259                                         elif M == 113:  #Extruder PWM (these should not be in the final GCode, but they are)
260                                                 pass
261                                         elif M == 117:  #LCD message
262                                                 pass
263                                         elif M == 140:  #Set bed temperature
264                                                 pass
265                                         elif M == 190:  #Set bed temperature & wait
266                                                 pass
267                                         elif M == 221:  #Extrude amount multiplier
268                                                 s = getCodeFloat(line, 'S')
269                                                 if s is not None:
270                                                         extrudeAmountMultiply = s / 100.0
271                                         else:
272                                                 print "Unknown M code:" + str(M)
273                 for path in currentLayer:
274                         path['points'] = numpy.array(path['points'], numpy.float32)
275                         path['extrusion'] = numpy.array(path['extrusion'], numpy.float32)
276                 self.layerList.append(currentLayer)
277                 if self.progressCallback is not None and self._fileSize > 0:
278                         self.progressCallback(float(gcodeFile.tell()) / float(self._fileSize))
279                 self.extrusionAmount = maxExtrusion
280                 self.totalMoveTimeMinute = totalMoveTimeMinute
281                 #print "Extruded a total of: %d mm of filament" % (self.extrusionAmount)
282                 #print "Estimated print duration: %.2f minutes" % (self.totalMoveTimeMinute)
283
284 def getCodeInt(line, code):
285         n = line.find(code) + 1
286         if n < 1:
287                 return None
288         m = line.find(' ', n)
289         try:
290                 if m < 0:
291                         return int(line[n:])
292                 return int(line[n:m])
293         except:
294                 return None
295
296 def getCodeFloat(line, code):
297         n = line.find(code) + 1
298         if n < 1:
299                 return None
300         m = line.find(' ', n)
301         try:
302                 if m < 0:
303                         return float(line[n:])
304                 return float(line[n:m])
305         except:
306                 return None
307
308 if __name__ == '__main__':
309         t = time.time()
310         for filename in sys.argv[1:]:
311                 g = gcode()
312                 g.load(filename)
313                 print g.totalMoveTimeMinute
314         print time.time() - t
315