chiark / gitweb /
Show print time, filemant used and cost estimate after slicing.
[cura.git] / Cura / util / gcodeInterpreter.py
1 from __future__ import absolute_import
2 import __init__
3
4 import sys
5 import math
6 import re
7 import os
8
9 from util import util3d
10 from util import profile
11
12 class gcodePath():
13         def __init__(self, newType, pathType, startPoint):
14                 self.type = newType
15                 self.pathType = pathType
16                 self.list = [startPoint]
17
18 class gcode():
19         def __init__(self):
20                 self.regMatch = {}
21                 self.layerList = []
22                 self.extrusionAmount = 0
23                 self.totalMoveTimeMinute = 0
24                 self.progressCallback = None
25         
26         def load(self, filename):
27                 self._fileSize = os.stat(filename).st_size
28                 gcodeFile = open(filename, 'r')
29                 self._load(gcodeFile)
30                 gcodeFile.close()
31         
32         def loadList(self, l):
33                 self._load(l)
34         
35         def calculateWeight(self):
36                 #Calculates the weight of the filament in kg
37                 radius = float(profile.getProfileSetting('filament_diameter')) / 2
38                 volumeM3 = (self.extrusionAmount * (math.pi * radius * radius)) / (1000*1000*1000)
39                 return volumeM3 * float(profile.getPreference('filament_density'))
40         
41         def calculateCost(self):
42                 cost_kg = float(profile.getPreference('filament_cost_kg'))
43                 cost_meter = float(profile.getPreference('filament_cost_meter'))
44                 if cost_kg > 0.0 and cost_meter > 0.0:
45                         return "%.2f / %.2f" % (self.calculateWeight() * cost_kg, self.extrusionAmount / 1000 * cost_meter)
46                 elif cost_kg > 0.0:
47                         return "%.2f" % (self.calculateWeight() * cost_kg)
48                 elif cost_meter > 0.0:
49                         return "%.2f" % (self.extrusionAmount / 1000 * cost_meter)
50                 return False
51         
52         def _load(self, gcodeFile):
53                 filePos = 0
54                 pos = util3d.Vector3()
55                 posOffset = util3d.Vector3()
56                 currentE = 0.0
57                 totalExtrusion = 0.0
58                 maxExtrusion = 0.0
59                 totalMoveTimeMinute = 0.0
60                 scale = 1.0
61                 posAbs = True
62                 feedRate = 3600
63                 pathType = 'CUSTOM';
64                 startCodeDone = False
65                 currentLayer = []
66                 currentPath = gcodePath('move', pathType, pos.copy())
67                 currentPath.list[0].e = totalExtrusion
68                 currentLayer.append(currentPath)
69                 for line in gcodeFile:
70                         if self.progressCallback != None:
71                                 if filePos != gcodeFile.tell():
72                                         filePos = gcodeFile.tell()
73                                         self.progressCallback(float(filePos) / float(self._fileSize))
74                         
75                         #Parse Cura_SF comments
76                         if line.startswith(';TYPE:'):
77                                 pathType = line[6:].strip()
78                                 if pathType != "CUSTOM":
79                                         startCodeDone = True
80                                         
81                         if ';' in line:
82                                 #Slic3r GCode comment parser
83                                 comment = line[line.find(';')+1:].strip()
84                                 if comment == 'fill':
85                                         pathType = 'FILL'
86                                 elif comment == 'perimeter':
87                                         pathType = 'WALL-INNER'
88                                 elif comment == 'skirt':
89                                         pathType = 'SKIRT'
90                                 if pathType != "CUSTOM":
91                                         startCodeDone = True
92                                 line = line[0:line.find(';')]
93                         
94                         G = self.getCodeInt(line, 'G')
95                         if G is not None:
96                                 if G == 0 or G == 1:    #Move
97                                         x = self.getCodeFloat(line, 'X')
98                                         y = self.getCodeFloat(line, 'Y')
99                                         z = self.getCodeFloat(line, 'Z')
100                                         e = self.getCodeFloat(line, 'E')
101                                         f = self.getCodeFloat(line, 'F')
102                                         oldPos = pos.copy()
103                                         if x is not None:
104                                                 if posAbs:
105                                                         pos.x = x * scale
106                                                 else:
107                                                         pos.x += x * scale
108                                         if y is not None:
109                                                 if posAbs:
110                                                         pos.y = y * scale
111                                                 else:
112                                                         pos.y += y * scale
113                                         if z is not None:
114                                                 if posAbs:
115                                                         pos.z = z * scale
116                                                 else:
117                                                         pos.z += z * scale
118                                                 #Check if we have a new layer.
119                                                 if oldPos.z < pos.z and startCodeDone and len(currentLayer) > 0:
120                                                         self.layerList.append(currentLayer)
121                                                         currentLayer = []
122                                         if f is not None:
123                                                 feedRate = f
124                                         if x is not None or y is not None or z is not None:
125                                                 totalMoveTimeMinute += (oldPos - pos).vsize() / feedRate
126                                         moveType = 'move'
127                                         if e is not None:
128                                                 if posAbs:
129                                                         if e > currentE:
130                                                                 moveType = 'extrude'
131                                                         if e < currentE:
132                                                                 moveType = 'retract'
133                                                         totalExtrusion += e - currentE
134                                                         currentE = e
135                                                 else:
136                                                         if e > 0:
137                                                                 moveType = 'extrude'
138                                                         if e < 0:
139                                                                 moveType = 'retract'
140                                                         totalExtrusion += e
141                                                         currentE += e
142                                                 if totalExtrusion > maxExtrusion:
143                                                         maxExtrusion = totalExtrusion
144                                         if currentPath.type != moveType or currentPath.pathType != pathType:
145                                                 currentPath = gcodePath(moveType, pathType, currentPath.list[-1])
146                                                 currentLayer.append(currentPath)
147                                         newPos = pos.copy()
148                                         newPos.e = totalExtrusion
149                                         currentPath.list.append(newPos)
150                                 elif G == 20:   #Units are inches
151                                         scale = 25.4
152                                 elif G == 21:   #Units are mm
153                                         scale = 1.0
154                                 elif G == 28:   #Home
155                                         x = self.getCodeFloat(line, 'X')
156                                         y = self.getCodeFloat(line, 'Y')
157                                         z = self.getCodeFloat(line, 'Z')
158                                         if x is None and y is None and z is None:
159                                                 pos = util3d.Vector3()
160                                         else:
161                                                 if x is not None:
162                                                         pos.x = 0.0
163                                                 if y is not None:
164                                                         pos.y = 0.0
165                                                 if z is not None:
166                                                         pos.z = 0.0
167                                 elif G == 90:   #Absolute position
168                                         posAbs = True
169                                 elif G == 91:   #Relative position
170                                         posAbs = False
171                                 elif G == 92:
172                                         x = self.getCodeFloat(line, 'X')
173                                         y = self.getCodeFloat(line, 'Y')
174                                         z = self.getCodeFloat(line, 'Z')
175                                         e = self.getCodeFloat(line, 'E')
176                                         if e is not None:
177                                                 currentE = e
178                                         if x is not None:
179                                                 posOffset.x = pos.x + x
180                                         if y is not None:
181                                                 posOffset.y = pos.y + y
182                                         if z is not None:
183                                                 posOffset.z = pos.z + z
184                                 else:
185                                         print "Unknown G code:" + str(G)
186                         else:
187                                 M = self.getCodeInt(line, 'M')
188                                 if M is not None:
189                                         if M == 1:      #Message with possible wait (ignored)
190                                                 pass
191                                         elif M == 84:   #Disable step drivers
192                                                 pass
193                                         elif M == 92:   #Set steps per unit
194                                                 pass
195                                         elif M == 104:  #Set temperature, no wait
196                                                 pass
197                                         elif M == 105:  #Get temperature
198                                                 pass
199                                         elif M == 106:  #Enable fan
200                                                 pass
201                                         elif M == 107:  #Disable fan
202                                                 pass
203                                         elif M == 108:  #Extruder RPM (these should not be in the final GCode, but they are)
204                                                 pass
205                                         elif M == 109:  #Set temperature, wait
206                                                 pass
207                                         elif M == 113:  #Extruder PWM (these should not be in the final GCode, but they are)
208                                                 pass
209                                         else:
210                                                 print "Unknown M code:" + str(M)
211                 self.layerList.append(currentLayer)
212                 self.extrusionAmount = maxExtrusion
213                 self.totalMoveTimeMinute = totalMoveTimeMinute
214                 #print "Extruded a total of: %d mm of filament" % (self.extrusionAmount)
215                 #print "Estimated print duration: %.2f minutes" % (self.totalMoveTimeMinute)
216
217         def getCodeInt(self, line, code):
218                 if code not in self.regMatch:
219                         self.regMatch[code] = re.compile(code + '([^\s]+)')
220                 m = self.regMatch[code].search(line)
221                 if m == None:
222                         return None
223                 try:
224                         return int(m.group(1))
225                 except:
226                         return None
227
228         def getCodeFloat(self, line, code):
229                 if code not in self.regMatch:
230                         self.regMatch[code] = re.compile(code + '([^\s]+)')
231                 m = self.regMatch[code].search(line)
232                 if m == None:
233                         return None
234                 try:
235                         return float(m.group(1))
236                 except:
237                         return None
238
239 if __name__ == '__main__':
240         for filename in sys.argv[1:]:
241                 gcode().load(filename)
242