mirror of
https://github.com/OrcaSlicer/OrcaSlicer.git
synced 2026-09-27 02:41:17 +00:00
Merge branch 'main' into feature/texture_displacement
This commit is contained in:
+4
-3
@@ -10,16 +10,17 @@ Rules for writing tests under `tests/`. [CATCH2.md](CATCH2.md) is the Catch2 ref
|
||||
- `libnest2d`: 2D nesting and packing.
|
||||
- `slic3rutils`: the Python plugin system and its slicing-pipeline bindings.
|
||||
- `filament_group`: filament-to-extruder grouping, checked against golden files.
|
||||
- `cli`: end-to-end runs of the built `orca-slicer` binary, Linux only. These tests carry the `RequiresApp` label, which the CI unit-test job excludes because it receives only `build/tests`; run them with `ctest --test-dir build/tests -C Release -L RequiresApp`.
|
||||
|
||||
## Building and running
|
||||
|
||||
Tests are off by default, so the build has to be told to include them.
|
||||
|
||||
- Windows: `build_release_vs.bat tests`, then `ctest --test-dir build/tests -C Release`
|
||||
- Windows: `build_win.bat -ds --run-tests`, which builds the dependencies and the tests and runs them (`-l -x` for the clang-cl and Ninja build CI uses)
|
||||
- macOS: `./build_release_macos.sh -s -a arm64 -T`, which builds and runs them
|
||||
- Linux: `./build_linux.sh -t`, then `ctest --test-dir build/tests`
|
||||
- Linux: `./build_linux.sh -t`, then `ctest --test-dir build/tests -C Release`
|
||||
|
||||
Rebuild a single suite with `cmake --build build --config Release --target <suite>_tests`. Visual Studio and Xcode are multi-configuration generators, so `ctest` needs `-C` there; on Linux it does not.
|
||||
Rebuild a single suite with `cmake --build build --config Release --target <suite>_tests`. Visual Studio, Xcode and the Ninja Multi-Config generator that `build_linux.sh` uses are all multi-configuration, so `ctest` needs `-C` on every platform; without it, tests registered with plain `add_test()` lose their labels and report "Not Run".
|
||||
|
||||
## Where a test goes
|
||||
|
||||
|
||||
@@ -85,4 +85,9 @@ add_subdirectory(fff_print)
|
||||
add_subdirectory(sla_print)
|
||||
add_subdirectory(filament_group)
|
||||
|
||||
# End-to-end checks of the orca-slicer binary. Linux only: they read result.json, which the CLI
|
||||
# writes on Linux only. src/ is added before tests/, so the target is known here.
|
||||
if (UNIX AND NOT APPLE AND TARGET OrcaSlicer)
|
||||
add_subdirectory(cli)
|
||||
endif ()
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# Runs the real orca-slicer binary, so it needs the built app and resources/, not just build/tests.
|
||||
# The CI unit-test job only receives build/tests, so the test carries the RequiresApp label that
|
||||
# scripts/run_unit_tests.sh excludes. Run it with `ctest -C Release -L RequiresApp`. It also exits 77
|
||||
# (skipped) when the binary is missing.
|
||||
|
||||
find_program(ORCA_CLI_TEST_PYTHON NAMES python3)
|
||||
if (NOT ORCA_CLI_TEST_PYTHON)
|
||||
message(STATUS "python3 not found, not registering the CLI tests")
|
||||
return()
|
||||
endif ()
|
||||
|
||||
add_test(NAME cli_strict_mode
|
||||
COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/test_cli_strict.sh $<TARGET_FILE:OrcaSlicer> ${ORCA_CLI_TEST_PYTHON})
|
||||
set_tests_properties(cli_strict_mode PROPERTIES
|
||||
LABELS "CLI;RequiresApp"
|
||||
SKIP_RETURN_CODE 77
|
||||
TIMEOUT 900)
|
||||
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env bash
|
||||
# End-to-end check of the CLI --strict option against the real orca-slicer binary.
|
||||
#
|
||||
# A model with a large unsupported overhang, sliced with support off, raises the NON_CRITICAL
|
||||
# "support needed" slicing warning. The CLI lists it in result.json's "warnings" array, and with
|
||||
# --strict it also fails the run with CLI_SLICING_ERROR. --strict with --no-check is rejected up
|
||||
# front, because --no-check skips that check.
|
||||
#
|
||||
# usage: test_cli_strict.sh <orca-slicer binary> <python3>
|
||||
set -u
|
||||
|
||||
BIN="${1:-}"
|
||||
PY="${2:-python3}"
|
||||
# 77 is the test's SKIP_RETURN_CODE.
|
||||
[ -x "$BIN" ] || { echo "SKIP: orca-slicer binary not found: $BIN"; exit 77; }
|
||||
|
||||
# From src/libslic3r/Utils.hpp. main() returns them, so the shell sees them modulo 256.
|
||||
CLI_SUCCESS=0
|
||||
CLI_INVALID_PARAMS=-2
|
||||
CLI_SLICING_ERROR=-100
|
||||
|
||||
WORK="$(mktemp -d "${TMPDIR:-/tmp}/orca-cli-strict.XXXXXX")"
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
mkdir -p "$WORK/datadir"
|
||||
|
||||
# Standalone presets: without "inherits" the CLI loads them as-is, with no preset bundle.
|
||||
cat > "$WORK/machine.json" <<'EOF'
|
||||
{
|
||||
"type": "machine",
|
||||
"from": "User",
|
||||
"name": "CLI strict test printer",
|
||||
"printable_area": ["0x0", "200x0", "200x200", "0x200"],
|
||||
"printable_height": "100",
|
||||
"layer_change_gcode": "G92 E0"
|
||||
}
|
||||
EOF
|
||||
cat > "$WORK/process.json" <<'EOF'
|
||||
{
|
||||
"type": "process",
|
||||
"from": "User",
|
||||
"name": "CLI strict test process",
|
||||
"enable_support": "0",
|
||||
"enforce_support_layers": "0"
|
||||
}
|
||||
EOF
|
||||
|
||||
# A 40x40mm cap on an 8x8mm stem: the cap reaches ~22mm past the stem, beyond the 6mm
|
||||
# cantilever limit of PrintObject::is_support_necessary().
|
||||
"$PY" - "$WORK/capital.stl" <<'EOF'
|
||||
import sys
|
||||
|
||||
def box(x0, y0, z0, x1, y1, z1):
|
||||
v = [(x, y, z) for z in (z0, z1) for y in (y0, y1) for x in (x0, x1)]
|
||||
# Faces wound counter-clockwise seen from outside: -z, +z, -y, +y, -x, +x.
|
||||
for a, b, c, d in ((0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)):
|
||||
yield v[a], v[b], v[c]
|
||||
yield v[a], v[c], v[d]
|
||||
|
||||
with open(sys.argv[1], "w") as f:
|
||||
f.write("solid capital\n")
|
||||
for tri in (*box(16, 16, 0, 24, 24, 13), *box(0, 0, 12, 40, 40, 14)):
|
||||
f.write("facet normal 0 0 0\nouter loop\n")
|
||||
for p in tri:
|
||||
f.write("vertex %g %g %g\n" % p)
|
||||
f.write("endloop\nendfacet\n")
|
||||
f.write("endsolid capital\n")
|
||||
EOF
|
||||
|
||||
fails=0
|
||||
fail() { echo "FAIL: $*"; fails=$((fails + 1)); }
|
||||
|
||||
# run <tag> [option...]: slice into $WORK/<tag>, keeping the log and the shell status there.
|
||||
run() {
|
||||
local out="$WORK/$1"; shift
|
||||
mkdir -p "$out"
|
||||
timeout 300 "$BIN" --datadir "$WORK/datadir" --load-settings "$WORK/machine.json;$WORK/process.json" \
|
||||
"$@" --slice 0 --outputdir "$out" "$WORK/capital.stl" > "$out/log" 2>&1
|
||||
echo $? > "$out/status"
|
||||
}
|
||||
|
||||
# expect_status <tag> <cli code>
|
||||
expect_status() {
|
||||
local got; got="$(cat "$WORK/$1/status")"
|
||||
[ "$got" -eq $(( $2 & 255 )) ] || fail "$1: shell status $got, want $(( $2 & 255 )) (code $2)"
|
||||
}
|
||||
|
||||
# expect_gcode <tag> yes|no
|
||||
expect_gcode() {
|
||||
if compgen -G "$WORK/$1/*.gcode" > /dev/null; then
|
||||
[ "$2" = yes ] || fail "$1: G-code was exported"
|
||||
else
|
||||
[ "$2" = no ] || fail "$1: no G-code was exported"
|
||||
fi
|
||||
}
|
||||
|
||||
# expect_result <tag> <return_code> <strict_mode true|false> <non-critical warning: some|none>
|
||||
expect_result() {
|
||||
"$PY" - "$WORK/$1/result.json" "$2" "$3" "$4" <<'EOF' || fail "$1: result.json"
|
||||
import json, sys
|
||||
|
||||
path, want_rc, want_strict, want_warning = sys.argv[1], int(sys.argv[2]), sys.argv[3] == "true", sys.argv[4]
|
||||
try:
|
||||
with open(path) as f:
|
||||
result = json.load(f)
|
||||
except (OSError, ValueError) as e:
|
||||
sys.exit("cannot read %s: %s" % (path, e))
|
||||
|
||||
errors = []
|
||||
if result.get("return_code") != want_rc:
|
||||
errors.append("return_code %r, want %d" % (result.get("return_code"), want_rc))
|
||||
if result.get("strict_mode") is not want_strict:
|
||||
errors.append("strict_mode %r, want %r" % (result.get("strict_mode"), want_strict))
|
||||
warnings = result.get("warnings")
|
||||
if not isinstance(warnings, list):
|
||||
errors.append("warnings %r is not a list" % (warnings,))
|
||||
else:
|
||||
found = any(isinstance(w, dict) and w.get("class") == "slicing_warning_non_critical" for w in warnings)
|
||||
if found != (want_warning == "some"):
|
||||
errors.append("warnings %r, want %s slicing_warning_non_critical" % (warnings, want_warning))
|
||||
for e in errors:
|
||||
print(e)
|
||||
sys.exit(1 if errors else 0)
|
||||
EOF
|
||||
}
|
||||
|
||||
echo "== without --strict the warning is listed and the slice succeeds"
|
||||
run plain
|
||||
expect_status plain $CLI_SUCCESS
|
||||
expect_result plain $CLI_SUCCESS false some
|
||||
expect_gcode plain yes
|
||||
|
||||
echo "== --strict fails the run on the same warning, before G-code export"
|
||||
run strict --strict
|
||||
expect_status strict $CLI_SLICING_ERROR
|
||||
expect_result strict $CLI_SLICING_ERROR true some
|
||||
expect_gcode strict no
|
||||
|
||||
echo "== --strict with --no-check is rejected before slicing"
|
||||
run conflict --strict --no-check
|
||||
expect_status conflict $CLI_INVALID_PARAMS
|
||||
expect_result conflict $CLI_INVALID_PARAMS true none
|
||||
expect_gcode conflict no
|
||||
grep -q -- "--strict cannot be combined with --no-check" "$WORK/conflict/log" \
|
||||
|| fail "conflict: error message missing"
|
||||
|
||||
if [ "$fails" -ne 0 ]; then
|
||||
for log in "$WORK"/*/log; do
|
||||
echo "--- $log"
|
||||
tail -n 40 "$log"
|
||||
done
|
||||
exit 1
|
||||
fi
|
||||
echo "PASS"
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -19,7 +19,9 @@ 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.cpp
|
||||
test_wipe_tower.cpp
|
||||
)
|
||||
target_link_libraries(${_TEST_NAME}_tests test_common libslic3r Catch2::Catch2WithMain)
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -9,11 +9,13 @@
|
||||
#include <vector>
|
||||
|
||||
#include "libslic3r/ClipperUtils.hpp"
|
||||
#include "libslic3r/AABBTreeLines.hpp"
|
||||
#include "libslic3r/Fill/Fill.hpp"
|
||||
#include "libslic3r/Flow.hpp"
|
||||
#include "libslic3r/Geometry.hpp"
|
||||
#include "libslic3r/Layer.hpp"
|
||||
#include "libslic3r/Print.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
#include "libslic3r/SVG.hpp"
|
||||
#include "libslic3r/libslic3r.h"
|
||||
|
||||
@@ -675,6 +677,73 @@ TEST_CASE("Ironing follows the solid infill rotation template", "[Fill]")
|
||||
REQUIRE(compared > int(ironing.size()) / 2);
|
||||
}
|
||||
|
||||
|
||||
namespace {
|
||||
|
||||
PrintRegionConfig ironing_config(IroningType type,
|
||||
int top_surface_filament_id = 1,
|
||||
int top_shell_layers = 3,
|
||||
int bottom_shell_layers = 1)
|
||||
{
|
||||
PrintRegionConfig cfg;
|
||||
cfg.ironing_type.value = type;
|
||||
cfg.top_surface_filament_id.value = top_surface_filament_id;
|
||||
cfg.top_shell_layers.value = top_shell_layers;
|
||||
cfg.bottom_shell_layers.value = bottom_shell_layers;
|
||||
cfg.outer_wall_filament_id.value = 1;
|
||||
cfg.wall_loops.value = 2;
|
||||
return cfg;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Ironing an all-solid region uses the top surface filament on every layer", "[Fill]")
|
||||
{
|
||||
const PrintRegionConfig cfg = ironing_config(IroningType::AllSolid, /*top_surface_filament_id=*/2);
|
||||
const bool is_topmost_layer = GENERATE(false, true);
|
||||
CAPTURE(is_topmost_layer);
|
||||
REQUIRE(Layer::choose_ironing_extruder(cfg, /*spiral_mode=*/false, is_topmost_layer) == 2);
|
||||
}
|
||||
|
||||
TEST_CASE("Ironing top surfaces uses the top surface filament when the region has top shells", "[Fill]")
|
||||
{
|
||||
const PrintRegionConfig cfg = ironing_config(IroningType::TopSurfaces,
|
||||
/*top_surface_filament_id=*/3,
|
||||
/*top_shell_layers=*/2);
|
||||
REQUIRE(Layer::choose_ironing_extruder(cfg, /*spiral_mode=*/false, /*is_topmost_layer=*/false) == 3);
|
||||
}
|
||||
|
||||
TEST_CASE("Ironing top surfaces without top shells needs spiral mode and more than one bottom shell", "[Fill]")
|
||||
{
|
||||
const PrintRegionConfig one_bottom_shell = ironing_config(IroningType::TopSurfaces,
|
||||
/*top_surface_filament_id=*/1,
|
||||
/*top_shell_layers=*/0,
|
||||
/*bottom_shell_layers=*/1);
|
||||
const PrintRegionConfig two_bottom_shells = ironing_config(IroningType::TopSurfaces,
|
||||
/*top_surface_filament_id=*/1,
|
||||
/*top_shell_layers=*/0,
|
||||
/*bottom_shell_layers=*/2);
|
||||
|
||||
REQUIRE(Layer::choose_ironing_extruder(two_bottom_shells, /*spiral_mode=*/true, /*is_topmost_layer=*/false) == 1);
|
||||
REQUIRE(Layer::choose_ironing_extruder(one_bottom_shell, /*spiral_mode=*/true, /*is_topmost_layer=*/false) == -1);
|
||||
REQUIRE(Layer::choose_ironing_extruder(two_bottom_shells, /*spiral_mode=*/false, /*is_topmost_layer=*/false) == -1);
|
||||
}
|
||||
|
||||
TEST_CASE("Ironing the topmost surface only applies to the topmost layer", "[Fill]")
|
||||
{
|
||||
const PrintRegionConfig cfg = ironing_config(IroningType::TopmostOnly, /*top_surface_filament_id=*/4);
|
||||
REQUIRE(Layer::choose_ironing_extruder(cfg, /*spiral_mode=*/false, /*is_topmost_layer=*/true) == 4);
|
||||
REQUIRE(Layer::choose_ironing_extruder(cfg, /*spiral_mode=*/false, /*is_topmost_layer=*/false) == -1);
|
||||
}
|
||||
|
||||
TEST_CASE("A region with ironing turned off is never ironed", "[Fill]")
|
||||
{
|
||||
const PrintRegionConfig cfg = ironing_config(IroningType::NoIroning);
|
||||
const bool spiral_mode = GENERATE(false, true);
|
||||
CAPTURE(spiral_mode);
|
||||
REQUIRE(Layer::choose_ironing_extruder(cfg, spiral_mode, /*is_topmost_layer=*/true) == -1);
|
||||
}
|
||||
|
||||
TEST_CASE("Solid infill direction offsets every layer when no template is set", "[Fill]")
|
||||
{
|
||||
auto angles_for = [](int direction) {
|
||||
@@ -699,6 +768,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.
|
||||
@@ -1022,3 +1298,68 @@ TEST_CASE("Smoothing multiline lightning infill keeps its outlines connected", "
|
||||
REQUIRE(smooth.point_count > sharp.point_count);
|
||||
REQUIRE(smooth.sharp_turns < sharp.sharp_turns);
|
||||
}
|
||||
|
||||
TEST_CASE("Sparse plane-path anchors match the printed infill", "[Fill][InternalBridge][Regression]")
|
||||
{
|
||||
// Orca: Compare generated anchors with actual extrusion across plane-path patterns,
|
||||
// smoothing, multiline and rotations; an origin shift must not pass as valid support.
|
||||
const std::string pattern = GENERATE("hilbertcurve", "octagramspiral", "archimedeanchords");
|
||||
const std::string smoothing = GENERATE("0%", "100%");
|
||||
const int multiline = GENERATE(1, 2);
|
||||
const bool rotated = GENERATE(false, true);
|
||||
const bool separated = GENERATE(false, true);
|
||||
CAPTURE(pattern, smoothing, multiline, rotated, separated);
|
||||
|
||||
auto config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict({{"sparse_infill_pattern", pattern},
|
||||
{"sparse_infill_density", "15%"},
|
||||
{"sparse_infill_smooth_factor", smoothing},
|
||||
{"fill_multiline", multiline},
|
||||
{"infill_direction", 45},
|
||||
{"sparse_infill_rotate_template", rotated ? "0,25,50" : ""},
|
||||
{"align_infill_direction_to_model", rotated},
|
||||
{"separated_infills", separated},
|
||||
{"top_shell_layers", 0},
|
||||
{"bottom_shell_layers", 0},
|
||||
{"top_shell_thickness", 0},
|
||||
{"bottom_shell_thickness", 0},
|
||||
{"layer_height", 0.2},
|
||||
{"initial_layer_print_height", 0.2},
|
||||
{"resolution", 0.012}});
|
||||
Print print;
|
||||
Model model;
|
||||
TriangleMesh mesh = make_cube(30, 24, 1);
|
||||
if (separated) {
|
||||
// Orca: Two disconnected bodies in one object must each use their own infill origin.
|
||||
TriangleMesh second = make_cube(30, 24, 1);
|
||||
second.translate(50, 0, 0);
|
||||
mesh.merge(second);
|
||||
}
|
||||
Slic3r::Test::init_print({mesh}, print, model, config, nullptr, false);
|
||||
if (rotated) {
|
||||
model.objects.front()->instances.front()->set_rotation(Vec3d(0., 0., Geometry::deg2rad(23.)));
|
||||
print.apply(model, config);
|
||||
}
|
||||
print.process();
|
||||
|
||||
const Layer &layer = *print.objects().front()->get_layer(4);
|
||||
Polylines printed;
|
||||
for (const LayerRegion *region : layer.regions())
|
||||
for (const ExtrusionEntity *entity : region->fills.flatten().entities)
|
||||
if (entity->role() == erInternalInfill)
|
||||
entity->collect_polylines(printed);
|
||||
REQUIRE_FALSE(printed.empty());
|
||||
const AABBTreeLines::LinesDistancer<Line> printed_tree(to_lines(printed));
|
||||
|
||||
// Orca: Exclude perimeter connections: anchoring and extrusion can trim those differently.
|
||||
const Polylines anchors = intersection_pl(layer.generate_sparse_infill_polylines_for_anchoring(nullptr, nullptr, nullptr),
|
||||
shrink(to_polygons(layer.lslices), scale_(3.)));
|
||||
REQUIRE_FALSE(anchors.empty());
|
||||
double max_distance = 0.;
|
||||
for (const Polyline &path : anchors)
|
||||
for (const Point &point : path.equally_spaced_points(scale_(0.25)))
|
||||
max_distance = std::max(max_distance, printed_tree.distance_from_lines<false>(point));
|
||||
// Orca: Allow only the configured simplification tolerance; infill-scale offsets
|
||||
// would hide anchors that no longer coincide with printed lines.
|
||||
CHECK(unscale<double>(max_distance) <= config.opt_float("resolution"));
|
||||
}
|
||||
|
||||
@@ -574,6 +574,9 @@ static DynamicPrintConfig dual_extruder_toolchange_config()
|
||||
config.set_key_value("nozzle_temperature_range_high", new ConfigOptionInts({240, 240}));
|
||||
config.set_key_value("flush_multiplier", new ConfigOptionFloats({1}));
|
||||
config.set_key_value("flush_volumes_matrix", new ConfigOptionFloats({0, 140, 140, 0}));
|
||||
// Inside the 200x200 test bed; the default y, 220, is not, and generation rejects that.
|
||||
config.set_key_value("wipe_tower_x", new ConfigOptionFloats({50.}));
|
||||
config.set_key_value("wipe_tower_y", new ConfigOptionFloats({50.}));
|
||||
return config;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,9 +4,14 @@
|
||||
#include "libslic3r/ExtrusionEntityCollection.hpp"
|
||||
#include "libslic3r/Layer.hpp"
|
||||
#include "libslic3r/Print.hpp"
|
||||
#include "libslic3r/GCodeReader.hpp"
|
||||
#include "libslic3r/Model.hpp"
|
||||
#include "libslic3r/TriangleMesh.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "test_helpers.hpp"
|
||||
@@ -255,3 +260,238 @@ TEST_CASE("Only one wall on the first layer needs a bottom shell", "[Perimeters]
|
||||
// No bottom shell: the option is inert, down to the same walls an unchecked box gives.
|
||||
CHECK_THAT(one_wall_no_shell, Catch::Matchers::WithinAbs(plain_no_shell, 1.0));
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// The layer that closes the cavity of box_over_cavity(), the first one printed over air.
|
||||
const double cavity_ceiling_z = 6.2;
|
||||
|
||||
// A cone standing on its tip, flaring by 5mm of radius per mm of height: at a layer height of 0.2 every
|
||||
// wall of a layer lands a full millimetre outside the one below, entirely off the layer below but right
|
||||
// alongside the walls printed with it.
|
||||
TriangleMesh flared_cone()
|
||||
{
|
||||
TriangleMesh cone = make_cone(20., 4.);
|
||||
cone.mirror(Z);
|
||||
cone.translate(0., 0., 4.);
|
||||
return cone;
|
||||
}
|
||||
|
||||
// A 30mm box holding a 20mm cavity from z=2 to z=6, with a 4mm hole punched down through the ceiling
|
||||
// of that cavity. The layer at cavity_ceiling_z bridges the cavity, and the walls of the hole sit in
|
||||
// the middle of that bridge, 15mm clear of anything the layer below supports.
|
||||
Print &box_over_cavity(Print &print, Model &model, const DynamicPrintConfig &config)
|
||||
{
|
||||
ModelObject *object = model.add_object();
|
||||
object->name = "box_over_cavity.stl";
|
||||
object->add_volume(make_cube(30., 30., 8.), ModelVolumeType::MODEL_PART, false);
|
||||
TriangleMesh cavity = make_cube(20., 20., 4.);
|
||||
cavity.translate(5.f, 5.f, 2.f);
|
||||
object->add_volume(std::move(cavity), ModelVolumeType::NEGATIVE_VOLUME, false);
|
||||
TriangleMesh hole = make_cube(4., 4., 6.);
|
||||
hole.translate(13.f, 13.f, 5.f);
|
||||
object->add_volume(std::move(hole), ModelVolumeType::NEGATIVE_VOLUME, false);
|
||||
object->add_instance();
|
||||
object->ensure_on_bed();
|
||||
|
||||
print.auto_assign_extruders(object);
|
||||
print.apply(model, config);
|
||||
print.validate();
|
||||
print.set_status_silent();
|
||||
return print;
|
||||
}
|
||||
|
||||
// Every setting the assertions below depend on, so none of them rests on a default.
|
||||
DynamicPrintConfig unsupported_walls_config(const char *wall_generator, bool unsupported_wall_last)
|
||||
{
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict({
|
||||
{ "wall_generator", wall_generator },
|
||||
{ "layer_height", 0.2 },
|
||||
{ "initial_layer_print_height", 0.2 },
|
||||
{ "wall_loops", 3 },
|
||||
{ "detect_overhang_wall", true },
|
||||
// Outer wall first, so an unsupported loop only ends up last if the feature puts it there.
|
||||
{ "wall_sequence", "outer wall/inner wall" },
|
||||
{ "is_infill_first", false },
|
||||
{ "sparse_infill_density", "15%" },
|
||||
{ "unsupported_wall_last", unsupported_wall_last },
|
||||
{ "gcode_comments", true },
|
||||
});
|
||||
return config;
|
||||
}
|
||||
|
||||
// A loop extruded entirely in mid air: every one of its paths is an overhang.
|
||||
bool unsupported_loop(const ExtrusionEntity *entity)
|
||||
{
|
||||
if (! entity->is_loop())
|
||||
return false;
|
||||
const ExtrusionPaths &paths = static_cast<const ExtrusionLoop *>(entity)->paths;
|
||||
return ! paths.empty() && std::all_of(paths.begin(), paths.end(),
|
||||
[](const ExtrusionPath &path) { return path.role() == erOverhangPerimeter; });
|
||||
}
|
||||
|
||||
// The loops of every wall island of the print, island by island, in extrusion order.
|
||||
std::vector<std::vector<const ExtrusionLoop*>> wall_islands(const Print &print)
|
||||
{
|
||||
std::vector<std::vector<const ExtrusionLoop*>> islands;
|
||||
for (const Layer *layer : print.objects().front()->layers())
|
||||
for (const LayerRegion *region : layer->regions())
|
||||
for (const ExtrusionEntity *island : region->perimeters.entities) {
|
||||
std::vector<const ExtrusionLoop*> loops;
|
||||
for (const ExtrusionEntity *entity : static_cast<const ExtrusionEntityCollection*>(island)->entities)
|
||||
if (entity->is_loop())
|
||||
loops.push_back(static_cast<const ExtrusionLoop*>(entity));
|
||||
islands.push_back(std::move(loops));
|
||||
}
|
||||
return islands;
|
||||
}
|
||||
|
||||
// Islands where a loop that is anchored is extruded after one that is not.
|
||||
int islands_with_a_supported_loop_last(const Print &print)
|
||||
{
|
||||
int count = 0;
|
||||
for (const std::vector<const ExtrusionLoop*> &loops : wall_islands(print)) {
|
||||
bool seen_unsupported = false;
|
||||
for (const ExtrusionLoop *loop : loops) {
|
||||
if (unsupported_loop(loop))
|
||||
seen_unsupported = true;
|
||||
else if (seen_unsupported) {
|
||||
++ count;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// The unsupported loops of the print, and those of them held back for the infill.
|
||||
std::vector<const ExtrusionLoop*> unsupported_loops(const Print &print, double print_z = -1.)
|
||||
{
|
||||
std::vector<const ExtrusionLoop*> loops;
|
||||
for (const Layer *layer : print.objects().front()->layers()) {
|
||||
if (print_z >= 0. && std::abs(layer->print_z - print_z) > EPSILON)
|
||||
continue;
|
||||
for (const LayerRegion *region : layer->regions())
|
||||
for (const ExtrusionEntity *island : region->perimeters.entities)
|
||||
for (const ExtrusionEntity *entity : static_cast<const ExtrusionEntityCollection*>(island)->entities)
|
||||
if (unsupported_loop(entity))
|
||||
loops.push_back(static_cast<const ExtrusionLoop*>(entity));
|
||||
}
|
||||
return loops;
|
||||
}
|
||||
|
||||
int loops_held_back_for_infill(const std::vector<const ExtrusionLoop*> &loops)
|
||||
{
|
||||
return int(std::count_if(loops.begin(), loops.end(), [](const ExtrusionLoop *loop) { return loop->print_after_infill; }));
|
||||
}
|
||||
|
||||
// The G-code emitted at `print_z`, so the order of one layer can be read on its own.
|
||||
std::string layer_gcode(const std::string &gcode, double print_z)
|
||||
{
|
||||
std::string out;
|
||||
GCodeReader reader;
|
||||
reader.parse_buffer(gcode, [&out, print_z](GCodeReader &self, const GCodeReader::GCodeLine &line) {
|
||||
if (std::abs(self.z() - print_z) < EPSILON)
|
||||
out += line.raw() + "\n";
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Whatever the wall order asks for, a loop with nothing under it cannot be extruded before the loops it
|
||||
// leans on. The flared cone gives every layer an outer wall that lands completely off the one below, and
|
||||
// the outer wall first sequence would otherwise put it down before any of them.
|
||||
TEST_CASE("Unsupported wall loops are extruded after the walls that anchor them", "[Perimeters]")
|
||||
{
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
CAPTURE(wall_generator);
|
||||
|
||||
auto slice_cone = [wall_generator](bool unsupported_wall_last, Print &print) {
|
||||
init_and_process_print({ flared_cone() }, print, unsupported_walls_config(wall_generator, unsupported_wall_last));
|
||||
REQUIRE_FALSE(print.objects().empty());
|
||||
};
|
||||
|
||||
Print on;
|
||||
slice_cone(true, on);
|
||||
// Without unsupported loops to reorder the rest of the test would pass on an empty print.
|
||||
REQUIRE(unsupported_loops(on).size() > 0);
|
||||
CHECK(islands_with_a_supported_loop_last(on) == 0);
|
||||
|
||||
SECTION("the held back loops run innermost first") {
|
||||
for (const std::vector<const ExtrusionLoop*> &loops : wall_islands(on)) {
|
||||
int previous_inset = std::numeric_limits<int>::max();
|
||||
for (const ExtrusionLoop *loop : loops)
|
||||
if (unsupported_loop(loop)) {
|
||||
CHECK(loop->inset_idx <= previous_inset);
|
||||
previous_inset = loop->inset_idx;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("switched off, the configured wall order is left alone") {
|
||||
Print off;
|
||||
slice_cone(false, off);
|
||||
REQUIRE(unsupported_loops(off).size() == unsupported_loops(on).size());
|
||||
// Outer wall first puts the unsupported outer wall ahead of the walls behind it.
|
||||
CHECK(islands_with_a_supported_loop_last(off) > 0);
|
||||
}
|
||||
}
|
||||
|
||||
// A loop the walls cannot reach is a different case: only the bridges of its own layer will ever hold it,
|
||||
// so it has to wait for them - while a loop that runs alongside a wall keeps its place, because the
|
||||
// bridges anchor on it instead.
|
||||
TEST_CASE("A wall loop out of reach of the layer below waits for the infill", "[Perimeters]")
|
||||
{
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
CAPTURE(wall_generator);
|
||||
|
||||
Print print;
|
||||
Model model;
|
||||
box_over_cavity(print, model, unsupported_walls_config(wall_generator, true));
|
||||
print.process();
|
||||
|
||||
const std::vector<const ExtrusionLoop*> hole_loops = unsupported_loops(print, cavity_ceiling_z);
|
||||
REQUIRE(hole_loops.size() > 0);
|
||||
CHECK(loops_held_back_for_infill(hole_loops) == int(hole_loops.size()));
|
||||
|
||||
SECTION("a loop alongside a supported wall is not held back") {
|
||||
Print cone;
|
||||
init_and_process_print({ flared_cone() }, cone, unsupported_walls_config(wall_generator, true));
|
||||
const std::vector<const ExtrusionLoop*> loops = unsupported_loops(cone);
|
||||
REQUIRE(loops.size() > 0);
|
||||
CHECK(loops_held_back_for_infill(loops) == 0);
|
||||
}
|
||||
|
||||
SECTION("switched off, no loop is held back") {
|
||||
Print off;
|
||||
Model off_model;
|
||||
box_over_cavity(off, off_model, unsupported_walls_config(wall_generator, false));
|
||||
off.process();
|
||||
const std::vector<const ExtrusionLoop*> loops = unsupported_loops(off, cavity_ceiling_z);
|
||||
REQUIRE(loops.size() == hole_loops.size());
|
||||
CHECK(loops_held_back_for_infill(loops) == 0);
|
||||
}
|
||||
}
|
||||
|
||||
// The held back loops reach the G-code in a second pass, after the infill of their layer: on the layer
|
||||
// that closes the cavity the walls of the hole are extruded once the bridge is down, so the layer emits
|
||||
// perimeters, then infill, then the perimeters that were waiting for it.
|
||||
TEST_CASE("Loops waiting for the infill are extruded after it", "[Perimeters]")
|
||||
{
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
CAPTURE(wall_generator);
|
||||
|
||||
auto ceiling_roles = [wall_generator](bool unsupported_wall_last) {
|
||||
Print print;
|
||||
Model model;
|
||||
box_over_cavity(print, model, unsupported_walls_config(wall_generator, unsupported_wall_last));
|
||||
const std::string layer = layer_gcode(gcode(print), cavity_ceiling_z);
|
||||
REQUIRE_FALSE(layer.empty());
|
||||
return role_sequence(layer, { "perimeter", "infill" });
|
||||
};
|
||||
|
||||
CHECK(ceiling_roles(true) == std::vector<std::string>{ "perimeter", "infill", "perimeter" });
|
||||
CHECK(ceiling_roles(false) == std::vector<std::string>{ "perimeter", "infill" });
|
||||
}
|
||||
|
||||
@@ -4,11 +4,18 @@
|
||||
#include "libslic3r/Print.hpp"
|
||||
#include "libslic3r/Layer.hpp"
|
||||
#include "libslic3r/GCodeReader.hpp"
|
||||
#include "libslic3r/ClipperUtils.hpp"
|
||||
#include "libslic3r/AABBTreeLines.hpp"
|
||||
|
||||
#include "test_helpers.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <iterator>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
using namespace Slic3r;
|
||||
using namespace Slic3r::Test;
|
||||
@@ -130,3 +137,438 @@ TEST_CASE("Initial layer height is honored", "[PrintObject]")
|
||||
REQUIRE_THAT(*layer_zs.begin(), Catch::Matchers::WithinAbs(0.3, 1e-4));
|
||||
REQUIRE_THAT(*std::next(layer_zs.begin()), Catch::Matchers::WithinAbs(0.5, 1e-4));
|
||||
}
|
||||
|
||||
static TriangleMesh internal_bridge_step()
|
||||
{
|
||||
// Orca: The smaller tower leaves a shoulder whose solid skin needs internal bridges
|
||||
// over the sparse infill in the base, without relying on an external model file.
|
||||
TriangleMesh mesh = make_cube(30, 24, 3);
|
||||
TriangleMesh tower = make_cube(14, 10, 1);
|
||||
tower.translate(8, 7, 3);
|
||||
mesh.merge(tower);
|
||||
return mesh;
|
||||
}
|
||||
|
||||
static DynamicPrintConfig internal_bridge_config(const std::string &pattern, int multiline)
|
||||
{
|
||||
auto config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict({{"sparse_infill_pattern", pattern},
|
||||
{"fill_multiline", multiline},
|
||||
{"sparse_infill_density", "15%"},
|
||||
{"sparse_infill_smooth_factor", "100%"},
|
||||
{"infill_direction", 45},
|
||||
{"internal_bridge_angle", 0},
|
||||
{"thick_internal_bridges", true},
|
||||
{"top_shell_layers", 3},
|
||||
{"bottom_shell_layers", 2},
|
||||
{"top_shell_thickness", 0},
|
||||
{"bottom_shell_thickness", 0},
|
||||
{"layer_height", 0.2},
|
||||
{"initial_layer_print_height", 0.2}});
|
||||
return config;
|
||||
}
|
||||
|
||||
TEST_CASE("Internal bridge angles follow the lower infill layer and model rotation", "[PrintObject][InternalBridge][Regression]")
|
||||
{
|
||||
const std::string pattern = GENERATE("hilbertcurve", "octagramspiral");
|
||||
// Orca: Cover both a central line (odd counts) and offset pairs (even counts).
|
||||
const int multiline = GENERATE(1, 2, 3);
|
||||
CAPTURE(multiline);
|
||||
const double rotation = GENERATE(23., -123.);
|
||||
const std::vector<double> cycle{10., 30., 70.};
|
||||
auto config = internal_bridge_config(pattern, multiline);
|
||||
config.set_deserialize_strict({{"sparse_infill_rotate_template", "10,30,70"},
|
||||
{"align_infill_direction_to_model", true},
|
||||
{"separated_infills", false}});
|
||||
Print print;
|
||||
Model model;
|
||||
init_print({internal_bridge_step()}, print, model, config, nullptr, false);
|
||||
model.objects.front()->instances.front()->set_rotation(Vec3d(0., 0., Geometry::deg2rad(rotation)));
|
||||
print.apply(model, config);
|
||||
print.process();
|
||||
const PrintObject &object = *print.objects().front();
|
||||
size_t bridges = 0;
|
||||
for (size_t i = 1; i < object.layer_count(); ++i) {
|
||||
// Orca: The support is one layer below the bridge. Check the template and model
|
||||
// rotation together, including normalization when the resulting angle is negative.
|
||||
double expected = std::fmod(cycle[(i - 1) % cycle.size()] + 90. + rotation, 180.);
|
||||
if (expected < 0.) expected += 180.;
|
||||
for (const LayerRegion *region : object.get_layer(i)->regions())
|
||||
for (const Surface *surface : region->fill_surfaces.filter_by_type(stInternalBridge)) {
|
||||
CAPTURE(pattern, rotation, i);
|
||||
CHECK_THAT(Geometry::rad2deg(surface->bridge_angle), Catch::Matchers::WithinAbs(expected, 0.001));
|
||||
++bridges;
|
||||
}
|
||||
}
|
||||
REQUIRE(bridges > 0);
|
||||
}
|
||||
|
||||
TEST_CASE("Turning infill does not replace the anchors of another region", "[PrintObject][InternalBridge][Regression]")
|
||||
{
|
||||
// Orca: Keep the right-hand region fixed while changing the left-hand pattern in the
|
||||
// same object. Its bridge areas must be independent of a previous candidate's anchors.
|
||||
const int multiline = GENERATE(1, 2, 3);
|
||||
CAPTURE(multiline);
|
||||
auto right_bridges = [multiline](const std::string &left_pattern) {
|
||||
auto config = internal_bridge_config(left_pattern, multiline);
|
||||
Print print;
|
||||
Model model;
|
||||
init_print({internal_bridge_step()}, print, model, config, nullptr, false);
|
||||
TriangleMesh right = internal_bridge_step();
|
||||
right.translate(50, 0, 0);
|
||||
ModelVolume *volume = model.objects.front()->add_volume(std::move(right));
|
||||
volume->config.set_key_value("sparse_infill_pattern", new ConfigOptionEnum<InfillPattern>(ipRectilinear));
|
||||
volume->config.set_key_value("infill_direction", new ConfigOptionFloat(17.));
|
||||
print.apply(model, config);
|
||||
print.process();
|
||||
std::map<size_t, Polygons> result;
|
||||
const PrintObject &object = *print.objects().front();
|
||||
for (size_t i = 0; i < object.layer_count(); ++i)
|
||||
for (const LayerRegion *region : object.get_layer(i)->regions())
|
||||
if (region->region().config().infill_direction == 17.)
|
||||
polygons_append(result[i], to_polygons(region->fill_surfaces.filter_by_type(stInternalBridge)));
|
||||
return result;
|
||||
};
|
||||
const auto baseline = right_bridges("rectilinear");
|
||||
const auto actual = right_bridges(GENERATE("hilbertcurve", "octagramspiral"));
|
||||
REQUIRE(actual.size() == baseline.size());
|
||||
double total_area = 0.;
|
||||
for (const auto &[layer, expected] : baseline) {
|
||||
CAPTURE(layer);
|
||||
const auto &polys = actual.at(layer);
|
||||
CHECK(area(diff(expected, polys)) < scaled<double>(1.) * scaled<double>(1.) * 1e-6);
|
||||
CHECK(area(diff(polys, expected)) < scaled<double>(1.) * scaled<double>(1.) * 1e-6);
|
||||
total_area += area(expected);
|
||||
}
|
||||
REQUIRE(total_area > 0.);
|
||||
}
|
||||
|
||||
TEST_CASE("Rounded internal bridges end on printed support", "[PrintObject][InternalBridge][Regression]")
|
||||
{
|
||||
const std::string pattern = GENERATE("hilbertcurve", "octagramspiral");
|
||||
const bool separated = GENERATE(false, true);
|
||||
CAPTURE(pattern, separated);
|
||||
auto config = internal_bridge_config(pattern, 1);
|
||||
config.set_deserialize_strict({{"infill_wall_overlap", "0%"}, {"separated_infills", separated}});
|
||||
TriangleMesh mesh = internal_bridge_step();
|
||||
if (separated) {
|
||||
TriangleMesh second = internal_bridge_step();
|
||||
second.translate(50, 0, 0);
|
||||
mesh.merge(second);
|
||||
}
|
||||
Print print;
|
||||
Model model;
|
||||
init_print({mesh}, print, model, config, nullptr, false);
|
||||
print.process();
|
||||
|
||||
// Orca: Check final extrusion endpoints after polygon cleanup and fill generation.
|
||||
// A correct bridge angle and correct sparse anchors alone do not guarantee contact.
|
||||
const PrintObject &object = *print.objects().front();
|
||||
size_t checked = 0;
|
||||
for (size_t i = 1; i < object.layer_count(); ++i) {
|
||||
Polygons support;
|
||||
Polylines walls;
|
||||
for (const LayerRegion *region : object.get_layer(i - 1)->regions()) {
|
||||
region->perimeters.polygons_covered_by_width(support, 0.f);
|
||||
region->fills.polygons_covered_by_width(support, 0.f);
|
||||
region->perimeters.collect_polylines(walls);
|
||||
}
|
||||
REQUIRE_FALSE(support.empty());
|
||||
const AABBTreeLines::LinesDistancer<Line> support_tree(to_lines(union_(support)));
|
||||
const AABBTreeLines::LinesDistancer<Line> wall_tree(to_lines(walls));
|
||||
for (const LayerRegion *region : object.get_layer(i)->regions())
|
||||
for (const ExtrusionEntity *entity : region->fills.flatten().entities) {
|
||||
if (entity->role() != erInternalBridgeInfill)
|
||||
continue;
|
||||
const auto *path = dynamic_cast<const ExtrusionPath *>(entity);
|
||||
REQUIRE(path != nullptr);
|
||||
for (const Line &line : path->polyline.to_polyline().lines()) {
|
||||
// Orca: Sample span ends, excluding short connectors and wall overlap.
|
||||
if (line.length() < scale_(std::max(0.7, 3. * path->width)))
|
||||
continue;
|
||||
for (const Point &point : {line.a, line.b}) {
|
||||
if (wall_tree.distance_from_lines<false>(point) <= scale_(0.5))
|
||||
continue;
|
||||
CAPTURE(i, point.x(), point.y());
|
||||
const double gap = unscale<double>(support_tree.distance_from_lines<true>(point)) - 0.5 * path->width;
|
||||
CHECK(gap <= 0.1);
|
||||
++checked;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
REQUIRE(checked > 0);
|
||||
}
|
||||
|
||||
TEST_CASE("Enabling separated infill recomputes body origins", "[PrintObject][InternalBridge][Regression]")
|
||||
{
|
||||
const std::string pattern = GENERATE("hilbertcurve", "octagramspiral", "archimedeanchords");
|
||||
CAPTURE(pattern);
|
||||
auto footprint = [&](bool reslice) {
|
||||
auto config = internal_bridge_config(pattern, 2);
|
||||
config.set_deserialize_strict({{"separated_infills", !reslice}});
|
||||
TriangleMesh mesh = internal_bridge_step();
|
||||
TriangleMesh second = internal_bridge_step();
|
||||
second.translate(50, 0, 0);
|
||||
mesh.merge(second);
|
||||
Print print;
|
||||
Model model;
|
||||
init_print({mesh}, print, model, config, nullptr, false);
|
||||
print.process();
|
||||
if (reslice) {
|
||||
// Orca: Enabling centering after a completed slice must rebuild the body
|
||||
// origins now shared by bridge preparation and printed infill.
|
||||
config.set_deserialize_strict({{"separated_infills", true}});
|
||||
print.apply(model, config);
|
||||
print.process();
|
||||
}
|
||||
Polygons result;
|
||||
for (const LayerRegion *region : print.objects().front()->get_layer(4)->regions())
|
||||
region->fills.polygons_covered_by_width(result, 0.f);
|
||||
return union_(result);
|
||||
};
|
||||
const Polygons fresh = footprint(false);
|
||||
const Polygons resliced = footprint(true);
|
||||
REQUIRE_FALSE(fresh.empty());
|
||||
CHECK(area(diff(fresh, resliced)) < scaled<double>(1.) * scaled<double>(1.) * 1e-6);
|
||||
CHECK(area(diff(resliced, fresh)) < scaled<double>(1.) * scaled<double>(1.) * 1e-6);
|
||||
}
|
||||
|
||||
TEST_CASE("Surface centering survives changes to separated infill settings", "[PrintObject][SurfaceInfill][Regression]")
|
||||
{
|
||||
const std::string pattern = GENERATE("archimedeanchords", "octagramspiral");
|
||||
const std::string initial_center = GENERATE("each_surface", "each_model", "each_assembly");
|
||||
const std::string final_center = GENERATE("each_surface", "each_model", "each_assembly");
|
||||
const bool separated = GENERATE(false, true);
|
||||
const std::string top_order = GENERATE("default", "outward", "inward");
|
||||
const std::string bottom_order = top_order == "outward" ? "inward" : top_order == "inward" ? "outward" : "default";
|
||||
const std::string density = GENERATE("80%", "100%");
|
||||
const bool change_center = initial_center != final_center;
|
||||
CAPTURE(pattern, initial_center, final_center, separated, top_order, bottom_order, density);
|
||||
|
||||
auto config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict({{"top_surface_pattern", pattern},
|
||||
{"bottom_surface_pattern", pattern},
|
||||
{"top_surface_fill_order", top_order},
|
||||
{"bottom_surface_fill_order", bottom_order},
|
||||
{"top_surface_density", density},
|
||||
{"bottom_surface_density", density},
|
||||
{"center_of_surface_pattern", initial_center},
|
||||
{"separated_infills", change_center ? separated : !separated},
|
||||
{"sparse_infill_pattern", "rectilinear"},
|
||||
{"sparse_infill_density", "15%"},
|
||||
{"top_shell_layers", 2},
|
||||
{"bottom_shell_layers", 2},
|
||||
{"top_shell_thickness", 0},
|
||||
{"bottom_shell_thickness", 0},
|
||||
{"layer_height", 0.2},
|
||||
{"initial_layer_print_height", 0.2}});
|
||||
|
||||
// Orca: Two disconnected bodies exercise per-body centering. The offset tower also
|
||||
// makes each-surface and each-model centering differ on the top surfaces.
|
||||
TriangleMesh mesh = make_cube(30, 24, 2);
|
||||
TriangleMesh tower = make_cube(12, 10, 1);
|
||||
tower.translate(4, 3, 2);
|
||||
mesh.merge(tower);
|
||||
TriangleMesh second = mesh;
|
||||
second.translate(50, 0, 0);
|
||||
mesh.merge(second);
|
||||
|
||||
// Orca: Equal footprints can hide reordered or reversed paths. Retain their point
|
||||
// sequences and ordering protection to cover the directional surface behavior too.
|
||||
struct SurfaceFillSnapshot {
|
||||
std::map<bool, std::vector<Points>> paths;
|
||||
bool protected_order = true;
|
||||
};
|
||||
auto surface_fills = [](const Print &print) {
|
||||
std::map<std::pair<size_t, ExtrusionRole>, SurfaceFillSnapshot> result;
|
||||
const PrintObject &object = *print.objects().front();
|
||||
for (size_t i = 0; i < object.layer_count(); ++i) {
|
||||
auto collect = [&](const auto &self, const ExtrusionEntity &entity, bool no_sort) -> void {
|
||||
if (const auto *collection = dynamic_cast<const ExtrusionEntityCollection *>(&entity)) {
|
||||
for (const ExtrusionEntity *child : collection->entities)
|
||||
self(self, *child, no_sort || collection->no_sort);
|
||||
} else if (entity.role() == erTopSolidInfill || entity.role() == erBottomSurface) {
|
||||
const auto *path = dynamic_cast<const ExtrusionPath *>(&entity);
|
||||
REQUIRE(path != nullptr);
|
||||
auto &snapshot = result[{i, entity.role()}];
|
||||
// Orca: The centered test model has one body on either side of X=0.
|
||||
// Their traversal order may vary; preserve path order within each body.
|
||||
Points points = path->polyline.to_polyline().points;
|
||||
REQUIRE_FALSE(points.empty());
|
||||
snapshot.paths[points.front().x() > 0].push_back(std::move(points));
|
||||
snapshot.protected_order &= no_sort && !path->can_reverse();
|
||||
}
|
||||
};
|
||||
for (const LayerRegion *region : object.get_layer(i)->regions())
|
||||
collect(collect, region->fills, false);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
Print print;
|
||||
Model model;
|
||||
init_print({mesh}, print, model, config, nullptr, false);
|
||||
print.process();
|
||||
const auto initial = surface_fills(print);
|
||||
config.set_deserialize_strict({{"center_of_surface_pattern", final_center}, {"separated_infills", separated}});
|
||||
print.apply(model, config);
|
||||
// Orca: Preparation owns the body origins, and its invalidation must also force
|
||||
// regeneration of top/bottom extrusion paths, even when sparse infill is unchanged.
|
||||
CHECK_FALSE(print.objects().front()->is_step_done(posPrepareInfill));
|
||||
CHECK_FALSE(print.objects().front()->is_step_done(posInfill));
|
||||
print.process();
|
||||
const auto resliced = surface_fills(print);
|
||||
|
||||
Print fresh_print;
|
||||
Model fresh_model;
|
||||
init_print({mesh}, fresh_print, fresh_model, config, nullptr, false);
|
||||
fresh_print.process();
|
||||
const auto fresh = surface_fills(fresh_print);
|
||||
REQUIRE_FALSE(fresh.empty());
|
||||
REQUIRE(resliced.size() == fresh.size());
|
||||
std::set<ExtrusionRole> roles;
|
||||
bool changed_paths = false;
|
||||
for (const auto &entry : fresh) {
|
||||
CAPTURE(entry.first.first, entry.first.second);
|
||||
REQUIRE_FALSE(entry.second.paths.empty());
|
||||
roles.insert(entry.first.second);
|
||||
REQUIRE(resliced.count(entry.first) == 1);
|
||||
REQUIRE(initial.count(entry.first) == 1);
|
||||
const auto &actual = resliced.at(entry.first);
|
||||
const auto &expected = entry.second;
|
||||
const auto &before = initial.at(entry.first);
|
||||
CHECK((actual.paths == expected.paths));
|
||||
if (!change_center)
|
||||
CHECK((actual.paths == before.paths));
|
||||
if (top_order != "default") {
|
||||
CHECK(expected.protected_order);
|
||||
CHECK(actual.protected_order);
|
||||
CHECK(before.protected_order);
|
||||
}
|
||||
changed_paths |= expected.paths != before.paths;
|
||||
}
|
||||
CHECK(roles.count(erTopSolidInfill) == 1);
|
||||
CHECK(roles.count(erBottomSurface) == 1);
|
||||
// Orca: Guard against a vacuous comparison: changing surface centering must change
|
||||
// the printed pattern, while toggling separated sparse infill must leave it alone.
|
||||
CHECK(changed_paths == change_center);
|
||||
}
|
||||
|
||||
TEST_CASE("Separated infill keeps fragmented and nested bodies independent", "[PrintObject][SurfaceInfill][Regression]")
|
||||
{
|
||||
constexpr size_t grid_size = 8;
|
||||
TriangleMesh mesh;
|
||||
auto add_box = [&](double x, double y, double width, double depth) {
|
||||
TriangleMesh box = make_cube(width, depth, 0.6);
|
||||
box.translate(x, y, 0);
|
||||
mesh.merge(box);
|
||||
};
|
||||
// Orca: Many small islands exercise spatial pruning and the tree's original
|
||||
// island indices. A pillar inside a frame also overlaps its bounding box,
|
||||
// but must remain a separate body because it lies entirely inside the hole.
|
||||
for (size_t x = 0; x < grid_size; ++ x)
|
||||
for (size_t y = 0; y < grid_size; ++ y)
|
||||
add_box(6 * x, 6 * y, 3, 3);
|
||||
add_box(54, 0, 20, 4);
|
||||
add_box(54, 16, 20, 4);
|
||||
add_box(54, 0, 4, 20);
|
||||
add_box(70, 0, 4, 20);
|
||||
add_box(62, 8, 4, 4);
|
||||
|
||||
auto config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict({{"separated_infills", true},
|
||||
{"center_of_surface_pattern", "each_surface"},
|
||||
{"layer_height", 0.2},
|
||||
{"initial_layer_print_height", 0.2},
|
||||
{"elefant_foot_compensation", 0},
|
||||
{"wall_loops", 1}});
|
||||
Print print;
|
||||
Model model;
|
||||
init_print({mesh}, print, model, config, nullptr, false);
|
||||
// Orca: Prepare body bounds through the public pipeline, then inspect the object read-only.
|
||||
print.process();
|
||||
const PrintObject &object = *print.objects().front();
|
||||
REQUIRE(object.layer_count() > 1);
|
||||
for (const Layer *layer : object.layers()) {
|
||||
REQUIRE(layer->lslices.size() == grid_size * grid_size + 2);
|
||||
REQUIRE(layer->lslices_separated_component_bboxes.size() == layer->lslices.size());
|
||||
size_t holes = 0;
|
||||
for (size_t i = 0; i < layer->lslices.size(); ++ i) {
|
||||
const BoundingBox &body = layer->lslices_separated_component_bboxes[i];
|
||||
const BoundingBox &island = layer->lslices_bboxes[i];
|
||||
CHECK(body.min == island.min);
|
||||
CHECK(body.max == island.max);
|
||||
holes += layer->lslices[i].holes.size();
|
||||
}
|
||||
CHECK(holes == 1);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Body centering survives islands merging and splitting between layers", "[PrintObject][SurfaceInfill][Regression]")
|
||||
{
|
||||
const bool separated = GENERATE(false, true);
|
||||
CAPTURE(separated);
|
||||
// Orca: Four posts join through horizontal then vertical rails, creating a
|
||||
// cycle of overlaps before splitting into four islands again. This exercises
|
||||
// redundant connections and indexing either adjacent layer. A fifth post
|
||||
// stays separate at every height.
|
||||
TriangleMesh mesh;
|
||||
for (int x : {0, 8})
|
||||
for (int y : {0, 8}) {
|
||||
TriangleMesh post = make_cube(4, 4, 1);
|
||||
post.translate(x, y, 0);
|
||||
mesh.merge(post);
|
||||
}
|
||||
for (int y : {0, 8}) {
|
||||
TriangleMesh rail = make_cube(12, 4, 0.2);
|
||||
rail.translate(0, y, 0.2);
|
||||
mesh.merge(rail);
|
||||
}
|
||||
for (int x : {0, 8}) {
|
||||
TriangleMesh rail = make_cube(4, 12, 0.2);
|
||||
rail.translate(x, 0, 0.4);
|
||||
mesh.merge(rail);
|
||||
}
|
||||
TriangleMesh isolated = make_cube(4, 4, 1);
|
||||
isolated.translate(20, 0, 0);
|
||||
mesh.merge(isolated);
|
||||
|
||||
auto config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict({{"separated_infills", separated},
|
||||
{"center_of_surface_pattern", separated ? "each_surface" : "each_model"},
|
||||
{"layer_height", 0.2},
|
||||
{"initial_layer_print_height", 0.2},
|
||||
{"elefant_foot_compensation", 0},
|
||||
{"wall_loops", 1}});
|
||||
Print print;
|
||||
Model model;
|
||||
init_print({mesh}, print, model, config, nullptr, false);
|
||||
// Orca: Prepare body bounds through the public pipeline, then inspect the object read-only.
|
||||
print.process();
|
||||
const PrintObject &object = *print.objects().front();
|
||||
REQUIRE(object.layer_count() == 5);
|
||||
REQUIRE(object.get_layer(0)->lslices.size() == 5);
|
||||
REQUIRE(object.get_layer(1)->lslices.size() == 3);
|
||||
REQUIRE(object.get_layer(2)->lslices.size() == 3);
|
||||
REQUIRE(object.get_layer(4)->lslices.size() == 5);
|
||||
|
||||
BoundingBox isolated_bbox = object.get_layer(0)->lslices_bboxes.front();
|
||||
for (const BoundingBox &bbox : object.get_layer(0)->lslices_bboxes)
|
||||
if (bbox.min.x() > isolated_bbox.min.x())
|
||||
isolated_bbox = bbox;
|
||||
BoundingBox connected_bbox;
|
||||
for (const Layer *layer : object.layers())
|
||||
for (const BoundingBox &bbox : layer->lslices_bboxes)
|
||||
if (bbox.min.x() < isolated_bbox.min.x())
|
||||
connected_bbox.merge(bbox);
|
||||
for (const Layer *layer : object.layers()) {
|
||||
REQUIRE(layer->lslices_separated_component_bboxes.size() == layer->lslices.size());
|
||||
for (size_t i = 0; i < layer->lslices.size(); ++ i) {
|
||||
const BoundingBox &expected = layer->lslices_bboxes[i].min.x() < isolated_bbox.min.x() ? connected_bbox : isolated_bbox;
|
||||
const BoundingBox &actual = layer->lslices_separated_component_bboxes[i];
|
||||
CHECK(actual.min == expected.min);
|
||||
CHECK(actual.max == expected.max);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,11 +3,104 @@
|
||||
#include "libslic3r/GCodeReader.hpp"
|
||||
#include "libslic3r/Layer.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#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;
|
||||
@@ -36,6 +129,49 @@ TEST_CASE("Enforced support layers are generated", "[SupportMaterial]")
|
||||
REQUIRE(enforced.objects().front()->support_layers().size() > 0);
|
||||
}
|
||||
|
||||
// Support-needed statuses raised while slicing support_capital() with support off. The CLI lists these
|
||||
// in result.json and fails on them under --strict. Collected under a lock: generate_support_material()
|
||||
// runs on TBB workers.
|
||||
static std::vector<PrintBase::SlicingStatus> support_needed_statuses(bool no_check)
|
||||
{
|
||||
Slic3r::Print print;
|
||||
Slic3r::Model model;
|
||||
Slic3r::Test::init_print({ support_capital() }, print, model, {
|
||||
{ "enable_support", 0 },
|
||||
{ "enforce_support_layers", 0 }
|
||||
});
|
||||
print.set_no_check_flag(no_check);
|
||||
|
||||
std::mutex mutex;
|
||||
std::vector<PrintBase::SlicingStatus> statuses;
|
||||
print.set_status_callback([&mutex, &statuses](const PrintBase::SlicingStatus &status) {
|
||||
if (status.message_type != PrintStateBase::SlicingNeedSupportOn)
|
||||
return;
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
statuses.push_back(status);
|
||||
});
|
||||
print.process();
|
||||
return statuses;
|
||||
}
|
||||
|
||||
TEST_CASE("An overhang sliced with support off reports that support is needed", "[SupportMaterial]")
|
||||
{
|
||||
// The 40mm cap reaches ~22mm past its 8mm stem, beyond the 6mm cantilever limit of
|
||||
// PrintObject::is_support_necessary().
|
||||
const std::vector<PrintBase::SlicingStatus> statuses = support_needed_statuses(false);
|
||||
REQUIRE(! statuses.empty());
|
||||
for (const PrintBase::SlicingStatus &status : statuses) {
|
||||
// The CLI only considers step warnings (warning_step != -1), and --strict only NON_CRITICAL ones.
|
||||
CHECK(status.warning_level == PrintStateBase::WarningLevel::NON_CRITICAL);
|
||||
CHECK(status.warning_step != -1);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("The no-check flag skips the support-needed check", "[SupportMaterial]")
|
||||
{
|
||||
CHECK(support_needed_statuses(true).empty());
|
||||
}
|
||||
|
||||
SCENARIO("Support layer Z honors contact distance", "[SupportMaterial]")
|
||||
{
|
||||
// Box h = 20mm, hole bottom at 5mm, hole height 10mm (top edge at 15mm).
|
||||
@@ -104,3 +240,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#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;
|
||||
}
|
||||
|
||||
// `extra` is applied last, so a caller can add or override any key.
|
||||
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,
|
||||
std::initializer_list<Slic3r::ConfigBase::SetDeserializeItem> extra = {})
|
||||
{
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict({
|
||||
{ "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 },
|
||||
});
|
||||
config.set_deserialize_strict(extra);
|
||||
Slic3r::Test::init_and_process_print({ mesh }, print, config);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
// Index of the first differing point, or the common length when they match. An index keeps a
|
||||
// failure readable; comparing the vectors themselves dumps thousands of points.
|
||||
size_t first_difference(const Points &a, const Points &b)
|
||||
{
|
||||
const size_t common = std::min(a.size(), b.size());
|
||||
for (size_t i = 0; i < common; ++i)
|
||||
if (a[i] != b[i])
|
||||
return i;
|
||||
return common;
|
||||
}
|
||||
|
||||
// Slice `mesh` twice and require an identical support point sequence. Point counts and total
|
||||
// length are order insensitive, so the sequence is what a reordering shows up in.
|
||||
void sliced_twice_matches(const TriangleMesh &mesh, int build_plate_only, const char *style = "tree_slim",
|
||||
std::initializer_list<Slic3r::ConfigBase::SetDeserializeItem> extra = {})
|
||||
{
|
||||
Slic3r::Print first_print, second_print;
|
||||
slice_with_tree_support(mesh, first_print, style, 30, build_plate_only, 0, extra);
|
||||
slice_with_tree_support(mesh, second_print, style, 30, build_plate_only, 0, extra);
|
||||
const Points first = support_points(first_print);
|
||||
const Points second = support_points(second_print);
|
||||
REQUIRE(first.size() > 1000); // without support the comparison below passes vacuously
|
||||
REQUIRE(second.size() == first.size());
|
||||
REQUIRE(first_difference(first, second) == first.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);
|
||||
}
|
||||
|
||||
// drop_nodes() decides the node merges and spawns the next layer's nodes in parallel. Every one of
|
||||
// those decisions has to be applied in a fixed order, or the same model gives different branches on
|
||||
// each slice.
|
||||
TEST_CASE("Tree support toolpaths do not depend on thread scheduling", "[TreeSupport][Regression]")
|
||||
{
|
||||
// Scaled up so that a layer holds enough nodes for the parallel range to be split. At stock
|
||||
// size it stays in one chunk and the order never varies.
|
||||
SECTION("overhang") { sliced_twice_matches(scaled(TestMesh::overhang, 2.f), 0); }
|
||||
SECTION("bridge with hole") { sliced_twice_matches(scaled(TestMesh::bridge_with_hole, 3.f), 0); }
|
||||
// Dropping every branch that cannot reach the bed leaves the survivors dense enough that the
|
||||
// neighbour merge fires in bulk.
|
||||
SECTION("on the build plate") { sliced_twice_matches(scaled(TestMesh::overhang, 4.f), 1); }
|
||||
// Branches resting on the model are what put nodes in a part group other than 0, which is the
|
||||
// only way to reach the prune in the second pass. tree_hybrid additionally builds polygon
|
||||
// nodes, so it is the only style that exercises the overhang merge.
|
||||
SECTION("resting on the model") { sliced_twice_matches(two_tier_mesh(), 0); }
|
||||
SECTION("hybrid on the model") { sliced_twice_matches(two_tier_mesh(), 0, "tree_hybrid"); }
|
||||
}
|
||||
|
||||
// Prim breaks equal-distance ties by heap address. A 1 mm branch diameter puts neighbours close
|
||||
// enough to tie, and an explicit line width pins max_move_dist, so the moved tie winner reaches
|
||||
// the support toolpaths.
|
||||
TEST_CASE("Tree support toolpaths do not depend on the MST tie order", "[TreeSupport][Regression]")
|
||||
{
|
||||
sliced_twice_matches(two_tier_mesh(), 0, "tree_hybrid", {
|
||||
{ "tree_support_branch_diameter", 1.0 },
|
||||
{ "tree_support_branch_distance", 5.0 },
|
||||
{ "tree_support_branch_angle", 40 },
|
||||
{ "support_line_width", 0.4 },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,653 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
#include "libslic3r/GCode/GCodeProcessor.hpp"
|
||||
#include "libslic3r/GCodeReader.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
#include "libslic3r/Layer.hpp"
|
||||
|
||||
#include "test_helpers.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
using namespace Slic3r::Test;
|
||||
|
||||
namespace {
|
||||
|
||||
DynamicPrintConfig wipe_config(const char *wall_generator, bool wipe_inward,
|
||||
const char *wipe_inward_distance = "50%",
|
||||
const char *seam_gap = "10%", bool wipe_on_loops = false,
|
||||
const char *wall_loops = "2",
|
||||
const char *wall_sequence = "inner wall/outer wall",
|
||||
bool alternate_extra_wall = false,
|
||||
const char *sparse_infill_density = "0%",
|
||||
const char *seam_position = "aligned")
|
||||
{
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict({
|
||||
{ "nozzle_diameter", "0.4" },
|
||||
{ "layer_height", "0.2" },
|
||||
{ "initial_layer_print_height", "0.2" },
|
||||
{ "line_width", "0.45" },
|
||||
{ "outer_wall_line_width", "0" }, // Orca: Auto must use the actual path width.
|
||||
{ "wall_loops", wall_loops },
|
||||
{ "wall_generator", wall_generator },
|
||||
{ "wall_sequence", wall_sequence },
|
||||
{ "top_shell_layers", "0" },
|
||||
{ "bottom_shell_layers", "0" },
|
||||
{ "sparse_infill_density", sparse_infill_density },
|
||||
{ "seam_position", seam_position },
|
||||
{ "seam_gap", seam_gap },
|
||||
{ "wipe", "1" },
|
||||
{ "wipe_distance", "2" },
|
||||
{ "retraction_length", "0.8" },
|
||||
{ "retract_when_changing_layer", "1" },
|
||||
{ "wipe_inward", wipe_inward ? "1" : "0" },
|
||||
{ "wipe_inward_distance", wipe_inward_distance },
|
||||
{ "wipe_on_loops", wipe_on_loops ? "1" : "0" },
|
||||
{ "alternate_extra_wall", alternate_extra_wall ? "1" : "0" },
|
||||
{ "gcode_comments", "1" },
|
||||
{ "machine_start_gcode", "" },
|
||||
{ "machine_end_gcode", "" },
|
||||
});
|
||||
return config;
|
||||
}
|
||||
|
||||
struct WipeTrajectory {
|
||||
Vec2d start;
|
||||
double z;
|
||||
std::vector<Vec2d> destinations;
|
||||
};
|
||||
|
||||
std::vector<WipeTrajectory> wipe_trajectories(const std::string &gcode)
|
||||
{
|
||||
const std::string &start_tag = GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Wipe_Start);
|
||||
const std::string &end_tag = GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Wipe_End);
|
||||
std::vector<WipeTrajectory> trajectories;
|
||||
bool in_wipe = false;
|
||||
|
||||
GCodeReader parser;
|
||||
parser.parse_buffer(gcode, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) {
|
||||
const std::string_view comment = line.comment();
|
||||
if (comment.find(start_tag) != std::string_view::npos) {
|
||||
in_wipe = true;
|
||||
trajectories.push_back({Vec2d(self.x(), self.y()), self.z(), {}});
|
||||
return;
|
||||
}
|
||||
if (comment.find(end_tag) != std::string_view::npos) {
|
||||
in_wipe = false;
|
||||
return;
|
||||
}
|
||||
if (in_wipe && line.dist_XY(self) > EPSILON)
|
||||
trajectories.back().destinations.emplace_back(line.new_X(self), line.new_Y(self));
|
||||
});
|
||||
return trajectories;
|
||||
}
|
||||
|
||||
std::vector<Vec2d> wipe_destinations(const std::string &gcode)
|
||||
{
|
||||
std::vector<Vec2d> destinations;
|
||||
for (const WipeTrajectory &trajectory : wipe_trajectories(gcode))
|
||||
destinations.insert(destinations.end(), trajectory.destinations.begin(), trajectory.destinations.end());
|
||||
return destinations;
|
||||
}
|
||||
|
||||
bool trajectories_differ(const std::vector<Vec2d> &lhs, const std::vector<Vec2d> &rhs)
|
||||
{
|
||||
if (lhs.size() != rhs.size())
|
||||
return true;
|
||||
for (size_t i = 0; i < lhs.size(); ++i)
|
||||
if ((lhs[i] - rhs[i]).norm() > 0.01)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
double trajectory_length(const WipeTrajectory &trajectory)
|
||||
{
|
||||
double length = 0.;
|
||||
Vec2d previous = trajectory.start;
|
||||
for (const Vec2d &destination : trajectory.destinations) {
|
||||
length += (destination - previous).norm();
|
||||
previous = destination;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Wipe retraction preserves fractional speed with inward wipe disabled", "[Wipe][Regression]")
|
||||
{
|
||||
const char *retraction_speed = GENERATE("25.25", "25.5", "25.75");
|
||||
const char *relative_e = GENERATE("0", "1");
|
||||
INFO("retraction speed: " << retraction_speed);
|
||||
INFO("relative E: " << relative_e);
|
||||
DynamicPrintConfig config = wipe_config("classic", false);
|
||||
config.set_deserialize_strict({
|
||||
{"gcode_flavor", "marlin2"},
|
||||
{"use_relative_e_distances", relative_e},
|
||||
{"retraction_speed", retraction_speed},
|
||||
{"retraction_length", "0.8"},
|
||||
{"retract_before_wipe", "0%"},
|
||||
{"retract_after_wipe", "0%"},
|
||||
{"role_based_wipe_speed", "0"},
|
||||
{"wipe_speed", "100"},
|
||||
{"wipe_distance", "2"},
|
||||
});
|
||||
const std::string output = slice({make_cube(10., 10., 1.)}, config);
|
||||
const auto &start_tag = GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Wipe_Start);
|
||||
const auto &end_tag = GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Wipe_End);
|
||||
double before_wipe = 0.;
|
||||
double during_wipe = 0.;
|
||||
bool in_wipe = false;
|
||||
bool complete = false;
|
||||
GCodeReader parser;
|
||||
parser.apply_config(config);
|
||||
parser.parse_buffer(output, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) {
|
||||
if (complete)
|
||||
return;
|
||||
if (line.comment().find(start_tag) != std::string_view::npos) {
|
||||
in_wipe = true;
|
||||
} else if (in_wipe && line.comment().find(end_tag) != std::string_view::npos) {
|
||||
complete = true;
|
||||
} else if (line.retracting(self)) {
|
||||
(in_wipe ? during_wipe : before_wipe) -= line.dist_E(self);
|
||||
} else if (line.extruding(self)) {
|
||||
before_wipe = 0.;
|
||||
}
|
||||
});
|
||||
|
||||
REQUIRE(complete);
|
||||
// At 100 mm/s, the 2 mm wipe lasts 0.02 seconds. The remaining part of
|
||||
// the configured 0.8 mm retraction must be emitted before that wipe.
|
||||
const double expected_during = std::stod(retraction_speed) * 2. / 100.;
|
||||
CHECK_THAT(during_wipe, Catch::Matchers::WithinAbs(expected_during, 0.00005));
|
||||
CHECK_THAT(before_wipe, Catch::Matchers::WithinAbs(0.8 - expected_during, 0.00005));
|
||||
}
|
||||
|
||||
TEST_CASE("Inward wipe respects the minimum travel for retraction and Z hop", "[Wipe][Regression]")
|
||||
{
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
const char *relative_e = GENERATE("0", "1");
|
||||
const char *reduce_crossing_wall = GENERATE("0", "1");
|
||||
const char *minimum_travel = GENERATE("5", "0");
|
||||
CAPTURE(wall_generator, relative_e, reduce_crossing_wall, minimum_travel);
|
||||
DynamicPrintConfig config = wipe_config(
|
||||
wall_generator, true, "50%", "10%", false, "3", "inner-outer-inner wall");
|
||||
config.set_deserialize_strict({
|
||||
{"gcode_flavor", "marlin2"},
|
||||
{"use_relative_e_distances", relative_e},
|
||||
{"reduce_crossing_wall", reduce_crossing_wall},
|
||||
{"retraction_minimum_travel", minimum_travel},
|
||||
{"retract_when_changing_layer", "0"},
|
||||
{"use_firmware_retraction", "0"},
|
||||
{"retract_before_wipe", "0%"},
|
||||
{"retract_after_wipe", "0%"},
|
||||
{"retraction_speed", "25.5"},
|
||||
{"role_based_wipe_speed", "0"},
|
||||
{"wipe_speed", "100"},
|
||||
{"z_hop", "0.4"},
|
||||
{"retract_lift_above", "0"},
|
||||
{"retract_lift_below", "0"},
|
||||
});
|
||||
config.set_key_value("z_hop_types", new ConfigOptionEnumsGeneric{zhtNormal});
|
||||
config.set_key_value("retract_lift_enforce", new ConfigOptionEnumsGeneric{rletAllSurfaces});
|
||||
const std::string output = slice({make_cube(10., 10., 1.)}, config);
|
||||
const auto &role_tag = GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Role);
|
||||
const auto &start_tag = GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Wipe_Start);
|
||||
const auto &end_tag = GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Wipe_End);
|
||||
ExtrusionRole role = erNone;
|
||||
bool after_outer_wall = false;
|
||||
bool in_wipe = false;
|
||||
size_t transitions = 0;
|
||||
size_t same_layer_transitions = 0;
|
||||
size_t inward_wipes = 0;
|
||||
double retraction = 0.;
|
||||
double lift = 0.;
|
||||
double outer_z = 0.;
|
||||
GCodeReader parser;
|
||||
parser.apply_config(config);
|
||||
parser.parse_buffer(output, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) {
|
||||
if (line.comment().find(role_tag) == 0)
|
||||
role = ExtrusionEntity::string_to_role(line.comment().substr(role_tag.size()));
|
||||
if (line.comment().find(start_tag) == 0) {
|
||||
in_wipe = true;
|
||||
if (after_outer_wall)
|
||||
++inward_wipes;
|
||||
} else if (line.comment().find(end_tag) == 0) {
|
||||
in_wipe = false;
|
||||
}
|
||||
if (line.extruding(self) && line.dist_XY(self) > EPSILON) {
|
||||
if (role == erExternalPerimeter) {
|
||||
after_outer_wall = true;
|
||||
retraction = lift = 0.;
|
||||
outer_z = line.new_Z(self);
|
||||
} else if (after_outer_wall) {
|
||||
REQUIRE(role == erPerimeter);
|
||||
++transitions;
|
||||
const double layer_rise = std::max(0., double(self.z()) - outer_z);
|
||||
if (layer_rise < EPSILON)
|
||||
++same_layer_transitions;
|
||||
// A 5 mm threshold suppresses retraction across a few wall widths.
|
||||
// A zero threshold still permits the ordinary retract and lift.
|
||||
const bool retract = std::stod(minimum_travel) == 0.;
|
||||
CHECK_THAT(retraction, Catch::Matchers::WithinAbs(retract ? 0.8 : 0., 0.00005));
|
||||
// Exclude an ordinary layer change from the accumulated upward motion.
|
||||
CHECK_THAT(lift - layer_rise, Catch::Matchers::WithinAbs(retract ? 0.4 : 0., 0.001));
|
||||
after_outer_wall = false;
|
||||
}
|
||||
} else if (after_outer_wall) {
|
||||
if (line.retracting(self))
|
||||
retraction -= line.dist_E(self);
|
||||
lift += std::max(0., double(line.dist_Z(self)));
|
||||
if (in_wipe)
|
||||
CHECK_THAT(line.dist_E(self), Catch::Matchers::WithinAbs(0., 0.00005));
|
||||
}
|
||||
});
|
||||
// The 1 mm cube has five 0.2 mm layers: every outer wall must still wipe.
|
||||
REQUIRE(transitions == 5);
|
||||
REQUIRE(same_layer_transitions >= 4);
|
||||
REQUIRE(inward_wipes == transitions);
|
||||
}
|
||||
|
||||
TEST_CASE("Changing inward wipe settings preserves the sliced geometry", "[Wipe][Regression]")
|
||||
{
|
||||
const char *key = GENERATE("wipe_inward", "wipe_inward_distance");
|
||||
DynamicPrintConfig config = wipe_config("classic", false);
|
||||
Print print;
|
||||
Model model;
|
||||
init_print({make_cube(10., 10., 1.)}, print, model, config);
|
||||
gcode(print);
|
||||
const PrintObject &object = *print.objects().front();
|
||||
REQUIRE(object.is_step_done(posPerimeters));
|
||||
REQUIRE(object.is_step_done(posInfill));
|
||||
REQUIRE(print.is_step_done(psWipeTower));
|
||||
REQUIRE(print.is_step_done(psGCodeExport));
|
||||
|
||||
DynamicPrintConfig changed = config;
|
||||
changed.set_deserialize_strict({{key, std::string(key) == "wipe_inward" ? "1" : "75%"}});
|
||||
print.apply(model, changed);
|
||||
|
||||
CHECK(print.objects().front()->is_step_done(posPerimeters));
|
||||
CHECK(print.objects().front()->is_step_done(posInfill));
|
||||
CHECK(print.is_step_done(psWipeTower));
|
||||
CHECK_FALSE(print.is_step_done(psGCodeExport));
|
||||
}
|
||||
|
||||
TEST_CASE("Retraction and pressure advance calibration suppress inward wipe overrides", "[Wipe][Regression]")
|
||||
{
|
||||
const auto mode = GENERATE(CalibMode::Calib_None, CalibMode::Calib_PA_Tower,
|
||||
CalibMode::Calib_Auto_PA_Line, CalibMode::Calib_Retraction_tower,
|
||||
CalibMode::Calib_Flow_Rate);
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
const bool per_object = GENERATE(false, true);
|
||||
INFO("calibration mode: " << int(mode) << ", wall generator: " << wall_generator
|
||||
<< ", per-object override: " << per_object);
|
||||
|
||||
const auto trajectories = [&](bool inward) {
|
||||
DynamicPrintConfig config = wipe_config(wall_generator, inward && !per_object);
|
||||
const std::vector<std::vector<ConfigBase::SetDeserializeItem>> overrides{
|
||||
{{"wipe_inward", inward ? "1" : "0"}}
|
||||
};
|
||||
Print print;
|
||||
Model model;
|
||||
init_print({make_cube(10., 10., 1.)}, print, model, config, per_object ? &overrides : nullptr);
|
||||
Calib_Params params;
|
||||
params.mode = mode;
|
||||
params.start = 0.2;
|
||||
params.end = 0.4;
|
||||
params.step = 0.1;
|
||||
print.set_calib_params(params);
|
||||
return wipe_destinations(gcode(print));
|
||||
};
|
||||
|
||||
const auto regular = trajectories(false);
|
||||
const auto inward = trajectories(true);
|
||||
REQUIRE_FALSE(regular.empty());
|
||||
REQUIRE_FALSE(inward.empty());
|
||||
// Other calibration modes and ordinary prints must still honor the option.
|
||||
const bool should_differ = mode == CalibMode::Calib_None || mode == CalibMode::Calib_Flow_Rate;
|
||||
CHECK(trajectories_differ(regular, inward) == should_differ);
|
||||
}
|
||||
|
||||
TEST_CASE("Inactive inward wipe settings preserve the exported trajectory", "[Wipe][Regression]")
|
||||
{
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
const bool disable_wiping = GENERATE(false, true);
|
||||
DynamicPrintConfig regular = wipe_config(wall_generator, false);
|
||||
DynamicPrintConfig inward = wipe_config(wall_generator, true, disable_wiping ? "50%" : "0");
|
||||
if (disable_wiping) {
|
||||
regular.set_deserialize_strict({{"wipe", "0"}});
|
||||
inward.set_deserialize_strict({{"wipe", "0"}});
|
||||
}
|
||||
const auto regular_paths = wipe_destinations(slice({make_cube(10., 10., 1.)}, regular));
|
||||
const auto inward_paths = wipe_destinations(slice({make_cube(10., 10., 1.)}, inward));
|
||||
if (!disable_wiping)
|
||||
REQUIRE_FALSE(regular_paths.empty());
|
||||
CHECK_FALSE(trajectories_differ(regular_paths, inward_paths));
|
||||
}
|
||||
|
||||
TEST_CASE("Inward wipe changes the exported trajectory when outer wall width is Auto", "[Wipe][Regression]")
|
||||
{
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
INFO("wall generator: " << wall_generator);
|
||||
|
||||
const std::vector<Vec2d> regular = wipe_destinations(
|
||||
slice({make_cube(10., 10., 1.)}, wipe_config(wall_generator, false)));
|
||||
const std::vector<Vec2d> inward = wipe_destinations(
|
||||
slice({make_cube(10., 10., 1.)}, wipe_config(wall_generator, true)));
|
||||
|
||||
REQUIRE_FALSE(regular.empty());
|
||||
REQUIRE_FALSE(inward.empty());
|
||||
REQUIRE(trajectories_differ(regular, inward));
|
||||
}
|
||||
|
||||
TEST_CASE("Inward wipe recognizes an external wall starting on an overhang", "[Wipe][Regression]")
|
||||
{
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
const bool inward = GENERATE(false, true);
|
||||
CAPTURE(wall_generator, inward);
|
||||
const auto config = wipe_config(wall_generator, inward, "50%", "0%", false,
|
||||
"3", "inner-outer-inner wall", false, "0%", "back");
|
||||
Print print;
|
||||
Model model;
|
||||
init_print({make_cube(10., 10., 1.)}, print, model, config);
|
||||
print.process();
|
||||
size_t mixed_loops = 0;
|
||||
const auto mark_overhangs = [&](auto &&self, ExtrusionEntity *entity) -> void {
|
||||
if (auto *collection = dynamic_cast<ExtrusionEntityCollection *>(entity)) {
|
||||
for (ExtrusionEntity *child : collection->entities)
|
||||
self(self, child);
|
||||
} else if (auto *loop = dynamic_cast<ExtrusionLoop *>(entity); loop && is_external_perimeter(loop->role())) {
|
||||
// Keep the printed geometry intact and give the back seam overhang
|
||||
// roles. The front edge remains an ordinary external-wall segment.
|
||||
ExtrusionPaths paths;
|
||||
bool has_overhang = false;
|
||||
bool has_external = false;
|
||||
for (const ExtrusionPath &source : loop->paths) {
|
||||
for (size_t i = 1; i < source.polyline.points.size(); ++i) {
|
||||
ExtrusionPath path = source;
|
||||
path.polyline.points = {source.polyline.points[i - 1], source.polyline.points[i]};
|
||||
const bool overhang = path.polyline.points.front().y() > 0 || path.polyline.points.back().y() > 0;
|
||||
path.set_extrusion_role(overhang ? erOverhangPerimeter : erExternalPerimeter);
|
||||
has_overhang |= overhang;
|
||||
has_external |= !overhang;
|
||||
paths.push_back(std::move(path));
|
||||
}
|
||||
}
|
||||
REQUIRE(has_overhang);
|
||||
REQUIRE(has_external);
|
||||
loop->paths = std::move(paths);
|
||||
++mixed_loops;
|
||||
}
|
||||
};
|
||||
for (const PrintObject *object : print.objects())
|
||||
for (Layer *layer : object->layers())
|
||||
for (LayerRegion *region : layer->regions())
|
||||
mark_overhangs(mark_overhangs, ®ion->perimeters);
|
||||
REQUIRE(mixed_loops > 0);
|
||||
|
||||
bool has_inward_wipe = false;
|
||||
for (const WipeTrajectory &trajectory : wipe_trajectories(gcode(print))) {
|
||||
if (trajectory.destinations.empty())
|
||||
continue;
|
||||
const Vec2d move = trajectory.destinations.front() - trajectory.start;
|
||||
if (trajectory.start.x() > 4. && trajectory.start.y() > 4. && move.x() < -0.05 && move.y() < -0.05)
|
||||
has_inward_wipe = true;
|
||||
}
|
||||
CHECK(has_inward_wipe == inward);
|
||||
}
|
||||
|
||||
TEST_CASE("Inward wipe keeps its offset when seam gap is zero", "[Wipe][Regression]")
|
||||
{
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
INFO("wall generator: " << wall_generator);
|
||||
|
||||
const std::vector<Vec2d> regular = wipe_destinations(
|
||||
slice({make_cube(10., 10., 1.)}, wipe_config(wall_generator, false, "50%", "0%")));
|
||||
const std::vector<Vec2d> inward = wipe_destinations(
|
||||
slice({make_cube(10., 10., 1.)}, wipe_config(wall_generator, true, "50%", "0%")));
|
||||
|
||||
REQUIRE_FALSE(regular.empty());
|
||||
REQUIRE_FALSE(inward.empty());
|
||||
REQUIRE(trajectories_differ(regular, inward));
|
||||
}
|
||||
|
||||
TEST_CASE("Inward wipe is retained across layers with a back seam", "[Wipe][Regression]")
|
||||
{
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
INFO("wall generator: " << wall_generator);
|
||||
|
||||
const DynamicPrintConfig inward_config = wipe_config(
|
||||
wall_generator, true, "50%", "0%", false, "3", "inner-outer-inner wall", false, "0%", "back");
|
||||
const std::vector<WipeTrajectory> inward = wipe_trajectories(slice({make_cube(27., 27., 1.)}, inward_config));
|
||||
|
||||
REQUIRE_FALSE(inward.empty());
|
||||
std::map<double, bool> inward_wipe_by_layer;
|
||||
for (const WipeTrajectory &trajectory : inward) {
|
||||
bool &has_inward_wipe = inward_wipe_by_layer[trajectory.z];
|
||||
if (trajectory.destinations.empty())
|
||||
continue;
|
||||
const Vec2d first_move = trajectory.destinations.front() - trajectory.start;
|
||||
// Orca: a back seam lands on the cube's positive-X/positive-Y corner.
|
||||
// Its inward wipe must move diagonally away from both external faces.
|
||||
has_inward_wipe = has_inward_wipe ||
|
||||
(trajectory.start.x() > 13. && trajectory.start.y() > 13. &&
|
||||
first_move.x() < -0.05 && first_move.y() < -0.05);
|
||||
}
|
||||
REQUIRE(inward_wipe_by_layer.size() == 5);
|
||||
for (const auto &[z, has_inward_wipe] : inward_wipe_by_layer) {
|
||||
INFO("layer Z: " << z);
|
||||
REQUIRE(has_inward_wipe);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Literal inward wipe distance is clamped to the outer wall width", "[Wipe][Regression]")
|
||||
{
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
INFO("wall generator: " << wall_generator);
|
||||
|
||||
const std::vector<Vec2d> regular = wipe_destinations(
|
||||
slice({make_cube(10., 10., 1.)}, wipe_config(wall_generator, false)));
|
||||
const std::vector<Vec2d> full_width = wipe_destinations(
|
||||
slice({make_cube(10., 10., 1.)}, wipe_config(wall_generator, true, "100%")));
|
||||
const std::vector<Vec2d> oversized = wipe_destinations(
|
||||
slice({make_cube(10., 10., 1.)}, wipe_config(wall_generator, true, "2")));
|
||||
|
||||
REQUIRE_FALSE(full_width.empty());
|
||||
REQUIRE(trajectories_differ(regular, full_width));
|
||||
REQUIRE(oversized.size() == full_width.size());
|
||||
for (size_t i = 0; i < full_width.size(); ++i)
|
||||
REQUIRE_THAT((oversized[i] - full_width[i]).norm(), Catch::Matchers::WithinAbs(0., 0.01));
|
||||
}
|
||||
|
||||
TEST_CASE("Inward wipe is not applied without an adjacent wall", "[Wipe][Regression]")
|
||||
{
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
INFO("wall generator: " << wall_generator);
|
||||
|
||||
const std::vector<Vec2d> regular = wipe_destinations(
|
||||
slice({make_cube(10., 10., 1.)}, wipe_config(wall_generator, false, "50%", "10%", false, "1")));
|
||||
const std::vector<Vec2d> inward = wipe_destinations(
|
||||
slice({make_cube(10., 10., 1.)}, wipe_config(wall_generator, true, "50%", "10%", false, "1")));
|
||||
|
||||
REQUIRE_FALSE(regular.empty());
|
||||
REQUIRE_FALSE(trajectories_differ(regular, inward));
|
||||
}
|
||||
|
||||
TEST_CASE("Inward wipe uses an alternate extra wall when the configured wall count is one", "[Wipe][Regression]")
|
||||
{
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
INFO("wall generator: " << wall_generator);
|
||||
|
||||
const DynamicPrintConfig regular_config = wipe_config(
|
||||
wall_generator, false, "50%", "10%", false, "1", "inner wall/outer wall", true, "15%");
|
||||
const DynamicPrintConfig inward_config = wipe_config(
|
||||
wall_generator, true, "50%", "10%", false, "1", "inner wall/outer wall", true, "15%");
|
||||
const std::vector<Vec2d> regular = wipe_destinations(
|
||||
slice({make_cube(10., 10., 1.)}, regular_config));
|
||||
const std::vector<Vec2d> inward = wipe_destinations(
|
||||
slice({make_cube(10., 10., 1.)}, inward_config));
|
||||
|
||||
REQUIRE_FALSE(regular.empty());
|
||||
REQUIRE_FALSE(inward.empty());
|
||||
REQUIRE(trajectories_differ(regular, inward));
|
||||
}
|
||||
|
||||
TEST_CASE("Inward wipe is not applied before the adjacent wall is printed", "[Wipe][Regression]")
|
||||
{
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
INFO("wall generator: " << wall_generator);
|
||||
|
||||
const std::vector<Vec2d> regular = wipe_destinations(
|
||||
slice({make_cube(10., 10., 1.)}, wipe_config(
|
||||
wall_generator, false, "50%", "10%", false, "2", "outer wall/inner wall")));
|
||||
const std::vector<Vec2d> inward = wipe_destinations(
|
||||
slice({make_cube(10., 10., 1.)}, wipe_config(
|
||||
wall_generator, true, "50%", "10%", false, "2", "outer wall/inner wall")));
|
||||
|
||||
REQUIRE_FALSE(regular.empty());
|
||||
REQUIRE_FALSE(trajectories_differ(regular, inward));
|
||||
}
|
||||
|
||||
TEST_CASE("Wipe on loops preserves the corner move with inward wipe disabled", "[Wipe][Regression]")
|
||||
{
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
const char *nozzle_diameter = GENERATE("0.4", "0.8");
|
||||
const char *comments = GENERATE("0", "1");
|
||||
CAPTURE(comments);
|
||||
INFO("wall generator: " << wall_generator << ", nozzle diameter: " << nozzle_diameter);
|
||||
// A closed square gives a 90-degree material-side corner at the seam.
|
||||
DynamicPrintConfig config = wipe_config(wall_generator, false, "50%", "0", true);
|
||||
config.set_deserialize_strict({{"nozzle_diameter", nozzle_diameter}, {"seam_position", "nearest"},
|
||||
{"gcode_comments", comments}});
|
||||
const std::string output = slice({make_cube(10., 10., 1.)}, config);
|
||||
const auto &role_tag = GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Role);
|
||||
const auto &wipe_tag = GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Wipe_Start);
|
||||
ExtrusionRole role = erNone;
|
||||
std::vector<Vec2d> loop;
|
||||
bool after_extrusion = false;
|
||||
size_t moves = 0;
|
||||
GCodeReader parser;
|
||||
parser.apply_config(config);
|
||||
parser.parse_buffer(output, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) {
|
||||
if (line.comment().find(role_tag) == 0) {
|
||||
role = ExtrusionEntity::string_to_role(line.comment().substr(role_tag.size()));
|
||||
loop.clear();
|
||||
after_extrusion = false;
|
||||
}
|
||||
if (line.comment().find(wipe_tag) == 0)
|
||||
after_extrusion = false;
|
||||
if (role != erExternalPerimeter)
|
||||
return;
|
||||
if (line.extruding(self) && line.dist_XY(self) > EPSILON) {
|
||||
if (loop.empty())
|
||||
loop.emplace_back(self.x(), self.y());
|
||||
loop.emplace_back(line.new_X(self), line.new_Y(self));
|
||||
after_extrusion = true;
|
||||
return;
|
||||
}
|
||||
// The loop move is the first non-extruding XY move after the external
|
||||
// wall and before the reserved wipe marker, regardless of comment text.
|
||||
if (!after_extrusion || line.dist_XY(self) <= EPSILON)
|
||||
return;
|
||||
after_extrusion = false;
|
||||
|
||||
++moves;
|
||||
INFO("layer Z: " << self.z());
|
||||
REQUIRE(loop.size() >= 4);
|
||||
const Vec2d seam = loop.front();
|
||||
REQUIRE_THAT((loop.back() - seam).norm(), Catch::Matchers::WithinAbs(0., 0.003));
|
||||
const Vec2d outgoing = (loop[1] - seam).normalized();
|
||||
const Vec2d into_corner = (loop[loop.size() - 2] - seam).normalized();
|
||||
REQUIRE_THAT(outgoing.dot(into_corner), Catch::Matchers::WithinAbs(0., 0.01));
|
||||
const Vec2d move = Vec2d(line.new_X(self), line.new_Y(self)) - seam;
|
||||
// The legacy corner move is 20% of the nozzle diameter, turned 30 degrees
|
||||
// from the outgoing edge into the square. Check both components independently.
|
||||
const double distance = 0.2 * std::stod(nozzle_diameter);
|
||||
CHECK_THAT(move.dot(outgoing), Catch::Matchers::WithinAbs(distance * std::sqrt(3.) / 2., 0.003));
|
||||
CHECK_THAT(move.dot(into_corner), Catch::Matchers::WithinAbs(distance / 2., 0.003));
|
||||
});
|
||||
REQUIRE(moves == 5);
|
||||
}
|
||||
|
||||
TEST_CASE("Inward wipe remains valid after wipe on loops moves the nozzle", "[Wipe][Regression]")
|
||||
{
|
||||
const char *wall_generator = GENERATE("classic", "arachne");
|
||||
const char *comments = GENERATE("0", "1");
|
||||
CAPTURE(comments);
|
||||
INFO("wall generator: " << wall_generator);
|
||||
|
||||
DynamicPrintConfig config = wipe_config(wall_generator, false, "50%", "10%", true);
|
||||
config.set_deserialize_strict({{"gcode_comments", comments}});
|
||||
const std::string loop_move = slice({make_cube(10., 10., 1.)}, config);
|
||||
config.set_deserialize_strict({{"wipe_inward", "1"}});
|
||||
const std::string combined = slice({make_cube(10., 10., 1.)}, config);
|
||||
config.set_deserialize_strict({{"wipe_on_loops", "0"}});
|
||||
const std::string inward_only = slice({make_cube(10., 10., 1.)}, config);
|
||||
|
||||
for (const std::string *output : {&loop_move, &combined}) {
|
||||
INFO("wipe_inward: " << (output == &combined));
|
||||
std::map<double, std::vector<Vec2d>> loop_moves_by_layer;
|
||||
const auto &role_tag = GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Role);
|
||||
const auto &wipe_tag = GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Wipe_Start);
|
||||
ExtrusionRole role = erNone;
|
||||
bool after_extrusion = false;
|
||||
GCodeReader parser;
|
||||
parser.apply_config(config);
|
||||
parser.parse_buffer(*output, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) {
|
||||
if (line.comment().find(role_tag) == 0) {
|
||||
role = ExtrusionEntity::string_to_role(line.comment().substr(role_tag.size()));
|
||||
after_extrusion = false;
|
||||
}
|
||||
if (line.comment().find(wipe_tag) == 0)
|
||||
after_extrusion = false;
|
||||
if (role != erExternalPerimeter || line.dist_XY(self) <= EPSILON)
|
||||
return;
|
||||
if (line.extruding(self)) {
|
||||
after_extrusion = true;
|
||||
} else if (after_extrusion) {
|
||||
loop_moves_by_layer[line.new_Z(self)].emplace_back(line.new_X(self), line.new_Y(self));
|
||||
after_extrusion = false;
|
||||
}
|
||||
});
|
||||
|
||||
// The 1 mm cube at 0.2 mm layer height has one external loop on each of five layers.
|
||||
const auto trajectories = wipe_trajectories(*output);
|
||||
REQUIRE(loop_moves_by_layer.size() == 5);
|
||||
for (size_t layer = 1; layer <= 5; ++layer) {
|
||||
const double z = layer * 0.2;
|
||||
const auto moves = std::find_if(loop_moves_by_layer.begin(), loop_moves_by_layer.end(),
|
||||
[z](const auto &entry) { return std::abs(entry.first - z) < 0.001; });
|
||||
REQUIRE(moves != loop_moves_by_layer.end());
|
||||
REQUIRE(moves->second.size() == 1);
|
||||
const auto wipe = std::find_if(trajectories.begin(), trajectories.end(), [&](const WipeTrajectory &trajectory) {
|
||||
return std::abs(trajectory.z - z) < 0.001 &&
|
||||
(trajectory.start - moves->second.front()).norm() < 0.001;
|
||||
});
|
||||
REQUIRE(wipe != trajectories.end());
|
||||
// The configured 2 mm wipe must be measured from the inward move's
|
||||
// endpoint, including when wipe_inward is off (set_last_pos regression).
|
||||
CHECK_THAT(trajectory_length(*wipe), Catch::Matchers::WithinAbs(2., 0.003));
|
||||
}
|
||||
}
|
||||
|
||||
const std::vector<WipeTrajectory> combined_trajectories = wipe_trajectories(combined);
|
||||
const std::vector<WipeTrajectory> inward_trajectories = wipe_trajectories(inward_only);
|
||||
REQUIRE_FALSE(combined_trajectories.empty());
|
||||
REQUIRE(combined_trajectories.size() == inward_trajectories.size());
|
||||
REQUIRE(trajectories_differ(wipe_destinations(combined), wipe_destinations(loop_move)));
|
||||
|
||||
bool start_changed = false;
|
||||
for (size_t i = 0; i < combined_trajectories.size(); ++i) {
|
||||
start_changed = start_changed ||
|
||||
(combined_trajectories[i].start - inward_trajectories[i].start).norm() > 0.01;
|
||||
REQUIRE_THAT(trajectory_length(combined_trajectories[i]),
|
||||
Catch::Matchers::WithinAbs(trajectory_length(inward_trajectories[i]), 0.01));
|
||||
}
|
||||
REQUIRE(start_changed);
|
||||
}
|
||||
@@ -152,6 +152,8 @@ static DynamicPrintConfig wipe_tower_toolchange_config(const std::string &gcode_
|
||||
{ "outer_wall_filament_id", 2 },
|
||||
{ "inner_wall_filament_id", 2 },
|
||||
{ "enable_prime_tower", true },
|
||||
{ "wipe_tower_x", 50 }, // inside the 200x200 test bed
|
||||
{ "wipe_tower_y", 50 }, // (the default y, 220, is not)
|
||||
{ "layer_height", 0.3 },
|
||||
{ "gcode_flavor", gcode_flavor },
|
||||
});
|
||||
@@ -182,3 +184,148 @@ TEST_CASE("The wipe tower's toolchange planner flush follows the gcode flavor",
|
||||
CHECK_THAT(tower, !Catch::Matchers::ContainsSubstring(unexpected));
|
||||
}
|
||||
}
|
||||
|
||||
// What Print feeds the shared estimate. The libslic3r WipeTowerEstimate cases cannot see this:
|
||||
// they call the estimator directly. The estimate counts the filaments the print really uses,
|
||||
// so the two-filament shape gives the outer wall the second one.
|
||||
static DynamicPrintConfig tower_estimate_config(const char *wall_type, unsigned int filaments = 2)
|
||||
{
|
||||
// 100 mm3 per purge on a 50 mm wide tower: one purge is 100/(layer_height * 50) of depth.
|
||||
return multifilament_config(filaments, {
|
||||
{ "outer_wall_filament_id", filaments == 2 ? "2" : "1" },
|
||||
{ "enable_prime_tower", "1" },
|
||||
{ "wipe_tower_wall_type", wall_type },
|
||||
{ "prime_tower_width", "50" },
|
||||
{ "prime_volume", "100" },
|
||||
{ "prime_tower_infill_gap", "100%" },
|
||||
{ "prime_tower_brim_width", "3" },
|
||||
{ "purge_in_prime_tower", "0" },
|
||||
{ "single_extruder_multi_material", "0" },
|
||||
{ "timelapse_type", "0" },
|
||||
{ "layer_height", "0.2" },
|
||||
{ "enable_wrapping_detection", "0" },
|
||||
{ "raft_layers", "0" } });
|
||||
}
|
||||
|
||||
TEST_CASE("The tower is sized for the thinnest layer any object on the plate is sliced at", "[WipeTower]")
|
||||
{
|
||||
// The tower has to survive its thinnest layer, so an override finer than the preset drives
|
||||
// the estimate even on the second object. Two 20 mm cubes, the second at 0.1 mm.
|
||||
const DynamicPrintConfig config = tower_estimate_config("rectangle");
|
||||
const std::vector<std::vector<ConfigBase::SetDeserializeItem>> overrides = {
|
||||
{}, { { "layer_height", "0.1" } } };
|
||||
|
||||
Print print;
|
||||
Model model;
|
||||
init_print({ cube(20), cube(20) }, print, model, config, &overrides);
|
||||
|
||||
// One purge at 0.1 mm: 100 / (0.1 * 50) = 20 mm, above the 20 mm-tall tower's stability
|
||||
// floor. At the preset's 0.2 mm it would be half that, so the two are easy to tell apart.
|
||||
const float floor_20mm = WipeTower::get_limit_depth_by_height(20.f);
|
||||
REQUIRE(floor_20mm < 10.f);
|
||||
CHECK_THAT(print.wipe_tower_data(2).depth, Catch::Matchers::WithinAbs(20., 1e-4));
|
||||
}
|
||||
|
||||
TEST_CASE("Validation is given the tower's effective width, not the configured one", "[WipeTower]")
|
||||
{
|
||||
// A rib wall squares the tower, so its width is its depth. Validation reads this rather
|
||||
// than re-deriving the rule from the wall type.
|
||||
Print print;
|
||||
Model model;
|
||||
|
||||
SECTION("a rectangle wall keeps the configured width") {
|
||||
const DynamicPrintConfig config = tower_estimate_config("rectangle");
|
||||
init_print({ cube(20) }, print, model, config);
|
||||
const WipeTowerData &data = print.wipe_tower_data(2);
|
||||
CHECK_THAT(data.width, Catch::Matchers::WithinAbs(50., 1e-4));
|
||||
CHECK(data.depth < data.width);
|
||||
}
|
||||
|
||||
SECTION("a rib wall reports the squared footprint") {
|
||||
const DynamicPrintConfig config = tower_estimate_config("rib");
|
||||
init_print({ cube(20) }, print, model, config);
|
||||
const WipeTowerData &data = print.wipe_tower_data(2);
|
||||
CHECK_THAT(data.width, Catch::Matchers::WithinAbs(data.depth, 1e-4));
|
||||
CHECK(data.width > 0.f);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Generating the tower keeps its reported width current", "[WipeTower]")
|
||||
{
|
||||
// width is handed out after the slice, so leaving it at the estimate reports a zero-width
|
||||
// tower to every post-generation consumer.
|
||||
const DynamicPrintConfig config = wipe_tower_toolchange_config("marlin");
|
||||
Print print;
|
||||
Model model;
|
||||
init_print({ cube(10) }, print, model, config);
|
||||
print.apply(model, config);
|
||||
REQUIRE(print.wipe_tower_data(2).width > 0.f);
|
||||
|
||||
print.process();
|
||||
REQUIRE(print.is_step_done(psWipeTower));
|
||||
const WipeTowerData &data = print.wipe_tower_data();
|
||||
// A width the generator never wrote reads as zero. A rib wall squares the tower, so the
|
||||
// generated width is the body square: under the configured 50 mm, and inside the depth.
|
||||
CHECK(data.width > 0.f);
|
||||
CHECK(data.width < 50.f);
|
||||
CHECK(data.width <= data.depth + EPSILON);
|
||||
}
|
||||
|
||||
TEST_CASE("A single-filament plate reserves a tower only when one is actually printed", "[WipeTower]")
|
||||
{
|
||||
// The estimate has to answer this the way Print::apply does: reporting no tower for one
|
||||
// that is built collapses the validation hull to a point, and reporting one for a tower
|
||||
// that is not built takes that bed area away from the arranger and draws a preview box
|
||||
// over nothing.
|
||||
Print print;
|
||||
Model model;
|
||||
|
||||
SECTION("no tool change and nothing else that prints one") {
|
||||
const DynamicPrintConfig config = tower_estimate_config("rib", 1);
|
||||
init_print({ cube(20) }, print, model, config);
|
||||
REQUIRE_FALSE(print.has_wipe_tower());
|
||||
CHECK_THAT(print.wipe_tower_data(1).depth, Catch::Matchers::WithinAbs(0., 1e-6));
|
||||
}
|
||||
|
||||
// A raft puts the tower on every layer below the object, but only where there is a tower:
|
||||
// Print::apply runs normalize_fdm_2, which clears enable_prime_tower for a plate that
|
||||
// purges one filament and has neither smooth timelapse nor wrapping detection on.
|
||||
SECTION("a raft alone does not print one") {
|
||||
DynamicPrintConfig config = tower_estimate_config("rib", 1);
|
||||
config.set_deserialize_strict({ { "raft_layers", "3" } });
|
||||
init_print({ cube(20) }, print, model, config);
|
||||
REQUIRE_FALSE(print.config().enable_prime_tower.value);
|
||||
REQUIRE_FALSE(print.has_wipe_tower());
|
||||
CHECK_THAT(print.wipe_tower_data(1).depth, Catch::Matchers::WithinAbs(0., 1e-6));
|
||||
}
|
||||
|
||||
SECTION("smooth timelapse prints one, and keeps enable_prime_tower on") {
|
||||
DynamicPrintConfig config = tower_estimate_config("rib", 1);
|
||||
config.set_deserialize_strict({ { "timelapse_type", "1" } });
|
||||
init_print({ cube(20) }, print, model, config);
|
||||
REQUIRE(print.has_wipe_tower());
|
||||
CHECK(print.wipe_tower_data(1).depth > 0.f);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("A tower printed without a tool change is still validated against the bed", "[WipeTower]")
|
||||
{
|
||||
// Wrapping detection prints a tower on a plate that purges one filament. Neither the old
|
||||
// estimate (which read the wall type and smooth timelapse) nor the old containment gate (the
|
||||
// filament count or smooth timelapse) knew about it, so between them that tower was never
|
||||
// checked against the bed.
|
||||
Print print;
|
||||
Model model;
|
||||
DynamicPrintConfig config = tower_estimate_config("rectangle", 1);
|
||||
// Relative E without a per-layer G92 is rejected before the tower is ever looked at, and
|
||||
// has_wipe_tower() wants a real exclusion polygon before it honours wrapping detection.
|
||||
config.set_deserialize_strict({ { "enable_wrapping_detection", "1" },
|
||||
{ "wrapping_exclude_area", "180x180,190x180,190x190,180x190" },
|
||||
{ "wipe_tower_x", "500" }, { "wipe_tower_y", "500" }, { "use_relative_e_distances", "0" } });
|
||||
|
||||
init_print({ cube(20) }, print, model, config);
|
||||
REQUIRE(print.extruders(true).size() == 1);
|
||||
REQUIRE(print.has_wipe_tower());
|
||||
CHECK(print.wipe_tower_data(1).depth > 0.f);
|
||||
CHECK_THAT(print.validate().string, Catch::Matchers::ContainsSubstring("printable area"));
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -18,6 +19,7 @@ add_executable(${_TEST_NAME}_tests
|
||||
test_preset_setting_id.cpp
|
||||
test_preset_diff.cpp
|
||||
test_vendor_cache.cpp
|
||||
test_preset_options.cpp
|
||||
test_elephant_foot_compensation.cpp
|
||||
test_fill_corner_smoothing.cpp
|
||||
test_filament_mixer.cpp
|
||||
@@ -28,16 +30,21 @@ add_executable(${_TEST_NAME}_tests
|
||||
test_polygon.cpp
|
||||
test_mutable_polygon.cpp
|
||||
test_mutable_priority_queue.cpp
|
||||
test_minimum_spanning_tree.cpp
|
||||
test_nozzle_volume_type.cpp
|
||||
test_step.cpp
|
||||
test_stl.cpp
|
||||
test_triangle_selector.cpp
|
||||
test_meshboolean.cpp
|
||||
test_marchingsquares.cpp
|
||||
test_lay_on_face.cpp
|
||||
test_model.cpp
|
||||
test_utils.cpp
|
||||
test_timeutils.cpp
|
||||
test_voronoi.cpp
|
||||
test_wipe_tower_estimate.cpp
|
||||
test_wipe_tower.cpp
|
||||
test_wipe_path.cpp
|
||||
test_optimizers.cpp
|
||||
test_ordering_strategies.cpp
|
||||
# test_png_io.cpp
|
||||
@@ -46,6 +53,17 @@ add_executable(${_TEST_NAME}_tests
|
||||
../libnest2d/printer_parts.cpp
|
||||
)
|
||||
|
||||
if (SLIC3R_CAD)
|
||||
target_sources(${_TEST_NAME}_tests PRIVATE
|
||||
test_caddocument.cpp
|
||||
test_sketchconstraints.cpp
|
||||
test_sketchedit.cpp
|
||||
test_sketchprofile.cpp
|
||||
test_sketchimport.cpp
|
||||
test_sketchinference.cpp
|
||||
test_slvs_constraints.cpp)
|
||||
endif ()
|
||||
|
||||
if (TARGET OpenVDB::openvdb)
|
||||
target_sources(${_TEST_NAME}_tests PRIVATE test_hollowing.cpp)
|
||||
endif()
|
||||
|
||||
@@ -1,18 +1,24 @@
|
||||
|
||||
#include "libslic3r/Model.hpp"
|
||||
#include "libslic3r/TriangleSelector.hpp"
|
||||
#include "libslic3r/Format/3mf.hpp"
|
||||
#include "libslic3r/Format/bbs_3mf.hpp"
|
||||
#include "libslic3r/Format/STL.hpp"
|
||||
#include "libslic3r/miniz_extension.hpp"
|
||||
#include "libslic3r/Zipper.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
#include "libslic3r/Semver.hpp"
|
||||
#include "libslic3r/Preset.hpp"
|
||||
#include "libslic3r/MultiNozzleUtils.hpp"
|
||||
#include "libslic3r/ProjectTask.hpp"
|
||||
#include "libslic3r/PublishSettings.hpp"
|
||||
|
||||
#include "test_utils.hpp"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <boost/filesystem/operations.hpp>
|
||||
#include <boost/algorithm/string/predicate.hpp>
|
||||
#include <algorithm>
|
||||
|
||||
#include <catch2/catch_tostring.hpp>
|
||||
#include <Eigen/Core>
|
||||
@@ -141,6 +147,236 @@ SCENARIO("Export+Import geometry to/from 3mf file cycle", "[3mf]") {
|
||||
}
|
||||
}
|
||||
|
||||
// The recipe is an opaque binary blob (CadDocument::serialize_recipe()), so the 3mf backend has
|
||||
// to carry it byte-for-byte — no XML/text mangling, embedded NULs intact.
|
||||
static std::string make_cad_recipe()
|
||||
{
|
||||
// Built from an explicit length, not append(const char*), which would stop at the first
|
||||
// embedded NUL — the one thing this blob exists to prove survives the archive.
|
||||
static const char blob[] = "\x01" "RECIPE" "\0" "\xff\xfe\x00\x10" "cad-features-blob";
|
||||
return std::string(blob, sizeof(blob) - 1);
|
||||
}
|
||||
|
||||
static const std::string CAD_RECIPE_ENTRY = "Metadata/orca_cad.bin";
|
||||
static const std::string LEGACY_CAD_RECIPE_ENTRY = "Metadata/SnapOrca_cad.bin";
|
||||
|
||||
// Pulls one named entry out of a 3mf archive; false when it is absent.
|
||||
static bool read_cad_recipe_entry(const std::string& path, std::string& out,
|
||||
const std::string& entry = CAD_RECIPE_ENTRY)
|
||||
{
|
||||
mz_zip_archive zip;
|
||||
mz_zip_zero_struct(&zip);
|
||||
REQUIRE(open_zip_reader(&zip, path));
|
||||
bool found = false;
|
||||
mz_uint n = mz_zip_reader_get_num_files(&zip);
|
||||
for (mz_uint i = 0; i < n; ++i) {
|
||||
mz_zip_archive_file_stat st;
|
||||
if (!mz_zip_reader_file_stat(&zip, i, &st)) continue;
|
||||
std::string name(st.m_filename);
|
||||
std::replace(name.begin(), name.end(), '\\', '/');
|
||||
if (boost::algorithm::iequals(name, entry)) {
|
||||
out.resize(st.m_uncomp_size);
|
||||
found = mz_zip_reader_extract_to_mem(&zip, i, out.data(), out.size(), 0) != 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
close_zip_reader(&zip);
|
||||
return found;
|
||||
}
|
||||
|
||||
// Rewrites the archive at `path` with the recipe entry back under the name it had before the
|
||||
// rename, which is what every project saved by an earlier build looks like on disk. Generated
|
||||
// rather than checked in because a whole project archive is not frozen evidence the way a bare
|
||||
// recipe blob is -- it has to be whatever today's exporter writes, with only the name aged.
|
||||
// miniz cannot rename in place and open_zip_writer truncates, so the entries are held across
|
||||
// the switch.
|
||||
static void rename_cad_recipe_entry_to_legacy(const std::string& path)
|
||||
{
|
||||
std::vector<std::pair<std::string, std::string>> entries;
|
||||
bool renamed = false;
|
||||
{
|
||||
mz_zip_archive zip;
|
||||
mz_zip_zero_struct(&zip);
|
||||
REQUIRE(open_zip_reader(&zip, path));
|
||||
mz_uint n = mz_zip_reader_get_num_files(&zip);
|
||||
for (mz_uint i = 0; i < n; ++i) {
|
||||
mz_zip_archive_file_stat st;
|
||||
REQUIRE(mz_zip_reader_file_stat(&zip, i, &st));
|
||||
if (st.m_is_directory) continue;
|
||||
std::string name(st.m_filename);
|
||||
std::replace(name.begin(), name.end(), '\\', '/');
|
||||
std::string data((size_t) st.m_uncomp_size, '\0');
|
||||
if (st.m_uncomp_size > 0)
|
||||
REQUIRE(mz_zip_reader_extract_to_mem(&zip, i, data.data(), data.size(), 0));
|
||||
if (boost::algorithm::iequals(name, CAD_RECIPE_ENTRY)) {
|
||||
name = LEGACY_CAD_RECIPE_ENTRY;
|
||||
renamed = true;
|
||||
}
|
||||
entries.emplace_back(std::move(name), std::move(data));
|
||||
}
|
||||
close_zip_reader(&zip);
|
||||
}
|
||||
// Without this the scenario would degrade silently into re-testing the new name if the
|
||||
// exporter's constant ever moved again: every load below would still pass.
|
||||
REQUIRE(renamed);
|
||||
|
||||
Zipper out(path);
|
||||
for (const auto& e : entries)
|
||||
out.add_entry(e.first, e.second.data(), e.second.size());
|
||||
out.finalize();
|
||||
}
|
||||
|
||||
// The recipe lives only in the BBS-native backend, because that is the only one that runs:
|
||||
// store_bbs_3mf is the sole exporter the app calls, and 3mf.cpp's load_3mf is reached only for
|
||||
// files fingerprinted as PrusaSlicer's, which never carry a recipe. This locks in both halves:
|
||||
// the archive entry is at the exact path the importer looks for, and the recipe comes back
|
||||
// through the real importer.
|
||||
SCENARIO("CAD recipe is embedded in the BBS 3mf archive", "[3mf][CAD]") {
|
||||
GIVEN("a model carrying a binary cad_recipe") {
|
||||
Model model;
|
||||
std::string src = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
|
||||
REQUIRE(load_stl(src.c_str(), &model));
|
||||
model.add_default_instances();
|
||||
|
||||
// store_bbs_3mf stages its metadata through the model's backup path; point it at a
|
||||
// writable temp dir, as the sibling BBS scenarios do. The process-global
|
||||
// set_temporary_dir() would leak into every test that ran afterwards.
|
||||
ScopedTemporaryDir backup_dir("orca_cad");
|
||||
model.set_backup_path(backup_dir.string());
|
||||
|
||||
const std::string recipe = make_cad_recipe();
|
||||
model.cad_recipe = recipe;
|
||||
|
||||
WHEN("saved through the BBS backend (the format the GUI uses)") {
|
||||
ScopedTemporaryFile temp(".3mf");
|
||||
const std::string test_file = temp.string();
|
||||
|
||||
DynamicPrintConfig cfg;
|
||||
StoreParams sp;
|
||||
sp.path = test_file.c_str();
|
||||
sp.model = &model;
|
||||
sp.config = &cfg;
|
||||
sp.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
|
||||
REQUIRE(store_bbs_3mf(sp));
|
||||
|
||||
THEN("the archive entry is present byte-for-byte") {
|
||||
std::string got;
|
||||
REQUIRE(read_cad_recipe_entry(test_file, got));
|
||||
REQUIRE(got.size() == recipe.size());
|
||||
REQUIRE(got == recipe);
|
||||
}
|
||||
|
||||
THEN("the importer restores it onto the loaded model") {
|
||||
Model dst_model;
|
||||
ScopedTemporaryDir dst_backup_dir("orca_cad_dst");
|
||||
dst_model.set_backup_path(dst_backup_dir.string());
|
||||
|
||||
DynamicPrintConfig dst_config;
|
||||
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
|
||||
PlateDataPtrs dst_plates;
|
||||
std::vector<Preset*> project_presets;
|
||||
bool is_bbl_3mf = false, is_orca_3mf = false;
|
||||
Semver file_version;
|
||||
REQUIRE(load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
|
||||
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
|
||||
LoadStrategy::LoadModel | LoadStrategy::LoadConfig));
|
||||
REQUIRE(dst_model.cad_recipe.size() == recipe.size());
|
||||
REQUIRE(dst_model.cad_recipe == recipe);
|
||||
|
||||
release_PlateData_list(dst_plates);
|
||||
}
|
||||
}
|
||||
|
||||
WHEN("the same model is saved with no recipe") {
|
||||
model.cad_recipe.clear();
|
||||
ScopedTemporaryFile temp(".3mf");
|
||||
const std::string test_file = temp.string();
|
||||
|
||||
DynamicPrintConfig cfg;
|
||||
StoreParams sp;
|
||||
sp.path = test_file.c_str();
|
||||
sp.model = &model;
|
||||
sp.config = &cfg;
|
||||
sp.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
|
||||
REQUIRE(store_bbs_3mf(sp));
|
||||
|
||||
THEN("no entry is written at all") {
|
||||
std::string got;
|
||||
REQUIRE_FALSE(read_cad_recipe_entry(test_file, got));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The recipe entry was renamed from Metadata/SnapOrca_cad.bin to Metadata/orca_cad.bin. Nothing
|
||||
// in the blob marks that move, so a reader that knows only the new name loads a project written
|
||||
// before it with an empty cad_recipe and no error at all — a feature tree gone with no symptom
|
||||
// but an empty Design tab. The importer must still accept the old name; the exporter may never
|
||||
// write it.
|
||||
SCENARIO("a project saved under the pre-rename recipe name still loads", "[3mf][CAD]") {
|
||||
GIVEN("a project whose recipe entry carries the old name") {
|
||||
Model model;
|
||||
std::string src = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
|
||||
REQUIRE(load_stl(src.c_str(), &model));
|
||||
model.add_default_instances();
|
||||
const std::string recipe = make_cad_recipe();
|
||||
model.cad_recipe = recipe;
|
||||
|
||||
WHEN("it was written by the BBS backend") {
|
||||
ScopedTemporaryDir backup_dir("orca_cad_legacy");
|
||||
model.set_backup_path(backup_dir.string());
|
||||
|
||||
ScopedTemporaryFile temp(".3mf");
|
||||
const std::string test_file = temp.string();
|
||||
DynamicPrintConfig cfg;
|
||||
StoreParams sp;
|
||||
sp.path = test_file.c_str();
|
||||
sp.model = &model;
|
||||
sp.config = &cfg;
|
||||
sp.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
|
||||
REQUIRE(store_bbs_3mf(sp));
|
||||
rename_cad_recipe_entry_to_legacy(test_file);
|
||||
|
||||
// Catch2 replays the enclosing sections per THEN, so one load here serves both.
|
||||
Model dst_model;
|
||||
ScopedTemporaryDir dst_backup_dir("orca_cad_legacy_dst");
|
||||
dst_model.set_backup_path(dst_backup_dir.string());
|
||||
|
||||
DynamicPrintConfig dst_config;
|
||||
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
|
||||
PlateDataPtrs dst_plates;
|
||||
std::vector<Preset*> project_presets;
|
||||
bool is_bbl_3mf = false, is_orca_3mf = false;
|
||||
Semver file_version;
|
||||
REQUIRE(load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
|
||||
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
|
||||
LoadStrategy::LoadModel | LoadStrategy::LoadConfig));
|
||||
release_PlateData_list(dst_plates);
|
||||
|
||||
THEN("the recipe still comes back byte-for-byte") {
|
||||
REQUIRE(dst_model.cad_recipe == recipe);
|
||||
}
|
||||
|
||||
THEN("re-saving migrates it to the new name and leaves the old one behind") {
|
||||
ScopedTemporaryFile again(".3mf");
|
||||
const std::string resaved = again.string();
|
||||
DynamicPrintConfig cfg2;
|
||||
StoreParams sp2;
|
||||
sp2.path = resaved.c_str();
|
||||
sp2.model = &dst_model;
|
||||
sp2.config = &cfg2;
|
||||
sp2.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
|
||||
REQUIRE(store_bbs_3mf(sp2));
|
||||
|
||||
std::string got;
|
||||
REQUIRE(read_cad_recipe_entry(resaved, got));
|
||||
REQUIRE(got == recipe);
|
||||
REQUIRE_FALSE(read_cad_recipe_entry(resaved, got, LEGACY_CAD_RECIPE_ENTRY));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// .3mf multi-nozzle round-trip.
|
||||
// Locks the load/save handling for the H2C multi-nozzle plate metadata:
|
||||
// * filament_volume_maps -> plate config "filament_volume_map" (with the >1 -> 0 clamp)
|
||||
@@ -499,7 +735,6 @@ SCENARIO("Nozzle-group metadata .3mf round-trip", "[3mf][MultiNozzle]") {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// A mixed-color filament occupies an ordinary filament slot, and painting with it stores an
|
||||
// ordinary extruder state: a project saved by BambuStudio encodes filament 5 of a 5-slot setup
|
||||
// as paint state 5, with the mix described by the parallel filament_mixed_* project arrays.
|
||||
@@ -590,3 +825,639 @@ SCENARIO("Mixed-color filament setup and painting round-trip through a .3mf", "[
|
||||
}
|
||||
}
|
||||
}
|
||||
// Locks the serialization contract of the "Publish" metadata: the orca_published flag and the
|
||||
// orca_published_keys JSON array in model.model_info->metadata_items must survive a store_bbs_3mf ->
|
||||
// load_bbs_3mf round-trip unchanged. (The full preset-preservation behavior is exercised
|
||||
// headlessly in test_preset_bundle_loading.cpp.)
|
||||
SCENARIO("Published 3MF round-trips the published flag and published_keys metadata", "[3mf]") {
|
||||
GIVEN("a model carrying published metadata") {
|
||||
Model model;
|
||||
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
|
||||
REQUIRE(load_stl(src_file.c_str(), &model));
|
||||
model.add_default_instances();
|
||||
|
||||
model.model_info = std::make_shared<ModelInfo>();
|
||||
model.model_info->metadata_items[ORCA_PUBLISHED_TAG] = "1";
|
||||
model.model_info->metadata_items[ORCA_PUBLISHED_KEYS_TAG] = R"(["layer_height","wall_thickness"])";
|
||||
|
||||
// store_bbs_3mf stages project_settings.config through the model's backup path; point
|
||||
// it at a writable temp dir (the default lives under a read-only root in CI).
|
||||
ScopedTemporaryDir backup_dir("orca_pub");
|
||||
model.set_backup_path(backup_dir.string());
|
||||
|
||||
WHEN("stored to and reloaded from a .3mf") {
|
||||
ScopedTemporaryFile temp(".3mf");
|
||||
const std::string test_file = temp.string();
|
||||
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
StoreParams store_params;
|
||||
store_params.path = test_file.c_str();
|
||||
store_params.model = &model;
|
||||
store_params.config = &config;
|
||||
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
|
||||
REQUIRE(store_bbs_3mf(store_params));
|
||||
|
||||
Model dst_model;
|
||||
DynamicPrintConfig dst_config;
|
||||
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
|
||||
PlateDataPtrs dst_plates;
|
||||
std::vector<Preset*> project_presets;
|
||||
bool is_bbl_3mf = false, is_orca_3mf = false;
|
||||
Semver file_version;
|
||||
bool loaded = load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
|
||||
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
|
||||
LoadStrategy::LoadModel | LoadStrategy::LoadConfig);
|
||||
THEN("the published metadata round-trips unchanged") {
|
||||
REQUIRE(loaded);
|
||||
REQUIRE(dst_model.model_info != nullptr);
|
||||
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_TAG] == "1");
|
||||
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_KEYS_TAG] == R"(["layer_height","wall_thickness"])");
|
||||
|
||||
// The orca_published_keys value is a JSON array of setting keys; it must parse back to
|
||||
// the same keys that were selected.
|
||||
nlohmann::json keys = nlohmann::json::parse(dst_model.model_info->metadata_items[ORCA_PUBLISHED_KEYS_TAG]);
|
||||
REQUIRE(keys.is_array());
|
||||
REQUIRE(keys.size() == 2);
|
||||
REQUIRE(keys[0] == "layer_height");
|
||||
REQUIRE(keys[1] == "wall_thickness");
|
||||
}
|
||||
release_PlateData_list(dst_plates);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A normal 3MF (no Publish metadata) must load identically: the loader must not fabricate a
|
||||
// "orca_published" flag or orca_published_keys for files that never carried them.
|
||||
SCENARIO("Legacy 3MF without published metadata loads unchanged", "[3mf]") {
|
||||
GIVEN("a model without any published metadata") {
|
||||
Model model;
|
||||
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
|
||||
REQUIRE(load_stl(src_file.c_str(), &model));
|
||||
model.add_default_instances();
|
||||
|
||||
ScopedTemporaryDir backup_dir("orca_legacy");
|
||||
model.set_backup_path(backup_dir.string());
|
||||
|
||||
WHEN("stored to and reloaded from a .3mf") {
|
||||
ScopedTemporaryFile temp(".3mf");
|
||||
const std::string test_file = temp.string();
|
||||
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
StoreParams store_params;
|
||||
store_params.path = test_file.c_str();
|
||||
store_params.model = &model;
|
||||
store_params.config = &config;
|
||||
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
|
||||
REQUIRE(store_bbs_3mf(store_params));
|
||||
|
||||
Model dst_model;
|
||||
DynamicPrintConfig dst_config;
|
||||
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
|
||||
PlateDataPtrs dst_plates;
|
||||
std::vector<Preset*> project_presets;
|
||||
bool is_bbl_3mf = false, is_orca_3mf = false;
|
||||
Semver file_version;
|
||||
bool loaded = load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
|
||||
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
|
||||
LoadStrategy::LoadModel | LoadStrategy::LoadConfig);
|
||||
THEN("no published key is fabricated") {
|
||||
REQUIRE(loaded);
|
||||
REQUIRE(dst_model.model_info != nullptr);
|
||||
REQUIRE(dst_model.model_info->metadata_items.count(ORCA_PUBLISHED_TAG) == 0);
|
||||
REQUIRE(dst_model.model_info->metadata_items.count(ORCA_PUBLISHED_KEYS_TAG) == 0);
|
||||
}
|
||||
release_PlateData_list(dst_plates);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Locks the serialization contract of the orca_published_material_keys metadata: the per-entry JSON
|
||||
// must survive a store_bbs_3mf -> load_bbs_3mf round-trip verbatim, exactly like orca_published_keys.
|
||||
SCENARIO("Published 3MF round-trips the published_material_keys metadata", "[3mf]") {
|
||||
GIVEN("a model carrying published material keys metadata") {
|
||||
Model model;
|
||||
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
|
||||
REQUIRE(load_stl(src_file.c_str(), &model));
|
||||
model.add_default_instances();
|
||||
|
||||
const std::string material_keys_json =
|
||||
R"([{"material":{"filament_type":"PLA","filament_vendor":"Generic","filament_id":"GFL99"},"slot":0,"keys":["filament_retraction_length","filament_z_hop"]}])";
|
||||
|
||||
model.model_info = std::make_shared<ModelInfo>();
|
||||
model.model_info->metadata_items[ORCA_PUBLISHED_MATERIAL_TAG] = material_keys_json;
|
||||
|
||||
ScopedTemporaryDir backup_dir("orca_pub_mat");
|
||||
model.set_backup_path(backup_dir.string());
|
||||
|
||||
WHEN("stored to and reloaded from a .3mf") {
|
||||
ScopedTemporaryFile temp(".3mf");
|
||||
const std::string test_file = temp.string();
|
||||
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
StoreParams store_params;
|
||||
store_params.path = test_file.c_str();
|
||||
store_params.model = &model;
|
||||
store_params.config = &config;
|
||||
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
|
||||
REQUIRE(store_bbs_3mf(store_params));
|
||||
|
||||
Model dst_model;
|
||||
DynamicPrintConfig dst_config;
|
||||
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
|
||||
PlateDataPtrs dst_plates;
|
||||
std::vector<Preset*> project_presets;
|
||||
bool is_bbl_3mf = false, is_orca_3mf = false;
|
||||
Semver file_version;
|
||||
bool loaded = load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
|
||||
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
|
||||
LoadStrategy::LoadModel | LoadStrategy::LoadConfig);
|
||||
THEN("the published material keys metadata round-trips unchanged") {
|
||||
REQUIRE(loaded);
|
||||
REQUIRE(dst_model.model_info != nullptr);
|
||||
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_MATERIAL_TAG] == material_keys_json);
|
||||
|
||||
// The value must parse back to one material entry carrying the nested identity
|
||||
// object, the author slot ordinal and the key list.
|
||||
nlohmann::json entries = nlohmann::json::parse(material_keys_json);
|
||||
REQUIRE(entries.is_array());
|
||||
REQUIRE(entries.size() == 1);
|
||||
REQUIRE(entries[0]["material"]["filament_type"] == "PLA");
|
||||
REQUIRE(entries[0]["material"]["filament_vendor"] == "Generic");
|
||||
REQUIRE(entries[0]["material"]["filament_id"] == "GFL99");
|
||||
REQUIRE(entries[0]["slot"] == 0);
|
||||
REQUIRE(entries[0]["keys"].is_array());
|
||||
REQUIRE(entries[0]["keys"].size() == 2);
|
||||
REQUIRE(entries[0]["keys"][0] == "filament_retraction_length");
|
||||
}
|
||||
release_PlateData_list(dst_plates);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SCENARIO("Minimal published 3MF omits project config, preset dumps and slicer tags", "[3mf]") {
|
||||
GIVEN("a multi-instance model carrying published metadata and a published_config payload") {
|
||||
Model model;
|
||||
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
|
||||
REQUIRE(load_stl(src_file.c_str(), &model));
|
||||
model.add_default_instances();
|
||||
// A second instance: tag-less third-party files get their multi-instance objects split,
|
||||
// published files must not (the loader recognizes them by their metadata).
|
||||
model.objects.front()->add_instance();
|
||||
|
||||
DynamicPrintConfig full_cfg = DynamicPrintConfig::full_print_config();
|
||||
full_cfg.set_key_value("layer_height", new ConfigOptionFloat(0.24));
|
||||
full_cfg.set_key_value("retraction_length", new ConfigOptionFloats({ 1.2 }));
|
||||
|
||||
const std::vector<std::string> published_keys = { "layer_height", "retraction_length" };
|
||||
const std::vector<PublishedMaterialEntry> material_keys = {
|
||||
{ "PLA", "Generic", "GFL99", "", "Generic PLA", 0, { "filament_retraction_length" } }
|
||||
};
|
||||
|
||||
// The payload builder keeps the published and identity keys and drops everything else.
|
||||
DynamicPrintConfig filtered_cfg = filter_published_config(full_cfg, published_keys, material_keys);
|
||||
REQUIRE(filtered_cfg.option("layer_height") != nullptr);
|
||||
REQUIRE(filtered_cfg.option("retraction_length") != nullptr);
|
||||
REQUIRE(filtered_cfg.option("filament_colour") != nullptr);
|
||||
REQUIRE(filtered_cfg.option("filament_type") != nullptr);
|
||||
REQUIRE(filtered_cfg.option("wipe_tower_x") != nullptr);
|
||||
REQUIRE(filtered_cfg.option("sparse_infill_density") == nullptr);
|
||||
REQUIRE(filtered_cfg.option("machine_start_gcode") == nullptr);
|
||||
|
||||
// Serialize the payload exactly like export_published_3mf does.
|
||||
std::string payload;
|
||||
for (const std::string &key : filtered_cfg.keys())
|
||||
payload += key + " = " + filtered_cfg.opt_serialize(key) + "\n";
|
||||
|
||||
model.model_info = std::make_shared<ModelInfo>();
|
||||
model.model_info->metadata_items[ORCA_PUBLISHED_TAG] = "1";
|
||||
model.model_info->metadata_items[ORCA_PUBLISHED_KEYS_TAG] = R"(["layer_height","retraction_length"])";
|
||||
model.model_info->metadata_items[ORCA_PUBLISHED_CONFIG_TAG] = payload;
|
||||
|
||||
ScopedTemporaryDir backup_dir("orca_min_pub");
|
||||
model.set_backup_path(backup_dir.string());
|
||||
|
||||
WHEN("stored using SaveStrategy::MinimalPublished and reloaded") {
|
||||
ScopedTemporaryFile temp(".3mf");
|
||||
const std::string test_file = temp.string();
|
||||
|
||||
// Create a fake project preset to verify MinimalPublished omits it.
|
||||
Preset preset(Preset::TYPE_PRINT, "TestPrintPreset");
|
||||
preset.config = full_cfg;
|
||||
std::vector<Preset*> project_presets = { &preset };
|
||||
|
||||
StoreParams store_params;
|
||||
store_params.path = test_file.c_str();
|
||||
store_params.model = &model;
|
||||
store_params.config = &filtered_cfg;
|
||||
store_params.project_presets = project_presets;
|
||||
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence | SaveStrategy::MinimalPublished;
|
||||
REQUIRE(store_bbs_3mf(store_params));
|
||||
|
||||
Model dst_model;
|
||||
ScopedTemporaryDir loaded_backup_dir("orca_min_pub_loaded");
|
||||
dst_model.set_backup_path(loaded_backup_dir.string());
|
||||
DynamicPrintConfig dst_config;
|
||||
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
|
||||
PlateDataPtrs dst_plates;
|
||||
std::vector<Preset*> loaded_presets;
|
||||
bool is_bbl_3mf = false, is_orca_3mf = false;
|
||||
Semver file_version;
|
||||
bool loaded = load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
|
||||
&loaded_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
|
||||
LoadStrategy::LoadModel | LoadStrategy::LoadConfig);
|
||||
THEN("the 3MF loads without project config or embedded presets") {
|
||||
REQUIRE(loaded);
|
||||
REQUIRE(dst_config.empty());
|
||||
REQUIRE(loaded_presets.empty());
|
||||
}
|
||||
THEN("the file carries no slicer tags and classifies as a generic 3MF") {
|
||||
REQUIRE_FALSE(is_bbl_3mf);
|
||||
REQUIRE_FALSE(is_orca_3mf);
|
||||
// No Application / OrcaSlicer tag: old receivers import the geometry silently
|
||||
// instead of showing a baked-in, wrong "old version" popup.
|
||||
REQUIRE_FALSE(file_version.valid());
|
||||
}
|
||||
THEN("the geometry keeps BBS-grade handling: instances are not split") {
|
||||
REQUIRE(dst_model.objects.size() == 1);
|
||||
REQUIRE(dst_model.objects.front()->instances.size() == 2);
|
||||
}
|
||||
THEN("the published metadata and payload round-trip unchanged") {
|
||||
REQUIRE(dst_model.model_info != nullptr);
|
||||
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_TAG] == "1");
|
||||
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_KEYS_TAG] == R"(["layer_height","retraction_length"])");
|
||||
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_CONFIG_TAG] == payload);
|
||||
}
|
||||
THEN("the payload parses back to the published values") {
|
||||
DynamicPrintConfig parsed_payload;
|
||||
parsed_payload.load_from_ini_string(dst_model.model_info->metadata_items[ORCA_PUBLISHED_CONFIG_TAG], ForwardCompatibilitySubstitutionRule::Enable);
|
||||
REQUIRE(parsed_payload.option("layer_height") != nullptr);
|
||||
REQUIRE_THAT(parsed_payload.opt_float("layer_height"), Catch::Matchers::WithinAbs(0.24, 1e-6));
|
||||
REQUIRE(parsed_payload.option("retraction_length") != nullptr);
|
||||
REQUIRE_THAT(parsed_payload.opt<ConfigOptionFloats>("retraction_length")->get_at(0), Catch::Matchers::WithinAbs(1.2, 1e-6));
|
||||
}
|
||||
release_PlateData_list(dst_plates);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A minimal published 3MF must not leak the slicer tags of the source project. The exporter seeds
|
||||
// metadata_item_map from the input file's metadata_items, so re-publishing a project opened from a
|
||||
// regular Orca/BBS 3MF (the typical remix flow) must strip the Application / OrcaSlicer tags it
|
||||
// came with, otherwise old receivers route onto the baked-in "old version" popup.
|
||||
SCENARIO("MinimalPublished strips slicer tags carried by the source project", "[3mf]") {
|
||||
GIVEN("a model loaded from a regular Orca/BBS 3MF whose metadata carries the slicer tags") {
|
||||
Model model;
|
||||
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
|
||||
REQUIRE(load_stl(src_file.c_str(), &model));
|
||||
model.add_default_instances();
|
||||
|
||||
model.model_info = std::make_shared<ModelInfo>();
|
||||
model.model_info->metadata_items[ORCA_PUBLISHED_TAG] = "1";
|
||||
model.model_info->metadata_items["Application"] = "BambuStudio-2.0.0";
|
||||
model.model_info->metadata_items["OrcaSlicer"] = "2.1.0";
|
||||
|
||||
ScopedTemporaryDir backup_dir("orca_strip_tags");
|
||||
model.set_backup_path(backup_dir.string());
|
||||
|
||||
WHEN("stored using SaveStrategy::MinimalPublished and reloaded") {
|
||||
ScopedTemporaryFile temp(".3mf");
|
||||
const std::string test_file = temp.string();
|
||||
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
StoreParams store_params;
|
||||
store_params.path = test_file.c_str();
|
||||
store_params.model = &model;
|
||||
store_params.config = &config;
|
||||
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence | SaveStrategy::MinimalPublished;
|
||||
REQUIRE(store_bbs_3mf(store_params));
|
||||
|
||||
Model dst_model;
|
||||
DynamicPrintConfig dst_config;
|
||||
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
|
||||
PlateDataPtrs dst_plates;
|
||||
std::vector<Preset*> loaded_presets;
|
||||
bool is_bbl_3mf = false, is_orca_3mf = false;
|
||||
Semver file_version;
|
||||
bool loaded = load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
|
||||
&loaded_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
|
||||
LoadStrategy::LoadModel | LoadStrategy::LoadConfig);
|
||||
THEN("the source slicer tags are stripped, not carried through") {
|
||||
REQUIRE(loaded);
|
||||
REQUIRE(dst_model.model_info != nullptr);
|
||||
REQUIRE(dst_model.model_info->metadata_items.count("Application") == 0);
|
||||
REQUIRE(dst_model.model_info->metadata_items.count("OrcaSlicer") == 0);
|
||||
// The published marker itself must survive.
|
||||
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_TAG] == "1");
|
||||
}
|
||||
THEN("the file classifies as a generic 3MF without a version popup") {
|
||||
REQUIRE_FALSE(is_bbl_3mf);
|
||||
REQUIRE_FALSE(is_orca_3mf);
|
||||
REQUIRE_FALSE(file_version.valid());
|
||||
}
|
||||
release_PlateData_list(dst_plates);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An entry masks the non-published slots to their defaults so publishing slot 1 never leaks slot
|
||||
// 0's value into the file. Both a full entry (the whole-slot key list) and a partial entry (a
|
||||
// per-slot key) go through the same masking path in filter_published_config (keys and full_keys
|
||||
// are filtered identically), so the two forms are exercised together.
|
||||
SCENARIO("Published entries mask the other slots to their defaults", "[3mf]") {
|
||||
const bool full = GENERATE(true, false);
|
||||
GIVEN("a full print configuration with two filament slots") {
|
||||
DynamicPrintConfig full_cfg = DynamicPrintConfig::full_print_config();
|
||||
full_cfg.opt<ConfigOptionFloats>("filament_diameter")->values = { 1.75, 1.75 };
|
||||
full_cfg.opt<ConfigOptionStrings>("filament_colour")->values = { "#111111", "#222222" };
|
||||
// filament_flow_ratio carries a non-empty option default (1.0) of the same type, so the
|
||||
// mask can restore it on the non-published slot.
|
||||
full_cfg.opt<ConfigOptionFloatsNullable>("filament_flow_ratio", true)->values = { 1.02, 0.98 };
|
||||
|
||||
WHEN("filtering with a published entry for slot 1") {
|
||||
PublishedMaterialEntry entry;
|
||||
entry.slot = 1;
|
||||
if (full) {
|
||||
entry.full = true;
|
||||
entry.full_keys = { "filament_flow_ratio" };
|
||||
} else {
|
||||
entry.keys = { "filament_flow_ratio" };
|
||||
}
|
||||
DynamicPrintConfig filtered_cfg = filter_published_config(full_cfg, {}, { entry });
|
||||
|
||||
THEN("the selected key is present with the author's slot value") {
|
||||
REQUIRE(filtered_cfg.option("filament_flow_ratio") != nullptr);
|
||||
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloatsNullable>("filament_flow_ratio")->values[1], Catch::Matchers::WithinAbs(0.98, 1e-6));
|
||||
}
|
||||
THEN("the non-published slot is masked to its default") {
|
||||
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloatsNullable>("filament_flow_ratio")->values[0], Catch::Matchers::WithinAbs(1.0, 1e-6));
|
||||
}
|
||||
THEN("the identity keys stay present") {
|
||||
REQUIRE(filtered_cfg.option("filament_colour") != nullptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A key needing slot masking that cannot be masked (no registered option default of the same
|
||||
// type) is dropped from the payload entirely instead of shipping the author's whole vector.
|
||||
SCENARIO("Unmaskable keys are dropped from the published payload instead of leaking", "[3mf]") {
|
||||
GIVEN("a config carrying a synthetic def-less vector key and a maskable one") {
|
||||
DynamicPrintConfig full_cfg = DynamicPrintConfig::full_print_config();
|
||||
full_cfg.opt<ConfigOptionFloats>("filament_diameter")->values = { 1.75, 1.75 };
|
||||
full_cfg.opt<ConfigOptionStrings>("filament_colour")->values = { "#111111", "#222222" };
|
||||
// Not a PrintConfig key: print_config_def has no default to mask with.
|
||||
full_cfg.set_key_value("orca_synthetic_setting", new ConfigOptionFloats({ 9.9, 8.8 }));
|
||||
full_cfg.opt<ConfigOptionFloatsNullable>("filament_flow_ratio", true)->values = { 1.02, 0.98 };
|
||||
|
||||
PublishedMaterialEntry partial_entry;
|
||||
partial_entry.slot = 1;
|
||||
partial_entry.keys = { "orca_synthetic_setting", "filament_flow_ratio" };
|
||||
|
||||
WHEN("filtering with a partial entry for slot 1") {
|
||||
DynamicPrintConfig filtered_cfg = filter_published_config(full_cfg, {}, { partial_entry });
|
||||
|
||||
THEN("the unmaskable synthetic key is not published") {
|
||||
REQUIRE(filtered_cfg.option("orca_synthetic_setting") == nullptr);
|
||||
}
|
||||
THEN("the maskable key is present, author slot kept, other slot masked") {
|
||||
REQUIRE(filtered_cfg.opt<ConfigOptionFloatsNullable>("filament_flow_ratio") != nullptr);
|
||||
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloatsNullable>("filament_flow_ratio")->values[1], Catch::Matchers::WithinAbs(0.98, 1e-6));
|
||||
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloatsNullable>("filament_flow_ratio")->values[0], Catch::Matchers::WithinAbs(1.0, 1e-6));
|
||||
}
|
||||
THEN("the identity keys stay present") {
|
||||
REQUIRE(filtered_cfg.option("filament_colour") != nullptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A per-extruder printer key carrying a "#N" variant (e.g. retraction_length#1) must not serialize
|
||||
// every extruder's value: the base is masked to the author's extruder and the other slots are
|
||||
// restored to their option default, matching the material-side slot-masking invariant. A bare
|
||||
// printer base key (no variant) keeps whole-vector serialization.
|
||||
SCENARIO("Published per-extruder printer keys mask the other extruders to their defaults", "[3mf]") {
|
||||
GIVEN("a full print configuration with three extruders carrying per-extruder retraction values") {
|
||||
DynamicPrintConfig full_cfg = DynamicPrintConfig::full_print_config();
|
||||
// Non-default values on the un-selected slots, so a leak is distinguishable from the mask
|
||||
// restoring the option default (retraction_length defaults to {0.8}).
|
||||
full_cfg.opt<ConfigOptionFloats>("retraction_length")->values = { 3.0, 1.2, 4.0 };
|
||||
|
||||
WHEN("filtering with only extruder 1's retraction_length checked") {
|
||||
DynamicPrintConfig filtered_cfg = filter_published_config(full_cfg, { "retraction_length#1" }, {});
|
||||
|
||||
THEN("the author's extruder value survives") {
|
||||
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloats>("retraction_length")->values[1], Catch::Matchers::WithinAbs(1.2, 1e-6));
|
||||
}
|
||||
THEN("the other extruders are masked to their default") {
|
||||
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloats>("retraction_length")->values[0], Catch::Matchers::WithinAbs(0.8, 1e-6));
|
||||
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloats>("retraction_length")->values[2], Catch::Matchers::WithinAbs(0.8, 1e-6));
|
||||
}
|
||||
}
|
||||
WHEN("filtering the bare base key without a '#N' variant") {
|
||||
DynamicPrintConfig filtered_cfg = filter_published_config(full_cfg, { "retraction_length" }, {});
|
||||
|
||||
THEN("the whole vector is serialized unmasked") {
|
||||
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloats>("retraction_length")->values[0], Catch::Matchers::WithinAbs(3.0, 1e-6));
|
||||
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloats>("retraction_length")->values[1], Catch::Matchers::WithinAbs(1.2, 1e-6));
|
||||
REQUIRE_THAT(filtered_cfg.opt<ConfigOptionFloats>("retraction_length")->values[2], Catch::Matchers::WithinAbs(4.0, 1e-6));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The extended per-entry fields (full dump list, published type and colour) travel inside the
|
||||
// published_material_keys metadata and round-trip unchanged.
|
||||
SCENARIO("Published 3MF round-trips the extended material metadata", "[3mf]") {
|
||||
GIVEN("a model carrying extended published material keys metadata") {
|
||||
Model model;
|
||||
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
|
||||
REQUIRE(load_stl(src_file.c_str(), &model));
|
||||
model.add_default_instances();
|
||||
|
||||
const std::string material_keys_json =
|
||||
R"([{"material":{"filament_type":"PLA","filament_vendor":"Generic","filament_id":"GFL99","setting_id":"RFs9eCKYOMUSmvZf","name":"Generic PLA Matte @System"},"slot":1,"keys":[],"full":true,"full_keys":["filament_retraction_length","filament_colour"],"publish_type":true,"type":"PLA","publish_color":false,"color":""}])";
|
||||
|
||||
model.model_info = std::make_shared<ModelInfo>();
|
||||
model.model_info->metadata_items[ORCA_PUBLISHED_MATERIAL_TAG] = material_keys_json;
|
||||
|
||||
ScopedTemporaryDir backup_dir("orca_pub_mat2");
|
||||
model.set_backup_path(backup_dir.string());
|
||||
|
||||
WHEN("stored to and reloaded from a .3mf") {
|
||||
ScopedTemporaryFile temp(".3mf");
|
||||
const std::string test_file = temp.string();
|
||||
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
StoreParams store_params;
|
||||
store_params.path = test_file.c_str();
|
||||
store_params.model = &model;
|
||||
store_params.config = &config;
|
||||
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
|
||||
REQUIRE(store_bbs_3mf(store_params));
|
||||
|
||||
Model dst_model;
|
||||
DynamicPrintConfig dst_config;
|
||||
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
|
||||
PlateDataPtrs dst_plates;
|
||||
std::vector<Preset*> project_presets;
|
||||
bool is_bbl_3mf = false, is_orca_3mf = false;
|
||||
Semver file_version;
|
||||
bool loaded = load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
|
||||
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
|
||||
LoadStrategy::LoadModel | LoadStrategy::LoadConfig);
|
||||
THEN("the extended material metadata round-trips unchanged") {
|
||||
REQUIRE(loaded);
|
||||
REQUIRE(dst_model.model_info != nullptr);
|
||||
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_MATERIAL_TAG] == material_keys_json);
|
||||
|
||||
// The value must parse back with every extended field intact.
|
||||
nlohmann::json entries = nlohmann::json::parse(material_keys_json);
|
||||
REQUIRE(entries.is_array());
|
||||
REQUIRE(entries.size() == 1);
|
||||
REQUIRE(entries[0]["full"].get<bool>() == true);
|
||||
REQUIRE(entries[0]["full_keys"].is_array());
|
||||
REQUIRE(entries[0]["full_keys"].size() == 2);
|
||||
REQUIRE(entries[0]["publish_type"].get<bool>() == true);
|
||||
REQUIRE(entries[0]["type"] == "PLA");
|
||||
REQUIRE(entries[0]["publish_color"].get<bool>() == false);
|
||||
}
|
||||
release_PlateData_list(dst_plates);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A published mixed filament serializes its whole definition (components, ratios, gradient)
|
||||
// masked to the author's slot: the mix slot's values survive, the non-published slots reset to
|
||||
// their defaults, so a partial publish never leaks another slot's mix data.
|
||||
SCENARIO("Published mixed-filament keys are masked to the author's slot", "[3mf]") {
|
||||
GIVEN("a full print configuration with three slots, one of them mixed") {
|
||||
DynamicPrintConfig full_cfg = DynamicPrintConfig::full_print_config();
|
||||
full_cfg.opt<ConfigOptionFloats>("filament_diameter")->values = { 1.75, 1.75, 1.75 };
|
||||
full_cfg.opt<ConfigOptionStrings>("filament_colour")->values = { "#111111", "#222222", "#333333" };
|
||||
full_cfg.opt<ConfigOptionBools>("filament_is_mixed")->values = { 0, 0, 1 };
|
||||
full_cfg.opt<ConfigOptionStrings>("filament_mixed_components")->values = { "", "", "1,2" };
|
||||
full_cfg.opt<ConfigOptionStrings>("filament_mixed_sublayer_ratios")->values = { "", "", "0.6,0.4" };
|
||||
full_cfg.opt<ConfigOptionBools>("filament_mixed_gradient")->values = { 0, 0, 1 };
|
||||
full_cfg.opt<ConfigOptionStrings>("filament_mixed_gradient_range")->values = { "", "", "0.9,0.1" };
|
||||
full_cfg.opt<ConfigOptionStrings>("filament_mixed_gradient_curve")->values = { "", "", "0,0.1|1,0.9" };
|
||||
full_cfg.opt<ConfigOptionBools>("filament_mixed_gradient_per_part")->values = { 0, 0, 1 };
|
||||
|
||||
PublishedMaterialEntry mix_entry;
|
||||
mix_entry.slot = 2;
|
||||
mix_entry.keys = {
|
||||
"filament_is_mixed", "filament_mixed_components", "filament_mixed_sublayer_ratios",
|
||||
"filament_mixed_gradient", "filament_mixed_gradient_range", "filament_mixed_gradient_curve",
|
||||
"filament_mixed_gradient_per_part"
|
||||
};
|
||||
|
||||
WHEN("filtering with a mixed entry for slot 2") {
|
||||
DynamicPrintConfig filtered_cfg = filter_published_config(full_cfg, {}, { mix_entry });
|
||||
|
||||
THEN("the author's mixed slot keeps its definition") {
|
||||
REQUIRE(filtered_cfg.option("filament_is_mixed") != nullptr);
|
||||
REQUIRE(filtered_cfg.opt<ConfigOptionBools>("filament_is_mixed")->values == std::vector<unsigned char>{ 0, 0, 1 });
|
||||
const auto& components = filtered_cfg.opt<ConfigOptionStrings>("filament_mixed_components")->values;
|
||||
REQUIRE(components.size() == 3);
|
||||
CHECK(components[2] == "1,2");
|
||||
CHECK(filtered_cfg.opt<ConfigOptionStrings>("filament_mixed_sublayer_ratios")->values[2] == "0.6,0.4");
|
||||
CHECK(filtered_cfg.opt<ConfigOptionStrings>("filament_mixed_gradient_curve")->values[2] == "0,0.1|1,0.9");
|
||||
CHECK(filtered_cfg.opt<ConfigOptionBools>("filament_mixed_gradient")->values[2]);
|
||||
CHECK(filtered_cfg.opt<ConfigOptionBools>("filament_mixed_gradient_per_part")->values[2]);
|
||||
}
|
||||
THEN("the non-published slots are masked to their defaults") {
|
||||
CHECK(filtered_cfg.opt<ConfigOptionStrings>("filament_mixed_components")->values[0] == "");
|
||||
CHECK(filtered_cfg.opt<ConfigOptionStrings>("filament_mixed_components")->values[1] == "");
|
||||
CHECK(filtered_cfg.opt<ConfigOptionBools>("filament_is_mixed")->values[0] == 0);
|
||||
CHECK(filtered_cfg.opt<ConfigOptionBools>("filament_is_mixed")->values[1] == 0);
|
||||
}
|
||||
THEN("the identity keys stay present") {
|
||||
REQUIRE(filtered_cfg.option("filament_colour") != nullptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The published flag is gated on the exact string "1": any other serialized value means "not
|
||||
// published", so a receiver never treats a file as published on a loose truthiness check.
|
||||
TEST_CASE("is_published_3mf_flag accepts only the literal \"1\"", "[3mf]") {
|
||||
CHECK(is_published_3mf_flag("1"));
|
||||
CHECK_FALSE(is_published_3mf_flag("0"));
|
||||
CHECK_FALSE(is_published_3mf_flag("false"));
|
||||
CHECK_FALSE(is_published_3mf_flag("true"));
|
||||
CHECK_FALSE(is_published_3mf_flag(""));
|
||||
CHECK_FALSE(is_published_3mf_flag("YES"));
|
||||
}
|
||||
|
||||
// bbs_3mf_is_published is the lightweight metadata probe used to decide whether a file was
|
||||
// produced by the publish feature (GUI "recently published" tracking). It must return true only
|
||||
// for a file whose metadata carries the flag set to "1", and false for legacy files and for a
|
||||
// file whose flag is present but not "1" (which loads as a normal, non-published 3MF).
|
||||
SCENARIO("bbs_3mf_is_published detects only genuinely published 3MFs", "[3mf]") {
|
||||
auto store_model = [](const std::string &path, const std::string &flag_value, const std::string &keys_value) {
|
||||
Model model;
|
||||
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
|
||||
REQUIRE(load_stl(src_file.c_str(), &model));
|
||||
model.add_default_instances();
|
||||
model.model_info = std::make_shared<ModelInfo>();
|
||||
// An empty flag_value means "don't write the flag at all" (a legacy file).
|
||||
if (!flag_value.empty())
|
||||
model.model_info->metadata_items[ORCA_PUBLISHED_TAG] = flag_value;
|
||||
model.model_info->metadata_items[ORCA_PUBLISHED_KEYS_TAG] = keys_value;
|
||||
ScopedTemporaryDir backup_dir("orca_is_pub");
|
||||
model.set_backup_path(backup_dir.string());
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
StoreParams store_params;
|
||||
store_params.path = path.c_str();
|
||||
store_params.model = &model;
|
||||
store_params.config = &config;
|
||||
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
|
||||
REQUIRE(store_bbs_3mf(store_params));
|
||||
};
|
||||
|
||||
GIVEN("a minimal published 3MF whose flag is \"1\"") {
|
||||
ScopedTemporaryFile temp(".3mf");
|
||||
store_model(temp.string(), "1", R"(["layer_height"])");
|
||||
WHEN("probed by bbs_3mf_is_published") {
|
||||
THEN("it is recognized as published") {
|
||||
CHECK(bbs_3mf_is_published(temp.string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
GIVEN("a legacy 3MF without any published flag") {
|
||||
ScopedTemporaryFile temp(".3mf");
|
||||
store_model(temp.string(), "", R"(["layer_height"])");
|
||||
WHEN("probed by bbs_3mf_is_published") {
|
||||
THEN("it is not recognized as published") {
|
||||
CHECK_FALSE(bbs_3mf_is_published(temp.string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
GIVEN("a 3MF carrying the flag set to \"0\"") {
|
||||
ScopedTemporaryFile temp(".3mf");
|
||||
store_model(temp.string(), "0", R"(["layer_height"])");
|
||||
WHEN("probed and loaded") {
|
||||
THEN("it is not recognized as published") {
|
||||
CHECK_FALSE(bbs_3mf_is_published(temp.string()));
|
||||
}
|
||||
THEN("it loads as a normal, non-published 3MF") {
|
||||
Model dst_model;
|
||||
DynamicPrintConfig dst_config;
|
||||
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
|
||||
PlateDataPtrs dst_plates;
|
||||
std::vector<Preset*> project_presets;
|
||||
bool is_bbl_3mf = false, is_orca_3mf = false;
|
||||
Semver file_version;
|
||||
REQUIRE(load_bbs_3mf(temp.string().c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
|
||||
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
|
||||
LoadStrategy::LoadModel | LoadStrategy::LoadConfig));
|
||||
REQUIRE(dst_model.model_info != nullptr);
|
||||
// The key is present but not "1", so nothing treats the file as published; the
|
||||
// stored keys still round-trip verbatim.
|
||||
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_TAG] == "0");
|
||||
REQUIRE(dst_model.model_info->metadata_items[ORCA_PUBLISHED_KEYS_TAG] == R"(["layer_height"])");
|
||||
release_PlateData_list(dst_plates);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,8 @@
|
||||
#include "libslic3r/Arachne/utils/ExtrusionLine.hpp"
|
||||
#include "libslic3r/Arachne/BeadingStrategy/BeadingStrategyFactory.hpp"
|
||||
#include "libslic3r/Arachne/BeadingStrategy/BeadingStrategy.hpp"
|
||||
#include "libslic3r/Feature/FuzzySkin/FuzzySkin.hpp"
|
||||
#include "libslic3r/Flow.hpp"
|
||||
#include "libslic3r/Polygon.hpp"
|
||||
#include "libslic3r/ExPolygon.hpp"
|
||||
#include "libslic3r/ClipperUtils.hpp"
|
||||
@@ -309,3 +311,71 @@ TEST_CASE("Beading interpolation tolerates a thicker side with fewer insets", "[
|
||||
CHECK(result.bead_widths[i] == expected.bead_widths[i]);
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// Closed 20 mm square loop at a uniform width.
|
||||
Arachne::ExtrusionJunctions square_loop(coord_t width)
|
||||
{
|
||||
const coord_t s = scaled<coord_t>(20.);
|
||||
return {{Point(0, 0), width, 0}, {Point(s, 0), width, 0}, {Point(s, s), width, 0}, {Point(0, s), width, 0}, {Point(0, 0), width, 0}};
|
||||
}
|
||||
|
||||
FuzzySkinConfig thick_fuzzy_config(FuzzySkinMode mode, NoiseType noise_type, double thickness_mm)
|
||||
{
|
||||
FuzzySkinConfig cfg{};
|
||||
cfg.type = FuzzySkinType::All;
|
||||
cfg.thickness = scaled<coord_t>(thickness_mm);
|
||||
cfg.point_distance = scaled<coord_t>(0.3);
|
||||
cfg.fuzzy_first_layer = true;
|
||||
cfg.noise_type = noise_type;
|
||||
cfg.noise_scale = 1.0;
|
||||
cfg.noise_octaves = 4;
|
||||
cfg.noise_persistence = 0.5;
|
||||
cfg.mode = mode;
|
||||
cfg.layer_id = 5;
|
||||
return cfg;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Extrusion and Combined mode add noise to each junction's width. A junction narrower than
|
||||
// height * (1 - PI/4) makes Flow::rounded_rectangle_extrusion_spacing() throw and fails the slice.
|
||||
// The fuzz thickness is 3x the line width so the clamp is hit on every run regardless of RNG seed.
|
||||
// Ridged multifractal is covered because its output is not bounded to [-1, 1], so it scales past
|
||||
// the configured thickness; the floor has to hold for any noise value, not just an in-range one.
|
||||
TEST_CASE("Fuzzy skin extrusion width is floored at the minimum the flow accepts", "[Arachne][FuzzySkin]") {
|
||||
using namespace Slic3r::Feature::FuzzySkin;
|
||||
|
||||
const double layer_height = GENERATE(0.08, 0.2, 0.28);
|
||||
const auto mode = GENERATE(FuzzySkinMode::Extrusion, FuzzySkinMode::Combined);
|
||||
const auto noise_type = GENERATE(NoiseType::Classic, NoiseType::Perlin, NoiseType::Billow, NoiseType::RidgedMulti, NoiseType::Voronoi);
|
||||
CAPTURE(layer_height, int(mode), int(noise_type));
|
||||
|
||||
const double line_width_mm = 0.42;
|
||||
auto loop = square_loop(scaled<coord_t>(line_width_mm));
|
||||
fuzzy_extrusion_line(loop, /*slice_z*/ 1.0, layer_height, thick_fuzzy_config(mode, noise_type, 3 * line_width_mm));
|
||||
|
||||
REQUIRE(loop.size() > 100);
|
||||
|
||||
const auto narrowest = std::min_element(loop.begin(), loop.end(), [](const auto& a, const auto& b) { return a.w < b.w; });
|
||||
const double narrowest_mm = unscaled<double>(narrowest->w);
|
||||
const double floor_mm = layer_height * (1. - 0.25 * PI);
|
||||
CAPTURE(narrowest_mm, floor_mm);
|
||||
|
||||
CHECK(narrowest_mm < line_width_mm); // the clamp was exercised
|
||||
CHECK(narrowest_mm > floor_mm);
|
||||
CHECK_NOTHROW(Flow::rounded_rectangle_extrusion_spacing(float(narrowest_mm), float(layer_height)));
|
||||
}
|
||||
|
||||
// Displacement mode only moves points; widths must pass through unchanged.
|
||||
TEST_CASE("Fuzzy skin displacement mode leaves widths untouched", "[Arachne][FuzzySkin]") {
|
||||
using namespace Slic3r::Feature::FuzzySkin;
|
||||
|
||||
const coord_t width = scaled<coord_t>(0.42);
|
||||
auto loop = square_loop(width);
|
||||
fuzzy_extrusion_line(loop, /*slice_z*/ 1.0, /*layer_height*/ 0.2, thick_fuzzy_config(FuzzySkinMode::Displacement, NoiseType::Classic, 1.26));
|
||||
|
||||
REQUIRE(loop.size() > 100);
|
||||
CHECK(std::all_of(loop.begin(), loop.end(), [width](const auto& j) { return j.w == width; }));
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
#include "libslic3r/BoundingBox.hpp"
|
||||
#include "libslic3r/ClipperUtils.hpp"
|
||||
#include "libslic3r/ExPolygon.hpp"
|
||||
#include "libslic3r/Print.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
using namespace Slic3r::arrangement;
|
||||
@@ -24,11 +26,13 @@ ArrangePolygon make_square(coord_t side)
|
||||
return ap;
|
||||
}
|
||||
|
||||
ArrangePolygons squares(int n, double side_mm)
|
||||
ArrangePolygons squares(int n, double side_mm, double height_mm = 0.)
|
||||
{
|
||||
ArrangePolygons items;
|
||||
for (int i = 0; i < n; ++i)
|
||||
for (int i = 0; i < n; ++i) {
|
||||
items.emplace_back(make_square(scaled(side_mm)));
|
||||
items.back().height = height_mm;
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
@@ -82,6 +86,38 @@ void require_no_overlap(const ArrangePolygons &items)
|
||||
REQUIRE(disjoint(placed_shapes(items)));
|
||||
}
|
||||
|
||||
// The sequential-print floor is chosen by comparing object height against the nozzle,
|
||||
// so the two are defined together and every expectation is derived from them.
|
||||
constexpr double NOZZLE_HEIGHT_MM = 2.5;
|
||||
constexpr double CLEARANCE_MM = 30.;
|
||||
constexpr double NOZZLE_FLOOR_MM = MAX_OUTER_NOZZLE_DIAMETER / 2.;
|
||||
|
||||
ArrangeParams seq_print_params(coord_t min_dist)
|
||||
{
|
||||
ArrangeParams p = quiet_params(min_dist);
|
||||
p.is_seq_print = true;
|
||||
p.clearance_radius = float(CLEARANCE_MM);
|
||||
p.nozzle_height = float(NOZZLE_HEIGHT_MM);
|
||||
p.object_skirt_offset = 0.f;
|
||||
return p;
|
||||
}
|
||||
|
||||
// update_selected_items_inflation reads the bed out of the config to cap inflation.
|
||||
DynamicPrintConfig bed_config()
|
||||
{
|
||||
DynamicPrintConfig c;
|
||||
c.set_key_value("printable_area", new ConfigOptionPoints{{0, 0}, {200, 0}, {200, 200}, {0, 200}});
|
||||
return c;
|
||||
}
|
||||
|
||||
ArrangePolygons squares_of_heights(const std::vector<double> &heights_mm)
|
||||
{
|
||||
ArrangePolygons items;
|
||||
for (double height_mm : heights_mm)
|
||||
items.push_back(squares(1, 20., height_mm).front());
|
||||
return items;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Prove the overlap check the other tests rely on actually detects overlap.
|
||||
@@ -222,3 +258,61 @@ TEST_CASE("Arrange aligns the pile to a custom center", "[Arrange]")
|
||||
REQUIRE(ap.bed_idx == 0);
|
||||
require_no_overlap(items);
|
||||
}
|
||||
|
||||
TEST_CASE("Sequential print floors the object distance by object height", "[Arrange]")
|
||||
{
|
||||
// The only place sequential-print clearance is enforced. The arrange menu offers
|
||||
// no floor of its own, so a stored 0 has to be raised here or not at all.
|
||||
struct Case
|
||||
{
|
||||
std::string description;
|
||||
std::vector<double> heights;
|
||||
double skirt_offset_mm;
|
||||
double expected_floor_mm;
|
||||
};
|
||||
|
||||
auto c = GENERATE(values<Case>({
|
||||
{"objects taller than the nozzle need the full clearance", {NOZZLE_HEIGHT_MM * 2, NOZZLE_HEIGHT_MM * 2}, 0., CLEARANCE_MM},
|
||||
{"an object exactly at the nozzle height counts as tall", {NOZZLE_HEIGHT_MM, NOZZLE_HEIGHT_MM}, 0., CLEARANCE_MM},
|
||||
{"one tall object among short ones is enough", {NOZZLE_HEIGHT_MM / 2, NOZZLE_HEIGHT_MM * 2}, 0., CLEARANCE_MM},
|
||||
{"objects the nozzle clears keep only the nozzle-width floor", {NOZZLE_HEIGHT_MM / 2, NOZZLE_HEIGHT_MM / 2}, 0., NOZZLE_FLOOR_MM},
|
||||
{"a wide skirt raises the floor for short objects", {NOZZLE_HEIGHT_MM / 2, NOZZLE_HEIGHT_MM / 2}, 3., 6.},
|
||||
}));
|
||||
|
||||
DYNAMIC_SECTION(c.description)
|
||||
{
|
||||
ArrangePolygons items = squares_of_heights(c.heights);
|
||||
DynamicPrintConfig cfg = bed_config();
|
||||
ArrangeParams p = seq_print_params(0);
|
||||
p.object_skirt_offset = float(c.skirt_offset_mm);
|
||||
|
||||
update_selected_items_inflation(items, &cfg, p);
|
||||
|
||||
CHECK(p.min_obj_distance >= scaled(c.expected_floor_mm));
|
||||
CHECK(p.min_obj_distance <= scaled(c.expected_floor_mm + 0.01));
|
||||
// Half each, so a pair ends up a full min_obj_distance apart.
|
||||
CHECK(items.front().inflation == p.min_obj_distance / 2);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Sequential print keeps an object distance already above the floor", "[Arrange]")
|
||||
{
|
||||
const coord_t stored = scaled(CLEARANCE_MM * 2);
|
||||
ArrangePolygons items = squares_of_heights({NOZZLE_HEIGHT_MM * 2, NOZZLE_HEIGHT_MM * 2});
|
||||
DynamicPrintConfig cfg = bed_config();
|
||||
ArrangeParams p = seq_print_params(stored);
|
||||
|
||||
update_selected_items_inflation(items, &cfg, p);
|
||||
CHECK(p.min_obj_distance == stored);
|
||||
}
|
||||
|
||||
TEST_CASE("Layered printing does not floor the object distance", "[Arrange]")
|
||||
{
|
||||
ArrangePolygons items = squares_of_heights({NOZZLE_HEIGHT_MM * 2, NOZZLE_HEIGHT_MM * 2});
|
||||
DynamicPrintConfig cfg = bed_config();
|
||||
ArrangeParams p = seq_print_params(0);
|
||||
p.is_seq_print = false;
|
||||
|
||||
update_selected_items_inflation(items, &cfg, p);
|
||||
CHECK(p.min_obj_distance == 0);
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -15,6 +15,8 @@
|
||||
#include <boost/nowide/fstream.hpp>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <sstream>
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
SCENARIO("Generic config validation performs as expected.", "[Config]") {
|
||||
@@ -488,6 +490,59 @@ TEST_CASE("save_to_json round-trips plugin capability references as strings", "[
|
||||
CHECK(reloaded.option<ConfigOptionStrings>("slicing_pipeline_plugin")->values == refs);
|
||||
}
|
||||
|
||||
TEST_CASE("save_to_json writes the same document to a stream as to a file", "[Config]") {
|
||||
DynamicPrintConfig config;
|
||||
config.set_key_value("layer_height", new ConfigOptionFloat(0.2));
|
||||
config.set_key_value("wall_loops", new ConfigOptionInt(3));
|
||||
config.set_key_value("filament_type", new ConfigOptionStrings({ "PLA", "PETG" }));
|
||||
config.set_key_value("machine_start_gcode", new ConfigOptionString("G28\nG1 Z5"));
|
||||
|
||||
ScopedTemporaryFile tmp(".json");
|
||||
config.save_to_json(tmp.string(), "test_preset", "User", "1.0.0.0");
|
||||
std::string file_contents;
|
||||
{
|
||||
boost::nowide::ifstream ifs(tmp.string());
|
||||
file_contents.assign(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
|
||||
}
|
||||
// The file format: one tab per nesting level and a trailing newline.
|
||||
REQUIRE_FALSE(file_contents.empty());
|
||||
CHECK(file_contents.rfind("{\n\t\"", 0) == 0);
|
||||
CHECK(file_contents.back() == '\n');
|
||||
|
||||
std::ostringstream strict, replaced;
|
||||
config.save_to_json(strict, "test_preset", "User", "1.0.0.0");
|
||||
config.save_to_json(replaced, "test_preset", "User", "1.0.0.0", true);
|
||||
CHECK(strict.str() == file_contents);
|
||||
CHECK(replaced.str() == file_contents);
|
||||
CHECK(nlohmann::json::parse(strict.str())["machine_start_gcode"] == "G28\nG1 Z5");
|
||||
}
|
||||
|
||||
TEST_CASE("save_to_json replaces invalid UTF-8 in a stream only when asked", "[Config]") {
|
||||
DynamicPrintConfig config;
|
||||
config.set_key_value("machine_start_gcode", new ConfigOptionString("G28 ; \xff"));
|
||||
|
||||
std::ostringstream strict, replaced;
|
||||
CHECK_THROWS_AS(config.save_to_json(strict, "test_preset", "User", "1.0.0.0"), nlohmann::json::type_error);
|
||||
REQUIRE_NOTHROW(config.save_to_json(replaced, "test_preset", "User", "1.0.0.0", true));
|
||||
CHECK(nlohmann::json::parse(replaced.str())["machine_start_gcode"] == "G28 ; \xEF\xBF\xBD");
|
||||
}
|
||||
|
||||
TEST_CASE("save_to_json leaves an existing file untouched when the config cannot be serialized", "[Config]") {
|
||||
DynamicPrintConfig config;
|
||||
config.set_key_value("machine_start_gcode", new ConfigOptionString("G28 ; \xff"));
|
||||
|
||||
ScopedTemporaryFile tmp(".json");
|
||||
{
|
||||
boost::nowide::ofstream ofs(tmp.string());
|
||||
ofs << "previous";
|
||||
}
|
||||
CHECK_THROWS_AS(config.save_to_json(tmp.string(), "test_preset", "User", "1.0.0.0"), nlohmann::json::type_error);
|
||||
|
||||
boost::nowide::ifstream ifs(tmp.string());
|
||||
const std::string contents((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
|
||||
CHECK(contents == "previous");
|
||||
}
|
||||
|
||||
TEST_CASE("plugin capability references survive string-map serialization", "[Config][plugins]") {
|
||||
const std::vector<std::string> refs = {
|
||||
"master_plugin;;header-stamp",
|
||||
@@ -828,3 +883,391 @@ 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");
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// min_object_distance reads exactly these three options.
|
||||
DynamicPrintConfig spacing_config(PrinterTechnology tech, PrintSequence seq, double clearance_radius)
|
||||
{
|
||||
DynamicPrintConfig c;
|
||||
c.set_key_value("printer_technology", new ConfigOptionEnum<PrinterTechnology>(tech));
|
||||
c.set_key_value("print_sequence", new ConfigOptionEnum<PrintSequence>(seq));
|
||||
c.set_key_value("extruder_clearance_radius", new ConfigOptionFloat(clearance_radius));
|
||||
return c;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("min_object_distance floors object spacing per print sequence", "[Config]")
|
||||
{
|
||||
struct Case
|
||||
{
|
||||
std::string description;
|
||||
PrinterTechnology tech;
|
||||
PrintSequence sequence;
|
||||
double clearance_radius;
|
||||
double expected;
|
||||
};
|
||||
|
||||
auto c = GENERATE(values<Case>({
|
||||
{"sequential FFF takes a clearance radius above the floor", ptFFF, PrintSequence::ByObject, 12., 12.},
|
||||
{"sequential FFF holds the floor at the radius", ptFFF, PrintSequence::ByObject, 6., 6.},
|
||||
{"sequential FFF holds the floor below the radius", ptFFF, PrintSequence::ByObject, 4., 6.},
|
||||
{"layered FFF ignores the clearance radius", ptFFF, PrintSequence::ByLayer, 12., 6.},
|
||||
{"SLA is a flat 6mm", ptSLA, PrintSequence::ByObject, 12., 6.},
|
||||
{"SLA ignores the print sequence too", ptSLA, PrintSequence::ByLayer, 12., 6.},
|
||||
}));
|
||||
|
||||
DYNAMIC_SECTION(c.description)
|
||||
{
|
||||
CHECK_THAT(min_object_distance(spacing_config(c.tech, c.sequence, c.clearance_radius)),
|
||||
Catch::Matchers::WithinAbs(c.expected, 1e-9));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("min_object_distance yields no floor when an FFF config lacks the options", "[Config]")
|
||||
{
|
||||
// Missing options yield 0 rather than an error, so a caller gets no floor at all.
|
||||
SECTION("no clearance radius") {
|
||||
DynamicPrintConfig c;
|
||||
c.set_key_value("printer_technology", new ConfigOptionEnum<PrinterTechnology>(ptFFF));
|
||||
c.set_key_value("print_sequence", new ConfigOptionEnum<PrintSequence>(PrintSequence::ByObject));
|
||||
CHECK_THAT(min_object_distance(c), Catch::Matchers::WithinAbs(0., 1e-9));
|
||||
}
|
||||
|
||||
SECTION("no print sequence") {
|
||||
DynamicPrintConfig c;
|
||||
c.set_key_value("printer_technology", new ConfigOptionEnum<PrinterTechnology>(ptFFF));
|
||||
c.set_key_value("extruder_clearance_radius", new ConfigOptionFloat(12.));
|
||||
CHECK_THAT(min_object_distance(c), Catch::Matchers::WithinAbs(0., 1e-9));
|
||||
}
|
||||
|
||||
SECTION("nothing at all") {
|
||||
CHECK_THAT(min_object_distance(DynamicPrintConfig{}), Catch::Matchers::WithinAbs(0., 1e-9));
|
||||
}
|
||||
|
||||
SECTION("an unset printer technology is treated as FFF") {
|
||||
DynamicPrintConfig c;
|
||||
c.set_key_value("print_sequence", new ConfigOptionEnum<PrintSequence>(PrintSequence::ByObject));
|
||||
c.set_key_value("extruder_clearance_radius", new ConfigOptionFloat(12.));
|
||||
CHECK_THAT(min_object_distance(c), Catch::Matchers::WithinAbs(12., 1e-9));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Static print configs compare, order and hash by their option values", "[Config]")
|
||||
{
|
||||
// PrintObjectConfig comes from PRINT_CONFIG_CLASS_DEFINE; PrintConfig combines MachineEnvelopeConfig
|
||||
// and GCodeConfig through PRINT_CONFIG_CLASS_DERIVED_DEFINE. Both generate hash(), operator==,
|
||||
// operator< and the option registration from the same option list. The hash inequalities use fixed
|
||||
// inputs, so they are deterministic; they check that hash() covers the changed option.
|
||||
SECTION("default-constructed configs are equal and find their options by key")
|
||||
{
|
||||
PrintObjectConfig a, b;
|
||||
REQUIRE(a == b);
|
||||
REQUIRE(a.hash() == b.hash());
|
||||
REQUIRE_FALSE(a < b);
|
||||
REQUIRE_FALSE(b < a);
|
||||
REQUIRE(a.optptr("layer_height") == &a.layer_height);
|
||||
REQUIRE(a.optptr("brim_object_gap") == &a.brim_object_gap);
|
||||
}
|
||||
|
||||
SECTION("one differing option makes the configs unequal and orders them")
|
||||
{
|
||||
PrintObjectConfig a, b;
|
||||
b.layer_height.value = a.layer_height.value + 0.05;
|
||||
REQUIRE(a != b);
|
||||
REQUIRE(a.hash() != b.hash());
|
||||
REQUIRE(a < b);
|
||||
REQUIRE_FALSE(b < a);
|
||||
}
|
||||
|
||||
SECTION("ordering is decided by the first option in declaration order that differs")
|
||||
{
|
||||
PrintObjectConfig a, b;
|
||||
a.brim_object_gap.value = b.brim_object_gap.value + 1.0; // declared first
|
||||
a.layer_height.value = b.layer_height.value - 0.05; // declared later, points the other way
|
||||
REQUIRE(b < a);
|
||||
REQUIRE_FALSE(a < b);
|
||||
}
|
||||
|
||||
SECTION("a derived config sees differences in its parents and in its own options")
|
||||
{
|
||||
PrintConfig a, b;
|
||||
REQUIRE(a == b);
|
||||
REQUIRE(a.hash() == b.hash());
|
||||
|
||||
b.gcode_flavor.value = b.gcode_flavor.value == gcfMarlinLegacy ? gcfKlipper : gcfMarlinLegacy; // GCodeConfig parent
|
||||
REQUIRE(a != b);
|
||||
REQUIRE(a.hash() != b.hash());
|
||||
|
||||
PrintConfig c, d;
|
||||
d.skirt_distance.value = c.skirt_distance.value + 1.0; // PrintConfig's own list
|
||||
REQUIRE(c != d);
|
||||
REQUIRE(c.hash() != d.hash());
|
||||
REQUIRE(c.optptr("skirt_distance") == &c.skirt_distance);
|
||||
REQUIRE(c.optptr("gcode_flavor") == &c.gcode_flavor);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -478,4 +484,113 @@ TEST_CASE("update_values_to_printer_extruders_for_multiple_filaments resolves pe
|
||||
REQUIRE(config.option<ConfigOptionFloats>("filament_max_volumetric_speed")->values == std::vector<double>({12., 21.}));
|
||||
REQUIRE(config.option<ConfigOptionInts>("filament_self_index")->values == std::vector<int>({1, 2}));
|
||||
}
|
||||
|
||||
SECTION("a variant option shorter than the filament slots keeps its first value instead of zero") {
|
||||
DynamicPrintConfig config;
|
||||
config.option<ConfigOptionEnumsGeneric>("extruder_type", true)->values = {etDirectDrive, etDirectDrive};
|
||||
config.option<ConfigOptionEnumsGeneric>("nozzle_volume_type", true)->values = {nvtStandard, nvtHighFlow};
|
||||
config.option<ConfigOptionStrings>("extruder_variant_list", true)->values = {"Direct Drive Standard,Direct Drive High Flow",
|
||||
"Direct Drive Standard,Direct Drive High Flow"};
|
||||
make_filament_arrays(config);
|
||||
config.option<ConfigOptionInts>("filament_map", true)->values = {1, 2};
|
||||
// no loaded preset carries the key, so only its single registered default is present
|
||||
config.option<ConfigOptionFloatsNullable>("filament_cooling_before_tower", true)->values = {10.};
|
||||
// only the first filament's two variant columns were loaded
|
||||
config.option<ConfigOptionFloatsNullable>("filament_ramming_volumetric_speed", true)->values = {-1., -2.};
|
||||
|
||||
std::vector<std::vector<NozzleVolumeType>> nozzle_volume_types;
|
||||
int extruder_count = 2;
|
||||
int count = config.get_extruder_nozzle_volume_count(extruder_count, nozzle_volume_types);
|
||||
|
||||
config.update_values_to_printer_extruders_for_multiple_filaments(config, extruder_count, count, filament_keys,
|
||||
"filament_self_index", "filament_extruder_variant");
|
||||
|
||||
// filament 2 resolves to column 3 (its extruder's High Flow column), past the end of both vectors
|
||||
REQUIRE_THAT(config.option<ConfigOptionFloatsNullable>("filament_cooling_before_tower")->values,
|
||||
Catch::Matchers::Approx(std::vector<double>({10., 10.})));
|
||||
REQUIRE_THAT(config.option<ConfigOptionFloatsNullable>("filament_ramming_volumetric_speed")->values,
|
||||
Catch::Matchers::Approx(std::vector<double>({-1., -1.})));
|
||||
REQUIRE(config.option<ConfigOptionFloats>("filament_max_volumetric_speed")->values == std::vector<double>({12., 21.}));
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include "libslic3r/LayOnFace.hpp"
|
||||
#include "libslic3r/Model.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
using Catch::Matchers::WithinAbs;
|
||||
|
||||
namespace {
|
||||
|
||||
// Adds a box part spanning `origin` to `origin + size`, in object coordinates.
|
||||
void add_box(ModelObject &object, const Vec3d &size, const Vec3d &origin = Vec3d::Zero())
|
||||
{
|
||||
TriangleMesh mesh = make_cube(size.x(), size.y(), size.z());
|
||||
mesh.translate(origin.cast<float>());
|
||||
object.add_volume(std::move(mesh), ModelVolumeType::MODEL_PART, false);
|
||||
}
|
||||
|
||||
ModelObject &add_box_object(Model &model, const Vec3d &size)
|
||||
{
|
||||
ModelObject *object = model.add_object();
|
||||
add_box(*object, size);
|
||||
object->add_instance();
|
||||
return *object;
|
||||
}
|
||||
|
||||
// A 30 x 30 x 2 plate with three 1 mm thick, 20 mm tall ribs along Y. The rib sides facing -X add up
|
||||
// to more area than the plate's bottom, but only the bottom is a face of the convex hull.
|
||||
ModelObject &add_ribbed_plate(Model &model)
|
||||
{
|
||||
ModelObject *object = model.add_object();
|
||||
add_box(*object, { 30, 30, 2 });
|
||||
for (double x : { 5., 14.5, 24. })
|
||||
add_box(*object, { 1, 30, 20 }, { x, 0, 2 });
|
||||
object->add_instance();
|
||||
return *object;
|
||||
}
|
||||
|
||||
std::vector<LayOnFacePlane> instance_planes(const ModelObject &object)
|
||||
{
|
||||
return lay_on_face_planes(object, object.instances.front()->get_matrix_no_offset());
|
||||
}
|
||||
|
||||
void lay_on_largest_face(ModelObject &object)
|
||||
{
|
||||
const std::vector<LayOnFacePlane> planes = instance_planes(object);
|
||||
const int idx = find_largest_plane(planes);
|
||||
REQUIRE(idx >= 0);
|
||||
lay_on_face(object, 0, planes[idx].normal);
|
||||
}
|
||||
|
||||
void check_size(const ModelObject &object, const Vec3d &expected)
|
||||
{
|
||||
const Vec3d size = object.instance_bounding_box(0).size();
|
||||
CHECK_THAT(size.x(), WithinAbs(expected.x(), 1e-3));
|
||||
CHECK_THAT(size.y(), WithinAbs(expected.y(), 1e-3));
|
||||
CHECK_THAT(size.z(), WithinAbs(expected.z(), 1e-3));
|
||||
}
|
||||
|
||||
void check_on_bed(const ModelObject &object) { CHECK_THAT(object.instance_bounding_box(0).min.z(), WithinAbs(0., 1e-3)); }
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("A tilted box is laid on its largest face and dropped onto the bed", "[LayOnFace]")
|
||||
{
|
||||
Model model;
|
||||
ModelObject &box = add_box_object(model, { 40, 20, 10 }); // the 40 x 20 faces are the largest
|
||||
box.instances.front()->set_rotation({ 0.3, 0.5, 0.2 });
|
||||
box.instances.front()->set_offset({ 0, 0, 50 });
|
||||
REQUIRE(box.instance_bounding_box(0).size().z() > 11.);
|
||||
|
||||
const std::vector<LayOnFacePlane> planes = instance_planes(box);
|
||||
REQUIRE(planes.size() == 6);
|
||||
CHECK_THAT(planes.front().area, WithinAbs(40. * 20., 1e-2));
|
||||
|
||||
lay_on_largest_face(box);
|
||||
CHECK_THAT(box.instance_bounding_box(0).size().z(), WithinAbs(10., 1e-3));
|
||||
check_on_bed(box);
|
||||
}
|
||||
|
||||
TEST_CASE("A box lying on one of its equally large faces is not flipped", "[LayOnFace]")
|
||||
{
|
||||
// A half turn about X puts the other large face down, so the two cases expect different faces
|
||||
// and neither can pass on the order in which the hull lists them.
|
||||
const double rotation_x = GENERATE(0., PI);
|
||||
Model model;
|
||||
ModelObject &box = add_box_object(model, { 40, 20, 10 }); // the bottom and top are both 40 x 20
|
||||
box.instances.front()->set_rotation({ rotation_x, 0, 0 });
|
||||
const Transform3d before = box.instances.front()->get_matrix_no_offset();
|
||||
|
||||
const std::vector<LayOnFacePlane> planes = instance_planes(box);
|
||||
const int idx = find_largest_plane(planes);
|
||||
REQUIRE(idx >= 0);
|
||||
// The face down on the plate is the object's -Z face, or its +Z face after the half turn.
|
||||
CHECK_THAT(planes[idx].normal.z(), WithinAbs(rotation_x == 0. ? -1. : 1., 1e-6));
|
||||
|
||||
lay_on_face(box, 0, planes[idx].normal);
|
||||
CHECK(box.instances.front()->get_matrix_no_offset().isApprox(before, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Faces are chosen from the orientation left by an earlier part rotation", "[LayOnFace]")
|
||||
{
|
||||
Model model;
|
||||
ModelObject &box = add_box_object(model, { 40, 20, 10 });
|
||||
box.rotate(PI / 2., X); // what --rotate-x 90 does: rotates the parts, not the instance
|
||||
check_size(box, { 40, 10, 20 });
|
||||
|
||||
SECTION("the largest face") {
|
||||
lay_on_largest_face(box);
|
||||
check_size(box, { 40, 20, 10 });
|
||||
check_on_bed(box);
|
||||
}
|
||||
|
||||
SECTION("the face pointing along +X") {
|
||||
const std::vector<LayOnFacePlane> planes = instance_planes(box);
|
||||
const int idx = find_plane_by_normal(planes, { 1, 0, 0 });
|
||||
REQUIRE(idx >= 0);
|
||||
CHECK_THAT(planes[idx].normal.x(), WithinAbs(1., 1e-6));
|
||||
lay_on_face(box, 0, planes[idx].normal);
|
||||
check_size(box, { 20, 10, 40 });
|
||||
check_on_bed(box);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Objects are laid on their own faces independently", "[LayOnFace]")
|
||||
{
|
||||
Model model;
|
||||
// Standing on end through its instance rotation.
|
||||
ModelObject &standing = add_box_object(model, { 40, 20, 10 });
|
||||
standing.instances.front()->set_rotation({ 0, PI / 2., 0 });
|
||||
// Standing on edge through a part rotation, lifted above the bed.
|
||||
ModelObject &on_edge = add_box_object(model, { 30, 20, 5 });
|
||||
on_edge.rotate(PI / 2., X);
|
||||
on_edge.instances.front()->set_offset({ 100, 0, 30 });
|
||||
check_size(standing, { 10, 20, 40 });
|
||||
check_size(on_edge, { 30, 5, 20 });
|
||||
|
||||
for (ModelObject *object : model.objects)
|
||||
lay_on_largest_face(*object);
|
||||
|
||||
check_size(standing, { 40, 20, 10 });
|
||||
check_on_bed(standing);
|
||||
check_size(on_edge, { 30, 20, 5 });
|
||||
check_on_bed(on_edge);
|
||||
}
|
||||
|
||||
TEST_CASE("A part rests on its largest hull face even when parallel inner faces add up to more area", "[LayOnFace]")
|
||||
{
|
||||
Model model;
|
||||
ModelObject &plate = add_ribbed_plate(model);
|
||||
|
||||
double area_facing_minus_x = 0.;
|
||||
for (const ModelVolume *volume : plate.volumes) {
|
||||
const indexed_triangle_set &its = volume->mesh().its;
|
||||
for (const Vec3i32 &face : its.indices) {
|
||||
const Vec3d cross = (its.vertices[face[1]] - its.vertices[face[0]]).cast<double>().cross(
|
||||
(its.vertices[face[2]] - its.vertices[face[0]]).cast<double>());
|
||||
if (cross.normalized().x() < -0.999)
|
||||
area_facing_minus_x += 0.5 * cross.norm();
|
||||
}
|
||||
}
|
||||
// Summing triangle area per normal would pick a rib side over the 900 mm² bottom.
|
||||
REQUIRE(area_facing_minus_x > 30. * 30.);
|
||||
|
||||
plate.instances.front()->set_rotation({ 0, PI / 2., 0 }); // stand the plate on its side
|
||||
check_size(plate, { 22, 30, 30 });
|
||||
|
||||
const std::vector<LayOnFacePlane> planes = instance_planes(plate);
|
||||
const int idx = find_largest_plane(planes);
|
||||
REQUIRE(idx >= 0);
|
||||
CHECK_THAT(planes[idx].area, WithinAbs(30. * 30., 1e-2));
|
||||
CHECK_THAT(planes[idx].normal.z(), WithinAbs(-1., 1e-6));
|
||||
|
||||
lay_on_face(plate, 0, planes[idx].normal);
|
||||
check_size(plate, { 30, 30, 22 });
|
||||
check_on_bed(plate);
|
||||
}
|
||||
|
||||
TEST_CASE("Faces are selected in object coordinates whatever the instance rotation", "[LayOnFace]")
|
||||
{
|
||||
Model model;
|
||||
ModelObject &plate = add_ribbed_plate(model);
|
||||
plate.instances.front()->set_rotation({ 0, 0, PI / 2. });
|
||||
const Transform3d instance_matrix = plate.instances.front()->get_matrix_no_offset();
|
||||
const std::vector<LayOnFacePlane> planes = lay_on_face_planes(plate, instance_matrix);
|
||||
REQUIRE_FALSE(planes.empty());
|
||||
|
||||
// Every face center, as --inspect-mesh reports it, selects its own face.
|
||||
for (size_t i = 0; i < planes.size(); ++i)
|
||||
CHECK(find_plane_at_point(planes, instance_matrix, planes[i].center, 0.01) == int(i));
|
||||
|
||||
const int bottom = find_plane_at_point(planes, instance_matrix, { 15, 15, 0 }, 0.01);
|
||||
REQUIRE(bottom >= 0);
|
||||
CHECK_THAT(planes[bottom].normal.z(), WithinAbs(-1., 1e-6));
|
||||
CHECK(find_plane_by_normal(planes, { 0, 0, -1 }) == bottom);
|
||||
// Above the bottom plane, and on a rib side that lies inside the hull.
|
||||
CHECK(find_plane_at_point(planes, instance_matrix, { 15, 15, 0.5 }, 0.01) == -1);
|
||||
CHECK(find_plane_at_point(planes, instance_matrix, { 14.5, 15, 12 }, 0.01) == -1);
|
||||
}
|
||||
|
||||
TEST_CASE("A part too small to rest on offers no faces", "[LayOnFace]")
|
||||
{
|
||||
Model model;
|
||||
CHECK(instance_planes(add_box_object(model, { 2, 2, 2 })).empty()); // every face is 4 mm², under the 5 mm² minimum
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
|
||||
#include <catch2/catch_all.hpp>
|
||||
#include "test_utils.hpp"
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "libslic3r/MinimumSpanningTree.hpp"
|
||||
#include "libslic3r/Point.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
// A 5x5 lattice: at every step of Prim's algorithm several candidates sit at the same
|
||||
// distance from the tree, so the tie-break decides the tree's shape.
|
||||
static std::vector<Point> lattice()
|
||||
{
|
||||
std::vector<Point> vertices;
|
||||
for (int y = 0; y < 5; ++y)
|
||||
for (int x = 0; x < 5; ++x)
|
||||
vertices.emplace_back(Point::new_scale(x, y));
|
||||
return vertices;
|
||||
}
|
||||
|
||||
static std::vector<Point> sorted_neighbours(const MinimumSpanningTree &mst, const Point &vertex)
|
||||
{
|
||||
std::vector<Point> neighbours = mst.adjacent_nodes(vertex);
|
||||
std::sort(neighbours.begin(), neighbours.end());
|
||||
return neighbours;
|
||||
}
|
||||
|
||||
TEST_CASE("Minimum spanning tree connects every vertex", "[MinimumSpanningTree]")
|
||||
{
|
||||
const std::vector<Point> vertices = lattice();
|
||||
const MinimumSpanningTree mst(vertices);
|
||||
|
||||
REQUIRE(mst.vertices().size() == vertices.size());
|
||||
size_t adjacency_entries = 0;
|
||||
for (const Point &vertex : vertices) {
|
||||
const std::vector<Point> neighbours = mst.adjacent_nodes(vertex);
|
||||
REQUIRE(! neighbours.empty());
|
||||
adjacency_entries += neighbours.size();
|
||||
}
|
||||
// A tree on n vertices has n - 1 edges, each listed from both ends.
|
||||
REQUIRE(adjacency_entries == 2 * (vertices.size() - 1));
|
||||
}
|
||||
|
||||
TEST_CASE("Minimum spanning tree does not depend on the order of the non-root vertices", "[MinimumSpanningTree][Regression]")
|
||||
{
|
||||
const std::vector<Point> vertices = lattice();
|
||||
const MinimumSpanningTree reference(vertices);
|
||||
|
||||
// The root stays first: Prim's tree legitimately depends on where it starts.
|
||||
// Every other order of the remaining vertices must give the same tree.
|
||||
std::vector<std::vector<Point>> orders;
|
||||
orders.emplace_back(vertices);
|
||||
std::reverse(orders.back().begin() + 1, orders.back().end());
|
||||
for (size_t shift = 1; shift + 1 < vertices.size(); ++shift) {
|
||||
orders.emplace_back(vertices);
|
||||
std::rotate(orders.back().begin() + 1, orders.back().begin() + 1 + shift, orders.back().end());
|
||||
}
|
||||
|
||||
for (const std::vector<Point> &order : orders) {
|
||||
const MinimumSpanningTree mst(order);
|
||||
for (const Point &vertex : vertices) {
|
||||
INFO("vertex " << vertex.x() << "," << vertex.y());
|
||||
REQUIRE(sorted_neighbours(mst, vertex) == sorted_neighbours(reference, vertex));
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -33,3 +33,20 @@ TEST_CASE("deep_diff flags new vector entries that duplicate values[0]", "[Prese
|
||||
// specific to new indices rather than flagging the whole vector.
|
||||
REQUIRE(std::find(diff.begin(), diff.end(), "nozzle_diameter#0") == diff.end());
|
||||
}
|
||||
|
||||
TEST_CASE("deep_diff distinguishes absolute and percentage speeds for each variant", "[PresetDiff][Config]")
|
||||
{
|
||||
const size_t changed_index = GENERATE(size_t(0), size_t(1));
|
||||
Preset reference(Preset::TYPE_PRINT, "ref");
|
||||
reference.config.set_key_value("small_perimeter_speed", new ConfigOptionFloatsOrPercents{{50., false}, {50., false}});
|
||||
|
||||
Preset edited = reference;
|
||||
edited.config.option<ConfigOptionFloatsOrPercents>("small_perimeter_speed")->values[changed_index].percent = true;
|
||||
|
||||
const auto diff = PresetCollection::dirty_options(&edited, &reference, /*deep_compare=*/true);
|
||||
REQUIRE(diff == std::vector<std::string>{"small_perimeter_speed#" + std::to_string(changed_index)});
|
||||
|
||||
DynamicPrintConfig transferred = reference.config;
|
||||
transferred.apply_only(edited.config, diff);
|
||||
REQUIRE(*transferred.option("small_perimeter_speed") == *edited.config.option("small_perimeter_speed"));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// Regression test for the "option in def + UI but missing from preset key list"
|
||||
// crash class.
|
||||
//
|
||||
// The print preset's DynamicPrintConfig is seeded with only the keys returned by
|
||||
// Preset::print_options() (PresetBundle.cpp). A field added to PrintRegionConfig
|
||||
// or PrintObjectConfig and registered via print_config_def plus a TabPrint
|
||||
// optgroup, but left out of print_options(), still gets its control built; on tab
|
||||
// activation reload_config -> get_config_value dispatches to opt_bool/opt_int on a
|
||||
// DynamicPrintConfig with no entry for the key, and the accessor null-derefs the
|
||||
// result of option<T>(key).
|
||||
//
|
||||
// The invariant asserted here is the inverse: every key declared on
|
||||
// PrintRegionConfig and PrintObjectConfig appears in Preset::print_options() or
|
||||
// Preset::filament_options(), the two preset key lists that seed a print preset's
|
||||
// DynamicConfig.
|
||||
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include "libslic3r/Preset.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
|
||||
#include <set>
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
namespace {
|
||||
|
||||
// Deprecated keys renamed in handle_legacy() (ironing_direction ->
|
||||
// ironing_angle, wall_infill_order -> wall_sequence); neither is in a
|
||||
// preset list. Register new options in a preset list, not here.
|
||||
const std::set<std::string> kDeprecatedRegionFields = {
|
||||
"ironing_direction",
|
||||
"wall_infill_order",
|
||||
};
|
||||
|
||||
void check_keys_are_in_a_preset(const t_config_option_keys& keys, const std::string& class_name)
|
||||
{
|
||||
REQUIRE_FALSE(keys.empty());
|
||||
const auto& print_options = Preset::print_options();
|
||||
const auto& filament_options = Preset::filament_options();
|
||||
const std::set<std::string> in_print(print_options.begin(), print_options.end());
|
||||
const std::set<std::string> in_filament(filament_options.begin(), filament_options.end());
|
||||
for (const std::string& key : keys) {
|
||||
DYNAMIC_SECTION(class_name << "::" << key)
|
||||
{
|
||||
INFO("'" << key << "' on " << class_name
|
||||
<< " is missing from "
|
||||
"Preset::print_options()/filament_options(); add it to "
|
||||
"s_Preset_print_options (or s_Preset_filament_options) in Preset.cpp.");
|
||||
const bool registered = in_print.count(key) || in_filament.count(key) || kDeprecatedRegionFields.count(key);
|
||||
REQUIRE(registered);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Bodies are laid out like the rest of the test suite rather than collapsed
|
||||
// onto the brace line.
|
||||
// clang-format off
|
||||
TEST_CASE("Every PrintRegionConfig field is registered in a preset key list", "[Preset][Config]")
|
||||
{
|
||||
check_keys_are_in_a_preset(PrintRegionConfig::defaults().keys(), "PrintRegionConfig");
|
||||
}
|
||||
|
||||
TEST_CASE("Every PrintObjectConfig field is registered in a preset key list", "[Preset][Config]")
|
||||
{
|
||||
check_keys_are_in_a_preset(PrintObjectConfig::defaults().keys(), "PrintObjectConfig");
|
||||
}
|
||||
// clang-format on
|
||||
@@ -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_profile_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_profile_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[] = {
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
#include <catch2/catch_all.hpp> // mainline OrcaSlicer ships Catch2 v3 (v2 was catch2/catch.hpp)
|
||||
#include "libslic3r/CAD/SketchConstraints.hpp"
|
||||
#include "libslic3r/CAD/SketchEngine.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
namespace {
|
||||
SketchEntity mk_line(double x0, double y0, double x1, double y1)
|
||||
{
|
||||
SketchEntity e; e.type = SketchEntity::Type::Line;
|
||||
e.p0 = Vec2d(x0, y0); e.p1 = Vec2d(x1, y1); return e;
|
||||
}
|
||||
SketchEntity mk_point(double x, double y)
|
||||
{
|
||||
SketchEntity e; e.type = SketchEntity::Type::Point; e.p0 = Vec2d(x, y); return e;
|
||||
}
|
||||
SketchEntity mk_circle(double cx, double cy, double r)
|
||||
{
|
||||
SketchEntity e; e.type = SketchEntity::Type::Circle;
|
||||
e.center = Vec2d(cx, cy); e.radius = r; return e;
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Coincident with anchor", "[SketchConstraints]")
|
||||
{
|
||||
SketchConstraints sc;
|
||||
int a = sc.add_point(0, 0);
|
||||
int b = sc.add_point(5, 5);
|
||||
sc.fix_point(a);
|
||||
sc.coincident(a, b);
|
||||
REQUIRE(sc.solve());
|
||||
Vec2d pb = sc.get_point(b);
|
||||
REQUIRE_THAT(pb.x(), Catch::Matchers::WithinAbs(0.0, 1e-4));
|
||||
REQUIRE_THAT(pb.y(), Catch::Matchers::WithinAbs(0.0, 1e-4));
|
||||
}
|
||||
|
||||
TEST_CASE("Horizontal + distance", "[SketchConstraints]")
|
||||
{
|
||||
SketchConstraints sc;
|
||||
int a = sc.add_point(0, 0);
|
||||
int b = sc.add_point(5, 3);
|
||||
sc.fix_point(a);
|
||||
sc.horizontal(a, b);
|
||||
sc.distance(a, b, 10);
|
||||
REQUIRE(sc.solve());
|
||||
Vec2d pb = sc.get_point(b);
|
||||
REQUIRE_THAT(pb.y(), Catch::Matchers::WithinAbs(0.0, 1e-3));
|
||||
REQUIRE_THAT(std::abs(pb.x()), Catch::Matchers::WithinAbs(10.0, 1e-3));
|
||||
}
|
||||
|
||||
TEST_CASE("Rectangle", "[SketchConstraints]")
|
||||
{
|
||||
SketchConstraints sc;
|
||||
int p0 = sc.add_point(0, 0);
|
||||
int p1 = sc.add_point(8, 1);
|
||||
int p2 = sc.add_point(9, 5);
|
||||
int p3 = sc.add_point(-1, 4);
|
||||
sc.fix_point(p0);
|
||||
sc.lock_x(p0, 0);
|
||||
sc.lock_y(p0, 0);
|
||||
sc.horizontal(p0, p1);
|
||||
sc.vertical(p1, p2);
|
||||
sc.horizontal(p2, p3);
|
||||
sc.vertical(p3, p0);
|
||||
sc.distance(p0, p1, 10);
|
||||
sc.distance(p1, p2, 6);
|
||||
REQUIRE(sc.solve());
|
||||
Vec2d pp1 = sc.get_point(p1);
|
||||
Vec2d pp2 = sc.get_point(p2);
|
||||
Vec2d pp3 = sc.get_point(p3);
|
||||
REQUIRE_THAT(pp1.x(), Catch::Matchers::WithinAbs(10.0, 1e-3));
|
||||
REQUIRE_THAT(pp1.y(), Catch::Matchers::WithinAbs(0.0, 1e-3));
|
||||
REQUIRE_THAT(pp2.x(), Catch::Matchers::WithinAbs(10.0, 1e-3));
|
||||
REQUIRE_THAT(pp2.y(), Catch::Matchers::WithinAbs(6.0, 1e-3));
|
||||
REQUIRE_THAT(pp3.x(), Catch::Matchers::WithinAbs(0.0, 1e-3));
|
||||
REQUIRE_THAT(pp3.y(), Catch::Matchers::WithinAbs(6.0, 1e-3));
|
||||
}
|
||||
|
||||
TEST_CASE("residual_norm after each solve", "[SketchConstraints]")
|
||||
{
|
||||
SECTION("coincident case")
|
||||
{
|
||||
SketchConstraints sc;
|
||||
int a = sc.add_point(0, 0);
|
||||
int b = sc.add_point(5, 5);
|
||||
sc.fix_point(a);
|
||||
sc.coincident(a, b);
|
||||
REQUIRE(sc.solve());
|
||||
REQUIRE(sc.residual_norm() < 1e-5);
|
||||
}
|
||||
SECTION("horizontal+distance case")
|
||||
{
|
||||
SketchConstraints sc;
|
||||
int a = sc.add_point(0, 0);
|
||||
int b = sc.add_point(5, 3);
|
||||
sc.fix_point(a);
|
||||
sc.horizontal(a, b);
|
||||
sc.distance(a, b, 10);
|
||||
REQUIRE(sc.solve());
|
||||
REQUIRE(sc.residual_norm() < 1e-5);
|
||||
}
|
||||
SECTION("rectangle case")
|
||||
{
|
||||
SketchConstraints sc;
|
||||
int p0 = sc.add_point(0, 0);
|
||||
int p1 = sc.add_point(8, 1);
|
||||
int p2 = sc.add_point(9, 5);
|
||||
int p3 = sc.add_point(-1, 4);
|
||||
sc.fix_point(p0);
|
||||
sc.lock_x(p0, 0);
|
||||
sc.lock_y(p0, 0);
|
||||
sc.horizontal(p0, p1);
|
||||
sc.vertical(p1, p2);
|
||||
sc.horizontal(p2, p3);
|
||||
sc.vertical(p3, p0);
|
||||
sc.distance(p0, p1, 10);
|
||||
sc.distance(p1, p2, 6);
|
||||
REQUIRE(sc.solve());
|
||||
REQUIRE(sc.residual_norm() < 1e-5);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("midpoint", "[SketchConstraints]")
|
||||
{
|
||||
SketchConstraints sc;
|
||||
int a = sc.add_point(0, 0);
|
||||
int b = sc.add_point(10, 0);
|
||||
int m = sc.add_point(3, 7);
|
||||
sc.fix_point(a);
|
||||
sc.fix_point(b);
|
||||
sc.midpoint(m, a, b);
|
||||
REQUIRE(sc.solve());
|
||||
Vec2d pm = sc.get_point(m);
|
||||
REQUIRE_THAT(pm.x(), Catch::Matchers::WithinAbs(5.0, 1e-3));
|
||||
REQUIRE_THAT(pm.y(), Catch::Matchers::WithinAbs(0.0, 1e-3));
|
||||
}
|
||||
|
||||
TEST_CASE("symmetric across Y axis", "[SketchConstraints]")
|
||||
{
|
||||
SketchConstraints sc;
|
||||
int a = sc.add_point(2, 3);
|
||||
int b = sc.add_point(-1, 1);
|
||||
int c = sc.add_point(0, 0);
|
||||
int d = sc.add_point(0, 1);
|
||||
sc.fix_point(a);
|
||||
sc.fix_point(c);
|
||||
sc.fix_point(d);
|
||||
sc.symmetric(a, b, c, d);
|
||||
REQUIRE(sc.solve());
|
||||
Vec2d pb = sc.get_point(b);
|
||||
REQUIRE_THAT(pb.x(), Catch::Matchers::WithinAbs(-2.0, 1e-3));
|
||||
REQUIRE_THAT(pb.y(), Catch::Matchers::WithinAbs(3.0, 1e-3));
|
||||
}
|
||||
|
||||
TEST_CASE("angle 90 degrees", "[SketchConstraints]")
|
||||
{
|
||||
SketchConstraints sc;
|
||||
int a = sc.add_point(0, 0);
|
||||
int b = sc.add_point(1, 0);
|
||||
int c = sc.add_point(0, 0);
|
||||
int d = sc.add_point(1, 1);
|
||||
sc.fix_point(a);
|
||||
sc.fix_point(b);
|
||||
sc.fix_point(c);
|
||||
sc.angle(a, b, c, d, M_PI / 2);
|
||||
REQUIRE(sc.solve());
|
||||
Vec2d pd = sc.get_point(d);
|
||||
Vec2d pc = sc.get_point(c);
|
||||
REQUIRE_THAT(pd.x() - pc.x(), Catch::Matchers::WithinAbs(0.0, 1e-3));
|
||||
REQUIRE(pd.y() > pc.y());
|
||||
}
|
||||
|
||||
TEST_CASE("point-line distance", "[SketchConstraints]")
|
||||
{
|
||||
SketchConstraints sc;
|
||||
int a = sc.add_point(0, 0);
|
||||
int b = sc.add_point(10, 0);
|
||||
int p = sc.add_point(3, 1);
|
||||
sc.fix_point(a);
|
||||
sc.fix_point(b);
|
||||
sc.lock_x(p, 3.0);
|
||||
sc.point_line_distance(p, a, b, 5.0);
|
||||
REQUIRE(sc.solve());
|
||||
Vec2d pp = sc.get_point(p);
|
||||
REQUIRE_THAT(std::abs(pp.y()), Catch::Matchers::WithinAbs(5.0, 1e-3));
|
||||
REQUIRE_THAT(pp.x(), Catch::Matchers::WithinAbs(3.0, 1e-3));
|
||||
}
|
||||
|
||||
// ---- entity-constraint planner (kernel port of DesignPanel::apply_entity_constraint) ----
|
||||
|
||||
TEST_CASE("sketch_entity_ends exposes real roles only", "[SketchConstraints]")
|
||||
{
|
||||
std::pair<SketchPointRole, Vec2d> out[2];
|
||||
REQUIRE(sketch_entity_ends(mk_point(3, 4), out) == 1);
|
||||
REQUIRE(out[0].first == SketchPointRole::P0);
|
||||
REQUIRE(sketch_entity_ends(mk_circle(1, 2, 5), out) == 1);
|
||||
REQUIRE(out[0].first == SketchPointRole::Center);
|
||||
REQUIRE_THAT(out[0].second.x(), Catch::Matchers::WithinAbs(1.0, 1e-9));
|
||||
REQUIRE_THAT(out[0].second.y(), Catch::Matchers::WithinAbs(2.0, 1e-9));
|
||||
REQUIRE(sketch_entity_ends(mk_line(0, 0, 10, 0), out) == 2);
|
||||
REQUIRE(out[0].first == SketchPointRole::P0);
|
||||
REQUIRE(out[1].first == SketchPointRole::P1);
|
||||
}
|
||||
|
||||
TEST_CASE("Coincident on two Points binds P0/P0, not phantom p1", "[SketchConstraints]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { mk_point(0, 0), mk_point(5, 5) };
|
||||
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, SketchConstraintType::Coincident);
|
||||
REQUIRE(p.kind == ConstraintPlan::Kind::Apply);
|
||||
REQUIRE(p.defs.size() == 1);
|
||||
REQUIRE(p.defs[0].type == SketchConstraintType::Coincident);
|
||||
REQUIRE(p.defs[0].ea == 0);
|
||||
REQUIRE(p.defs[0].ra == SketchPointRole::P0);
|
||||
REQUIRE(p.defs[0].eb == 1);
|
||||
REQUIRE(p.defs[0].rb == SketchPointRole::P0);
|
||||
}
|
||||
|
||||
TEST_CASE("DistanceX on two Points binds real roles with non-negative prefill", "[SketchConstraints]")
|
||||
{
|
||||
// e0 is right of e1, so the raw projected delta is negative: the plan must swap the
|
||||
// refs so accepting the shown (positive) value is a no-op, not a sign flip.
|
||||
std::vector<SketchEntity> ents = { mk_point(5, 1), mk_point(2, 3) };
|
||||
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, SketchConstraintType::DistanceX);
|
||||
REQUIRE(p.kind == ConstraintPlan::Kind::AskValue);
|
||||
REQUIRE(p.defs.size() == 1);
|
||||
REQUIRE(p.defs[0].type == SketchConstraintType::DistanceX);
|
||||
REQUIRE(p.defs[0].ra == SketchPointRole::P0);
|
||||
REQUIRE(p.defs[0].rb == SketchPointRole::P0);
|
||||
REQUIRE(p.prefill >= 0.0);
|
||||
REQUIRE(p.defs[0].ea == 1);
|
||||
REQUIRE(p.defs[0].eb == 0);
|
||||
}
|
||||
|
||||
TEST_CASE("Horizontal on a Point rejects with NeedALine", "[SketchConstraints]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { mk_point(1, 2) };
|
||||
ConstraintPlan p = plan_entity_constraint(ents, 0, -1, -1, SketchConstraintType::Horizontal);
|
||||
REQUIRE(p.kind == ConstraintPlan::Kind::Reject);
|
||||
REQUIRE(p.reason == ConstraintReject::NeedALine);
|
||||
}
|
||||
|
||||
TEST_CASE("Angle on two Circles rejects with NeedTwoLines", "[SketchConstraints]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { mk_circle(0, 0, 1), mk_circle(5, 0, 1) };
|
||||
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, SketchConstraintType::Angle);
|
||||
REQUIRE(p.kind == ConstraintPlan::Kind::Reject);
|
||||
REQUIRE(p.reason == ConstraintReject::NeedTwoLines);
|
||||
}
|
||||
|
||||
TEST_CASE("Parallel on a Line + Circle rejects with NeedTwoLines (new guard)", "[SketchConstraints]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { mk_line(0, 0, 1, 0), mk_circle(5, 0, 1) };
|
||||
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, SketchConstraintType::Parallel);
|
||||
REQUIRE(p.kind == ConstraintPlan::Kind::Reject);
|
||||
REQUIRE(p.reason == ConstraintReject::NeedTwoLines);
|
||||
}
|
||||
|
||||
TEST_CASE("Equal on two Circles promotes to EqualRadius", "[SketchConstraints]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { mk_circle(0, 0, 1), mk_circle(5, 0, 2) };
|
||||
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, SketchConstraintType::EqualLength);
|
||||
REQUIRE(p.kind == ConstraintPlan::Kind::Apply);
|
||||
REQUIRE(p.defs.size() == 1);
|
||||
REQUIRE(p.defs[0].type == SketchConstraintType::EqualRadius);
|
||||
REQUIRE(p.defs[0].ea == 0);
|
||||
REQUIRE(p.defs[0].eb == 1);
|
||||
}
|
||||
|
||||
TEST_CASE("Symmetric on two Lines returns two defs with ec set to the axis", "[SketchConstraints]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { mk_line(0, 1, 5, 1), mk_line(0, -1, 5, -1), mk_line(0, 0, 0, 1) };
|
||||
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, 2, SketchConstraintType::Symmetric);
|
||||
REQUIRE(p.kind == ConstraintPlan::Kind::Apply);
|
||||
REQUIRE(p.defs.size() == 2);
|
||||
for (const auto& d : p.defs) {
|
||||
REQUIRE(d.type == SketchConstraintType::Symmetric);
|
||||
REQUIRE(d.ea == 0);
|
||||
REQUIRE(d.eb == 1);
|
||||
REQUIRE(d.ec == 2);
|
||||
}
|
||||
REQUIRE(p.defs[0].ra == SketchPointRole::P0);
|
||||
REQUIRE(p.defs[0].rb == SketchPointRole::P0);
|
||||
REQUIRE(p.defs[1].ra == SketchPointRole::P1);
|
||||
REQUIRE(p.defs[1].rb == SketchPointRole::P1);
|
||||
}
|
||||
|
||||
TEST_CASE("Symmetric with no axis rejects with NeedAxisLine", "[SketchConstraints]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { mk_point(0, 0), mk_point(5, 0) };
|
||||
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, SketchConstraintType::Symmetric);
|
||||
REQUIRE(p.kind == ConstraintPlan::Kind::Reject);
|
||||
REQUIRE(p.reason == ConstraintReject::NeedAxisLine);
|
||||
}
|
||||
|
||||
TEST_CASE("SymmetricAboutY on two Points returns one def with ec == kSketchRefAxisY", "[SketchConstraints]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { mk_point(1, 0), mk_point(-2, 0) };
|
||||
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, SketchConstraintType::SymmetricAboutY);
|
||||
REQUIRE(p.kind == ConstraintPlan::Kind::Apply);
|
||||
REQUIRE(p.defs.size() == 1);
|
||||
REQUIRE(p.defs[0].type == SketchConstraintType::SymmetricAboutY);
|
||||
REQUIRE(p.defs[0].ec == kSketchRefAxisY);
|
||||
REQUIRE(p.defs[0].ea == 0);
|
||||
REQUIRE(p.defs[0].eb == 1);
|
||||
}
|
||||
|
||||
TEST_CASE("constraint planner apply/askvalue matrix", "[SketchConstraints]")
|
||||
{
|
||||
struct C {
|
||||
const char* name; SketchConstraintType type; std::vector<SketchEntity> ents;
|
||||
int e0, e1, e2; ConstraintPlan::Kind kind;
|
||||
};
|
||||
const std::vector<C> cases = {
|
||||
{ "Fix", SketchConstraintType::Fix, { mk_point(1, 2) }, 0, -1, -1, ConstraintPlan::Kind::Apply },
|
||||
{ "Coincident", SketchConstraintType::Coincident, { mk_point(0, 0), mk_point(5, 5) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
|
||||
{ "Horizontal", SketchConstraintType::Horizontal, { mk_line(0, 0, 5, 0) }, 0, -1, -1, ConstraintPlan::Kind::Apply },
|
||||
{ "Vertical", SketchConstraintType::Vertical, { mk_line(0, 0, 0, 5) }, 0, -1, -1, ConstraintPlan::Kind::Apply },
|
||||
{ "Parallel", SketchConstraintType::Parallel, { mk_line(0, 0, 1, 0), mk_line(0, 1, 1, 1) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
|
||||
{ "Perpendicular", SketchConstraintType::Perpendicular, { mk_line(0, 0, 1, 0), mk_line(0, 0, 0, 1) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
|
||||
{ "EqualLength", SketchConstraintType::EqualLength, { mk_line(0, 0, 1, 0), mk_line(0, 1, 2, 1) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
|
||||
{ "Concentric", SketchConstraintType::Concentric, { mk_circle(0, 0, 1), mk_circle(5, 0, 1) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
|
||||
{ "Tangent", SketchConstraintType::Tangent, { mk_line(0, 0, 1, 0), mk_circle(0, 1, 1) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
|
||||
{ "Midpoint", SketchConstraintType::Midpoint, { mk_point(2, 0), mk_line(0, 0, 5, 0) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
|
||||
{ "Symmetric", SketchConstraintType::Symmetric, { mk_point(0, 0), mk_point(5, 0), mk_line(0, -1, 0, 1) }, 0, 1, 2, ConstraintPlan::Kind::Apply },
|
||||
{ "SymmetricAboutY", SketchConstraintType::SymmetricAboutY, { mk_point(1, 0), mk_point(-2, 0) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
|
||||
{ "SymmetricAboutX", SketchConstraintType::SymmetricAboutX, { mk_point(0, 1), mk_point(0, -2) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
|
||||
{ "EqualRadius", SketchConstraintType::EqualRadius, { mk_circle(0, 0, 1), mk_circle(5, 0, 2) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
|
||||
{ "Collinear", SketchConstraintType::Collinear, { mk_line(0, 0, 1, 0), mk_line(2, 0, 3, 0) }, 0, 1, -1, ConstraintPlan::Kind::Apply },
|
||||
{ "Angle", SketchConstraintType::Angle, { mk_line(0, 0, 1, 0), mk_line(0, 0, 0, 1) }, 0, 1, -1, ConstraintPlan::Kind::AskValue },
|
||||
{ "Radius", SketchConstraintType::Radius, { mk_circle(0, 0, 2.5) }, 0, -1, -1, ConstraintPlan::Kind::AskValue },
|
||||
{ "Diameter", SketchConstraintType::Diameter, { mk_circle(0, 0, 2.5) }, 0, -1, -1, ConstraintPlan::Kind::AskValue },
|
||||
{ "DistanceX", SketchConstraintType::DistanceX, { mk_point(0, 0), mk_point(5, 3) }, 0, 1, -1, ConstraintPlan::Kind::AskValue },
|
||||
{ "DistanceY", SketchConstraintType::DistanceY, { mk_point(0, 0), mk_point(5, 3) }, 0, 1, -1, ConstraintPlan::Kind::AskValue },
|
||||
};
|
||||
for (const C& c : cases) {
|
||||
DYNAMIC_SECTION("apply " << c.name) {
|
||||
ConstraintPlan p = plan_entity_constraint(c.ents, c.e0, c.e1, c.e2, c.type);
|
||||
REQUIRE(p.kind == c.kind);
|
||||
REQUIRE(p.defs.size() >= 1);
|
||||
for (const auto& d : p.defs) REQUIRE(d.type == c.type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("constraint planner reject matrix", "[SketchConstraints]")
|
||||
{
|
||||
struct C {
|
||||
const char* name; SketchConstraintType type; std::vector<SketchEntity> ents;
|
||||
int e0, e1, e2; ConstraintReject reason;
|
||||
};
|
||||
const std::vector<C> cases = {
|
||||
{ "Fix", SketchConstraintType::Fix, {}, 0, -1, -1, ConstraintReject::NeedOneEntity },
|
||||
{ "Coincident", SketchConstraintType::Coincident, { mk_point(0, 0) }, 0, -1, -1, ConstraintReject::NeedTwoEntities },
|
||||
{ "Horizontal", SketchConstraintType::Horizontal, { mk_point(1, 2) }, 0, -1, -1, ConstraintReject::NeedALine },
|
||||
{ "Vertical", SketchConstraintType::Vertical, { mk_circle(0, 0, 1) }, 0, -1, -1, ConstraintReject::NeedALine },
|
||||
{ "Parallel", SketchConstraintType::Parallel, { mk_line(0, 0, 1, 0), mk_circle(5, 0, 1) }, 0, 1, -1, ConstraintReject::NeedTwoLines },
|
||||
{ "Perpendicular", SketchConstraintType::Perpendicular, { mk_circle(0, 0, 1), mk_line(0, 0, 1, 0) }, 0, 1, -1, ConstraintReject::NeedTwoLines },
|
||||
{ "EqualLength", SketchConstraintType::EqualLength, { mk_line(0, 0, 1, 0), mk_circle(5, 0, 1) }, 0, 1, -1, ConstraintReject::NeedTwoLines },
|
||||
{ "Concentric", SketchConstraintType::Concentric, { mk_line(0, 0, 1, 0), mk_circle(5, 0, 1) }, 0, 1, -1, ConstraintReject::NeedTwoRounds },
|
||||
{ "Tangent", SketchConstraintType::Tangent, { mk_line(0, 0, 1, 0), mk_line(0, 1, 1, 1) }, 0, 1, -1, ConstraintReject::NeedTangentPair },
|
||||
{ "Midpoint", SketchConstraintType::Midpoint, { mk_line(0, 0, 1, 0), mk_line(0, 1, 1, 1) }, 0, 1, -1, ConstraintReject::NeedPointAndLine },
|
||||
{ "Symmetric", SketchConstraintType::Symmetric, { mk_line(0, 0, 1, 0), mk_point(1, 1), mk_line(0, -1, 0, 1) }, 0, 1, 2, ConstraintReject::NeedTwoPointsOrLines },
|
||||
{ "SymmetricAboutY", SketchConstraintType::SymmetricAboutY, { mk_line(0, 0, 1, 0), mk_point(1, 1) }, 0, 1, -1, ConstraintReject::NeedTwoPointsOrLines },
|
||||
{ "SymmetricAboutX", SketchConstraintType::SymmetricAboutX, { mk_point(1, 1), mk_line(0, 0, 1, 0) }, 0, 1, -1, ConstraintReject::NeedTwoPointsOrLines },
|
||||
{ "EqualRadius", SketchConstraintType::EqualRadius, { mk_line(0, 0, 1, 0), mk_circle(5, 0, 1) }, 0, 1, -1, ConstraintReject::NeedTwoRounds },
|
||||
{ "Collinear", SketchConstraintType::Collinear, { mk_line(0, 0, 1, 0), mk_circle(5, 0, 1) }, 0, 1, -1, ConstraintReject::NeedTwoLines },
|
||||
{ "Angle", SketchConstraintType::Angle, { mk_circle(0, 0, 1), mk_circle(5, 0, 1) }, 0, 1, -1, ConstraintReject::NeedTwoLines },
|
||||
{ "Radius", SketchConstraintType::Radius, { mk_line(0, 0, 1, 0) }, 0, -1, -1, ConstraintReject::NeedRound },
|
||||
{ "Diameter", SketchConstraintType::Diameter, { mk_point(1, 2) }, 0, -1, -1, ConstraintReject::NeedRound },
|
||||
{ "DistanceX", SketchConstraintType::DistanceX, { mk_point(0, 0) }, 0, -1, -1, ConstraintReject::NeedTwoEntities },
|
||||
{ "DistanceY", SketchConstraintType::DistanceY, { mk_point(0, 0) }, 0, -1, -1, ConstraintReject::NeedTwoEntities },
|
||||
};
|
||||
for (const C& c : cases) {
|
||||
DYNAMIC_SECTION("reject " << c.name) {
|
||||
ConstraintPlan p = plan_entity_constraint(c.ents, c.e0, c.e1, c.e2, c.type);
|
||||
REQUIRE(p.kind == ConstraintPlan::Kind::Reject);
|
||||
REQUIRE(p.reason == c.reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("constraint planner rejects types with no entity binding", "[SketchConstraints]")
|
||||
{
|
||||
const SketchConstraintType unsupported[] = {
|
||||
SketchConstraintType::Distance, SketchConstraintType::LockX, SketchConstraintType::LockY,
|
||||
SketchConstraintType::PointOnLine, SketchConstraintType::PointOnObject,
|
||||
};
|
||||
std::vector<SketchEntity> ents = { mk_point(0, 0), mk_point(1, 1) };
|
||||
for (SketchConstraintType t : unsupported) {
|
||||
DYNAMIC_SECTION("unsupported " << int(t)) {
|
||||
ConstraintPlan p = plan_entity_constraint(ents, 0, 1, -1, t);
|
||||
REQUIRE(p.kind == ConstraintPlan::Kind::Reject);
|
||||
REQUIRE(p.reason == ConstraintReject::Unsupported);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,730 @@
|
||||
#include <catch2/catch_all.hpp> // mainline OrcaSlicer ships Catch2 v3 (v2 was catch2/catch.hpp)
|
||||
#include "libslic3r/CAD/SketchEngine.hpp"
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
#include <TopExp_Explorer.hxx>
|
||||
#include <TopAbs.hxx>
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
using Catch::Matchers::WithinAbs;
|
||||
|
||||
// CONTRACT: mirror_entities hands the reflected half back REVERSED — the order of the entities
|
||||
// and the direction of each — because a reflection reverses orientation and the result has to
|
||||
// CONTINUE the chain it was made from. So a mirrored line's p0 is the reflection of the source's
|
||||
// p1, not its p0. See [SketchProfile] "a mirrored half continues the original chain".
|
||||
TEST_CASE("Mirror Line across Y axis (reversed: p0 is the reflection of the source p1)", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Line;
|
||||
e.p0 = Vec2d(3, 2);
|
||||
e.p1 = Vec2d(5, 4);
|
||||
|
||||
Vec2d a(0, -1);
|
||||
Vec2d b(0, 1);
|
||||
|
||||
auto result = SketchEngine::mirror_entities({e}, a, b);
|
||||
REQUIRE(result.size() == 1);
|
||||
|
||||
const auto& m = result[0];
|
||||
REQUIRE(m.type == SketchEntity::Type::Line);
|
||||
REQUIRE_THAT(m.p0.x(), WithinAbs(-5.0, 1e-9)); // reflection of the SOURCE p1
|
||||
REQUIRE_THAT(m.p0.y(), WithinAbs(4.0, 1e-9));
|
||||
REQUIRE_THAT(m.p1.x(), WithinAbs(-3.0, 1e-9)); // reflection of the SOURCE p0
|
||||
REQUIRE_THAT(m.p1.y(), WithinAbs(2.0, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Mirror Circle across Y axis", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Circle;
|
||||
e.center = Vec2d(5, 0);
|
||||
e.p0 = Vec2d(5, 0);
|
||||
e.radius = 3;
|
||||
|
||||
Vec2d a(0, -1);
|
||||
Vec2d b(0, 1);
|
||||
|
||||
auto result = SketchEngine::mirror_entities({e}, a, b);
|
||||
REQUIRE(result.size() == 1);
|
||||
|
||||
const auto& m = result[0];
|
||||
REQUIRE(m.type == SketchEntity::Type::Circle);
|
||||
REQUIRE_THAT(m.center.x(), WithinAbs(-5.0, 1e-9));
|
||||
REQUIRE_THAT(m.center.y(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(m.radius, WithinAbs(3.0, 1e-9));
|
||||
REQUIRE_THAT(m.p0.x(), WithinAbs(-5.0, 1e-9));
|
||||
REQUIRE_THAT(m.p0.y(), WithinAbs(0.0, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Mirror Arc across X axis", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Arc;
|
||||
e.center = Vec2d(0, 0);
|
||||
e.radius = 1.0;
|
||||
e.start_angle = 0.0;
|
||||
e.end_angle = M_PI / 2.0;
|
||||
e.p0 = Vec2d(1, 0);
|
||||
e.p1 = Vec2d(0, 1);
|
||||
|
||||
Vec2d a(-1, 0);
|
||||
Vec2d b(1, 0);
|
||||
|
||||
auto result = SketchEngine::mirror_entities({e}, a, b);
|
||||
REQUIRE(result.size() == 1);
|
||||
|
||||
const auto& m = result[0];
|
||||
REQUIRE(m.type == SketchEntity::Type::Arc);
|
||||
|
||||
// Reversed with the rest of the half: the mirrored arc STARTS where the reflection of the
|
||||
// source's end is, and finishes at the reflection of its start.
|
||||
REQUIRE_THAT(m.p0.x(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(m.p0.y(), WithinAbs(-1.0, 1e-9));
|
||||
REQUIRE_THAT(m.p1.x(), WithinAbs(1.0, 1e-9));
|
||||
REQUIRE_THAT(m.p1.y(), WithinAbs(0.0, 1e-9));
|
||||
|
||||
// The reflection alone would negate the sweep; walking the arc the other way negates it
|
||||
// again, so a mirrored CCW arc is CCW once more and a mirrored CCW loop stays CCW.
|
||||
double sweep = m.end_angle - m.start_angle;
|
||||
double orig_sweep = e.end_angle - e.start_angle;
|
||||
REQUIRE(orig_sweep > 0.0);
|
||||
REQUIRE(sweep > 0.0);
|
||||
}
|
||||
|
||||
TEST_CASE("Offset Line by positive d", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Line;
|
||||
e.p0 = Vec2d(0, 0);
|
||||
e.p1 = Vec2d(10, 0);
|
||||
|
||||
auto result = SketchEngine::offset_entities({e}, 2.0);
|
||||
REQUIRE(result.size() == 1);
|
||||
|
||||
const auto& o = result[0];
|
||||
REQUIRE(o.type == SketchEntity::Type::Line);
|
||||
REQUIRE_THAT(o.p0.x(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(o.p0.y(), WithinAbs(2.0, 1e-9));
|
||||
REQUIRE_THAT(o.p1.x(), WithinAbs(10.0, 1e-9));
|
||||
REQUIRE_THAT(o.p1.y(), WithinAbs(2.0, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Offset Circle: expand and collapse", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Circle;
|
||||
e.center = Vec2d(0, 0);
|
||||
e.p0 = Vec2d(0, 0);
|
||||
e.radius = 5;
|
||||
|
||||
auto expanded = SketchEngine::offset_entities({e}, 2.0);
|
||||
REQUIRE(expanded.size() == 1);
|
||||
REQUIRE_THAT(expanded[0].radius, WithinAbs(7.0, 1e-9));
|
||||
|
||||
auto collapsed = SketchEngine::offset_entities({e}, -5.0);
|
||||
REQUIRE(collapsed.empty());
|
||||
}
|
||||
|
||||
// CONTRACT CHANGED: +d used to mean "radius + d" for every arc regardless of its sweep, while
|
||||
// for a line it meant "left of the direction of travel". The two disagreed, so a profile made
|
||||
// of lines AND arcs (any slot outline) offset with its straights going one way and its caps the
|
||||
// other, and could never come back closed. The arc now follows the line's rule: +d is left of
|
||||
// travel, which for this CCW quarter-arc is inward -> r = 3. See [SketchProfile].
|
||||
TEST_CASE("Offset Arc by positive d (left of travel: a CCW arc shrinks)", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Arc;
|
||||
e.center = Vec2d(0, 0);
|
||||
e.radius = 4.0;
|
||||
e.start_angle = 0.0;
|
||||
e.end_angle = M_PI / 2.0;
|
||||
e.p0 = Vec2d(4, 0);
|
||||
e.p1 = Vec2d(0, 4);
|
||||
|
||||
auto result = SketchEngine::offset_entities({e}, 1.0);
|
||||
REQUIRE(result.size() == 1);
|
||||
|
||||
const auto& o = result[0];
|
||||
REQUIRE(o.type == SketchEntity::Type::Arc);
|
||||
REQUIRE_THAT(o.radius, WithinAbs(3.0, 1e-9));
|
||||
REQUIRE_THAT(o.p0.x(), WithinAbs(3.0, 1e-9));
|
||||
REQUIRE_THAT(o.p0.y(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(o.p1.x(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(o.p1.y(), WithinAbs(3.0, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Fillet right-angle corner", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity a;
|
||||
a.type = SketchEntity::Type::Line;
|
||||
a.p0 = Vec2d(0, 0);
|
||||
a.p1 = Vec2d(10, 0);
|
||||
|
||||
SketchEntity b;
|
||||
b.type = SketchEntity::Type::Line;
|
||||
b.p0 = Vec2d(10, 0);
|
||||
b.p1 = Vec2d(10, 10);
|
||||
|
||||
SketchEntity a_out, b_out, arc_out;
|
||||
bool ok = SketchEngine::fillet_lines(a, b, 2.0, a_out, b_out, arc_out);
|
||||
REQUIRE(ok);
|
||||
|
||||
REQUIRE_THAT(a_out.p0.x(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(a_out.p0.y(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(a_out.p1.x(), WithinAbs(8.0, 1e-9));
|
||||
REQUIRE_THAT(a_out.p1.y(), WithinAbs(0.0, 1e-9));
|
||||
|
||||
REQUIRE_THAT(b_out.p0.x(), WithinAbs(10.0, 1e-9));
|
||||
REQUIRE_THAT(b_out.p0.y(), WithinAbs(2.0, 1e-9));
|
||||
REQUIRE_THAT(b_out.p1.x(), WithinAbs(10.0, 1e-9));
|
||||
REQUIRE_THAT(b_out.p1.y(), WithinAbs(10.0, 1e-9));
|
||||
|
||||
REQUIRE(arc_out.type == SketchEntity::Type::Arc);
|
||||
REQUIRE_THAT(arc_out.radius, WithinAbs(2.0, 1e-9));
|
||||
REQUIRE_THAT(arc_out.center.x(), WithinAbs(8.0, 1e-9));
|
||||
REQUIRE_THAT(arc_out.center.y(), WithinAbs(2.0, 1e-9));
|
||||
REQUIRE_THAT((arc_out.p0 - arc_out.center).norm(), WithinAbs(2.0, 1e-9));
|
||||
REQUIRE_THAT((arc_out.p1 - arc_out.center).norm(), WithinAbs(2.0, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Fillet parallel lines returns false", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity a;
|
||||
a.type = SketchEntity::Type::Line;
|
||||
a.p0 = Vec2d(0, 0);
|
||||
a.p1 = Vec2d(10, 0);
|
||||
|
||||
SketchEntity b;
|
||||
b.type = SketchEntity::Type::Line;
|
||||
b.p0 = Vec2d(0, 5);
|
||||
b.p1 = Vec2d(10, 5);
|
||||
|
||||
SketchEntity a_out, b_out, arc_out;
|
||||
REQUIRE_FALSE(SketchEngine::fillet_lines(a, b, 1.0, a_out, b_out, arc_out));
|
||||
}
|
||||
|
||||
TEST_CASE("Fillet arc too big returns false", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity a;
|
||||
a.type = SketchEntity::Type::Line;
|
||||
a.p0 = Vec2d(0, 0);
|
||||
a.p1 = Vec2d(1, 0);
|
||||
|
||||
SketchEntity b;
|
||||
b.type = SketchEntity::Type::Line;
|
||||
b.p0 = Vec2d(1, 0);
|
||||
b.p1 = Vec2d(1, 1);
|
||||
|
||||
SketchEntity a_out, b_out, arc_out;
|
||||
REQUIRE_FALSE(SketchEngine::fillet_lines(a, b, 5.0, a_out, b_out, arc_out));
|
||||
}
|
||||
|
||||
TEST_CASE("Trim right arm", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Line;
|
||||
e.p0 = Vec2d(-5, 0);
|
||||
e.p1 = Vec2d(5, 0);
|
||||
|
||||
SketchEntity vc;
|
||||
vc.type = SketchEntity::Type::Line;
|
||||
vc.p0 = Vec2d(0, -5);
|
||||
vc.p1 = Vec2d(0, 5);
|
||||
|
||||
bool ok = SketchEngine::trim_entity(e, {vc}, Vec2d(3, 0));
|
||||
REQUIRE(ok);
|
||||
REQUIRE_THAT(e.p0.x(), WithinAbs(-5.0, 1e-9));
|
||||
REQUIRE_THAT(e.p0.y(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(e.p1.x(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(e.p1.y(), WithinAbs(0.0, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Trim left arm", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Line;
|
||||
e.p0 = Vec2d(-5, 0);
|
||||
e.p1 = Vec2d(5, 0);
|
||||
|
||||
SketchEntity vc;
|
||||
vc.type = SketchEntity::Type::Line;
|
||||
vc.p0 = Vec2d(0, -5);
|
||||
vc.p1 = Vec2d(0, 5);
|
||||
|
||||
bool ok = SketchEngine::trim_entity(e, {vc}, Vec2d(-3, 0));
|
||||
REQUIRE(ok);
|
||||
REQUIRE_THAT(e.p0.x(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(e.p0.y(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(e.p1.x(), WithinAbs(5.0, 1e-9));
|
||||
REQUIRE_THAT(e.p1.y(), WithinAbs(0.0, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Trim no cut (u out of range)", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Line;
|
||||
e.p0 = Vec2d(-5, 0);
|
||||
e.p1 = Vec2d(5, 0);
|
||||
|
||||
SketchEntity other;
|
||||
other.type = SketchEntity::Type::Line;
|
||||
other.p0 = Vec2d(0, 3);
|
||||
other.p1 = Vec2d(0, 8);
|
||||
|
||||
REQUIRE_FALSE(SketchEngine::trim_entity(e, {other}, Vec2d(3, 0)));
|
||||
}
|
||||
|
||||
TEST_CASE("Extend forward to line", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Line;
|
||||
e.p0 = Vec2d(0, 0);
|
||||
e.p1 = Vec2d(2, 0);
|
||||
|
||||
SketchEntity other;
|
||||
other.type = SketchEntity::Type::Line;
|
||||
other.p0 = Vec2d(5, -5);
|
||||
other.p1 = Vec2d(5, 5);
|
||||
|
||||
bool ok = SketchEngine::extend_entity(e, {other}, Vec2d(2, 0));
|
||||
REQUIRE(ok);
|
||||
REQUIRE_THAT(e.p0.x(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(e.p0.y(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(e.p1.x(), WithinAbs(5.0, 1e-9));
|
||||
REQUIRE_THAT(e.p1.y(), WithinAbs(0.0, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Extend forward to circle", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Line;
|
||||
e.p0 = Vec2d(0, 0);
|
||||
e.p1 = Vec2d(2, 0);
|
||||
|
||||
SketchEntity other;
|
||||
other.type = SketchEntity::Type::Circle;
|
||||
other.center = Vec2d(10, 0);
|
||||
other.p0 = Vec2d(10, 0);
|
||||
other.radius = 3;
|
||||
|
||||
bool ok = SketchEngine::extend_entity(e, {other}, Vec2d(2, 0));
|
||||
REQUIRE(ok);
|
||||
REQUIRE_THAT(e.p0.x(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(e.p0.y(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(e.p1.x(), WithinAbs(7.0, 1e-9));
|
||||
REQUIRE_THAT(e.p1.y(), WithinAbs(0.0, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Extend backward", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Line;
|
||||
e.p0 = Vec2d(0, 0);
|
||||
e.p1 = Vec2d(2, 0);
|
||||
|
||||
SketchEntity other;
|
||||
other.type = SketchEntity::Type::Line;
|
||||
other.p0 = Vec2d(-3, -5);
|
||||
other.p1 = Vec2d(-3, 5);
|
||||
|
||||
bool ok = SketchEngine::extend_entity(e, {other}, Vec2d(0, 0));
|
||||
REQUIRE(ok);
|
||||
REQUIRE_THAT(e.p0.x(), WithinAbs(-3.0, 1e-9));
|
||||
REQUIRE_THAT(e.p0.y(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(e.p1.x(), WithinAbs(2.0, 1e-9));
|
||||
REQUIRE_THAT(e.p1.y(), WithinAbs(0.0, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Extend no target", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Line;
|
||||
e.p0 = Vec2d(0, 0);
|
||||
e.p1 = Vec2d(2, 0);
|
||||
|
||||
SketchEntity other;
|
||||
other.type = SketchEntity::Type::Line;
|
||||
other.p0 = Vec2d(5, -5);
|
||||
other.p1 = Vec2d(5, -1);
|
||||
|
||||
REQUIRE_FALSE(SketchEngine::extend_entity(e, {other}, Vec2d(2, 0)));
|
||||
}
|
||||
|
||||
// --- Arc/Circle subject trim & extend (Fase 4.5 kernel) -------------------
|
||||
|
||||
TEST_CASE("Trim arc drops the picked (start) side", "[SketchEdit]")
|
||||
{
|
||||
// Upper semicircle r=5, ccw from (5,0) to (-5,0); cutter = vertical axis.
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Arc;
|
||||
e.center = Vec2d(0, 0);
|
||||
e.radius = 5;
|
||||
e.start_angle = 0.0;
|
||||
e.end_angle = M_PI;
|
||||
|
||||
SketchEntity cut;
|
||||
cut.type = SketchEntity::Type::Line;
|
||||
cut.p0 = Vec2d(0, -10);
|
||||
cut.p1 = Vec2d(0, 10);
|
||||
|
||||
// Pick the right quarter (phi=pi/4) -> it is removed, left quarter kept.
|
||||
bool ok = SketchEngine::trim_entity(e, {cut}, Vec2d(5 * std::cos(M_PI/4), 5 * std::sin(M_PI/4)));
|
||||
REQUIRE(ok);
|
||||
REQUIRE(e.type == SketchEntity::Type::Arc);
|
||||
REQUIRE_THAT(e.radius, WithinAbs(5.0, 1e-9));
|
||||
REQUIRE_THAT(e.start_angle, WithinAbs(M_PI / 2.0, 1e-9));
|
||||
REQUIRE_THAT(e.end_angle, WithinAbs(M_PI, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Trim arc drops the picked (end) side", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Arc;
|
||||
e.center = Vec2d(0, 0);
|
||||
e.radius = 5;
|
||||
e.start_angle = 0.0;
|
||||
e.end_angle = M_PI;
|
||||
|
||||
SketchEntity cut;
|
||||
cut.type = SketchEntity::Type::Line;
|
||||
cut.p0 = Vec2d(0, -10);
|
||||
cut.p1 = Vec2d(0, 10);
|
||||
|
||||
// Pick the left quarter (phi=3pi/4) -> removed, right quarter kept.
|
||||
bool ok = SketchEngine::trim_entity(e, {cut}, Vec2d(5 * std::cos(3*M_PI/4), 5 * std::sin(3*M_PI/4)));
|
||||
REQUIRE(ok);
|
||||
REQUIRE(e.type == SketchEntity::Type::Arc);
|
||||
REQUIRE_THAT(e.start_angle, WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(e.end_angle, WithinAbs(M_PI / 2.0, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Trim circle opens into an arc excluding the pick", "[SketchEdit]")
|
||||
{
|
||||
// Full circle r=5; vertical axis cuts it at (0,+-5). Pick the right side
|
||||
// (5,0): the kept arc is the left half, sweeping pi and centred on (-5,0).
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Circle;
|
||||
e.center = Vec2d(0, 0);
|
||||
e.p0 = Vec2d(5, 0);
|
||||
e.radius = 5;
|
||||
|
||||
SketchEntity cut;
|
||||
cut.type = SketchEntity::Type::Line;
|
||||
cut.p0 = Vec2d(0, -10);
|
||||
cut.p1 = Vec2d(0, 10);
|
||||
|
||||
bool ok = SketchEngine::trim_entity(e, {cut}, Vec2d(5, 0));
|
||||
REQUIRE(ok);
|
||||
REQUIRE(e.type == SketchEntity::Type::Arc);
|
||||
REQUIRE_THAT(e.radius, WithinAbs(5.0, 1e-9));
|
||||
REQUIRE_THAT(e.end_angle - e.start_angle, WithinAbs(M_PI, 1e-9));
|
||||
// Midpoint of the kept arc must point left (away from the pick).
|
||||
double mid = 0.5 * (e.start_angle + e.end_angle);
|
||||
REQUIRE_THAT(5 * std::cos(mid), WithinAbs(-5.0, 1e-9));
|
||||
REQUIRE_THAT(5 * std::sin(mid), WithinAbs(0.0, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Extend arc forward (end) to a crossing", "[SketchEdit]")
|
||||
{
|
||||
// Quarter arc (5,0)->(0,5); cutter crosses the circle at (-5,0). Picking
|
||||
// near the end grows the sweep ccw to pi.
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Arc;
|
||||
e.center = Vec2d(0, 0);
|
||||
e.radius = 5;
|
||||
e.start_angle = 0.0;
|
||||
e.end_angle = M_PI / 2.0;
|
||||
|
||||
SketchEntity cut;
|
||||
cut.type = SketchEntity::Type::Line;
|
||||
cut.p0 = Vec2d(-10, 0);
|
||||
cut.p1 = Vec2d(0, 0);
|
||||
|
||||
bool ok = SketchEngine::extend_entity(e, {cut}, Vec2d(0, 5));
|
||||
REQUIRE(ok);
|
||||
REQUIRE(e.type == SketchEntity::Type::Arc);
|
||||
REQUIRE_THAT(e.start_angle, WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(e.end_angle, WithinAbs(M_PI, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Extend arc backward (start) to a crossing", "[SketchEdit]")
|
||||
{
|
||||
// Quarter arc (0,5)->(-5,0); cutter crosses at (5,0). Picking near the
|
||||
// start grows the sweep cw to start_angle 0.
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Arc;
|
||||
e.center = Vec2d(0, 0);
|
||||
e.radius = 5;
|
||||
e.start_angle = M_PI / 2.0;
|
||||
e.end_angle = M_PI;
|
||||
|
||||
SketchEntity cut;
|
||||
cut.type = SketchEntity::Type::Line;
|
||||
cut.p0 = Vec2d(10, 0);
|
||||
cut.p1 = Vec2d(0, 0);
|
||||
|
||||
bool ok = SketchEngine::extend_entity(e, {cut}, Vec2d(0, 5));
|
||||
REQUIRE(ok);
|
||||
REQUIRE_THAT(e.start_angle, WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(e.end_angle, WithinAbs(M_PI, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Extend circle returns false (closed)", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Circle;
|
||||
e.center = Vec2d(0, 0);
|
||||
e.p0 = Vec2d(5, 0);
|
||||
e.radius = 5;
|
||||
|
||||
SketchEntity cut;
|
||||
cut.type = SketchEntity::Type::Line;
|
||||
cut.p0 = Vec2d(0, -10);
|
||||
cut.p1 = Vec2d(0, 10);
|
||||
|
||||
REQUIRE_FALSE(SketchEngine::extend_entity(e, {cut}, Vec2d(5, 0)));
|
||||
}
|
||||
|
||||
TEST_CASE("Trim arc with no crossing returns false", "[SketchEdit]")
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Arc;
|
||||
e.center = Vec2d(0, 0);
|
||||
e.radius = 5;
|
||||
e.start_angle = 0.0;
|
||||
e.end_angle = M_PI / 2.0;
|
||||
|
||||
SketchEntity cut; // far away, never reaches the r=5 circle
|
||||
cut.type = SketchEntity::Type::Line;
|
||||
cut.p0 = Vec2d(20, -5);
|
||||
cut.p1 = Vec2d(20, 5);
|
||||
|
||||
REQUIRE_FALSE(SketchEngine::trim_entity(e, {cut}, Vec2d(5 * std::cos(M_PI/4), 5 * std::sin(M_PI/4))));
|
||||
}
|
||||
|
||||
// Regression guard: BEFORE the weld fix this test failed with 4 edges instead of 6.
|
||||
// BRepLib_MakeWire::Add silently DROPS a disconnected edge (BRepLib_DisconnectedWire + NotDone)
|
||||
// yet every successful Add ends with BRepLib_WireDone + Done(), so IsDone() reported only whether
|
||||
// the LAST edge connected. This sketch is a real user loop (2 arcs + 4 lines) given in
|
||||
// creation order, which is NOT traversal order, and its joint between the 3rd and 4th entity
|
||||
// below is open by 2.28e-5 mm — larger than OCCT's default vertex tolerance.
|
||||
TEST_CASE("entities_to_wires keeps every edge of a loop drawn out of order", "[SketchEngine]")
|
||||
{
|
||||
std::vector<SketchEntity> ents(6);
|
||||
|
||||
ents[0].type = SketchEntity::Type::Line;
|
||||
ents[0].p0 = Vec2d(-0.537697713190522, -0.0009077462579133498);
|
||||
ents[0].p1 = Vec2d(99.46230228680926, -0.0009141694814321626);
|
||||
|
||||
ents[1].type = SketchEntity::Type::Arc;
|
||||
ents[1].p0 = Vec2d(-0.537697713190522, -0.0009077462579133498);
|
||||
ents[1].p1 = Vec2d(-100.14602636660666, -0.27673132181233495);
|
||||
ents[1].center = Vec2d(-50.313868583115394, -10.248112903179617);
|
||||
ents[1].radius = 50.81999999999999;
|
||||
ents[1].start_angle = 0.20302922018398933;
|
||||
ents[1].end_angle = 2.944101582158999;
|
||||
|
||||
ents[2].type = SketchEntity::Type::Line;
|
||||
ents[2].p0 = Vec2d(99.46228668626469, -39.22091416947833);
|
||||
ents[2].p1 = Vec2d(-0.537864366432629, -39.22420589376945);
|
||||
|
||||
ents[3].type = SketchEntity::Type::Arc;
|
||||
ents[3].p0 = Vec2d(-100.14602636694521, -38.94673132181234);
|
||||
ents[3].p1 = Vec2d(-0.5378420354900413, -39.22421049164698);
|
||||
ents[3].center = Vec2d(-50.31377078666179, -28.975499083790503);
|
||||
ents[3].radius = 50.82006659345552;
|
||||
ents[3].start_angle = -2.944104841286737;
|
||||
ents[3].end_angle = -0.20305921095748136;
|
||||
|
||||
ents[4].type = SketchEntity::Type::Line;
|
||||
ents[4].p0 = Vec2d(99.46228668626469, -39.22091416947833);
|
||||
ents[4].p1 = Vec2d(99.46230228680926, -0.0009141694814321626);
|
||||
|
||||
ents[5].type = SketchEntity::Type::Line;
|
||||
ents[5].p0 = Vec2d(-100.14602636694521, -38.94673132181234);
|
||||
ents[5].p1 = Vec2d(-100.14602636660666, -0.27673132181233495);
|
||||
|
||||
auto wires = SketchEngine::entities_to_wires(ents, SketchPlane::XY());
|
||||
|
||||
REQUIRE(wires.size() == 1);
|
||||
|
||||
int edge_count = 0;
|
||||
for (TopExp_Explorer ex(wires[0], TopAbs_EDGE); ex.More(); ex.Next())
|
||||
++edge_count;
|
||||
REQUIRE(edge_count == 6);
|
||||
|
||||
REQUIRE(wires[0].Closed());
|
||||
}
|
||||
|
||||
// Regression guard: this fails at 1e-4 (the wire builder refuses a joint the viewport had
|
||||
// already shaded closed) and passes at kSketchJoinTol. A 20x10 quad with one joint left open
|
||||
// by 9e-4 mm — just inside kSketchJoinTol, exactly the case the viewport shades closed — given
|
||||
// in an order that is NOT traversal order, so the ordering path is covered too.
|
||||
TEST_CASE("a loop the viewport shades closed is buildable by the kernel", "[SketchEngine]")
|
||||
{
|
||||
std::vector<SketchEntity> ents(4);
|
||||
|
||||
// (0,0) -> (20,0) -> (20,10) -> (0,10) -> (0.0009, 0): last endpoint misses (0,0) by 9e-4.
|
||||
ents[0].type = SketchEntity::Type::Line;
|
||||
ents[0].p0 = Vec2d(0, 0);
|
||||
ents[0].p1 = Vec2d(20, 0);
|
||||
|
||||
// Index 1 is the FAR side, not the neighbour of index 0: creation order here is
|
||||
// deliberately not traversal order, so a partial wire would reject it without the
|
||||
// traversal walk.
|
||||
ents[1].type = SketchEntity::Type::Line;
|
||||
ents[1].p0 = Vec2d(20, 10);
|
||||
ents[1].p1 = Vec2d(0, 10);
|
||||
|
||||
ents[2].type = SketchEntity::Type::Line;
|
||||
ents[2].p0 = Vec2d(20, 0);
|
||||
ents[2].p1 = Vec2d(20, 10);
|
||||
|
||||
ents[3].type = SketchEntity::Type::Line;
|
||||
ents[3].p0 = Vec2d(0, 10);
|
||||
ents[3].p1 = Vec2d(0.0009, 0);
|
||||
|
||||
auto wires = SketchEngine::entities_to_wires(ents, SketchPlane::XY());
|
||||
|
||||
REQUIRE(wires.size() == 1);
|
||||
|
||||
int edge_count = 0;
|
||||
for (TopExp_Explorer ex(wires[0], TopAbs_EDGE); ex.More(); ex.Next())
|
||||
++edge_count;
|
||||
REQUIRE(edge_count == 4);
|
||||
|
||||
REQUIRE(wires[0].Closed());
|
||||
}
|
||||
|
||||
// Regression guard for the auto-close preference. Same 20x10 quad, one joint open by 9e-4 mm
|
||||
// and given out of traversal order, as "a loop the viewport shades closed is buildable by the
|
||||
// kernel". With auto-close ON the gap welds (one closed wire); with auto-close OFF it must not.
|
||||
TEST_CASE("auto-close off makes the kernel demand an exact joint", "[SketchEngine]")
|
||||
{
|
||||
std::vector<SketchEntity> ents(4);
|
||||
|
||||
ents[0].type = SketchEntity::Type::Line;
|
||||
ents[0].p0 = Vec2d(0, 0);
|
||||
ents[0].p1 = Vec2d(20, 0);
|
||||
|
||||
ents[1].type = SketchEntity::Type::Line;
|
||||
ents[1].p0 = Vec2d(20, 10);
|
||||
ents[1].p1 = Vec2d(0, 10);
|
||||
|
||||
ents[2].type = SketchEntity::Type::Line;
|
||||
ents[2].p0 = Vec2d(20, 0);
|
||||
ents[2].p1 = Vec2d(20, 10);
|
||||
|
||||
ents[3].type = SketchEntity::Type::Line;
|
||||
ents[3].p0 = Vec2d(0, 10);
|
||||
ents[3].p1 = Vec2d(0.0009, 0);
|
||||
|
||||
auto edge_count = [](const TopoDS_Wire& w) {
|
||||
int n = 0;
|
||||
for (TopExp_Explorer ex(w, TopAbs_EDGE); ex.More(); ex.Next()) ++n;
|
||||
return n;
|
||||
};
|
||||
|
||||
// ON: the 9e-4 mm gap is inside kSketchJoinTol, so the loop welds into one closed wire.
|
||||
Slic3r::set_sketch_auto_close(true);
|
||||
auto wires_on = SketchEngine::entities_to_wires(ents, SketchPlane::XY());
|
||||
REQUIRE(wires_on.size() == 1);
|
||||
REQUIRE(edge_count(wires_on[0]) == 4);
|
||||
REQUIRE(wires_on[0].Closed());
|
||||
|
||||
// OFF: the joint is not exact, so the gap is NOT welded. entities_to_wires legitimately
|
||||
// returns open chains (a sweep path is open), so the observable is an OPEN wire — the
|
||||
// kernel no longer hands back the closed loop the viewport would have shaded.
|
||||
Slic3r::set_sketch_auto_close(false);
|
||||
auto wires_off = SketchEngine::entities_to_wires(ents, SketchPlane::XY());
|
||||
REQUIRE(wires_off.size() == 1);
|
||||
REQUIRE(edge_count(wires_off[0]) == 4);
|
||||
REQUIRE_FALSE(wires_off[0].Closed());
|
||||
|
||||
// OFF + an EXACT joint (last endpoint exactly (0,0)): the quad still builds closed,
|
||||
// proving "off" means exact rather than broken.
|
||||
ents[3].p1 = Vec2d(0, 0);
|
||||
auto wires_exact = SketchEngine::entities_to_wires(ents, SketchPlane::XY());
|
||||
REQUIRE(wires_exact.size() == 1);
|
||||
REQUIRE(edge_count(wires_exact[0]) == 4);
|
||||
REQUIRE(wires_exact[0].Closed());
|
||||
|
||||
// Restore the default so test order cannot leak OFF into the other cases.
|
||||
Slic3r::set_sketch_auto_close(true);
|
||||
}
|
||||
|
||||
// A stray open segment touching nothing must not break a closed profile: the viewport
|
||||
// discards open chains when it shades a region extrudable, so with closed_only the kernel
|
||||
// must discard them too — otherwise Revolve/Extrude fail on a sketch that looks perfect.
|
||||
TEST_CASE("a stray open segment does not break a closed profile", "[SketchEngine]")
|
||||
{
|
||||
auto line = [](double x0, double y0, double x1, double y1) {
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Line;
|
||||
e.p0 = Vec2d(x0, y0);
|
||||
e.p1 = Vec2d(x1, y1);
|
||||
return e;
|
||||
};
|
||||
|
||||
std::vector<SketchEntity> ents;
|
||||
ents.push_back(line(0, 0, 20, 0)); // 20x10 quad
|
||||
ents.push_back(line(20, 0, 20, 10));
|
||||
ents.push_back(line(20, 10, 0, 10));
|
||||
ents.push_back(line(0, 10, 0, 0));
|
||||
ents.push_back(line(5, 5, 6, 5.2)); // stray, touches nothing
|
||||
|
||||
auto edge_count = [](const TopoDS_Wire& w) {
|
||||
int n = 0;
|
||||
for (TopExp_Explorer ex(w, TopAbs_EDGE); ex.More(); ex.Next()) ++n;
|
||||
return n;
|
||||
};
|
||||
|
||||
// Unchanged behaviour: the stray line is its own open wire.
|
||||
auto wires_all = SketchEngine::entities_to_wires(ents, SketchPlane::XY(), /*closed_only=*/false);
|
||||
REQUIRE(wires_all.size() == 2);
|
||||
|
||||
// closed_only drops the open chain: one closed quad survives.
|
||||
auto wires_closed = SketchEngine::entities_to_wires(ents, SketchPlane::XY(), /*closed_only=*/true);
|
||||
REQUIRE(wires_closed.size() == 1);
|
||||
REQUIRE(edge_count(wires_closed[0]) == 4);
|
||||
REQUIRE(wires_closed[0].Closed());
|
||||
|
||||
// The Revolve path (entities_to_wire) finds the single closed loop.
|
||||
TopoDS_Wire w = SketchEngine::entities_to_wire(ents, SketchPlane::XY(), /*closed_only=*/true);
|
||||
REQUIRE_FALSE(w.IsNull());
|
||||
REQUIRE(edge_count(w) == 4);
|
||||
}
|
||||
|
||||
// sketch_open_ends names the two free endpoints of an open chain, so the "does not form a
|
||||
// single closed wire" failure can say WHERE the sketch is open.
|
||||
TEST_CASE("sketch_open_ends names where a chain fails to close", "[SketchEngine]")
|
||||
{
|
||||
auto line = [](double x0, double y0, double x1, double y1) {
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Line;
|
||||
e.p0 = Vec2d(x0, y0);
|
||||
e.p1 = Vec2d(x1, y1);
|
||||
return e;
|
||||
};
|
||||
|
||||
// Open C shape: three lines, free endpoints at (0,0) and (0,10).
|
||||
std::vector<SketchEntity> ents;
|
||||
ents.push_back(line(0, 0, 10, 0));
|
||||
ents.push_back(line(10, 0, 10, 10));
|
||||
ents.push_back(line(10, 10, 0, 10));
|
||||
|
||||
auto got = sketch_open_ends(ents, SketchPlane::XY());
|
||||
REQUIRE(got.size() == 2);
|
||||
|
||||
std::sort(got.begin(), got.end(), [](const Vec2d& a, const Vec2d& b) {
|
||||
if (a.x() < b.x()) return true;
|
||||
if (a.x() > b.x()) return false;
|
||||
return a.y() < b.y();
|
||||
});
|
||||
|
||||
REQUIRE_THAT(got[0].x(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(got[0].y(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(got[1].x(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT(got[1].y(), WithinAbs(10.0, 1e-9));
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
#include <catch2/catch_all.hpp> // mainline OrcaSlicer ships Catch2 v3 (v2 was catch2/catch.hpp)
|
||||
|
||||
#include "libslic3r/CAD/SketchImport.hpp"
|
||||
#include "libslic3r/Utils.hpp" // resources_dir
|
||||
#include "test_utils.hpp" // ScopedTemporaryFile
|
||||
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
// A 10x10 mm filled square, on disk because nanosvg reads from a file. The path
|
||||
// must come from the system temp dir: a hardcoded /tmp is not writable on
|
||||
// Windows, where the stream fails silently and the parse then sees no file.
|
||||
static void write_square_svg(const std::string& path)
|
||||
{
|
||||
std::ofstream f(path);
|
||||
f << "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"10mm\" height=\"10mm\" "
|
||||
"viewBox=\"0 0 10 10\">"
|
||||
"<path d=\"M0,0 L10,0 L10,10 L0,10 Z\" fill=\"#000000\"/></svg>";
|
||||
REQUIRE(f.good());
|
||||
}
|
||||
|
||||
TEST_CASE("svg_to_regions parses a filled path into a region", "[SketchImport]")
|
||||
{
|
||||
ScopedTemporaryFile square(".svg");
|
||||
write_square_svg(square.string());
|
||||
|
||||
ImportRegions regs = svg_to_regions(square.string(), 1.0);
|
||||
REQUIRE(regs.size() >= 1);
|
||||
// Outer contour present with at least a few vertices.
|
||||
REQUIRE(regs[0].size() >= 1);
|
||||
REQUIRE(regs[0][0].size() >= 4);
|
||||
|
||||
// Centred on the origin: bbox half-extent ~5 mm on each side.
|
||||
double hi = 0.0;
|
||||
for (const auto& region : regs)
|
||||
for (const auto& contour : region)
|
||||
for (const Vec2d& p : contour)
|
||||
hi = std::max(hi, std::max(std::abs(p.x()), std::abs(p.y())));
|
||||
REQUIRE(hi > 3.0); // not collapsed
|
||||
REQUIRE(hi < 8.0); // ~5 mm half-size after centring
|
||||
}
|
||||
|
||||
TEST_CASE("svg_to_regions rejects bad input gracefully", "[SketchImport]")
|
||||
{
|
||||
ScopedTemporaryFile square(".svg");
|
||||
write_square_svg(square.string());
|
||||
ScopedTemporaryFile missing(".svg"); // name reserved, never written
|
||||
|
||||
REQUIRE(svg_to_regions("", 1.0).empty());
|
||||
REQUIRE(svg_to_regions(missing.string(), 1.0).empty());
|
||||
REQUIRE(svg_to_regions(square.string(), 0.0).empty()); // scale<=0
|
||||
}
|
||||
|
||||
TEST_CASE("transform_regions moves and scales independently", "[SketchImport]")
|
||||
{
|
||||
ImportRegions r = {{ {Vec2d(-1,-1), Vec2d(1,-1), Vec2d(1,1), Vec2d(-1,1)} }};
|
||||
ImportRegions t = transform_regions(r, Vec2d(10, 20), 2.0, 3.0);
|
||||
REQUIRE(t.size() == 1);
|
||||
REQUIRE(t[0][0].size() == 4);
|
||||
// (-1,-1) -> (-1*2+10, -1*3+20) = (8, 17)
|
||||
REQUIRE_THAT(t[0][0][0].x(), Catch::Matchers::WithinAbs(8.0, 1e-9));
|
||||
REQUIRE_THAT(t[0][0][0].y(), Catch::Matchers::WithinAbs(17.0, 1e-9));
|
||||
// (1,1) -> (1*2+10, 1*3+20) = (12, 23)
|
||||
REQUIRE_THAT(t[0][0][2].x(), Catch::Matchers::WithinAbs(12.0, 1e-9));
|
||||
REQUIRE_THAT(t[0][0][2].y(), Catch::Matchers::WithinAbs(23.0, 1e-9));
|
||||
// identity is a no-op
|
||||
ImportRegions id = transform_regions(r, Vec2d(0,0), 1.0, 1.0);
|
||||
REQUIRE_THAT(id[0][0][1].x(), Catch::Matchers::WithinAbs(1.0, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("text_to_regions vectorizes glyphs with counters", "[SketchImport]")
|
||||
{
|
||||
// Locate the bundled font; resources_dir() may be unset under ctest, so
|
||||
// fall back to a cwd-relative path (tests run from the repo root).
|
||||
std::string font = resources_dir().empty()
|
||||
? std::string("resources/fonts/HarmonyOS_Sans_SC_Regular.ttf")
|
||||
: resources_dir() + "/fonts/HarmonyOS_Sans_SC_Regular.ttf";
|
||||
{
|
||||
std::ifstream probe(font);
|
||||
if (!probe.good()) {
|
||||
SUCCEED("bundled font not reachable in this environment; covered live on :10");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Bad input is rejected without throwing.
|
||||
REQUIRE(text_to_regions("", 10.0, font).empty());
|
||||
REQUIRE(text_to_regions("A", 0.0, font).empty());
|
||||
|
||||
// 'A' has one triangular counter -> a region with an outer + 1 hole.
|
||||
ImportRegions a = text_to_regions("A", 12.0, font);
|
||||
REQUIRE(a.size() >= 1);
|
||||
bool has_hole = false;
|
||||
for (const auto& region : a)
|
||||
if (region.size() >= 2) has_hole = true;
|
||||
REQUIRE(has_hole);
|
||||
|
||||
// Two letters produce more regions than one.
|
||||
ImportRegions ab = text_to_regions("AB", 12.0, font);
|
||||
REQUIRE(ab.size() >= a.size());
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
#include <catch2/catch_all.hpp> // mainline OrcaSlicer ships Catch2 v3 (v2 was catch2/catch.hpp)
|
||||
using Catch::Approx; // v3 scopes Approx into the Catch namespace; v2 had it at global scope
|
||||
|
||||
#include "libslic3r/CAD/SketchInference.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
using K = InferenceSnap::Kind;
|
||||
|
||||
static SketchEntity line(Vec2d a, Vec2d b)
|
||||
{
|
||||
SketchEntity e; e.type = SketchEntity::Type::Line; e.p0 = a; e.p1 = b; return e;
|
||||
}
|
||||
static SketchEntity circle(Vec2d c, double r)
|
||||
{
|
||||
SketchEntity e; e.type = SketchEntity::Type::Circle; e.center = c; e.p0 = c; e.radius = r; return e;
|
||||
}
|
||||
|
||||
TEST_CASE("inference: cursor near a line endpoint snaps Coincident-able to it", "[inference]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}) };
|
||||
auto s = infer_point_snap(ents, {10.3, 0.2}, 1.0);
|
||||
REQUIRE(s.kind == K::Endpoint);
|
||||
CHECK(s.entity == 0);
|
||||
CHECK(s.role == SketchPointRole::P1);
|
||||
CHECK((s.point - Vec2d(10, 0)).norm() == Approx(0.0).margin(1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("inference: endpoint beats midpoint when both are in range", "[inference]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {2, 0}) };
|
||||
// Query equidistant-ish but closer to the endpoint: endpoint tier wins regardless.
|
||||
auto s = infer_point_snap(ents, {1.9, 0.0}, 5.0);
|
||||
CHECK(s.kind == K::Endpoint);
|
||||
CHECK(s.role == SketchPointRole::P1);
|
||||
}
|
||||
|
||||
TEST_CASE("inference: midpoint of a line is detected", "[inference]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}) };
|
||||
auto s = infer_point_snap(ents, {5.1, 0.1}, 0.5, /*include_origin=*/false);
|
||||
REQUIRE(s.kind == K::Midpoint);
|
||||
CHECK((s.point - Vec2d(5, 0)).norm() == Approx(0.0).margin(1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("inference: circle centre and rim", "[inference]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { circle({0, 0}, 5.0) };
|
||||
auto c = infer_point_snap(ents, {0.2, 0.1}, 1.0, false);
|
||||
CHECK(c.kind == K::Center);
|
||||
auto r = infer_point_snap(ents, {5.1, 0.0}, 1.0, false);
|
||||
REQUIRE(r.kind == K::OnEdge);
|
||||
CHECK((r.point - Vec2d(5, 0)).norm() == Approx(0.0).margin(1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("inference: origin snap when nothing else is near", "[inference]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({20, 20}, {30, 20}) };
|
||||
auto s = infer_point_snap(ents, {0.1, 0.1}, 1.0);
|
||||
REQUIRE(s.kind == K::Origin);
|
||||
CHECK(s.entity == -1);
|
||||
CHECK((s.point - Vec2d(0, 0)).norm() == Approx(0.0).margin(1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("inference: nothing in range returns None and the raw query", "[inference]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}) };
|
||||
auto s = infer_point_snap(ents, {50, 50}, 1.0, /*include_origin=*/false);
|
||||
CHECK(s.kind == K::None);
|
||||
CHECK((s.point - Vec2d(50, 50)).norm() == Approx(0.0).margin(1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("inference: axis inference flags horizontal / vertical segments", "[inference]")
|
||||
{
|
||||
CHECK(infer_axis_constraint({0, 0}, {10, 0.05}).value() == SketchConstraintType::Horizontal);
|
||||
CHECK(infer_axis_constraint({0, 0}, {0.05, 10}).value() == SketchConstraintType::Vertical);
|
||||
CHECK_FALSE(infer_axis_constraint({0, 0}, {10, 10}).has_value()); // 45 deg
|
||||
CHECK_FALSE(infer_axis_constraint({0, 0}, {0, 0}).has_value()); // degenerate
|
||||
}
|
||||
|
||||
TEST_CASE("inference: perpendicular inferred for a connected square corner", "[inference]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({10, 0}, {10, 7}) };
|
||||
auto r = infer_relations(ents, 1);
|
||||
REQUIRE(r.size() == 1);
|
||||
CHECK(r[0].type == SketchConstraintType::Perpendicular);
|
||||
CHECK(r[0].ea == 0);
|
||||
CHECK(r[0].eb == 1);
|
||||
}
|
||||
|
||||
TEST_CASE("inference: parallel inferred for connected collinear-ish lines", "[inference]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({10, 0}, {21, 0.1}) };
|
||||
auto r = infer_relations(ents, 1);
|
||||
REQUIRE(r.size() == 1);
|
||||
CHECK(r[0].type == SketchConstraintType::Parallel);
|
||||
CHECK(r[0].ea == 0);
|
||||
CHECK(r[0].eb == 1);
|
||||
}
|
||||
|
||||
TEST_CASE("inference: two unconnected parallel lines infer nothing", "[inference]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({0, 5}, {10, 5}) };
|
||||
auto r = infer_relations(ents, 1);
|
||||
CHECK(r.empty());
|
||||
}
|
||||
|
||||
TEST_CASE("inference: a corner outside tolerance infers nothing", "[inference]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({10, 0}, {15, 7}) };
|
||||
auto r = infer_relations(ents, 1);
|
||||
CHECK(r.empty());
|
||||
}
|
||||
|
||||
TEST_CASE("inference: equal radius inferred for near-equal circles", "[inference]")
|
||||
{
|
||||
auto r = infer_relations({ circle({0, 0}, 5.0), circle({30, 0}, 5.02) }, 1);
|
||||
REQUIRE(r.size() == 1);
|
||||
CHECK(r[0].type == SketchConstraintType::EqualRadius);
|
||||
CHECK(r[0].ea == 0);
|
||||
CHECK(r[0].eb == 1);
|
||||
|
||||
auto r2 = infer_relations({ circle({0, 0}, 5.0), circle({30, 0}, 6.0) }, 1);
|
||||
CHECK(r2.empty());
|
||||
}
|
||||
|
||||
TEST_CASE("inference: tangent inferred for a line meeting a circle tangentially", "[inference]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { circle({0, 0}, 5.0), line({0, 5}, {10, 5}) };
|
||||
auto r = infer_relations(ents, 1);
|
||||
REQUIRE(r.size() == 1);
|
||||
CHECK(r[0].type == SketchConstraintType::Tangent);
|
||||
CHECK(r[0].ea == 0);
|
||||
CHECK(r[0].eb == 1);
|
||||
|
||||
std::vector<SketchEntity> off = { circle({0, 0}, 5.0), line({0, 5}, {10, 9}) };
|
||||
CHECK(infer_relations(off, 1).empty());
|
||||
}
|
||||
|
||||
TEST_CASE("inference: nothing inferred against a higher index", "[inference]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({10, 0}, {10, 7}) };
|
||||
auto r = infer_relations(ents, 0);
|
||||
CHECK(r.empty());
|
||||
}
|
||||
|
||||
TEST_CASE("inference: degenerate entities are ignored", "[inference]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({10, 0}, {10, 0}) };
|
||||
auto r = infer_relations(ents, 1);
|
||||
CHECK(r.empty());
|
||||
}
|
||||
|
||||
// The cap that keeps infer_relations linear rather than quadratic. Without it a drawing with
|
||||
// many equal holes yields a constraint per PAIR: 200 equal circles produced ~20000 candidates,
|
||||
// the batch was rejected as over-constrained, and the caller's one-at-a-time fallback then ran
|
||||
// a solve per constraint -- which pinned the app at 95% of a core with the MCP socket
|
||||
// unresponsive, and is what the corpus rung caught.
|
||||
TEST_CASE("inference: at most one relation per rule per new entity", "[inference]")
|
||||
{
|
||||
// 40 circles of the same radius; the 41st must not produce 40 EqualRadius constraints.
|
||||
std::vector<SketchEntity> ents;
|
||||
for (int i = 0; i < 41; ++i) {
|
||||
SketchEntity c;
|
||||
c.type = SketchEntity::Type::Circle;
|
||||
c.center = Vec2d(i * 20.0, 0.0);
|
||||
c.p0 = c.center;
|
||||
c.radius = 5.0;
|
||||
ents.push_back(c);
|
||||
}
|
||||
auto rels = infer_relations(ents, 40);
|
||||
CHECK(rels.size() == 1);
|
||||
CHECK(rels[0].type == SketchConstraintType::EqualRadius);
|
||||
CHECK(rels[0].eb == 40);
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
// Closed-profile harness for the 2D sketch layer.
|
||||
//
|
||||
// The existing [SketchEdit] cases check one entity at a time — offset ONE line, mirror ONE
|
||||
// arc — and every one of them passes while the feature they belong to is unusable. What a
|
||||
// user actually does is combine 2D features into a CLOSED PROFILE and extrude it, and the
|
||||
// property that makes that work is topological, not per-entity: after the operation, do the
|
||||
// pieces still form a single closed loop?
|
||||
//
|
||||
// So these cases assert the loop, not the coordinates. That is the invariant every sketch
|
||||
// operation has to preserve and the only one that predicts whether the GUI can build a solid
|
||||
// out of the result.
|
||||
#include <catch2/catch_all.hpp> // mainline OrcaSlicer ships Catch2 v3 (v2 was catch2/catch.hpp)
|
||||
#include "libslic3r/CAD/SketchEngine.hpp"
|
||||
#include <BRepGProp.hxx>
|
||||
#include <GProp_GProps.hxx>
|
||||
#include <cmath>
|
||||
|
||||
using namespace Slic3r;
|
||||
using Catch::Matchers::WithinAbs;
|
||||
|
||||
namespace {
|
||||
|
||||
SketchPlane xy_plane() { return SketchPlane::XY(); }
|
||||
|
||||
SketchEntity line(const Vec2d& a, const Vec2d& b)
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Line;
|
||||
e.p0 = a; e.p1 = b;
|
||||
return e;
|
||||
}
|
||||
|
||||
// A CCW rectangle as four Line entities sharing endpoints exactly.
|
||||
std::vector<SketchEntity> rect(double w, double h)
|
||||
{
|
||||
return { line({0, 0}, {w, 0}), line({w, 0}, {w, h}),
|
||||
line({w, h}, {0, h}), line({0, h}, {0, 0}) };
|
||||
}
|
||||
|
||||
// How many of the wires the sketch resolves to are CLOSED.
|
||||
int closed_wires(const std::vector<SketchEntity>& ents)
|
||||
{
|
||||
const auto ws = SketchEngine::entities_to_wires(ents, xy_plane());
|
||||
int n = 0;
|
||||
for (const auto& w : ws)
|
||||
if (!w.IsNull() && w.Closed()) ++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
// Enclosed area of the single closed loop the sketch resolves to. -1 when it is not one
|
||||
// closed loop — the failure the whole file exists to catch.
|
||||
double profile_area(const std::vector<SketchEntity>& ents)
|
||||
{
|
||||
const auto ws = SketchEngine::entities_to_wires(ents, xy_plane());
|
||||
if (ws.size() != 1 || ws[0].IsNull() || !ws[0].Closed()) return -1.0;
|
||||
const TopoDS_Face f = SketchEngine::wires_to_face(ws, xy_plane());
|
||||
GProp_GProps props;
|
||||
BRepGProp::SurfaceProperties(f, props);
|
||||
return props.Mass();
|
||||
}
|
||||
|
||||
SketchEntity arc(const Vec2d& c, double r, double a0, double a1)
|
||||
{
|
||||
SketchEntity e;
|
||||
e.type = SketchEntity::Type::Arc;
|
||||
e.center = c;
|
||||
e.radius = r;
|
||||
e.start_angle = a0;
|
||||
e.end_angle = a1;
|
||||
e.p0 = c + r * Vec2d(std::cos(a0), std::sin(a0));
|
||||
e.p1 = c + r * Vec2d(std::cos(a1), std::sin(a1));
|
||||
return e;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("profile baseline: a hand-built rectangle is one closed loop", "[SketchProfile]")
|
||||
{
|
||||
REQUIRE(closed_wires(rect(40, 20)) == 1);
|
||||
}
|
||||
|
||||
TEST_CASE("profile: mirroring a closed rectangle keeps it closed", "[SketchProfile]")
|
||||
{
|
||||
const auto m = SketchEngine::mirror_entities(rect(40, 20), Vec2d(-10, 0), Vec2d(-10, 1));
|
||||
REQUIRE(m.size() == 4);
|
||||
REQUIRE(closed_wires(m) == 1);
|
||||
}
|
||||
|
||||
TEST_CASE("profile: mirroring an open half-profile closes it against the axis", "[SketchProfile]")
|
||||
{
|
||||
// Half a rectangle, open along x=0 — the classic "draw half, mirror it" gesture.
|
||||
const std::vector<SketchEntity> half = {
|
||||
line({0, 0}, {20, 0}), line({20, 0}, {20, 10}), line({20, 10}, {0, 10}) };
|
||||
auto all = half;
|
||||
for (const auto& e : SketchEngine::mirror_entities(half, Vec2d(0, 0), Vec2d(0, 1)))
|
||||
all.push_back(e);
|
||||
REQUIRE(all.size() == 6);
|
||||
REQUIRE(closed_wires(all) == 1);
|
||||
}
|
||||
|
||||
TEST_CASE("profile: offsetting a closed rectangle keeps it closed", "[SketchProfile]")
|
||||
{
|
||||
const auto out = SketchEngine::offset_entities(rect(40, 20), 5.0);
|
||||
REQUIRE(out.size() == 4);
|
||||
REQUIRE(closed_wires(out) == 1);
|
||||
}
|
||||
|
||||
TEST_CASE("profile: offset outward grows the enclosed area by the right amount", "[SketchProfile]")
|
||||
{
|
||||
// A rectangle offset outward by d is (w+2d) x (h+2d) with the corners rounded at r=d,
|
||||
// so its area is w*h + 2d(w+h) + pi*d^2 whichever way the corners are healed... except
|
||||
// for a sharp-corner offset, which is exactly (w+2d)*(h+2d). Either healing is defensible;
|
||||
// a set of four disconnected segments is not, and that is what this measures.
|
||||
const double w = 40, h = 20, d = 5;
|
||||
const auto out = SketchEngine::offset_entities(rect(w, h), d);
|
||||
const auto ws = SketchEngine::entities_to_wires(out, xy_plane());
|
||||
REQUIRE(ws.size() == 1);
|
||||
REQUIRE(ws[0].Closed());
|
||||
}
|
||||
|
||||
TEST_CASE("profile: offset sign is left-of-travel, so +d shrinks a CCW rectangle", "[SketchProfile]")
|
||||
{
|
||||
// The convention has to be pinned by a test, because it is the one thing a caller cannot
|
||||
// read off the geometry: +d = left of the direction of travel = inward for a CCW loop.
|
||||
// Miter join on a rectangle keeps the corners sharp, so the result is exact.
|
||||
const double w = 40, h = 20, d = 5;
|
||||
REQUIRE_THAT(profile_area(SketchEngine::offset_entities(rect(w, h), d)),
|
||||
WithinAbs((w - 2 * d) * (h - 2 * d), 1e-6));
|
||||
REQUIRE_THAT(profile_area(SketchEngine::offset_entities(rect(w, h), -d)),
|
||||
WithinAbs((w + 2 * d) * (h + 2 * d), 1e-6));
|
||||
}
|
||||
|
||||
TEST_CASE("profile: offsetting a stadium (two lines + two arcs) stays closed", "[SketchProfile]")
|
||||
{
|
||||
// A slot outline: straight top and bottom joined by half-circle caps. This is the case the
|
||||
// per-entity offset could never repair, because both seams are line-to-arc.
|
||||
const double L = 30, r = 8, d = 3;
|
||||
const std::vector<SketchEntity> slot = {
|
||||
line({0, -r}, {L, -r}),
|
||||
arc({L, 0}, r, -M_PI / 2, M_PI / 2),
|
||||
line({L, r}, {0, r}),
|
||||
arc({0, 0}, r, M_PI / 2, 3 * M_PI / 2),
|
||||
};
|
||||
REQUIRE(closed_wires(slot) == 1);
|
||||
const auto out = SketchEngine::offset_entities(slot, -d); // -d = outward for this CCW loop
|
||||
REQUIRE(closed_wires(out) == 1);
|
||||
// Offsetting a stadium outward by d gives the stadium with radius r+d: L*2(r+d) + pi(r+d)^2.
|
||||
// Lines and caps must move the SAME way — that is the assertion this case exists for.
|
||||
const double rr = r + d;
|
||||
REQUIRE_THAT(profile_area(out), WithinAbs(L * 2 * rr + M_PI * rr * rr, 1e-6));
|
||||
}
|
||||
|
||||
TEST_CASE("profile: an open chain offsets without being forced closed", "[SketchProfile]")
|
||||
{
|
||||
// A sweep path is legitimately open; the repair must join its interior seams and leave
|
||||
// the two free ends alone.
|
||||
const std::vector<SketchEntity> open_chain = {
|
||||
line({0, 0}, {20, 0}), line({20, 0}, {20, 10}) };
|
||||
const auto out = SketchEngine::offset_entities(open_chain, 4.0);
|
||||
REQUIRE(out.size() == 2);
|
||||
REQUIRE(closed_wires(out) == 0);
|
||||
// The interior seam is repaired: the two offset segments still meet.
|
||||
REQUIRE_THAT((out[0].p1 - out[1].p0).norm(), WithinAbs(0.0, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("profile: a mirrored half offsets as one loop, not two", "[SketchProfile]")
|
||||
{
|
||||
// The classic "draw half, mirror it" gesture on a stadium. mirror_entities emits a half
|
||||
// that travels the opposite way round, so the concatenation must still chain as ONE closed
|
||||
// loop and its mirrored cap must offset outward like the original, not inward.
|
||||
const double L = 30, R = 15, d = 4;
|
||||
const std::vector<SketchEntity> half = {
|
||||
line({0, -R}, {L, -R}),
|
||||
arc({L, 0}, R, -M_PI / 2, M_PI / 2),
|
||||
line({L, R}, {0, R}),
|
||||
};
|
||||
std::vector<SketchEntity> all = half;
|
||||
for (const auto& e : SketchEngine::mirror_entities(half, Vec2d(0, 0), Vec2d(0, 1)))
|
||||
all.push_back(e);
|
||||
REQUIRE(closed_wires(all) == 1);
|
||||
|
||||
const auto out = SketchEngine::offset_entities(all, -d); // -d = outward for this loop
|
||||
REQUIRE(closed_wires(out) == 1);
|
||||
for (const auto& o : out)
|
||||
if (o.type == SketchEntity::Type::Arc)
|
||||
REQUIRE_THAT(o.radius, WithinAbs(R + d, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("profile: a mirrored half continues the original chain", "[SketchProfile]")
|
||||
{
|
||||
// The point of emitting the reflected half reversed: appending it to the source must give a
|
||||
// chain you can WALK, head-to-tail, with no consumer having to notice that half of it came
|
||||
// from a mirror. The end of the last source entity must be the start of the first mirrored
|
||||
// one, and the end of the last mirrored one must close back to the very first start.
|
||||
const std::vector<SketchEntity> half = {
|
||||
line({0, -15}, {50, -15}), line({50, -15}, {50, 15}), line({50, 15}, {0, 15}) };
|
||||
const auto m = SketchEngine::mirror_entities(half, Vec2d(0, 0), Vec2d(0, 1));
|
||||
REQUIRE(m.size() == 3);
|
||||
|
||||
REQUIRE_THAT((half.back().p1 - m.front().p0).norm(), WithinAbs(0.0, 1e-9));
|
||||
REQUIRE_THAT((m.back().p1 - half.front().p0).norm(), WithinAbs(0.0, 1e-9));
|
||||
|
||||
for (size_t i = 0; i + 1 < m.size(); ++i)
|
||||
REQUIRE_THAT((m[i].p1 - m[i + 1].p0).norm(), WithinAbs(0.0, 1e-9));
|
||||
|
||||
auto all = half;
|
||||
for (const auto& e : m) all.push_back(e);
|
||||
REQUIRE(closed_wires(all) == 1);
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
#include <catch2/catch_all.hpp> // mainline OrcaSlicer ships Catch2 v3 (v2 was catch2/catch.hpp)
|
||||
using Catch::Approx; // v3 scopes Approx into the Catch namespace; v2 had it at global scope
|
||||
|
||||
#include "libslic3r/CAD/SketchSolver.hpp"
|
||||
#include "libslic3r/CAD/SketchEngine.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
using CT = SketchConstraintType;
|
||||
using R = SketchPointRole;
|
||||
|
||||
static SketchEntity line(Vec2d a, Vec2d b)
|
||||
{
|
||||
SketchEntity e; e.type = SketchEntity::Type::Line; e.p0 = a; e.p1 = b; return e;
|
||||
}
|
||||
static SketchEntity circle(Vec2d c, double r)
|
||||
{
|
||||
SketchEntity e; e.type = SketchEntity::Type::Circle; e.center = c; e.p0 = c; e.radius = r; return e;
|
||||
}
|
||||
static SketchEntityConstraintDef con(CT t, int ea, R ra, int eb, R rb, double v = 0.0)
|
||||
{
|
||||
SketchEntityConstraintDef c; c.type = t; c.ea = ea; c.ra = ra; c.eb = eb; c.rb = rb; c.value = v; return c;
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: distance + horizontal + fix solves a line length", "[slvs]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {5, 1}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::Fix, 0, R::P0, 0, R::P0),
|
||||
con(CT::Horizontal, 0, R::P0, 0, R::P1),
|
||||
con(CT::Distance, 0, R::P0, 0, R::P1, 10.0),
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK((ents[0].p1 - ents[0].p0).norm() == Approx(10.0).margin(1e-6));
|
||||
CHECK(ents[0].p0.x() == Approx(0.0).margin(1e-6));
|
||||
CHECK(ents[0].p0.y() == Approx(0.0).margin(1e-6));
|
||||
CHECK(ents[0].p1.y() == Approx(0.0).margin(1e-6)); // horizontal
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: coincident joins two line endpoints (loop closes)", "[slvs]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({10.3, 0.2}, {10, 10}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::Coincident, 0, R::P1, 1, R::P0),
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK((ents[0].p1 - ents[1].p0).norm() == Approx(0.0).margin(1e-6));
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: parallel + perpendicular on lines", "[slvs]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {10, 1}), line({0, 5}, {10, 5.5}), line({0, 0}, {0.5, 10}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::Fix, 0, R::P0, 0, R::P0),
|
||||
con(CT::Horizontal, 0, R::P0, 0, R::P1),
|
||||
con(CT::Parallel, 0, R::P0, 1, R::P0), // line1 parallel to line0
|
||||
con(CT::Perpendicular, 0, R::P0, 2, R::P0), // line2 perpendicular to line0
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK(ents[1].p1.y() - ents[1].p0.y() == Approx(0.0).margin(1e-6)); // line1 horizontal
|
||||
CHECK(ents[2].p1.x() - ents[2].p0.x() == Approx(0.0).margin(1e-6)); // line2 vertical
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: circle radius constraint", "[slvs]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { circle({2, 2}, 3.0) };
|
||||
std::vector<SketchEntityConstraintDef> cons = { con(CT::Radius, 0, R::P0, -1, R::P0, 7.0) };
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK(ents[0].radius == Approx(7.0).margin(1e-6));
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: degrees of freedom reported", "[slvs]")
|
||||
{
|
||||
// One free line with only a Fix on the start: 4 DoF total minus 2 (fix) = 2 remaining.
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {3, 4}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = { con(CT::Fix, 0, R::P0, 0, R::P0) };
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK(res.dof == 2);
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: drag pulls a point while constraints hold", "[slvs]")
|
||||
{
|
||||
// A vertical line of fixed length 10, P0 pinned at the origin. Dragging P1 toward
|
||||
// (10,0) must keep the length (Distance constraint) but rotate the line so the end
|
||||
// follows the cursor into positive x — the dragged param wins the under-constrained DoF.
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {0, 10}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::Fix, 0, R::P0, 0, R::P0),
|
||||
con(CT::Distance, 0, R::P0, 0, R::P1, 10.0),
|
||||
};
|
||||
ents[0].p1 = Vec2d(10, 0); // user dropped the endpoint here
|
||||
auto res = sketch_solve_drag(ents, cons, 0, R::P1);
|
||||
REQUIRE(res.ok);
|
||||
CHECK((ents[0].p1 - ents[0].p0).norm() == Approx(10.0).margin(1e-6)); // length held
|
||||
CHECK(ents[0].p0.x() == Approx(0.0).margin(1e-6)); // P0 still pinned
|
||||
CHECK(ents[0].p0.y() == Approx(0.0).margin(1e-6));
|
||||
CHECK(ents[0].p1.x() > 1.0); // end followed the drag toward +x (not stuck vertical)
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: over-constrained / inconsistent is detected", "[slvs]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {5, 0}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::Fix, 0, R::P0, 0, R::P0),
|
||||
con(CT::Fix, 0, R::P1, 0, R::P1),
|
||||
con(CT::Distance, 0, R::P0, 0, R::P1, 99.0), // contradicts the pinned endpoints
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
CHECK_FALSE(res.ok); // SLVS_RESULT_INCONSISTENT
|
||||
}
|
||||
|
||||
// yww4. libslvs sizes its System with a compile-time `MAX_UNKNOWNS = 1024`, and the
|
||||
// solver is handed every entity in the sketch at 2 params per point — so a sketch of about 480
|
||||
// lines is the last one that fits and the next comes back TOO_MANY_UNKNOWNS. Because
|
||||
// try_add_constraints rolls a failed batch back, that turned into: every auto-inferred constraint
|
||||
// on a large sketch silently dropped, and from then on no dimension could ever be applied to it.
|
||||
// Constraints only couple entities that share a point, so the sketch is solved component by
|
||||
// component when the whole system does not fit.
|
||||
TEST_CASE("slvs: a sketch past the solver's unknown limit still solves", "[slvs]")
|
||||
{
|
||||
// 300 disjoint squares: 1200 lines, 4800 unknowns whole, 8 per component.
|
||||
const int N = 300;
|
||||
std::vector<SketchEntity> ents;
|
||||
std::vector<SketchEntityConstraintDef> cons;
|
||||
for (int i = 0; i < N; ++i) {
|
||||
const double x = (i % 30) * 10.0, y = (i / 30) * 10.0;
|
||||
const int b = int(ents.size());
|
||||
ents.push_back(line({x, y}, {x + 4.0, y}));
|
||||
ents.push_back(line({x + 4.0, y}, {x + 4.0, y + 4.0}));
|
||||
ents.push_back(line({x + 4.0, y + 4.0}, {x, y + 4.0}));
|
||||
ents.push_back(line({x, y + 4.0}, {x, y}));
|
||||
for (int k = 0; k < 4; ++k)
|
||||
cons.push_back(con(CT::Coincident, b + k, R::P1, b + (k + 1) % 4, R::P0));
|
||||
}
|
||||
REQUIRE(ents.size() == size_t(4 * N));
|
||||
|
||||
std::vector<SketchEntity> before = ents;
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
for (size_t i = 0; i < ents.size(); ++i) { // already satisfied: nothing may move
|
||||
CHECK(ents[i].p0.x() == Approx(before[i].p0.x()).margin(1e-9));
|
||||
CHECK(ents[i].p0.y() == Approx(before[i].p0.y()).margin(1e-9));
|
||||
CHECK(ents[i].p1.x() == Approx(before[i].p1.x()).margin(1e-9));
|
||||
CHECK(ents[i].p1.y() == Approx(before[i].p1.y()).margin(1e-9));
|
||||
}
|
||||
|
||||
// And a dimension typed onto one of them lands exactly, which is what stopped working.
|
||||
cons.push_back(con(CT::Distance, 0, R::P0, 0, R::P1, 7.0));
|
||||
auto res2 = sketch_solve(ents, cons);
|
||||
REQUIRE(res2.ok);
|
||||
CHECK((ents[0].p1 - ents[0].p0).norm() == Approx(7.0).margin(1e-9));
|
||||
|
||||
// A conflict inside ONE component must still be caught, not swallowed by the split.
|
||||
cons.push_back(con(CT::Distance, 0, R::P0, 0, R::P1, 99.0));
|
||||
auto res3 = sketch_solve(ents, cons);
|
||||
CHECK_FALSE(res3.ok);
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: equal radius drives two circles to one radius", "[slvs][CadDocument]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { circle({0, 0}, 5.0), circle({10, 0}, 12.0) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::EqualRadius, 0, R::P0, 1, R::P0),
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK(ents[0].radius == Approx(ents[1].radius).margin(1e-9));
|
||||
CHECK(ents[0].radius > 1e-6); // equal-at-zero would satisfy the line above trivially
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: equal radius plus a radius dimension pins both", "[slvs][CadDocument]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { circle({0, 0}, 5.0), circle({10, 0}, 12.0) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::EqualRadius, 0, R::P0, 1, R::P0),
|
||||
con(CT::Radius, 0, R::P0, -1, R::P0, 8.0),
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK(ents[0].radius == Approx(8.0).margin(1e-9));
|
||||
CHECK(ents[1].radius == Approx(8.0).margin(1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: collinear makes two offset lines share one line", "[slvs][CadDocument]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({0, 4}, {10, 4}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::Collinear, 0, R::P0, 1, R::P0),
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
const Vec2d& a0 = ents[0].p0;
|
||||
const Vec2d ad = ents[0].p1 - ents[0].p0;
|
||||
for (int k = 0; k <= 1; ++k) {
|
||||
const Vec2d& pk = (k == 0) ? ents[1].p0 : ents[1].p1;
|
||||
const double cross = ad.x() * (pk.y() - a0.y()) - ad.y() * (pk.x() - a0.x());
|
||||
CHECK(cross == Approx(0.0).margin(1e-9));
|
||||
}
|
||||
// A line collapsed to a point is trivially collinear with anything, so the cross
|
||||
// products above would pass on a degenerate solve. Both lines must survive intact.
|
||||
CHECK(ad.norm() == Approx(10.0).margin(1e-9));
|
||||
CHECK((ents[1].p1 - ents[1].p0).norm() == Approx(10.0).margin(1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: collinear on already-collinear lines moves nothing", "[slvs][CadDocument]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {10, 0}), line({20, 0}, {30, 0}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::Collinear, 0, R::P0, 1, R::P0),
|
||||
};
|
||||
std::vector<SketchEntity> before = ents;
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
for (size_t i = 0; i < ents.size(); ++i) { // already satisfied: nothing may move
|
||||
CHECK(ents[i].p0.x() == Approx(before[i].p0.x()).margin(1e-9));
|
||||
CHECK(ents[i].p0.y() == Approx(before[i].p0.y()).margin(1e-9));
|
||||
CHECK(ents[i].p1.x() == Approx(before[i].p1.x()).margin(1e-9));
|
||||
CHECK(ents[i].p1.y() == Approx(before[i].p1.y()).margin(1e-9));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: distance-x drives the horizontal gap and leaves Y alone", "[slvs][CadDocument]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {3, 7}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::Fix, 0, R::P0, 0, R::P0),
|
||||
con(CT::DistanceX, 0, R::P0, 0, R::P1, 10.0),
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
// SIGNED, not abs. PROJ_PT_DISTANCE constrains (pB - pA).dot(unit(dir)), and a
|
||||
// LINE_SEGMENT's direction is point[0] - point[1] (slvs entity.cpp), so the reference
|
||||
// line is built head-first to mean +X. Assert on abs and a flipped reference passes
|
||||
// while every dimension lands the point on the wrong side of its anchor.
|
||||
CHECK(ents[0].p1.x() - ents[0].p0.x() == Approx(10.0).margin(1e-9));
|
||||
CHECK(ents[0].p1.y() == Approx(7.0).margin(1e-9)); // Y must not be disturbed
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: distance-y drives the vertical gap and leaves X alone", "[slvs][CadDocument]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {3, 7}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::Fix, 0, R::P0, 0, R::P0),
|
||||
con(CT::DistanceY, 0, R::P0, 0, R::P1, 10.0),
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK(ents[0].p1.y() - ents[0].p0.y() == Approx(10.0).margin(1e-9)); // signed: see above
|
||||
CHECK(ents[0].p1.x() == Approx(3.0).margin(1e-9)); // X must not be disturbed
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: distance-x is not the straight-line distance", "[slvs][CadDocument]")
|
||||
{
|
||||
// B is at straight-line distance 10 from A; DistanceX = 6 is already satisfied, so a
|
||||
// correct projection leaves B untouched. This is the case that fails if the constraint
|
||||
// were wired to SLVS_C_PT_PT_DISTANCE, which would drag B onto the radius-6 circle.
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {6, 8}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::Fix, 0, R::P0, 0, R::P0),
|
||||
con(CT::DistanceX, 0, R::P0, 0, R::P1, 6.0),
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK(ents[0].p1.x() == Approx(6.0).margin(1e-9));
|
||||
CHECK(ents[0].p1.y() == Approx(8.0).margin(1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: distance-x plus distance-y fully locates a point", "[slvs][CadDocument]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {1, 1}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::Fix, 0, R::P0, 0, R::P0),
|
||||
con(CT::DistanceX, 0, R::P0, 0, R::P1, 4.0),
|
||||
con(CT::DistanceY, 0, R::P0, 0, R::P1, 3.0),
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK(ents[0].p1.x() - ents[0].p0.x() == Approx(4.0).margin(1e-9)); // signed: see above
|
||||
CHECK(ents[0].p1.y() - ents[0].p0.y() == Approx(3.0).margin(1e-9));
|
||||
}
|
||||
|
||||
// The property the GUI's ref-ordering exists to preserve: DistanceX is SIGNED, so applying
|
||||
// the CURRENT projected delta as the target must not move anything. If the refs are ordered
|
||||
// so the shown value is positive while the actual signed delta is negative, accepting the
|
||||
// value a dimension opens with teleports the point to the other side of its anchor.
|
||||
TEST_CASE("slvs: applying a point's own distance-x is a no-op", "[slvs][CadDocument]")
|
||||
{
|
||||
// p1 sits to the LEFT of p0, so the signed delta p1 - p0 is negative.
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {-4, 7}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::Fix, 0, R::P0, 0, R::P0),
|
||||
con(CT::DistanceX, 0, R::P0, 0, R::P1, -4.0), // the CURRENT signed delta
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK(ents[0].p1.x() == Approx(-4.0).margin(1e-9)); // stayed left, did not flip to +4
|
||||
CHECK(ents[0].p1.y() == Approx(7.0).margin(1e-9));
|
||||
}
|
||||
|
||||
static SketchEntity point(Vec2d p)
|
||||
{
|
||||
SketchEntity e; e.type = SketchEntity::Type::Point; e.p0 = p; return e;
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: coincident onto the origin sentinel pins a point", "[slvs][CadDocument]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { point({5, 5}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::Coincident, 0, R::P0, kSketchRefOrigin, R::P0),
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK(ents[0].p0.x() == Approx(0.0).margin(1e-9));
|
||||
CHECK(ents[0].p0.y() == Approx(0.0).margin(1e-9));
|
||||
}
|
||||
|
||||
// NOTE on why these pin the free direction instead of asserting "the other coordinate is
|
||||
// left alone". sys.dragged[] is populated only while a drag is in progress, so a plain
|
||||
// sketch_solve of an UNDER-constrained system is free to move any parameter -- solvespace
|
||||
// runs a Newton iteration, it does not minimise movement. PointOnLine alone is one equation
|
||||
// in two unknowns, and the point measurably slides along the axis (from (7,4) to (4,0)).
|
||||
// That is legal, not a defect, so the well-posed test states both coordinates.
|
||||
TEST_CASE("slvs: point-on-line onto the X axis, located along it from the origin", "[slvs][CadDocument]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { point({7, 4}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::PointOnLine, 0, R::P0, kSketchRefAxisX, R::P0),
|
||||
con(CT::DistanceX, kSketchRefOrigin, R::P0, 0, R::P0, 7.0), // both sentinels at once
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK(ents[0].p0.y() == Approx(0.0).margin(1e-9)); // driven onto the X axis
|
||||
CHECK(ents[0].p0.x() == Approx(7.0).margin(1e-9)); // and located along it
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: point-on-line onto the Y axis, located along it from the origin", "[slvs][CadDocument]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { point({4, 7}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::PointOnLine, 0, R::P0, kSketchRefAxisY, R::P0),
|
||||
con(CT::DistanceY, kSketchRefOrigin, R::P0, 0, R::P0, 7.0),
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK(ents[0].p0.x() == Approx(0.0).margin(1e-9)); // driven onto the Y axis
|
||||
CHECK(ents[0].p0.y() == Approx(7.0).margin(1e-9)); // and located along it
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: parallel to the X axis levels a line without collapsing it", "[slvs][CadDocument]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {10, 3}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::Fix, 0, R::P0, 0, R::P0),
|
||||
con(CT::Parallel, 0, R::P0, kSketchRefAxisX, R::P0),
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK(ents[0].p1.y() == Approx(0.0).margin(1e-9)); // leveled onto y = 0
|
||||
// A bare Parallel leaves length free; the solver preserves the endpoint's free
|
||||
// x-coordinate, so the line lands at (10,0) — length 10, not the original sqrt(109).
|
||||
// Assert that free coordinate rather than abs(): a flipped/collapsed line would not
|
||||
// land exactly here.
|
||||
CHECK(ents[0].p1.x() == Approx(10.0).margin(1e-9));
|
||||
CHECK((ents[0].p1 - ents[0].p0).norm() == Approx(10.0).margin(1e-6)); // did not collapse
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: symmetric-about-Y mirrors two points across x = 0", "[slvs][CadDocument]")
|
||||
{
|
||||
std::vector<SketchEntity> ents = { point({3, 5}), point({9, 5}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::SymmetricAboutY, 0, R::P0, 1, R::P0),
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK(ents[0].p0.x() == Approx(-ents[1].p0.x()).margin(1e-9)); // mirror across x = 0
|
||||
// Neither x may be 0: a both-collapsed-to-the-axis solution also satisfies the mirror
|
||||
// trivially. Squared, not abs(), so a near-zero x still fails cleanly.
|
||||
CHECK(ents[0].p0.x() * ents[0].p0.x() > 1e-12);
|
||||
CHECK(ents[1].p0.x() * ents[1].p0.x() > 1e-12);
|
||||
CHECK(ents[0].p0.y() == Approx(5.0).margin(1e-9)); // Y values untouched
|
||||
CHECK(ents[1].p0.y() == Approx(5.0).margin(1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("slvs: reference-based constraint adds no degrees of freedom", "[slvs][CadDocument]")
|
||||
{
|
||||
// A free line with Fix on P0 and Parallel to the X axis: 4 DoF - 2 (fix) - 1 (angle)
|
||||
// = 1 (length still free). If the G_FIXED reference entities leaked unknowns into the
|
||||
// solved group, this figure would be wrong.
|
||||
std::vector<SketchEntity> ents = { line({0, 0}, {3, 4}) };
|
||||
std::vector<SketchEntityConstraintDef> cons = {
|
||||
con(CT::Fix, 0, R::P0, 0, R::P0),
|
||||
con(CT::Parallel, 0, R::P0, kSketchRefAxisX, R::P0),
|
||||
};
|
||||
auto res = sketch_solve(ents, cons);
|
||||
REQUIRE(res.ok);
|
||||
CHECK(res.dof == 1);
|
||||
}
|
||||
@@ -163,6 +163,50 @@ TEST_CASE("H2C multi-nozzle: filaments get distinct nozzles on the 6-nozzle extr
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Grouping context spans the filament count with mis-sized config arrays", "[ToolOrdering][H2C]")
|
||||
{
|
||||
// FilamentGroup indexes the grouping context's filament_info by filament id, so a short
|
||||
// per-filament array must not shorten it: the reads run off the end.
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
// Single 6-nozzle extruder: opens the grouping engine without needing a BBL multi-extruder.
|
||||
config.option<ConfigOptionFloats>("nozzle_diameter", true)->values = {0.4};
|
||||
config.option<ConfigOptionIntsNullable>("extruder_max_nozzle_count", true)->values = {6};
|
||||
config.option<ConfigOptionStrings>("extruder_nozzle_stats", true)->values = {"Standard#6"};
|
||||
|
||||
// Four filaments, with filament_type / filament_is_support left short on purpose.
|
||||
config.option<ConfigOptionStrings>("filament_colour", true)->values = {"#FF0000", "#00FF00", "#0000FF", "#FFFF00"};
|
||||
config.option<ConfigOptionStrings>("filament_type", true)->values = {"PLA"};
|
||||
config.option<ConfigOptionBools>("filament_is_support", true)->values = {0};
|
||||
config.option<ConfigOptionFloats>("filament_diameter", true)->values = {1.75, 1.75, 1.75, 1.75};
|
||||
config.option<ConfigOptionInts>("filament_map", true)->values = {1, 1, 1, 1};
|
||||
config.option<ConfigOptionFloats>("flush_volumes_matrix", true)->values = std::vector<double>(16, 140.);
|
||||
config.option<ConfigOptionFloats>("flush_multiplier", true)->values = {1.};
|
||||
|
||||
Model model;
|
||||
model.add_object("cube", "", make_cube(20, 20, 20))->add_instance();
|
||||
|
||||
Print print;
|
||||
print.apply(model, config);
|
||||
// apply() does not pad the per-filament arrays, so the mis-sizing survives into the engine.
|
||||
REQUIRE(print.config().filament_type.values.size() < print.config().filament_colour.values.size());
|
||||
|
||||
std::vector<std::vector<unsigned int>> layer_filaments = {{0, 1}, {1, 2}, {2, 3}};
|
||||
|
||||
SECTION("short per-filament arrays still yield one entry per filament") {
|
||||
auto result = ToolOrdering::get_recommended_filament_maps(layer_filaments, &print, FilamentMapMode::fmmAutoForFlush, {}, {});
|
||||
REQUIRE(result.get_extruder_map(false).size() == 4);
|
||||
for (int f = 0; f < 4; ++f)
|
||||
REQUIRE(result.get_extruder_id(f) == 0);
|
||||
}
|
||||
|
||||
SECTION("filament_ids longer than the filament count is truncated, not paired past the end") {
|
||||
config.option<ConfigOptionStrings>("filament_ids", true)->values = {"a", "b", "c", "d", "e", "f"};
|
||||
print.apply(model, config);
|
||||
auto result = ToolOrdering::get_recommended_filament_maps(layer_filaments, &print, FilamentMapMode::fmmAutoForFlush, {}, {});
|
||||
REQUIRE(result.get_extruder_map(false).size() == 4);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("H2C dynamic selector: per-layer nozzle ids reach the g-code surface", "[ToolOrdering][H2C][Dynamic]")
|
||||
{
|
||||
// The per-layer regroup engine
|
||||
@@ -981,3 +1025,41 @@ TEST_CASE("Selector slicing keeps the result valid across re-apply", "[Print][H2
|
||||
REQUIRE(status != PrintBase::APPLY_STATUS_INVALIDATED);
|
||||
REQUIRE(print.is_step_done(psSlicingFinished));
|
||||
}
|
||||
|
||||
TEST_CASE("parse_cyclic_order parses user cyclic toolchange sequences", "[ToolOrdering][Cyclic]")
|
||||
{
|
||||
// Filament numbers are 1-based in the UI; the parser returns 0-based indices.
|
||||
SECTION("well-formed sequence") {
|
||||
REQUIRE(parse_cyclic_order("3,2,1,4", 4) == std::vector<unsigned int>({2, 1, 0, 3}));
|
||||
}
|
||||
|
||||
SECTION("surrounding whitespace is tolerated") {
|
||||
REQUIRE(parse_cyclic_order(" 3 , 2 ,1, 4 ", 4) == std::vector<unsigned int>({2, 1, 0, 3}));
|
||||
}
|
||||
|
||||
SECTION("out-of-range and non-positive entries are dropped") {
|
||||
// 0 is below the 1-based range, 5 is above it for a 4-filament setup, -1 is invalid.
|
||||
REQUIRE(parse_cyclic_order("0,5,-1,2", 4) == std::vector<unsigned int>({1}));
|
||||
}
|
||||
|
||||
SECTION("duplicates keep only the first occurrence") {
|
||||
REQUIRE(parse_cyclic_order("2,2,1,2", 4) == std::vector<unsigned int>({1, 0}));
|
||||
}
|
||||
|
||||
SECTION("garbage tokens are ignored") {
|
||||
REQUIRE(parse_cyclic_order("3,abc,,2,x1", 4) == std::vector<unsigned int>({2, 1}));
|
||||
}
|
||||
|
||||
SECTION("tokens that only start with a number are ignored") {
|
||||
// "2x" must be dropped rather than parsed as filament 2.
|
||||
REQUIRE(parse_cyclic_order("3,2x,1", 4) == std::vector<unsigned int>({2, 0}));
|
||||
}
|
||||
|
||||
SECTION("empty string yields an empty order") {
|
||||
REQUIRE(parse_cyclic_order("", 4).empty());
|
||||
}
|
||||
|
||||
SECTION("a partial sequence only names the filaments it lists") {
|
||||
REQUIRE(parse_cyclic_order("3,1", 4) == std::vector<unsigned int>({2, 0}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,15 @@
|
||||
|
||||
#include "libslic3r/Utils.hpp"
|
||||
|
||||
#include "test_utils.hpp"
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <unistd.h> // getuid
|
||||
#endif
|
||||
@@ -52,3 +61,94 @@ TEST_CASE("per-user temp root is unchanged on Windows, isolated elsewhere", "[ut
|
||||
REQUIRE_THAT(root, Catch::Matchers::StartsWith(base + "/orcaslicer_"));
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST_CASE("copy_file reports the OS error when the destination cannot be written", "[utils]") {
|
||||
ScopedTemporaryFile source(".txt");
|
||||
{
|
||||
std::ofstream ofs(source.string(), std::ios::binary);
|
||||
ofs << "orca";
|
||||
}
|
||||
REQUIRE(boost::filesystem::exists(source.path()));
|
||||
|
||||
// A directory that was never created, so the copy fails on every platform.
|
||||
const boost::filesystem::path destination = source.path().parent_path() / "orca-missing-dir" / "copy.txt";
|
||||
REQUIRE_FALSE(boost::filesystem::exists(destination.parent_path()));
|
||||
|
||||
std::string error_message;
|
||||
REQUIRE(copy_file(source.string(), destination.string(), error_message) == FAIL_COPY_FILE);
|
||||
REQUIRE_FALSE(error_message.empty());
|
||||
|
||||
#ifdef _WIN32
|
||||
// The Windows branch formats GetLastError() itself. Writing that as
|
||||
// "Error: " + errCode adds an integer to a string literal, which indexes into the
|
||||
// literal instead of appending and runs off its end for any code above 7.
|
||||
const std::string prefix = "Error: ";
|
||||
REQUIRE(error_message.rfind(prefix, 0) == 0);
|
||||
|
||||
const std::string code = error_message.substr(prefix.size());
|
||||
REQUIRE_FALSE(code.empty());
|
||||
REQUIRE(std::all_of(code.begin(), code.end(), [](unsigned char c) { return std::isdigit(c) != 0; }));
|
||||
#endif // _WIN32
|
||||
}
|
||||
|
||||
TEST_CASE("A resolved input path still names the same file after the working directory changes", "[utils]") {
|
||||
ScopedTemporaryFile model(".3mf");
|
||||
{ std::ofstream out(model.string()); out << "3mf"; }
|
||||
const std::string name = model.path().filename().string();
|
||||
|
||||
// Resolve the bare name from the directory holding the file, then move away from it. The guard
|
||||
// restores the directory the test started in, wherever this leaves it.
|
||||
ScopedWorkingDirectory cwd(model.path().parent_path());
|
||||
const std::string resolved = resolve_cli_input_path(name);
|
||||
boost::filesystem::current_path(boost::filesystem::path(TEST_DATA_DIR));
|
||||
|
||||
REQUIRE(boost::filesystem::exists(resolved));
|
||||
REQUIRE(boost::filesystem::equivalent(resolved, model.path()));
|
||||
// Control: the bare name finds nothing from here, so resolving it this late would have failed.
|
||||
REQUIRE_FALSE(boost::filesystem::exists(name));
|
||||
}
|
||||
|
||||
TEST_CASE("resolve_cli_input_path completes a relative path against the working directory", "[utils]") {
|
||||
ScopedWorkingDirectory cwd(boost::filesystem::temp_directory_path());
|
||||
// Read back rather than reusing temp_directory_path(): changing to it resolves any symlink.
|
||||
const boost::filesystem::path here = boost::filesystem::current_path();
|
||||
|
||||
SECTION("a bare name") {
|
||||
REQUIRE(resolve_cli_input_path("model.3mf") == (here / "model.3mf").make_preferred().string());
|
||||
}
|
||||
SECTION("a ./ prefix is dropped") {
|
||||
REQUIRE(resolve_cli_input_path("./model.3mf") == (here / "model.3mf").make_preferred().string());
|
||||
}
|
||||
SECTION("a ../ traversal is collapsed") {
|
||||
REQUIRE(resolve_cli_input_path("../model.3mf") == (here.parent_path() / "model.3mf").make_preferred().string());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("resolve_cli_input_path leaves inputs that must not be completed unchanged", "[utils]") {
|
||||
SECTION("an absolute path") {
|
||||
const boost::filesystem::path absolute = (boost::filesystem::temp_directory_path() / "model.3mf").make_preferred();
|
||||
REQUIRE(resolve_cli_input_path(absolute.string()) == absolute.string());
|
||||
}
|
||||
#ifdef _WIN32
|
||||
// Every absolute form Windows accepts opens today, so each must come back byte for byte:
|
||||
// normalizing them would rewrite the forward slashes and rebuild the \\?\ and UNC prefixes.
|
||||
SECTION("an absolute Windows path of any form") {
|
||||
for (const std::string absolute : {R"(C:\models\model.3mf)",
|
||||
R"(C:/models/model.3mf)",
|
||||
R"(\\server\share\model.3mf)",
|
||||
R"(\\?\C:\models\model.3mf)"})
|
||||
REQUIRE(resolve_cli_input_path(absolute) == absolute);
|
||||
}
|
||||
#endif
|
||||
// These are downloaded rather than opened, and completing one would produce a path, not a URL.
|
||||
SECTION("a custom open protocol URL") {
|
||||
for (const std::string url : {"orcaslicer://open/?file=https://example.com/model.3mf",
|
||||
"prusaslicer://open/?file=https://example.com/model.3mf",
|
||||
"bambustudio://open/?file=https://example.com/model.3mf",
|
||||
"cura://open/?file=https://example.com/model.3mf"})
|
||||
REQUIRE(resolve_cli_input_path(url) == url);
|
||||
}
|
||||
SECTION("an empty argument") {
|
||||
REQUIRE(resolve_cli_input_path("").empty());
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,289 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <cmath>
|
||||
|
||||
#include "libslic3r/BoundingBox.hpp"
|
||||
#include "libslic3r/ClipperUtils.hpp"
|
||||
#include "libslic3r/GCode/WipeTower.hpp"
|
||||
#include "libslic3r/GCode/WipeTower2.hpp"
|
||||
#include "libslic3r/Print.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
using Catch::Matchers::WithinAbs;
|
||||
|
||||
// A Bambu P1S project that reproduced the off-plate brim: two PLAs priming 30 and 45 mm3 in
|
||||
// separate adhesiveness categories on a 35 mm tower, 0.21 mm layers, 0.4 nozzle (0.5 mm lines),
|
||||
// 150 % infill gap (0.75 mm line pitch), rib width 8, 16 mm tall.
|
||||
static std::vector<WipeTower::PurgeEstimate> cube_purges(int first_category = 100)
|
||||
{
|
||||
return {{30.f, first_category}, {45.f, 0}};
|
||||
}
|
||||
|
||||
TEST_CASE("Cone base polygon bulges past the body box", "[WipeTower]") {
|
||||
// Zero angle: plain body box.
|
||||
const Polygon box = WipeTower2::cone_base_polygon(35., 20., 100., 0.);
|
||||
CHECK(box.points.size() == 4);
|
||||
CHECK(get_extents(box).size() == Point::new_scale(Vec2d(35., 20.)));
|
||||
// A 25-degree cone on a 100 mm tower: base radius R = tan(12.5deg)*100 = 22.2 mm,
|
||||
// which exceeds the body half-depth, so the footprint bulges to center +- R in y
|
||||
// (support_scale keeps the x extent compressed near the body).
|
||||
const Polygon base = WipeTower2::cone_base_polygon(35., 20., 100., 25.);
|
||||
const BoundingBox bb = get_extents(base);
|
||||
const double R = std::tan(25. / 2. * M_PI / 180.) * 100.;
|
||||
CHECK_THAT(unscaled(bb.min.y()), WithinAbs(10. - R, 0.1));
|
||||
CHECK_THAT(unscaled(bb.max.y()), WithinAbs(10. + R, 0.1));
|
||||
// The footprint always contains the body box.
|
||||
CHECK(diff(Polygons{box}, Polygons{base}).empty());
|
||||
}
|
||||
|
||||
TEST_CASE("Type1 block-stack depth quantizes each purge to whole lines", "[WipeTower]") {
|
||||
// A 0.5 mm line at 0.21 mm carries 0.0955 mm3 per mm, so across the 34 mm between the
|
||||
// perimeters 30 mm3 is 10 lines and 45 mm3 is 14: 7.5 + 10.5 at the 0.75 mm pitch behind
|
||||
// one perimeter width. The generated mesh of the project measured exactly this.
|
||||
CHECK_THAT(WipeTower::estimate_tower_blocks_depth(cube_purges(), 35.f, 0.21f, 0.4f, 1.5f), WithinAbs(18.5f, 0.01f));
|
||||
// Sharing one category, a layer can never purge into every filament (one of them starts
|
||||
// the layer), so the block is sized by its worst layer and the 10-line purge drops out.
|
||||
CHECK_THAT(WipeTower::estimate_tower_blocks_depth(cube_purges(0), 35.f, 0.21f, 0.4f, 1.5f), WithinAbs(11.0f, 0.01f));
|
||||
CHECK_THAT(WipeTower::estimate_tower_blocks_depth({}, 35.f, 0.2f, 0.4f, 1.f), WithinAbs(0.f, 1e-6f));
|
||||
// A width narrower than two perimeter widths cannot hold purge lines.
|
||||
CHECK_THAT(WipeTower::estimate_tower_blocks_depth({{45.f, 0}}, 0.9f, 0.2f, 0.4f, 1.f), WithinAbs(0.f, 1e-6f));
|
||||
}
|
||||
|
||||
TEST_CASE("A nozzle change adds its ramming lines to the block", "[WipeTower]") {
|
||||
// 10 mm of 1.75 mm filament (24.05 mm3) laid as 1.0 mm nozzle-change lines at 0.2 mm
|
||||
// (0.1914 mm2 each) is 125.7 mm; across the 48.5 mm available that is 3 lines of 1.0 mm.
|
||||
std::vector<WipeTower::PurgeEstimate> purges{{100.f, 0}, {100.f, 0}};
|
||||
const float without_change = WipeTower::estimate_tower_blocks_depth(purges, 50.f, 0.2f, 0.4f, 1.f);
|
||||
purges.front().filament_change_length = 10.f;
|
||||
CHECK_THAT(WipeTower::estimate_tower_blocks_depth(purges, 50.f, 0.2f, 0.4f, 1.f) - without_change, WithinAbs(3.f, 1e-4f));
|
||||
}
|
||||
|
||||
TEST_CASE("Rib tower footprint estimate covers the generated footprint", "[WipeTower]") {
|
||||
// The generated first-layer wall bbox of the project measured 29.56 mm from the sliced
|
||||
// G-code; the volume-only estimate said 23.585 mm.
|
||||
const float side = WipeTower::estimate_rib_tower_bbox_side(cube_purges(), 35.f, 0.21f, 0.4f, 1.5f, 8.f, 0.f, 16.f);
|
||||
CHECK(side >= 29.56f);
|
||||
CHECK(side <= 29.56f + 4.f); // without grossly over-reserving plate space
|
||||
// Separate categories stack their blocks, so the footprint must not shrink when they differ.
|
||||
CHECK(side >= WipeTower::estimate_rib_tower_bbox_side(cube_purges(0), 35.f, 0.21f, 0.4f, 1.5f, 8.f, 0.f, 16.f));
|
||||
CHECK_THAT(WipeTower::estimate_rib_tower_bbox_side({}, 35.f, 0.2f, 0.4f, 1.f, 8.f, 0.f, 16.f), WithinAbs(0.f, 1e-6f));
|
||||
}
|
||||
|
||||
TEST_CASE("Rib footprint extends the ribs, not the body, below the stability minimum", "[WipeTower]") {
|
||||
// A 10 mm body under a 90 mm print: the ribs stretch to the minimum depth's diagonal, and
|
||||
// the rib width is capped at half the body, so the square grows to minimum + 5 / sqrt(2).
|
||||
const float min_depth = WipeTower::get_limit_depth_by_height(90.f);
|
||||
REQUIRE(min_depth > 10.f);
|
||||
CHECK_THAT(WipeTower::rib_footprint_side(10.f, 10.f, 8.f, 0.f, 90.f), WithinAbs(min_depth + 5.f / std::sqrt(2.f), 1e-4f));
|
||||
// The extra rib length runs along the diagonal, so it shows as its projection on each axis.
|
||||
const float plain = WipeTower::rib_footprint_side(30.f, 30.f, 8.f, 0.f, 5.f);
|
||||
CHECK_THAT(plain, WithinAbs(30.f + 8.f / std::sqrt(2.f), 1e-4f));
|
||||
CHECK_THAT(WipeTower::rib_footprint_side(30.f, 30.f, 8.f, 4.f, 5.f) - plain, WithinAbs(4.f / std::sqrt(2.f), 1e-4f));
|
||||
// A negative extra length cannot pull the ribs inside the diagonal.
|
||||
CHECK_THAT(WipeTower::rib_footprint_side(30.f, 30.f, 8.f, -4.f, 5.f), WithinAbs(plain, 1e-4f));
|
||||
CHECK_THAT(WipeTower::rib_footprint_side(0.f, 30.f, 8.f, 0.f, 5.f), WithinAbs(0.f, 1e-6f));
|
||||
}
|
||||
|
||||
TEST_CASE("Brim width estimate matches each generator's loop quantization", "[WipeTower]") {
|
||||
// 3 mm configured, 0.4 nozzle, 0.2 first layer: 0.4571 mm spacing, 7 loops. WipeTower2
|
||||
// prints and reports the 7 loops; WipeTower reports half a spacing of line width on top.
|
||||
const float spacing = 0.5f - 0.2f * float(1. - M_PI_4);
|
||||
CHECK_THAT(WipeTower::estimate_brim_real_width(3.f, 0.4f, 0.2f, true), WithinAbs(7.f * spacing, 1e-4f));
|
||||
CHECK_THAT(WipeTower::estimate_brim_real_width(3.f, 0.4f, 0.2f, false), WithinAbs(7.5f * spacing, 1e-4f));
|
||||
CHECK_THAT(WipeTower::estimate_brim_real_width(0.f, 0.4f, 0.2f, true), WithinAbs(0.f, 1e-6f));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// "No sparse layers": the compaction rule and the clearance it demands of the plate.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
// A square of side mm centred on (cx, cy), in bed coordinates.
|
||||
static Polygon centered_square(double cx, double cy, double side)
|
||||
{
|
||||
const double h = 0.5 * side;
|
||||
Polygon poly;
|
||||
poly.points = {Point::new_scale(cx - h, cy - h), Point::new_scale(cx + h, cy - h),
|
||||
Point::new_scale(cx + h, cy + h), Point::new_scale(cx - h, cy + h)};
|
||||
return poly;
|
||||
}
|
||||
|
||||
static WipeTower::ToolChangeResult make_tcr(int initial_tool, int new_tool, float layer_height)
|
||||
{
|
||||
WipeTower::ToolChangeResult tcr{};
|
||||
tcr.initial_tool = initial_tool;
|
||||
tcr.new_tool = new_tool;
|
||||
tcr.layer_height = layer_height;
|
||||
return tcr;
|
||||
}
|
||||
|
||||
// A 20 mm square tower at the bed origin, no spiral z-hop, so the keep-out zone is the bare
|
||||
// footprint and every distance below is one the test sets.
|
||||
static PrintConfig clearance_config()
|
||||
{
|
||||
PrintConfig cfg;
|
||||
cfg.extruder_clearance_radius.value = 40.;
|
||||
cfg.extruder_clearance_dist_to_rod.value = 20.;
|
||||
cfg.extruder_clearance_height_to_rod.value = 25.;
|
||||
cfg.extruder_clearance_height_to_lid.value = 120.;
|
||||
cfg.nozzle_height.value = 5.;
|
||||
cfg.nozzle_diameter.values = {0.4};
|
||||
cfg.z_hop.values = {0.};
|
||||
cfg.travel_slope.values = {3.};
|
||||
return cfg;
|
||||
}
|
||||
|
||||
TEST_CASE("Sparse layers are skipped only when nothing else needs a tower on every layer", "[WipeTower][NoSparseLayers]") {
|
||||
PrintConfig cfg;
|
||||
cfg.timelapse_type.value = TimelapseType::tlTraditional;
|
||||
cfg.enable_wrapping_detection.value = false;
|
||||
|
||||
cfg.wipe_tower_no_sparse_layers.value = false;
|
||||
CHECK_FALSE(wipe_tower_sparse_layers_skipped(cfg));
|
||||
cfg.wipe_tower_no_sparse_layers.value = true;
|
||||
CHECK(wipe_tower_sparse_layers_skipped(cfg));
|
||||
|
||||
// Both park the nozzle on the tower every layer, so no layer is ever dropped and the option
|
||||
// must read as off everywhere rather than compact in one place and not another.
|
||||
cfg.timelapse_type.value = TimelapseType::tlSmooth;
|
||||
CHECK_FALSE(wipe_tower_sparse_layers_skipped(cfg));
|
||||
cfg.timelapse_type.value = TimelapseType::tlTraditional;
|
||||
cfg.enable_wrapping_detection.value = true;
|
||||
CHECK_FALSE(wipe_tower_sparse_layers_skipped(cfg));
|
||||
}
|
||||
|
||||
TEST_CASE("A planned layer is sparse only when its single tool change keeps the filament", "[WipeTower][NoSparseLayers]") {
|
||||
CHECK(wipe_tower_layer_is_sparse({make_tcr(1, 1, 0.2f)}));
|
||||
CHECK_FALSE(wipe_tower_layer_is_sparse({make_tcr(0, 1, 0.2f)}));
|
||||
// A second entry means the layer carries real work whatever the tools are.
|
||||
CHECK_FALSE(wipe_tower_layer_is_sparse({make_tcr(1, 1, 0.2f), make_tcr(1, 1, 0.2f)}));
|
||||
CHECK_FALSE(wipe_tower_layer_is_sparse({}));
|
||||
}
|
||||
|
||||
TEST_CASE("The compacted tower falls one layer height behind the object per sparse layer", "[WipeTower][NoSparseLayers]") {
|
||||
// Five 0.2 mm layers off a 0.1 mm z offset, the middle two sparse. The object reaches
|
||||
// 0.1 + 5 * 0.2 = 1.1; the tower only grows on the three printed layers, so it ends at
|
||||
// 0.1 + 3 * 0.2 = 0.7 and a sparse layer carries the previous value rather than its own.
|
||||
const std::vector<std::vector<WipeTower::ToolChangeResult>> tool_changes{
|
||||
{make_tcr(0, 1, 0.2f)}, {make_tcr(1, 1, 0.2f)}, {make_tcr(1, 1, 0.2f)},
|
||||
{make_tcr(1, 0, 0.2f)}, {make_tcr(0, 1, 0.2f)}};
|
||||
|
||||
const std::vector<float> tower_z = compute_compacted_wipe_tower_z(tool_changes, 0.1f);
|
||||
REQUIRE(tower_z.size() == tool_changes.size());
|
||||
CHECK_THAT(tower_z[0], WithinAbs(0.3f, 1e-5f));
|
||||
CHECK_THAT(tower_z[1], WithinAbs(0.3f, 1e-5f));
|
||||
CHECK_THAT(tower_z[2], WithinAbs(0.3f, 1e-5f));
|
||||
CHECK_THAT(tower_z[3], WithinAbs(0.5f, 1e-5f));
|
||||
CHECK_THAT(tower_z[4], WithinAbs(0.7f, 1e-5f));
|
||||
CHECK_THAT(1.1f - tower_z.back(), WithinAbs(2 * 0.2f, 1e-5f));
|
||||
|
||||
// Without a base the tower starts at the bed, and an empty layer carries over like a sparse one.
|
||||
const std::vector<float> no_offset = compute_compacted_wipe_tower_z({{make_tcr(0, 1, 0.2f)}, {}}, 0.f);
|
||||
CHECK_THAT(no_offset[0], WithinAbs(0.2f, 1e-5f));
|
||||
CHECK_THAT(no_offset[1], WithinAbs(0.2f, 1e-5f));
|
||||
}
|
||||
|
||||
TEST_CASE("The tower keep-out zone grows by the spiral z-hop envelope", "[WipeTower][NoSparseLayers]") {
|
||||
PrintConfig cfg = clearance_config();
|
||||
const Polygon footprint = centered_square(0., 0., 20.);
|
||||
|
||||
// No lift, no envelope: the zone works on the bare footprint.
|
||||
CHECK_THAT(unscaled(compacted_wipe_tower_zone(cfg, footprint).hull.bounding_box().max.x()), WithinAbs(10., 1e-6));
|
||||
|
||||
// A spiral lift leaves the outline at low z, so it counts as tower. The circle reaches
|
||||
// 2 * lift / (2*pi*atan(slope)) past the outline, matching GCodeWriter: 2*2/(2*pi*atan(3)) = 0.51 mm.
|
||||
cfg.z_hop.values = {2.};
|
||||
const CompactedTowerZone lifted = compacted_wipe_tower_zone(cfg, footprint);
|
||||
CHECK_THAT(unscaled(lifted.hull.bounding_box().max.x()), WithinAbs(10.51, 0.02));
|
||||
CHECK_THAT(unscaled(lifted.hull.bounding_box().min.y()), WithinAbs(-10.51, 0.02));
|
||||
CHECK(diff(Polygons{footprint}, Polygons{lifted.hull}).empty());
|
||||
|
||||
// z_hop is capped at 5 mm by the option, so a taller lift cannot widen the zone further.
|
||||
cfg.z_hop.values = {10.};
|
||||
const double capped = unscaled(compacted_wipe_tower_zone(cfg, footprint).hull.bounding_box().max.x());
|
||||
CHECK_THAT(capped, WithinAbs(10. + 2. * 5. / (2. * M_PI * std::atan(3.)), 0.02));
|
||||
|
||||
// The rod sweeps the whole X axis, so its band is the tower's y span plus half the rod offset.
|
||||
CHECK_THAT(unscaled(lifted.bbox_rod.max.y()), WithinAbs(10.51 + 10., 0.02));
|
||||
}
|
||||
|
||||
TEST_CASE("An object beside a compacted tower is limited by the nearest part of the toolhead", "[WipeTower][NoSparseLayers]") {
|
||||
const PrintConfig cfg = clearance_config();
|
||||
const CompactedTowerZone zone = compacted_wipe_tower_zone(cfg, centered_square(0., 0., 20.));
|
||||
|
||||
// Each side carries half its clearance less 0.1 mm slack, so the two outlines meet when the
|
||||
// objects are a full clearance apart: 2 * (4 - 0.2) / 2 = 3.8 mm for the bare nozzle cone,
|
||||
// 2 * (40 - 0.2) / 2 = 39.8 mm for the head body. A 10 mm object at x leaves a gap of x - 15.
|
||||
const double tall = 50., shortish = 3.;
|
||||
|
||||
// Gap 1 mm, inside the nozzle cone: the object may not rise above the tower at all.
|
||||
const CompactedTowerClearance touching = compacted_wipe_tower_clearance(cfg, zone, centered_square(16., 0., 10.), tall);
|
||||
CHECK_THAT(touching.allowed_rise, WithinAbs(0., 1e-9));
|
||||
|
||||
// Gap 10 mm: clear of the cone but inside the head body, which starts at nozzle_height.
|
||||
const CompactedTowerClearance near_body = compacted_wipe_tower_clearance(cfg, zone, centered_square(25., 0., 10.), tall);
|
||||
CHECK(near_body.near_body);
|
||||
CHECK_THAT(near_body.allowed_rise, WithinAbs(5., 1e-9));
|
||||
CHECK_THAT(near_body.body_clearance, WithinAbs(40., 1e-9));
|
||||
|
||||
// The same spot, but an object that never rises past the cone. The body sits above the cone, so
|
||||
// it cannot reach this object however close it stands, and only the narrow tier applies.
|
||||
const CompactedTowerClearance low = compacted_wipe_tower_clearance(cfg, zone, centered_square(25., 0., 10.), shortish);
|
||||
CHECK_FALSE(low.near_body);
|
||||
CHECK_THAT(low.body_clearance, WithinAbs(4., 1e-9));
|
||||
CHECK_THAT(low.allowed_rise, WithinAbs(25., 1e-9));
|
||||
|
||||
// Gap 55 mm, clear of the head entirely: the rod is the obstacle, since the object shares the
|
||||
// tower's y band and the rod spans the whole x axis however far apart the two stand.
|
||||
const CompactedTowerClearance far_in_band = compacted_wipe_tower_clearance(cfg, zone, centered_square(70., 0., 10.), tall);
|
||||
CHECK_FALSE(far_in_band.near_body);
|
||||
CHECK_THAT(far_in_band.far_clearance, WithinAbs(25., 1e-9));
|
||||
CHECK_THAT(far_in_band.allowed_rise, WithinAbs(25., 1e-9));
|
||||
|
||||
// Out of the band the rod passes over it and only the lid is left.
|
||||
const CompactedTowerClearance out_of_band = compacted_wipe_tower_clearance(cfg, zone, centered_square(70., 60., 10.), tall);
|
||||
CHECK_THAT(out_of_band.allowed_rise, WithinAbs(120., 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("The ring drawn around the tower meets the outline drawn around an offender", "[WipeTower][NoSparseLayers]") {
|
||||
const PrintConfig cfg = clearance_config();
|
||||
const CompactedTowerZone zone = compacted_wipe_tower_zone(cfg, centered_square(0., 0., 20.));
|
||||
|
||||
// What the plater draws has to be what the check tested, otherwise a user moves an object until
|
||||
// the outlines part and slicing still refuses the plate. Both halves of the 3.8 mm nozzle
|
||||
// clearance: at a 3 mm gap the rings overlap and the rise limit is zero, at 5 mm neither holds.
|
||||
for (const auto &c : {std::make_pair(18., true), std::make_pair(20., false)}) {
|
||||
DYNAMIC_SECTION("object at x = " << c.first) {
|
||||
const Polygon hull = centered_square(c.first, 0., 10.);
|
||||
const CompactedTowerClearance clearance = compacted_wipe_tower_clearance(cfg, zone, hull, 3.);
|
||||
const Polygons rings = compacted_wipe_tower_rings(zone, compacted_tower_body_tier(clearance));
|
||||
const Polygon outline = compacted_wipe_tower_offender_outline(hull, clearance.body_clearance);
|
||||
const bool outlines_meet = ! intersection(rings, Polygons{outline}).empty();
|
||||
const bool rise_denied = clearance.allowed_rise < EPSILON;
|
||||
CHECK(outlines_meet == c.second);
|
||||
CHECK(rise_denied == c.second);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Only the keep-out ring an object is measured against is drawn", "[WipeTower][NoSparseLayers]") {
|
||||
const PrintConfig cfg = clearance_config();
|
||||
const CompactedTowerZone zone = compacted_wipe_tower_zone(cfg, centered_square(0., 0., 20.));
|
||||
|
||||
// Drawing the wide ring when no object is judged on it would show a keep-out zone the check can
|
||||
// never trip, so it is added only once some object reaches past the nozzle cone.
|
||||
CHECK(compacted_wipe_tower_rings(zone, false).size() == zone.grown_nozzle.size());
|
||||
CHECK(compacted_wipe_tower_rings(zone, true).size() == zone.grown_nozzle.size() + zone.grown_body.size());
|
||||
CHECK_THAT(unscaled(get_extents(zone.grown_nozzle).max.x()), WithinAbs(10. + 0.5 * (4. - 0.2), 0.02));
|
||||
CHECK_THAT(unscaled(get_extents(zone.grown_body).max.x()), WithinAbs(10. + 0.5 * (40. - 0.2), 0.02));
|
||||
}
|
||||
|
||||
TEST_CASE("Footprint padding covers the brim and the extrusion half width on each side", "[WipeTower][NoSparseLayers]") {
|
||||
// A nominal outline hulls extrusion centre lines and is re-centred once the real wall is known,
|
||||
// so a line width per side on top of the brim is what keeps an estimate enclosing the real tower.
|
||||
const PrintConfig cfg = clearance_config();
|
||||
CHECK_THAT(compacted_tower_footprint_padding(cfg, 2.), WithinAbs(2. + 2. * 0.4, 1e-9));
|
||||
CHECK_THAT(compacted_tower_footprint_padding(cfg, 0.), WithinAbs(2. * 0.4, 1e-9));
|
||||
// Callers whose outline already carries the brim pass zero, and a negative one cannot shrink it.
|
||||
CHECK_THAT(compacted_tower_footprint_padding(cfg, -5.), WithinAbs(2. * 0.4, 1e-9));
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include "libslic3r/BoundingBox.hpp"
|
||||
#include "libslic3r/ClipperUtils.hpp"
|
||||
#include "libslic3r/GCode/WipeTower.hpp"
|
||||
#include "libslic3r/GCode/WipeTower2.hpp"
|
||||
#include "libslic3r/GCode/WipeTowerEstimate.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <numeric>
|
||||
#include <string>
|
||||
|
||||
using namespace Slic3r;
|
||||
using Catch::Matchers::WithinAbs;
|
||||
|
||||
// Rectangle wall, one nozzle, 100 mm3 prime volume on a 50 mm wide tower at 0.2 mm layers: one
|
||||
// purge is 10 mm of depth. The flush matrix is off here; the shipped-default case covers it.
|
||||
// Built as PresetBundle::full_config builds the GUI's: apply() creates each enum as a
|
||||
// ConfigOptionEnumGeneric, where full_print_config() would clone the static defaults'
|
||||
// ConfigOptionEnum<T>. The estimate has to read either.
|
||||
static DynamicPrintConfig preset_shaped_defaults()
|
||||
{
|
||||
DynamicPrintConfig config;
|
||||
config.apply(FullPrintConfig::defaults());
|
||||
return config;
|
||||
}
|
||||
|
||||
static DynamicPrintConfig make_config(const char *wall_type = "rectangle")
|
||||
{
|
||||
DynamicPrintConfig config = preset_shaped_defaults();
|
||||
config.set_key_value("prime_tower_width", new ConfigOptionFloat(50.));
|
||||
config.set_key_value("prime_volume", new ConfigOptionFloat(100.));
|
||||
config.set_key_value("filament_prime_volume", new ConfigOptionFloats({100.}));
|
||||
config.set_key_value("filament_adhesiveness_category", new ConfigOptionInts({0}));
|
||||
config.set_key_value("prime_tower_infill_gap", new ConfigOptionPercent(100.));
|
||||
config.set_key_value("wipe_tower_extra_spacing", new ConfigOptionPercent(100.));
|
||||
config.set_key_value("prime_tower_brim_width", new ConfigOptionFloat(3.));
|
||||
config.set_deserialize_strict("wipe_tower_wall_type", wall_type);
|
||||
config.set_key_value("wipe_tower_rib_width", new ConfigOptionFloat(8.));
|
||||
config.set_key_value("wipe_tower_extra_rib_length", new ConfigOptionFloat(0.));
|
||||
config.set_key_value("nozzle_diameter", new ConfigOptionFloats({0.4}));
|
||||
config.set_key_value("initial_layer_print_height", new ConfigOptionFloat(0.2));
|
||||
config.set_deserialize_strict("timelapse_type", "0");
|
||||
config.set_key_value("enable_wrapping_detection", new ConfigOptionBool(false));
|
||||
config.set_key_value("raft_layers", new ConfigOptionInt(0));
|
||||
config.set_key_value("purge_in_prime_tower", new ConfigOptionBool(false));
|
||||
config.set_key_value("single_extruder_multi_material", new ConfigOptionBool(false));
|
||||
return config;
|
||||
}
|
||||
|
||||
static std::vector<unsigned int> filaments(size_t count)
|
||||
{
|
||||
std::vector<unsigned int> ids(count);
|
||||
std::iota(ids.begin(), ids.end(), 0u);
|
||||
return ids;
|
||||
}
|
||||
|
||||
// The first `count` filaments on the given planner; Type2 unless a case says otherwise.
|
||||
static WipeTowerFootprint estimate(const ConfigBase &config, size_t count, double layer_height, double height, WipeTowerType type = WipeTowerType::Type2)
|
||||
{
|
||||
return estimate_wipe_tower_footprint(config, type, filaments(count), layer_height, height);
|
||||
}
|
||||
|
||||
// What both planners print for a 3 mm brim at 0.4 nozzle and 0.2 first layer (0.4571 mm loops).
|
||||
static double printed_brim(double configured, WipeTowerType type)
|
||||
{
|
||||
return WipeTower::estimate_brim_real_width(float(configured), 0.4f, 0.2f, type == WipeTowerType::Type2);
|
||||
}
|
||||
|
||||
TEST_CASE("A rectangle wall tower is sized by the purge volume", "[WipeTowerEstimate]") {
|
||||
const DynamicPrintConfig config = make_config();
|
||||
// Three filaments purge twice per layer; a 5 mm object keeps the stability floor at 5 mm.
|
||||
const WipeTowerFootprint fp = estimate(config, 3, 0.2, 5.);
|
||||
CHECK_THAT(fp.width, WithinAbs(50., 1e-9));
|
||||
CHECK_THAT(fp.depth, WithinAbs(20., 1e-9));
|
||||
CHECK_THAT(fp.height, WithinAbs(5., 1e-9));
|
||||
CHECK_THAT(fp.brim_width, WithinAbs(printed_brim(3., WipeTowerType::Type2), 1e-6));
|
||||
// Thinner layers need more depth for the same volume.
|
||||
CHECK_THAT(estimate(config, 3, 0.1, 5.).depth, WithinAbs(40., 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Each planner spaces its purge lines by its own option", "[WipeTowerEstimate]") {
|
||||
// Type2 reads wipe_tower_extra_spacing and Type1 prime_tower_infill_gap; neither sees the
|
||||
// other's key. Type2's extra flow cancels out of its depth.
|
||||
DynamicPrintConfig config = make_config();
|
||||
config.set_key_value("wipe_tower_extra_flow", new ConfigOptionPercent(250.));
|
||||
CHECK_THAT(estimate(config, 3, 0.2, 5.).depth, WithinAbs(20., 1e-9));
|
||||
config.set_key_value("wipe_tower_extra_spacing", new ConfigOptionPercent(150.));
|
||||
CHECK_THAT(estimate(config, 3, 0.2, 5.).depth, WithinAbs(30., 1e-9));
|
||||
const double type1_spaced = estimate(config, 3, 0.2, 5., WipeTowerType::Type1).depth;
|
||||
config.set_key_value("prime_tower_infill_gap", new ConfigOptionPercent(150.));
|
||||
CHECK_THAT(estimate(config, 3, 0.2, 5.).depth, WithinAbs(30., 1e-9));
|
||||
// Type1 stacks whole lines behind one 0.5 mm perimeter width, so only the stack scales.
|
||||
CHECK_THAT(estimate(config, 3, 0.2, 5., WipeTowerType::Type1).depth - 0.5, WithinAbs(1.5 * (type1_spaced - 0.5), 1e-6));
|
||||
}
|
||||
|
||||
TEST_CASE("Type1 sizes the tower from each filament's own prime volume", "[WipeTowerEstimate]") {
|
||||
// The Bambu P1S project of the WipeTower cases: 30 and 45 mm3 in two categories on a 35 mm
|
||||
// tower at 0.21 mm, 150 % gap, is 18.5 mm of stacked blocks (11 mm sharing one category).
|
||||
DynamicPrintConfig config = make_config();
|
||||
config.set_key_value("prime_tower_width", new ConfigOptionFloat(35.));
|
||||
config.set_key_value("prime_tower_infill_gap", new ConfigOptionPercent(150.));
|
||||
config.set_key_value("initial_layer_print_height", new ConfigOptionFloat(0.21));
|
||||
config.set_key_value("filament_prime_volume", new ConfigOptionFloats({30., 45.}));
|
||||
config.set_key_value("filament_adhesiveness_category", new ConfigOptionInts({100, 0}));
|
||||
const std::vector<WipeTower::PurgeEstimate> purges{{30.f, 100}, {45.f, 0}};
|
||||
const double blocks = WipeTower::estimate_tower_blocks_depth(purges, 35.f, 0.21f, 0.4f, 1.5f);
|
||||
REQUIRE_THAT(blocks, WithinAbs(18.5, 0.01));
|
||||
CHECK_THAT(estimate(config, 2, 0.21, 5., WipeTowerType::Type1).depth, WithinAbs(blocks, 1e-4));
|
||||
// The ids pick the volumes, so their order does not matter and a lone filament has no purge.
|
||||
CHECK_THAT(estimate_wipe_tower_footprint(config, WipeTowerType::Type1, {1, 0}, 0.21, 5.).depth, WithinAbs(blocks, 1e-4));
|
||||
CHECK_THAT(estimate(config, 1, 0.21, 5., WipeTowerType::Type1).depth, WithinAbs(0., 1e-9));
|
||||
config.set_key_value("filament_adhesiveness_category", new ConfigOptionInts({0, 0}));
|
||||
CHECK_THAT(estimate(config, 2, 0.21, 5., WipeTowerType::Type1).depth, WithinAbs(11., 0.01));
|
||||
// A rib wall squares the same stack.
|
||||
config.set_deserialize_strict("wipe_tower_wall_type", "rib");
|
||||
const WipeTowerFootprint rib = estimate(config, 2, 0.21, 5., WipeTowerType::Type1);
|
||||
CHECK_THAT(rib.width, WithinAbs(rib.depth, 1e-9));
|
||||
CHECK_THAT(rib.depth, WithinAbs(WipeTower::estimate_rib_tower_bbox_side({{30.f, 0}, {45.f, 0}}, 35.f, 0.21f, 0.4f, 1.5f, 8.f, 0.f, 5.f), 1e-4));
|
||||
}
|
||||
|
||||
TEST_CASE("A second nozzle adds the ramming of one nozzle change per layer", "[WipeTowerEstimate]") {
|
||||
// Two filaments on two nozzles: the tool order crosses once per layer, and Type1 rams 10 mm
|
||||
// of filament as three 1.0 mm nozzle-change lines (see the WipeTower case).
|
||||
DynamicPrintConfig config = make_config();
|
||||
config.set_key_value("nozzle_diameter", new ConfigOptionFloats({0.4, 0.4}));
|
||||
config.set_key_value("filament_change_length", new ConfigOptionFloats({10., 10.}));
|
||||
config.set_key_value("filament_diameter", new ConfigOptionFloats({1.75, 1.75}));
|
||||
config.set_key_value("filament_map", new ConfigOptionInts({1, 1}));
|
||||
const double same_nozzle = estimate(config, 2, 0.2, 5., WipeTowerType::Type1).depth;
|
||||
config.set_key_value("filament_map", new ConfigOptionInts({1, 2}));
|
||||
CHECK_THAT(estimate(config, 2, 0.2, 5., WipeTowerType::Type1).depth - same_nozzle, WithinAbs(3., 1e-4));
|
||||
}
|
||||
|
||||
TEST_CASE("The tower is sized for the first layer when it is the thinnest", "[WipeTowerEstimate]") {
|
||||
// Both planners reserve the worst layer: a 0.28 mm print with a 0.2 mm first layer needs
|
||||
// the 0.2 mm depth, while a thicker first layer changes nothing.
|
||||
DynamicPrintConfig config = make_config();
|
||||
const double at_thinnest = estimate(config, 3, 0.2, 5.).depth;
|
||||
CHECK_THAT(estimate(config, 3, 0.28, 5.).depth, WithinAbs(at_thinnest, 1e-9));
|
||||
config.set_key_value("initial_layer_print_height", new ConfigOptionFloat(0.3));
|
||||
CHECK(estimate(config, 3, 0.28, 5.).depth < at_thinnest);
|
||||
}
|
||||
|
||||
TEST_CASE("Object height sets the stability floor and the auto brim", "[WipeTowerEstimate]") {
|
||||
DynamicPrintConfig config = make_config();
|
||||
// Two filaments purge once: 10 mm, lifted to the 20 mm floor of a 100 mm tower.
|
||||
CHECK_THAT(estimate(config, 2, 0.2, 100.).depth, WithinAbs(20., 1e-9));
|
||||
config.set_key_value("prime_tower_brim_width", new ConfigOptionFloat(-1.));
|
||||
const double auto_brim = WipeTower::get_auto_brim_by_height(50.f);
|
||||
CHECK_THAT(estimate(config, 2, 0.2, 50.).brim_width, WithinAbs(printed_brim(auto_brim, WipeTowerType::Type2), 1e-6));
|
||||
CHECK_THAT(estimate(config, 2, 0.2, 50., WipeTowerType::Type1).brim_width, WithinAbs(printed_brim(auto_brim, WipeTowerType::Type1), 1e-6));
|
||||
}
|
||||
|
||||
TEST_CASE("A single filament only gets a tower when one is printed anyway", "[WipeTowerEstimate]") {
|
||||
DynamicPrintConfig config = make_config();
|
||||
CHECK_THAT(estimate(config, 1, 0.2, 100.).depth, WithinAbs(0., 1e-9));
|
||||
CHECK_THAT(estimate(config, 0, 0.2, 100.).width, WithinAbs(0., 1e-9));
|
||||
|
||||
// Wrapping detection prints a tower on the first layers whatever the filament count: the
|
||||
// Type1 planner's fixed 10 mm, the stability floor otherwise.
|
||||
config.set_key_value("enable_wrapping_detection", new ConfigOptionBool(true));
|
||||
CHECK_THAT(estimate(config, 1, 0.2, 100.).depth, WithinAbs(20., 1e-9));
|
||||
CHECK_THAT(estimate(config, 1, 0.2, 100., WipeTowerType::Type1).depth, WithinAbs(WipeTower::get_wrapping_detection_depth(), 1e-9));
|
||||
config.set_key_value("enable_wrapping_detection", new ConfigOptionBool(false));
|
||||
|
||||
// A raft is not one of them: normalize_fdm_2 clears enable_prime_tower for a plate that
|
||||
// purges one filament unless smooth timelapse or wrapping detection is on, so a raft
|
||||
// alone leaves no tower to reserve for.
|
||||
config.set_key_value("raft_layers", new ConfigOptionInt(3));
|
||||
CHECK_THAT(estimate(config, 1, 0.2, 100.).depth, WithinAbs(0., 1e-9));
|
||||
config.set_key_value("raft_layers", new ConfigOptionInt(0));
|
||||
|
||||
config.set_deserialize_strict("timelapse_type", "1");
|
||||
// A tower printed with no tool change is exactly the planner's idle depth: there is
|
||||
// nothing to purge, and WipeTower2 sizes it at the stability floor.
|
||||
CHECK_THAT(estimate(config, 1, 0.2, 100.).depth, WithinAbs(20., 1e-9));
|
||||
CHECK_THAT(estimate(config, 1, 0.2, 5.).depth, WithinAbs(WipeTower::get_limit_depth_by_height(5.f), 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("A tool change reserves a tower even with nothing to purge", "[WipeTowerEstimate]") {
|
||||
// The purge volumes are configurable down to zero, but the tool changes are still printed
|
||||
// on the tower and both planners still floor it - so the estimate has to floor it too.
|
||||
// Type1 plans per filament and already reserves one; Type2 has only the volume to go on.
|
||||
const double height = GENERATE(5., 100.);
|
||||
const float floor = WipeTower::get_limit_depth_by_height(float(height));
|
||||
const char *wall = GENERATE("rectangle", "rib");
|
||||
DynamicPrintConfig config = make_config(wall);
|
||||
config.set_key_value("prime_volume", new ConfigOptionFloat(0.));
|
||||
config.set_key_value("filament_prime_volume", new ConfigOptionFloats({0.}));
|
||||
|
||||
CHECK(estimate(config, 3, 0.2, height, WipeTowerType::Type2).depth >= floor);
|
||||
CHECK(estimate(config, 3, 0.2, height, WipeTowerType::Type1).depth >= floor);
|
||||
// Still nothing for a lone filament with no other reason.
|
||||
CHECK_THAT(estimate(config, 1, 0.2, height, WipeTowerType::Type2).depth, WithinAbs(0., 1e-9));
|
||||
CHECK_THAT(estimate(config, 1, 0.2, height, WipeTowerType::Type1).depth, WithinAbs(0., 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Both wall types agree on whether there is a tower at all", "[WipeTowerEstimate]") {
|
||||
// A wall type may only change the shape of the tower, never whether one is reserved:
|
||||
// reporting no tower for one that is built collapses the validation hull to a point.
|
||||
const double height = GENERATE(5., 100.);
|
||||
DynamicPrintConfig rect = make_config();
|
||||
DynamicPrintConfig rib = make_config("rib");
|
||||
|
||||
// No tool change and nothing else that prints a tower - neither wall type reserves one.
|
||||
CHECK_THAT(estimate(rect, 1, 0.2, height).depth, WithinAbs(0., 1e-9));
|
||||
CHECK_THAT(estimate(rib, 1, 0.2, height).depth, WithinAbs(0., 1e-9));
|
||||
|
||||
// Not even on a dual-nozzle printer, where a lone filament still needs no purge.
|
||||
rect.set_key_value("nozzle_diameter", new ConfigOptionFloats({0.4, 0.4}));
|
||||
rib.set_key_value("nozzle_diameter", new ConfigOptionFloats({0.4, 0.4}));
|
||||
CHECK_THAT(estimate(rect, 1, 0.2, height).depth, WithinAbs(0., 1e-9));
|
||||
CHECK_THAT(estimate(rib, 1, 0.2, height).depth, WithinAbs(0., 1e-9));
|
||||
|
||||
// With a tool change both reserve one, and both respect the stability floor.
|
||||
CHECK(estimate(rect, 2, 0.2, height).depth >= WipeTower::get_limit_depth_by_height(float(height)));
|
||||
CHECK(estimate(rib, 2, 0.2, height).depth >= WipeTower::get_limit_depth_by_height(float(height)));
|
||||
}
|
||||
|
||||
TEST_CASE("A rib wall squares the tower and caps the rib width", "[WipeTowerEstimate]") {
|
||||
DynamicPrintConfig config = make_config("rib");
|
||||
// sqrt(200 / 0.2) = 31.62 mm square, plus the 8 mm rib bulge along the diagonal.
|
||||
const double body = std::sqrt(1000.);
|
||||
WipeTowerFootprint fp = estimate(config, 3, 0.2, 5.);
|
||||
CHECK_THAT(fp.depth, WithinAbs(8. / std::sqrt(2.) + body, 1e-5));
|
||||
CHECK_THAT(fp.width, WithinAbs(fp.depth, 1e-9));
|
||||
// The extra rib length runs along the diagonal and grows the footprint by its projection.
|
||||
config.set_key_value("wipe_tower_extra_rib_length", new ConfigOptionFloat(4.));
|
||||
CHECK_THAT(estimate(config, 3, 0.2, 5.).depth, WithinAbs((8. + 4.) / std::sqrt(2.) + body, 1e-5));
|
||||
// A tiny tower caps the rib width at half its depth: 5 mm body, 2.5 mm rib.
|
||||
config.set_key_value("wipe_tower_extra_rib_length", new ConfigOptionFloat(0.));
|
||||
config.set_key_value("prime_volume", new ConfigOptionFloat(5.));
|
||||
CHECK_THAT(estimate(config, 2, 0.2, 5.).depth, WithinAbs(2.5 / std::sqrt(2.) + 5., 1e-5));
|
||||
}
|
||||
|
||||
TEST_CASE("Every wall and tower type is read the same from a preset and a static config", "[WipeTowerEstimate]") {
|
||||
// The GUI, arrange and the CLI pass a DynamicPrintConfig whose enums are
|
||||
// ConfigOptionEnumGeneric; Print passes a static config whose enums are ConfigOptionEnum<T>.
|
||||
// Both the wall type and the planner selection are read by value, so both give the same shape.
|
||||
const char *wall_type = GENERATE("rectangle", "cone", "rib");
|
||||
const char *tower_type = GENERATE("type1", "type2");
|
||||
DynamicPrintConfig preset = make_config(wall_type);
|
||||
preset.set_deserialize_strict("wipe_tower_type", tower_type);
|
||||
REQUIRE(dynamic_cast<const ConfigOptionEnumGeneric *>(preset.option("wipe_tower_wall_type")) != nullptr);
|
||||
|
||||
FullPrintConfig static_config;
|
||||
static_config.apply(preset, true);
|
||||
REQUIRE(static_config.wipe_tower_wall_type.serialize() == wall_type);
|
||||
REQUIRE(static_config.wipe_tower_type.serialize() == tower_type);
|
||||
|
||||
const WipeTowerType type = resolve_wipe_tower_type(preset);
|
||||
CHECK(type == (std::string(tower_type) == "type1" ? WipeTowerType::Type1 : WipeTowerType::Type2));
|
||||
CHECK(resolve_wipe_tower_type(static_config) == type);
|
||||
|
||||
// Three filaments purge twice per layer on a 5 mm object.
|
||||
const WipeTowerFootprint fp = estimate(preset, 3, 0.2, 5., type);
|
||||
const WipeTowerFootprint from_static = estimate(static_config, 3, 0.2, 5., type);
|
||||
CHECK(fp.depth > 0.);
|
||||
if (std::string(wall_type) == "rib")
|
||||
CHECK_THAT(fp.width, WithinAbs(fp.depth, 1e-9));
|
||||
else
|
||||
CHECK_THAT(fp.width, WithinAbs(50., 1e-9));
|
||||
CHECK_THAT(from_static.width, WithinAbs(fp.width, 1e-9));
|
||||
CHECK_THAT(from_static.depth, WithinAbs(fp.depth, 1e-9));
|
||||
CHECK_THAT(from_static.brim_width, WithinAbs(fp.brim_width, 1e-9));
|
||||
|
||||
// Smooth timelapse is the other enum the estimate reads: a lone filament gets a tower
|
||||
// through both storages too.
|
||||
preset.set_deserialize_strict("timelapse_type", "1");
|
||||
static_config.apply(preset, true);
|
||||
CHECK(estimate(preset, 1, 0.2, 5., type).depth > 0.);
|
||||
CHECK(estimate(static_config, 1, 0.2, 5., type).depth > 0.);
|
||||
}
|
||||
|
||||
TEST_CASE("The first-layer outline bulges only for a Type2 cone wall", "[WipeTowerEstimate]") {
|
||||
// Read off a preset-shaped config, whose enums are ConfigOptionEnumGeneric: a cast to
|
||||
// ConfigOptionEnum<T> sees no wall type there and would never find the cone.
|
||||
DynamicPrintConfig config = make_config("cone");
|
||||
config.set_key_value("wipe_tower_cone_angle", new ConfigOptionFloat(25.));
|
||||
REQUIRE(dynamic_cast<const ConfigOptionEnumGeneric *>(config.option("wipe_tower_wall_type")) != nullptr);
|
||||
const Polygon box = Polygon::new_scale({{0., 0.}, {35., 0.}, {35., 20.}, {0., 20.}});
|
||||
auto is_box = [&box](const Polygon &outline) { return diff(Polygons{outline}, Polygons{box}).empty(); };
|
||||
|
||||
// A 25-degree cone on a 100 mm tower has a 22 mm base radius, past the 10 mm half-depth.
|
||||
const Polygon cone = estimate_wipe_tower_first_layer_outline(config, WipeTowerType::Type2, 35., 20., 100.);
|
||||
CHECK(unscaled(get_extents(cone).max.y()) > 20. + 1.);
|
||||
CHECK(diff(Polygons{box}, Polygons{cone}).empty());
|
||||
// Type1 ignores the cone option, and the other wall types have no cone.
|
||||
CHECK(is_box(estimate_wipe_tower_first_layer_outline(config, WipeTowerType::Type1, 35., 20., 100.)));
|
||||
for (const char *wall_type : {"rectangle", "rib"}) {
|
||||
config.set_deserialize_strict("wipe_tower_wall_type", wall_type);
|
||||
CHECK(is_box(estimate_wipe_tower_first_layer_outline(config, WipeTowerType::Type2, 35., 20., 100.)));
|
||||
}
|
||||
// The static config Print holds gives the same outline.
|
||||
config.set_deserialize_strict("wipe_tower_wall_type", "cone");
|
||||
FullPrintConfig static_config;
|
||||
static_config.apply(config, true);
|
||||
const Polygon from_static = estimate_wipe_tower_first_layer_outline(static_config, WipeTowerType::Type2, 35., 20., 100.);
|
||||
CHECK(from_static.points == cone.points);
|
||||
}
|
||||
|
||||
TEST_CASE("A Bambu Lab printer always gets the Type1 planner", "[WipeTowerEstimate]") {
|
||||
DynamicPrintConfig config = make_config();
|
||||
config.set_deserialize_strict("wipe_tower_type", "type2");
|
||||
config.set_key_value("printer_model", new ConfigOptionString("Bambu Lab X1 Carbon"));
|
||||
CHECK(resolve_wipe_tower_type(config) == WipeTowerType::Type1);
|
||||
config.set_key_value("printer_model", new ConfigOptionString("Voron 2.4"));
|
||||
CHECK(resolve_wipe_tower_type(config) == WipeTowerType::Type2);
|
||||
config.erase("wipe_tower_type");
|
||||
CHECK(resolve_wipe_tower_type(config) == WipeTowerType::Type2);
|
||||
}
|
||||
|
||||
TEST_CASE("A dual nozzle purges every filament plus the filament change", "[WipeTowerEstimate]") {
|
||||
DynamicPrintConfig config = make_config();
|
||||
config.set_key_value("nozzle_diameter", new ConfigOptionFloats({0.4, 0.4}));
|
||||
config.set_key_value("filament_change_length", new ConfigOptionFloats({10., 10.}));
|
||||
config.set_key_value("filament_diameter", new ConfigOptionFloats({1.75, 1.75}));
|
||||
// Two purges of 100 mm3 plus one 10 mm filament change: (200 + 10 * pi * 1.75^2 / 4) / (0.2 * 50).
|
||||
const double change_volume = 10. * PI * 1.75 * 1.75 / 4.;
|
||||
CHECK_THAT(estimate(config, 2, 0.2, 5.).depth, WithinAbs((200. + change_volume) / 10., 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("The shipped defaults size the tower from the flush matrix", "[WipeTowerEstimate]") {
|
||||
// Both keys default to true, so the shipped configuration purges the flush volumes rather
|
||||
// than the prime volume, with no infill gap on top - the flush volumes already hold it.
|
||||
DynamicPrintConfig config = preset_shaped_defaults();
|
||||
REQUIRE(config.opt_bool("purge_in_prime_tower"));
|
||||
REQUIRE(config.opt_bool("single_extruder_multi_material"));
|
||||
config.set_key_value("prime_tower_width", new ConfigOptionFloat(50.));
|
||||
config.set_deserialize_strict("wipe_tower_wall_type", "rectangle");
|
||||
config.set_key_value("nozzle_diameter", new ConfigOptionFloats({0.4}));
|
||||
|
||||
const double flush_volume = WipeTower2::estimate_semm_flush_volume(config, 2);
|
||||
const double expected = std::max(double(WipeTower::get_limit_depth_by_height(5.f)), flush_volume / (0.2 * 50.));
|
||||
CHECK_THAT(estimate(config, 2, 0.2, 5.).depth, WithinAbs(expected, 1e-6));
|
||||
}
|
||||
|
||||
TEST_CASE("A config missing a tower key falls back to that key's default", "[WipeTowerEstimate]") {
|
||||
// The signature takes any ConfigBase: an absent key must read as its declared default.
|
||||
const DynamicPrintConfig full = make_config();
|
||||
DynamicPrintConfig partial = full;
|
||||
partial.erase("wipe_tower_extra_spacing");
|
||||
REQUIRE(partial.option("wipe_tower_extra_spacing") == nullptr);
|
||||
|
||||
DynamicPrintConfig defaulted = full;
|
||||
defaulted.set_key_value("wipe_tower_extra_spacing",
|
||||
print_config_def.get("wipe_tower_extra_spacing")->default_value->clone());
|
||||
CHECK_THAT(estimate(partial, 3, 0.2, 5.).depth, WithinAbs(estimate(defaulted, 3, 0.2, 5.).depth, 1e-9));
|
||||
}
|
||||
@@ -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
|
||||
@@ -53,6 +55,18 @@ elseif (APPLE)
|
||||
COMMENT "Copying Python runtime for macOS plugin host API tests"
|
||||
VERBATIM
|
||||
)
|
||||
elseif (FLATPAK)
|
||||
# Same <testdir>/python home as WIN32/APPLE; symlink since /app/libpython
|
||||
# already ships in the flatpak (the test exe links libpython3.12.so from it).
|
||||
add_custom_command(TARGET ${_TEST_NAME}_tests POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E rm -rf
|
||||
"$<TARGET_FILE_DIR:${_TEST_NAME}_tests>/python"
|
||||
COMMAND ${CMAKE_COMMAND} -E create_symlink
|
||||
"${CMAKE_PREFIX_PATH}/libpython"
|
||||
"$<TARGET_FILE_DIR:${_TEST_NAME}_tests>/python"
|
||||
COMMENT "Linking Python runtime for flatpak plugin host API tests"
|
||||
VERBATIM
|
||||
)
|
||||
endif()
|
||||
|
||||
orcaslicer_discover_tests(${_TEST_NAME}_tests)
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,4 +176,22 @@ inline void write_debug_stream([[maybe_unused]] const std::string &name, [[maybe
|
||||
#endif
|
||||
}
|
||||
|
||||
// Changes the working directory and restores the previous one on scope exit, including when an
|
||||
// assertion throws. It is process wide state shared with every other test.
|
||||
class ScopedWorkingDirectory
|
||||
{
|
||||
public:
|
||||
explicit ScopedWorkingDirectory(const boost::filesystem::path &dir)
|
||||
: m_previous(boost::filesystem::current_path())
|
||||
{
|
||||
boost::filesystem::current_path(dir);
|
||||
}
|
||||
~ScopedWorkingDirectory() { boost::system::error_code ec; boost::filesystem::current_path(m_previous, ec); }
|
||||
ScopedWorkingDirectory(const ScopedWorkingDirectory &) = delete;
|
||||
ScopedWorkingDirectory &operator=(const ScopedWorkingDirectory &) = delete;
|
||||
|
||||
private:
|
||||
boost::filesystem::path m_previous;
|
||||
};
|
||||
|
||||
#endif // SLIC3R_TEST_UTILS
|
||||
|
||||
Reference in New Issue
Block a user