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