mirror of
https://github.com/Ultimaker/Cura.git
synced 2025-11-02 20:52:20 -07: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
19
.gitignore
vendored
19
.gitignore
vendored
|
|
@ -10,6 +10,7 @@ resources/i18n/x-test
|
|||
resources/firmware
|
||||
resources/materials
|
||||
LC_MESSAGES
|
||||
.cache
|
||||
|
||||
# Editors and IDEs.
|
||||
*kdev*
|
||||
|
|
@ -18,6 +19,7 @@ LC_MESSAGES
|
|||
*~
|
||||
*.qm
|
||||
.idea
|
||||
cura.desktop
|
||||
|
||||
# Eclipse+PyDev
|
||||
.project
|
||||
|
|
@ -32,4 +34,21 @@ plugins/Doodle3D-cura-plugin
|
|||
plugins/GodMode
|
||||
plugins/PostProcessingPlugin
|
||||
plugins/X3GWriter
|
||||
plugins/FlatProfileExporter
|
||||
plugins/cura-god-mode-plugin
|
||||
|
||||
#Build stuff
|
||||
CMakeCache.txt
|
||||
CMakeFiles
|
||||
CPackSourceConfig.cmake
|
||||
Testing/
|
||||
CTestTestfile.cmake
|
||||
Makefile*
|
||||
junit-pytest-*
|
||||
CuraVersion.py
|
||||
cmake_install.cmake
|
||||
|
||||
#Debug
|
||||
*.gcode
|
||||
run.sh
|
||||
|
||||
|
|
|
|||
|
|
@ -1,23 +1,32 @@
|
|||
project(cura NONE)
|
||||
cmake_minimum_required(VERSION 2.8.12)
|
||||
|
||||
set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/
|
||||
${CMAKE_MODULE_PATH})
|
||||
|
||||
include(GNUInstallDirs)
|
||||
|
||||
set(URANIUM_SCRIPTS_DIR "${CMAKE_SOURCE_DIR}/../uranium/scripts" CACHE DIRECTORY "The location of the scripts directory of the Uranium repository")
|
||||
set(URANIUM_DIR "${CMAKE_SOURCE_DIR}/../Uranium" CACHE DIRECTORY "The location of the Uranium repository")
|
||||
set(URANIUM_SCRIPTS_DIR "${URANIUM_DIR}/scripts" CACHE DIRECTORY "The location of the scripts directory of the Uranium repository")
|
||||
|
||||
# Tests
|
||||
# Note that we use exit 0 here to not mark the build as a failure on test failure
|
||||
add_custom_target(tests)
|
||||
add_custom_command(TARGET tests POST_BUILD COMMAND "PYTHONPATH=${CMAKE_SOURCE_DIR}/../Uranium/:${CMAKE_SOURCE_DIR}" ${PYTHON_EXECUTABLE} -m pytest -r a --junitxml=${CMAKE_BINARY_DIR}/junit.xml ${CMAKE_SOURCE_DIR} || exit 0)
|
||||
include(CuraTests)
|
||||
|
||||
option(CURA_DEBUGMODE "Enable debug dialog and other debug features" OFF)
|
||||
if(CURA_DEBUGMODE)
|
||||
set(_cura_debugmode "ON")
|
||||
endif()
|
||||
|
||||
set(CURA_VERSION "master" CACHE STRING "Version name of Cura")
|
||||
set(CURA_BUILDTYPE "" CACHE STRING "Build type of Cura, eg. 'PPA'")
|
||||
configure_file(${CMAKE_SOURCE_DIR}/cura.desktop.in ${CMAKE_BINARY_DIR}/cura.desktop @ONLY)
|
||||
configure_file(cura/CuraVersion.py.in CuraVersion.py @ONLY)
|
||||
|
||||
if(NOT ${URANIUM_DIR} STREQUAL "")
|
||||
set(CMAKE_MODULE_PATH "${URANIUM_DIR}/cmake")
|
||||
endif()
|
||||
if(NOT ${URANIUM_SCRIPTS_DIR} STREQUAL "")
|
||||
list(APPEND CMAKE_MODULE_PATH ${URANIUM_DIR}/cmake)
|
||||
include(UraniumTranslationTools)
|
||||
# Extract Strings
|
||||
add_custom_target(extract-messages ${URANIUM_SCRIPTS_DIR}/extract-messages ${CMAKE_SOURCE_DIR} cura)
|
||||
|
|
@ -58,5 +67,3 @@ else()
|
|||
install(FILES ${CMAKE_BINARY_DIR}/CuraVersion.py
|
||||
DESTINATION lib/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/site-packages/cura)
|
||||
endif()
|
||||
|
||||
include(CPackConfig.cmake)
|
||||
|
|
|
|||
|
|
@ -1,16 +0,0 @@
|
|||
set(CPACK_PACKAGE_VENDOR "Ultimaker B.V.")
|
||||
set(CPACK_PACKAGE_CONTACT "Arjen Hiemstra <a.hiemstra@ultimaker.com>")
|
||||
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Cura application to drive the CuraEngine")
|
||||
set(CPACK_PACKAGE_VERSION_MAJOR 15)
|
||||
set(CPACK_PACKAGE_VERSION_MINOR 05)
|
||||
set(CPACK_PACKAGE_VERSION_PATCH 90)
|
||||
set(CPACK_PACKAGE_VERSION_REVISION 1)
|
||||
set(CPACK_GENERATOR "DEB")
|
||||
|
||||
set(DEB_DEPENDS
|
||||
"uranium (>= 15.05.93)"
|
||||
)
|
||||
string(REPLACE ";" ", " DEB_DEPENDS "${DEB_DEPENDS}")
|
||||
set(CPACK_DEBIAN_PACKAGE_DEPENDS ${DEB_DEPENDS})
|
||||
|
||||
include(CPack)
|
||||
40
Jenkinsfile
vendored
Normal file
40
Jenkinsfile
vendored
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
parallel_nodes(['linux && cura', 'windows && cura']) {
|
||||
// Prepare building
|
||||
stage('Prepare') {
|
||||
// Ensure we start with a clean build directory.
|
||||
step([$class: 'WsCleanup'])
|
||||
|
||||
// Checkout whatever sources are linked to this pipeline.
|
||||
checkout scm
|
||||
}
|
||||
|
||||
// If any error occurs during building, we want to catch it and continue with the "finale" stage.
|
||||
catchError {
|
||||
// Building and testing should happen in a subdirectory.
|
||||
dir('build') {
|
||||
// Perform the "build". Since Uranium is Python code, this basically only ensures CMake is setup.
|
||||
stage('Build') {
|
||||
// Ensure CMake is setup. Note that since this is Python code we do not really "build" it.
|
||||
def uranium_dir = get_workspace_dir("Ultimaker/Uranium/master")
|
||||
cmake("..", "-DCMAKE_PREFIX_PATH=${env.CURA_ENVIRONMENT_PATH} -DCMAKE_BUILD_TYPE=Release -DURANIUM_DIR=${uranium_dir}")
|
||||
}
|
||||
|
||||
// Try and run the unit tests. If this stage fails, we consider the build to be "unstable".
|
||||
stage('Unit Test') {
|
||||
try {
|
||||
make('test')
|
||||
} catch(e) {
|
||||
currentBuild.result = "UNSTABLE"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Perform any post-build actions like notification and publishing of unit tests.
|
||||
stage('Finalize') {
|
||||
// Publish the test results to Jenkins.
|
||||
junit allowEmptyResults: true, testResults: 'build/junit*.xml'
|
||||
|
||||
notify_build_result(env.CURA_EMAIL_RECIPIENTS, '#cura-dev', ['master', '2.'])
|
||||
}
|
||||
}
|
||||
|
|
@ -50,6 +50,7 @@ Third party plugins
|
|||
* [X3G Writer](https://github.com/Ghostkeeper/X3GWriter): Adds support for exporting X3G files.
|
||||
* [Auto orientation](https://github.com/nallath/CuraOrientationPlugin): Calculate the optimal orientation for a model.
|
||||
* [OctoPrint Plugin](https://github.com/fieldofview/OctoPrintPlugin): Send printjobs directly to OctoPrint and monitor their progress in Cura.
|
||||
* [WirelessPrinting Plugin](https://github.com/probonopd/WirelessPrinting): Print wirelessly from Cura to your 3D printer connected to an ESP8266 module.
|
||||
|
||||
Making profiles for other printers
|
||||
----------------------------------
|
||||
|
|
|
|||
48
cmake/CuraTests.cmake
Normal file
48
cmake/CuraTests.cmake
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
# Copyright (c) 2017 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
enable_testing()
|
||||
include(CMakeParseArguments)
|
||||
|
||||
find_package(PythonInterp 3.5.0 REQUIRED)
|
||||
|
||||
function(cura_add_test)
|
||||
set(_single_args NAME DIRECTORY PYTHONPATH)
|
||||
cmake_parse_arguments("" "" "${_single_args}" "" ${ARGN})
|
||||
|
||||
if(NOT _NAME)
|
||||
message(FATAL_ERROR "cura_add_test requires a test name argument")
|
||||
endif()
|
||||
|
||||
if(NOT _DIRECTORY)
|
||||
message(FATAL_ERROR "cura_add_test requires a directory to test")
|
||||
endif()
|
||||
|
||||
if(NOT _PYTHONPATH)
|
||||
set(_PYTHONPATH ${_DIRECTORY})
|
||||
endif()
|
||||
|
||||
if(WIN32)
|
||||
string(REPLACE "|" "\\;" _PYTHONPATH ${_PYTHONPATH})
|
||||
else()
|
||||
string(REPLACE "|" ":" _PYTHONPATH ${_PYTHONPATH})
|
||||
endif()
|
||||
|
||||
add_test(
|
||||
NAME ${_NAME}
|
||||
COMMAND ${PYTHON_EXECUTABLE} -m pytest --junitxml=${CMAKE_BINARY_DIR}/junit-${_NAME}.xml ${_DIRECTORY}
|
||||
)
|
||||
set_tests_properties(${_NAME} PROPERTIES ENVIRONMENT LANG=C)
|
||||
set_tests_properties(${_NAME} PROPERTIES ENVIRONMENT "PYTHONPATH=${_PYTHONPATH}")
|
||||
endfunction()
|
||||
|
||||
cura_add_test(NAME pytest-main DIRECTORY ${CMAKE_SOURCE_DIR}/tests PYTHONPATH "${CMAKE_SOURCE_DIR}|${URANIUM_DIR}")
|
||||
|
||||
file(GLOB_RECURSE _plugins plugins/*/__init__.py)
|
||||
foreach(_plugin ${_plugins})
|
||||
get_filename_component(_plugin_directory ${_plugin} DIRECTORY)
|
||||
if(EXISTS ${_plugin_directory}/tests)
|
||||
get_filename_component(_plugin_name ${_plugin_directory} NAME)
|
||||
cura_add_test(NAME pytest-${_plugin_name} DIRECTORY ${_plugin_directory} PYTHONPATH "${_plugin_directory}|${CMAKE_SOURCE_DIR}|${URANIUM_DIR}")
|
||||
endif()
|
||||
endforeach()
|
||||
188
cura/Arrange.py
Executable file
188
cura/Arrange.py
Executable file
|
|
@ -0,0 +1,188 @@
|
|||
from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
|
||||
from UM.Logger import Logger
|
||||
from UM.Math.Vector import Vector
|
||||
from cura.ShapeArray import ShapeArray
|
||||
from cura import ZOffsetDecorator
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
import numpy
|
||||
import copy
|
||||
|
||||
|
||||
## Return object for bestSpot
|
||||
LocationSuggestion = namedtuple("LocationSuggestion", ["x", "y", "penalty_points", "priority"])
|
||||
|
||||
|
||||
## The Arrange classed is used together with ShapeArray. Use it to find
|
||||
# good locations for objects that you try to put on a build place.
|
||||
# Different priority schemes can be defined so it alters the behavior while using
|
||||
# the same logic.
|
||||
class Arrange:
|
||||
build_volume = None
|
||||
|
||||
def __init__(self, x, y, offset_x, offset_y, scale= 1.0):
|
||||
self.shape = (y, x)
|
||||
self._priority = numpy.zeros((x, y), dtype=numpy.int32)
|
||||
self._priority_unique_values = []
|
||||
self._occupied = numpy.zeros((x, y), dtype=numpy.int32)
|
||||
self._scale = scale # convert input coordinates to arrange coordinates
|
||||
self._offset_x = offset_x
|
||||
self._offset_y = offset_y
|
||||
self._last_priority = 0
|
||||
|
||||
## Helper to create an Arranger instance
|
||||
#
|
||||
# Either fill in scene_root and create will find all sliceable nodes by itself,
|
||||
# or use fixed_nodes to provide the nodes yourself.
|
||||
# \param scene_root Root for finding all scene nodes
|
||||
# \param fixed_nodes Scene nodes to be placed
|
||||
@classmethod
|
||||
def create(cls, scene_root = None, fixed_nodes = None, scale = 0.5):
|
||||
arranger = Arrange(220, 220, 110, 110, scale = scale)
|
||||
arranger.centerFirst()
|
||||
|
||||
if fixed_nodes is None:
|
||||
fixed_nodes = []
|
||||
for node_ in DepthFirstIterator(scene_root):
|
||||
# Only count sliceable objects
|
||||
if node_.callDecoration("isSliceable"):
|
||||
fixed_nodes.append(node_)
|
||||
|
||||
# Place all objects fixed nodes
|
||||
for fixed_node in fixed_nodes:
|
||||
vertices = fixed_node.callDecoration("getConvexHull")
|
||||
points = copy.deepcopy(vertices._points)
|
||||
shape_arr = ShapeArray.fromPolygon(points, scale = scale)
|
||||
arranger.place(0, 0, shape_arr)
|
||||
|
||||
# If a build volume was set, add the disallowed areas
|
||||
if Arrange.build_volume:
|
||||
disallowed_areas = Arrange.build_volume.getDisallowedAreas()
|
||||
for area in disallowed_areas:
|
||||
points = copy.deepcopy(area._points)
|
||||
shape_arr = ShapeArray.fromPolygon(points, scale = scale)
|
||||
arranger.place(0, 0, shape_arr)
|
||||
return arranger
|
||||
|
||||
## Find placement for a node (using offset shape) and place it (using hull shape)
|
||||
# return the nodes that should be placed
|
||||
# \param node
|
||||
# \param offset_shape_arr ShapeArray with offset, used to find location
|
||||
# \param hull_shape_arr ShapeArray without offset, for placing the shape
|
||||
def findNodePlacement(self, node, offset_shape_arr, hull_shape_arr, step = 1):
|
||||
new_node = copy.deepcopy(node)
|
||||
best_spot = self.bestSpot(
|
||||
offset_shape_arr, start_prio = self._last_priority, step = step)
|
||||
x, y = best_spot.x, best_spot.y
|
||||
|
||||
# Save the last priority.
|
||||
self._last_priority = best_spot.priority
|
||||
|
||||
# Ensure that the object is above the build platform
|
||||
new_node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
|
||||
if new_node.getBoundingBox():
|
||||
center_y = new_node.getWorldPosition().y - new_node.getBoundingBox().bottom
|
||||
else:
|
||||
center_y = 0
|
||||
|
||||
if x is not None: # We could find a place
|
||||
new_node.setPosition(Vector(x, center_y, y))
|
||||
found_spot = True
|
||||
self.place(x, y, hull_shape_arr) # place the object in arranger
|
||||
else:
|
||||
Logger.log("d", "Could not find spot!"),
|
||||
found_spot = False
|
||||
new_node.setPosition(Vector(200, center_y, 100))
|
||||
return new_node, found_spot
|
||||
|
||||
## Fill priority, center is best. Lower value is better
|
||||
# This is a strategy for the arranger.
|
||||
def centerFirst(self):
|
||||
# Square distance: creates a more round shape
|
||||
self._priority = numpy.fromfunction(
|
||||
lambda i, j: (self._offset_x - i) ** 2 + (self._offset_y - j) ** 2, self.shape, dtype=numpy.int32)
|
||||
self._priority_unique_values = numpy.unique(self._priority)
|
||||
self._priority_unique_values.sort()
|
||||
|
||||
## Fill priority, back is best. Lower value is better
|
||||
# This is a strategy for the arranger.
|
||||
def backFirst(self):
|
||||
self._priority = numpy.fromfunction(
|
||||
lambda i, j: 10 * j + abs(self._offset_x - i), self.shape, dtype=numpy.int32)
|
||||
self._priority_unique_values = numpy.unique(self._priority)
|
||||
self._priority_unique_values.sort()
|
||||
|
||||
## Return the amount of "penalty points" for polygon, which is the sum of priority
|
||||
# None if occupied
|
||||
# \param x x-coordinate to check shape
|
||||
# \param y y-coordinate
|
||||
# \param shape_arr the ShapeArray object to place
|
||||
def checkShape(self, x, y, shape_arr):
|
||||
x = int(self._scale * x)
|
||||
y = int(self._scale * y)
|
||||
offset_x = x + self._offset_x + shape_arr.offset_x
|
||||
offset_y = y + self._offset_y + shape_arr.offset_y
|
||||
occupied_slice = self._occupied[
|
||||
offset_y:offset_y + shape_arr.arr.shape[0],
|
||||
offset_x:offset_x + shape_arr.arr.shape[1]]
|
||||
try:
|
||||
if numpy.any(occupied_slice[numpy.where(shape_arr.arr == 1)]):
|
||||
return None
|
||||
except IndexError: # out of bounds if you try to place an object outside
|
||||
return None
|
||||
prio_slice = self._priority[
|
||||
offset_y:offset_y + shape_arr.arr.shape[0],
|
||||
offset_x:offset_x + shape_arr.arr.shape[1]]
|
||||
return numpy.sum(prio_slice[numpy.where(shape_arr.arr == 1)])
|
||||
|
||||
## Find "best" spot for ShapeArray
|
||||
# Return namedtuple with properties x, y, penalty_points, priority
|
||||
# \param shape_arr ShapeArray
|
||||
# \param start_prio Start with this priority value (and skip the ones before)
|
||||
# \param step Slicing value, higher = more skips = faster but less accurate
|
||||
def bestSpot(self, shape_arr, start_prio = 0, step = 1):
|
||||
start_idx_list = numpy.where(self._priority_unique_values == start_prio)
|
||||
if start_idx_list:
|
||||
start_idx = start_idx_list[0][0]
|
||||
else:
|
||||
start_idx = 0
|
||||
for priority in self._priority_unique_values[start_idx::step]:
|
||||
tryout_idx = numpy.where(self._priority == priority)
|
||||
for idx in range(len(tryout_idx[0])):
|
||||
x = tryout_idx[0][idx]
|
||||
y = tryout_idx[1][idx]
|
||||
projected_x = x - self._offset_x
|
||||
projected_y = y - self._offset_y
|
||||
|
||||
# array to "world" coordinates
|
||||
penalty_points = self.checkShape(projected_x, projected_y, shape_arr)
|
||||
if penalty_points is not None:
|
||||
return LocationSuggestion(x = projected_x, y = projected_y, penalty_points = penalty_points, priority = priority)
|
||||
return LocationSuggestion(x = None, y = None, penalty_points = None, priority = priority) # No suitable location found :-(
|
||||
|
||||
## Place the object.
|
||||
# Marks the locations in self._occupied and self._priority
|
||||
# \param x x-coordinate
|
||||
# \param y y-coordinate
|
||||
# \param shape_arr ShapeArray object
|
||||
def place(self, x, y, shape_arr):
|
||||
x = int(self._scale * x)
|
||||
y = int(self._scale * y)
|
||||
offset_x = x + self._offset_x + shape_arr.offset_x
|
||||
offset_y = y + self._offset_y + shape_arr.offset_y
|
||||
shape_y, shape_x = self._occupied.shape
|
||||
|
||||
min_x = min(max(offset_x, 0), shape_x - 1)
|
||||
min_y = min(max(offset_y, 0), shape_y - 1)
|
||||
max_x = min(max(offset_x + shape_arr.arr.shape[1], 0), shape_x - 1)
|
||||
max_y = min(max(offset_y + shape_arr.arr.shape[0], 0), shape_y - 1)
|
||||
occupied_slice = self._occupied[min_y:max_y, min_x:max_x]
|
||||
# we use a slice of shape because it can be out of bounds
|
||||
occupied_slice[numpy.where(shape_arr.arr[
|
||||
min_y - offset_y:max_y - offset_y, min_x - offset_x:max_x - offset_x] == 1)] = 1
|
||||
|
||||
# Set priority to low (= high number), so it won't get picked at trying out.
|
||||
prio_slice = self._priority[min_y:max_y, min_x:max_x]
|
||||
prio_slice[numpy.where(shape_arr.arr[
|
||||
min_y - offset_y:max_y - offset_y, min_x - offset_x:max_x - offset_x] == 1)] = 999
|
||||
86
cura/ArrangeObjectsJob.py
Executable file
86
cura/ArrangeObjectsJob.py
Executable file
|
|
@ -0,0 +1,86 @@
|
|||
# Copyright (c) 2017 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
from UM.Job import Job
|
||||
from UM.Scene.SceneNode import SceneNode
|
||||
from UM.Math.Vector import Vector
|
||||
from UM.Operations.SetTransformOperation import SetTransformOperation
|
||||
from UM.Operations.TranslateOperation import TranslateOperation
|
||||
from UM.Operations.GroupedOperation import GroupedOperation
|
||||
from UM.Logger import Logger
|
||||
from UM.Message import Message
|
||||
from UM.i18n import i18nCatalog
|
||||
i18n_catalog = i18nCatalog("cura")
|
||||
|
||||
from cura.ZOffsetDecorator import ZOffsetDecorator
|
||||
from cura.Arrange import Arrange
|
||||
from cura.ShapeArray import ShapeArray
|
||||
|
||||
from typing import List
|
||||
|
||||
|
||||
class ArrangeObjectsJob(Job):
|
||||
def __init__(self, nodes: List[SceneNode], fixed_nodes: List[SceneNode], min_offset = 8):
|
||||
super().__init__()
|
||||
self._nodes = nodes
|
||||
self._fixed_nodes = fixed_nodes
|
||||
self._min_offset = min_offset
|
||||
|
||||
def run(self):
|
||||
status_message = Message(i18n_catalog.i18nc("@info:status", "Finding new location for objects"), lifetime = 0, dismissable=False, progress = 0)
|
||||
status_message.show()
|
||||
arranger = Arrange.create(fixed_nodes = self._fixed_nodes)
|
||||
|
||||
# Collect nodes to be placed
|
||||
nodes_arr = [] # fill with (size, node, offset_shape_arr, hull_shape_arr)
|
||||
for node in self._nodes:
|
||||
offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(node, min_offset = self._min_offset)
|
||||
nodes_arr.append((offset_shape_arr.arr.shape[0] * offset_shape_arr.arr.shape[1], node, offset_shape_arr, hull_shape_arr))
|
||||
|
||||
# Sort the nodes with the biggest area first.
|
||||
nodes_arr.sort(key=lambda item: item[0])
|
||||
nodes_arr.reverse()
|
||||
|
||||
# Place nodes one at a time
|
||||
start_priority = 0
|
||||
last_priority = start_priority
|
||||
last_size = None
|
||||
grouped_operation = GroupedOperation()
|
||||
found_solution_for_all = True
|
||||
for idx, (size, node, offset_shape_arr, hull_shape_arr) in enumerate(nodes_arr):
|
||||
# For performance reasons, we assume that when a location does not fit,
|
||||
# it will also not fit for the next object (while what can be untrue).
|
||||
# We also skip possibilities by slicing through the possibilities (step = 10)
|
||||
if last_size == size: # This optimization works if many of the objects have the same size
|
||||
start_priority = last_priority
|
||||
else:
|
||||
start_priority = 0
|
||||
best_spot = arranger.bestSpot(offset_shape_arr, start_prio=start_priority, step=10)
|
||||
x, y = best_spot.x, best_spot.y
|
||||
node.removeDecorator(ZOffsetDecorator)
|
||||
if node.getBoundingBox():
|
||||
center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
|
||||
else:
|
||||
center_y = 0
|
||||
if x is not None: # We could find a place
|
||||
last_size = size
|
||||
last_priority = best_spot.priority
|
||||
|
||||
arranger.place(x, y, hull_shape_arr) # take place before the next one
|
||||
|
||||
grouped_operation.addOperation(TranslateOperation(node, Vector(x, center_y, y), set_position = True))
|
||||
else:
|
||||
Logger.log("d", "Arrange all: could not find spot!")
|
||||
found_solution_for_all = False
|
||||
grouped_operation.addOperation(TranslateOperation(node, Vector(200, center_y, - idx * 20), set_position = True))
|
||||
|
||||
status_message.setProgress((idx + 1) / len(nodes_arr) * 100)
|
||||
Job.yieldThread()
|
||||
|
||||
grouped_operation.push()
|
||||
|
||||
status_message.hide()
|
||||
|
||||
if not found_solution_for_all:
|
||||
no_full_solution_message = Message(i18n_catalog.i18nc("@info:status", "Unable to find a location within the build volume for all objects"))
|
||||
no_full_solution_message.show()
|
||||
123
cura/BuildVolume.py
Normal file → Executable file
123
cura/BuildVolume.py
Normal file → Executable file
|
|
@ -2,6 +2,7 @@
|
|||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
from UM.i18n import i18nCatalog
|
||||
from UM.Scene.Platform import Platform
|
||||
from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
|
||||
|
|
@ -22,11 +23,9 @@ from UM.View.GL.OpenGL import OpenGL
|
|||
catalog = i18nCatalog("cura")
|
||||
|
||||
import numpy
|
||||
import copy
|
||||
import math
|
||||
|
||||
import UM.Settings.ContainerRegistry
|
||||
|
||||
from typing import List
|
||||
|
||||
# Setting for clearance around the prime
|
||||
PRIME_CLEARANCE = 6.5
|
||||
|
|
@ -70,6 +69,7 @@ class BuildVolume(SceneNode):
|
|||
self._volume_aabb = None
|
||||
|
||||
self._raft_thickness = 0.0
|
||||
self._extra_z_clearance = 0.0
|
||||
self._adhesion_type = None
|
||||
self._platform = Platform(self)
|
||||
|
||||
|
|
@ -111,10 +111,11 @@ class BuildVolume(SceneNode):
|
|||
|
||||
def _onChangeTimerFinished(self):
|
||||
root = Application.getInstance().getController().getScene().getRoot()
|
||||
new_scene_objects = set(node for node in BreadthFirstIterator(root) if node.getMeshData() and type(node) is SceneNode)
|
||||
new_scene_objects = set(node for node in BreadthFirstIterator(root) if node.callDecoration("isSliceable"))
|
||||
if new_scene_objects != self._scene_objects:
|
||||
for node in new_scene_objects - self._scene_objects: #Nodes that were added to the scene.
|
||||
node.decoratorsChanged.connect(self._onNodeDecoratorChanged)
|
||||
self._updateNodeListeners(node)
|
||||
node.decoratorsChanged.connect(self._updateNodeListeners) # Make sure that decoration changes afterwards also receive the same treatment
|
||||
for node in self._scene_objects - new_scene_objects: #Nodes that were removed from the scene.
|
||||
per_mesh_stack = node.callDecoration("getStack")
|
||||
if per_mesh_stack:
|
||||
|
|
@ -122,7 +123,7 @@ class BuildVolume(SceneNode):
|
|||
active_extruder_changed = node.callDecoration("getActiveExtruderChangedSignal")
|
||||
if active_extruder_changed is not None:
|
||||
node.callDecoration("getActiveExtruderChangedSignal").disconnect(self._updateDisallowedAreasAndRebuild)
|
||||
node.decoratorsChanged.disconnect(self._onNodeDecoratorChanged)
|
||||
node.decoratorsChanged.disconnect(self._updateNodeListeners)
|
||||
|
||||
self._scene_objects = new_scene_objects
|
||||
self._onSettingPropertyChanged("print_sequence", "value") # Create fake event, so right settings are triggered.
|
||||
|
|
@ -130,7 +131,7 @@ class BuildVolume(SceneNode):
|
|||
## Updates the listeners that listen for changes in per-mesh stacks.
|
||||
#
|
||||
# \param node The node for which the decorators changed.
|
||||
def _onNodeDecoratorChanged(self, node):
|
||||
def _updateNodeListeners(self, node: SceneNode):
|
||||
per_mesh_stack = node.callDecoration("getStack")
|
||||
if per_mesh_stack:
|
||||
per_mesh_stack.propertyChanged.connect(self._onSettingPropertyChanged)
|
||||
|
|
@ -140,21 +141,25 @@ class BuildVolume(SceneNode):
|
|||
self._updateDisallowedAreasAndRebuild()
|
||||
|
||||
def setWidth(self, width):
|
||||
if width: self._width = width
|
||||
if width is not None:
|
||||
self._width = width
|
||||
|
||||
def setHeight(self, height):
|
||||
if height: self._height = height
|
||||
if height is not None:
|
||||
self._height = height
|
||||
|
||||
def setDepth(self, depth):
|
||||
if depth: self._depth = depth
|
||||
if depth is not None:
|
||||
self._depth = depth
|
||||
|
||||
def setShape(self, shape):
|
||||
if shape: self._shape = shape
|
||||
def setShape(self, shape: str):
|
||||
if shape:
|
||||
self._shape = shape
|
||||
|
||||
def getDisallowedAreas(self):
|
||||
def getDisallowedAreas(self) -> List[Polygon]:
|
||||
return self._disallowed_areas
|
||||
|
||||
def setDisallowedAreas(self, areas):
|
||||
def setDisallowedAreas(self, areas: List[Polygon]):
|
||||
self._disallowed_areas = areas
|
||||
|
||||
def render(self, renderer):
|
||||
|
|
@ -180,6 +185,53 @@ class BuildVolume(SceneNode):
|
|||
|
||||
return True
|
||||
|
||||
## For every sliceable node, update node._outside_buildarea
|
||||
#
|
||||
def updateNodeBoundaryCheck(self):
|
||||
root = Application.getInstance().getController().getScene().getRoot()
|
||||
nodes = list(BreadthFirstIterator(root))
|
||||
group_nodes = []
|
||||
|
||||
build_volume_bounding_box = self.getBoundingBox()
|
||||
if build_volume_bounding_box:
|
||||
# It's over 9000!
|
||||
build_volume_bounding_box = build_volume_bounding_box.set(bottom=-9001)
|
||||
else:
|
||||
# No bounding box. This is triggered when running Cura from command line with a model for the first time
|
||||
# In that situation there is a model, but no machine (and therefore no build volume.
|
||||
return
|
||||
|
||||
for node in nodes:
|
||||
# Need to check group nodes later
|
||||
if node.callDecoration("isGroup"):
|
||||
group_nodes.append(node) # Keep list of affected group_nodes
|
||||
|
||||
if node.callDecoration("isSliceable") or node.callDecoration("isGroup"):
|
||||
node._outside_buildarea = False
|
||||
bbox = node.getBoundingBox()
|
||||
|
||||
# Mark the node as outside the build volume if the bounding box test fails.
|
||||
if build_volume_bounding_box.intersectsBox(bbox) != AxisAlignedBox.IntersectionResult.FullIntersection:
|
||||
node._outside_buildarea = True
|
||||
continue
|
||||
|
||||
convex_hull = node.callDecoration("getConvexHull")
|
||||
if convex_hull:
|
||||
if not convex_hull.isValid():
|
||||
return
|
||||
# Check for collisions between disallowed areas and the object
|
||||
for area in self.getDisallowedAreas():
|
||||
overlap = convex_hull.intersectsPolygon(area)
|
||||
if overlap is None:
|
||||
continue
|
||||
node._outside_buildarea = True
|
||||
continue
|
||||
|
||||
# Group nodes should override the _outside_buildarea property of their children.
|
||||
for group_node in group_nodes:
|
||||
for child_node in group_node.getAllChildren():
|
||||
child_node._outside_buildarea = group_node._outside_buildarea
|
||||
|
||||
## Recalculates the build volume & disallowed areas.
|
||||
def rebuild(self):
|
||||
if not self._width or not self._height or not self._depth:
|
||||
|
|
@ -349,7 +401,7 @@ class BuildVolume(SceneNode):
|
|||
|
||||
self._volume_aabb = AxisAlignedBox(
|
||||
minimum = Vector(min_w, min_h - 1.0, min_d),
|
||||
maximum = Vector(max_w, max_h - self._raft_thickness, max_d))
|
||||
maximum = Vector(max_w, max_h - self._raft_thickness - self._extra_z_clearance, max_d))
|
||||
|
||||
bed_adhesion_size = self._getEdgeDisallowedSize()
|
||||
|
||||
|
|
@ -358,15 +410,17 @@ class BuildVolume(SceneNode):
|
|||
# The +1 and -1 is added as there is always a bit of extra room required to work properly.
|
||||
scale_to_max_bounds = AxisAlignedBox(
|
||||
minimum = Vector(min_w + bed_adhesion_size + 1, min_h, min_d + disallowed_area_size - bed_adhesion_size + 1),
|
||||
maximum = Vector(max_w - bed_adhesion_size - 1, max_h - self._raft_thickness, max_d - disallowed_area_size + bed_adhesion_size - 1)
|
||||
maximum = Vector(max_w - bed_adhesion_size - 1, max_h - self._raft_thickness - self._extra_z_clearance, max_d - disallowed_area_size + bed_adhesion_size - 1)
|
||||
)
|
||||
|
||||
Application.getInstance().getController().getScene()._maximum_bounds = scale_to_max_bounds
|
||||
|
||||
def getBoundingBox(self):
|
||||
self.updateNodeBoundaryCheck()
|
||||
|
||||
def getBoundingBox(self) -> AxisAlignedBox:
|
||||
return self._volume_aabb
|
||||
|
||||
def getRaftThickness(self):
|
||||
def getRaftThickness(self) -> float:
|
||||
return self._raft_thickness
|
||||
|
||||
def _updateRaftThickness(self):
|
||||
|
|
@ -386,6 +440,23 @@ class BuildVolume(SceneNode):
|
|||
self.setPosition(Vector(0, -self._raft_thickness, 0), SceneNode.TransformSpace.World)
|
||||
self.raftThicknessChanged.emit()
|
||||
|
||||
def _updateExtraZClearance(self) -> None:
|
||||
extra_z = 0.0
|
||||
extruders = ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())
|
||||
use_extruders = False
|
||||
for extruder in extruders:
|
||||
if extruder.getProperty("retraction_hop_enabled", "value"):
|
||||
retraction_hop = extruder.getProperty("retraction_hop", "value")
|
||||
if extra_z is None or retraction_hop > extra_z:
|
||||
extra_z = retraction_hop
|
||||
use_extruders = True
|
||||
if not use_extruders:
|
||||
# If no extruders, take global value.
|
||||
if self._global_container_stack.getProperty("retraction_hop_enabled", "value"):
|
||||
extra_z = self._global_container_stack.getProperty("retraction_hop", "value")
|
||||
if extra_z != self._extra_z_clearance:
|
||||
self._extra_z_clearance = extra_z
|
||||
|
||||
## Update the build volume visualization
|
||||
def _onStackChanged(self):
|
||||
if self._global_container_stack:
|
||||
|
|
@ -426,7 +497,7 @@ class BuildVolume(SceneNode):
|
|||
self._engine_ready = True
|
||||
self.rebuild()
|
||||
|
||||
def _onSettingPropertyChanged(self, setting_key, property_name):
|
||||
def _onSettingPropertyChanged(self, setting_key: str, property_name: str):
|
||||
if property_name != "value":
|
||||
return
|
||||
|
||||
|
|
@ -452,10 +523,14 @@ class BuildVolume(SceneNode):
|
|||
self._updateRaftThickness()
|
||||
rebuild_me = True
|
||||
|
||||
if setting_key in self._extra_z_settings:
|
||||
self._updateExtraZClearance()
|
||||
rebuild_me = True
|
||||
|
||||
if rebuild_me:
|
||||
self.rebuild()
|
||||
|
||||
def hasErrors(self):
|
||||
def hasErrors(self) -> bool:
|
||||
return self._has_errors
|
||||
|
||||
## Calls _updateDisallowedAreas and makes sure the changes appear in the
|
||||
|
|
@ -609,11 +684,12 @@ class BuildVolume(SceneNode):
|
|||
|
||||
if not self._global_container_stack.getProperty("machine_center_is_zero", "value"):
|
||||
prime_x = prime_x - machine_width / 2 #Offset by half machine_width and _depth to put the origin in the front-left.
|
||||
prime_y = prime_x + machine_depth / 2
|
||||
prime_y = prime_y + machine_depth / 2
|
||||
|
||||
prime_polygon = Polygon.approximatedCircle(PRIME_CLEARANCE)
|
||||
prime_polygon = prime_polygon.translate(prime_x, prime_y)
|
||||
prime_polygon = prime_polygon.getMinkowskiHull(Polygon.approximatedCircle(border_size))
|
||||
|
||||
prime_polygon = prime_polygon.translate(prime_x, prime_y)
|
||||
result[extruder.getId()] = [prime_polygon]
|
||||
|
||||
return result
|
||||
|
|
@ -796,7 +872,7 @@ class BuildVolume(SceneNode):
|
|||
stack = self._global_container_stack
|
||||
else:
|
||||
extruder_stack_id = ExtruderManager.getInstance().extruderIds[str(extruder_index)]
|
||||
stack = UM.Settings.ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
|
||||
stack = ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
|
||||
|
||||
value = stack.getProperty(setting_key, property)
|
||||
setting_type = stack.getProperty(setting_key, "type")
|
||||
|
|
@ -874,6 +950,7 @@ class BuildVolume(SceneNode):
|
|||
|
||||
_skirt_settings = ["adhesion_type", "skirt_gap", "skirt_line_count", "skirt_brim_line_width", "brim_width", "brim_line_count", "raft_margin", "draft_shield_enabled", "draft_shield_dist"]
|
||||
_raft_settings = ["adhesion_type", "raft_base_thickness", "raft_interface_thickness", "raft_surface_layers", "raft_surface_thickness", "raft_airgap"]
|
||||
_extra_z_settings = ["retraction_hop_enabled", "retraction_hop"]
|
||||
_prime_settings = ["extruder_prime_pos_x", "extruder_prime_pos_y", "extruder_prime_pos_z"]
|
||||
_tower_settings = ["prime_tower_enable", "prime_tower_size", "prime_tower_position_x", "prime_tower_position_y"]
|
||||
_ooze_shield_settings = ["ooze_shield_enabled", "ooze_shield_dist"]
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ from PyQt5.QtGui import QVector3D
|
|||
|
||||
from UM.Math.Vector import Vector
|
||||
|
||||
|
||||
class CameraAnimation(QVariantAnimation):
|
||||
def __init__(self, parent = None):
|
||||
super().__init__(parent)
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
# Copyright (c) 2016 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
from UM.Scene.SceneNodeDecorator import SceneNodeDecorator
|
||||
from UM.Application import Application
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
from UM.Math.Polygon import Polygon
|
||||
from . import ConvexHullNode
|
||||
from UM.Scene.SceneNodeDecorator import SceneNodeDecorator
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
|
||||
import UM.Settings.ContainerRegistry
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
from . import ConvexHullNode
|
||||
|
||||
import numpy
|
||||
|
||||
|
|
@ -59,7 +59,8 @@ class ConvexHullDecorator(SceneNodeDecorator):
|
|||
hull = self._compute2DConvexHull()
|
||||
|
||||
if self._global_stack and self._node:
|
||||
if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" and not self._node.getParent().callDecoration("isGroup"):
|
||||
# Parent can be None if node is just loaded.
|
||||
if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" and (self._node.getParent() is None or not self._node.getParent().callDecoration("isGroup")):
|
||||
hull = hull.getMinkowskiHull(Polygon(numpy.array(self._global_stack.getProperty("machine_head_polygon", "value"), numpy.float32)))
|
||||
hull = self._add2DAdhesionMargin(hull)
|
||||
return hull
|
||||
|
|
@ -79,7 +80,7 @@ class ConvexHullDecorator(SceneNodeDecorator):
|
|||
return None
|
||||
|
||||
if self._global_stack:
|
||||
if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" and not self._node.getParent().callDecoration("isGroup"):
|
||||
if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" and (self._node.getParent() is None or not self._node.getParent().callDecoration("isGroup")):
|
||||
head_with_fans = self._compute2DConvexHeadMin()
|
||||
head_with_fans_with_adhesion_margin = self._add2DAdhesionMargin(head_with_fans)
|
||||
return head_with_fans_with_adhesion_margin
|
||||
|
|
@ -93,8 +94,7 @@ class ConvexHullDecorator(SceneNodeDecorator):
|
|||
return None
|
||||
|
||||
if self._global_stack:
|
||||
if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" and not self._node.getParent().callDecoration("isGroup"):
|
||||
|
||||
if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" and (self._node.getParent() is None or not self._node.getParent().callDecoration("isGroup")):
|
||||
# Printing one at a time and it's not an object in a group
|
||||
return self._compute2DConvexHull()
|
||||
return None
|
||||
|
|
@ -197,7 +197,7 @@ class ConvexHullDecorator(SceneNodeDecorator):
|
|||
|
||||
hull = Polygon(vertex_data)
|
||||
|
||||
if len(vertex_data) >= 4:
|
||||
if len(vertex_data) >= 3:
|
||||
convex_hull = hull.getConvexHull()
|
||||
offset_hull = self._offsetHull(convex_hull)
|
||||
else:
|
||||
|
|
@ -253,21 +253,25 @@ class ConvexHullDecorator(SceneNodeDecorator):
|
|||
|
||||
## Offset the convex hull with settings that influence the collision area.
|
||||
#
|
||||
# This also applies a minimum offset of 0.5mm, because of edge cases due
|
||||
# to the rounding we apply.
|
||||
#
|
||||
# \param convex_hull Polygon of the original convex hull.
|
||||
# \return New Polygon instance that is offset with everything that
|
||||
# influences the collision area.
|
||||
def _offsetHull(self, convex_hull):
|
||||
horizontal_expansion = max(0.5, self._getSettingProperty("xy_offset", "value"))
|
||||
expansion_polygon = Polygon(numpy.array([
|
||||
[-horizontal_expansion, -horizontal_expansion],
|
||||
[-horizontal_expansion, horizontal_expansion],
|
||||
[horizontal_expansion, horizontal_expansion],
|
||||
[horizontal_expansion, -horizontal_expansion]
|
||||
], numpy.float32))
|
||||
return convex_hull.getMinkowskiHull(expansion_polygon)
|
||||
horizontal_expansion = self._getSettingProperty("xy_offset", "value")
|
||||
mold_width = 0
|
||||
if self._getSettingProperty("mold_enabled", "value"):
|
||||
mold_width = self._getSettingProperty("mold_width", "value")
|
||||
hull_offset = horizontal_expansion + mold_width
|
||||
if hull_offset != 0:
|
||||
expansion_polygon = Polygon(numpy.array([
|
||||
[-hull_offset, -hull_offset],
|
||||
[-hull_offset, hull_offset],
|
||||
[hull_offset, hull_offset],
|
||||
[hull_offset, -hull_offset]
|
||||
], numpy.float32))
|
||||
return convex_hull.getMinkowskiHull(expansion_polygon)
|
||||
else:
|
||||
return convex_hull
|
||||
|
||||
def _onChanged(self, *args):
|
||||
self._raft_thickness = self._build_volume.getRaftThickness()
|
||||
|
|
@ -308,11 +312,11 @@ class ConvexHullDecorator(SceneNodeDecorator):
|
|||
extruder_stack_id = self._node.callDecoration("getActiveExtruder")
|
||||
if not extruder_stack_id: #Decoration doesn't exist.
|
||||
extruder_stack_id = ExtruderManager.getInstance().extruderIds["0"]
|
||||
extruder_stack = UM.Settings.ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
|
||||
extruder_stack = ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
|
||||
return extruder_stack.getProperty(setting_key, property)
|
||||
else: #Limit_to_extruder is set. Use that one.
|
||||
extruder_stack_id = ExtruderManager.getInstance().extruderIds[str(extruder_index)]
|
||||
stack = UM.Settings.ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
|
||||
stack = ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
|
||||
return stack.getProperty(setting_key, property)
|
||||
|
||||
## Returns true if node is a descendant or the same as the root node.
|
||||
|
|
@ -331,4 +335,4 @@ class ConvexHullDecorator(SceneNodeDecorator):
|
|||
## Settings that change the convex hull.
|
||||
#
|
||||
# If these settings change, the convex hull should be recalculated.
|
||||
_influencing_settings = {"xy_offset"}
|
||||
_influencing_settings = {"xy_offset", "mold_enabled", "mold_width"}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,10 @@ from UM.Mesh.MeshBuilder import MeshBuilder # To create a mesh to display the c
|
|||
|
||||
from UM.View.GL.OpenGL import OpenGL
|
||||
|
||||
|
||||
class ConvexHullNode(SceneNode):
|
||||
shader = None # To prevent the shader from being re-built over and over again, only load it once.
|
||||
|
||||
## Convex hull node is a special type of scene node that is used to display an area, to indicate the
|
||||
# location an object uses on the buildplate. This area (or area's in case of one at a time printing) is
|
||||
# then displayed as a transparent shadow. If the adhesion type is set to raft, the area is extruded
|
||||
|
|
@ -19,12 +22,10 @@ class ConvexHullNode(SceneNode):
|
|||
|
||||
self.setCalculateBoundingBox(False)
|
||||
|
||||
self._shader = None
|
||||
|
||||
self._original_parent = parent
|
||||
|
||||
# Color of the drawn convex hull
|
||||
self._color = None
|
||||
self._color = Color(*Application.getInstance().getTheme().getColor("convex_hull").getRgb())
|
||||
|
||||
# The y-coordinate of the convex hull mesh. Must not be 0, to prevent z-fighting.
|
||||
self._mesh_height = 0.1
|
||||
|
|
@ -59,22 +60,20 @@ class ConvexHullNode(SceneNode):
|
|||
return self._node
|
||||
|
||||
def render(self, renderer):
|
||||
if not self._shader:
|
||||
self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "transparent_object.shader"))
|
||||
self._shader.setUniformValue("u_diffuseColor", self._color)
|
||||
self._shader.setUniformValue("u_opacity", 0.6)
|
||||
if not ConvexHullNode.shader:
|
||||
ConvexHullNode.shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "transparent_object.shader"))
|
||||
ConvexHullNode.shader.setUniformValue("u_diffuseColor", self._color)
|
||||
ConvexHullNode.shader.setUniformValue("u_opacity", 0.6)
|
||||
|
||||
if self.getParent():
|
||||
if self.getMeshData():
|
||||
renderer.queueNode(self, transparent = True, shader = self._shader, backface_cull = True, sort = -8)
|
||||
renderer.queueNode(self, transparent = True, shader = ConvexHullNode.shader, backface_cull = True, sort = -8)
|
||||
if self._convex_hull_head_mesh:
|
||||
renderer.queueNode(self, shader = self._shader, transparent = True, mesh = self._convex_hull_head_mesh, backface_cull = True, sort = -8)
|
||||
renderer.queueNode(self, shader = ConvexHullNode.shader, transparent = True, mesh = self._convex_hull_head_mesh, backface_cull = True, sort = -8)
|
||||
|
||||
return True
|
||||
|
||||
def _onNodeDecoratorsChanged(self, node):
|
||||
self._color = Color(*Application.getInstance().getTheme().getColor("convex_hull").getRgb())
|
||||
|
||||
convex_hull_head = self._node.callDecoration("getConvexHullHead")
|
||||
if convex_hull_head:
|
||||
convex_hull_head_builder = MeshBuilder()
|
||||
|
|
|
|||
|
|
@ -12,10 +12,14 @@ from UM.Logger import Logger
|
|||
from UM.i18n import i18nCatalog
|
||||
catalog = i18nCatalog("cura")
|
||||
|
||||
try:
|
||||
from cura.CuraVersion import CuraDebugMode
|
||||
except ImportError:
|
||||
CuraDebugMode = False # [CodeStyle: Reflecting imported value]
|
||||
MYPY = False
|
||||
if MYPY:
|
||||
CuraDebugMode = False
|
||||
else:
|
||||
try:
|
||||
from cura.CuraVersion import CuraDebugMode
|
||||
except ImportError:
|
||||
CuraDebugMode = False # [CodeStyle: Reflecting imported value]
|
||||
|
||||
# List of exceptions that should be considered "fatal" and abort the program.
|
||||
# These are primarily some exception types that we simply cannot really recover from
|
||||
|
|
|
|||
442
cura/CuraApplication.py
Normal file → Executable file
442
cura/CuraApplication.py
Normal file → Executable file
|
|
@ -1,5 +1,7 @@
|
|||
# Copyright (c) 2015 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
from PyQt5.QtNetwork import QLocalServer
|
||||
from PyQt5.QtNetwork import QLocalSocket
|
||||
|
||||
from UM.Qt.QtApplication import QtApplication
|
||||
from UM.Scene.SceneNode import SceneNode
|
||||
|
|
@ -14,26 +16,39 @@ from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
|
|||
from UM.Mesh.ReadMeshJob import ReadMeshJob
|
||||
from UM.Logger import Logger
|
||||
from UM.Preferences import Preferences
|
||||
from UM.JobQueue import JobQueue
|
||||
from UM.SaveFile import SaveFile
|
||||
from UM.Scene.Selection import Selection
|
||||
from UM.Scene.GroupDecorator import GroupDecorator
|
||||
from UM.Settings.ContainerStack import ContainerStack
|
||||
from UM.Settings.InstanceContainer import InstanceContainer
|
||||
from UM.Settings.Validator import Validator
|
||||
from UM.Message import Message
|
||||
from UM.i18n import i18nCatalog
|
||||
from UM.Workspace.WorkspaceReader import WorkspaceReader
|
||||
from UM.Platform import Platform
|
||||
|
||||
from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
|
||||
from UM.Operations.RemoveSceneNodeOperation import RemoveSceneNodeOperation
|
||||
from UM.Operations.GroupedOperation import GroupedOperation
|
||||
from UM.Operations.SetTransformOperation import SetTransformOperation
|
||||
from UM.Operations.TranslateOperation import TranslateOperation
|
||||
from cura.Arrange import Arrange
|
||||
from cura.ShapeArray import ShapeArray
|
||||
from cura.ConvexHullDecorator import ConvexHullDecorator
|
||||
from cura.SetParentOperation import SetParentOperation
|
||||
from cura.SliceableObjectDecorator import SliceableObjectDecorator
|
||||
from cura.BlockSlicingDecorator import BlockSlicingDecorator
|
||||
|
||||
from cura.ArrangeObjectsJob import ArrangeObjectsJob
|
||||
from cura.MultiplyObjectsJob import MultiplyObjectsJob
|
||||
|
||||
from UM.Settings.SettingDefinition import SettingDefinition, DefinitionPropertyType
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
from UM.Settings.SettingFunction import SettingFunction
|
||||
from cura.Settings.MachineNameValidator import MachineNameValidator
|
||||
from cura.Settings.ProfilesModel import ProfilesModel
|
||||
from cura.Settings.QualityAndUserProfilesModel import QualityAndUserProfilesModel
|
||||
from cura.Settings.SettingInheritanceManager import SettingInheritanceManager
|
||||
from cura.Settings.UserProfilesModel import UserProfilesModel
|
||||
|
||||
from . import PlatformPhysics
|
||||
from . import BuildVolume
|
||||
|
|
@ -45,7 +60,14 @@ from . import CuraSplashScreen
|
|||
from . import CameraImageProvider
|
||||
from . import MachineActionManager
|
||||
|
||||
import cura.Settings
|
||||
from cura.Settings.MachineManager import MachineManager
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
from cura.Settings.UserChangesModel import UserChangesModel
|
||||
from cura.Settings.ExtrudersModel import ExtrudersModel
|
||||
from cura.Settings.ContainerSettingsModel import ContainerSettingsModel
|
||||
from cura.Settings.MaterialSettingsVisibilityHandler import MaterialSettingsVisibilityHandler
|
||||
from cura.Settings.QualitySettingsModel import QualitySettingsModel
|
||||
from cura.Settings.ContainerManager import ContainerManager
|
||||
|
||||
from PyQt5.QtCore import QUrl, pyqtSignal, pyqtProperty, QEvent, Q_ENUMS
|
||||
from UM.FlameProfiler import pyqtSlot
|
||||
|
|
@ -59,15 +81,19 @@ import numpy
|
|||
import copy
|
||||
import urllib.parse
|
||||
import os
|
||||
|
||||
import argparse
|
||||
import json
|
||||
|
||||
numpy.seterr(all="ignore")
|
||||
|
||||
try:
|
||||
from cura.CuraVersion import CuraVersion, CuraBuildType
|
||||
except ImportError:
|
||||
CuraVersion = "master" # [CodeStyle: Reflecting imported value]
|
||||
CuraBuildType = ""
|
||||
MYPY = False
|
||||
if not MYPY:
|
||||
try:
|
||||
from cura.CuraVersion import CuraVersion, CuraBuildType
|
||||
except ImportError:
|
||||
CuraVersion = "master" # [CodeStyle: Reflecting imported value]
|
||||
CuraBuildType = ""
|
||||
|
||||
|
||||
class CuraApplication(QtApplication):
|
||||
class ResourceTypes:
|
||||
|
|
@ -83,6 +109,10 @@ class CuraApplication(QtApplication):
|
|||
Q_ENUMS(ResourceTypes)
|
||||
|
||||
def __init__(self):
|
||||
# this list of dir names will be used by UM to detect an old cura directory
|
||||
for dir_name in ["extruders", "machine_instances", "materials", "plugins", "quality", "user", "variants"]:
|
||||
Resources.addExpectedDirNameInData(dir_name)
|
||||
|
||||
Resources.addSearchPath(os.path.join(QtApplication.getInstallPrefix(), "share", "cura", "resources"))
|
||||
if not hasattr(sys, "frozen"):
|
||||
Resources.addSearchPath(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "resources"))
|
||||
|
|
@ -107,9 +137,11 @@ class CuraApplication(QtApplication):
|
|||
|
||||
SettingDefinition.addSettingType("extruder", None, str, Validator)
|
||||
|
||||
SettingFunction.registerOperator("extruderValues", cura.Settings.ExtruderManager.getExtruderValues)
|
||||
SettingFunction.registerOperator("extruderValue", cura.Settings.ExtruderManager.getExtruderValue)
|
||||
SettingFunction.registerOperator("resolveOrValue", cura.Settings.ExtruderManager.getResolveOrValue)
|
||||
SettingDefinition.addSettingType("[int]", None, str, None)
|
||||
|
||||
SettingFunction.registerOperator("extruderValues", ExtruderManager.getExtruderValues)
|
||||
SettingFunction.registerOperator("extruderValue", ExtruderManager.getExtruderValue)
|
||||
SettingFunction.registerOperator("resolveOrValue", ExtruderManager.getResolveOrValue)
|
||||
|
||||
## Add the 4 types of profiles to storage.
|
||||
Resources.addStorageType(self.ResourceTypes.QualityInstanceContainer, "quality")
|
||||
|
|
@ -128,13 +160,14 @@ class CuraApplication(QtApplication):
|
|||
|
||||
## Initialise the version upgrade manager with Cura's storage paths.
|
||||
import UM.VersionUpgradeManager #Needs to be here to prevent circular dependencies.
|
||||
|
||||
UM.VersionUpgradeManager.VersionUpgradeManager.getInstance().setCurrentVersions(
|
||||
{
|
||||
("quality", UM.Settings.InstanceContainer.Version): (self.ResourceTypes.QualityInstanceContainer, "application/x-uranium-instancecontainer"),
|
||||
("machine_stack", UM.Settings.ContainerStack.Version): (self.ResourceTypes.MachineStack, "application/x-uranium-containerstack"),
|
||||
("extruder_train", UM.Settings.ContainerStack.Version): (self.ResourceTypes.ExtruderStack, "application/x-uranium-extruderstack"),
|
||||
("preferences", UM.Preferences.Version): (Resources.Preferences, "application/x-uranium-preferences"),
|
||||
("user", UM.Settings.InstanceContainer.Version): (self.ResourceTypes.UserInstanceContainer, "application/x-uranium-instancecontainer")
|
||||
("quality", InstanceContainer.Version): (self.ResourceTypes.QualityInstanceContainer, "application/x-uranium-instancecontainer"),
|
||||
("machine_stack", ContainerStack.Version): (self.ResourceTypes.MachineStack, "application/x-uranium-containerstack"),
|
||||
("extruder_train", ContainerStack.Version): (self.ResourceTypes.ExtruderStack, "application/x-uranium-extruderstack"),
|
||||
("preferences", Preferences.Version): (Resources.Preferences, "application/x-uranium-preferences"),
|
||||
("user", InstanceContainer.Version): (self.ResourceTypes.UserInstanceContainer, "application/x-uranium-instancecontainer")
|
||||
}
|
||||
)
|
||||
|
||||
|
|
@ -159,7 +192,10 @@ class CuraApplication(QtApplication):
|
|||
"SelectionTool",
|
||||
"CameraTool",
|
||||
"GCodeWriter",
|
||||
"LocalFileOutputDevice"
|
||||
"LocalFileOutputDevice",
|
||||
"TranslateTool",
|
||||
"FileLogger",
|
||||
"XmlMaterialProfile"
|
||||
])
|
||||
self._physics = None
|
||||
self._volume = None
|
||||
|
|
@ -177,7 +213,7 @@ class CuraApplication(QtApplication):
|
|||
|
||||
self._message_box_callback = None
|
||||
self._message_box_callback_arguments = []
|
||||
|
||||
self._preferred_mimetype = ""
|
||||
self._i18n_catalog = i18nCatalog("cura")
|
||||
|
||||
self.getController().getScene().sceneChanged.connect(self.updatePlatformActivity)
|
||||
|
|
@ -202,7 +238,7 @@ class CuraApplication(QtApplication):
|
|||
ContainerRegistry.getInstance().addContainer(empty_material_container)
|
||||
empty_quality_container = copy.deepcopy(empty_container)
|
||||
empty_quality_container._id = "empty_quality"
|
||||
empty_quality_container.setName("Not supported")
|
||||
empty_quality_container.setName("Not Supported")
|
||||
empty_quality_container.addMetaDataEntry("quality_type", "normal")
|
||||
empty_quality_container.addMetaDataEntry("type", "quality")
|
||||
ContainerRegistry.getInstance().addContainer(empty_quality_container)
|
||||
|
|
@ -215,7 +251,7 @@ class CuraApplication(QtApplication):
|
|||
ContainerRegistry.getInstance().load()
|
||||
|
||||
Preferences.getInstance().addPreference("cura/active_mode", "simple")
|
||||
Preferences.getInstance().addPreference("cura/recent_files", "")
|
||||
|
||||
Preferences.getInstance().addPreference("cura/categories_expanded", "")
|
||||
Preferences.getInstance().addPreference("cura/jobname_prefix", True)
|
||||
Preferences.getInstance().addPreference("view/center_on_select", False)
|
||||
|
|
@ -223,10 +259,14 @@ class CuraApplication(QtApplication):
|
|||
Preferences.getInstance().addPreference("mesh/scale_tiny_meshes", True)
|
||||
Preferences.getInstance().addPreference("cura/dialog_on_project_save", True)
|
||||
Preferences.getInstance().addPreference("cura/asked_dialog_on_project_save", False)
|
||||
Preferences.getInstance().addPreference("cura/choice_on_profile_override", "always_ask")
|
||||
Preferences.getInstance().addPreference("cura/choice_on_open_project", "always_ask")
|
||||
|
||||
Preferences.getInstance().addPreference("cura/currency", "€")
|
||||
Preferences.getInstance().addPreference("cura/material_settings", "{}")
|
||||
|
||||
Preferences.getInstance().addPreference("view/invert_zoom", False)
|
||||
|
||||
for key in [
|
||||
"dialog_load_path", # dialog_save_path is in LocalFileOutputDevicePlugin
|
||||
"dialog_profile_path",
|
||||
|
|
@ -287,17 +327,11 @@ class CuraApplication(QtApplication):
|
|||
experimental
|
||||
""".replace("\n", ";").replace(" ", ""))
|
||||
|
||||
JobQueue.getInstance().jobFinished.connect(self._onJobFinished)
|
||||
|
||||
self.applicationShuttingDown.connect(self.saveSettings)
|
||||
self.engineCreatedSignal.connect(self._onEngineCreated)
|
||||
self._recent_files = []
|
||||
files = Preferences.getInstance().getValue("cura/recent_files").split(";")
|
||||
for f in files:
|
||||
if not os.path.isfile(f):
|
||||
continue
|
||||
|
||||
self._recent_files.append(QUrl.fromLocalFile(f))
|
||||
self.globalContainerStackChanged.connect(self._onGlobalContainerChanged)
|
||||
self._onGlobalContainerChanged()
|
||||
|
||||
def _onEngineCreated(self):
|
||||
self._engine.addImageProvider("camera", CameraImageProvider.CameraImageProvider())
|
||||
|
|
@ -305,11 +339,35 @@ class CuraApplication(QtApplication):
|
|||
## A reusable dialogbox
|
||||
#
|
||||
showMessageBox = pyqtSignal(str, str, str, str, int, int, arguments = ["title", "text", "informativeText", "detailedText", "buttons", "icon"])
|
||||
|
||||
def messageBox(self, title, text, informativeText = "", detailedText = "", buttons = QMessageBox.Ok, icon = QMessageBox.NoIcon, callback = None, callback_arguments = []):
|
||||
self._message_box_callback = callback
|
||||
self._message_box_callback_arguments = callback_arguments
|
||||
self.showMessageBox.emit(title, text, informativeText, detailedText, buttons, icon)
|
||||
|
||||
showDiscardOrKeepProfileChanges = pyqtSignal()
|
||||
|
||||
def discardOrKeepProfileChanges(self):
|
||||
choice = Preferences.getInstance().getValue("cura/choice_on_profile_override")
|
||||
if choice == "always_discard":
|
||||
# don't show dialog and DISCARD the profile
|
||||
self.discardOrKeepProfileChangesClosed("discard")
|
||||
elif choice == "always_keep":
|
||||
# don't show dialog and KEEP the profile
|
||||
self.discardOrKeepProfileChangesClosed("keep")
|
||||
else:
|
||||
# ALWAYS ask whether to keep or discard the profile
|
||||
self.showDiscardOrKeepProfileChanges.emit()
|
||||
|
||||
@pyqtSlot(str)
|
||||
def discardOrKeepProfileChangesClosed(self, option):
|
||||
if option == "discard":
|
||||
global_stack = self.getGlobalContainerStack()
|
||||
for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
|
||||
extruder.getTop().clear()
|
||||
|
||||
global_stack.getTop().clear()
|
||||
|
||||
@pyqtSlot(int)
|
||||
def messageBoxClosed(self, button):
|
||||
if self._message_box_callback:
|
||||
|
|
@ -319,11 +377,6 @@ class CuraApplication(QtApplication):
|
|||
|
||||
showPrintMonitor = pyqtSignal(bool, arguments = ["show"])
|
||||
|
||||
def setViewLegendItems(self, items):
|
||||
self.viewLegendItemsChanged.emit(items)
|
||||
|
||||
viewLegendItemsChanged = pyqtSignal("QVariantList", arguments = ["items"])
|
||||
|
||||
## Cura has multiple locations where instance containers need to be saved, so we need to handle this differently.
|
||||
#
|
||||
# Note that the AutoSave plugin also calls this method.
|
||||
|
|
@ -400,7 +453,11 @@ class CuraApplication(QtApplication):
|
|||
|
||||
@pyqtSlot(str, str)
|
||||
def setDefaultPath(self, key, default_path):
|
||||
Preferences.getInstance().setValue("local_file/%s" % key, default_path)
|
||||
Preferences.getInstance().setValue("local_file/%s" % key, QUrl(default_path).toLocalFile())
|
||||
|
||||
@classmethod
|
||||
def getStaticVersion(cls):
|
||||
return CuraVersion
|
||||
|
||||
## Handle loading of all plugin types (and the backend explicitly)
|
||||
# \sa PluginRegistery
|
||||
|
|
@ -420,16 +477,111 @@ class CuraApplication(QtApplication):
|
|||
|
||||
self._plugins_loaded = True
|
||||
|
||||
@classmethod
|
||||
def addCommandLineOptions(self, parser):
|
||||
super().addCommandLineOptions(parser)
|
||||
parser.add_argument("file", nargs="*", help="Files to load after starting the application.")
|
||||
parser.add_argument("--single-instance", action="store_true", default=False)
|
||||
|
||||
# Set up a local socket server which listener which coordinates single instances Curas and accepts commands.
|
||||
def _setUpSingleInstanceServer(self):
|
||||
if self.getCommandLineOption("single_instance", False):
|
||||
self.__single_instance_server = QLocalServer()
|
||||
self.__single_instance_server.newConnection.connect(self._singleInstanceServerNewConnection)
|
||||
self.__single_instance_server.listen("ultimaker-cura")
|
||||
|
||||
def _singleInstanceServerNewConnection(self):
|
||||
Logger.log("i", "New connection recevied on our single-instance server")
|
||||
remote_cura_connection = self.__single_instance_server.nextPendingConnection()
|
||||
|
||||
if remote_cura_connection is not None:
|
||||
def readCommands():
|
||||
line = remote_cura_connection.readLine()
|
||||
while len(line) != 0: # There is also a .canReadLine()
|
||||
try:
|
||||
payload = json.loads(str(line, encoding="ASCII").strip())
|
||||
command = payload["command"]
|
||||
|
||||
# Command: Remove all models from the build plate.
|
||||
if command == "clear-all":
|
||||
self.deleteAll()
|
||||
|
||||
# Command: Load a model file
|
||||
elif command == "open":
|
||||
self._openFile(payload["filePath"])
|
||||
# WARNING ^ this method is async and we really should wait until
|
||||
# the file load is complete before processing more commands.
|
||||
|
||||
# Command: Activate the window and bring it to the top.
|
||||
elif command == "focus":
|
||||
# Operating systems these days prevent windows from moving around by themselves.
|
||||
# 'alert' or flashing the icon in the taskbar is the best thing we do now.
|
||||
self.getMainWindow().alert(0)
|
||||
|
||||
# Command: Close the socket connection. We're done.
|
||||
elif command == "close-connection":
|
||||
remote_cura_connection.close()
|
||||
|
||||
else:
|
||||
Logger.log("w", "Received an unrecognized command " + str(command))
|
||||
except json.decoder.JSONDecodeError as ex:
|
||||
Logger.log("w", "Unable to parse JSON command in _singleInstanceServerNewConnection(): " + repr(ex))
|
||||
line = remote_cura_connection.readLine()
|
||||
|
||||
remote_cura_connection.readyRead.connect(readCommands)
|
||||
|
||||
## Perform any checks before creating the main application.
|
||||
#
|
||||
# This should be called directly before creating an instance of CuraApplication.
|
||||
# \returns \type{bool} True if the whole Cura app should continue running.
|
||||
@classmethod
|
||||
def preStartUp(cls):
|
||||
# Peek the arguments and look for the 'single-instance' flag.
|
||||
parser = argparse.ArgumentParser(prog="cura") # pylint: disable=bad-whitespace
|
||||
CuraApplication.addCommandLineOptions(parser)
|
||||
parsed_command_line = vars(parser.parse_args())
|
||||
|
||||
if "single_instance" in parsed_command_line and parsed_command_line["single_instance"]:
|
||||
Logger.log("i", "Checking for the presence of an ready running Cura instance.")
|
||||
single_instance_socket = QLocalSocket()
|
||||
Logger.log("d", "preStartUp(): full server name: " + single_instance_socket.fullServerName())
|
||||
single_instance_socket.connectToServer("ultimaker-cura")
|
||||
single_instance_socket.waitForConnected()
|
||||
if single_instance_socket.state() == QLocalSocket.ConnectedState:
|
||||
Logger.log("i", "Connection has been made to the single-instance Cura socket.")
|
||||
|
||||
# Protocol is one line of JSON terminated with a carriage return.
|
||||
# "command" field is required and holds the name of the command to execute.
|
||||
# Other fields depend on the command.
|
||||
|
||||
payload = {"command": "clear-all"}
|
||||
single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
|
||||
|
||||
payload = {"command": "focus"}
|
||||
single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
|
||||
|
||||
if len(parsed_command_line["file"]) != 0:
|
||||
for filename in parsed_command_line["file"]:
|
||||
payload = {"command": "open", "filePath": filename}
|
||||
single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
|
||||
|
||||
payload = {"command": "close-connection"}
|
||||
single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ASCII"))
|
||||
|
||||
single_instance_socket.flush()
|
||||
single_instance_socket.waitForDisconnected()
|
||||
return False
|
||||
return True
|
||||
|
||||
def run(self):
|
||||
self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Setting up scene..."))
|
||||
|
||||
self._setUpSingleInstanceServer()
|
||||
|
||||
controller = self.getController()
|
||||
|
||||
controller.setActiveView("SolidView")
|
||||
|
||||
controller.setCameraTool("CameraTool")
|
||||
controller.setSelectionTool("SelectionTool")
|
||||
|
||||
|
|
@ -444,6 +596,9 @@ class CuraApplication(QtApplication):
|
|||
# The platform is a child of BuildVolume
|
||||
self._volume = BuildVolume.BuildVolume(root)
|
||||
|
||||
# Set the build volume of the arranger to the used build volume
|
||||
Arrange.build_volume = self._volume
|
||||
|
||||
self.getRenderer().setBackgroundColor(QColor(245, 245, 245))
|
||||
|
||||
self._physics = PlatformPhysics.PlatformPhysics(controller, self._volume)
|
||||
|
|
@ -462,9 +617,11 @@ class CuraApplication(QtApplication):
|
|||
self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading interface..."))
|
||||
|
||||
# Initialise extruder so as to listen to global container stack changes before the first global container stack is set.
|
||||
cura.Settings.ExtruderManager.getInstance()
|
||||
qmlRegisterSingletonType(cura.Settings.MachineManager, "Cura", 1, 0, "MachineManager", self.getMachineManager)
|
||||
qmlRegisterSingletonType(cura.Settings.SettingInheritanceManager, "Cura", 1, 0, "SettingInheritanceManager", self.getSettingInheritanceManager)
|
||||
ExtruderManager.getInstance()
|
||||
qmlRegisterSingletonType(MachineManager, "Cura", 1, 0, "MachineManager", self.getMachineManager)
|
||||
qmlRegisterSingletonType(SettingInheritanceManager, "Cura", 1, 0, "SettingInheritanceManager",
|
||||
self.getSettingInheritanceManager)
|
||||
|
||||
qmlRegisterSingletonType(MachineActionManager.MachineActionManager, "Cura", 1, 0, "MachineActionManager", self.getMachineActionManager)
|
||||
self.setMainQml(Resources.getPath(self.ResourceTypes.QmlFiles, "Cura.qml"))
|
||||
self._qml_import_paths.append(Resources.getPath(self.ResourceTypes.QmlFiles))
|
||||
|
|
@ -484,12 +641,12 @@ class CuraApplication(QtApplication):
|
|||
|
||||
def getMachineManager(self, *args):
|
||||
if self._machine_manager is None:
|
||||
self._machine_manager = cura.Settings.MachineManager.createMachineManager()
|
||||
self._machine_manager = MachineManager.createMachineManager()
|
||||
return self._machine_manager
|
||||
|
||||
def getSettingInheritanceManager(self, *args):
|
||||
if self._setting_inheritance_manager is None:
|
||||
self._setting_inheritance_manager = cura.Settings.SettingInheritanceManager.createSettingInheritanceManager()
|
||||
self._setting_inheritance_manager = SettingInheritanceManager.createSettingInheritanceManager()
|
||||
return self._setting_inheritance_manager
|
||||
|
||||
## Get the machine action manager
|
||||
|
|
@ -516,6 +673,7 @@ class CuraApplication(QtApplication):
|
|||
#
|
||||
# \param engine The QML engine.
|
||||
def registerObjects(self, engine):
|
||||
super().registerObjects(engine)
|
||||
engine.rootContext().setContextProperty("Printer", self)
|
||||
engine.rootContext().setContextProperty("CuraApplication", self)
|
||||
self._print_information = PrintInformation.PrintInformation()
|
||||
|
|
@ -525,29 +683,34 @@ class CuraApplication(QtApplication):
|
|||
|
||||
qmlRegisterUncreatableType(CuraApplication, "Cura", 1, 0, "ResourceTypes", "Just an Enum type")
|
||||
|
||||
qmlRegisterType(cura.Settings.ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")
|
||||
qmlRegisterType(ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")
|
||||
|
||||
qmlRegisterType(cura.Settings.ContainerSettingsModel, "Cura", 1, 0, "ContainerSettingsModel")
|
||||
qmlRegisterSingletonType(cura.Settings.ProfilesModel, "Cura", 1, 0, "ProfilesModel", cura.Settings.ProfilesModel.createProfilesModel)
|
||||
qmlRegisterType(cura.Settings.QualityAndUserProfilesModel, "Cura", 1, 0, "QualityAndUserProfilesModel")
|
||||
qmlRegisterType(cura.Settings.UserProfilesModel, "Cura", 1, 0, "UserProfilesModel")
|
||||
qmlRegisterType(cura.Settings.MaterialSettingsVisibilityHandler, "Cura", 1, 0, "MaterialSettingsVisibilityHandler")
|
||||
qmlRegisterType(cura.Settings.QualitySettingsModel, "Cura", 1, 0, "QualitySettingsModel")
|
||||
qmlRegisterType(cura.Settings.MachineNameValidator, "Cura", 1, 0, "MachineNameValidator")
|
||||
qmlRegisterType(ContainerSettingsModel, "Cura", 1, 0, "ContainerSettingsModel")
|
||||
qmlRegisterSingletonType(ProfilesModel, "Cura", 1, 0, "ProfilesModel", ProfilesModel.createProfilesModel)
|
||||
qmlRegisterType(QualityAndUserProfilesModel, "Cura", 1, 0, "QualityAndUserProfilesModel")
|
||||
qmlRegisterType(UserProfilesModel, "Cura", 1, 0, "UserProfilesModel")
|
||||
qmlRegisterType(MaterialSettingsVisibilityHandler, "Cura", 1, 0, "MaterialSettingsVisibilityHandler")
|
||||
qmlRegisterType(QualitySettingsModel, "Cura", 1, 0, "QualitySettingsModel")
|
||||
qmlRegisterType(MachineNameValidator, "Cura", 1, 0, "MachineNameValidator")
|
||||
qmlRegisterType(UserChangesModel, "Cura", 1, 1, "UserChangesModel")
|
||||
|
||||
qmlRegisterSingletonType(cura.Settings.ContainerManager, "Cura", 1, 0, "ContainerManager", cura.Settings.ContainerManager.createContainerManager)
|
||||
qmlRegisterSingletonType(ContainerManager, "Cura", 1, 0, "ContainerManager", ContainerManager.createContainerManager)
|
||||
|
||||
# As of Qt5.7, it is necessary to get rid of any ".." in the path for the singleton to work.
|
||||
actions_url = QUrl.fromLocalFile(os.path.abspath(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles, "Actions.qml")))
|
||||
qmlRegisterSingletonType(actions_url, "Cura", 1, 0, "Actions")
|
||||
|
||||
engine.rootContext().setContextProperty("ExtruderManager", cura.Settings.ExtruderManager.getInstance())
|
||||
engine.rootContext().setContextProperty("ExtruderManager", ExtruderManager.getInstance())
|
||||
|
||||
for path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.QmlFiles):
|
||||
type_name = os.path.splitext(os.path.basename(path))[0]
|
||||
if type_name in ("Cura", "Actions"):
|
||||
continue
|
||||
|
||||
# Ignore anything that is not a QML file.
|
||||
if not path.endswith(".qml"):
|
||||
continue
|
||||
|
||||
qmlRegisterType(QUrl.fromLocalFile(path), "Cura", 1, 0, type_name)
|
||||
|
||||
def onSelectionChanged(self):
|
||||
|
|
@ -566,7 +729,9 @@ class CuraApplication(QtApplication):
|
|||
else:
|
||||
# Default
|
||||
self.getController().setActiveTool("TranslateTool")
|
||||
if Preferences.getInstance().getValue("view/center_on_select"):
|
||||
|
||||
# Hack: QVector bindings are broken on PyQt 5.7.1 on Windows. This disables it being called at all.
|
||||
if Preferences.getInstance().getValue("view/center_on_select") and not Platform.isWindows():
|
||||
self._center_after_select = True
|
||||
else:
|
||||
if self.getController().getActiveTool():
|
||||
|
|
@ -574,20 +739,36 @@ class CuraApplication(QtApplication):
|
|||
self.getController().setActiveTool(None)
|
||||
|
||||
def _onToolOperationStopped(self, event):
|
||||
if self._center_after_select:
|
||||
if self._center_after_select and Selection.getSelectedObject(0) is not None:
|
||||
self._center_after_select = False
|
||||
self._camera_animation.setStart(self.getController().getTool("CameraTool").getOrigin())
|
||||
self._camera_animation.setTarget(Selection.getSelectedObject(0).getWorldPosition())
|
||||
self._camera_animation.start()
|
||||
|
||||
def _onGlobalContainerChanged(self):
|
||||
if self._global_container_stack is not None:
|
||||
machine_file_formats = [file_type.strip() for file_type in self._global_container_stack.getMetaDataEntry("file_formats").split(";")]
|
||||
new_preferred_mimetype = ""
|
||||
if machine_file_formats:
|
||||
new_preferred_mimetype = machine_file_formats[0]
|
||||
|
||||
if new_preferred_mimetype != self._preferred_mimetype:
|
||||
self._preferred_mimetype = new_preferred_mimetype
|
||||
self.preferredOutputMimetypeChanged.emit()
|
||||
|
||||
requestAddPrinter = pyqtSignal()
|
||||
activityChanged = pyqtSignal()
|
||||
sceneBoundingBoxChanged = pyqtSignal()
|
||||
preferredOutputMimetypeChanged = pyqtSignal()
|
||||
|
||||
@pyqtProperty(bool, notify = activityChanged)
|
||||
def getPlatformActivity(self):
|
||||
def platformActivity(self):
|
||||
return self._platform_activity
|
||||
|
||||
@pyqtProperty(str, notify=preferredOutputMimetypeChanged)
|
||||
def preferredOutputMimetype(self):
|
||||
return self._preferred_mimetype
|
||||
|
||||
@pyqtProperty(str, notify = sceneBoundingBoxChanged)
|
||||
def getSceneBoundingBoxString(self):
|
||||
return self._i18n_catalog.i18nc("@info", "%(width).1f x %(depth).1f x %(height).1f mm") % {'width' : self._scene_bounding_box.width.item(), 'depth': self._scene_bounding_box.depth.item(), 'height' : self._scene_bounding_box.height.item()}
|
||||
|
|
@ -669,24 +850,14 @@ class CuraApplication(QtApplication):
|
|||
op.push()
|
||||
|
||||
## Create a number of copies of existing object.
|
||||
# \param object_id
|
||||
# \param count number of copies
|
||||
# \param min_offset minimum offset to other objects.
|
||||
@pyqtSlot("quint64", int)
|
||||
def multiplyObject(self, object_id, count):
|
||||
node = self.getController().getScene().findObject(object_id)
|
||||
|
||||
if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
|
||||
node = Selection.getSelectedObject(0)
|
||||
|
||||
if node:
|
||||
current_node = node
|
||||
# Find the topmost group
|
||||
while current_node.getParent() and current_node.getParent().callDecoration("isGroup"):
|
||||
current_node = current_node.getParent()
|
||||
|
||||
op = GroupedOperation()
|
||||
for _ in range(count):
|
||||
new_node = copy.deepcopy(current_node)
|
||||
op.addOperation(AddSceneNodeOperation(new_node, current_node.getParent()))
|
||||
op.push()
|
||||
def multiplyObject(self, object_id, count, min_offset = 8):
|
||||
job = MultiplyObjectsJob(object_id, count, min_offset)
|
||||
job.start()
|
||||
return
|
||||
|
||||
## Center object on platform.
|
||||
@pyqtSlot("quint64")
|
||||
|
|
@ -804,6 +975,52 @@ class CuraApplication(QtApplication):
|
|||
op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0), Quaternion(), Vector(1, 1, 1)))
|
||||
op.push()
|
||||
|
||||
## Arrange all objects.
|
||||
@pyqtSlot()
|
||||
def arrangeAll(self):
|
||||
nodes = []
|
||||
for node in DepthFirstIterator(self.getController().getScene().getRoot()):
|
||||
if type(node) is not SceneNode:
|
||||
continue
|
||||
if not node.getMeshData() and not node.callDecoration("isGroup"):
|
||||
continue # Node that doesnt have a mesh and is not a group.
|
||||
if node.getParent() and node.getParent().callDecoration("isGroup"):
|
||||
continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
|
||||
if not node.isSelectable():
|
||||
continue # i.e. node with layer data
|
||||
# Skip nodes that are too big
|
||||
if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
|
||||
nodes.append(node)
|
||||
self.arrange(nodes, fixed_nodes = [])
|
||||
|
||||
## Arrange Selection
|
||||
@pyqtSlot()
|
||||
def arrangeSelection(self):
|
||||
nodes = Selection.getAllSelectedObjects()
|
||||
|
||||
# What nodes are on the build plate and are not being moved
|
||||
fixed_nodes = []
|
||||
for node in DepthFirstIterator(self.getController().getScene().getRoot()):
|
||||
if type(node) is not SceneNode:
|
||||
continue
|
||||
if not node.getMeshData() and not node.callDecoration("isGroup"):
|
||||
continue # Node that doesnt have a mesh and is not a group.
|
||||
if node.getParent() and node.getParent().callDecoration("isGroup"):
|
||||
continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
|
||||
if not node.isSelectable():
|
||||
continue # i.e. node with layer data
|
||||
if node in nodes: # exclude selected node from fixed_nodes
|
||||
continue
|
||||
fixed_nodes.append(node)
|
||||
self.arrange(nodes, fixed_nodes)
|
||||
|
||||
## Arrange a set of nodes given a set of fixed nodes
|
||||
# \param nodes nodes that we have to place
|
||||
# \param fixed_nodes nodes that are placed in the arranger before finding spots for nodes
|
||||
def arrange(self, nodes, fixed_nodes):
|
||||
job = ArrangeObjectsJob(nodes, fixed_nodes)
|
||||
job.start()
|
||||
|
||||
## Reload all mesh data on the screen from file.
|
||||
@pyqtSlot()
|
||||
def reloadAll(self):
|
||||
|
|
@ -839,12 +1056,6 @@ class CuraApplication(QtApplication):
|
|||
|
||||
return log
|
||||
|
||||
recentFilesChanged = pyqtSignal()
|
||||
|
||||
@pyqtProperty("QVariantList", notify = recentFilesChanged)
|
||||
def recentFiles(self):
|
||||
return self._recent_files
|
||||
|
||||
@pyqtSlot("QStringList")
|
||||
def setExpandedCategories(self, categories):
|
||||
categories = list(set(categories))
|
||||
|
|
@ -880,7 +1091,9 @@ class CuraApplication(QtApplication):
|
|||
transformation.setTranslation(zero_translation)
|
||||
transformed_mesh = mesh.getTransformed(transformation)
|
||||
center = transformed_mesh.getCenterPosition()
|
||||
object_centers.append(center)
|
||||
if center is not None:
|
||||
object_centers.append(center)
|
||||
|
||||
if object_centers and len(object_centers) > 0:
|
||||
middle_x = sum([v.x for v in object_centers]) / len(object_centers)
|
||||
middle_y = sum([v.y for v in object_centers]) / len(object_centers)
|
||||
|
|
@ -950,37 +1163,6 @@ class CuraApplication(QtApplication):
|
|||
|
||||
fileLoaded = pyqtSignal(str)
|
||||
|
||||
def _onFileLoaded(self, job):
|
||||
nodes = job.getResult()
|
||||
for node in nodes:
|
||||
if node is not None:
|
||||
self.fileLoaded.emit(job.getFileName())
|
||||
node.setSelectable(True)
|
||||
node.setName(os.path.basename(job.getFileName()))
|
||||
op = AddSceneNodeOperation(node, self.getController().getScene().getRoot())
|
||||
op.push()
|
||||
|
||||
self.getController().getScene().sceneChanged.emit(node) #Force scene change.
|
||||
|
||||
def _onJobFinished(self, job):
|
||||
if type(job) is not ReadMeshJob or not job.getResult():
|
||||
return
|
||||
|
||||
f = QUrl.fromLocalFile(job.getFileName())
|
||||
if f in self._recent_files:
|
||||
self._recent_files.remove(f)
|
||||
|
||||
self._recent_files.insert(0, f)
|
||||
if len(self._recent_files) > 10:
|
||||
del self._recent_files[10]
|
||||
|
||||
pref = ""
|
||||
for path in self._recent_files:
|
||||
pref += path.toLocalFile() + ";"
|
||||
|
||||
Preferences.getInstance().setValue("cura/recent_files", pref)
|
||||
self.recentFilesChanged.emit()
|
||||
|
||||
def _reloadMeshFinished(self, job):
|
||||
# TODO; This needs to be fixed properly. We now make the assumption that we only load a single mesh!
|
||||
mesh_data = job.getResult()[0].getMeshData()
|
||||
|
|
@ -989,10 +1171,8 @@ class CuraApplication(QtApplication):
|
|||
else:
|
||||
Logger.log("w", "Could not find a mesh in reloaded node.")
|
||||
|
||||
def _openFile(self, file):
|
||||
job = ReadMeshJob(os.path.abspath(file))
|
||||
job.finished.connect(self._onFileLoaded)
|
||||
job.start()
|
||||
def _openFile(self, filename):
|
||||
self.readLocalFile(QUrl.fromLocalFile(filename))
|
||||
|
||||
def _addProfileReader(self, profile_reader):
|
||||
# TODO: Add the profile reader to the list of plug-ins that can be used when importing profiles.
|
||||
|
|
@ -1077,6 +1257,10 @@ class CuraApplication(QtApplication):
|
|||
filename = job.getFileName()
|
||||
self._currently_loading_files.remove(filename)
|
||||
|
||||
root = self.getController().getScene().getRoot()
|
||||
arranger = Arrange.create(scene_root = root)
|
||||
min_offset = 8
|
||||
|
||||
for node in nodes:
|
||||
node.setSelectable(True)
|
||||
node.setName(os.path.basename(filename))
|
||||
|
|
@ -1097,10 +1281,42 @@ class CuraApplication(QtApplication):
|
|||
|
||||
scene = self.getController().getScene()
|
||||
|
||||
# If there is no convex hull for the node, start calculating it and continue.
|
||||
if not node.getDecorator(ConvexHullDecorator):
|
||||
node.addDecorator(ConvexHullDecorator())
|
||||
for child in node.getAllChildren():
|
||||
if not child.getDecorator(ConvexHullDecorator):
|
||||
child.addDecorator(ConvexHullDecorator())
|
||||
|
||||
if node.callDecoration("isSliceable"):
|
||||
# Only check position if it's not already blatantly obvious that it won't fit.
|
||||
if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
|
||||
# Find node location
|
||||
offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(node, min_offset = min_offset)
|
||||
|
||||
# Step is for skipping tests to make it a lot faster. it also makes the outcome somewhat rougher
|
||||
node, _ = arranger.findNodePlacement(node, offset_shape_arr, hull_shape_arr, step = 10)
|
||||
|
||||
op = AddSceneNodeOperation(node, scene.getRoot())
|
||||
op.push()
|
||||
|
||||
scene.sceneChanged.emit(node)
|
||||
|
||||
def addNonSliceableExtension(self, extension):
|
||||
self._non_sliceable_extensions.append(extension)
|
||||
|
||||
@pyqtSlot(str, result=bool)
|
||||
def checkIsValidProjectFile(self, file_url):
|
||||
"""
|
||||
Checks if the given file URL is a valid project file.
|
||||
"""
|
||||
try:
|
||||
file_path = QUrl(file_url).toLocalFile()
|
||||
workspace_reader = self.getWorkspaceFileHandler().getReaderForFile(file_path)
|
||||
if workspace_reader is None:
|
||||
return False # non-project files won't get a reader
|
||||
|
||||
result = workspace_reader.preRead(file_path, show_dialog=False)
|
||||
return result == WorkspaceReader.PreReadResult.accepted
|
||||
except Exception as e:
|
||||
Logger.log("e", "Could not check file %s: %s", file_url, e)
|
||||
return False
|
||||
|
|
|
|||
|
|
@ -3,4 +3,4 @@
|
|||
|
||||
CuraVersion = "@CURA_VERSION@"
|
||||
CuraBuildType = "@CURA_BUILDTYPE@"
|
||||
CuraDebugMode = True if "@CURA_DEBUGMODE@" == "ON" else False
|
||||
CuraDebugMode = True if "@_cura_debugmode@" == "ON" else False
|
||||
|
|
|
|||
|
|
@ -1,10 +1,8 @@
|
|||
from .LayerPolygon import LayerPolygon
|
||||
|
||||
from UM.Math.Vector import Vector
|
||||
from UM.Mesh.MeshBuilder import MeshBuilder
|
||||
|
||||
import numpy
|
||||
|
||||
|
||||
class Layer:
|
||||
def __init__(self, layer_id):
|
||||
self._id = layer_id
|
||||
|
|
@ -49,12 +47,12 @@ class Layer:
|
|||
|
||||
return result
|
||||
|
||||
def build(self, vertex_offset, index_offset, vertices, colors, indices):
|
||||
def build(self, vertex_offset, index_offset, vertices, colors, line_dimensions, extruders, line_types, indices):
|
||||
result_vertex_offset = vertex_offset
|
||||
result_index_offset = index_offset
|
||||
self._element_count = 0
|
||||
for polygon in self._polygons:
|
||||
polygon.build(result_vertex_offset, result_index_offset, vertices, colors, indices)
|
||||
polygon.build(result_vertex_offset, result_index_offset, vertices, colors, line_dimensions, extruders, line_types, indices)
|
||||
result_vertex_offset += polygon.lineMeshVertexCount()
|
||||
result_index_offset += polygon.lineMeshElementCount()
|
||||
self._element_count += polygon.elementCount
|
||||
|
|
@ -81,7 +79,6 @@ class Layer:
|
|||
for polygon in self._polygons:
|
||||
line_count += polygon.jumpCount
|
||||
|
||||
|
||||
# Reserve the neccesary space for the data upfront
|
||||
builder.reserveFaceAndVertexCount(2 * line_count, 4 * line_count)
|
||||
|
||||
|
|
@ -94,7 +91,7 @@ class Layer:
|
|||
# Line types of the points we want to draw
|
||||
line_types = polygon.types[index_mask]
|
||||
|
||||
# Shift the z-axis according to previous implementation.
|
||||
# Shift the z-axis according to previous implementation.
|
||||
if make_mesh:
|
||||
points[polygon.isInfillOrSkinType(line_types), 1::3] -= 0.01
|
||||
else:
|
||||
|
|
@ -106,13 +103,14 @@ class Layer:
|
|||
# Scale all normals by the line width of the current line so we can easily offset.
|
||||
normals *= (polygon.lineWidths[index_mask.ravel()] / 2)
|
||||
|
||||
# Create 4 points to draw each line segment, points +- normals results in 2 points each. Reshape to one point per line
|
||||
# Create 4 points to draw each line segment, points +- normals results in 2 points each.
|
||||
# After this we reshape to one point per line.
|
||||
f_points = numpy.concatenate((points-normals, points+normals), 1).reshape((-1, 3))
|
||||
|
||||
# __index_pattern defines which points to use to draw the two faces for each lines egment, the following linesegment is offset by 4
|
||||
f_indices = ( self.__index_pattern + numpy.arange(0, 4 * len(normals), 4, dtype=numpy.int32).reshape((-1, 1)) ).reshape((-1, 3))
|
||||
f_colors = numpy.repeat(polygon.mapLineTypeToColor(line_types), 4, 0)
|
||||
|
||||
builder.addFacesWithColor(f_points, f_indices, f_colors)
|
||||
|
||||
|
||||
return builder.build()
|
||||
|
|
@ -2,13 +2,14 @@
|
|||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
from UM.Mesh.MeshData import MeshData
|
||||
|
||||
|
||||
## Class to holds the layer mesh and information about the layers.
|
||||
# Immutable, use LayerDataBuilder to create one of these.
|
||||
class LayerData(MeshData):
|
||||
def __init__(self, vertices = None, normals = None, indices = None, colors = None, uvs = None, file_name = None,
|
||||
center_position = None, layers=None, element_counts=None):
|
||||
center_position = None, layers=None, element_counts=None, attributes=None):
|
||||
super().__init__(vertices=vertices, normals=normals, indices=indices, colors=colors, uvs=uvs,
|
||||
file_name=file_name, center_position=center_position)
|
||||
file_name=file_name, center_position=center_position, attributes=attributes)
|
||||
self._layers = layers
|
||||
self._element_counts = element_counts
|
||||
|
||||
|
|
|
|||
47
cura/LayerDataBuilder.py
Normal file → Executable file
47
cura/LayerDataBuilder.py
Normal file → Executable file
|
|
@ -8,6 +8,7 @@ from .LayerData import LayerData
|
|||
|
||||
import numpy
|
||||
|
||||
|
||||
## Builder class for constructing a LayerData object
|
||||
class LayerDataBuilder(MeshBuilder):
|
||||
def __init__(self):
|
||||
|
|
@ -48,7 +49,11 @@ class LayerDataBuilder(MeshBuilder):
|
|||
|
||||
self._layers[layer].setThickness(thickness)
|
||||
|
||||
def build(self):
|
||||
## Return the layer data as LayerData.
|
||||
#
|
||||
# \param material_color_map: [r, g, b, a] for each extruder row.
|
||||
# \param line_type_brightness: compatibility layer view uses line type brightness of 0.5
|
||||
def build(self, material_color_map, line_type_brightness = 1.0):
|
||||
vertex_count = 0
|
||||
index_count = 0
|
||||
for layer, data in self._layers.items():
|
||||
|
|
@ -56,20 +61,56 @@ class LayerDataBuilder(MeshBuilder):
|
|||
index_count += data.lineMeshElementCount()
|
||||
|
||||
vertices = numpy.empty((vertex_count, 3), numpy.float32)
|
||||
line_dimensions = numpy.empty((vertex_count, 2), numpy.float32)
|
||||
colors = numpy.empty((vertex_count, 4), numpy.float32)
|
||||
indices = numpy.empty((index_count, 2), numpy.int32)
|
||||
extruders = numpy.empty((vertex_count), numpy.float32)
|
||||
line_types = numpy.empty((vertex_count), numpy.float32)
|
||||
|
||||
vertex_offset = 0
|
||||
index_offset = 0
|
||||
for layer, data in self._layers.items():
|
||||
( vertex_offset, index_offset ) = data.build( vertex_offset, index_offset, vertices, colors, indices)
|
||||
( vertex_offset, index_offset ) = data.build( vertex_offset, index_offset, vertices, colors, line_dimensions, extruders, line_types, indices)
|
||||
self._element_counts[layer] = data.elementCount
|
||||
|
||||
self.addVertices(vertices)
|
||||
colors[:, 0:3] *= line_type_brightness
|
||||
self.addColors(colors)
|
||||
self.addIndices(indices.flatten())
|
||||
|
||||
# Note: we're using numpy indexing here.
|
||||
# See also: https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
|
||||
material_colors = numpy.zeros((line_dimensions.shape[0], 4), dtype=numpy.float32)
|
||||
for extruder_nr in range(material_color_map.shape[0]):
|
||||
material_colors[extruders == extruder_nr] = material_color_map[extruder_nr]
|
||||
# Set material_colors with indices where line_types (also numpy array) == MoveCombingType
|
||||
material_colors[line_types == LayerPolygon.MoveCombingType] = colors[line_types == LayerPolygon.MoveCombingType]
|
||||
material_colors[line_types == LayerPolygon.MoveRetractionType] = colors[line_types == LayerPolygon.MoveRetractionType]
|
||||
|
||||
attributes = {
|
||||
"line_dimensions": {
|
||||
"value": line_dimensions,
|
||||
"opengl_name": "a_line_dim",
|
||||
"opengl_type": "vector2f"
|
||||
},
|
||||
"extruders": {
|
||||
"value": extruders,
|
||||
"opengl_name": "a_extruder",
|
||||
"opengl_type": "float" # Strangely enough, the type has to be float while it is actually an int.
|
||||
},
|
||||
"colors": {
|
||||
"value": material_colors,
|
||||
"opengl_name": "a_material_color",
|
||||
"opengl_type": "vector4f"
|
||||
},
|
||||
"line_types": {
|
||||
"value": line_types,
|
||||
"opengl_name": "a_line_type",
|
||||
"opengl_type": "float"
|
||||
}
|
||||
}
|
||||
|
||||
return LayerData(vertices=self.getVertices(), normals=self.getNormals(), indices=self.getIndices(),
|
||||
colors=self.getColors(), uvs=self.getUVCoordinates(), file_name=self.getFileName(),
|
||||
center_position=self.getCenterPosition(), layers=self._layers,
|
||||
element_counts=self._element_counts)
|
||||
element_counts=self._element_counts, attributes=attributes)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
from UM.Math.Color import Color
|
||||
from UM.Application import Application
|
||||
|
||||
from typing import Any
|
||||
import numpy
|
||||
|
||||
|
||||
|
|
@ -19,12 +19,18 @@ class LayerPolygon:
|
|||
|
||||
__jump_map = numpy.logical_or(numpy.logical_or(numpy.arange(11) == NoneType, numpy.arange(11) == MoveCombingType), numpy.arange(11) == MoveRetractionType)
|
||||
|
||||
def __init__(self, mesh, extruder, line_types, data, line_widths):
|
||||
self._mesh = mesh
|
||||
## LayerPolygon, used in ProcessSlicedLayersJob
|
||||
# \param extruder
|
||||
# \param line_types array with line_types
|
||||
# \param data new_points
|
||||
# \param line_widths array with line widths
|
||||
# \param line_thicknesses: array with type as index and thickness as value
|
||||
def __init__(self, extruder, line_types, data, line_widths, line_thicknesses):
|
||||
self._extruder = extruder
|
||||
self._types = line_types
|
||||
self._data = data
|
||||
self._line_widths = line_widths
|
||||
self._line_thicknesses = line_thicknesses
|
||||
|
||||
self._vertex_begin = 0
|
||||
self._vertex_end = 0
|
||||
|
|
@ -38,7 +44,7 @@ class LayerPolygon:
|
|||
|
||||
# Buffering the colors shouldn't be necessary as it is not
|
||||
# re-used and can save alot of memory usage.
|
||||
self._color_map = LayerPolygon.getColorMap() * [1, 1, 1, self._extruder] # The alpha component is used to store the extruder nr
|
||||
self._color_map = LayerPolygon.getColorMap()
|
||||
self._colors = self._color_map[self._types]
|
||||
|
||||
# When type is used as index returns true if type == LayerPolygon.InfillType or type == LayerPolygon.SkinType or type == LayerPolygon.SupportInfillType
|
||||
|
|
@ -50,7 +56,7 @@ class LayerPolygon:
|
|||
|
||||
def buildCache(self):
|
||||
# For the line mesh we do not draw Infill or Jumps. Therefore those lines are filtered out.
|
||||
self._build_cache_line_mesh_mask = numpy.logical_not(numpy.logical_or(self._jump_mask, self._types == LayerPolygon.InfillType ))
|
||||
self._build_cache_line_mesh_mask = numpy.ones(self._jump_mask.shape, dtype=bool)
|
||||
mesh_line_count = numpy.sum(self._build_cache_line_mesh_mask)
|
||||
self._index_begin = 0
|
||||
self._index_end = mesh_line_count
|
||||
|
|
@ -64,9 +70,19 @@ class LayerPolygon:
|
|||
self._vertex_begin = 0
|
||||
self._vertex_end = numpy.sum( self._build_cache_needed_points )
|
||||
|
||||
|
||||
def build(self, vertex_offset, index_offset, vertices, colors, indices):
|
||||
if (self._build_cache_line_mesh_mask is None) or (self._build_cache_needed_points is None ):
|
||||
## Set all the arrays provided by the function caller, representing the LayerPolygon
|
||||
# The arrays are either by vertex or by indices.
|
||||
#
|
||||
# \param vertex_offset : determines where to start and end filling the arrays
|
||||
# \param index_offset : determines where to start and end filling the arrays
|
||||
# \param vertices : vertex numpy array to be filled
|
||||
# \param colors : vertex numpy array to be filled
|
||||
# \param line_dimensions : vertex numpy array to be filled
|
||||
# \param extruders : vertex numpy array to be filled
|
||||
# \param line_types : vertex numpy array to be filled
|
||||
# \param indices : index numpy array to be filled
|
||||
def build(self, vertex_offset, index_offset, vertices, colors, line_dimensions, extruders, line_types, indices):
|
||||
if self._build_cache_line_mesh_mask is None or self._build_cache_needed_points is None:
|
||||
self.buildCache()
|
||||
|
||||
line_mesh_mask = self._build_cache_line_mesh_mask
|
||||
|
|
@ -83,9 +99,18 @@ class LayerPolygon:
|
|||
|
||||
# Points are picked based on the index list to get the vertices needed.
|
||||
vertices[self._vertex_begin:self._vertex_end, :] = self._data[index_list, :]
|
||||
|
||||
# Create an array with colors for each vertex and remove the color data for the points that has been thrown away.
|
||||
colors[self._vertex_begin:self._vertex_end, :] = numpy.tile(self._colors, (1, 2)).reshape((-1, 4))[needed_points_list.ravel()]
|
||||
colors[self._vertex_begin:self._vertex_end, :] *= numpy.array([[0.5, 0.5, 0.5, 1.0]], numpy.float32)
|
||||
|
||||
# Create an array with line widths for each vertex.
|
||||
line_dimensions[self._vertex_begin:self._vertex_end, 0] = numpy.tile(self._line_widths, (1, 2)).reshape((-1, 1))[needed_points_list.ravel()][:, 0]
|
||||
line_dimensions[self._vertex_begin:self._vertex_end, 1] = numpy.tile(self._line_thicknesses, (1, 2)).reshape((-1, 1))[needed_points_list.ravel()][:, 0]
|
||||
|
||||
extruders[self._vertex_begin:self._vertex_end] = self._extruder
|
||||
|
||||
# Convert type per vertex to type per line
|
||||
line_types[self._vertex_begin:self._vertex_end] = numpy.tile(self._types, (1, 2)).reshape((-1, 1))[needed_points_list.ravel()][:, 0]
|
||||
|
||||
# The relative values of begin and end indices have already been set in buildCache, so we only need to offset them to the parents offset.
|
||||
self._index_begin += index_offset
|
||||
|
|
@ -173,7 +198,7 @@ class LayerPolygon:
|
|||
|
||||
return normals
|
||||
|
||||
__color_map = None
|
||||
__color_map = None # type: numpy.ndarray[Any]
|
||||
|
||||
## Gets the instance of the VersionUpgradeManager, or creates one.
|
||||
@classmethod
|
||||
|
|
|
|||
|
|
@ -105,7 +105,7 @@ class MachineActionManager(QObject):
|
|||
if definition_id in self._supported_actions:
|
||||
return list(self._supported_actions[definition_id])
|
||||
else:
|
||||
return set()
|
||||
return list()
|
||||
|
||||
## Get all actions required by given machine
|
||||
# \param definition_id The ID of the definition you want the required actions of
|
||||
|
|
|
|||
80
cura/MultiplyObjectsJob.py
Normal file
80
cura/MultiplyObjectsJob.py
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
# Copyright (c) 2017 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
from UM.Job import Job
|
||||
from UM.Scene.SceneNode import SceneNode
|
||||
from UM.Math.Vector import Vector
|
||||
from UM.Operations.SetTransformOperation import SetTransformOperation
|
||||
from UM.Operations.TranslateOperation import TranslateOperation
|
||||
from UM.Operations.GroupedOperation import GroupedOperation
|
||||
from UM.Logger import Logger
|
||||
from UM.Message import Message
|
||||
from UM.i18n import i18nCatalog
|
||||
i18n_catalog = i18nCatalog("cura")
|
||||
|
||||
from cura.ZOffsetDecorator import ZOffsetDecorator
|
||||
from cura.Arrange import Arrange
|
||||
from cura.ShapeArray import ShapeArray
|
||||
|
||||
from typing import List
|
||||
|
||||
from UM.Application import Application
|
||||
from UM.Scene.Selection import Selection
|
||||
from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
|
||||
|
||||
|
||||
class MultiplyObjectsJob(Job):
|
||||
def __init__(self, object_id, count, min_offset = 8):
|
||||
super().__init__()
|
||||
self._object_id = object_id
|
||||
self._count = count
|
||||
self._min_offset = min_offset
|
||||
|
||||
def run(self):
|
||||
status_message = Message(i18n_catalog.i18nc("@info:status", "Multiplying and placing objects"), lifetime=0,
|
||||
dismissable=False, progress=0)
|
||||
status_message.show()
|
||||
scene = Application.getInstance().getController().getScene()
|
||||
node = scene.findObject(self._object_id)
|
||||
|
||||
if not node and self._object_id != 0: # Workaround for tool handles overlapping the selected object
|
||||
node = Selection.getSelectedObject(0)
|
||||
|
||||
# If object is part of a group, multiply group
|
||||
current_node = node
|
||||
while current_node.getParent() and current_node.getParent().callDecoration("isGroup"):
|
||||
current_node = current_node.getParent()
|
||||
|
||||
root = scene.getRoot()
|
||||
arranger = Arrange.create(scene_root=root)
|
||||
node_too_big = False
|
||||
if node.getBoundingBox().width < 300 or node.getBoundingBox().depth < 300:
|
||||
offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(current_node, min_offset=self._min_offset)
|
||||
else:
|
||||
node_too_big = True
|
||||
nodes = []
|
||||
found_solution_for_all = True
|
||||
for i in range(self._count):
|
||||
# We do place the nodes one by one, as we want to yield in between.
|
||||
if not node_too_big:
|
||||
node, solution_found = arranger.findNodePlacement(current_node, offset_shape_arr, hull_shape_arr)
|
||||
if node_too_big or not solution_found:
|
||||
found_solution_for_all = False
|
||||
new_location = node.getPosition()
|
||||
new_location = new_location.set(z = 100 - i * 20)
|
||||
node.setPosition(new_location)
|
||||
|
||||
nodes.append(node)
|
||||
Job.yieldThread()
|
||||
status_message.setProgress((i + 1) / self._count * 100)
|
||||
|
||||
if nodes:
|
||||
op = GroupedOperation()
|
||||
for new_node in nodes:
|
||||
op.addOperation(AddSceneNodeOperation(new_node, current_node.getParent()))
|
||||
op.push()
|
||||
status_message.hide()
|
||||
|
||||
if not found_solution_for_all:
|
||||
no_full_solution_message = Message(i18n_catalog.i18nc("@info:status", "Unable to find a location within the build volume for all objects"))
|
||||
no_full_solution_message.show()
|
||||
48
cura/PlatformPhysics.py
Normal file → Executable file
48
cura/PlatformPhysics.py
Normal file → Executable file
|
|
@ -3,10 +3,10 @@
|
|||
|
||||
from PyQt5.QtCore import QTimer
|
||||
|
||||
from UM.Application import Application
|
||||
from UM.Scene.SceneNode import SceneNode
|
||||
from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
|
||||
from UM.Math.Vector import Vector
|
||||
from UM.Math.AxisAlignedBox import AxisAlignedBox
|
||||
from UM.Scene.Selection import Selection
|
||||
from UM.Preferences import Preferences
|
||||
|
||||
|
|
@ -51,10 +51,13 @@ class PlatformPhysics:
|
|||
# same direction.
|
||||
transformed_nodes = []
|
||||
|
||||
group_nodes = []
|
||||
# We try to shuffle all the nodes to prevent "locked" situations, where iteration B inverts iteration A.
|
||||
# By shuffling the order of the nodes, this might happen a few times, but at some point it will resolve.
|
||||
nodes = list(BreadthFirstIterator(root))
|
||||
|
||||
# Only check nodes inside build area.
|
||||
nodes = [node for node in nodes if (hasattr(node, "_outside_buildarea") and not node._outside_buildarea)]
|
||||
|
||||
random.shuffle(nodes)
|
||||
for node in nodes:
|
||||
if node is root or type(node) is not SceneNode or node.getBoundingBox() is None:
|
||||
|
|
@ -62,24 +65,6 @@ class PlatformPhysics:
|
|||
|
||||
bbox = node.getBoundingBox()
|
||||
|
||||
# Ignore intersections with the bottom
|
||||
build_volume_bounding_box = self._build_volume.getBoundingBox()
|
||||
if build_volume_bounding_box:
|
||||
# It's over 9000!
|
||||
build_volume_bounding_box = build_volume_bounding_box.set(bottom=-9001)
|
||||
else:
|
||||
# No bounding box. This is triggered when running Cura from command line with a model for the first time
|
||||
# In that situation there is a model, but no machine (and therefore no build volume.
|
||||
return
|
||||
node._outside_buildarea = False
|
||||
|
||||
# Mark the node as outside the build volume if the bounding box test fails.
|
||||
if build_volume_bounding_box.intersectsBox(bbox) != AxisAlignedBox.IntersectionResult.FullIntersection:
|
||||
node._outside_buildarea = True
|
||||
|
||||
if node.callDecoration("isGroup"):
|
||||
group_nodes.append(node) # Keep list of affected group_nodes
|
||||
|
||||
# Move it downwards if bottom is above platform
|
||||
move_vector = Vector()
|
||||
if Preferences.getInstance().getValue("physics/automatic_drop_down") and not (node.getParent() and node.getParent().callDecoration("isGroup")) and node.isEnabled(): #If an object is grouped, don't move it down
|
||||
|
|
@ -145,32 +130,23 @@ class PlatformPhysics:
|
|||
# Simply waiting for the next tick seems to resolve this correctly.
|
||||
overlap = None
|
||||
|
||||
convex_hull = node.callDecoration("getConvexHull")
|
||||
if convex_hull:
|
||||
if not convex_hull.isValid():
|
||||
return
|
||||
# Check for collisions between disallowed areas and the object
|
||||
for area in self._build_volume.getDisallowedAreas():
|
||||
overlap = convex_hull.intersectsPolygon(area)
|
||||
if overlap is None:
|
||||
continue
|
||||
node._outside_buildarea = True
|
||||
|
||||
if not Vector.Null.equals(move_vector, epsilon=1e-5):
|
||||
transformed_nodes.append(node)
|
||||
op = PlatformPhysicsOperation.PlatformPhysicsOperation(node, move_vector)
|
||||
op.push()
|
||||
|
||||
# Group nodes should override the _outside_buildarea property of their children.
|
||||
for group_node in group_nodes:
|
||||
for child_node in group_node.getAllChildren():
|
||||
child_node._outside_buildarea = group_node._outside_buildarea
|
||||
|
||||
# After moving, we have to evaluate the boundary checks for nodes
|
||||
build_volume = Application.getInstance().getBuildVolume()
|
||||
build_volume.updateNodeBoundaryCheck()
|
||||
|
||||
def _onToolOperationStarted(self, tool):
|
||||
self._enabled = False
|
||||
|
||||
def _onToolOperationStopped(self, tool):
|
||||
# Selection tool should not trigger an update.
|
||||
if tool.getPluginId() == "SelectionTool":
|
||||
return
|
||||
|
||||
if tool.getPluginId() == "TranslateTool":
|
||||
for node in Selection.getAllSelectedObjects():
|
||||
if node.getBoundingBox().bottom < 0:
|
||||
|
|
|
|||
|
|
@ -5,11 +5,12 @@ from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty
|
|||
from UM.FlameProfiler import pyqtSlot
|
||||
|
||||
from UM.Application import Application
|
||||
from UM.Logger import Logger
|
||||
from UM.Qt.Duration import Duration
|
||||
from UM.Preferences import Preferences
|
||||
from UM.Settings import ContainerRegistry
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
|
||||
import cura.Settings.ExtruderManager
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
|
||||
import math
|
||||
import os.path
|
||||
|
|
@ -74,6 +75,8 @@ class PrintInformation(QObject):
|
|||
Application.getInstance().getMachineManager().activeMaterialChanged.connect(self._onActiveMaterialChanged)
|
||||
self._onActiveMaterialChanged()
|
||||
|
||||
self._material_amounts = []
|
||||
|
||||
currentPrintTimeChanged = pyqtSignal()
|
||||
|
||||
preSlicedChanged = pyqtSignal()
|
||||
|
|
@ -109,22 +112,30 @@ class PrintInformation(QObject):
|
|||
return self._material_costs
|
||||
|
||||
def _onPrintDurationMessage(self, total_time, material_amounts):
|
||||
self._current_print_time.setDuration(total_time)
|
||||
if total_time != total_time: # Check for NaN. Engine can sometimes give us weird values.
|
||||
Logger.log("w", "Received NaN for print duration message")
|
||||
self._current_print_time.setDuration(0)
|
||||
else:
|
||||
self._current_print_time.setDuration(total_time)
|
||||
|
||||
self.currentPrintTimeChanged.emit()
|
||||
|
||||
self._material_amounts = material_amounts
|
||||
self._calculateInformation()
|
||||
|
||||
def _calculateInformation(self):
|
||||
if Application.getInstance().getGlobalContainerStack() is None:
|
||||
return
|
||||
|
||||
# Material amount is sent as an amount of mm^3, so calculate length from that
|
||||
r = Application.getInstance().getGlobalContainerStack().getProperty("material_diameter", "value") / 2
|
||||
radius = Application.getInstance().getGlobalContainerStack().getProperty("material_diameter", "value") / 2
|
||||
self._material_lengths = []
|
||||
self._material_weights = []
|
||||
self._material_costs = []
|
||||
|
||||
material_preference_values = json.loads(Preferences.getInstance().getValue("cura/material_settings"))
|
||||
|
||||
extruder_stacks = list(cura.Settings.ExtruderManager.getInstance().getMachineExtruders(Application.getInstance().getGlobalContainerStack().getId()))
|
||||
extruder_stacks = list(ExtruderManager.getInstance().getMachineExtruders(Application.getInstance().getGlobalContainerStack().getId()))
|
||||
for index, amount in enumerate(self._material_amounts):
|
||||
## Find the right extruder stack. As the list isn't sorted because it's a annoying generator, we do some
|
||||
# list comprehension filtering to solve this for us.
|
||||
|
|
@ -152,8 +163,12 @@ class PrintInformation(QObject):
|
|||
else:
|
||||
cost = 0
|
||||
|
||||
if radius != 0:
|
||||
length = round((amount / (math.pi * radius ** 2)) / 1000, 2)
|
||||
else:
|
||||
length = 0
|
||||
self._material_weights.append(weight)
|
||||
self._material_lengths.append(round((amount / (math.pi * r ** 2)) / 1000, 2))
|
||||
self._material_lengths.append(length)
|
||||
self._material_costs.append(cost)
|
||||
|
||||
self.materialLengthsChanged.emit()
|
||||
|
|
@ -177,7 +192,7 @@ class PrintInformation(QObject):
|
|||
self._active_material_container = active_material_containers[0]
|
||||
self._active_material_container.metaDataChanged.connect(self._onMaterialMetaDataChanged)
|
||||
|
||||
def _onMaterialMetaDataChanged(self):
|
||||
def _onMaterialMetaDataChanged(self, *args, **kwargs):
|
||||
self._calculateInformation()
|
||||
|
||||
@pyqtSlot(str)
|
||||
|
|
@ -200,11 +215,16 @@ class PrintInformation(QObject):
|
|||
|
||||
@pyqtSlot(str, result = str)
|
||||
def createJobName(self, base_name):
|
||||
if base_name == "":
|
||||
return ""
|
||||
base_name = self._stripAccents(base_name)
|
||||
self._setAbbreviatedMachineName()
|
||||
if self._pre_sliced:
|
||||
return catalog.i18nc("@label", "Pre-sliced file {0}", base_name)
|
||||
elif Preferences.getInstance().getValue("cura/jobname_prefix"):
|
||||
# Don't add abbreviation if it already has the exact same abbreviation.
|
||||
if base_name.startswith(self._abbr_machine + "_"):
|
||||
return base_name
|
||||
return self._abbr_machine + "_" + base_name
|
||||
else:
|
||||
return base_name
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
# Copyright (c) 2017 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
from UM.i18n import i18nCatalog
|
||||
from UM.OutputDevice.OutputDevice import OutputDevice
|
||||
from PyQt5.QtCore import pyqtProperty, pyqtSignal, pyqtSlot, QObject
|
||||
from PyQt5.QtCore import pyqtProperty, pyqtSignal, pyqtSlot, QObject, QTimer
|
||||
from PyQt5.QtWidgets import QMessageBox
|
||||
import UM.Settings.ContainerRegistry
|
||||
|
||||
from enum import IntEnum # For the connection state tracking.
|
||||
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
from UM.Logger import Logger
|
||||
from UM.Application import Application
|
||||
from UM.Signal import signalemitter
|
||||
|
||||
i18n_catalog = i18nCatalog("cura")
|
||||
|
|
@ -25,7 +27,7 @@ class PrinterOutputDevice(QObject, OutputDevice):
|
|||
def __init__(self, device_id, parent = None):
|
||||
super().__init__(device_id = device_id, parent = parent)
|
||||
|
||||
self._container_registry = UM.Settings.ContainerRegistry.getInstance()
|
||||
self._container_registry = ContainerRegistry.getInstance()
|
||||
self._target_bed_temperature = 0
|
||||
self._bed_temperature = 0
|
||||
self._num_extruders = 1
|
||||
|
|
@ -45,6 +47,10 @@ class PrinterOutputDevice(QObject, OutputDevice):
|
|||
self._job_name = ""
|
||||
self._error_text = ""
|
||||
self._accepts_commands = True
|
||||
self._preheat_bed_timeout = 900 # Default time-out for pre-heating the bed, in seconds.
|
||||
self._preheat_bed_timer = QTimer() # Timer that tracks how long to preheat still.
|
||||
self._preheat_bed_timer.setSingleShot(True)
|
||||
self._preheat_bed_timer.timeout.connect(self.cancelPreheatBed)
|
||||
|
||||
self._printer_state = ""
|
||||
self._printer_type = "unknown"
|
||||
|
|
@ -102,6 +108,9 @@ class PrinterOutputDevice(QObject, OutputDevice):
|
|||
|
||||
printerTypeChanged = pyqtSignal()
|
||||
|
||||
# Signal to be emitted when some drastic change occurs in the remaining time (not when the time just passes on normally).
|
||||
preheatBedRemainingTimeChanged = pyqtSignal()
|
||||
|
||||
@pyqtProperty(str, notify=printerTypeChanged)
|
||||
def printerType(self):
|
||||
return self._printer_type
|
||||
|
|
@ -161,6 +170,17 @@ class PrinterOutputDevice(QObject, OutputDevice):
|
|||
self._job_name = name
|
||||
self.jobNameChanged.emit()
|
||||
|
||||
## Gives a human-readable address where the device can be found.
|
||||
@pyqtProperty(str, constant = True)
|
||||
def address(self):
|
||||
Logger.log("w", "address is not implemented by this output device.")
|
||||
|
||||
## A human-readable name for the device.
|
||||
@pyqtProperty(str, constant = True)
|
||||
def name(self):
|
||||
Logger.log("w", "name is not implemented by this output device.")
|
||||
return ""
|
||||
|
||||
@pyqtProperty(str, notify = errorTextChanged)
|
||||
def errorText(self):
|
||||
return self._error_text
|
||||
|
|
@ -199,6 +219,30 @@ class PrinterOutputDevice(QObject, OutputDevice):
|
|||
self._target_bed_temperature = temperature
|
||||
self.targetBedTemperatureChanged.emit()
|
||||
|
||||
## The total duration of the time-out to pre-heat the bed, in seconds.
|
||||
#
|
||||
# \return The duration of the time-out to pre-heat the bed, in seconds.
|
||||
@pyqtProperty(int, constant = True)
|
||||
def preheatBedTimeout(self):
|
||||
return self._preheat_bed_timeout
|
||||
|
||||
## The remaining duration of the pre-heating of the bed.
|
||||
#
|
||||
# This is formatted in M:SS format.
|
||||
# \return The duration of the time-out to pre-heat the bed, formatted.
|
||||
@pyqtProperty(str, notify = preheatBedRemainingTimeChanged)
|
||||
def preheatBedRemainingTime(self):
|
||||
if not self._preheat_bed_timer.isActive():
|
||||
return ""
|
||||
period = self._preheat_bed_timer.remainingTime()
|
||||
if period <= 0:
|
||||
return ""
|
||||
minutes, period = divmod(period, 60000) #60000 milliseconds in a minute.
|
||||
seconds, _ = divmod(period, 1000) #1000 milliseconds in a second.
|
||||
if minutes <= 0 and seconds <= 0:
|
||||
return ""
|
||||
return "%d:%02d" % (minutes, seconds)
|
||||
|
||||
## Time the print has been printing.
|
||||
# Note that timeTotal - timeElapsed should give time remaining.
|
||||
@pyqtProperty(float, notify = timeElapsedChanged)
|
||||
|
|
@ -254,6 +298,22 @@ class PrinterOutputDevice(QObject, OutputDevice):
|
|||
def _setTargetBedTemperature(self, temperature):
|
||||
Logger.log("w", "_setTargetBedTemperature is not implemented by this output device")
|
||||
|
||||
## 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):
|
||||
Logger.log("w", "preheatBed is not implemented by this output device.")
|
||||
|
||||
## Cancels pre-heating the heated bed of the printer.
|
||||
#
|
||||
# If the bed is not pre-heated, nothing happens.
|
||||
@pyqtSlot()
|
||||
def cancelPreheatBed(self):
|
||||
Logger.log("w", "cancelPreheatBed is not implemented by this output device.")
|
||||
|
||||
## Protected setter for the current bed temperature.
|
||||
# This simply sets the bed temperature, but ensures that a signal is emitted.
|
||||
# /param temperature temperature of the bed.
|
||||
|
|
@ -323,6 +383,28 @@ class PrinterOutputDevice(QObject, OutputDevice):
|
|||
result.append(i18n_catalog.i18nc("@item:material", "Unknown material"))
|
||||
return result
|
||||
|
||||
## List of the colours of the currently loaded materials.
|
||||
#
|
||||
# The list is in order of extruders. If there is no material in an
|
||||
# extruder, the colour is shown as transparent.
|
||||
#
|
||||
# The colours are returned in hex-format AARRGGBB or RRGGBB
|
||||
# (e.g. #800000ff for transparent blue or #00ff00 for pure green).
|
||||
@pyqtProperty("QVariantList", notify = materialIdChanged)
|
||||
def materialColors(self):
|
||||
result = []
|
||||
for material_id in self._material_ids:
|
||||
if material_id is None:
|
||||
result.append("#00000000") #No material.
|
||||
continue
|
||||
|
||||
containers = self._container_registry.findInstanceContainers(type = "material", GUID = material_id)
|
||||
if containers:
|
||||
result.append(containers[0].getMetaDataEntry("color_code"))
|
||||
else:
|
||||
result.append("#00000000") #Unknown material.
|
||||
return result
|
||||
|
||||
## Protected setter for the current material id.
|
||||
# /param index Index of the extruder
|
||||
# /param material_id id of the material
|
||||
|
|
@ -340,10 +422,14 @@ class PrinterOutputDevice(QObject, OutputDevice):
|
|||
# /param index Index of the extruder
|
||||
# /param hotend_id id of the hotend
|
||||
def _setHotendId(self, index, hotend_id):
|
||||
if hotend_id and hotend_id != "" and hotend_id != self._hotend_ids[index]:
|
||||
if hotend_id and hotend_id != self._hotend_ids[index]:
|
||||
Logger.log("d", "Setting hotend id of hotend %d to %s" % (index, hotend_id))
|
||||
self._hotend_ids[index] = hotend_id
|
||||
self.hotendIdChanged.emit(index, hotend_id)
|
||||
elif not hotend_id:
|
||||
Logger.log("d", "Removing hotend id of hotend %d.", index)
|
||||
self._hotend_ids[index] = None
|
||||
self.hotendIdChanged.emit(index, None)
|
||||
|
||||
## Let the user decide if the hotends and/or material should be synced with the printer
|
||||
# NB: the UX needs to be implemented by the plugin
|
||||
|
|
|
|||
|
|
@ -1,24 +1,28 @@
|
|||
# Copyright (c) 2016 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
import UM.Application
|
||||
import cura.Settings.ExtruderManager
|
||||
import UM.Settings.ContainerRegistry
|
||||
|
||||
# This collects a lot of quality and quality changes related code which was split between ContainerManager
|
||||
# and the MachineManager and really needs to usable from both.
|
||||
from typing import List
|
||||
|
||||
from UM.Application import Application
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
from UM.Settings.DefinitionContainer import DefinitionContainer
|
||||
from UM.Settings.InstanceContainer import InstanceContainer
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
|
||||
|
||||
class QualityManager:
|
||||
|
||||
## Get the singleton instance for this class.
|
||||
@classmethod
|
||||
def getInstance(cls):
|
||||
def getInstance(cls) -> "QualityManager":
|
||||
# Note: Explicit use of class name to prevent issues with inheritance.
|
||||
if QualityManager.__instance is None:
|
||||
if not QualityManager.__instance:
|
||||
QualityManager.__instance = cls()
|
||||
return QualityManager.__instance
|
||||
|
||||
__instance = None
|
||||
__instance = None # type: "QualityManager"
|
||||
|
||||
## Find a quality by name for a specific machine definition and materials.
|
||||
#
|
||||
|
|
@ -121,14 +125,14 @@ class QualityManager:
|
|||
#
|
||||
# \param machine_definition \type{DefinitionContainer} the machine definition.
|
||||
# \return \type{List[InstanceContainer]} the list of quality changes
|
||||
def findAllQualityChangesForMachine(self, machine_definition):
|
||||
def findAllQualityChangesForMachine(self, machine_definition: DefinitionContainer) -> List[InstanceContainer]:
|
||||
if machine_definition.getMetaDataEntry("has_machine_quality"):
|
||||
definition_id = machine_definition.getId()
|
||||
else:
|
||||
definition_id = "fdmprinter"
|
||||
|
||||
filter_dict = { "type": "quality_changes", "extruder": None, "definition": definition_id }
|
||||
quality_changes_list = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(**filter_dict)
|
||||
quality_changes_list = ContainerRegistry.getInstance().findInstanceContainers(**filter_dict)
|
||||
return quality_changes_list
|
||||
|
||||
## Find all usable qualities for a machine and extruders.
|
||||
|
|
@ -177,7 +181,7 @@ class QualityManager:
|
|||
if base_material:
|
||||
# There is a basic material specified
|
||||
criteria = { "type": "material", "name": base_material, "definition": definition_id }
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(**criteria)
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(**criteria)
|
||||
containers = [basic_material for basic_material in containers if
|
||||
basic_material.getMetaDataEntry("variant") == material_container.getMetaDataEntry(
|
||||
"variant")]
|
||||
|
|
@ -191,13 +195,13 @@ class QualityManager:
|
|||
def _getFilteredContainersForStack(self, machine_definition=None, material_containers=None, **kwargs):
|
||||
# Fill in any default values.
|
||||
if machine_definition is None:
|
||||
machine_definition = UM.Application.getInstance().getGlobalContainerStack().getBottom()
|
||||
machine_definition = Application.getInstance().getGlobalContainerStack().getBottom()
|
||||
quality_definition_id = machine_definition.getMetaDataEntry("quality_definition")
|
||||
if quality_definition_id is not None:
|
||||
machine_definition = UM.Settings.ContainerRegistry.getInstance().findDefinitionContainers(id=quality_definition_id)[0]
|
||||
machine_definition = ContainerRegistry.getInstance().findDefinitionContainers(id=quality_definition_id)[0]
|
||||
|
||||
if material_containers is None:
|
||||
active_stacks = cura.Settings.ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks()
|
||||
active_stacks = ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks()
|
||||
material_containers = [stack.findContainer(type="material") for stack in active_stacks]
|
||||
|
||||
criteria = kwargs
|
||||
|
|
@ -225,7 +229,7 @@ class QualityManager:
|
|||
material_ids.add(basic_material.getId())
|
||||
material_ids.add(material_instance.getId())
|
||||
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(**criteria)
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(**criteria)
|
||||
|
||||
result = []
|
||||
for container in containers:
|
||||
|
|
@ -241,8 +245,8 @@ class QualityManager:
|
|||
# an extruder definition.
|
||||
# \return \type{DefinitionContainer} the parent machine definition. If the given machine
|
||||
# definition doesn't have a parent then it is simply returned.
|
||||
def getParentMachineDefinition(self, machine_definition):
|
||||
container_registry = UM.Settings.ContainerRegistry.getInstance()
|
||||
def getParentMachineDefinition(self, machine_definition: DefinitionContainer) -> DefinitionContainer:
|
||||
container_registry = ContainerRegistry.getInstance()
|
||||
|
||||
machine_entry = machine_definition.getMetaDataEntry("machine")
|
||||
if machine_entry is None:
|
||||
|
|
@ -277,6 +281,6 @@ class QualityManager:
|
|||
# This already is a 'global' machine definition.
|
||||
return machine_definition
|
||||
else:
|
||||
container_registry = UM.Settings.ContainerRegistry.getInstance()
|
||||
container_registry = ContainerRegistry.getInstance()
|
||||
whole_machine = container_registry.findDefinitionContainers(id=machine_entry)[0]
|
||||
return whole_machine
|
||||
|
|
|
|||
|
|
@ -3,24 +3,31 @@
|
|||
|
||||
import os.path
|
||||
import urllib
|
||||
from typing import Dict, Union
|
||||
|
||||
from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal, QUrl, QVariant
|
||||
from PyQt5.QtCore import QObject, QUrl, QVariant
|
||||
from UM.FlameProfiler import pyqtSlot
|
||||
from PyQt5.QtWidgets import QMessageBox
|
||||
|
||||
import UM.PluginRegistry
|
||||
import UM.Settings
|
||||
import UM.SaveFile
|
||||
import UM.Platform
|
||||
import UM.MimeTypeDatabase
|
||||
import UM.Logger
|
||||
from UM.PluginRegistry import PluginRegistry
|
||||
from UM.SaveFile import SaveFile
|
||||
from UM.Platform import Platform
|
||||
from UM.MimeTypeDatabase import MimeTypeDatabase
|
||||
|
||||
import cura.Settings
|
||||
from UM.Logger import Logger
|
||||
from UM.Application import Application
|
||||
from UM.Settings.ContainerStack import ContainerStack
|
||||
from UM.Settings.DefinitionContainer import DefinitionContainer
|
||||
from UM.Settings.InstanceContainer import InstanceContainer
|
||||
from cura.QualityManager import QualityManager
|
||||
|
||||
from UM.MimeTypeDatabase import MimeTypeNotFoundError
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
|
||||
from UM.i18n import i18nCatalog
|
||||
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
|
||||
catalog = i18nCatalog("cura")
|
||||
|
||||
## Manager class that contains common actions to deal with containers in Cura.
|
||||
|
|
@ -32,9 +39,8 @@ class ContainerManager(QObject):
|
|||
def __init__(self, parent = None):
|
||||
super().__init__(parent)
|
||||
|
||||
self._container_registry = UM.Settings.ContainerRegistry.getInstance()
|
||||
self._machine_manager = UM.Application.getInstance().getMachineManager()
|
||||
|
||||
self._container_registry = ContainerRegistry.getInstance()
|
||||
self._machine_manager = Application.getInstance().getMachineManager()
|
||||
self._container_name_filters = {}
|
||||
|
||||
## Create a duplicate of the specified container
|
||||
|
|
@ -49,7 +55,7 @@ class ContainerManager(QObject):
|
|||
def duplicateContainer(self, container_id):
|
||||
containers = self._container_registry.findContainers(None, id = container_id)
|
||||
if not containers:
|
||||
UM.Logger.log("w", "Could duplicate container %s because it was not found.", container_id)
|
||||
Logger.log("w", "Could duplicate container %s because it was not found.", container_id)
|
||||
return ""
|
||||
|
||||
container = containers[0]
|
||||
|
|
@ -81,7 +87,7 @@ class ContainerManager(QObject):
|
|||
def renameContainer(self, container_id, new_id, new_name):
|
||||
containers = self._container_registry.findContainers(None, id = container_id)
|
||||
if not containers:
|
||||
UM.Logger.log("w", "Could rename container %s because it was not found.", container_id)
|
||||
Logger.log("w", "Could rename container %s because it was not found.", container_id)
|
||||
return False
|
||||
|
||||
container = containers[0]
|
||||
|
|
@ -109,7 +115,7 @@ class ContainerManager(QObject):
|
|||
def removeContainer(self, container_id):
|
||||
containers = self._container_registry.findContainers(None, id = container_id)
|
||||
if not containers:
|
||||
UM.Logger.log("w", "Could remove container %s because it was not found.", container_id)
|
||||
Logger.log("w", "Could remove container %s because it was not found.", container_id)
|
||||
return False
|
||||
|
||||
self._container_registry.removeContainer(containers[0].getId())
|
||||
|
|
@ -129,20 +135,20 @@ class ContainerManager(QObject):
|
|||
def mergeContainers(self, merge_into_id, merge_id):
|
||||
containers = self._container_registry.findContainers(None, id = merge_into_id)
|
||||
if not containers:
|
||||
UM.Logger.log("w", "Could merge into container %s because it was not found.", merge_into_id)
|
||||
Logger.log("w", "Could merge into container %s because it was not found.", merge_into_id)
|
||||
return False
|
||||
|
||||
merge_into = containers[0]
|
||||
|
||||
containers = self._container_registry.findContainers(None, id = merge_id)
|
||||
if not containers:
|
||||
UM.Logger.log("w", "Could not merge container %s because it was not found", merge_id)
|
||||
Logger.log("w", "Could not merge container %s because it was not found", merge_id)
|
||||
return False
|
||||
|
||||
merge = containers[0]
|
||||
|
||||
if not isinstance(merge, type(merge_into)):
|
||||
UM.Logger.log("w", "Cannot merge two containers of different types")
|
||||
Logger.log("w", "Cannot merge two containers of different types")
|
||||
return False
|
||||
|
||||
self._performMerge(merge_into, merge)
|
||||
|
|
@ -158,11 +164,11 @@ class ContainerManager(QObject):
|
|||
def clearContainer(self, container_id):
|
||||
containers = self._container_registry.findContainers(None, id = container_id)
|
||||
if not containers:
|
||||
UM.Logger.log("w", "Could clear container %s because it was not found.", container_id)
|
||||
Logger.log("w", "Could clear container %s because it was not found.", container_id)
|
||||
return False
|
||||
|
||||
if containers[0].isReadOnly():
|
||||
UM.Logger.log("w", "Cannot clear read-only container %s", container_id)
|
||||
Logger.log("w", "Cannot clear read-only container %s", container_id)
|
||||
return False
|
||||
|
||||
containers[0].clear()
|
||||
|
|
@ -173,7 +179,7 @@ class ContainerManager(QObject):
|
|||
def getContainerMetaDataEntry(self, container_id, entry_name):
|
||||
containers = self._container_registry.findContainers(None, id=container_id)
|
||||
if not containers:
|
||||
UM.Logger.log("w", "Could not get metadata of container %s because it was not found.", container_id)
|
||||
Logger.log("w", "Could not get metadata of container %s because it was not found.", container_id)
|
||||
return ""
|
||||
|
||||
result = containers[0].getMetaDataEntry(entry_name)
|
||||
|
|
@ -198,13 +204,13 @@ class ContainerManager(QObject):
|
|||
def setContainerMetaDataEntry(self, container_id, entry_name, entry_value):
|
||||
containers = self._container_registry.findContainers(None, id = container_id)
|
||||
if not containers:
|
||||
UM.Logger.log("w", "Could not set metadata of container %s because it was not found.", container_id)
|
||||
Logger.log("w", "Could not set metadata of container %s because it was not found.", container_id)
|
||||
return False
|
||||
|
||||
container = containers[0]
|
||||
|
||||
if container.isReadOnly():
|
||||
UM.Logger.log("w", "Cannot set metadata of read-only container %s.", container_id)
|
||||
Logger.log("w", "Cannot set metadata of read-only container %s.", container_id)
|
||||
return False
|
||||
|
||||
entries = entry_name.split("/")
|
||||
|
|
@ -232,13 +238,13 @@ class ContainerManager(QObject):
|
|||
def setContainerName(self, container_id, new_name):
|
||||
containers = self._container_registry.findContainers(None, id = container_id)
|
||||
if not containers:
|
||||
UM.Logger.log("w", "Could not set name of container %s because it was not found.", container_id)
|
||||
Logger.log("w", "Could not set name of container %s because it was not found.", container_id)
|
||||
return False
|
||||
|
||||
container = containers[0]
|
||||
|
||||
if container.isReadOnly():
|
||||
UM.Logger.log("w", "Cannot set name of read-only container %s.", container_id)
|
||||
Logger.log("w", "Cannot set name of read-only container %s.", container_id)
|
||||
return False
|
||||
|
||||
container.setName(new_name)
|
||||
|
|
@ -262,11 +268,11 @@ class ContainerManager(QObject):
|
|||
|
||||
@pyqtSlot(str, result = bool)
|
||||
def isContainerUsed(self, container_id):
|
||||
UM.Logger.log("d", "Checking if container %s is currently used", container_id)
|
||||
Logger.log("d", "Checking if container %s is currently used", container_id)
|
||||
containers = self._container_registry.findContainerStacks()
|
||||
for stack in containers:
|
||||
if container_id in [child.getId() for child in stack.getContainers()]:
|
||||
UM.Logger.log("d", "The container is in use by %s", stack.getId())
|
||||
Logger.log("d", "The container is in use by %s", stack.getId())
|
||||
return True
|
||||
return False
|
||||
|
||||
|
|
@ -301,18 +307,20 @@ class ContainerManager(QObject):
|
|||
#
|
||||
# \param container_id The ID of the container to export
|
||||
# \param file_type The type of file to save as. Should be in the form of "description (*.extension, *.ext)"
|
||||
# \param file_url The URL where to save the file.
|
||||
# \param file_url_or_string The URL where to save the file.
|
||||
#
|
||||
# \return A dictionary containing a key "status" with a status code and a key "message" with a message
|
||||
# explaining the status.
|
||||
# The status code can be one of "error", "cancelled", "success"
|
||||
@pyqtSlot(str, str, QUrl, result = "QVariantMap")
|
||||
def exportContainer(self, container_id, file_type, file_url):
|
||||
if not container_id or not file_type or not file_url:
|
||||
def exportContainer(self, container_id: str, file_type: str, file_url_or_string: Union[QUrl, str]) -> Dict[str, str]:
|
||||
if not container_id or not file_type or not file_url_or_string:
|
||||
return { "status": "error", "message": "Invalid arguments"}
|
||||
|
||||
if isinstance(file_url, QUrl):
|
||||
file_url = file_url.toLocalFile()
|
||||
if isinstance(file_url_or_string, QUrl):
|
||||
file_url = file_url_or_string.toLocalFile()
|
||||
else:
|
||||
file_url = file_url_or_string
|
||||
|
||||
if not file_url:
|
||||
return { "status": "error", "message": "Invalid path"}
|
||||
|
|
@ -320,7 +328,7 @@ class ContainerManager(QObject):
|
|||
mime_type = None
|
||||
if not file_type in self._container_name_filters:
|
||||
try:
|
||||
mime_type = UM.MimeTypeDatabase.getMimeTypeForFile(file_url)
|
||||
mime_type = MimeTypeDatabase.getMimeTypeForFile(file_url)
|
||||
except MimeTypeNotFoundError:
|
||||
return { "status": "error", "message": "Unknown File Type" }
|
||||
else:
|
||||
|
|
@ -331,7 +339,7 @@ class ContainerManager(QObject):
|
|||
return { "status": "error", "message": "Container not found"}
|
||||
container = containers[0]
|
||||
|
||||
if UM.Platform.isOSX() and "." in file_url:
|
||||
if Platform.isOSX() and "." in file_url:
|
||||
file_url = file_url[:file_url.rfind(".")]
|
||||
|
||||
for suffix in mime_type.suffixes:
|
||||
|
|
@ -340,7 +348,7 @@ class ContainerManager(QObject):
|
|||
else:
|
||||
file_url += "." + mime_type.preferredSuffix
|
||||
|
||||
if not UM.Platform.isWindows():
|
||||
if not Platform.isWindows():
|
||||
if os.path.exists(file_url):
|
||||
result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"),
|
||||
catalog.i18nc("@label", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_url))
|
||||
|
|
@ -355,7 +363,7 @@ class ContainerManager(QObject):
|
|||
if contents is None:
|
||||
return {"status": "error", "message": "Serialization returned None. Unable to write to file"}
|
||||
|
||||
with UM.SaveFile(file_url, "w") as f:
|
||||
with SaveFile(file_url, "w") as f:
|
||||
f.write(contents)
|
||||
|
||||
return { "status": "success", "message": "Succesfully exported container", "path": file_url}
|
||||
|
|
@ -367,22 +375,24 @@ class ContainerManager(QObject):
|
|||
# \return \type{Dict} dict with a 'status' key containing the string 'success' or 'error', and a 'message' key
|
||||
# containing a message for the user
|
||||
@pyqtSlot(QUrl, result = "QVariantMap")
|
||||
def importContainer(self, file_url):
|
||||
if not file_url:
|
||||
def importContainer(self, file_url_or_string: Union[QUrl, str]) -> Dict[str, str]:
|
||||
if not file_url_or_string:
|
||||
return { "status": "error", "message": "Invalid path"}
|
||||
|
||||
if isinstance(file_url, QUrl):
|
||||
file_url = file_url.toLocalFile()
|
||||
if isinstance(file_url_or_string, QUrl):
|
||||
file_url = file_url_or_string.toLocalFile()
|
||||
else:
|
||||
file_url = file_url_or_string
|
||||
|
||||
if not file_url or not os.path.exists(file_url):
|
||||
return { "status": "error", "message": "Invalid path" }
|
||||
|
||||
try:
|
||||
mime_type = UM.MimeTypeDatabase.getMimeTypeForFile(file_url)
|
||||
mime_type = MimeTypeDatabase.getMimeTypeForFile(file_url)
|
||||
except MimeTypeNotFoundError:
|
||||
return { "status": "error", "message": "Could not determine mime type of file" }
|
||||
|
||||
container_type = UM.Settings.ContainerRegistry.getContainerForMimeType(mime_type)
|
||||
container_type = self._container_registry.getContainerForMimeType(mime_type)
|
||||
if not container_type:
|
||||
return { "status": "error", "message": "Could not find a container to handle the specified file."}
|
||||
|
||||
|
|
@ -411,17 +421,17 @@ class ContainerManager(QObject):
|
|||
# \return \type{bool} True if successful, False if not.
|
||||
@pyqtSlot(result = bool)
|
||||
def updateQualityChanges(self):
|
||||
global_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if not global_stack:
|
||||
return False
|
||||
|
||||
self._machine_manager.blurSettings.emit()
|
||||
|
||||
for stack in cura.Settings.ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
|
||||
for stack in ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
|
||||
# Find the quality_changes container for this stack and merge the contents of the top container into it.
|
||||
quality_changes = stack.findContainer(type = "quality_changes")
|
||||
if not quality_changes or quality_changes.isReadOnly():
|
||||
UM.Logger.log("e", "Could not update quality of a nonexistant or read only quality profile in stack %s", stack.getId())
|
||||
Logger.log("e", "Could not update quality of a nonexistant or read only quality profile in stack %s", stack.getId())
|
||||
continue
|
||||
|
||||
self._performMerge(quality_changes, stack.getTop())
|
||||
|
|
@ -432,13 +442,13 @@ class ContainerManager(QObject):
|
|||
|
||||
## Clear the top-most (user) containers of the active stacks.
|
||||
@pyqtSlot()
|
||||
def clearUserContainers(self):
|
||||
def clearUserContainers(self) -> None:
|
||||
self._machine_manager.blurSettings.emit()
|
||||
|
||||
send_emits_containers = []
|
||||
|
||||
# Go through global and extruder stacks and clear their topmost container (the user settings).
|
||||
for stack in cura.Settings.ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
|
||||
for stack in ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
|
||||
container = stack.getTop()
|
||||
container.clear()
|
||||
send_emits_containers.append(container)
|
||||
|
|
@ -455,13 +465,13 @@ class ContainerManager(QObject):
|
|||
# \return \type{bool} True if the operation was successfully, False if not.
|
||||
@pyqtSlot(str, result = bool)
|
||||
def createQualityChanges(self, base_name):
|
||||
global_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if not global_stack:
|
||||
return False
|
||||
|
||||
active_quality_name = self._machine_manager.activeQualityName
|
||||
if active_quality_name == "":
|
||||
UM.Logger.log("w", "No quality container found in stack %s, cannot create profile", global_stack.getId())
|
||||
Logger.log("w", "No quality container found in stack %s, cannot create profile", global_stack.getId())
|
||||
return False
|
||||
|
||||
self._machine_manager.blurSettings.emit()
|
||||
|
|
@ -470,17 +480,17 @@ class ContainerManager(QObject):
|
|||
unique_name = self._container_registry.uniqueName(base_name)
|
||||
|
||||
# Go through the active stacks and create quality_changes containers from the user containers.
|
||||
for stack in cura.Settings.ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
|
||||
for stack in ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
|
||||
user_container = stack.getTop()
|
||||
quality_container = stack.findContainer(type = "quality")
|
||||
quality_changes_container = stack.findContainer(type = "quality_changes")
|
||||
if not quality_container or not quality_changes_container:
|
||||
UM.Logger.log("w", "No quality or quality changes container found in stack %s, ignoring it", stack.getId())
|
||||
Logger.log("w", "No quality or quality changes container found in stack %s, ignoring it", stack.getId())
|
||||
continue
|
||||
|
||||
extruder_id = None if stack is global_stack else QualityManager.getInstance().getParentMachineDefinition(stack.getBottom()).getId()
|
||||
new_changes = self._createQualityChanges(quality_container, unique_name,
|
||||
UM.Application.getInstance().getGlobalContainerStack().getBottom(),
|
||||
Application.getInstance().getGlobalContainerStack().getBottom(),
|
||||
extruder_id)
|
||||
self._performMerge(new_changes, quality_changes_container, clear_settings = False)
|
||||
self._performMerge(new_changes, user_container)
|
||||
|
|
@ -502,7 +512,7 @@ class ContainerManager(QObject):
|
|||
# \return \type{bool} True if successful, False if not.
|
||||
@pyqtSlot(str, result = bool)
|
||||
def removeQualityChanges(self, quality_name):
|
||||
UM.Logger.log("d", "Attempting to remove the quality change containers with name %s", quality_name)
|
||||
Logger.log("d", "Attempting to remove the quality change containers with name %s", quality_name)
|
||||
containers_found = False
|
||||
|
||||
if not quality_name:
|
||||
|
|
@ -512,7 +522,7 @@ class ContainerManager(QObject):
|
|||
activate_quality = quality_name == self._machine_manager.activeQualityName
|
||||
activate_quality_type = None
|
||||
|
||||
global_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if not global_stack or not quality_name:
|
||||
return ""
|
||||
machine_definition = global_stack.getBottom()
|
||||
|
|
@ -524,7 +534,7 @@ class ContainerManager(QObject):
|
|||
self._container_registry.removeContainer(container.getId())
|
||||
|
||||
if not containers_found:
|
||||
UM.Logger.log("d", "Unable to remove quality containers, as we did not find any by the name of %s", quality_name)
|
||||
Logger.log("d", "Unable to remove quality containers, as we did not find any by the name of %s", quality_name)
|
||||
|
||||
elif activate_quality:
|
||||
definition_id = "fdmprinter" if not self._machine_manager.filterQualityByMachine else self._machine_manager.activeDefinitionId
|
||||
|
|
@ -547,15 +557,15 @@ class ContainerManager(QObject):
|
|||
# \return True if successful, False if not.
|
||||
@pyqtSlot(str, str, result = bool)
|
||||
def renameQualityChanges(self, quality_name, new_name):
|
||||
UM.Logger.log("d", "User requested QualityChanges container rename of %s to %s", quality_name, new_name)
|
||||
Logger.log("d", "User requested QualityChanges container rename of %s to %s", quality_name, new_name)
|
||||
if not quality_name or not new_name:
|
||||
return False
|
||||
|
||||
if quality_name == new_name:
|
||||
UM.Logger.log("w", "Unable to rename %s to %s, because they are the same.", quality_name, new_name)
|
||||
Logger.log("w", "Unable to rename %s to %s, because they are the same.", quality_name, new_name)
|
||||
return True
|
||||
|
||||
global_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if not global_stack:
|
||||
return False
|
||||
|
||||
|
|
@ -572,7 +582,7 @@ class ContainerManager(QObject):
|
|||
container_registry.renameContainer(container.getId(), new_name, self._createUniqueId(stack_id, new_name))
|
||||
|
||||
if not containers_to_rename:
|
||||
UM.Logger.log("e", "Unable to rename %s, because we could not find the profile", quality_name)
|
||||
Logger.log("e", "Unable to rename %s, because we could not find the profile", quality_name)
|
||||
|
||||
self._machine_manager.activeQualityChanged.emit()
|
||||
return True
|
||||
|
|
@ -588,12 +598,12 @@ class ContainerManager(QObject):
|
|||
# \return A string containing the name of the duplicated containers, or an empty string if it failed.
|
||||
@pyqtSlot(str, str, result = str)
|
||||
def duplicateQualityOrQualityChanges(self, quality_name, base_name):
|
||||
global_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if not global_stack or not quality_name:
|
||||
return ""
|
||||
machine_definition = global_stack.getBottom()
|
||||
|
||||
active_stacks = cura.Settings.ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks()
|
||||
active_stacks = ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks()
|
||||
material_containers = [stack.findContainer(type="material") for stack in active_stacks]
|
||||
|
||||
result = self._duplicateQualityOrQualityChangesForMachineType(quality_name, base_name,
|
||||
|
|
@ -609,16 +619,16 @@ class ContainerManager(QObject):
|
|||
# \param material_instances \type{List[InstanceContainer]}
|
||||
# \return \type{str} the name of the newly created container.
|
||||
def _duplicateQualityOrQualityChangesForMachineType(self, quality_name, base_name, machine_definition, material_instances):
|
||||
UM.Logger.log("d", "Attempting to duplicate the quality %s", quality_name)
|
||||
Logger.log("d", "Attempting to duplicate the quality %s", quality_name)
|
||||
|
||||
if base_name is None:
|
||||
base_name = quality_name
|
||||
# Try to find a Quality with the name.
|
||||
container = QualityManager.getInstance().findQualityByName(quality_name, machine_definition, material_instances)
|
||||
if container:
|
||||
UM.Logger.log("d", "We found a quality to duplicate.")
|
||||
Logger.log("d", "We found a quality to duplicate.")
|
||||
return self._duplicateQualityForMachineType(container, base_name, machine_definition)
|
||||
UM.Logger.log("d", "We found a quality_changes to duplicate.")
|
||||
Logger.log("d", "We found a quality_changes to duplicate.")
|
||||
# Assume it is a quality changes.
|
||||
return self._duplicateQualityChangesForMachineType(quality_name, base_name, machine_definition)
|
||||
|
||||
|
|
@ -662,14 +672,14 @@ class ContainerManager(QObject):
|
|||
return new_change_instances
|
||||
|
||||
@pyqtSlot(str, result = str)
|
||||
def duplicateMaterial(self, material_id):
|
||||
def duplicateMaterial(self, material_id: str) -> str:
|
||||
containers = self._container_registry.findInstanceContainers(id=material_id)
|
||||
if not containers:
|
||||
UM.Logger.log("d", "Unable to duplicate the material with id %s, because it doesn't exist.", material_id)
|
||||
Logger.log("d", "Unable to duplicate the material with id %s, because it doesn't exist.", material_id)
|
||||
return ""
|
||||
|
||||
# Ensure all settings are saved.
|
||||
UM.Application.getInstance().saveSettings()
|
||||
Application.getInstance().saveSettings()
|
||||
|
||||
# Create a new ID & container to hold the data.
|
||||
new_id = self._container_registry.uniqueName(material_id)
|
||||
|
|
@ -686,13 +696,13 @@ class ContainerManager(QObject):
|
|||
|
||||
## Get the singleton instance for this class.
|
||||
@classmethod
|
||||
def getInstance(cls):
|
||||
def getInstance(cls) -> "ContainerManager":
|
||||
# Note: Explicit use of class name to prevent issues with inheritance.
|
||||
if ContainerManager.__instance is None:
|
||||
ContainerManager.__instance = cls()
|
||||
return ContainerManager.__instance
|
||||
|
||||
__instance = None
|
||||
__instance = None # type: "ContainerManager"
|
||||
|
||||
# Factory function, used by QML
|
||||
@staticmethod
|
||||
|
|
@ -711,16 +721,16 @@ class ContainerManager(QObject):
|
|||
if clear_settings:
|
||||
merge.clear()
|
||||
|
||||
def _updateContainerNameFilters(self):
|
||||
def _updateContainerNameFilters(self) -> None:
|
||||
self._container_name_filters = {}
|
||||
for plugin_id, container_type in UM.Settings.ContainerRegistry.getContainerTypes():
|
||||
for plugin_id, container_type in self._container_registry.getContainerTypes():
|
||||
# Ignore default container types since those are not plugins
|
||||
if container_type in (UM.Settings.InstanceContainer, UM.Settings.ContainerStack, UM.Settings.DefinitionContainer):
|
||||
if container_type in (InstanceContainer, ContainerStack, DefinitionContainer):
|
||||
continue
|
||||
|
||||
serialize_type = ""
|
||||
try:
|
||||
plugin_metadata = UM.PluginRegistry.getInstance().getMetaData(plugin_id)
|
||||
plugin_metadata = PluginRegistry.getInstance().getMetaData(plugin_id)
|
||||
if plugin_metadata:
|
||||
serialize_type = plugin_metadata["settings_container"]["type"]
|
||||
else:
|
||||
|
|
@ -728,7 +738,7 @@ class ContainerManager(QObject):
|
|||
except KeyError as e:
|
||||
continue
|
||||
|
||||
mime_type = UM.Settings.ContainerRegistry.getMimeTypeForContainer(container_type)
|
||||
mime_type = self._container_registry.getMimeTypeForContainer(container_type)
|
||||
|
||||
entry = {
|
||||
"type": serialize_type,
|
||||
|
|
@ -737,7 +747,7 @@ class ContainerManager(QObject):
|
|||
}
|
||||
|
||||
suffix = mime_type.preferredSuffix
|
||||
if UM.Platform.isOSX() and "." in suffix:
|
||||
if Platform.isOSX() and "." in suffix:
|
||||
# OSX's File dialog is stupid and does not allow selecting files with a . in its name
|
||||
suffix = suffix[suffix.index(".") + 1:]
|
||||
|
||||
|
|
@ -746,7 +756,7 @@ class ContainerManager(QObject):
|
|||
if suffix == mime_type.preferredSuffix:
|
||||
continue
|
||||
|
||||
if UM.Platform.isOSX() and "." in suffix:
|
||||
if Platform.isOSX() and "." in suffix:
|
||||
# OSX's File dialog is stupid and does not allow selecting files with a . in its name
|
||||
suffix = suffix[suffix.index("."):]
|
||||
|
||||
|
|
@ -791,7 +801,7 @@ class ContainerManager(QObject):
|
|||
base_id = machine_definition.getId() if extruder_id is None else extruder_id
|
||||
|
||||
# Create a new quality_changes container for the quality.
|
||||
quality_changes = UM.Settings.InstanceContainer(self._createUniqueId(base_id, new_name))
|
||||
quality_changes = InstanceContainer(self._createUniqueId(base_id, new_name))
|
||||
quality_changes.setName(new_name)
|
||||
quality_changes.addMetaDataEntry("type", "quality_changes")
|
||||
quality_changes.addMetaDataEntry("quality_type", quality_container.getMetaDataEntry("quality_type"))
|
||||
|
|
@ -813,7 +823,7 @@ class ContainerManager(QObject):
|
|||
#
|
||||
# \param QVariant<QUrl>, essentially a list with QUrl objects.
|
||||
# \return Dict with keys status, text
|
||||
@pyqtSlot(QVariant, result="QVariantMap")
|
||||
@pyqtSlot("QVariantList", result="QVariantMap")
|
||||
def importProfiles(self, file_urls):
|
||||
status = "ok"
|
||||
results = {"ok": [], "error": []}
|
||||
|
|
@ -826,7 +836,7 @@ class ContainerManager(QObject):
|
|||
if not path.endswith(".curaprofile"):
|
||||
continue
|
||||
|
||||
single_result = UM.Settings.ContainerRegistry.getInstance().importProfile(path)
|
||||
single_result = self._container_registry.importProfile(path)
|
||||
if single_result["status"] == "error":
|
||||
status = "error"
|
||||
results[single_result["status"]].append(single_result["message"])
|
||||
|
|
@ -843,13 +853,13 @@ class ContainerManager(QObject):
|
|||
path = file_url.toLocalFile()
|
||||
if not path:
|
||||
return
|
||||
return UM.Settings.ContainerRegistry.getInstance().importProfile(path)
|
||||
return self._container_registry.importProfile(path)
|
||||
|
||||
@pyqtSlot("QVariantList", QUrl, str)
|
||||
def exportProfile(self, instance_id, file_url, file_type):
|
||||
def exportProfile(self, instance_id: str, file_url: QUrl, file_type: str) -> None:
|
||||
if not file_url.isValid():
|
||||
return
|
||||
path = file_url.toLocalFile()
|
||||
if not path:
|
||||
return
|
||||
UM.Settings.ContainerRegistry.getInstance().exportProfile(instance_id, path, file_type)
|
||||
self._container_registry.exportProfile(instance_id, path, file_type)
|
||||
|
|
|
|||
163
cura/Settings/ExtruderManager.py
Normal file → Executable file
163
cura/Settings/ExtruderManager.py
Normal file → Executable file
|
|
@ -4,13 +4,16 @@
|
|||
from PyQt5.QtCore import pyqtSignal, pyqtProperty, QObject, QVariant #For communicating data and events to Qt.
|
||||
from UM.FlameProfiler import pyqtSlot
|
||||
|
||||
import UM.Application #To get the global container stack to find the current machine.
|
||||
import UM.Logger
|
||||
from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator #To find which extruders are used in the scene.
|
||||
from UM.Scene.SceneNode import SceneNode #To find which extruders are used in the scene.
|
||||
import UM.Settings.ContainerRegistry #Finding containers by ID.
|
||||
import UM.Settings.SettingFunction
|
||||
|
||||
from UM.Application import Application #To get the global container stack to find the current machine.
|
||||
from UM.Logger import Logger
|
||||
from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
|
||||
from UM.Scene.SceneNode import SceneNode
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry #Finding containers by ID.
|
||||
from UM.Settings.InstanceContainer import InstanceContainer
|
||||
from UM.Settings.SettingFunction import SettingFunction
|
||||
from UM.Settings.ContainerStack import ContainerStack
|
||||
from UM.Settings.DefinitionContainer import DefinitionContainer
|
||||
from typing import Optional
|
||||
|
||||
## Manages all existing extruder stacks.
|
||||
#
|
||||
|
|
@ -31,7 +34,7 @@ class ExtruderManager(QObject):
|
|||
super().__init__(parent)
|
||||
self._extruder_trains = { } #Per machine, a dictionary of extruder container stack IDs.
|
||||
self._active_extruder_index = 0
|
||||
UM.Application.getInstance().globalContainerStackChanged.connect(self.__globalContainerStackChanged)
|
||||
Application.getInstance().globalContainerStackChanged.connect(self.__globalContainerStackChanged)
|
||||
self._global_container_stack_definition_id = None
|
||||
self._addCurrentMachineExtruders()
|
||||
|
||||
|
|
@ -42,34 +45,35 @@ class ExtruderManager(QObject):
|
|||
#
|
||||
# \return The unique ID of the currently active extruder stack.
|
||||
@pyqtProperty(str, notify = activeExtruderChanged)
|
||||
def activeExtruderStackId(self):
|
||||
if not UM.Application.getInstance().getGlobalContainerStack():
|
||||
def activeExtruderStackId(self) -> Optional[str]:
|
||||
if not Application.getInstance().getGlobalContainerStack():
|
||||
return None # No active machine, so no active extruder.
|
||||
try:
|
||||
return self._extruder_trains[UM.Application.getInstance().getGlobalContainerStack().getId()][str(self._active_extruder_index)].getId()
|
||||
return self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()][str(self._active_extruder_index)].getId()
|
||||
except KeyError: # Extruder index could be -1 if the global tab is selected, or the entry doesn't exist if the machine definition is wrong.
|
||||
return None
|
||||
|
||||
## Return extruder count according to extruder trains.
|
||||
@pyqtProperty(int, notify = extrudersChanged)
|
||||
def extruderCount(self):
|
||||
if not UM.Application.getInstance().getGlobalContainerStack():
|
||||
if not Application.getInstance().getGlobalContainerStack():
|
||||
return 0 # No active machine, so no extruders.
|
||||
try:
|
||||
return len(self._extruder_trains[UM.Application.getInstance().getGlobalContainerStack().getId()])
|
||||
return len(self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()])
|
||||
except KeyError:
|
||||
return 0
|
||||
|
||||
@pyqtProperty("QVariantMap", notify=extrudersChanged)
|
||||
def extruderIds(self):
|
||||
map = {}
|
||||
for position in self._extruder_trains[UM.Application.getInstance().getGlobalContainerStack().getId()]:
|
||||
map[position] = self._extruder_trains[UM.Application.getInstance().getGlobalContainerStack().getId()][position].getId()
|
||||
for position in self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()]:
|
||||
map[position] = self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()][position].getId()
|
||||
return map
|
||||
|
||||
@pyqtSlot(str, result = str)
|
||||
def getQualityChangesIdByExtruderStackId(self, id):
|
||||
for position in self._extruder_trains[UM.Application.getInstance().getGlobalContainerStack().getId()]:
|
||||
extruder = self._extruder_trains[UM.Application.getInstance().getGlobalContainerStack().getId()][position]
|
||||
def getQualityChangesIdByExtruderStackId(self, id: str) -> str:
|
||||
for position in self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()]:
|
||||
extruder = self._extruder_trains[Application.getInstance().getGlobalContainerStack().getId()][position]
|
||||
if extruder.getId() == id:
|
||||
return extruder.findContainer(type = "quality_changes").getId()
|
||||
|
||||
|
|
@ -86,7 +90,7 @@ class ExtruderManager(QObject):
|
|||
#
|
||||
# \return The extruder manager.
|
||||
@classmethod
|
||||
def getInstance(cls):
|
||||
def getInstance(cls) -> "ExtruderManager":
|
||||
if not cls.__instance:
|
||||
cls.__instance = ExtruderManager()
|
||||
return cls.__instance
|
||||
|
|
@ -95,16 +99,27 @@ class ExtruderManager(QObject):
|
|||
#
|
||||
# \param index The index of the new active extruder.
|
||||
@pyqtSlot(int)
|
||||
def setActiveExtruderIndex(self, index):
|
||||
def setActiveExtruderIndex(self, index: int) -> None:
|
||||
self._active_extruder_index = index
|
||||
self.activeExtruderChanged.emit()
|
||||
|
||||
@pyqtProperty(int, notify = activeExtruderChanged)
|
||||
def activeExtruderIndex(self):
|
||||
def activeExtruderIndex(self) -> int:
|
||||
return self._active_extruder_index
|
||||
|
||||
def getActiveExtruderStack(self):
|
||||
global_container_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
## Gets the extruder name of an extruder of the currently active machine.
|
||||
#
|
||||
# \param index The index of the extruder whose name to get.
|
||||
@pyqtSlot(int, result = str)
|
||||
def getExtruderName(self, index):
|
||||
try:
|
||||
return list(self.getActiveExtruderStacks())[index].getName()
|
||||
except IndexError:
|
||||
return ""
|
||||
|
||||
def getActiveExtruderStack(self) -> ContainerStack:
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
|
||||
if global_container_stack:
|
||||
if global_container_stack.getId() in self._extruder_trains:
|
||||
if str(self._active_extruder_index) in self._extruder_trains[global_container_stack.getId()]:
|
||||
|
|
@ -113,31 +128,38 @@ class ExtruderManager(QObject):
|
|||
|
||||
## Get an extruder stack by index
|
||||
def getExtruderStack(self, index):
|
||||
global_container_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if global_container_stack:
|
||||
if global_container_stack.getId() in self._extruder_trains:
|
||||
if str(index) in self._extruder_trains[global_container_stack.getId()]:
|
||||
return self._extruder_trains[global_container_stack.getId()][str(index)]
|
||||
return None
|
||||
|
||||
## Get all extruder stacks
|
||||
def getExtruderStacks(self):
|
||||
result = []
|
||||
for i in range(self.extruderCount):
|
||||
result.append(self.getExtruderStack(i))
|
||||
return result
|
||||
|
||||
## Adds all extruders of a specific machine definition to the extruder
|
||||
# manager.
|
||||
#
|
||||
# \param machine_definition The machine definition to add the extruders for.
|
||||
# \param machine_id The machine_id to add the extruders for.
|
||||
def addMachineExtruders(self, machine_definition, machine_id):
|
||||
def addMachineExtruders(self, machine_definition: DefinitionContainer, machine_id: str) -> None:
|
||||
changed = False
|
||||
machine_definition_id = machine_definition.getId()
|
||||
if machine_id not in self._extruder_trains:
|
||||
self._extruder_trains[machine_id] = { }
|
||||
changed = True
|
||||
container_registry = UM.Settings.ContainerRegistry.getInstance()
|
||||
container_registry = ContainerRegistry.getInstance()
|
||||
if container_registry:
|
||||
# Add the extruder trains that don't exist yet.
|
||||
for extruder_definition in container_registry.findDefinitionContainers(machine = machine_definition_id):
|
||||
position = extruder_definition.getMetaDataEntry("position", None)
|
||||
if not position:
|
||||
UM.Logger.log("w", "Extruder definition %s specifies no position metadata entry.", extruder_definition.getId())
|
||||
Logger.log("w", "Extruder definition %s specifies no position metadata entry.", extruder_definition.getId())
|
||||
if not container_registry.findContainerStacks(machine = machine_id, position = position): # Doesn't exist yet.
|
||||
self.createExtruderTrain(extruder_definition, machine_definition, position, machine_id)
|
||||
changed = True
|
||||
|
|
@ -148,7 +170,7 @@ class ExtruderManager(QObject):
|
|||
self._extruder_trains[machine_id][extruder_train.getMetaDataEntry("position")] = extruder_train
|
||||
|
||||
# regardless of what the next stack is, we have to set it again, because of signal routing.
|
||||
extruder_train.setNextStack(UM.Application.getInstance().getGlobalContainerStack())
|
||||
extruder_train.setNextStack(Application.getInstance().getGlobalContainerStack())
|
||||
changed = True
|
||||
if changed:
|
||||
self.extrudersChanged.emit(machine_id)
|
||||
|
|
@ -177,14 +199,15 @@ class ExtruderManager(QObject):
|
|||
# \param machine_definition The machine that the extruder train belongs to.
|
||||
# \param position The position of this extruder train in the extruder slots of the machine.
|
||||
# \param machine_id The id of the "global" stack this extruder is linked to.
|
||||
def createExtruderTrain(self, extruder_definition, machine_definition, position, machine_id):
|
||||
def createExtruderTrain(self, extruder_definition: DefinitionContainer, machine_definition: DefinitionContainer,
|
||||
position, machine_id: str) -> None:
|
||||
# Cache some things.
|
||||
container_registry = UM.Settings.ContainerRegistry.getInstance()
|
||||
machine_definition_id = UM.Application.getInstance().getMachineManager().getQualityDefinitionId(machine_definition)
|
||||
container_registry = ContainerRegistry.getInstance()
|
||||
machine_definition_id = Application.getInstance().getMachineManager().getQualityDefinitionId(machine_definition)
|
||||
|
||||
# Create a container stack for this extruder.
|
||||
extruder_stack_id = container_registry.uniqueName(extruder_definition.getId())
|
||||
container_stack = UM.Settings.ContainerStack(extruder_stack_id)
|
||||
container_stack = ContainerStack(extruder_stack_id)
|
||||
container_stack.setName(extruder_definition.getName()) # Take over the display name to display the stack with.
|
||||
container_stack.addMetaDataEntry("type", "extruder_train")
|
||||
container_stack.addMetaDataEntry("machine", machine_id)
|
||||
|
|
@ -204,7 +227,7 @@ class ExtruderManager(QObject):
|
|||
if len(preferred_variants) >= 1:
|
||||
variant = preferred_variants[0]
|
||||
else:
|
||||
UM.Logger.log("w", "The preferred variant \"%s\" of machine %s doesn't exist or is not a variant profile.", preferred_variant_id, machine_id)
|
||||
Logger.log("w", "The preferred variant \"%s\" of machine %s doesn't exist or is not a variant profile.", preferred_variant_id, machine_id)
|
||||
# And leave it at the default variant.
|
||||
container_stack.addContainer(variant)
|
||||
|
||||
|
|
@ -221,7 +244,13 @@ class ExtruderManager(QObject):
|
|||
material = materials[0]
|
||||
preferred_material_id = machine_definition.getMetaDataEntry("preferred_material")
|
||||
if preferred_material_id:
|
||||
search_criteria = { "type": "material", "id": preferred_material_id}
|
||||
global_stack = ContainerRegistry.getInstance().findContainerStacks(id = machine_id)
|
||||
if global_stack:
|
||||
approximate_material_diameter = round(global_stack[0].getProperty("material_diameter", "value"))
|
||||
else:
|
||||
approximate_material_diameter = round(machine_definition.getProperty("material_diameter", "value"))
|
||||
|
||||
search_criteria = { "type": "material", "id": preferred_material_id, "approximate_diameter": approximate_material_diameter}
|
||||
if machine_definition.getMetaDataEntry("has_machine_materials"):
|
||||
search_criteria["definition"] = machine_definition_id
|
||||
|
||||
|
|
@ -232,9 +261,14 @@ class ExtruderManager(QObject):
|
|||
|
||||
preferred_materials = container_registry.findInstanceContainers(**search_criteria)
|
||||
if len(preferred_materials) >= 1:
|
||||
material = preferred_materials[0]
|
||||
# In some cases we get multiple materials. In that case, prefer materials that are marked as read only.
|
||||
read_only_preferred_materials = [preferred_material for preferred_material in preferred_materials if preferred_material.isReadOnly()]
|
||||
if len(read_only_preferred_materials) >= 1:
|
||||
material = read_only_preferred_materials[0]
|
||||
else:
|
||||
material = preferred_materials[0]
|
||||
else:
|
||||
UM.Logger.log("w", "The preferred material \"%s\" of machine %s doesn't exist or is not a material profile.", preferred_material_id, machine_id)
|
||||
Logger.log("w", "The preferred material \"%s\" of machine %s doesn't exist or is not a material profile.", preferred_material_id, machine_id)
|
||||
# And leave it at the default material.
|
||||
container_stack.addContainer(material)
|
||||
|
||||
|
|
@ -253,11 +287,11 @@ class ExtruderManager(QObject):
|
|||
if preferred_quality:
|
||||
search_criteria["id"] = preferred_quality
|
||||
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
|
||||
if not containers and preferred_quality:
|
||||
UM.Logger.log("w", "The preferred quality \"%s\" of machine %s doesn't exist or is not a quality profile.", preferred_quality, machine_id)
|
||||
Logger.log("w", "The preferred quality \"%s\" of machine %s doesn't exist or is not a quality profile.", preferred_quality, machine_id)
|
||||
search_criteria.pop("id", None)
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
|
||||
if containers:
|
||||
quality = containers[0]
|
||||
|
||||
|
|
@ -270,7 +304,7 @@ class ExtruderManager(QObject):
|
|||
if user_profile: # There was already a user profile, loaded from settings.
|
||||
user_profile = user_profile[0]
|
||||
else:
|
||||
user_profile = UM.Settings.InstanceContainer(extruder_stack_id + "_current_settings") # Add an empty user profile.
|
||||
user_profile = InstanceContainer(extruder_stack_id + "_current_settings") # Add an empty user profile.
|
||||
user_profile.addMetaDataEntry("type", "user")
|
||||
user_profile.addMetaDataEntry("extruder", extruder_stack_id)
|
||||
user_profile.setDefinition(machine_definition)
|
||||
|
|
@ -278,7 +312,7 @@ class ExtruderManager(QObject):
|
|||
container_stack.addContainer(user_profile)
|
||||
|
||||
# regardless of what the next stack is, we have to set it again, because of signal routing.
|
||||
container_stack.setNextStack(UM.Application.getInstance().getGlobalContainerStack())
|
||||
container_stack.setNextStack(Application.getInstance().getGlobalContainerStack())
|
||||
|
||||
container_registry.addContainer(container_stack)
|
||||
|
||||
|
|
@ -291,14 +325,14 @@ class ExtruderManager(QObject):
|
|||
# \param property \type{str} The property to get.
|
||||
# \return \type{List} the list of results
|
||||
def getAllExtruderSettings(self, setting_key, property):
|
||||
global_container_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if global_container_stack.getProperty("machine_extruder_count", "value") <= 1:
|
||||
return [global_container_stack.getProperty(setting_key, property)]
|
||||
|
||||
result = []
|
||||
for index in self.extruderIds:
|
||||
extruder_stack_id = self.extruderIds[str(index)]
|
||||
stack = UM.Settings.ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
|
||||
stack = ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
|
||||
result.append(stack.getProperty(setting_key, property))
|
||||
return result
|
||||
|
||||
|
|
@ -313,8 +347,8 @@ class ExtruderManager(QObject):
|
|||
#
|
||||
# \return A list of extruder stacks.
|
||||
def getUsedExtruderStacks(self):
|
||||
global_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
container_registry = UM.Settings.ContainerRegistry.getInstance()
|
||||
global_stack = Application.getInstance().getGlobalContainerStack()
|
||||
container_registry = ContainerRegistry.getInstance()
|
||||
|
||||
if global_stack.getProperty("machine_extruder_count", "value") <= 1: #For single extrusion.
|
||||
return [global_stack]
|
||||
|
|
@ -324,7 +358,7 @@ class ExtruderManager(QObject):
|
|||
#Get the extruders of all meshes in the scene.
|
||||
support_enabled = False
|
||||
support_interface_enabled = False
|
||||
scene_root = UM.Application.getInstance().getController().getScene().getRoot()
|
||||
scene_root = Application.getInstance().getController().getScene().getRoot()
|
||||
meshes = [node for node in DepthFirstIterator(scene_root) if type(node) is SceneNode and node.isSelectable()] #Only use the nodes that will be printed.
|
||||
for mesh in meshes:
|
||||
extruder_stack_id = mesh.callDecoration("getActiveExtruder")
|
||||
|
|
@ -355,7 +389,7 @@ class ExtruderManager(QObject):
|
|||
try:
|
||||
return [container_registry.findContainerStacks(id = stack_id)[0] for stack_id in used_extruder_stack_ids]
|
||||
except IndexError: # One or more of the extruders was not found.
|
||||
UM.Logger.log("e", "Unable to find one or more of the extruders in %s", used_extruder_stack_ids)
|
||||
Logger.log("e", "Unable to find one or more of the extruders in %s", used_extruder_stack_ids)
|
||||
return []
|
||||
|
||||
## Removes the container stack and user profile for the extruders for a specific machine.
|
||||
|
|
@ -363,27 +397,26 @@ class ExtruderManager(QObject):
|
|||
# \param machine_id The machine to remove the extruders for.
|
||||
def removeMachineExtruders(self, machine_id):
|
||||
for extruder in self.getMachineExtruders(machine_id):
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(type = "user", extruder = extruder.getId())
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(type = "user", extruder = extruder.getId())
|
||||
for container in containers:
|
||||
UM.Settings.ContainerRegistry.getInstance().removeContainer(container.getId())
|
||||
UM.Settings.ContainerRegistry.getInstance().removeContainer(extruder.getId())
|
||||
ContainerRegistry.getInstance().removeContainer(container.getId())
|
||||
ContainerRegistry.getInstance().removeContainer(extruder.getId())
|
||||
|
||||
## Returns extruders for a specific machine.
|
||||
#
|
||||
# \param machine_id The machine to get the extruders of.
|
||||
def getMachineExtruders(self, machine_id):
|
||||
if machine_id not in self._extruder_trains:
|
||||
UM.Logger.log("w", "Tried to get the extruder trains for machine %s, which doesn't exist.", machine_id)
|
||||
return
|
||||
for name in self._extruder_trains[machine_id]:
|
||||
yield self._extruder_trains[machine_id][name]
|
||||
Logger.log("w", "Tried to get the extruder trains for machine %s, which doesn't exist.", machine_id)
|
||||
return []
|
||||
return [self._extruder_trains[machine_id][name] for name in self._extruder_trains[machine_id]]
|
||||
|
||||
## Returns a list containing the global stack and active extruder stacks.
|
||||
#
|
||||
# The first element is the global container stack, followed by any extruder stacks.
|
||||
# \return \type{List[ContainerStack]}
|
||||
def getActiveGlobalAndExtruderStacks(self):
|
||||
global_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if not global_stack:
|
||||
return None
|
||||
|
||||
|
|
@ -395,7 +428,7 @@ class ExtruderManager(QObject):
|
|||
#
|
||||
# \return \type{List[ContainerStack]} a list of
|
||||
def getActiveExtruderStacks(self):
|
||||
global_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_stack = Application.getInstance().getGlobalContainerStack()
|
||||
|
||||
result = []
|
||||
if global_stack:
|
||||
|
|
@ -403,17 +436,17 @@ class ExtruderManager(QObject):
|
|||
result.append(self._extruder_trains[global_stack.getId()][extruder])
|
||||
return result
|
||||
|
||||
def __globalContainerStackChanged(self):
|
||||
def __globalContainerStackChanged(self) -> None:
|
||||
self._addCurrentMachineExtruders()
|
||||
global_container_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if global_container_stack and global_container_stack.getBottom() and global_container_stack.getBottom().getId() != self._global_container_stack_definition_id:
|
||||
self._global_container_stack_definition_id = global_container_stack.getBottom().getId()
|
||||
self.globalContainerStackDefinitionChanged.emit()
|
||||
self.activeExtruderChanged.emit()
|
||||
|
||||
## Adds the extruders of the currently active machine.
|
||||
def _addCurrentMachineExtruders(self):
|
||||
global_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
def _addCurrentMachineExtruders(self) -> None:
|
||||
global_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if global_stack and global_stack.getBottom():
|
||||
self.addMachineExtruders(global_stack.getBottom(), global_stack.getId())
|
||||
|
||||
|
|
@ -427,7 +460,7 @@ class ExtruderManager(QObject):
|
|||
# If no extruder has the value, the list will contain the global value.
|
||||
@staticmethod
|
||||
def getExtruderValues(key):
|
||||
global_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_stack = Application.getInstance().getGlobalContainerStack()
|
||||
|
||||
result = []
|
||||
for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
|
||||
|
|
@ -436,7 +469,7 @@ class ExtruderManager(QObject):
|
|||
if value is None:
|
||||
continue
|
||||
|
||||
if isinstance(value, UM.Settings.SettingFunction):
|
||||
if isinstance(value, SettingFunction):
|
||||
value = value(extruder)
|
||||
|
||||
result.append(value)
|
||||
|
|
@ -472,10 +505,10 @@ class ExtruderManager(QObject):
|
|||
|
||||
if extruder:
|
||||
value = extruder.getRawProperty(key, "value")
|
||||
if isinstance(value, UM.Settings.SettingFunction):
|
||||
if isinstance(value, SettingFunction):
|
||||
value = value(extruder)
|
||||
else: #Just a value from global.
|
||||
value = UM.Application.getInstance().getGlobalContainerStack().getProperty(key, "value")
|
||||
value = Application.getInstance().getGlobalContainerStack().getProperty(key, "value")
|
||||
|
||||
return value
|
||||
|
||||
|
|
@ -488,7 +521,7 @@ class ExtruderManager(QObject):
|
|||
# \return The effective value
|
||||
@staticmethod
|
||||
def getResolveOrValue(key):
|
||||
global_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_stack = Application.getInstance().getGlobalContainerStack()
|
||||
|
||||
resolved_value = global_stack.getProperty(key, "resolve")
|
||||
if resolved_value is not None:
|
||||
|
|
|
|||
|
|
@ -4,8 +4,9 @@
|
|||
from PyQt5.QtCore import Qt, pyqtSignal, pyqtProperty
|
||||
|
||||
import UM.Qt.ListModel
|
||||
from UM.Application import Application
|
||||
|
||||
from . import ExtruderManager
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
|
||||
## Model that holds extruders.
|
||||
#
|
||||
|
|
@ -55,7 +56,7 @@ class ExtrudersModel(UM.Qt.ListModel.ListModel):
|
|||
self._active_extruder_stack = None
|
||||
|
||||
#Listen to changes.
|
||||
UM.Application.getInstance().globalContainerStackChanged.connect(self._updateExtruders)
|
||||
Application.getInstance().globalContainerStackChanged.connect(self._updateExtruders)
|
||||
manager = ExtruderManager.getInstance()
|
||||
|
||||
self._updateExtruders()
|
||||
|
|
@ -105,8 +106,7 @@ class ExtrudersModel(UM.Qt.ListModel.ListModel):
|
|||
|
||||
def _onExtruderStackContainersChanged(self, container):
|
||||
# The ExtrudersModel needs to be updated when the material-name or -color changes, because the user identifies extruders by material-name
|
||||
if container.getMetaDataEntry("type") == "material":
|
||||
self._updateExtruders()
|
||||
self._updateExtruders()
|
||||
|
||||
modelChanged = pyqtSignal()
|
||||
|
||||
|
|
@ -121,7 +121,7 @@ class ExtrudersModel(UM.Qt.ListModel.ListModel):
|
|||
|
||||
items = []
|
||||
|
||||
global_container_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if global_container_stack:
|
||||
if self._add_global:
|
||||
material = global_container_stack.findContainer({ "type": "material" })
|
||||
|
|
|
|||
457
cura/Settings/MachineManager.py
Normal file → Executable file
457
cura/Settings/MachineManager.py
Normal file → Executable file
|
|
@ -1,7 +1,8 @@
|
|||
# Copyright (c) 2016 Ultimaker B.V.
|
||||
# Copyright (c) 2017 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
from typing import Union
|
||||
|
||||
from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal
|
||||
from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal, QTimer
|
||||
from UM.FlameProfiler import pyqtSlot
|
||||
from PyQt5.QtWidgets import QMessageBox
|
||||
from UM import Util
|
||||
|
|
@ -11,23 +12,32 @@ from UM.Preferences import Preferences
|
|||
from UM.Logger import Logger
|
||||
from UM.Message import Message
|
||||
|
||||
import UM.Settings
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
from UM.Settings.ContainerStack import ContainerStack
|
||||
from UM.Settings.InstanceContainer import InstanceContainer
|
||||
from UM.Settings.SettingFunction import SettingFunction
|
||||
from UM.Signal import postponeSignals
|
||||
|
||||
from cura.QualityManager import QualityManager
|
||||
from cura.PrinterOutputDevice import PrinterOutputDevice
|
||||
from . import ExtruderManager
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
|
||||
from UM.i18n import i18nCatalog
|
||||
catalog = i18nCatalog("cura")
|
||||
|
||||
from typing import TYPE_CHECKING, Optional
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from UM.Settings.DefinitionContainer import DefinitionContainer
|
||||
|
||||
import os
|
||||
|
||||
class MachineManager(QObject):
|
||||
def __init__(self, parent = None):
|
||||
super().__init__(parent)
|
||||
|
||||
self._active_container_stack = None
|
||||
self._global_container_stack = None
|
||||
self._active_container_stack = None # type: ContainerStack
|
||||
self._global_container_stack = None # type: ContainerStack
|
||||
|
||||
Application.getInstance().globalContainerStackChanged.connect(self._onGlobalContainerChanged)
|
||||
## When the global container is changed, active material probably needs to be updated.
|
||||
|
|
@ -36,10 +46,10 @@ class MachineManager(QObject):
|
|||
self.globalContainerChanged.connect(self.activeQualityChanged)
|
||||
|
||||
self._stacks_have_errors = None
|
||||
self._empty_variant_container = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(id="empty_variant")[0]
|
||||
self._empty_material_container = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(id="empty_material")[0]
|
||||
self._empty_quality_container = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(id="empty_quality")[0]
|
||||
self._empty_quality_changes_container = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(id="empty_quality_changes")[0]
|
||||
self._empty_variant_container = ContainerRegistry.getInstance().findInstanceContainers(id="empty_variant")[0]
|
||||
self._empty_material_container = ContainerRegistry.getInstance().findInstanceContainers(id="empty_material")[0]
|
||||
self._empty_quality_container = ContainerRegistry.getInstance().findInstanceContainers(id="empty_quality")[0]
|
||||
self._empty_quality_changes_container = ContainerRegistry.getInstance().findInstanceContainers(id="empty_quality_changes")[0]
|
||||
self._onGlobalContainerChanged()
|
||||
|
||||
ExtruderManager.getInstance().activeExtruderChanged.connect(self._onActiveExtruderStackChanged)
|
||||
|
|
@ -76,6 +86,11 @@ class MachineManager(QObject):
|
|||
self._material_incompatible_message = Message(catalog.i18nc("@info:status",
|
||||
"The selected material is incompatible with the selected machine or configuration."))
|
||||
|
||||
self._error_check_timer = QTimer()
|
||||
self._error_check_timer.setInterval(250)
|
||||
self._error_check_timer.setSingleShot(True)
|
||||
self._error_check_timer.timeout.connect(self._updateStacksHaveErrors)
|
||||
|
||||
globalContainerChanged = pyqtSignal() # Emitted whenever the global stack is changed (ie: when changing between printers, changing a global profile, but not when changing a value)
|
||||
activeMaterialChanged = pyqtSignal()
|
||||
activeVariantChanged = pyqtSignal()
|
||||
|
|
@ -91,7 +106,7 @@ class MachineManager(QObject):
|
|||
|
||||
outputDevicesChanged = pyqtSignal()
|
||||
|
||||
def _onOutputDevicesChanged(self):
|
||||
def _onOutputDevicesChanged(self) -> None:
|
||||
for printer_output_device in self._printer_output_devices:
|
||||
printer_output_device.hotendIdChanged.disconnect(self._onHotendIdChanged)
|
||||
printer_output_device.materialIdChanged.disconnect(self._onMaterialIdChanged)
|
||||
|
|
@ -112,16 +127,17 @@ class MachineManager(QObject):
|
|||
|
||||
@pyqtProperty(int, constant=True)
|
||||
def totalNumberOfSettings(self):
|
||||
return len(UM.Settings.ContainerRegistry.getInstance().findDefinitionContainers(id="fdmprinter")[0].getAllKeys())
|
||||
return len(ContainerRegistry.getInstance().findDefinitionContainers(id="fdmprinter")[0].getAllKeys())
|
||||
|
||||
def _onHotendIdChanged(self, index, hotend_id):
|
||||
def _onHotendIdChanged(self, index: Union[str, int], hotend_id: str) -> None:
|
||||
if not self._global_container_stack:
|
||||
return
|
||||
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(type="variant", definition=self._global_container_stack.getBottom().getId(), name=hotend_id)
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(type="variant", definition=self._global_container_stack.getBottom().getId(), name=hotend_id)
|
||||
if containers: # New material ID is known
|
||||
extruder_manager = ExtruderManager.getInstance()
|
||||
extruders = list(extruder_manager.getMachineExtruders(self.activeMachineId))
|
||||
machine_id = self.activeMachineId
|
||||
extruders = extruder_manager.getMachineExtruders(machine_id)
|
||||
matching_extruder = None
|
||||
for extruder in extruders:
|
||||
if str(index) == extruder.getMetaDataEntry("position"):
|
||||
|
|
@ -142,7 +158,7 @@ class MachineManager(QObject):
|
|||
if self._global_container_stack.getMetaDataEntry("has_machine_materials", False):
|
||||
definition_id = self.activeQualityDefinitionId
|
||||
extruder_manager = ExtruderManager.getInstance()
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(type = "material", definition = definition_id, GUID = material_id)
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(type = "material", definition = definition_id, GUID = material_id)
|
||||
if containers: # New material ID is known
|
||||
extruders = list(extruder_manager.getMachineExtruders(self.activeMachineId))
|
||||
matching_extruder = None
|
||||
|
|
@ -220,6 +236,11 @@ class MachineManager(QObject):
|
|||
quality = self._global_container_stack.findContainer({"type": "quality"})
|
||||
quality.nameChanged.disconnect(self._onQualityNameChanged)
|
||||
|
||||
if self._global_container_stack.getProperty("machine_extruder_count", "value") > 1:
|
||||
for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
|
||||
extruder_stack.propertyChanged.disconnect(self._onPropertyChanged)
|
||||
extruder_stack.containersChanged.disconnect(self._onInstanceContainersChanged)
|
||||
|
||||
self._global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
self._active_container_stack = self._global_container_stack
|
||||
|
||||
|
|
@ -243,6 +264,10 @@ class MachineManager(QObject):
|
|||
if global_material != self._empty_material_container:
|
||||
self._global_container_stack.replaceContainer(self._global_container_stack.getContainerIndex(global_material), self._empty_material_container)
|
||||
|
||||
for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks(): #Listen for changes on all extruder stacks.
|
||||
extruder_stack.propertyChanged.connect(self._onPropertyChanged)
|
||||
extruder_stack.containersChanged.connect(self._onInstanceContainersChanged)
|
||||
|
||||
else:
|
||||
material = self._global_container_stack.findContainer({"type": "material"})
|
||||
material.nameChanged.connect(self._onMaterialNameChanged)
|
||||
|
|
@ -263,14 +288,8 @@ class MachineManager(QObject):
|
|||
self.blurSettings.emit() # Ensure no-one has focus.
|
||||
old_active_container_stack = self._active_container_stack
|
||||
|
||||
if self._active_container_stack and self._active_container_stack != self._global_container_stack:
|
||||
self._active_container_stack.containersChanged.disconnect(self._onInstanceContainersChanged)
|
||||
self._active_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
|
||||
self._active_container_stack = ExtruderManager.getInstance().getActiveExtruderStack()
|
||||
if self._active_container_stack:
|
||||
self._active_container_stack.containersChanged.connect(self._onInstanceContainersChanged)
|
||||
self._active_container_stack.propertyChanged.connect(self._onPropertyChanged)
|
||||
else:
|
||||
if not self._active_container_stack:
|
||||
self._active_container_stack = self._global_container_stack
|
||||
|
||||
self._updateStacksHaveErrors()
|
||||
|
|
@ -283,12 +302,9 @@ class MachineManager(QObject):
|
|||
def _onInstanceContainersChanged(self, container):
|
||||
container_type = container.getMetaDataEntry("type")
|
||||
|
||||
if container_type == "material":
|
||||
self.activeMaterialChanged.emit()
|
||||
elif container_type == "variant":
|
||||
self.activeVariantChanged.emit()
|
||||
elif container_type == "quality":
|
||||
self.activeQualityChanged.emit()
|
||||
self.activeVariantChanged.emit()
|
||||
self.activeMaterialChanged.emit()
|
||||
self.activeQualityChanged.emit()
|
||||
|
||||
self._updateStacksHaveErrors()
|
||||
|
||||
|
|
@ -297,59 +313,39 @@ class MachineManager(QObject):
|
|||
# Notify UI items, such as the "changed" star in profile pull down menu.
|
||||
self.activeStackValueChanged.emit()
|
||||
|
||||
if property_name == "validationState":
|
||||
if not self._stacks_have_errors:
|
||||
# fast update, we only have to look at the current changed property
|
||||
if self._active_container_stack.getProperty(key, "settable_per_extruder"):
|
||||
changed_validation_state = self._active_container_stack.getProperty(key, property_name)
|
||||
else:
|
||||
changed_validation_state = self._global_container_stack.getProperty(key, property_name)
|
||||
|
||||
if changed_validation_state is None:
|
||||
# Setting is not validated. This can happen if there is only a setting definition.
|
||||
# We do need to validate it, because a setting defintions value can be set by a function, which could
|
||||
# be an invalid setting.
|
||||
definition = self._active_container_stack.getSettingDefinition(key)
|
||||
validator_type = UM.Settings.SettingDefinition.getValidatorForType(definition.type)
|
||||
if validator_type:
|
||||
validator = validator_type(key)
|
||||
changed_validation_state = validator(self._active_container_stack)
|
||||
if changed_validation_state in (UM.Settings.ValidatorState.Exception, UM.Settings.ValidatorState.MaximumError, UM.Settings.ValidatorState.MinimumError):
|
||||
self._stacks_have_errors = True
|
||||
self.stacksValidationChanged.emit()
|
||||
else:
|
||||
# Normal check
|
||||
self._updateStacksHaveErrors()
|
||||
elif property_name == "validationState":
|
||||
self._error_check_timer.start()
|
||||
|
||||
@pyqtSlot(str)
|
||||
def setActiveMachine(self, stack_id):
|
||||
def setActiveMachine(self, stack_id: str) -> None:
|
||||
self.blurSettings.emit() # Ensure no-one has focus.
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findContainerStacks(id = stack_id)
|
||||
containers = ContainerRegistry.getInstance().findContainerStacks(id = stack_id)
|
||||
if containers:
|
||||
Application.getInstance().setGlobalContainerStack(containers[0])
|
||||
|
||||
@pyqtSlot(str, str)
|
||||
def addMachine(self, name, definition_id):
|
||||
container_registry = UM.Settings.ContainerRegistry.getInstance()
|
||||
def addMachine(self, name: str, definition_id: str) -> None:
|
||||
container_registry = ContainerRegistry.getInstance()
|
||||
definitions = container_registry.findDefinitionContainers(id = definition_id)
|
||||
if definitions:
|
||||
definition = definitions[0]
|
||||
name = self._createUniqueName("machine", "", name, definition.getName())
|
||||
new_global_stack = UM.Settings.ContainerStack(name)
|
||||
new_global_stack = ContainerStack(name)
|
||||
new_global_stack.addMetaDataEntry("type", "machine")
|
||||
new_global_stack.addContainer(definition)
|
||||
container_registry.addContainer(new_global_stack)
|
||||
|
||||
variant_instance_container = self._updateVariantContainer(definition)
|
||||
material_instance_container = self._updateMaterialContainer(definition, variant_instance_container)
|
||||
material_instance_container = self._updateMaterialContainer(definition, new_global_stack, variant_instance_container)
|
||||
quality_instance_container = self._updateQualityContainer(definition, variant_instance_container, material_instance_container)
|
||||
|
||||
current_settings_instance_container = UM.Settings.InstanceContainer(name + "_current_settings")
|
||||
current_settings_instance_container = InstanceContainer(name + "_current_settings")
|
||||
current_settings_instance_container.addMetaDataEntry("machine", name)
|
||||
current_settings_instance_container.addMetaDataEntry("type", "user")
|
||||
current_settings_instance_container.setDefinition(definitions[0])
|
||||
container_registry.addContainer(current_settings_instance_container)
|
||||
|
||||
new_global_stack.addContainer(definition)
|
||||
|
||||
if variant_instance_container:
|
||||
new_global_stack.addContainer(variant_instance_container)
|
||||
if material_instance_container:
|
||||
|
|
@ -371,17 +367,16 @@ class MachineManager(QObject):
|
|||
# \param new_name \type{string} Base name, which may not be unique
|
||||
# \param fallback_name \type{string} Name to use when (stripped) new_name is empty
|
||||
# \return \type{string} Name that is unique for the specified type and name/id
|
||||
def _createUniqueName(self, container_type, current_name, new_name, fallback_name):
|
||||
return UM.Settings.ContainerRegistry.getInstance().createUniqueName(container_type, current_name, new_name, fallback_name)
|
||||
def _createUniqueName(self, container_type: str, current_name: str, new_name: str, fallback_name: str) -> str:
|
||||
return ContainerRegistry.getInstance().createUniqueName(container_type, current_name, new_name, fallback_name)
|
||||
|
||||
def _checkStacksHaveErrors(self):
|
||||
if self._global_container_stack is not None and self._global_container_stack.hasErrors():
|
||||
return True
|
||||
|
||||
if self._global_container_stack is None:
|
||||
if self._global_container_stack is None: #No active machine.
|
||||
return False
|
||||
stacks = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
|
||||
for stack in stacks:
|
||||
|
||||
if self._global_container_stack.hasErrors():
|
||||
return True
|
||||
for stack in ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()):
|
||||
if stack.hasErrors():
|
||||
return True
|
||||
|
||||
|
|
@ -463,35 +458,35 @@ class MachineManager(QObject):
|
|||
return bool(self._stacks_have_errors)
|
||||
|
||||
@pyqtProperty(str, notify = activeStackChanged)
|
||||
def activeUserProfileId(self):
|
||||
def activeUserProfileId(self) -> str:
|
||||
if self._active_container_stack:
|
||||
return self._active_container_stack.getTop().getId()
|
||||
|
||||
return ""
|
||||
|
||||
@pyqtProperty(str, notify = globalContainerChanged)
|
||||
def activeMachineName(self):
|
||||
def activeMachineName(self) -> str:
|
||||
if self._global_container_stack:
|
||||
return self._global_container_stack.getName()
|
||||
|
||||
return ""
|
||||
|
||||
@pyqtProperty(str, notify = globalContainerChanged)
|
||||
def activeMachineId(self):
|
||||
def activeMachineId(self) -> str:
|
||||
if self._global_container_stack:
|
||||
return self._global_container_stack.getId()
|
||||
|
||||
return ""
|
||||
|
||||
@pyqtProperty(str, notify = activeStackChanged)
|
||||
def activeStackId(self):
|
||||
def activeStackId(self) -> str:
|
||||
if self._active_container_stack:
|
||||
return self._active_container_stack.getId()
|
||||
|
||||
return ""
|
||||
|
||||
@pyqtProperty(str, notify = activeMaterialChanged)
|
||||
def activeMaterialName(self):
|
||||
def activeMaterialName(self) -> str:
|
||||
if self._active_container_stack:
|
||||
material = self._active_container_stack.findContainer({"type":"material"})
|
||||
if material:
|
||||
|
|
@ -521,7 +516,7 @@ class MachineManager(QObject):
|
|||
return result
|
||||
|
||||
@pyqtProperty(str, notify=activeMaterialChanged)
|
||||
def activeMaterialId(self):
|
||||
def activeMaterialId(self) -> str:
|
||||
if self._active_container_stack:
|
||||
material = self._active_container_stack.findContainer({"type": "material"})
|
||||
if material:
|
||||
|
|
@ -559,13 +554,13 @@ class MachineManager(QObject):
|
|||
quality_changes = self._global_container_stack.findContainer({"type": "quality_changes"})
|
||||
if quality_changes:
|
||||
value = self._global_container_stack.getRawProperty("layer_height", "value", skip_until_container = quality_changes.getId())
|
||||
if isinstance(value, UM.Settings.SettingFunction):
|
||||
if isinstance(value, SettingFunction):
|
||||
value = value(self._global_container_stack)
|
||||
return value
|
||||
quality = self._global_container_stack.findContainer({"type": "quality"})
|
||||
if quality:
|
||||
value = self._global_container_stack.getRawProperty("layer_height", "value", skip_until_container = quality.getId())
|
||||
if isinstance(value, UM.Settings.SettingFunction):
|
||||
if isinstance(value, SettingFunction):
|
||||
value = value(self._global_container_stack)
|
||||
return value
|
||||
|
||||
|
|
@ -574,7 +569,7 @@ class MachineManager(QObject):
|
|||
## Get the Material ID associated with the currently active material
|
||||
# \returns MaterialID (string) if found, empty string otherwise
|
||||
@pyqtProperty(str, notify=activeQualityChanged)
|
||||
def activeQualityMaterialId(self):
|
||||
def activeQualityMaterialId(self) -> str:
|
||||
if self._active_container_stack:
|
||||
quality = self._active_container_stack.findContainer({"type": "quality"})
|
||||
if quality:
|
||||
|
|
@ -664,8 +659,8 @@ class MachineManager(QObject):
|
|||
|
||||
## Check if a container is read_only
|
||||
@pyqtSlot(str, result = bool)
|
||||
def isReadOnly(self, container_id):
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(id = container_id)
|
||||
def isReadOnly(self, container_id) -> bool:
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(id = container_id)
|
||||
if not containers or not self._active_container_stack:
|
||||
return True
|
||||
return containers[0].isReadOnly()
|
||||
|
|
@ -687,134 +682,148 @@ class MachineManager(QObject):
|
|||
# Depending on from/to material+current variant, a quality profile is chosen and set.
|
||||
@pyqtSlot(str)
|
||||
def setActiveMaterial(self, material_id):
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(id = material_id)
|
||||
if not containers or not self._active_container_stack:
|
||||
return
|
||||
material_container = containers[0]
|
||||
with postponeSignals(*self._getContainerChangedSignals(), compress = True):
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(id = material_id)
|
||||
if not containers or not self._active_container_stack:
|
||||
return
|
||||
material_container = containers[0]
|
||||
|
||||
Logger.log("d", "Attempting to change the active material to %s", material_id)
|
||||
Logger.log("d", "Attempting to change the active material to %s", material_id)
|
||||
|
||||
old_material = self._active_container_stack.findContainer({"type": "material"})
|
||||
old_quality = self._active_container_stack.findContainer({"type": "quality"})
|
||||
old_quality_changes = self._active_container_stack.findContainer({"type": "quality_changes"})
|
||||
if not old_material:
|
||||
Logger.log("w", "While trying to set the active material, no material was found to replace it.")
|
||||
return
|
||||
old_material = self._active_container_stack.findContainer({"type": "material"})
|
||||
old_quality = self._active_container_stack.findContainer({"type": "quality"})
|
||||
old_quality_changes = self._active_container_stack.findContainer({"type": "quality_changes"})
|
||||
if not old_material:
|
||||
Logger.log("w", "While trying to set the active material, no material was found to replace it.")
|
||||
return
|
||||
|
||||
if old_quality_changes.getId() == "empty_quality_changes":
|
||||
old_quality_changes = None
|
||||
if old_quality_changes.getId() == "empty_quality_changes":
|
||||
old_quality_changes = None
|
||||
|
||||
self.blurSettings.emit()
|
||||
old_material.nameChanged.disconnect(self._onMaterialNameChanged)
|
||||
self.blurSettings.emit()
|
||||
old_material.nameChanged.disconnect(self._onMaterialNameChanged)
|
||||
|
||||
material_index = self._active_container_stack.getContainerIndex(old_material)
|
||||
self._active_container_stack.replaceContainer(material_index, material_container)
|
||||
Logger.log("d", "Active material changed")
|
||||
material_index = self._active_container_stack.getContainerIndex(old_material)
|
||||
self._active_container_stack.replaceContainer(material_index, material_container)
|
||||
Logger.log("d", "Active material changed")
|
||||
|
||||
material_container.nameChanged.connect(self._onMaterialNameChanged)
|
||||
material_container.nameChanged.connect(self._onMaterialNameChanged)
|
||||
|
||||
if material_container.getMetaDataEntry("compatible") == False:
|
||||
self._material_incompatible_message.show()
|
||||
else:
|
||||
self._material_incompatible_message.hide()
|
||||
if material_container.getMetaDataEntry("compatible") == False:
|
||||
self._material_incompatible_message.show()
|
||||
else:
|
||||
self._material_incompatible_message.hide()
|
||||
|
||||
new_quality_id = old_quality.getId()
|
||||
quality_type = old_quality.getMetaDataEntry("quality_type")
|
||||
if old_quality_changes:
|
||||
quality_type = old_quality_changes.getMetaDataEntry("quality_type")
|
||||
new_quality_id = old_quality_changes.getId()
|
||||
quality_type = None
|
||||
new_quality_id = None
|
||||
if old_quality:
|
||||
new_quality_id = old_quality.getId()
|
||||
quality_type = old_quality.getMetaDataEntry("quality_type")
|
||||
if old_quality_changes:
|
||||
quality_type = old_quality_changes.getMetaDataEntry("quality_type")
|
||||
new_quality_id = old_quality_changes.getId()
|
||||
|
||||
# See if the requested quality type is available in the new situation.
|
||||
machine_definition = self._active_container_stack.getBottom()
|
||||
quality_manager = QualityManager.getInstance()
|
||||
candidate_quality = quality_manager.findQualityByQualityType(quality_type,
|
||||
quality_manager.getWholeMachineDefinition(machine_definition),
|
||||
[material_container])
|
||||
if not candidate_quality or candidate_quality.getId() == "empty_quality":
|
||||
# Fall back to a quality
|
||||
new_quality = quality_manager.findQualityByQualityType(None,
|
||||
quality_manager.getWholeMachineDefinition(machine_definition),
|
||||
[material_container])
|
||||
if new_quality:
|
||||
new_quality_id = new_quality.getId()
|
||||
else:
|
||||
if not old_quality_changes:
|
||||
new_quality_id = candidate_quality.getId()
|
||||
# See if the requested quality type is available in the new situation.
|
||||
machine_definition = self._active_container_stack.getBottom()
|
||||
quality_manager = QualityManager.getInstance()
|
||||
candidate_quality = None
|
||||
if quality_type:
|
||||
candidate_quality = quality_manager.findQualityByQualityType(quality_type,
|
||||
quality_manager.getWholeMachineDefinition(machine_definition),
|
||||
[material_container])
|
||||
if not candidate_quality or candidate_quality.getId() == "empty_quality":
|
||||
# Fall back to a quality (which must be compatible with all other extruders)
|
||||
new_qualities = quality_manager.findAllUsableQualitiesForMachineAndExtruders(
|
||||
self._global_container_stack, ExtruderManager.getInstance().getExtruderStacks())
|
||||
|
||||
self.setActiveQuality(new_quality_id)
|
||||
if new_qualities:
|
||||
new_quality_id = new_qualities[0].getId() # Just pick the first available one
|
||||
else:
|
||||
Logger.log("w", "No quality profile found that matches the current machine and extruders.")
|
||||
else:
|
||||
if not old_quality_changes:
|
||||
new_quality_id = candidate_quality.getId()
|
||||
|
||||
self.setActiveQuality(new_quality_id)
|
||||
|
||||
@pyqtSlot(str)
|
||||
def setActiveVariant(self, variant_id):
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(id = variant_id)
|
||||
if not containers or not self._active_container_stack:
|
||||
return
|
||||
Logger.log("d", "Attempting to change the active variant to %s", variant_id)
|
||||
old_variant = self._active_container_stack.findContainer({"type": "variant"})
|
||||
old_material = self._active_container_stack.findContainer({"type": "material"})
|
||||
if old_variant:
|
||||
self.blurSettings.emit()
|
||||
variant_index = self._active_container_stack.getContainerIndex(old_variant)
|
||||
self._active_container_stack.replaceContainer(variant_index, containers[0])
|
||||
Logger.log("d", "Active variant changed")
|
||||
preferred_material = None
|
||||
if old_material:
|
||||
preferred_material_name = old_material.getName()
|
||||
with postponeSignals(*self._getContainerChangedSignals(), compress = True):
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(id = variant_id)
|
||||
if not containers or not self._active_container_stack:
|
||||
return
|
||||
Logger.log("d", "Attempting to change the active variant to %s", variant_id)
|
||||
old_variant = self._active_container_stack.findContainer({"type": "variant"})
|
||||
old_material = self._active_container_stack.findContainer({"type": "material"})
|
||||
if old_variant:
|
||||
self.blurSettings.emit()
|
||||
variant_index = self._active_container_stack.getContainerIndex(old_variant)
|
||||
self._active_container_stack.replaceContainer(variant_index, containers[0])
|
||||
Logger.log("d", "Active variant changed")
|
||||
preferred_material = None
|
||||
if old_material:
|
||||
preferred_material_name = old_material.getName()
|
||||
|
||||
self.setActiveMaterial(self._updateMaterialContainer(self._global_container_stack.getBottom(), containers[0], preferred_material_name).id)
|
||||
else:
|
||||
Logger.log("w", "While trying to set the active variant, no variant was found to replace.")
|
||||
self.setActiveMaterial(self._updateMaterialContainer(self._global_container_stack.getBottom(), self._global_container_stack, containers[0], preferred_material_name).id)
|
||||
else:
|
||||
Logger.log("w", "While trying to set the active variant, no variant was found to replace.")
|
||||
|
||||
## set the active quality
|
||||
# \param quality_id The quality_id of either a quality or a quality_changes
|
||||
@pyqtSlot(str)
|
||||
def setActiveQuality(self, quality_id):
|
||||
self.blurSettings.emit()
|
||||
with postponeSignals(*self._getContainerChangedSignals(), compress = True):
|
||||
self.blurSettings.emit()
|
||||
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(id = quality_id)
|
||||
if not containers or not self._global_container_stack:
|
||||
return
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(id = quality_id)
|
||||
if not containers or not self._global_container_stack:
|
||||
return
|
||||
|
||||
Logger.log("d", "Attempting to change the active quality to %s", quality_id)
|
||||
Logger.log("d", "Attempting to change the active quality to %s", quality_id)
|
||||
|
||||
# Quality profile come in two flavours: type=quality and type=quality_changes
|
||||
# If we found a quality_changes profile then look up its parent quality profile.
|
||||
container_type = containers[0].getMetaDataEntry("type")
|
||||
quality_name = containers[0].getName()
|
||||
quality_type = containers[0].getMetaDataEntry("quality_type")
|
||||
# Quality profile come in two flavours: type=quality and type=quality_changes
|
||||
# If we found a quality_changes profile then look up its parent quality profile.
|
||||
container_type = containers[0].getMetaDataEntry("type")
|
||||
quality_name = containers[0].getName()
|
||||
quality_type = containers[0].getMetaDataEntry("quality_type")
|
||||
|
||||
# Get quality container and optionally the quality_changes container.
|
||||
if container_type == "quality":
|
||||
new_quality_settings_list = self.determineQualityAndQualityChangesForQualityType(quality_type)
|
||||
elif container_type == "quality_changes":
|
||||
new_quality_settings_list = self._determineQualityAndQualityChangesForQualityChanges(quality_name)
|
||||
else:
|
||||
Logger.log("e", "Tried to set quality to a container that is not of the right type")
|
||||
return
|
||||
# Get quality container and optionally the quality_changes container.
|
||||
if container_type == "quality":
|
||||
new_quality_settings_list = self.determineQualityAndQualityChangesForQualityType(quality_type)
|
||||
elif container_type == "quality_changes":
|
||||
new_quality_settings_list = self._determineQualityAndQualityChangesForQualityChanges(quality_name)
|
||||
else:
|
||||
Logger.log("e", "Tried to set quality to a container that is not of the right type")
|
||||
return
|
||||
|
||||
name_changed_connect_stacks = [] # Connect these stacks to the name changed callback
|
||||
for setting_info in new_quality_settings_list:
|
||||
stack = setting_info["stack"]
|
||||
stack_quality = setting_info["quality"]
|
||||
stack_quality_changes = setting_info["quality_changes"]
|
||||
# Check if it was at all possible to find new settings
|
||||
if new_quality_settings_list is None:
|
||||
return
|
||||
|
||||
name_changed_connect_stacks.append(stack_quality)
|
||||
name_changed_connect_stacks.append(stack_quality_changes)
|
||||
self._replaceQualityOrQualityChangesInStack(stack, stack_quality, postpone_emit = True)
|
||||
self._replaceQualityOrQualityChangesInStack(stack, stack_quality_changes, postpone_emit = True)
|
||||
name_changed_connect_stacks = [] # Connect these stacks to the name changed callback
|
||||
for setting_info in new_quality_settings_list:
|
||||
stack = setting_info["stack"]
|
||||
stack_quality = setting_info["quality"]
|
||||
stack_quality_changes = setting_info["quality_changes"]
|
||||
|
||||
# Send emits that are postponed in replaceContainer.
|
||||
# Here the stacks are finished replacing and every value can be resolved based on the current state.
|
||||
for setting_info in new_quality_settings_list:
|
||||
setting_info["stack"].sendPostponedEmits()
|
||||
name_changed_connect_stacks.append(stack_quality)
|
||||
name_changed_connect_stacks.append(stack_quality_changes)
|
||||
self._replaceQualityOrQualityChangesInStack(stack, stack_quality)
|
||||
self._replaceQualityOrQualityChangesInStack(stack, stack_quality_changes)
|
||||
|
||||
# Connect to onQualityNameChanged
|
||||
for stack in name_changed_connect_stacks:
|
||||
stack.nameChanged.connect(self._onQualityNameChanged)
|
||||
# Send emits that are postponed in replaceContainer.
|
||||
# Here the stacks are finished replacing and every value can be resolved based on the current state.
|
||||
for setting_info in new_quality_settings_list:
|
||||
setting_info["stack"].sendPostponedEmits()
|
||||
|
||||
if self.hasUserSettings and Preferences.getInstance().getValue("cura/active_mode") == 1:
|
||||
self._askUserToKeepOrClearCurrentSettings()
|
||||
# Connect to onQualityNameChanged
|
||||
for stack in name_changed_connect_stacks:
|
||||
stack.nameChanged.connect(self._onQualityNameChanged)
|
||||
|
||||
self.activeQualityChanged.emit()
|
||||
if self.hasUserSettings and Preferences.getInstance().getValue("cura/active_mode") == 1:
|
||||
self._askUserToKeepOrClearCurrentSettings()
|
||||
|
||||
self.activeQualityChanged.emit()
|
||||
|
||||
## Determine the quality and quality changes settings for the current machine for a quality name.
|
||||
#
|
||||
|
|
@ -867,7 +876,12 @@ class MachineManager(QObject):
|
|||
quality_changes_profiles = quality_manager.findQualityChangesByName(quality_changes_name,
|
||||
global_machine_definition)
|
||||
|
||||
global_quality_changes = [qcp for qcp in quality_changes_profiles if qcp.getMetaDataEntry("extruder") is None][0]
|
||||
global_quality_changes = [qcp for qcp in quality_changes_profiles if qcp.getMetaDataEntry("extruder") is None]
|
||||
if global_quality_changes:
|
||||
global_quality_changes = global_quality_changes[0]
|
||||
else:
|
||||
Logger.log("e", "Could not find the global quality changes container with name %s", quality_changes_name)
|
||||
return None
|
||||
material = global_container_stack.findContainer(type="material")
|
||||
|
||||
# For the global stack, find a quality which matches the quality_type in
|
||||
|
|
@ -924,48 +938,7 @@ class MachineManager(QObject):
|
|||
container.nameChanged.connect(self._onQualityNameChanged)
|
||||
|
||||
def _askUserToKeepOrClearCurrentSettings(self):
|
||||
# Ask the user if the user profile should be cleared or not (discarding the current settings)
|
||||
# In Simple Mode we assume the user always wants to keep the (limited) current settings
|
||||
details_text = catalog.i18nc("@label", "You made changes to the following setting(s)/override(s):")
|
||||
|
||||
# user changes in global stack
|
||||
details_list = [setting.definition.label for setting in self._global_container_stack.getTop().findInstances(**{})]
|
||||
|
||||
# user changes in extruder stacks
|
||||
stacks = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
|
||||
for stack in stacks:
|
||||
details_list.extend([
|
||||
"%s (%s)" % (setting.definition.label, stack.getName())
|
||||
for setting in stack.getTop().findInstances(**{})])
|
||||
|
||||
# Format to output string
|
||||
details = "\n ".join([details_text, ] + details_list)
|
||||
|
||||
num_changed_settings = len(details_list)
|
||||
Application.getInstance().messageBox(
|
||||
catalog.i18nc("@window:title", "Switched profiles"),
|
||||
catalog.i18nc(
|
||||
"@label",
|
||||
"Do you want to transfer your %d changed setting(s)/override(s) to this profile?") % num_changed_settings,
|
||||
catalog.i18nc(
|
||||
"@label",
|
||||
"If you transfer your settings they will override settings in the profile. If you don't transfer these settings, they will be lost."),
|
||||
details,
|
||||
buttons=QMessageBox.Yes + QMessageBox.No,
|
||||
icon=QMessageBox.Question,
|
||||
callback=self._keepUserSettingsDialogCallback)
|
||||
|
||||
def _keepUserSettingsDialogCallback(self, button):
|
||||
if button == QMessageBox.Yes:
|
||||
# Yes, keep the settings in the user profile with this profile
|
||||
pass
|
||||
elif button == QMessageBox.No:
|
||||
# No, discard the settings in the user profile
|
||||
global_stack = Application.getInstance().getGlobalContainerStack()
|
||||
for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
|
||||
extruder.getTop().clear()
|
||||
|
||||
global_stack.getTop().clear()
|
||||
Application.getInstance().discardOrKeepProfileChanges()
|
||||
|
||||
@pyqtProperty(str, notify = activeVariantChanged)
|
||||
def activeVariantName(self):
|
||||
|
|
@ -1057,7 +1030,7 @@ class MachineManager(QObject):
|
|||
|
||||
@pyqtSlot(str, str)
|
||||
def renameMachine(self, machine_id, new_name):
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findContainerStacks(id = machine_id)
|
||||
containers = ContainerRegistry.getInstance().findContainerStacks(id = machine_id)
|
||||
if containers:
|
||||
new_name = self._createUniqueName("machine", containers[0].getName(), new_name, containers[0].getBottom().getName())
|
||||
containers[0].setName(new_name)
|
||||
|
|
@ -1070,13 +1043,13 @@ class MachineManager(QObject):
|
|||
|
||||
ExtruderManager.getInstance().removeMachineExtruders(machine_id)
|
||||
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(type = "user", machine = machine_id)
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(type = "user", machine = machine_id)
|
||||
for container in containers:
|
||||
UM.Settings.ContainerRegistry.getInstance().removeContainer(container.getId())
|
||||
UM.Settings.ContainerRegistry.getInstance().removeContainer(machine_id)
|
||||
ContainerRegistry.getInstance().removeContainer(container.getId())
|
||||
ContainerRegistry.getInstance().removeContainer(machine_id)
|
||||
|
||||
if activate_new_machine:
|
||||
stacks = UM.Settings.ContainerRegistry.getInstance().findContainerStacks(type = "machine")
|
||||
stacks = ContainerRegistry.getInstance().findContainerStacks(type = "machine")
|
||||
if stacks:
|
||||
Application.getInstance().setGlobalContainerStack(stacks[0])
|
||||
|
||||
|
|
@ -1117,7 +1090,7 @@ class MachineManager(QObject):
|
|||
# \returns DefinitionID (string) if found, None otherwise
|
||||
@pyqtSlot(str, result = str)
|
||||
def getDefinitionByMachineId(self, machine_id):
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findContainerStacks(id=machine_id)
|
||||
containers = ContainerRegistry.getInstance().findContainerStacks(id=machine_id)
|
||||
if containers:
|
||||
return containers[0].getBottom().getId()
|
||||
|
||||
|
|
@ -1125,27 +1098,28 @@ class MachineManager(QObject):
|
|||
def createMachineManager(engine=None, script_engine=None):
|
||||
return MachineManager()
|
||||
|
||||
def _updateVariantContainer(self, definition):
|
||||
def _updateVariantContainer(self, definition: "DefinitionContainer"):
|
||||
if not definition.getMetaDataEntry("has_variants"):
|
||||
return self._empty_variant_container
|
||||
machine_definition_id = UM.Application.getInstance().getMachineManager().getQualityDefinitionId(definition)
|
||||
machine_definition_id = Application.getInstance().getMachineManager().getQualityDefinitionId(definition)
|
||||
containers = []
|
||||
preferred_variant = definition.getMetaDataEntry("preferred_variant")
|
||||
if preferred_variant:
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(type = "variant", definition = machine_definition_id, id = preferred_variant)
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(type = "variant", definition = machine_definition_id, id = preferred_variant)
|
||||
if not containers:
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(type = "variant", definition = machine_definition_id)
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(type = "variant", definition = machine_definition_id)
|
||||
|
||||
if containers:
|
||||
return containers[0]
|
||||
|
||||
return self._empty_variant_container
|
||||
|
||||
def _updateMaterialContainer(self, definition, variant_container = None, preferred_material_name = None):
|
||||
def _updateMaterialContainer(self, definition: "DefinitionContainer", stack: "ContainerStack", variant_container: Optional["InstanceContainer"] = None, preferred_material_name: Optional[str] = None):
|
||||
if not definition.getMetaDataEntry("has_materials"):
|
||||
return self._empty_material_container
|
||||
|
||||
search_criteria = { "type": "material" }
|
||||
approximate_material_diameter = round(stack.getProperty("material_diameter", "value"))
|
||||
search_criteria = { "type": "material", "approximate_diameter": approximate_material_diameter }
|
||||
|
||||
if definition.getMetaDataEntry("has_machine_materials"):
|
||||
search_criteria["definition"] = self.getQualityDefinitionId(definition)
|
||||
|
|
@ -1162,23 +1136,23 @@ class MachineManager(QObject):
|
|||
if preferred_material:
|
||||
search_criteria["id"] = preferred_material
|
||||
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
|
||||
if containers:
|
||||
return containers[0]
|
||||
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
|
||||
if "variant" in search_criteria or "id" in search_criteria:
|
||||
# If a material by this name can not be found, try a wider set of search criteria
|
||||
search_criteria.pop("variant", None)
|
||||
search_criteria.pop("id", None)
|
||||
containers = UM.Settings.ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
|
||||
|
||||
containers = ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
|
||||
if containers:
|
||||
return containers[0]
|
||||
Logger.log("w", "Unable to find a material container with provided criteria, returning an empty one instead.")
|
||||
return self._empty_material_container
|
||||
|
||||
def _updateQualityContainer(self, definition, variant_container, material_container = None, preferred_quality_name = None):
|
||||
container_registry = UM.Settings.ContainerRegistry.getInstance()
|
||||
def _updateQualityContainer(self, definition: "DefinitionContainer", variant_container: "ContainerStack", material_container = None, preferred_quality_name: Optional[str] = None):
|
||||
container_registry = ContainerRegistry.getInstance()
|
||||
search_criteria = { "type": "quality" }
|
||||
|
||||
if definition.getMetaDataEntry("has_machine_quality"):
|
||||
|
|
@ -1261,7 +1235,7 @@ class MachineManager(QObject):
|
|||
# \param preferred_quality_changes_name The name of the quality-changes to
|
||||
# pick, if any such quality-changes profile is available.
|
||||
def _updateQualityChangesContainer(self, quality_type, preferred_quality_changes_name = None):
|
||||
container_registry = UM.Settings.ContainerRegistry.getInstance() # Cache.
|
||||
container_registry = ContainerRegistry.getInstance() # Cache.
|
||||
search_criteria = { "type": "quality_changes" }
|
||||
|
||||
search_criteria["quality"] = quality_type
|
||||
|
|
@ -1289,3 +1263,8 @@ class MachineManager(QObject):
|
|||
|
||||
def _onQualityNameChanged(self):
|
||||
self.activeQualityChanged.emit()
|
||||
|
||||
def _getContainerChangedSignals(self):
|
||||
stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
|
||||
stacks.append(self._global_container_stack)
|
||||
return [ s.containersChanged for s in stacks ]
|
||||
|
|
|
|||
|
|
@ -6,9 +6,9 @@ from PyQt5.QtGui import QValidator
|
|||
import os #For statvfs.
|
||||
import urllib #To escape machine names for how they're saved to file.
|
||||
|
||||
import UM.Resources
|
||||
import UM.Settings.ContainerRegistry
|
||||
import UM.Settings.InstanceContainer
|
||||
from UM.Resources import Resources
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
from UM.Settings.InstanceContainer import InstanceContainer
|
||||
|
||||
## Are machine names valid?
|
||||
#
|
||||
|
|
@ -19,10 +19,10 @@ class MachineNameValidator(QObject):
|
|||
|
||||
#Compute the validation regex for printer names. This is limited by the maximum file name length.
|
||||
try:
|
||||
filename_max_length = os.statvfs(UM.Resources.getDataStoragePath()).f_namemax
|
||||
filename_max_length = os.statvfs(Resources.getDataStoragePath()).f_namemax
|
||||
except AttributeError: #Doesn't support statvfs. Probably because it's not a Unix system.
|
||||
filename_max_length = 255 #Assume it's Windows on NTFS.
|
||||
machine_name_max_length = filename_max_length - len("_current_settings.") - len(UM.Settings.ContainerRegistry.getMimeTypeForContainer(UM.Settings.InstanceContainer).preferredSuffix)
|
||||
machine_name_max_length = filename_max_length - len("_current_settings.") - len(ContainerRegistry.getMimeTypeForContainer(InstanceContainer).preferredSuffix)
|
||||
# Characters that urllib.parse.quote_plus escapes count for 12! So now
|
||||
# we must devise a regex that allows only 12 normal characters or 1
|
||||
# special character, and that up to [machine_name_max_length / 12] times.
|
||||
|
|
@ -41,11 +41,11 @@ class MachineNameValidator(QObject):
|
|||
def validate(self, name, position):
|
||||
#Check for file name length of the current settings container (which is the longest file we're saving with the name).
|
||||
try:
|
||||
filename_max_length = os.statvfs(UM.Resources.getDataStoragePath()).f_namemax
|
||||
filename_max_length = os.statvfs(Resources.getDataStoragePath()).f_namemax
|
||||
except AttributeError: #Doesn't support statvfs. Probably because it's not a Unix system.
|
||||
filename_max_length = 255 #Assume it's Windows on NTFS.
|
||||
escaped_name = urllib.parse.quote_plus(name)
|
||||
current_settings_filename = escaped_name + "_current_settings." + UM.Settings.ContainerRegistry.getMimeTypeForContainer(UM.Settings.InstanceContainer).preferredSuffix
|
||||
current_settings_filename = escaped_name + "_current_settings." + ContainerRegistry.getMimeTypeForContainer(InstanceContainer).preferredSuffix
|
||||
if len(current_settings_filename) > filename_max_length:
|
||||
return QValidator.Invalid
|
||||
|
||||
|
|
|
|||
|
|
@ -1,19 +1,19 @@
|
|||
# Copyright (c) 2016 Ultimaker B.V.
|
||||
# Copyright (c) 2017 Ultimaker B.V.
|
||||
# Uranium is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
import UM.Settings.Models
|
||||
import UM.Settings.Models.SettingVisibilityHandler
|
||||
|
||||
class MaterialSettingsVisibilityHandler(UM.Settings.Models.SettingVisibilityHandler):
|
||||
class MaterialSettingsVisibilityHandler(UM.Settings.Models.SettingVisibilityHandler.SettingVisibilityHandler):
|
||||
def __init__(self, parent = None, *args, **kwargs):
|
||||
super().__init__(parent = parent, *args, **kwargs)
|
||||
|
||||
material_settings = set([
|
||||
material_settings = {
|
||||
"default_material_print_temperature",
|
||||
"material_bed_temperature",
|
||||
"material_standby_temperature",
|
||||
"cool_fan_speed",
|
||||
"retraction_amount",
|
||||
"retraction_speed",
|
||||
])
|
||||
}
|
||||
|
||||
self.setVisible(material_settings)
|
||||
|
|
|
|||
|
|
@ -32,13 +32,13 @@ class ProfilesModel(InstanceContainersModel):
|
|||
|
||||
## Get the singleton instance for this class.
|
||||
@classmethod
|
||||
def getInstance(cls):
|
||||
def getInstance(cls) -> "ProfilesModel":
|
||||
# Note: Explicit use of class name to prevent issues with inheritance.
|
||||
if ProfilesModel.__instance is None:
|
||||
if not ProfilesModel.__instance:
|
||||
ProfilesModel.__instance = cls()
|
||||
return ProfilesModel.__instance
|
||||
|
||||
__instance = None
|
||||
__instance = None # type: "ProfilesModel"
|
||||
|
||||
## Fetch the list of containers to display.
|
||||
#
|
||||
|
|
|
|||
|
|
@ -5,15 +5,14 @@ import collections
|
|||
|
||||
from PyQt5.QtCore import pyqtProperty, pyqtSignal, Qt
|
||||
|
||||
import UM.Application
|
||||
import UM.Logger
|
||||
import UM.Qt
|
||||
import UM.Settings
|
||||
from UM.i18n import i18nCatalog
|
||||
from UM.Application import Application
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
|
||||
import os
|
||||
|
||||
from UM.i18n import i18nCatalog
|
||||
|
||||
|
||||
class QualitySettingsModel(UM.Qt.ListModel.ListModel):
|
||||
KeyRole = Qt.UserRole + 1
|
||||
|
|
@ -27,7 +26,7 @@ class QualitySettingsModel(UM.Qt.ListModel.ListModel):
|
|||
def __init__(self, parent = None):
|
||||
super().__init__(parent = parent)
|
||||
|
||||
self._container_registry = UM.Settings.ContainerRegistry.getInstance()
|
||||
self._container_registry = ContainerRegistry.getInstance()
|
||||
|
||||
self._extruder_id = None
|
||||
self._extruder_definition_id = None
|
||||
|
|
@ -94,7 +93,7 @@ class QualitySettingsModel(UM.Qt.ListModel.ListModel):
|
|||
items = []
|
||||
|
||||
settings = collections.OrderedDict()
|
||||
definition_container = UM.Application.getInstance().getGlobalContainerStack().getBottom()
|
||||
definition_container = Application.getInstance().getGlobalContainerStack().getBottom()
|
||||
|
||||
containers = self._container_registry.findInstanceContainers(id = self._quality_id)
|
||||
if not containers:
|
||||
|
|
@ -122,7 +121,7 @@ class QualitySettingsModel(UM.Qt.ListModel.ListModel):
|
|||
quality_container = quality_container[0]
|
||||
|
||||
quality_type = quality_container.getMetaDataEntry("quality_type")
|
||||
definition_id = UM.Application.getInstance().getMachineManager().getQualityDefinitionId(quality_container.getDefinition())
|
||||
definition_id = Application.getInstance().getMachineManager().getQualityDefinitionId(quality_container.getDefinition())
|
||||
definition = quality_container.getDefinition()
|
||||
|
||||
# Check if the definition container has a translation file.
|
||||
|
|
@ -169,7 +168,7 @@ class QualitySettingsModel(UM.Qt.ListModel.ListModel):
|
|||
if self._extruder_definition_id != "":
|
||||
extruder_definitions = self._container_registry.findDefinitionContainers(id = self._extruder_definition_id)
|
||||
if extruder_definitions:
|
||||
criteria["extruder"] = UM.Application.getInstance().getMachineManager().getQualityDefinitionId(extruder_definitions[0])
|
||||
criteria["extruder"] = Application.getInstance().getMachineManager().getQualityDefinitionId(extruder_definitions[0])
|
||||
criteria["name"] = quality_changes_container.getName()
|
||||
else:
|
||||
criteria["extruder"] = None
|
||||
|
|
@ -178,7 +177,7 @@ class QualitySettingsModel(UM.Qt.ListModel.ListModel):
|
|||
if changes:
|
||||
containers.extend(changes)
|
||||
|
||||
global_container_stack = UM.Application.getInstance().getGlobalContainerStack()
|
||||
global_container_stack = Application.getInstance().getGlobalContainerStack()
|
||||
is_multi_extrusion = global_container_stack.getProperty("machine_extruder_count", "value") > 1
|
||||
|
||||
current_category = ""
|
||||
|
|
|
|||
|
|
@ -3,9 +3,7 @@
|
|||
|
||||
from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal
|
||||
from UM.FlameProfiler import pyqtSlot
|
||||
import UM.Settings
|
||||
from UM.Application import Application
|
||||
import cura.Settings
|
||||
from UM.Logger import Logger
|
||||
|
||||
|
||||
|
|
@ -14,6 +12,12 @@ from UM.Logger import Logger
|
|||
# because some profiles tend to have 'hardcoded' values that break our inheritance. A good example of that are the
|
||||
# speed settings. If all the children of print_speed have a single value override, changing the speed won't
|
||||
# actually do anything, as only the 'leaf' settings are used by the engine.
|
||||
from UM.Settings.ContainerStack import ContainerStack
|
||||
from UM.Settings.SettingFunction import SettingFunction
|
||||
from UM.Settings.SettingInstance import InstanceState
|
||||
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
|
||||
class SettingInheritanceManager(QObject):
|
||||
def __init__(self, parent = None):
|
||||
super().__init__(parent)
|
||||
|
|
@ -23,7 +27,7 @@ class SettingInheritanceManager(QObject):
|
|||
self._active_container_stack = None
|
||||
self._onGlobalContainerChanged()
|
||||
|
||||
cura.Settings.ExtruderManager.getInstance().activeExtruderChanged.connect(self._onActiveExtruderChanged)
|
||||
ExtruderManager.getInstance().activeExtruderChanged.connect(self._onActiveExtruderChanged)
|
||||
self._onActiveExtruderChanged()
|
||||
|
||||
settingsWithIntheritanceChanged = pyqtSignal()
|
||||
|
|
@ -46,7 +50,7 @@ class SettingInheritanceManager(QObject):
|
|||
multi_extrusion = self._global_container_stack.getProperty("machine_extruder_count", "value") > 1
|
||||
if not multi_extrusion:
|
||||
return self._settings_with_inheritance_warning
|
||||
extruder = cura.Settings.ExtruderManager.getInstance().getExtruderStack(extruder_index)
|
||||
extruder = ExtruderManager.getInstance().getExtruderStack(extruder_index)
|
||||
if not extruder:
|
||||
Logger.log("w", "Unable to find extruder for current machine with index %s", extruder_index)
|
||||
return []
|
||||
|
|
@ -73,7 +77,7 @@ class SettingInheritanceManager(QObject):
|
|||
self._update()
|
||||
|
||||
def _onActiveExtruderChanged(self):
|
||||
new_active_stack = cura.Settings.ExtruderManager.getInstance().getActiveExtruderStack()
|
||||
new_active_stack = ExtruderManager.getInstance().getActiveExtruderStack()
|
||||
if not new_active_stack:
|
||||
new_active_stack = self._global_container_stack
|
||||
|
||||
|
|
@ -139,14 +143,14 @@ class SettingInheritanceManager(QObject):
|
|||
return self._settings_with_inheritance_warning
|
||||
|
||||
## Check if a setting has an inheritance function that is overwritten
|
||||
def _settingIsOverwritingInheritance(self, key, stack = None):
|
||||
def _settingIsOverwritingInheritance(self, key: str, stack: ContainerStack = None) -> bool:
|
||||
has_setting_function = False
|
||||
if not stack:
|
||||
stack = self._active_container_stack
|
||||
containers = []
|
||||
|
||||
## Check if the setting has a user state. If not, it is never overwritten.
|
||||
has_user_state = stack.getProperty(key, "state") == UM.Settings.InstanceState.User
|
||||
has_user_state = stack.getProperty(key, "state") == InstanceState.User
|
||||
if not has_user_state:
|
||||
return False
|
||||
|
||||
|
|
@ -155,7 +159,7 @@ class SettingInheritanceManager(QObject):
|
|||
return False
|
||||
|
||||
## Also check if the top container is not a setting function (this happens if the inheritance is restored).
|
||||
if isinstance(stack.getTop().getProperty(key, "value"), UM.Settings.SettingFunction):
|
||||
if isinstance(stack.getTop().getProperty(key, "value"), SettingFunction):
|
||||
return False
|
||||
|
||||
## Mash all containers for all the stacks together.
|
||||
|
|
@ -170,7 +174,7 @@ class SettingInheritanceManager(QObject):
|
|||
continue
|
||||
if value is not None:
|
||||
# If a setting doesn't use any keys, it won't change it's value, so treat it as if it's a fixed value
|
||||
has_setting_function = isinstance(value, UM.Settings.SettingFunction)
|
||||
has_setting_function = isinstance(value, SettingFunction)
|
||||
if has_setting_function:
|
||||
for setting_key in value.getUsedSettingKeys():
|
||||
if setting_key in self._active_container_stack.getAllKeys():
|
||||
|
|
|
|||
|
|
@ -8,12 +8,12 @@ from UM.Signal import Signal, signalemitter
|
|||
from UM.Settings.ContainerStack import ContainerStack
|
||||
from UM.Settings.InstanceContainer import InstanceContainer
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
import UM.Logger
|
||||
|
||||
import cura.Settings
|
||||
from UM.Logger import Logger
|
||||
|
||||
from UM.Application import Application
|
||||
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
|
||||
## A decorator that adds a container stack to a Node. This stack should be queried for all settings regarding
|
||||
# the linked node. The Stack in question will refer to the global stack (so that settings that are not defined by
|
||||
# this stack still resolve.
|
||||
|
|
@ -29,8 +29,8 @@ class SettingOverrideDecorator(SceneNodeDecorator):
|
|||
self._instance = InstanceContainer(container_id = "SettingOverrideInstanceContainer")
|
||||
self._stack.addContainer(self._instance)
|
||||
|
||||
if cura.Settings.ExtruderManager.getInstance().extruderCount > 1:
|
||||
self._extruder_stack = cura.Settings.ExtruderManager.getInstance().getExtruderStack(0).getId()
|
||||
if ExtruderManager.getInstance().extruderCount > 1:
|
||||
self._extruder_stack = ExtruderManager.getInstance().getExtruderStack(0).getId()
|
||||
else:
|
||||
self._extruder_stack = None
|
||||
|
||||
|
|
@ -77,8 +77,10 @@ class SettingOverrideDecorator(SceneNodeDecorator):
|
|||
return container_stack.getMetaDataEntry("position", default=None)
|
||||
|
||||
def _onSettingChanged(self, instance, property_name): # Reminder: 'property' is a built-in function
|
||||
if property_name == "value": # Only reslice if the value has changed.
|
||||
Application.getInstance().getBackend().forceSlice()
|
||||
# Trigger slice/need slicing if the value has changed.
|
||||
if property_name == "value":
|
||||
Application.getInstance().getBackend().needsSlicing()
|
||||
Application.getInstance().getBackend().tickle()
|
||||
|
||||
## Makes sure that the stack upon which the container stack is placed is
|
||||
# kept up to date.
|
||||
|
|
@ -92,10 +94,12 @@ class SettingOverrideDecorator(SceneNodeDecorator):
|
|||
old_extruder_stack_id = ""
|
||||
|
||||
self._stack.setNextStack(extruder_stack[0])
|
||||
if self._stack.getNextStack().getId() != old_extruder_stack_id: #Only reslice if the extruder changed.
|
||||
Application.getInstance().getBackend().forceSlice()
|
||||
# Trigger slice/need slicing if the extruder changed.
|
||||
if self._stack.getNextStack().getId() != old_extruder_stack_id:
|
||||
Application.getInstance().getBackend().needsSlicing()
|
||||
Application.getInstance().getBackend().tickle()
|
||||
else:
|
||||
UM.Logger.log("e", "Extruder stack %s below per-object settings does not exist.", self._extruder_stack)
|
||||
Logger.log("e", "Extruder stack %s below per-object settings does not exist.", self._extruder_stack)
|
||||
else:
|
||||
self._stack.setNextStack(Application.getInstance().getGlobalContainerStack())
|
||||
|
||||
|
|
|
|||
122
cura/Settings/UserChangesModel.py
Normal file
122
cura/Settings/UserChangesModel.py
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
from UM.Qt.ListModel import ListModel
|
||||
|
||||
from PyQt5.QtCore import pyqtSlot, Qt
|
||||
from UM.Application import Application
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
from UM.i18n import i18nCatalog
|
||||
from UM.Settings.SettingFunction import SettingFunction
|
||||
|
||||
from collections import OrderedDict
|
||||
import os
|
||||
|
||||
|
||||
class UserChangesModel(ListModel):
|
||||
KeyRole = Qt.UserRole + 1
|
||||
LabelRole = Qt.UserRole + 2
|
||||
ExtruderRole = Qt.UserRole + 3
|
||||
OriginalValueRole = Qt.UserRole + 4
|
||||
UserValueRole = Qt.UserRole + 6
|
||||
CategoryRole = Qt.UserRole + 7
|
||||
|
||||
def __init__(self, parent = None):
|
||||
super().__init__(parent = parent)
|
||||
self.addRoleName(self.KeyRole, "key")
|
||||
self.addRoleName(self.LabelRole, "label")
|
||||
self.addRoleName(self.ExtruderRole, "extruder")
|
||||
self.addRoleName(self.OriginalValueRole, "original_value")
|
||||
self.addRoleName(self.UserValueRole, "user_value")
|
||||
self.addRoleName(self.CategoryRole, "category")
|
||||
|
||||
self._i18n_catalog = None
|
||||
|
||||
self._update()
|
||||
|
||||
@pyqtSlot()
|
||||
def forceUpdate(self):
|
||||
self._update()
|
||||
|
||||
def _update(self):
|
||||
item_dict = OrderedDict()
|
||||
item_list = []
|
||||
global_stack = Application.getInstance().getGlobalContainerStack()
|
||||
if not global_stack:
|
||||
return
|
||||
stacks = ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks()
|
||||
|
||||
# Check if the definition container has a translation file and ensure it's loaded.
|
||||
definition = global_stack.getBottom()
|
||||
|
||||
definition_suffix = ContainerRegistry.getMimeTypeForContainer(type(definition)).preferredSuffix
|
||||
catalog = i18nCatalog(os.path.basename(definition.getId() + "." + definition_suffix))
|
||||
|
||||
if catalog.hasTranslationLoaded():
|
||||
self._i18n_catalog = catalog
|
||||
|
||||
for file_name in definition.getInheritedFiles():
|
||||
catalog = i18nCatalog(os.path.basename(file_name))
|
||||
if catalog.hasTranslationLoaded():
|
||||
self._i18n_catalog = catalog
|
||||
|
||||
for stack in stacks:
|
||||
# Make a list of all containers in the stack.
|
||||
containers = []
|
||||
latest_stack = stack
|
||||
while latest_stack:
|
||||
containers.extend(latest_stack.getContainers())
|
||||
latest_stack = latest_stack.getNextStack()
|
||||
|
||||
# Drop the user container.
|
||||
user_changes = containers.pop(0)
|
||||
|
||||
for setting_key in user_changes.getAllKeys():
|
||||
original_value = None
|
||||
|
||||
# Find the category of the instance by moving up until we find a category.
|
||||
category = user_changes.getInstance(setting_key).definition
|
||||
while category.type != "category":
|
||||
category = category.parent
|
||||
|
||||
# Handle translation (and fallback if we weren't able to find any translation files.
|
||||
if self._i18n_catalog:
|
||||
category_label = self._i18n_catalog.i18nc(category.key + " label", category.label)
|
||||
else:
|
||||
category_label = category.label
|
||||
|
||||
if self._i18n_catalog:
|
||||
label = self._i18n_catalog.i18nc(setting_key + " label", stack.getProperty(setting_key, "label"))
|
||||
else:
|
||||
label = stack.getProperty(setting_key, "label")
|
||||
|
||||
for container in containers:
|
||||
if stack == global_stack:
|
||||
resolve = global_stack.getProperty(setting_key, "resolve")
|
||||
if resolve is not None:
|
||||
original_value = resolve
|
||||
break
|
||||
|
||||
original_value = container.getProperty(setting_key, "value")
|
||||
|
||||
# If a value is a function, ensure it's called with the stack it's in.
|
||||
if isinstance(original_value, SettingFunction):
|
||||
original_value = original_value(stack)
|
||||
|
||||
if original_value is not None:
|
||||
break
|
||||
|
||||
item_to_add = {"key": setting_key,
|
||||
"label": label,
|
||||
"user_value": str(user_changes.getProperty(setting_key, "value")),
|
||||
"original_value": str(original_value),
|
||||
"extruder": "",
|
||||
"category": category_label}
|
||||
|
||||
if stack != global_stack:
|
||||
item_to_add["extruder"] = stack.getName()
|
||||
|
||||
if category_label not in item_dict:
|
||||
item_dict[category_label] = []
|
||||
item_dict[category_label].append(item_to_add)
|
||||
for each_item_list in item_dict.values():
|
||||
item_list += each_item_list
|
||||
self.setItems(item_list)
|
||||
|
|
@ -1,18 +1,2 @@
|
|||
# Copyright (c) 2016 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
from .MaterialSettingsVisibilityHandler import MaterialSettingsVisibilityHandler
|
||||
from .ContainerManager import ContainerManager
|
||||
from .ContainerSettingsModel import ContainerSettingsModel
|
||||
from .CuraContainerRegistry import CuraContainerRegistry
|
||||
from .ExtruderManager import ExtruderManager
|
||||
from .ExtrudersModel import ExtrudersModel
|
||||
from .MachineManager import MachineManager
|
||||
from .MachineNameValidator import MachineNameValidator
|
||||
from .MaterialSettingsVisibilityHandler import MaterialSettingsVisibilityHandler
|
||||
from .SettingOverrideDecorator import SettingOverrideDecorator
|
||||
from .QualitySettingsModel import QualitySettingsModel
|
||||
from .SettingInheritanceManager import SettingInheritanceManager
|
||||
from .ProfilesModel import ProfilesModel
|
||||
from .QualityAndUserProfilesModel import QualityAndUserProfilesModel
|
||||
from .UserProfilesModel import UserProfilesModel
|
||||
|
|
|
|||
113
cura/ShapeArray.py
Executable file
113
cura/ShapeArray.py
Executable file
|
|
@ -0,0 +1,113 @@
|
|||
import numpy
|
||||
import copy
|
||||
|
||||
from UM.Math.Polygon import Polygon
|
||||
|
||||
|
||||
## Polygon representation as an array for use with Arrange
|
||||
class ShapeArray:
|
||||
def __init__(self, arr, offset_x, offset_y, scale = 1):
|
||||
self.arr = arr
|
||||
self.offset_x = offset_x
|
||||
self.offset_y = offset_y
|
||||
self.scale = scale
|
||||
|
||||
## Instantiate from a bunch of vertices
|
||||
# \param vertices
|
||||
# \param scale scale the coordinates
|
||||
@classmethod
|
||||
def fromPolygon(cls, vertices, scale = 1):
|
||||
# scale
|
||||
vertices = vertices * scale
|
||||
# flip y, x -> x, y
|
||||
flip_vertices = numpy.zeros((vertices.shape))
|
||||
flip_vertices[:, 0] = vertices[:, 1]
|
||||
flip_vertices[:, 1] = vertices[:, 0]
|
||||
flip_vertices = flip_vertices[::-1]
|
||||
# offset, we want that all coordinates have positive values
|
||||
offset_y = int(numpy.amin(flip_vertices[:, 0]))
|
||||
offset_x = int(numpy.amin(flip_vertices[:, 1]))
|
||||
flip_vertices[:, 0] = numpy.add(flip_vertices[:, 0], -offset_y)
|
||||
flip_vertices[:, 1] = numpy.add(flip_vertices[:, 1], -offset_x)
|
||||
shape = [int(numpy.amax(flip_vertices[:, 0])), int(numpy.amax(flip_vertices[:, 1]))]
|
||||
arr = cls.arrayFromPolygon(shape, flip_vertices)
|
||||
return cls(arr, offset_x, offset_y)
|
||||
|
||||
## Instantiate an offset and hull ShapeArray from a scene node.
|
||||
# \param node source node where the convex hull must be present
|
||||
# \param min_offset offset for the offset ShapeArray
|
||||
# \param scale scale the coordinates
|
||||
@classmethod
|
||||
def fromNode(cls, node, min_offset, scale = 0.5):
|
||||
transform = node._transformation
|
||||
transform_x = transform._data[0][3]
|
||||
transform_y = transform._data[2][3]
|
||||
hull_verts = node.callDecoration("getConvexHull")
|
||||
# For one_at_a_time printing you need the convex hull head.
|
||||
hull_head_verts = node.callDecoration("getConvexHullHead") or hull_verts
|
||||
|
||||
offset_verts = hull_head_verts.getMinkowskiHull(Polygon.approximatedCircle(min_offset))
|
||||
offset_points = copy.deepcopy(offset_verts._points) # x, y
|
||||
offset_points[:, 0] = numpy.add(offset_points[:, 0], -transform_x)
|
||||
offset_points[:, 1] = numpy.add(offset_points[:, 1], -transform_y)
|
||||
offset_shape_arr = ShapeArray.fromPolygon(offset_points, scale = scale)
|
||||
|
||||
hull_points = copy.deepcopy(hull_verts._points)
|
||||
hull_points[:, 0] = numpy.add(hull_points[:, 0], -transform_x)
|
||||
hull_points[:, 1] = numpy.add(hull_points[:, 1], -transform_y)
|
||||
hull_shape_arr = ShapeArray.fromPolygon(hull_points, scale = scale) # x, y
|
||||
|
||||
return offset_shape_arr, hull_shape_arr
|
||||
|
||||
## Create np.array with dimensions defined by shape
|
||||
# Fills polygon defined by vertices with ones, all other values zero
|
||||
# Only works correctly for convex hull vertices
|
||||
# Originally from: http://stackoverflow.com/questions/37117878/generating-a-filled-polygon-inside-a-numpy-array
|
||||
# \param shape numpy format shape, [x-size, y-size]
|
||||
# \param vertices
|
||||
@classmethod
|
||||
def arrayFromPolygon(cls, shape, vertices):
|
||||
base_array = numpy.zeros(shape, dtype=float) # Initialize your array of zeros
|
||||
|
||||
fill = numpy.ones(base_array.shape) * True # Initialize boolean array defining shape fill
|
||||
|
||||
# Create check array for each edge segment, combine into fill array
|
||||
for k in range(vertices.shape[0]):
|
||||
fill = numpy.all([fill, cls._check(vertices[k - 1], vertices[k], base_array)], axis=0)
|
||||
|
||||
# Set all values inside polygon to one
|
||||
base_array[fill] = 1
|
||||
|
||||
return base_array
|
||||
|
||||
## Return indices that mark one side of the line, used by arrayFromPolygon
|
||||
# Uses the line defined by p1 and p2 to check array of
|
||||
# input indices against interpolated value
|
||||
# Returns boolean array, with True inside and False outside of shape
|
||||
# Originally from: http://stackoverflow.com/questions/37117878/generating-a-filled-polygon-inside-a-numpy-array
|
||||
# \param p1 2-tuple with x, y for point 1
|
||||
# \param p2 2-tuple with x, y for point 2
|
||||
# \param base_array boolean array to project the line on
|
||||
@classmethod
|
||||
def _check(cls, p1, p2, base_array):
|
||||
if p1[0] == p2[0] and p1[1] == p2[1]:
|
||||
return
|
||||
idxs = numpy.indices(base_array.shape) # Create 3D array of indices
|
||||
|
||||
p1 = p1.astype(float)
|
||||
p2 = p2.astype(float)
|
||||
|
||||
if p2[0] == p1[0]:
|
||||
sign = numpy.sign(p2[1] - p1[1])
|
||||
return idxs[1] * sign
|
||||
|
||||
if p2[1] == p1[1]:
|
||||
sign = numpy.sign(p2[0] - p1[0])
|
||||
return idxs[1] * sign
|
||||
|
||||
# Calculate max column idx for each row idx based on interpolated line between two points
|
||||
|
||||
max_col_idx = (idxs[0] - p1[0]) / (p2[0] - p1[0]) * (p2[1] - p1[1]) + p1[1]
|
||||
sign = numpy.sign(p2[0] - p1[0])
|
||||
return idxs[1] * sign <= max_col_idx * sign
|
||||
|
||||
14
cura_app.py
14
cura_app.py
|
|
@ -2,7 +2,6 @@
|
|||
|
||||
# Copyright (c) 2015 Ultimaker B.V.
|
||||
# Cura is released under the terms of the AGPLv3 or higher.
|
||||
|
||||
import os
|
||||
import sys
|
||||
import platform
|
||||
|
|
@ -18,6 +17,12 @@ if Platform.isLinux(): # Needed for platform.linux_distribution, which is not av
|
|||
libGL = find_library("GL")
|
||||
ctypes.CDLL(libGL, ctypes.RTLD_GLOBAL)
|
||||
|
||||
# When frozen, i.e. installer version, don't let PYTHONPATH mess up the search path for DLLs.
|
||||
if Platform.isWindows() and hasattr(sys, "frozen"):
|
||||
try:
|
||||
del os.environ["PYTHONPATH"]
|
||||
except KeyError: pass
|
||||
|
||||
#WORKAROUND: GITHUB-704 GITHUB-708
|
||||
# It looks like setuptools creates a .pth file in
|
||||
# the default /usr/lib which causes the default site-packages
|
||||
|
|
@ -45,7 +50,6 @@ sys.excepthook = exceptHook
|
|||
# first seems to prevent Sip from going into a state where it
|
||||
# tries to create PyQt objects on a non-main thread.
|
||||
import Arcus #@UnusedImport
|
||||
from UM.Platform import Platform
|
||||
import cura.CuraApplication
|
||||
import cura.Settings.CuraContainerRegistry
|
||||
|
||||
|
|
@ -56,7 +60,11 @@ if Platform.isWindows() and hasattr(sys, "frozen"):
|
|||
sys.stderr = open(os.path.join(dirpath, "stderr.log"), "w")
|
||||
|
||||
# Force an instance of CuraContainerRegistry to be created and reused later.
|
||||
cura.Settings.CuraContainerRegistry.getInstance()
|
||||
cura.Settings.CuraContainerRegistry.CuraContainerRegistry.getInstance()
|
||||
|
||||
# This prestart up check is needed to determine if we should start the application at all.
|
||||
if not cura.CuraApplication.CuraApplication.preStartUp():
|
||||
sys.exit(0)
|
||||
|
||||
app = cura.CuraApplication.CuraApplication.getInstance()
|
||||
app.run()
|
||||
|
|
|
|||
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
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
268
plugins/CuraEngineBackend/CuraEngineBackend.py
Normal file → Executable file
268
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,7 +523,12 @@ 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):
|
||||
|
|
@ -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)
|
||||
|
|
@ -111,20 +124,25 @@ 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)
|
||||
|
|
@ -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,7 +30,6 @@ 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):
|
||||
|
|
@ -36,6 +37,12 @@ class LayerViewProxy(QObject):
|
|||
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):
|
||||
|
|
@ -45,12 +52,77 @@ class LayerViewProxy(QObject):
|
|||
|
||||
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()
|
||||
|
||||
|
|
@ -64,9 +136,17 @@ class LayerViewProxy(QObject):
|
|||
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.
|
||||
|
|
|
|||
84
resources/definitions/abax_pri3.def.json
Normal file
84
resources/definitions/abax_pri3.def.json
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
{
|
||||
"id": "PRi3",
|
||||
"name": "ABAX PRi3",
|
||||
"version": 2,
|
||||
"inherits": "fdmprinter",
|
||||
"metadata": {
|
||||
"visible": true,
|
||||
"author": "ABAX 3d Technologies",
|
||||
"manufacturer": "ABAX 3d Technologies",
|
||||
"category": "Other",
|
||||
"file_formats": "text/x-gcode"
|
||||
},
|
||||
"overrides": {
|
||||
"machine_start_gcode": {
|
||||
"default_value": "; -- START GCODE --\nG21 ;set units to millimetres\nG90 ;set to absolute positioning\nM106 S0 ;set fan speed to zero (turned off)\nG28 X0 Y0 ;move to the X/Y origin (Home)\nG28 Z0 ;move to the Z origin (Home)\nG1 Z5.0 F200 ;move Z to position 5.0 mm\nG92 E0 ;zero the extruded length\n; -- end of START GCODE --"
|
||||
},
|
||||
"machine_end_gcode": {
|
||||
"default_value": "; -- END GCODE --\nM104 S0 ;set extruder temperature to zero (turned off)\nM140 S0 ;set temp of bed to Zero \nG91 ;set to relative positioning\nG1 E-10 F300 ;retract the filament a bit to release some of the pressure\nG1 F2000 X0 Y215 ;move X to min and Y to max \nG90 ;set to absolute positioning\nM84 ;turn off steppers\n; -- end of END GCODE --"
|
||||
},
|
||||
"machine_width": {
|
||||
"default_value": 225
|
||||
},
|
||||
"machine_depth": {
|
||||
"default_value": 220
|
||||
},
|
||||
"machine_height": {
|
||||
"default_value": 200
|
||||
},
|
||||
"machine_heated_bed": {
|
||||
"default_value": false
|
||||
},
|
||||
"machine_center_is_zero": {
|
||||
"default_value": false
|
||||
},
|
||||
"machine_gcode_flavor": {
|
||||
"default_value": "RepRap"
|
||||
},
|
||||
"layer_height": {
|
||||
"default_value": 0.2
|
||||
},
|
||||
"layer_height_0": {
|
||||
"default_value": 0.2
|
||||
},
|
||||
"wall_thickness": {
|
||||
"default_value": 1
|
||||
},
|
||||
"top_bottom_thickness": {
|
||||
"default_value": 1
|
||||
},
|
||||
"bottom_thickness": {
|
||||
"default_value": 1
|
||||
},
|
||||
"material_print_temperature": {
|
||||
"default_value": 200
|
||||
},
|
||||
"material_bed_temperature": {
|
||||
"default_value": 0
|
||||
},
|
||||
"material_diameter": {
|
||||
"default_value": 1.75
|
||||
},
|
||||
"speed_print": {
|
||||
"default_value": 40
|
||||
},
|
||||
"speed_infill": {
|
||||
"default_value": 70
|
||||
},
|
||||
"speed_wall": {
|
||||
"default_value": 25
|
||||
},
|
||||
"speed_topbottom": {
|
||||
"default_value": 15
|
||||
},
|
||||
"speed_travel": {
|
||||
"default_value": 150
|
||||
},
|
||||
"speed_layer_0": {
|
||||
"default_value": 30
|
||||
},
|
||||
"support_enable": {
|
||||
"default_value": true
|
||||
}
|
||||
}
|
||||
}
|
||||
84
resources/definitions/abax_pri5.def.json
Normal file
84
resources/definitions/abax_pri5.def.json
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
{
|
||||
"id": "PRi5",
|
||||
"name": "ABAX PRi5",
|
||||
"version": 2,
|
||||
"inherits": "fdmprinter",
|
||||
"metadata": {
|
||||
"visible": true,
|
||||
"author": "ABAX 3d Technologies",
|
||||
"manufacturer": "ABAX 3d Technologies",
|
||||
"category": "Other",
|
||||
"file_formats": "text/x-gcode"
|
||||
},
|
||||
"overrides": {
|
||||
"machine_start_gcode": {
|
||||
"default_value": "; -- START GCODE --\nG21 ;set units to millimetres\nG90 ;set to absolute positioning\nM106 S0 ;set fan speed to zero (turned off)\nG28 X0 Y0 ;move to the X/Y origin (Home)\nG28 Z0 ;move to the Z origin (Home)\nG1 Z5.0 F200 ;move Z to position 5.0 mm\nG92 E0 ;zero the extruded length\n; -- end of START GCODE --"
|
||||
},
|
||||
"machine_end_gcode": {
|
||||
"default_value": "; -- END GCODE --\nM104 S0 ;set extruder temperature to zero (turned off)\nM140 S0 ;set temp of bed to Zero \nG91 ;set to relative positioning\nG1 E-10 F300 ;retract the filament a bit to release some of the pressure\nG1 F2000 X0 Y300 ;move X to min and Y to max \nG90 ;set to absolute positioning\nM84 ;turn off steppers\n; -- end of END GCODE --"
|
||||
},
|
||||
"machine_width": {
|
||||
"default_value": 310
|
||||
},
|
||||
"machine_depth": {
|
||||
"default_value": 310
|
||||
},
|
||||
"machine_height": {
|
||||
"default_value": 300
|
||||
},
|
||||
"machine_heated_bed": {
|
||||
"default_value": false
|
||||
},
|
||||
"machine_center_is_zero": {
|
||||
"default_value": false
|
||||
},
|
||||
"machine_gcode_flavor": {
|
||||
"default_value": "RepRap"
|
||||
},
|
||||
"layer_height": {
|
||||
"default_value": 0.2
|
||||
},
|
||||
"layer_height_0": {
|
||||
"default_value": 0.2
|
||||
},
|
||||
"wall_thickness": {
|
||||
"default_value": 1
|
||||
},
|
||||
"top_bottom_thickness": {
|
||||
"default_value": 1
|
||||
},
|
||||
"bottom_thickness": {
|
||||
"default_value": 1
|
||||
},
|
||||
"material_print_temperature": {
|
||||
"default_value": 200
|
||||
},
|
||||
"material_bed_temperature": {
|
||||
"default_value": 0
|
||||
},
|
||||
"material_diameter": {
|
||||
"default_value": 1.75
|
||||
},
|
||||
"speed_print": {
|
||||
"default_value": 40
|
||||
},
|
||||
"speed_infill": {
|
||||
"default_value": 70
|
||||
},
|
||||
"speed_wall": {
|
||||
"default_value": 25
|
||||
},
|
||||
"speed_topbottom": {
|
||||
"default_value": 15
|
||||
},
|
||||
"speed_travel": {
|
||||
"default_value": 150
|
||||
},
|
||||
"speed_layer_0": {
|
||||
"default_value": 30
|
||||
},
|
||||
"support_enable": {
|
||||
"default_value": true
|
||||
}
|
||||
}
|
||||
}
|
||||
84
resources/definitions/abax_titan.def.json
Normal file
84
resources/definitions/abax_titan.def.json
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
{
|
||||
"id": "Titan",
|
||||
"name": "ABAX Titan",
|
||||
"version": 2,
|
||||
"inherits": "fdmprinter",
|
||||
"metadata": {
|
||||
"visible": true,
|
||||
"author": "ABAX 3d Technologies",
|
||||
"manufacturer": "ABAX 3d Technologies",
|
||||
"category": "Other",
|
||||
"file_formats": "text/x-gcode"
|
||||
},
|
||||
"overrides": {
|
||||
"machine_start_gcode": {
|
||||
"default_value": "; -- START GCODE --\nG21 ;set units to millimetres\nG90 ;set to absolute positioning\nM106 S0 ;set fan speed to zero (turned off)\nG28 X0 Y0 ;move to the X/Y origin (Home)\nG28 Z0 ;move to the Z origin (Home)\nG1 Z5.0 F200 ;move Z to position 5.0 mm\nG92 E0 ;zero the extruded length\n; -- end of START GCODE --"
|
||||
},
|
||||
"machine_end_gcode": {
|
||||
"default_value": "; -- END GCODE --\nM104 S0 ;set extruder temperature to zero (turned off)\nM140 S0 ;set temp of bed to Zero \nG91 ;set to relative positioning\nG1 E-10 F300 ;retract the filament a bit to release some of the pressure\nG1 F2000 X0 Y300 ;move X to min and Y to max \nG90 ;set to absolute positioning\nM84 ;turn off steppers\n; -- end of END GCODE --"
|
||||
},
|
||||
"machine_width": {
|
||||
"default_value": 310
|
||||
},
|
||||
"machine_depth": {
|
||||
"default_value": 310
|
||||
},
|
||||
"machine_height": {
|
||||
"default_value": 300
|
||||
},
|
||||
"machine_heated_bed": {
|
||||
"default_value": false
|
||||
},
|
||||
"machine_center_is_zero": {
|
||||
"default_value": false
|
||||
},
|
||||
"machine_gcode_flavor": {
|
||||
"default_value": "RepRap"
|
||||
},
|
||||
"layer_height": {
|
||||
"default_value": 0.2
|
||||
},
|
||||
"layer_height_0": {
|
||||
"default_value": 0.2
|
||||
},
|
||||
"wall_thickness": {
|
||||
"default_value": 1
|
||||
},
|
||||
"top_bottom_thickness": {
|
||||
"default_value": 1
|
||||
},
|
||||
"bottom_thickness": {
|
||||
"default_value": 1
|
||||
},
|
||||
"material_print_temperature": {
|
||||
"default_value": 200
|
||||
},
|
||||
"material_bed_temperature": {
|
||||
"default_value": 0
|
||||
},
|
||||
"material_diameter": {
|
||||
"default_value": 1.75
|
||||
},
|
||||
"speed_print": {
|
||||
"default_value": 40
|
||||
},
|
||||
"speed_infill": {
|
||||
"default_value": 70
|
||||
},
|
||||
"speed_wall": {
|
||||
"default_value": 25
|
||||
},
|
||||
"speed_topbottom": {
|
||||
"default_value": 15
|
||||
},
|
||||
"speed_travel": {
|
||||
"default_value": 150
|
||||
},
|
||||
"speed_layer_0": {
|
||||
"default_value": 30
|
||||
},
|
||||
"support_enable": {
|
||||
"default_value": true
|
||||
}
|
||||
}
|
||||
}
|
||||
66
resources/definitions/cartesio.def.json
Normal file
66
resources/definitions/cartesio.def.json
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
{
|
||||
"id": "cartesio",
|
||||
"name": "Cartesio",
|
||||
"version": 2,
|
||||
"inherits": "fdmprinter",
|
||||
"metadata": {
|
||||
"visible": true,
|
||||
"author": "Scheepers",
|
||||
"manufacturer": "Cartesio bv",
|
||||
"category": "Other",
|
||||
"file_formats": "text/x-gcode",
|
||||
|
||||
"has_machine_quality": true,
|
||||
"has_materials": true,
|
||||
"has_machine_materials": true,
|
||||
"has_variant_materials": true,
|
||||
"has_variants": true,
|
||||
|
||||
"variants_name": "Nozzle size",
|
||||
"preferred_variant": "*0.4*",
|
||||
"preferred_material": "*pla*",
|
||||
"preferred_quality": "*normal*",
|
||||
|
||||
"machine_extruder_trains":
|
||||
{
|
||||
"0": "cartesio_extruder_0",
|
||||
"1": "cartesio_extruder_1",
|
||||
"2": "cartesio_extruder_2",
|
||||
"3": "cartesio_extruder_3"
|
||||
},
|
||||
"platform": "cartesio_platform.stl",
|
||||
"platform_offset": [ -120, -1.5, 130],
|
||||
"first_start_actions": ["MachineSettingsAction"],
|
||||
"supported_actions": ["MachineSettingsAction"]
|
||||
},
|
||||
|
||||
"overrides": {
|
||||
"machine_extruder_count": { "default_value": 4 },
|
||||
"machine_heated_bed": { "default_value": true },
|
||||
"machine_center_is_zero": { "default_value": false },
|
||||
"gantry_height": { "default_value": 35 },
|
||||
"machine_height": { "default_value": 400 },
|
||||
"machine_depth": { "default_value": 270 },
|
||||
"machine_width": { "default_value": 430 },
|
||||
"machine_gcode_flavor": { "default_value": "RepRap (Marlin/Sprinter)" },
|
||||
"material_print_temp_wait": { "default_value": false },
|
||||
"material_bed_temp_wait": { "default_value": false },
|
||||
"infill_pattern": { "default_value": "grid"},
|
||||
"prime_tower_enable": { "default_value": true },
|
||||
"prime_tower_wall_thickness": { "resolve": 0.7 },
|
||||
"prime_tower_position_x": { "default_value": 50 },
|
||||
"prime_tower_position_y": { "default_value": 71 },
|
||||
"machine_start_gcode": {
|
||||
"default_value": "\nM104 S120 T1\nM104 S120 T2\nM104 S120 T3\n\nM92 E159\n\nG21\nG90\nM42 S255 P13;chamber lights\nM42 S255 P12;fume extraction\n\nM117 Homing Y ......\nG28 Y\nM117 Homing X ......\nG28 X\nM117 Homing Z ......\nG28 Z F100\nG1 Z10 F600\nG1 X70 Y20 F9000;go to wipe point\n\nM190 S{material_bed_temperature_layer_0}\n\nM117 Heating for 50 sec.\nG4 S20\nM117 Heating for 30 sec.\nG4 S20\nM117 Heating for 10 sec.\nM300 S600 P1000\nG4 S9\n\nM117 purging nozzle....\nT0\nG92 E0;set E\nG1 E10 F100\nG92 E0\nG1 E-1 F600\n\nM117 wiping nozzle....\nG1 X1 Y24 F3000\nG1 X70 F9000\n\nM104 S21 T1\nM104 S21 T2\nM104 S21 T3\n\nM117 Printing .....\n"
|
||||
},
|
||||
"machine_end_gcode": {
|
||||
"default_value": "; -- END GCODE --\nM106 S255\nM140 S5\nM104 S5 T0\nM104 S5 T1\nM104 S5 T2\nM104 S5 T3\nG1 X20.0 Y260.0 F6000\nG4 S7\nM84\nG4 S90\nM107\nM42 P12 S0\nM42 P13 S0\nM84\nT0\n; -- end of GCODE --"
|
||||
},
|
||||
"layer_height": { "maximum_value": "(0.8 * min(extruderValues('machine_nozzle_size')))" },
|
||||
"layer_height_0": { "maximum_value": "(0.8 * min(extruderValues('machine_nozzle_size')))" },
|
||||
"layer_height_0": { "resolve": "0.2 if min(extruderValues('machine_nozzle_size')) < 0.3 else 0.3 "},
|
||||
"machine_nozzle_heat_up_speed": {"default_value": 20},
|
||||
"machine_nozzle_cool_down_speed": {"default_value": 20},
|
||||
"machine_min_cool_heat_time_window": {"default_value": 5}
|
||||
}
|
||||
}
|
||||
370
resources/definitions/fdmprinter.def.json
Normal file → Executable file
370
resources/definitions/fdmprinter.def.json
Normal file → Executable file
|
|
@ -93,6 +93,7 @@
|
|||
"description": "Whether to wait until the nozzle temperature is reached at the start.",
|
||||
"default_value": true,
|
||||
"type": "bool",
|
||||
"enabled": "machine_nozzle_temp_enabled",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": false,
|
||||
"settable_per_meshgroup": false
|
||||
|
|
@ -103,6 +104,7 @@
|
|||
"description": "Whether to include nozzle temperature commands at the start of the gcode. When the start_gcode already contains nozzle temperature commands Cura frontend will automatically disable this setting.",
|
||||
"default_value": true,
|
||||
"type": "bool",
|
||||
"enabled": "machine_nozzle_temp_enabled",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": false,
|
||||
"settable_per_meshgroup": false
|
||||
|
|
@ -219,8 +221,11 @@
|
|||
{
|
||||
"label": "Nozzle angle",
|
||||
"description": "The angle between the horizontal plane and the conical part right above the tip of the nozzle.",
|
||||
"default_value": 45,
|
||||
"unit": "°",
|
||||
"type": "int",
|
||||
"default_value": 45,
|
||||
"maximum_value": "89",
|
||||
"minimum_value": "1",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": false,
|
||||
"settable_per_meshgroup": false
|
||||
|
|
@ -246,6 +251,17 @@
|
|||
"settable_per_extruder": true,
|
||||
"settable_per_meshgroup": false
|
||||
},
|
||||
"machine_nozzle_temp_enabled":
|
||||
{
|
||||
"label": "Enable Nozzle Temperature Control",
|
||||
"description": "Whether to control temperature from Cura. Turn this off to control nozzle temperature from outside of Cura.",
|
||||
"default_value": true,
|
||||
"value": "machine_gcode_flavor != \"UltiGCode\"",
|
||||
"type": "bool",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": true,
|
||||
"settable_per_meshgroup": false
|
||||
},
|
||||
"machine_nozzle_heat_up_speed":
|
||||
{
|
||||
"label": "Heat up speed",
|
||||
|
|
@ -253,6 +269,7 @@
|
|||
"default_value": 2.0,
|
||||
"unit": "°C/s",
|
||||
"type": "float",
|
||||
"enabled": "machine_nozzle_temp_enabled",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": true
|
||||
},
|
||||
|
|
@ -263,6 +280,7 @@
|
|||
"default_value": 2.0,
|
||||
"unit": "°C/s",
|
||||
"type": "float",
|
||||
"enabled": "machine_nozzle_temp_enabled",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": true
|
||||
},
|
||||
|
|
@ -273,6 +291,7 @@
|
|||
"default_value": 50.0,
|
||||
"unit": "s",
|
||||
"type": "float",
|
||||
"enabled": "machine_nozzle_temp_enabled",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": true
|
||||
},
|
||||
|
|
@ -615,8 +634,8 @@
|
|||
"label": "Line Width",
|
||||
"description": "Width of a single line. Generally, the width of each line should correspond to the width of the nozzle. However, slightly reducing this value could produce better prints.",
|
||||
"unit": "mm",
|
||||
"minimum_value": "0.0001",
|
||||
"minimum_value_warning": "0.5 * machine_nozzle_size",
|
||||
"minimum_value": "0.001",
|
||||
"minimum_value_warning": "0.1 + 0.4 * machine_nozzle_size",
|
||||
"maximum_value_warning": "2 * machine_nozzle_size",
|
||||
"default_value": 0.4,
|
||||
"type": "float",
|
||||
|
|
@ -629,8 +648,8 @@
|
|||
"label": "Wall Line Width",
|
||||
"description": "Width of a single wall line.",
|
||||
"unit": "mm",
|
||||
"minimum_value": "0.0001",
|
||||
"minimum_value_warning": "0.75 * machine_nozzle_size",
|
||||
"minimum_value": "0.001",
|
||||
"minimum_value_warning": "0.1 + 0.4 * machine_nozzle_size",
|
||||
"maximum_value_warning": "2 * machine_nozzle_size",
|
||||
"value": "line_width",
|
||||
"default_value": 0.4,
|
||||
|
|
@ -643,8 +662,8 @@
|
|||
"label": "Outer Wall Line Width",
|
||||
"description": "Width of the outermost wall line. By lowering this value, higher levels of detail can be printed.",
|
||||
"unit": "mm",
|
||||
"minimum_value": "0.0001",
|
||||
"minimum_value_warning": "0.75 * machine_nozzle_size if outer_inset_first else 0.1 * machine_nozzle_size",
|
||||
"minimum_value": "0.001",
|
||||
"minimum_value_warning": "(0.1 + 0.4 * machine_nozzle_size) if outer_inset_first else 0.1 * machine_nozzle_size",
|
||||
"maximum_value_warning": "2 * machine_nozzle_size",
|
||||
"default_value": 0.4,
|
||||
"value": "wall_line_width",
|
||||
|
|
@ -656,8 +675,8 @@
|
|||
"label": "Inner Wall(s) Line Width",
|
||||
"description": "Width of a single wall line for all wall lines except the outermost one.",
|
||||
"unit": "mm",
|
||||
"minimum_value": "0.0001",
|
||||
"minimum_value_warning": "0.5 * machine_nozzle_size",
|
||||
"minimum_value": "0.001",
|
||||
"minimum_value_warning": "0.1 + 0.4 * machine_nozzle_size",
|
||||
"maximum_value_warning": "2 * machine_nozzle_size",
|
||||
"default_value": 0.4,
|
||||
"value": "wall_line_width",
|
||||
|
|
@ -671,8 +690,8 @@
|
|||
"label": "Top/Bottom Line Width",
|
||||
"description": "Width of a single top/bottom line.",
|
||||
"unit": "mm",
|
||||
"minimum_value": "0.0001",
|
||||
"minimum_value_warning": "0.1 * machine_nozzle_size",
|
||||
"minimum_value": "0.001",
|
||||
"minimum_value_warning": "0.1 + 0.4 * machine_nozzle_size",
|
||||
"maximum_value_warning": "2 * machine_nozzle_size",
|
||||
"default_value": 0.4,
|
||||
"type": "float",
|
||||
|
|
@ -684,8 +703,8 @@
|
|||
"label": "Infill Line Width",
|
||||
"description": "Width of a single infill line.",
|
||||
"unit": "mm",
|
||||
"minimum_value": "0.0001",
|
||||
"minimum_value_warning": "0.75 * machine_nozzle_size",
|
||||
"minimum_value": "0.001",
|
||||
"minimum_value_warning": "0.1 + 0.4 * machine_nozzle_size",
|
||||
"maximum_value_warning": "3 * machine_nozzle_size",
|
||||
"default_value": 0.4,
|
||||
"type": "float",
|
||||
|
|
@ -698,8 +717,8 @@
|
|||
"label": "Skirt/Brim Line Width",
|
||||
"description": "Width of a single skirt or brim line.",
|
||||
"unit": "mm",
|
||||
"minimum_value": "0.0001",
|
||||
"minimum_value_warning": "0.75 * machine_nozzle_size",
|
||||
"minimum_value": "0.001",
|
||||
"minimum_value_warning": "0.1 + 0.4 * machine_nozzle_size",
|
||||
"maximum_value_warning": "3 * machine_nozzle_size",
|
||||
"default_value": 0.4,
|
||||
"type": "float",
|
||||
|
|
@ -713,8 +732,8 @@
|
|||
"label": "Support Line Width",
|
||||
"description": "Width of a single support structure line.",
|
||||
"unit": "mm",
|
||||
"minimum_value": "0.0001",
|
||||
"minimum_value_warning": "0.75 * machine_nozzle_size",
|
||||
"minimum_value": "0.001",
|
||||
"minimum_value_warning": "0.1 + 0.4 * machine_nozzle_size",
|
||||
"maximum_value_warning": "3 * machine_nozzle_size",
|
||||
"default_value": 0.4,
|
||||
"type": "float",
|
||||
|
|
@ -730,8 +749,8 @@
|
|||
"description": "Width of a single support interface line.",
|
||||
"unit": "mm",
|
||||
"default_value": 0.4,
|
||||
"minimum_value": "0.0001",
|
||||
"minimum_value_warning": "0.4 * machine_nozzle_size",
|
||||
"minimum_value": "0.001",
|
||||
"minimum_value_warning": "0.1 + 0.4 * machine_nozzle_size",
|
||||
"maximum_value_warning": "2 * machine_nozzle_size",
|
||||
"type": "float",
|
||||
"enabled": "support_enable and support_interface_enable",
|
||||
|
|
@ -749,8 +768,8 @@
|
|||
"enabled": "resolveOrValue('prime_tower_enable')",
|
||||
"default_value": 0.4,
|
||||
"value": "line_width",
|
||||
"minimum_value": "0.0001",
|
||||
"minimum_value_warning": "0.75 * machine_nozzle_size",
|
||||
"minimum_value": "0.001",
|
||||
"minimum_value_warning": "0.1 + 0.4 * machine_nozzle_size",
|
||||
"maximum_value_warning": "2 * machine_nozzle_size",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": true
|
||||
|
|
@ -826,7 +845,7 @@
|
|||
"unit": "mm",
|
||||
"default_value": 0.8,
|
||||
"minimum_value": "0",
|
||||
"minimum_value_warning": "3 * resolveOrValue('layer_height')",
|
||||
"minimum_value_warning": "0.2 + resolveOrValue('layer_height')",
|
||||
"maximum_value": "machine_height",
|
||||
"type": "float",
|
||||
"value": "top_bottom_thickness",
|
||||
|
|
@ -841,7 +860,7 @@
|
|||
"minimum_value": "0",
|
||||
"maximum_value_warning": "100",
|
||||
"type": "int",
|
||||
"minimum_value_warning": "4",
|
||||
"minimum_value_warning": "2",
|
||||
"value": "0 if infill_sparse_density == 100 else math.ceil(round(top_thickness / resolveOrValue('layer_height'), 4))",
|
||||
"settable_per_mesh": true
|
||||
}
|
||||
|
|
@ -854,7 +873,7 @@
|
|||
"unit": "mm",
|
||||
"default_value": 0.6,
|
||||
"minimum_value": "0",
|
||||
"minimum_value_warning": "3 * resolveOrValue('layer_height')",
|
||||
"minimum_value_warning": "0.2 + resolveOrValue('layer_height')",
|
||||
"type": "float",
|
||||
"value": "top_bottom_thickness",
|
||||
"maximum_value": "machine_height",
|
||||
|
|
@ -866,7 +885,7 @@
|
|||
"label": "Bottom Layers",
|
||||
"description": "The number of bottom layers. When calculated by the bottom thickness, this value is rounded to a whole number.",
|
||||
"minimum_value": "0",
|
||||
"minimum_value_warning": "4",
|
||||
"minimum_value_warning": "2",
|
||||
"default_value": 6,
|
||||
"type": "int",
|
||||
"value": "999999 if infill_sparse_density == 100 else math.ceil(round(bottom_thickness / resolveOrValue('layer_height'), 4))",
|
||||
|
|
@ -905,6 +924,15 @@
|
|||
"value": "top_bottom_pattern",
|
||||
"settable_per_mesh": true
|
||||
},
|
||||
"skin_angles":
|
||||
{
|
||||
"label": "Top/Bottom Line Directions",
|
||||
"description": "A list of integer line directions to use when the top/bottom layers use the lines or zig zag pattern. Elements from the list are used sequentially as the layers progress and when the end of the list is reached, it starts at the beginning again. The list items are separated by commas and the whole list is contained in square brackets. Default is an empty list which means use the traditional default angles (45 and 135 degrees).",
|
||||
"type": "[int]",
|
||||
"default_value": "[ ]",
|
||||
"enabled": "top_bottom_pattern != 'concentric'",
|
||||
"settable_per_mesh": true
|
||||
},
|
||||
"wall_0_inset":
|
||||
{
|
||||
"label": "Outer Wall Inset",
|
||||
|
|
@ -1059,7 +1087,7 @@
|
|||
"default_value": 2,
|
||||
"minimum_value": "0",
|
||||
"minimum_value_warning": "infill_line_width",
|
||||
"value": "0 if infill_sparse_density == 0 else (infill_line_width * 100) / infill_sparse_density * (2 if infill_pattern == 'grid' else (3 if infill_pattern == 'triangles' or infill_pattern == 'cubic' or infill_pattern == 'cubicsubdiv' else (4 if infill_pattern == 'tetrahedral' else 1)))",
|
||||
"value": "0 if infill_sparse_density == 0 else (infill_line_width * 100) / infill_sparse_density * (2 if infill_pattern == 'grid' else (3 if infill_pattern == 'triangles' or infill_pattern == 'cubic' or infill_pattern == 'cubicsubdiv' else (2 if infill_pattern == 'tetrahedral' else 1)))",
|
||||
"settable_per_mesh": true
|
||||
}
|
||||
}
|
||||
|
|
@ -1086,6 +1114,74 @@
|
|||
"value": "'lines' if infill_sparse_density > 25 else 'grid'",
|
||||
"settable_per_mesh": true
|
||||
},
|
||||
"infill_angles":
|
||||
{
|
||||
"label": "Infill Line Directions",
|
||||
"description": "A list of integer line directions to use. Elements from the list are used sequentially as the layers progress and when the end of the list is reached, it starts at the beginning again. The list items are separated by commas and the whole list is contained in square brackets. Default is an empty list which means use the traditional default angles (45 and 135 degrees for the lines and zig zag patterns and 45 degrees for all other patterns).",
|
||||
"type": "[int]",
|
||||
"default_value": "[ ]",
|
||||
"enabled": "infill_pattern != 'concentric' and infill_pattern != 'concentric_3d' and infill_pattern != 'cubicsubdiv'",
|
||||
"enabled": "infill_sparse_density > 0",
|
||||
"settable_per_mesh": true
|
||||
},
|
||||
"spaghetti_infill_enabled":
|
||||
{
|
||||
"label": "Spaghetti Infill",
|
||||
"description": "Print the infill every so often, so that the filament will curl up chaotically inside the object. This reduces print time, but the behaviour is rather unpredictable.",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"enabled": "infill_sparse_density > 0",
|
||||
"settable_per_mesh": true
|
||||
},
|
||||
"spaghetti_max_infill_angle":
|
||||
{
|
||||
"label": "Spaghetti Maximum Infill Angle",
|
||||
"description": "The maximum angle w.r.t. the Z axis of the inside of the print for areas which are to be filled with spaghetti infill afterwards. Lowering this value causes more angled parts in your model to be filled on each layer.",
|
||||
"unit": "°",
|
||||
"type": "float",
|
||||
"default_value": 10,
|
||||
"minimum_value": "0",
|
||||
"maximum_value": "90",
|
||||
"maximum_value_warning": "45",
|
||||
"enabled": "infill_sparse_density > 0 and spaghetti_infill_enabled",
|
||||
"settable_per_mesh": true
|
||||
},
|
||||
"spaghetti_max_height":
|
||||
{
|
||||
"label": "Spaghetti Infill Maximum Height",
|
||||
"description": "The maximum height of inside space which can be combined and filled from the top.",
|
||||
"unit": "mm",
|
||||
"type": "float",
|
||||
"default_value": 2.0,
|
||||
"minimum_value": "layer_height",
|
||||
"maximum_value_warning": "10.0",
|
||||
"enabled": "infill_sparse_density > 0 and spaghetti_infill_enabled",
|
||||
"settable_per_mesh": true
|
||||
},
|
||||
"spaghetti_inset":
|
||||
{
|
||||
"label": "Spaghetti Inset",
|
||||
"description": "The offset from the walls from where the spaghetti infill will be printed.",
|
||||
"unit": "mm",
|
||||
"type": "float",
|
||||
"default_value": 0.2,
|
||||
"minimum_value_warning": "0",
|
||||
"maximum_value_warning": "5.0",
|
||||
"enabled": "infill_sparse_density > 0 and spaghetti_infill_enabled",
|
||||
"settable_per_mesh": true
|
||||
},
|
||||
"spaghetti_flow":
|
||||
{
|
||||
"label": "Spaghetti Flow",
|
||||
"description": "Adjusts the density of the spaghetti infill. Note that the Infill Density only controls the line spacing of the filling pattern, not the amount of extrusion for spaghetti infill.",
|
||||
"unit": "%",
|
||||
"type": "float",
|
||||
"default_value": 20,
|
||||
"minimum_value": "0",
|
||||
"maximum_value_warning": "100",
|
||||
"enabled": "infill_sparse_density > 0 and spaghetti_infill_enabled",
|
||||
"settable_per_mesh": true
|
||||
},
|
||||
"sub_div_rad_mult":
|
||||
{
|
||||
"label": "Cubic Subdivision Radius",
|
||||
|
|
@ -1192,9 +1288,9 @@
|
|||
"default_value": 0.1,
|
||||
"minimum_value": "resolveOrValue('layer_height')",
|
||||
"maximum_value_warning": "0.75 * machine_nozzle_size",
|
||||
"maximum_value": "resolveOrValue('layer_height') * 8",
|
||||
"maximum_value": "resolveOrValue('layer_height') * (1.45 if spaghetti_infill_enabled else 8)",
|
||||
"value": "resolveOrValue('layer_height')",
|
||||
"enabled": "infill_sparse_density > 0",
|
||||
"enabled": "infill_sparse_density > 0 and not spaghetti_infill_enabled",
|
||||
"settable_per_mesh": true
|
||||
},
|
||||
"gradual_infill_steps":
|
||||
|
|
@ -1205,8 +1301,8 @@
|
|||
"type": "int",
|
||||
"minimum_value": "0",
|
||||
"maximum_value_warning": "4",
|
||||
"maximum_value": "(20 - math.log(infill_line_distance) / math.log(2)) if infill_line_distance > 0 else 0",
|
||||
"enabled": "infill_sparse_density > 0 and infill_pattern != 'cubicsubdiv'",
|
||||
"maximum_value": "(20 - math.log(infill_line_distance) / math.log(2)) if infill_line_distance > 0 and not spaghetti_infill_enabled else (0 if spaghetti_infill_enabled else 20)",
|
||||
"enabled": "infill_sparse_density > 0 and infill_pattern != 'cubicsubdiv' and not spaghetti_infill_enabled",
|
||||
"settable_per_mesh": true
|
||||
},
|
||||
"gradual_infill_step_height":
|
||||
|
|
@ -1240,6 +1336,75 @@
|
|||
"minimum_value": "0",
|
||||
"default_value": 0,
|
||||
"settable_per_mesh": true
|
||||
},
|
||||
"expand_skins_into_infill":
|
||||
{
|
||||
"label": "Expand Skins Into Infill",
|
||||
"description": "Expand skin areas of top and/or bottom skin of flat surfaces. By default, skins stop under the wall lines that surround infill but this can lead to holes appearing when the infill density is low. This setting extends the skins beyond the wall lines so that the infill on the next layer rests on skin.",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"settable_per_mesh": true,
|
||||
"children":
|
||||
{
|
||||
"expand_upper_skins":
|
||||
{
|
||||
"label": "Expand Upper Skins",
|
||||
"description": "Expand upper skin areas (areas with air above) so that they support infill above.",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"value": "expand_skins_into_infill",
|
||||
"settable_per_mesh": true
|
||||
},
|
||||
"expand_lower_skins":
|
||||
{
|
||||
"label": "Expand Lower Skins",
|
||||
"description": "Expand lower skin areas (areas with air below) so that they are anchored by the infill layers above and below.",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"settable_per_mesh": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"expand_skins_expand_distance":
|
||||
{
|
||||
"label": "Skin Expand Distance",
|
||||
"description": "The distance the skins are expanded into the infill. The default distance is enough to bridge the gap between the infill lines and will stop holes appearing in the skin where it meets the wall when the infill density is low. A smaller distance will often be sufficient.",
|
||||
"unit": "mm",
|
||||
"type": "float",
|
||||
"default_value": 2.8,
|
||||
"value": "infill_line_distance * 1.4",
|
||||
"minimum_value": "0",
|
||||
"enabled": "expand_upper_skins or expand_lower_skins",
|
||||
"settable_per_mesh": true
|
||||
},
|
||||
"max_skin_angle_for_expansion":
|
||||
{
|
||||
"label": "Maximum Skin Angle for Expansion",
|
||||
"description": "Top and/or bottom surfaces of your object with an angle larger than this setting, won't have their top/bottom skin expanded. This avoids expanding the narrow skin areas that are created when the model surface has a near vertical slope. An angle of 0° is horizontal, while an angle of 90° is vertical.",
|
||||
"unit": "°",
|
||||
"type": "float",
|
||||
"minimum_value": "0",
|
||||
"minimum_value_warning": "2",
|
||||
"maximum_value_warning": "45",
|
||||
"maximum_value": "90",
|
||||
"default_value": 20,
|
||||
"enabled": "expand_upper_skins or expand_lower_skins",
|
||||
"settable_per_mesh": true,
|
||||
"children":
|
||||
{
|
||||
"min_skin_width_for_expansion":
|
||||
{
|
||||
"label": "Minimum Skin Width for Expansion",
|
||||
"description": "Skin areas narrower than this are not expanded. This avoids expanding the narrow skin areas that are created when the model surface has a slope close to the vertical.",
|
||||
"unit": "mm",
|
||||
"type": "float",
|
||||
"default_value": 2.24,
|
||||
"value": "top_layers * layer_height / math.tan(math.radians(max_skin_angle_for_expansion))",
|
||||
"minimum_value": "0",
|
||||
"enabled": "expand_upper_skins or expand_lower_skins",
|
||||
"settable_per_mesh": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -1257,7 +1422,7 @@
|
|||
"description": "Change the temperature for each layer automatically with the average flow speed of that layer.",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"enabled": "False",
|
||||
"enabled": "machine_nozzle_temp_enabled and False",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": true
|
||||
},
|
||||
|
|
@ -1268,22 +1433,24 @@
|
|||
"unit": "°C",
|
||||
"type": "float",
|
||||
"default_value": 210,
|
||||
"enabled": false,
|
||||
"minimum_value_warning": "0",
|
||||
"maximum_value_warning": "285",
|
||||
"enabled": "machine_nozzle_temp_enabled",
|
||||
"settable_per_extruder": true,
|
||||
"minimum_value": "-273.15"
|
||||
},
|
||||
"material_print_temperature":
|
||||
{
|
||||
"label": "Printing Temperature",
|
||||
"description": "The temperature used for printing. Set at 0 to pre-heat the printer manually.",
|
||||
"description": "The temperature used for printing.",
|
||||
"unit": "°C",
|
||||
"type": "float",
|
||||
"default_value": 210,
|
||||
"value": "default_material_print_temperature",
|
||||
"minimum_value": "-273.15",
|
||||
"minimum_value_warning": "0",
|
||||
"maximum_value_warning": "260",
|
||||
"enabled": "not (material_flow_dependent_temperature) and machine_gcode_flavor != \"UltiGCode\"",
|
||||
"maximum_value_warning": "285",
|
||||
"enabled": "machine_nozzle_temp_enabled and not (material_flow_dependent_temperature)",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": true
|
||||
},
|
||||
|
|
@ -1294,11 +1461,11 @@
|
|||
"unit": "°C",
|
||||
"type": "float",
|
||||
"default_value": 215,
|
||||
"value": "material_print_temperature + 5",
|
||||
"value": "material_print_temperature",
|
||||
"minimum_value": "-273.15",
|
||||
"minimum_value_warning": "0",
|
||||
"maximum_value_warning": "260",
|
||||
"enabled": "machine_gcode_flavor != \"UltiGCode\"",
|
||||
"maximum_value_warning": "285",
|
||||
"enabled": "machine_nozzle_temp_enabled",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": true
|
||||
},
|
||||
|
|
@ -1313,7 +1480,7 @@
|
|||
"minimum_value": "-273.15",
|
||||
"minimum_value_warning": "material_standby_temperature",
|
||||
"maximum_value_warning": "material_print_temperature",
|
||||
"enabled": "machine_gcode_flavor != \"UltiGCode\"",
|
||||
"enabled": "machine_nozzle_temp_enabled",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": true
|
||||
},
|
||||
|
|
@ -1328,7 +1495,7 @@
|
|||
"minimum_value": "-273.15",
|
||||
"minimum_value_warning": "material_standby_temperature",
|
||||
"maximum_value_warning": "material_print_temperature",
|
||||
"enabled": "machine_gcode_flavor != \"UltiGCode\"",
|
||||
"enabled": "machine_nozzle_temp_enabled",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": true
|
||||
},
|
||||
|
|
@ -1339,8 +1506,7 @@
|
|||
"unit": "[[mm³,°C]]",
|
||||
"type": "str",
|
||||
"default_value": "[[3.5,200],[7.0,240]]",
|
||||
"enabled": "False",
|
||||
"comments": "old enabled function: material_flow_dependent_temperature",
|
||||
"enabled": "False and machine_nozzle_temp_enabled and material_flow_dependent_temperature",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": true
|
||||
},
|
||||
|
|
@ -1354,22 +1520,21 @@
|
|||
"minimum_value": "0",
|
||||
"maximum_value_warning": "10.0",
|
||||
"maximum_value": "machine_nozzle_heat_up_speed",
|
||||
"enabled": "False",
|
||||
"comments": "old enabled function: material_flow_dependent_temperature or machine_extruder_count > 1",
|
||||
"enabled": "material_flow_dependent_temperature or (machine_extruder_count > 1 and material_final_print_temperature != material_print_temperature)",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": true
|
||||
},
|
||||
"material_bed_temperature":
|
||||
{
|
||||
"label": "Build Plate Temperature",
|
||||
"description": "The temperature used for the heated build plate. Set at 0 to pre-heat the printer manually.",
|
||||
"description": "The temperature used for the heated build plate. If this is 0, the bed will not heat up for this print.",
|
||||
"unit": "°C",
|
||||
"type": "float",
|
||||
"resolve": "max(extruderValues('material_bed_temperature'))",
|
||||
"default_value": 60,
|
||||
"minimum_value": "-273.15",
|
||||
"minimum_value_warning": "0",
|
||||
"maximum_value_warning": "260",
|
||||
"maximum_value_warning": "130",
|
||||
"enabled": "machine_heated_bed and machine_gcode_flavor != \"UltiGCode\"",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": false,
|
||||
|
|
@ -1386,7 +1551,7 @@
|
|||
"value": "resolveOrValue('material_bed_temperature')",
|
||||
"minimum_value": "-273.15",
|
||||
"minimum_value_warning": "max(extruderValues('material_bed_temperature'))",
|
||||
"maximum_value_warning": "260",
|
||||
"maximum_value_warning": "130",
|
||||
"enabled": "machine_heated_bed and machine_gcode_flavor != \"UltiGCode\"",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": false,
|
||||
|
|
@ -1562,7 +1727,7 @@
|
|||
"minimum_value": "-273.15",
|
||||
"minimum_value_warning": "0",
|
||||
"maximum_value_warning": "260",
|
||||
"enabled": "machine_extruder_count > 1 and machine_gcode_flavor != \"UltiGCode\"",
|
||||
"enabled": "machine_extruder_count > 1 and machine_nozzle_temp_enabled",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": true
|
||||
},
|
||||
|
|
@ -2167,7 +2332,6 @@
|
|||
"unit": "mm/s",
|
||||
"type": "float",
|
||||
"minimum_value": "0.1",
|
||||
"minimum_value_warning": "5",
|
||||
"maximum_value_warning": "50",
|
||||
"default_value": 20,
|
||||
"enabled": "resolveOrValue('jerk_enabled')",
|
||||
|
|
@ -2181,7 +2345,6 @@
|
|||
"unit": "mm/s",
|
||||
"type": "float",
|
||||
"minimum_value": "0.1",
|
||||
"minimum_value_warning": "5",
|
||||
"maximum_value_warning": "50",
|
||||
"default_value": 20,
|
||||
"value": "jerk_print",
|
||||
|
|
@ -2195,7 +2358,6 @@
|
|||
"unit": "mm/s",
|
||||
"type": "float",
|
||||
"minimum_value": "0.1",
|
||||
"minimum_value_warning": "5",
|
||||
"maximum_value_warning": "50",
|
||||
"default_value": 20,
|
||||
"value": "jerk_print",
|
||||
|
|
@ -2210,7 +2372,6 @@
|
|||
"unit": "mm/s",
|
||||
"type": "float",
|
||||
"minimum_value": "0.1",
|
||||
"minimum_value_warning": "5",
|
||||
"maximum_value_warning": "50",
|
||||
"default_value": 20,
|
||||
"value": "jerk_wall",
|
||||
|
|
@ -2224,7 +2385,6 @@
|
|||
"unit": "mm/s",
|
||||
"type": "float",
|
||||
"minimum_value": "0.1",
|
||||
"minimum_value_warning": "5",
|
||||
"maximum_value_warning": "50",
|
||||
"default_value": 20,
|
||||
"value": "jerk_wall",
|
||||
|
|
@ -2240,7 +2400,6 @@
|
|||
"unit": "mm/s",
|
||||
"type": "float",
|
||||
"minimum_value": "0.1",
|
||||
"minimum_value_warning": "5",
|
||||
"maximum_value_warning": "50",
|
||||
"default_value": 20,
|
||||
"value": "jerk_print",
|
||||
|
|
@ -2254,7 +2413,6 @@
|
|||
"unit": "mm/s",
|
||||
"type": "float",
|
||||
"minimum_value": "0.1",
|
||||
"minimum_value_warning": "5",
|
||||
"maximum_value_warning": "50",
|
||||
"default_value": 20,
|
||||
"value": "jerk_print",
|
||||
|
|
@ -2273,7 +2431,6 @@
|
|||
"default_value": 20,
|
||||
"value": "jerk_support",
|
||||
"minimum_value": "0.1",
|
||||
"minimum_value_warning": "5",
|
||||
"maximum_value_warning": "50",
|
||||
"enabled": "resolveOrValue('jerk_enabled') and support_enable",
|
||||
"limit_to_extruder": "support_infill_extruder_nr",
|
||||
|
|
@ -2289,7 +2446,6 @@
|
|||
"default_value": 20,
|
||||
"value": "jerk_support",
|
||||
"minimum_value": "0.1",
|
||||
"minimum_value_warning": "5",
|
||||
"maximum_value_warning": "50",
|
||||
"enabled": "resolveOrValue('jerk_enabled') and extruderValue(support_interface_extruder_nr, 'support_interface_enable') and support_enable",
|
||||
"limit_to_extruder": "support_interface_extruder_nr",
|
||||
|
|
@ -2305,7 +2461,6 @@
|
|||
"unit": "mm/s",
|
||||
"type": "float",
|
||||
"minimum_value": "0.1",
|
||||
"minimum_value_warning": "5",
|
||||
"maximum_value_warning": "50",
|
||||
"default_value": 20,
|
||||
"value": "jerk_print",
|
||||
|
|
@ -2322,7 +2477,6 @@
|
|||
"type": "float",
|
||||
"default_value": 30,
|
||||
"minimum_value": "0.1",
|
||||
"minimum_value_warning": "5",
|
||||
"maximum_value_warning": "50",
|
||||
"value": "jerk_print if magic_spiralize else 30",
|
||||
"enabled": "resolveOrValue('jerk_enabled')",
|
||||
|
|
@ -2337,7 +2491,6 @@
|
|||
"default_value": 20,
|
||||
"value": "jerk_print",
|
||||
"minimum_value": "0.1",
|
||||
"minimum_value_warning": "5",
|
||||
"maximum_value_warning": "50",
|
||||
"enabled": "resolveOrValue('jerk_enabled')",
|
||||
"settable_per_mesh": true,
|
||||
|
|
@ -2352,7 +2505,6 @@
|
|||
"default_value": 20,
|
||||
"value": "jerk_layer_0",
|
||||
"minimum_value": "0.1",
|
||||
"minimum_value_warning": "5",
|
||||
"maximum_value_warning": "50",
|
||||
"enabled": "resolveOrValue('jerk_enabled')",
|
||||
"settable_per_mesh": true
|
||||
|
|
@ -2366,7 +2518,6 @@
|
|||
"default_value": 20,
|
||||
"value": "jerk_layer_0 * jerk_travel / jerk_print",
|
||||
"minimum_value": "0.1",
|
||||
"minimum_value_warning": "5",
|
||||
"maximum_value_warning": "50",
|
||||
"enabled": "resolveOrValue('jerk_enabled')",
|
||||
"settable_per_extruder": true,
|
||||
|
|
@ -2382,7 +2533,6 @@
|
|||
"type": "float",
|
||||
"default_value": 20,
|
||||
"minimum_value": "0.1",
|
||||
"minimum_value_warning": "5",
|
||||
"maximum_value_warning": "50",
|
||||
"value": "jerk_layer_0",
|
||||
"enabled": "resolveOrValue('jerk_enabled')",
|
||||
|
|
@ -2415,6 +2565,16 @@
|
|||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": false
|
||||
},
|
||||
"travel_retract_before_outer_wall":
|
||||
{
|
||||
"label": "Retract Before Outer Wall",
|
||||
"description": "Always retract when moving to start an outer wall.",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"enabled": "retraction_enable",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": false
|
||||
},
|
||||
"travel_avoid_other_parts":
|
||||
{
|
||||
"label": "Avoid Printed Parts When Traveling",
|
||||
|
|
@ -2446,6 +2606,7 @@
|
|||
"description": "In each layer start with printing the object near the same point, so that we don't start a new layer with printing the piece which the previous layer ended with. This makes for better overhangs and small parts, but increases printing time.",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"enabled": false,
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": false,
|
||||
"settable_per_meshgroup": true
|
||||
|
|
@ -2458,9 +2619,8 @@
|
|||
"type": "float",
|
||||
"default_value": 0.0,
|
||||
"minimum_value": "0",
|
||||
"enabled": "start_layers_at_same_position",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": false,
|
||||
"settable_per_extruder": true,
|
||||
"settable_per_meshgroup": true
|
||||
},
|
||||
"layer_start_y":
|
||||
|
|
@ -2471,9 +2631,8 @@
|
|||
"type": "float",
|
||||
"default_value": 0.0,
|
||||
"minimum_value": "0",
|
||||
"enabled": "start_layers_at_same_position",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": false,
|
||||
"settable_per_extruder": true,
|
||||
"settable_per_meshgroup": true
|
||||
},
|
||||
"retraction_hop_enabled": {
|
||||
|
|
@ -2677,8 +2836,8 @@
|
|||
{
|
||||
"support_enable":
|
||||
{
|
||||
"label": "Enable Support",
|
||||
"description": "Enable support structures. These structures support parts of the model with severe overhangs.",
|
||||
"label": "Generate Support",
|
||||
"description": "Generate structures to support parts of the model which have overhangs. Without these structures, such parts would collapse during printing.",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"settable_per_mesh": true,
|
||||
|
|
@ -2965,7 +3124,7 @@
|
|||
"type": "float",
|
||||
"default_value": 1,
|
||||
"minimum_value": "0",
|
||||
"minimum_value_warning": "3 * resolveOrValue('layer_height')",
|
||||
"minimum_value_warning": "0.2 + resolveOrValue('layer_height')",
|
||||
"maximum_value_warning": "10",
|
||||
"limit_to_extruder": "support_interface_extruder_nr",
|
||||
"enabled": "extruderValue(support_interface_extruder_nr, 'support_interface_enable') and support_enable",
|
||||
|
|
@ -2980,7 +3139,7 @@
|
|||
"type": "float",
|
||||
"default_value": 1,
|
||||
"minimum_value": "0",
|
||||
"minimum_value_warning": "3 * resolveOrValue('layer_height')",
|
||||
"minimum_value_warning": "0.2 + resolveOrValue('layer_height')",
|
||||
"maximum_value_warning": "10",
|
||||
"value": "extruderValue(support_interface_extruder_nr, 'support_interface_height')",
|
||||
"limit_to_extruder": "support_interface_extruder_nr",
|
||||
|
|
@ -2996,7 +3155,7 @@
|
|||
"default_value": 1,
|
||||
"value": "extruderValue(support_interface_extruder_nr, 'support_interface_height')",
|
||||
"minimum_value": "0",
|
||||
"minimum_value_warning": "min(3 * resolveOrValue('layer_height'), extruderValue(support_interface_extruder_nr, 'support_bottom_stair_step_height'))",
|
||||
"minimum_value_warning": "min(0.2 + resolveOrValue('layer_height'), extruderValue(support_interface_extruder_nr, 'support_bottom_stair_step_height'))",
|
||||
"maximum_value_warning": "10",
|
||||
"limit_to_extruder": "support_interface_extruder_nr",
|
||||
"enabled": "extruderValue(support_interface_extruder_nr, 'support_interface_enable') and support_enable",
|
||||
|
|
@ -3347,7 +3506,7 @@
|
|||
"type": "float",
|
||||
"default_value": 0.4,
|
||||
"value": "line_width",
|
||||
"minimum_value": "0.0001",
|
||||
"minimum_value": "0.001",
|
||||
"minimum_value_warning": "extruderValue(adhesion_extruder_nr, 'machine_nozzle_size') * 0.1",
|
||||
"maximum_value_warning": "extruderValue(adhesion_extruder_nr, 'machine_nozzle_size') * 2",
|
||||
"enabled": "resolveOrValue('adhesion_type') == 'raft'",
|
||||
|
|
@ -3362,7 +3521,7 @@
|
|||
"unit": "mm",
|
||||
"type": "float",
|
||||
"default_value": 0.4,
|
||||
"minimum_value": "0.0001",
|
||||
"minimum_value": "0",
|
||||
"minimum_value_warning": "extruderValue(adhesion_extruder_nr, 'raft_surface_line_width')",
|
||||
"maximum_value_warning": "extruderValue(adhesion_extruder_nr, 'raft_surface_line_width') * 3",
|
||||
"enabled": "resolveOrValue('adhesion_type') == 'raft'",
|
||||
|
|
@ -3381,7 +3540,7 @@
|
|||
"value": "resolveOrValue('layer_height') * 1.5",
|
||||
"minimum_value": "0.001",
|
||||
"minimum_value_warning": "0.04",
|
||||
"maximum_value_warning": "0.75 * extruderValue(adhesion_extruder_nr, 'raft_interface_line_width')",
|
||||
"maximum_value_warning": "0.75 * extruderValue(adhesion_extruder_nr, 'machine_nozzle_size')",
|
||||
"enabled": "resolveOrValue('adhesion_type') == 'raft'",
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": true,
|
||||
|
|
@ -3395,7 +3554,7 @@
|
|||
"type": "float",
|
||||
"default_value": 0.7,
|
||||
"value": "line_width * 2",
|
||||
"minimum_value": "0.0001",
|
||||
"minimum_value": "0.001",
|
||||
"minimum_value_warning": "extruderValue(adhesion_extruder_nr, 'machine_nozzle_size') * 0.5",
|
||||
"maximum_value_warning": "extruderValue(adhesion_extruder_nr, 'machine_nozzle_size') * 3",
|
||||
"enabled": "resolveOrValue('adhesion_type') == 'raft'",
|
||||
|
|
@ -3442,7 +3601,7 @@
|
|||
"unit": "mm",
|
||||
"type": "float",
|
||||
"default_value": 0.8,
|
||||
"minimum_value": "0.0001",
|
||||
"minimum_value": "0.001",
|
||||
"value": "extruderValue(adhesion_extruder_nr, 'machine_nozzle_size') * 2",
|
||||
"minimum_value_warning": "extruderValue(adhesion_extruder_nr, 'machine_nozzle_size') * 0.5",
|
||||
"maximum_value_warning": "extruderValue(adhesion_extruder_nr, 'machine_nozzle_size') * 3",
|
||||
|
|
@ -3459,7 +3618,7 @@
|
|||
"type": "float",
|
||||
"default_value": 1.6,
|
||||
"value": "raft_base_line_width * 2",
|
||||
"minimum_value": "0.0001",
|
||||
"minimum_value": "0",
|
||||
"minimum_value_warning": "extruderValue(adhesion_extruder_nr, 'raft_base_line_width')",
|
||||
"maximum_value_warning": "100",
|
||||
"enabled": "resolveOrValue('adhesion_type') == 'raft'",
|
||||
|
|
@ -3780,10 +3939,10 @@
|
|||
"unit": "mm",
|
||||
"type": "float",
|
||||
"default_value": 2,
|
||||
"value": "max(2 * min(extruderValues('prime_tower_line_width')), 0.5 * (resolveOrValue('prime_tower_size') - math.sqrt(max(0, resolveOrValue('prime_tower_size') ** 2 - max(extruderValues('prime_tower_min_volume')) / resolveOrValue('layer_height')))))",
|
||||
"value": "round(max(2 * min(extruderValues('prime_tower_line_width')), 0.5 * (resolveOrValue('prime_tower_size') - math.sqrt(max(0, resolveOrValue('prime_tower_size') ** 2 - max(extruderValues('prime_tower_min_volume')) / resolveOrValue('layer_height'))))), 3)",
|
||||
"resolve": "max(extruderValues('prime_tower_wall_thickness'))",
|
||||
"minimum_value": "0.001",
|
||||
"minimum_value_warning": "2 * min(extruderValues('prime_tower_line_width'))",
|
||||
"minimum_value_warning": "2 * min(extruderValues('prime_tower_line_width')) - 0.0001",
|
||||
"maximum_value_warning": "resolveOrValue('prime_tower_size') / 2",
|
||||
"enabled": "resolveOrValue('prime_tower_enable')",
|
||||
"settable_per_mesh": false,
|
||||
|
|
@ -3816,8 +3975,6 @@
|
|||
"default_value": 200,
|
||||
"minimum_value_warning": "-1000",
|
||||
"maximum_value_warning": "1000",
|
||||
"maximum_value": "machine_depth - resolveOrValue('prime_tower_size')",
|
||||
"minimum_value": "0",
|
||||
"maximum_value": "machine_depth / 2 - resolveOrValue('prime_tower_size') if machine_center_is_zero else machine_depth - resolveOrValue('prime_tower_size')",
|
||||
"minimum_value": "machine_depth / -2 if machine_center_is_zero else 0",
|
||||
"settable_per_mesh": false,
|
||||
|
|
@ -4009,6 +4166,40 @@
|
|||
"settable_per_meshgroup": false,
|
||||
"settable_globally": false
|
||||
},
|
||||
"mold_enabled":
|
||||
{
|
||||
"label": "Mold",
|
||||
"description": "Print models as a mold, which can be cast in order to get a model which resembles the models on the build plate.",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"settable_per_mesh": true
|
||||
},
|
||||
"mold_width":
|
||||
{
|
||||
"label": "Minimal Mold Width",
|
||||
"description": "The minimal distance between the ouside of the mold and the outside of the model.",
|
||||
"unit": "mm",
|
||||
"type": "float",
|
||||
"minimum_value_warning": "wall_line_width_0 * 2",
|
||||
"maximum_value_warning": "100",
|
||||
"default_value": 5,
|
||||
"settable_per_mesh": true,
|
||||
"enabled": "mold_enabled"
|
||||
},
|
||||
"mold_angle":
|
||||
{
|
||||
"label": "Mold Angle",
|
||||
"description": "The angle of overhang of the outer walls created for the mold. 0° will make the outer shell of the mold vertical, while 90° will make the outside of the model follow the contour of the model.",
|
||||
"unit": "°",
|
||||
"type": "float",
|
||||
"minimum_value": "-89",
|
||||
"minimum_value_warning": "0",
|
||||
"maximum_value_warning": "support_angle",
|
||||
"maximum_value": "90",
|
||||
"default_value": 40,
|
||||
"settable_per_mesh": true,
|
||||
"enabled": "mold_enabled"
|
||||
},
|
||||
"infill_mesh_order":
|
||||
{
|
||||
"label": "Infill Mesh Order",
|
||||
|
|
@ -4034,6 +4225,18 @@
|
|||
"settable_per_meshgroup": false,
|
||||
"settable_globally": false
|
||||
},
|
||||
"support_mesh_drop_down":
|
||||
{
|
||||
"label": "Drop Down Support Mesh",
|
||||
"description": "Make support everywhere below the support mesh, so that there's no overhang in the support mesh.",
|
||||
"type": "bool",
|
||||
"default_value": true,
|
||||
"enabled": "support_mesh",
|
||||
"settable_per_mesh": true,
|
||||
"settable_per_extruder": false,
|
||||
"settable_per_meshgroup": false,
|
||||
"settable_globally": false
|
||||
},
|
||||
"anti_overhang_mesh":
|
||||
{
|
||||
"label": "Anti Overhang Mesh",
|
||||
|
|
@ -4065,7 +4268,8 @@
|
|||
"description": "Spiralize smooths out the Z move of the outer edge. This will create a steady Z increase over the whole print. This feature turns a solid model into a single walled print with a solid bottom. This feature used to be called Joris in older versions.",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"settable_per_mesh": true
|
||||
"settable_per_mesh": false,
|
||||
"settable_per_extruder": false
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
|
|||
28
resources/definitions/folgertech_FT-5.def.json
Normal file
28
resources/definitions/folgertech_FT-5.def.json
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
{
|
||||
"version": 2,
|
||||
"name": "Folger Tech FT-5",
|
||||
"inherits": "fdmprinter",
|
||||
"metadata": {
|
||||
"visible": true,
|
||||
"author": "Jaime van Kessel & Paul Bussiere",
|
||||
"manufacturer": "Folger Tech",
|
||||
"category": "Other",
|
||||
"file_formats": "text/x-gcode",
|
||||
"platform": "FT-5_build_plate.stl"
|
||||
},
|
||||
"overrides": {
|
||||
"machine_heated_bed": { "default_value": true },
|
||||
"machine_width": { "default_value": 300 },
|
||||
"machine_height": { "default_value": 400 },
|
||||
"machine_depth": { "default_value": 300 },
|
||||
"material_diameter": { "default_value": 1.75 },
|
||||
"gantry_height": { "default_value": 55 },
|
||||
|
||||
"machine_start_gcode": {
|
||||
"default_value": "G21 ;metric values\nG90 ;absolute positioning\nM82 ;set extruder to absolute mode\nM107 ;start with the fan off\nG28 X0 Y0 ;move X/Y to min endstops\nG28 Z0 ;move Z to min endstops\nG1 Z15.0 F9000 ;move the platform down 15mm\nG92 E0 ;zero the extruded length\nG1 F200 E3 ;extrude 3mm of feed stock\nG92 E0 ;zero the extruded length again\nG1 F9000\n;Put printing message on LCD screen\nM117 Printing..."
|
||||
},
|
||||
"machine_end_gcode": {
|
||||
"default_value": "M104 S0 ;extruder heater off\nM140 S0 ;heated bed heater off (if you have it)\nG91 ;relative positioning\nG1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure\nG1 Z+0.5 E-5 X-20 Y-20 F9000 ;move Z up a bit and retract filament even more\nG28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way\nM84 ;steppers off\nG90 ;absolute positioning"
|
||||
}
|
||||
}
|
||||
}
|
||||
50
resources/definitions/helloBEEprusa.def.json
Normal file
50
resources/definitions/helloBEEprusa.def.json
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
{
|
||||
"id": "BEEVERYCREATIVE-helloBEEprusa",
|
||||
"version": 2,
|
||||
"name": "Hello BEE Prusa",
|
||||
"inherits": "fdmprinter",
|
||||
"metadata": {
|
||||
"visible": true,
|
||||
"author": "BEEVERYCREATIVE",
|
||||
"manufacturer": "BEEVERYCREATIVE",
|
||||
"category": "Other",
|
||||
"platform": "BEEVERYCREATIVE-helloBEEprusa.stl",
|
||||
"platform_offset": [-226, -75, -196],
|
||||
"file_formats": "text/x-gcode"
|
||||
},
|
||||
|
||||
"overrides": {
|
||||
"machine_name": { "default_value": "hello BEE prusa" },
|
||||
"machine_start_gcode": { "default_value": "; -- START GCODE --\nG21 ;set units to millimetres\nG90 ;set to absolute positioning\nM107 ;set fan speed to zero (turned off)\nG28 X0 Y0 ;move to the X/Y origin (Home)\nG28 Z0 ;move to the Z origin (Home)\nG92 E0 ;zero the extruded length\nG1 F3600 ;set feedrate to 60 mm/sec\n; -- end of START GCODE --" },
|
||||
"machine_end_gcode": { "default_value": "; -- END GCODE --\nM104 S0 ;set extruder temperature to zero (turned off)\nM140 S0 ;set bed temperature to zero (turned off)\nG28 X0 Y0 ;move to the X/Y origin (Home)\nM84 ;turn off steppers\n; -- end of END GCODE --" },
|
||||
"machine_width": { "default_value": 185 },
|
||||
"machine_depth": { "default_value": 200 },
|
||||
"machine_height": { "default_value": 190 },
|
||||
"machine_heated_bed": { "default_value": true },
|
||||
"machine_center_is_zero": { "default_value": false },
|
||||
"material_print_temperature": { "default_value": 220 },
|
||||
"material_bed_temperature": { "default_value": 60 },
|
||||
"material_diameter": { "default_value": 1.75 },
|
||||
"layer_height": { "default_value": 0.2 },
|
||||
"layer_height_0": { "default_value": 0.2 },
|
||||
"wall_line_count": { "default_value": 3 },
|
||||
"wall_thickness": { "default_value": 1.2 },
|
||||
"top_bottom_thickness": { "default_value": 1.2 },
|
||||
"infill_sparse_density": { "default_value": 20 },
|
||||
"infill_overlap": { "default_value": 15 },
|
||||
"speed_print": { "default_value": 60 },
|
||||
"speed_travel": { "default_value": 160 },
|
||||
"speed_layer_0": { "default_value": 30 },
|
||||
"speed_wall_x": { "default_value": 35 },
|
||||
"speed_wall_0": { "default_value": 30 },
|
||||
"speed_infill": { "default_value": 60 },
|
||||
"speed_topbottom": { "default_value": 20 },
|
||||
"skirt_brim_speed": { "default_value": 35 },
|
||||
"skirt_line_count": { "default_value": 4 },
|
||||
"skirt_brim_minimal_length": { "default_value": 30 },
|
||||
"skirt_gap": { "default_value": 6 },
|
||||
"cool_fan_full_at_height": { "default_value": 0.4 },
|
||||
"retraction_speed": { "default_value": 50.0},
|
||||
"retraction_amount": { "default_value": 5.2}
|
||||
}
|
||||
}
|
||||
41
resources/definitions/imade3d_jellybox.def.json
Normal file
41
resources/definitions/imade3d_jellybox.def.json
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
{
|
||||
"id": "imade3d_jellybox",
|
||||
"version": 2,
|
||||
"name": "IMADE3D JellyBOX",
|
||||
"inherits": "fdmprinter",
|
||||
"metadata": {
|
||||
"visible": true,
|
||||
"author": "IMADE3D",
|
||||
"manufacturer": "IMADE3D",
|
||||
"category": "Other",
|
||||
"platform": "imade3d_jellybox_platform.stl",
|
||||
"platform_offset": [ 0, -0.3, 0],
|
||||
"file_formats": "text/x-gcode",
|
||||
"preferred_variant": "*0.4*",
|
||||
"preferred_material": "*generic_pla*",
|
||||
"preferred_quality": "*fast*",
|
||||
"has_materials": true,
|
||||
"has_variants": true,
|
||||
"has_machine_materials": true,
|
||||
"has_machine_quality": true
|
||||
},
|
||||
|
||||
"overrides": {
|
||||
"machine_head_with_fans_polygon": { "default_value": [[ 0, 0 ],[ 0, 0 ],[ 0, 0 ],[ 0, 0 ]]},
|
||||
"machine_name": { "default_value": "IMADE3D JellyBOX" },
|
||||
"machine_width": { "default_value": 170 },
|
||||
"machine_height": { "default_value": 145 },
|
||||
"machine_depth": { "default_value": 160 },
|
||||
"machine_nozzle_size": { "default_value": 0.4 },
|
||||
"material_diameter": { "default_value": 1.75 },
|
||||
"machine_heated_bed": { "default_value": true },
|
||||
"machine_center_is_zero": { "default_value": false },
|
||||
"machine_gcode_flavor": { "default_value": "RepRap (Marlin/Sprinter)" },
|
||||
"machine_start_gcode": {
|
||||
"default_value": ";---------------------------------------\n; ; ; Jellybox Start Script Begin ; ; ;\n;_______________________________________\n; M92 E140 ;optionally adjust steps per mm for your filament\n\n; Print Settings Summary\n; (leave these alone: this is only a list of the slicing settings)\n; (overwriting these values will NOT change your printer's behavior)\n; sliced for : {machine_name}\n; nozzle diameter : {machine_nozzle_size}\n; filament diameter : {material_diameter}\n; layer height : {layer_height}\n; 1st layer height : {layer_height_0}\n; line width : {line_width}\n; outer wall wipe dist. : {wall_0_wipe_dist}\n; infill line width : {infill_line_width}\n; wall thickness : {wall_thickness}\n; top thickness : {top_thickness}\n; bottom thickness : {bottom_thickness}\n; infill density : {infill_sparse_density}\n; infill pattern : {infill_pattern}\n; print temperature : {material_print_temperature}\n; 1st layer print temp. : {material_print_temperature_layer_0}\n; heated bed temperature : {material_bed_temperature}\n; 1st layer bed temp. : {material_bed_temperature_layer_0}\n; regular fan speed : {cool_fan_speed_min}\n; max fan speed : {cool_fan_speed_max}\n; retraction amount : {retraction_amount}\n; retr. retract speed : {retraction_retract_speed}\n; retr. prime speed : {retraction_prime_speed}\n; build plate adhesion : {adhesion_type}\n; support ? {support_enable}\n; spiralized ? {magic_spiralize}\n\nM117 Preparing ;write Preparing\nM140 S{material_bed_temperature_layer_0} ;set bed temperature and move on\nM109 S{material_print_temperature} ; wait for the extruder to reach desired temperature\nM206 X10.0 Y0.0 ;set x homing offset for default bed leveling\nG21 ;metric values\nG90 ;absolute positioning\nM107 ;start with the fan off\nM82 ;set extruder to absolute mode\nG28 ;home all axes\nM203 Z4 ;slow Z speed down for greater accuracy when probing\nG29 ;auto bed leveling procedure\nM203 Z7 ;pick up z speed again for printing\nM190 S{material_bed_temperature_layer_0} ;wait for the bed to reach desired temperature\nM109 S{material_print_temperature_layer_0} ;wait for the extruder to reach desired temperature\nG92 E0 ;reset the extruder position\nG1 F1500 E15 ;extrude 15mm of feed stock\nG92 E0 ;reset the extruder position again\nM117 Print starting ;write Print starting\n;---------------------------------------------\n; ; ; Jellybox Printer Start Script End ; ; ;\n;_____________________________________________\n"
|
||||
},
|
||||
"machine_end_gcode": {
|
||||
"default_value": "\n;---------------------------------\n;;; Jellybox End Script Begin ;;;\n;_________________________________\nM117 Finishing Up ;write Finishing Up\n\nM104 S0 ;extruder heater off\nM140 S0 ;bed heater off (if you have it)\nG91 ;relative positioning\nG1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure\nG1 Z+0.5 E-5 X-20 Y-20 F9000 ;move Z up a bit and retract filament even more\nG90 ;absolute positioning\nG28 X ;home x, so the head is out of the way\nG1 Y100 ;move Y forward, so the print is more accessible\nM84 ;steppers off\n\nM117 Print finished ;write Print finished\n;---------------------------------------\n;;; Jellybox End Script End ;;;\n;_______________________________________"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
{
|
||||
"id": "jellybox",
|
||||
"version": 2,
|
||||
"name": "JellyBOX",
|
||||
"inherits": "fdmprinter",
|
||||
"metadata": {
|
||||
"visible": true,
|
||||
"author": "IMADE3D",
|
||||
"manufacturer": "IMADE3D",
|
||||
"category": "Other",
|
||||
"platform": "jellybox_platform.stl",
|
||||
"platform_offset": [ 0, -0.3, 0],
|
||||
"file_formats": "text/x-gcode",
|
||||
"has_materials": true,
|
||||
"has_machine_materials": true
|
||||
},
|
||||
|
||||
"overrides": {
|
||||
"machine_name": { "default_value": "IMADE3D JellyBOX" },
|
||||
"machine_width": { "default_value": 170 },
|
||||
"machine_height": { "default_value": 145 },
|
||||
"machine_depth": { "default_value": 160 },
|
||||
"machine_nozzle_size": { "default_value": 0.4 },
|
||||
"material_diameter": { "default_value": 1.75 },
|
||||
"machine_heated_bed": { "default_value": true },
|
||||
"machine_center_is_zero": { "default_value": false },
|
||||
"machine_gcode_flavor": { "default_value": "RepRap (Marlin/Sprinter)" },
|
||||
"machine_start_gcode": {
|
||||
"default_value": ";---------------------------------------\n; ; ; Jellybox Start Script Begin ; ; ;\n;_______________________________________\n; M92 E140 ;optionally adjust steps per mm for your filament\n\n; Print Settings Summary\n; (overwriting these values will NOT change your printer's behavior)\n; sliced for: {machine_name}\n; nozzle diameter: {machine_nozzle_size}\n; filament diameter: {material_diameter}\n; layer height: {layer_height}\n; 1st layer height: {layer_height_0}\n; line width: {line_width}\n; wall thickness: {wall_thickness}\n; infill density: {infill_sparse_density}\n; infill pattern: {infill_pattern}\n; print temperature: {material_print_temperature}\n; heated bed temperature: {material_bed_temperature}\n; regular fan speed: {cool_fan_speed_min}\n; max fan speed: {cool_fan_speed_max}\n; support? {support_enable}\n; spiralized? {magic_spiralize}\n\nM117 Preparing ;write Preparing\nM140 S{material_bed_temperature} ;set bed temperature and move on\nM104 S{material_print_temperature} ;set extruder temperature and move on\nM206 X10.0 Y0.0 ;set x homing offset for default bed leveling\nG21 ;metric values\nG90 ;absolute positioning\nM107 ;start with the fan off\nM82 ;set extruder to absolute mode\nG28 ;home all axes\nM203 Z5 ;slow Z speed down for greater accuracy when probing\nG29 ;auto bed leveling procedure\nM203 Z7 ;pick up z speed again for printing\nM190 S{material_bed_temperature} ;wait for the bed to reach desired temperature\nM109 S{material_print_temperature} ;wait for the extruder to reach desired temperature\nG92 E0 ;reset the extruder position\nG1 F200 E5 ;extrude 5mm of feed stock\nG92 E0 ;reset the extruder position again\nM117 Print starting ;write Print starting\n;---------------------------------------------\n; ; ; Jellybox Printer Start Script End ; ; ;\n;_____________________________________________"
|
||||
},
|
||||
"machine_end_gcode": {
|
||||
"default_value": "\n;---------------------------------\n;;; Jellybox End Script Begin ;;;\n;_________________________________\nM117 Finishing Up ;write Finishing Up\n\nM104 S0 ;extruder heater off\nM140 S0 ;bed heater off (if you have it)\nG91 ;relative positioning\nG1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure\nG1 Z+0.5 E-5 X-20 Y-20 F9000 ;move Z up a bit and retract filament even more\nG90 ;absolute positioning\nG28 X ;home x, so the head is out of the way\nG1 Y100 ;move Y forward, so the print is more accessible\nM84 ;steppers off\n\nM117 Print finished ;write Print finished\n;---------------------------------------\n;;; Jellybox End Script End ;;;\n;_______________________________________"
|
||||
}
|
||||
}
|
||||
}
|
||||
70
resources/definitions/makeR_pegasus.def.json
Normal file
70
resources/definitions/makeR_pegasus.def.json
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
{
|
||||
"id": "makeR_pegasus",
|
||||
"version": 2,
|
||||
"name": "makeR Pegasus",
|
||||
"inherits": "fdmprinter",
|
||||
"metadata": {
|
||||
"visible": true,
|
||||
"author": "makeR",
|
||||
"manufacturer": "makeR",
|
||||
"category": "Other",
|
||||
"file_formats": "text/x-gcode",
|
||||
"icon": "icon_ultimaker2",
|
||||
"platform": "makeR_pegasus_platform.stl",
|
||||
"platform_offset": [-200,-10,200]
|
||||
},
|
||||
|
||||
"overrides": {
|
||||
"machine_name": { "default_value": " makeR Pegasus" },
|
||||
"machine_heated_bed": {
|
||||
"default_value": true
|
||||
},
|
||||
"machine_width": {
|
||||
"default_value": 400
|
||||
},
|
||||
"machine_height": {
|
||||
"default_value": 400
|
||||
},
|
||||
"machine_depth": {
|
||||
"default_value": 400
|
||||
},
|
||||
"machine_center_is_zero": {
|
||||
"default_value": false
|
||||
},
|
||||
"machine_nozzle_size": {
|
||||
"default_value": 0.4
|
||||
},
|
||||
"material_diameter": {
|
||||
"default_value": 2.85
|
||||
},
|
||||
"machine_nozzle_heat_up_speed": {
|
||||
"default_value": 2
|
||||
},
|
||||
"machine_nozzle_cool_down_speed": {
|
||||
"default_value": 2
|
||||
},
|
||||
"machine_head_polygon": {
|
||||
"default_value": [
|
||||
[-75, -18],
|
||||
[-75, 35],
|
||||
[18, 35],
|
||||
[18, -18]
|
||||
]
|
||||
},
|
||||
"gantry_height": {
|
||||
"default_value": -25
|
||||
},
|
||||
"machine_platform_offset":{
|
||||
"default_value":-25
|
||||
},
|
||||
"machine_gcode_flavor": {
|
||||
"default_value": "RepRap (Marlin/Sprinter)"
|
||||
},
|
||||
"machine_start_gcode": {
|
||||
"default_value": "G1 Z15;\nG28;Home\nG29;Auto Level\nG1 Z5 F5000;Move the platform down 15mm"
|
||||
},
|
||||
"machine_end_gcode": {
|
||||
"default_value": "M104 S0;Turn off temperature\nG28 X0; Home X\nM84; Disable Motors"
|
||||
}
|
||||
}
|
||||
}
|
||||
67
resources/definitions/makeR_prusa_tairona_i3.def.json
Normal file
67
resources/definitions/makeR_prusa_tairona_i3.def.json
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
{
|
||||
"id": "makeR_prusa_tairona_i3",
|
||||
"version": 2,
|
||||
"name": "makeR Prusa Tairona i3",
|
||||
"inherits": "fdmprinter",
|
||||
"metadata": {
|
||||
"visible": true,
|
||||
"author": "makeR",
|
||||
"manufacturer": "makeR",
|
||||
"category": "Other",
|
||||
"file_formats": "text/x-gcode",
|
||||
"icon": "icon_ultimaker2",
|
||||
"platform": "makeR_prusa_tairona_i3_platform.stl",
|
||||
"platform_offset": [-2,0,0]
|
||||
},
|
||||
|
||||
"overrides": {
|
||||
"machine_name": { "default_value": "makeR Prusa Tairona I3" },
|
||||
"machine_heated_bed": {
|
||||
"default_value": true
|
||||
},
|
||||
"machine_width": {
|
||||
"default_value": 200
|
||||
},
|
||||
"machine_height": {
|
||||
"default_value": 200
|
||||
},
|
||||
"machine_depth": {
|
||||
"default_value": 200
|
||||
},
|
||||
"machine_center_is_zero": {
|
||||
"default_value": false
|
||||
},
|
||||
"machine_nozzle_size": {
|
||||
"default_value": 0.4
|
||||
},
|
||||
"material_diameter": {
|
||||
"default_value": 1.75
|
||||
},
|
||||
"machine_nozzle_heat_up_speed": {
|
||||
"default_value": 2
|
||||
},
|
||||
"machine_nozzle_cool_down_speed": {
|
||||
"default_value": 2
|
||||
},
|
||||
"machine_head_polygon": {
|
||||
"default_value": [
|
||||
[-75, -18],
|
||||
[-75, 35],
|
||||
[18, 35],
|
||||
[18, -18]
|
||||
]
|
||||
},
|
||||
"gantry_height": {
|
||||
"default_value": 55
|
||||
},
|
||||
"machine_gcode_flavor": {
|
||||
"default_value": "RepRap (Marlin/Sprinter)"
|
||||
},
|
||||
"machine_start_gcode": {
|
||||
"default_value": "G1 Z15;\nG28;Home\nG29;Auto Level\nG1 Z5 F5000;Move the platform down 15mm"
|
||||
},
|
||||
"machine_end_gcode": {
|
||||
"default_value": "M104 S0;Turn off temperature\nG28 X0; Home X\nM84; Disable Motors"
|
||||
}
|
||||
}
|
||||
}
|
||||
129
resources/definitions/makeit_pro_l.def.json
Normal file
129
resources/definitions/makeit_pro_l.def.json
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
{
|
||||
"id": "makeit_pro_l",
|
||||
"version": 2,
|
||||
"name": "MAKEiT Pro-L",
|
||||
"inherits": "fdmprinter",
|
||||
"metadata": {
|
||||
"visible": true,
|
||||
"author": "NA",
|
||||
"manufacturer": "NA",
|
||||
"category": "Other",
|
||||
"file_formats": "text/x-gcode",
|
||||
"has_materials": false,
|
||||
"supported_actions": [ "MachineSettingsAction", "UpgradeFirmware" ],
|
||||
"machine_extruder_trains":
|
||||
{
|
||||
"0": "makeit_l_dual_1st",
|
||||
"1": "makeit_l_dual_2nd"
|
||||
}
|
||||
},
|
||||
|
||||
"overrides": {
|
||||
"machine_name": { "default_value": "MAKEiT Pro-L" },
|
||||
"machine_width": {
|
||||
"default_value": 305
|
||||
},
|
||||
"machine_height": {
|
||||
"default_value": 330
|
||||
},
|
||||
"machine_depth": {
|
||||
"default_value": 254
|
||||
},
|
||||
"machine_center_is_zero": {
|
||||
"default_value": false
|
||||
},
|
||||
"machine_nozzle_size": {
|
||||
"default_value": 0.4
|
||||
},
|
||||
"machine_nozzle_heat_up_speed": {
|
||||
"default_value": 2
|
||||
},
|
||||
"machine_nozzle_cool_down_speed": {
|
||||
"default_value": 2
|
||||
},
|
||||
"machine_head_with_fans_polygon":
|
||||
{
|
||||
"default_value": [
|
||||
[ -305, 28 ],
|
||||
[ -305, -28 ],
|
||||
[ 305, 28 ],
|
||||
[ 305, -28 ]
|
||||
]
|
||||
},
|
||||
"gantry_height": {
|
||||
"default_value": 330
|
||||
},
|
||||
"machine_use_extruder_offset_to_offset_coords": {
|
||||
"default_value": true
|
||||
},
|
||||
"machine_gcode_flavor": {
|
||||
"default_value": "RepRap (Marlin/Sprinter)"
|
||||
},
|
||||
"machine_start_gcode": {
|
||||
"default_value": "G21 ;metric values\nG90 ;absolute positioning\nM82 ;set extruder to absolute mode\nG92 E0 ;zero the extruded length\nG28 ;home\nG1 F200 E30 ;extrude 30 mm of feed stock\nG92 E0 ;zero the extruded length\nG1 E-5 ;retract 5 mm\nG28 SC ;Do homeing, clean nozzles and let printer to know that printing started\nG92 X-6 ;Sets Curas checker board to match printers heated bed coordinates\nG1 F{speed_travel}\nM117 Printing..."
|
||||
},
|
||||
"machine_end_gcode": {
|
||||
"default_value": "M104 T0 S0 ;1st extruder heater off\nM104 T1 S0 ;2nd extruder heater off\nM140 S0 ;heated bed heater off (if you have it)\nG91 ;relative positioning\nG1 E-5 F9000 ;retract the filament a bit before lifting the nozzle, to release some of the pressure\nG1 Z+5 X+20 Y+20 F9000 ;move Z up a bit\nM117 MAKEiT Pro@Done\nG28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way\nM84 ;steppers off\nG90 ;absolute positioning\nM81"
|
||||
},
|
||||
"machine_extruder_count": {
|
||||
"default_value": 2
|
||||
},
|
||||
"print_sequence": {
|
||||
"enabled": true
|
||||
},
|
||||
"prime_tower_position_x": {
|
||||
"default_value": 185
|
||||
},
|
||||
"prime_tower_position_y": {
|
||||
"default_value": 160
|
||||
},
|
||||
"material_diameter": {
|
||||
"default_value": 1.75
|
||||
},
|
||||
"layer_height": {
|
||||
"default_value": 0.2
|
||||
},
|
||||
"retraction_speed": {
|
||||
"default_value": 180
|
||||
},
|
||||
"infill_sparse_density": {
|
||||
"default_value": 20
|
||||
},
|
||||
"retraction_amount": {
|
||||
"default_value": 6
|
||||
},
|
||||
"retraction_min_travel": {
|
||||
"default_value": 1.5
|
||||
},
|
||||
"speed_travel": {
|
||||
"default_value": 150
|
||||
},
|
||||
"speed_print": {
|
||||
"default_value": 60
|
||||
},
|
||||
"wall_thickness": {
|
||||
"default_value": 1.2
|
||||
},
|
||||
"bottom_thickness": {
|
||||
"default_value": 0.2
|
||||
},
|
||||
"speed_layer_0": {
|
||||
"default_value": 20
|
||||
},
|
||||
"speed_print_layer_0": {
|
||||
"default_value": 20
|
||||
},
|
||||
"cool_min_layer_time_fan_speed_max": {
|
||||
"default_value": 5
|
||||
},
|
||||
"adhesion_type": {
|
||||
"default_value": "skirt"
|
||||
},
|
||||
"machine_heated_bed": {
|
||||
"default_value": true
|
||||
},
|
||||
"machine_heat_zone_length": {
|
||||
"default_value": 20
|
||||
}
|
||||
}
|
||||
}
|
||||
126
resources/definitions/makeit_pro_m.def.json
Normal file
126
resources/definitions/makeit_pro_m.def.json
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
{
|
||||
"id": "makeit_pro_m",
|
||||
"version": 2,
|
||||
"name": "MAKEiT Pro-M",
|
||||
"inherits": "fdmprinter",
|
||||
"metadata": {
|
||||
"visible": true,
|
||||
"author": "NA",
|
||||
"manufacturer": "NA",
|
||||
"category": "Other",
|
||||
"file_formats": "text/x-gcode",
|
||||
"has_materials": false,
|
||||
"supported_actions": [ "MachineSettingsAction", "UpgradeFirmware" ],
|
||||
"machine_extruder_trains":
|
||||
{
|
||||
"0": "makeit_dual_1st",
|
||||
"1": "makeit_dual_2nd"
|
||||
}
|
||||
},
|
||||
|
||||
"overrides": {
|
||||
"machine_name": { "default_value": "MAKEiT Pro-M" },
|
||||
"machine_width": {
|
||||
"default_value": 200
|
||||
},
|
||||
"machine_height": {
|
||||
"default_value": 200
|
||||
},
|
||||
"machine_depth": {
|
||||
"default_value": 240
|
||||
},
|
||||
"machine_center_is_zero": {
|
||||
"default_value": false
|
||||
},
|
||||
"machine_nozzle_size": {
|
||||
"default_value": 0.4
|
||||
},
|
||||
"machine_nozzle_heat_up_speed": {
|
||||
"default_value": 2
|
||||
},
|
||||
"machine_nozzle_cool_down_speed": {
|
||||
"default_value": 2
|
||||
},
|
||||
"machine_head_with_fans_polygon":
|
||||
{
|
||||
"default_value": [
|
||||
[ -200, 240 ],
|
||||
[ -200, -32 ],
|
||||
[ 200, 240 ],
|
||||
[ 200, -32 ]
|
||||
]
|
||||
},
|
||||
"gantry_height": {
|
||||
"default_value": 200
|
||||
},
|
||||
"machine_use_extruder_offset_to_offset_coords": {
|
||||
"default_value": true
|
||||
},
|
||||
"machine_gcode_flavor": {
|
||||
"default_value": "RepRap (Marlin/Sprinter)"
|
||||
},
|
||||
"machine_start_gcode": {
|
||||
"default_value": "G21 ;metric values\nG90 ;absolute positioning\nM82 ;set extruder to absolute mode\nG92 E0 ;zero the extruded length\nG28 ;home\nG1 F200 E30 ;extrude 30 mm of feed stock\nG92 E0 ;zero the extruded length\nG1 E-5 ;retract 5 mm\nG28 SC ;Do homeing, clean nozzles and let printer to know that printing started\nG92 X-6 ;Sets Curas checker board to match printers heated bed coordinates\nG1 F{speed_travel}\nM117 Printing..."
|
||||
},
|
||||
"machine_end_gcode": {
|
||||
"default_value": "M104 T0 S0 ;1st extruder heater off\nM104 T1 S0 ;2nd extruder heater off\nM140 S0 ;heated bed heater off (if you have it)\nG91 ;relative positioning\nG1 E-5 F9000 ;retract the filament a bit before lifting the nozzle, to release some of the pressure\nG1 Z+5 X+20 Y+20 F9000 ;move Z up a bit\nM117 MAKEiT Pro@Done\nG28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way\nM84 ;steppers off\nG90 ;absolute positioning\nM81"
|
||||
},
|
||||
"machine_extruder_count": {
|
||||
"default_value": 2
|
||||
},
|
||||
"print_sequence": {
|
||||
"enabled": false
|
||||
},
|
||||
"prime_tower_position_x": {
|
||||
"default_value": 185
|
||||
},
|
||||
"prime_tower_position_y": {
|
||||
"default_value": 160
|
||||
},
|
||||
"material_diameter": {
|
||||
"default_value": 1.75
|
||||
},
|
||||
"layer_height": {
|
||||
"default_value": 0.2
|
||||
},
|
||||
"retraction_speed": {
|
||||
"default_value": 180
|
||||
},
|
||||
"infill_sparse_density": {
|
||||
"default_value": 20
|
||||
},
|
||||
"retraction_amount": {
|
||||
"default_value": 6
|
||||
},
|
||||
"retraction_min_travel": {
|
||||
"default_value": 1.5
|
||||
},
|
||||
"speed_travel": {
|
||||
"default_value": 150
|
||||
},
|
||||
"speed_print": {
|
||||
"default_value": 60
|
||||
},
|
||||
"wall_thickness": {
|
||||
"default_value": 1.2
|
||||
},
|
||||
"bottom_thickness": {
|
||||
"default_value": 0.2
|
||||
},
|
||||
"speed_layer_0": {
|
||||
"default_value": 20
|
||||
},
|
||||
"speed_print_layer_0": {
|
||||
"default_value": 20
|
||||
},
|
||||
"cool_min_layer_time_fan_speed_max": {
|
||||
"default_value": 5
|
||||
},
|
||||
"adhesion_type": {
|
||||
"default_value": "skirt"
|
||||
},
|
||||
"machine_heated_bed": {
|
||||
"default_value": true
|
||||
}
|
||||
}
|
||||
}
|
||||
162
resources/definitions/peopoly_moai.def.json
Normal file
162
resources/definitions/peopoly_moai.def.json
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
{
|
||||
"id": "peopoly_moai",
|
||||
"version": 2,
|
||||
"name": "Peopoly Moai",
|
||||
"inherits": "fdmprinter",
|
||||
"metadata": {
|
||||
"visible": true,
|
||||
"author": "fieldOfView",
|
||||
"manufacturer": "Peopoly",
|
||||
"category": "Other",
|
||||
"file_formats": "text/x-gcode",
|
||||
"has_machine_quality": true,
|
||||
"has_materials": false
|
||||
},
|
||||
|
||||
"overrides": {
|
||||
"machine_name": {
|
||||
"default_value": "Moai"
|
||||
},
|
||||
"machine_width": {
|
||||
"default_value": 130
|
||||
},
|
||||
"machine_height": {
|
||||
"default_value": 180
|
||||
},
|
||||
"machine_depth": {
|
||||
"default_value": 130
|
||||
},
|
||||
"machine_nozzle_size": {
|
||||
"default_value": 0.067
|
||||
},
|
||||
"machine_head_with_fans_polygon":
|
||||
{
|
||||
"default_value": [
|
||||
[ -20, 10 ],
|
||||
[ -20, -10 ],
|
||||
[ 10, 10 ],
|
||||
[ 10, -10 ]
|
||||
]
|
||||
},
|
||||
"machine_gcode_flavor": {
|
||||
"default_value": "RepRap (Marlin/Sprinter)"
|
||||
},
|
||||
"machine_start_gcode": {
|
||||
"default_value": "G28 ;Home"
|
||||
},
|
||||
"machine_end_gcode": {
|
||||
"default_value": "M104 S0\nM140 S0\nG28 X0 Y0\nM84"
|
||||
},
|
||||
|
||||
"line_width": {
|
||||
"minimum_value_warning": "machine_nozzle_size"
|
||||
},
|
||||
"wall_line_width": {
|
||||
"minimum_value_warning": "machine_nozzle_size"
|
||||
},
|
||||
"wall_line_width_x": {
|
||||
"minimum_value_warning": "machine_nozzle_size"
|
||||
},
|
||||
"skin_line_width": {
|
||||
"minimum_value_warning": "machine_nozzle_size"
|
||||
},
|
||||
"infill_line_width": {
|
||||
"minimum_value_warning": "machine_nozzle_size"
|
||||
},
|
||||
"skirt_brim_line_width": {
|
||||
"minimum_value_warning": "machine_nozzle_size"
|
||||
},
|
||||
"layer_height": {
|
||||
"maximum_value_warning": "0.5",
|
||||
"minimum_value_warning": "0.02"
|
||||
},
|
||||
"layer_height_0": {
|
||||
"maximum_value_warning": "0.5",
|
||||
"minimum_value_warning": "0.02",
|
||||
"value": "0.1"
|
||||
},
|
||||
"top_bottom_thickness": {
|
||||
"minimum_value_warning": "0.1"
|
||||
},
|
||||
"infill_sparse_thickness": {
|
||||
"maximum_value_warning": "0.5"
|
||||
},
|
||||
"speed_print": {
|
||||
"maximum_value_warning": "300"
|
||||
},
|
||||
"speed_infill": {
|
||||
"maximum_value_warning": "300"
|
||||
},
|
||||
"speed_wall": {
|
||||
"maximum_value_warning": "300",
|
||||
"value": "speed_print"
|
||||
},
|
||||
"speed_wall_0": {
|
||||
"maximum_value_warning": "300"
|
||||
},
|
||||
"speed_wall_x": {
|
||||
"maximum_value_warning": "300",
|
||||
"value": "speed_print"
|
||||
},
|
||||
"speed_topbottom": {
|
||||
"maximum_value_warning": "300",
|
||||
"value": "speed_print"
|
||||
},
|
||||
"speed_travel": {
|
||||
"value": "300"
|
||||
},
|
||||
"speed_travel_layer_0": {
|
||||
"value": "300"
|
||||
},
|
||||
"speed_layer_0": {
|
||||
"value": "5"
|
||||
},
|
||||
"speed_slowdown_layers": {
|
||||
"value": "2"
|
||||
},
|
||||
|
||||
"acceleration_enabled": {
|
||||
"value": "False"
|
||||
},
|
||||
"print_sequence": {
|
||||
"enabled": false
|
||||
},
|
||||
"support_enable": {
|
||||
"enabled": false
|
||||
},
|
||||
"machine_nozzle_temp_enabled": {
|
||||
"value": "False"
|
||||
},
|
||||
"material_bed_temperature": {
|
||||
"enabled": false
|
||||
},
|
||||
"material_diameter": {
|
||||
"enabled": false,
|
||||
"value": "1.75"
|
||||
},
|
||||
"cool_fan_enabled": {
|
||||
"enabled": false,
|
||||
"value": "False"
|
||||
},
|
||||
"retraction_enable": {
|
||||
"enabled": false,
|
||||
"value": "False"
|
||||
},
|
||||
"retraction_combing": {
|
||||
"enabled": false,
|
||||
"value": "'off'"
|
||||
},
|
||||
"retract_at_layer_change": {
|
||||
"enabled": false
|
||||
},
|
||||
"cool_min_layer_time_fan_speed_max": {
|
||||
"enabled": false
|
||||
},
|
||||
"cool_fan_full_at_height": {
|
||||
"enabled": false
|
||||
},
|
||||
"cool_fan_full_layer": {
|
||||
"enabled": false
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue