Merge branch 'main' into pr/tommasobbianchi/15238

This commit is contained in:
SoftFever
2026-09-08 14:28:31 +08:00
4759 changed files with 44361 additions and 18139 deletions
+39 -17
View File
@@ -30,25 +30,47 @@ if (APPLE)
target_link_libraries(test_common INTERFACE "-liconv -framework IOKit" "-framework CoreFoundation" -lc++)
endif()
# Copies runtime DLLs next to each test executable. Handles both single-config
# generators (CMAKE_BUILD_TYPE set) and multi-config generators (Ninja
# Multi-Config, Visual Studio) where CMAKE_BUILD_TYPE is empty and DLLs must
# land in every per-config output directory.
# Copies runtime shared libraries next to each test executable. Handles both
# single-config generators (CMAKE_BUILD_TYPE set) and multi-config generators
# (Ninja Multi-Config, Visual Studio) where CMAKE_BUILD_TYPE is empty and DLLs
# must land in every per-config output directory. On Windows the loader finds
# DLLs in the executable's directory; the Linux branch below does the same for
# the deps-built FFmpeg libraries and adds an $ORIGIN rpath, since the ELF
# loader does not search the executable's directory and the CI unit-test runner
# only receives the tests artifact (no deps install).
function(orcaslicer_copy_test_dlls)
if (NOT WIN32)
return()
endif()
set(_configs ${CMAKE_CONFIGURATION_TYPES})
if (NOT _configs)
set(_configs "${CMAKE_BUILD_TYPE}")
endif()
foreach(_cfg IN LISTS _configs)
if (_cfg STREQUAL "Debug")
orcaslicer_copy_dlls(COPY_DLLS "Debug" "d" _unused_dlls)
else()
orcaslicer_copy_dlls(COPY_DLLS "${_cfg}" "" _unused_dlls)
if (WIN32)
set(_configs ${CMAKE_CONFIGURATION_TYPES})
if (NOT _configs)
set(_configs "${CMAKE_BUILD_TYPE}")
endif()
endforeach()
foreach(_cfg IN LISTS _configs)
if (_cfg STREQUAL "Debug")
orcaslicer_copy_dlls(COPY_DLLS "Debug" "d" _unused_dlls)
else()
orcaslicer_copy_dlls(COPY_DLLS "${_cfg}" "" _unused_dlls)
endif()
endforeach()
elseif (UNIX AND NOT APPLE)
# Only test executables that link libslic3r_gui pull in the FFmpeg
# shared libraries (src/slic3r/CMakeLists.txt links PkgConfig::LIBAV
# into it). Copy them next to the executable and give it an $ORIGIN
# rpath so the loader finds them when the tests run on the CI unit-test
# runner, which only receives this build/tests tree.
get_target_property(_linked_libs ${_TEST_NAME}_tests LINK_LIBRARIES)
if (NOT "libslic3r_gui" IN_LIST _linked_libs)
return()
endif()
set_property(TARGET ${_TEST_NAME}_tests PROPERTY BUILD_RPATH "$ORIGIN")
set(_configs ${CMAKE_CONFIGURATION_TYPES})
if (NOT _configs)
set(_configs "${CMAKE_BUILD_TYPE}")
endif()
foreach(_cfg IN LISTS _configs)
orcaslicer_copy_sos(${_TEST_NAME}_tests "${_cfg}" "" _unused_sos)
endforeach()
endif()
endfunction()
# Register Catch2 tags as CTest labels so `ctest -L`/`-LE` can filter by tag.
+1
View File
@@ -19,6 +19,7 @@ add_executable(${_TEST_NAME}_tests
test_skirt_brim.cpp
test_slicing_pipeline_hook.cpp
test_support_material.cpp
test_tree_support.cpp
test_trianglemesh.cpp
test_wipe_tower.cpp
)
+68
View File
@@ -2,7 +2,10 @@
#include "test_helpers.hpp"
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
using namespace Slic3r;
using namespace Slic3r::Test;
@@ -25,3 +28,68 @@ TEST_CASE("Cooling consumes its internal speed markers", "[Cooling]")
const std::string gcode = slice({ cube(20) }, { { "layer_height", 0.2 } });
CHECK(gcode.find(";_EXTRUDE_SET_SPEED") == std::string::npos);
}
TEST_CASE("Overhang fan transitions do not depend on overhang speed", "[Cooling][Regression]")
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "bridge_speed", 2.0 },
{ "enable_arc_fitting", false },
{ "enable_overhang_bridge_fan", true },
{ "enable_overhang_speed", false },
{ "initial_layer_print_height", 0.3 },
{ "inner_wall_speed", 30.0 },
{ "layer_height", 0.3 },
{ "outer_wall_speed", 30.0 },
{ "overhang_1_4_speed", "30" },
{ "overhang_2_4_speed", "29" },
{ "overhang_3_4_speed", "6" },
{ "overhang_4_4_speed", "3" },
{ "slow_down_for_layer_cooling", false },
{ "slowdown_for_curled_perimeters", false },
});
config.set_key_value("fan_max_speed", new ConfigOptionFloats{20.0});
config.set_key_value("fan_min_speed", new ConfigOptionFloats{20.0});
config.set_key_value("overhang_fan_speed", new ConfigOptionInts{100});
config.set_key_value("overhang_fan_threshold", new ConfigOptionEnumsGeneric{Overhang_threshold_2_4});
config.set_key_value("layer_change_gcode", new ConfigOptionString{";TEST_LAYER_Z=[layer_z]"});
const auto fan_commands = [](const std::string &gcode) {
std::vector<std::pair<std::string, std::string>> commands;
std::istringstream input(gcode);
std::string layer;
std::string line;
while (std::getline(input, line)) {
if (line.rfind(";TEST_LAYER_Z=", 0) == 0)
layer = line;
else if (!layer.empty() && (line.rfind("M106", 0) == 0 || line.rfind("M107", 0) == 0))
commands.emplace_back(layer, line);
}
return commands;
};
const auto feedrates = [](const std::string &gcode) {
std::vector<std::string> values;
std::istringstream input(gcode);
std::string word;
while (input >> word)
if (!word.empty() && word.front() == 'F')
values.push_back(word);
return values;
};
constexpr double sphere_radius = 50.0; // 100 mm diameter.
const std::string without_speed_gcode = slice({make_sphere(sphere_radius, PI / 24.0)}, config);
config.set_deserialize_strict({{"enable_overhang_speed", true}});
const std::string with_speed_gcode = slice({make_sphere(sphere_radius, PI / 24.0)}, config);
const auto without_speed_fan = fan_commands(without_speed_gcode);
const auto with_speed_fan = fan_commands(with_speed_gcode);
const auto without_speed_feedrates = feedrates(without_speed_gcode);
const auto with_speed_feedrates = feedrates(with_speed_gcode);
REQUIRE_FALSE(without_speed_fan.empty());
REQUIRE(std::any_of(without_speed_fan.begin(), without_speed_fan.end(),
[](const auto &command) { return command.second.find("S255") != std::string::npos; }));
REQUIRE(with_speed_feedrates != without_speed_feedrates);
CHECK(with_speed_fan == without_speed_fan);
}
+207
View File
@@ -699,6 +699,213 @@ TEST_CASE("Solid infill direction offsets every layer when no template is set",
}
}
// Orca: the spiral inset pattern chains the concentric loops into a single continuous path per
// island, so it has to cope with the degenerate loops offsetting leaves behind and it must not join
// loops that only look adjacent.
namespace {
Slic3r::Polylines spiral_inset_fill(const Slic3r::ExPolygon &surface_shape, double spacing)
{
std::unique_ptr<Slic3r::Fill> filler(Slic3r::Fill::new_from_type("spiralinset"));
filler->spacing = spacing;
// Cancel the half-spacing contraction fill_surface() applies, so the filler sees the shape as given.
filler->overlap = 0.5 * spacing;
Slic3r::FillParams fill_params;
fill_params.density = 1.f;
fill_params.dont_adjust = true;
Slic3r::Surface surface(Slic3r::stBottom, surface_shape);
return filler->fill_surface(&surface, fill_params);
}
Slic3r::ExPolygon rectangle(double x, double y, double w, double h)
{
return Slic3r::ExPolygon({Slic3r::Point::new_scale(x, y), Slic3r::Point::new_scale(x + w, y),
Slic3r::Point::new_scale(x + w, y + h), Slic3r::Point::new_scale(x, y + h)});
}
// Area of the surface the toolpaths fail to cover, and the largest single patch of it, in mm2. Each
// bead is measured at its own width so the variable width walls are not sold short.
std::pair<double, double> uncovered_area(const Slic3r::ExPolygon &surface_shape, const Slic3r::Polygons &covered)
{
double total = 0, biggest = 0;
for (const Slic3r::ExPolygon &gap : Slic3r::diff_ex(Slic3r::ExPolygons{surface_shape}, Slic3r::union_(covered))) {
const double area = unscale<double>(unscale<double>(gap.area()));
total += area;
biggest = std::max(biggest, area);
}
return {total, biggest};
}
Slic3r::Polygons beads_of(const Slic3r::Polylines &paths, double width)
{
return Slic3r::offset(paths, float(scale_(0.5 * width)));
}
Slic3r::Polygons beads_of(const Slic3r::ThickPolylines &paths)
{
Slic3r::Polygons covered;
for (const Slic3r::ThickPolyline &path : paths)
for (size_t i = 0; i + 1 < path.points.size(); ++i) {
Slic3r::Polyline segment;
segment.points = {path.points[i], path.points[i + 1]};
Slic3r::append(covered, Slic3r::offset(Slic3r::Polylines{segment},
float(0.5 * std::max(path.width[2 * i], path.width[2 * i + 1]))));
}
return covered;
}
} // namespace
TEST_CASE("Spiral inset fill drops loops shorter than the end clipping", "[Fill][Regression]")
{
// A sliver whose whole perimeter is shorter than the length clipped off the end of a loop, so the
// clipping consumes the path entirely. Such a loop carries no extrusion and must be dropped
// rather than kept as an empty path and read back from.
const double spacing = 0.45;
Slic3r::Polylines paths;
REQUIRE_NOTHROW(paths = spiral_inset_fill(rectangle(0, 0, 0.05, 0.05), spacing));
for (const Slic3r::Polyline &path : paths)
CHECK(path.size() >= 2);
// The same surface at a size the clipping cannot swallow still gets filled.
REQUIRE_NOTHROW(paths = spiral_inset_fill(rectangle(0, 0, 5, 5), spacing));
REQUIRE(paths.size() == 1);
CHECK(paths.front().size() >= 2);
}
TEST_CASE("Spiral inset fill keeps separate islands on separate paths", "[Fill]")
{
// Two lobes joined by a neck narrower than the loop spacing: the inward offsets break the surface
// into two islands, which cannot share one spiral, and no path may leave the surface.
const double spacing = 0.45;
Slic3r::ExPolygon dumbbell = rectangle(0, 0, 6, 6);
dumbbell = Slic3r::union_ex(Slic3r::ExPolygons{dumbbell, rectangle(6, 2.9, 4, 0.2), rectangle(10, 0, 6, 6)}).front();
const Slic3r::Polylines paths = spiral_inset_fill(dumbbell, spacing);
REQUIRE(paths.size() >= 2);
// Inflate by a hair so that loops sitting exactly on the outline still count as contained.
const Slic3r::ExPolygons within = Slic3r::offset_ex(dumbbell, float(SCALED_EPSILON));
REQUIRE(within.size() == 1);
for (const Slic3r::Polyline &path : paths) {
CHECK(path.size() >= 2);
CHECK(within.front().contains(path));
}
}
TEST_CASE("Spiral inset fill stays connected across sharp corners", "[Fill][Regression]")
{
// At a corner of half-angle a, the next ring inward retreats along the bisector by spacing/sin(a),
// which leaves it several spacings from the end of the ring it continues. Judging the break by
// distance broke the spiral into loose rings at every spike; nesting is what decides the island.
const double spacing = 0.45;
const Slic3r::ExPolygon spike({Slic3r::Point::new_scale(0, 0), Slic3r::Point::new_scale(30, 0),
Slic3r::Point::new_scale(15, 4)});
const Slic3r::Polylines paths = spiral_inset_fill(spike, spacing);
CHECK(paths.size() == 1);
const Slic3r::ExPolygons within = Slic3r::offset_ex(spike, float(SCALED_EPSILON));
REQUIRE(within.size() == 1);
for (const Slic3r::Polyline &path : paths)
CHECK(within.front().contains(path));
}
TEST_CASE("Spiral inset fill starts on a convex corner", "[Fill][Regression]")
{
// The only right angle on this outline is the reflex one: the two edges meeting at the origin
// span 90 degrees exactly as a square corner would, but the material lies outside them. The next
// ring in steps away from a reflex corner along the bisector instead of hugging it, so starting
// the spiral there sent it across a long diagonal on every single ring.
const double spacing = 0.45;
const Slic3r::ExPolygon notched({Slic3r::Point::new_scale(0, 0), Slic3r::Point::new_scale(0, 10),
Slic3r::Point::new_scale(-16, 18), Slic3r::Point::new_scale(-16, -2),
Slic3r::Point::new_scale(-8, -16), Slic3r::Point::new_scale(18, -16),
Slic3r::Point::new_scale(10, 0)});
const Slic3r::Polylines paths = spiral_inset_fill(notched, spacing);
REQUIRE(paths.size() >= 1);
// Every edge of the outline is at least 45 degrees off the bisector of that reflex corner, and
// so is every ring offset from it. A long segment running along the bisector can therefore only
// be the spiral striking out across the rings to reach the next one.
for (const Slic3r::Polyline &path : paths)
for (const Slic3r::Line &segment : path.lines()) {
const Vec2d v = (segment.b - segment.a).cast<double>();
const double direction = std::fmod(std::atan2(v.y(), v.x()) * 180.0 / M_PI + 180.0, 180.0);
if (std::abs(direction - 45.0) > 25.0)
continue;
CAPTURE(direction, unscale<double>(segment.length()));
CHECK(segment.length() <= scale_(1.5 * spacing));
}
}
TEST_CASE("Spiral inset fill closes the gaps with variable width walls", "[Fill]")
{
// Fixed width loops cannot fill a region that is not a whole number of lines across and leave the
// remainder open, which on a ring shows up as a wedge several lines wide. Plain concentric avoids
// that by building solid surfaces out of Arachne's variable width walls, and so must this pattern.
const double spacing = 0.45;
Slic3r::ExPolygon ring = rectangle(0, 0, 24, 24);
Slic3r::Polygon hole;
for (int i = 0; i < 64; ++i) {
const double angle = -2.0 * PI * i / 64.0; // clockwise, so it reads as a hole
hole.points.emplace_back(Slic3r::Point::new_scale(12 + 7.3 * std::cos(angle), 12 + 7.3 * std::sin(angle)));
}
ring.holes.emplace_back(hole);
Slic3r::PrintConfig print_config;
Slic3r::PrintObjectConfig object_config;
auto make_filler = [&]() {
std::unique_ptr<Slic3r::Fill> filler(Slic3r::Fill::new_from_type("spiralinset"));
filler->spacing = spacing;
filler->overlap = 0.5 * spacing; // cancel the contraction, so both see the same surface
filler->print_config = &print_config;
filler->print_object_config = &object_config;
return filler;
};
Slic3r::FillParams params;
params.density = 1.f;
params.dont_adjust = false;
params.layer_height = 0.2;
const Slic3r::Surface surface(Slic3r::stTop, ring);
std::unique_ptr<Slic3r::Fill> fixed = make_filler();
const Slic3r::Polylines fixed_width = fixed->fill_surface(&surface, params);
REQUIRE(!fixed_width.empty());
const auto fixed_gaps = uncovered_area(ring, beads_of(fixed_width, fixed->spacing));
params.use_arachne = true;
std::unique_ptr<Slic3r::Fill> variable = make_filler();
const Slic3r::ThickPolylines variable_width = variable->fill_surface_arachne(&surface, params);
REQUIRE(!variable_width.empty());
const auto variable_gaps = uncovered_area(ring, beads_of(variable_width));
CAPTURE(fixed_gaps.first, fixed_gaps.second, variable_gaps.first, variable_gaps.second);
// The wedges the fixed width loops leave behind are what the variable width walls take up.
CHECK(variable_gaps.second < 0.5 * fixed_gaps.second);
CHECK(variable_gaps.first < fixed_gaps.first);
// And it is still a spiral: far fewer paths than the ring has loops.
// And the walls are still chained into spirals rather than printed one path per wall. The ring is
// at its narrowest (12 - 7.3) mm across and is filled from both sides, so it is at least this many
// walls thick there and thicker elsewhere. Arachne's short thin feature walls cannot join a spiral,
// so only the substantial paths count towards this.
const size_t walls_across = size_t(2.0 * (12.0 - 7.3) / spacing);
size_t spirals = 0;
for (const Slic3r::ThickPolyline &path : variable_width)
if (path.length() > scale_(10.0 * spacing))
++spirals;
CAPTURE(spirals, walls_across, variable_width.size(), fixed_width.size());
CHECK(2 * spirals < walls_across);
}
TEST_CASE("Honeycomb infill rounds its cell corners with the smooth factor", "[Fill]")
{
// A cell whose sides are several times the line width, so that the corners have room to be rounded.
+361
View File
@@ -3,11 +3,103 @@
#include "libslic3r/GCodeReader.hpp"
#include "libslic3r/Layer.hpp"
#include <cmath>
#include <map>
#include <set>
#include <vector>
#include "test_helpers.hpp" // get access to init_print, etc
// Not self-contained: its inline constructor uses PrintObject, PrintRegion, SlicingParameters and
// Geometry, so it must follow the headers (pulled in via test_helpers.hpp) that define them.
#include "libslic3r/Support/SupportParameters.hpp"
using namespace Slic3r::Test;
using namespace Slic3r;
// Distinct layer Z heights carrying support interface extrusion.
static size_t support_interface_layer_count(const std::string &gcode)
{
return layers_with_role(gcode, "support material interface").size();
}
// Distinct layer Z heights carrying support base extrusion. The base G-code label "support material"
// is a substring of "support material interface", so a base line is a support line that is not an
// interface line.
static size_t support_base_layer_count(const std::string &gcode)
{
std::set<double> layers;
GCodeReader parser;
parser.parse_buffer(gcode, [&layers](GCodeReader &self, const GCodeReader::GCodeLine &line) {
if (! line.extruding(self)) return;
const std::string_view comment = line.comment();
if (comment.find("support material") != std::string_view::npos &&
comment.find("interface") == std::string_view::npos)
layers.insert(self.z());
});
return layers.size();
}
// Dominant support-interface fill direction per interface layer, in radians [0, pi). Uses the
// length-weighted axial mean (each segment angle doubled so a line and its reverse agree, then
// halved): the parallel infill lines reinforce while the surrounding perimeter cancels.
static std::map<double, double> interface_fill_angle_by_layer(const std::string &gcode)
{
std::map<double, std::pair<double, double>> acc; // z -> summed length*(cos2a, sin2a)
GCodeReader parser;
parser.parse_buffer(gcode, [&acc](GCodeReader &self, const GCodeReader::GCodeLine &line) {
if (! line.extruding(self)) return;
if (line.comment().find("support material interface") == std::string_view::npos) return;
const double dx = line.dist_X(self), dy = line.dist_Y(self);
const double len = std::hypot(dx, dy);
if (len < 1e-6) return;
const double a2 = 2.0 * std::atan2(dy, dx);
auto &p = acc[self.z()];
p.first += len * std::cos(a2);
p.second += len * std::sin(a2);
});
std::map<double, double> out;
for (const auto &kv : acc) {
double a = 0.5 * std::atan2(kv.second.second, kv.second.first);
if (a < 0) a += M_PI;
out[kv.first] = a;
}
return out;
}
// Acute angle (degrees) between two axial fill directions in [0, pi).
static double axial_angle_diff_deg(double a, double b)
{
const double d = std::fmod(std::fabs(a - b), M_PI);
return std::min(d, M_PI - d) * 180.0 / M_PI;
}
// Denser interface spacing yields more extruded length.
static double support_interface_extrusion_length(const std::string &gcode)
{
double len = 0;
GCodeReader parser;
parser.parse_buffer(gcode, [&len](GCodeReader &self, const GCodeReader::GCodeLine &line) {
if (! line.extruding(self)) return;
if (line.comment().find("support material interface") == std::string_view::npos) return;
len += std::hypot(line.dist_X(self), line.dist_Y(self));
});
return len;
}
// A cap slab overhanging a base, joined by a central stem: the cap can only be supported by resting on the
// base, forcing a genuine bottom contact. A horizontal tunnel does not work here -- tree/organic can arch a
// branch in from the opening and avoid the floor entirely.
static TriangleMesh support_capital()
{
TriangleMesh model = make_cube(40, 40, 2); // base [0,40]x[0,40]x[0,2]
TriangleMesh stem = make_cube(8, 8, 12); stem.translate(16, 16, 1); // stem centered, z 1..13
TriangleMesh cap = make_cube(40, 40, 2); cap.translate(0, 0, 12); // cap z 12..14
model.merge(stem);
model.merge(cap);
return model;
}
TEST_CASE("Three raft layers are created", "[SupportMaterial]")
{
Slic3r::Print print;
@@ -104,3 +196,272 @@ TEST_CASE("Support G-code emission survives a second slice in the same process",
const std::string second = slice({ TestMesh::overhang }, { { "enable_support", 1 } });
REQUIRE(! layers_with_role(second, "support").empty());
}
// The contact layer counts toward the configured interface layer count, so N configured top
// interface layers produce exactly N interface layers, not N+1.
TEST_CASE("Support top interface layer count matches the configured value", "[SupportMaterial]")
{
const int top = GENERATE(1, 2, 3, 4, 6);
const std::string g = slice({ TestMesh::overhang }, {
{ "enable_support", 1 },
{ "layer_height", 0.2 },
{ "support_on_build_plate_only", 1 },
{ "support_interface_top_layers", top },
{ "support_interface_bottom_layers", 0 },
});
CAPTURE(top);
REQUIRE(support_base_layer_count(g) > 0); // support actually formed
REQUIRE(support_interface_layer_count(g) == size_t(top));
}
// A rotated cube-with-hole is a horizontal tunnel whose ceiling and floor both receive support, so top
// and bottom interfaces can be exercised independently (the floor is the bottom contact).
static TriangleMesh support_tunnel()
{
TriangleMesh tunnel = Slic3r::Test::mesh(TestMesh::cube_with_hole);
tunnel.rotate_x(float(M_PI / 2));
return tunnel;
}
static size_t tunnel_interface_layers(const TriangleMesh &tunnel, int top, int bottom)
{
const std::string g = slice({ tunnel }, {
{ "enable_support", 1 },
{ "layer_height", 0.2 },
{ "support_on_build_plate_only", 0 },
{ "support_interface_top_layers", top },
{ "support_interface_bottom_layers", bottom },
});
REQUIRE(support_base_layer_count(g) > 0); // support actually formed
return support_interface_layer_count(g);
}
TEST_CASE("No support interface is generated when neither top nor bottom is configured", "[SupportMaterial]")
{
REQUIRE(tunnel_interface_layers(support_tunnel(), 0, 0) == 0);
}
TEST_CASE("Bottom interface layer count matches its setting with top interface off", "[SupportMaterial]")
{
const int bottom = GENERATE(1, 3, 6);
CAPTURE(bottom);
REQUIRE(tunnel_interface_layers(support_tunnel(), 0, bottom) == size_t(bottom));
}
// support_interface_bottom_layers = -1 means "same as top".
TEST_CASE("Support interface bottom layers default to the top layer count", "[SupportMaterial]")
{
const TriangleMesh tunnel = support_tunnel();
REQUIRE(tunnel_interface_layers(tunnel, 0, -1) == tunnel_interface_layers(tunnel, 0, 0));
REQUIRE(tunnel_interface_layers(tunnel, 3, -1) == tunnel_interface_layers(tunnel, 3, 3));
}
TEST_CASE("Default support still emits base and interface material", "[SupportMaterial][Regression]")
{
const std::string g = slice({ TestMesh::overhang }, { { "enable_support", 1 } });
REQUIRE(support_base_layer_count(g) > 0);
REQUIRE(support_interface_layer_count(g) > 0);
}
// Organic runs TreeSupport3D + TreeModelVolumes, the others the classic TreeSupport.cpp path.
TEST_CASE("Every tree support style produces base and interface material", "[SupportMaterial]")
{
const char *style = GENERATE("organic", "tree_slim", "tree_strong", "tree_hybrid");
INFO("style=" << style);
const std::string g = slice({ TestMesh::overhang }, {
{ "enable_support", 1 },
{ "layer_height", 0.2 },
{ "support_type", "tree(auto)" },
{ "support_style", style },
{ "support_interface_top_layers", 3 },
});
CHECK(support_base_layer_count(g) > 0);
CHECK(support_interface_layer_count(g) > 0);
}
TEST_CASE("Raft interface angle alternates by 45 degrees per interface id", "[SupportMaterial]")
{
Slic3r::Print print;
Slic3r::Test::init_and_process_print({ TestMesh::overhang }, print, { { "enable_support", 1 } });
SupportParameters sp(*print.objects().front());
sp.raft_angle_interface = 0.5f;
REQUIRE_THAT(sp.raft_interface_angle(0), Catch::Matchers::WithinAbs(0.5 + M_PI / 4., 1e-6));
REQUIRE_THAT(sp.raft_interface_angle(1), Catch::Matchers::WithinAbs(0.5 - M_PI / 4., 1e-6));
}
// The angle inputs are overwritten directly, so the pattern-to-angle mapping is checked
// independently of the sliced object's configuration.
TEST_CASE("Support interface fill angle follows the configured interface pattern", "[SupportMaterial]")
{
Slic3r::Print print;
Slic3r::Test::init_and_process_print({ TestMesh::overhang }, print, { { "enable_support", 1 } });
SupportParameters sp(*print.objects().front());
sp.interface_angle = 0.3f;
sp.base_angle = 1.1f;
const double tol = 1e-6;
SECTION("Rectilinear shifts the interface angle by -45deg for snug support") {
sp.support_interface_pattern = smipRectilinear;
sp.support_style = smsSnug;
REQUIRE_THAT(sp.support_interface_angle(0), Catch::Matchers::WithinAbs(sp.interface_angle - M_PI_4, tol));
REQUIRE_THAT(sp.support_interface_angle(3), Catch::Matchers::WithinAbs(sp.interface_angle - M_PI_4, tol));
}
SECTION("Rectilinear leaves the interface angle alone for the other styles") {
sp.support_interface_pattern = smipRectilinear;
sp.support_style = smsGrid;
REQUIRE_THAT(sp.support_interface_angle(0), Catch::Matchers::WithinAbs(sp.interface_angle, tol));
}
SECTION("Rectilinear interlaced alternates -/+45deg by interface id parity") {
sp.support_interface_pattern = smipRectilinearInterlaced;
REQUIRE_THAT(sp.support_interface_angle(0), Catch::Matchers::WithinAbs(sp.interface_angle - M_PI_4, tol));
REQUIRE_THAT(sp.support_interface_angle(1), Catch::Matchers::WithinAbs(sp.interface_angle + M_PI_4, tol));
}
SECTION("Grid uses the base angle") {
sp.support_interface_pattern = smipGrid;
REQUIRE_THAT(sp.support_interface_angle(0), Catch::Matchers::WithinAbs(sp.base_angle, tol));
}
SECTION("Auto and concentric use the interface angle unchanged") {
sp.support_interface_pattern = smipAuto;
REQUIRE_THAT(sp.support_interface_angle(0), Catch::Matchers::WithinAbs(sp.interface_angle, tol));
sp.support_interface_pattern = smipConcentric;
REQUIRE_THAT(sp.support_interface_angle(0), Catch::Matchers::WithinAbs(sp.interface_angle, tol));
}
}
// End-to-end that the pattern reaches the emitted fill, not just support_interface_angle().
TEST_CASE("Interlaced support interface alternates fill angle while rectilinear does not", "[SupportMaterial]")
{
auto interface_angles = [](const char *pattern) {
std::vector<double> a;
for (const auto &kv : interface_fill_angle_by_layer(slice({ TestMesh::overhang }, {
{ "enable_support", 1 },
{ "layer_height", 0.2 },
{ "support_on_build_plate_only", 1 },
{ "support_interface_top_layers", 6 },
{ "support_interface_pattern", pattern } })))
a.push_back(kv.second);
return a;
};
const std::vector<double> rectilinear = interface_angles("rectilinear");
const std::vector<double> interlaced = interface_angles("rectilinear_interlaced");
REQUIRE(rectilinear.size() >= 3);
REQUIRE(interlaced.size() >= 3);
for (size_t i = 1; i < rectilinear.size(); ++i)
REQUIRE(axial_angle_diff_deg(rectilinear[i], rectilinear[0]) < 15.0);
for (size_t i = 1; i < interlaced.size(); ++i)
REQUIRE(axial_angle_diff_deg(interlaced[i], interlaced[i - 1]) > 60.0);
}
// Normal and non-organic tree support share the same interface angle logic: with a rectilinear interface
// pattern both emit their interface fill at the same angle (both go through support_interface_angle()).
TEST_CASE("Normal and tree support use the same interface fill angle", "[SupportMaterial]")
{
auto mean_interface_angle = [](const char *type, const char *style) {
const auto angles = interface_fill_angle_by_layer(slice({ TestMesh::overhang }, {
{ "enable_support", 1 }, { "layer_height", 0.2 }, { "support_on_build_plate_only", 1 },
{ "support_type", type }, { "support_style", style },
{ "support_interface_top_layers", 6 }, { "support_interface_pattern", "rectilinear" } }));
REQUIRE(angles.size() >= 3);
// Axial mean, as in interface_fill_angle_by_layer: a plain mean would split angles either
// side of the [0, pi) wrap.
double x = 0, y = 0;
for (const auto &kv : angles) {
x += std::cos(2.0 * kv.second);
y += std::sin(2.0 * kv.second);
}
double mean = 0.5 * std::atan2(y, x);
if (mean < 0) mean += M_PI;
return mean;
};
REQUIRE(axial_angle_diff_deg(mean_interface_angle("normal(auto)", "default"),
mean_interface_angle("tree(auto)", "tree_slim")) < 10.0);
}
// Every style, because the non-organic tree styles once emitted one more top interface layer than the rest.
TEST_CASE("Top interface layer count equals the configured value for every support style", "[SupportMaterial]")
{
auto [type, style] = GENERATE(table<const char *, const char *>({
{ "normal(auto)", "grid" }, { "normal(auto)", "snug" },
{ "tree(auto)", "organic" }, { "tree(auto)", "tree_slim" },
{ "tree(auto)", "tree_strong" }, { "tree(auto)", "tree_hybrid" },
}));
CAPTURE(style);
const std::string g = slice({ TestMesh::overhang }, {
{ "enable_support", 1 },
{ "layer_height", 0.2 },
{ "support_type", type },
{ "support_style", style },
{ "support_interface_top_layers", 4 },
});
REQUIRE(support_interface_layer_count(g) == 4u);
}
// The bottom interface was dropped in earlier versions when support started on the model rather
// than the plate.
TEST_CASE("Non-organic tree support generates a bottom interface on internal geometry", "[SupportMaterial]")
{
const std::string g = slice({ support_tunnel() }, {
{ "enable_support", 1 },
{ "layer_height", 0.2 },
{ "support_on_build_plate_only", 0 },
{ "support_type", "tree(auto)" },
{ "support_style", "tree_slim" },
{ "support_interface_top_layers", 0 },
{ "support_interface_bottom_layers", 6 },
});
REQUIRE(support_base_layer_count(g) > 0);
REQUIRE(support_interface_layer_count(g) > 0);
}
// The capital forces the model contact; on a horizontal tunnel organic can arch a branch in and make none.
TEST_CASE("A bottom interface is produced for every support style on a forced model contact", "[SupportMaterial]")
{
auto [type, style] = GENERATE(table<const char *, const char *>({
{ "normal(auto)", "default" }, { "tree(auto)", "tree_slim" },
{ "tree(auto)", "tree_strong" }, { "tree(auto)", "tree_hybrid" },
{ "tree(auto)", "organic" },
}));
CAPTURE(style);
REQUIRE(support_interface_layer_count(slice({ support_capital() }, {
{ "enable_support", 1 }, { "layer_height", 0.2 }, { "support_on_build_plate_only", 0 },
{ "support_type", type }, { "support_style", style },
{ "support_interface_top_layers", 0 }, { "support_interface_bottom_layers", 6 } })) > 0);
}
TEST_CASE("Bottom interface spacing controls bottom interface density for every support style", "[SupportMaterial]")
{
auto [type, style] = GENERATE(table<const char *, const char *>({
{ "normal(auto)", "default" }, { "tree(auto)", "tree_slim" },
{ "tree(auto)", "tree_strong" }, { "tree(auto)", "tree_hybrid" },
{ "tree(auto)", "organic" },
}));
CAPTURE(style);
const TriangleMesh model = support_capital();
auto len = [&model](const char *support_type, const char *support_style, double spacing) {
return support_interface_extrusion_length(slice({ model }, {
{ "enable_support", 1 }, { "layer_height", 0.2 }, { "support_on_build_plate_only", 0 },
{ "support_type", support_type }, { "support_style", support_style }, { "support_interface_top_layers", 0 },
{ "support_interface_bottom_layers", 6 }, { "support_bottom_interface_spacing", spacing } }));
};
REQUIRE(len(type, style, 0.0) > len(type, style, 4.0) * 1.5);
}
// Interface and base flows are identical in width and rate unless a separate support-interface
// filament is used, so density is the observable here, not flow.
TEST_CASE("Bottom-only support interface keeps the dense interface density", "[SupportMaterial]")
{
Slic3r::Print print;
Slic3r::Test::init_and_process_print({ TestMesh::overhang }, print, {
{ "enable_support", 1 },
{ "support_interface_top_layers", 0 },
{ "support_interface_bottom_layers", 6 },
{ "support_bottom_interface_spacing", 0.0 }, // solid: density resolves to 1.0
{ "support_base_pattern_spacing", 2.5 }, // sparse: density stays below 1.0
});
SupportParameters sp(*print.objects().front());
REQUIRE(sp.bottom_interface_density > sp.support_density);
}
+125
View File
@@ -0,0 +1,125 @@
#include <catch2/catch_all.hpp>
#include "libslic3r/Layer.hpp"
#include "libslic3r/TriangleMesh.hpp"
#include "test_helpers.hpp"
using namespace Slic3r::Test;
using namespace Slic3r;
namespace {
// The upper plate overhangs both the lower plate and open air, so branches land on the model and on
// the bed in the same slice.
TriangleMesh two_tier_mesh()
{
TriangleMesh lower = make_cube(30, 30, 3);
TriangleMesh column = make_cube(8, 8, 15);
TriangleMesh upper = make_cube(50, 50, 3);
// Each part overlaps the one below rather than resting on it; a coplanar join slices ambiguously.
column.translate(11.f, 11.f, 2.f);
upper.translate(-10.f, -10.f, 16.f);
TriangleMesh mesh = lower;
mesh.merge(column);
mesh.merge(upper);
return mesh;
}
TriangleMesh scaled(TestMesh id, float scale)
{
TriangleMesh mesh = Slic3r::Test::mesh(id);
mesh.scale(scale);
return mesh;
}
void slice_with_tree_support(const TriangleMesh &mesh, Slic3r::Print &print, const char *style,
int threshold_angle = 30, int build_plate_only = 0, int raft_layers = 0)
{
Slic3r::Test::init_and_process_print({ mesh }, print, {
{ "enable_support", 1 },
{ "support_type", "tree(auto)" },
{ "support_style", style },
{ "support_on_build_plate_only", build_plate_only },
{ "support_threshold_angle", threshold_angle },
{ "raft_layers", raft_layers },
{ "layer_height", 0.2 },
});
}
Points support_points(const Slic3r::Print &print)
{
Points points;
for (const SupportLayer *layer : print.objects().front()->support_layers())
layer->support_fills.collect_points(points);
return points;
}
size_t support_point_count(const TriangleMesh &mesh, const char *style, int threshold_angle = 30,
int build_plate_only = 0)
{
Slic3r::Print print;
slice_with_tree_support(mesh, print, style, threshold_angle, build_plate_only);
return support_points(print).size();
}
} // namespace
TEST_CASE("Tree support is generated for an overhang and not for a plain cube", "[TreeSupport]")
{
REQUIRE(support_point_count(scaled(TestMesh::overhang, 2.f), "tree_slim") > 1000);
REQUIRE(support_point_count(Slic3r::Test::cube(20), "tree_slim") == 0);
}
TEST_CASE("Restricting tree support to the build plate changes what is generated", "[TreeSupport]")
{
const TriangleMesh mesh = two_tier_mesh();
const size_t anywhere = support_point_count(mesh, "tree_slim", 30, 0);
const size_t plate_only = support_point_count(mesh, "tree_slim", 30, 1);
REQUIRE(anywhere > 1000);
REQUIRE(plate_only > 1000);
// The upper plate overhangs the lower one, so some branches would land on the model.
REQUIRE(plate_only != anywhere);
}
TEST_CASE("Tree support layers rise monotonically within the layer height limits", "[TreeSupport]")
{
Slic3r::Print print;
slice_with_tree_support(scaled(TestMesh::overhang, 2.f), print, "tree_slim");
const double nozzle = print.config().nozzle_diameter.values.front();
size_t checked = 0;
double previous = 0;
bool previous_was_adjacent = false;
for (const SupportLayer *layer : print.objects().front()->support_layers()) {
if (layer->print_z <= 0 || layer->height <= 0) {
// Layers with no nodes are left at zero. Skipping one leaves a hole, so the next pair
// spans more than one layer and its gap says nothing about the layer height limit.
previous_was_adjacent = false;
continue;
}
if (previous > 0) {
CAPTURE(previous, layer->print_z);
REQUIRE(layer->print_z > previous);
if (previous_was_adjacent)
REQUIRE(layer->print_z - previous <= nozzle + EPSILON);
}
previous = layer->print_z;
previous_was_adjacent = true;
++checked;
}
REQUIRE(checked > 10);
}
TEST_CASE("A raft is still generated under tree support", "[TreeSupport]")
{
// The mesh supports itself, so a layer count alone passes with no raft at all.
Slic3r::Print rafted, unrafted;
slice_with_tree_support(scaled(TestMesh::overhang, 2.f), rafted, "tree_slim", 30, 0, 3);
slice_with_tree_support(scaled(TestMesh::overhang, 2.f), unrafted, "tree_slim", 30, 0, 0);
const PrintObject *rafted_object = rafted.objects().front();
const PrintObject *unrafted_object = unrafted.objects().front();
REQUIRE(rafted_object->support_layers().size() > unrafted_object->support_layers().size());
// The raft goes under the object.
REQUIRE(rafted_object->layers().front()->print_z > unrafted_object->layers().front()->print_z);
}
+1
View File
@@ -8,6 +8,7 @@ add_executable(${_TEST_NAME}_tests
test_arachne_walls.cpp
test_arrange.cpp
test_bambu_networking.cpp
test_buildvolume.cpp
test_calib.cpp
test_clipper_offset.cpp
test_clipper_utils.cpp
+40
View File
@@ -0,0 +1,40 @@
#include <catch2/catch_all.hpp>
#include "libslic3r/BuildVolume.hpp"
using namespace Slic3r;
static std::vector<Vec2d> rect_area(double w, double d)
{
return { { 0., 0. }, { w, 0. }, { w, d }, { 0., d } };
}
// extruder_printable_height and extruder_printable_area are independent config options, so a
// profile can leave the heights short. BuildVolume must not index past the end of the heights.
TEST_CASE("BuildVolume falls back to the bed height when extruder_printable_height is short", "[BuildVolume]")
{
const std::vector<Vec2d> bed = rect_area(200., 200.);
const std::vector<std::vector<Vec2d>> areas = { rect_area(200., 200.), rect_area(100., 200.) };
const std::vector<double> heights = { 180. };
const BuildVolume build_volume(bed, 250., areas, heights);
REQUIRE(build_volume.get_extruder_area_count() == 2);
// The extruder with a height of its own keeps it, and differs from the bed, so it gets its own volume.
CHECK_THAT(build_volume.get_extruder_area_volume(0).bboxf.max.z(), Catch::Matchers::WithinAbs(180., 1e-6));
// The extruder without one falls back to the bed's printable_height instead of reading out of range.
CHECK_THAT(build_volume.get_extruder_area_volume(1).bboxf.max.z(), Catch::Matchers::WithinAbs(250., 1e-6));
}
TEST_CASE("BuildVolume keeps per-extruder heights when both vectors match", "[BuildVolume]")
{
const std::vector<Vec2d> bed = rect_area(200., 200.);
const std::vector<std::vector<Vec2d>> areas = { rect_area(120., 200.), rect_area(100., 200.) };
const std::vector<double> heights = { 180., 200.5 };
const BuildVolume build_volume(bed, 250., areas, heights);
REQUIRE(build_volume.get_extruder_area_count() == 2);
CHECK_THAT(build_volume.get_extruder_area_volume(0).bboxf.max.z(), Catch::Matchers::WithinAbs(180., 1e-6));
CHECK_THAT(build_volume.get_extruder_area_volume(1).bboxf.max.z(), Catch::Matchers::WithinAbs(200.5, 1e-6));
}
+263
View File
@@ -828,3 +828,266 @@ SCENARIO("ConfigOptionVector::set_to_index throws on incompatible type", "[Confi
}
}
}
TEST_CASE("read_cli applies valid values and collects non-option arguments", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--nozzle-temperature", "210,190", "--reduce-crossing-wall=1", "model.3mf"};
REQUIRE(config.read_cli(5, argv, &extra, &keys));
REQUIRE(config.opt<ConfigOptionInts>("nozzle_temperature")->values == std::vector<int>{210, 190});
REQUIRE(config.opt<ConfigOptionBool>("reduce_crossing_wall")->value);
REQUIRE(extra == t_config_option_keys{"model.3mf"});
REQUIRE(keys == t_config_option_keys{"nozzle_temperature", "reduce_crossing_wall"});
}
TEST_CASE("read_cli rejects nil for a non-nullable vector option", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--nozzle-temperature", "nil"};
REQUIRE_FALSE(config.read_cli(3, argv, &extra, &keys));
}
TEST_CASE("read_cli rejects an invalid boolean value", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--reduce-crossing-wall=maybe"};
REQUIRE_FALSE(config.read_cli(2, argv, &extra, &keys));
}
TEST_CASE("read_cli accepts the common spellings of a boolean value", "[Config]") {
const auto [text, expected] = GENERATE(table<const char*, bool>({
{"--reduce-crossing-wall=1", true},
{"--reduce-crossing-wall=true", true},
{"--reduce-crossing-wall=Yes", true},
{"--reduce-crossing-wall=on", true},
{"--reduce-crossing-wall=enabled", true},
{"--reduce-crossing-wall=TRUE", true},
{"--reduce-crossing-wall=oN", true},
{"--reduce-crossing-wall=0", false},
{"--reduce-crossing-wall=false", false},
{"--reduce-crossing-wall=No", false},
{"--reduce-crossing-wall=off", false},
{"--reduce-crossing-wall=disabled", false},
{"--reduce-crossing-wall=FALSE", false},
{"--reduce-crossing-wall=DiSaBlEd", false},
}));
DYNAMIC_SECTION(text) {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", text};
REQUIRE(config.read_cli(2, argv, &extra, &keys));
REQUIRE(config.opt<ConfigOptionBool>("reduce_crossing_wall")->value == expected);
}
}
TEST_CASE("read_cli accepts the common boolean spellings inside a bools vector", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--filament-soluble=true,no,1"};
REQUIRE(config.read_cli(2, argv, &extra, &keys));
REQUIRE(config.opt<ConfigOptionBools>("filament_soluble")->values == std::vector<unsigned char>{1, 0, 1});
}
TEST_CASE("read_cli trims whitespace around boolean spellings", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--reduce-crossing-wall= true ", "--filament-soluble= true , no ,1"};
REQUIRE(config.read_cli(3, argv, &extra, &keys));
REQUIRE(config.opt<ConfigOptionBool>("reduce_crossing_wall")->value);
REQUIRE(config.opt<ConfigOptionBools>("filament_soluble")->values == std::vector<unsigned char>{1, 0, 1});
}
TEST_CASE("read_cli normalizes boolean spellings when a bools vector is repeated", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--filament-soluble=true", "--filament-soluble=off"};
REQUIRE(config.read_cli(3, argv, &extra, &keys));
REQUIRE(config.opt<ConfigOptionBools>("filament_soluble")->values == std::vector<unsigned char>{1, 0});
}
TEST_CASE("read_cli keeps nil alongside boolean spellings in a nullable bools vector", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--enable-overhang-speed=nil,yes,off"};
REQUIRE(config.read_cli(2, argv, &extra, &keys));
auto* opt = config.opt<ConfigOptionBoolsNullable>("enable_overhang_speed");
REQUIRE(opt != nullptr);
REQUIRE(opt->values.size() == 3);
REQUIRE(opt->is_nil(0));
REQUIRE(opt->values[1] == 1);
REQUIRE(opt->values[2] == 0);
}
TEST_CASE("read_cli rejects an empty item inside a bools vector", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--filament-soluble=true,,1"};
REQUIRE_FALSE(config.read_cli(2, argv, &extra, &keys));
}
TEST_CASE("read_cli rejects an unknown spelling next to a valid one in a bools vector", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--filament-soluble=true,affirmative"};
REQUIRE_FALSE(config.read_cli(2, argv, &extra, &keys));
}
// The normalization lives in read_cli's boolean branches, so options of other types keep the
// value verbatim - a path named "on" or a colour named "true" must not turn into "1".
TEST_CASE("read_cli leaves boolean spellings alone for non-boolean options", "[Config]") {
SECTION("string option") {
Slic3r::DynamicPrintAndCLIConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--logfile=true"};
REQUIRE(config.read_cli(2, argv, &extra, &keys));
REQUIRE(config.opt<ConfigOptionString>("logfile")->value == "true");
}
SECTION("strings vector option") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--filament-colour=on;off"};
REQUIRE(config.read_cli(2, argv, &extra, &keys));
REQUIRE(config.opt<ConfigOptionStrings>("filament_colour")->values == std::vector<std::string>{"on", "off"});
}
}
TEST_CASE("read_cli treats a bare boolean flag as true without consuming the next argument", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--reduce-crossing-wall", "model.3mf"};
REQUIRE(config.read_cli(3, argv, &extra, &keys));
REQUIRE(config.opt<ConfigOptionBool>("reduce_crossing_wall")->value);
REQUIRE(extra == t_config_option_keys{"model.3mf"});
}
TEST_CASE("read_cli rejects an invalid scalar numeric value", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--top-shell-layers", "several"};
REQUIRE_FALSE(config.read_cli(3, argv, &extra, &keys));
}
TEST_CASE("read_cli appends values when a vector option is repeated", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--nozzle-temperature", "210", "--nozzle-temperature", "190,200"};
REQUIRE(config.read_cli(5, argv, &extra, &keys));
REQUIRE(config.opt<ConfigOptionInts>("nozzle_temperature")->values == std::vector<int>{210, 190, 200});
// the key is recorded once, on first use
REQUIRE(keys == t_config_option_keys{"nozzle_temperature"});
}
TEST_CASE("read_cli parses a bools vector given in the --flag=values form", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--filament-soluble=1,0,1"};
REQUIRE(config.read_cli(2, argv, &extra, &keys));
REQUIRE(config.opt<ConfigOptionBools>("filament_soluble")->values == std::vector<unsigned char>{1, 0, 1});
}
TEST_CASE("read_cli rejects an invalid value inside a bools vector", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--filament-soluble=1,maybe"};
REQUIRE_FALSE(config.read_cli(2, argv, &extra, &keys));
}
TEST_CASE("read_cli appends true for a bare bools vector flag", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--filament-soluble"};
REQUIRE(config.read_cli(2, argv, &extra, &keys));
REQUIRE(config.opt<ConfigOptionBools>("filament_soluble")->values == std::vector<unsigned char>{1});
}
TEST_CASE("read_cli splits a strings vector on semicolons and unescapes quoted items", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--filament-colour", "#FF0000;\"a\\nb\";#00FF00"};
REQUIRE(config.read_cli(3, argv, &extra, &keys));
auto& values = config.opt<ConfigOptionStrings>("filament_colour")->values;
REQUIRE(values == std::vector<std::string>{"#FF0000", "a\nb", "#00FF00"});
}
TEST_CASE("read_cli rejects a strings vector with an unterminated quote", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--filament-colour", "\"oops"};
REQUIRE_FALSE(config.read_cli(3, argv, &extra, &keys));
}
TEST_CASE("read_cli parses a points vector in the NxM coordinate form", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--printable-area", "0x0,200x0,200x200,0x200"};
REQUIRE(config.read_cli(3, argv, &extra, &keys));
auto& points = config.opt<ConfigOptionPoints>("printable_area")->values;
REQUIRE(points.size() == 4);
REQUIRE_THAT(points[1].x(), Catch::Matchers::WithinAbs(200.0, 1e-9));
REQUIRE_THAT(points[1].y(), Catch::Matchers::WithinAbs(0.0, 1e-9));
REQUIRE_THAT(points[3].x(), Catch::Matchers::WithinAbs(0.0, 1e-9));
REQUIRE_THAT(points[3].y(), Catch::Matchers::WithinAbs(200.0, 1e-9));
}
// logfile is a CLI-only option, so it needs the config type whose def pulls in cli_misc_config_def.
TEST_CASE("read_cli stores the log file path as a string", "[Config]") {
Slic3r::DynamicPrintAndCLIConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--logfile", "orca.log"};
REQUIRE(config.read_cli(3, argv, &extra, &keys));
REQUIRE(config.opt<ConfigOptionString>("logfile")->value == "orca.log");
}
TEST_CASE("read_cli accepts nil entries for a nullable vector option", "[Config]") {
Slic3r::DynamicPrintConfig config;
t_config_option_keys extra, keys;
const char* argv[] = {"orca-slicer", "--filament-retraction-length", "nil,2.5"};
REQUIRE(config.read_cli(3, argv, &extra, &keys));
auto* opt = config.opt<ConfigOptionFloatsNullable>("filament_retraction_length");
REQUIRE(opt != nullptr);
REQUIRE(opt->values.size() == 2);
REQUIRE(opt->is_nil(0));
REQUIRE_FALSE(opt->is_nil(1));
REQUIRE_THAT(opt->values[1], Catch::Matchers::WithinAbs(2.5, 1e-9));
}
// get_at() returns values.front() for an out-of-range index, so calling it on an empty vector
// option is UB. filament_id and filament_is_support are unpopulated on a CLI from-scratch slice.
TEST_CASE("get_filament_type treats empty vector options as absent", "[Config][Filament]")
{
DynamicPrintConfig config;
std::string displayed;
SECTION("an empty filament_type yields no type at all")
{
config.set_key_value("filament_type", new ConfigOptionStrings());
REQUIRE(config.get_filament_type(displayed, 0) == "");
}
SECTION("an empty filament_is_support falls back to the plain filament type")
{
config.set_key_value("filament_type", new ConfigOptionStrings({"PETG"}));
config.set_key_value("filament_is_support", new ConfigOptionBools());
REQUIRE(config.get_filament_type(displayed, 0) == "PETG");
REQUIRE(displayed == "PETG");
}
SECTION("a support filament with an empty filament_id resolves from the type alone")
{
config.set_key_value("filament_type", new ConfigOptionStrings({"PLA"}));
config.set_key_value("filament_is_support", new ConfigOptionBools({true}));
config.set_key_value("filament_id", new ConfigOptionStrings());
REQUIRE(config.get_filament_type(displayed, 0) == "PLA-S");
REQUIRE(displayed == "Sup.PLA");
}
SECTION("a populated filament_id still selects the support type by id")
{
config.set_key_value("filament_type", new ConfigOptionStrings({"PETG"}));
config.set_key_value("filament_is_support", new ConfigOptionBools({true}));
config.set_key_value("filament_id", new ConfigOptionStrings({"GFS00"}));
REQUIRE(config.get_filament_type(displayed, 0) == "PLA-S");
REQUIRE(displayed == "Sup.PLA");
}
}
@@ -130,6 +130,12 @@ TEST_CASE("get_config_index_base resolves (volume type, extruder type, id) to a
}
}
TEST_CASE("support interface pattern registry includes spiral inset", "[Config]")
{
const auto &values = ConfigOptionEnum<SupportMaterialInterfacePattern>::get_enum_values();
REQUIRE(values.at("spiralinset") == SupportMaterialInterfacePattern::smipSpiralInset);
}
TEST_CASE("get_extruder_nozzle_volume_count reads the per-extruder volume-type layout", "[Config]")
{
std::vector<std::vector<NozzleVolumeType>> nozzle_volume_types;
@@ -479,3 +485,84 @@ TEST_CASE("update_values_to_printer_extruders_for_multiple_filaments resolves pe
REQUIRE(config.option<ConfigOptionInts>("filament_self_index")->values == std::vector<int>({1, 2}));
}
}
// update_values_from_multi_to_multi_2 walks the DESTINATION PRINTER's variant list while writing
// into a row taken from the destination PRINT preset, whose arrays are sized to its own
// print_extruder_variant. Those two widths disagree until the print preset is re-selected for the
// new printer -- Tab::load_current_preset() runs this migration first -- so a project authored on
// a single-variant printer, opened and switched to a wider one, wrote past the end of the row.
TEST_CASE("update_values_from_multi_to_multi_2 sizes the destination row to the variant count",
"[Config][VariantExpansion]")
{
const std::vector<std::string> src_variants{"Direct Drive Standard"};
const std::vector<std::string> dst_variants{"Direct Drive Standard", "Direct Drive High Flow",
"Direct Drive Standard", "Direct Drive High Flow"};
const std::set<std::string> keys{"outer_wall_speed"};
// The per-object override as authored on the single-variant printer.
const auto object_override = [] {
DynamicPrintConfig c;
c.option<ConfigOptionFloatsNullable>("outer_wall_speed", true)->values = {42.};
return c;
};
SECTION("a row narrower than the variant list is grown, not overrun") {
DynamicPrintConfig object_config = object_override();
DynamicPrintConfig dst;
dst.option<ConfigOptionFloatsNullable>("outer_wall_speed", true)->values = {200.};
REQUIRE(object_config.update_values_from_multi_to_multi_2(src_variants, dst_variants, dst, keys) == 0);
const auto& out = object_config.option<ConfigOptionFloatsNullable>("outer_wall_speed")->values;
REQUIRE(out.size() == dst_variants.size());
// Both "Direct Drive Standard" columns match the source variant, so they take the override.
CHECK(out[0] == Catch::Approx(42.));
CHECK(out[2] == Catch::Approx(42.));
// The High Flow columns have no matching source variant: nil, so the destination keeps
// tracking the print preset rather than being pinned to another variant's value.
CHECK(std::isnan(out[1]));
CHECK(std::isnan(out[3]));
}
// The regression guard: where the row already matches the variant list -- every case that was
// not corrupting the heap -- the resize is a no-op and the output is unchanged.
SECTION("a correctly sized row is untouched") {
DynamicPrintConfig object_config = object_override();
DynamicPrintConfig dst;
dst.option<ConfigOptionFloatsNullable>("outer_wall_speed", true)->values = {200., 500., 210., 510.};
REQUIRE(object_config.update_values_from_multi_to_multi_2(src_variants, dst_variants, dst, keys) == 0);
const auto& out = object_config.option<ConfigOptionFloatsNullable>("outer_wall_speed")->values;
REQUIRE(out.size() == 4);
CHECK(out[0] == Catch::Approx(42.)); // matched -> override
CHECK(out[1] == Catch::Approx(500.)); // unmatched -> preset value preserved
CHECK(out[2] == Catch::Approx(42.));
CHECK(out[3] == Catch::Approx(510.));
}
// is_nil(idx) indexes values[idx] with no bounds check, so a source shorter than its own
// variant list read out of range before the guard was added.
SECTION("a source shorter than its variant list is read in range") {
DynamicPrintConfig object_config = object_override(); // one value...
DynamicPrintConfig dst;
dst.option<ConfigOptionFloatsNullable>("outer_wall_speed", true)->values = {200., 500.};
REQUIRE(object_config.update_values_from_multi_to_multi_2(
{"Direct Drive Standard", "Direct Drive Standard"}, // ...but two source variants
{"Direct Drive Standard", "Direct Drive High Flow"}, dst, keys) == 0);
const auto& out = object_config.option<ConfigOptionFloatsNullable>("outer_wall_speed")->values;
REQUIRE(out.size() == 2);
CHECK(out[0] == Catch::Approx(42.));
CHECK(out[1] == Catch::Approx(500.));
}
SECTION("an empty destination variant list is refused") {
DynamicPrintConfig object_config = object_override();
DynamicPrintConfig dst;
dst.option<ConfigOptionFloatsNullable>("outer_wall_speed", true)->values = {200.};
CHECK(object_config.update_values_from_multi_to_multi_2(src_variants, {}, dst, keys) == -1);
}
}
@@ -1,5 +1,6 @@
#include <catch2/catch_all.hpp>
#include <algorithm>
#include <boost/filesystem.hpp>
#include <fstream>
@@ -184,6 +185,44 @@ TEST_CASE("Printer extruder count tolerates missing nozzle diameter", "[Preset][
CHECK(bundle.get_printer_extruder_count() == 2);
}
TEST_CASE("Selected printer uses its default or saved bed type", "[Preset][Bundle]")
{
PresetBundle bundle;
Preset& printer = add_inmemory_preset(bundle.printers, "Test Printer");
printer.is_system = true;
printer.config.option<ConfigOptionString>("printer_model")->value = "TEST-MODEL";
printer.config.option<ConfigOptionString>("printer_variant")->value = "0.4";
printer.config.option<ConfigOptionString>("default_bed_type")->value = "Engineering Plate";
AppConfig app_config;
app_config.set("curr_bed_type", std::to_string(static_cast<int>(btPTE)));
PresetBundle::PresetPreferences preferred_selection;
BedType expected_bed_type;
SECTION("New printer uses its symbolic default") {
expected_bed_type = btEP;
preferred_selection = {"TEST-MODEL", "0.4"};
}
SECTION("Re-enabled printer uses its saved selection") {
expected_bed_type = btPC;
preferred_selection = {"TEST-MODEL", "0.4"};
app_config.set_printer_setting("Test Printer", "curr_bed_type",
std::to_string(static_cast<int>(expected_bed_type)));
}
SECTION("Existing printer keeps its saved selection after presets reload") {
expected_bed_type = btPCT;
app_config.set("presets", PRESET_PRINTER_NAME, "Test Printer");
app_config.set_printer_setting("Test Printer", "curr_bed_type",
std::to_string(static_cast<int>(expected_bed_type)));
}
bundle.load_selections(app_config, preferred_selection);
bundle.export_selections(app_config);
CHECK(bundle.project_config.opt_enum<BedType>("curr_bed_type") == expected_bed_type);
CHECK(app_config.get_printer_setting("Test Printer", "curr_bed_type") == std::to_string(static_cast<int>(expected_bed_type)));
}
TEST_CASE("find_preset resolves a system preset's renamed_from", "[Preset][Rename]")
{
RenameTestCollection coll;
@@ -567,6 +606,88 @@ TEST_CASE("A printer specific filament supersedes the generic library filament w
}
namespace {
// One system printer plus the filament presets a machine facing dialog has to choose between:
// an Orca Filament Library generic with no compatible_printers, a same alias vendor filament
// that names the printer, a library filament with no vendor twin, and a vendor filament that
// belongs to a different printer.
struct MachineFilaments
{
PresetBundle bundle;
VendorProfile library{PresetBundle::ORCA_FILAMENT_LIBRARY};
VendorProfile vendor{"Vendor"};
MachineFilaments()
{
// VendorProfile's constructor takes an id; the library rule keys off the name.
library.name = PresetBundle::ORCA_FILAMENT_LIBRARY;
vendor.name = "Vendor";
Preset &printer = add_inmemory_preset(bundle.printers, "Printer A 0.4 nozzle");
printer.is_system = true;
printer.vendor = &vendor;
printer.config.option<ConfigOptionString>("printer_model", true)->value = "Printer A";
add_filament(library, "Generic ABS @System", "Generic ABS", {});
add_filament(vendor, "Generic ABS @Printer A", "Generic ABS", { "Printer A 0.4 nozzle" });
add_filament(library, "FilAr ABS @System", "FilAr ABS", {});
add_filament(vendor, "Vendor PLA @Printer B", "Vendor PLA", { "Printer B 0.4 nozzle" });
// update_library_profile_excluded_from() is protected and has its own test above; record
// the exclusion it derives from the same alias vendor filament.
Preset *shadowed = bundle.filaments.find_preset("Generic ABS @System");
REQUIRE(shadowed != nullptr);
shadowed->m_excluded_from.insert("Printer A 0.4 nozzle");
}
void add_filament(const VendorProfile &owner, const std::string &name, const std::string &alias,
std::vector<std::string> compatible_printers)
{
Preset &preset = add_inmemory_preset(bundle.filaments, name);
preset.is_system = true;
preset.alias = alias;
preset.vendor = &owner;
compatible_list(bundle.filaments, name, "compatible_printers") = std::move(compatible_printers);
}
bool offers(const std::string &preset_name, bool include_user_presets = false)
{
const std::vector<Preset *> offered =
bundle.get_filament_presets_for_machine("Printer A", "0.4", include_user_presets);
return std::any_of(offered.begin(), offered.end(),
[&preset_name](const Preset *p) { return p->name == preset_name; });
}
};
} // namespace
TEST_CASE("Filaments offered for a machine follow the app's compatibility rule", "[Preset][Bundle]")
{
MachineFilaments f;
SECTION("a library filament with no compatible_printers is offered") {
CHECK(f.offers("FilAr ABS @System"));
}
SECTION("a same alias vendor filament shadows the library generic") {
CHECK(f.offers("Generic ABS @Printer A"));
CHECK_FALSE(f.offers("Generic ABS @System"));
}
SECTION("a filament naming a different printer is not offered") {
CHECK_FALSE(f.offers("Vendor PLA @Printer B"));
}
SECTION("a user filament is offered only when the printer supports user presets") {
add_inmemory_preset(f.bundle.filaments, "My PLA");
CHECK_FALSE(f.offers("My PLA", /*include_user_presets=*/false));
CHECK(f.offers("My PLA", /*include_user_presets=*/true));
}
}
namespace {
const char *kMixedKeys[] = {
+3 -3
View File
@@ -5,10 +5,10 @@
using namespace Slic3r;
// Golden vectors from the Python reference generate_preset_setting_id (defined in
// scripts/assign_vendor_setting_ids.py). The C++ generate_preset_setting_id() MUST stay
// byte-identical to it, otherwise app-side on-the-fly ids would diverge from the
// scripts/orca_id_tool.py). The C++ generate_preset_setting_id() MUST stay byte-identical
// to it, otherwise app-side on-the-fly ids would diverge from the
// script-assigned ones in the profiles. Regenerate a vector with:
// python3 -c "from assign_vendor_setting_ids import generate_preset_setting_id as g; print(g('Afinia','filament','Afinia ABS @Afinia H400'))"
// python3 -c "import sys; sys.path.insert(0, 'scripts'); from orca_id_tool import generate_preset_setting_id as g; print(g('Afinia','filament','Afinia ABS @Afinia H400'))"
TEST_CASE("preset setting_id matches the Python reference", "[Preset][setting_id]") {
struct Vec { const char* vendor; const char* type; const char* name; const char* expected; };
const Vec vectors[] = {
+2
View File
@@ -1,6 +1,8 @@
get_filename_component(_TEST_NAME ${CMAKE_CURRENT_LIST_DIR} NAME)
add_executable(${_TEST_NAME}_tests
${_TEST_NAME}_tests_main.cpp
test_bambu_filament_ids.cpp
test_creality_cfs_match.cpp
test_dev_mapping.cpp
test_filament_bitmap_utils.cpp
test_network_versions.cpp
+20
View File
@@ -34,4 +34,24 @@ struct ScopedDataDir
ScopedDataDir& operator=(const ScopedDataDir&) = delete;
};
// Point resources_dir() at a throwaway directory for the lifetime of a test and restore the
// previous value afterwards, mirroring ScopedDataDir.
struct ScopedResourcesDir
{
ScopedTemporaryDir tmp;
boost::filesystem::path dir;
std::string previous;
explicit ScopedResourcesDir(const std::string& tag)
: tmp("orca-" + tag), dir(tmp.path()), previous(resources_dir())
{
set_resources_dir(dir.string());
}
~ScopedResourcesDir() { set_resources_dir(previous); }
ScopedResourcesDir(const ScopedResourcesDir&) = delete;
ScopedResourcesDir& operator=(const ScopedResourcesDir&) = delete;
};
} // namespace Slic3r
@@ -0,0 +1,81 @@
#include <catch2/catch_all.hpp>
#include <boost/filesystem.hpp>
#include <boost/nowide/fstream.hpp>
#include <nlohmann/json.hpp>
#include "libslic3r/Utils.hpp"
#include "slic3r/Utils/BBLPrinterAgent.hpp"
#include "slic3r/Utils/OrcaPrinterAgent.hpp"
using json = nlohmann::json;
using namespace Slic3r;
namespace {
// Point resources_dir() at the repo's own tree for the lifetime of a test and restore it
// afterwards, mirroring ScopedResourcesDir (which only ever makes a throwaway directory).
// PROFILES_DIR is <repo>/resources/profiles; the map lives in <repo>/resources/printers.
struct ScopedRepoResourcesDir
{
std::string previous{resources_dir()};
ScopedRepoResourcesDir() { set_resources_dir(boost::filesystem::path(PROFILES_DIR).parent_path().string()); }
~ScopedRepoResourcesDir() { set_resources_dir(previous); }
ScopedRepoResourcesDir(const ScopedRepoResourcesDir&) = delete;
ScopedRepoResourcesDir& operator=(const ScopedRepoResourcesDir&) = delete;
};
std::string orca_id_of(const std::string& bambu_id)
{
boost::nowide::ifstream file(resources_dir() + "/printers/bambu_filament_ids.json");
json doc;
file >> doc;
for (const auto& [orca_id, row] : doc["filaments"].items())
if (row["bambu_id"] == bambu_id)
return orca_id;
FAIL("no map row for " << bambu_id);
return {};
}
} // namespace
TEST_CASE("Bambu filament id map is one-to-one and leaves unmapped ids alone", "[BambuFilamentIds]")
{
const ScopedRepoResourcesDir repo_resources;
const BBLPrinterAgent bbl;
const std::string abs = orca_id_of("GFB00"); // Bambu ABS
REQUIRE(abs.rfind("OF", 0) == 0);
CHECK(bbl.from_orca_filament_id(abs) == "GFB00");
CHECK(bbl.to_orca_filament_id("GFB00") == abs);
CHECK(bbl.from_orca_filament_id("OFnotarow") == "OFnotarow");
CHECK(bbl.to_orca_filament_id("GFZZ99") == "GFZZ99"); // Bambu id we do not ship
CHECK(bbl.to_orca_filament_id("P1234567") == "P1234567"); // user root
CHECK(bbl.from_orca_filament_id("") == "");
// An agent whose printers already speak our ids inherits IPrinterAgent's identity default.
const OrcaPrinterAgent other{""};
CHECK(other.from_orca_filament_id(abs) == abs);
CHECK(other.to_orca_filament_id("GFB00") == "GFB00");
}
TEST_CASE("Payload rewrite covers nested trays, calibration lists and mapping info", "[BambuFilamentIds]")
{
const ScopedRepoResourcesDir repo_resources;
const std::string abs = orca_id_of("GFB00"), pla = orca_id_of("GFA00");
const std::string status =
R"({"print":{"ams":{"ams":[{"tray":[{"tray_info_idx":"GFB00"},{"tray_info_idx":"GFZZ99"}]}]},)"
R"("vt_tray":{"tray_info_idx":"GFA00"},"filaments":[{"filament_id":"GFA00","setting_id":"GFB00"}]}})";
json inbound = json::parse(BBLPrinterAgent::to_orca_payload(status));
CHECK(inbound["print"]["ams"]["ams"][0]["tray"][0]["tray_info_idx"] == abs);
CHECK(inbound["print"]["ams"]["ams"][0]["tray"][1]["tray_info_idx"] == "GFZZ99"); // no row: untouched
CHECK(inbound["print"]["vt_tray"]["tray_info_idx"] == pla);
CHECK(inbound["print"]["filaments"][0]["filament_id"] == pla);
CHECK(inbound["print"]["filaments"][0]["setting_id"] == "GFB00"); // not an id key: has a map row but must stay put
CHECK(json::parse(BBLPrinterAgent::from_orca_payload(inbound.dump())) == json::parse(status)); // round trip
const std::string mapping = R"([{"ams":0,"filamentId":")" + abs + R"(","filamentType":"ABS"}])";
CHECK(BBLPrinterAgent::from_orca_payload(mapping) == R"([{"ams":0,"filamentId":"GFB00","filamentType":"ABS"}])");
CHECK(BBLPrinterAgent::from_orca_payload("not json") == "not json");
CHECK(BBLPrinterAgent::from_orca_payload(R"({"print":{"command":"pushall"}})") == R"({"print":{"command":"pushall"}})");
}
@@ -0,0 +1,141 @@
#include <catch2/catch_test_macros.hpp>
#include "libslic3r/Preset.hpp"
#include "libslic3r/PresetBundle.hpp"
#include "libslic3r/PrintConfig.hpp"
#include "slic3r/Utils/CrealityPrintAgent.hpp"
using namespace Slic3r;
namespace {
// A standalone filament collection, built the same way PresetBundle builds its own, so the
// CFS matcher can be exercised without loading the shipped profiles or touching a printer.
struct FilamentTestCollection : public PresetCollection
{
FilamentTestCollection()
: PresetCollection(Preset::TYPE_FILAMENT, Preset::filament_options(),
static_cast<const PrintRegionConfig &>(FullPrintConfig::defaults()))
{}
};
struct FilamentSpec
{
const char *name;
const char *filament_id;
const char *filament_type;
bool is_library = false; // belongs to the Orca Filament Library, not the printer vendor
bool is_system = true;
};
// Load the specs into the collection, then stamp the fields the matcher reads. Done in a second
// pass because load_preset() keeps m_presets sorted, so a reference taken during the first pass
// can be left dangling by a later load.
void populate(PresetCollection &filaments, const std::vector<FilamentSpec> &specs,
const VendorProfile &vendor, const VendorProfile &library)
{
for (const FilamentSpec &spec : specs) {
DynamicPrintConfig config(filaments.default_preset().config);
config.option<ConfigOptionStrings>("filament_type", true)->values = {spec.filament_type};
filaments.load_preset(std::string(), spec.name, config, /*select=*/false);
}
for (auto it = filaments.begin(); it != filaments.end(); ++it) {
const auto spec = std::find_if(specs.begin(), specs.end(),
[&](const FilamentSpec &s) { return it->name == s.name; });
if (spec == specs.end())
continue;
it->filament_id = spec->filament_id;
it->vendor = spec->is_library ? &library : &vendor;
it->is_system = spec->is_system;
it->is_default = false;
it->is_visible = true;
it->is_compatible = true;
}
}
// What a stock K2 with a 0.4 nozzle sees after the filament_id rework: the vendor's plain generics
// carry no "Creality" in their name (they are "Generic <material> @<scope>"), while the subtype
// variants that do keep a vendor scope are separate products with their own filament_ids.
const std::vector<FilamentSpec> k2_stock_nozzle{
{"AliZ PLA @System", "ALIZ-PLA", "PLA", /*is_library=*/true},
{"Generic PETG @K2-all", "PETG-GENERIC", "PETG"},
{"Generic PLA @K2-all", "PLA-GENERIC", "PLA"},
{"Generic PLA High Speed @Creality K2-all","PLA-HS", "PLA"},
{"Generic PLA Matte @Creality K2-all", "PLA-MATTE", "PLA"},
{"Generic PLA Silk @Creality K2-all", "PLA-SILK", "PLA"},
{"Hyper PLA @K2-all", "PLA-HYPER", "PLA"},
};
std::string match(const std::vector<FilamentSpec> &specs, const std::string &spool_vendor,
const std::string &spool_name, const std::string &base_type)
{
FilamentTestCollection filaments;
VendorProfile vendor("Creality");
VendorProfile library(PresetBundle::ORCA_FILAMENT_LIBRARY);
vendor.name = "Creality";
library.name = PresetBundle::ORCA_FILAMENT_LIBRARY;
populate(filaments, specs, vendor, library);
return CrealityPrintAgent::match_filament_preset(filaments, spool_vendor, spool_name, base_type);
}
} // namespace
// Orca: a CFS spool that names no recognised product must map to the vendor's plain generic. The
// subtype variants ("High Speed", "Matte", "Silk") score just as well on vendor alone, and since
// each is its own product with its own filament_id, letting one of them win sends the printer the
// id of a filament the user does not have loaded.
TEST_CASE("An unbranded CFS spool maps to the vendor's plain generic, not a subtype", "[CFS][Creality]")
{
CHECK(match(k2_stock_nozzle, "Creality", "", "PLA") == "PLA-GENERIC");
}
// Orca: the vendor bonus reads the preset's owning VendorProfile. "Generic PETG @K2-all" does not
// repeat "Creality" anywhere in its name, so a name based vendor test scored nothing for it and the
// spool fell through to the collection wide first-of-type - an unrelated third party PETG.
TEST_CASE("A CFS spool matches its vendor's presets even when the name omits the vendor", "[CFS][Creality]")
{
CHECK(match(k2_stock_nozzle, "Creality", "", "PETG") == "PETG-GENERIC");
}
TEST_CASE("A branded CFS spool still beats the generic", "[CFS][Creality]")
{
CHECK(match(k2_stock_nozzle, "Creality", "Hyper PLA", "PLA") == "PLA-HYPER");
}
// Orca: the specificity penalty must not stop a spool that genuinely asks for a subtype from
// getting it - only unclaimed qualifiers are penalised.
TEST_CASE("A CFS spool that names a subtype gets that subtype", "[CFS][Creality]")
{
CHECK(match(k2_stock_nozzle, "Creality", "Generic PLA Silk", "PLA") == "PLA-SILK");
CHECK(match(k2_stock_nozzle, "Creality", "Generic PLA Matte", "PLA") == "PLA-MATTE");
}
// Orca: a third party spool matches no preset by brand or vendor, so it falls back to the first
// visible preset of the same type rather than returning nothing. Which one that is depends on the
// collection's ordering, so only the type is pinned here - what matters is that a PLA spool never
// comes back empty and never comes back as another material.
TEST_CASE("A CFS spool from an unknown vendor falls back to a preset of the same type", "[CFS][Creality]")
{
const std::string matched = match(k2_stock_nozzle, "SomeOtherBrand", "", "PLA");
REQUIRE_FALSE(matched.empty());
const auto spec = std::find_if(k2_stock_nozzle.begin(), k2_stock_nozzle.end(),
[&](const FilamentSpec &s) { return matched == s.filament_id; });
REQUIRE(spec != k2_stock_nozzle.end());
CHECK(std::string(spec->filament_type) == "PLA");
}
// Orca: Creality's bundle also ships third party filaments ("eSUN PLA+ @K2 Plus-all"). Those carry
// Creality's VendorProfile but name their real brand, so the vendor bonus has to accept a name
// match as well as a profile match - otherwise an eSUN spool stops matching its own preset.
TEST_CASE("A third party spool matches its preset inside the printer vendor's bundle", "[CFS][Creality]")
{
const std::vector<FilamentSpec> with_third_party{
{"Generic PLA @K2-all", "PLA-GENERIC", "PLA"},
{"eSUN PLA+ @K2 Plus-all", "ESUN-PLA", "PLA"}, // shipped by Creality, branded eSUN
};
CHECK(match(with_third_party, "eSUN", "", "PLA") == "ESUN-PLA");
// ... and a Creality spool still prefers Creality's own generic over the eSUN preset, which
// carries Creality's profile too but adds a brand word the spool never claimed.
CHECK(match(with_third_party, "Creality", "", "PLA") == "PLA-GENERIC");
}
+159 -8
View File
@@ -27,6 +27,16 @@ void seed_denied_names()
mgr.add_denied_filename(name);
}
// Seed the keyword registry with the same list install_hook() uses. Same rationale as
// seed_denied_names(): a process-singleton registry, seeded from the single shared source so
// production and tests cannot drift apart.
void seed_denied_keywords()
{
PluginAuditManager& mgr = PluginAuditManager::instance();
for (const auto& keyword : PluginAuditManager::default_denied_path_keywords())
mgr.add_denied_path_keyword(keyword);
}
} // namespace
TEST_CASE("Plugin audit denies app config and token filenames anywhere", "[audit]")
@@ -81,7 +91,7 @@ TEST_CASE("Plugin audit denies app config and token filenames anywhere", "[audit
}
}
TEST_CASE("Plugin audit deny beats allowed roots and the Loading read exemption", "[audit]")
TEST_CASE("Plugin audit deny beats allowed roots", "[audit]")
{
ScopedDataDir data_dir_guard("plugin-audit-deny");
seed_denied_names();
@@ -91,8 +101,8 @@ TEST_CASE("Plugin audit deny beats allowed roots and the Loading read exemption"
// config and the token would otherwise be reachable simply by living inside it.
mgr.add_global_allowed_root(data_dir());
// Enter a plugin context. The deny must hold in Loading mode, which every scope runs in.
ScopedPluginAuditContext ctx("test_plugin", "", PluginAuditManager::AuditMode::Loading);
// Enter a plugin context. The deny must hold even inside a globally allowed root.
ScopedPluginAuditContext ctx("test_plugin", "");
const fs::path conf = fs::path(data_dir()) / (SLIC3R_APP_KEY ".conf");
const fs::path token = fs::path(data_dir()) / secret_constants::USER_SECRET_FILENAME;
@@ -103,6 +113,13 @@ TEST_CASE("Plugin audit deny beats allowed roots and the Loading read exemption"
CHECK(decision.allowed);
}
SECTION("a file outside the allowed root is blocked for reads as well as writes")
{
AuditDecision decision = mgr.check_open((fs::path(data_dir()).parent_path() / "outside.txt").string(), "r");
CHECK_FALSE(decision.allowed);
CHECK(decision.reason == "outside allowed root");
}
SECTION("writing the app config is blocked despite data_dir() being allowed")
{
AuditDecision decision = mgr.check_open(conf.string(), "w");
@@ -110,16 +127,14 @@ TEST_CASE("Plugin audit deny beats allowed roots and the Loading read exemption"
CHECK(decision.reason == "denied filename");
}
SECTION("reading the app config is blocked even though Loading exempts reads")
SECTION("reading the app config is blocked despite the allowed root")
{
// Without the deny, a read in Loading mode short-circuits to allow. The deny sits above
// that exemption, so this must still be blocked.
AuditDecision decision = mgr.check_open(conf.string(), "r");
CHECK_FALSE(decision.allowed);
CHECK(decision.reason == "denied filename");
}
SECTION("reading the cloud refresh token is blocked in Loading mode")
SECTION("reading the cloud refresh token is blocked")
{
AuditDecision decision = mgr.check_open(token.string(), "r");
CHECK_FALSE(decision.allowed);
@@ -150,7 +165,7 @@ TEST_CASE("Plugin audit deny beats a plugin's own scoped root", "[audit]")
const fs::path plugin_dir = fs::path(data_dir()) / "plugins" / "test_plugin";
fs::create_directories(plugin_dir);
ScopedPluginAuditContext ctx("test_plugin", "", PluginAuditManager::AuditMode::Loading);
ScopedPluginAuditContext ctx("test_plugin", "");
mgr.add_scoped_allowed_root(plugin_dir);
SECTION("the plugin's own non-denied file opens for read and write")
@@ -185,3 +200,139 @@ TEST_CASE("Plugin audit does not constrain non-plugin code", "[audit]")
CHECK(mgr.check_open(conf.string(), "w").allowed);
CHECK(mgr.check_open(conf.string(), "r").allowed);
}
TEST_CASE("Plugin audit denies secret/certificate/config-like paths by keyword", "[audit]")
{
seed_denied_keywords();
const PluginAuditManager& mgr = PluginAuditManager::instance();
SECTION("a 'secrets' directory component is denied")
{
CHECK(mgr.is_denied_path_keyword(fs::path("/plugin/secrets/api_key.json")));
CHECK(mgr.is_denied_path_keyword(fs::path("/plugin/secret/token.txt")));
}
SECTION("a 'certificate(s)' directory component is denied")
{
CHECK(mgr.is_denied_path_keyword(fs::path("/resources/cert/slicer_base64.cer")));
CHECK(mgr.is_denied_path_keyword(fs::path("/resources/certificates/ca.pem")));
}
SECTION("a 'conf'/'config' directory or file component is denied")
{
CHECK(mgr.is_denied_path_keyword(fs::path("/plugin/conf/settings.json")));
CHECK(mgr.is_denied_path_keyword(fs::path("/plugin/config/settings.json")));
CHECK(mgr.is_denied_path_keyword(fs::path("/plugin/plugin.conf")));
}
SECTION("matching is case-insensitive")
{
CHECK(mgr.is_denied_path_keyword(fs::path("/plugin/SECRETS/token.txt")));
CHECK(mgr.is_denied_path_keyword(fs::path("/resources/CertBundle/ca.pem")));
CHECK(mgr.is_denied_path_keyword(fs::path("/plugin/CONFIG.JSON")));
}
SECTION("matching is not limited to the base name -- any ancestor component counts")
{
CHECK(mgr.is_denied_path_keyword(fs::path("/data/secrets/nested/deep/file.txt")));
}
SECTION("an unrelated path is not denied")
{
CHECK_FALSE(mgr.is_denied_path_keyword(fs::path("/plugin/output/model.gcode")));
CHECK_FALSE(mgr.is_denied_path_keyword(fs::path("/plugin/storage/state.json")));
}
SECTION("an empty path is not denied")
{
CHECK_FALSE(mgr.is_denied_path_keyword(fs::path()));
}
}
TEST_CASE("Plugin audit is_denied_path combines the filename and keyword registries", "[audit]")
{
seed_denied_names();
seed_denied_keywords();
const PluginAuditManager& mgr = PluginAuditManager::instance();
SECTION("a filename-registry match is denied")
{
CHECK(mgr.is_denied_path(fs::path(SLIC3R_APP_KEY ".conf")));
}
SECTION("a keyword-registry match is denied")
{
CHECK(mgr.is_denied_path(fs::path("/plugin/secrets/token.txt")));
}
SECTION("a path matching neither registry is not denied")
{
CHECK_FALSE(mgr.is_denied_path(fs::path("/plugin/output/model.gcode")));
}
}
TEST_CASE("Plugin audit a read-only allowed root blocks writes but not reads", "[audit]")
{
ScopedDataDir data_dir_guard("plugin-audit-readonly");
ScopedResourcesDir resources_dir_guard("plugin-audit-readonly-resources");
seed_denied_names();
seed_denied_keywords();
PluginAuditManager& mgr = PluginAuditManager::instance();
mgr.add_global_allowed_root(resources_dir(), /*allow_write=*/false);
ScopedPluginAuditContext ctx("test_plugin", "");
const fs::path readonly_file = fs::path(resources_dir()) / "profiles" / "vendor.json";
SECTION("a read inside the read-only root is allowed")
{
CHECK(mgr.check_open(readonly_file.string(), "r").allowed);
}
SECTION("a write inside the read-only root is blocked")
{
AuditDecision decision = mgr.check_open(readonly_file.string(), "w");
CHECK_FALSE(decision.allowed);
CHECK(decision.reason == "outside allowed root");
}
SECTION("a create inside the read-only root is blocked")
{
AuditDecision decision = mgr.check_path_access(readonly_file, /*is_write=*/true);
CHECK_FALSE(decision.allowed);
}
SECTION("the bundled cert underneath the read-only root is denied even for reads")
{
const fs::path cert = fs::path(resources_dir()) / "cert" / "slicer_base64.cer";
AuditDecision decision = mgr.check_open(cert.string(), "r");
CHECK_FALSE(decision.allowed);
CHECK(decision.reason == "denied path keyword");
}
}
TEST_CASE("Plugin audit a scoped root can also be registered read-only", "[audit]")
{
ScopedDataDir data_dir_guard("plugin-audit-scoped-readonly");
seed_denied_names();
seed_denied_keywords();
PluginAuditManager& mgr = PluginAuditManager::instance();
const fs::path readonly_dir = fs::path(data_dir()) / "readonly_scope";
fs::create_directories(readonly_dir);
ScopedPluginAuditContext ctx("test_plugin", "");
mgr.add_scoped_allowed_root(readonly_dir, /*allow_write=*/false);
SECTION("a read inside the scoped read-only root is allowed")
{
CHECK(mgr.check_open((readonly_dir / "vendor.json").string(), "r").allowed);
}
SECTION("a write inside the scoped read-only root is blocked")
{
CHECK_FALSE(mgr.check_open((readonly_dir / "vendor.json").string(), "w").allowed);
}
}
+17 -1
View File
@@ -112,6 +112,22 @@ TEST_CASE("install-state sidecar is the source of truth for a cloud plugin's ins
REQUIRE(read_install_state(plugin_dir, state));
CHECK(state.installed_version == "1.2.0");
state.permissions.fs_read = {"/path/to/read"};
state.permissions.fs_readwrite = {"/path/to/readwrite"};
state.permissions.network_http = {"https://api.example.com"};
state.permissions.network_socket = {"192.168.45.6:443"};
state.permissions.process = {"/usr/bin/curl"};
REQUIRE(write_install_state(plugin_dir, state));
// Permission data is persisted in the same sidecar as the installation metadata.
PluginInstallState persisted;
REQUIRE(read_install_state(plugin_dir, persisted));
CHECK(persisted.permissions.fs_read == state.permissions.fs_read);
CHECK(persisted.permissions.fs_readwrite == state.permissions.fs_readwrite);
CHECK(persisted.permissions.network_http == state.permissions.network_http);
CHECK(persisted.permissions.network_socket == state.permissions.network_socket);
CHECK(persisted.permissions.process == state.permissions.process);
// Reading the sidecar back onto a freshly-scanned descriptor (whose header version is still
// 1.0.0) must surface the cloud-installed 1.2.0. This is what lets update_cloud_metadata compare
// the cloud's latest version against the installed version instead of the stale header, so an
@@ -120,4 +136,4 @@ TEST_CASE("install-state sidecar is the source of truth for a cloud plugin's ins
scanned.version = "1.0.0"; // as parsed from the unchanged PEP723 header
read_install_state(plugin_dir, scanned);
CHECK(scanned.installed_version == "1.2.0");
}
}