mirror of
https://github.com/Ultimaker/Cura.git
synced 2025-08-07 14:04:03 -06:00
Merge remote-tracking branch 'um/master' into gcode-keywords
This commit is contained in:
commit
e47ca7a68d
379 changed files with 147832 additions and 59891 deletions
248
plugins/3MFReader/ThreeMFReader.py
Normal file → Executable file
248
plugins/3MFReader/ThreeMFReader.py
Normal file → Executable file
|
@ -11,15 +11,21 @@ from UM.Math.Vector import Vector
|
|||
from UM.Mesh.MeshBuilder import MeshBuilder
|
||||
from UM.Mesh.MeshReader import MeshReader
|
||||
from UM.Scene.GroupDecorator import GroupDecorator
|
||||
import UM.Application
|
||||
from cura.Settings.SettingOverrideDecorator import SettingOverrideDecorator
|
||||
from UM.Application import Application
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
from cura.QualityManager import QualityManager
|
||||
from UM.Scene.SceneNode import SceneNode
|
||||
from cura.SliceableObjectDecorator import SliceableObjectDecorator
|
||||
|
||||
MYPY = False
|
||||
|
||||
import Savitar
|
||||
import numpy
|
||||
|
||||
try:
|
||||
import xml.etree.cElementTree as ET
|
||||
if not MYPY:
|
||||
import xml.etree.cElementTree as ET
|
||||
except ImportError:
|
||||
Logger.log("w", "Unable to load cElementTree, switching to slower version")
|
||||
import xml.etree.ElementTree as ET
|
||||
|
@ -37,98 +43,10 @@ class ThreeMFReader(MeshReader):
|
|||
self._base_name = ""
|
||||
self._unit = None
|
||||
|
||||
def _createNodeFromObject(self, object, name = ""):
|
||||
node = SceneNode()
|
||||
node.setName(name)
|
||||
mesh_builder = MeshBuilder()
|
||||
vertex_list = []
|
||||
|
||||
components = object.find(".//3mf:components", self._namespaces)
|
||||
if components:
|
||||
for component in components:
|
||||
id = component.get("objectid")
|
||||
new_object = self._root.find("./3mf:resources/3mf:object[@id='{0}']".format(id), self._namespaces)
|
||||
new_node = self._createNodeFromObject(new_object, self._base_name + "_" + str(id))
|
||||
node.addChild(new_node)
|
||||
transform = component.get("transform")
|
||||
if transform is not None:
|
||||
new_node.setTransformation(self._createMatrixFromTransformationString(transform))
|
||||
|
||||
# for vertex in entry.mesh.vertices.vertex:
|
||||
for vertex in object.findall(".//3mf:vertex", self._namespaces):
|
||||
vertex_list.append([vertex.get("x"), vertex.get("y"), vertex.get("z")])
|
||||
Job.yieldThread()
|
||||
|
||||
xml_settings = list(object.findall(".//cura:setting", self._namespaces))
|
||||
|
||||
# Add the setting override decorator, so we can add settings to this node.
|
||||
if xml_settings:
|
||||
node.addDecorator(SettingOverrideDecorator())
|
||||
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
# Ensure the correct next container for the SettingOverride decorator is set.
|
||||
if global_container_stack:
|
||||
multi_extrusion = global_container_stack.getProperty("machine_extruder_count", "value") > 1
|
||||
# Ensure that all extruder data is reset
|
||||
if not multi_extrusion:
|
||||
default_stack_id = global_container_stack.getId()
|
||||
else:
|
||||
default_stack = ExtruderManager.getInstance().getExtruderStack(0)
|
||||
if default_stack:
|
||||
default_stack_id = default_stack.getId()
|
||||
else:
|
||||
default_stack_id = global_container_stack.getId()
|
||||
node.callDecoration("setActiveExtruder", default_stack_id)
|
||||
|
||||
# Get the definition & set it
|
||||
definition = QualityManager.getInstance().getParentMachineDefinition(global_container_stack.getBottom())
|
||||
node.callDecoration("getStack").getTop().setDefinition(definition)
|
||||
|
||||
setting_container = node.callDecoration("getStack").getTop()
|
||||
for setting in xml_settings:
|
||||
setting_key = setting.get("key")
|
||||
setting_value = setting.text
|
||||
|
||||
# Extruder_nr is a special case.
|
||||
if setting_key == "extruder_nr":
|
||||
extruder_stack = ExtruderManager.getInstance().getExtruderStack(int(setting_value))
|
||||
if extruder_stack:
|
||||
node.callDecoration("setActiveExtruder", extruder_stack.getId())
|
||||
else:
|
||||
Logger.log("w", "Unable to find extruder in position %s", setting_value)
|
||||
continue
|
||||
setting_container.setProperty(setting_key,"value", setting_value)
|
||||
|
||||
if len(node.getChildren()) > 0:
|
||||
group_decorator = GroupDecorator()
|
||||
node.addDecorator(group_decorator)
|
||||
|
||||
triangles = object.findall(".//3mf:triangle", self._namespaces)
|
||||
mesh_builder.reserveFaceCount(len(triangles))
|
||||
|
||||
for triangle in triangles:
|
||||
v1 = int(triangle.get("v1"))
|
||||
v2 = int(triangle.get("v2"))
|
||||
v3 = int(triangle.get("v3"))
|
||||
|
||||
mesh_builder.addFaceByPoints(vertex_list[v1][0], vertex_list[v1][1], vertex_list[v1][2],
|
||||
vertex_list[v2][0], vertex_list[v2][1], vertex_list[v2][2],
|
||||
vertex_list[v3][0], vertex_list[v3][1], vertex_list[v3][2])
|
||||
|
||||
Job.yieldThread()
|
||||
|
||||
# TODO: We currently do not check for normals and simply recalculate them.
|
||||
mesh_builder.calculateNormals(fast=True)
|
||||
mesh_builder.setFileName(name)
|
||||
mesh_data = mesh_builder.build()
|
||||
|
||||
if len(mesh_data.getVertices()):
|
||||
node.setMeshData(mesh_data)
|
||||
|
||||
node.setSelectable(True)
|
||||
return node
|
||||
|
||||
def _createMatrixFromTransformationString(self, transformation):
|
||||
if transformation == "":
|
||||
return Matrix()
|
||||
|
||||
splitted_transformation = transformation.split()
|
||||
## Transformation is saved as:
|
||||
## M00 M01 M02 0.0
|
||||
|
@ -155,53 +73,110 @@ class ThreeMFReader(MeshReader):
|
|||
|
||||
return temp_mat
|
||||
|
||||
|
||||
## Convenience function that converts a SceneNode object (as obtained from libSavitar) to a Uranium scenenode.
|
||||
# \returns Uranium Scenen node.
|
||||
def _convertSavitarNodeToUMNode(self, savitar_node):
|
||||
um_node = SceneNode()
|
||||
transformation = self._createMatrixFromTransformationString(savitar_node.getTransformation())
|
||||
um_node.setTransformation(transformation)
|
||||
mesh_builder = MeshBuilder()
|
||||
|
||||
data = numpy.fromstring(savitar_node.getMeshData().getFlatVerticesAsBytes(), dtype=numpy.float32)
|
||||
|
||||
vertices = numpy.resize(data, (int(data.size / 3), 3))
|
||||
mesh_builder.setVertices(vertices)
|
||||
mesh_builder.calculateNormals(fast=True)
|
||||
mesh_data = mesh_builder.build()
|
||||
|
||||
if len(mesh_data.getVertices()):
|
||||
um_node.setMeshData(mesh_data)
|
||||
|
||||
for child in savitar_node.getChildren():
|
||||
child_node = self._convertSavitarNodeToUMNode(child)
|
||||
if child_node:
|
||||
um_node.addChild(child_node)
|
||||
|
||||
if um_node.getMeshData() is None and len(um_node.getChildren()) == 0:
|
||||
return None
|
||||
|
||||
settings = savitar_node.getSettings()
|
||||
|
||||
# Add the setting override decorator, so we can add settings to this node.
|
||||
if settings:
|
||||
um_node.addDecorator(SettingOverrideDecorator())
|
||||
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
# Ensure the correct next container for the SettingOverride decorator is set.
|
||||
if global_container_stack:
|
||||
multi_extrusion = global_container_stack.getProperty("machine_extruder_count", "value") > 1
|
||||
|
||||
# Ensure that all extruder data is reset
|
||||
if not multi_extrusion:
|
||||
default_stack_id = global_container_stack.getId()
|
||||
else:
|
||||
default_stack = ExtruderManager.getInstance().getExtruderStack(0)
|
||||
if default_stack:
|
||||
default_stack_id = default_stack.getId()
|
||||
else:
|
||||
default_stack_id = global_container_stack.getId()
|
||||
um_node.callDecoration("setActiveExtruder", default_stack_id)
|
||||
|
||||
# Get the definition & set it
|
||||
definition = QualityManager.getInstance().getParentMachineDefinition(global_container_stack.getBottom())
|
||||
um_node.callDecoration("getStack").getTop().setDefinition(definition)
|
||||
|
||||
setting_container = um_node.callDecoration("getStack").getTop()
|
||||
|
||||
for key in settings:
|
||||
setting_value = settings[key]
|
||||
|
||||
# Extruder_nr is a special case.
|
||||
if key == "extruder_nr":
|
||||
extruder_stack = ExtruderManager.getInstance().getExtruderStack(int(setting_value))
|
||||
if extruder_stack:
|
||||
um_node.callDecoration("setActiveExtruder", extruder_stack.getId())
|
||||
else:
|
||||
Logger.log("w", "Unable to find extruder in position %s", setting_value)
|
||||
continue
|
||||
setting_container.setProperty(key,"value", setting_value)
|
||||
|
||||
if len(um_node.getChildren()) > 0:
|
||||
group_decorator = GroupDecorator()
|
||||
um_node.addDecorator(group_decorator)
|
||||
um_node.setSelectable(True)
|
||||
if um_node.getMeshData():
|
||||
# Assuming that all nodes with mesh data are printable objects
|
||||
# affects (auto) slicing
|
||||
sliceable_decorator = SliceableObjectDecorator()
|
||||
um_node.addDecorator(sliceable_decorator)
|
||||
return um_node
|
||||
|
||||
def read(self, file_name):
|
||||
result = []
|
||||
# The base object of 3mf is a zipped archive.
|
||||
archive = zipfile.ZipFile(file_name, "r")
|
||||
self._base_name = os.path.basename(file_name)
|
||||
try:
|
||||
self._root = ET.parse(archive.open("3D/3dmodel.model"))
|
||||
self._unit = self._root.getroot().get("unit")
|
||||
|
||||
build_items = self._root.findall("./3mf:build/3mf:item", self._namespaces)
|
||||
|
||||
for build_item in build_items:
|
||||
id = build_item.get("objectid")
|
||||
object = self._root.find("./3mf:resources/3mf:object[@id='{0}']".format(id), self._namespaces)
|
||||
if "type" in object.attrib:
|
||||
if object.attrib["type"] == "support" or object.attrib["type"] == "other":
|
||||
# Ignore support objects, as cura does not support these.
|
||||
# We can't guarantee that they wont be made solid.
|
||||
# We also ignore "other", as I have no idea what to do with them.
|
||||
Logger.log("w", "3MF file contained an object of type %s which is not supported by Cura", object.attrib["type"])
|
||||
continue
|
||||
elif object.attrib["type"] == "solidsupport" or object.attrib["type"] == "model":
|
||||
pass # Load these as normal
|
||||
else:
|
||||
# We should technically fail at this point because it's an invalid 3MF, but try to continue anyway.
|
||||
Logger.log("e", "3MF file contained an object of type %s which is not supported by the 3mf spec",
|
||||
object.attrib["type"])
|
||||
continue
|
||||
|
||||
build_item_node = self._createNodeFromObject(object, self._base_name + "_" + str(id))
|
||||
|
||||
archive = zipfile.ZipFile(file_name, "r")
|
||||
self._base_name = os.path.basename(file_name)
|
||||
parser = Savitar.ThreeMFParser()
|
||||
scene_3mf = parser.parse(archive.open("3D/3dmodel.model").read())
|
||||
self._unit = scene_3mf.getUnit()
|
||||
for node in scene_3mf.getSceneNodes():
|
||||
um_node = self._convertSavitarNodeToUMNode(node)
|
||||
if um_node is None:
|
||||
continue
|
||||
# compensate for original center position, if object(s) is/are not around its zero position
|
||||
|
||||
transform_matrix = Matrix()
|
||||
mesh_data = build_item_node.getMeshData()
|
||||
mesh_data = um_node.getMeshData()
|
||||
if mesh_data is not None:
|
||||
extents = mesh_data.getExtents()
|
||||
center_vector = Vector(extents.center.x, extents.center.y, extents.center.z)
|
||||
transform_matrix.setByTranslation(center_vector)
|
||||
transform_matrix.multiply(um_node.getLocalTransformation())
|
||||
um_node.setTransformation(transform_matrix)
|
||||
|
||||
# offset with transform from 3mf
|
||||
transform = build_item.get("transform")
|
||||
if transform is not None:
|
||||
transform_matrix.multiply(self._createMatrixFromTransformationString(transform))
|
||||
|
||||
build_item_node.setTransformation(transform_matrix)
|
||||
|
||||
global_container_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
|
||||
# Create a transformation Matrix to convert from 3mf worldspace into ours.
|
||||
# First step: flip the y and z axis.
|
||||
|
@ -214,9 +189,9 @@ class ThreeMFReader(MeshReader):
|
|||
# Second step: 3MF defines the left corner of the machine as center, whereas cura uses the center of the
|
||||
# build volume.
|
||||
if global_container_stack:
|
||||
translation_vector = Vector(x = -global_container_stack.getProperty("machine_width", "value") / 2,
|
||||
y = -global_container_stack.getProperty("machine_depth", "value") / 2,
|
||||
z = 0)
|
||||
translation_vector = Vector(x=-global_container_stack.getProperty("machine_width", "value") / 2,
|
||||
y=-global_container_stack.getProperty("machine_depth", "value") / 2,
|
||||
z=0)
|
||||
translation_matrix = Matrix()
|
||||
translation_matrix.setByTranslation(translation_vector)
|
||||
transformation_matrix.multiply(translation_matrix)
|
||||
|
@ -227,12 +202,13 @@ class ThreeMFReader(MeshReader):
|
|||
transformation_matrix.multiply(scale_matrix)
|
||||
|
||||
# Pre multiply the transformation with the loaded transformation, so the data is handled correctly.
|
||||
build_item_node.setTransformation(build_item_node.getLocalTransformation().preMultiply(transformation_matrix))
|
||||
um_node.setTransformation(um_node.getLocalTransformation().preMultiply(transformation_matrix))
|
||||
|
||||
result.append(build_item_node)
|
||||
result.append(um_node)
|
||||
|
||||
except Exception as e:
|
||||
Logger.log("e", "An exception occurred in 3mf reader: %s", e)
|
||||
except Exception:
|
||||
Logger.logException("e", "An exception occurred in 3mf reader.")
|
||||
return []
|
||||
|
||||
return result
|
||||
|
||||
|
|
|
@ -47,7 +47,7 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
|
|||
self._id_mapping[old_id] = self._container_registry.uniqueName(old_id)
|
||||
return self._id_mapping[old_id]
|
||||
|
||||
def preRead(self, file_name):
|
||||
def preRead(self, file_name, show_dialog=True, *args, **kwargs):
|
||||
self._3mf_mesh_reader = Application.getInstance().getMeshFileHandler().getReaderForFile(file_name)
|
||||
if self._3mf_mesh_reader and self._3mf_mesh_reader.preRead(file_name) == WorkspaceReader.PreReadResult.accepted:
|
||||
pass
|
||||
|
@ -167,6 +167,10 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
|
|||
Logger.log("w", "File %s is not a valid workspace.", file_name)
|
||||
return WorkspaceReader.PreReadResult.failed
|
||||
|
||||
# In case we use preRead() to check if a file is a valid project file, we don't want to show a dialog.
|
||||
if not show_dialog:
|
||||
return WorkspaceReader.PreReadResult.accepted
|
||||
|
||||
# Show the dialog, informing the user what is about to happen.
|
||||
self._dialog.setMachineConflict(machine_conflict)
|
||||
self._dialog.setQualityChangesConflict(quality_changes_conflict)
|
||||
|
@ -182,7 +186,7 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
|
|||
self._dialog.setMachineType(machine_type)
|
||||
self._dialog.setExtruders(extruders)
|
||||
self._dialog.setVariantType(variant_type_name)
|
||||
self._dialog.setHasObjectsOnPlate(Application.getInstance().getPlatformActivity)
|
||||
self._dialog.setHasObjectsOnPlate(Application.getInstance().platformActivity)
|
||||
self._dialog.show()
|
||||
|
||||
# Block until the dialog is closed.
|
||||
|
@ -476,7 +480,9 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
|
|||
return nodes
|
||||
|
||||
def _stripFileToId(self, file):
|
||||
return file.replace("Cura/", "").split(".")[0]
|
||||
mime_type = MimeTypeDatabase.getMimeTypeForFile(file)
|
||||
file = mime_type.stripExtension(file)
|
||||
return file.replace("Cura/", "")
|
||||
|
||||
def _getXmlProfileClass(self):
|
||||
return self._container_registry.getContainerForMimeType(MimeTypeDatabase.getMimeType("application/x-ultimaker-material-profile"))
|
||||
|
|
|
@ -12,15 +12,15 @@ UM.Dialog
|
|||
{
|
||||
title: catalog.i18nc("@title:window", "Open Project")
|
||||
|
||||
width: 550
|
||||
minimumWidth: 550
|
||||
maximumWidth: 550
|
||||
width: 550 * Screen.devicePixelRatio
|
||||
minimumWidth: 550 * Screen.devicePixelRatio
|
||||
maximumWidth: minimumWidth
|
||||
|
||||
height: 400
|
||||
minimumHeight: 400
|
||||
maximumHeight: 400
|
||||
property int comboboxHeight: 15
|
||||
property int spacerHeight: 10
|
||||
height: 400 * Screen.devicePixelRatio
|
||||
minimumHeight: 400 * Screen.devicePixelRatio
|
||||
maximumHeight: minimumHeight
|
||||
property int comboboxHeight: 15 * Screen.devicePixelRatio
|
||||
property int spacerHeight: 10 * Screen.devicePixelRatio
|
||||
onClosing: manager.notifyClosed()
|
||||
onVisibleChanged:
|
||||
{
|
||||
|
@ -33,20 +33,17 @@ UM.Dialog
|
|||
}
|
||||
Item
|
||||
{
|
||||
anchors.top: parent.top
|
||||
anchors.bottom: parent.bottom
|
||||
anchors.left: parent.left
|
||||
anchors.right: parent.right
|
||||
|
||||
anchors.topMargin: 20
|
||||
anchors.bottomMargin: 20
|
||||
anchors.leftMargin:20
|
||||
anchors.rightMargin: 20
|
||||
anchors.fill: parent
|
||||
anchors.margins: 20 * Screen.devicePixelRatio
|
||||
|
||||
UM.I18nCatalog
|
||||
{
|
||||
id: catalog;
|
||||
name: "cura";
|
||||
id: catalog
|
||||
name: "cura"
|
||||
}
|
||||
SystemPalette
|
||||
{
|
||||
id: palette
|
||||
}
|
||||
|
||||
ListModel
|
||||
|
@ -70,12 +67,12 @@ UM.Dialog
|
|||
{
|
||||
id: titleLabel
|
||||
text: catalog.i18nc("@action:title", "Summary - Cura Project")
|
||||
font.pixelSize: 22
|
||||
font.pointSize: 18
|
||||
}
|
||||
Rectangle
|
||||
{
|
||||
id: separator
|
||||
color: "black"
|
||||
color: palette.text
|
||||
width: parent.width
|
||||
height: 1
|
||||
}
|
||||
|
@ -93,7 +90,7 @@ UM.Dialog
|
|||
{
|
||||
text: catalog.i18nc("@action:label", "Printer settings")
|
||||
font.bold: true
|
||||
width: parent.width /3
|
||||
width: parent.width / 3
|
||||
}
|
||||
Item
|
||||
{
|
||||
|
@ -360,7 +357,7 @@ UM.Dialog
|
|||
height: width
|
||||
|
||||
source: UM.Theme.getIcon("notice")
|
||||
color: "black"
|
||||
color: palette.text
|
||||
|
||||
}
|
||||
Label
|
||||
|
@ -392,4 +389,4 @@ UM.Dialog
|
|||
anchors.right: parent.right
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,43 +1,56 @@
|
|||
# Copyright (c) 2015 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
from typing import Dict
|
||||
import sys
|
||||
|
||||
from UM.Logger import Logger
|
||||
try:
|
||||
from . import ThreeMFReader
|
||||
except ImportError:
|
||||
Logger.log("w", "Could not import ThreeMFReader; libSavitar may be missing")
|
||||
|
||||
from . import ThreeMFReader
|
||||
from . import ThreeMFWorkspaceReader
|
||||
|
||||
from UM.i18n import i18nCatalog
|
||||
import UM.Platform
|
||||
from UM.Platform import Platform
|
||||
catalog = i18nCatalog("cura")
|
||||
|
||||
|
||||
def getMetaData():
|
||||
def getMetaData() -> Dict:
|
||||
# Workarround for osx not supporting double file extensions correclty.
|
||||
if UM.Platform.isOSX():
|
||||
if Platform.isOSX():
|
||||
workspace_extension = "3mf"
|
||||
else:
|
||||
workspace_extension = "curaproject.3mf"
|
||||
return {
|
||||
|
||||
metaData = {
|
||||
"plugin": {
|
||||
"name": catalog.i18nc("@label", "3MF Reader"),
|
||||
"author": "Ultimaker",
|
||||
"version": "1.0",
|
||||
"description": catalog.i18nc("@info:whatsthis", "Provides support for reading 3MF files."),
|
||||
"api": 3
|
||||
},
|
||||
"mesh_reader": [
|
||||
}
|
||||
}
|
||||
if "3MFReader.ThreeMFReader" in sys.modules:
|
||||
metaData["mesh_reader"] = [
|
||||
{
|
||||
"extension": "3mf",
|
||||
"description": catalog.i18nc("@item:inlistbox", "3MF File")
|
||||
}
|
||||
],
|
||||
"workspace_reader":
|
||||
[
|
||||
]
|
||||
metaData["workspace_reader"] = [
|
||||
{
|
||||
"extension": workspace_extension,
|
||||
"description": catalog.i18nc("@item:inlistbox", "3MF File")
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return metaData
|
||||
|
||||
|
||||
def register(app):
|
||||
return {"mesh_reader": ThreeMFReader.ThreeMFReader(),
|
||||
"workspace_reader": ThreeMFWorkspaceReader.ThreeMFWorkspaceReader()}
|
||||
if "3MFReader.ThreeMFReader" in sys.modules:
|
||||
return {"mesh_reader": ThreeMFReader.ThreeMFReader(),
|
||||
"workspace_reader": ThreeMFWorkspaceReader.ThreeMFWorkspaceReader()}
|
||||
else:
|
||||
return {}
|
||||
|
|
|
@ -6,9 +6,16 @@ from UM.Math.Vector import Vector
|
|||
from UM.Logger import Logger
|
||||
from UM.Math.Matrix import Matrix
|
||||
from UM.Application import Application
|
||||
import UM.Scene.SceneNode
|
||||
|
||||
import Savitar
|
||||
|
||||
import numpy
|
||||
|
||||
MYPY = False
|
||||
try:
|
||||
import xml.etree.cElementTree as ET
|
||||
if not MYPY:
|
||||
import xml.etree.cElementTree as ET
|
||||
except ImportError:
|
||||
Logger.log("w", "Unable to load cElementTree, switching to slower version")
|
||||
import xml.etree.ElementTree as ET
|
||||
|
@ -33,18 +40,18 @@ class ThreeMFWriter(MeshWriter):
|
|||
|
||||
def _convertMatrixToString(self, matrix):
|
||||
result = ""
|
||||
result += str(matrix._data[0,0]) + " "
|
||||
result += str(matrix._data[1,0]) + " "
|
||||
result += str(matrix._data[2,0]) + " "
|
||||
result += str(matrix._data[0,1]) + " "
|
||||
result += str(matrix._data[1,1]) + " "
|
||||
result += str(matrix._data[2,1]) + " "
|
||||
result += str(matrix._data[0,2]) + " "
|
||||
result += str(matrix._data[1,2]) + " "
|
||||
result += str(matrix._data[2,2]) + " "
|
||||
result += str(matrix._data[0,3]) + " "
|
||||
result += str(matrix._data[1,3]) + " "
|
||||
result += str(matrix._data[2,3])
|
||||
result += str(matrix._data[0, 0]) + " "
|
||||
result += str(matrix._data[1, 0]) + " "
|
||||
result += str(matrix._data[2, 0]) + " "
|
||||
result += str(matrix._data[0, 1]) + " "
|
||||
result += str(matrix._data[1, 1]) + " "
|
||||
result += str(matrix._data[2, 1]) + " "
|
||||
result += str(matrix._data[0, 2]) + " "
|
||||
result += str(matrix._data[1, 2]) + " "
|
||||
result += str(matrix._data[2, 2]) + " "
|
||||
result += str(matrix._data[0, 3]) + " "
|
||||
result += str(matrix._data[1, 3]) + " "
|
||||
result += str(matrix._data[2, 3])
|
||||
return result
|
||||
|
||||
## Should we store the archive
|
||||
|
@ -53,6 +60,48 @@ class ThreeMFWriter(MeshWriter):
|
|||
def setStoreArchive(self, store_archive):
|
||||
self._store_archive = store_archive
|
||||
|
||||
## Convenience function that converts an Uranium SceneNode object to a SavitarSceneNode
|
||||
# \returns Uranium Scenen node.
|
||||
def _convertUMNodeToSavitarNode(self, um_node, transformation = Matrix()):
|
||||
if type(um_node) is not UM.Scene.SceneNode.SceneNode:
|
||||
return None
|
||||
|
||||
savitar_node = Savitar.SceneNode()
|
||||
|
||||
node_matrix = um_node.getLocalTransformation()
|
||||
|
||||
matrix_string = self._convertMatrixToString(node_matrix.preMultiply(transformation))
|
||||
|
||||
savitar_node.setTransformation(matrix_string)
|
||||
mesh_data = um_node.getMeshData()
|
||||
if mesh_data is not None:
|
||||
savitar_node.getMeshData().setVerticesFromBytes(mesh_data.getVerticesAsByteArray())
|
||||
indices_array = mesh_data.getIndicesAsByteArray()
|
||||
if indices_array is not None:
|
||||
savitar_node.getMeshData().setFacesFromBytes(indices_array)
|
||||
else:
|
||||
savitar_node.getMeshData().setFacesFromBytes(numpy.arange(mesh_data.getVertices().size / 3, dtype=numpy.int32).tostring())
|
||||
|
||||
# Handle per object settings (if any)
|
||||
stack = um_node.callDecoration("getStack")
|
||||
if stack is not None:
|
||||
changed_setting_keys = set(stack.getTop().getAllKeys())
|
||||
|
||||
# Ensure that we save the extruder used for this object.
|
||||
if stack.getProperty("machine_extruder_count", "value") > 1:
|
||||
changed_setting_keys.add("extruder_nr")
|
||||
|
||||
# Get values for all changed settings & save them.
|
||||
for key in changed_setting_keys:
|
||||
savitar_node.setSetting(key, str(stack.getProperty(key, "value")))
|
||||
|
||||
for child_node in um_node.getChildren():
|
||||
savitar_child_node = self._convertUMNodeToSavitarNode(child_node)
|
||||
if savitar_child_node is not None:
|
||||
savitar_node.addChild(savitar_child_node)
|
||||
|
||||
return savitar_node
|
||||
|
||||
def getArchive(self):
|
||||
return self._archive
|
||||
|
||||
|
@ -77,105 +126,14 @@ class ThreeMFWriter(MeshWriter):
|
|||
relations_element = ET.Element("Relationships", xmlns = self._namespaces["relationships"])
|
||||
model_relation_element = ET.SubElement(relations_element, "Relationship", Target = "/3D/3dmodel.model", Id = "rel0", Type = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel")
|
||||
|
||||
model = ET.Element("model", unit = "millimeter", xmlns = self._namespaces["3mf"])
|
||||
model.set("xmlns:cura", self._namespaces["cura"])
|
||||
|
||||
# Add the version of Cura this was created with. Since there is no "version" or similar metadata name we need
|
||||
# to prefix it with the cura namespace, as specified by the 3MF specification.
|
||||
version_metadata = ET.SubElement(model, "metadata", name = "cura:version")
|
||||
version_metadata.text = Application.getInstance().getVersion()
|
||||
|
||||
resources = ET.SubElement(model, "resources")
|
||||
build = ET.SubElement(model, "build")
|
||||
|
||||
added_nodes = []
|
||||
index = 0 # Ensure index always exists (even if there are no nodes to write)
|
||||
# Write all nodes with meshData to the file as objects inside the resource tag
|
||||
for index, n in enumerate(MeshWriter._meshNodes(nodes)):
|
||||
added_nodes.append(n) # Save the nodes that have mesh data
|
||||
object = ET.SubElement(resources, "object", id = str(index+1), type = "model")
|
||||
mesh = ET.SubElement(object, "mesh")
|
||||
|
||||
mesh_data = n.getMeshData()
|
||||
vertices = ET.SubElement(mesh, "vertices")
|
||||
verts = mesh_data.getVertices()
|
||||
|
||||
if verts is None:
|
||||
Logger.log("d", "3mf writer can't write nodes without mesh data. Skipping this node.")
|
||||
continue # No mesh data, nothing to do.
|
||||
if mesh_data.hasIndices():
|
||||
for face in mesh_data.getIndices():
|
||||
v1 = verts[face[0]]
|
||||
v2 = verts[face[1]]
|
||||
v3 = verts[face[2]]
|
||||
xml_vertex1 = ET.SubElement(vertices, "vertex", x = str(v1[0]), y = str(v1[1]), z = str(v1[2]))
|
||||
xml_vertex2 = ET.SubElement(vertices, "vertex", x = str(v2[0]), y = str(v2[1]), z = str(v2[2]))
|
||||
xml_vertex3 = ET.SubElement(vertices, "vertex", x = str(v3[0]), y = str(v3[1]), z = str(v3[2]))
|
||||
|
||||
triangles = ET.SubElement(mesh, "triangles")
|
||||
for face in mesh_data.getIndices():
|
||||
triangle = ET.SubElement(triangles, "triangle", v1 = str(face[0]) , v2 = str(face[1]), v3 = str(face[2]))
|
||||
else:
|
||||
triangles = ET.SubElement(mesh, "triangles")
|
||||
for idx, vert in enumerate(verts):
|
||||
xml_vertex = ET.SubElement(vertices, "vertex", x = str(vert[0]), y = str(vert[1]), z = str(vert[2]))
|
||||
|
||||
# If we have no faces defined, assume that every three subsequent vertices form a face.
|
||||
if idx % 3 == 0:
|
||||
triangle = ET.SubElement(triangles, "triangle", v1 = str(idx), v2 = str(idx + 1), v3 = str(idx + 2))
|
||||
|
||||
# Handle per object settings
|
||||
stack = n.callDecoration("getStack")
|
||||
if stack is not None:
|
||||
changed_setting_keys = set(stack.getTop().getAllKeys())
|
||||
|
||||
# Ensure that we save the extruder used for this object.
|
||||
if stack.getProperty("machine_extruder_count", "value") > 1:
|
||||
changed_setting_keys.add("extruder_nr")
|
||||
|
||||
settings_xml = ET.SubElement(object, "settings", xmlns=self._namespaces["cura"])
|
||||
|
||||
# Get values for all changed settings & save them.
|
||||
for key in changed_setting_keys:
|
||||
setting_xml = ET.SubElement(settings_xml, "setting", key = key)
|
||||
setting_xml.text = str(stack.getProperty(key, "value"))
|
||||
|
||||
# Add one to the index as we haven't incremented the last iteration.
|
||||
index += 1
|
||||
nodes_to_add = set()
|
||||
|
||||
for node in added_nodes:
|
||||
# Check the parents of the nodes with mesh_data and ensure that they are also added.
|
||||
parent_node = node.getParent()
|
||||
while parent_node is not None:
|
||||
if parent_node.callDecoration("isGroup"):
|
||||
nodes_to_add.add(parent_node)
|
||||
parent_node = parent_node.getParent()
|
||||
else:
|
||||
parent_node = None
|
||||
|
||||
# Sort all the nodes by depth (so nodes with the highest depth are done first)
|
||||
sorted_nodes_to_add = sorted(nodes_to_add, key=lambda node: node.getDepth(), reverse = True)
|
||||
|
||||
# We have already saved the nodes with mesh data, but now we also want to save nodes required for the scene
|
||||
for node in sorted_nodes_to_add:
|
||||
object = ET.SubElement(resources, "object", id=str(index + 1), type="model")
|
||||
components = ET.SubElement(object, "components")
|
||||
for child in node.getChildren():
|
||||
if child in added_nodes:
|
||||
component = ET.SubElement(components, "component", objectid = str(added_nodes.index(child) + 1), transform = self._convertMatrixToString(child.getLocalTransformation()))
|
||||
index += 1
|
||||
added_nodes.append(node)
|
||||
|
||||
# Create a transformation Matrix to convert from our worldspace into 3MF.
|
||||
# First step: flip the y and z axis.
|
||||
savitar_scene = Savitar.Scene()
|
||||
transformation_matrix = Matrix()
|
||||
transformation_matrix._data[1, 1] = 0
|
||||
transformation_matrix._data[1, 2] = -1
|
||||
transformation_matrix._data[2, 1] = 1
|
||||
transformation_matrix._data[2, 2] = 0
|
||||
|
||||
global_container_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
# Second step: 3MF defines the left corner of the machine as center, whereas cura uses the center of the
|
||||
# build volume.
|
||||
if global_container_stack:
|
||||
|
@ -186,14 +144,22 @@ class ThreeMFWriter(MeshWriter):
|
|||
translation_matrix.setByTranslation(translation_vector)
|
||||
transformation_matrix.preMultiply(translation_matrix)
|
||||
|
||||
# Find out what the final build items are and add them.
|
||||
for node in added_nodes:
|
||||
if node.getParent().callDecoration("isGroup") is None:
|
||||
node_matrix = node.getLocalTransformation()
|
||||
root_node = UM.Application.Application.getInstance().getController().getScene().getRoot()
|
||||
for node in nodes:
|
||||
if node == root_node:
|
||||
for root_child in node.getChildren():
|
||||
savitar_node = self._convertUMNodeToSavitarNode(root_child, transformation_matrix)
|
||||
if savitar_node:
|
||||
savitar_scene.addSceneNode(savitar_node)
|
||||
else:
|
||||
savitar_node = self._convertUMNodeToSavitarNode(node, transformation_matrix)
|
||||
if savitar_node:
|
||||
savitar_scene.addSceneNode(savitar_node)
|
||||
|
||||
ET.SubElement(build, "item", objectid = str(added_nodes.index(node) + 1), transform = self._convertMatrixToString(node_matrix.preMultiply(transformation_matrix)))
|
||||
parser = Savitar.ThreeMFParser()
|
||||
scene_string = parser.sceneToString(savitar_scene)
|
||||
|
||||
archive.writestr(model_file, b'<?xml version="1.0" encoding="UTF-8"?> \n' + ET.tostring(model))
|
||||
archive.writestr(model_file, scene_string)
|
||||
archive.writestr(content_types_file, b'<?xml version="1.0" encoding="UTF-8"?> \n' + ET.tostring(content_types))
|
||||
archive.writestr(relations_file, b'<?xml version="1.0" encoding="UTF-8"?> \n' + ET.tostring(relations_element))
|
||||
except Exception as e:
|
||||
|
|
|
@ -1,30 +1,39 @@
|
|||
# Copyright (c) 2015 Ultimaker B.V.
|
||||
# Uranium is released under the terms of the AGPLv3 or higher.
|
||||
import sys
|
||||
|
||||
from UM.Logger import Logger
|
||||
try:
|
||||
from . import ThreeMFWriter
|
||||
except ImportError:
|
||||
Logger.log("w", "Could not import ThreeMFWriter; libSavitar may be missing")
|
||||
from . import ThreeMFWorkspaceWriter
|
||||
|
||||
from UM.i18n import i18nCatalog
|
||||
from . import ThreeMFWorkspaceWriter
|
||||
from . import ThreeMFWriter
|
||||
|
||||
i18n_catalog = i18nCatalog("uranium")
|
||||
|
||||
def getMetaData():
|
||||
return {
|
||||
metaData = {
|
||||
"plugin": {
|
||||
"name": i18n_catalog.i18nc("@label", "3MF Writer"),
|
||||
"author": "Ultimaker",
|
||||
"version": "1.0",
|
||||
"description": i18n_catalog.i18nc("@info:whatsthis", "Provides support for writing 3MF files."),
|
||||
"api": 3
|
||||
},
|
||||
"mesh_writer": {
|
||||
}
|
||||
}
|
||||
|
||||
if "3MFWriter.ThreeMFWriter" in sys.modules:
|
||||
metaData["mesh_writer"] = {
|
||||
"output": [{
|
||||
"extension": "3mf",
|
||||
"description": i18n_catalog.i18nc("@item:inlistbox", "3MF file"),
|
||||
"mime_type": "application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
|
||||
"mode": ThreeMFWriter.ThreeMFWriter.OutputMode.BinaryMode
|
||||
}]
|
||||
},
|
||||
"workspace_writer": {
|
||||
}
|
||||
metaData["workspace_writer"] = {
|
||||
"output": [{
|
||||
"extension": "curaproject.3mf",
|
||||
"description": i18n_catalog.i18nc("@item:inlistbox", "Cura Project 3MF file"),
|
||||
|
@ -32,7 +41,12 @@ def getMetaData():
|
|||
"mode": ThreeMFWorkspaceWriter.ThreeMFWorkspaceWriter.OutputMode.BinaryMode
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
return metaData
|
||||
|
||||
def register(app):
|
||||
return {"mesh_writer": ThreeMFWriter.ThreeMFWriter(), "workspace_writer": ThreeMFWorkspaceWriter.ThreeMFWorkspaceWriter()}
|
||||
if "3MFWriter.ThreeMFWriter" in sys.modules:
|
||||
return {"mesh_writer": ThreeMFWriter.ThreeMFWriter(),
|
||||
"workspace_writer": ThreeMFWorkspaceWriter.ThreeMFWorkspaceWriter()}
|
||||
else:
|
||||
return {}
|
||||
|
|
54
plugins/ChangeLogPlugin/ChangeLog.txt
Normal file → Executable file
54
plugins/ChangeLogPlugin/ChangeLog.txt
Normal file → Executable file
|
@ -1,3 +1,55 @@
|
|||
[2.5.0]
|
||||
*Improved speed
|
||||
We’ve made changing printers, profiles, materials, and print cores even faster. 3MF processing is also much faster now. Opening a 3MF file now takes one tenth of the time.
|
||||
|
||||
*Speedup engine – Multithreading
|
||||
Cura can process multiple operations at the same time during slicing. Supported by Windows and Linux operating systems only.
|
||||
|
||||
*Preheat the build plate (with a connected printer)
|
||||
Users can now set the Ultimaker 3 to preheat the build plate, which reduces the downtime, allowing to manually speed up the printing workflow.
|
||||
|
||||
*Better layout for 3D layer view options
|
||||
An improved layer view has been implemented for computers that support OpenGL 4.1. For OpenGL 2.0 to 4.0, we will automatically switch to the old layer view.
|
||||
|
||||
*Disable automatic slicing
|
||||
An option to disable auto-slicing has been added for the better user experience.
|
||||
|
||||
*Auto-scale off by default
|
||||
This change speaks for itself.
|
||||
|
||||
*Print cost calculation
|
||||
The latest version of Cura now contains code to help users calculate the cost of their prints. To do so, users need to enter a cost per spool and an amount of materials per spool. It is also possible to set the cost per material and gain better control of the expenses. Thanks to our community member Aldo Hoeben for adding this feature.
|
||||
|
||||
*G-code reader
|
||||
The g-code reader has been reintroduced, which means users can load g-code from file and display it in layer view. Users can also print saved g-code files with Cura, share and re-use them, as well as preview the printed object via the g-code viewer. Thanks to AlephObjects for this feature.
|
||||
|
||||
*Discard or Keep Changes popup
|
||||
We’ve changed the popup that appears when a user changes a printing profile after setting custom printing settings. It is now more informative and helpful.
|
||||
|
||||
*Bug fixes
|
||||
- Window overflow: On some configurations (OS and screen dependant), an overflow on the General (Preferences) panel and the credits list on the About window occurred. This is now fixed.
|
||||
- “Center camera when the item is selected”: This is now set to ‘off’ by default.
|
||||
- Removal of file extension: When users save a file or project (without changing the file type), no file extension is added to the name. It’s only when users change to another file type that the extension is added.
|
||||
- Ultimaker 3 Extended connectivity. Selecting Ultimaker 3 Extended in Cura let you connect and print with Ultimaker 3, without any warning. This now has been fixed.
|
||||
- Different Y / Z colors: Y and Z colors in the tool menu are now similar to the colors on the build plate.
|
||||
- No collision areas: No collision areas used to be generated for some models when "keep models apart" was activated. This is now fixed.
|
||||
- Perimeter gaps: Perimeter gaps are not filled often enough; we’ve now amended this.
|
||||
- File location after restart: The old version of Cura didn’t remember the last opened file location after it’s been restarted. Now it has been fixed.
|
||||
- Project name: The project name changes after the project is opened. This now has been fixed.
|
||||
- Slicing when error value is given (print core 2): When a support is printed with the Extruder 2 (PVA), some support settings will trigger a slice when an error value is given. We’ve now sorted this out.
|
||||
- Support Towers: Support Towers can now be disabled.
|
||||
- Support bottoms: When putting one object on top of another with some space in between, and selecting support with support bottom interface, no support bottom is printed. This has now been resolved.
|
||||
- Summary box size: We’ve enlarged the summary box when saving the project.
|
||||
- Cubic subdivision infill: In the past, the cubic subdivision infill sometimes didn’t produce the infill (WIN) – this has now been addressed.
|
||||
- Spiralize outer contour and fill small gaps: When combining Fill Gaps Between Walls with Spiralize Outer Contour, the model gets a massive infill.
|
||||
- Experimental post-processing plugin: Since the TweakAtZ post-processing plugin is not officially supported, we added the ‘Experimental’ tag.
|
||||
|
||||
*3rd party printers (bug fixes)
|
||||
- Folgertech printer definition has been added.
|
||||
- Hello BEE Prusa printer definition has been added.
|
||||
- Velleman Vertex K8400 printer definitions have been added for both single-extrusion and dual-extrusion versions.
|
||||
- Material profiles for Cartesio printers have been updated.
|
||||
|
||||
[2.4.0]
|
||||
*Project saving & opening
|
||||
You can now save your build plate configuration - with all your active machine’s meshes and settings. When you reopen the project file, you’ll find that the build plate configuration and all settings will be exactly as you last left them when you saved the project.
|
||||
|
@ -24,7 +76,7 @@ When slicing is blocked by settings with error values, a message now appears, cl
|
|||
The initial and final printing temperatures reduce the amount of oozing during PLA-PLA, PLA-PVA and Nylon-PVA prints. This means printing a prime tower is now optional (except for CPE and ABS at the moment). The new Ultimaker 3 printing profiles ensure increased reliability and shorter print time.
|
||||
|
||||
*Initial Layer Printing Temperature
|
||||
Initial and final printing temperature settings have been tuned for higher quality results.
|
||||
Initial and final printing temperature settings have been tuned for higher quality results. For all materials the initial print temperature is 5 degrees above the default value.
|
||||
|
||||
*Printing temperature of the materials
|
||||
The printing temperature of the materials in the material profiles is now the same as the printing temperature for the Normal Quality profile.
|
||||
|
|
270
plugins/CuraEngineBackend/CuraEngineBackend.py
Normal file → Executable file
270
plugins/CuraEngineBackend/CuraEngineBackend.py
Normal file → Executable file
|
@ -14,13 +14,10 @@ from UM.Settings.Validator import ValidatorState #To find if a setting is in an
|
|||
from UM.Platform import Platform
|
||||
from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
|
||||
from UM.Qt.Duration import DurationFormat
|
||||
from PyQt5.QtCore import QObject, pyqtSlot
|
||||
|
||||
import cura.Settings
|
||||
|
||||
from cura.OneAtATimeIterator import OneAtATimeIterator
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
from . import ProcessSlicedLayersJob
|
||||
from . import ProcessGCodeJob
|
||||
from . import StartSliceJob
|
||||
|
||||
import os
|
||||
|
@ -34,13 +31,14 @@ import Arcus
|
|||
from UM.i18n import i18nCatalog
|
||||
catalog = i18nCatalog("cura")
|
||||
|
||||
class CuraEngineBackend(Backend):
|
||||
class CuraEngineBackend(QObject, Backend):
|
||||
## Starts the back-end plug-in.
|
||||
#
|
||||
# This registers all the signal listeners and prepares for communication
|
||||
# with the back-end in general.
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
# CuraEngineBackend is exposed to qml as well.
|
||||
def __init__(self, parent = None):
|
||||
super().__init__(parent = parent)
|
||||
# Find out where the engine is located, and how it is called.
|
||||
# This depends on how Cura is packaged and which OS we are running on.
|
||||
executable_name = "CuraEngine"
|
||||
|
@ -68,11 +66,6 @@ class CuraEngineBackend(Backend):
|
|||
default_engine_location = os.path.abspath(default_engine_location)
|
||||
Preferences.getInstance().addPreference("backend/location", default_engine_location)
|
||||
|
||||
self._scene = Application.getInstance().getController().getScene()
|
||||
self._scene.sceneChanged.connect(self._onSceneChanged)
|
||||
|
||||
self._pause_slicing = False
|
||||
|
||||
# Workaround to disable layer view processing if layer view is not active.
|
||||
self._layer_view_active = False
|
||||
Application.getInstance().getController().activeViewChanged.connect(self._onActiveViewChanged)
|
||||
|
@ -80,23 +73,18 @@ class CuraEngineBackend(Backend):
|
|||
self._stored_layer_data = []
|
||||
self._stored_optimized_layer_data = []
|
||||
|
||||
self._scene = Application.getInstance().getController().getScene()
|
||||
self._scene.sceneChanged.connect(self._onSceneChanged)
|
||||
|
||||
# Triggers for when to (re)start slicing:
|
||||
self._global_container_stack = None
|
||||
Application.getInstance().globalContainerStackChanged.connect(self._onGlobalStackChanged)
|
||||
self._onGlobalStackChanged()
|
||||
|
||||
self._active_extruder_stack = None
|
||||
cura.Settings.ExtruderManager.getInstance().activeExtruderChanged.connect(self._onActiveExtruderChanged)
|
||||
ExtruderManager.getInstance().activeExtruderChanged.connect(self._onActiveExtruderChanged)
|
||||
self._onActiveExtruderChanged()
|
||||
|
||||
# When you update a setting and other settings get changed through inheritance, many propertyChanged signals are fired.
|
||||
# This timer will group them up, and only slice for the last setting changed signal.
|
||||
# TODO: Properly group propertyChanged signals by whether they are triggered by the same user interaction.
|
||||
self._change_timer = QTimer()
|
||||
self._change_timer.setInterval(500)
|
||||
self._change_timer.setSingleShot(True)
|
||||
self._change_timer.timeout.connect(self.slice)
|
||||
|
||||
# Listeners for receiving messages from the back-end.
|
||||
self._message_handlers["cura.proto.Layer"] = self._onLayerMessage
|
||||
self._message_handlers["cura.proto.LayerOptimized"] = self._onOptimizedLayerMessage
|
||||
|
@ -109,12 +97,16 @@ class CuraEngineBackend(Backend):
|
|||
self._start_slice_job = None
|
||||
self._slicing = False # Are we currently slicing?
|
||||
self._restart = False # Back-end is currently restarting?
|
||||
self._enabled = True # Should we be slicing? Slicing might be paused when, for instance, the user is dragging the mesh around.
|
||||
self._tool_active = False # If a tool is active, some tasks do not have to do anything
|
||||
self._always_restart = True # Always restart the engine when starting a new slice. Don't keep the process running. TODO: Fix engine statelessness.
|
||||
self._process_layers_job = None # The currently active job to process layers, or None if it is not processing layers.
|
||||
self._need_slicing = False
|
||||
self._engine_is_fresh = True # Is the newly started engine used before or not?
|
||||
|
||||
self._backend_log_max_lines = 20000 # Maximum number of lines to buffer
|
||||
self._error_message = None # Pop-up message that shows errors.
|
||||
self._last_num_objects = 0 # Count number of objects to see if there is something changed
|
||||
self._postponed_scene_change_sources = [] # scene change is postponed (by a tool)
|
||||
|
||||
self.backendQuit.connect(self._onBackendQuit)
|
||||
self.backendConnected.connect(self._onBackendConnected)
|
||||
|
@ -125,9 +117,22 @@ class CuraEngineBackend(Backend):
|
|||
|
||||
self._slice_start_time = None
|
||||
|
||||
## Called when closing the application.
|
||||
Preferences.getInstance().addPreference("general/auto_slice", True)
|
||||
|
||||
self._use_timer = False
|
||||
# When you update a setting and other settings get changed through inheritance, many propertyChanged signals are fired.
|
||||
# This timer will group them up, and only slice for the last setting changed signal.
|
||||
# TODO: Properly group propertyChanged signals by whether they are triggered by the same user interaction.
|
||||
self._change_timer = QTimer()
|
||||
self._change_timer.setSingleShot(True)
|
||||
self._change_timer.setInterval(500)
|
||||
self.determineAutoSlicing()
|
||||
Preferences.getInstance().preferenceChanged.connect(self._onPreferencesChanged)
|
||||
|
||||
## Terminate the engine process.
|
||||
#
|
||||
# This function should terminate the engine process.
|
||||
# Called when closing the application.
|
||||
def close(self):
|
||||
# Terminate CuraEngine if it is still running at this point
|
||||
self._terminate()
|
||||
|
@ -151,24 +156,12 @@ class CuraEngineBackend(Backend):
|
|||
## Emitted when the slicing process is aborted forcefully.
|
||||
slicingCancelled = Signal()
|
||||
|
||||
## Perform a slice of the scene.
|
||||
def slice(self):
|
||||
Logger.log("d", "Starting slice job...")
|
||||
if self._pause_slicing:
|
||||
return
|
||||
self._slice_start_time = time()
|
||||
if not self._enabled or not self._global_container_stack: # We shouldn't be slicing.
|
||||
# try again in a short time
|
||||
self._change_timer.start()
|
||||
return
|
||||
|
||||
self.printDurationMessage.emit(0, [0])
|
||||
|
||||
self._stored_layer_data = []
|
||||
self._stored_optimized_layer_data = []
|
||||
|
||||
@pyqtSlot()
|
||||
def stopSlicing(self):
|
||||
self.backendStateChange.emit(BackendState.NotStarted)
|
||||
if self._slicing: # We were already slicing. Stop the old job.
|
||||
self._terminate()
|
||||
self._createSocket()
|
||||
|
||||
if self._process_layers_job: # We were processing layers. Stop that, the layers are going to change soon.
|
||||
self._process_layers_job.abort()
|
||||
|
@ -177,6 +170,33 @@ class CuraEngineBackend(Backend):
|
|||
if self._error_message:
|
||||
self._error_message.hide()
|
||||
|
||||
## Manually triggers a reslice
|
||||
@pyqtSlot()
|
||||
def forceSlice(self):
|
||||
if self._use_timer:
|
||||
self._change_timer.start()
|
||||
else:
|
||||
self.slice()
|
||||
|
||||
## Perform a slice of the scene.
|
||||
def slice(self):
|
||||
self._slice_start_time = time()
|
||||
if not self._need_slicing:
|
||||
self.processingProgress.emit(1.0)
|
||||
self.backendStateChange.emit(BackendState.Done)
|
||||
Logger.log("w", "Slice unnecessary, nothing has changed that needs reslicing.")
|
||||
return
|
||||
|
||||
self.printDurationMessage.emit(0, [0])
|
||||
|
||||
self._stored_layer_data = []
|
||||
self._stored_optimized_layer_data = []
|
||||
|
||||
if self._process is None:
|
||||
self._createSocket()
|
||||
self.stopSlicing()
|
||||
self._engine_is_fresh = False # Yes we're going to use the engine
|
||||
|
||||
self.processingProgress.emit(0.0)
|
||||
self.backendStateChange.emit(BackendState.NotStarted)
|
||||
|
||||
|
@ -189,21 +209,10 @@ class CuraEngineBackend(Backend):
|
|||
self._start_slice_job.start()
|
||||
self._start_slice_job.finished.connect(self._onStartSliceCompleted)
|
||||
|
||||
|
||||
def pauseSlicing(self):
|
||||
self.close()
|
||||
self._pause_slicing = True
|
||||
self.backendStateChange.emit(BackendState.Disabled)
|
||||
|
||||
def continueSlicing(self):
|
||||
if self._pause_slicing:
|
||||
self._pause_slicing = False
|
||||
self.backendStateChange.emit(BackendState.NotStarted)
|
||||
|
||||
## Terminate the engine process.
|
||||
# Start the engine process by calling _createSocket()
|
||||
def _terminate(self):
|
||||
self._slicing = False
|
||||
self._restart = True
|
||||
self._stored_layer_data = []
|
||||
self._stored_optimized_layer_data = []
|
||||
if self._start_slice_job is not None:
|
||||
|
@ -225,9 +234,6 @@ class CuraEngineBackend(Backend):
|
|||
|
||||
except Exception as e: # terminating a process that is already terminating causes an exception, silently ignore this.
|
||||
Logger.log("d", "Exception occurred while trying to kill the engine %s", str(e))
|
||||
else:
|
||||
# Process is none, but something did went wrong here. Try and re-create the socket
|
||||
self._createSocket()
|
||||
|
||||
## Event handler to call when the job to initiate the slicing process is
|
||||
# completed.
|
||||
|
@ -249,7 +255,7 @@ class CuraEngineBackend(Backend):
|
|||
return
|
||||
|
||||
if job.getResult() == StartSliceJob.StartJobResult.MaterialIncompatible:
|
||||
if Application.getInstance().getPlatformActivity:
|
||||
if Application.getInstance().platformActivity:
|
||||
self._error_message = Message(catalog.i18nc("@info:status",
|
||||
"The selected material is incompatible with the selected machine or configuration."))
|
||||
self._error_message.show()
|
||||
|
@ -259,7 +265,7 @@ class CuraEngineBackend(Backend):
|
|||
return
|
||||
|
||||
if job.getResult() == StartSliceJob.StartJobResult.SettingError:
|
||||
if Application.getInstance().getPlatformActivity:
|
||||
if Application.getInstance().platformActivity:
|
||||
extruders = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
|
||||
error_keys = []
|
||||
for extruder in extruders:
|
||||
|
@ -280,7 +286,7 @@ class CuraEngineBackend(Backend):
|
|||
return
|
||||
|
||||
if job.getResult() == StartSliceJob.StartJobResult.BuildPlateError:
|
||||
if Application.getInstance().getPlatformActivity:
|
||||
if Application.getInstance().platformActivity:
|
||||
self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice because the prime tower or prime position(s) are invalid."))
|
||||
self._error_message.show()
|
||||
self.backendStateChange.emit(BackendState.Error)
|
||||
|
@ -288,7 +294,7 @@ class CuraEngineBackend(Backend):
|
|||
self.backendStateChange.emit(BackendState.NotStarted)
|
||||
|
||||
if job.getResult() == StartSliceJob.StartJobResult.NothingToSlice:
|
||||
if Application.getInstance().getPlatformActivity:
|
||||
if Application.getInstance().platformActivity:
|
||||
self._error_message = Message(catalog.i18nc("@info:status", "Nothing to slice because none of the models fit the build volume. Please scale or rotate models to fit."))
|
||||
self._error_message.show()
|
||||
self.backendStateChange.emit(BackendState.Error)
|
||||
|
@ -303,6 +309,33 @@ class CuraEngineBackend(Backend):
|
|||
|
||||
Logger.log("d", "Sending slice message took %s seconds", time() - self._slice_start_time )
|
||||
|
||||
## Determine enable or disable auto slicing. Return True for enable timer and False otherwise.
|
||||
# It disables when
|
||||
# - preference auto slice is off
|
||||
# - decorator isBlockSlicing is found (used in g-code reader)
|
||||
def determineAutoSlicing(self):
|
||||
enable_timer = True
|
||||
|
||||
if not Preferences.getInstance().getValue("general/auto_slice"):
|
||||
enable_timer = False
|
||||
for node in DepthFirstIterator(self._scene.getRoot()):
|
||||
if node.callDecoration("isBlockSlicing"):
|
||||
enable_timer = False
|
||||
self.backendStateChange.emit(BackendState.Disabled)
|
||||
gcode_list = node.callDecoration("getGCodeList")
|
||||
if gcode_list is not None:
|
||||
self._scene.gcode_list = gcode_list
|
||||
|
||||
if self._use_timer == enable_timer:
|
||||
return self._use_timer
|
||||
if enable_timer:
|
||||
self.backendStateChange.emit(BackendState.NotStarted)
|
||||
self.enableTimer()
|
||||
return True
|
||||
else:
|
||||
self.disableTimer()
|
||||
return False
|
||||
|
||||
## Listener for when the scene has changed.
|
||||
#
|
||||
# This should start a slice if the scene is now ready to slice.
|
||||
|
@ -312,28 +345,33 @@ class CuraEngineBackend(Backend):
|
|||
if type(source) is not SceneNode:
|
||||
return
|
||||
|
||||
if source is self._scene.getRoot():
|
||||
return
|
||||
|
||||
should_pause = False
|
||||
for node in DepthFirstIterator(self._scene.getRoot()):
|
||||
if node.callDecoration("isBlockSlicing"):
|
||||
should_pause = True
|
||||
gcode_list = node.callDecoration("getGCodeList")
|
||||
if gcode_list is not None:
|
||||
self._scene.gcode_list = gcode_list
|
||||
|
||||
if should_pause:
|
||||
self.pauseSlicing()
|
||||
else:
|
||||
self.continueSlicing()
|
||||
|
||||
if source.getMeshData() is None:
|
||||
return
|
||||
|
||||
if source.getMeshData().getVertices() is None:
|
||||
root_scene_nodes_changed = False
|
||||
if source == self._scene.getRoot():
|
||||
num_objects = 0
|
||||
for node in DepthFirstIterator(self._scene.getRoot()):
|
||||
# Only count sliceable objects
|
||||
if node.callDecoration("isSliceable"):
|
||||
num_objects += 1
|
||||
if num_objects != self._last_num_objects:
|
||||
self._last_num_objects = num_objects
|
||||
root_scene_nodes_changed = True
|
||||
else:
|
||||
return
|
||||
|
||||
if not source.callDecoration("isGroup") and not root_scene_nodes_changed:
|
||||
if source.getMeshData() is None:
|
||||
return
|
||||
if source.getMeshData().getVertices() is None:
|
||||
return
|
||||
|
||||
if self._tool_active:
|
||||
# do it later, each source only has to be done once
|
||||
if source not in self._postponed_scene_change_sources:
|
||||
self._postponed_scene_change_sources.append(source)
|
||||
return
|
||||
|
||||
self.needsSlicing()
|
||||
self.stopSlicing()
|
||||
self._onChanged()
|
||||
|
||||
## Called when an error occurs in the socket connection towards the engine.
|
||||
|
@ -348,16 +386,34 @@ class CuraEngineBackend(Backend):
|
|||
return
|
||||
|
||||
self._terminate()
|
||||
self._createSocket()
|
||||
|
||||
if error.getErrorCode() not in [Arcus.ErrorCode.BindFailedError, Arcus.ErrorCode.ConnectionResetError, Arcus.ErrorCode.Debug]:
|
||||
Logger.log("w", "A socket error caused the connection to be reset")
|
||||
|
||||
## Remove old layer data (if any)
|
||||
def _clearLayerData(self):
|
||||
for node in DepthFirstIterator(self._scene.getRoot()):
|
||||
if node.callDecoration("getLayerData"):
|
||||
node.getParent().removeChild(node)
|
||||
break
|
||||
|
||||
## Convenient function: set need_slicing, emit state and clear layer data
|
||||
def needsSlicing(self):
|
||||
self._need_slicing = True
|
||||
self.processingProgress.emit(0.0)
|
||||
self.backendStateChange.emit(BackendState.NotStarted)
|
||||
if not self._use_timer:
|
||||
# With manually having to slice, we want to clear the old invalid layer data.
|
||||
self._clearLayerData()
|
||||
|
||||
## A setting has changed, so check if we must reslice.
|
||||
#
|
||||
# \param instance The setting instance that has changed.
|
||||
# \param property The property of the setting instance that has changed.
|
||||
def _onSettingChanged(self, instance, property):
|
||||
if property == "value": # Only reslice if the value has changed.
|
||||
self.needsSlicing()
|
||||
self._onChanged()
|
||||
|
||||
## Called when a sliced layer data message is received from the engine.
|
||||
|
@ -397,6 +453,7 @@ class CuraEngineBackend(Backend):
|
|||
self._scene.gcode_list[self._scene.gcode_list.index(line)] = replaced
|
||||
|
||||
self._slicing = False
|
||||
self._need_slicing = False
|
||||
Logger.log("d", "Slicing took %s seconds", time() - self._slice_start_time )
|
||||
if self._layer_view_active and (self._process_layers_job is None or not self._process_layers_job.isRunning()):
|
||||
self._process_layers_job = ProcessSlicedLayersJob.ProcessSlicedLayersJob(self._stored_optimized_layer_data)
|
||||
|
@ -430,22 +487,21 @@ class CuraEngineBackend(Backend):
|
|||
## Creates a new socket connection.
|
||||
def _createSocket(self):
|
||||
super()._createSocket(os.path.abspath(os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), "Cura.proto")))
|
||||
|
||||
## Manually triggers a reslice
|
||||
def forceSlice(self):
|
||||
self._change_timer.start()
|
||||
self._engine_is_fresh = True
|
||||
|
||||
## Called when anything has changed to the stuff that needs to be sliced.
|
||||
#
|
||||
# This indicates that we should probably re-slice soon.
|
||||
def _onChanged(self, *args, **kwargs):
|
||||
self._change_timer.start()
|
||||
self.needsSlicing()
|
||||
if self._use_timer:
|
||||
self._change_timer.start()
|
||||
|
||||
## Called when the back-end connects to the front-end.
|
||||
def _onBackendConnected(self):
|
||||
if self._restart:
|
||||
self._onChanged()
|
||||
self._restart = False
|
||||
self._onChanged()
|
||||
|
||||
## Called when the user starts using some tool.
|
||||
#
|
||||
|
@ -454,9 +510,12 @@ class CuraEngineBackend(Backend):
|
|||
#
|
||||
# \param tool The tool that the user is using.
|
||||
def _onToolOperationStarted(self, tool):
|
||||
self._enabled = False # Do not reslice when a tool is doing it's 'thing'
|
||||
self._terminate() # Do not continue slicing once a tool has started
|
||||
|
||||
self._tool_active = True # Do not react on scene change
|
||||
self.disableTimer()
|
||||
# Restart engine as soon as possible, we know we want to slice afterwards
|
||||
if not self._engine_is_fresh:
|
||||
self._terminate()
|
||||
self._createSocket()
|
||||
|
||||
## Called when the user stops using some tool.
|
||||
#
|
||||
|
@ -464,8 +523,13 @@ class CuraEngineBackend(Backend):
|
|||
#
|
||||
# \param tool The tool that the user was using.
|
||||
def _onToolOperationStopped(self, tool):
|
||||
self._enabled = True # Tool stop, start listening for changes again.
|
||||
|
||||
self._tool_active = False # React on scene change again
|
||||
self.determineAutoSlicing() # Switch timer on if appropriate
|
||||
# Process all the postponed scene changes
|
||||
while self._postponed_scene_change_sources:
|
||||
source = self._postponed_scene_change_sources.pop(0)
|
||||
self._onSceneChanged(source)
|
||||
|
||||
## Called when the user changes the active view mode.
|
||||
def _onActiveViewChanged(self):
|
||||
if Application.getInstance().getController().getActiveView():
|
||||
|
@ -490,7 +554,6 @@ class CuraEngineBackend(Backend):
|
|||
if self._process:
|
||||
Logger.log("d", "Backend quit with return code %s. Resetting process and socket.", self._process.wait())
|
||||
self._process = None
|
||||
self._createSocket()
|
||||
|
||||
## Called when the global container stack changes
|
||||
def _onGlobalStackChanged(self):
|
||||
|
@ -525,9 +588,34 @@ class CuraEngineBackend(Backend):
|
|||
if self._active_extruder_stack:
|
||||
self._active_extruder_stack.containersChanged.disconnect(self._onChanged)
|
||||
|
||||
self._active_extruder_stack = cura.Settings.ExtruderManager.getInstance().getActiveExtruderStack()
|
||||
self._active_extruder_stack = ExtruderManager.getInstance().getActiveExtruderStack()
|
||||
if self._active_extruder_stack:
|
||||
self._active_extruder_stack.containersChanged.connect(self._onChanged)
|
||||
|
||||
def _onProcessLayersFinished(self, job):
|
||||
self._process_layers_job = None
|
||||
|
||||
## Connect slice function to timer.
|
||||
def enableTimer(self):
|
||||
if not self._use_timer:
|
||||
self._change_timer.timeout.connect(self.slice)
|
||||
self._use_timer = True
|
||||
|
||||
## Disconnect slice function from timer.
|
||||
# This means that slicing will not be triggered automatically
|
||||
def disableTimer(self):
|
||||
if self._use_timer:
|
||||
self._use_timer = False
|
||||
self._change_timer.timeout.disconnect(self.slice)
|
||||
|
||||
def _onPreferencesChanged(self, preference):
|
||||
if preference != "general/auto_slice":
|
||||
return
|
||||
auto_slice = self.determineAutoSlicing()
|
||||
if auto_slice:
|
||||
self._change_timer.start()
|
||||
|
||||
## Tickle the backend so in case of auto slicing, it starts the timer.
|
||||
def tickle(self):
|
||||
if self._use_timer:
|
||||
self._change_timer.start()
|
||||
|
|
|
@ -8,6 +8,8 @@ from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
|
|||
from UM.Scene.SceneNode import SceneNode
|
||||
from UM.Application import Application
|
||||
from UM.Mesh.MeshData import MeshData
|
||||
from UM.Preferences import Preferences
|
||||
from UM.View.GL.OpenGLContext import OpenGLContext
|
||||
|
||||
from UM.Message import Message
|
||||
from UM.i18n import i18nCatalog
|
||||
|
@ -15,6 +17,7 @@ from UM.Logger import Logger
|
|||
|
||||
from UM.Math.Vector import Vector
|
||||
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
from cura import LayerDataBuilder
|
||||
from cura import LayerDataDecorator
|
||||
from cura import LayerPolygon
|
||||
|
@ -24,6 +27,17 @@ from time import time
|
|||
catalog = i18nCatalog("cura")
|
||||
|
||||
|
||||
## Return a 4-tuple with floats 0-1 representing the html color code
|
||||
#
|
||||
# \param color_code html color code, i.e. "#FF0000" -> red
|
||||
def colorCodeToRGBA(color_code):
|
||||
return [
|
||||
int(color_code[1:3], 16) / 255,
|
||||
int(color_code[3:5], 16) / 255,
|
||||
int(color_code[5:7], 16) / 255,
|
||||
1.0]
|
||||
|
||||
|
||||
class ProcessSlicedLayersJob(Job):
|
||||
def __init__(self, layers):
|
||||
super().__init__()
|
||||
|
@ -92,7 +106,6 @@ class ProcessSlicedLayersJob(Job):
|
|||
layer_data.addLayer(abs_layer_number)
|
||||
this_layer = layer_data.getLayer(abs_layer_number)
|
||||
layer_data.setLayerHeight(abs_layer_number, layer.height)
|
||||
layer_data.setLayerThickness(abs_layer_number, layer.thickness)
|
||||
|
||||
for p in range(layer.repeatedMessageCount("path_segment")):
|
||||
polygon = layer.getRepeatedMessage("path_segment", p)
|
||||
|
@ -110,23 +123,28 @@ class ProcessSlicedLayersJob(Job):
|
|||
|
||||
line_widths = numpy.fromstring(polygon.line_width, dtype="f4") # Convert bytearray to numpy array
|
||||
line_widths = line_widths.reshape((-1,1)) # We get a linear list of pairs that make up the points, so make numpy interpret them correctly.
|
||||
|
||||
|
||||
# In the future, line_thicknesses should be given by CuraEngine as well.
|
||||
# Currently the infill layer thickness also translates to line width
|
||||
line_thicknesses = numpy.zeros(line_widths.shape, dtype="f4")
|
||||
line_thicknesses[:] = layer.thickness / 1000 # from micrometer to millimeter
|
||||
|
||||
# Create a new 3D-array, copy the 2D points over and insert the right height.
|
||||
# This uses manual array creation + copy rather than numpy.insert since this is
|
||||
# faster.
|
||||
new_points = numpy.empty((len(points), 3), numpy.float32)
|
||||
if polygon.point_type == 0: # Point2D
|
||||
new_points[:, 0] = points[:, 0]
|
||||
new_points[:, 1] = layer.height / 1000 # layer height value is in backend representation
|
||||
new_points[:, 1] = layer.height / 1000 # layer height value is in backend representation
|
||||
new_points[:, 2] = -points[:, 1]
|
||||
else: # Point3D
|
||||
new_points[:, 0] = points[:, 0]
|
||||
new_points[:, 1] = points[:, 2]
|
||||
new_points[:, 2] = -points[:, 1]
|
||||
|
||||
this_poly = LayerPolygon.LayerPolygon(layer_data, extruder, line_types, new_points, line_widths)
|
||||
this_poly = LayerPolygon.LayerPolygon(extruder, line_types, new_points, line_widths, line_thicknesses)
|
||||
this_poly.buildCache()
|
||||
|
||||
|
||||
this_layer.polygons.append(this_poly)
|
||||
|
||||
Job.yieldThread()
|
||||
|
@ -144,7 +162,35 @@ class ProcessSlicedLayersJob(Job):
|
|||
self._progress.setProgress(progress)
|
||||
|
||||
# We are done processing all the layers we got from the engine, now create a mesh out of the data
|
||||
layer_mesh = layer_data.build()
|
||||
|
||||
# Find out colors per extruder
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
manager = ExtruderManager.getInstance()
|
||||
extruders = list(manager.getMachineExtruders(global_container_stack.getId()))
|
||||
if extruders:
|
||||
material_color_map = numpy.zeros((len(extruders), 4), dtype=numpy.float32)
|
||||
for extruder in extruders:
|
||||
material = extruder.findContainer({"type": "material"})
|
||||
position = int(extruder.getMetaDataEntry("position", default="0")) # Get the position
|
||||
color_code = material.getMetaDataEntry("color_code")
|
||||
color = colorCodeToRGBA(color_code)
|
||||
material_color_map[position, :] = color
|
||||
else:
|
||||
# Single extruder via global stack.
|
||||
material_color_map = numpy.zeros((1, 4), dtype=numpy.float32)
|
||||
material = global_container_stack.findContainer({"type": "material"})
|
||||
color_code = material.getMetaDataEntry("color_code")
|
||||
if color_code is None: # not all stacks have a material color
|
||||
color_code = "#e0e000"
|
||||
color = colorCodeToRGBA(color_code)
|
||||
material_color_map[0, :] = color
|
||||
|
||||
# We have to scale the colors for compatibility mode
|
||||
if OpenGLContext.isLegacyOpenGL() or bool(Preferences.getInstance().getValue("view/force_layer_view_compatibility_mode")):
|
||||
line_type_brightness = 0.5 # for compatibility mode
|
||||
else:
|
||||
line_type_brightness = 1.0
|
||||
layer_mesh = layer_data.build(material_color_map, line_type_brightness)
|
||||
|
||||
if self._abort_requested:
|
||||
if self._progress:
|
||||
|
|
|
@ -17,8 +17,7 @@ from UM.Settings.Validator import ValidatorState
|
|||
from UM.Settings.SettingRelation import RelationType
|
||||
|
||||
from cura.OneAtATimeIterator import OneAtATimeIterator
|
||||
|
||||
import cura.Settings
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
|
||||
class StartJobResult(IntEnum):
|
||||
Finished = 1
|
||||
|
@ -85,7 +84,7 @@ class StartSliceJob(Job):
|
|||
self.setResult(StartJobResult.BuildPlateError)
|
||||
return
|
||||
|
||||
for extruder_stack in cura.Settings.ExtruderManager.getInstance().getMachineExtruders(stack.getId()):
|
||||
for extruder_stack in ExtruderManager.getInstance().getMachineExtruders(stack.getId()):
|
||||
material = extruder_stack.findContainer({"type": "material"})
|
||||
if material:
|
||||
if material.getMetaDataEntry("compatible") == False:
|
||||
|
@ -150,7 +149,7 @@ class StartSliceJob(Job):
|
|||
self._buildGlobalSettingsMessage(stack)
|
||||
self._buildGlobalInheritsStackMessage(stack)
|
||||
|
||||
for extruder_stack in cura.Settings.ExtruderManager.getInstance().getMachineExtruders(stack.getId()):
|
||||
for extruder_stack in ExtruderManager.getInstance().getMachineExtruders(stack.getId()):
|
||||
self._buildExtruderMessage(extruder_stack)
|
||||
|
||||
for group in object_groups:
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
import configparser
|
||||
|
||||
from UM import PluginRegistry
|
||||
from UM.PluginRegistry import PluginRegistry
|
||||
from UM.Logger import Logger
|
||||
from UM.Settings.InstanceContainer import InstanceContainer # The new profile to make.
|
||||
from cura.ProfileReader import ProfileReader
|
||||
|
|
197
plugins/GCodeReader/GCodeReader.py
Normal file → Executable file
197
plugins/GCodeReader/GCodeReader.py
Normal file → Executable file
|
@ -2,6 +2,8 @@
|
|||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
from UM.Application import Application
|
||||
from UM.Backend import Backend
|
||||
from UM.Job import Job
|
||||
from UM.Logger import Logger
|
||||
from UM.Math.AxisAlignedBox import AxisAlignedBox
|
||||
from UM.Math.Vector import Vector
|
||||
|
@ -9,6 +11,7 @@ from UM.Mesh.MeshReader import MeshReader
|
|||
from UM.Message import Message
|
||||
from UM.Scene.SceneNode import SceneNode
|
||||
from UM.i18n import i18nCatalog
|
||||
from UM.Preferences import Preferences
|
||||
|
||||
catalog = i18nCatalog("cura")
|
||||
|
||||
|
@ -17,6 +20,7 @@ from cura import LayerDataBuilder
|
|||
from cura import LayerDataDecorator
|
||||
from cura.LayerPolygon import LayerPolygon
|
||||
from cura.GCodeListDecorator import GCodeListDecorator
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
|
||||
import numpy
|
||||
import math
|
||||
|
@ -32,14 +36,21 @@ class GCodeReader(MeshReader):
|
|||
Application.getInstance().hideMessageSignal.connect(self._onHideMessage)
|
||||
self._cancelled = False
|
||||
self._message = None
|
||||
self._layer_number = 0
|
||||
self._extruder_number = 0
|
||||
self._clearValues()
|
||||
self._scene_node = None
|
||||
self._position = namedtuple('Position', ['x', 'y', 'z', 'e'])
|
||||
self._is_layers_in_file = False # Does the Gcode have the layers comment?
|
||||
self._extruder_offsets = {} # Offsets for multi extruders. key is index, value is [x-offset, y-offset]
|
||||
self._current_layer_thickness = 0.2 # default
|
||||
|
||||
Preferences.getInstance().addPreference("gcodereader/show_caution", True)
|
||||
|
||||
def _clearValues(self):
|
||||
self._extruder = 0
|
||||
self._extruder_number = 0
|
||||
self._layer_type = LayerPolygon.Inset0Type
|
||||
self._layer = 0
|
||||
self._layer_number = 0
|
||||
self._previous_z = 0
|
||||
self._layer_data_builder = LayerDataBuilder.LayerDataBuilder()
|
||||
self._center_is_zero = False
|
||||
|
@ -82,38 +93,41 @@ class GCodeReader(MeshReader):
|
|||
def _getNullBoundingBox():
|
||||
return AxisAlignedBox(minimum=Vector(0, 0, 0), maximum=Vector(10, 10, 10))
|
||||
|
||||
def _createPolygon(self, current_z, path):
|
||||
def _createPolygon(self, layer_thickness, path, extruder_offsets):
|
||||
countvalid = 0
|
||||
for point in path:
|
||||
if point[3] > 0:
|
||||
countvalid += 1
|
||||
if countvalid >= 2:
|
||||
# we know what to do now, no need to count further
|
||||
continue
|
||||
if countvalid < 2:
|
||||
return False
|
||||
try:
|
||||
self._layer_data_builder.addLayer(self._layer)
|
||||
self._layer_data_builder.setLayerHeight(self._layer, path[0][2])
|
||||
self._layer_data_builder.setLayerThickness(self._layer, math.fabs(current_z - self._previous_z))
|
||||
this_layer = self._layer_data_builder.getLayer(self._layer)
|
||||
self._layer_data_builder.addLayer(self._layer_number)
|
||||
self._layer_data_builder.setLayerHeight(self._layer_number, path[0][2])
|
||||
self._layer_data_builder.setLayerThickness(self._layer_number, layer_thickness)
|
||||
this_layer = self._layer_data_builder.getLayer(self._layer_number)
|
||||
except ValueError:
|
||||
return False
|
||||
count = len(path)
|
||||
line_types = numpy.empty((count - 1, 1), numpy.int32)
|
||||
line_widths = numpy.empty((count - 1, 1), numpy.float32)
|
||||
line_thicknesses = numpy.empty((count - 1, 1), numpy.float32)
|
||||
# TODO: need to calculate actual line width based on E values
|
||||
line_widths[:, 0] = 0.4
|
||||
line_widths[:, 0] = 0.35 # Just a guess
|
||||
line_thicknesses[:, 0] = layer_thickness
|
||||
points = numpy.empty((count, 3), numpy.float32)
|
||||
i = 0
|
||||
for point in path:
|
||||
points[i, 0] = point[0]
|
||||
points[i, 1] = point[2]
|
||||
points[i, 2] = -point[1]
|
||||
points[i, :] = [point[0] + extruder_offsets[0], point[2], -point[1] - extruder_offsets[1]]
|
||||
if i > 0:
|
||||
line_types[i - 1] = point[3]
|
||||
if point[3] in [LayerPolygon.MoveCombingType, LayerPolygon.MoveRetractionType]:
|
||||
line_widths[i - 1] = 0.2
|
||||
line_widths[i - 1] = 0.1
|
||||
i += 1
|
||||
|
||||
this_poly = LayerPolygon(self._layer_data_builder, self._extruder, line_types, points, line_widths)
|
||||
this_poly = LayerPolygon(self._extruder_number, line_types, points, line_widths, line_thicknesses)
|
||||
this_poly.buildCache()
|
||||
|
||||
this_layer.polygons.append(this_poly)
|
||||
|
@ -123,30 +137,28 @@ class GCodeReader(MeshReader):
|
|||
x, y, z, e = position
|
||||
x = params.x if params.x is not None else x
|
||||
y = params.y if params.y is not None else y
|
||||
z_changed = False
|
||||
if params.z is not None:
|
||||
if z != params.z:
|
||||
z_changed = True
|
||||
self._previous_z = z
|
||||
z = params.z
|
||||
z = params.z if params.z is not None else position.z
|
||||
|
||||
if params.e is not None:
|
||||
if params.e > e[self._extruder]:
|
||||
if params.e > e[self._extruder_number]:
|
||||
path.append([x, y, z, self._layer_type]) # extrusion
|
||||
else:
|
||||
path.append([x, y, z, LayerPolygon.MoveRetractionType]) # retraction
|
||||
e[self._extruder] = params.e
|
||||
e[self._extruder_number] = params.e
|
||||
|
||||
# Only when extruding we can determine the latest known "layer height" which is the difference in height between extrusions
|
||||
# Also, 1.5 is a heuristic for any priming or whatsoever, we skip those.
|
||||
if z > self._previous_z and (z - self._previous_z < 1.5):
|
||||
self._current_layer_thickness = z - self._previous_z + 0.05 # allow a tiny overlap
|
||||
self._previous_z = z
|
||||
else:
|
||||
path.append([x, y, z, LayerPolygon.MoveCombingType])
|
||||
if z_changed:
|
||||
if not self._is_layers_in_file:
|
||||
if len(path) > 1 and z > 0:
|
||||
if self._createPolygon(z, path):
|
||||
self._layer += 1
|
||||
path.clear()
|
||||
else:
|
||||
path.clear()
|
||||
return self._position(x, y, z, e)
|
||||
|
||||
# G0 and G1 should be handled exactly the same.
|
||||
_gCode1 = _gCode0
|
||||
|
||||
## Home the head.
|
||||
def _gCode28(self, position, params, path):
|
||||
return self._position(
|
||||
params.x if params.x is not None else position.x,
|
||||
|
@ -154,24 +166,36 @@ class GCodeReader(MeshReader):
|
|||
0,
|
||||
position.e)
|
||||
|
||||
## Reset the current position to the values specified.
|
||||
# For example: G92 X10 will set the X to 10 without any physical motion.
|
||||
def _gCode92(self, position, params, path):
|
||||
if params.e is not None:
|
||||
position.e[self._extruder] = params.e
|
||||
position.e[self._extruder_number] = params.e
|
||||
return self._position(
|
||||
params.x if params.x is not None else position.x,
|
||||
params.y if params.y is not None else position.y,
|
||||
params.z if params.z is not None else position.z,
|
||||
position.e)
|
||||
|
||||
_gCode1 = _gCode0
|
||||
|
||||
def _processGCode(self, G, line, position, path):
|
||||
func = getattr(self, "_gCode%s" % G, None)
|
||||
x = self._getFloat(line, "X")
|
||||
y = self._getFloat(line, "Y")
|
||||
z = self._getFloat(line, "Z")
|
||||
e = self._getFloat(line, "E")
|
||||
line = line.split(";", 1)[0] # Remove comments (if any)
|
||||
if func is not None:
|
||||
s = line.upper().split(" ")
|
||||
x, y, z, e = None, None, None, None
|
||||
for item in s[1:]:
|
||||
if len(item) <= 1:
|
||||
continue
|
||||
if item.startswith(";"):
|
||||
continue
|
||||
if item[0] == "X":
|
||||
x = float(item[1:])
|
||||
if item[0] == "Y":
|
||||
y = float(item[1:])
|
||||
if item[0] == "Z":
|
||||
z = float(item[1:])
|
||||
if item[0] == "E":
|
||||
e = float(item[1:])
|
||||
if (x is not None and x < 0) or (y is not None and y < 0):
|
||||
self._center_is_zero = True
|
||||
params = self._position(x, y, z, e)
|
||||
|
@ -179,40 +203,46 @@ class GCodeReader(MeshReader):
|
|||
return position
|
||||
|
||||
def _processTCode(self, T, line, position, path):
|
||||
self._extruder = T
|
||||
if self._extruder + 1 > len(position.e):
|
||||
position.e.extend([0] * (self._extruder - len(position.e) + 1))
|
||||
if not self._is_layers_in_file:
|
||||
if len(path) > 1 and position[2] > 0:
|
||||
if self._createPolygon(position[2], path):
|
||||
self._layer += 1
|
||||
path.clear()
|
||||
else:
|
||||
path.clear()
|
||||
self._extruder_number = T
|
||||
if self._extruder_number + 1 > len(position.e):
|
||||
position.e.extend([0] * (self._extruder_number - len(position.e) + 1))
|
||||
return position
|
||||
|
||||
_type_keyword = ";TYPE:"
|
||||
_layer_keyword = ";LAYER:"
|
||||
|
||||
## For showing correct x, y offsets for each extruder
|
||||
def _extruderOffsets(self):
|
||||
result = {}
|
||||
for extruder in ExtruderManager.getInstance().getExtruderStacks():
|
||||
result[int(extruder.getMetaData().get("position", "0"))] = [
|
||||
extruder.getProperty("machine_nozzle_offset_x", "value"),
|
||||
extruder.getProperty("machine_nozzle_offset_y", "value")]
|
||||
return result
|
||||
|
||||
def read(self, file_name):
|
||||
Logger.log("d", "Preparing to load %s" % file_name)
|
||||
self._cancelled = False
|
||||
|
||||
scene_node = SceneNode()
|
||||
scene_node.getBoundingBox = self._getNullBoundingBox # Manually set bounding box, because mesh doesn't have mesh data
|
||||
# Override getBoundingBox function of the sceneNode, as this node should return a bounding box, but there is no
|
||||
# real data to calculate it from.
|
||||
scene_node.getBoundingBox = self._getNullBoundingBox
|
||||
|
||||
glist = []
|
||||
gcode_list = []
|
||||
self._is_layers_in_file = False
|
||||
|
||||
|
||||
Logger.log("d", "Opening file %s" % file_name)
|
||||
|
||||
self._extruder_offsets = self._extruderOffsets() # dict with index the extruder number. can be empty
|
||||
|
||||
last_z = 0
|
||||
with open(file_name, "r") as file:
|
||||
file_lines = 0
|
||||
current_line = 0
|
||||
for line in file:
|
||||
file_lines += 1
|
||||
glist.append(line)
|
||||
gcode_list.append(line)
|
||||
if not self._is_layers_in_file and line[:len(self._layer_keyword)] == self._layer_keyword:
|
||||
self._is_layers_in_file = True
|
||||
file.seek(0)
|
||||
|
@ -225,7 +255,7 @@ class GCodeReader(MeshReader):
|
|||
self._message.setProgress(0)
|
||||
self._message.show()
|
||||
|
||||
Logger.log("d", "Parsing %s" % file_name)
|
||||
Logger.log("d", "Parsing %s..." % file_name)
|
||||
|
||||
current_position = self._position(0, 0, 0, [0])
|
||||
current_path = []
|
||||
|
@ -235,10 +265,14 @@ class GCodeReader(MeshReader):
|
|||
Logger.log("d", "Parsing %s cancelled" % file_name)
|
||||
return None
|
||||
current_line += 1
|
||||
last_z = current_position.z
|
||||
|
||||
if current_line % file_step == 0:
|
||||
self._message.setProgress(math.floor(current_line / file_lines * 100))
|
||||
Job.yieldThread()
|
||||
if len(line) == 0:
|
||||
continue
|
||||
|
||||
if line.find(self._type_keyword) == 0:
|
||||
type = line[len(self._type_keyword):].strip()
|
||||
if type == "WALL-INNER":
|
||||
|
@ -253,42 +287,67 @@ class GCodeReader(MeshReader):
|
|||
self._layer_type = LayerPolygon.SupportType
|
||||
elif type == "FILL":
|
||||
self._layer_type = LayerPolygon.InfillType
|
||||
else:
|
||||
Logger.log("w", "Encountered a unknown type (%s) while parsing g-code.", type)
|
||||
|
||||
if self._is_layers_in_file and line[:len(self._layer_keyword)] == self._layer_keyword:
|
||||
try:
|
||||
layer_number = int(line[len(self._layer_keyword):])
|
||||
self._createPolygon(current_position[2], current_path)
|
||||
self._createPolygon(self._current_layer_thickness, current_path, self._extruder_offsets.get(self._extruder_number, [0, 0]))
|
||||
current_path.clear()
|
||||
self._layer = layer_number
|
||||
self._layer_number = layer_number
|
||||
except:
|
||||
pass
|
||||
if line[0] == ";":
|
||||
|
||||
# This line is a comment. Ignore it (except for the layer_keyword)
|
||||
if line.startswith(";"):
|
||||
continue
|
||||
|
||||
G = self._getInt(line, "G")
|
||||
if G is not None:
|
||||
current_position = self._processGCode(G, line, current_position, current_path)
|
||||
T = self._getInt(line, "T")
|
||||
if T is not None:
|
||||
current_position = self._processTCode(T, line, current_position, current_path)
|
||||
|
||||
if not self._is_layers_in_file and len(current_path) > 1 and current_position[2] > 0:
|
||||
if self._createPolygon(current_position[2], current_path):
|
||||
self._layer += 1
|
||||
current_path.clear()
|
||||
# < 2 is a heuristic for a movement only, that should not be counted as a layer
|
||||
if current_position.z > last_z and abs(current_position.z - last_z) < 2:
|
||||
if self._createPolygon(self._current_layer_thickness, current_path, self._extruder_offsets.get(self._extruder_number, [0, 0])):
|
||||
current_path.clear()
|
||||
if not self._is_layers_in_file:
|
||||
self._layer_number += 1
|
||||
|
||||
layer_mesh = self._layer_data_builder.build()
|
||||
continue
|
||||
|
||||
if line.startswith("T"):
|
||||
T = self._getInt(line, "T")
|
||||
if T is not None:
|
||||
self._createPolygon(self._current_layer_thickness, current_path, self._extruder_offsets.get(self._extruder_number, [0, 0]))
|
||||
current_path.clear()
|
||||
|
||||
current_position = self._processTCode(T, line, current_position, current_path)
|
||||
|
||||
# "Flush" leftovers
|
||||
if not self._is_layers_in_file and len(current_path) > 1:
|
||||
if self._createPolygon(self._current_layer_thickness, current_path, self._extruder_offsets.get(self._extruder_number, [0, 0])):
|
||||
self._layer_number += 1
|
||||
current_path.clear()
|
||||
|
||||
material_color_map = numpy.zeros((10, 4), dtype = numpy.float32)
|
||||
material_color_map[0, :] = [0.0, 0.7, 0.9, 1.0]
|
||||
material_color_map[1, :] = [0.7, 0.9, 0.0, 1.0]
|
||||
layer_mesh = self._layer_data_builder.build(material_color_map)
|
||||
decorator = LayerDataDecorator.LayerDataDecorator()
|
||||
decorator.setLayerData(layer_mesh)
|
||||
scene_node.addDecorator(decorator)
|
||||
|
||||
gcode_list_decorator = GCodeListDecorator()
|
||||
gcode_list_decorator.setGCodeList(glist)
|
||||
gcode_list_decorator.setGCodeList(gcode_list)
|
||||
scene_node.addDecorator(gcode_list_decorator)
|
||||
|
||||
Application.getInstance().getController().getScene().gcode_list = gcode_list
|
||||
|
||||
Logger.log("d", "Finished parsing %s" % file_name)
|
||||
self._message.hide()
|
||||
|
||||
if self._layer == 0:
|
||||
if self._layer_number == 0:
|
||||
Logger.log("w", "File %s doesn't contain any valid layers" % file_name)
|
||||
|
||||
settings = Application.getInstance().getGlobalContainerStack()
|
||||
|
@ -300,4 +359,14 @@ class GCodeReader(MeshReader):
|
|||
|
||||
Logger.log("d", "Loaded %s" % file_name)
|
||||
|
||||
if Preferences.getInstance().getValue("gcodereader/show_caution"):
|
||||
caution_message = Message(catalog.i18nc(
|
||||
"@info:generic",
|
||||
"Make sure the g-code is suitable for your printer and printer configuration before sending the file to it. The g-code representation may not be accurate."), lifetime=0)
|
||||
caution_message.show()
|
||||
|
||||
# The "save/print" button's state is bound to the backend state.
|
||||
backend = Application.getInstance().getBackend()
|
||||
backend.backendStateChange.emit(Backend.BackendState.Disabled)
|
||||
|
||||
return scene_node
|
||||
|
|
|
@ -4,13 +4,10 @@
|
|||
from UM.Mesh.MeshWriter import MeshWriter
|
||||
from UM.Logger import Logger
|
||||
from UM.Application import Application
|
||||
import UM.Settings.ContainerRegistry
|
||||
|
||||
from cura.CuraApplication import CuraApplication
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
|
||||
from UM.Settings.InstanceContainer import InstanceContainer
|
||||
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
|
||||
import re #For escaping characters in the settings.
|
||||
import json
|
||||
import copy
|
||||
|
|
|
@ -21,7 +21,7 @@ class ImageReader(MeshReader):
|
|||
self._supported_extensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"]
|
||||
self._ui = ImageReaderUI(self)
|
||||
|
||||
def preRead(self, file_name):
|
||||
def preRead(self, file_name, *args, **kwargs):
|
||||
img = QImage(file_name)
|
||||
|
||||
if img.isNull():
|
||||
|
|
41
plugins/LayerView/LayerPass.py
Normal file → Executable file
41
plugins/LayerView/LayerPass.py
Normal file → Executable file
|
@ -14,6 +14,7 @@ from UM.View.GL.OpenGL import OpenGL
|
|||
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
|
||||
|
||||
import os.path
|
||||
|
||||
## RenderPass used to display g-code paths.
|
||||
|
@ -28,15 +29,37 @@ class LayerPass(RenderPass):
|
|||
self._extruder_manager = ExtruderManager.getInstance()
|
||||
|
||||
self._layer_view = None
|
||||
self._compatibility_mode = None
|
||||
|
||||
def setLayerView(self, layerview):
|
||||
self._layerview = layerview
|
||||
self._layer_view = layerview
|
||||
self._compatibility_mode = layerview.getCompatibilityMode()
|
||||
|
||||
def render(self):
|
||||
if not self._layer_shader:
|
||||
self._layer_shader = OpenGL.getInstance().createShaderProgram(os.path.join(PluginRegistry.getInstance().getPluginPath("LayerView"), "layers.shader"))
|
||||
if self._compatibility_mode:
|
||||
shader_filename = "layers.shader"
|
||||
else:
|
||||
shader_filename = "layers3d.shader"
|
||||
self._layer_shader = OpenGL.getInstance().createShaderProgram(os.path.join(PluginRegistry.getInstance().getPluginPath("LayerView"), shader_filename))
|
||||
# Use extruder 0 if the extruder manager reports extruder index -1 (for single extrusion printers)
|
||||
self._layer_shader.setUniformValue("u_active_extruder", float(max(0, self._extruder_manager.activeExtruderIndex)))
|
||||
if self._layer_view:
|
||||
self._layer_shader.setUniformValue("u_layer_view_type", self._layer_view.getLayerViewType())
|
||||
self._layer_shader.setUniformValue("u_extruder_opacity", self._layer_view.getExtruderOpacities())
|
||||
self._layer_shader.setUniformValue("u_show_travel_moves", self._layer_view.getShowTravelMoves())
|
||||
self._layer_shader.setUniformValue("u_show_helpers", self._layer_view.getShowHelpers())
|
||||
self._layer_shader.setUniformValue("u_show_skin", self._layer_view.getShowSkin())
|
||||
self._layer_shader.setUniformValue("u_show_infill", self._layer_view.getShowInfill())
|
||||
else:
|
||||
#defaults
|
||||
self._layer_shader.setUniformValue("u_layer_view_type", 1)
|
||||
self._layer_shader.setUniformValue("u_extruder_opacity", [1, 1, 1, 1])
|
||||
self._layer_shader.setUniformValue("u_show_travel_moves", 0)
|
||||
self._layer_shader.setUniformValue("u_show_helpers", 1)
|
||||
self._layer_shader.setUniformValue("u_show_skin", 1)
|
||||
self._layer_shader.setUniformValue("u_show_infill", 1)
|
||||
|
||||
if not self._tool_handle_shader:
|
||||
self._tool_handle_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "toolhandle.shader"))
|
||||
|
||||
|
@ -55,13 +78,15 @@ class LayerPass(RenderPass):
|
|||
continue
|
||||
|
||||
# Render all layers below a certain number as line mesh instead of vertices.
|
||||
if self._layerview._current_layer_num - self._layerview._solid_layers > -1 and not self._layerview._only_show_top_layers:
|
||||
if self._layer_view._current_layer_num > -1 and ((not self._layer_view._only_show_top_layers) or (not self._layer_view.getCompatibilityMode())):
|
||||
start = 0
|
||||
end = 0
|
||||
element_counts = layer_data.getElementCounts()
|
||||
for layer, counts in element_counts.items():
|
||||
if layer + self._layerview._solid_layers > self._layerview._current_layer_num:
|
||||
if layer > self._layer_view._current_layer_num:
|
||||
break
|
||||
if self._layer_view._minimum_layer_num > layer:
|
||||
start += counts
|
||||
end += counts
|
||||
|
||||
# This uses glDrawRangeElements internally to only draw a certain range of lines.
|
||||
|
@ -72,11 +97,11 @@ class LayerPass(RenderPass):
|
|||
# Create a new batch that is not range-limited
|
||||
batch = RenderBatch(self._layer_shader, type = RenderBatch.RenderType.Solid)
|
||||
|
||||
if self._layerview._current_layer_mesh:
|
||||
batch.addItem(node.getWorldTransformation(), self._layerview._current_layer_mesh)
|
||||
if self._layer_view.getCurrentLayerMesh():
|
||||
batch.addItem(node.getWorldTransformation(), self._layer_view.getCurrentLayerMesh())
|
||||
|
||||
if self._layerview._current_layer_jumps:
|
||||
batch.addItem(node.getWorldTransformation(), self._layerview._current_layer_jumps)
|
||||
if self._layer_view.getCurrentLayerJumps():
|
||||
batch.addItem(node.getWorldTransformation(), self._layer_view.getCurrentLayerJumps())
|
||||
|
||||
if len(batch.items) > 0:
|
||||
batch.render(self._scene.getActiveCamera())
|
||||
|
|
206
plugins/LayerView/LayerView.py
Normal file → Executable file
206
plugins/LayerView/LayerView.py
Normal file → Executable file
|
@ -1,6 +1,8 @@
|
|||
# Copyright (c) 2015 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
import sys
|
||||
|
||||
from UM.PluginRegistry import PluginRegistry
|
||||
from UM.View.View import View
|
||||
from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
|
||||
|
@ -13,15 +15,15 @@ from UM.Mesh.MeshBuilder import MeshBuilder
|
|||
from UM.Job import Job
|
||||
from UM.Preferences import Preferences
|
||||
from UM.Logger import Logger
|
||||
from UM.Scene.SceneNode import SceneNode
|
||||
from UM.View.RenderBatch import RenderBatch
|
||||
from UM.View.GL.OpenGL import OpenGL
|
||||
from UM.Message import Message
|
||||
from UM.Application import Application
|
||||
from UM.View.GL.OpenGLContext import OpenGLContext
|
||||
|
||||
from cura.ConvexHullNode import ConvexHullNode
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
|
||||
from PyQt5.QtCore import Qt, QTimer
|
||||
from PyQt5.QtCore import Qt
|
||||
from PyQt5.QtWidgets import QApplication
|
||||
|
||||
from . import LayerViewProxy
|
||||
|
@ -36,11 +38,16 @@ import os.path
|
|||
|
||||
## View used to display g-code paths.
|
||||
class LayerView(View):
|
||||
# Must match LayerView.qml
|
||||
LAYER_VIEW_TYPE_MATERIAL_TYPE = 0
|
||||
LAYER_VIEW_TYPE_LINE_TYPE = 1
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self._max_layers = 0
|
||||
self._current_layer_num = 0
|
||||
self._minimum_layer_num = 0
|
||||
self._current_layer_mesh = None
|
||||
self._current_layer_jumps = None
|
||||
self._top_layers_job = None
|
||||
|
@ -60,17 +67,40 @@ class LayerView(View):
|
|||
self._proxy = LayerViewProxy.LayerViewProxy()
|
||||
self._controller.getScene().getRoot().childrenChanged.connect(self._onSceneChanged)
|
||||
|
||||
self._resetSettings()
|
||||
self._legend_items = None
|
||||
self._show_travel_moves = False
|
||||
|
||||
Preferences.getInstance().addPreference("view/top_layer_count", 5)
|
||||
Preferences.getInstance().addPreference("view/only_show_top_layers", False)
|
||||
Preferences.getInstance().addPreference("view/force_layer_view_compatibility_mode", False)
|
||||
|
||||
Preferences.getInstance().addPreference("layerview/layer_view_type", 0)
|
||||
Preferences.getInstance().addPreference("layerview/extruder_opacities", "")
|
||||
|
||||
Preferences.getInstance().addPreference("layerview/show_travel_moves", False)
|
||||
Preferences.getInstance().addPreference("layerview/show_helpers", True)
|
||||
Preferences.getInstance().addPreference("layerview/show_skin", True)
|
||||
Preferences.getInstance().addPreference("layerview/show_infill", True)
|
||||
|
||||
Preferences.getInstance().preferenceChanged.connect(self._onPreferencesChanged)
|
||||
self._updateWithPreferences()
|
||||
|
||||
self._solid_layers = int(Preferences.getInstance().getValue("view/top_layer_count"))
|
||||
self._only_show_top_layers = bool(Preferences.getInstance().getValue("view/only_show_top_layers"))
|
||||
self._compatibility_mode = True # for safety
|
||||
|
||||
self._wireprint_warning_message = Message(catalog.i18nc("@info:status", "Cura does not accurately display layers when Wire Printing is enabled"))
|
||||
|
||||
def _resetSettings(self):
|
||||
self._layer_view_type = 0 # 0 is material color, 1 is color by linetype, 2 is speed
|
||||
self._extruder_count = 0
|
||||
self._extruder_opacity = [1.0, 1.0, 1.0, 1.0]
|
||||
self._show_travel_moves = 0
|
||||
self._show_helpers = 1
|
||||
self._show_skin = 1
|
||||
self._show_infill = 1
|
||||
|
||||
def getActivity(self):
|
||||
return self._activity
|
||||
|
||||
|
@ -79,6 +109,7 @@ class LayerView(View):
|
|||
# Currently the RenderPass constructor requires a size > 0
|
||||
# This should be fixed in RenderPass's constructor.
|
||||
self._layer_pass = LayerPass.LayerPass(1, 1)
|
||||
self._compatibility_mode = OpenGLContext.isLegacyOpenGL() or bool(Preferences.getInstance().getValue("view/force_layer_view_compatibility_mode"))
|
||||
self._layer_pass.setLayerView(self)
|
||||
self.getRenderer().addRenderPass(self._layer_pass)
|
||||
return self._layer_pass
|
||||
|
@ -86,6 +117,9 @@ class LayerView(View):
|
|||
def getCurrentLayer(self):
|
||||
return self._current_layer_num
|
||||
|
||||
def getMinimumLayer(self):
|
||||
return self._minimum_layer_num
|
||||
|
||||
def _onSceneChanged(self, node):
|
||||
self.calculateMaxLayers()
|
||||
|
||||
|
@ -131,11 +165,84 @@ class LayerView(View):
|
|||
self._current_layer_num = 0
|
||||
if self._current_layer_num > self._max_layers:
|
||||
self._current_layer_num = self._max_layers
|
||||
if self._current_layer_num < self._minimum_layer_num:
|
||||
self._minimum_layer_num = self._current_layer_num
|
||||
|
||||
self._startUpdateTopLayers()
|
||||
|
||||
self.currentLayerNumChanged.emit()
|
||||
|
||||
def setMinimumLayer(self, value):
|
||||
if self._minimum_layer_num != value:
|
||||
self._minimum_layer_num = value
|
||||
if self._minimum_layer_num < 0:
|
||||
self._minimum_layer_num = 0
|
||||
if self._minimum_layer_num > self._max_layers:
|
||||
self._minimum_layer_num = self._max_layers
|
||||
if self._minimum_layer_num > self._current_layer_num:
|
||||
self._current_layer_num = self._minimum_layer_num
|
||||
|
||||
self._startUpdateTopLayers()
|
||||
|
||||
self.currentLayerNumChanged.emit()
|
||||
|
||||
## Set the layer view type
|
||||
#
|
||||
# \param layer_view_type integer as in LayerView.qml and this class
|
||||
def setLayerViewType(self, layer_view_type):
|
||||
self._layer_view_type = layer_view_type
|
||||
self.currentLayerNumChanged.emit()
|
||||
|
||||
## Return the layer view type, integer as in LayerView.qml and this class
|
||||
def getLayerViewType(self):
|
||||
return self._layer_view_type
|
||||
|
||||
## Set the extruder opacity
|
||||
#
|
||||
# \param extruder_nr 0..3
|
||||
# \param opacity 0.0 .. 1.0
|
||||
def setExtruderOpacity(self, extruder_nr, opacity):
|
||||
if 0 <= extruder_nr <= 3:
|
||||
self._extruder_opacity[extruder_nr] = opacity
|
||||
self.currentLayerNumChanged.emit()
|
||||
|
||||
def getExtruderOpacities(self):
|
||||
return self._extruder_opacity
|
||||
|
||||
def setShowTravelMoves(self, show):
|
||||
self._show_travel_moves = show
|
||||
self.currentLayerNumChanged.emit()
|
||||
|
||||
def getShowTravelMoves(self):
|
||||
return self._show_travel_moves
|
||||
|
||||
def setShowHelpers(self, show):
|
||||
self._show_helpers = show
|
||||
self.currentLayerNumChanged.emit()
|
||||
|
||||
def getShowHelpers(self):
|
||||
return self._show_helpers
|
||||
|
||||
def setShowSkin(self, show):
|
||||
self._show_skin = show
|
||||
self.currentLayerNumChanged.emit()
|
||||
|
||||
def getShowSkin(self):
|
||||
return self._show_skin
|
||||
|
||||
def setShowInfill(self, show):
|
||||
self._show_infill = show
|
||||
self.currentLayerNumChanged.emit()
|
||||
|
||||
def getShowInfill(self):
|
||||
return self._show_infill
|
||||
|
||||
def getCompatibilityMode(self):
|
||||
return self._compatibility_mode
|
||||
|
||||
def getExtruderCount(self):
|
||||
return self._extruder_count
|
||||
|
||||
def calculateMaxLayers(self):
|
||||
scene = self.getController().getScene()
|
||||
self._activity = True
|
||||
|
@ -148,8 +255,17 @@ class LayerView(View):
|
|||
if not layer_data:
|
||||
continue
|
||||
|
||||
if new_max_layers < len(layer_data.getLayers()):
|
||||
new_max_layers = len(layer_data.getLayers()) - 1
|
||||
min_layer_number = sys.maxsize
|
||||
max_layer_number = -sys.maxsize
|
||||
for layer_id in layer_data.getLayers():
|
||||
if max_layer_number < layer_id:
|
||||
max_layer_number = layer_id
|
||||
if min_layer_number > layer_id:
|
||||
min_layer_number = layer_id
|
||||
layer_count = max_layer_number - min_layer_number
|
||||
|
||||
if new_max_layers < layer_count:
|
||||
new_max_layers = layer_count
|
||||
|
||||
if new_max_layers > 0 and new_max_layers != self._old_max_layers:
|
||||
self._max_layers = new_max_layers
|
||||
|
@ -167,6 +283,8 @@ class LayerView(View):
|
|||
|
||||
maxLayersChanged = Signal()
|
||||
currentLayerNumChanged = Signal()
|
||||
globalStackChanged = Signal()
|
||||
preferencesChanged = Signal()
|
||||
|
||||
## Hackish way to ensure the proxy is already created, which ensures that the layerview.qml is already created
|
||||
# as this caused some issues.
|
||||
|
@ -178,13 +296,15 @@ class LayerView(View):
|
|||
|
||||
def event(self, event):
|
||||
modifiers = QApplication.keyboardModifiers()
|
||||
ctrl_is_active = modifiers == Qt.ControlModifier
|
||||
ctrl_is_active = modifiers & Qt.ControlModifier
|
||||
shift_is_active = modifiers & Qt.ShiftModifier
|
||||
if event.type == Event.KeyPressEvent and ctrl_is_active:
|
||||
amount = 10 if shift_is_active else 1
|
||||
if event.key == KeyEvent.UpKey:
|
||||
self.setLayer(self._current_layer_num + 1)
|
||||
self.setLayer(self._current_layer_num + amount)
|
||||
return True
|
||||
if event.key == KeyEvent.DownKey:
|
||||
self.setLayer(self._current_layer_num - 1)
|
||||
self.setLayer(self._current_layer_num - amount)
|
||||
return True
|
||||
|
||||
if event.type == Event.ViewActivateEvent:
|
||||
|
@ -208,8 +328,6 @@ class LayerView(View):
|
|||
self._old_composite_shader = self._composite_pass.getCompositeShader()
|
||||
self._composite_pass.setCompositeShader(self._layerview_composite_shader)
|
||||
|
||||
Application.getInstance().setViewLegendItems(self._getLegendItems())
|
||||
|
||||
elif event.type == Event.ViewDeactivateEvent:
|
||||
self._wireprint_warning_message.hide()
|
||||
Application.getInstance().globalContainerStackChanged.disconnect(self._onGlobalStackChanged)
|
||||
|
@ -219,7 +337,11 @@ class LayerView(View):
|
|||
self._composite_pass.setLayerBindings(self._old_layer_bindings)
|
||||
self._composite_pass.setCompositeShader(self._old_composite_shader)
|
||||
|
||||
Application.getInstance().setViewLegendItems([])
|
||||
def getCurrentLayerMesh(self):
|
||||
return self._current_layer_mesh
|
||||
|
||||
def getCurrentLayerJumps(self):
|
||||
return self._current_layer_jumps
|
||||
|
||||
def _onGlobalStackChanged(self):
|
||||
if self._global_container_stack:
|
||||
|
@ -227,7 +349,9 @@ class LayerView(View):
|
|||
self._global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if self._global_container_stack:
|
||||
self._global_container_stack.propertyChanged.connect(self._onPropertyChanged)
|
||||
self._extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
|
||||
self._onPropertyChanged("wireframe_enabled", "value")
|
||||
self.globalStackChanged.emit()
|
||||
else:
|
||||
self._wireprint_warning_message.hide()
|
||||
|
||||
|
@ -239,6 +363,9 @@ class LayerView(View):
|
|||
self._wireprint_warning_message.hide()
|
||||
|
||||
def _startUpdateTopLayers(self):
|
||||
if not self._compatibility_mode:
|
||||
return
|
||||
|
||||
if self._top_layers_job:
|
||||
self._top_layers_job.finished.disconnect(self._updateCurrentLayerMesh)
|
||||
self._top_layers_job.cancel()
|
||||
|
@ -256,37 +383,50 @@ class LayerView(View):
|
|||
return
|
||||
self.resetLayerData() # Reset the layer data only when job is done. Doing it now prevents "blinking" data.
|
||||
self._current_layer_mesh = job.getResult().get("layers")
|
||||
self._current_layer_jumps = job.getResult().get("jumps")
|
||||
if self._show_travel_moves:
|
||||
self._current_layer_jumps = job.getResult().get("jumps")
|
||||
self._controller.getScene().sceneChanged.emit(self._controller.getScene().getRoot())
|
||||
|
||||
self._top_layers_job = None
|
||||
|
||||
def _onPreferencesChanged(self, preference):
|
||||
if preference != "view/top_layer_count" and preference != "view/only_show_top_layers":
|
||||
return
|
||||
|
||||
def _updateWithPreferences(self):
|
||||
self._solid_layers = int(Preferences.getInstance().getValue("view/top_layer_count"))
|
||||
self._only_show_top_layers = bool(Preferences.getInstance().getValue("view/only_show_top_layers"))
|
||||
self._compatibility_mode = OpenGLContext.isLegacyOpenGL() or bool(
|
||||
Preferences.getInstance().getValue("view/force_layer_view_compatibility_mode"))
|
||||
|
||||
self.setLayerViewType(int(float(Preferences.getInstance().getValue("layerview/layer_view_type"))));
|
||||
|
||||
for extruder_nr, extruder_opacity in enumerate(Preferences.getInstance().getValue("layerview/extruder_opacities").split("|")):
|
||||
try:
|
||||
opacity = float(extruder_opacity)
|
||||
except ValueError:
|
||||
opacity = 1.0
|
||||
self.setExtruderOpacity(extruder_nr, opacity)
|
||||
|
||||
self.setShowTravelMoves(bool(Preferences.getInstance().getValue("layerview/show_travel_moves")))
|
||||
self.setShowHelpers(bool(Preferences.getInstance().getValue("layerview/show_helpers")))
|
||||
self.setShowSkin(bool(Preferences.getInstance().getValue("layerview/show_skin")))
|
||||
self.setShowInfill(bool(Preferences.getInstance().getValue("layerview/show_infill")))
|
||||
|
||||
self._startUpdateTopLayers()
|
||||
self.preferencesChanged.emit()
|
||||
|
||||
def _getLegendItems(self):
|
||||
if self._legend_items is None:
|
||||
theme = Application.getInstance().getTheme()
|
||||
self._legend_items = [
|
||||
{"color": theme.getColor("layerview_inset_0").name(), "title": catalog.i18nc("@label:layerview polygon type", "Outer Wall")}, # Inset0Type
|
||||
{"color": theme.getColor("layerview_inset_x").name(), "title": catalog.i18nc("@label:layerview polygon type", "Inner Wall")}, # InsetXType
|
||||
{"color": theme.getColor("layerview_skin").name(), "title": catalog.i18nc("@label:layerview polygon type", "Top / Bottom")}, # SkinType
|
||||
{"color": theme.getColor("layerview_infill").name(), "title": catalog.i18nc("@label:layerview polygon type", "Infill")}, # InfillType
|
||||
{"color": theme.getColor("layerview_support").name(), "title": catalog.i18nc("@label:layerview polygon type", "Support Skin")}, # SupportType
|
||||
{"color": theme.getColor("layerview_support_infill").name(), "title": catalog.i18nc("@label:layerview polygon type", "Support Infill")}, # SupportInfillType
|
||||
{"color": theme.getColor("layerview_support_interface").name(), "title": catalog.i18nc("@label:layerview polygon type", "Support Interface")}, # SupportInterfaceType
|
||||
{"color": theme.getColor("layerview_skirt").name(), "title": catalog.i18nc("@label:layerview polygon type", "Build Plate Adhesion")}, # SkirtType
|
||||
{"color": theme.getColor("layerview_move_combing").name(), "title": catalog.i18nc("@label:layerview polygon type", "Travel Move")}, # MoveCombingType
|
||||
{"color": theme.getColor("layerview_move_retraction").name(), "title": catalog.i18nc("@label:layerview polygon type", "Retraction Move")}, # MoveRetractionType
|
||||
#{"color": theme.getColor("layerview_none").name(), "title": catalog.i18nc("@label:layerview polygon type", "Unknown")} # NoneType
|
||||
]
|
||||
return self._legend_items
|
||||
def _onPreferencesChanged(self, preference):
|
||||
if preference not in {
|
||||
"view/top_layer_count",
|
||||
"view/only_show_top_layers",
|
||||
"view/force_layer_view_compatibility_mode",
|
||||
"layerview/layer_view_type",
|
||||
"layerview/extruder_opacities",
|
||||
"layerview/show_travel_moves",
|
||||
"layerview/show_helpers",
|
||||
"layerview/show_skin",
|
||||
"layerview/show_infill",
|
||||
}:
|
||||
return
|
||||
|
||||
self._updateWithPreferences()
|
||||
|
||||
|
||||
class _CreateTopLayersJob(Job):
|
||||
|
|
|
@ -10,107 +10,610 @@ import UM 1.0 as UM
|
|||
|
||||
Item
|
||||
{
|
||||
width: UM.Theme.getSize("button").width
|
||||
height: UM.Theme.getSize("slider_layerview_size").height
|
||||
|
||||
Slider
|
||||
{
|
||||
id: slider
|
||||
width: UM.Theme.getSize("slider_layerview_size").width
|
||||
height: UM.Theme.getSize("slider_layerview_size").height
|
||||
anchors.left: parent.left
|
||||
anchors.leftMargin: UM.Theme.getSize("slider_layerview_margin").width/2
|
||||
orientation: Qt.Vertical
|
||||
minimumValue: 0;
|
||||
maximumValue: UM.LayerView.numLayers;
|
||||
stepSize: 1
|
||||
|
||||
property real pixelsPerStep: ((height - UM.Theme.getSize("slider_handle").height) / (maximumValue - minimumValue)) * stepSize;
|
||||
|
||||
value: UM.LayerView.currentLayer
|
||||
onValueChanged: UM.LayerView.setCurrentLayer(value)
|
||||
|
||||
style: UM.Theme.styles.slider;
|
||||
|
||||
Rectangle
|
||||
{
|
||||
x: parent.width + UM.Theme.getSize("slider_layerview_background").width / 2;
|
||||
y: parent.height - (parent.value * parent.pixelsPerStep) - UM.Theme.getSize("slider_handle").height * 1.25;
|
||||
|
||||
height: UM.Theme.getSize("slider_handle").height + UM.Theme.getSize("default_margin").height
|
||||
width: valueLabel.width + UM.Theme.getSize("default_margin").width
|
||||
Behavior on height { NumberAnimation { duration: 50; } }
|
||||
|
||||
border.width: UM.Theme.getSize("default_lining").width
|
||||
border.color: UM.Theme.getColor("slider_groove_border")
|
||||
color: UM.Theme.getColor("tool_panel_background")
|
||||
|
||||
visible: UM.LayerView.getLayerActivity && Printer.getPlatformActivity ? true : false
|
||||
|
||||
TextField
|
||||
{
|
||||
id: valueLabel
|
||||
property string maxValue: slider.maximumValue + 1
|
||||
text: slider.value + 1
|
||||
horizontalAlignment: TextInput.AlignRight;
|
||||
onEditingFinished:
|
||||
{
|
||||
// Ensure that the cursor is at the first position. On some systems the text isn't fully visible
|
||||
// Seems to have to do something with different dpi densities that QML doesn't quite handle.
|
||||
// Another option would be to increase the size even further, but that gives pretty ugly results.
|
||||
cursorPosition = 0;
|
||||
if(valueLabel.text != '')
|
||||
{
|
||||
slider.value = valueLabel.text - 1;
|
||||
}
|
||||
}
|
||||
validator: IntValidator { bottom: 1; top: slider.maximumValue + 1; }
|
||||
|
||||
anchors.left: parent.left;
|
||||
anchors.leftMargin: UM.Theme.getSize("default_margin").width / 2;
|
||||
anchors.verticalCenter: parent.verticalCenter;
|
||||
|
||||
width: Math.max(UM.Theme.getSize("line").width * maxValue.length + 2, 20);
|
||||
style: TextFieldStyle
|
||||
{
|
||||
textColor: UM.Theme.getColor("setting_control_text");
|
||||
font: UM.Theme.getFont("default");
|
||||
background: Item { }
|
||||
}
|
||||
}
|
||||
|
||||
BusyIndicator
|
||||
{
|
||||
id: busyIndicator;
|
||||
anchors.left: parent.right;
|
||||
anchors.leftMargin: UM.Theme.getSize("default_margin").width / 2;
|
||||
anchors.verticalCenter: parent.verticalCenter;
|
||||
|
||||
width: UM.Theme.getSize("slider_handle").height;
|
||||
height: width;
|
||||
|
||||
running: UM.LayerView.busy;
|
||||
visible: UM.LayerView.busy;
|
||||
}
|
||||
width: {
|
||||
if (UM.LayerView.compatibilityMode) {
|
||||
return UM.Theme.getSize("layerview_menu_size_compatibility").width;
|
||||
} else {
|
||||
return UM.Theme.getSize("layerview_menu_size").width;
|
||||
}
|
||||
}
|
||||
height: {
|
||||
if (UM.LayerView.compatibilityMode) {
|
||||
return UM.Theme.getSize("layerview_menu_size_compatibility").height;
|
||||
} else {
|
||||
return UM.Theme.getSize("layerview_menu_size").height + UM.LayerView.extruderCount * (UM.Theme.getSize("layerview_row").height + UM.Theme.getSize("layerview_row_spacing").height)
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
id: layerViewMenu
|
||||
anchors.left: parent.left
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
anchors.top: parent.top
|
||||
width: parent.width
|
||||
height: parent.height
|
||||
z: slider.z - 1
|
||||
width: UM.Theme.getSize("slider_layerview_background").width
|
||||
height: slider.height + UM.Theme.getSize("default_margin").height * 2
|
||||
color: UM.Theme.getColor("tool_panel_background");
|
||||
border.width: UM.Theme.getSize("default_lining").width
|
||||
border.color: UM.Theme.getColor("lining")
|
||||
color: UM.Theme.getColor("tool_panel_background")
|
||||
|
||||
MouseArea {
|
||||
id: sliderMouseArea
|
||||
property double manualStepSize: slider.maximumValue / 11
|
||||
anchors.fill: parent
|
||||
onWheel: {
|
||||
slider.value = wheel.angleDelta.y < 0 ? slider.value - sliderMouseArea.manualStepSize : slider.value + sliderMouseArea.manualStepSize
|
||||
ColumnLayout {
|
||||
id: view_settings
|
||||
|
||||
property var extruder_opacities: UM.Preferences.getValue("layerview/extruder_opacities").split("|")
|
||||
property bool show_travel_moves: UM.Preferences.getValue("layerview/show_travel_moves")
|
||||
property bool show_helpers: UM.Preferences.getValue("layerview/show_helpers")
|
||||
property bool show_skin: UM.Preferences.getValue("layerview/show_skin")
|
||||
property bool show_infill: UM.Preferences.getValue("layerview/show_infill")
|
||||
property bool show_legend: UM.LayerView.compatibilityMode || UM.Preferences.getValue("layerview/layer_view_type") == 1
|
||||
property bool only_show_top_layers: UM.Preferences.getValue("view/only_show_top_layers")
|
||||
property int top_layer_count: UM.Preferences.getValue("view/top_layer_count")
|
||||
|
||||
anchors.top: parent.top
|
||||
anchors.topMargin: UM.Theme.getSize("default_margin").height
|
||||
anchors.left: parent.left
|
||||
anchors.leftMargin: UM.Theme.getSize("default_margin").width
|
||||
spacing: UM.Theme.getSize("layerview_row_spacing").height
|
||||
|
||||
Label
|
||||
{
|
||||
id: layersLabel
|
||||
anchors.left: parent.left
|
||||
text: catalog.i18nc("@label","View Mode: Layers")
|
||||
font.bold: true
|
||||
}
|
||||
|
||||
Label
|
||||
{
|
||||
id: spaceLabel
|
||||
anchors.left: parent.left
|
||||
text: " "
|
||||
font.pointSize: 0.5
|
||||
}
|
||||
|
||||
Label
|
||||
{
|
||||
id: layerViewTypesLabel
|
||||
anchors.left: parent.left
|
||||
text: catalog.i18nc("@label","Color scheme")
|
||||
visible: !UM.LayerView.compatibilityMode
|
||||
Layout.fillWidth: true
|
||||
}
|
||||
|
||||
ListModel // matches LayerView.py
|
||||
{
|
||||
id: layerViewTypes
|
||||
}
|
||||
|
||||
Component.onCompleted:
|
||||
{
|
||||
layerViewTypes.append({
|
||||
text: catalog.i18nc("@label:listbox", "Material Color"),
|
||||
type_id: 0
|
||||
})
|
||||
layerViewTypes.append({
|
||||
text: catalog.i18nc("@label:listbox", "Line Type"),
|
||||
type_id: 1 // these ids match the switching in the shader
|
||||
})
|
||||
}
|
||||
|
||||
ComboBox
|
||||
{
|
||||
id: layerTypeCombobox
|
||||
anchors.left: parent.left
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredWidth: UM.Theme.getSize("layerview_row").width
|
||||
model: layerViewTypes
|
||||
visible: !UM.LayerView.compatibilityMode
|
||||
|
||||
property int layer_view_type: UM.Preferences.getValue("layerview/layer_view_type")
|
||||
currentIndex: layer_view_type // index matches type_id
|
||||
onActivated: {
|
||||
// Combobox selection
|
||||
var type_id = index;
|
||||
UM.Preferences.setValue("layerview/layer_view_type", type_id);
|
||||
updateLegend(type_id);
|
||||
}
|
||||
onModelChanged: {
|
||||
updateLegend(UM.Preferences.getValue("layerview/layer_view_type"));
|
||||
}
|
||||
|
||||
// Update visibility of legend.
|
||||
function updateLegend(type_id) {
|
||||
if (UM.LayerView.compatibilityMode || (type_id == 1)) {
|
||||
// Line type
|
||||
view_settings.show_legend = true;
|
||||
} else {
|
||||
view_settings.show_legend = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Label
|
||||
{
|
||||
id: compatibilityModeLabel
|
||||
anchors.left: parent.left
|
||||
text: catalog.i18nc("@label","Compatibility Mode")
|
||||
visible: UM.LayerView.compatibilityMode
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredHeight: UM.Theme.getSize("layerview_row").height
|
||||
Layout.preferredWidth: UM.Theme.getSize("layerview_row").width
|
||||
}
|
||||
|
||||
Label
|
||||
{
|
||||
id: space2Label
|
||||
anchors.left: parent.left
|
||||
text: " "
|
||||
font.pointSize: 0.5
|
||||
}
|
||||
|
||||
Connections {
|
||||
target: UM.Preferences
|
||||
onPreferenceChanged:
|
||||
{
|
||||
layerTypeCombobox.layer_view_type = UM.Preferences.getValue("layerview/layer_view_type");
|
||||
view_settings.extruder_opacities = UM.Preferences.getValue("layerview/extruder_opacities").split("|");
|
||||
view_settings.show_travel_moves = UM.Preferences.getValue("layerview/show_travel_moves");
|
||||
view_settings.show_helpers = UM.Preferences.getValue("layerview/show_helpers");
|
||||
view_settings.show_skin = UM.Preferences.getValue("layerview/show_skin");
|
||||
view_settings.show_infill = UM.Preferences.getValue("layerview/show_infill");
|
||||
view_settings.only_show_top_layers = UM.Preferences.getValue("view/only_show_top_layers");
|
||||
view_settings.top_layer_count = UM.Preferences.getValue("view/top_layer_count");
|
||||
}
|
||||
}
|
||||
|
||||
Repeater {
|
||||
model: UM.LayerView.extruderCount
|
||||
CheckBox {
|
||||
checked: view_settings.extruder_opacities[index] > 0.5 || view_settings.extruder_opacities[index] == undefined || view_settings.extruder_opacities[index] == ""
|
||||
onClicked: {
|
||||
view_settings.extruder_opacities[index] = checked ? 1.0 : 0.0
|
||||
UM.Preferences.setValue("layerview/extruder_opacities", view_settings.extruder_opacities.join("|"));
|
||||
}
|
||||
text: catalog.i18nc("@label", "Extruder %1").arg(index + 1)
|
||||
visible: !UM.LayerView.compatibilityMode
|
||||
enabled: index + 1 <= 4
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredHeight: UM.Theme.getSize("layerview_row").height
|
||||
Layout.preferredWidth: UM.Theme.getSize("layerview_row").width
|
||||
}
|
||||
}
|
||||
|
||||
CheckBox {
|
||||
checked: view_settings.show_travel_moves
|
||||
onClicked: {
|
||||
UM.Preferences.setValue("layerview/show_travel_moves", checked);
|
||||
}
|
||||
text: catalog.i18nc("@label", "Show Travels")
|
||||
Rectangle {
|
||||
anchors.top: parent.top
|
||||
anchors.topMargin: 2
|
||||
anchors.right: parent.right
|
||||
width: UM.Theme.getSize("layerview_legend_size").width
|
||||
height: UM.Theme.getSize("layerview_legend_size").height
|
||||
color: UM.Theme.getColor("layerview_move_combing")
|
||||
border.width: UM.Theme.getSize("default_lining").width
|
||||
border.color: UM.Theme.getColor("lining")
|
||||
visible: view_settings.show_legend
|
||||
}
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredHeight: UM.Theme.getSize("layerview_row").height
|
||||
Layout.preferredWidth: UM.Theme.getSize("layerview_row").width
|
||||
}
|
||||
CheckBox {
|
||||
checked: view_settings.show_helpers
|
||||
onClicked: {
|
||||
UM.Preferences.setValue("layerview/show_helpers", checked);
|
||||
}
|
||||
text: catalog.i18nc("@label", "Show Helpers")
|
||||
Rectangle {
|
||||
anchors.top: parent.top
|
||||
anchors.topMargin: 2
|
||||
anchors.right: parent.right
|
||||
width: UM.Theme.getSize("layerview_legend_size").width
|
||||
height: UM.Theme.getSize("layerview_legend_size").height
|
||||
color: UM.Theme.getColor("layerview_support")
|
||||
border.width: UM.Theme.getSize("default_lining").width
|
||||
border.color: UM.Theme.getColor("lining")
|
||||
visible: view_settings.show_legend
|
||||
}
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredHeight: UM.Theme.getSize("layerview_row").height
|
||||
Layout.preferredWidth: UM.Theme.getSize("layerview_row").width
|
||||
}
|
||||
CheckBox {
|
||||
checked: view_settings.show_skin
|
||||
onClicked: {
|
||||
UM.Preferences.setValue("layerview/show_skin", checked);
|
||||
}
|
||||
text: catalog.i18nc("@label", "Show Shell")
|
||||
Rectangle {
|
||||
anchors.top: parent.top
|
||||
anchors.topMargin: 2
|
||||
anchors.right: parent.right
|
||||
width: UM.Theme.getSize("layerview_legend_size").width
|
||||
height: UM.Theme.getSize("layerview_legend_size").height
|
||||
color: UM.Theme.getColor("layerview_inset_0")
|
||||
border.width: UM.Theme.getSize("default_lining").width
|
||||
border.color: UM.Theme.getColor("lining")
|
||||
visible: view_settings.show_legend
|
||||
}
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredHeight: UM.Theme.getSize("layerview_row").height
|
||||
Layout.preferredWidth: UM.Theme.getSize("layerview_row").width
|
||||
}
|
||||
CheckBox {
|
||||
checked: view_settings.show_infill
|
||||
onClicked: {
|
||||
UM.Preferences.setValue("layerview/show_infill", checked);
|
||||
}
|
||||
text: catalog.i18nc("@label", "Show Infill")
|
||||
Rectangle {
|
||||
anchors.top: parent.top
|
||||
anchors.topMargin: 2
|
||||
anchors.right: parent.right
|
||||
width: UM.Theme.getSize("layerview_legend_size").width
|
||||
height: UM.Theme.getSize("layerview_legend_size").height
|
||||
color: UM.Theme.getColor("layerview_infill")
|
||||
border.width: UM.Theme.getSize("default_lining").width
|
||||
border.color: UM.Theme.getColor("lining")
|
||||
visible: view_settings.show_legend
|
||||
}
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredHeight: UM.Theme.getSize("layerview_row").height
|
||||
Layout.preferredWidth: UM.Theme.getSize("layerview_row").width
|
||||
}
|
||||
CheckBox {
|
||||
checked: view_settings.only_show_top_layers
|
||||
onClicked: {
|
||||
UM.Preferences.setValue("view/only_show_top_layers", checked ? 1.0 : 0.0);
|
||||
}
|
||||
text: catalog.i18nc("@label", "Only Show Top Layers")
|
||||
visible: UM.LayerView.compatibilityMode
|
||||
}
|
||||
CheckBox {
|
||||
checked: view_settings.top_layer_count == 5
|
||||
onClicked: {
|
||||
UM.Preferences.setValue("view/top_layer_count", checked ? 5 : 1);
|
||||
}
|
||||
text: catalog.i18nc("@label", "Show 5 Detailed Layers On Top")
|
||||
visible: UM.LayerView.compatibilityMode
|
||||
}
|
||||
|
||||
Label
|
||||
{
|
||||
id: topBottomLabel
|
||||
anchors.left: parent.left
|
||||
text: catalog.i18nc("@label","Top / Bottom")
|
||||
Rectangle {
|
||||
anchors.top: parent.top
|
||||
anchors.topMargin: 2
|
||||
anchors.right: parent.right
|
||||
width: UM.Theme.getSize("layerview_legend_size").width
|
||||
height: UM.Theme.getSize("layerview_legend_size").height
|
||||
color: UM.Theme.getColor("layerview_skin")
|
||||
border.width: UM.Theme.getSize("default_lining").width
|
||||
border.color: UM.Theme.getColor("lining")
|
||||
}
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredHeight: UM.Theme.getSize("layerview_row").height
|
||||
Layout.preferredWidth: UM.Theme.getSize("layerview_row").width
|
||||
visible: view_settings.show_legend
|
||||
}
|
||||
|
||||
Label
|
||||
{
|
||||
id: innerWallLabel
|
||||
anchors.left: parent.left
|
||||
text: catalog.i18nc("@label","Inner Wall")
|
||||
Rectangle {
|
||||
anchors.top: parent.top
|
||||
anchors.topMargin: 2
|
||||
anchors.right: parent.right
|
||||
width: UM.Theme.getSize("layerview_legend_size").width
|
||||
height: UM.Theme.getSize("layerview_legend_size").height
|
||||
color: UM.Theme.getColor("layerview_inset_x")
|
||||
border.width: UM.Theme.getSize("default_lining").width
|
||||
border.color: UM.Theme.getColor("lining")
|
||||
visible: view_settings.show_legend
|
||||
}
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredHeight: UM.Theme.getSize("layerview_row").height
|
||||
Layout.preferredWidth: UM.Theme.getSize("layerview_row").width
|
||||
visible: view_settings.show_legend
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Item
|
||||
{
|
||||
id: slider
|
||||
width: handleSize
|
||||
height: parent.height - 2*UM.Theme.getSize("slider_layerview_margin").height
|
||||
anchors.top: parent.top
|
||||
anchors.topMargin: UM.Theme.getSize("slider_layerview_margin").height
|
||||
anchors.right: layerViewMenu.right
|
||||
anchors.rightMargin: UM.Theme.getSize("slider_layerview_margin").width
|
||||
|
||||
property real handleSize: UM.Theme.getSize("slider_handle").width
|
||||
property real handleRadius: handleSize / 2
|
||||
property real minimumRangeHandleSize: UM.Theme.getSize("slider_handle").width / 2
|
||||
property real trackThickness: UM.Theme.getSize("slider_groove").width
|
||||
property real trackRadius: trackThickness / 2
|
||||
property real trackBorderWidth: UM.Theme.getSize("default_lining").width
|
||||
property color upperHandleColor: UM.Theme.getColor("slider_handle")
|
||||
property color lowerHandleColor: UM.Theme.getColor("slider_handle")
|
||||
property color rangeHandleColor: UM.Theme.getColor("slider_groove_fill")
|
||||
property color trackColor: UM.Theme.getColor("slider_groove")
|
||||
property color trackBorderColor: UM.Theme.getColor("slider_groove_border")
|
||||
|
||||
property real maximumValue: UM.LayerView.numLayers
|
||||
property real minimumValue: 0
|
||||
property real minimumRange: 0
|
||||
property bool roundValues: true
|
||||
|
||||
property var activeHandle: upperHandle
|
||||
property bool layersVisible: UM.LayerView.layerActivity && CuraApplication.platformActivity ? true : false
|
||||
|
||||
function getUpperValueFromHandle()
|
||||
{
|
||||
var result = upperHandle.y / (height - (2 * handleSize + minimumRangeHandleSize));
|
||||
result = maximumValue + result * (minimumValue - (maximumValue - minimumRange));
|
||||
result = roundValues ? Math.round(result) | 0 : result;
|
||||
return result;
|
||||
}
|
||||
|
||||
function getLowerValueFromHandle()
|
||||
{
|
||||
var result = (lowerHandle.y - (handleSize + minimumRangeHandleSize)) / (height - (2 * handleSize + minimumRangeHandleSize));
|
||||
result = maximumValue - minimumRange + result * (minimumValue - (maximumValue - minimumRange));
|
||||
result = roundValues ? Math.round(result) : result;
|
||||
return result;
|
||||
}
|
||||
|
||||
function setUpperValue(value)
|
||||
{
|
||||
var value = (value - maximumValue) / (minimumValue - maximumValue);
|
||||
var new_upper_y = Math.round(value * (height - (2 * handleSize + minimumRangeHandleSize)));
|
||||
|
||||
if(new_upper_y != upperHandle.y)
|
||||
{
|
||||
upperHandle.y = new_upper_y;
|
||||
}
|
||||
rangeHandle.height = lowerHandle.y - (upperHandle.y + upperHandle.height);
|
||||
}
|
||||
|
||||
function setLowerValue(value)
|
||||
{
|
||||
var value = (value - maximumValue) / (minimumValue - maximumValue);
|
||||
var new_lower_y = Math.round((handleSize + minimumRangeHandleSize) + value * (height - (2 * handleSize + minimumRangeHandleSize)));
|
||||
|
||||
if(new_lower_y != lowerHandle.y)
|
||||
{
|
||||
lowerHandle.y = new_lower_y;
|
||||
}
|
||||
rangeHandle.height = lowerHandle.y - (upperHandle.y + upperHandle.height);
|
||||
}
|
||||
|
||||
Connections
|
||||
{
|
||||
target: UM.LayerView
|
||||
onMinimumLayerChanged: slider.setLowerValue(UM.LayerView.minimumLayer)
|
||||
onCurrentLayerChanged: slider.setUpperValue(UM.LayerView.currentLayer)
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
width: parent.trackThickness
|
||||
height: parent.height - parent.handleSize
|
||||
radius: parent.trackRadius
|
||||
anchors.centerIn: parent
|
||||
color: parent.trackColor
|
||||
border.width: parent.trackBorderWidth;
|
||||
border.color: parent.trackBorderColor;
|
||||
}
|
||||
|
||||
Item {
|
||||
id: rangeHandle
|
||||
y: upperHandle.y + upperHandle.height
|
||||
width: parent.handleSize
|
||||
height: parent.minimumRangeHandleSize
|
||||
anchors.horizontalCenter: parent.horizontalCenter
|
||||
|
||||
visible: slider.layersVisible
|
||||
|
||||
property real value: UM.LayerView.currentLayer
|
||||
function setValue(value)
|
||||
{
|
||||
var range = upperHandle.value - lowerHandle.value;
|
||||
value = Math.min(value, slider.maximumValue);
|
||||
value = Math.max(value, slider.minimumValue + range);
|
||||
UM.LayerView.setCurrentLayer(value);
|
||||
UM.LayerView.setMinimumLayer(value - range);
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
anchors.centerIn: parent
|
||||
width: parent.parent.trackThickness - 2 * parent.parent.trackBorderWidth
|
||||
height: parent.height + parent.parent.handleSize
|
||||
color: parent.parent.rangeHandleColor
|
||||
}
|
||||
|
||||
MouseArea {
|
||||
anchors.fill: parent
|
||||
|
||||
drag.target: parent
|
||||
drag.axis: Drag.YAxis
|
||||
drag.minimumY: upperHandle.height
|
||||
drag.maximumY: parent.parent.height - (parent.height + lowerHandle.height)
|
||||
|
||||
onPressed: parent.parent.activeHandle = rangeHandle
|
||||
onPositionChanged:
|
||||
{
|
||||
upperHandle.y = parent.y - upperHandle.height
|
||||
lowerHandle.y = parent.y + parent.height
|
||||
|
||||
var upper_value = slider.getUpperValueFromHandle();
|
||||
var lower_value = upper_value - (upperHandle.value - lowerHandle.value);
|
||||
UM.LayerView.setCurrentLayer(upper_value);
|
||||
UM.LayerView.setMinimumLayer(lower_value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
id: upperHandle
|
||||
y: parent.height - (parent.minimumRangeHandleSize + 2 * parent.handleSize)
|
||||
width: parent.handleSize
|
||||
height: parent.handleSize
|
||||
anchors.horizontalCenter: parent.horizontalCenter
|
||||
radius: parent.handleRadius
|
||||
color: parent.upperHandleColor
|
||||
|
||||
visible: slider.layersVisible
|
||||
|
||||
property real value: UM.LayerView.currentLayer
|
||||
function setValue(value)
|
||||
{
|
||||
UM.LayerView.setCurrentLayer(value);
|
||||
}
|
||||
|
||||
MouseArea {
|
||||
anchors.fill: parent
|
||||
|
||||
drag.target: parent
|
||||
drag.axis: Drag.YAxis
|
||||
drag.minimumY: 0
|
||||
drag.maximumY: parent.parent.height - (2 * parent.parent.handleSize + parent.parent.minimumRangeHandleSize)
|
||||
|
||||
onPressed: parent.parent.activeHandle = upperHandle
|
||||
onPositionChanged:
|
||||
{
|
||||
if(lowerHandle.y - (upperHandle.y + upperHandle.height) < parent.parent.minimumRangeHandleSize)
|
||||
{
|
||||
lowerHandle.y = upperHandle.y + upperHandle.height + parent.parent.minimumRangeHandleSize;
|
||||
}
|
||||
rangeHandle.height = lowerHandle.y - (upperHandle.y + upperHandle.height);
|
||||
|
||||
UM.LayerView.setCurrentLayer(slider.getUpperValueFromHandle());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
id: lowerHandle
|
||||
y: parent.height - parent.handleSize
|
||||
width: parent.handleSize
|
||||
height: parent.handleSize
|
||||
anchors.horizontalCenter: parent.horizontalCenter
|
||||
radius: parent.handleRadius
|
||||
color: parent.lowerHandleColor
|
||||
|
||||
visible: slider.layersVisible
|
||||
|
||||
property real value: UM.LayerView.minimumLayer
|
||||
function setValue(value)
|
||||
{
|
||||
UM.LayerView.setMinimumLayer(value);
|
||||
}
|
||||
|
||||
MouseArea {
|
||||
anchors.fill: parent
|
||||
|
||||
drag.target: parent
|
||||
drag.axis: Drag.YAxis
|
||||
drag.minimumY: upperHandle.height + parent.parent.minimumRangeHandleSize
|
||||
drag.maximumY: parent.parent.height - parent.height
|
||||
|
||||
onPressed: parent.parent.activeHandle = lowerHandle
|
||||
onPositionChanged:
|
||||
{
|
||||
if(lowerHandle.y - (upperHandle.y + upperHandle.height) < parent.parent.minimumRangeHandleSize)
|
||||
{
|
||||
upperHandle.y = lowerHandle.y - (upperHandle.height + parent.parent.minimumRangeHandleSize);
|
||||
}
|
||||
rangeHandle.height = lowerHandle.y - (upperHandle.y + upperHandle.height)
|
||||
|
||||
UM.LayerView.setMinimumLayer(slider.getLowerValueFromHandle());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
UM.PointingRectangle
|
||||
{
|
||||
x: parent.width + UM.Theme.getSize("slider_layerview_background").width / 2;
|
||||
y: Math.floor(slider.activeHandle.y + slider.activeHandle.height / 2 - height / 2);
|
||||
|
||||
target: Qt.point(0, slider.activeHandle.y + slider.activeHandle.height / 2)
|
||||
arrowSize: UM.Theme.getSize("default_arrow").width
|
||||
|
||||
height: (Math.floor(UM.Theme.getSize("slider_handle").height + UM.Theme.getSize("default_margin").height) / 2) * 2 // Make sure height has an integer middle so drawing a pointy border is easier
|
||||
width: valueLabel.width + UM.Theme.getSize("default_margin").width
|
||||
Behavior on height { NumberAnimation { duration: 50; } }
|
||||
|
||||
color: UM.Theme.getColor("lining");
|
||||
|
||||
visible: slider.layersVisible
|
||||
|
||||
UM.PointingRectangle
|
||||
{
|
||||
color: UM.Theme.getColor("tool_panel_background")
|
||||
target: Qt.point(0, height / 2 + UM.Theme.getSize("default_lining").width)
|
||||
arrowSize: UM.Theme.getSize("default_arrow").width
|
||||
anchors.fill: parent
|
||||
anchors.margins: UM.Theme.getSize("default_lining").width
|
||||
|
||||
MouseArea //Catch all mouse events (so scene doesnt handle them)
|
||||
{
|
||||
anchors.fill: parent
|
||||
}
|
||||
}
|
||||
|
||||
TextField
|
||||
{
|
||||
id: valueLabel
|
||||
property string maxValue: slider.maximumValue + 1
|
||||
text: slider.activeHandle.value + 1
|
||||
horizontalAlignment: TextInput.AlignRight;
|
||||
onEditingFinished:
|
||||
{
|
||||
// Ensure that the cursor is at the first position. On some systems the text isn't fully visible
|
||||
// Seems to have to do something with different dpi densities that QML doesn't quite handle.
|
||||
// Another option would be to increase the size even further, but that gives pretty ugly results.
|
||||
cursorPosition = 0;
|
||||
if(valueLabel.text != '')
|
||||
{
|
||||
slider.activeHandle.setValue(valueLabel.text - 1);
|
||||
}
|
||||
}
|
||||
validator: IntValidator { bottom: 1; top: slider.maximumValue + 1; }
|
||||
|
||||
anchors.left: parent.left;
|
||||
anchors.leftMargin: UM.Theme.getSize("default_margin").width / 2;
|
||||
anchors.verticalCenter: parent.verticalCenter;
|
||||
|
||||
width: Math.max(UM.Theme.getSize("line").width * maxValue.length + 2, 20);
|
||||
style: TextFieldStyle
|
||||
{
|
||||
textColor: UM.Theme.getColor("setting_control_text");
|
||||
font: UM.Theme.getFont("default");
|
||||
background: Item { }
|
||||
}
|
||||
|
||||
Keys.onUpPressed: slider.activeHandle.setValue(slider.activeHandle.value + ((event.modifiers & Qt.ShiftModifier) ? 10 : 1))
|
||||
Keys.onDownPressed: slider.activeHandle.setValue(slider.activeHandle.value - ((event.modifiers & Qt.ShiftModifier) ? 10 : 1))
|
||||
}
|
||||
|
||||
BusyIndicator
|
||||
{
|
||||
id: busyIndicator;
|
||||
anchors.left: parent.right;
|
||||
anchors.leftMargin: UM.Theme.getSize("default_margin").width / 2;
|
||||
anchors.verticalCenter: parent.verticalCenter;
|
||||
|
||||
width: UM.Theme.getSize("slider_handle").height;
|
||||
height: width;
|
||||
|
||||
running: UM.LayerView.busy;
|
||||
visible: UM.LayerView.busy;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -16,9 +16,11 @@ class LayerViewProxy(QObject):
|
|||
currentLayerChanged = pyqtSignal()
|
||||
maxLayersChanged = pyqtSignal()
|
||||
activityChanged = pyqtSignal()
|
||||
globalStackChanged = pyqtSignal()
|
||||
preferencesChanged = pyqtSignal()
|
||||
|
||||
@pyqtProperty(bool, notify = activityChanged)
|
||||
def getLayerActivity(self):
|
||||
def layerActivity(self):
|
||||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
return active_view.getActivity()
|
||||
|
@ -28,14 +30,19 @@ class LayerViewProxy(QObject):
|
|||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
return active_view.getMaxLayers()
|
||||
#return 100
|
||||
|
||||
|
||||
@pyqtProperty(int, notify = currentLayerChanged)
|
||||
def currentLayer(self):
|
||||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
return active_view.getCurrentLayer()
|
||||
|
||||
@pyqtProperty(int, notify = currentLayerChanged)
|
||||
def minimumLayer(self):
|
||||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
return active_view.getMinimumLayer()
|
||||
|
||||
busyChanged = pyqtSignal()
|
||||
@pyqtProperty(bool, notify = busyChanged)
|
||||
def busy(self):
|
||||
|
@ -44,29 +51,102 @@ class LayerViewProxy(QObject):
|
|||
return active_view.isBusy()
|
||||
|
||||
return False
|
||||
|
||||
|
||||
@pyqtProperty(bool, notify = preferencesChanged)
|
||||
def compatibilityMode(self):
|
||||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
return active_view.getCompatibilityMode()
|
||||
|
||||
return False
|
||||
|
||||
@pyqtSlot(int)
|
||||
def setCurrentLayer(self, layer_num):
|
||||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
active_view.setLayer(layer_num)
|
||||
|
||||
@pyqtSlot(int)
|
||||
def setMinimumLayer(self, layer_num):
|
||||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
active_view.setMinimumLayer(layer_num)
|
||||
|
||||
@pyqtSlot(int)
|
||||
def setLayerViewType(self, layer_view_type):
|
||||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
active_view.setLayerViewType(layer_view_type)
|
||||
|
||||
@pyqtSlot(result = int)
|
||||
def getLayerViewType(self):
|
||||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
return active_view.getLayerViewType()
|
||||
return 0
|
||||
|
||||
# Opacity 0..1
|
||||
@pyqtSlot(int, float)
|
||||
def setExtruderOpacity(self, extruder_nr, opacity):
|
||||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
active_view.setExtruderOpacity(extruder_nr, opacity)
|
||||
|
||||
@pyqtSlot(int)
|
||||
def setShowTravelMoves(self, show):
|
||||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
active_view.setShowTravelMoves(show)
|
||||
|
||||
@pyqtSlot(int)
|
||||
def setShowHelpers(self, show):
|
||||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
active_view.setShowHelpers(show)
|
||||
|
||||
@pyqtSlot(int)
|
||||
def setShowSkin(self, show):
|
||||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
active_view.setShowSkin(show)
|
||||
|
||||
@pyqtSlot(int)
|
||||
def setShowInfill(self, show):
|
||||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
active_view.setShowInfill(show)
|
||||
|
||||
@pyqtProperty(int, notify = globalStackChanged)
|
||||
def extruderCount(self):
|
||||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
return active_view.getExtruderCount()
|
||||
return 0
|
||||
|
||||
def _layerActivityChanged(self):
|
||||
self.activityChanged.emit()
|
||||
|
||||
def _onLayerChanged(self):
|
||||
self.currentLayerChanged.emit()
|
||||
self._layerActivityChanged()
|
||||
|
||||
|
||||
def _onMaxLayersChanged(self):
|
||||
self.maxLayersChanged.emit()
|
||||
|
||||
def _onBusyChanged(self):
|
||||
self.busyChanged.emit()
|
||||
|
||||
|
||||
def _onGlobalStackChanged(self):
|
||||
self.globalStackChanged.emit()
|
||||
|
||||
def _onPreferencesChanged(self):
|
||||
self.preferencesChanged.emit()
|
||||
|
||||
def _onActiveViewChanged(self):
|
||||
active_view = self._controller.getActiveView()
|
||||
if type(active_view) == LayerView.LayerView.LayerView:
|
||||
active_view.currentLayerNumChanged.connect(self._onLayerChanged)
|
||||
active_view.maxLayersChanged.connect(self._onMaxLayersChanged)
|
||||
active_view.busyChanged.connect(self._onBusyChanged)
|
||||
active_view.globalStackChanged.connect(self._onGlobalStackChanged)
|
||||
active_view.preferencesChanged.connect(self._onPreferencesChanged)
|
||||
|
|
127
plugins/LayerView/layers.shader
Normal file → Executable file
127
plugins/LayerView/layers.shader
Normal file → Executable file
|
@ -3,29 +3,147 @@ vertex =
|
|||
uniform highp mat4 u_modelViewProjectionMatrix;
|
||||
uniform lowp float u_active_extruder;
|
||||
uniform lowp float u_shade_factor;
|
||||
uniform highp int u_layer_view_type;
|
||||
|
||||
attribute highp float a_extruder;
|
||||
attribute highp float a_line_type;
|
||||
attribute highp vec4 a_vertex;
|
||||
attribute lowp vec4 a_color;
|
||||
attribute lowp vec4 a_material_color;
|
||||
|
||||
varying lowp vec4 v_color;
|
||||
varying float v_line_type;
|
||||
|
||||
void main()
|
||||
{
|
||||
gl_Position = u_modelViewProjectionMatrix * a_vertex;
|
||||
// shade the color depending on the extruder index stored in the alpha component of the color
|
||||
v_color = (a_color.a == u_active_extruder) ? a_color : a_color * u_shade_factor;
|
||||
v_color.a = 1.0;
|
||||
// shade the color depending on the extruder index
|
||||
v_color = a_color;
|
||||
// 8 and 9 are travel moves
|
||||
if ((a_line_type != 8.0) && (a_line_type != 9.0)) {
|
||||
v_color = (a_extruder == u_active_extruder) ? v_color : vec4(u_shade_factor * v_color.rgb, v_color.a);
|
||||
}
|
||||
|
||||
v_line_type = a_line_type;
|
||||
}
|
||||
|
||||
fragment =
|
||||
varying lowp vec4 v_color;
|
||||
varying float v_line_type;
|
||||
|
||||
uniform int u_show_travel_moves;
|
||||
uniform int u_show_helpers;
|
||||
uniform int u_show_skin;
|
||||
uniform int u_show_infill;
|
||||
|
||||
void main()
|
||||
{
|
||||
if ((u_show_travel_moves == 0) && (v_line_type >= 7.5) && (v_line_type <= 9.5)) { // actually, 8 and 9
|
||||
// discard movements
|
||||
discard;
|
||||
}
|
||||
// support: 4, 5, 7, 10
|
||||
if ((u_show_helpers == 0) && (
|
||||
((v_line_type >= 3.5) && (v_line_type <= 4.5)) ||
|
||||
((v_line_type >= 6.5) && (v_line_type <= 7.5)) ||
|
||||
((v_line_type >= 9.5) && (v_line_type <= 10.5)) ||
|
||||
((v_line_type >= 4.5) && (v_line_type <= 5.5))
|
||||
)) {
|
||||
discard;
|
||||
}
|
||||
// skin: 1, 2, 3
|
||||
if ((u_show_skin == 0) && (
|
||||
(v_line_type >= 0.5) && (v_line_type <= 3.5)
|
||||
)) {
|
||||
discard;
|
||||
}
|
||||
// infill:
|
||||
if ((u_show_infill == 0) && (v_line_type >= 5.5) && (v_line_type <= 6.5)) {
|
||||
// discard movements
|
||||
discard;
|
||||
}
|
||||
|
||||
gl_FragColor = v_color;
|
||||
}
|
||||
|
||||
vertex41core =
|
||||
#version 410
|
||||
uniform highp mat4 u_modelViewProjectionMatrix;
|
||||
uniform lowp float u_active_extruder;
|
||||
uniform lowp float u_shade_factor;
|
||||
uniform highp int u_layer_view_type;
|
||||
|
||||
in highp float a_extruder;
|
||||
in highp float a_line_type;
|
||||
in highp vec4 a_vertex;
|
||||
in lowp vec4 a_color;
|
||||
in lowp vec4 a_material_color;
|
||||
|
||||
out lowp vec4 v_color;
|
||||
out float v_line_type;
|
||||
|
||||
void main()
|
||||
{
|
||||
gl_Position = u_modelViewProjectionMatrix * a_vertex;
|
||||
v_color = a_color;
|
||||
if ((a_line_type != 8) && (a_line_type != 9)) {
|
||||
v_color = (a_extruder == u_active_extruder) ? v_color : vec4(u_shade_factor * v_color.rgb, v_color.a);
|
||||
}
|
||||
|
||||
v_line_type = a_line_type;
|
||||
}
|
||||
|
||||
fragment41core =
|
||||
#version 410
|
||||
in lowp vec4 v_color;
|
||||
in float v_line_type;
|
||||
out vec4 frag_color;
|
||||
|
||||
uniform int u_show_travel_moves;
|
||||
uniform int u_show_helpers;
|
||||
uniform int u_show_skin;
|
||||
uniform int u_show_infill;
|
||||
|
||||
void main()
|
||||
{
|
||||
if ((u_show_travel_moves == 0) && (v_line_type >= 7.5) && (v_line_type <= 9.5)) { // actually, 8 and 9
|
||||
// discard movements
|
||||
discard;
|
||||
}
|
||||
// helpers: 4, 5, 7, 10
|
||||
if ((u_show_helpers == 0) && (
|
||||
((v_line_type >= 3.5) && (v_line_type <= 4.5)) ||
|
||||
((v_line_type >= 6.5) && (v_line_type <= 7.5)) ||
|
||||
((v_line_type >= 9.5) && (v_line_type <= 10.5)) ||
|
||||
((v_line_type >= 4.5) && (v_line_type <= 5.5))
|
||||
)) {
|
||||
discard;
|
||||
}
|
||||
// skin: 1, 2, 3
|
||||
if ((u_show_skin == 0) && (
|
||||
(v_line_type >= 0.5) && (v_line_type <= 3.5)
|
||||
)) {
|
||||
discard;
|
||||
}
|
||||
// infill:
|
||||
if ((u_show_infill == 0) && (v_line_type >= 5.5) && (v_line_type <= 6.5)) {
|
||||
// discard movements
|
||||
discard;
|
||||
}
|
||||
|
||||
frag_color = v_color;
|
||||
}
|
||||
|
||||
[defaults]
|
||||
u_active_extruder = 0.0
|
||||
u_shade_factor = 0.60
|
||||
u_layer_view_type = 0
|
||||
u_extruder_opacity = [1.0, 1.0, 1.0, 1.0]
|
||||
|
||||
u_show_travel_moves = 0
|
||||
u_show_helpers = 1
|
||||
u_show_skin = 1
|
||||
u_show_infill = 1
|
||||
|
||||
[bindings]
|
||||
u_modelViewProjectionMatrix = model_view_projection_matrix
|
||||
|
@ -33,3 +151,6 @@ u_modelViewProjectionMatrix = model_view_projection_matrix
|
|||
[attributes]
|
||||
a_vertex = vertex
|
||||
a_color = color
|
||||
a_extruder = extruder
|
||||
a_line_type = line_type
|
||||
a_material_color = material_color
|
||||
|
|
264
plugins/LayerView/layers3d.shader
Executable file
264
plugins/LayerView/layers3d.shader
Executable file
|
@ -0,0 +1,264 @@
|
|||
[shaders]
|
||||
vertex41core =
|
||||
#version 410
|
||||
uniform highp mat4 u_modelViewProjectionMatrix;
|
||||
|
||||
uniform highp mat4 u_modelMatrix;
|
||||
uniform highp mat4 u_viewProjectionMatrix;
|
||||
uniform lowp float u_active_extruder;
|
||||
uniform lowp int u_layer_view_type;
|
||||
uniform lowp vec4 u_extruder_opacity; // currently only for max 4 extruders, others always visible
|
||||
|
||||
uniform highp mat4 u_normalMatrix;
|
||||
|
||||
in highp vec4 a_vertex;
|
||||
in lowp vec4 a_color;
|
||||
in lowp vec4 a_material_color;
|
||||
in highp vec4 a_normal;
|
||||
in highp vec2 a_line_dim; // line width and thickness
|
||||
in highp float a_extruder;
|
||||
in highp float a_line_type;
|
||||
|
||||
out lowp vec4 v_color;
|
||||
|
||||
out highp vec3 v_vertex;
|
||||
out highp vec3 v_normal;
|
||||
out lowp vec2 v_line_dim;
|
||||
out highp int v_extruder;
|
||||
out highp vec4 v_extruder_opacity;
|
||||
out float v_line_type;
|
||||
|
||||
out lowp vec4 f_color;
|
||||
out highp vec3 f_vertex;
|
||||
out highp vec3 f_normal;
|
||||
|
||||
void main()
|
||||
{
|
||||
vec4 v1_vertex = a_vertex;
|
||||
v1_vertex.y -= a_line_dim.y / 2; // half layer down
|
||||
|
||||
vec4 world_space_vert = u_modelMatrix * v1_vertex;
|
||||
gl_Position = world_space_vert;
|
||||
// shade the color depending on the extruder index stored in the alpha component of the color
|
||||
|
||||
switch (u_layer_view_type) {
|
||||
case 0: // "Material color"
|
||||
v_color = a_material_color;
|
||||
break;
|
||||
case 1: // "Line type"
|
||||
v_color = a_color;
|
||||
break;
|
||||
}
|
||||
|
||||
v_vertex = world_space_vert.xyz;
|
||||
v_normal = (u_normalMatrix * normalize(a_normal)).xyz;
|
||||
v_line_dim = a_line_dim;
|
||||
v_extruder = int(a_extruder);
|
||||
v_line_type = a_line_type;
|
||||
v_extruder_opacity = u_extruder_opacity;
|
||||
|
||||
// for testing without geometry shader
|
||||
f_color = v_color;
|
||||
f_vertex = v_vertex;
|
||||
f_normal = v_normal;
|
||||
}
|
||||
|
||||
geometry41core =
|
||||
#version 410
|
||||
|
||||
uniform highp mat4 u_viewProjectionMatrix;
|
||||
uniform int u_show_travel_moves;
|
||||
uniform int u_show_helpers;
|
||||
uniform int u_show_skin;
|
||||
uniform int u_show_infill;
|
||||
|
||||
layout(lines) in;
|
||||
layout(triangle_strip, max_vertices = 26) out;
|
||||
|
||||
in vec4 v_color[];
|
||||
in vec3 v_vertex[];
|
||||
in vec3 v_normal[];
|
||||
in vec2 v_line_dim[];
|
||||
in int v_extruder[];
|
||||
in vec4 v_extruder_opacity[];
|
||||
in float v_line_type[];
|
||||
|
||||
out vec4 f_color;
|
||||
out vec3 f_normal;
|
||||
out vec3 f_vertex;
|
||||
|
||||
// Set the set of variables and EmitVertex
|
||||
void myEmitVertex(vec3 vertex, vec4 color, vec3 normal, vec4 pos) {
|
||||
f_vertex = vertex;
|
||||
f_color = color;
|
||||
f_normal = normal;
|
||||
gl_Position = pos;
|
||||
EmitVertex();
|
||||
}
|
||||
|
||||
void main()
|
||||
{
|
||||
vec4 g_vertex_delta;
|
||||
vec3 g_vertex_normal_horz; // horizontal and vertical in respect to layers
|
||||
vec4 g_vertex_offset_horz; // vec4 to match gl_in[x].gl_Position
|
||||
vec3 g_vertex_normal_vert;
|
||||
vec4 g_vertex_offset_vert;
|
||||
vec3 g_vertex_normal_horz_head;
|
||||
vec4 g_vertex_offset_horz_head;
|
||||
|
||||
float size_x;
|
||||
float size_y;
|
||||
|
||||
if ((v_extruder_opacity[0][v_extruder[0]] == 0.0) && (v_line_type[0] != 8) && (v_line_type[0] != 9)) {
|
||||
return;
|
||||
}
|
||||
// See LayerPolygon; 8 is MoveCombingType, 9 is RetractionType
|
||||
if ((u_show_travel_moves == 0) && ((v_line_type[0] == 8) || (v_line_type[0] == 9))) {
|
||||
return;
|
||||
}
|
||||
if ((u_show_helpers == 0) && ((v_line_type[0] == 4) || (v_line_type[0] == 5) || (v_line_type[0] == 7) || (v_line_type[0] == 10))) {
|
||||
return;
|
||||
}
|
||||
if ((u_show_skin == 0) && ((v_line_type[0] == 1) || (v_line_type[0] == 2) || (v_line_type[0] == 3))) {
|
||||
return;
|
||||
}
|
||||
if ((u_show_infill == 0) && (v_line_type[0] == 6)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ((v_line_type[0] == 8) || (v_line_type[0] == 9)) {
|
||||
// fixed size for movements
|
||||
size_x = 0.05;
|
||||
} else {
|
||||
size_x = v_line_dim[0].x / 2 + 0.01; // radius, and make it nicely overlapping
|
||||
}
|
||||
size_y = v_line_dim[0].y / 2 + 0.01;
|
||||
|
||||
g_vertex_delta = gl_in[1].gl_Position - gl_in[0].gl_Position;
|
||||
g_vertex_normal_horz_head = normalize(vec3(-g_vertex_delta.x, -g_vertex_delta.y, -g_vertex_delta.z));
|
||||
g_vertex_offset_horz_head = vec4(g_vertex_normal_horz_head * size_x, 0.0);
|
||||
|
||||
g_vertex_normal_horz = normalize(vec3(g_vertex_delta.z, g_vertex_delta.y, -g_vertex_delta.x));
|
||||
|
||||
g_vertex_offset_horz = vec4(g_vertex_normal_horz * size_x, 0.0); //size * g_vertex_normal_horz;
|
||||
g_vertex_normal_vert = vec3(0.0, 1.0, 0.0);
|
||||
g_vertex_offset_vert = vec4(g_vertex_normal_vert * size_y, 0.0);
|
||||
|
||||
if ((v_line_type[0] == 8) || (v_line_type[0] == 9)) {
|
||||
// Travels: flat plane with pointy ends
|
||||
myEmitVertex(v_vertex[0], v_color[0], g_vertex_normal_vert, u_viewProjectionMatrix * (gl_in[0].gl_Position + g_vertex_offset_horz + g_vertex_offset_vert));
|
||||
myEmitVertex(v_vertex[0], v_color[0], g_vertex_normal_vert, u_viewProjectionMatrix * (gl_in[0].gl_Position + g_vertex_offset_horz_head + g_vertex_offset_vert));
|
||||
myEmitVertex(v_vertex[0], v_color[0], g_vertex_normal_vert, u_viewProjectionMatrix * (gl_in[0].gl_Position - g_vertex_offset_horz + g_vertex_offset_vert));
|
||||
myEmitVertex(v_vertex[0], v_color[0], g_vertex_normal_vert, u_viewProjectionMatrix * (gl_in[0].gl_Position + g_vertex_offset_horz + g_vertex_offset_vert));
|
||||
myEmitVertex(v_vertex[1], v_color[1], g_vertex_normal_vert, u_viewProjectionMatrix * (gl_in[1].gl_Position - g_vertex_offset_horz + g_vertex_offset_vert));
|
||||
myEmitVertex(v_vertex[1], v_color[1], g_vertex_normal_vert, u_viewProjectionMatrix * (gl_in[1].gl_Position + g_vertex_offset_horz + g_vertex_offset_vert));
|
||||
myEmitVertex(v_vertex[1], v_color[1], g_vertex_normal_vert, u_viewProjectionMatrix * (gl_in[1].gl_Position - g_vertex_offset_horz_head + g_vertex_offset_vert));
|
||||
|
||||
EndPrimitive();
|
||||
} else {
|
||||
// All normal lines are rendered as 3d tubes.
|
||||
myEmitVertex(v_vertex[0], v_color[0], g_vertex_normal_horz, u_viewProjectionMatrix * (gl_in[0].gl_Position + g_vertex_offset_horz));
|
||||
myEmitVertex(v_vertex[1], v_color[1], g_vertex_normal_horz, u_viewProjectionMatrix * (gl_in[1].gl_Position + g_vertex_offset_horz));
|
||||
myEmitVertex(v_vertex[0], v_color[0], g_vertex_normal_vert, u_viewProjectionMatrix * (gl_in[0].gl_Position + g_vertex_offset_vert));
|
||||
myEmitVertex(v_vertex[1], v_color[1], g_vertex_normal_vert, u_viewProjectionMatrix * (gl_in[1].gl_Position + g_vertex_offset_vert));
|
||||
myEmitVertex(v_vertex[0], v_color[0], -g_vertex_normal_horz, u_viewProjectionMatrix * (gl_in[0].gl_Position - g_vertex_offset_horz));
|
||||
myEmitVertex(v_vertex[1], v_color[1], -g_vertex_normal_horz, u_viewProjectionMatrix * (gl_in[1].gl_Position - g_vertex_offset_horz));
|
||||
myEmitVertex(v_vertex[0], v_color[0], -g_vertex_normal_vert, u_viewProjectionMatrix * (gl_in[0].gl_Position - g_vertex_offset_vert));
|
||||
myEmitVertex(v_vertex[1], v_color[1], -g_vertex_normal_vert, u_viewProjectionMatrix * (gl_in[1].gl_Position - g_vertex_offset_vert));
|
||||
myEmitVertex(v_vertex[0], v_color[0], g_vertex_normal_horz, u_viewProjectionMatrix * (gl_in[0].gl_Position + g_vertex_offset_horz));
|
||||
myEmitVertex(v_vertex[1], v_color[1], g_vertex_normal_horz, u_viewProjectionMatrix * (gl_in[1].gl_Position + g_vertex_offset_horz));
|
||||
|
||||
EndPrimitive();
|
||||
|
||||
// left side
|
||||
myEmitVertex(v_vertex[0], v_color[0], g_vertex_normal_horz, u_viewProjectionMatrix * (gl_in[0].gl_Position + g_vertex_offset_horz));
|
||||
myEmitVertex(v_vertex[0], v_color[0], g_vertex_normal_vert, u_viewProjectionMatrix * (gl_in[0].gl_Position + g_vertex_offset_vert));
|
||||
myEmitVertex(v_vertex[0], v_color[0], g_vertex_normal_horz_head, u_viewProjectionMatrix * (gl_in[0].gl_Position + g_vertex_offset_horz_head));
|
||||
myEmitVertex(v_vertex[0], v_color[0], -g_vertex_normal_horz, u_viewProjectionMatrix * (gl_in[0].gl_Position - g_vertex_offset_horz));
|
||||
|
||||
EndPrimitive();
|
||||
|
||||
myEmitVertex(v_vertex[0], v_color[0], -g_vertex_normal_horz, u_viewProjectionMatrix * (gl_in[0].gl_Position - g_vertex_offset_horz));
|
||||
myEmitVertex(v_vertex[0], v_color[0], -g_vertex_normal_vert, u_viewProjectionMatrix * (gl_in[0].gl_Position - g_vertex_offset_vert));
|
||||
myEmitVertex(v_vertex[0], v_color[0], g_vertex_normal_horz_head, u_viewProjectionMatrix * (gl_in[0].gl_Position + g_vertex_offset_horz_head));
|
||||
myEmitVertex(v_vertex[0], v_color[0], g_vertex_normal_horz, u_viewProjectionMatrix * (gl_in[0].gl_Position + g_vertex_offset_horz));
|
||||
|
||||
EndPrimitive();
|
||||
|
||||
// right side
|
||||
myEmitVertex(v_vertex[1], v_color[1], g_vertex_normal_horz, u_viewProjectionMatrix * (gl_in[1].gl_Position + g_vertex_offset_horz));
|
||||
myEmitVertex(v_vertex[1], v_color[1], g_vertex_normal_vert, u_viewProjectionMatrix * (gl_in[1].gl_Position + g_vertex_offset_vert));
|
||||
myEmitVertex(v_vertex[1], v_color[1], -g_vertex_normal_horz_head, u_viewProjectionMatrix * (gl_in[1].gl_Position - g_vertex_offset_horz_head));
|
||||
myEmitVertex(v_vertex[1], v_color[1], -g_vertex_normal_horz, u_viewProjectionMatrix * (gl_in[1].gl_Position - g_vertex_offset_horz));
|
||||
|
||||
EndPrimitive();
|
||||
|
||||
myEmitVertex(v_vertex[1], v_color[1], -g_vertex_normal_horz, u_viewProjectionMatrix * (gl_in[1].gl_Position - g_vertex_offset_horz));
|
||||
myEmitVertex(v_vertex[1], v_color[1], -g_vertex_normal_vert, u_viewProjectionMatrix * (gl_in[1].gl_Position - g_vertex_offset_vert));
|
||||
myEmitVertex(v_vertex[1], v_color[1], -g_vertex_normal_horz_head, u_viewProjectionMatrix * (gl_in[1].gl_Position - g_vertex_offset_horz_head));
|
||||
myEmitVertex(v_vertex[1], v_color[1], g_vertex_normal_horz, u_viewProjectionMatrix * (gl_in[1].gl_Position + g_vertex_offset_horz));
|
||||
|
||||
EndPrimitive();
|
||||
}
|
||||
}
|
||||
|
||||
fragment41core =
|
||||
#version 410
|
||||
in lowp vec4 f_color;
|
||||
in lowp vec3 f_normal;
|
||||
in lowp vec3 f_vertex;
|
||||
|
||||
out vec4 frag_color;
|
||||
|
||||
uniform mediump vec4 u_ambientColor;
|
||||
uniform highp vec3 u_lightPosition;
|
||||
|
||||
void main()
|
||||
{
|
||||
mediump vec4 finalColor = vec4(0.0);
|
||||
float alpha = f_color.a;
|
||||
|
||||
finalColor.rgb += f_color.rgb * 0.3;
|
||||
|
||||
highp vec3 normal = normalize(f_normal);
|
||||
highp vec3 light_dir = normalize(u_lightPosition - f_vertex);
|
||||
|
||||
// Diffuse Component
|
||||
highp float NdotL = clamp(dot(normal, light_dir), 0.0, 1.0);
|
||||
finalColor += (NdotL * f_color);
|
||||
finalColor.a = alpha; // Do not change alpha in any way
|
||||
|
||||
frag_color = finalColor;
|
||||
}
|
||||
|
||||
|
||||
[defaults]
|
||||
u_active_extruder = 0.0
|
||||
u_layer_view_type = 0
|
||||
u_extruder_opacity = [1.0, 1.0, 1.0, 1.0]
|
||||
|
||||
u_specularColor = [0.4, 0.4, 0.4, 1.0]
|
||||
u_ambientColor = [0.3, 0.3, 0.3, 0.0]
|
||||
u_diffuseColor = [1.0, 0.79, 0.14, 1.0]
|
||||
u_shininess = 20.0
|
||||
|
||||
u_show_travel_moves = 0
|
||||
u_show_helpers = 1
|
||||
u_show_skin = 1
|
||||
u_show_infill = 1
|
||||
|
||||
[bindings]
|
||||
u_modelViewProjectionMatrix = model_view_projection_matrix
|
||||
u_modelMatrix = model_matrix
|
||||
u_viewProjectionMatrix = view_projection_matrix
|
||||
u_normalMatrix = normal_matrix
|
||||
u_lightPosition = light_0_position
|
||||
|
||||
[attributes]
|
||||
a_vertex = vertex
|
||||
a_color = color
|
||||
a_normal = normal
|
||||
a_line_dim = line_dim
|
||||
a_extruder = extruder
|
||||
a_material_color = material_color
|
||||
a_line_type = line_type
|
|
@ -33,6 +33,7 @@ fragment =
|
|||
|
||||
void main()
|
||||
{
|
||||
// blur kernel
|
||||
kernel[0] = 0.0; kernel[1] = 1.0; kernel[2] = 0.0;
|
||||
kernel[3] = 1.0; kernel[4] = -4.0; kernel[5] = 1.0;
|
||||
kernel[6] = 0.0; kernel[7] = 1.0; kernel[8] = 0.0;
|
||||
|
@ -63,6 +64,75 @@ fragment =
|
|||
}
|
||||
}
|
||||
|
||||
vertex41core =
|
||||
#version 410
|
||||
uniform highp mat4 u_modelViewProjectionMatrix;
|
||||
in highp vec4 a_vertex;
|
||||
in highp vec2 a_uvs;
|
||||
|
||||
out highp vec2 v_uvs;
|
||||
|
||||
void main()
|
||||
{
|
||||
gl_Position = u_modelViewProjectionMatrix * a_vertex;
|
||||
v_uvs = a_uvs;
|
||||
}
|
||||
|
||||
fragment41core =
|
||||
#version 410
|
||||
uniform sampler2D u_layer0;
|
||||
uniform sampler2D u_layer1;
|
||||
uniform sampler2D u_layer2;
|
||||
|
||||
uniform vec2 u_offset[9];
|
||||
|
||||
uniform vec4 u_background_color;
|
||||
uniform float u_outline_strength;
|
||||
uniform vec4 u_outline_color;
|
||||
|
||||
in vec2 v_uvs;
|
||||
|
||||
float kernel[9];
|
||||
|
||||
const vec3 x_axis = vec3(1.0, 0.0, 0.0);
|
||||
const vec3 y_axis = vec3(0.0, 1.0, 0.0);
|
||||
const vec3 z_axis = vec3(0.0, 0.0, 1.0);
|
||||
|
||||
out vec4 frag_color;
|
||||
|
||||
void main()
|
||||
{
|
||||
// blur kernel
|
||||
kernel[0] = 0.0; kernel[1] = 1.0; kernel[2] = 0.0;
|
||||
kernel[3] = 1.0; kernel[4] = -4.0; kernel[5] = 1.0;
|
||||
kernel[6] = 0.0; kernel[7] = 1.0; kernel[8] = 0.0;
|
||||
|
||||
vec4 result = u_background_color;
|
||||
|
||||
vec4 main_layer = texture(u_layer0, v_uvs);
|
||||
vec4 selection_layer = texture(u_layer1, v_uvs);
|
||||
vec4 layerview_layer = texture(u_layer2, v_uvs);
|
||||
|
||||
result = main_layer * main_layer.a + result * (1.0 - main_layer.a);
|
||||
result = layerview_layer * layerview_layer.a + result * (1.0 - layerview_layer.a);
|
||||
|
||||
vec4 sum = vec4(0.0);
|
||||
for (int i = 0; i < 9; i++)
|
||||
{
|
||||
vec4 color = vec4(texture(u_layer1, v_uvs.xy + u_offset[i]).a);
|
||||
sum += color * (kernel[i] / u_outline_strength);
|
||||
}
|
||||
|
||||
if((selection_layer.rgb == x_axis || selection_layer.rgb == y_axis || selection_layer.rgb == z_axis))
|
||||
{
|
||||
frag_color = result;
|
||||
}
|
||||
else
|
||||
{
|
||||
frag_color = mix(result, u_outline_color, abs(sum.a));
|
||||
}
|
||||
}
|
||||
|
||||
[defaults]
|
||||
u_layer0 = 0
|
||||
u_layer1 = 1
|
||||
|
|
|
@ -6,11 +6,13 @@ from UM.FlameProfiler import pyqtSlot
|
|||
|
||||
from cura.MachineAction import MachineAction
|
||||
|
||||
import UM.Application
|
||||
import UM.Settings.InstanceContainer
|
||||
import UM.Settings.DefinitionContainer
|
||||
import UM.Settings.ContainerRegistry
|
||||
import UM.Logger
|
||||
from UM.Application import Application
|
||||
from UM.Settings.InstanceContainer import InstanceContainer
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
from UM.Settings.DefinitionContainer import DefinitionContainer
|
||||
from UM.Logger import Logger
|
||||
|
||||
from cura.Settings.CuraContainerRegistry import CuraContainerRegistry
|
||||
|
||||
import UM.i18n
|
||||
catalog = UM.i18n.i18nCatalog("cura")
|
||||
|
@ -25,11 +27,11 @@ class MachineSettingsAction(MachineAction):
|
|||
|
||||
self._container_index = 0
|
||||
|
||||
self._container_registry = UM.Settings.ContainerRegistry.getInstance()
|
||||
self._container_registry = ContainerRegistry.getInstance()
|
||||
self._container_registry.containerAdded.connect(self._onContainerAdded)
|
||||
|
||||
def _reset(self):
|
||||
global_container_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if not global_container_stack:
|
||||
return
|
||||
|
||||
|
@ -45,7 +47,7 @@ class MachineSettingsAction(MachineAction):
|
|||
self.containerIndexChanged.emit()
|
||||
|
||||
def _createDefinitionChangesContainer(self, global_container_stack, container_index = None):
|
||||
definition_changes_container = UM.Settings.InstanceContainer(global_container_stack.getName() + "_settings")
|
||||
definition_changes_container = InstanceContainer(global_container_stack.getName() + "_settings")
|
||||
definition = global_container_stack.getBottom()
|
||||
definition_changes_container.setDefinition(definition)
|
||||
definition_changes_container.addMetaDataEntry("type", "definition_changes")
|
||||
|
@ -64,24 +66,24 @@ class MachineSettingsAction(MachineAction):
|
|||
|
||||
def _onContainerAdded(self, container):
|
||||
# Add this action as a supported action to all machine definitions
|
||||
if isinstance(container, UM.Settings.DefinitionContainer) and container.getMetaDataEntry("type") == "machine":
|
||||
if isinstance(container, DefinitionContainer) and container.getMetaDataEntry("type") == "machine":
|
||||
if container.getProperty("machine_extruder_count", "value") > 1:
|
||||
# Multiextruder printers are not currently supported
|
||||
UM.Logger.log("d", "Not attaching MachineSettingsAction to %s; Multi-extrusion printers are not supported", container.getId())
|
||||
Logger.log("d", "Not attaching MachineSettingsAction to %s; Multi-extrusion printers are not supported", container.getId())
|
||||
return
|
||||
|
||||
UM.Application.getInstance().getMachineActionManager().addSupportedAction(container.getId(), self.getKey())
|
||||
Application.getInstance().getMachineActionManager().addSupportedAction(container.getId(), self.getKey())
|
||||
|
||||
@pyqtSlot()
|
||||
def forceUpdate(self):
|
||||
# Force rebuilding the build volume by reloading the global container stack.
|
||||
# This is a bit of a hack, but it seems quick enough.
|
||||
UM.Application.getInstance().globalContainerStackChanged.emit()
|
||||
Application.getInstance().globalContainerStackChanged.emit()
|
||||
|
||||
@pyqtSlot()
|
||||
def updateHasMaterialsMetadata(self):
|
||||
# Updates the has_materials metadata flag after switching gcode flavor
|
||||
global_container_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if global_container_stack:
|
||||
definition = global_container_stack.getBottom()
|
||||
if definition.getProperty("machine_gcode_flavor", "value") == "UltiGCode" and not definition.getMetaDataEntry("has_materials", False):
|
||||
|
@ -111,4 +113,4 @@ class MachineSettingsAction(MachineAction):
|
|||
empty_material = self._container_registry.findInstanceContainers(id = "empty_material")[0]
|
||||
global_container_stack.replaceContainer(material_index, empty_material)
|
||||
|
||||
UM.Application.getInstance().globalContainerStackChanged.emit()
|
||||
Application.getInstance().globalContainerStackChanged.emit()
|
||||
|
|
|
@ -4,16 +4,17 @@
|
|||
from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal
|
||||
|
||||
from UM.Application import Application
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
from UM.Settings.SettingInstance import SettingInstance
|
||||
from UM.Logger import Logger
|
||||
import UM.Settings.Models
|
||||
import UM.Settings.Models.SettingVisibilityHandler
|
||||
|
||||
from cura.Settings.ExtruderManager import ExtruderManager #To get global-inherits-stack setting values from different extruders.
|
||||
from cura.Settings.SettingOverrideDecorator import SettingOverrideDecorator
|
||||
|
||||
## The per object setting visibility handler ensures that only setting
|
||||
# definitions that have a matching instance Container are returned as visible.
|
||||
class PerObjectSettingVisibilityHandler(UM.Settings.Models.SettingVisibilityHandler):
|
||||
class PerObjectSettingVisibilityHandler(UM.Settings.Models.SettingVisibilityHandler.SettingVisibilityHandler):
|
||||
def __init__(self, parent = None, *args, **kwargs):
|
||||
super().__init__(parent = parent, *args, **kwargs)
|
||||
|
||||
|
@ -72,7 +73,7 @@ class PerObjectSettingVisibilityHandler(UM.Settings.Models.SettingVisibilityHand
|
|||
|
||||
# Use the found stack number to get the right stack to copy the value from.
|
||||
if stack_nr in ExtruderManager.getInstance().extruderIds:
|
||||
stack = UM.Settings.ContainerRegistry.getInstance().findContainerStacks(id = ExtruderManager.getInstance().extruderIds[stack_nr])[0]
|
||||
stack = ContainerRegistry.getInstance().findContainerStacks(id = ExtruderManager.getInstance().extruderIds[stack_nr])[0]
|
||||
|
||||
# Use the raw property to set the value (so the inheritance doesn't break)
|
||||
if stack is not None:
|
||||
|
|
|
@ -209,6 +209,8 @@ Item {
|
|||
{
|
||||
case "int":
|
||||
return settingTextField
|
||||
case "[int]":
|
||||
return settingTextField
|
||||
case "float":
|
||||
return settingTextField
|
||||
case "enum":
|
||||
|
|
|
@ -37,7 +37,8 @@ class RemovableDriveOutputDevice(OutputDevice):
|
|||
# meshes.
|
||||
# \param limit_mimetypes Should we limit the available MIME types to the
|
||||
# MIME types available to the currently active machine?
|
||||
def requestWrite(self, nodes, file_name = None, filter_by_machine = False, file_handler = None):
|
||||
#
|
||||
def requestWrite(self, nodes, file_name = None, filter_by_machine = False, file_handler = None, **kwargs):
|
||||
filter_by_machine = True # This plugin is indended to be used by machine (regardless of what it was told to do)
|
||||
if self._writing:
|
||||
raise OutputDeviceError.DeviceBusyError()
|
||||
|
@ -90,7 +91,7 @@ class RemovableDriveOutputDevice(OutputDevice):
|
|||
|
||||
self.writeStarted.emit(self)
|
||||
|
||||
job._message = message
|
||||
job.setMessage(message)
|
||||
self._writing = True
|
||||
job.start()
|
||||
except PermissionError as e:
|
||||
|
@ -117,8 +118,6 @@ class RemovableDriveOutputDevice(OutputDevice):
|
|||
raise OutputDeviceError.WriteRequestFailedError("Could not find a file name when trying to write to {device}.".format(device = self.getName()))
|
||||
|
||||
def _onProgress(self, job, progress):
|
||||
if hasattr(job, "_message"):
|
||||
job._message.setProgress(progress)
|
||||
self.writeProgress.emit(self, progress)
|
||||
|
||||
def _onFinished(self, job):
|
||||
|
@ -127,10 +126,6 @@ class RemovableDriveOutputDevice(OutputDevice):
|
|||
self._stream.close()
|
||||
self._stream = None
|
||||
|
||||
if hasattr(job, "_message"):
|
||||
job._message.hide()
|
||||
job._message = None
|
||||
|
||||
self._writing = False
|
||||
self.writeFinished.emit(self)
|
||||
if job.getResult():
|
||||
|
|
|
@ -8,7 +8,7 @@ catalog = i18nCatalog("cura")
|
|||
from . import RemovableDrivePlugin
|
||||
|
||||
import string
|
||||
import ctypes
|
||||
import ctypes # type: ignore
|
||||
from ctypes import wintypes # Using ctypes.wintypes in the code below does not seem to work
|
||||
|
||||
from UM.i18n import i18nCatalog
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
from UM.Platform import Platform
|
||||
|
||||
from UM.Logger import Logger
|
||||
from UM.i18n import i18nCatalog
|
||||
catalog = i18nCatalog("cura")
|
||||
|
||||
|
|
10
plugins/SliceInfoPlugin/SliceInfo.py
Normal file → Executable file
10
plugins/SliceInfoPlugin/SliceInfo.py
Normal file → Executable file
|
@ -1,5 +1,6 @@
|
|||
# Copyright (c) 2015 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
from typing import Any
|
||||
|
||||
from cura.CuraApplication import CuraApplication
|
||||
|
||||
|
@ -26,8 +27,8 @@ import json
|
|||
catalog = i18nCatalog("cura")
|
||||
|
||||
class SliceInfoJob(Job):
|
||||
data = None
|
||||
url = None
|
||||
data = None # type: Any
|
||||
url = None # type: str
|
||||
|
||||
def __init__(self, url, data):
|
||||
super().__init__()
|
||||
|
@ -89,9 +90,8 @@ class SliceInfo(Extension):
|
|||
# Listing all files placed on the buildplate
|
||||
modelhashes = []
|
||||
for node in DepthFirstIterator(CuraApplication.getInstance().getController().getScene().getRoot()):
|
||||
if type(node) is not SceneNode or not node.getMeshData():
|
||||
continue
|
||||
modelhashes.append(node.getMeshData().getHash())
|
||||
if node.callDecoration("isSliceable"):
|
||||
modelhashes.append(node.getMeshData().getHash())
|
||||
|
||||
# Creating md5sums and formatting them as discussed on JIRA
|
||||
modelhash_formatted = ",".join(modelhashes)
|
||||
|
|
|
@ -12,12 +12,13 @@ from UM.Settings.Validator import ValidatorState
|
|||
from UM.Math.Color import Color
|
||||
from UM.View.GL.OpenGL import OpenGL
|
||||
|
||||
import cura.Settings
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
from cura.Settings.ExtrudersModel import ExtrudersModel
|
||||
|
||||
import math
|
||||
|
||||
## Standard view for mesh models.
|
||||
|
||||
class SolidView(View):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
@ -27,7 +28,7 @@ class SolidView(View):
|
|||
self._enabled_shader = None
|
||||
self._disabled_shader = None
|
||||
|
||||
self._extruders_model = cura.Settings.ExtrudersModel()
|
||||
self._extruders_model = ExtrudersModel()
|
||||
|
||||
def beginRendering(self):
|
||||
scene = self.getController().getScene()
|
||||
|
|
|
@ -35,6 +35,7 @@ class DiscoverUM3Action(MachineAction):
|
|||
@pyqtSlot()
|
||||
def startDiscovery(self):
|
||||
if not self._network_plugin:
|
||||
Logger.log("d", "Starting printer discovery.")
|
||||
self._network_plugin = Application.getInstance().getOutputDeviceManager().getOutputDevicePlugin("UM3NetworkPrinting")
|
||||
self._network_plugin.printerListChanged.connect(self._onPrinterDiscoveryChanged)
|
||||
self.printersChanged.emit()
|
||||
|
@ -42,6 +43,7 @@ class DiscoverUM3Action(MachineAction):
|
|||
## Re-filters the list of printers.
|
||||
@pyqtSlot()
|
||||
def reset(self):
|
||||
Logger.log("d", "Reset the list of found printers.")
|
||||
self.printersChanged.emit()
|
||||
|
||||
@pyqtSlot()
|
||||
|
@ -95,12 +97,14 @@ class DiscoverUM3Action(MachineAction):
|
|||
|
||||
@pyqtSlot(str)
|
||||
def setKey(self, key):
|
||||
Logger.log("d", "Attempting to set the network key of the active machine to %s", key)
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if global_container_stack:
|
||||
meta_data = global_container_stack.getMetaData()
|
||||
if "um_network_key" in meta_data:
|
||||
global_container_stack.setMetaDataEntry("um_network_key", key)
|
||||
# Delete old authentication data.
|
||||
Logger.log("d", "Removing old authentication id %s for device %s", global_container_stack.getMetaDataEntry("network_authentication_id", None), key)
|
||||
global_container_stack.removeMetaDataEntry("network_authentication_id")
|
||||
global_container_stack.removeMetaDataEntry("network_authentication_key")
|
||||
else:
|
||||
|
|
326
plugins/UM3NetworkPrinting/NetworkPrinterOutputDevice.py
Normal file → Executable file
326
plugins/UM3NetworkPrinting/NetworkPrinterOutputDevice.py
Normal file → Executable file
|
@ -1,4 +1,4 @@
|
|||
# Copyright (c) 2016 Ultimaker B.V.
|
||||
# Copyright (c) 2017 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
from UM.i18n import i18nCatalog
|
||||
|
@ -8,7 +8,8 @@ from UM.Signal import signalemitter
|
|||
|
||||
from UM.Message import Message
|
||||
|
||||
import UM.Settings
|
||||
import UM.Settings.ContainerRegistry
|
||||
import UM.Version #To compare firmware version numbers.
|
||||
|
||||
from cura.PrinterOutputDevice import PrinterOutputDevice, ConnectionState
|
||||
import cura.Settings.ExtruderManager
|
||||
|
@ -97,6 +98,8 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
|
||||
self._material_ids = [""] * self._num_extruders
|
||||
self._hotend_ids = [""] * self._num_extruders
|
||||
self._target_bed_temperature = 0
|
||||
self._processing_preheat_requests = True
|
||||
|
||||
self.setPriority(2) # Make sure the output device gets selected above local file output
|
||||
self.setName(key)
|
||||
|
@ -197,11 +200,11 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
|
||||
def _onAuthenticationRequired(self, reply, authenticator):
|
||||
if self._authentication_id is not None and self._authentication_key is not None:
|
||||
Logger.log("d", "Authentication was required. Setting up authenticator.")
|
||||
Logger.log("d", "Authentication was required. Setting up authenticator with ID %s and key %s", self._authentication_id, self._getSafeAuthKey())
|
||||
authenticator.setUser(self._authentication_id)
|
||||
authenticator.setPassword(self._authentication_key)
|
||||
else:
|
||||
Logger.log("d", "No authentication was required. The id is: %s", self._authentication_id)
|
||||
Logger.log("d", "No authentication is available to use, but we did got a request for it.")
|
||||
|
||||
def getProperties(self):
|
||||
return self._properties
|
||||
|
@ -220,12 +223,17 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
def getKey(self):
|
||||
return self._key
|
||||
|
||||
## Name of the printer (as returned from the zeroConf properties)
|
||||
## The IP address of the printer.
|
||||
@pyqtProperty(str, constant = True)
|
||||
def address(self):
|
||||
return self._properties.get(b"address", b"").decode("utf-8")
|
||||
|
||||
## Name of the printer (as returned from the ZeroConf properties)
|
||||
@pyqtProperty(str, constant = True)
|
||||
def name(self):
|
||||
return self._properties.get(b"name", b"").decode("utf-8")
|
||||
|
||||
## Firmware version (as returned from the zeroConf properties)
|
||||
## Firmware version (as returned from the ZeroConf properties)
|
||||
@pyqtProperty(str, constant=True)
|
||||
def firmwareVersion(self):
|
||||
return self._properties.get(b"firmware_version", b"").decode("utf-8")
|
||||
|
@ -235,6 +243,66 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
def ipAddress(self):
|
||||
return self._address
|
||||
|
||||
## Pre-heats the heated bed of the printer.
|
||||
#
|
||||
# \param temperature The temperature to heat the bed to, in degrees
|
||||
# Celsius.
|
||||
# \param duration How long the bed should stay warm, in seconds.
|
||||
@pyqtSlot(float, float)
|
||||
def preheatBed(self, temperature, duration):
|
||||
temperature = round(temperature) #The API doesn't allow floating point.
|
||||
duration = round(duration)
|
||||
if UM.Version.Version(self.firmwareVersion) < UM.Version.Version("3.5.92"): #Real bed pre-heating support is implemented from 3.5.92 and up.
|
||||
self.setTargetBedTemperature(temperature = temperature) #No firmware-side duration support then.
|
||||
return
|
||||
url = QUrl("http://" + self._address + self._api_prefix + "printer/bed/pre_heat")
|
||||
if duration > 0:
|
||||
data = """{"temperature": "%i", "timeout": "%i"}""" % (temperature, duration)
|
||||
else:
|
||||
data = """{"temperature": "%i"}""" % temperature
|
||||
Logger.log("i", "Pre-heating bed to %i degrees.", temperature)
|
||||
put_request = QNetworkRequest(url)
|
||||
put_request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
|
||||
self._processing_preheat_requests = False
|
||||
self._manager.put(put_request, data.encode())
|
||||
self._preheat_bed_timer.start(self._preheat_bed_timeout * 1000) #Times 1000 because it needs to be provided as milliseconds.
|
||||
self.preheatBedRemainingTimeChanged.emit()
|
||||
|
||||
## Cancels pre-heating the heated bed of the printer.
|
||||
#
|
||||
# If the bed is not pre-heated, nothing happens.
|
||||
@pyqtSlot()
|
||||
def cancelPreheatBed(self):
|
||||
Logger.log("i", "Cancelling pre-heating of the bed.")
|
||||
self.preheatBed(temperature = 0, duration = 0)
|
||||
self._preheat_bed_timer.stop()
|
||||
self._preheat_bed_timer.setInterval(0)
|
||||
self.preheatBedRemainingTimeChanged.emit()
|
||||
|
||||
## Changes the target bed temperature on the printer.
|
||||
#
|
||||
# /param temperature The new target temperature of the bed.
|
||||
def _setTargetBedTemperature(self, temperature):
|
||||
if not self._updateTargetBedTemperature(temperature):
|
||||
return
|
||||
|
||||
url = QUrl("http://" + self._address + self._api_prefix + "printer/bed/temperature/target")
|
||||
data = str(temperature)
|
||||
put_request = QNetworkRequest(url)
|
||||
put_request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
|
||||
self._manager.put(put_request, data.encode())
|
||||
|
||||
## Updates the target bed temperature from the printer, and emit a signal if it was changed.
|
||||
#
|
||||
# /param temperature The new target temperature of the bed.
|
||||
# /return boolean, True if the temperature was changed, false if the new temperature has the same value as the already stored temperature
|
||||
def _updateTargetBedTemperature(self, temperature):
|
||||
if self._target_bed_temperature == temperature:
|
||||
return False
|
||||
self._target_bed_temperature = temperature
|
||||
self.targetBedTemperatureChanged.emit()
|
||||
return True
|
||||
|
||||
def _stopCamera(self):
|
||||
self._camera_timer.stop()
|
||||
if self._image_reply:
|
||||
|
@ -268,17 +336,20 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
## Set the authentication state.
|
||||
# \param auth_state \type{AuthState} Enum value representing the new auth state
|
||||
def setAuthenticationState(self, auth_state):
|
||||
if auth_state == self._authentication_state:
|
||||
return # Nothing to do here.
|
||||
|
||||
if auth_state == AuthState.AuthenticationRequested:
|
||||
Logger.log("d", "Authentication state changed to authentication requested.")
|
||||
self.setAcceptsCommands(False)
|
||||
self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connected over the network to {0}. Please approve the access request on the printer.").format(self.name))
|
||||
self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connected over the network. Please approve the access request on the printer."))
|
||||
self._authentication_requested_message.show()
|
||||
self._authentication_request_active = True
|
||||
self._authentication_timer.start() # Start timer so auth will fail after a while.
|
||||
elif auth_state == AuthState.Authenticated:
|
||||
Logger.log("d", "Authentication state changed to authenticated")
|
||||
self.setAcceptsCommands(True)
|
||||
self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connected over the network to {0}.").format(self.name))
|
||||
self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connected over the network."))
|
||||
self._authentication_requested_message.hide()
|
||||
if self._authentication_request_active:
|
||||
self._authentication_succeeded_message.show()
|
||||
|
@ -291,7 +362,7 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
self.sendMaterialProfiles()
|
||||
elif auth_state == AuthState.AuthenticationDenied:
|
||||
self.setAcceptsCommands(False)
|
||||
self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connected over the network to {0}. No access to control the printer.").format(self.name))
|
||||
self.setConnectionText(i18n_catalog.i18nc("@info:status", "Connected over the network. No access to control the printer."))
|
||||
self._authentication_requested_message.hide()
|
||||
if self._authentication_request_active:
|
||||
if self._authentication_timer.remainingTime() > 0:
|
||||
|
@ -308,9 +379,8 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
self._authentication_timer.stop()
|
||||
self._authentication_counter = 0
|
||||
|
||||
if auth_state != self._authentication_state:
|
||||
self._authentication_state = auth_state
|
||||
self.authenticationStateChanged.emit()
|
||||
self._authentication_state = auth_state
|
||||
self.authenticationStateChanged.emit()
|
||||
|
||||
authenticationStateChanged = pyqtSignal()
|
||||
|
||||
|
@ -466,6 +536,8 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
|
||||
bed_temperature = self._json_printer_state["bed"]["temperature"]["current"]
|
||||
self._setBedTemperature(bed_temperature)
|
||||
target_bed_temperature = self._json_printer_state["bed"]["temperature"]["target"]
|
||||
self._updateTargetBedTemperature(target_bed_temperature)
|
||||
|
||||
head_x = self._json_printer_state["heads"][0]["position"]["x"]
|
||||
head_y = self._json_printer_state["heads"][0]["position"]["y"]
|
||||
|
@ -473,6 +545,29 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
self._updateHeadPosition(head_x, head_y, head_z)
|
||||
self._updatePrinterState(self._json_printer_state["status"])
|
||||
|
||||
if self._processing_preheat_requests:
|
||||
try:
|
||||
is_preheating = self._json_printer_state["bed"]["pre_heat"]["active"]
|
||||
except KeyError: #Old firmware doesn't support that.
|
||||
pass #Don't update the pre-heat remaining time.
|
||||
else:
|
||||
if is_preheating:
|
||||
try:
|
||||
remaining_preheat_time = self._json_printer_state["bed"]["pre_heat"]["remaining"]
|
||||
except KeyError: #Error in firmware. If "active" is supported, "remaining" should also be supported.
|
||||
pass #Anyway, don't update.
|
||||
else:
|
||||
#Only update if time estimate is significantly off (>5000ms).
|
||||
#Otherwise we get issues with latency causing the timer to count inconsistently.
|
||||
if abs(self._preheat_bed_timer.remainingTime() - remaining_preheat_time * 1000) > 5000:
|
||||
self._preheat_bed_timer.setInterval(remaining_preheat_time * 1000)
|
||||
self._preheat_bed_timer.start()
|
||||
self.preheatBedRemainingTimeChanged.emit()
|
||||
else: #Not pre-heating. Must've cancelled.
|
||||
if self._preheat_bed_timer.isActive():
|
||||
self._preheat_bed_timer.setInterval(0)
|
||||
self._preheat_bed_timer.stop()
|
||||
self.preheatBedRemainingTimeChanged.emit()
|
||||
|
||||
def close(self):
|
||||
Logger.log("d", "Closing connection of printer %s with ip %s", self._key, self._address)
|
||||
|
@ -515,11 +610,8 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
# This is ignored.
|
||||
# \param filter_by_machine Whether to filter MIME types by machine. This
|
||||
# is ignored.
|
||||
def requestWrite(self, nodes, file_name = None, filter_by_machine = False, file_handler = None):
|
||||
if self._progress != 0:
|
||||
self._error_message = Message(i18n_catalog.i18nc("@info:status", "Unable to start a new print job because the printer is busy. Please check the printer."))
|
||||
self._error_message.show()
|
||||
return
|
||||
# \param kwargs Keyword arguments.
|
||||
def requestWrite(self, nodes, file_name = None, filter_by_machine = False, file_handler = None, **kwargs):
|
||||
if self._printer_state != "idle":
|
||||
self._error_message = Message(
|
||||
i18n_catalog.i18nc("@info:status", "Unable to start a new print job, printer is busy. Current printer status is %s.") % self._printer_state)
|
||||
|
@ -536,64 +628,67 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
self._gcode = getattr(Application.getInstance().getController().getScene(), "gcode_list")
|
||||
|
||||
print_information = Application.getInstance().getPrintInformation()
|
||||
|
||||
# Check if print cores / materials are loaded at all. Any failure in these results in an Error.
|
||||
for index in range(0, self._num_extruders):
|
||||
if print_information.materialLengths[index] != 0:
|
||||
if self._json_printer_state["heads"][0]["extruders"][index]["hotend"]["id"] == "":
|
||||
Logger.log("e", "No cartridge loaded in slot %s, unable to start print", index + 1)
|
||||
self._error_message = Message(
|
||||
i18n_catalog.i18nc("@info:status", "Unable to start a new print job. No PrinterCore loaded in slot {0}".format(index + 1)))
|
||||
self._error_message.show()
|
||||
return
|
||||
if self._json_printer_state["heads"][0]["extruders"][index]["active_material"]["guid"] == "":
|
||||
Logger.log("e", "No material loaded in slot %s, unable to start print", index + 1)
|
||||
self._error_message = Message(
|
||||
i18n_catalog.i18nc("@info:status",
|
||||
"Unable to start a new print job. No material loaded in slot {0}".format(index + 1)))
|
||||
self._error_message.show()
|
||||
return
|
||||
|
||||
warnings = [] # There might be multiple things wrong. Keep a list of all the stuff we need to warn about.
|
||||
|
||||
for index in range(0, self._num_extruders):
|
||||
# Check if there is enough material. Any failure in these results in a warning.
|
||||
material_length = self._json_printer_state["heads"][0]["extruders"][index]["active_material"]["length_remaining"]
|
||||
if material_length != -1 and print_information.materialLengths[index] > material_length:
|
||||
Logger.log("w", "Printer reports that there is not enough material left for extruder %s. We need %s and the printer has %s", index + 1, print_information.materialLengths[index], material_length)
|
||||
warnings.append(i18n_catalog.i18nc("@label", "Not enough material for spool {0}.").format(index+1))
|
||||
# Only check for mistakes if there is material length information.
|
||||
if print_information.materialLengths:
|
||||
# Check if print cores / materials are loaded at all. Any failure in these results in an Error.
|
||||
for index in range(0, self._num_extruders):
|
||||
if index < len(print_information.materialLengths) and print_information.materialLengths[index] != 0:
|
||||
if self._json_printer_state["heads"][0]["extruders"][index]["hotend"]["id"] == "":
|
||||
Logger.log("e", "No cartridge loaded in slot %s, unable to start print", index + 1)
|
||||
self._error_message = Message(
|
||||
i18n_catalog.i18nc("@info:status", "Unable to start a new print job. No PrinterCore loaded in slot {0}".format(index + 1)))
|
||||
self._error_message.show()
|
||||
return
|
||||
if self._json_printer_state["heads"][0]["extruders"][index]["active_material"]["guid"] == "":
|
||||
Logger.log("e", "No material loaded in slot %s, unable to start print", index + 1)
|
||||
self._error_message = Message(
|
||||
i18n_catalog.i18nc("@info:status",
|
||||
"Unable to start a new print job. No material loaded in slot {0}".format(index + 1)))
|
||||
self._error_message.show()
|
||||
return
|
||||
|
||||
# Check if the right cartridges are loaded. Any failure in these results in a warning.
|
||||
extruder_manager = cura.Settings.ExtruderManager.getInstance()
|
||||
if print_information.materialLengths[index] != 0:
|
||||
variant = extruder_manager.getExtruderStack(index).findContainer({"type": "variant"})
|
||||
core_name = self._json_printer_state["heads"][0]["extruders"][index]["hotend"]["id"]
|
||||
if variant:
|
||||
if variant.getName() != core_name:
|
||||
Logger.log("w", "Extruder %s has a different Cartridge (%s) as Cura (%s)", index + 1, core_name, variant.getName())
|
||||
warnings.append(i18n_catalog.i18nc("@label", "Different print core (Cura: {0}, Printer: {1}) selected for extruder {2}".format(variant.getName(), core_name, index + 1)))
|
||||
for index in range(0, self._num_extruders):
|
||||
# Check if there is enough material. Any failure in these results in a warning.
|
||||
material_length = self._json_printer_state["heads"][0]["extruders"][index]["active_material"]["length_remaining"]
|
||||
if material_length != -1 and index < len(print_information.materialLengths) and print_information.materialLengths[index] > material_length:
|
||||
Logger.log("w", "Printer reports that there is not enough material left for extruder %s. We need %s and the printer has %s", index + 1, print_information.materialLengths[index], material_length)
|
||||
warnings.append(i18n_catalog.i18nc("@label", "Not enough material for spool {0}.").format(index+1))
|
||||
|
||||
material = extruder_manager.getExtruderStack(index).findContainer({"type": "material"})
|
||||
if material:
|
||||
remote_material_guid = self._json_printer_state["heads"][0]["extruders"][index]["active_material"]["guid"]
|
||||
if material.getMetaDataEntry("GUID") != remote_material_guid:
|
||||
Logger.log("w", "Extruder %s has a different material (%s) as Cura (%s)", index + 1,
|
||||
remote_material_guid,
|
||||
material.getMetaDataEntry("GUID"))
|
||||
# Check if the right cartridges are loaded. Any failure in these results in a warning.
|
||||
extruder_manager = cura.Settings.ExtruderManager.ExtruderManager.getInstance()
|
||||
if index < len(print_information.materialLengths) and print_information.materialLengths[index] != 0:
|
||||
variant = extruder_manager.getExtruderStack(index).findContainer({"type": "variant"})
|
||||
core_name = self._json_printer_state["heads"][0]["extruders"][index]["hotend"]["id"]
|
||||
if variant:
|
||||
if variant.getName() != core_name:
|
||||
Logger.log("w", "Extruder %s has a different Cartridge (%s) as Cura (%s)", index + 1, core_name, variant.getName())
|
||||
warnings.append(i18n_catalog.i18nc("@label", "Different print core (Cura: {0}, Printer: {1}) selected for extruder {2}".format(variant.getName(), core_name, index + 1)))
|
||||
|
||||
remote_materials = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(type = "material", GUID = remote_material_guid, read_only = True)
|
||||
remote_material_name = "Unknown"
|
||||
if remote_materials:
|
||||
remote_material_name = remote_materials[0].getName()
|
||||
warnings.append(i18n_catalog.i18nc("@label", "Different material (Cura: {0}, Printer: {1}) selected for extruder {2}").format(material.getName(), remote_material_name, index + 1))
|
||||
material = extruder_manager.getExtruderStack(index).findContainer({"type": "material"})
|
||||
if material:
|
||||
remote_material_guid = self._json_printer_state["heads"][0]["extruders"][index]["active_material"]["guid"]
|
||||
if material.getMetaDataEntry("GUID") != remote_material_guid:
|
||||
Logger.log("w", "Extruder %s has a different material (%s) as Cura (%s)", index + 1,
|
||||
remote_material_guid,
|
||||
material.getMetaDataEntry("GUID"))
|
||||
|
||||
try:
|
||||
is_offset_calibrated = self._json_printer_state["heads"][0]["extruders"][index]["hotend"]["offset"]["state"] == "valid"
|
||||
except KeyError: # Older versions of the API don't expose the offset property, so we must asume that all is well.
|
||||
is_offset_calibrated = True
|
||||
remote_materials = UM.Settings.ContainerRegistry.ContainerRegistry.getInstance().findInstanceContainers(type = "material", GUID = remote_material_guid, read_only = True)
|
||||
remote_material_name = "Unknown"
|
||||
if remote_materials:
|
||||
remote_material_name = remote_materials[0].getName()
|
||||
warnings.append(i18n_catalog.i18nc("@label", "Different material (Cura: {0}, Printer: {1}) selected for extruder {2}").format(material.getName(), remote_material_name, index + 1))
|
||||
|
||||
if not is_offset_calibrated:
|
||||
warnings.append(i18n_catalog.i18nc("@label", "Print core {0} is not properly calibrated. XY calibration needs to be performed on the printer.").format(index + 1))
|
||||
try:
|
||||
is_offset_calibrated = self._json_printer_state["heads"][0]["extruders"][index]["hotend"]["offset"]["state"] == "valid"
|
||||
except KeyError: # Older versions of the API don't expose the offset property, so we must asume that all is well.
|
||||
is_offset_calibrated = True
|
||||
|
||||
if not is_offset_calibrated:
|
||||
warnings.append(i18n_catalog.i18nc("@label", "Print core {0} is not properly calibrated. XY calibration needs to be performed on the printer.").format(index + 1))
|
||||
else:
|
||||
Logger.log("w", "There was no material usage found. No check to match used material with machine is done.")
|
||||
|
||||
if warnings:
|
||||
text = i18n_catalog.i18nc("@label", "Are you sure you wish to print with the selected configuration?")
|
||||
|
@ -630,7 +725,8 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
|
||||
## Start requesting data from printer
|
||||
def connect(self):
|
||||
self.close() # Ensure that previous connection (if any) is killed.
|
||||
if self.isConnected():
|
||||
self.close() # Close previous connection
|
||||
|
||||
self._createNetworkManager()
|
||||
|
||||
|
@ -644,8 +740,12 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
self._authentication_id = Application.getInstance().getGlobalContainerStack().getMetaDataEntry("network_authentication_id", None)
|
||||
self._authentication_key = Application.getInstance().getGlobalContainerStack().getMetaDataEntry("network_authentication_key", None)
|
||||
|
||||
if self._authentication_id is None and self._authentication_key is None:
|
||||
Logger.log("d", "No authentication found in metadata.")
|
||||
else:
|
||||
Logger.log("d", "Loaded authentication id %s and key %s from the metadata entry", self._authentication_id, self._getSafeAuthKey())
|
||||
|
||||
self._update_timer.start()
|
||||
#self.startCamera()
|
||||
|
||||
## Stop requesting data from printer
|
||||
def disconnect(self):
|
||||
|
@ -706,19 +806,41 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
Logger.log("d", "Started sending g-code to remote printer.")
|
||||
self._compressing_print = True
|
||||
## Mash the data into single string
|
||||
|
||||
max_chars_per_line = 1024 * 1024 / 4 # 1 / 4 MB
|
||||
|
||||
byte_array_file_data = b""
|
||||
batched_line = ""
|
||||
|
||||
def _compress_data_and_notify_qt(data_to_append):
|
||||
compressed_data = gzip.compress(data_to_append.encode("utf-8"))
|
||||
QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
|
||||
# Pretend that this is a response, as zipping might take a bit of time.
|
||||
self._last_response_time = time()
|
||||
return compressed_data
|
||||
|
||||
for line in self._gcode:
|
||||
if not self._compressing_print:
|
||||
self._progress_message.hide()
|
||||
return # Stop trying to zip, abort was called.
|
||||
|
||||
if self._use_gzip:
|
||||
byte_array_file_data += gzip.compress(line.encode("utf-8"))
|
||||
QCoreApplication.processEvents() # Ensure that the GUI does not freeze.
|
||||
# Pretend that this is a response, as zipping might take a bit of time.
|
||||
self._last_response_time = time()
|
||||
batched_line += line
|
||||
# if the gcode was read from a gcode file, self._gcode will be a list of all lines in that file.
|
||||
# Compressing line by line in this case is extremely slow, so we need to batch them.
|
||||
if len(batched_line) < max_chars_per_line:
|
||||
continue
|
||||
|
||||
byte_array_file_data += _compress_data_and_notify_qt(batched_line)
|
||||
batched_line = ""
|
||||
else:
|
||||
byte_array_file_data += line.encode("utf-8")
|
||||
|
||||
# don't miss the last batch if it's there
|
||||
if self._use_gzip:
|
||||
if batched_line:
|
||||
byte_array_file_data += _compress_data_and_notify_qt(batched_line)
|
||||
|
||||
if self._use_gzip:
|
||||
file_name = "%s.gcode.gz" % Application.getInstance().getPrintInformation().jobName
|
||||
else:
|
||||
|
@ -760,7 +882,7 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
|
||||
## Check if the authentication request was allowed by the printer.
|
||||
def _checkAuthentication(self):
|
||||
Logger.log("d", "Checking if authentication is correct.")
|
||||
Logger.log("d", "Checking if authentication is correct for id %s and key %s", self._authentication_id, self._getSafeAuthKey())
|
||||
self._manager.get(QNetworkRequest(QUrl("http://" + self._address + self._api_prefix + "auth/check/" + str(self._authentication_id))))
|
||||
|
||||
## Request a authentication key from the printer so we can be authenticated
|
||||
|
@ -768,12 +890,14 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
url = QUrl("http://" + self._address + self._api_prefix + "auth/request")
|
||||
request = QNetworkRequest(url)
|
||||
request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
|
||||
self.setAuthenticationState(AuthState.AuthenticationRequested)
|
||||
self._authentication_key = None
|
||||
self._authentication_id = None
|
||||
self._manager.post(request, json.dumps({"application": "Cura-" + Application.getInstance().getVersion(), "user": self._getUserName()}).encode())
|
||||
self.setAuthenticationState(AuthState.AuthenticationRequested)
|
||||
|
||||
## Send all material profiles to the printer.
|
||||
def sendMaterialProfiles(self):
|
||||
for container in UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(type = "material"):
|
||||
for container in UM.Settings.ContainerRegistry.ContainerRegistry.getInstance().findInstanceContainers(type = "material"):
|
||||
try:
|
||||
xml_data = container.serialize()
|
||||
if xml_data == "" or xml_data is None:
|
||||
|
@ -839,7 +963,11 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
if status_code == 200:
|
||||
if self._connection_state == ConnectionState.connecting:
|
||||
self.setConnectionState(ConnectionState.connected)
|
||||
self._json_printer_state = json.loads(bytes(reply.readAll()).decode("utf-8"))
|
||||
try:
|
||||
self._json_printer_state = json.loads(bytes(reply.readAll()).decode("utf-8"))
|
||||
except json.decoder.JSONDecodeError:
|
||||
Logger.log("w", "Received an invalid printer state message: Not valid JSON.")
|
||||
return
|
||||
self._spliceJSONData()
|
||||
|
||||
# Hide connection error message if the connection was restored
|
||||
|
@ -851,7 +979,11 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
pass # TODO: Handle errors
|
||||
elif "print_job" in reply_url: # Status update from print_job:
|
||||
if status_code == 200:
|
||||
json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
|
||||
try:
|
||||
json_data = json.loads(bytes(reply.readAll()).decode("utf-8"))
|
||||
except json.decoder.JSONDecodeError:
|
||||
Logger.log("w", "Received an invalid print job state message: Not valid JSON.")
|
||||
return
|
||||
progress = json_data["progress"]
|
||||
## If progress is 0 add a bit so another print can't be sent.
|
||||
if progress == 0:
|
||||
|
@ -907,7 +1039,7 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
if status_code == 401:
|
||||
if self._authentication_state != AuthState.AuthenticationRequested:
|
||||
# Only request a new authentication when we have not already done so.
|
||||
Logger.log("i", "Not authenticated. Attempting to request authentication")
|
||||
Logger.log("i", "Not authenticated (Current auth state is %s). Attempting to request authentication", self._authentication_state )
|
||||
self._requestAuthentication()
|
||||
elif status_code == 403:
|
||||
# If we already had an auth (eg; didn't request one), we only need a single 403 to see it as denied.
|
||||
|
@ -917,6 +1049,7 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
elif status_code == 200:
|
||||
self.setAuthenticationState(AuthState.Authenticated)
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
|
||||
## Save authentication details.
|
||||
if global_container_stack:
|
||||
if "network_authentication_key" in global_container_stack.getMetaData():
|
||||
|
@ -928,13 +1061,17 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
else:
|
||||
global_container_stack.addMetaDataEntry("network_authentication_id", self._authentication_id)
|
||||
Application.getInstance().saveStack(global_container_stack) # Force save so we are sure the data is not lost.
|
||||
Logger.log("i", "Authentication succeeded")
|
||||
Logger.log("i", "Authentication succeeded for id %s and key %s", self._authentication_id, self._getSafeAuthKey())
|
||||
else: # Got a response that we didn't expect, so something went wrong.
|
||||
Logger.log("w", "While trying to authenticate, we got an unexpected response: %s", reply.attribute(QNetworkRequest.HttpStatusCodeAttribute))
|
||||
Logger.log("e", "While trying to authenticate, we got an unexpected response: %s", reply.attribute(QNetworkRequest.HttpStatusCodeAttribute))
|
||||
self.setAuthenticationState(AuthState.NotAuthenticated)
|
||||
|
||||
elif "auth/check" in reply_url: # Check if we are authenticated (user can refuse this!)
|
||||
data = json.loads(bytes(reply.readAll()).decode("utf-8"))
|
||||
try:
|
||||
data = json.loads(bytes(reply.readAll()).decode("utf-8"))
|
||||
except json.decoder.JSONDecodeError:
|
||||
Logger.log("w", "Received an invalid authentication check from printer: Not valid JSON.")
|
||||
return
|
||||
if data.get("message", "") == "authorized":
|
||||
Logger.log("i", "Authentication was approved")
|
||||
self._verifyAuthentication() # Ensure that the verification is really used and correct.
|
||||
|
@ -947,17 +1084,21 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
elif reply.operation() == QNetworkAccessManager.PostOperation:
|
||||
if "/auth/request" in reply_url:
|
||||
# We got a response to requesting authentication.
|
||||
data = json.loads(bytes(reply.readAll()).decode("utf-8"))
|
||||
|
||||
try:
|
||||
data = json.loads(bytes(reply.readAll()).decode("utf-8"))
|
||||
except json.decoder.JSONDecodeError:
|
||||
Logger.log("w", "Received an invalid authentication request reply from printer: Not valid JSON.")
|
||||
return
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if global_container_stack: # Remove any old data.
|
||||
Logger.log("d", "Removing old network authentication data as a new one was requested.")
|
||||
global_container_stack.removeMetaDataEntry("network_authentication_key")
|
||||
global_container_stack.removeMetaDataEntry("network_authentication_id")
|
||||
Application.getInstance().saveStack(global_container_stack) # Force saving so we don't keep wrong auth data.
|
||||
|
||||
self._authentication_key = data["key"]
|
||||
self._authentication_id = data["id"]
|
||||
Logger.log("i", "Got a new authentication ID. Waiting for authorization: %s", self._authentication_id )
|
||||
Logger.log("i", "Got a new authentication ID (%s) and KEY (%s). Waiting for authorization.", self._authentication_id, self._getSafeAuthKey())
|
||||
|
||||
# Check if the authentication is accepted.
|
||||
self._checkAuthentication()
|
||||
|
@ -973,7 +1114,9 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
self._progress_message.hide()
|
||||
|
||||
elif reply.operation() == QNetworkAccessManager.PutOperation:
|
||||
if status_code == 204:
|
||||
if "printer/bed/pre_heat" in reply_url: #Pre-heat command has completed. Re-enable syncing pre-heating.
|
||||
self._processing_preheat_requests = True
|
||||
if status_code in [200, 201, 202, 204]:
|
||||
pass # Request was successful!
|
||||
else:
|
||||
Logger.log("d", "Something went wrong when trying to update data of API (%s). Message: %s Statuscode: %s", reply_url, reply.readAll(), status_code)
|
||||
|
@ -1025,3 +1168,12 @@ class NetworkPrinterOutputDevice(PrinterOutputDevice):
|
|||
icon=QMessageBox.Question,
|
||||
callback=callback
|
||||
)
|
||||
|
||||
## Convenience function to "blur" out all but the last 5 characters of the auth key.
|
||||
# This can be used to debug print the key, without it compromising the security.
|
||||
def _getSafeAuthKey(self):
|
||||
if self._authentication_key is not None:
|
||||
result = self._authentication_key[-5:]
|
||||
result = "********" + result
|
||||
return result
|
||||
return self._authentication_key
|
||||
|
|
|
@ -1,7 +1,10 @@
|
|||
# Copyright (c) 2017 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
from UM.OutputDevice.OutputDevicePlugin import OutputDevicePlugin
|
||||
from . import NetworkPrinterOutputDevice
|
||||
|
||||
from zeroconf import Zeroconf, ServiceBrowser, ServiceStateChange, ServiceInfo
|
||||
from zeroconf import Zeroconf, ServiceBrowser, ServiceStateChange, ServiceInfo # type: ignore
|
||||
from UM.Logger import Logger
|
||||
from UM.Signal import Signal, signalemitter
|
||||
from UM.Application import Application
|
||||
|
@ -75,9 +78,13 @@ class NetworkPrinterOutputDevicePlugin(OutputDevicePlugin):
|
|||
self._manual_instances.append(address)
|
||||
self._preferences.setValue("um3networkprinting/manual_instances", ",".join(self._manual_instances))
|
||||
|
||||
name = address
|
||||
instance_name = "manual:%s" % address
|
||||
properties = { b"name": name.encode("utf-8"), b"manual": b"true", b"incomplete": b"true" }
|
||||
properties = {
|
||||
b"name": address.encode("utf-8"),
|
||||
b"address": address.encode("utf-8"),
|
||||
b"manual": b"true",
|
||||
b"incomplete": b"true"
|
||||
}
|
||||
|
||||
if instance_name not in self._printers:
|
||||
# Add a preliminary printer instance
|
||||
|
@ -112,10 +119,23 @@ class NetworkPrinterOutputDevicePlugin(OutputDevicePlugin):
|
|||
if status_code == 200:
|
||||
system_info = json.loads(bytes(reply.readAll()).decode("utf-8"))
|
||||
address = reply.url().host()
|
||||
name = ("%s (%s)" % (system_info["name"], address))
|
||||
|
||||
instance_name = "manual:%s" % address
|
||||
properties = { b"name": name.encode("utf-8"), b"firmware_version": system_info["firmware"].encode("utf-8"), b"manual": b"true" }
|
||||
machine = "unknown"
|
||||
if "variant" in system_info:
|
||||
variant = system_info["variant"]
|
||||
if variant == "Ultimaker 3":
|
||||
machine = "9066"
|
||||
elif variant == "Ultimaker 3 Extended":
|
||||
machine = "9511"
|
||||
|
||||
properties = {
|
||||
b"name": system_info["name"].encode("utf-8"),
|
||||
b"address": address.encode("utf-8"),
|
||||
b"firmware_version": system_info["firmware"].encode("utf-8"),
|
||||
b"manual": b"true",
|
||||
b"machine": machine.encode("utf-8")
|
||||
}
|
||||
if instance_name in self._printers:
|
||||
# Only replace the printer if it is still in the list of (manual) printers
|
||||
self.removePrinter(instance_name)
|
||||
|
@ -137,13 +157,15 @@ class NetworkPrinterOutputDevicePlugin(OutputDevicePlugin):
|
|||
|
||||
for key in self._printers:
|
||||
if key == active_machine.getMetaDataEntry("um_network_key"):
|
||||
Logger.log("d", "Connecting [%s]..." % key)
|
||||
self._printers[key].connect()
|
||||
self._printers[key].connectionStateChanged.connect(self._onPrinterConnectionStateChanged)
|
||||
if not self._printers[key].isConnected():
|
||||
Logger.log("d", "Connecting [%s]..." % key)
|
||||
self._printers[key].connect()
|
||||
self._printers[key].connectionStateChanged.connect(self._onPrinterConnectionStateChanged)
|
||||
else:
|
||||
if self._printers[key].isConnected():
|
||||
Logger.log("d", "Closing connection [%s]..." % key)
|
||||
self._printers[key].close()
|
||||
self._printers[key].connectionStateChanged.disconnect(self._onPrinterConnectionStateChanged)
|
||||
|
||||
## Because the model needs to be created in the same thread as the QMLEngine, we use a signal.
|
||||
def addPrinter(self, name, address, properties):
|
||||
|
@ -161,9 +183,9 @@ class NetworkPrinterOutputDevicePlugin(OutputDevicePlugin):
|
|||
printer = self._printers.pop(name, None)
|
||||
if printer:
|
||||
if printer.isConnected():
|
||||
printer.disconnect()
|
||||
printer.connectionStateChanged.disconnect(self._onPrinterConnectionStateChanged)
|
||||
Logger.log("d", "removePrinter, disconnecting [%s]..." % name)
|
||||
printer.disconnect()
|
||||
self.printerListChanged.emit()
|
||||
|
||||
## Handler for when the connection state of one of the detected printers changes
|
||||
|
@ -196,12 +218,13 @@ class NetworkPrinterOutputDevicePlugin(OutputDevicePlugin):
|
|||
info = zeroconf.get_service_info(service_type, name)
|
||||
|
||||
if info:
|
||||
type_of_device = info.properties.get(b"type", None).decode("utf-8")
|
||||
if type_of_device == "printer":
|
||||
address = '.'.join(map(lambda n: str(n), info.address))
|
||||
self.addPrinterSignal.emit(str(name), address, info.properties)
|
||||
else:
|
||||
Logger.log("w", "The type of the found device is '%s', not 'printer'! Ignoring.." %type_of_device )
|
||||
type_of_device = info.properties.get(b"type", None)
|
||||
if type_of_device:
|
||||
if type_of_device == b"printer":
|
||||
address = '.'.join(map(lambda n: str(n), info.address))
|
||||
self.addPrinterSignal.emit(str(name), address, info.properties)
|
||||
else:
|
||||
Logger.log("w", "The type of the found device is '%s', not 'printer'! Ignoring.." % type_of_device )
|
||||
else:
|
||||
Logger.log("w", "Could not get information about %s" % name)
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
from .avr_isp import stk500v2, ispBase, intelHex
|
||||
import serial
|
||||
import serial # type: ignore
|
||||
import threading
|
||||
import time
|
||||
import queue
|
||||
|
@ -19,8 +19,8 @@ from PyQt5.QtCore import QUrl, pyqtSlot, pyqtSignal, pyqtProperty
|
|||
from UM.i18n import i18nCatalog
|
||||
catalog = i18nCatalog("cura")
|
||||
|
||||
class USBPrinterOutputDevice(PrinterOutputDevice):
|
||||
|
||||
class USBPrinterOutputDevice(PrinterOutputDevice):
|
||||
def __init__(self, serial_port):
|
||||
super().__init__(serial_port)
|
||||
self.setName(catalog.i18nc("@item:inmenu", "USB printing"))
|
||||
|
@ -124,6 +124,16 @@ class USBPrinterOutputDevice(PrinterOutputDevice):
|
|||
def _homeBed(self):
|
||||
self._sendCommand("G28 Z")
|
||||
|
||||
## A name for the device.
|
||||
@pyqtProperty(str, constant = True)
|
||||
def name(self):
|
||||
return self.getName()
|
||||
|
||||
## The address of the device.
|
||||
@pyqtProperty(str, constant = True)
|
||||
def address(self):
|
||||
return self._serial_port
|
||||
|
||||
def startPrint(self):
|
||||
self.writeStarted.emit(self)
|
||||
gcode_list = getattr( Application.getInstance().getController().getScene(), "gcode_list")
|
||||
|
@ -138,6 +148,7 @@ class USBPrinterOutputDevice(PrinterOutputDevice):
|
|||
## Start a print based on a g-code.
|
||||
# \param gcode_list List with gcode (strings).
|
||||
def printGCode(self, gcode_list):
|
||||
Logger.log("d", "Started printing g-code")
|
||||
if self._progress or self._connection_state != ConnectionState.connected:
|
||||
self._error_message = Message(catalog.i18nc("@info:status", "Unable to start a new job because the printer is busy or not connected."))
|
||||
self._error_message.show()
|
||||
|
@ -173,6 +184,7 @@ class USBPrinterOutputDevice(PrinterOutputDevice):
|
|||
|
||||
## Private function (threaded) that actually uploads the firmware.
|
||||
def _updateFirmware(self):
|
||||
Logger.log("d", "Attempting to update firmware")
|
||||
self._error_code = 0
|
||||
self.setProgress(0, 100)
|
||||
self._firmware_update_finished = False
|
||||
|
@ -192,6 +204,7 @@ class USBPrinterOutputDevice(PrinterOutputDevice):
|
|||
try:
|
||||
programmer.connect(self._serial_port)
|
||||
except Exception:
|
||||
programmer.close()
|
||||
pass
|
||||
|
||||
# Give programmer some time to connect. Might need more in some cases, but this worked in all tested cases.
|
||||
|
@ -302,8 +315,10 @@ class USBPrinterOutputDevice(PrinterOutputDevice):
|
|||
programmer.connect(self._serial_port) # Connect with the serial, if this succeeds, it's an arduino based usb device.
|
||||
self._serial = programmer.leaveISP()
|
||||
except ispBase.IspError as e:
|
||||
programmer.close()
|
||||
Logger.log("i", "Could not establish connection on %s: %s. Device is not arduino based." %(self._serial_port,str(e)))
|
||||
except Exception as e:
|
||||
programmer.close()
|
||||
Logger.log("i", "Could not establish connection on %s, unknown reasons. Device is not arduino based." % self._serial_port)
|
||||
|
||||
# If the programmer connected, we know its an atmega based version.
|
||||
|
@ -433,11 +448,16 @@ class USBPrinterOutputDevice(PrinterOutputDevice):
|
|||
# This is ignored.
|
||||
# \param filter_by_machine Whether to filter MIME types by machine. This
|
||||
# is ignored.
|
||||
def requestWrite(self, nodes, file_name = None, filter_by_machine = False, file_handler = None):
|
||||
# \param kwargs Keyword arguments.
|
||||
def requestWrite(self, nodes, file_name = None, filter_by_machine = False, file_handler = None, **kwargs):
|
||||
container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if container_stack.getProperty("machine_gcode_flavor", "value") == "UltiGCode" or not container_stack.getMetaDataEntry("supports_usb_connection"):
|
||||
self._error_message = Message(catalog.i18nc("@info:status",
|
||||
"Unable to start a new job because the printer does not support usb printing."))
|
||||
|
||||
if container_stack.getProperty("machine_gcode_flavor", "value") == "UltiGCode":
|
||||
self._error_message = Message(catalog.i18nc("@info:status", "This printer does not support USB printing because it uses UltiGCode flavor."))
|
||||
self._error_message.show()
|
||||
return
|
||||
elif not container_stack.getMetaDataEntry("supports_usb_connection"):
|
||||
self._error_message = Message(catalog.i18nc("@info:status", "Unable to start a new job because the printer does not support usb printing."))
|
||||
self._error_message.show()
|
||||
return
|
||||
|
||||
|
@ -518,6 +538,7 @@ class USBPrinterOutputDevice(PrinterOutputDevice):
|
|||
self._sendNextGcodeLine()
|
||||
elif b"resend" in line.lower() or b"rs" in line: # Because a resend can be asked with "resend" and "rs"
|
||||
try:
|
||||
Logger.log("d", "Got a resend response")
|
||||
self._gcode_position = int(line.replace(b"N:",b" ").replace(b"N",b" ").replace(b":",b" ").split()[-1])
|
||||
except:
|
||||
if b"rs" in line:
|
||||
|
@ -544,15 +565,20 @@ class USBPrinterOutputDevice(PrinterOutputDevice):
|
|||
if ";" in line:
|
||||
line = line[:line.find(";")]
|
||||
line = line.strip()
|
||||
|
||||
# Don't send empty lines. But we do have to send something, so send
|
||||
# m105 instead.
|
||||
# Don't send the M0 or M1 to the machine, as M0 and M1 are handled as
|
||||
# an LCD menu pause.
|
||||
if line == "" or line == "M0" or line == "M1":
|
||||
line = "M105"
|
||||
try:
|
||||
if line == "M0" or line == "M1":
|
||||
line = "M105" # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
|
||||
if ("G0" in line or "G1" in line) and "Z" in line:
|
||||
z = float(re.search("Z([0-9\.]*)", line).group(1))
|
||||
if self._current_z != z:
|
||||
self._current_z = z
|
||||
except Exception as e:
|
||||
Logger.log("e", "Unexpected error with printer connection: %s" % e)
|
||||
Logger.log("e", "Unexpected error with printer connection, could not parse current Z: %s: %s" % (e, line))
|
||||
self._setErrorState("Unexpected error: %s" %e)
|
||||
checksum = functools.reduce(lambda x,y: x^y, map(ord, "N%d%s" % (self._gcode_position, line)))
|
||||
|
||||
|
@ -631,3 +657,24 @@ class USBPrinterOutputDevice(PrinterOutputDevice):
|
|||
self._update_firmware_thread.daemon = True
|
||||
|
||||
self.connect()
|
||||
|
||||
## Pre-heats the heated bed of the printer, if it has one.
|
||||
#
|
||||
# \param temperature The temperature to heat the bed to, in degrees
|
||||
# Celsius.
|
||||
# \param duration How long the bed should stay warm, in seconds. This is
|
||||
# ignored because there is no g-code to set this.
|
||||
@pyqtSlot(float, float)
|
||||
def preheatBed(self, temperature, duration):
|
||||
Logger.log("i", "Pre-heating the bed to %i degrees.", temperature)
|
||||
self._setTargetBedTemperature(temperature)
|
||||
self.preheatBedRemainingTimeChanged.emit()
|
||||
|
||||
## Cancels pre-heating the heated bed of the printer.
|
||||
#
|
||||
# If the bed is not pre-heated, nothing happens.
|
||||
@pyqtSlot()
|
||||
def cancelPreheatBed(self):
|
||||
Logger.log("i", "Cancelling pre-heating of the bed.")
|
||||
self._setTargetBedTemperature(0)
|
||||
self.preheatBedRemainingTimeChanged.emit()
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
# Copyright (c) 2015 Ultimaker B.V.
|
||||
# Copyright (c) 2017 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
from UM.Signal import Signal, signalemitter
|
||||
|
@ -79,10 +79,6 @@ class USBPrinterOutputDeviceManager(QObject, OutputDevicePlugin, Extension):
|
|||
|
||||
def stop(self):
|
||||
self._check_updates = False
|
||||
try:
|
||||
self._update_thread.join()
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
def _updateThread(self):
|
||||
while self._check_updates:
|
||||
|
@ -240,8 +236,7 @@ class USBPrinterOutputDeviceManager(QObject, OutputDevicePlugin, Extension):
|
|||
self.getOutputDeviceManager().removeOutputDevice(serial_port)
|
||||
self.connectionStateChanged.emit()
|
||||
except KeyError:
|
||||
pass # no output device by this device_id found in connection list.
|
||||
|
||||
Logger.log("w", "Connection state of %s changed, but it was not found in the list")
|
||||
|
||||
@pyqtProperty(QObject , notify = connectionStateChanged)
|
||||
def connectedPrinterList(self):
|
||||
|
@ -258,7 +253,7 @@ class USBPrinterOutputDeviceManager(QObject, OutputDevicePlugin, Extension):
|
|||
def getSerialPortList(self, only_list_usb = False):
|
||||
base_list = []
|
||||
if platform.system() == "Windows":
|
||||
import winreg #@UnresolvedImport
|
||||
import winreg # type: ignore @UnresolvedImport
|
||||
try:
|
||||
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM")
|
||||
i = 0
|
||||
|
@ -271,10 +266,10 @@ class USBPrinterOutputDeviceManager(QObject, OutputDevicePlugin, Extension):
|
|||
pass
|
||||
else:
|
||||
if only_list_usb:
|
||||
base_list = base_list + glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*") + glob.glob("/dev/cu.usb*")
|
||||
base_list = base_list + glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*") + glob.glob("/dev/cu.usb*") + glob.glob("/dev/tty.wchusb*") + glob.glob("/dev/cu.wchusb*")
|
||||
base_list = filter(lambda s: "Bluetooth" not in s, base_list) # Filter because mac sometimes puts them in the list
|
||||
else:
|
||||
base_list = base_list + glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*") + glob.glob("/dev/cu.*") + glob.glob("/dev/tty.usb*") + glob.glob("/dev/rfcomm*") + glob.glob("/dev/serial/by-id/*")
|
||||
base_list = base_list + glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*") + glob.glob("/dev/cu.*") + glob.glob("/dev/tty.usb*") + glob.glob("/dev/tty.wchusb*") + glob.glob("/dev/cu.wchusb*") + glob.glob("/dev/rfcomm*") + glob.glob("/dev/serial/by-id/*")
|
||||
return list(base_list)
|
||||
|
||||
_instance = None
|
||||
_instance = None # type: "USBPrinterOutputDeviceManager"
|
||||
|
|
|
@ -7,7 +7,7 @@ import struct
|
|||
import sys
|
||||
import time
|
||||
|
||||
from serial import Serial
|
||||
from serial import Serial # type: ignore
|
||||
from serial import SerialException
|
||||
from serial import SerialTimeoutException
|
||||
from UM.Logger import Logger
|
||||
|
@ -184,7 +184,7 @@ class Stk500v2(ispBase.IspBase):
|
|||
|
||||
def portList():
|
||||
ret = []
|
||||
import _winreg
|
||||
import _winreg # type: ignore
|
||||
key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM") #@UndefinedVariable
|
||||
i=0
|
||||
while True:
|
||||
|
|
|
@ -1,3 +1,8 @@
|
|||
# Copyright (c) 2017 Ultimaker B.V.
|
||||
# Uranium is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
from UM.Settings.InstanceContainer import InstanceContainer
|
||||
from cura.MachineAction import MachineAction
|
||||
from PyQt5.QtCore import pyqtSlot, pyqtSignal, pyqtProperty
|
||||
|
||||
|
@ -40,12 +45,12 @@ class UMOUpgradeSelection(MachineAction):
|
|||
|
||||
def _createDefinitionChangesContainer(self, global_container_stack):
|
||||
# Create a definition_changes container to store the settings in and add it to the stack
|
||||
definition_changes_container = UM.Settings.InstanceContainer(global_container_stack.getName() + "_settings")
|
||||
definition_changes_container = UM.Settings.InstanceContainer.InstanceContainer(global_container_stack.getName() + "_settings")
|
||||
definition = global_container_stack.getBottom()
|
||||
definition_changes_container.setDefinition(definition)
|
||||
definition_changes_container.addMetaDataEntry("type", "definition_changes")
|
||||
|
||||
UM.Settings.ContainerRegistry.getInstance().addContainer(definition_changes_container)
|
||||
UM.Settings.ContainerRegistry.ContainerRegistry.getInstance().addContainer(definition_changes_container)
|
||||
# Insert definition_changes between the definition and the variant
|
||||
global_container_stack.insertContainer(-1, definition_changes_container)
|
||||
|
||||
|
|
|
@ -1,18 +1,19 @@
|
|||
from UM.Application import Application
|
||||
from UM.Settings.DefinitionContainer import DefinitionContainer
|
||||
from cura.MachineAction import MachineAction
|
||||
from UM.i18n import i18nCatalog
|
||||
import cura.Settings.CuraContainerRegistry
|
||||
import UM.Settings.DefinitionContainer
|
||||
catalog = i18nCatalog("cura")
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
|
||||
catalog = i18nCatalog("cura")
|
||||
|
||||
## Upgrade the firmware of a machine by USB with this action.
|
||||
class UpgradeFirmwareMachineAction(MachineAction):
|
||||
def __init__(self):
|
||||
super().__init__("UpgradeFirmware", catalog.i18nc("@action", "Upgrade Firmware"))
|
||||
self._qml_url = "UpgradeFirmwareMachineAction.qml"
|
||||
cura.Settings.CuraContainerRegistry.getInstance().containerAdded.connect(self._onContainerAdded)
|
||||
ContainerRegistry.getInstance().containerAdded.connect(self._onContainerAdded)
|
||||
|
||||
def _onContainerAdded(self, container):
|
||||
# Add this action as a supported action to all machine definitions if they support USB connection
|
||||
if isinstance(container, UM.Settings.DefinitionContainer) and container.getMetaDataEntry("type") == "machine" and container.getMetaDataEntry("supports_usb_connection"):
|
||||
UM.Application.getInstance().getMachineActionManager().addSupportedAction(container.getId(), self.getKey())
|
||||
if isinstance(container, DefinitionContainer) and container.getMetaDataEntry("type") == "machine" and container.getMetaDataEntry("supports_usb_connection"):
|
||||
Application.getInstance().getMachineActionManager().addSupportedAction(container.getId(), self.getKey())
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
|
||||
import UM.VersionUpgrade #To indicate that a file is of incorrect format.
|
||||
import UM.VersionUpgradeManager #To schedule more files to be upgraded.
|
||||
import UM.Resources #To get the config storage path.
|
||||
from UM.Resources import Resources #To get the config storage path.
|
||||
|
||||
import configparser #To read config files.
|
||||
import io #To write config files to strings as if they were files.
|
||||
|
@ -107,7 +107,7 @@ class MachineInstance:
|
|||
user_profile["values"] = {}
|
||||
|
||||
version_upgrade_manager = UM.VersionUpgradeManager.VersionUpgradeManager.getInstance()
|
||||
user_storage = os.path.join(UM.Resources.getDataStoragePath(), next(iter(version_upgrade_manager.getStoragePaths("user"))))
|
||||
user_storage = os.path.join(Resources.getDataStoragePath(), next(iter(version_upgrade_manager.getStoragePaths("user"))))
|
||||
user_profile_file = os.path.join(user_storage, urllib.parse.quote_plus(self._name) + "_current_settings.inst.cfg")
|
||||
if not os.path.exists(user_storage):
|
||||
os.makedirs(user_storage)
|
||||
|
|
|
@ -3,6 +3,8 @@
|
|||
|
||||
import configparser #To read config files.
|
||||
import io #To write config files to strings as if they were files.
|
||||
from typing import Dict
|
||||
from typing import List
|
||||
|
||||
import UM.VersionUpgrade
|
||||
from UM.Logger import Logger
|
||||
|
@ -26,7 +28,7 @@ class Profile:
|
|||
#
|
||||
# \param serialised A string with the contents of a profile.
|
||||
# \param filename The supposed filename of the profile, without extension.
|
||||
def __init__(self, serialised, filename):
|
||||
def __init__(self, serialised: str, filename: str) -> None:
|
||||
self._filename = filename
|
||||
|
||||
parser = configparser.ConfigParser(interpolation = None)
|
||||
|
@ -58,17 +60,17 @@ class Profile:
|
|||
self._material_name = None
|
||||
|
||||
# Parse the settings.
|
||||
self._settings = {}
|
||||
self._settings = {} # type: Dict[str,str]
|
||||
if parser.has_section("settings"):
|
||||
for key, value in parser["settings"].items():
|
||||
self._settings[key] = value
|
||||
|
||||
# Parse the defaults and the disabled defaults.
|
||||
self._changed_settings_defaults = {}
|
||||
self._changed_settings_defaults = {} # type: Dict[str,str]
|
||||
if parser.has_section("defaults"):
|
||||
for key, value in parser["defaults"].items():
|
||||
self._changed_settings_defaults[key] = value
|
||||
self._disabled_settings_defaults = []
|
||||
self._disabled_settings_defaults = [] # type: List[str]
|
||||
if parser.has_section("disabled_defaults"):
|
||||
disabled_defaults_string = parser.get("disabled_defaults", "values")
|
||||
self._disabled_settings_defaults = [item for item in disabled_defaults_string.split(",") if item != ""] # Split by comma.
|
||||
|
|
|
@ -6,7 +6,7 @@ import os
|
|||
import os.path
|
||||
import io
|
||||
|
||||
from UM import Resources
|
||||
from UM.Resources import Resources
|
||||
from UM.VersionUpgrade import VersionUpgrade # Superclass of the plugin.
|
||||
import UM.VersionUpgrade
|
||||
|
||||
|
|
|
@ -0,0 +1,77 @@
|
|||
# Copyright (c) 2017 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
import configparser #To parse the files we need to upgrade and write the new files.
|
||||
import io #To serialise configparser output to a string.
|
||||
|
||||
from UM.VersionUpgrade import VersionUpgrade
|
||||
|
||||
_removed_settings = { #Settings that were removed in 2.5.
|
||||
"start_layers_at_same_position"
|
||||
}
|
||||
|
||||
## A collection of functions that convert the configuration of the user in Cura
|
||||
# 2.4 to a configuration for Cura 2.5.
|
||||
#
|
||||
# All of these methods are essentially stateless.
|
||||
class VersionUpgrade24to25(VersionUpgrade):
|
||||
## Gets the version number from a CFG file in Uranium's 2.4 format.
|
||||
#
|
||||
# Since the format may change, this is implemented for the 2.4 format only
|
||||
# and needs to be included in the version upgrade system rather than
|
||||
# globally in Uranium.
|
||||
#
|
||||
# \param serialised The serialised form of a CFG file.
|
||||
# \return The version number stored in the CFG file.
|
||||
# \raises ValueError The format of the version number in the file is
|
||||
# incorrect.
|
||||
# \raises KeyError The format of the file is incorrect.
|
||||
def getCfgVersion(self, serialised):
|
||||
parser = configparser.ConfigParser(interpolation = None)
|
||||
parser.read_string(serialised)
|
||||
return int(parser.get("general", "version")) #Explicitly give an exception when this fails. That means that the file format is not recognised.
|
||||
|
||||
## Upgrades the preferences file from version 2.4 to 2.5.
|
||||
#
|
||||
# \param serialised The serialised form of a preferences file.
|
||||
# \param filename The name of the file to upgrade.
|
||||
def upgradePreferences(self, serialised, filename):
|
||||
parser = configparser.ConfigParser(interpolation = None)
|
||||
parser.read_string(serialised)
|
||||
|
||||
#Remove settings from the visible_settings.
|
||||
if parser.has_section("general") and "visible_settings" in parser["general"]:
|
||||
visible_settings = parser["general"]["visible_settings"].split(";")
|
||||
visible_settings = filter(lambda setting: setting not in _removed_settings, visible_settings)
|
||||
parser["general"]["visible_settings"] = ";".join(visible_settings)
|
||||
|
||||
#Change the version number in the file.
|
||||
if parser.has_section("general"): #It better have!
|
||||
parser["general"]["version"] = "5"
|
||||
|
||||
#Re-serialise the file.
|
||||
output = io.StringIO()
|
||||
parser.write(output)
|
||||
return [filename], [output.getvalue()]
|
||||
|
||||
## Upgrades an instance container from version 2.4 to 2.5.
|
||||
#
|
||||
# \param serialised The serialised form of a quality profile.
|
||||
# \param filename The name of the file to upgrade.
|
||||
def upgradeInstanceContainer(self, serialised, filename):
|
||||
parser = configparser.ConfigParser(interpolation = None)
|
||||
parser.read_string(serialised)
|
||||
|
||||
#Remove settings from the [values] section.
|
||||
if parser.has_section("values"):
|
||||
for removed_setting in (_removed_settings & parser["values"].keys()): #Both in keys that need to be removed and in keys present in the file.
|
||||
del parser["values"][removed_setting]
|
||||
|
||||
#Change the version number in the file.
|
||||
if parser.has_section("general"):
|
||||
parser["general"]["version"] = "3"
|
||||
|
||||
#Re-serialise the file.
|
||||
output = io.StringIO()
|
||||
parser.write(output)
|
||||
return [filename], [output.getvalue()]
|
45
plugins/VersionUpgrade/VersionUpgrade24to25/__init__.py
Normal file
45
plugins/VersionUpgrade/VersionUpgrade24to25/__init__.py
Normal file
|
@ -0,0 +1,45 @@
|
|||
# Copyright (c) 2017 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
from . import VersionUpgrade24to25
|
||||
|
||||
from UM.i18n import i18nCatalog
|
||||
catalog = i18nCatalog("cura")
|
||||
|
||||
upgrade = VersionUpgrade24to25.VersionUpgrade24to25()
|
||||
|
||||
def getMetaData():
|
||||
return {
|
||||
"plugin": {
|
||||
"name": catalog.i18nc("@label", "Version Upgrade 2.4 to 2.5"),
|
||||
"author": "Ultimaker",
|
||||
"version": "1.0",
|
||||
"description": catalog.i18nc("@info:whatsthis", "Upgrades configurations from Cura 2.4 to Cura 2.5."),
|
||||
"api": 3
|
||||
},
|
||||
"version_upgrade": {
|
||||
# From To Upgrade function
|
||||
("preferences", 4): ("preferences", 5, upgrade.upgradePreferences),
|
||||
("quality", 2): ("quality", 3, upgrade.upgradeInstanceContainer),
|
||||
("variant", 2): ("variant", 3, upgrade.upgradeInstanceContainer), #We can re-use upgradeContainerStack since there is nothing specific to quality, variant or user profiles being changed.
|
||||
("user", 2): ("user", 3, upgrade.upgradeInstanceContainer)
|
||||
},
|
||||
"sources": {
|
||||
"quality": {
|
||||
"get_version": upgrade.getCfgVersion,
|
||||
"location": {"./quality"}
|
||||
},
|
||||
"preferences": {
|
||||
"get_version": upgrade.getCfgVersion,
|
||||
"location": {"."}
|
||||
},
|
||||
"user": {
|
||||
"get_version": upgrade.getCfgVersion,
|
||||
"location": {"./user"}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def register(app):
|
||||
return {}
|
||||
return { "version_upgrade": upgrade }
|
|
@ -0,0 +1,190 @@
|
|||
# Copyright (c) 2017 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
import configparser #To check whether the appropriate exceptions are raised.
|
||||
import pytest #To register tests with.
|
||||
|
||||
import VersionUpgrade24to25 #The module we're testing.
|
||||
|
||||
## Creates an instance of the upgrader to test with.
|
||||
@pytest.fixture
|
||||
def upgrader():
|
||||
return VersionUpgrade24to25.VersionUpgrade24to25()
|
||||
|
||||
test_cfg_version_good_data = [
|
||||
{
|
||||
"test_name": "Simple",
|
||||
"file_data": """[general]
|
||||
version = 1
|
||||
""",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"test_name": "Other Data Around",
|
||||
"file_data": """[nonsense]
|
||||
life = good
|
||||
|
||||
[general]
|
||||
version = 3
|
||||
|
||||
[values]
|
||||
layer_height = 0.12
|
||||
infill_sparse_density = 42
|
||||
""",
|
||||
"version": 3
|
||||
},
|
||||
{
|
||||
"test_name": "Negative Version", #Why not?
|
||||
"file_data": """[general]
|
||||
version = -20
|
||||
""",
|
||||
"version": -20
|
||||
}
|
||||
]
|
||||
|
||||
## Tests the technique that gets the version number from CFG files.
|
||||
#
|
||||
# \param data The parametrised data to test with. It contains a test name
|
||||
# to debug with, the serialised contents of a CFG file and the correct
|
||||
# version number in that CFG file.
|
||||
# \param upgrader The instance of the upgrade class to test.
|
||||
@pytest.mark.parametrize("data", test_cfg_version_good_data)
|
||||
def test_cfgVersionGood(data, upgrader):
|
||||
version = upgrader.getCfgVersion(data["file_data"])
|
||||
assert version == data["version"]
|
||||
|
||||
test_cfg_version_bad_data = [
|
||||
{
|
||||
"test_name": "Empty",
|
||||
"file_data": "",
|
||||
"exception": configparser.Error #Explicitly not specified further which specific error we're getting, because that depends on the implementation of configparser.
|
||||
},
|
||||
{
|
||||
"test_name": "No General",
|
||||
"file_data": """[values]
|
||||
layer_height = 0.1337
|
||||
""",
|
||||
"exception": configparser.Error
|
||||
},
|
||||
{
|
||||
"test_name": "No Version",
|
||||
"file_data": """[general]
|
||||
true = false
|
||||
""",
|
||||
"exception": configparser.Error
|
||||
},
|
||||
{
|
||||
"test_name": "Not a Number",
|
||||
"file_data": """[general]
|
||||
version = not-a-text-version-number
|
||||
""",
|
||||
"exception": ValueError
|
||||
}
|
||||
]
|
||||
|
||||
## Tests whether getting a version number from bad CFG files gives an
|
||||
# exception.
|
||||
#
|
||||
# \param data The parametrised data to test with. It contains a test name
|
||||
# to debug with, the serialised contents of a CFG file and the class of
|
||||
# exception it needs to throw.
|
||||
# \param upgrader The instance of the upgrader to test.
|
||||
@pytest.mark.parametrize("data", test_cfg_version_bad_data)
|
||||
def test_cfgVersionBad(data, upgrader):
|
||||
with pytest.raises(data["exception"]):
|
||||
upgrader.getCfgVersion(data["file_data"])
|
||||
|
||||
test_upgrade_preferences_removed_settings_data = [
|
||||
{
|
||||
"test_name": "Removed Setting",
|
||||
"file_data": """[general]
|
||||
visible_settings = baby;you;know;how;I;like;to;start_layers_at_same_position
|
||||
""",
|
||||
},
|
||||
{
|
||||
"test_name": "No Removed Setting",
|
||||
"file_data": """[general]
|
||||
visible_settings = baby;you;now;how;I;like;to;eat;chocolate;muffins
|
||||
"""
|
||||
},
|
||||
{
|
||||
"test_name": "No Visible Settings Key",
|
||||
"file_data": """[general]
|
||||
cura = cool
|
||||
"""
|
||||
},
|
||||
{
|
||||
"test_name": "No General Category",
|
||||
"file_data": """[foos]
|
||||
foo = bar
|
||||
"""
|
||||
}
|
||||
]
|
||||
|
||||
## Tests whether the settings that should be removed are removed for the 2.5
|
||||
# version of preferences.
|
||||
@pytest.mark.parametrize("data", test_upgrade_preferences_removed_settings_data)
|
||||
def test_upgradePreferencesRemovedSettings(data, upgrader):
|
||||
#Get the settings from the original file.
|
||||
original_parser = configparser.ConfigParser(interpolation = None)
|
||||
original_parser.read_string(data["file_data"])
|
||||
settings = set()
|
||||
if original_parser.has_section("general") and "visible_settings" in original_parser["general"]:
|
||||
settings = set(original_parser["general"]["visible_settings"].split(";"))
|
||||
|
||||
#Perform the upgrade.
|
||||
_, upgraded_preferences = upgrader.upgradePreferences(data["file_data"], "<string>")
|
||||
upgraded_preferences = upgraded_preferences[0]
|
||||
|
||||
#Find whether the removed setting is removed from the file now.
|
||||
settings -= VersionUpgrade24to25._removed_settings
|
||||
parser = configparser.ConfigParser(interpolation = None)
|
||||
parser.read_string(upgraded_preferences)
|
||||
assert (parser.has_section("general") and "visible_settings" in parser["general"]) == (len(settings) > 0) #If there are settings, there must also be a preference.
|
||||
if settings:
|
||||
assert settings == set(parser["general"]["visible_settings"].split(";"))
|
||||
|
||||
test_upgrade_instance_container_removed_settings_data = [
|
||||
{
|
||||
"test_name": "Removed Setting",
|
||||
"file_data": """[values]
|
||||
layer_height = 0.1337
|
||||
start_layers_at_same_position = True
|
||||
"""
|
||||
},
|
||||
{
|
||||
"test_name": "No Removed Setting",
|
||||
"file_data": """[values]
|
||||
oceans_number = 11
|
||||
"""
|
||||
},
|
||||
{
|
||||
"test_name": "No Values Category",
|
||||
"file_data": """[general]
|
||||
type = instance_container
|
||||
"""
|
||||
}
|
||||
]
|
||||
|
||||
## Tests whether the settings that should be removed are removed for the 2.5
|
||||
# version of instance containers.
|
||||
@pytest.mark.parametrize("data", test_upgrade_instance_container_removed_settings_data)
|
||||
def test_upgradeInstanceContainerRemovedSettings(data, upgrader):
|
||||
#Get the settings from the original file.
|
||||
original_parser = configparser.ConfigParser(interpolation = None)
|
||||
original_parser.read_string(data["file_data"])
|
||||
settings = set()
|
||||
if original_parser.has_section("values"):
|
||||
settings = set(original_parser["values"])
|
||||
|
||||
#Perform the upgrade.
|
||||
_, upgraded_container = upgrader.upgradeInstanceContainer(data["file_data"], "<string>")
|
||||
upgraded_container = upgraded_container[0]
|
||||
|
||||
#Find whether the forbidden setting is still in the container.
|
||||
settings -= VersionUpgrade24to25._removed_settings
|
||||
parser = configparser.ConfigParser(interpolation = None)
|
||||
parser.read_string(upgraded_container)
|
||||
assert parser.has_section("values") == (len(settings) > 0) #If there are settings, there must also be the values category.
|
||||
if settings:
|
||||
assert settings == set(parser["values"])
|
|
@ -13,8 +13,10 @@ from UM.Mesh.MeshBuilder import MeshBuilder
|
|||
from UM.Mesh.MeshReader import MeshReader
|
||||
from UM.Scene.SceneNode import SceneNode
|
||||
|
||||
MYPY = False
|
||||
try:
|
||||
import xml.etree.cElementTree as ET
|
||||
if not MYPY:
|
||||
import xml.etree.cElementTree as ET
|
||||
except ImportError:
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
|
|
@ -17,6 +17,28 @@ fragment =
|
|||
gl_FragColor = u_color;
|
||||
}
|
||||
|
||||
vertex41core =
|
||||
#version 410
|
||||
uniform highp mat4 u_modelViewProjectionMatrix;
|
||||
|
||||
in highp vec4 a_vertex;
|
||||
|
||||
void main()
|
||||
{
|
||||
gl_Position = u_modelViewProjectionMatrix * a_vertex;
|
||||
}
|
||||
|
||||
fragment41core =
|
||||
#version 410
|
||||
uniform lowp vec4 u_color;
|
||||
|
||||
out vec4 frag_color;
|
||||
|
||||
void main()
|
||||
{
|
||||
frag_color = u_color;
|
||||
}
|
||||
|
||||
[defaults]
|
||||
u_color = [0.02, 0.02, 0.02, 1.0]
|
||||
|
||||
|
|
|
@ -67,6 +67,77 @@ fragment =
|
|||
}
|
||||
}
|
||||
|
||||
vertex41core =
|
||||
#version 410
|
||||
uniform highp mat4 u_modelViewProjectionMatrix;
|
||||
in highp vec4 a_vertex;
|
||||
in highp vec2 a_uvs;
|
||||
|
||||
out highp vec2 v_uvs;
|
||||
|
||||
void main()
|
||||
{
|
||||
gl_Position = u_modelViewProjectionMatrix * a_vertex;
|
||||
v_uvs = a_uvs;
|
||||
}
|
||||
|
||||
fragment41core =
|
||||
#version 410
|
||||
uniform sampler2D u_layer0;
|
||||
uniform sampler2D u_layer1;
|
||||
uniform sampler2D u_layer2;
|
||||
|
||||
uniform vec2 u_offset[9];
|
||||
|
||||
uniform float u_outline_strength;
|
||||
uniform vec4 u_outline_color;
|
||||
uniform vec4 u_error_color;
|
||||
uniform vec4 u_background_color;
|
||||
|
||||
const vec3 x_axis = vec3(1.0, 0.0, 0.0);
|
||||
const vec3 y_axis = vec3(0.0, 1.0, 0.0);
|
||||
const vec3 z_axis = vec3(0.0, 0.0, 1.0);
|
||||
|
||||
in vec2 v_uvs;
|
||||
out vec4 frag_color;
|
||||
|
||||
float kernel[9];
|
||||
|
||||
void main()
|
||||
{
|
||||
kernel[0] = 0.0; kernel[1] = 1.0; kernel[2] = 0.0;
|
||||
kernel[3] = 1.0; kernel[4] = -4.0; kernel[5] = 1.0;
|
||||
kernel[6] = 0.0; kernel[7] = 1.0; kernel[8] = 0.0;
|
||||
|
||||
vec4 result = u_background_color;
|
||||
vec4 layer0 = texture(u_layer0, v_uvs);
|
||||
|
||||
result = layer0 * layer0.a + result * (1.0 - layer0.a);
|
||||
|
||||
float intersection_count = (texture(u_layer2, v_uvs).r * 255.0) / 5.0;
|
||||
if(mod(intersection_count, 2.0) == 1.0)
|
||||
{
|
||||
result = u_error_color;
|
||||
}
|
||||
|
||||
vec4 sum = vec4(0.0);
|
||||
for (int i = 0; i < 9; i++)
|
||||
{
|
||||
vec4 color = vec4(texture(u_layer1, v_uvs.xy + u_offset[i]).a);
|
||||
sum += color * (kernel[i] / u_outline_strength);
|
||||
}
|
||||
|
||||
vec4 layer1 = texture(u_layer1, v_uvs);
|
||||
if((layer1.rgb == x_axis || layer1.rgb == y_axis || layer1.rgb == z_axis))
|
||||
{
|
||||
frag_color = result;
|
||||
}
|
||||
else
|
||||
{
|
||||
frag_color = mix(result, vec4(abs(sum.a)) * u_outline_color, abs(sum.a));
|
||||
}
|
||||
}
|
||||
|
||||
[defaults]
|
||||
u_layer0 = 0
|
||||
u_layer1 = 1
|
||||
|
|
|
@ -1,11 +1,10 @@
|
|||
# Copyright (c) 2016 Ultimaker B.V.
|
||||
# Copyright (c) 2017 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
import math
|
||||
import copy
|
||||
import io
|
||||
from typing import Optional
|
||||
import xml.etree.ElementTree as ET
|
||||
import uuid
|
||||
|
||||
from UM.Resources import Resources
|
||||
from UM.Logger import Logger
|
||||
|
@ -13,11 +12,11 @@ from UM.Util import parseBool
|
|||
from cura.CuraApplication import CuraApplication
|
||||
|
||||
import UM.Dictionary
|
||||
|
||||
import UM.Settings
|
||||
from UM.Settings.InstanceContainer import InstanceContainer, InvalidInstanceError
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
|
||||
## Handles serializing and deserializing material containers from an XML file
|
||||
class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
||||
class XmlMaterialProfile(InstanceContainer):
|
||||
def __init__(self, container_id, *args, **kwargs):
|
||||
super().__init__(container_id, *args, **kwargs)
|
||||
self._inherited_files = []
|
||||
|
@ -30,7 +29,7 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
super().setReadOnly(read_only)
|
||||
|
||||
basefile = self.getMetaDataEntry("base_file", self._id) # if basefile is self.id, this is a basefile.
|
||||
for container in UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
|
||||
for container in ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
|
||||
container._read_only = read_only # prevent loop instead of calling setReadOnly
|
||||
|
||||
## Overridden from InstanceContainer
|
||||
|
@ -46,7 +45,7 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
|
||||
basefile = self.getMetaDataEntry("base_file", self._id) #if basefile is self.id, this is a basefile.
|
||||
# Update all containers that share GUID and basefile
|
||||
for container in UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
|
||||
for container in ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
|
||||
container.setMetaDataEntry(key, value)
|
||||
|
||||
## Overridden from InstanceContainer, similar to setMetaDataEntry.
|
||||
|
@ -65,7 +64,7 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
basefile = self.getMetaDataEntry("base_file", self._id) # if basefile is self.id, this is a basefile.
|
||||
# Update the basefile as well, this is actually what we're trying to do
|
||||
# Update all containers that share GUID and basefile
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile)
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile)
|
||||
for container in containers:
|
||||
container.setName(new_name)
|
||||
|
||||
|
@ -74,7 +73,7 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
super().setDirty(dirty)
|
||||
base_file = self.getMetaDataEntry("base_file", None)
|
||||
if base_file is not None and base_file != self._id:
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findContainers(id=base_file)
|
||||
containers = ContainerRegistry.getInstance().findContainers(id=base_file)
|
||||
if containers:
|
||||
base_container = containers[0]
|
||||
if not base_container.isReadOnly():
|
||||
|
@ -88,7 +87,7 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
# super().setProperty(key, property_name, property_value)
|
||||
#
|
||||
# basefile = self.getMetaDataEntry("base_file", self._id) #if basefile is self.id, this is a basefile.
|
||||
# for container in UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
|
||||
# for container in UM.Settings.ContainerRegistry.ContainerRegistry.getInstance().findInstanceContainers(base_file = basefile):
|
||||
# if not container.isReadOnly():
|
||||
# container.setDirty(True)
|
||||
|
||||
|
@ -96,7 +95,7 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
# base file: global settings + supported machines
|
||||
# machine / variant combination: only changes for itself.
|
||||
def serialize(self):
|
||||
registry = UM.Settings.ContainerRegistry.getInstance()
|
||||
registry = ContainerRegistry.getInstance()
|
||||
|
||||
base_file = self.getMetaDataEntry("base_file", "")
|
||||
if base_file and self.id != base_file:
|
||||
|
@ -120,6 +119,7 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
metadata.pop("variant", "")
|
||||
metadata.pop("type", "")
|
||||
metadata.pop("base_file", "")
|
||||
metadata.pop("approximate_diameter", "")
|
||||
|
||||
## Begin Name Block
|
||||
builder.start("name")
|
||||
|
@ -250,11 +250,12 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
|
||||
root = builder.close()
|
||||
_indent(root)
|
||||
stream = io.StringIO()
|
||||
stream = io.BytesIO()
|
||||
tree = ET.ElementTree(root)
|
||||
tree.write(stream, encoding="unicode", xml_declaration=True)
|
||||
# this makes sure that the XML header states encoding="utf-8"
|
||||
tree.write(stream, encoding="utf-8", xml_declaration=True)
|
||||
|
||||
return stream.getvalue()
|
||||
return stream.getvalue().decode('utf-8')
|
||||
|
||||
# Recursively resolve loading inherited files
|
||||
def _resolveInheritance(self, file_name):
|
||||
|
@ -370,18 +371,38 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
self._dirty = False
|
||||
self._path = ""
|
||||
|
||||
def getConfigurationTypeFromSerialized(self, serialized: str) -> Optional[str]:
|
||||
return "material"
|
||||
|
||||
def getVersionFromSerialized(self, serialized: str) -> Optional[int]:
|
||||
version = None
|
||||
data = ET.fromstring(serialized)
|
||||
metadata = data.iterfind("./um:metadata/*", self.__namespaces)
|
||||
for entry in metadata:
|
||||
tag_name = _tag_without_namespace(entry)
|
||||
if tag_name == "version":
|
||||
try:
|
||||
version = int(entry.text)
|
||||
except Exception as e:
|
||||
raise InvalidInstanceError("Invalid version string '%s': %s" % (entry.text, e))
|
||||
break
|
||||
if version is None:
|
||||
raise InvalidInstanceError("Missing version in metadata")
|
||||
return version
|
||||
|
||||
## Overridden from InstanceContainer
|
||||
def deserialize(self, serialized):
|
||||
# update the serialized data first
|
||||
from UM.Settings.Interfaces import ContainerInterface
|
||||
serialized = ContainerInterface.deserialize(self, serialized)
|
||||
data = ET.fromstring(serialized)
|
||||
|
||||
# Reset previous metadata
|
||||
self.clearData() # Ensure any previous data is gone.
|
||||
|
||||
self.addMetaDataEntry("type", "material")
|
||||
self.addMetaDataEntry("base_file", self.id)
|
||||
|
||||
# TODO: Add material verfication
|
||||
self.addMetaDataEntry("status", "unknown")
|
||||
meta_data = {}
|
||||
meta_data["type"] = "material"
|
||||
meta_data["base_file"] = self.id
|
||||
meta_data["status"] = "unknown" # TODO: Add material verfication
|
||||
|
||||
inherits = data.find("./um:inherits", self.__namespaces)
|
||||
if inherits is not None:
|
||||
|
@ -399,23 +420,20 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
label = entry.find("./um:label", self.__namespaces)
|
||||
|
||||
if label is not None:
|
||||
self.setName(label.text)
|
||||
self._name = label.text
|
||||
else:
|
||||
self.setName(self._profile_name(material.text, color.text))
|
||||
|
||||
self.addMetaDataEntry("brand", brand.text)
|
||||
self.addMetaDataEntry("material", material.text)
|
||||
self.addMetaDataEntry("color_name", color.text)
|
||||
|
||||
self._name = self._profile_name(material.text, color.text)
|
||||
meta_data["brand"] = brand.text
|
||||
meta_data["material"] = material.text
|
||||
meta_data["color_name"] = color.text
|
||||
continue
|
||||
meta_data[tag_name] = entry.text
|
||||
|
||||
self.addMetaDataEntry(tag_name, entry.text)
|
||||
if "description" not in meta_data:
|
||||
meta_data["description"] = ""
|
||||
|
||||
if not "description" in self.getMetaData():
|
||||
self.addMetaDataEntry("description", "")
|
||||
|
||||
if not "adhesion_info" in self.getMetaData():
|
||||
self.addMetaDataEntry("adhesion_info", "")
|
||||
if "adhesion_info" not in meta_data:
|
||||
meta_data["adhesion_info"] = ""
|
||||
|
||||
property_values = {}
|
||||
properties = data.iterfind("./um:properties/*", self.__namespaces)
|
||||
|
@ -425,10 +443,9 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
|
||||
diameter = float(property_values.get("diameter", 2.85)) # In mm
|
||||
density = float(property_values.get("density", 1.3)) # In g/cm3
|
||||
meta_data["properties"] = property_values
|
||||
|
||||
self.addMetaDataEntry("properties", property_values)
|
||||
|
||||
self.setDefinition(UM.Settings.ContainerRegistry.getInstance().findDefinitionContainers(id = "fdmprinter")[0])
|
||||
self.setDefinition(ContainerRegistry.getInstance().findDefinitionContainers(id = "fdmprinter")[0])
|
||||
|
||||
global_compatibility = True
|
||||
global_setting_values = {}
|
||||
|
@ -436,16 +453,17 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
for entry in settings:
|
||||
key = entry.get("key")
|
||||
if key in self.__material_property_setting_map:
|
||||
self.setProperty(self.__material_property_setting_map[key], "value", entry.text)
|
||||
global_setting_values[self.__material_property_setting_map[key]] = entry.text
|
||||
elif key in self.__unmapped_settings:
|
||||
if key == "hardware compatible":
|
||||
global_compatibility = parseBool(entry.text)
|
||||
else:
|
||||
Logger.log("d", "Unsupported material setting %s", key)
|
||||
self._cached_values = global_setting_values
|
||||
|
||||
self.addMetaDataEntry("compatible", global_compatibility)
|
||||
|
||||
meta_data["approximate_diameter"] = round(diameter)
|
||||
meta_data["compatible"] = global_compatibility
|
||||
self.setMetaData(meta_data)
|
||||
self._dirty = False
|
||||
|
||||
machines = data.iterfind("./um:settings/um:machine", self.__namespaces)
|
||||
|
@ -463,6 +481,9 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
else:
|
||||
Logger.log("d", "Unsupported material setting %s", key)
|
||||
|
||||
cached_machine_setting_properties = global_setting_values.copy()
|
||||
cached_machine_setting_properties.update(machine_setting_values)
|
||||
|
||||
identifiers = machine.iterfind("./um:machine_identifier", self.__namespaces)
|
||||
for identifier in identifiers:
|
||||
machine_id = self.__product_id_map.get(identifier.get("product"), None)
|
||||
|
@ -470,7 +491,7 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
# Lets try again with some naive heuristics.
|
||||
machine_id = identifier.get("product").replace(" ", "").lower()
|
||||
|
||||
definitions = UM.Settings.ContainerRegistry.getInstance().findDefinitionContainers(id = machine_id)
|
||||
definitions = ContainerRegistry.getInstance().findDefinitionContainers(id = machine_id)
|
||||
if not definitions:
|
||||
Logger.log("w", "No definition found for machine ID %s", machine_id)
|
||||
continue
|
||||
|
@ -480,29 +501,20 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
if machine_compatibility:
|
||||
new_material_id = self.id + "_" + machine_id
|
||||
|
||||
# It could be that we are overwriting, so check if the ID already exists.
|
||||
materials = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(id=new_material_id)
|
||||
if materials:
|
||||
new_material = materials[0]
|
||||
new_material.clearData()
|
||||
else:
|
||||
new_material = XmlMaterialProfile(new_material_id)
|
||||
new_material = XmlMaterialProfile(new_material_id)
|
||||
|
||||
new_material.setName(self.getName())
|
||||
# Update the private directly, as we want to prevent the lookup that is done when using setName
|
||||
new_material._name = self.getName()
|
||||
new_material.setMetaData(copy.deepcopy(self.getMetaData()))
|
||||
new_material.setDefinition(definition)
|
||||
# Don't use setMetadata, as that overrides it for all materials with same base file
|
||||
new_material.getMetaData()["compatible"] = machine_compatibility
|
||||
|
||||
for key, value in global_setting_values.items():
|
||||
new_material.setProperty(key, "value", value)
|
||||
|
||||
for key, value in machine_setting_values.items():
|
||||
new_material.setProperty(key, "value", value)
|
||||
new_material.setCachedValues(cached_machine_setting_properties)
|
||||
|
||||
new_material._dirty = False
|
||||
if not materials:
|
||||
UM.Settings.ContainerRegistry.getInstance().addContainer(new_material)
|
||||
|
||||
ContainerRegistry.getInstance().addContainer(new_material)
|
||||
|
||||
hotends = machine.iterfind("./um:hotend", self.__namespaces)
|
||||
for hotend in hotends:
|
||||
|
@ -510,10 +522,10 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
if hotend_id is None:
|
||||
continue
|
||||
|
||||
variant_containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(id = hotend_id)
|
||||
variant_containers = ContainerRegistry.getInstance().findInstanceContainers(id = hotend_id)
|
||||
if not variant_containers:
|
||||
# It is not really properly defined what "ID" is so also search for variants by name.
|
||||
variant_containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(definition = definition.id, name = hotend_id)
|
||||
variant_containers = ContainerRegistry.getInstance().findInstanceContainers(definition = definition.id, name = hotend_id)
|
||||
|
||||
if not variant_containers:
|
||||
Logger.log("d", "No variants found with ID or name %s for machine %s", hotend_id, definition.id)
|
||||
|
@ -532,34 +544,26 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
else:
|
||||
Logger.log("d", "Unsupported material setting %s", key)
|
||||
|
||||
# It could be that we are overwriting, so check if the ID already exists.
|
||||
new_hotend_id = self.id + "_" + machine_id + "_" + hotend_id.replace(" ", "_")
|
||||
materials = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(id=new_hotend_id)
|
||||
if materials:
|
||||
new_hotend_material = materials[0]
|
||||
new_hotend_material.clearData()
|
||||
else:
|
||||
new_hotend_material = XmlMaterialProfile(new_hotend_id)
|
||||
|
||||
new_hotend_material.setName(self.getName())
|
||||
new_hotend_material = XmlMaterialProfile(new_hotend_id)
|
||||
|
||||
# Update the private directly, as we want to prevent the lookup that is done when using setName
|
||||
new_hotend_material._name = self.getName()
|
||||
new_hotend_material.setMetaData(copy.deepcopy(self.getMetaData()))
|
||||
new_hotend_material.setDefinition(definition)
|
||||
new_hotend_material.addMetaDataEntry("variant", variant_containers[0].id)
|
||||
# Don't use setMetadata, as that overrides it for all materials with same base file
|
||||
new_hotend_material.getMetaData()["compatible"] = hotend_compatibility
|
||||
|
||||
for key, value in global_setting_values.items():
|
||||
new_hotend_material.setProperty(key, "value", value)
|
||||
cached_hotend_setting_properties = cached_machine_setting_properties.copy()
|
||||
cached_hotend_setting_properties.update(hotend_setting_values)
|
||||
|
||||
for key, value in machine_setting_values.items():
|
||||
new_hotend_material.setProperty(key, "value", value)
|
||||
|
||||
for key, value in hotend_setting_values.items():
|
||||
new_hotend_material.setProperty(key, "value", value)
|
||||
new_hotend_material.setCachedValues(cached_hotend_setting_properties)
|
||||
|
||||
new_hotend_material._dirty = False
|
||||
if not materials: # It was not added yet, do so now.
|
||||
UM.Settings.ContainerRegistry.getInstance().addContainer(new_hotend_material)
|
||||
|
||||
ContainerRegistry.getInstance().addContainer(new_hotend_material)
|
||||
|
||||
def _addSettingElement(self, builder, instance):
|
||||
try:
|
||||
|
@ -602,7 +606,8 @@ class XmlMaterialProfile(UM.Settings.InstanceContainer):
|
|||
"Ultimaker 2 Extended": "ultimaker2_extended",
|
||||
"Ultimaker 2 Extended+": "ultimaker2_extended_plus",
|
||||
"Ultimaker Original": "ultimaker_original",
|
||||
"Ultimaker Original+": "ultimaker_original_plus"
|
||||
"Ultimaker Original+": "ultimaker_original_plus",
|
||||
"IMADE3D JellyBOX": "imade3d_jellybox"
|
||||
}
|
||||
|
||||
# Map of recognised namespaces with a proper prefix.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue