From 6bcd735655f3d42e529a9e3340e78d90aa85faea Mon Sep 17 00:00:00 2001 From: tamasmeszaros Date: Mon, 16 Jul 2018 16:07:29 +0200 Subject: [PATCH] Change to firstfit selection because DJD needs further testing. --- xs/CMakeLists.txt | 21 +- xs/src/libnest2d/CMakeLists.txt | 134 +- xs/src/libnest2d/cmake_modules/FindGMP.cmake | 35 + xs/src/libnest2d/{tests => examples}/main.cpp | 60 +- xs/src/libnest2d/libnest2d.h | 8 +- xs/src/libnest2d/libnest2d/boost_alg.hpp | 35 +- .../clipper_backend/clipper_backend.cpp | 134 +- .../clipper_backend/clipper_backend.hpp | 402 +++-- xs/src/libnest2d/libnest2d/common.hpp | 15 +- xs/src/libnest2d/libnest2d/geometries_io.hpp | 18 - xs/src/libnest2d/libnest2d/geometries_nfp.hpp | 223 --- .../libnest2d/libnest2d/geometry_traits.hpp | 56 +- .../libnest2d/geometry_traits_nfp.hpp | 258 +++ xs/src/libnest2d/libnest2d/libnest2d.hpp | 61 +- .../libnest2d/libnest2d/placers/nfpplacer.hpp | 172 +- .../libnest2d/selections/djd_heuristic.hpp | 113 +- .../libnest2d/libnest2d/selections/filler.hpp | 11 +- .../libnest2d/selections/firstfit.hpp | 18 +- xs/src/libnest2d/tests/CMakeLists.txt | 16 +- xs/src/libnest2d/tests/printer_parts.cpp | 650 +++++++ xs/src/libnest2d/tests/printer_parts.h | 28 + xs/src/libnest2d/tests/test.cpp | 102 +- xs/src/libnest2d/{tests => tools}/benchmark.h | 0 xs/src/libnest2d/tools/libnfpglue.cpp | 182 ++ xs/src/libnest2d/tools/libnfpglue.hpp | 44 + xs/src/libnest2d/tools/libnfporb/LICENSE | 674 +++++++ xs/src/libnest2d/tools/libnfporb/ORIGIN | 2 + xs/src/libnest2d/tools/libnfporb/README.md | 89 + .../libnest2d/tools/libnfporb/libnfporb.hpp | 1547 +++++++++++++++++ .../libnest2d/{tests => tools}/svgtools.hpp | 18 +- xs/src/libslic3r/Model.cpp | 17 +- 31 files changed, 4317 insertions(+), 826 deletions(-) create mode 100644 xs/src/libnest2d/cmake_modules/FindGMP.cmake rename xs/src/libnest2d/{tests => examples}/main.cpp (92%) delete mode 100644 xs/src/libnest2d/libnest2d/geometries_io.hpp delete mode 100644 xs/src/libnest2d/libnest2d/geometries_nfp.hpp create mode 100644 xs/src/libnest2d/libnest2d/geometry_traits_nfp.hpp rename xs/src/libnest2d/{tests => tools}/benchmark.h (100%) create mode 100644 xs/src/libnest2d/tools/libnfpglue.cpp create mode 100644 xs/src/libnest2d/tools/libnfpglue.hpp create mode 100644 xs/src/libnest2d/tools/libnfporb/LICENSE create mode 100644 xs/src/libnest2d/tools/libnfporb/ORIGIN create mode 100644 xs/src/libnest2d/tools/libnfporb/README.md create mode 100644 xs/src/libnest2d/tools/libnfporb/libnfporb.hpp rename xs/src/libnest2d/{tests => tools}/svgtools.hpp (89%) diff --git a/xs/CMakeLists.txt b/xs/CMakeLists.txt index 5544c5c2d..976943d64 100644 --- a/xs/CMakeLists.txt +++ b/xs/CMakeLists.txt @@ -724,29 +724,12 @@ add_custom_target(pot # ############################################################################## set(LIBNEST2D_UNITTESTS ON CACHE BOOL "Force generating unittests for libnest2d") -set(LIBNEST2D_BUILD_SHARED_LIB OFF CACHE BOOL "Disable build of shared lib.") - -if(LIBNEST2D_UNITTESTS) - # If we want the libnest2d unit tests we need to build and executable with - # all the libslic3r dependencies. This is needed because the clipper library - # in the slic3r project is hacked so that it depends on the slic3r sources. - # Unfortunately, this implies that the test executable is also dependent on - # the libslic3r target. - -# add_library(libslic3r_standalone STATIC ${LIBDIR}/libslic3r/utils.cpp) -# set(LIBNEST2D_TEST_LIBRARIES -# libslic3r libslic3r_standalone nowide libslic3r_gui admesh miniz -# ${Boost_LIBRARIES} clipper ${EXPAT_LIBRARIES} ${GLEW_LIBRARIES} -# polypartition poly2tri ${TBB_LIBRARIES} ${wxWidgets_LIBRARIES} -# ${CURL_LIBRARIES} -# ) -endif() add_subdirectory(${LIBDIR}/libnest2d) target_include_directories(libslic3r PUBLIC BEFORE ${LIBNEST2D_INCLUDES}) -# Add the binpack2d main sources and link them to libslic3r -target_link_libraries(libslic3r libnest2d_static) +message(STATUS "Libnest2D Libraries: ${LIBNEST2D_LIBRARIES}") +target_link_libraries(libslic3r ${LIBNEST2D_LIBRARIES}) # ############################################################################## # Installation diff --git a/xs/src/libnest2d/CMakeLists.txt b/xs/src/libnest2d/CMakeLists.txt index 7977066c1..e16733cdd 100644 --- a/xs/src/libnest2d/CMakeLists.txt +++ b/xs/src/libnest2d/CMakeLists.txt @@ -5,8 +5,7 @@ project(Libnest2D) enable_testing() if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX) - # Update if necessary -# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-long-long -pedantic") + # Update if necessary set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-long-long ") endif() @@ -20,39 +19,37 @@ option(LIBNEST2D_UNITTESTS "If enabled, googletest framework will be downloaded and the provided unit tests will be included in the build." OFF) option(LIBNEST2D_BUILD_EXAMPLES "If enabled, examples will be built." OFF) -option(LIBNEST2D_BUILD_SHARED_LIB "Build shared library." ON) -#set(LIBNEST2D_GEOMETRIES_TARGET "" CACHE STRING -# "Build libnest2d with geometry classes implemented by the chosen target.") - -#set(libnest2D_TEST_LIBRARIES "" CACHE STRING -# "Libraries needed to compile the test executable for libnest2d.") +set(LIBNEST2D_GEOMETRIES_BACKEND "clipper" CACHE STRING + "Build libnest2d with geometry classes implemented by the chosen backend.") +set(LIBNEST2D_OPTIMIZER_BACKEND "nlopt" CACHE STRING + "Build libnest2d with optimization features implemented by the chosen backend.") set(LIBNEST2D_SRCFILES - libnest2d/libnest2d.hpp # Templates only - libnest2d.h # Exports ready made types using template arguments - libnest2d/geometry_traits.hpp - libnest2d/geometries_io.hpp - libnest2d/common.hpp - libnest2d/optimizer.hpp - libnest2d/placers/placer_boilerplate.hpp - libnest2d/placers/bottomleftplacer.hpp - libnest2d/placers/nfpplacer.hpp - libnest2d/geometries_nfp.hpp - libnest2d/selections/selection_boilerplate.hpp - libnest2d/selections/filler.hpp - libnest2d/selections/firstfit.hpp - libnest2d/selections/djd_heuristic.hpp - libnest2d/optimizers/simplex.hpp - libnest2d/optimizers/subplex.hpp - libnest2d/optimizers/genetic.hpp - libnest2d/optimizers/nlopt_boilerplate.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/libnest2d.hpp # Templates only + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d.h # Exports ready made types using template arguments + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/geometry_traits.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/common.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/optimizer.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/placers/placer_boilerplate.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/placers/bottomleftplacer.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/placers/nfpplacer.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/geometry_traits_nfp.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/selections/selection_boilerplate.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/selections/filler.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/selections/firstfit.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/selections/djd_heuristic.hpp ) -if((NOT LIBNEST2D_GEOMETRIES_TARGET) OR (LIBNEST2D_GEOMETRIES_TARGET STREQUAL "")) - message(STATUS "libnest2D backend is default") +set(LIBNEST2D_LIBRARIES "") +set(LIBNEST2D_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}) + +if(LIBNEST2D_GEOMETRIES_BACKEND STREQUAL "clipper") + + # Clipper backend is not enough on its own, it still needs some functions + # from Boost geometry if(NOT Boost_INCLUDE_DIRS_FOUND) find_package(Boost 1.58 REQUIRED) # TODO automatic download of boost geometry headers @@ -60,56 +57,63 @@ if((NOT LIBNEST2D_GEOMETRIES_TARGET) OR (LIBNEST2D_GEOMETRIES_TARGET STREQUAL "" add_subdirectory(libnest2d/clipper_backend) - set(LIBNEST2D_GEOMETRIES_TARGET ${CLIPPER_LIBRARIES}) - include_directories(BEFORE ${CLIPPER_INCLUDE_DIRS}) include_directories(${Boost_INCLUDE_DIRS}) - list(APPEND LIBNEST2D_SRCFILES libnest2d/clipper_backend/clipper_backend.cpp - libnest2d/clipper_backend/clipper_backend.hpp - libnest2d/boost_alg.hpp) - -else() - message(STATUS "Libnest2D backend is: ${LIBNEST2D_GEOMETRIES_TARGET}") + list(APPEND LIBNEST2D_SRCFILES ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/clipper_backend/clipper_backend.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/clipper_backend/clipper_backend.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/boost_alg.hpp) + list(APPEND LIBNEST2D_LIBRARIES ${CLIPPER_LIBRARIES}) + list(APPEND LIBNEST2D_HEADERS ${CLIPPER_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS_FOUND}) endif() -message(STATUS "clipper lib is: ${LIBNEST2D_GEOMETRIES_TARGET}") +if(LIBNEST2D_OPTIMIZER_BACKEND STREQUAL "nlopt") + find_package(NLopt 1.4) + if(NOT NLopt_FOUND) + message(STATUS "NLopt not found so downloading " + "and automatic build is performed...") + include(DownloadNLopt) + endif() + find_package(Threads REQUIRED) -find_package(NLopt 1.4) -if(NOT NLopt_FOUND) - message(STATUS "NLopt not found so downloading and automatic build is performed...") - include(DownloadNLopt) -endif() -find_package(Threads REQUIRED) - -add_library(libnest2d_static STATIC ${LIBNEST2D_SRCFILES} ) -target_link_libraries(libnest2d_static PRIVATE ${LIBNEST2D_GEOMETRIES_TARGET} ${NLopt_LIBS}) -target_include_directories(libnest2d_static PUBLIC ${CMAKE_SOURCE_DIR} ${NLopt_INCLUDE_DIR}) -set_target_properties(libnest2d_static PROPERTIES PREFIX "") - -if(LIBNEST2D_BUILD_SHARED_LIB) - add_library(libnest2d SHARED ${LIBNEST2D_SRCFILES} ) - target_link_libraries(libnest2d PRIVATE ${LIBNEST2D_GEOMETRIES_TARGET} ${NLopt_LIBS}) - target_include_directories(libnest2d PUBLIC ${CMAKE_SOURCE_DIR} ${NLopt_INCLUDE_DIR}) - set_target_properties(libnest2d PROPERTIES PREFIX "") + list(APPEND LIBNEST2D_SRCFILES ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/optimizers/simplex.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/optimizers/subplex.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/optimizers/genetic.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/optimizers/nlopt_boilerplate.hpp) + list(APPEND LIBNEST2D_LIBRARIES ${NLopt_LIBS} Threads::Threads) + list(APPEND LIBNEST2D_HEADERS ${NLopt_INCLUDE_DIR}) endif() -set(LIBNEST2D_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}) - -get_directory_property(hasParent PARENT_DIRECTORY) -if(hasParent) - set(LIBNEST2D_INCLUDES ${CMAKE_CURRENT_SOURCE_DIR} PARENT_SCOPE) -endif() +# Currently we are outsourcing the non-convex NFP implementation from +# libnfporb and it needs libgmp to work +#find_package(GMP) +#if(GMP_FOUND) +# list(APPEND LIBNEST2D_LIBRARIES ${GMP_LIBRARIES}) +# list(APPEND LIBNEST2D_HEADERS ${GMP_INCLUDE_DIR}) +# add_definitions(-DLIBNFP_USE_RATIONAL) +#endif() if(LIBNEST2D_UNITTESTS) add_subdirectory(tests) endif() if(LIBNEST2D_BUILD_EXAMPLES) - add_executable(example tests/main.cpp - tests/svgtools.hpp + add_executable(example examples/main.cpp +# tools/libnfpglue.hpp +# tools/libnfpglue.cpp + tools/svgtools.hpp tests/printer_parts.cpp - tests/printer_parts.h) - target_link_libraries(example libnest2d_static Threads::Threads) - target_include_directories(example PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) + tests/printer_parts.h + ${LIBNEST2D_SRCFILES}) + + + target_link_libraries(example ${LIBNEST2D_LIBRARIES}) + target_include_directories(example PUBLIC ${LIBNEST2D_HEADERS}) +endif() + +get_directory_property(hasParent PARENT_DIRECTORY) +if(hasParent) + set(LIBNEST2D_INCLUDES ${LIBNEST2D_HEADERS} PARENT_SCOPE) + set(LIBNEST2D_LIBRARIES ${LIBNEST2D_LIBRARIES} PARENT_SCOPE) endif() diff --git a/xs/src/libnest2d/cmake_modules/FindGMP.cmake b/xs/src/libnest2d/cmake_modules/FindGMP.cmake new file mode 100644 index 000000000..db173bc90 --- /dev/null +++ b/xs/src/libnest2d/cmake_modules/FindGMP.cmake @@ -0,0 +1,35 @@ +# Try to find the GMP libraries: +# GMP_FOUND - System has GMP lib +# GMP_INCLUDE_DIR - The GMP include directory +# GMP_LIBRARIES - Libraries needed to use GMP + +if (GMP_INCLUDE_DIR AND GMP_LIBRARIES) + # Force search at every time, in case configuration changes + unset(GMP_INCLUDE_DIR CACHE) + unset(GMP_LIBRARIES CACHE) +endif (GMP_INCLUDE_DIR AND GMP_LIBRARIES) + +find_path(GMP_INCLUDE_DIR NAMES gmp.h) + +if(WIN32) + find_library(GMP_LIBRARIES NAMES libgmp.a gmp gmp.lib mpir mpir.lib) +else(WIN32) + if(STBIN) + message(STATUS "STBIN: ${STBIN}") + find_library(GMP_LIBRARIES NAMES libgmp.a gmp) + else(STBIN) + find_library(GMP_LIBRARIES NAMES libgmp.so gmp) + endif(STBIN) +endif(WIN32) + +if(GMP_INCLUDE_DIR AND GMP_LIBRARIES) + set(GMP_FOUND TRUE) +endif(GMP_INCLUDE_DIR AND GMP_LIBRARIES) + +if(GMP_FOUND) + message(STATUS "Configured GMP: ${GMP_LIBRARIES}") +else(GMP_FOUND) + message(STATUS "Could NOT find GMP") +endif(GMP_FOUND) + +mark_as_advanced(GMP_INCLUDE_DIR GMP_LIBRARIES) \ No newline at end of file diff --git a/xs/src/libnest2d/tests/main.cpp b/xs/src/libnest2d/examples/main.cpp similarity index 92% rename from xs/src/libnest2d/tests/main.cpp rename to xs/src/libnest2d/examples/main.cpp index 88b958c07..3d3f30b76 100644 --- a/xs/src/libnest2d/tests/main.cpp +++ b/xs/src/libnest2d/examples/main.cpp @@ -5,13 +5,11 @@ //#define DEBUG_EXPORT_NFP #include -#include -#include "printer_parts.h" -#include "benchmark.h" -#include "svgtools.hpp" -//#include -//#include +#include "tests/printer_parts.h" +#include "tools/benchmark.h" +#include "tools/svgtools.hpp" +//#include "tools/libnfpglue.hpp" using namespace libnest2d; using ItemGroup = std::vector>; @@ -37,10 +35,22 @@ std::vector& stegoParts() { return _parts(ret, STEGOSAUR_POLYGONS); } +std::vector& prusaExParts() { + static std::vector ret; + if(ret.empty()) { + ret.reserve(PRINTER_PART_POLYGONS_EX.size()); + for(auto& p : PRINTER_PART_POLYGONS_EX) { + ret.emplace_back(p.Contour, p.Holes); + } + } + return ret; +} + void arrangeRectangles() { using namespace libnest2d; const int SCALE = 1000000; +// const int SCALE = 1; std::vector rects = { {80*SCALE, 80*SCALE}, {60*SCALE, 90*SCALE}, @@ -506,38 +516,59 @@ void arrangeRectangles() { }, }; + std::vector proba = { + { + { {0, 0}, {20, 20}, {40, 0}, {0, 0} } + }, + { + { {0, 100}, {50, 60}, {100, 100}, {50, 0}, {0, 100} } + + }, + }; + std::vector input; // input.insert(input.end(), prusaParts().begin(), prusaParts().end()); +// input.insert(input.end(), prusaExParts().begin(), prusaExParts().end()); // input.insert(input.end(), stegoParts().begin(), stegoParts().end()); // input.insert(input.end(), rects.begin(), rects.end()); +// input.insert(input.end(), proba.begin(), proba.end()); input.insert(input.end(), crasher.begin(), crasher.end()); Box bin(250*SCALE, 210*SCALE); Coord min_obj_distance = 6*SCALE; - using Packer = Arranger; + using Placer = NfpPlacer; + using Packer = Arranger; Packer arrange(bin, min_obj_distance); Packer::PlacementConfig pconf; - pconf.alignment = NfpPlacer::Config::Alignment::CENTER; + pconf.alignment = Placer::Config::Alignment::CENTER; pconf.rotations = {0.0/*, Pi/2.0, Pi, 3*Pi/2*/}; - pconf.object_function = [&bin](NfpPlacer::Pile pile, double area, + pconf.object_function = [&bin](Placer::Pile pile, double area, double norm, double penality) { auto bb = ShapeLike::boundingBox(pile); - double score = (2*bb.width() + 2*bb.height()) / norm; + double diameter = PointLike::distance(bb.minCorner(), + bb.maxCorner()); + + // We will optimize to the diameter of the circle around the bounding + // box and use the norming factor to get rid of the physical dimensions + double score = diameter / norm; + + // If it does not fit into the print bed we will beat it + // with a large penality if(!NfpPlacer::wouldFit(bb, bin)) score = 2*penality - score; return score; }; Packer::SelectionConfig sconf; - sconf.allow_parallel = true; - sconf.force_parallel = true; - sconf.try_reverse_order = true; +// sconf.allow_parallel = false; +// sconf.force_parallel = false; +// sconf.try_reverse_order = true; arrange.configure(pconf, sconf); @@ -610,10 +641,9 @@ void arrangeRectangles() { svgw.save("out"); } - - int main(void /*int argc, char **argv*/) { arrangeRectangles(); // findDegenerateCase(); + return EXIT_SUCCESS; } diff --git a/xs/src/libnest2d/libnest2d.h b/xs/src/libnest2d/libnest2d.h index dff7009ee..1e0a98f6a 100644 --- a/xs/src/libnest2d/libnest2d.h +++ b/xs/src/libnest2d/libnest2d.h @@ -5,6 +5,10 @@ // for now we set it statically to clipper backend #include +// We include the stock optimizers for local and global optimization +#include // Local subplex for NfpPlacer +#include // Genetic for min. bounding box + #include #include #include @@ -31,7 +35,9 @@ using DJDHeuristic = strategies::_DJDHeuristic; using NfpPlacer = strategies::_NofitPolyPlacer; using BottomLeftPlacer = strategies::_BottomLeftPlacer; -using NofitPolyPlacer = strategies::_NofitPolyPlacer; + +//template +//using NofitPolyPlacer = strategies::_NofitPolyPlacer; } diff --git a/xs/src/libnest2d/libnest2d/boost_alg.hpp b/xs/src/libnest2d/libnest2d/boost_alg.hpp index 8cd126f68..a50b397d3 100644 --- a/xs/src/libnest2d/libnest2d/boost_alg.hpp +++ b/xs/src/libnest2d/libnest2d/boost_alg.hpp @@ -139,7 +139,7 @@ template<> struct indexed_access { }; /* ************************************************************************** */ -/* Segement concept adaptaion *********************************************** */ +/* Segment concept adaptaion ************************************************ */ /* ************************************************************************** */ template<> struct tag { @@ -461,21 +461,19 @@ inline bp2d::Shapes Nfp::merge(const bp2d::Shapes& shapes, } #endif -#ifndef DISABLE_BOOST_MINKOWSKI_ADD -template<> -inline PolygonImpl& Nfp::minkowskiAdd(PolygonImpl& sh, - const PolygonImpl& /*other*/) -{ - return sh; -} -#endif +//#ifndef DISABLE_BOOST_MINKOWSKI_ADD +//template<> +//inline PolygonImpl& Nfp::minkowskiAdd(PolygonImpl& sh, +// const PolygonImpl& /*other*/) +//{ +// return sh; +//} +//#endif #ifndef DISABLE_BOOST_SERIALIZE -template<> -inline std::string ShapeLike::serialize( +template<> inline std::string ShapeLike::serialize( const PolygonImpl& sh, double scale) { - std::stringstream ss; std::string style = "fill: none; stroke: black; stroke-width: 1px;"; @@ -484,14 +482,27 @@ inline std::string ShapeLike::serialize( using Polygonf = model::polygon; Polygonf::ring_type ring; + Polygonf::inner_container_type holes; ring.reserve(ShapeLike::contourVertexCount(sh)); for(auto it = ShapeLike::cbegin(sh); it != ShapeLike::cend(sh); it++) { auto& v = *it; ring.emplace_back(getX(v)*scale, getY(v)*scale); }; + + auto H = ShapeLike::holes(sh); + for(PathImpl& h : H ) { + Polygonf::ring_type hf; + for(auto it = h.begin(); it != h.end(); it++) { + auto& v = *it; + hf.emplace_back(getX(v)*scale, getY(v)*scale); + }; + holes.push_back(hf); + } + Polygonf poly; poly.outer() = ring; + poly.inners() = holes; auto svg_data = boost::geometry::svg(poly, style); ss << svg_data << std::endl; diff --git a/xs/src/libnest2d/libnest2d/clipper_backend/clipper_backend.cpp b/xs/src/libnest2d/libnest2d/clipper_backend/clipper_backend.cpp index 746edf1f4..830d235a3 100644 --- a/xs/src/libnest2d/libnest2d/clipper_backend/clipper_backend.cpp +++ b/xs/src/libnest2d/libnest2d/clipper_backend/clipper_backend.cpp @@ -1,112 +1,58 @@ -#include "clipper_backend.hpp" -#include +//#include "clipper_backend.hpp" +//#include -namespace libnest2d { +//namespace libnest2d { -namespace { +//namespace { -class SpinLock { - std::atomic_flag& lck_; -public: +//class SpinLock { +// std::atomic_flag& lck_; +//public: - inline SpinLock(std::atomic_flag& flg): lck_(flg) {} +// inline SpinLock(std::atomic_flag& flg): lck_(flg) {} - inline void lock() { - while(lck_.test_and_set(std::memory_order_acquire)) {} - } +// inline void lock() { +// while(lck_.test_and_set(std::memory_order_acquire)) {} +// } - inline void unlock() { lck_.clear(std::memory_order_release); } -}; +// inline void unlock() { lck_.clear(std::memory_order_release); } +//}; -class HoleCache { - friend struct libnest2d::ShapeLike; +//class HoleCache { +// friend struct libnest2d::ShapeLike; - std::unordered_map< const PolygonImpl*, ClipperLib::Paths> map; +// std::unordered_map< const PolygonImpl*, ClipperLib::Paths> map; - ClipperLib::Paths& _getHoles(const PolygonImpl* p) { - static std::atomic_flag flg = ATOMIC_FLAG_INIT; - SpinLock lock(flg); +// ClipperLib::Paths& _getHoles(const PolygonImpl* p) { +// static std::atomic_flag flg = ATOMIC_FLAG_INIT; +// SpinLock lock(flg); - lock.lock(); - ClipperLib::Paths& paths = map[p]; - lock.unlock(); +// lock.lock(); +// ClipperLib::Paths& paths = map[p]; +// lock.unlock(); - if(paths.size() != p->Childs.size()) { - paths.reserve(p->Childs.size()); +// if(paths.size() != p->Childs.size()) { +// paths.reserve(p->Childs.size()); - for(auto np : p->Childs) { - paths.emplace_back(np->Contour); - } - } +// for(auto np : p->Childs) { +// paths.emplace_back(np->Contour); +// } +// } - return paths; - } +// return paths; +// } - ClipperLib::Paths& getHoles(PolygonImpl& p) { - return _getHoles(&p); - } +// ClipperLib::Paths& getHoles(PolygonImpl& p) { +// return _getHoles(&p); +// } - const ClipperLib::Paths& getHoles(const PolygonImpl& p) { - return _getHoles(&p); - } -}; -} +// const ClipperLib::Paths& getHoles(const PolygonImpl& p) { +// return _getHoles(&p); +// } +//}; +//} -HoleCache holeCache; +//HoleCache holeCache; -template<> -std::string ShapeLike::toString(const PolygonImpl& sh) -{ - std::stringstream ss; - - for(auto p : sh.Contour) { - ss << p.X << " " << p.Y << "\n"; - } - - return ss.str(); -} - -template<> PolygonImpl ShapeLike::create( const PathImpl& path ) -{ - PolygonImpl p; - p.Contour = path; - - // Expecting that the coordinate system Y axis is positive in upwards - // direction - if(ClipperLib::Orientation(p.Contour)) { - // Not clockwise then reverse the b*tch - ClipperLib::ReversePath(p.Contour); - } - - return p; -} - -template<> PolygonImpl ShapeLike::create( PathImpl&& path ) -{ - PolygonImpl p; - p.Contour.swap(path); - - // Expecting that the coordinate system Y axis is positive in upwards - // direction - if(ClipperLib::Orientation(p.Contour)) { - // Not clockwise then reverse the b*tch - ClipperLib::ReversePath(p.Contour); - } - - return p; -} - -template<> -const THolesContainer& ShapeLike::holes( - const PolygonImpl& sh) -{ - return holeCache.getHoles(sh); -} - -template<> -THolesContainer& ShapeLike::holes(PolygonImpl& sh) { - return holeCache.getHoles(sh); -} - -} +//} diff --git a/xs/src/libnest2d/libnest2d/clipper_backend/clipper_backend.hpp b/xs/src/libnest2d/libnest2d/clipper_backend/clipper_backend.hpp index 8fb458a15..8cc27573a 100644 --- a/xs/src/libnest2d/libnest2d/clipper_backend/clipper_backend.hpp +++ b/xs/src/libnest2d/libnest2d/clipper_backend/clipper_backend.hpp @@ -4,18 +4,36 @@ #include #include #include - +#include #include #include "../geometry_traits.hpp" -#include "../geometries_nfp.hpp" +#include "../geometry_traits_nfp.hpp" #include namespace ClipperLib { using PointImpl = IntPoint; -using PolygonImpl = PolyNode; using PathImpl = Path; +using HoleStore = std::vector; + +struct PolygonImpl { + PathImpl Contour; + HoleStore Holes; + + inline PolygonImpl() {} + + inline explicit PolygonImpl(const PathImpl& cont): Contour(cont) {} + inline explicit PolygonImpl(const HoleStore& holes): + Holes(holes) {} + inline PolygonImpl(const Path& cont, const HoleStore& holes): + Contour(cont), Holes(holes) {} + + inline explicit PolygonImpl(PathImpl&& cont): Contour(std::move(cont)) {} + inline explicit PolygonImpl(HoleStore&& holes): Holes(std::move(holes)) {} + inline PolygonImpl(Path&& cont, HoleStore&& holes): + Contour(std::move(cont)), Holes(std::move(holes)) {} +}; inline PointImpl& operator +=(PointImpl& p, const PointImpl& pa ) { // This could be done with SIMD @@ -53,11 +71,10 @@ inline PointImpl operator-(const PointImpl& p1, const PointImpl& p2) { namespace libnest2d { // Aliases for convinience -using PointImpl = ClipperLib::IntPoint; -using PolygonImpl = ClipperLib::PolyNode; -using PathImpl = ClipperLib::Path; - -//extern HoleCache holeCache; +using ClipperLib::PointImpl; +using ClipperLib::PathImpl; +using ClipperLib::PolygonImpl; +using ClipperLib::HoleStore; // Type of coordinate units used by Clipper template<> struct CoordType { @@ -124,12 +141,26 @@ inline double area(const PolygonImpl& sh) { template<> inline double area(const PolygonImpl& sh) { - return -ClipperLib::Area(sh.Contour); + double a = 0; + + std::for_each(sh.Holes.begin(), sh.Holes.end(), [&a](const PathImpl& h) + { + a -= ClipperLib::Area(h); + }); + + return -ClipperLib::Area(sh.Contour) + a; } template<> inline double area(const PolygonImpl& sh) { - return ClipperLib::Area(sh.Contour); + double a = 0; + + std::for_each(sh.Holes.begin(), sh.Holes.end(), [&a](const PathImpl& h) + { + a += ClipperLib::Area(h); + }); + + return ClipperLib::Area(sh.Contour) + a; } } @@ -149,140 +180,85 @@ inline void ShapeLike::offset(PolygonImpl& sh, TCoord distance) { using ClipperLib::Paths; // If the input is not at least a triangle, we can not do this algorithm - if(sh.Contour.size() <= 3) throw GeometryException(GeomErr::OFFSET); + if(sh.Contour.size() <= 3 || + std::any_of(sh.Holes.begin(), sh.Holes.end(), + [](const PathImpl& p) { return p.size() <= 3; }) + ) throw GeometryException(GeomErr::OFFSET); ClipperOffset offs; Paths result; offs.AddPath(sh.Contour, jtMiter, etClosedPolygon); + offs.AddPaths(sh.Holes, jtMiter, etClosedPolygon); offs.Execute(result, static_cast(distance)); - // I dont know why does the offsetting revert the orientation and - // it removes the last vertex as well so boost will not have a closed - // polygon + // Offsetting reverts the orientation and also removes the last vertex + // so boost will not have a closed polygon. - if(result.size() != 1) throw GeometryException(GeomErr::OFFSET); + bool found_the_contour = false; + for(auto& r : result) { + if(ClipperLib::Orientation(r)) { + // We don't like if the offsetting generates more than one contour + // but throwing would be an overkill. Instead, we should warn the + // caller about the inability to create correct geometries + if(!found_the_contour) { + sh.Contour = r; + ClipperLib::ReversePath(sh.Contour); + sh.Contour.push_back(sh.Contour.front()); + found_the_contour = true; + } else { + dout() << "Warning: offsetting result is invalid!"; + /* TODO warning */ + } + } else { + // TODO If there are multiple contours we can't be sure which hole + // belongs to the first contour. (But in this case the situation is + // bad enough to let it go...) + sh.Holes.push_back(r); + ClipperLib::ReversePath(sh.Holes.back()); + sh.Holes.back().push_back(sh.Holes.back().front()); + } + } +} - sh.Contour = result.front(); +//template<> // TODO make it support holes if this method will ever be needed. +//inline PolygonImpl Nfp::minkowskiDiff(const PolygonImpl& sh, +// const PolygonImpl& other) +//{ +// #define DISABLE_BOOST_MINKOWSKI_ADD - // recreate closed polygon - sh.Contour.push_back(sh.Contour.front()); +// ClipperLib::Paths solution; - if(ClipperLib::Orientation(sh.Contour)) { - // Not clockwise then reverse the b*tch - ClipperLib::ReversePath(sh.Contour); +// ClipperLib::MinkowskiDiff(sh.Contour, other.Contour, solution); + +// PolygonImpl ret; +// ret.Contour = solution.front(); + +// return sh; +//} + +// Tell libnest2d how to make string out of a ClipperPolygon object +template<> inline std::string ShapeLike::toString(const PolygonImpl& sh) { + std::stringstream ss; + + ss << "Contour {\n"; + for(auto p : sh.Contour) { + ss << "\t" << p.X << " " << p.Y << "\n"; + } + ss << "}\n"; + + for(auto& h : sh.Holes) { + ss << "Holes {\n"; + for(auto p : h) { + ss << "\t{\n"; + ss << "\t\t" << p.X << " " << p.Y << "\n"; + ss << "\t}\n"; + } + ss << "}\n"; } + return ss.str(); } -// TODO : make it convex hull right and faster than boost - -//#define DISABLE_BOOST_CONVEX_HULL -//inline TCoord cross( const PointImpl &O, -// const PointImpl &A, -// const PointImpl &B) -//{ -// return (A.X - O.X) * (B.Y - O.Y) - (A.Y - O.Y) * (B.X - O.X); -//} - -//template<> -//inline PolygonImpl ShapeLike::convexHull(const PolygonImpl& sh) -//{ -// auto& P = sh.Contour; -// PolygonImpl ret; - -// size_t n = P.size(), k = 0; -// if (n <= 3) return ret; - -// auto& H = ret.Contour; -// H.resize(2*n); -// std::vector indices(P.size(), 0); -// std::iota(indices.begin(), indices.end(), 0); - -// // Sort points lexicographically -// std::sort(indices.begin(), indices.end(), [&P](unsigned i1, unsigned i2){ -// auto& p1 = P[i1], &p2 = P[i2]; -// return p1.X < p2.X || (p1.X == p2.X && p1.Y < p2.Y); -// }); - -// // Build lower hull -// for (size_t i = 0; i < n; ++i) { -// while (k >= 2 && cross(H[k-2], H[k-1], P[i]) <= 0) k--; -// H[k++] = P[i]; -// } - -// // Build upper hull -// for (size_t i = n-1, t = k+1; i > 0; --i) { -// while (k >= t && cross(H[k-2], H[k-1], P[i-1]) <= 0) k--; -// H[k++] = P[i-1]; -// } - -// H.resize(k-1); -// return ret; -//} - -//template<> -//inline PolygonImpl ShapeLike::convexHull( -// const ShapeLike::Shapes& shapes) -//{ -// PathImpl P; -// PolygonImpl ret; - -// size_t n = 0, k = 0; -// for(auto& sh : shapes) { n += sh.Contour.size(); } - -// P.reserve(n); -// for(auto& sh : shapes) { P.insert(P.end(), -// sh.Contour.begin(), sh.Contour.end()); } - -// if (n <= 3) { ret.Contour = P; return ret; } - -// auto& H = ret.Contour; -// H.resize(2*n); -// std::vector indices(P.size(), 0); -// std::iota(indices.begin(), indices.end(), 0); - -// // Sort points lexicographically -// std::sort(indices.begin(), indices.end(), [&P](unsigned i1, unsigned i2){ -// auto& p1 = P[i1], &p2 = P[i2]; -// return p1.X < p2.X || (p1.X == p2.X && p1.Y < p2.Y); -// }); - -// // Build lower hull -// for (size_t i = 0; i < n; ++i) { -// while (k >= 2 && cross(H[k-2], H[k-1], P[i]) <= 0) k--; -// H[k++] = P[i]; -// } - -// // Build upper hull -// for (size_t i = n-1, t = k+1; i > 0; --i) { -// while (k >= t && cross(H[k-2], H[k-1], P[i-1]) <= 0) k--; -// H[k++] = P[i-1]; -// } - -// H.resize(k-1); -// return ret; -//} - -template<> -inline PolygonImpl& Nfp::minkowskiAdd(PolygonImpl& sh, - const PolygonImpl& other) -{ - #define DISABLE_BOOST_MINKOWSKI_ADD - - ClipperLib::Paths solution; - - ClipperLib::MinkowskiSum(sh.Contour, other.Contour, solution, true); - - assert(solution.size() == 1); - - sh.Contour = solution.front(); - - return sh; -} - -// Tell binpack2d how to make string out of a ClipperPolygon object -template<> std::string ShapeLike::toString(const PolygonImpl& sh); - template<> inline TVertexIterator ShapeLike::begin(PolygonImpl& sh) { @@ -313,34 +289,78 @@ template<> struct HolesContainer { using Type = ClipperLib::Paths; }; -template<> PolygonImpl ShapeLike::create( const PathImpl& path); +template<> inline PolygonImpl ShapeLike::create(const PathImpl& path, + const HoleStore& holes) { + PolygonImpl p; + p.Contour = path; -template<> PolygonImpl ShapeLike::create( PathImpl&& path); + // Expecting that the coordinate system Y axis is positive in upwards + // direction + if(ClipperLib::Orientation(p.Contour)) { + // Not clockwise then reverse the b*tch + ClipperLib::ReversePath(p.Contour); + } -template<> -const THolesContainer& ShapeLike::holes( - const PolygonImpl& sh); + p.Holes = holes; + for(auto& h : p.Holes) { + if(!ClipperLib::Orientation(h)) { + ClipperLib::ReversePath(h); + } + } -template<> -THolesContainer& ShapeLike::holes(PolygonImpl& sh); - -template<> -inline TContour& ShapeLike::getHole(PolygonImpl& sh, - unsigned long idx) -{ - return sh.Childs[idx]->Contour; + return p; } -template<> -inline const TContour& ShapeLike::getHole(const PolygonImpl& sh, - unsigned long idx) +template<> inline PolygonImpl ShapeLike::create( PathImpl&& path, + HoleStore&& holes) { + PolygonImpl p; + p.Contour.swap(path); + + // Expecting that the coordinate system Y axis is positive in upwards + // direction + if(ClipperLib::Orientation(p.Contour)) { + // Not clockwise then reverse the b*tch + ClipperLib::ReversePath(p.Contour); + } + + p.Holes.swap(holes); + + for(auto& h : p.Holes) { + if(!ClipperLib::Orientation(h)) { + ClipperLib::ReversePath(h); + } + } + + return p; +} + +template<> inline const THolesContainer& +ShapeLike::holes(const PolygonImpl& sh) { - return sh.Childs[idx]->Contour; + return sh.Holes; +} + +template<> inline THolesContainer& +ShapeLike::holes(PolygonImpl& sh) +{ + return sh.Holes; +} + +template<> inline TContour& +ShapeLike::getHole(PolygonImpl& sh, unsigned long idx) +{ + return sh.Holes[idx]; +} + +template<> inline const TContour& +ShapeLike::getHole(const PolygonImpl& sh, unsigned long idx) +{ + return sh.Holes[idx]; } template<> inline size_t ShapeLike::holeCount(const PolygonImpl& sh) { - return sh.Childs.size(); + return sh.Holes.size(); } template<> inline PathImpl& ShapeLike::getContour(PolygonImpl& sh) @@ -359,7 +379,7 @@ template<> inline void ShapeLike::translate(PolygonImpl& sh, const PointImpl& offs) { for(auto& p : sh.Contour) { p += offs; } - for(auto& hole : sh.Childs) for(auto& p : hole->Contour) { p += offs; } + for(auto& hole : sh.Holes) for(auto& p : hole) { p += offs; } } #define DISABLE_BOOST_ROTATE @@ -368,69 +388,77 @@ inline void ShapeLike::rotate(PolygonImpl& sh, const Radians& rads) { using Coord = TCoord; - auto cosa = rads.cos();//std::cos(rads); - auto sina = rads.sin(); //std::sin(rads); + auto cosa = rads.cos(); + auto sina = rads.sin(); for(auto& p : sh.Contour) { p = { static_cast(p.X * cosa - p.Y * sina), static_cast(p.X * sina + p.Y * cosa) - }; + }; } - for(auto& hole : sh.Childs) for(auto& p : hole->Contour) { + for(auto& hole : sh.Holes) for(auto& p : hole) { p = { - static_cast(p.X * cosa - p.Y * sina), - static_cast(p.X * sina + p.Y * cosa) - }; + static_cast(p.X * cosa - p.Y * sina), + static_cast(p.X * sina + p.Y * cosa) + }; } } #define DISABLE_BOOST_NFP_MERGE -template<> inline -Nfp::Shapes Nfp::merge(const Nfp::Shapes& shapes, - const PolygonImpl& sh) +template<> inline Nfp::Shapes +Nfp::merge(const Nfp::Shapes& shapes, const PolygonImpl& sh) { Nfp::Shapes retv; - ClipperLib::Clipper clipper; + ClipperLib::Clipper clipper(ClipperLib::ioReverseSolution); - bool closed = true; - -#ifndef NDEBUG -#define _valid() valid = + bool closed = true; bool valid = false; -#else -#define _valid() -#endif - _valid() clipper.AddPath(sh.Contour, ClipperLib::ptSubject, closed); + valid = clipper.AddPath(sh.Contour, ClipperLib::ptSubject, closed); - for(auto& hole : sh.Childs) { - _valid() clipper.AddPath(hole->Contour, ClipperLib::ptSubject, closed); - assert(valid); + for(auto& hole : sh.Holes) { + valid &= clipper.AddPath(hole, ClipperLib::ptSubject, closed); } for(auto& path : shapes) { - _valid() clipper.AddPath(path.Contour, ClipperLib::ptSubject, closed); - assert(valid); - for(auto& hole : path.Childs) { - _valid() clipper.AddPath(hole->Contour, ClipperLib::ptSubject, closed); - assert(valid); + valid &= clipper.AddPath(path.Contour, ClipperLib::ptSubject, closed); + + for(auto& hole : path.Holes) { + valid &= clipper.AddPath(hole, ClipperLib::ptSubject, closed); } } - ClipperLib::Paths rret; - clipper.Execute(ClipperLib::ctUnion, rret, ClipperLib::pftNonZero); - retv.reserve(rret.size()); - for(auto& p : rret) { - if(ClipperLib::Orientation(p)) { - // Not clockwise then reverse the b*tch - ClipperLib::ReversePath(p); + if(!valid) throw GeometryException(GeomErr::MERGE); + + ClipperLib::PolyTree result; + clipper.Execute(ClipperLib::ctUnion, result, ClipperLib::pftNonZero); + retv.reserve(result.Total()); + + std::function processHole; + + auto processPoly = [&retv, &processHole](ClipperLib::PolyNode *pptr) { + PolygonImpl poly(pptr->Contour); + poly.Contour.push_back(poly.Contour.front()); + for(auto h : pptr->Childs) { processHole(h, poly); } + retv.push_back(poly); + }; + + processHole = [&processPoly](ClipperLib::PolyNode *pptr, PolygonImpl& poly) { + poly.Holes.push_back(pptr->Contour); + poly.Holes.back().push_back(poly.Holes.back().front()); + for(auto c : pptr->Childs) processPoly(c); + }; + + auto traverse = [&processPoly] (ClipperLib::PolyNode *node) + { + for(auto ch : node->Childs) { + processPoly(ch); } - retv.emplace_back(); - retv.back().Contour = p; - retv.back().Contour.emplace_back(p.front()); - } + }; + + traverse(&result); return retv; } diff --git a/xs/src/libnest2d/libnest2d/common.hpp b/xs/src/libnest2d/libnest2d/common.hpp index b9c252977..18f313712 100644 --- a/xs/src/libnest2d/libnest2d/common.hpp +++ b/xs/src/libnest2d/libnest2d/common.hpp @@ -18,7 +18,6 @@ #define BP2D_CONSTEXPR constexpr #endif - /* * Debugging output dout and derr definition */ @@ -211,16 +210,16 @@ enum class GeomErr : std::size_t { NFP }; -static const std::string ERROR_STR[] = { - "Offsetting could not be done! An invalid geometry may have been added." - "Error while merging geometries!" - "No fit polygon cannaot be calculated." +const std::string ERROR_STR[] = { + "Offsetting could not be done! An invalid geometry may have been added.", + "Error while merging geometries!", + "No fit polygon cannot be calculated." }; class GeometryException: public std::exception { - virtual const char * errorstr(GeomErr errcode) const BP2D_NOEXCEPT { - return ERROR_STR[static_cast(errcode)].c_str(); + virtual const std::string& errorstr(GeomErr errcode) const BP2D_NOEXCEPT { + return ERROR_STR[static_cast(errcode)]; } GeomErr errcode_; @@ -231,7 +230,7 @@ public: GeomErr errcode() const { return errcode_; } virtual const char * what() const BP2D_NOEXCEPT override { - return errorstr(errcode_); + return errorstr(errcode_).c_str(); } }; diff --git a/xs/src/libnest2d/libnest2d/geometries_io.hpp b/xs/src/libnest2d/libnest2d/geometries_io.hpp deleted file mode 100644 index dbcae5256..000000000 --- a/xs/src/libnest2d/libnest2d/geometries_io.hpp +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef GEOMETRIES_IO_HPP -#define GEOMETRIES_IO_HPP - -#include "libnest2d.hpp" - -#include - -namespace libnest2d { - -template -std::ostream& operator<<(std::ostream& stream, const _Item& sh) { - stream << sh.toString() << "\n"; - return stream; -} - -} - -#endif // GEOMETRIES_IO_HPP diff --git a/xs/src/libnest2d/libnest2d/geometries_nfp.hpp b/xs/src/libnest2d/libnest2d/geometries_nfp.hpp deleted file mode 100644 index f3672d4fe..000000000 --- a/xs/src/libnest2d/libnest2d/geometries_nfp.hpp +++ /dev/null @@ -1,223 +0,0 @@ -#ifndef GEOMETRIES_NOFITPOLYGON_HPP -#define GEOMETRIES_NOFITPOLYGON_HPP - -#include "geometry_traits.hpp" -#include -#include - -namespace libnest2d { - -struct Nfp { - -template -using Shapes = typename ShapeLike::Shapes; - -template -static RawShape& minkowskiAdd(RawShape& sh, const RawShape& /*other*/) -{ - static_assert(always_false::value, - "Nfp::minkowskiAdd() unimplemented!"); - return sh; -} - -template -static Shapes merge(const Shapes& shc, const RawShape& sh) -{ - static_assert(always_false::value, - "Nfp::merge(shapes, shape) unimplemented!"); -} - -template -inline static TPoint referenceVertex(const RawShape& sh) -{ - return rightmostUpVertex(sh); -} - -template -static TPoint leftmostDownVertex(const RawShape& sh) { - - // find min x and min y vertex - auto it = std::min_element(ShapeLike::cbegin(sh), ShapeLike::cend(sh), - _vsort); - - return *it; -} - -template -static TPoint rightmostUpVertex(const RawShape& sh) { - - // find min x and min y vertex - auto it = std::max_element(ShapeLike::cbegin(sh), ShapeLike::cend(sh), - _vsort); - - return *it; -} - -template -static RawShape noFitPolygon(const RawShape& sh, const RawShape& other) { - auto isConvex = [](const RawShape& sh) { - - return true; - }; - - using Vertex = TPoint; - using Edge = _Segment; - - auto nfpConvexConvex = [] ( - const RawShape& sh, - const RawShape& cother) - { - RawShape other = cother; - - // Make the other polygon counter-clockwise - std::reverse(ShapeLike::begin(other), ShapeLike::end(other)); - - RawShape rsh; // Final nfp placeholder - std::vector edgelist; - - auto cap = ShapeLike::contourVertexCount(sh) + - ShapeLike::contourVertexCount(other); - - // Reserve the needed memory - edgelist.reserve(cap); - ShapeLike::reserve(rsh, static_cast(cap)); - - { // place all edges from sh into edgelist - auto first = ShapeLike::cbegin(sh); - auto next = first + 1; - auto endit = ShapeLike::cend(sh); - - while(next != endit) edgelist.emplace_back(*(first++), *(next++)); - } - - { // place all edges from other into edgelist - auto first = ShapeLike::cbegin(other); - auto next = first + 1; - auto endit = ShapeLike::cend(other); - - while(next != endit) edgelist.emplace_back(*(first++), *(next++)); - } - - // Sort the edges by angle to X axis. - std::sort(edgelist.begin(), edgelist.end(), - [](const Edge& e1, const Edge& e2) - { - return e1.angleToXaxis() > e2.angleToXaxis(); - }); - - // Add the two vertices from the first edge into the final polygon. - ShapeLike::addVertex(rsh, edgelist.front().first()); - ShapeLike::addVertex(rsh, edgelist.front().second()); - - auto tmp = std::next(ShapeLike::begin(rsh)); - - // Construct final nfp by placing each edge to the end of the previous - for(auto eit = std::next(edgelist.begin()); - eit != edgelist.end(); - ++eit) - { - auto d = *tmp - eit->first(); - auto p = eit->second() + d; - - ShapeLike::addVertex(rsh, p); - - tmp = std::next(tmp); - } - - // Now we have an nfp somewhere in the dark. We need to get it - // to the right position around the stationary shape. - // This is done by choosing the leftmost lowest vertex of the - // orbiting polygon to be touched with the rightmost upper - // vertex of the stationary polygon. In this configuration, the - // reference vertex of the orbiting polygon (which can be dragged around - // the nfp) will be its rightmost upper vertex that coincides with the - // rightmost upper vertex of the nfp. No proof provided other than Jonas - // Lindmark's reasoning about the reference vertex of nfp in his thesis - // ("No fit polygon problem" - section 2.1.9) - - auto csh = sh; // Copy sh, we will sort the verices in the copy - auto& cmp = _vsort; - std::sort(ShapeLike::begin(csh), ShapeLike::end(csh), cmp); - std::sort(ShapeLike::begin(other), ShapeLike::end(other), cmp); - - // leftmost lower vertex of the stationary polygon - auto& touch_sh = *(std::prev(ShapeLike::end(csh))); - // rightmost upper vertex of the orbiting polygon - auto& touch_other = *(ShapeLike::begin(other)); - - // Calculate the difference and move the orbiter to the touch position. - auto dtouch = touch_sh - touch_other; - auto top_other = *(std::prev(ShapeLike::end(other))) + dtouch; - - // Get the righmost upper vertex of the nfp and move it to the RMU of - // the orbiter because they should coincide. - auto&& top_nfp = rightmostUpVertex(rsh); - auto dnfp = top_other - top_nfp; - std::for_each(ShapeLike::begin(rsh), ShapeLike::end(rsh), - [&dnfp](Vertex& v) { v+= dnfp; } ); - - return rsh; - }; - - RawShape rsh; - - enum e_dispatch { - CONVEX_CONVEX, - CONCAVE_CONVEX, - CONVEX_CONCAVE, - CONCAVE_CONCAVE - }; - - int sel = isConvex(sh) ? CONVEX_CONVEX : CONCAVE_CONVEX; - sel += isConvex(other) ? CONVEX_CONVEX : CONVEX_CONCAVE; - - switch(sel) { - case CONVEX_CONVEX: - rsh = nfpConvexConvex(sh, other); break; - case CONCAVE_CONVEX: - break; - case CONVEX_CONCAVE: - break; - case CONCAVE_CONCAVE: - break; - } - - return rsh; -} - -template -static inline Shapes noFitPolygon(const Shapes& shapes, - const RawShape& other) -{ - assert(shapes.size() >= 1); - auto shit = shapes.begin(); - - Shapes ret; - ret.emplace_back(noFitPolygon(*shit, other)); - - while(++shit != shapes.end()) ret = merge(ret, noFitPolygon(*shit, other)); - - return ret; -} - -private: - -// Do not specialize this... -template -static inline bool _vsort(const TPoint& v1, - const TPoint& v2) -{ - using Coord = TCoord>; - Coord &&x1 = getX(v1), &&x2 = getX(v2), &&y1 = getY(v1), &&y2 = getY(v2); - auto diff = y1 - y2; - if(std::abs(diff) <= std::numeric_limits::epsilon()) - return x1 < x2; - - return diff < 0; -} - -}; - -} - -#endif // GEOMETRIES_NOFITPOLYGON_HPP diff --git a/xs/src/libnest2d/libnest2d/geometry_traits.hpp b/xs/src/libnest2d/libnest2d/geometry_traits.hpp index 758bdd1bd..dbd609201 100644 --- a/xs/src/libnest2d/libnest2d/geometry_traits.hpp +++ b/xs/src/libnest2d/libnest2d/geometry_traits.hpp @@ -328,23 +328,37 @@ enum class Formats { SVG }; -// This struct serves as a namespace. The only difference is that is can be +// This struct serves as a namespace. The only difference is that it can be // used in friend declarations. struct ShapeLike { template using Shapes = std::vector; + template + static RawShape create(const TContour& contour, + const THolesContainer& holes) + { + return RawShape(contour, holes); + } + + template + static RawShape create(TContour&& contour, + THolesContainer&& holes) + { + return RawShape(contour, holes); + } + template static RawShape create(const TContour& contour) { - return RawShape(contour); + return create(contour, {}); } template static RawShape create(TContour&& contour) { - return RawShape(contour); + return create(contour, {}); } // Optional, does nothing by default @@ -551,10 +565,44 @@ struct ShapeLike { } template - static std::pair isValid(const RawShape& /*sh*/) { + static std::pair isValid(const RawShape& /*sh*/) + { return {false, "ShapeLike::isValid() unimplemented!"}; } + template + static inline bool isConvex(const TContour& sh) + { + using Vertex = TPoint; + auto first = sh.begin(); + auto middle = std::next(first); + auto last = std::next(middle); + using CVrRef = const Vertex&; + + auto zcrossproduct = [](CVrRef k, CVrRef k1, CVrRef k2) { + auto dx1 = getX(k1) - getX(k); + auto dy1 = getY(k1) - getY(k); + auto dx2 = getX(k2) - getX(k1); + auto dy2 = getY(k2) - getY(k1); + return dx1*dy2 - dy1*dx2; + }; + + auto firstprod = zcrossproduct( *(std::prev(std::prev(sh.end()))), + *first, + *middle ); + + bool ret = true; + bool frsign = firstprod > 0; + while(last != sh.end()) { + auto &k = *first, &k1 = *middle, &k2 = *last; + auto zc = zcrossproduct(k, k1, k2); + ret &= frsign == (zc > 0); + ++first; ++middle; ++last; + } + + return ret; + } + // ************************************************************************* // No need to implement these // ************************************************************************* diff --git a/xs/src/libnest2d/libnest2d/geometry_traits_nfp.hpp b/xs/src/libnest2d/libnest2d/geometry_traits_nfp.hpp new file mode 100644 index 000000000..56e8527b4 --- /dev/null +++ b/xs/src/libnest2d/libnest2d/geometry_traits_nfp.hpp @@ -0,0 +1,258 @@ +#ifndef GEOMETRIES_NOFITPOLYGON_HPP +#define GEOMETRIES_NOFITPOLYGON_HPP + +#include "geometry_traits.hpp" +#include +#include + +namespace libnest2d { + +/// The complexity level of a polygon that an NFP implementation can handle. +enum class NfpLevel: unsigned { + CONVEX_ONLY, + ONE_CONVEX, + BOTH_CONCAVE, + ONE_CONVEX_WITH_HOLES, + BOTH_CONCAVE_WITH_HOLES +}; + +/// A collection of static methods for handling the no fit polygon creation. +struct Nfp { + +// Shorthand for a pile of polygons +template +using Shapes = typename ShapeLike::Shapes; + +/// Minkowski addition (not used yet) +template +static RawShape minkowskiDiff(const RawShape& sh, const RawShape& /*other*/) +{ + + + return sh; +} + +/** + * Merge a bunch of polygons with the specified additional polygon. + * + * \tparam RawShape the Polygon data type. + * \param shc The pile of polygons that will be unified with sh. + * \param sh A single polygon to unify with shc. + * + * \return A set of polygons that is the union of the input polygons. Note that + * mostly it will be a set containing only one big polygon but if the input + * polygons are disjuct than the resulting set will contain more polygons. + */ +template +static Shapes merge(const Shapes& shc, const RawShape& sh) +{ + static_assert(always_false::value, + "Nfp::merge(shapes, shape) unimplemented!"); +} + +/** + * A method to get a vertex from a polygon that always maintains a relative + * position to the coordinate system: It is always the rightmost top vertex. + * + * This way it does not matter in what order the vertices are stored, the + * reference will be always the same for the same polygon. + */ +template +inline static TPoint referenceVertex(const RawShape& sh) +{ + return rightmostUpVertex(sh); +} + +/** + * Get the vertex of the polygon that is at the lowest values (bottom) in the Y + * axis and if there are more than one vertices on the same Y coordinate than + * the result will be the leftmost (with the highest X coordinate). + */ +template +static TPoint leftmostDownVertex(const RawShape& sh) +{ + + // find min x and min y vertex + auto it = std::min_element(ShapeLike::cbegin(sh), ShapeLike::cend(sh), + _vsort); + + return *it; +} + +/** + * Get the vertex of the polygon that is at the highest values (top) in the Y + * axis and if there are more than one vertices on the same Y coordinate than + * the result will be the rightmost (with the lowest X coordinate). + */ +template +static TPoint rightmostUpVertex(const RawShape& sh) +{ + + // find min x and min y vertex + auto it = std::max_element(ShapeLike::cbegin(sh), ShapeLike::cend(sh), + _vsort); + + return *it; +} + +/// Helper function to get the NFP +template +static RawShape noFitPolygon(const RawShape& sh, const RawShape& other) +{ + NfpImpl nfp; + return nfp(sh, other); +} + +/** + * The "trivial" Cuninghame-Green implementation of NFP for convex polygons. + * + * You can use this even if you provide implementations for the more complex + * cases (Through specializing the the NfpImpl struct). Currently, no other + * cases are covered in the library. + * + * Complexity should be no more than linear in the number of edges of the input + * polygons. + * + * \tparam RawShape the Polygon data type. + * \param sh The stationary polygon + * \param cother The orbiting polygon + * \return Returns the NFP of the two input polygons which have to be strictly + * convex. The resulting NFP is proven to be convex as well in this case. + * + */ +template +static RawShape nfpConvexOnly(const RawShape& sh, const RawShape& cother) +{ + using Vertex = TPoint; using Edge = _Segment; + + RawShape other = cother; + + // Make the other polygon counter-clockwise + std::reverse(ShapeLike::begin(other), ShapeLike::end(other)); + + RawShape rsh; // Final nfp placeholder + std::vector edgelist; + + auto cap = ShapeLike::contourVertexCount(sh) + + ShapeLike::contourVertexCount(other); + + // Reserve the needed memory + edgelist.reserve(cap); + ShapeLike::reserve(rsh, static_cast(cap)); + + { // place all edges from sh into edgelist + auto first = ShapeLike::cbegin(sh); + auto next = first + 1; + auto endit = ShapeLike::cend(sh); + + while(next != endit) edgelist.emplace_back(*(first++), *(next++)); + } + + { // place all edges from other into edgelist + auto first = ShapeLike::cbegin(other); + auto next = first + 1; + auto endit = ShapeLike::cend(other); + + while(next != endit) edgelist.emplace_back(*(first++), *(next++)); + } + + // Sort the edges by angle to X axis. + std::sort(edgelist.begin(), edgelist.end(), + [](const Edge& e1, const Edge& e2) + { + return e1.angleToXaxis() > e2.angleToXaxis(); + }); + + // Add the two vertices from the first edge into the final polygon. + ShapeLike::addVertex(rsh, edgelist.front().first()); + ShapeLike::addVertex(rsh, edgelist.front().second()); + + auto tmp = std::next(ShapeLike::begin(rsh)); + + // Construct final nfp by placing each edge to the end of the previous + for(auto eit = std::next(edgelist.begin()); + eit != edgelist.end(); + ++eit) + { + auto d = *tmp - eit->first(); + auto p = eit->second() + d; + + ShapeLike::addVertex(rsh, p); + + tmp = std::next(tmp); + } + + // Now we have an nfp somewhere in the dark. We need to get it + // to the right position around the stationary shape. + // This is done by choosing the leftmost lowest vertex of the + // orbiting polygon to be touched with the rightmost upper + // vertex of the stationary polygon. In this configuration, the + // reference vertex of the orbiting polygon (which can be dragged around + // the nfp) will be its rightmost upper vertex that coincides with the + // rightmost upper vertex of the nfp. No proof provided other than Jonas + // Lindmark's reasoning about the reference vertex of nfp in his thesis + // ("No fit polygon problem" - section 2.1.9) + + auto csh = sh; // Copy sh, we will sort the verices in the copy + auto& cmp = _vsort; + std::sort(ShapeLike::begin(csh), ShapeLike::end(csh), cmp); + std::sort(ShapeLike::begin(other), ShapeLike::end(other), cmp); + + // leftmost lower vertex of the stationary polygon + auto& touch_sh = *(std::prev(ShapeLike::end(csh))); + // rightmost upper vertex of the orbiting polygon + auto& touch_other = *(ShapeLike::begin(other)); + + // Calculate the difference and move the orbiter to the touch position. + auto dtouch = touch_sh - touch_other; + auto top_other = *(std::prev(ShapeLike::end(other))) + dtouch; + + // Get the righmost upper vertex of the nfp and move it to the RMU of + // the orbiter because they should coincide. + auto&& top_nfp = rightmostUpVertex(rsh); + auto dnfp = top_other - top_nfp; + std::for_each(ShapeLike::begin(rsh), ShapeLike::end(rsh), + [&dnfp](Vertex& v) { v+= dnfp; } ); + + return rsh; +} + +// Specializable NFP implementation class. Specialize it if you have a faster +// or better NFP implementation +template +struct NfpImpl { + RawShape operator()(const RawShape& sh, const RawShape& other) { + static_assert(nfptype == NfpLevel::CONVEX_ONLY, + "Nfp::noFitPolygon() unimplemented!"); + + // Libnest2D has a default implementation for convex polygons and will + // use it if feasible. + return nfpConvexOnly(sh, other); + } +}; + +template struct MaxNfpLevel { + static const BP2D_CONSTEXPR NfpLevel value = NfpLevel::CONVEX_ONLY; +}; + +private: + +// Do not specialize this... +template +static inline bool _vsort(const TPoint& v1, + const TPoint& v2) +{ + using Coord = TCoord>; + Coord &&x1 = getX(v1), &&x2 = getX(v2), &&y1 = getY(v1), &&y2 = getY(v2); + auto diff = y1 - y2; + if(std::abs(diff) <= std::numeric_limits::epsilon()) + return x1 < x2; + + return diff < 0; +} + +}; + +} + +#endif // GEOMETRIES_NOFITPOLYGON_HPP diff --git a/xs/src/libnest2d/libnest2d/libnest2d.hpp b/xs/src/libnest2d/libnest2d/libnest2d.hpp index c661dc599..96316c344 100644 --- a/xs/src/libnest2d/libnest2d/libnest2d.hpp +++ b/xs/src/libnest2d/libnest2d/libnest2d.hpp @@ -9,9 +9,6 @@ #include #include "geometry_traits.hpp" -//#include "optimizers/subplex.hpp" -//#include "optimizers/simplex.hpp" -#include "optimizers/genetic.hpp" namespace libnest2d { @@ -52,6 +49,14 @@ class _Item { mutable RawShape offset_cache_; mutable bool offset_cache_valid_ = false; + enum class Convexity: char { + UNCHECKED, + TRUE, + FALSE + }; + + mutable Convexity convexity_ = Convexity::UNCHECKED; + public: /// The type of the shape which was handed over as the template argument. @@ -101,11 +106,14 @@ public: inline _Item(const std::initializer_list< Vertex >& il): sh_(ShapeLike::create(il)) {} - inline _Item(const TContour& contour): - sh_(ShapeLike::create(contour)) {} + inline _Item(const TContour& contour, + const THolesContainer& holes = {}): + sh_(ShapeLike::create(contour, holes)) {} - inline _Item(TContour&& contour): - sh_(ShapeLike::create(std::move(contour))) {} + inline _Item(TContour&& contour, + THolesContainer&& holes): + sh_(ShapeLike::create(std::move(contour), + std::move(holes))) {} /** * @brief Convert the polygon to string representation. The format depends @@ -117,7 +125,7 @@ public: return ShapeLike::toString(sh_); } - /// Iterator tho the first vertex in the polygon. + /// Iterator tho the first contour vertex in the polygon. inline Iterator begin() const { return ShapeLike::cbegin(sh_); @@ -129,7 +137,7 @@ public: return ShapeLike::cbegin(sh_); } - /// Iterator to the last element. + /// Iterator to the last contour vertex. inline Iterator end() const { return ShapeLike::cend(sh_); @@ -165,8 +173,7 @@ public: * @param idx The index of the requested vertex. * @param v The new vertex data. */ - inline void setVertex(unsigned long idx, - const Vertex& v ) + inline void setVertex(unsigned long idx, const Vertex& v ) { invalidateCache(); ShapeLike::vertex(sh_, idx) = v; @@ -191,11 +198,38 @@ public: return ret; } + inline bool isContourConvex() const { + bool ret = false; + + switch(convexity_) { + case Convexity::UNCHECKED: + ret = ShapeLike::isConvex(ShapeLike::getContour(transformedShape())); + convexity_ = ret? Convexity::TRUE : Convexity::FALSE; + break; + case Convexity::TRUE: ret = true; break; + case Convexity::FALSE:; + } + + return ret; + } + + inline bool isHoleConvex(unsigned holeidx) const { + return false; + } + + inline bool areHolesConvex() const { + return false; + } + /// The number of the outer ring vertices. inline size_t vertexCount() const { return ShapeLike::contourVertexCount(sh_); } + inline size_t holeCount() const { + return ShapeLike::holeCount(sh_); + } + /** * @brief isPointInside * @param p @@ -262,7 +296,7 @@ public: } } - inline RawShape transformedShape() const + inline const RawShape& transformedShape() const { if(tr_cache_valid_) return tr_cache_; @@ -271,7 +305,7 @@ public: if(has_translation_) ShapeLike::translate(cpy, translation_); tr_cache_ = cpy; tr_cache_valid_ = true; - return cpy; + return tr_cache_; } inline operator RawShape() const @@ -327,6 +361,7 @@ private: tr_cache_valid_ = false; area_cache_valid_ = false; offset_cache_valid_ = false; + convexity_ = Convexity::UNCHECKED; } }; diff --git a/xs/src/libnest2d/libnest2d/placers/nfpplacer.hpp b/xs/src/libnest2d/libnest2d/placers/nfpplacer.hpp index 26a0a2048..5ddb3a98d 100644 --- a/xs/src/libnest2d/libnest2d/placers/nfpplacer.hpp +++ b/xs/src/libnest2d/libnest2d/placers/nfpplacer.hpp @@ -5,9 +5,7 @@ #include #endif #include "placer_boilerplate.hpp" -#include "../geometries_nfp.hpp" -#include -//#include +#include "../geometry_traits_nfp.hpp" namespace libnest2d { namespace strategies { @@ -41,13 +39,13 @@ template class EdgeCache { using Coord = TCoord; using Edge = _Segment; - enum Corners { - BOTTOM, - LEFT, - RIGHT, - TOP, - NUM_CORNERS - }; +// enum Corners { +// BOTTOM, +// LEFT, +// RIGHT, +// TOP, +// NUM_CORNERS +// }; mutable std::vector corners_; @@ -72,43 +70,49 @@ template class EdgeCache { void fetchCorners() const { if(!corners_.empty()) return; - corners_ = std::vector(NUM_CORNERS, 0.0); + corners_ = distances_; + for(auto& d : corners_) { + d /= full_distance_; + } - std::vector idx_ud(emap_.size(), 0); - std::vector idx_lr(emap_.size(), 0); +// corners_ = std::vector(NUM_CORNERS, 0.0); - std::iota(idx_ud.begin(), idx_ud.end(), 0); - std::iota(idx_lr.begin(), idx_lr.end(), 0); +// std::vector idx_ud(emap_.size(), 0); +// std::vector idx_lr(emap_.size(), 0); - std::sort(idx_ud.begin(), idx_ud.end(), - [this](unsigned idx1, unsigned idx2) - { - const Vertex& v1 = emap_[idx1].first(); - const Vertex& v2 = emap_[idx2].first(); - auto diff = getY(v1) - getY(v2); - if(std::abs(diff) <= std::numeric_limits::epsilon()) - return getX(v1) < getX(v2); +// std::iota(idx_ud.begin(), idx_ud.end(), 0); +// std::iota(idx_lr.begin(), idx_lr.end(), 0); - return diff < 0; - }); +// std::sort(idx_ud.begin(), idx_ud.end(), +// [this](unsigned idx1, unsigned idx2) +// { +// const Vertex& v1 = emap_[idx1].first(); +// const Vertex& v2 = emap_[idx2].first(); - std::sort(idx_lr.begin(), idx_lr.end(), - [this](unsigned idx1, unsigned idx2) - { - const Vertex& v1 = emap_[idx1].first(); - const Vertex& v2 = emap_[idx2].first(); +// auto diff = getY(v1) - getY(v2); +// if(std::abs(diff) <= std::numeric_limits::epsilon()) +// return getX(v1) < getX(v2); - auto diff = getX(v1) - getX(v2); - if(std::abs(diff) <= std::numeric_limits::epsilon()) - return getY(v1) < getY(v2); +// return diff < 0; +// }); - return diff < 0; - }); +// std::sort(idx_lr.begin(), idx_lr.end(), +// [this](unsigned idx1, unsigned idx2) +// { +// const Vertex& v1 = emap_[idx1].first(); +// const Vertex& v2 = emap_[idx2].first(); - corners_[BOTTOM] = distances_[idx_ud.front()]/full_distance_; - corners_[TOP] = distances_[idx_ud.back()]/full_distance_; - corners_[LEFT] = distances_[idx_lr.front()]/full_distance_; - corners_[RIGHT] = distances_[idx_lr.back()]/full_distance_; +// auto diff = getX(v1) - getX(v2); +// if(std::abs(diff) <= std::numeric_limits::epsilon()) +// return getY(v1) < getY(v2); + +// return diff < 0; +// }); + +// corners_[BOTTOM] = distances_[idx_ud.front()]/full_distance_; +// corners_[TOP] = distances_[idx_ud.back()]/full_distance_; +// corners_[LEFT] = distances_[idx_lr.front()]/full_distance_; +// corners_[RIGHT] = distances_[idx_lr.back()]/full_distance_; } public: @@ -163,11 +167,11 @@ public: inline double circumference() const BP2D_NOEXCEPT { return full_distance_; } - inline double corner(Corners c) const BP2D_NOEXCEPT { - assert(c < NUM_CORNERS); - fetchCorners(); - return corners_[c]; - } +// inline double corner(Corners c) const BP2D_NOEXCEPT { +// assert(c < NUM_CORNERS); +// fetchCorners(); +// return corners_[c]; +// } inline const std::vector& corners() const BP2D_NOEXCEPT { fetchCorners(); @@ -176,18 +180,21 @@ public: }; -// Nfp for a bunch of polygons. If the polygons are convex, the nfp calculated -// for trsh can be the union of nfp-s calculated with each polygon +template +struct Lvl { static const NfpLevel value = lvl; }; + template -Nfp::Shapes nfp(const Container& polygons, const RawShape& trsh ) +Nfp::Shapes nfp( const Container& polygons, + const _Item& trsh, + Lvl) { using Item = _Item; Nfp::Shapes nfps; for(Item& sh : polygons) { - auto subnfp = Nfp::noFitPolygon(sh.transformedShape(), - trsh); + auto subnfp = Nfp::noFitPolygon( + sh.transformedShape(), trsh.transformedShape()); #ifndef NDEBUG auto vv = ShapeLike::isValid(sh.transformedShape()); assert(vv.first); @@ -202,6 +209,51 @@ Nfp::Shapes nfp(const Container& polygons, const RawShape& trsh ) return nfps; } +template +Nfp::Shapes nfp( const Container& polygons, + const _Item& trsh, + Level) +{ + using Item = _Item; + + Nfp::Shapes nfps, stationary; + + for(Item& sh : polygons) { + stationary = Nfp::merge(stationary, sh.transformedShape()); + } + + std::cout << "pile size: " << stationary.size() << std::endl; + for(RawShape& sh : stationary) { + + RawShape subnfp; +// if(sh.isContourConvex() && trsh.isContourConvex()) { +// subnfp = Nfp::noFitPolygon( +// sh.transformedShape(), trsh.transformedShape()); +// } else { + subnfp = Nfp::noFitPolygon( sh/*.transformedShape()*/, + trsh.transformedShape()); +// } + +// #ifndef NDEBUG +// auto vv = ShapeLike::isValid(sh.transformedShape()); +// assert(vv.first); + +// auto vnfp = ShapeLike::isValid(subnfp); +// assert(vnfp.first); +// #endif + +// auto vnfp = ShapeLike::isValid(subnfp); +// if(!vnfp.first) { +// std::cout << vnfp.second << std::endl; +// std::cout << ShapeLike::toString(subnfp) << std::endl; +// } + + nfps = Nfp::merge(nfps, subnfp); + } + + return nfps; +} + template class _NofitPolyPlacer: public PlacerBoilerplate<_NofitPolyPlacer, RawShape, _Box>, NfpPConfig> { @@ -216,6 +268,8 @@ class _NofitPolyPlacer: public PlacerBoilerplate<_NofitPolyPlacer, const double norm_; const double penality_; + using MaxNfpLevel = Nfp::MaxNfpLevel; + public: using Pile = const Nfp::Shapes&; @@ -275,7 +329,7 @@ public: auto trsh = item.transformedShape(); - nfps = nfp(items_, trsh); + nfps = nfp(items_, item, Lvl()); auto iv = Nfp::referenceVertex(trsh); auto startpos = item.translation(); @@ -348,7 +402,7 @@ public: stopcr.max_iterations = 1000; stopcr.stoplimit = 0.01; stopcr.type = opt::StopLimitType::RELATIVE; - opt::TOptimizer solver(stopcr); + opt::TOptimizer solver(stopcr); double optimum = 0; double best_score = penality_; @@ -386,14 +440,8 @@ public: best_score = result.score; optimum = std::get<0>(result.optimum); } - } catch(std::exception& - #ifndef NDEBUG - e - #endif - ) { - #ifndef NDEBUG - std::cerr << "ERROR " << e.what() << std::endl; - #endif + } catch(std::exception& e) { + derr() << "ERROR: " << e.what() << "\n"; } }); } @@ -420,6 +468,10 @@ public: } ~_NofitPolyPlacer() { + clearItems(); + } + + inline void clearItems() { Nfp::Shapes m; m.reserve(items_.size()); @@ -458,6 +510,8 @@ public: auto d = cb - ci; for(Item& item : items_) item.translate(d); + + Base::clearItems(); } private: diff --git a/xs/src/libnest2d/libnest2d/selections/djd_heuristic.hpp b/xs/src/libnest2d/libnest2d/selections/djd_heuristic.hpp index 2d1ca08cb..dcc029251 100644 --- a/xs/src/libnest2d/libnest2d/selections/djd_heuristic.hpp +++ b/xs/src/libnest2d/libnest2d/selections/djd_heuristic.hpp @@ -180,6 +180,29 @@ public: }); }; + using ItemListIt = typename ItemList::iterator; + + auto largestPiece = [](ItemListIt it, ItemList& not_packed) { + return it == not_packed.begin()? std::next(it) : not_packed.begin(); + }; + + auto secondLargestPiece = [&largestPiece](ItemListIt it, + ItemList& not_packed) { + auto ret = std::next(largestPiece(it, not_packed)); + return ret == it? std::next(ret) : ret; + }; + + auto smallestPiece = [](ItemListIt it, ItemList& not_packed) { + auto last = std::prev(not_packed.end()); + return it == last? std::prev(it) : last; + }; + + auto secondSmallestPiece = [&smallestPiece](ItemListIt it, + ItemList& not_packed) { + auto ret = std::prev(smallestPiece(it, not_packed)); + return ret == it? std::prev(ret) : ret; + }; + auto tryOneByOne = // Subroutine to try adding items one by one. [&bin_area] (Placer& placer, ItemList& not_packed, @@ -208,31 +231,25 @@ public: }; auto tryGroupsOfTwo = // Try adding groups of two items into the bin. - [&bin_area, &check_pair, + [&bin_area, &check_pair, &largestPiece, &smallestPiece, try_reverse] (Placer& placer, ItemList& not_packed, double waste, double& free_area, double& filled_area) { - double item_area = 0, largest_area = 0, smallest_area = 0; - double second_largest = 0, second_smallest = 0; - + double item_area = 0; const auto endit = not_packed.end(); if(not_packed.size() < 2) return false; // No group of two items else { - largest_area = not_packed.front().get().area(); + double largest_area = not_packed.front().get().area(); auto itmp = not_packed.begin(); itmp++; - second_largest = itmp->get().area(); + double second_largest = itmp->get().area(); if( free_area - second_largest - largest_area > waste) return false; // If even the largest two items do not fill // the bin to the desired waste than we can end here. - - smallest_area = not_packed.back().get().area(); - itmp = endit; std::advance(itmp, -2); - second_smallest = itmp->get().area(); } bool ret = false; @@ -241,17 +258,12 @@ public: std::vector wrong_pairs; - double largest = second_largest; - double smallest= smallest_area; - while(it != endit && !ret && free_area - - (item_area = it->get().area()) - largest <= waste ) + while(it != endit && !ret && + free_area - (item_area = it->get().area()) - + largestPiece(it, not_packed)->get().area() <= waste) { - // if this is the last element, the next smallest is the - // previous item - auto itmp = it; std::advance(itmp, 1); - if(itmp == endit) smallest = second_smallest; - - if(item_area + smallest > free_area ) { it++; continue; } + if(item_area + smallestPiece(it, not_packed)->get().area() > + free_area ) { it++; continue; } auto pr = placer.trypack(*it); @@ -300,8 +312,6 @@ public: } if(!ret) it++; - - largest = largest_area; } if(ret) { not_packed.erase(it); not_packed.erase(it2); } @@ -311,6 +321,8 @@ public: auto tryGroupsOfThree = // Try adding groups of three items. [&bin_area, + &smallestPiece, &largestPiece, + &secondSmallestPiece, &secondLargestPiece, &check_pair, &check_triplet, try_reverse] (Placer& placer, ItemList& not_packed, double waste, @@ -341,11 +353,8 @@ public: // We need to determine in each iteration the largest, second // largest, smallest and second smallest item in terms of area. - auto first = not_packed.begin(); - Item& largest = it == first? *std::next(it) : *first; - - auto second = std::next(first); - Item& second_largest = it == second ? *std::next(it) : *second; + Item& largest = *largestPiece(it, not_packed); + Item& second_largest = *secondLargestPiece(it, not_packed); double area_of_two_largest = largest.area() + second_largest.area(); @@ -356,23 +365,22 @@ public: break; // Determine the area of the two smallest item. - auto last = std::prev(endit); - Item& smallest = it == last? *std::prev(it) : *last; - auto second_last = std::prev(last); - Item& second_smallest = it == second_last? *std::prev(it) : - *second_last; + Item& smallest = *smallestPiece(it, not_packed); + Item& second_smallest = *secondSmallestPiece(it, not_packed); // Check if there is enough free area for the item and the two // smallest item. double area_of_two_smallest = smallest.area() + second_smallest.area(); + if(it->get().area() + area_of_two_smallest > free_area) { + it++; continue; + } + auto pr = placer.trypack(*it); // Check for free area and try to pack the 1st item... - if(!pr || it->get().area() + area_of_two_smallest > free_area) { - it++; continue; - } + if(!pr) { it++; continue; } it2 = not_packed.begin(); double rem2_area = free_area - largest.area(); @@ -434,6 +442,8 @@ public: check_triplet(wrong_triplets, *it, *it2, *it3)) { it3++; continue; } + if(a3_sum > free_area) { it3++; continue; } + placer.accept(pr12); placer.accept(pr2); bool can_pack3 = placer.pack(*it3); @@ -558,13 +568,12 @@ public: &makeProgress] (Placer& placer, ItemList& not_packed, size_t idx) { - bool can_pack = true; - double filled_area = placer.filledArea(); double free_area = bin_area - filled_area; double waste = .0; + bool lasttry = false; - while(!not_packed.empty() && can_pack) { + while(!not_packed.empty() ) { {// Fill the bin up to INITIAL_FILL_PROPORTION of its capacity auto it = not_packed.begin(); @@ -585,29 +594,31 @@ public: // try pieses one by one while(tryOneByOne(placer, not_packed, waste, free_area, filled_area)) { - waste = 0; + if(lasttry) std::cout << "Lasttry monopack" << std::endl; + waste = 0; lasttry = false; makeProgress(placer, idx, 1); } // try groups of 2 pieses while(tryGroupsOfTwo(placer, not_packed, waste, free_area, filled_area)) { - waste = 0; + if(lasttry) std::cout << "Lasttry bipack" << std::endl; + waste = 0; lasttry = false; makeProgress(placer, idx, 2); } - // try groups of 3 pieses - while(tryGroupsOfThree(placer, not_packed, waste, free_area, - filled_area)) { - waste = 0; - makeProgress(placer, idx, 3); - } +// // try groups of 3 pieses +// while(tryGroupsOfThree(placer, not_packed, waste, free_area, +// filled_area)) { +// if(lasttry) std::cout << "Lasttry tripack" << std::endl; +// waste = 0; lasttry = false; +// makeProgress(placer, idx, 3); +// } - if(waste < free_area) waste += w; - else if(!not_packed.empty()) can_pack = false; + waste += w; + if(!lasttry && waste > free_area) lasttry = true; + else if(lasttry) break; } - - return can_pack; }; size_t idx = 0; @@ -633,7 +644,7 @@ public: }; // We will create jobs for each bin - std::vector> rets(bincount_guess); + std::vector> rets(bincount_guess); for(unsigned b = 0; b < bincount_guess; b++) { // launch the jobs rets[b] = std::async(std::launch::async, job, b); diff --git a/xs/src/libnest2d/libnest2d/selections/filler.hpp b/xs/src/libnest2d/libnest2d/selections/filler.hpp index 94e30fd5b..d0018dc73 100644 --- a/xs/src/libnest2d/libnest2d/selections/filler.hpp +++ b/xs/src/libnest2d/libnest2d/selections/filler.hpp @@ -32,17 +32,20 @@ public: { store_.clear(); - store_.reserve(last-first); + auto total = last-first; + store_.reserve(total); packed_bins_.emplace_back(); - auto makeProgress = [this](PlacementStrategyLike& placer) { + auto makeProgress = [this, &total]( + PlacementStrategyLike& placer) + { packed_bins_.back() = placer.getItems(); #ifndef NDEBUG packed_bins_.back().insert(packed_bins_.back().end(), placer.getDebugItems().begin(), placer.getDebugItems().end()); #endif - this->progress_(packed_bins_.back().size()); + this->progress_(--total); }; std::copy(first, last, std::back_inserter(store_)); @@ -64,7 +67,7 @@ public: while(it != store_.end()) { if(!placer.pack(*it)) { if(packed_bins_.back().empty()) ++it; - makeProgress(placer); +// makeProgress(placer); placer.clearItems(); packed_bins_.emplace_back(); } else { diff --git a/xs/src/libnest2d/libnest2d/selections/firstfit.hpp b/xs/src/libnest2d/libnest2d/selections/firstfit.hpp index cf8f6da0b..8a8a09f91 100644 --- a/xs/src/libnest2d/libnest2d/selections/firstfit.hpp +++ b/xs/src/libnest2d/libnest2d/selections/firstfit.hpp @@ -49,24 +49,28 @@ public: std::sort(store_.begin(), store_.end(), sortfunc); + auto total = last-first; + auto makeProgress = [this, &total](Placer& placer, size_t idx) { + packed_bins_[idx] = placer.getItems(); + this->progress_(--total); + }; + for(auto& item : store_ ) { bool was_packed = false; while(!was_packed) { - for(size_t j = 0; j < placers.size() && !was_packed; j++) - was_packed = placers[j].pack(item); + for(size_t j = 0; j < placers.size() && !was_packed; j++) { + if(was_packed = placers[j].pack(item)) + makeProgress(placers[j], j); + } if(!was_packed) { placers.emplace_back(bin); placers.back().configure(pconfig); + packed_bins_.emplace_back(); } } } - - std::for_each(placers.begin(), placers.end(), - [this](Placer& placer){ - packed_bins_.push_back(placer.getItems()); - }); } }; diff --git a/xs/src/libnest2d/tests/CMakeLists.txt b/xs/src/libnest2d/tests/CMakeLists.txt index 3af5e6f70..3777f3c56 100644 --- a/xs/src/libnest2d/tests/CMakeLists.txt +++ b/xs/src/libnest2d/tests/CMakeLists.txt @@ -35,13 +35,17 @@ else() set(GTEST_LIBS_TO_LINK ${GTEST_BOTH_LIBRARIES} Threads::Threads) endif() -add_executable(bp2d_tests test.cpp svgtools.hpp printer_parts.h printer_parts.cpp) -target_link_libraries(bp2d_tests libnest2d_static ${GTEST_LIBS_TO_LINK} ) +add_executable(bp2d_tests test.cpp + ../tools/svgtools.hpp +# ../tools/libnfpglue.hpp +# ../tools/libnfpglue.cpp + printer_parts.h + printer_parts.cpp + ${LIBNEST2D_SRCFILES} + ) +target_link_libraries(bp2d_tests ${LIBNEST2D_LIBRARIES} ${GTEST_LIBS_TO_LINK} ) + target_include_directories(bp2d_tests PRIVATE BEFORE ${LIBNEST2D_HEADERS} ${GTEST_INCLUDE_DIRS}) -if(DEFINED LIBNEST2D_TEST_LIBRARIES) - target_link_libraries(bp2d_tests ${LIBNEST2D_TEST_LIBRARIES}) -endif() - add_test(libnest2d_tests bp2d_tests) diff --git a/xs/src/libnest2d/tests/printer_parts.cpp b/xs/src/libnest2d/tests/printer_parts.cpp index 6d36bc1cd..bdc2a3d43 100644 --- a/xs/src/libnest2d/tests/printer_parts.cpp +++ b/xs/src/libnest2d/tests/printer_parts.cpp @@ -2523,3 +2523,653 @@ const TestData STEGOSAUR_POLYGONS = {84531845, 127391708}, }, }; + +const TestDataEx PRINTER_PART_POLYGONS_EX = +{ + { + { + {533726562, 142141690}, + {532359712, 143386134}, + {530141290, 142155145}, + {528649729, 160091460}, + {533659500, 157607547}, + {538669739, 160091454}, + {537178168, 142155145}, + {534959534, 143386102}, + {533726562, 142141690}, + }, + { + }, + }, + { + { + {118305840, 11603332}, + {118311095, 26616786}, + {113311095, 26611146}, + {109311095, 29604752}, + {109300760, 44608489}, + {109311095, 49631801}, + {113300790, 52636806}, + {118311095, 52636806}, + {118308782, 103636810}, + {223830940, 103636981}, + {236845321, 90642174}, + {236832882, 11630488}, + {232825251, 11616786}, + {210149075, 11616786}, + {211308596, 13625149}, + {209315325, 17080886}, + {205326885, 17080886}, + {203334352, 13629720}, + {204493136, 11616786}, + {118305840, 11603332}, + }, + { + }, + }, + { + { + {365619370, 111280336}, + {365609100, 198818091}, + {387109100, 198804367}, + {387109100, 203279701}, + {471129120, 203279688}, + {471128689, 111283937}, + {365619370, 111280336}, + }, + { + }, + }, + { + { + {479997525, 19177632}, + {477473010, 21975778}, + {475272613, 21969219}, + {475267479, 32995796}, + {477026388, 32995796}, + {483041428, 22582411}, + {482560272, 20318630}, + {479997525, 19177632}, + }, + { + }, + }, + { + { + {476809080, 4972372}, + {475267479, 4975778}, + {475272613, 16002357}, + {481018177, 18281994}, + {482638044, 15466085}, + {476809080, 4972372}, + }, + { + }, + }, + { + { + {424866064, 10276075}, + {415113411, 10277960}, + {411723180, 13685293}, + {410473354, 18784347}, + {382490868, 18784008}, + {380996185, 17286945}, + {380996185, 11278161}, + {375976165, 11284347}, + {375976165, 56389754}, + {375169018, 57784347}, + {371996185, 57784347}, + {371996185, 53779177}, + {364976165, 53784347}, + {364969637, 56791976}, + {369214608, 61054367}, + {371474507, 61054367}, + {371473155, 98298160}, + {378476349, 105317193}, + {407491306, 105307497}, + {413509785, 99284903}, + {413496185, 48304367}, + {419496173, 48315719}, + {422501887, 45292801}, + {422500504, 39363184}, + {420425079, 37284347}, + {419476165, 43284347}, + {413496185, 43284347}, + {413497261, 30797428}, + {418986175, 25308513}, + {424005230, 25315076}, + {428496185, 20815924}, + {428512720, 13948847}, + {424866064, 10276075}, + }, + { + }, + }, + { + { + {723893066, 37354349}, + {717673034, 37370791}, + {717673034, 44872138}, + {715673034, 44867768}, + {715673034, 46055353}, + {699219526, 40066777}, + {697880758, 37748547}, + {691985477, 37748293}, + {689014018, 42869257}, + {691985477, 48016003}, + {697575093, 48003007}, + {715671494, 54589493}, + {715656800, 87142158}, + {759954611, 87142158}, + {764193054, 82897328}, + {764193054, 79872138}, + {757173034, 79866968}, + {757173034, 83872138}, + {754419422, 83869509}, + {753193054, 81739327}, + {753193054, 37360571}, + {723893066, 37354349}, + }, + { + }, + }, + { + { + {85607478, 4227596}, + {61739211, 4230337}, + {61739211, 13231393}, + {58725066, 13231405}, + {58721589, 27731406}, + {58738375, 30262521}, + {61739211, 30251413}, + {61736212, 38251411}, + {70759231, 38254724}, + {70905600, 33317391}, + {73749222, 31251468}, + {76592843, 33317393}, + {76739211, 38254516}, + {86765007, 38251411}, + {86759599, 4231393}, + {85607478, 4227596}, + }, + { + }, + }, + { + { + {534839721, 53437770}, + {534839721, 60849059}, + {539898273, 63773857}, + {545461140, 63757881}, + {544859741, 53447836}, + {541839721, 53437862}, + {541710836, 56353878}, + {540193984, 57229659}, + {538859741, 53437862}, + {534839721, 53437770}, + }, + { + }, + }, + { + { + {756086230, 136598477}, + {732054387, 136605752}, + {732052489, 172629505}, + {756091994, 172627853}, + {756086230, 136598477}, + }, + { + }, + }, + { + { + {100337034, 79731391}, + {70296833, 79731391}, + {70311095, 92263567}, + {74329808, 96264260}, + {96344976, 96257215}, + {100344419, 92232243}, + {100337034, 79731391}, + }, + { + }, + }, + { + { + {102331115, 44216643}, + {67311095, 44217252}, + {67311095, 69250964}, + {74329808, 76264260}, + {96334594, 76251411}, + {103335261, 69241401}, + {103345839, 44231404}, + {102331115, 44216643}, + }, + { + }, + }, + { + { + {93849749, 109613798}, + {91771666, 111698636}, + {91772404, 174626800}, + {96782902, 179645338}, + {241790509, 179645349}, + {246800716, 174626800}, + {246802574, 111699755}, + {243934250, 109616385}, + {93849749, 109613798}, + }, + { + }, + }, + { + { + {15856630, 87966835}, + {8414359, 91273170}, + {5891847, 99010553}, + {8403012, 104668172}, + {13739106, 107763252}, + {13739106, 116209175}, + {17959116, 116219127}, + {17959127, 107763252}, + {23952579, 103855773}, + {25806388, 96944174}, + {22553953, 90543787}, + {15856630, 87966835}, + }, + { + }, + }, + { + { + {503922805, 110421794}, + {491110107, 123244292}, + {479598157, 123244304}, + {479601067, 149264312}, + {494260327, 149265241}, + {502929782, 157948320}, + {506490250, 155806171}, + {502950518, 155094962}, + {507193172, 150852294}, + {504364680, 148023895}, + {535816833, 116571757}, + {538656617, 119411542}, + {542887886, 115157558}, + {543594970, 118693080}, + {545330008, 116966050}, + {540309189, 110425901}, + {503922805, 110421794}, + }, + { + }, + }, + { + { + {519310433, 62560296}, + {515749982, 64702434}, + {519289696, 65413661}, + {515047062, 69656303}, + {517875553, 72484703}, + {486423431, 103936848}, + {483595031, 101108448}, + {479352325, 105351055}, + {478645233, 101815525}, + {476917724, 103520870}, + {481923478, 110077233}, + {518337308, 110084297}, + {531130127, 97264312}, + {542630127, 97281049}, + {542639167, 71244292}, + {527979906, 71243363}, + {519310433, 62560296}, + }, + { + }, + }, + { + { + {528658425, 14775300}, + {525975568, 24475413}, + {522556814, 29181341}, + {517517474, 32090757}, + {511736147, 32698600}, + {506200465, 30901018}, + {501879743, 27011092}, + {497782491, 14775300}, + {492372374, 15588397}, + {489384268, 20795320}, + {491253082, 28537271}, + {495185363, 34469052}, + {495178475, 43927542}, + {502032399, 55796416}, + {524402581, 55807400}, + {531706434, 44295318}, + {531205383, 34469052}, + {536679415, 23789946}, + {535868173, 17264403}, + {532873348, 15073849}, + {528658425, 14775300}, + }, + { + }, + }, + { + { + {481122222, 166062916}, + {478115710, 166824472}, + {477103577, 169063247}, + {477106058, 192070670}, + {478623652, 194687013}, + {525109130, 195083267}, + {525117792, 198086965}, + {535129140, 198091624}, + {535129150, 195083267}, + {539038502, 194940807}, + {540865280, 193308821}, + {541132038, 169100183}, + {539614599, 166459484}, + {481122222, 166062916}, + }, + { + }, + }, + { + { + {23771404, 13005453}, + {24774973, 19182457}, + {31971050, 18727127}, + {32556286, 58337520}, + {25390683, 58337566}, + {25063762, 54707065}, + {20168811, 54707252}, + {20171550, 62917175}, + {70810377, 202895528}, + {74314421, 205588631}, + {88674817, 205515176}, + {91837376, 203083756}, + {92280287, 199307207}, + {40674807, 15904975}, + {36849630, 13006690}, + {23771404, 13005453}, + }, + { + }, + }, + { + { + {336421201, 2986256}, + {331176570, 6498191}, + {327552287, 5825511}, + {324913825, 2988891}, + {316226154, 2989990}, + {313040282, 6275291}, + {313040282, 23489990}, + {307126391, 23490002}, + {307140289, 25510010}, + {313040282, 25510010}, + {313040282, 28989990}, + {307126391, 28990002}, + {307140289, 31015515}, + {313040282, 31010010}, + {313040282, 35989990}, + {304534809, 37529785}, + {304524991, 73488855}, + {308554680, 77518546}, + {324040282, 77510010}, + {324040295, 93025333}, + {334574441, 93010010}, + {334574441, 90989990}, + {332560302, 90989990}, + {332560302, 85010010}, + {334560302, 85010010}, + {334561237, 82010010}, + {338540282, 82010010}, + {339540282, 83760010}, + {338540293, 93020012}, + {348060655, 93014679}, + {356564448, 84500000}, + {356560555, 28989990}, + {347334198, 29039989}, + {347334198, 25510010}, + {356510304, 25521084}, + {356510315, 23478922}, + {347560302, 23489990}, + {347560302, 5775291}, + {344874443, 2989990}, + {336421201, 2986256}, + }, + { + }, + }, + { + { + {465152221, 31684687}, + {457606880, 31688302}, + {452659362, 35508617}, + {449044605, 34734089}, + {446478972, 31692751}, + {437784814, 31692957}, + {435521210, 33956565}, + {435532195, 65697616}, + {426028494, 65691361}, + {426025938, 85049712}, + {435532195, 95717636}, + {435524445, 103754026}, + {436995898, 105225463}, + {447552204, 105226323}, + {447552215, 103197497}, + {444552215, 103197616}, + {444552215, 99217636}, + {452032195, 99217636}, + {452032195, 105221758}, + {465588513, 105225463}, + {467059965, 103754026}, + {467052215, 95717636}, + {478053039, 84511285}, + {478056214, 65697616}, + {468552215, 65697616}, + {468563959, 33957323}, + {465152221, 31684687}, + }, + { + }, + }, + { + { + {764927063, 92658416}, + {762115426, 94171595}, + {762122741, 131696443}, + {786415417, 132779578}, + {793690904, 129904572}, + {797383202, 124822853}, + {798269157, 120142660}, + {796710161, 114090278}, + {793387498, 110215980}, + {796094093, 103892242}, + {794107594, 96994001}, + {787445494, 92840355}, + {764927063, 92658416}, + }, + { + }, + }, + { + { + {27496331, 123147467}, + {3202195, 124246400}, + {3203433, 205768600}, + {20223453, 205775606}, + {20223644, 163243606}, + {31297341, 162189074}, + {36789517, 155659691}, + {36967183, 150566416}, + {34468182, 145711036}, + {38465496, 140400171}, + {38952460, 132613091}, + {34771593, 126022444}, + {27496331, 123147467}, + }, + { + }, + }, + { + { + {797556553, 39197820}, + {791313598, 39199767}, + {789506233, 39864015}, + {789522521, 48199767}, + {775974570, 48195721}, + {774022521, 50129235}, + {774008720, 76258022}, + {775974570, 78223833}, + {789522521, 78219787}, + {789522521, 86576919}, + {797556547, 87221747}, + {797556553, 39197820}, + }, + { + }, + }, + { + { + {676593113, 129820144}, + {676565322, 164844636}, + {701599609, 164858650}, + {701599609, 129823260}, + {676593113, 129820144}, + }, + { + }, + }, + { + { + {727646871, 93121321}, + {709122741, 93122138}, + {709122741, 125656310}, + {718769809, 135145243}, + {721622937, 135156111}, + {724152429, 132626619}, + {723734126, 112688301}, + {725837154, 107378546}, + {728976138, 104430846}, + {735847924, 102664848}, + {741289364, 104430846}, + {745202882, 108599767}, + {746590596, 114642158}, + {751137173, 114644887}, + {756151199, 109641674}, + {756149037, 94634278}, + {754642761, 93122138}, + {727646871, 93121321}, + }, + { + }, + }, + { + { + {135915724, 185598906}, + {131396265, 193419009}, + {131399444, 197643260}, + {140399444, 197636810}, + {140399444, 199138818}, + {157419464, 197643916}, + {157422805, 193210743}, + {153046747, 185604789}, + {149044579, 185614655}, + {147324399, 189850396}, + {144168954, 191108901}, + {141187892, 189479768}, + {139917659, 185615382}, + {135915724, 185598906}, + }, + { + }, + }, + { + { + {312619110, 154485844}, + {309601817, 157488332}, + {309599764, 203494810}, + {313109244, 207010010}, + {352900849, 207019221}, + {359629120, 200302405}, + {359638705, 159501827}, + {354621096, 154487830}, + {312619110, 154485844}, + }, + { + }, + }, + { + { + {313120315, 98984639}, + {309609100, 102486971}, + {309596977, 148492024}, + {312591195, 151510010}, + {354608772, 151524494}, + {359629120, 146515788}, + {359638123, 105715491}, + {352907860, 98987790}, + {313120315, 98984639}, + }, + { + }, + }, + { + { + {657746643, 86246732}, + {651722477, 92270881}, + {651720052, 131280884}, + {653947196, 131280884}, + {659746643, 125487816}, + {659746643, 119273826}, + {663742413, 112352691}, + {671726623, 112352691}, + {675733721, 119283349}, + {684745297, 119298573}, + {689758503, 114263168}, + {689752066, 91272158}, + {684746643, 86260871}, + {657746643, 86246732}, + }, + { + }, + }, + { + { + {653940791, 39260871}, + {651720052, 39260871}, + {651726623, 78280611}, + {657746631, 84295035}, + {684746643, 84280891}, + {689752066, 79269604}, + {689746643, 56247942}, + {684745283, 51243184}, + {675733721, 51258413}, + {671726623, 58189071}, + {663742413, 58189071}, + {659746643, 51267936}, + {659746643, 45053950}, + {653940791, 39260871}, + }, + { + }, + }, + { + { + {442365208, 3053303}, + {436408500, 5694021}, + {434342552, 11072741}, + {436986326, 17009033}, + {442365367, 19073360}, + {448299202, 16431441}, + {450365150, 11052721}, + {448299202, 5694021}, + {442365208, 3053303}, + }, + { + }, + }, +}; diff --git a/xs/src/libnest2d/tests/printer_parts.h b/xs/src/libnest2d/tests/printer_parts.h index 41791a189..b9a4eb8fa 100644 --- a/xs/src/libnest2d/tests/printer_parts.h +++ b/xs/src/libnest2d/tests/printer_parts.h @@ -4,9 +4,37 @@ #include #include +#ifndef CLIPPER_BACKEND_HPP +namespace ClipperLib { +using PointImpl = IntPoint; +using PathImpl = Path; +using HoleStore = std::vector; + +struct PolygonImpl { + PathImpl Contour; + HoleStore Holes; + + inline PolygonImpl() {} + + inline explicit PolygonImpl(const PathImpl& cont): Contour(cont) {} + inline explicit PolygonImpl(const HoleStore& holes): + Holes(holes) {} + inline PolygonImpl(const Path& cont, const HoleStore& holes): + Contour(cont), Holes(holes) {} + + inline explicit PolygonImpl(PathImpl&& cont): Contour(std::move(cont)) {} + inline explicit PolygonImpl(HoleStore&& holes): Holes(std::move(holes)) {} + inline PolygonImpl(Path&& cont, HoleStore&& holes): + Contour(std::move(cont)), Holes(std::move(holes)) {} +}; +} +#endif + using TestData = std::vector; +using TestDataEx = std::vector; extern const TestData PRINTER_PART_POLYGONS; extern const TestData STEGOSAUR_POLYGONS; +extern const TestDataEx PRINTER_PART_POLYGONS_EX; #endif // PRINTER_PARTS_H diff --git a/xs/src/libnest2d/tests/test.cpp b/xs/src/libnest2d/tests/test.cpp index 9791688ee..b37274f84 100644 --- a/xs/src/libnest2d/tests/test.cpp +++ b/xs/src/libnest2d/tests/test.cpp @@ -3,8 +3,8 @@ #include #include "printer_parts.h" -#include -#include +#include +//#include "../tools/libnfpglue.hpp" std::vector& prusaParts() { static std::vector ret; @@ -622,26 +622,65 @@ std::vector nfp_testdata = { } }; -} +std::vector nfp_concave_testdata = { + { // ItemPair + { + { + {533726, 142141}, + {532359, 143386}, + {530141, 142155}, + {528649, 160091}, + {533659, 157607}, + {538669, 160091}, + {537178, 142155}, + {534959, 143386}, + {533726, 142141}, + } + }, + { + { + {118305, 11603}, + {118311, 26616}, + {113311, 26611}, + {109311, 29604}, + {109300, 44608}, + {109311, 49631}, + {113300, 52636}, + {118311, 52636}, + {118308, 103636}, + {223830, 103636}, + {236845, 90642}, + {236832, 11630}, + {232825, 11616}, + {210149, 11616}, + {211308, 13625}, + {209315, 17080}, + {205326, 17080}, + {203334, 13629}, + {204493, 11616}, + {118305, 11603}, + } + }, + } +}; -TEST(GeometryAlgorithms, nfpConvexConvex) { +template +void testNfp(const std::vector& testdata) { using namespace libnest2d; - const Coord SCALE = 1000000; - Box bin(210*SCALE, 250*SCALE); int testcase = 0; - auto& exportfun = exportSVG<1, Box>; + auto& exportfun = exportSVG; auto onetest = [&](Item& orbiter, Item& stationary){ testcase++; orbiter.translate({210*SCALE, 0}); - auto&& nfp = Nfp::noFitPolygon(stationary.rawShape(), - orbiter.transformedShape()); + auto&& nfp = Nfp::noFitPolygon(stationary.rawShape(), + orbiter.transformedShape()); auto v = ShapeLike::isValid(nfp); @@ -667,11 +706,9 @@ TEST(GeometryAlgorithms, nfpConvexConvex) { tmp.translate({dx, dy}); - bool notinside = !tmp.isInside(stationary); - bool notintersecting = !Item::intersects(tmp, stationary) || - Item::touches(tmp, stationary); + bool touching = Item::touches(tmp, stationary); - if(!(notinside && notintersecting)) { + if(!touching) { std::vector> inp = { std::ref(stationary), std::ref(tmp), std::ref(infp) }; @@ -679,23 +716,31 @@ TEST(GeometryAlgorithms, nfpConvexConvex) { exportfun(inp, bin, testcase*i++); } - ASSERT_TRUE(notintersecting); - ASSERT_TRUE(notinside); + ASSERT_TRUE(touching); } }; - for(auto& td : nfp_testdata) { + for(auto& td : testdata) { auto orbiter = td.orbiter; auto stationary = td.stationary; onetest(orbiter, stationary); } - for(auto& td : nfp_testdata) { + for(auto& td : testdata) { auto orbiter = td.stationary; auto stationary = td.orbiter; onetest(orbiter, stationary); } } +} + +TEST(GeometryAlgorithms, nfpConvexConvex) { + testNfp(nfp_testdata); +} + +//TEST(GeometryAlgorithms, nfpConcaveConcave) { +// testNfp(nfp_concave_testdata); +//} TEST(GeometryAlgorithms, pointOnPolygonContour) { using namespace libnest2d; @@ -718,6 +763,29 @@ TEST(GeometryAlgorithms, pointOnPolygonContour) { } } +TEST(GeometryAlgorithms, mergePileWithPolygon) { + using namespace libnest2d; + + Rectangle rect1(10, 15); + Rectangle rect2(15, 15); + Rectangle rect3(20, 15); + + rect2.translate({10, 0}); + rect3.translate({25, 0}); + + ShapeLike::Shapes pile; + pile.push_back(rect1.transformedShape()); + pile.push_back(rect2.transformedShape()); + + auto result = Nfp::merge(pile, rect3.transformedShape()); + + ASSERT_EQ(result.size(), 1); + + Rectangle ref(45, 15); + + ASSERT_EQ(ShapeLike::area(result.front()), ref.area()); +} + int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/xs/src/libnest2d/tests/benchmark.h b/xs/src/libnest2d/tools/benchmark.h similarity index 100% rename from xs/src/libnest2d/tests/benchmark.h rename to xs/src/libnest2d/tools/benchmark.h diff --git a/xs/src/libnest2d/tools/libnfpglue.cpp b/xs/src/libnest2d/tools/libnfpglue.cpp new file mode 100644 index 000000000..4cbdb5442 --- /dev/null +++ b/xs/src/libnest2d/tools/libnfpglue.cpp @@ -0,0 +1,182 @@ +//#ifndef NDEBUG +//#define NFP_DEBUG +//#endif + +#include "libnfpglue.hpp" +#include "tools/libnfporb/libnfporb.hpp" + +namespace libnest2d { + +namespace { +inline bool vsort(const libnfporb::point_t& v1, const libnfporb::point_t& v2) +{ + using Coord = libnfporb::coord_t; + Coord x1 = v1.x_, x2 = v2.x_, y1 = v1.y_, y2 = v2.y_; + auto diff = y1 - y2; +#ifdef LIBNFP_USE_RATIONAL + long double diffv = diff.convert_to(); +#else + long double diffv = diff.val(); +#endif + if(std::abs(diffv) <= + std::numeric_limits::epsilon()) + return x1 < x2; + + return diff < 0; +} + +TCoord getX(const libnfporb::point_t& p) { +#ifdef LIBNFP_USE_RATIONAL + return p.x_.convert_to>(); +#else + return static_cast>(std::round(p.x_.val())); +#endif +} + +TCoord getY(const libnfporb::point_t& p) { +#ifdef LIBNFP_USE_RATIONAL + return p.y_.convert_to>(); +#else + return static_cast>(std::round(p.y_.val())); +#endif +} + +libnfporb::point_t scale(const libnfporb::point_t& p, long double factor) { +#ifdef LIBNFP_USE_RATIONAL + auto px = p.x_.convert_to(); + auto py = p.y_.convert_to(); +#else + long double px = p.x_.val(); + long double py = p.y_.val(); +#endif + return libnfporb::point_t(px*factor, py*factor); +} + +} + +PolygonImpl _nfp(const PolygonImpl &sh, const PolygonImpl &cother) +{ + using Vertex = PointImpl; + + PolygonImpl ret; + +// try { + libnfporb::polygon_t pstat, porb; + + boost::geometry::convert(sh, pstat); + boost::geometry::convert(cother, porb); + + long double factor = 0.0000001;//libnfporb::NFP_EPSILON; + long double refactor = 1.0/factor; + + for(auto& v : pstat.outer()) v = scale(v, factor); +// std::string message; +// boost::geometry::is_valid(pstat, message); +// std::cout << message << std::endl; + for(auto& h : pstat.inners()) for(auto& v : h) v = scale(v, factor); + + for(auto& v : porb.outer()) v = scale(v, factor); +// message; +// boost::geometry::is_valid(porb, message); +// std::cout << message << std::endl; + for(auto& h : porb.inners()) for(auto& v : h) v = scale(v, factor); + + + // this can throw + auto nfp = libnfporb::generateNFP(pstat, porb, true); + + auto &ct = ShapeLike::getContour(ret); + ct.reserve(nfp.front().size()+1); + for(auto v : nfp.front()) { + v = scale(v, refactor); + ct.emplace_back(getX(v), getY(v)); + } + ct.push_back(ct.front()); + std::reverse(ct.begin(), ct.end()); + + auto &rholes = ShapeLike::holes(ret); + for(size_t hidx = 1; hidx < nfp.size(); ++hidx) { + if(nfp[hidx].size() >= 3) { + rholes.push_back({}); + auto& h = rholes.back(); + h.reserve(nfp[hidx].size()+1); + + for(auto& v : nfp[hidx]) { + v = scale(v, refactor); + h.emplace_back(getX(v), getY(v)); + } + h.push_back(h.front()); + std::reverse(h.begin(), h.end()); + } + } + + auto& cmp = vsort; + std::sort(pstat.outer().begin(), pstat.outer().end(), cmp); + std::sort(porb.outer().begin(), porb.outer().end(), cmp); + + // leftmost lower vertex of the stationary polygon + auto& touch_sh = scale(pstat.outer().back(), refactor); + // rightmost upper vertex of the orbiting polygon + auto& touch_other = scale(porb.outer().front(), refactor); + + // Calculate the difference and move the orbiter to the touch position. + auto dtouch = touch_sh - touch_other; + auto _top_other = scale(porb.outer().back(), refactor) + dtouch; + + Vertex top_other(getX(_top_other), getY(_top_other)); + + // Get the righmost upper vertex of the nfp and move it to the RMU of + // the orbiter because they should coincide. + auto&& top_nfp = Nfp::rightmostUpVertex(ret); + auto dnfp = top_other - top_nfp; + + std::for_each(ShapeLike::begin(ret), ShapeLike::end(ret), + [&dnfp](Vertex& v) { v+= dnfp; } ); + + for(auto& h : ShapeLike::holes(ret)) + std::for_each( h.begin(), h.end(), + [&dnfp](Vertex& v) { v += dnfp; } ); + +// } catch(std::exception& e) { +// std::cout << "Error: " << e.what() << "\nTrying with convex hull..." << std::endl; +// auto ch_stat = ShapeLike::convexHull(sh); +// auto ch_orb = ShapeLike::convexHull(cother); +// ret = Nfp::nfpConvexOnly(ch_stat, ch_orb); +// } + + return ret; +} + +PolygonImpl Nfp::NfpImpl::operator()( + const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother) +{ + return _nfp(sh, cother);//nfpConvexOnly(sh, cother); +} + +PolygonImpl Nfp::NfpImpl::operator()( + const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother) +{ + return _nfp(sh, cother); +} + +PolygonImpl Nfp::NfpImpl::operator()( + const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother) +{ + return _nfp(sh, cother); +} + +PolygonImpl +Nfp::NfpImpl::operator()( + const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother) +{ + return _nfp(sh, cother); +} + +PolygonImpl +Nfp::NfpImpl::operator()( + const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother) +{ + return _nfp(sh, cother); +} + +} diff --git a/xs/src/libnest2d/tools/libnfpglue.hpp b/xs/src/libnest2d/tools/libnfpglue.hpp new file mode 100644 index 000000000..87b0e0833 --- /dev/null +++ b/xs/src/libnest2d/tools/libnfpglue.hpp @@ -0,0 +1,44 @@ +#ifndef LIBNFPGLUE_HPP +#define LIBNFPGLUE_HPP + +#include + +namespace libnest2d { + +PolygonImpl _nfp(const PolygonImpl& sh, const PolygonImpl& cother); + +template<> +struct Nfp::NfpImpl { + PolygonImpl operator()(const PolygonImpl& sh, const PolygonImpl& cother); +}; + +template<> +struct Nfp::NfpImpl { + PolygonImpl operator()(const PolygonImpl& sh, const PolygonImpl& cother); +}; + +template<> +struct Nfp::NfpImpl { + PolygonImpl operator()(const PolygonImpl& sh, const PolygonImpl& cother); +}; + +template<> +struct Nfp::NfpImpl { + PolygonImpl operator()(const PolygonImpl& sh, const PolygonImpl& cother); +}; + +template<> +struct Nfp::NfpImpl { + PolygonImpl operator()(const PolygonImpl& sh, const PolygonImpl& cother); +}; + +template<> struct Nfp::MaxNfpLevel { + static const BP2D_CONSTEXPR NfpLevel value = +// NfpLevel::CONVEX_ONLY; + NfpLevel::BOTH_CONCAVE_WITH_HOLES; +}; + +} + + +#endif // LIBNFPGLUE_HPP diff --git a/xs/src/libnest2d/tools/libnfporb/LICENSE b/xs/src/libnest2d/tools/libnfporb/LICENSE new file mode 100644 index 000000000..94a9ed024 --- /dev/null +++ b/xs/src/libnest2d/tools/libnfporb/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/xs/src/libnest2d/tools/libnfporb/ORIGIN b/xs/src/libnest2d/tools/libnfporb/ORIGIN new file mode 100644 index 000000000..788bfd9af --- /dev/null +++ b/xs/src/libnest2d/tools/libnfporb/ORIGIN @@ -0,0 +1,2 @@ +https://github.com/kallaballa/libnfp.git +commit hash a5cf9f6a76ddab95567fccf629d4d099b60237d7 \ No newline at end of file diff --git a/xs/src/libnest2d/tools/libnfporb/README.md b/xs/src/libnest2d/tools/libnfporb/README.md new file mode 100644 index 000000000..9698972be --- /dev/null +++ b/xs/src/libnest2d/tools/libnfporb/README.md @@ -0,0 +1,89 @@ +[![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0.en.html) +##### If you give me a real good reason i might be willing to give you permission to use it under a different license for a specific application. Real good reasons include the following (non-exhausive): the greater good, educational purpose and money :) + +# libnfporb +Implementation of a robust no-fit polygon generation in a C++ library using an orbiting approach. + +__Please note:__ The paper this implementation is based it on has several bad assumptions that required me to "improvise". That means the code doesn't reflect the paper anymore and is running way slower than expected. At the moment I'm working on implementing a new approach based on this paper (using minkowski sums): https://eprints.soton.ac.uk/36850/1/CORMSIS-05-05.pdf + +## Description + +The no-fit polygon optimization makes it possible to check for overlap (or non-overlapping touch) of two polygons with only 1 point in polygon check (by providing the set of non-overlapping placements). +This library implements the orbiting approach to generate the no-fit polygon: Given two polygons A and B, A is the stationary one and B the orbiting one, B is slid as tightly as possibly around the edges of polygon A. During the orbiting a chosen reference point is tracked. By tracking the movement of the reference point a third polygon can be generated: the no-fit polygon. + +Once the no-fit polygon has been generated it can be used to test for overlap by only checking if the reference point is inside the NFP (overlap) outside the NFP (no overlap) or exactly on the edge of the NFP (touch). + +### Examples: + +The polygons: + +![Start of NFP](/images/start.png?raw=true) + +Orbiting: + +![State 1](/images/next0.png?raw=true) +![State 2](/images/next1.png?raw=true) +![State 3](/images/next2.png?raw=true) +![State 4](/images/next3.png?raw=true) + +![State 5](/images/next4.png?raw=true) +![State 6](/images/next5.png?raw=true) +![State 7](/images/next6.png?raw=true) +![State 8](/images/next7.png?raw=true) + +![State 9](/images/next8.png?raw=true) + +The resulting NFP is red: + +![nfp](/images/nfp.png?raw=true) + +Polygons can have concavities, holes, interlocks or might fit perfectly: + +![concavities](/images/concavities.png?raw=true) +![hole](/images/hole.png?raw=true) +![interlock](/images/interlock.png?raw=true) +![jigsaw](/images/jigsaw.png?raw=true) + +## The Approach +The approch of this library is highly inspired by the scientific paper [Complete and robust no-fit polygon generation +for the irregular stock cutting problem](https://pdfs.semanticscholar.org/e698/0dd78306ba7d5bb349d20c6d8f2e0aa61062.pdf) and by [Svgnest](http://svgnest.com) + +Note that is wasn't completely possible to implement it as suggested in the paper because it had several shortcomings that prevent complete NFP generation on some of my test cases. Especially the termination criteria (reference point returns to first point of NFP) proved to be wrong (see: test-case rect). Also tracking of used edges can't be performed as suggested in the paper since there might be situations where no edge of A is traversed (see: test-case doublecon). + +By default the library is using floating point as coordinate type but by defining the flag "LIBNFP_USE_RATIONAL" the library can be instructed to use infinite precision. + +## Build +The library has two dependencies: [Boost Geometry](http://www.boost.org/doc/libs/1_65_1/libs/geometry/doc/html/index.html) and [libgmp](https://gmplib.org). You need to install those first before building. Note that building is only required for the examples. The library itself is header-only. + + git clone https://github.com/kallaballa/libnfp.git + cd libnfp + make + sudo make install + +## Code Example + +```c++ +//uncomment next line to use infinite precision (slow) +//#define LIBNFP_USE_RATIONAL +#include "../src/libnfp.hpp" + +int main(int argc, char** argv) { + using namespace libnfp; + polygon_t pA; + polygon_t pB; + //read polygons from wkt files + read_wkt_polygon(argv[1], pA); + read_wkt_polygon(argv[2], pB); + + //generate NFP of polygon A and polygon B and check the polygons for validity. + //When the third parameters is false validity check is skipped for a little performance increase + nfp_t nfp = generateNFP(pA, pB, true); + + //write a svg containing pA, pB and NFP + write_svg("nfp.svg",{pA,pB},nfp); + return 0; +} +``` +Run the example program: + + examples/nfp data/crossing/A.wkt data/crossing/B.wkt diff --git a/xs/src/libnest2d/tools/libnfporb/libnfporb.hpp b/xs/src/libnest2d/tools/libnfporb/libnfporb.hpp new file mode 100644 index 000000000..8cb34567e --- /dev/null +++ b/xs/src/libnest2d/tools/libnfporb/libnfporb.hpp @@ -0,0 +1,1547 @@ +#ifndef NFP_HPP_ +#define NFP_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_MSC_VER) && _MSC_VER <= 1800 || __cplusplus < 201103L + #define LIBNFP_NOEXCEPT + #define LIBNFP_CONSTEXPR +#elif __cplusplus >= 201103L + #define LIBNFP_NOEXCEPT noexcept + #define LIBNFP_CONSTEXPR constexpr +#endif + +#ifdef LIBNFP_USE_RATIONAL +#include +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef LIBNFP_USE_RATIONAL +namespace bm = boost::multiprecision; +#endif +namespace bg = boost::geometry; +namespace trans = boost::geometry::strategy::transform; + + +namespace libnfporb { +#ifdef NFP_DEBUG +#define DEBUG_VAL(x) std::cerr << x << std::endl; +#define DEBUG_MSG(title, value) std::cerr << title << ":" << value << std::endl; +#else +#define DEBUG_VAL(x) +#define DEBUG_MSG(title, value) +#endif + +using std::string; + +static LIBNFP_CONSTEXPR long double NFP_EPSILON=0.00000001; + +class LongDouble { +private: + long double val_; +public: + LongDouble() : val_(0) { + } + + LongDouble(const long double& val) : val_(val) { + } + + void setVal(const long double& v) { + val_ = v; + } + + long double val() const { + return val_; + } + + LongDouble operator/(const LongDouble& other) const { + return this->val_ / other.val_; + } + + LongDouble operator*(const LongDouble& other) const { + return this->val_ * other.val_; + } + + LongDouble operator-(const LongDouble& other) const { + return this->val_ - other.val_; + } + + LongDouble operator-() const { + return this->val_ * -1; + } + + LongDouble operator+(const LongDouble& other) const { + return this->val_ + other.val_; + } + + void operator/=(const LongDouble& other) { + this->val_ = this->val_ / other.val_; + } + + void operator*=(const LongDouble& other) { + this->val_ = this->val_ * other.val_; + } + + void operator-=(const LongDouble& other) { + this->val_ = this->val_ - other.val_; + } + + void operator+=(const LongDouble& other) { + this->val_ = this->val_ + other.val_; + } + + bool operator==(const int& other) const { + return this->operator ==(static_cast(other)); + } + + bool operator==(const LongDouble& other) const { + return this->operator ==(other.val()); + } + + bool operator==(const long double& other) const { + return this->val() == other; + } + + bool operator!=(const int& other) const { + return !this->operator ==(other); + } + + bool operator!=(const LongDouble& other) const { + return !this->operator ==(other); + } + + bool operator!=(const long double& other) const { + return !this->operator ==(other); + } + + bool operator<(const int& other) const { + return this->operator <(static_cast(other)); + } + + bool operator<(const LongDouble& other) const { + return this->operator <(other.val()); + } + + bool operator<(const long double& other) const { + return this->val() < other; + } + + bool operator>(const int& other) const { + return this->operator >(static_cast(other)); + } + + bool operator>(const LongDouble& other) const { + return this->operator >(other.val()); + } + + bool operator>(const long double& other) const { + return this->val() > other; + } + + bool operator>=(const int& other) const { + return this->operator >=(static_cast(other)); + } + + bool operator>=(const LongDouble& other) const { + return this->operator >=(other.val()); + } + + bool operator>=(const long double& other) const { + return this->val() >= other; + } + + bool operator<=(const int& other) const { + return this->operator <=(static_cast(other)); + } + + bool operator<=(const LongDouble& other) const { + return this->operator <=(other.val()); + } + + bool operator<=(const long double& other) const { + return this->val() <= other; + } +}; +} + + +namespace std { +template<> + struct numeric_limits + { + static const LIBNFP_CONSTEXPR bool is_specialized = true; + + static const LIBNFP_CONSTEXPR long double + min() LIBNFP_NOEXCEPT { return std::numeric_limits::min(); } + + static LIBNFP_CONSTEXPR long double + max() LIBNFP_NOEXCEPT { return std::numeric_limits::max(); } + +#if __cplusplus >= 201103L + static LIBNFP_CONSTEXPR long double + lowest() LIBNFP_NOEXCEPT { return -std::numeric_limits::lowest(); } +#endif + + static const LIBNFP_CONSTEXPR int digits = std::numeric_limits::digits; + static const LIBNFP_CONSTEXPR int digits10 = std::numeric_limits::digits10; +#if __cplusplus >= 201103L + static const LIBNFP_CONSTEXPR int max_digits10 + = std::numeric_limits::max_digits10; +#endif + static const LIBNFP_CONSTEXPR bool is_signed = true; + static const LIBNFP_CONSTEXPR bool is_integer = false; + static const LIBNFP_CONSTEXPR bool is_exact = false; + static const LIBNFP_CONSTEXPR int radix = std::numeric_limits::radix; + + static const LIBNFP_CONSTEXPR long double + epsilon() LIBNFP_NOEXCEPT { return libnfporb::NFP_EPSILON; } + + static const LIBNFP_CONSTEXPR long double + round_error() LIBNFP_NOEXCEPT { return 0.5L; } + + static const LIBNFP_CONSTEXPR int min_exponent = std::numeric_limits::min_exponent; + static const LIBNFP_CONSTEXPR int min_exponent10 = std::numeric_limits::min_exponent10; + static const LIBNFP_CONSTEXPR int max_exponent = std::numeric_limits::max_exponent; + static const LIBNFP_CONSTEXPR int max_exponent10 = std::numeric_limits::max_exponent10; + + + static const LIBNFP_CONSTEXPR bool has_infinity = std::numeric_limits::has_infinity; + static const LIBNFP_CONSTEXPR bool has_quiet_NaN = std::numeric_limits::has_quiet_NaN; + static const LIBNFP_CONSTEXPR bool has_signaling_NaN = has_quiet_NaN; + static const LIBNFP_CONSTEXPR float_denorm_style has_denorm + = std::numeric_limits::has_denorm; + static const LIBNFP_CONSTEXPR bool has_denorm_loss + = std::numeric_limits::has_denorm_loss; + + + static const LIBNFP_CONSTEXPR long double + infinity() LIBNFP_NOEXCEPT { return std::numeric_limits::infinity(); } + + static const LIBNFP_CONSTEXPR long double + quiet_NaN() LIBNFP_NOEXCEPT { return std::numeric_limits::quiet_NaN(); } + + static const LIBNFP_CONSTEXPR long double + signaling_NaN() LIBNFP_NOEXCEPT { return std::numeric_limits::signaling_NaN(); } + + + static const LIBNFP_CONSTEXPR long double + denorm_min() LIBNFP_NOEXCEPT { return std::numeric_limits::denorm_min(); } + + static const LIBNFP_CONSTEXPR bool is_iec559 + = has_infinity && has_quiet_NaN && has_denorm == denorm_present; + + static const LIBNFP_CONSTEXPR bool is_bounded = true; + static const LIBNFP_CONSTEXPR bool is_modulo = false; + + static const LIBNFP_CONSTEXPR bool traps = std::numeric_limits::traps; + static const LIBNFP_CONSTEXPR bool tinyness_before = + std::numeric_limits::tinyness_before; + static const LIBNFP_CONSTEXPR float_round_style round_style = + round_to_nearest; + }; +} + +namespace boost { +namespace numeric { + template<> + struct raw_converter> + { + typedef boost::numeric::conversion_traits::result_type result_type ; + typedef boost::numeric::conversion_traits::argument_type argument_type ; + + static result_type low_level_convert ( argument_type s ) { return s.val() ; } + } ; +} +} + +namespace libnfporb { + +#ifndef LIBNFP_USE_RATIONAL +typedef LongDouble coord_t; +#else +typedef bm::number rational_t; +typedef rational_t coord_t; +#endif + +bool equals(const LongDouble& lhs, const LongDouble& rhs); +#ifdef LIBNFP_USE_RATIONAL +bool equals(const rational_t& lhs, const rational_t& rhs); +#endif +bool equals(const long double& lhs, const long double& rhs); + +const coord_t MAX_COORD = 999999999999999999.0; +const coord_t MIN_COORD = std::numeric_limits::min(); + +class point_t { +public: + point_t() : x_(0), y_(0) { + } + point_t(coord_t x, coord_t y) : x_(x), y_(y) { + } + bool marked_ = false; + coord_t x_; + coord_t y_; + + point_t operator-(const point_t& other) const { + point_t result = *this; + bg::subtract_point(result, other); + return result; + } + + point_t operator+(const point_t& other) const { + point_t result = *this; + bg::add_point(result, other); + return result; + } + + bool operator==(const point_t& other) const { + return bg::equals(this, other); + } + + bool operator!=(const point_t& other) const { + return !this->operator ==(other); + } + + bool operator<(const point_t& other) const { + return boost::geometry::math::smaller(this->x_, other.x_) || (equals(this->x_, other.x_) && boost::geometry::math::smaller(this->y_, other.y_)); + } +}; + + + + +inline long double toLongDouble(const LongDouble& c) { + return c.val(); +} + +#ifdef LIBNFP_USE_RATIONAL +inline long double toLongDouble(const rational_t& c) { + return bm::numerator(c).convert_to() / bm::denominator(c).convert_to(); +} +#endif + +std::ostream& operator<<(std::ostream& os, const coord_t& p) { + os << toLongDouble(p); + return os; +} + +std::istream& operator>>(std::istream& is, LongDouble& c) { + long double val; + is >> val; + c.setVal(val); + return is; +} + +std::ostream& operator<<(std::ostream& os, const point_t& p) { + os << "{" << toLongDouble(p.x_) << "," << toLongDouble(p.y_) << "}"; + return os; +} +const point_t INVALID_POINT = {MAX_COORD, MAX_COORD}; + +typedef bg::model::segment segment_t; +} + +#ifdef LIBNFP_USE_RATIONAL +inline long double acos(const libnfporb::rational_t& r) { + return acos(libnfporb::toLongDouble(r)); +} +#endif + +inline long double acos(const libnfporb::LongDouble& ld) { + return acos(libnfporb::toLongDouble(ld)); +} + +#ifdef LIBNFP_USE_RATIONAL +inline long double sqrt(const libnfporb::rational_t& r) { + return sqrt(libnfporb::toLongDouble(r)); +} +#endif + +inline long double sqrt(const libnfporb::LongDouble& ld) { + return sqrt(libnfporb::toLongDouble(ld)); +} + +BOOST_GEOMETRY_REGISTER_POINT_2D(libnfporb::point_t, libnfporb::coord_t, cs::cartesian, x_, y_) + + +namespace boost { +namespace geometry { +namespace math { +namespace detail { + +template <> +struct square_root +{ + typedef libnfporb::LongDouble return_type; + + static inline libnfporb::LongDouble apply(libnfporb::LongDouble const& a) + { + return std::sqrt(a.val()); + } +}; + +#ifdef LIBNFP_USE_RATIONAL +template <> +struct square_root +{ + typedef libnfporb::rational_t return_type; + + static inline libnfporb::rational_t apply(libnfporb::rational_t const& a) + { + return std::sqrt(libnfporb::toLongDouble(a)); + } +}; +#endif + +template<> +struct abs + { + static libnfporb::LongDouble apply(libnfporb::LongDouble const& value) + { + libnfporb::LongDouble const zero = libnfporb::LongDouble(); + return value.val() < zero.val() ? -value.val() : value.val(); + } + }; + +template <> +struct equals +{ + template + static inline bool apply(libnfporb::LongDouble const& lhs, libnfporb::LongDouble const& rhs, Policy const& policy) + { + if(lhs.val() == rhs.val()) + return true; + + return bg::math::detail::abs::apply(lhs.val() - rhs.val()) <= policy.apply(lhs.val(), rhs.val()) * libnfporb::NFP_EPSILON; + } +}; + +template <> +struct smaller +{ + static inline bool apply(libnfporb::LongDouble const& lhs, libnfporb::LongDouble const& rhs) + { + if(lhs.val() == rhs.val() || bg::math::detail::abs::apply(lhs.val() - rhs.val()) <= libnfporb::NFP_EPSILON * std::max(lhs.val(), rhs.val())) + return false; + + return lhs < rhs; + } +}; +} +} +} +} + +namespace libnfporb { +inline bool smaller(const LongDouble& lhs, const LongDouble& rhs) { + return boost::geometry::math::detail::smaller::apply(lhs, rhs); +} + +inline bool larger(const LongDouble& lhs, const LongDouble& rhs) { + return smaller(rhs, lhs); +} + +bool equals(const LongDouble& lhs, const LongDouble& rhs) { + if(lhs.val() == rhs.val()) + return true; + + return bg::math::detail::abs::apply(lhs.val() - rhs.val()) <= libnfporb::NFP_EPSILON * std::max(lhs.val(), rhs.val()); +} + +#ifdef LIBNFP_USE_RATIONAL +inline bool smaller(const rational_t& lhs, const rational_t& rhs) { + return lhs < rhs; +} + +inline bool larger(const rational_t& lhs, const rational_t& rhs) { + return smaller(rhs, lhs); +} + +bool equals(const rational_t& lhs, const rational_t& rhs) { + return lhs == rhs; +} +#endif + +inline bool smaller(const long double& lhs, const long double& rhs) { + return lhs < rhs; +} + +inline bool larger(const long double& lhs, const long double& rhs) { + return smaller(rhs, lhs); +} + + +bool equals(const long double& lhs, const long double& rhs) { + return lhs == rhs; +} + +typedef bg::model::polygon polygon_t; +typedef std::vector nfp_t; +typedef bg::model::linestring linestring_t; + +typedef polygon_t::ring_type::size_type psize_t; + +typedef bg::model::d2::point_xy pointf_t; +typedef bg::model::segment segmentf_t; +typedef bg::model::polygon polygonf_t; + +polygonf_t::ring_type convert(const polygon_t::ring_type& r) { + polygonf_t::ring_type rf; + for(const auto& pt : r) { + rf.push_back(pointf_t(toLongDouble(pt.x_), toLongDouble(pt.y_))); + } + return rf; +} + +polygonf_t convert(polygon_t p) { + polygonf_t pf; + pf.outer() = convert(p.outer()); + + for(const auto& r : p.inners()) { + pf.inners().push_back(convert(r)); + } + + return pf; +} + +polygon_t nfpRingsToNfpPoly(const nfp_t& nfp) { + polygon_t nfppoly; + for (const auto& pt : nfp.front()) { + nfppoly.outer().push_back(pt); + } + + for (size_t i = 1; i < nfp.size(); ++i) { + nfppoly.inners().push_back({}); + for (const auto& pt : nfp[i]) { + nfppoly.inners().back().push_back(pt); + } + } + + return nfppoly; +} + +void write_svg(std::string const& filename,const std::vector& segments) { + std::ofstream svg(filename.c_str()); + + boost::geometry::svg_mapper mapper(svg, 100, 100, "width=\"200mm\" height=\"200mm\" viewBox=\"-250 -250 500 500\""); + for(const auto& seg : segments) { + segmentf_t segf({toLongDouble(seg.first.x_), toLongDouble(seg.first.y_)}, {toLongDouble(seg.second.x_), toLongDouble(seg.second.y_)}); + mapper.add(segf); + mapper.map(segf, "fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2"); + } +} + +void write_svg(std::string const& filename, const polygon_t& p, const polygon_t::ring_type& ring) { + std::ofstream svg(filename.c_str()); + + boost::geometry::svg_mapper mapper(svg, 100, 100, "width=\"200mm\" height=\"200mm\" viewBox=\"-250 -250 500 500\""); + auto pf = convert(p); + auto rf = convert(ring); + + mapper.add(pf); + mapper.map(pf, "fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2"); + mapper.add(rf); + mapper.map(rf, "fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2"); +} + +void write_svg(std::string const& filename, std::vector const& polygons) { + std::ofstream svg(filename.c_str()); + + boost::geometry::svg_mapper mapper(svg, 100, 100, "width=\"200mm\" height=\"200mm\" viewBox=\"-250 -250 500 500\""); + for (auto p : polygons) { + auto pf = convert(p); + mapper.add(pf); + mapper.map(pf, "fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2"); + } +} + +void write_svg(std::string const& filename, std::vector const& polygons, const nfp_t& nfp) { + polygon_t nfppoly; + for (const auto& pt : nfp.front()) { + nfppoly.outer().push_back(pt); + } + + for (size_t i = 1; i < nfp.size(); ++i) { + nfppoly.inners().push_back({}); + for (const auto& pt : nfp[i]) { + nfppoly.inners().back().push_back(pt); + } + } + std::ofstream svg(filename.c_str()); + + boost::geometry::svg_mapper mapper(svg, 100, 100, "width=\"200mm\" height=\"200mm\" viewBox=\"-250 -250 500 500\""); + for (auto p : polygons) { + auto pf = convert(p); + mapper.add(pf); + mapper.map(pf, "fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2"); + } + bg::correct(nfppoly); + auto nfpf = convert(nfppoly); + mapper.add(nfpf); + mapper.map(nfpf, "fill-opacity:0.5;fill:rgb(204,153,0);stroke:rgb(204,153,0);stroke-width:2"); + + for(auto& r: nfpf.inners()) { + if(r.size() == 1) { + mapper.add(r.front()); + mapper.map(r.front(), "fill-opacity:0.5;fill:rgb(204,153,0);stroke:rgb(204,153,0);stroke-width:2"); + } else if(r.size() == 2) { + segmentf_t seg(r.front(), *(r.begin()+1)); + mapper.add(seg); + mapper.map(seg, "fill-opacity:0.5;fill:rgb(204,153,0);stroke:rgb(204,153,0);stroke-width:2"); + } + } +} + +std::ostream& operator<<(std::ostream& os, const segment_t& seg) { + os << "{" << seg.first << "," << seg.second << "}"; + return os; +} + +bool operator<(const segment_t& lhs, const segment_t& rhs) { + return lhs.first < rhs.first || ((lhs.first == rhs.first) && (lhs.second < rhs.second)); +} + +bool operator==(const segment_t& lhs, const segment_t& rhs) { + return (lhs.first == rhs.first && lhs.second == rhs.second) || (lhs.first == rhs.second && lhs.second == rhs.first); +} + +bool operator!=(const segment_t& lhs, const segment_t& rhs) { + return !operator==(lhs,rhs); +} + +enum Alignment { + LEFT, + RIGHT, + ON +}; + +point_t normalize(const point_t& pt) { + point_t norm = pt; + coord_t len = bg::length(segment_t{{0,0},pt}); + + if(len == 0.0L) + return {0,0}; + + norm.x_ /= len; + norm.y_ /= len; + + return norm; +} + +Alignment get_alignment(const segment_t& seg, const point_t& pt){ + coord_t res = ((seg.second.x_ - seg.first.x_)*(pt.y_ - seg.first.y_) + - (seg.second.y_ - seg.first.y_)*(pt.x_ - seg.first.x_)); + + if(equals(res, 0)) { + return ON; + } else if(larger(res,0)) { + return LEFT; + } else { + return RIGHT; + } +} + +long double get_inner_angle(const point_t& joint, const point_t& end1, const point_t& end2) { + coord_t dx21 = end1.x_-joint.x_; + coord_t dx31 = end2.x_-joint.x_; + coord_t dy21 = end1.y_-joint.y_; + coord_t dy31 = end2.y_-joint.y_; + coord_t m12 = sqrt((dx21*dx21 + dy21*dy21)); + coord_t m13 = sqrt((dx31*dx31 + dy31*dy31)); + if(m12 == 0.0L || m13 == 0.0L) + return 0; + return acos( (dx21*dx31 + dy21*dy31) / (m12 * m13) ); +} + +struct TouchingPoint { + enum Type { + VERTEX, + A_ON_B, + B_ON_A + }; + Type type_; + psize_t A_; + psize_t B_; +}; + +struct TranslationVector { + point_t vector_; + segment_t edge_; + bool fromA_; + string name_; + + bool operator<(const TranslationVector& other) const { + return this->vector_ < other.vector_ || ((this->vector_ == other.vector_) && (this->edge_ < other.edge_)); + } +}; + +std::ostream& operator<<(std::ostream& os, const TranslationVector& tv) { + os << "{" << tv.edge_ << " -> " << tv.vector_ << "} = " << tv.name_; + return os; +} + + +void read_wkt_polygon(const string& filename, polygon_t& p) { + std::ifstream t(filename); + + std::string str; + t.seekg(0, std::ios::end); + str.reserve(t.tellg()); + t.seekg(0, std::ios::beg); + + str.assign((std::istreambuf_iterator(t)), + std::istreambuf_iterator()); + + str.pop_back(); + bg::read_wkt(str, p); + bg::correct(p); +} + +std::vector find_minimum_y(const polygon_t& p) { + std::vector result; + coord_t min = MAX_COORD; + auto& po = p.outer(); + for(psize_t i = 0; i < p.outer().size() - 1; ++i) { + if(smaller(po[i].y_, min)) { + result.clear(); + min = po[i].y_; + result.push_back(i); + } else if (equals(po[i].y_, min)) { + result.push_back(i); + } + } + return result; +} + +std::vector find_maximum_y(const polygon_t& p) { + std::vector result; + coord_t max = MIN_COORD; + auto& po = p.outer(); + for(psize_t i = 0; i < p.outer().size() - 1; ++i) { + if(larger(po[i].y_, max)) { + result.clear(); + max = po[i].y_; + result.push_back(i); + } else if (equals(po[i].y_, max)) { + result.push_back(i); + } + } + return result; +} + +psize_t find_point(const polygon_t::ring_type& ring, const point_t& pt) { + for(psize_t i = 0; i < ring.size(); ++i) { + if(ring[i] == pt) + return i; + } + return std::numeric_limits::max(); +} + +std::vector findTouchingPoints(const polygon_t::ring_type& ringA, const polygon_t::ring_type& ringB) { + std::vector touchers; + for(psize_t i = 0; i < ringA.size() - 1; i++) { + psize_t nextI = i+1; + for(psize_t j = 0; j < ringB.size() - 1; j++) { + psize_t nextJ = j+1; + if(ringA[i] == ringB[j]) { + touchers.push_back({TouchingPoint::VERTEX, i, j}); + } else if (ringA[nextI] != ringB[j] && bg::intersects(segment_t(ringA[i],ringA[nextI]), ringB[j])) { + touchers.push_back({TouchingPoint::B_ON_A, nextI, j}); + } else if (ringB[nextJ] != ringA[i] && bg::intersects(segment_t(ringB[j],ringB[nextJ]), ringA[i])) { + touchers.push_back({TouchingPoint::A_ON_B, i, nextJ}); + } + } + } + return touchers; +} + +//TODO deduplicate code +TranslationVector trimVector(const polygon_t::ring_type& rA, const polygon_t::ring_type& rB, const TranslationVector& tv) { + coord_t shortest = bg::length(tv.edge_); + TranslationVector trimmed = tv; + for(const auto& ptA : rA) { + point_t translated; + //for polygon A we invert the translation + trans::translate_transformer translate(-tv.vector_.x_, -tv.vector_.y_); + boost::geometry::transform(ptA, translated, translate); + linestring_t projection; + segment_t segproj(ptA, translated); + projection.push_back(ptA); + projection.push_back(translated); + std::vector intersections; + bg::intersection(rB, projection, intersections); + if(bg::touches(projection, rB) && intersections.size() < 2) { + continue; + } + + //find shortest intersection + coord_t len; + segment_t segi; + for(const auto& pti : intersections) { + segi = segment_t(ptA,pti); + len = bg::length(segi); + if(smaller(len, shortest)) { + trimmed.vector_ = ptA - pti; + trimmed.edge_ = segi; + shortest = len; + } + } + } + + for(const auto& ptB : rB) { + point_t translated; + + trans::translate_transformer translate(tv.vector_.x_, tv.vector_.y_); + boost::geometry::transform(ptB, translated, translate); + linestring_t projection; + segment_t segproj(ptB, translated); + projection.push_back(ptB); + projection.push_back(translated); + std::vector intersections; + bg::intersection(rA, projection, intersections); + if(bg::touches(projection, rA) && intersections.size() < 2) { + continue; + } + + //find shortest intersection + coord_t len; + segment_t segi; + for(const auto& pti : intersections) { + + segi = segment_t(ptB,pti); + len = bg::length(segi); + if(smaller(len, shortest)) { + trimmed.vector_ = pti - ptB; + trimmed.edge_ = segi; + shortest = len; + } + } + } + return trimmed; +} + +std::vector findFeasibleTranslationVectors(polygon_t::ring_type& ringA, polygon_t::ring_type& ringB, const std::vector& touchers) { + //use a set to automatically filter duplicate vectors + std::vector potentialVectors; + std::vector> touchEdges; + + for (psize_t i = 0; i < touchers.size(); i++) { + point_t& vertexA = ringA[touchers[i].A_]; + vertexA.marked_ = true; + + // adjacent A vertices + auto prevAindex = static_cast(touchers[i].A_ - 1); + auto nextAindex = static_cast(touchers[i].A_ + 1); + + prevAindex = (prevAindex < 0) ? static_cast(ringA.size() - 2) : prevAindex; // loop + nextAindex = (static_cast(nextAindex) >= ringA.size()) ? 1 : nextAindex; // loop + + point_t& prevA = ringA[prevAindex]; + point_t& nextA = ringA[nextAindex]; + + // adjacent B vertices + point_t& vertexB = ringB[touchers[i].B_]; + + auto prevBindex = static_cast(touchers[i].B_ - 1); + auto nextBindex = static_cast(touchers[i].B_ + 1); + + prevBindex = (prevBindex < 0) ? static_cast(ringB.size() - 2) : prevBindex; // loop + nextBindex = (static_cast(nextBindex) >= ringB.size()) ? 1 : nextBindex; // loop + + point_t& prevB = ringB[prevBindex]; + point_t& nextB = ringB[nextBindex]; + + if (touchers[i].type_ == TouchingPoint::VERTEX) { + segment_t a1 = { vertexA, nextA }; + segment_t a2 = { vertexA, prevA }; + segment_t b1 = { vertexB, nextB }; + segment_t b2 = { vertexB, prevB }; + + //swap the segment elements so that always the first point is the touching point + //also make the second segment always a segment of ringB + touchEdges.push_back({a1, b1}); + touchEdges.push_back({a1, b2}); + touchEdges.push_back({a2, b1}); + touchEdges.push_back({a2, b2}); +#ifdef NFP_DEBUG + write_svg("touchersV" + std::to_string(i) + ".svg", {a1,a2,b1,b2}); +#endif + + //TODO test parallel edges for floating point stability + Alignment al; + //a1 and b1 meet at start vertex + al = get_alignment(a1, b1.second); + if(al == LEFT) { + potentialVectors.push_back({b1.first - b1.second, b1, false, "vertex1"}); + } else if(al == RIGHT) { + potentialVectors.push_back({a1.second - a1.first, a1, true, "vertex2"}); + } else { + potentialVectors.push_back({a1.second - a1.first, a1, true, "vertex3"}); + } + + //a1 and b2 meet at start and end + al = get_alignment(a1, b2.second); + if(al == LEFT) { + //no feasible translation + } else if(al == RIGHT) { + potentialVectors.push_back({a1.second - a1.first, a1, true, "vertex4"}); + } else { + potentialVectors.push_back({a1.second - a1.first, a1, true, "vertex5"}); + } + + //a2 and b1 meet at end and start + al = get_alignment(a2, b1.second); + if(al == LEFT) { + //no feasible translation + } else if(al == RIGHT) { + potentialVectors.push_back({b1.first - b1.second, b1, false, "vertex6"}); + } else { + potentialVectors.push_back({b1.first - b1.second, b1, false, "vertex7"}); + } + } else if (touchers[i].type_ == TouchingPoint::B_ON_A) { + segment_t a1 = {vertexB, vertexA}; + segment_t a2 = {vertexB, prevA}; + segment_t b1 = {vertexB, prevB}; + segment_t b2 = {vertexB, nextB}; + + touchEdges.push_back({a1, b1}); + touchEdges.push_back({a1, b2}); + touchEdges.push_back({a2, b1}); + touchEdges.push_back({a2, b2}); +#ifdef NFP_DEBUG + write_svg("touchersB" + std::to_string(i) + ".svg", {a1,a2,b1,b2}); +#endif + potentialVectors.push_back({vertexA - vertexB, {vertexB, vertexA}, true, "bona"}); + } else if (touchers[i].type_ == TouchingPoint::A_ON_B) { + //TODO testme + segment_t a1 = {vertexA, prevA}; + segment_t a2 = {vertexA, nextA}; + segment_t b1 = {vertexA, vertexB}; + segment_t b2 = {vertexA, prevB}; +#ifdef NFP_DEBUG + write_svg("touchersA" + std::to_string(i) + ".svg", {a1,a2,b1,b2}); +#endif + touchEdges.push_back({a1, b1}); + touchEdges.push_back({a2, b1}); + touchEdges.push_back({a1, b2}); + touchEdges.push_back({a2, b2}); + potentialVectors.push_back({vertexA - vertexB, {vertexA, vertexB}, false, "aonb"}); + } + } + + //discard immediately intersecting translations + std::vector vectors; + for(const auto& v : potentialVectors) { + bool discarded = false; + for(const auto& sp : touchEdges) { + point_t normEdge = normalize(v.edge_.second - v.edge_.first); + point_t normFirst = normalize(sp.first.second - sp.first.first); + point_t normSecond = normalize(sp.second.second - sp.second.first); + + Alignment a1 = get_alignment({{0,0},normEdge}, normFirst); + Alignment a2 = get_alignment({{0,0},normEdge}, normSecond); + + if(a1 == a2 && a1 != ON) { + long double df = get_inner_angle({0,0},normEdge, normFirst); + long double ds = get_inner_angle({0,0},normEdge, normSecond); + + point_t normIn = normalize(v.edge_.second - v.edge_.first); + if (equals(df, ds)) { + TranslationVector trimmed = trimVector(ringA,ringB, v); + polygon_t::ring_type translated; + trans::translate_transformer translate(trimmed.vector_.x_, trimmed.vector_.y_); + boost::geometry::transform(ringB, translated, translate); + if (!(bg::intersects(translated, ringA) && !bg::overlaps(translated, ringA) && !bg::covered_by(translated, ringA) && !bg::covered_by(ringA, translated))) { + discarded = true; + break; + } + } else { + + if (normIn == normalize(v.vector_)) { + if (larger(ds, df)) { + discarded = true; + break; + } + } else { + if (smaller(ds, df)) { + discarded = true; + break; + } + } + } + } + } + if(!discarded) + vectors.push_back(v); + } + return vectors; +} + +bool find(const std::vector& h, const TranslationVector& tv) { + for(const auto& htv : h) { + if(htv.vector_ == tv.vector_) + return true; + } + return false; +} + +TranslationVector getLongest(const std::vector& tvs) { + coord_t len; + coord_t maxLen = MIN_COORD; + TranslationVector longest; + longest.vector_ = INVALID_POINT; + + for(auto& tv : tvs) { + len = bg::length(segment_t{{0,0},tv.vector_}); + if(larger(len, maxLen)) { + maxLen = len; + longest = tv; + } + } + return longest; +} + +TranslationVector selectNextTranslationVector(const polygon_t& pA, const polygon_t::ring_type& rA, const polygon_t::ring_type& rB, const std::vector& tvs, const std::vector& history) { + if(!history.empty()) { + TranslationVector last = history.back(); + std::vector historyCopy = history; + if(historyCopy.size() >= 2) { + historyCopy.erase(historyCopy.end() - 1); + historyCopy.erase(historyCopy.end() - 1); + if(historyCopy.size() > 4) { + historyCopy.erase(historyCopy.begin(), historyCopy.end() - 4); + } + + } else { + historyCopy.clear(); + } + DEBUG_MSG("last", last); + + psize_t laterI = std::numeric_limits::max(); + point_t previous = rA[0]; + point_t next; + + if(last.fromA_) { + for (psize_t i = 1; i < rA.size() + 1; ++i) { + if (i >= rA.size()) + next = rA[i % rA.size()]; + else + next = rA[i]; + + segment_t candidate( previous, next ); + if(candidate == last.edge_) { + laterI = i; + break; + } + previous = next; + } + + if (laterI == std::numeric_limits::max()) { + point_t later; + if (last.vector_ == (last.edge_.second - last.edge_.first)) { + later = last.edge_.second; + } else { + later = last.edge_.first; + } + + laterI = find_point(rA, later); + } + } else { + point_t later; + if (last.vector_ == (last.edge_.second - last.edge_.first)) { + later = last.edge_.second; + } else { + later = last.edge_.first; + } + + laterI = find_point(rA, later); + } + + if (laterI == std::numeric_limits::max()) { + throw std::runtime_error( + "Internal error: Can't find later point of last edge"); + } + + std::vector viableEdges; + previous = rA[laterI]; + for(psize_t i = laterI + 1; i < rA.size() + laterI + 1; ++i) { + if(i >= rA.size()) + next = rA[i % rA.size()]; + else + next = rA[i]; + + viableEdges.push_back({previous, next}); + previous = next; + } + +// auto rng = std::default_random_engine {}; +// std::shuffle(std::begin(viableEdges), std::end(viableEdges), rng); + + //search with consulting the history to prevent oscillation + std::vector viableTrans; + for(const auto& ve: viableEdges) { + for(const auto& tv : tvs) { + if((tv.fromA_ && (normalize(tv.vector_) == normalize(ve.second - ve.first))) && (tv.edge_ != last.edge_ || tv.vector_.x_ != -last.vector_.x_ || tv.vector_.y_ != -last.vector_.y_) && !find(historyCopy, tv)) { + viableTrans.push_back(tv); + } + } + for (const auto& tv : tvs) { + if (!tv.fromA_) { + point_t later; + if (tv.vector_ == (tv.edge_.second - tv.edge_.first) && (tv.edge_ != last.edge_ || tv.vector_.x_ != -last.vector_.x_ || tv.vector_.y_ != -last.vector_.y_) && !find(historyCopy, tv)) { + later = tv.edge_.second; + } else if (tv.vector_ == (tv.edge_.first - tv.edge_.second)) { + later = tv.edge_.first; + } else + continue; + + if (later == ve.first || later == ve.second) { + viableTrans.push_back(tv); + } + } + } + } + + if(!viableTrans.empty()) + return getLongest(viableTrans); + + //search again without the history + for(const auto& ve: viableEdges) { + for(const auto& tv : tvs) { + if((tv.fromA_ && (normalize(tv.vector_) == normalize(ve.second - ve.first))) && (tv.edge_ != last.edge_ || tv.vector_.x_ != -last.vector_.x_ || tv.vector_.y_ != -last.vector_.y_)) { + viableTrans.push_back(tv); + } + } + for (const auto& tv : tvs) { + if (!tv.fromA_) { + point_t later; + if (tv.vector_ == (tv.edge_.second - tv.edge_.first) && (tv.edge_ != last.edge_ || tv.vector_.x_ != -last.vector_.x_ || tv.vector_.y_ != -last.vector_.y_)) { + later = tv.edge_.second; + } else if (tv.vector_ == (tv.edge_.first - tv.edge_.second)) { + later = tv.edge_.first; + } else + continue; + + if (later == ve.first || later == ve.second) { + viableTrans.push_back(tv); + } + } + } + } + if(!viableTrans.empty()) + return getLongest(viableTrans); + + /* + //search again without the history and without checking last edge + for(const auto& ve: viableEdges) { + for(const auto& tv : tvs) { + if((tv.fromA_ && (normalize(tv.vector_) == normalize(ve.second - ve.first)))) { + return tv; + } + } + for (const auto& tv : tvs) { + if (!tv.fromA_) { + point_t later; + if (tv.vector_ == (tv.edge_.second - tv.edge_.first)) { + later = tv.edge_.second; + } else if (tv.vector_ == (tv.edge_.first - tv.edge_.second)) { + later = tv.edge_.first; + } else + continue; + + if (later == ve.first || later == ve.second) { + return tv; + } + } + } + }*/ + + if(tvs.size() == 1) + return *tvs.begin(); + + TranslationVector tv; + tv.vector_ = INVALID_POINT; + return tv; + } else { + return getLongest(tvs); + } +} + +bool inNfp(const point_t& pt, const nfp_t& nfp) { + for(const auto& r : nfp) { + if(bg::touches(pt, r)) + return true; + } + + return false; +} + +enum SearchStartResult { + FIT, + FOUND, + NOT_FOUND +}; + +SearchStartResult searchStartTranslation(polygon_t::ring_type& rA, const polygon_t::ring_type& rB, const nfp_t& nfp,const bool& inside, point_t& result) { + for(psize_t i = 0; i < rA.size() - 1; i++) { + psize_t index; + if (i >= rA.size()) + index = i % rA.size() + 1; + else + index = i; + + auto& ptA = rA[index]; + + if(ptA.marked_) + continue; + + ptA.marked_ = true; + + for(const auto& ptB: rB) { + point_t testTranslation = ptA - ptB; + polygon_t::ring_type translated; + boost::geometry::transform(rB, translated, trans::translate_transformer(testTranslation.x_, testTranslation.y_)); + + //check if the translated rB is identical to rA + bool identical = false; + for(const auto& ptT: translated) { + identical = false; + for(const auto& ptA: rA) { + if(ptT == ptA) { + identical = true; + break; + } + } + if(!identical) + break; + } + + if(identical) { + result = testTranslation; + return FIT; + } + + bool bInside = false; + for(const auto& ptT: translated) { + if(bg::within(ptT, rA)) { + bInside = true; + break; + } else if(!bg::touches(ptT, rA)) { + bInside = false; + break; + } + } + + if(((bInside && inside) || (!bInside && !inside)) && (!bg::overlaps(translated, rA) && !bg::covered_by(translated, rA) && !bg::covered_by(rA, translated)) && !inNfp(translated.front(), nfp)){ + result = testTranslation; + return FOUND; + } + + point_t nextPtA = rA[index + 1]; + TranslationVector slideVector; + slideVector.vector_ = nextPtA - ptA; + slideVector.edge_ = {ptA, nextPtA}; + slideVector.fromA_ = true; + TranslationVector trimmed = trimVector(rA, translated, slideVector); + polygon_t::ring_type translated2; + trans::translate_transformer trans(trimmed.vector_.x_, trimmed.vector_.y_); + boost::geometry::transform(translated, translated2, trans); + + //check if the translated rB is identical to rA + identical = false; + for(const auto& ptT: translated) { + identical = false; + for(const auto& ptA: rA) { + if(ptT == ptA) { + identical = true; + break; + } + } + if(!identical) + break; + } + + if(identical) { + result = trimmed.vector_ + testTranslation; + return FIT; + } + + bInside = false; + for(const auto& ptT: translated2) { + if(bg::within(ptT, rA)) { + bInside = true; + break; + } else if(!bg::touches(ptT, rA)) { + bInside = false; + break; + } + } + + if(((bInside && inside) || (!bInside && !inside)) && (!bg::overlaps(translated2, rA) && !bg::covered_by(translated2, rA) && !bg::covered_by(rA, translated2)) && !inNfp(translated2.front(), nfp)){ + result = trimmed.vector_ + testTranslation; + return FOUND; + } + } + } + return NOT_FOUND; +} + +enum SlideResult { + LOOP, + NO_LOOP, + NO_TRANSLATION +}; + +SlideResult slide(polygon_t& pA, polygon_t::ring_type& rA, polygon_t::ring_type& rB, nfp_t& nfp, const point_t& transB, bool inside) { + polygon_t::ring_type rifsB; + boost::geometry::transform(rB, rifsB, trans::translate_transformer(transB.x_, transB.y_)); + rB = std::move(rifsB); + +#ifdef NFP_DEBUG + write_svg("ifs.svg", pA, rB); +#endif + + bool startAvailable = true; + psize_t cnt = 0; + point_t referenceStart = rB.front(); + std::vector history; + + //generate the nfp for the ring + while(startAvailable) { + DEBUG_VAL(cnt); + //use first point of rB as reference + nfp.back().push_back(rB.front()); + if(cnt == 15) + std::cerr << ""; + + std::vector touchers = findTouchingPoints(rA, rB); + +#ifdef NFP_DEBUG + DEBUG_MSG("touchers", touchers.size()); + for(auto t : touchers) { + DEBUG_VAL(t.type_); + } +#endif + if(touchers.empty()) { + throw std::runtime_error("Internal error: No touching points found"); + } + std::vector transVectors = findFeasibleTranslationVectors(rA, rB, touchers); + +#ifdef NFP_DEBUG + DEBUG_MSG("collected vectors", transVectors.size()); + for(auto pt : transVectors) { + DEBUG_VAL(pt); + } +#endif + + if(transVectors.empty()) { + return NO_LOOP; + } + + TranslationVector next = selectNextTranslationVector(pA, rA, rB, transVectors, history); + + if(next.vector_ == INVALID_POINT) + return NO_TRANSLATION; + + DEBUG_MSG("next", next); + + TranslationVector trimmed = trimVector(rA, rB, next); + DEBUG_MSG("trimmed", trimmed); + + history.push_back(next); + + polygon_t::ring_type nextRB; + boost::geometry::transform(rB, nextRB, trans::translate_transformer(trimmed.vector_.x_, trimmed.vector_.y_)); + rB = std::move(nextRB); + +#ifdef NFP_DEBUG + write_svg("next" + std::to_string(cnt) + ".svg", pA,rB); +#endif + + ++cnt; + if(referenceStart == rB.front() || (inside && bg::touches(rB.front(), nfp.front()))) { + startAvailable = false; + } + } + return LOOP; +} + +void removeCoLinear(polygon_t::ring_type& r) { + assert(r.size() > 2); + psize_t nextI; + psize_t prevI = 0; + segment_t segment(r[r.size() - 2], r[0]); + polygon_t::ring_type newR; + + for (psize_t i = 1; i < r.size() + 1; ++i) { + if (i >= r.size()) + nextI = i % r.size() + 1; + else + nextI = i; + + if (get_alignment(segment, r[nextI]) != ON) { + newR.push_back(r[prevI]); + } + segment = {segment.second, r[nextI]}; + prevI = nextI; + } + + r = newR; +} + +void removeCoLinear(polygon_t& p) { + removeCoLinear(p.outer()); + for (auto& r : p.inners()) + removeCoLinear(r); +} + +nfp_t generateNFP(polygon_t& pA, polygon_t& pB, const bool checkValidity = true) { + removeCoLinear(pA); + removeCoLinear(pB); + + if(checkValidity) { + std::string reason; + if(!bg::is_valid(pA, reason)) + throw std::runtime_error("Polygon A is invalid: " + reason); + + if(!bg::is_valid(pB, reason)) + throw std::runtime_error("Polygon B is invalid: " + reason); + } + + nfp_t nfp; + +#ifdef NFP_DEBUG + write_svg("start.svg", {pA, pB}); +#endif + + DEBUG_VAL(bg::wkt(pA)) + DEBUG_VAL(bg::wkt(pB)); + + //prevent double vertex connections at start because we might come back the same way we go which would end the nfp prematurely + std::vector ptyaminI = find_minimum_y(pA); + std::vector ptybmaxI = find_maximum_y(pB); + + point_t pAstart; + point_t pBstart; + + if(ptyaminI.size() > 1 || ptybmaxI.size() > 1) { + //find right-most of A and left-most of B to prevent double connection at start + coord_t maxX = MIN_COORD; + psize_t iRightMost = 0; + for(psize_t& ia : ptyaminI) { + const point_t& candidateA = pA.outer()[ia]; + if(larger(candidateA.x_, maxX)) { + maxX = candidateA.x_; + iRightMost = ia; + } + } + + coord_t minX = MAX_COORD; + psize_t iLeftMost = 0; + for(psize_t& ib : ptybmaxI) { + const point_t& candidateB = pB.outer()[ib]; + if(smaller(candidateB.x_, minX)) { + minX = candidateB.x_; + iLeftMost = ib; + } + } + pAstart = pA.outer()[iRightMost]; + pBstart = pB.outer()[iLeftMost]; + } else { + pAstart = pA.outer()[ptyaminI.front()]; + pBstart = pB.outer()[ptybmaxI.front()]; + } + + nfp.push_back({}); + point_t transB = {pAstart - pBstart}; + + if(slide(pA, pA.outer(), pB.outer(), nfp, transB, false) != LOOP) { + throw std::runtime_error("Unable to complete outer nfp loop"); + } + + DEBUG_VAL("##### outer #####"); + point_t startTrans; + while(true) { + SearchStartResult res = searchStartTranslation(pA.outer(), pB.outer(), nfp, false, startTrans); + if(res == FOUND) { + nfp.push_back({}); + DEBUG_VAL("##### interlock start #####") + polygon_t::ring_type rifsB; + boost::geometry::transform(pB.outer(), rifsB, trans::translate_transformer(startTrans.x_, startTrans.y_)); + if(inNfp(rifsB.front(), nfp)) { + continue; + } + SlideResult sres = slide(pA, pA.outer(), pB.outer(), nfp, startTrans, true); + if(sres != LOOP) { + if(sres == NO_TRANSLATION) { + //no initial slide found -> jiggsaw + if(!inNfp(pB.outer().front(),nfp)) { + nfp.push_back({}); + nfp.back().push_back(pB.outer().front()); + } + } + } + DEBUG_VAL("##### interlock end #####"); + } else if(res == FIT) { + point_t reference = pB.outer().front(); + point_t translated; + trans::translate_transformer translate(startTrans.x_, startTrans.y_); + boost::geometry::transform(reference, translated, translate); + if(!inNfp(translated,nfp)) { + nfp.push_back({}); + nfp.back().push_back(translated); + } + break; + } else + break; + } + + + for(auto& rA : pA.inners()) { + while(true) { + SearchStartResult res = searchStartTranslation(rA, pB.outer(), nfp, true, startTrans); + if(res == FOUND) { + nfp.push_back({}); + DEBUG_VAL("##### hole start #####"); + slide(pA, rA, pB.outer(), nfp, startTrans, true); + DEBUG_VAL("##### hole end #####"); + } else if(res == FIT) { + point_t reference = pB.outer().front(); + point_t translated; + trans::translate_transformer translate(startTrans.x_, startTrans.y_); + boost::geometry::transform(reference, translated, translate); + if(!inNfp(translated,nfp)) { + nfp.push_back({}); + nfp.back().push_back(translated); + } + break; + } else + break; + } + } + +#ifdef NFP_DEBUG + write_svg("nfp.svg", {pA,pB}, nfp); +#endif + + return nfp; +} +} +#endif diff --git a/xs/src/libnest2d/tests/svgtools.hpp b/xs/src/libnest2d/tools/svgtools.hpp similarity index 89% rename from xs/src/libnest2d/tests/svgtools.hpp rename to xs/src/libnest2d/tools/svgtools.hpp index f0db85217..273ecabac 100644 --- a/xs/src/libnest2d/tests/svgtools.hpp +++ b/xs/src/libnest2d/tools/svgtools.hpp @@ -6,7 +6,6 @@ #include #include -#include namespace libnest2d { namespace svg { @@ -46,16 +45,19 @@ public: void writeItem(const Item& item) { if(svg_layers_.empty()) addLayer(); - Item tsh(item.transformedShape()); - if(conf_.origo_location == BOTTOMLEFT) - for(unsigned i = 0; i < tsh.vertexCount(); i++) { - auto v = tsh.vertex(i); + auto tsh = item.transformedShape(); + if(conf_.origo_location == BOTTOMLEFT) { auto d = static_cast( std::round(conf_.height*conf_.mm_in_coord_units) ); - setY(v, -getY(v) + d); - tsh.setVertex(i, v); + + auto& contour = ShapeLike::getContour(tsh); + for(auto& v : contour) setY(v, -getY(v) + d); + + auto& holes = ShapeLike::holes(tsh); + for(auto& h : holes) for(auto& v : h) setY(v, -getY(v) + d); + } - currentLayer() += ShapeLike::serialize(tsh.rawShape(), + currentLayer() += ShapeLike::serialize(tsh, 1.0/conf_.mm_in_coord_units) + "\n"; } diff --git a/xs/src/libslic3r/Model.cpp b/xs/src/libslic3r/Model.cpp index c1d58f963..fc49d68af 100644 --- a/xs/src/libslic3r/Model.cpp +++ b/xs/src/libslic3r/Model.cpp @@ -9,7 +9,6 @@ #include #include -#include #include #include "slic3r/GUI/GUI.hpp" @@ -412,7 +411,7 @@ ShapeData2D projectModelFromTop(const Slic3r::Model &model) { for(auto objinst : objptr->instances) { if(objinst) { Slic3r::TriangleMesh tmpmesh = rmesh; - ClipperLib::PolyNode pn; + ClipperLib::PolygonImpl pn; tmpmesh.scale(objinst->scaling_factor); @@ -553,25 +552,13 @@ bool arrange(Model &model, coordf_t dist, const Slic3r::BoundingBoxf* bb, // Will use the DJD selection heuristic with the BottomLeft placement // strategy - using Arranger = Arranger; + using Arranger = Arranger; using PConf = Arranger::PlacementConfig; using SConf = Arranger::SelectionConfig; PConf pcfg; // Placement configuration SConf scfg; // Selection configuration - // Try inserting groups of 2, and 3 items in all possible order. - scfg.try_reverse_order = false; - - // If there are more items that could possibly fit into one bin, - // use multiple threads. (Potencially decreased pack efficiency) - scfg.allow_parallel = true; - - // Use multiple threads whenever possible - scfg.force_parallel = false; - - scfg.waste_increment = 0.01; - // Align the arranged pile into the center of the bin pcfg.alignment = PConf::Alignment::CENTER;