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