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