PrintInformation.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty
  4. from UM.FlameProfiler import pyqtSlot
  5. from UM.Application import Application
  6. from UM.Logger import Logger
  7. from UM.Qt.Duration import Duration
  8. from UM.Preferences import Preferences
  9. from UM.Settings.ContainerRegistry import ContainerRegistry
  10. from cura.Settings.ExtruderManager import ExtruderManager
  11. import math
  12. import os.path
  13. import unicodedata
  14. import json
  15. from UM.i18n import i18nCatalog
  16. catalog = i18nCatalog("cura")
  17. ## A class for processing and calculating minimum, current and maximum print time as well as managing the job name
  18. #
  19. # This class contains all the logic relating to calculation and slicing for the
  20. # time/quality slider concept. It is a rather tricky combination of event handling
  21. # and state management. The logic behind this is as follows:
  22. #
  23. # - A scene change or setting change event happens.
  24. # We track what the source was of the change, either a scene change, a setting change, an active machine change or something else.
  25. # - This triggers a new slice with the current settings - this is the "current settings pass".
  26. # - When the slice is done, we update the current print time and material amount.
  27. # - If the source of the slice was not a Setting change, we start the second slice pass, the "low quality settings pass". Otherwise we stop here.
  28. # - When that is done, we update the minimum print time and start the final slice pass, the "Extra Fine settings pass".
  29. # - When the Extra Fine pass is done, we update the maximum print time.
  30. #
  31. # This class also mangles the current machine name and the filename of the first loaded mesh into a job name.
  32. # This job name is requested by the JobSpecs qml file.
  33. class PrintInformation(QObject):
  34. class SlicePass:
  35. CurrentSettings = 1
  36. LowQualitySettings = 2
  37. HighQualitySettings = 3
  38. class SliceReason:
  39. SceneChanged = 1
  40. SettingChanged = 2
  41. ActiveMachineChanged = 3
  42. Other = 4
  43. def __init__(self, parent = None):
  44. super().__init__(parent)
  45. self._current_print_time = Duration(None, self)
  46. self._print_times_per_feature = {
  47. "none": Duration(None, self),
  48. "inset_0": Duration(None, self),
  49. "inset_x": Duration(None, self),
  50. "skin": Duration(None, self),
  51. "support": Duration(None, self),
  52. "skirt": Duration(None, self),
  53. "infill": Duration(None, self),
  54. "support_infill": Duration(None, self),
  55. "travel": Duration(None, self),
  56. "retract": Duration(None, self),
  57. "support_interface": Duration(None, self)
  58. }
  59. self._material_lengths = []
  60. self._material_weights = []
  61. self._material_costs = []
  62. self._pre_sliced = False
  63. self._backend = Application.getInstance().getBackend()
  64. if self._backend:
  65. self._backend.printDurationMessage.connect(self._onPrintDurationMessage)
  66. self._base_name = ""
  67. self._abbr_machine = ""
  68. self._job_name = ""
  69. Application.getInstance().globalContainerStackChanged.connect(self._setAbbreviatedMachineName)
  70. Application.getInstance().fileLoaded.connect(self.setBaseName)
  71. Preferences.getInstance().preferenceChanged.connect(self._onPreferencesChanged)
  72. self._active_material_container = None
  73. Application.getInstance().getMachineManager().activeMaterialChanged.connect(self._onActiveMaterialChanged)
  74. self._onActiveMaterialChanged()
  75. self._material_amounts = []
  76. currentPrintTimeChanged = pyqtSignal()
  77. preSlicedChanged = pyqtSignal()
  78. @pyqtProperty(bool, notify=preSlicedChanged)
  79. def preSliced(self):
  80. return self._pre_sliced
  81. def setPreSliced(self, pre_sliced):
  82. self._pre_sliced = pre_sliced
  83. self.preSlicedChanged.emit()
  84. @pyqtProperty(Duration, notify = currentPrintTimeChanged)
  85. def currentPrintTime(self):
  86. return self._current_print_time
  87. @pyqtProperty("QVariantMap", notify = currentPrintTimeChanged)
  88. def printTimesPerFeature(self):
  89. return self._print_times_per_feature
  90. materialLengthsChanged = pyqtSignal()
  91. @pyqtProperty("QVariantList", notify = materialLengthsChanged)
  92. def materialLengths(self):
  93. return self._material_lengths
  94. materialWeightsChanged = pyqtSignal()
  95. @pyqtProperty("QVariantList", notify = materialWeightsChanged)
  96. def materialWeights(self):
  97. return self._material_weights
  98. materialCostsChanged = pyqtSignal()
  99. @pyqtProperty("QVariantList", notify = materialCostsChanged)
  100. def materialCosts(self):
  101. return self._material_costs
  102. def _onPrintDurationMessage(self, time_per_feature, material_amounts):
  103. total_time = 0
  104. for feature, time in time_per_feature.items():
  105. if time != time: # Check for NaN. Engine can sometimes give us weird values.
  106. self._print_times_per_feature[feature].setDuration(0)
  107. Logger.log("w", "Received NaN for print duration message")
  108. continue
  109. total_time += time
  110. self._print_times_per_feature[feature].setDuration(time)
  111. self._current_print_time.setDuration(total_time)
  112. self.currentPrintTimeChanged.emit()
  113. self._material_amounts = material_amounts
  114. self._calculateInformation()
  115. def _calculateInformation(self):
  116. if Application.getInstance().getGlobalContainerStack() is None:
  117. return
  118. # Material amount is sent as an amount of mm^3, so calculate length from that
  119. radius = Application.getInstance().getGlobalContainerStack().getProperty("material_diameter", "value") / 2
  120. self._material_lengths = []
  121. self._material_weights = []
  122. self._material_costs = []
  123. material_preference_values = json.loads(Preferences.getInstance().getValue("cura/material_settings"))
  124. extruder_stacks = list(ExtruderManager.getInstance().getMachineExtruders(Application.getInstance().getGlobalContainerStack().getId()))
  125. for index, amount in enumerate(self._material_amounts):
  126. ## Find the right extruder stack. As the list isn't sorted because it's a annoying generator, we do some
  127. # list comprehension filtering to solve this for us.
  128. material = None
  129. if extruder_stacks: # Multi extrusion machine
  130. extruder_stack = [extruder for extruder in extruder_stacks if extruder.getMetaDataEntry("position") == str(index)][0]
  131. density = extruder_stack.getMetaDataEntry("properties", {}).get("density", 0)
  132. material = extruder_stack.findContainer({"type": "material"})
  133. else: # Machine with no extruder stacks
  134. density = Application.getInstance().getGlobalContainerStack().getMetaDataEntry("properties", {}).get("density", 0)
  135. material = Application.getInstance().getGlobalContainerStack().findContainer({"type": "material"})
  136. weight = float(amount) * float(density) / 1000
  137. cost = 0
  138. if material:
  139. material_guid = material.getMetaDataEntry("GUID")
  140. if material_guid in material_preference_values:
  141. material_values = material_preference_values[material_guid]
  142. weight_per_spool = float(material_values["spool_weight"] if material_values and "spool_weight" in material_values else 0)
  143. cost_per_spool = float(material_values["spool_cost"] if material_values and "spool_cost" in material_values else 0)
  144. if weight_per_spool != 0:
  145. cost = cost_per_spool * weight / weight_per_spool
  146. else:
  147. cost = 0
  148. if radius != 0:
  149. length = round((amount / (math.pi * radius ** 2)) / 1000, 2)
  150. else:
  151. length = 0
  152. self._material_weights.append(weight)
  153. self._material_lengths.append(length)
  154. self._material_costs.append(cost)
  155. self.materialLengthsChanged.emit()
  156. self.materialWeightsChanged.emit()
  157. self.materialCostsChanged.emit()
  158. def _onPreferencesChanged(self, preference):
  159. if preference != "cura/material_settings":
  160. return
  161. self._calculateInformation()
  162. def _onActiveMaterialChanged(self):
  163. if self._active_material_container:
  164. try:
  165. self._active_material_container.metaDataChanged.disconnect(self._onMaterialMetaDataChanged)
  166. except TypeError: #pyQtSignal gives a TypeError when disconnecting from something that is already disconnected.
  167. pass
  168. active_material_id = Application.getInstance().getMachineManager().activeMaterialId
  169. active_material_containers = ContainerRegistry.getInstance().findInstanceContainers(id=active_material_id)
  170. if active_material_containers:
  171. self._active_material_container = active_material_containers[0]
  172. self._active_material_container.metaDataChanged.connect(self._onMaterialMetaDataChanged)
  173. def _onMaterialMetaDataChanged(self, *args, **kwargs):
  174. self._calculateInformation()
  175. @pyqtSlot(str)
  176. def setJobName(self, name):
  177. self._job_name = name
  178. self.jobNameChanged.emit()
  179. jobNameChanged = pyqtSignal()
  180. @pyqtProperty(str, notify = jobNameChanged)
  181. def jobName(self):
  182. return self._job_name
  183. def _updateJobName(self):
  184. if self._base_name == "":
  185. self._job_name = ""
  186. self.jobNameChanged.emit()
  187. return
  188. base_name = self._stripAccents(self._base_name)
  189. self._setAbbreviatedMachineName()
  190. if self._pre_sliced:
  191. self._job_name = catalog.i18nc("@label", "Pre-sliced file {0}", base_name)
  192. elif Preferences.getInstance().getValue("cura/jobname_prefix"):
  193. # Don't add abbreviation if it already has the exact same abbreviation.
  194. if base_name.startswith(self._abbr_machine + "_"):
  195. self._job_name = base_name
  196. else:
  197. self._job_name = self._abbr_machine + "_" + base_name
  198. else:
  199. self._job_name = base_name
  200. self.jobNameChanged.emit()
  201. @pyqtProperty(str)
  202. def baseName(self):
  203. return self._base_name
  204. @pyqtSlot(str)
  205. def setBaseName(self, base_name):
  206. # Ensure that we don't use entire path but only filename
  207. name = os.path.basename(base_name)
  208. # when a file is opened using the terminal; the filename comes from _onFileLoaded and still contains its
  209. # extension. This cuts the extension off if necessary.
  210. name = os.path.splitext(name)[0]
  211. # name is "" when I first had some meshes and afterwards I deleted them so the naming should start again
  212. if name == "" or (self._base_name == "" and self._base_name != name):
  213. self._base_name = name
  214. self._updateJobName()
  215. ## Created an acronymn-like abbreviated machine name from the currently active machine name
  216. # Called each time the global stack is switched
  217. def _setAbbreviatedMachineName(self):
  218. global_container_stack = Application.getInstance().getGlobalContainerStack()
  219. if not global_container_stack:
  220. self._abbr_machine = ""
  221. return
  222. global_stack_name = global_container_stack.getName()
  223. split_name = global_stack_name.split(" ")
  224. abbr_machine = ""
  225. for word in split_name:
  226. if word.lower() == "ultimaker":
  227. abbr_machine += "UM"
  228. elif word.isdigit():
  229. abbr_machine += word
  230. else:
  231. abbr_machine += self._stripAccents(word.strip("()[]{}#").upper())[0]
  232. self._abbr_machine = abbr_machine
  233. ## Utility method that strips accents from characters (eg: â -> a)
  234. def _stripAccents(self, str):
  235. return ''.join(char for char in unicodedata.normalize('NFD', str) if unicodedata.category(char) != 'Mn')