chiark / gitweb /
bunch of small things.
[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 abortSlicer(self):
36                 if self._process is not None:
37                         self._process.terminate()
38                         self._thread.join()
39
40         def getGCodeFilename(self):
41                 return self._exportFilename
42
43         def runSlicer(self, scene):
44                 self.abortSlicer()
45                 self._callback(0.0, False)
46
47                 commandList = [getEngineFilename(), '-vv']
48                 for k, v in self._engineSettings().iteritems():
49                         commandList += ['-s', '%s=%s' % (k, str(v))]
50                 commandList += ['-o', self._exportFilename]
51                 commandList += ['-b', self._binaryStorageFilename]
52                 self._objCount = 0
53                 with open(self._binaryStorageFilename, "wb") as f:
54                         for n in scene.printOrder():
55                                 obj = scene.objects()[n]
56                                 for mesh in obj._meshList:
57                                         n = numpy.array(mesh.vertexCount, numpy.int32)
58                                         f.write(n.tostring())
59                                         f.write(mesh.vertexes.tostring())
60                                 pos = obj.getPosition() * 1000
61                                 pos += numpy.array([profile.getPreferenceFloat('machine_width') * 1000 / 2, profile.getPreferenceFloat('machine_depth') * 1000 / 2])
62                                 commandList += ['-m', ','.join(map(str, obj._matrix.getA().flatten()))]
63                                 commandList += ['-s', 'posx=%d' % int(pos[0]), '-s', 'posy=%d' % int(pos[1]), '#']
64                                 self._objCount += 1
65                 if self._objCount > 0:
66                         print ' '.join(commandList)
67                         try:
68                                 self._process = self._runSliceProcess(commandList)
69                                 self._thread = threading.Thread(target=self._watchProcess)
70                                 self._thread.daemon = True
71                                 self._thread.start()
72                         except OSError:
73                                 traceback.print_exc()
74
75         def _watchProcess(self):
76                 self._callback(0.0, False)
77                 line = self._process.stdout.readline()
78                 objectNr = 0
79                 while len(line):
80                         line = line.strip()
81                         if line.startswith('Progress:'):
82                                 line = line.split(':')
83                                 if line[1] == 'process':
84                                         objectNr += 1
85                                 else:
86                                         progressValue = float(line[2]) / float(line[3])
87                                         progressValue /= len(self._progressSteps)
88                                         progressValue += 1.0 / len(self._progressSteps) * self._progressSteps.index(line[1])
89
90                                         progressValue /= self._objCount
91                                         progressValue += 1.0 / self._objCount * objectNr
92                                         self._callback(progressValue, False)
93                         else:
94                                 print '#', line.strip()
95                         line = self._process.stdout.readline()
96                 for line in self._process.stderr:
97                         print line.strip()
98                 returnCode = self._process.wait()
99                 print returnCode
100                 if returnCode == 0:
101                         self._callback(1.0, True)
102                 else:
103                         self._callback(0.0, False)
104                 self._process = None
105
106         def _engineSettings(self):
107                 return {
108                         'layerThickness': int(profile.getProfileSettingFloat('layer_height') * 1000),
109                         'initialLayerThickness': int(profile.getProfileSettingFloat('bottom_thickness') * 1000),
110                         'filamentDiameter': int(profile.getProfileSettingFloat('filament_diameter') * 1000),
111                         'extrusionWidth': int(profile.calculateEdgeWidth() * 1000),
112                         'insetCount': int(profile.calculateLineCount()),
113                         'downSkinCount': int(profile.calculateSolidLayerCount()),
114                         'upSkinCount': int(profile.calculateSolidLayerCount()),
115                         'sparseInfillLineDistance': int(100 * profile.calculateEdgeWidth() * 1000 / profile.getProfileSettingFloat('fill_density')),
116                         'skirtDistance': int(profile.getProfileSettingFloat('skirt_gap') * 1000),
117                         'skirtLineCount': int(profile.getProfileSettingFloat('skirt_line_count')),
118                         'initialSpeedupLayers': int(4),
119                         'initialLayerSpeed': int(profile.getProfileSettingFloat('bottom_layer_speed')),
120                         'printSpeed': int(profile.getProfileSettingFloat('print_speed')),
121                         'moveSpeed': int(profile.getProfileSettingFloat('travel_speed')),
122                         'fanOnLayerNr': int(profile.getProfileSettingFloat('fan_layer')),
123                         'supportAngle': int(-1) if profile.getProfileSetting('support') == 'None' else int(60),
124                         'supportEverywhere': int(1) if profile.getProfileSetting('support') == 'Everywhere' else int(0),
125                         'retractionAmount': int(profile.getProfileSettingFloat('retraction_amount') * 1000),
126                         'retractionSpeed': int(profile.getProfileSettingFloat('retraction_speed')),
127                         'objectSink': int(profile.getProfileSettingFloat('object_sink') * 1000),
128                 }
129
130         def _runSliceProcess(self, cmdList):
131                 kwargs = {}
132                 if subprocess.mswindows:
133                         su = subprocess.STARTUPINFO()
134                         su.dwFlags |= subprocess.STARTF_USESHOWWINDOW
135                         su.wShowWindow = subprocess.SW_HIDE
136                         kwargs['startupinfo'] = su
137                         kwargs['creationflags'] = 0x00004000 #BELOW_NORMAL_PRIORITY_CLASS
138                 return subprocess.Popen(cmdList, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)