chiark / gitweb /
Add very basic GCode viewing.
[cura.git] / Cura / util / sliceEngine.py
1 import subprocess
2 import time
3 import numpy
4 import os
5 import warnings
6 import threading
7 import traceback
8 import platform
9
10 from Cura.util import profile
11
12 def getEngineFilename():
13         if platform.system() == 'Windows':
14                 if os.path.exists('C:/Software/Cura_SteamEngine/_bin/Release/Cura_SteamEngine.exe'):
15                         return 'C:/Software/Cura_SteamEngine/_bin/Release/Cura_SteamEngine.exe'
16                 return os.path.abspath(os.path.join(os.path.dirname(__file__), '../..', 'SteamEngine.exe'))
17         return os.path.abspath(os.path.join(os.path.dirname(__file__), '../..', 'SteamEngine'))
18
19 def getTempFilename():
20         warnings.simplefilter('ignore')
21         ret = os.tempnam(None, "Cura_Tmp")
22         warnings.simplefilter('default')
23         return ret
24
25 class Slicer(object):
26         def __init__(self, progressCallback):
27                 self._process = None
28                 self._thread = None
29                 self._callback = progressCallback
30                 self._binaryStorageFilename = getTempFilename()
31                 self._exportFilename = getTempFilename()
32                 self._progressSteps = ['inset', 'skin', 'export']
33                 self._objCount = 0
34
35         def cleanup(self):
36                 self.abortSlicer()
37                 os.remove(self._binaryStorageFilename)
38                 os.remove(self._exportFilename)
39
40         def abortSlicer(self):
41                 if self._process is not None:
42                         self._process.terminate()
43                         self._thread.join()
44
45         def getGCodeFilename(self):
46                 return self._exportFilename
47
48         def runSlicer(self, scene):
49                 self.abortSlicer()
50                 self._callback(0.0, False)
51
52                 commandList = [getEngineFilename(), '-vv']
53                 for k, v in self._engineSettings().iteritems():
54                         commandList += ['-s', '%s=%s' % (k, str(v))]
55                 commandList += ['-o', self._exportFilename]
56                 commandList += ['-b', self._binaryStorageFilename]
57                 self._objCount = 0
58                 with open(self._binaryStorageFilename, "wb") as f:
59                         for n in scene.printOrder():
60                                 obj = scene.objects()[n]
61                                 for mesh in obj._meshList:
62                                         n = numpy.array([mesh.vertexCount], numpy.int32)
63                                         f.write(n.tostring())
64                                         f.write(mesh.vertexes.tostring())
65                                 pos = obj.getPosition() * 1000
66                                 pos += numpy.array([profile.getPreferenceFloat('machine_width') * 1000 / 2, profile.getPreferenceFloat('machine_depth') * 1000 / 2])
67                                 commandList += ['-m', ','.join(map(str, obj._matrix.getA().flatten()))]
68                                 commandList += ['-s', 'posx=%d' % int(pos[0]), '-s', 'posy=%d' % int(pos[1])]
69                                 commandList += ['#' * len(obj._meshList)]
70                                 self._objCount += 1
71                 if self._objCount > 0:
72                         print ' '.join(commandList)
73                         try:
74                                 self._process = self._runSliceProcess(commandList)
75                                 self._thread = threading.Thread(target=self._watchProcess)
76                                 self._thread.daemon = True
77                                 self._thread.start()
78                         except OSError:
79                                 traceback.print_exc()
80
81         def _watchProcess(self):
82                 self._callback(0.0, False)
83                 line = self._process.stdout.readline()
84                 objectNr = 0
85                 while len(line):
86                         line = line.strip()
87                         if line.startswith('Progress:'):
88                                 line = line.split(':')
89                                 if line[1] == 'process':
90                                         objectNr += 1
91                                 else:
92                                         progressValue = float(line[2]) / float(line[3])
93                                         progressValue /= len(self._progressSteps)
94                                         progressValue += 1.0 / len(self._progressSteps) * self._progressSteps.index(line[1])
95
96                                         progressValue /= self._objCount
97                                         progressValue += 1.0 / self._objCount * objectNr
98                                         try:
99                                                 self._callback(progressValue, False)
100                                         except:
101                                                 pass
102                         else:
103                                 #print '#', line.strip()
104                                 pass
105                         line = self._process.stdout.readline()
106                 for line in self._process.stderr:
107                         print line.strip()
108                 returnCode = self._process.wait()
109                 print returnCode
110                 try:
111                         if returnCode == 0:
112                                 self._callback(1.0, True)
113                         else:
114                                 self._callback(0.0, False)
115                 except:
116                         pass
117                 self._process = None
118
119         def _engineSettings(self):
120                 return {
121                         'layerThickness': int(profile.getProfileSettingFloat('layer_height') * 1000),
122                         'initialLayerThickness': int(profile.getProfileSettingFloat('bottom_thickness') * 1000),
123                         'filamentDiameter': int(profile.getProfileSettingFloat('filament_diameter') * 1000),
124                         'extrusionWidth': int(profile.calculateEdgeWidth() * 1000),
125                         'insetCount': int(profile.calculateLineCount()),
126                         'downSkinCount': int(profile.calculateSolidLayerCount()),
127                         'upSkinCount': int(profile.calculateSolidLayerCount()),
128                         'sparseInfillLineDistance': int(100 * profile.calculateEdgeWidth() * 1000 / profile.getProfileSettingFloat('fill_density')) if profile.getProfileSettingFloat('fill_density') > 0 else 9999999999,
129                         'skirtDistance': int(profile.getProfileSettingFloat('skirt_gap') * 1000),
130                         'skirtLineCount': int(profile.getProfileSettingFloat('skirt_line_count')),
131                         'initialSpeedupLayers': int(4),
132                         'initialLayerSpeed': int(profile.getProfileSettingFloat('bottom_layer_speed')),
133                         'printSpeed': int(profile.getProfileSettingFloat('print_speed')),
134                         'moveSpeed': int(profile.getProfileSettingFloat('travel_speed')),
135                         'fanOnLayerNr': int(profile.getProfileSettingFloat('fan_layer')),
136                         'supportAngle': int(-1) if profile.getProfileSetting('support') == 'None' else int(60),
137                         'supportEverywhere': int(1) if profile.getProfileSetting('support') == 'Everywhere' else int(0),
138                         'retractionAmount': int(profile.getProfileSettingFloat('retraction_amount') * 1000),
139                         'retractionSpeed': int(profile.getProfileSettingFloat('retraction_speed')),
140                         'objectSink': int(profile.getProfileSettingFloat('object_sink') * 1000),
141                 }
142
143         def _runSliceProcess(self, cmdList):
144                 kwargs = {}
145                 if subprocess.mswindows:
146                         su = subprocess.STARTUPINFO()
147                         su.dwFlags |= subprocess.STARTF_USESHOWWINDOW
148                         su.wShowWindow = subprocess.SW_HIDE
149                         kwargs['startupinfo'] = su
150                         kwargs['creationflags'] = 0x00004000 #BELOW_NORMAL_PRIORITY_CLASS
151                 return subprocess.Popen(cmdList, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)