1 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
13 from Cura.util import profile
15 def getEngineFilename():
16 if platform.system() == 'Windows':
17 if os.path.exists('C:/Software/Cura_SteamEngine/_bin/Release/Cura_SteamEngine.exe'):
18 return 'C:/Software/Cura_SteamEngine/_bin/Release/Cura_SteamEngine.exe'
19 return os.path.abspath(os.path.join(os.path.dirname(__file__), '../..', 'CuraEngine.exe'))
20 if hasattr(sys, 'frozen'):
21 return os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../../..', 'CuraEngine'))
22 return os.path.abspath(os.path.join(os.path.dirname(__file__), '../..', 'CuraEngine'))
24 def getTempFilename():
25 warnings.simplefilter('ignore')
26 ret = os.tempnam(None, "Cura_Tmp")
27 warnings.simplefilter('default')
31 def __init__(self, progressCallback):
34 self._callback = progressCallback
35 self._binaryStorageFilename = getTempFilename()
36 self._exportFilename = getTempFilename()
37 self._progressSteps = ['inset', 'skin', 'export']
40 self._printTimeSeconds = None
41 self._filamentMM = None
46 os.remove(self._binaryStorageFilename)
50 os.remove(self._exportFilename)
54 def abortSlicer(self):
55 if self._process is not None:
57 self._process.terminate()
62 def getGCodeFilename(self):
63 return self._exportFilename
65 def getSliceLog(self):
68 def getFilamentWeight(self):
69 #Calculates the weight of the filament in kg
70 radius = float(profile.getProfileSetting('filament_diameter')) / 2
71 volumeM3 = (self._filamentMM * (math.pi * radius * radius)) / (1000*1000*1000)
72 return volumeM3 * profile.getPreferenceFloat('filament_physical_density')
74 def getFilamentCost(self):
75 cost_kg = profile.getPreferenceFloat('filament_cost_kg')
76 cost_meter = profile.getPreferenceFloat('filament_cost_meter')
77 if cost_kg > 0.0 and cost_meter > 0.0:
78 return "%.2f / %.2f" % (self.getFilamentWeight() * cost_kg, self._filamentMM / 1000.0 * cost_meter)
80 return "%.2f" % (self.getFilamentWeight() * cost_kg)
81 elif cost_meter > 0.0:
82 return "%.2f" % (self._filamentMM / 1000.0 * cost_meter)
85 def getPrintTime(self):
86 if int(self._printTimeSeconds / 60 / 60) < 1:
87 return '%d minutes' % (int(self._printTimeSeconds / 60) % 60)
88 if int(self._printTimeSeconds / 60 / 60) == 1:
89 return '%d hour %d minutes' % (int(self._printTimeSeconds / 60 / 60), int(self._printTimeSeconds / 60) % 60)
90 return '%d hours %d minutes' % (int(self._printTimeSeconds / 60 / 60), int(self._printTimeSeconds / 60) % 60)
92 def getFilamentAmount(self):
93 return '%0.2f meter %0.0f gram' % (float(self._filamentMM) / 1000.0, self.getFilamentWeight() * 1000.0)
95 def runSlicer(self, scene):
97 self._callback(-1.0, False)
99 commandList = [getEngineFilename(), '-vv']
100 for k, v in self._engineSettings().iteritems():
101 commandList += ['-s', '%s=%s' % (k, str(v))]
102 commandList += ['-o', self._exportFilename]
103 commandList += ['-b', self._binaryStorageFilename]
105 with open(self._binaryStorageFilename, "wb") as f:
106 order = scene.printOrder()
108 pos = numpy.array(profile.getMachineCenterCoords()) * 1000
109 commandList += ['-s', 'posx=%d' % int(pos[0]), '-s', 'posy=%d' % int(pos[1])]
112 for obj in scene.objects():
113 if scene.checkPlatform(obj):
114 for mesh in obj._meshList:
115 vertexTotal += mesh.vertexCount
117 f.write(numpy.array([vertexTotal], numpy.int32).tostring())
118 for obj in scene.objects():
119 if scene.checkPlatform(obj):
120 for mesh in obj._meshList:
121 vertexes = (numpy.matrix(mesh.vertexes, copy = False) * numpy.matrix(obj._matrix, numpy.float32)).getA()
122 vertexes -= obj._drawOffset
123 vertexes += numpy.array([obj.getPosition()[0], obj.getPosition()[1], 0.0])
124 f.write(vertexes.tostring())
130 obj = scene.objects()[n]
131 for mesh in obj._meshList:
132 f.write(numpy.array([mesh.vertexCount], numpy.int32).tostring())
133 f.write(mesh.vertexes.tostring())
134 pos = obj.getPosition() * 1000
135 pos += numpy.array(profile.getMachineCenterCoords()) * 1000
136 commandList += ['-m', ','.join(map(str, obj._matrix.getA().flatten()))]
137 commandList += ['-s', 'posx=%d' % int(pos[0]), '-s', 'posy=%d' % int(pos[1])]
138 commandList += ['#' * len(obj._meshList)]
140 if self._objCount > 0:
142 self._process = self._runSliceProcess(commandList)
143 self._thread = threading.Thread(target=self._watchProcess)
144 self._thread.daemon = True
147 traceback.print_exc()
149 def _watchProcess(self):
150 self._callback(0.0, False)
152 self._printTimeSeconds = None
153 self._filamentMM = None
155 line = self._process.stdout.readline()
159 if line.startswith('Progress:'):
160 line = line.split(':')
161 if line[1] == 'process':
163 elif line[1] in self._progressSteps:
164 progressValue = float(line[2]) / float(line[3])
165 progressValue /= len(self._progressSteps)
166 progressValue += 1.0 / len(self._progressSteps) * self._progressSteps.index(line[1])
168 progressValue /= self._objCount
169 progressValue += 1.0 / self._objCount * objectNr
171 self._callback(progressValue, False)
174 elif line.startswith('Print time:'):
175 self._printTimeSeconds = int(line.split(':')[1].strip())
176 elif line.startswith('Filament:'):
177 self._filamentMM = int(line.split(':')[1].strip())
179 self._sliceLog.append(line.strip())
180 line = self._process.stdout.readline()
181 for line in self._process.stderr:
182 self._sliceLog.append(line.strip())
183 returnCode = self._process.wait()
186 profile.runPostProcessingPlugins(self._exportFilename)
187 self._callback(1.0, True)
189 self._callback(-1.0, False)
194 def _engineSettings(self):
196 'layerThickness': int(profile.getProfileSettingFloat('layer_height') * 1000),
197 'initialLayerThickness': int(profile.getProfileSettingFloat('bottom_thickness') * 1000) if profile.getProfileSettingFloat('bottom_thickness') > 0.0 else int(profile.getProfileSettingFloat('layer_height') * 1000),
198 'filamentDiameter': int(profile.getProfileSettingFloat('filament_diameter') * 1000),
199 'filamentFlow': int(profile.getProfileSettingFloat('filament_flow')),
200 'extrusionWidth': int(profile.calculateEdgeWidth() * 1000),
201 'insetCount': int(profile.calculateLineCount()),
202 'downSkinCount': int(profile.calculateSolidLayerCount()) if profile.getProfileSetting('solid_bottom') == 'True' else 0,
203 'upSkinCount': int(profile.calculateSolidLayerCount()) if profile.getProfileSetting('solid_top') == 'True' else 0,
204 'sparseInfillLineDistance': int(100 * profile.calculateEdgeWidth() * 1000 / profile.getProfileSettingFloat('fill_density')) if profile.getProfileSettingFloat('fill_density') > 0 else -1,
205 'infillOverlap': int(profile.getProfileSettingFloat('fill_overlap')),
206 'initialSpeedupLayers': int(4),
207 'initialLayerSpeed': int(profile.getProfileSettingFloat('bottom_layer_speed')),
208 'printSpeed': int(profile.getProfileSettingFloat('print_speed')),
209 'infillSpeed': int(profile.getProfileSettingFloat('infill_speed')) if int(profile.getProfileSettingFloat('infill_speed')) > 0 else int(profile.getProfileSettingFloat('print_speed')),
210 'moveSpeed': int(profile.getProfileSettingFloat('travel_speed')),
211 'fanOnLayerNr': int(profile.getProfileSettingFloat('fan_layer')),
212 'fanSpeedMin': int(profile.getProfileSettingFloat('fan_speed')) if profile.getProfileSetting('fan_enabled') == 'True' else 0,
213 'fanSpeedMax': int(profile.getProfileSettingFloat('fan_speed_max')) if profile.getProfileSetting('fan_enabled') == 'True' else 0,
214 'supportAngle': int(-1) if profile.getProfileSetting('support') == 'None' else int(60),
215 'supportEverywhere': int(1) if profile.getProfileSetting('support') == 'Everywhere' else int(0),
216 'supportLineWidth': int(profile.getProfileSettingFloat('support_rate') * profile.calculateEdgeWidth() * 1000 / 100),
217 'retractionAmount': int(profile.getProfileSettingFloat('retraction_amount') * 1000),
218 'retractionSpeed': int(profile.getProfileSettingFloat('retraction_speed')),
219 'objectSink': int(profile.getProfileSettingFloat('object_sink') * 1000),
220 'minimalLayerTime': int(profile.getProfileSettingFloat('cool_min_layer_time')),
221 'minimalFeedrate': int(profile.getProfileSettingFloat('cool_min_feedrate')),
222 'coolHeadLift': 1 if profile.getProfileSetting('cool_head_lift') == 'True' else 0,
223 'startCode': profile.getAlterationFileContents('start.gcode'),
224 'endCode': profile.getAlterationFileContents('end.gcode'),
226 'extruderOffset[1].X': int(profile.getPreferenceFloat('extruder_offset_x1') * 1000),
227 'extruderOffset[1].Y': int(profile.getPreferenceFloat('extruder_offset_y1') * 1000),
228 'extruderOffset[2].X': int(profile.getPreferenceFloat('extruder_offset_x2') * 1000),
229 'extruderOffset[2].Y': int(profile.getPreferenceFloat('extruder_offset_y2') * 1000),
230 'extruderOffset[3].X': int(profile.getPreferenceFloat('extruder_offset_x3') * 1000),
231 'extruderOffset[3].Y': int(profile.getPreferenceFloat('extruder_offset_y3') * 1000),
234 if profile.getProfileSetting('platform_adhesion') == 'Brim':
235 settings['skirtDistance'] = 0
236 settings['skirtLineCount'] = int(profile.getProfileSettingFloat('brim_line_count'))
237 elif profile.getProfileSetting('platform_adhesion') == 'Raft':
238 settings['skirtDistance'] = 0
239 settings['skirtLineCount'] = 0
240 settings['raftMargin'] = int(profile.getProfileSettingFloat('raft_margin') * 1000);
241 settings['raftBaseThickness'] = int(profile.getProfileSettingFloat('raft_base_thickness') * 1000);
242 settings['raftBaseLinewidth'] = int(profile.getProfileSettingFloat('raft_base_linewidth') * 1000);
243 settings['raftInterfaceThickness'] = int(profile.getProfileSettingFloat('raft_interface_thickness') * 1000);
244 settings['raftInterfaceLinewidth'] = int(profile.getProfileSettingFloat('raft_interface_linewidth') * 1000);
246 settings['skirtDistance'] = int(profile.getProfileSettingFloat('skirt_gap') * 1000)
247 settings['skirtLineCount'] = int(profile.getProfileSettingFloat('skirt_line_count'))
249 if profile.getProfileSetting('fix_horrible_union_all_type_a') == 'True':
250 settings['fixHorrible'] |= 0x01
251 if profile.getProfileSetting('fix_horrible_union_all_type_b') == 'True':
252 settings['fixHorrible'] |= 0x02
253 if profile.getProfileSetting('fix_horrible_use_open_bits') == 'True':
254 settings['fixHorrible'] |= 0x10
256 if settings['layerThickness'] <= 0:
257 settings['layerThickness'] = 1000
260 def _runSliceProcess(self, cmdList):
262 if subprocess.mswindows:
263 su = subprocess.STARTUPINFO()
264 su.dwFlags |= subprocess.STARTF_USESHOWWINDOW
265 su.wShowWindow = subprocess.SW_HIDE
266 kwargs['startupinfo'] = su
267 kwargs['creationflags'] = 0x00004000 #BELOW_NORMAL_PRIORITY_CLASS
268 return subprocess.Popen(cmdList, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)