Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/prusa3d/PrusaSlicer.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authortamasmeszaros <meszaros.q@gmail.com>2018-10-23 18:18:38 +0300
committertamasmeszaros <meszaros.q@gmail.com>2018-10-23 18:20:31 +0300
commit34e652b9858e88bee7dc549908e8f0389bfdda4f (patch)
treeb87eaa67383e1890051a8d6b5bd0bebdd48583a7 /src/libnest2d
parentbded28f88805f37c40ccd0cc0f4a3e3a233bee50 (diff)
Fixing nesting crash in debug mode.
Also commented out unnecessary bloat from AppController
Diffstat (limited to 'src/libnest2d')
-rw-r--r--src/libnest2d/CMakeLists.txt183
-rw-r--r--src/libnest2d/README.md43
-rw-r--r--src/libnest2d/cmake_modules/DownloadNLopt.cmake7
-rw-r--r--src/libnest2d/cmake_modules/FindClipper.cmake10
-rw-r--r--src/libnest2d/cmake_modules/FindNLopt.cmake9
-rw-r--r--src/libnest2d/cmake_modules/FindTBB.cmake322
-rw-r--r--src/libnest2d/examples/main.cpp218
-rw-r--r--src/libnest2d/include/libnest2d.h175
-rw-r--r--src/libnest2d/include/libnest2d/backends/clipper/CMakeLists.txt (renamed from src/libnest2d/libnest2d/clipper_backend/CMakeLists.txt)41
-rw-r--r--src/libnest2d/include/libnest2d/backends/clipper/geometries.hpp (renamed from src/libnest2d/libnest2d/clipper_backend/clipper_backend.hpp)24
-rw-r--r--src/libnest2d/include/libnest2d/common.hpp (renamed from src/libnest2d/libnest2d/common.hpp)0
-rw-r--r--src/libnest2d/include/libnest2d/geometry_traits.hpp965
-rw-r--r--src/libnest2d/include/libnest2d/geometry_traits_nfp.hpp (renamed from src/libnest2d/libnest2d/geometry_traits_nfp.hpp)466
-rw-r--r--src/libnest2d/include/libnest2d/libnest2d.hpp (renamed from src/libnest2d/libnest2d/libnest2d.hpp)10
-rw-r--r--src/libnest2d/include/libnest2d/optimizer.hpp (renamed from src/libnest2d/libnest2d/optimizer.hpp)5
-rw-r--r--src/libnest2d/include/libnest2d/optimizers/nlopt/CMakeLists.txt61
-rw-r--r--src/libnest2d/include/libnest2d/optimizers/nlopt/genetic.hpp (renamed from src/libnest2d/libnest2d/optimizers/genetic.hpp)3
-rw-r--r--src/libnest2d/include/libnest2d/optimizers/nlopt/nlopt_boilerplate.hpp (renamed from src/libnest2d/libnest2d/optimizers/nlopt_boilerplate.hpp)26
-rw-r--r--src/libnest2d/include/libnest2d/optimizers/nlopt/simplex.hpp (renamed from src/libnest2d/libnest2d/optimizers/simplex.hpp)0
-rw-r--r--src/libnest2d/include/libnest2d/optimizers/nlopt/subplex.hpp (renamed from src/libnest2d/libnest2d/optimizers/subplex.hpp)0
-rw-r--r--src/libnest2d/include/libnest2d/optimizers/optimlib/CMakeLists.txt5
-rw-r--r--src/libnest2d/include/libnest2d/placers/bottomleftplacer.hpp (renamed from src/libnest2d/libnest2d/placers/bottomleftplacer.hpp)9
-rw-r--r--src/libnest2d/include/libnest2d/placers/nfpplacer.hpp (renamed from src/libnest2d/libnest2d/placers/nfpplacer.hpp)56
-rw-r--r--src/libnest2d/include/libnest2d/placers/placer_boilerplate.hpp (renamed from src/libnest2d/libnest2d/placers/placer_boilerplate.hpp)2
-rw-r--r--src/libnest2d/include/libnest2d/selections/djd_heuristic.hpp (renamed from src/libnest2d/libnest2d/selections/djd_heuristic.hpp)0
-rw-r--r--src/libnest2d/include/libnest2d/selections/filler.hpp (renamed from src/libnest2d/libnest2d/selections/filler.hpp)0
-rw-r--r--src/libnest2d/include/libnest2d/selections/firstfit.hpp (renamed from src/libnest2d/libnest2d/selections/firstfit.hpp)1
-rw-r--r--src/libnest2d/include/libnest2d/selections/selection_boilerplate.hpp (renamed from src/libnest2d/libnest2d/selections/selection_boilerplate.hpp)2
-rw-r--r--src/libnest2d/include/libnest2d/utils/boost_alg.hpp (renamed from src/libnest2d/libnest2d/boost_alg.hpp)12
-rw-r--r--src/libnest2d/include/libnest2d/utils/metaloop.hpp (renamed from src/libnest2d/libnest2d/metaloop.hpp)4
-rw-r--r--src/libnest2d/include/libnest2d/utils/rotfinder.hpp (renamed from src/libnest2d/libnest2d/rotfinder.hpp)0
-rw-r--r--src/libnest2d/libnest2d.h42
-rw-r--r--src/libnest2d/libnest2d/geometry_traits.hpp825
-rw-r--r--src/libnest2d/tests/CMakeLists.txt32
-rw-r--r--src/libnest2d/tests/test.cpp56
-rw-r--r--src/libnest2d/tools/benchmark.h58
-rw-r--r--src/libnest2d/tools/libnfpglue.cpp157
-rw-r--r--src/libnest2d/tools/libnfpglue.hpp46
-rw-r--r--src/libnest2d/tools/libnfporb/LICENSE674
-rw-r--r--src/libnest2d/tools/libnfporb/ORIGIN2
-rw-r--r--src/libnest2d/tools/libnfporb/README.md89
-rw-r--r--src/libnest2d/tools/libnfporb/libnfporb.hpp1547
-rw-r--r--src/libnest2d/tools/nfp_svgnest.hpp1018
-rw-r--r--src/libnest2d/tools/nfp_svgnest_glue.hpp75
-rw-r--r--src/libnest2d/tools/svgtools.hpp2
45 files changed, 1833 insertions, 5449 deletions
diff --git a/src/libnest2d/CMakeLists.txt b/src/libnest2d/CMakeLists.txt
index f81355012..21840aee2 100644
--- a/src/libnest2d/CMakeLists.txt
+++ b/src/libnest2d/CMakeLists.txt
@@ -1,4 +1,4 @@
-cmake_minimum_required(VERSION 2.8)
+cmake_minimum_required(VERSION 3.0)
project(Libnest2D)
@@ -11,125 +11,112 @@ set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED)
# Add our own cmake module path.
-list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake_modules/)
+list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake_modules/)
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)
-set(LIBNEST2D_GEOMETRIES_BACKEND "clipper" CACHE STRING
- "Build libnest2d with geometry classes implemented by the chosen backend.")
+option(LIBNEST2D_HEADER_ONLY "If enabled static library will not be built." ON)
-set(LIBNEST2D_OPTIMIZER_BACKEND "nlopt" CACHE STRING
- "Build libnest2d with optimization features implemented by the chosen backend.")
+set(GEOMETRY_BACKENDS clipper boost eigen)
+set(LIBNEST2D_GEOMETRIES clipper CACHE STRING "Geometry backend")
+set_property(CACHE LIBNEST2D_GEOMETRIES PROPERTY STRINGS ${GEOMETRY_BACKENDS})
+list(FIND GEOMETRY_BACKENDS ${LIBNEST2D_GEOMETRIES} GEOMETRY_TYPE)
+if(${GEOMETRY_TYPE} EQUAL -1)
+ message(FATAL_ERROR "Option ${LIBNEST2D_GEOMETRIES} not supported, valid entries are ${GEOMETRY_BACKENDS}")
+endif()
-set(LIBNEST2D_SRCFILES
- ${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/metaloop.hpp
- ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/rotfinder.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
- )
+set(OPTIMIZERS nlopt optimlib)
+set(LIBNEST2D_OPTIMIZER nlopt CACHE STRING "Optimization backend")
+set_property(CACHE LIBNEST2D_OPTIMIZER PROPERTY STRINGS ${OPTIMIZERS})
+list(FIND OPTIMIZERS ${LIBNEST2D_OPTIMIZER} OPTIMIZER_TYPE)
+if(${OPTIMIZER_TYPE} EQUAL -1)
+ message(FATAL_ERROR "Option ${LIBNEST2D_OPTIMIZER} not supported, valid entries are ${OPTIMIZERS}")
+endif()
-set(LIBNEST2D_LIBRARIES "")
+add_library(libnest2d INTERFACE)
-set(LIBNEST2D_HEADERS ${CMAKE_CURRENT_SOURCE_DIR})
+set(SRC_DIR ${PROJECT_SOURCE_DIR}/include)
-if(LIBNEST2D_GEOMETRIES_BACKEND STREQUAL "clipper")
+set(LIBNEST2D_SRCFILES
+ ${SRC_DIR}/libnest2d/libnest2d.hpp # Templates only
+ ${SRC_DIR}/libnest2d/geometry_traits.hpp
+ ${SRC_DIR}/libnest2d/geometry_traits_nfp.hpp
+ ${SRC_DIR}/libnest2d/common.hpp
+ ${SRC_DIR}/libnest2d/optimizer.hpp
+ ${SRC_DIR}/libnest2d/utils/metaloop.hpp
+ ${SRC_DIR}/libnest2d/utils/rotfinder.hpp
+ ${SRC_DIR}/libnest2d/placers/placer_boilerplate.hpp
+ ${SRC_DIR}/libnest2d/placers/bottomleftplacer.hpp
+ ${SRC_DIR}/libnest2d/placers/nfpplacer.hpp
+ ${SRC_DIR}/libnest2d/selections/selection_boilerplate.hpp
+ ${SRC_DIR}/libnest2d/selections/filler.hpp
+ ${SRC_DIR}/libnest2d/selections/firstfit.hpp
+ ${SRC_DIR}/libnest2d/selections/djd_heuristic.hpp
+ )
- # 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
+set(TBB_STATIC ON)
+find_package(TBB QUIET)
+if(TBB_FOUND)
+ message(STATUS "Parallelization with Intel TBB")
+ target_include_directories(libnest2d INTERFACE ${TBB_INCLUDE_DIRS})
+ target_compile_definitions(libnest2d INTERFACE ${TBB_DEFINITIONS} -DUSE_TBB)
+ if(MSVC)
+ # Suppress implicit linking of the TBB libraries by the Visual Studio compiler.
+ target_compile_definitions(libnest2d INTERFACE -D__TBB_NO_IMPLICIT_LINKAGE)
endif()
+ # The Intel TBB library will use the std::exception_ptr feature of C++11.
+ target_compile_definitions(libnest2d INTERFACE -DTBB_USE_CAPTURED_EXCEPTION=1)
- add_subdirectory(libnest2d/clipper_backend)
-
- include_directories(BEFORE ${CLIPPER_INCLUDE_DIRS})
- include_directories(${Boost_INCLUDE_DIRS})
+ target_link_libraries(libnest2d INTERFACE ${TBB_LIBRARIES})
+else()
+ find_package(OpenMP QUIET)
- list(APPEND LIBNEST2D_SRCFILES ${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})
+ if(OpenMP_CXX_FOUND)
+ message(STATUS "Parallelization with OpenMP")
+ target_include_directories(libnest2d INTERFACE OpenMP::OpenMP_CXX)
+ target_link_libraries(libnest2d INTERFACE OpenMP::OpenMP_CXX)
+ else()
+ message("Parallelization with C++11 threads")
+ find_package(Threads REQUIRED)
+ target_link_libraries(libnest2d INTERFACE Threads::Threads)
+ endif()
endif()
-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)
-
- 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})
- list(APPEND LIBNEST2D_HEADERS ${NLopt_INCLUDE_DIR})
-endif()
+add_subdirectory(${SRC_DIR}/libnest2d/backends/${LIBNEST2D_GEOMETRIES})
+add_subdirectory(${SRC_DIR}/libnest2d/optimizers/${LIBNEST2D_OPTIMIZER})
-if(LIBNEST2D_UNITTESTS)
- enable_testing()
- add_subdirectory(tests)
+target_sources(libnest2d INTERFACE ${LIBNEST2D_SRCFILES})
+target_include_directories(libnest2d INTERFACE ${SRC_DIR})
+
+if(NOT LIBNEST2D_HEADER_ONLY)
+ set(LIBNAME libnest2d_${LIBNEST2D_GEOMETRIES}_${LIBNEST2D_OPTIMIZER})
+ add_library(${LIBNAME} ${PROJECT_SOURCE_DIR}/src/libnest2d.cpp)
+ target_link_libraries(${LIBNAME} PUBLIC libnest2d)
+ target_compile_definitions(${LIBNAME} PUBLIC LIBNEST2D_STATIC)
endif()
if(LIBNEST2D_BUILD_EXAMPLES)
- add_executable(example examples/main.cpp
-# tools/libnfpglue.hpp
-# tools/libnfpglue.cpp
- tools/nfp_svgnest.hpp
- tools/nfp_svgnest_glue.hpp
- tools/svgtools.hpp
- tests/printer_parts.cpp
- tests/printer_parts.h
- ${LIBNEST2D_SRCFILES}
- )
- set(TBB_STATIC ON)
- find_package(TBB QUIET)
- if(TBB_FOUND)
- message(STATUS "Parallelization with Intel TBB")
- target_include_directories(example PUBLIC ${TBB_INCLUDE_DIRS})
- target_compile_definitions(example PUBLIC ${TBB_DEFINITIONS} -DUSE_TBB)
- if(MSVC)
- # Suppress implicit linking of the TBB libraries by the Visual Studio compiler.
- target_compile_definitions(example PUBLIC -D__TBB_NO_IMPLICIT_LINKAGE)
- endif()
- # The Intel TBB library will use the std::exception_ptr feature of C++11.
- target_compile_definitions(example PUBLIC -DTBB_USE_CAPTURED_EXCEPTION=1)
-
- target_link_libraries(example ${TBB_LIBRARIES})
- else()
- find_package(OpenMP QUIET)
- if(OpenMP_CXX_FOUND)
- message(STATUS "Parallelization with OpenMP")
- target_include_directories(example PUBLIC OpenMP::OpenMP_CXX)
- target_link_libraries(example OpenMP::OpenMP_CXX)
- endif()
- endif()
-
- target_link_libraries(example ${LIBNEST2D_LIBRARIES})
- target_include_directories(example PUBLIC ${LIBNEST2D_HEADERS})
+ add_executable(example examples/main.cpp
+ # tools/libnfpglue.hpp
+ # tools/libnfpglue.cpp
+ tools/nfp_svgnest.hpp
+ tools/nfp_svgnest_glue.hpp
+ tools/svgtools.hpp
+ tests/printer_parts.cpp
+ tests/printer_parts.h
+ )
+
+ if(NOT LIBNEST2D_HEADER_ONLY)
+ target_link_libraries(example ${LIBNAME})
+ else()
+ target_link_libraries(example libnest2d)
+ endif()
endif()
-get_directory_property(hasParent PARENT_DIRECTORY)
-if(hasParent)
- set(LIBNEST2D_INCLUDES ${LIBNEST2D_HEADERS} PARENT_SCOPE)
- set(LIBNEST2D_LIBRARIES ${LIBNEST2D_LIBRARIES} PARENT_SCOPE)
+if(LIBNEST2D_UNITTESTS)
+ add_subdirectory(${PROJECT_SOURCE_DIR}/tests)
endif()
diff --git a/src/libnest2d/README.md b/src/libnest2d/README.md
deleted file mode 100644
index 61a7ac7d0..000000000
--- a/src/libnest2d/README.md
+++ /dev/null
@@ -1,43 +0,0 @@
-# Introduction
-
-Libnest2D is a library and framework for the 2D bin packaging problem.
-Inspired from the [SVGNest](svgnest.com) Javascript library the project is
-built from scratch in C++11. The library is written with a policy that it should
-be usable out of the box with a very simple interface but has to be customizable
-to the very core as well. The algorithms are defined in a header only fashion
-with templated geometry types. These geometries can have custom or already
-existing implementation to avoid copying or having unnecessary dependencies.
-
-A default backend is provided if the user of the library just wants to use it
-out of the box without additional integration. This backend is reasonably
-fast and robust, being built on top of boost geometry and the
-[polyclipping](http://www.angusj.com/delphi/clipper.php) library. Usage of
-this default backend implies the dependency on these packages but its header
-only as well.
-
-This software is currently under construction and lacks a throughout
-documentation and some essential algorithms as well. At this stage it works well
-for rectangles and convex closed polygons without considering holes and
-concavities.
-
-Holes and non-convex polygons will be usable in the near future as well. The
-no fit polygon based placer module combined with the first fit selection
-strategy is now used in the [Slic3r](https://github.com/prusa3d/Slic3r)
-application's arrangement feature. It uses local optimization techniques to find
-the best placement of each new item based on some features of the arrangement.
-
-In the near future I would like to use machine learning to evaluate the
-placements and (or) the order if items in which they are placed and see what
-results can be obtained. This is a different approach than that of SVGnest which
-uses genetic algorithms to find better and better selection orders. Maybe the
-two approaches can be combined as well.
-
-# References
-- [SVGNest](https://github.com/Jack000/SVGnest)
-- [An effective heuristic for the two-dimensional irregular
-bin packing problem](http://www.cs.stir.ac.uk/~goc/papers/EffectiveHueristic2DAOR2013.pdf)
-- [Complete and robust no-fit polygon generation for the irregular stock cutting problem](https://www.sciencedirect.com/science/article/abs/pii/S0377221706001639)
-- [Applying Meta-Heuristic Algorithms to the Nesting
-Problem Utilising the No Fit Polygon](http://www.graham-kendall.com/papers/k2001.pdf)
-- [A comprehensive and robust procedure for obtaining the nofit polygon
-using Minkowski sums](https://www.sciencedirect.com/science/article/pii/S0305054806000669) \ No newline at end of file
diff --git a/src/libnest2d/cmake_modules/DownloadNLopt.cmake b/src/libnest2d/cmake_modules/DownloadNLopt.cmake
index 65b1866db..62b2b4c1a 100644
--- a/src/libnest2d/cmake_modules/DownloadNLopt.cmake
+++ b/src/libnest2d/cmake_modules/DownloadNLopt.cmake
@@ -6,11 +6,14 @@ else()
set(UPDATE_DISCONNECTED_IF_AVAILABLE "UPDATE_DISCONNECTED 1")
endif()
+set(URL_NLOPT "https://github.com/stevengj/nlopt.git"
+ CACHE STRING "Location of the nlopt git repository")
+
# set(NLopt_DIR ${CMAKE_BINARY_DIR}/nlopt)
include(DownloadProject)
download_project( PROJ nlopt
- GIT_REPOSITORY https://github.com/stevengj/nlopt.git
- GIT_TAG v2.5.0 #1fcbcbf2fe8e34234e016cc43a6c41d3e8453e1f #master #nlopt-2.4.2
+ GIT_REPOSITORY ${URL_NLOPT}
+ GIT_TAG v2.5.0
# CMAKE_CACHE_ARGS -DBUILD_SHARED_LIBS:BOOL=OFF -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE} -DCMAKE_INSTALL_PREFIX=${NLopt_DIR}
${UPDATE_DISCONNECTED_IF_AVAILABLE}
)
diff --git a/src/libnest2d/cmake_modules/FindClipper.cmake b/src/libnest2d/cmake_modules/FindClipper.cmake
index f6b973440..01b6b99d5 100644
--- a/src/libnest2d/cmake_modules/FindClipper.cmake
+++ b/src/libnest2d/cmake_modules/FindClipper.cmake
@@ -47,4 +47,12 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(Clipper
MARK_AS_ADVANCED(
CLIPPER_INCLUDE_DIRS
- CLIPPER_LIBRARIES) \ No newline at end of file
+ CLIPPER_LIBRARIES)
+
+if(CLIPPER_FOUND)
+ add_library(Clipper::Clipper INTERFACE IMPORTED)
+ set_target_properties(Clipper::Clipper PROPERTIES INTERFACE_LINK_LIBRARIES ${CLIPPER_LIBRARIES})
+ set_target_properties(Clipper::Clipper PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CLIPPER_INCLUDE_DIRS})
+ #target_link_libraries(Clipper::Clipper INTERFACE ${CLIPPER_LIBRARIES})
+ #target_include_directories(Clipper::Clipper INTERFACE ${CLIPPER_INCLUDE_DIRS})
+endif()
diff --git a/src/libnest2d/cmake_modules/FindNLopt.cmake b/src/libnest2d/cmake_modules/FindNLopt.cmake
index 4b93be7b6..2f813b6aa 100644
--- a/src/libnest2d/cmake_modules/FindNLopt.cmake
+++ b/src/libnest2d/cmake_modules/FindNLopt.cmake
@@ -114,6 +114,13 @@ if(NLopt_FOUND)
message(STATUS "Found NLopt in '${NLopt_DIR}'.")
message(STATUS "Using NLopt include directory '${NLopt_INCLUDE_DIR}'.")
message(STATUS "Using NLopt library '${NLopt_LIBS}'.")
+ add_library(Nlopt::Nlopt INTERFACE IMPORTED)
+ set_target_properties(Nlopt::Nlopt PROPERTIES INTERFACE_LINK_LIBRARIES ${NLopt_LIBS})
+ set_target_properties(Nlopt::Nlopt PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${NLopt_INCLUDE_DIR})
+ set_target_properties(Nlopt::Nlopt PROPERTIES INTERFACE_COMPILE_DEFINITIONS "${NLopt_DEFINITIONS}")
+ # target_link_libraries(Nlopt::Nlopt INTERFACE ${NLopt_LIBS})
+ # target_include_directories(Nlopt::Nlopt INTERFACE ${NLopt_INCLUDE_DIR})
+ # target_compile_definitions(Nlopt::Nlopt INTERFACE ${NLopt_DEFINITIONS})
else()
if(NLopt_FIND_REQUIRED)
message(FATAL_ERROR "Unable to find requested NLopt installation:${NLopt_ERROR_REASON}")
@@ -122,4 +129,4 @@ else()
message(STATUS "NLopt was not found:${NLopt_ERROR_REASON}")
endif()
endif()
-endif() \ No newline at end of file
+endif()
diff --git a/src/libnest2d/cmake_modules/FindTBB.cmake b/src/libnest2d/cmake_modules/FindTBB.cmake
deleted file mode 100644
index 8b498d3ab..000000000
--- a/src/libnest2d/cmake_modules/FindTBB.cmake
+++ /dev/null
@@ -1,322 +0,0 @@
-# The MIT License (MIT)
-#
-# Copyright (c) 2015 Justus Calvin
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in all
-# copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-# SOFTWARE.
-
-#
-# FindTBB
-# -------
-#
-# Find TBB include directories and libraries.
-#
-# Usage:
-#
-# find_package(TBB [major[.minor]] [EXACT]
-# [QUIET] [REQUIRED]
-# [[COMPONENTS] [components...]]
-# [OPTIONAL_COMPONENTS components...])
-#
-# where the allowed components are tbbmalloc and tbb_preview. Users may modify
-# the behavior of this module with the following variables:
-#
-# * TBB_ROOT_DIR - The base directory the of TBB installation.
-# * TBB_INCLUDE_DIR - The directory that contains the TBB headers files.
-# * TBB_LIBRARY - The directory that contains the TBB library files.
-# * TBB_<library>_LIBRARY - The path of the TBB the corresponding TBB library.
-# These libraries, if specified, override the
-# corresponding library search results, where <library>
-# may be tbb, tbb_debug, tbbmalloc, tbbmalloc_debug,
-# tbb_preview, or tbb_preview_debug.
-# * TBB_USE_DEBUG_BUILD - The debug version of tbb libraries, if present, will
-# be used instead of the release version.
-# * TBB_STATIC - Static linking of libraries with a _static suffix.
-# For example, on Windows a tbb_static.lib will be searched for
-# instead of tbb.lib.
-#
-# Users may modify the behavior of this module with the following environment
-# variables:
-#
-# * TBB_INSTALL_DIR
-# * TBBROOT
-# * LIBRARY_PATH
-#
-# This module will set the following variables:
-#
-# * TBB_FOUND - Set to false, or undefined, if we haven’t found, or
-# don’t want to use TBB.
-# * TBB_<component>_FOUND - If False, optional <component> part of TBB sytem is
-# not available.
-# * TBB_VERSION - The full version string
-# * TBB_VERSION_MAJOR - The major version
-# * TBB_VERSION_MINOR - The minor version
-# * TBB_INTERFACE_VERSION - The interface version number defined in
-# tbb/tbb_stddef.h.
-# * TBB_<library>_LIBRARY_RELEASE - The path of the TBB release version of
-# <library>, where <library> may be tbb, tbb_debug,
-# tbbmalloc, tbbmalloc_debug, tbb_preview, or
-# tbb_preview_debug.
-# * TBB_<library>_LIBRARY_DEGUG - The path of the TBB release version of
-# <library>, where <library> may be tbb, tbb_debug,
-# tbbmalloc, tbbmalloc_debug, tbb_preview, or
-# tbb_preview_debug.
-#
-# The following varibles should be used to build and link with TBB:
-#
-# * TBB_INCLUDE_DIRS - The include directory for TBB.
-# * TBB_LIBRARIES - The libraries to link against to use TBB.
-# * TBB_LIBRARIES_RELEASE - The release libraries to link against to use TBB.
-# * TBB_LIBRARIES_DEBUG - The debug libraries to link against to use TBB.
-# * TBB_DEFINITIONS - Definitions to use when compiling code that uses
-# TBB.
-# * TBB_DEFINITIONS_RELEASE - Definitions to use when compiling release code that
-# uses TBB.
-# * TBB_DEFINITIONS_DEBUG - Definitions to use when compiling debug code that
-# uses TBB.
-#
-# This module will also create the "tbb" target that may be used when building
-# executables and libraries.
-
-include(FindPackageHandleStandardArgs)
-
-if(NOT TBB_FOUND)
-
- ##################################
- # Check the build type
- ##################################
-
- if(NOT DEFINED TBB_USE_DEBUG_BUILD)
- if(CMAKE_BUILD_TYPE MATCHES "(Debug|DEBUG|debug)")
- set(TBB_BUILD_TYPE DEBUG)
- else()
- set(TBB_BUILD_TYPE RELEASE)
- endif()
- elseif(TBB_USE_DEBUG_BUILD)
- set(TBB_BUILD_TYPE DEBUG)
- else()
- set(TBB_BUILD_TYPE RELEASE)
- endif()
-
- ##################################
- # Set the TBB search directories
- ##################################
-
- # Define search paths based on user input and environment variables
- set(TBB_SEARCH_DIR ${TBB_ROOT_DIR} $ENV{TBB_INSTALL_DIR} $ENV{TBBROOT})
-
- # Define the search directories based on the current platform
- if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
- set(TBB_DEFAULT_SEARCH_DIR "C:/Program Files/Intel/TBB"
- "C:/Program Files (x86)/Intel/TBB")
-
- # Set the target architecture
- if(CMAKE_SIZEOF_VOID_P EQUAL 8)
- set(TBB_ARCHITECTURE "intel64")
- else()
- set(TBB_ARCHITECTURE "ia32")
- endif()
-
- # Set the TBB search library path search suffix based on the version of VC
- if(WINDOWS_STORE)
- set(TBB_LIB_PATH_SUFFIX "lib/${TBB_ARCHITECTURE}/vc11_ui")
- elseif(MSVC14)
- set(TBB_LIB_PATH_SUFFIX "lib/${TBB_ARCHITECTURE}/vc14")
- elseif(MSVC12)
- set(TBB_LIB_PATH_SUFFIX "lib/${TBB_ARCHITECTURE}/vc12")
- elseif(MSVC11)
- set(TBB_LIB_PATH_SUFFIX "lib/${TBB_ARCHITECTURE}/vc11")
- elseif(MSVC10)
- set(TBB_LIB_PATH_SUFFIX "lib/${TBB_ARCHITECTURE}/vc10")
- endif()
-
- # Add the library path search suffix for the VC independent version of TBB
- list(APPEND TBB_LIB_PATH_SUFFIX "lib/${TBB_ARCHITECTURE}/vc_mt")
-
- elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
- # OS X
- set(TBB_DEFAULT_SEARCH_DIR "/opt/intel/tbb")
-
- # TODO: Check to see which C++ library is being used by the compiler.
- if(NOT ${CMAKE_SYSTEM_VERSION} VERSION_LESS 13.0)
- # The default C++ library on OS X 10.9 and later is libc++
- set(TBB_LIB_PATH_SUFFIX "lib/libc++" "lib")
- else()
- set(TBB_LIB_PATH_SUFFIX "lib")
- endif()
- elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
- # Linux
- set(TBB_DEFAULT_SEARCH_DIR "/opt/intel/tbb")
-
- # TODO: Check compiler version to see the suffix should be <arch>/gcc4.1 or
- # <arch>/gcc4.1. For now, assume that the compiler is more recent than
- # gcc 4.4.x or later.
- if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64")
- set(TBB_LIB_PATH_SUFFIX "lib/intel64/gcc4.4")
- elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "^i.86$")
- set(TBB_LIB_PATH_SUFFIX "lib/ia32/gcc4.4")
- endif()
- endif()
-
- ##################################
- # Find the TBB include dir
- ##################################
-
- find_path(TBB_INCLUDE_DIRS tbb/tbb.h
- HINTS ${TBB_INCLUDE_DIR} ${TBB_SEARCH_DIR}
- PATHS ${TBB_DEFAULT_SEARCH_DIR}
- PATH_SUFFIXES include)
-
- ##################################
- # Set version strings
- ##################################
-
- if(TBB_INCLUDE_DIRS)
- file(READ "${TBB_INCLUDE_DIRS}/tbb/tbb_stddef.h" _tbb_version_file)
- string(REGEX REPLACE ".*#define TBB_VERSION_MAJOR ([0-9]+).*" "\\1"
- TBB_VERSION_MAJOR "${_tbb_version_file}")
- string(REGEX REPLACE ".*#define TBB_VERSION_MINOR ([0-9]+).*" "\\1"
- TBB_VERSION_MINOR "${_tbb_version_file}")
- string(REGEX REPLACE ".*#define TBB_INTERFACE_VERSION ([0-9]+).*" "\\1"
- TBB_INTERFACE_VERSION "${_tbb_version_file}")
- set(TBB_VERSION "${TBB_VERSION_MAJOR}.${TBB_VERSION_MINOR}")
- endif()
-
- ##################################
- # Find TBB components
- ##################################
-
- if(TBB_VERSION VERSION_LESS 4.3)
- set(TBB_SEARCH_COMPOMPONENTS tbb_preview tbbmalloc tbb)
- else()
- set(TBB_SEARCH_COMPOMPONENTS tbb_preview tbbmalloc_proxy tbbmalloc tbb)
- endif()
-
- if(TBB_STATIC)
- set(TBB_STATIC_SUFFIX "_static")
- endif()
-
- # Find each component
- foreach(_comp ${TBB_SEARCH_COMPOMPONENTS})
- if(";${TBB_FIND_COMPONENTS};tbb;" MATCHES ";${_comp};")
-
- # Search for the libraries
- find_library(TBB_${_comp}_LIBRARY_RELEASE ${_comp}${TBB_STATIC_SUFFIX}
- HINTS ${TBB_LIBRARY} ${TBB_SEARCH_DIR}
- PATHS ${TBB_DEFAULT_SEARCH_DIR} ENV LIBRARY_PATH
- PATH_SUFFIXES ${TBB_LIB_PATH_SUFFIX})
-
- find_library(TBB_${_comp}_LIBRARY_DEBUG ${_comp}${TBB_STATIC_SUFFIX}_debug
- HINTS ${TBB_LIBRARY} ${TBB_SEARCH_DIR}
- PATHS ${TBB_DEFAULT_SEARCH_DIR} ENV LIBRARY_PATH
- PATH_SUFFIXES ${TBB_LIB_PATH_SUFFIX})
-
- if(TBB_${_comp}_LIBRARY_DEBUG)
- list(APPEND TBB_LIBRARIES_DEBUG "${TBB_${_comp}_LIBRARY_DEBUG}")
- endif()
- if(TBB_${_comp}_LIBRARY_RELEASE)
- list(APPEND TBB_LIBRARIES_RELEASE "${TBB_${_comp}_LIBRARY_RELEASE}")
- endif()
- if(TBB_${_comp}_LIBRARY_${TBB_BUILD_TYPE} AND NOT TBB_${_comp}_LIBRARY)
- set(TBB_${_comp}_LIBRARY "${TBB_${_comp}_LIBRARY_${TBB_BUILD_TYPE}}")
- endif()
-
- if(TBB_${_comp}_LIBRARY AND EXISTS "${TBB_${_comp}_LIBRARY}")
- set(TBB_${_comp}_FOUND TRUE)
- else()
- set(TBB_${_comp}_FOUND FALSE)
- endif()
-
- # Mark internal variables as advanced
- mark_as_advanced(TBB_${_comp}_LIBRARY_RELEASE)
- mark_as_advanced(TBB_${_comp}_LIBRARY_DEBUG)
- mark_as_advanced(TBB_${_comp}_LIBRARY)
-
- endif()
- endforeach()
-
- unset(TBB_STATIC_SUFFIX)
-
- ##################################
- # Set compile flags and libraries
- ##################################
-
- set(TBB_DEFINITIONS_RELEASE "")
- set(TBB_DEFINITIONS_DEBUG "-DTBB_USE_DEBUG=1")
-
- if(TBB_LIBRARIES_${TBB_BUILD_TYPE})
- set(TBB_DEFINITIONS "${TBB_DEFINITIONS_${TBB_BUILD_TYPE}}")
- set(TBB_LIBRARIES "${TBB_LIBRARIES_${TBB_BUILD_TYPE}}")
- elseif(TBB_LIBRARIES_RELEASE)
- set(TBB_DEFINITIONS "${TBB_DEFINITIONS_RELEASE}")
- set(TBB_LIBRARIES "${TBB_LIBRARIES_RELEASE}")
- elseif(TBB_LIBRARIES_DEBUG)
- set(TBB_DEFINITIONS "${TBB_DEFINITIONS_DEBUG}")
- set(TBB_LIBRARIES "${TBB_LIBRARIES_DEBUG}")
- endif()
-
- find_package_handle_standard_args(TBB
- REQUIRED_VARS TBB_INCLUDE_DIRS TBB_LIBRARIES
- HANDLE_COMPONENTS
- VERSION_VAR TBB_VERSION)
-
- ##################################
- # Create targets
- ##################################
-
- if(NOT CMAKE_VERSION VERSION_LESS 3.0 AND TBB_FOUND)
- add_library(tbb SHARED IMPORTED)
- set_target_properties(tbb PROPERTIES
- INTERFACE_INCLUDE_DIRECTORIES ${TBB_INCLUDE_DIRS}
- IMPORTED_LOCATION ${TBB_LIBRARIES})
- if(TBB_LIBRARIES_RELEASE AND TBB_LIBRARIES_DEBUG)
- set_target_properties(tbb PROPERTIES
- INTERFACE_COMPILE_DEFINITIONS "$<$<OR:$<CONFIG:Debug>,$<CONFIG:RelWithDebInfo>>:TBB_USE_DEBUG=1>"
- IMPORTED_LOCATION_DEBUG ${TBB_LIBRARIES_DEBUG}
- IMPORTED_LOCATION_RELWITHDEBINFO ${TBB_LIBRARIES_DEBUG}
- IMPORTED_LOCATION_RELEASE ${TBB_LIBRARIES_RELEASE}
- IMPORTED_LOCATION_MINSIZEREL ${TBB_LIBRARIES_RELEASE}
- )
- elseif(TBB_LIBRARIES_RELEASE)
- set_target_properties(tbb PROPERTIES IMPORTED_LOCATION ${TBB_LIBRARIES_RELEASE})
- else()
- set_target_properties(tbb PROPERTIES
- INTERFACE_COMPILE_DEFINITIONS "${TBB_DEFINITIONS_DEBUG}"
- IMPORTED_LOCATION ${TBB_LIBRARIES_DEBUG}
- )
- endif()
- endif()
-
- mark_as_advanced(TBB_INCLUDE_DIRS TBB_LIBRARIES)
-
- unset(TBB_ARCHITECTURE)
- unset(TBB_BUILD_TYPE)
- unset(TBB_LIB_PATH_SUFFIX)
- unset(TBB_DEFAULT_SEARCH_DIR)
-
- if(TBB_DEBUG)
- message(STATUS " TBB_INCLUDE_DIRS = ${TBB_INCLUDE_DIRS}")
- message(STATUS " TBB_DEFINITIONS = ${TBB_DEFINITIONS}")
- message(STATUS " TBB_LIBRARIES = ${TBB_LIBRARIES}")
- message(STATUS " TBB_DEFINITIONS_DEBUG = ${TBB_DEFINITIONS_DEBUG}")
- message(STATUS " TBB_LIBRARIES_DEBUG = ${TBB_LIBRARIES_DEBUG}")
- message(STATUS " TBB_DEFINITIONS_RELEASE = ${TBB_DEFINITIONS_RELEASE}")
- message(STATUS " TBB_LIBRARIES_RELEASE = ${TBB_LIBRARIES_RELEASE}")
- endif()
-
-endif()
diff --git a/src/libnest2d/examples/main.cpp b/src/libnest2d/examples/main.cpp
deleted file mode 100644
index ebc3fb15c..000000000
--- a/src/libnest2d/examples/main.cpp
+++ /dev/null
@@ -1,218 +0,0 @@
-#include <iostream>
-#include <string>
-#include <fstream>
-//#define DEBUG_EXPORT_NFP
-
-#include <libnest2d.h>
-
-#include "tests/printer_parts.h"
-#include "tools/benchmark.h"
-#include "tools/svgtools.hpp"
-#include "libnest2d/rotfinder.hpp"
-
-//#include "tools/libnfpglue.hpp"
-//#include "tools/nfp_svgnest_glue.hpp"
-
-
-using namespace libnest2d;
-using ItemGroup = std::vector<std::reference_wrapper<Item>>;
-
-std::vector<Item>& _parts(std::vector<Item>& ret, const TestData& data)
-{
- if(ret.empty()) {
- ret.reserve(data.size());
- for(auto& inp : data)
- ret.emplace_back(inp);
- }
-
- return ret;
-}
-
-std::vector<Item>& prusaParts() {
- static std::vector<Item> ret;
- return _parts(ret, PRINTER_PART_POLYGONS);
-}
-
-std::vector<Item>& stegoParts() {
- static std::vector<Item> ret;
- return _parts(ret, STEGOSAUR_POLYGONS);
-}
-
-std::vector<Item>& prusaExParts() {
- static std::vector<Item> 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;
-
- std::vector<Item> rects(202, {
- {-9945219, -3065619},
- {-9781479, -2031780},
- {-9510560, -1020730},
- {-9135450, -43529},
- {-2099999, 14110899},
- {2099999, 14110899},
- {9135450, -43529},
- {9510560, -1020730},
- {9781479, -2031780},
- {9945219, -3065619},
- {10000000, -4110899},
- {9945219, -5156179},
- {9781479, -6190019},
- {9510560, -7201069},
- {9135450, -8178270},
- {8660249, -9110899},
- {8090169, -9988750},
- {7431449, -10802209},
- {6691309, -11542349},
- {5877850, -12201069},
- {5000000, -12771149},
- {4067369, -13246350},
- {3090169, -13621459},
- {2079119, -13892379},
- {1045279, -14056119},
- {0, -14110899},
- {-1045279, -14056119},
- {-2079119, -13892379},
- {-3090169, -13621459},
- {-4067369, -13246350},
- {-5000000, -12771149},
- {-5877850, -12201069},
- {-6691309, -11542349},
- {-7431449, -10802209},
- {-8090169, -9988750},
- {-8660249, -9110899},
- {-9135450, -8178270},
- {-9510560, -7201069},
- {-9781479, -6190019},
- {-9945219, -5156179},
- {-10000000, -4110899},
- {-9945219, -3065619},
- });
-
- std::vector<Item> 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());
-
- Box bin(250*SCALE, 210*SCALE);
-// PolygonImpl bin = {
-// {
-// {25*SCALE, 0},
-// {0, 25*SCALE},
-// {0, 225*SCALE},
-// {25*SCALE, 250*SCALE},
-// {225*SCALE, 250*SCALE},
-// {250*SCALE, 225*SCALE},
-// {250*SCALE, 25*SCALE},
-// {225*SCALE, 0},
-// {25*SCALE, 0}
-// },
-// {}
-// };
-
-// Circle bin({0, 0}, 125*SCALE);
-
- auto min_obj_distance = static_cast<Coord>(6*SCALE);
-
- using Placer = placers::_NofitPolyPlacer<PolygonImpl, decltype(bin)>;
- using Packer = Nester<Placer, FirstFitSelection>;
-
- Packer arrange(bin, min_obj_distance);
-
- Packer::PlacementConfig pconf;
- pconf.alignment = Placer::Config::Alignment::CENTER;
- pconf.starting_point = Placer::Config::Alignment::CENTER;
- pconf.rotations = {0.0/*, Pi/2.0, Pi, 3*Pi/2*/};
- pconf.accuracy = 0.65f;
- pconf.parallel = true;
-
- Packer::SelectionConfig sconf;
-// sconf.allow_parallel = false;
-// sconf.force_parallel = false;
-// sconf.try_triplets = true;
-// sconf.try_reverse_order = true;
-// sconf.waste_increment = 0.01;
-
- arrange.configure(pconf, sconf);
-
- arrange.progressIndicator([&](unsigned r){
- std::cout << "Remaining items: " << r << std::endl;
- });
-
-// findMinimumBoundingBoxRotations(input.begin(), input.end());
-
- Benchmark bench;
-
- bench.start();
- Packer::ResultType result;
-
- try {
- result = arrange.execute(input.begin(), input.end());
- } catch(GeometryException& ge) {
- std::cerr << "Geometry error: " << ge.what() << std::endl;
- return ;
- } catch(std::exception& e) {
- std::cerr << "Exception: " << e.what() << std::endl;
- return ;
- }
-
- bench.stop();
-
- std::vector<double> eff;
- eff.reserve(result.size());
-
- auto bin_area = sl::area(bin);
- for(auto& r : result) {
- double a = 0;
- std::for_each(r.begin(), r.end(), [&a] (Item& e ){ a += e.area(); });
- eff.emplace_back(a/bin_area);
- };
-
- std::cout << bench.getElapsedSec() << " bin count: " << result.size()
- << std::endl;
-
- std::cout << "Bin efficiency: (";
- for(double e : eff) std::cout << e*100.0 << "% ";
- std::cout << ") Average: "
- << std::accumulate(eff.begin(), eff.end(), 0.0)*100.0/result.size()
- << " %" << std::endl;
-
- std::cout << "Bin usage: (";
- size_t total = 0;
- for(auto& r : result) { std::cout << r.size() << " "; total += r.size(); }
- std::cout << ") Total: " << total << std::endl;
-
-// for(auto& it : input) {
-// auto ret = sl::isValid(it.transformedShape());
-// std::cout << ret.second << std::endl;
-// }
-
- if(total != input.size()) std::cout << "ERROR " << "could not pack "
- << input.size() - total << " elements!"
- << std::endl;
-
- using SVGWriter = svg::SVGWriter<PolygonImpl>;
-
- SVGWriter::Config conf;
- conf.mm_in_coord_units = SCALE;
- SVGWriter svgw(conf);
- svgw.setSize(Box(250*SCALE, 210*SCALE));
- svgw.writePackGroup(result);
- svgw.save("out");
-}
-
-int main(void /*int argc, char **argv*/) {
- arrangeRectangles();
- return EXIT_SUCCESS;
-}
diff --git a/src/libnest2d/include/libnest2d.h b/src/libnest2d/include/libnest2d.h
new file mode 100644
index 000000000..4ad752421
--- /dev/null
+++ b/src/libnest2d/include/libnest2d.h
@@ -0,0 +1,175 @@
+#ifndef LIBNEST2D_H
+#define LIBNEST2D_H
+
+// The type of backend should be set conditionally by the cmake configuriation
+// for now we set it statically to clipper backend
+#ifdef LIBNEST2D_BACKEND_CLIPPER
+#include <libnest2d/backends/clipper/geometries.hpp>
+#endif
+
+#ifdef LIBNEST2D_OPTIMIZER_NLOPT
+// We include the stock optimizers for local and global optimization
+#include <libnest2d/optimizers/nlopt/subplex.hpp> // Local subplex for NfpPlacer
+#include <libnest2d/optimizers/nlopt/genetic.hpp> // Genetic for min. bounding box
+#endif
+
+#include <libnest2d/libnest2d.hpp>
+#include <libnest2d/placers/bottomleftplacer.hpp>
+#include <libnest2d/placers/nfpplacer.hpp>
+#include <libnest2d/selections/firstfit.hpp>
+#include <libnest2d/selections/filler.hpp>
+#include <libnest2d/selections/djd_heuristic.hpp>
+
+namespace libnest2d {
+
+using Point = PointImpl;
+using Coord = TCoord<PointImpl>;
+using Box = _Box<PointImpl>;
+using Segment = _Segment<PointImpl>;
+using Circle = _Circle<PointImpl>;
+
+using Item = _Item<PolygonImpl>;
+using Rectangle = _Rectangle<PolygonImpl>;
+
+using PackGroup = _PackGroup<PolygonImpl>;
+using IndexedPackGroup = _IndexedPackGroup<PolygonImpl>;
+
+using FillerSelection = selections::_FillerSelection<PolygonImpl>;
+using FirstFitSelection = selections::_FirstFitSelection<PolygonImpl>;
+using DJDHeuristic = selections::_DJDHeuristic<PolygonImpl>;
+
+template<class Bin> // Generic placer for arbitrary bin types
+using _NfpPlacer = placers::_NofitPolyPlacer<PolygonImpl, Bin>;
+
+// NfpPlacer is with Box bin
+using NfpPlacer = _NfpPlacer<Box>;
+
+// This supports only box shaped bins
+using BottomLeftPlacer = placers::_BottomLeftPlacer<PolygonImpl>;
+
+template<class Placer = NfpPlacer,
+ class Selector = FirstFitSelection,
+ class Iterator = std::vector<Item>::iterator>
+PackGroup nest(Iterator from, Iterator to,
+ const typename Placer::BinType& bin,
+ Coord dist = 0,
+ const typename Placer::Config& pconf = {},
+ const typename Selector::Config& sconf = {})
+{
+ Nester<Placer, Selector> nester(bin, dist, pconf, sconf);
+ return nester.execute(from, to);
+}
+
+template<class Placer = NfpPlacer,
+ class Selector = FirstFitSelection,
+ class Container = std::vector<Item>>
+PackGroup nest(Container&& cont,
+ const typename Placer::BinType& bin,
+ Coord dist = 0,
+ const typename Placer::Config& pconf = {},
+ const typename Selector::Config& sconf = {})
+{
+ return nest<Placer, Selector>(cont.begin(), cont.end(),
+ bin, dist, pconf, sconf);
+}
+
+template<class Placer = NfpPlacer,
+ class Selector = FirstFitSelection,
+ class Iterator = std::vector<Item>::iterator>
+PackGroup nest(Iterator from, Iterator to,
+ const typename Placer::BinType& bin,
+ ProgressFunction prg,
+ StopCondition scond = []() { return false; },
+ Coord dist = 0,
+ const typename Placer::Config& pconf = {},
+ const typename Selector::Config& sconf = {})
+{
+ Nester<Placer, Selector> nester(bin, dist, pconf, sconf);
+ if(prg) nester.progressIndicator(prg);
+ if(scond) nester.stopCondition(scond);
+ return nester.execute(from, to);
+}
+
+template<class Placer = NfpPlacer,
+ class Selector = FirstFitSelection,
+ class Container = std::vector<Item>>
+PackGroup nest(Container&& cont,
+ const typename Placer::BinType& bin,
+ ProgressFunction prg,
+ StopCondition scond = []() { return false; },
+ Coord dist = 0,
+ const typename Placer::Config& pconf = {},
+ const typename Selector::Config& sconf = {})
+{
+ return nest<Placer, Selector>(cont.begin(), cont.end(),
+ bin, prg, scond, dist, pconf, sconf);
+}
+
+#ifdef LIBNEST2D_STATIC
+extern template
+PackGroup nest<NfpPlacer, FirstFitSelection, std::vector<Item>&>(
+ std::vector<Item>& cont,
+ const Box& bin,
+ Coord dist,
+ const NfpPlacer::Config& pcfg,
+ const FirstFitSelection::Config& scfg
+);
+
+extern template
+PackGroup nest<NfpPlacer, FirstFitSelection, std::vector<Item>&>(
+ std::vector<Item>& cont,
+ const Box& bin,
+ ProgressFunction prg,
+ StopCondition scond,
+ Coord dist,
+ const NfpPlacer::Config& pcfg,
+ const FirstFitSelection::Config& scfg
+);
+
+extern template
+PackGroup nest<NfpPlacer, FirstFitSelection, std::vector<Item>>(
+ std::vector<Item>&& cont,
+ const Box& bin,
+ Coord dist,
+ const NfpPlacer::Config& pcfg,
+ const FirstFitSelection::Config& scfg
+);
+
+extern template
+PackGroup nest<NfpPlacer, FirstFitSelection, std::vector<Item>>(
+ std::vector<Item>&& cont,
+ const Box& bin,
+ ProgressFunction prg,
+ StopCondition scond,
+ Coord dist,
+ const NfpPlacer::Config& pcfg,
+ const FirstFitSelection::Config& scfg
+);
+
+extern template
+PackGroup nest<NfpPlacer, FirstFitSelection, std::vector<Item>::iterator>(
+ std::vector<Item>::iterator from,
+ std::vector<Item>::iterator to,
+ const Box& bin,
+ Coord dist,
+ const NfpPlacer::Config& pcfg,
+ const FirstFitSelection::Config& scfg
+);
+
+extern template
+PackGroup nest<NfpPlacer, FirstFitSelection, std::vector<Item>::iterator>(
+ std::vector<Item>::iterator from,
+ std::vector<Item>::iterator to,
+ const Box& bin,
+ ProgressFunction prg,
+ StopCondition scond,
+ Coord dist,
+ const NfpPlacer::Config& pcfg,
+ const FirstFitSelection::Config& scfg
+);
+
+#endif
+
+}
+
+#endif // LIBNEST2D_H
diff --git a/src/libnest2d/libnest2d/clipper_backend/CMakeLists.txt b/src/libnest2d/include/libnest2d/backends/clipper/CMakeLists.txt
index b6f2de439..995afcc76 100644
--- a/src/libnest2d/libnest2d/clipper_backend/CMakeLists.txt
+++ b/src/libnest2d/include/libnest2d/backends/clipper/CMakeLists.txt
@@ -5,6 +5,10 @@ if(NOT TARGET clipper) # If there is a clipper target in the parent project we a
if(NOT CLIPPER_FOUND)
find_package(Subversion QUIET)
if(Subversion_FOUND)
+
+ set(URL_CLIPPER "https://svn.code.sf.net/p/polyclipping/code/trunk/cpp"
+ CACHE STRING "Clipper source code repository location.")
+
message(STATUS "Clipper not found so it will be downloaded.")
# Silently download and build the library in the build dir
@@ -16,7 +20,7 @@ if(NOT TARGET clipper) # If there is a clipper target in the parent project we a
include(DownloadProject)
download_project( PROJ clipper_library
- SVN_REPOSITORY https://svn.code.sf.net/p/polyclipping/code/trunk/cpp
+ SVN_REPOSITORY ${URL_CLIPPER}
SVN_REVISION -r540
#SOURCE_SUBDIR cpp
INSTALL_COMMAND ""
@@ -29,20 +33,41 @@ if(NOT TARGET clipper) # If there is a clipper target in the parent project we a
# ${clipper_library_BINARY_DIR}
# )
- add_library(clipper_lib STATIC
+ add_library(ClipperBackend STATIC
${clipper_library_SOURCE_DIR}/clipper.cpp
${clipper_library_SOURCE_DIR}/clipper.hpp)
- set(CLIPPER_INCLUDE_DIRS ${clipper_library_SOURCE_DIR}
- PARENT_SCOPE)
-
- set(CLIPPER_LIBRARIES clipper_lib PARENT_SCOPE)
-
+ target_include_directories(ClipperBackend INTERFACE
+ ${clipper_library_SOURCE_DIR})
else()
message(FATAL_ERROR "Can't find clipper library and no SVN client found to download.
You can download the clipper sources and define a clipper target in your project, that will work for libnest2d.")
endif()
+ else()
+ add_library(ClipperBackend INTERFACE)
+ target_link_libraries(ClipperBackend INTERFACE Clipper::Clipper)
endif()
else()
- set(CLIPPER_LIBRARIES clipper PARENT_SCOPE)
+ # set(CLIPPER_INCLUDE_DIRS "" PARENT_SCOPE)
+ # set(CLIPPER_LIBRARIES clipper PARENT_SCOPE)
+ add_library(ClipperBackend INTERFACE)
+ target_link_libraries(ClipperBackend INTERFACE clipper)
+endif()
+
+# 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
endif()
+
+target_include_directories(ClipperBackend INTERFACE ${Boost_INCLUDE_DIRS} )
+target_sources(ClipperBackend INTERFACE
+ ${CMAKE_CURRENT_SOURCE_DIR}/geometries.hpp
+ ${SRC_DIR}/libnest2d/utils/boost_alg.hpp )
+
+target_compile_definitions(ClipperBackend INTERFACE LIBNEST2D_BACKEND_CLIPPER)
+
+# And finally plug the ClipperBackend into libnest2d
+target_link_libraries(libnest2d INTERFACE ClipperBackend)
+
diff --git a/src/libnest2d/libnest2d/clipper_backend/clipper_backend.hpp b/src/libnest2d/include/libnest2d/backends/clipper/geometries.hpp
index 745fd2108..c05d08d0d 100644
--- a/src/libnest2d/libnest2d/clipper_backend/clipper_backend.hpp
+++ b/src/libnest2d/include/libnest2d/backends/clipper/geometries.hpp
@@ -7,8 +7,8 @@
#include <vector>
#include <iostream>
-#include "../geometry_traits.hpp"
-#include "../geometry_traits_nfp.hpp"
+#include <libnest2d/geometry_traits.hpp>
+#include <libnest2d/geometry_traits_nfp.hpp>
#include <clipper.hpp>
@@ -99,6 +99,10 @@ template<> struct PointType<PolygonImpl> {
using Type = PointImpl;
};
+template<> struct PointType<PathImpl> {
+ using Type = PointImpl;
+};
+
template<> struct PointType<PointImpl> {
using Type = PointImpl;
};
@@ -108,6 +112,7 @@ template<> struct CountourType<PolygonImpl> {
};
template<> struct ShapeTag<PolygonImpl> { using Type = PolygonTag; };
+template<> struct ShapeTag<PathImpl> { using Type = PathTag; };
template<> struct ShapeTag<TMultiShape<PolygonImpl>> {
using Type = MultiPolygonTag;
@@ -185,11 +190,6 @@ inline double area<Orientation::COUNTER_CLOCKWISE>(const PolygonImpl& sh) {
namespace shapelike {
-template<> inline void reserve(PolygonImpl& sh, size_t vertex_capacity)
-{
- return sh.Contour.reserve(vertex_capacity);
-}
-
// Tell libnest2d how to make string out of a ClipperPolygon object
template<> inline double area(const PolygonImpl& sh, const PolygonTag&)
{
@@ -327,13 +327,13 @@ template<> inline THolesContainer<PolygonImpl>& holes(PolygonImpl& sh)
}
template<>
-inline TContour<PolygonImpl>& getHole(PolygonImpl& sh, unsigned long idx)
+inline TContour<PolygonImpl>& hole(PolygonImpl& sh, unsigned long idx)
{
return sh.Holes[idx];
}
template<>
-inline const TContour<PolygonImpl>& getHole(const PolygonImpl& sh,
+inline const TContour<PolygonImpl>& hole(const PolygonImpl& sh,
unsigned long idx)
{
return sh.Holes[idx];
@@ -344,13 +344,13 @@ template<> inline size_t holeCount(const PolygonImpl& sh)
return sh.Holes.size();
}
-template<> inline PathImpl& getContour(PolygonImpl& sh)
+template<> inline PathImpl& contour(PolygonImpl& sh)
{
return sh.Contour;
}
template<>
-inline const PathImpl& getContour(const PolygonImpl& sh)
+inline const PathImpl& contour(const PolygonImpl& sh)
{
return sh.Contour;
}
@@ -455,6 +455,6 @@ merge(const std::vector<PolygonImpl>& shapes)
//#define DISABLE_BOOST_UNSERIALIZE
// All other operators and algorithms are implemented with boost
-#include "../boost_alg.hpp"
+#include <libnest2d/utils/boost_alg.hpp>
#endif // CLIPPER_BACKEND_HPP
diff --git a/src/libnest2d/libnest2d/common.hpp b/src/libnest2d/include/libnest2d/common.hpp
index 6867f76f3..6867f76f3 100644
--- a/src/libnest2d/libnest2d/common.hpp
+++ b/src/libnest2d/include/libnest2d/common.hpp
diff --git a/src/libnest2d/include/libnest2d/geometry_traits.hpp b/src/libnest2d/include/libnest2d/geometry_traits.hpp
new file mode 100644
index 000000000..828044afe
--- /dev/null
+++ b/src/libnest2d/include/libnest2d/geometry_traits.hpp
@@ -0,0 +1,965 @@
+#ifndef GEOMETRY_TRAITS_HPP
+#define GEOMETRY_TRAITS_HPP
+
+#include <string>
+#include <type_traits>
+#include <algorithm>
+#include <array>
+#include <vector>
+#include <numeric>
+#include <limits>
+#include <iterator>
+#include <cmath>
+
+#include "common.hpp"
+
+namespace libnest2d {
+
+/// Getting the coordinate data type for a geometry class.
+template<class GeomClass> struct CoordType { using Type = long; };
+
+/// TCoord<GeomType> as shorthand for typename `CoordType<GeomType>::Type`.
+template<class GeomType>
+using TCoord = typename CoordType<remove_cvref_t<GeomType>>::Type;
+
+
+/// Getting the type of point structure used by a shape.
+template<class Sh> struct PointType { using Type = typename Sh::PointType; };
+
+/// TPoint<ShapeClass> as shorthand for `typename PointType<ShapeClass>::Type`.
+template<class Shape>
+using TPoint = typename PointType<remove_cvref_t<Shape>>::Type;
+
+
+template<class RawShape> struct CountourType { using Type = RawShape; };
+
+template<class RawShape>
+using TContour = typename CountourType<remove_cvref_t<RawShape>>::Type;
+
+
+template<class RawShape>
+struct HolesContainer { using Type = std::vector<TContour<RawShape>>; };
+
+template<class RawShape>
+using THolesContainer = typename HolesContainer<remove_cvref_t<RawShape>>::Type;
+
+
+template<class RawShape>
+struct LastPointIsFirst { static const bool Value = true; };
+
+enum class Orientation {
+ CLOCKWISE,
+ COUNTER_CLOCKWISE
+};
+
+template<class RawShape>
+struct OrientationType {
+
+ // Default Polygon orientation that the library expects
+ static const Orientation Value = Orientation::CLOCKWISE;
+};
+
+/**
+ * \brief A point pair base class for other point pairs (segment, box, ...).
+ * \tparam RawPoint The actual point type to use.
+ */
+template<class RawPoint>
+struct PointPair {
+ RawPoint p1;
+ RawPoint p2;
+};
+
+struct PolygonTag {};
+struct PathTag {};
+struct MultiPolygonTag {};
+struct BoxTag {};
+struct CircleTag {};
+
+template<class Shape> struct ShapeTag { using Type = typename Shape::Tag; };
+template<class S> using Tag = typename ShapeTag<remove_cvref_t<S>>::Type;
+
+template<class S> struct MultiShape { using Type = std::vector<S>; };
+template<class S>
+using TMultiShape =typename MultiShape<remove_cvref_t<S>>::Type;
+
+/**
+ * \brief An abstraction of a box;
+ */
+template<class RawPoint>
+class _Box: PointPair<RawPoint> {
+ using PointPair<RawPoint>::p1;
+ using PointPair<RawPoint>::p2;
+public:
+
+ using Tag = BoxTag;
+ using PointType = RawPoint;
+
+ inline _Box() = default;
+ inline _Box(const RawPoint& p, const RawPoint& pp):
+ PointPair<RawPoint>({p, pp}) {}
+
+ inline _Box(TCoord<RawPoint> width, TCoord<RawPoint> height):
+ _Box(RawPoint{0, 0}, RawPoint{width, height}) {}
+
+ inline const RawPoint& minCorner() const BP2D_NOEXCEPT { return p1; }
+ inline const RawPoint& maxCorner() const BP2D_NOEXCEPT { return p2; }
+
+ inline RawPoint& minCorner() BP2D_NOEXCEPT { return p1; }
+ inline RawPoint& maxCorner() BP2D_NOEXCEPT { return p2; }
+
+ inline TCoord<RawPoint> width() const BP2D_NOEXCEPT;
+ inline TCoord<RawPoint> height() const BP2D_NOEXCEPT;
+
+ inline RawPoint center() const BP2D_NOEXCEPT;
+
+ inline double area() const BP2D_NOEXCEPT {
+ return double(width()*height());
+ }
+};
+
+template<class RawPoint>
+class _Circle {
+ RawPoint center_;
+ double radius_ = 0;
+public:
+
+ using Tag = CircleTag;
+ using PointType = RawPoint;
+
+ _Circle() = default;
+
+ _Circle(const RawPoint& center, double r): center_(center), radius_(r) {}
+
+ inline const RawPoint& center() const BP2D_NOEXCEPT { return center_; }
+ inline const void center(const RawPoint& c) { center_ = c; }
+
+ inline double radius() const BP2D_NOEXCEPT { return radius_; }
+ inline void radius(double r) { radius_ = r; }
+
+ inline double area() const BP2D_NOEXCEPT {
+ return 2.0*Pi*radius_*radius_;
+ }
+};
+
+/**
+ * \brief An abstraction of a directed line segment with two points.
+ */
+template<class RawPoint>
+class _Segment: PointPair<RawPoint> {
+ using PointPair<RawPoint>::p1;
+ using PointPair<RawPoint>::p2;
+ mutable Radians angletox_ = std::nan("");
+public:
+
+ using PointType = RawPoint;
+
+ inline _Segment() = default;
+
+ inline _Segment(const RawPoint& p, const RawPoint& pp):
+ PointPair<RawPoint>({p, pp}) {}
+
+ /**
+ * @brief Get the first point.
+ * @return Returns the starting point.
+ */
+ inline const RawPoint& first() const BP2D_NOEXCEPT { return p1; }
+
+ /**
+ * @brief The end point.
+ * @return Returns the end point of the segment.
+ */
+ inline const RawPoint& second() const BP2D_NOEXCEPT { return p2; }
+
+ inline void first(const RawPoint& p) BP2D_NOEXCEPT
+ {
+ angletox_ = std::nan(""); p1 = p;
+ }
+
+ inline void second(const RawPoint& p) BP2D_NOEXCEPT {
+ angletox_ = std::nan(""); p2 = p;
+ }
+
+ /// Returns the angle measured to the X (horizontal) axis.
+ inline Radians angleToXaxis() const;
+
+ /// The length of the segment in the measure of the coordinate system.
+ inline double length();
+};
+
+// This struct serves almost as a namespace. The only difference is that is can
+// used in friend declarations.
+namespace pointlike {
+
+template<class RawPoint>
+inline TCoord<RawPoint> x(const RawPoint& p)
+{
+ return p.x();
+}
+
+template<class RawPoint>
+inline TCoord<RawPoint> y(const RawPoint& p)
+{
+ return p.y();
+}
+
+template<class RawPoint>
+inline TCoord<RawPoint>& x(RawPoint& p)
+{
+ return p.x();
+}
+
+template<class RawPoint>
+inline TCoord<RawPoint>& y(RawPoint& p)
+{
+ return p.y();
+}
+
+template<class RawPoint>
+inline double distance(const RawPoint& /*p1*/, const RawPoint& /*p2*/)
+{
+ static_assert(always_false<RawPoint>::value,
+ "PointLike::distance(point, point) unimplemented!");
+ return 0;
+}
+
+template<class RawPoint>
+inline double distance(const RawPoint& /*p1*/,
+ const _Segment<RawPoint>& /*s*/)
+{
+ static_assert(always_false<RawPoint>::value,
+ "PointLike::distance(point, segment) unimplemented!");
+ return 0;
+}
+
+template<class RawPoint>
+inline std::pair<TCoord<RawPoint>, bool> horizontalDistance(
+ const RawPoint& p, const _Segment<RawPoint>& s)
+{
+ using Unit = TCoord<RawPoint>;
+ auto x = pointlike::x(p), y = pointlike::y(p);
+ auto x1 = pointlike::x(s.first()), y1 = pointlike::y(s.first());
+ auto x2 = pointlike::x(s.second()), y2 = pointlike::y(s.second());
+
+ TCoord<RawPoint> ret;
+
+ if( (y < y1 && y < y2) || (y > y1 && y > y2) )
+ return {0, false};
+ if ((y == y1 && y == y2) && (x > x1 && x > x2))
+ ret = std::min( x-x1, x -x2);
+ else if( (y == y1 && y == y2) && (x < x1 && x < x2))
+ ret = -std::min(x1 - x, x2 - x);
+ else if(std::abs(y - y1) <= std::numeric_limits<Unit>::epsilon() &&
+ std::abs(y - y2) <= std::numeric_limits<Unit>::epsilon())
+ ret = 0;
+ else
+ ret = x - x1 + (x1 - x2)*(y1 - y)/(y1 - y2);
+
+ return {ret, true};
+}
+
+template<class RawPoint>
+inline std::pair<TCoord<RawPoint>, bool> verticalDistance(
+ const RawPoint& p, const _Segment<RawPoint>& s)
+{
+ using Unit = TCoord<RawPoint>;
+ auto x = pointlike::x(p), y = pointlike::y(p);
+ auto x1 = pointlike::x(s.first()), y1 = pointlike::y(s.first());
+ auto x2 = pointlike::x(s.second()), y2 = pointlike::y(s.second());
+
+ TCoord<RawPoint> ret;
+
+ if( (x < x1 && x < x2) || (x > x1 && x > x2) )
+ return {0, false};
+ if ((x == x1 && x == x2) && (y > y1 && y > y2))
+ ret = std::min( y-y1, y -y2);
+ else if( (x == x1 && x == x2) && (y < y1 && y < y2))
+ ret = -std::min(y1 - y, y2 - y);
+ else if(std::abs(x - x1) <= std::numeric_limits<Unit>::epsilon() &&
+ std::abs(x - x2) <= std::numeric_limits<Unit>::epsilon())
+ ret = 0;
+ else
+ ret = y - y1 + (y1 - y2)*(x1 - x)/(x1 - x2);
+
+ return {ret, true};
+}
+}
+
+template<class RawPoint>
+TCoord<RawPoint> _Box<RawPoint>::width() const BP2D_NOEXCEPT
+{
+ return pointlike::x(maxCorner()) - pointlike::x(minCorner());
+}
+
+template<class RawPoint>
+TCoord<RawPoint> _Box<RawPoint>::height() const BP2D_NOEXCEPT
+{
+ return pointlike::y(maxCorner()) - pointlike::y(minCorner());
+}
+
+template<class RawPoint>
+TCoord<RawPoint> getX(const RawPoint& p) { return pointlike::x<RawPoint>(p); }
+
+template<class RawPoint>
+TCoord<RawPoint> getY(const RawPoint& p) { return pointlike::y<RawPoint>(p); }
+
+template<class RawPoint>
+void setX(RawPoint& p, const TCoord<RawPoint>& val)
+{
+ pointlike::x<RawPoint>(p) = val;
+}
+
+template<class RawPoint>
+void setY(RawPoint& p, const TCoord<RawPoint>& val)
+{
+ pointlike::y<RawPoint>(p) = val;
+}
+
+template<class RawPoint>
+inline Radians _Segment<RawPoint>::angleToXaxis() const
+{
+ if(std::isnan(static_cast<double>(angletox_))) {
+ TCoord<RawPoint> dx = getX(second()) - getX(first());
+ TCoord<RawPoint> dy = getY(second()) - getY(first());
+
+ double a = std::atan2(dy, dx);
+ auto s = std::signbit(a);
+
+ if(s) a += Pi_2;
+ angletox_ = a;
+ }
+ return angletox_;
+}
+
+template<class RawPoint>
+inline double _Segment<RawPoint>::length()
+{
+ return pointlike::distance(first(), second());
+}
+
+template<class RawPoint>
+inline RawPoint _Box<RawPoint>::center() const BP2D_NOEXCEPT {
+ auto& minc = minCorner();
+ auto& maxc = maxCorner();
+
+ using Coord = TCoord<RawPoint>;
+
+ RawPoint ret = { // No rounding here, we dont know if these are int coords
+ static_cast<Coord>( (getX(minc) + getX(maxc))/2.0 ),
+ static_cast<Coord>( (getY(minc) + getY(maxc))/2.0 )
+ };
+
+ return ret;
+}
+
+enum class Formats {
+ WKT,
+ SVG
+};
+
+// This struct serves as a namespace. The only difference is that it can be
+// used in friend declarations and can be aliased at class scope.
+namespace shapelike {
+
+template<class RawShape>
+using Shapes = TMultiShape<RawShape>;
+
+template<class RawShape>
+inline RawShape create(const TContour<RawShape>& contour,
+ const THolesContainer<RawShape>& holes)
+{
+ return RawShape(contour, holes);
+}
+
+template<class RawShape>
+inline RawShape create(TContour<RawShape>&& contour,
+ THolesContainer<RawShape>&& holes)
+{
+ return RawShape(contour, holes);
+}
+
+template<class RawShape>
+inline RawShape create(const TContour<RawShape>& contour)
+{
+ return create<RawShape>(contour, {});
+}
+
+template<class RawShape>
+inline RawShape create(TContour<RawShape>&& contour)
+{
+ return create<RawShape>(contour, {});
+}
+
+template<class RawShape>
+inline THolesContainer<RawShape>& holes(RawShape& /*sh*/)
+{
+ static THolesContainer<RawShape> empty;
+ return empty;
+}
+
+template<class RawShape>
+inline const THolesContainer<RawShape>& holes(const RawShape& /*sh*/)
+{
+ static THolesContainer<RawShape> empty;
+ return empty;
+}
+
+template<class RawShape>
+inline TContour<RawShape>& hole(RawShape& sh, unsigned long idx)
+{
+ return holes(sh)[idx];
+}
+
+template<class RawShape>
+inline const TContour<RawShape>& hole(const RawShape& sh, unsigned long idx)
+{
+ return holes(sh)[idx];
+}
+
+template<class RawShape>
+inline size_t holeCount(const RawShape& sh)
+{
+ return holes(sh).size();
+}
+
+template<class RawShape>
+inline TContour<RawShape>& contour(RawShape& sh)
+{
+ static_assert(always_false<RawShape>::value,
+ "shapelike::contour() unimplemented!");
+ return sh;
+}
+
+template<class RawShape>
+inline const TContour<RawShape>& contour(const RawShape& sh)
+{
+ static_assert(always_false<RawShape>::value,
+ "shapelike::contour() unimplemented!");
+ return sh;
+}
+
+// Optional, does nothing by default
+template<class RawPath>
+inline void reserve(RawPath& p, size_t vertex_capacity, const PathTag&)
+{
+ p.reserve(vertex_capacity);
+}
+
+template<class RawShape, class...Args>
+inline void addVertex(RawShape& sh, const PathTag&, Args...args)
+{
+ return sh.emplace_back(std::forward<Args>(args)...);
+}
+
+template<class RawShape, class Fn>
+inline void foreachVertex(RawShape& sh, Fn fn, const PathTag&) {
+ std::for_each(sh.begin(), sh.end(), fn);
+}
+
+template<class RawShape>
+inline typename RawShape::iterator begin(RawShape& sh, const PathTag&)
+{
+ return sh.begin();
+}
+
+template<class RawShape>
+inline typename RawShape::iterator end(RawShape& sh, const PathTag&)
+{
+ return sh.end();
+}
+
+template<class RawShape>
+inline typename RawShape::const_iterator
+cbegin(const RawShape& sh, const PathTag&)
+{
+ return sh.cbegin();
+}
+
+template<class RawShape>
+inline typename RawShape::const_iterator
+cend(const RawShape& sh, const PathTag&)
+{
+ return sh.cend();
+}
+
+template<class RawShape>
+inline std::string toString(const RawShape& /*sh*/)
+{
+ return "";
+}
+
+template<Formats, class RawShape>
+inline std::string serialize(const RawShape& /*sh*/, double /*scale*/=1)
+{
+ static_assert(always_false<RawShape>::value,
+ "shapelike::serialize() unimplemented!");
+ return "";
+}
+
+template<Formats, class RawShape>
+inline void unserialize(RawShape& /*sh*/, const std::string& /*str*/)
+{
+ static_assert(always_false<RawShape>::value,
+ "shapelike::unserialize() unimplemented!");
+}
+
+template<class RawShape>
+inline double area(const RawShape& /*sh*/, const PolygonTag&)
+{
+ static_assert(always_false<RawShape>::value,
+ "shapelike::area() unimplemented!");
+ return 0;
+}
+
+template<class RawShape>
+inline bool intersects(const RawShape& /*sh*/, const RawShape& /*sh*/)
+{
+ static_assert(always_false<RawShape>::value,
+ "shapelike::intersects() unimplemented!");
+ return false;
+}
+
+template<class RawShape>
+inline bool isInside(const TPoint<RawShape>& /*point*/,
+ const RawShape& /*shape*/)
+{
+ static_assert(always_false<RawShape>::value,
+ "shapelike::isInside(point, shape) unimplemented!");
+ return false;
+}
+
+template<class RawShape>
+inline bool isInside(const RawShape& /*shape*/,
+ const RawShape& /*shape*/)
+{
+ static_assert(always_false<RawShape>::value,
+ "shapelike::isInside(shape, shape) unimplemented!");
+ return false;
+}
+
+template<class RawShape>
+inline bool touches( const RawShape& /*shape*/,
+ const RawShape& /*shape*/)
+{
+ static_assert(always_false<RawShape>::value,
+ "shapelike::touches(shape, shape) unimplemented!");
+ return false;
+}
+
+template<class RawShape>
+inline bool touches( const TPoint<RawShape>& /*point*/,
+ const RawShape& /*shape*/)
+{
+ static_assert(always_false<RawShape>::value,
+ "shapelike::touches(point, shape) unimplemented!");
+ return false;
+}
+
+template<class RawShape>
+inline _Box<TPoint<RawShape>> boundingBox(const RawShape& /*sh*/,
+ const PolygonTag&)
+{
+ static_assert(always_false<RawShape>::value,
+ "shapelike::boundingBox(shape) unimplemented!");
+}
+
+template<class RawShapes>
+inline _Box<TPoint<typename RawShapes::value_type>>
+boundingBox(const RawShapes& /*sh*/, const MultiPolygonTag&)
+{
+ static_assert(always_false<RawShapes>::value,
+ "shapelike::boundingBox(shapes) unimplemented!");
+}
+
+template<class RawShape>
+inline RawShape convexHull(const RawShape& /*sh*/, const PolygonTag&)
+{
+ static_assert(always_false<RawShape>::value,
+ "shapelike::convexHull(shape) unimplemented!");
+ return RawShape();
+}
+
+template<class RawShapes>
+inline typename RawShapes::value_type
+convexHull(const RawShapes& /*sh*/, const MultiPolygonTag&)
+{
+ static_assert(always_false<RawShapes>::value,
+ "shapelike::convexHull(shapes) unimplemented!");
+ return typename RawShapes::value_type();
+}
+
+template<class RawShape>
+inline void rotate(RawShape& /*sh*/, const Radians& /*rads*/)
+{
+ static_assert(always_false<RawShape>::value,
+ "shapelike::rotate() unimplemented!");
+}
+
+template<class RawShape, class RawPoint>
+inline void translate(RawShape& /*sh*/, const RawPoint& /*offs*/)
+{
+ static_assert(always_false<RawShape>::value,
+ "shapelike::translate() unimplemented!");
+}
+
+template<class RawShape>
+inline void offset(RawShape& /*sh*/, TCoord<TPoint<RawShape>> /*distance*/)
+{
+ dout() << "The current geometry backend does not support offsetting!\n";
+}
+
+template<class RawShape>
+inline std::pair<bool, std::string> isValid(const RawShape& /*sh*/)
+{
+ return {false, "shapelike::isValid() unimplemented!"};
+}
+
+template<class RawPath> inline bool isConvex(const RawPath& sh, const PathTag&)
+{
+ using Vertex = TPoint<RawPath>;
+ auto first = begin(sh);
+ 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(end(sh)))),
+ *first,
+ *middle );
+
+ bool ret = true;
+ bool frsign = firstprod > 0;
+ while(last != end(sh)) {
+ 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
+// *****************************************************************************
+
+template<class RawShape>
+inline typename TContour<RawShape>::iterator
+begin(RawShape& sh, const PolygonTag& t)
+{
+ return begin(contour(sh), PathTag());
+}
+
+template<class RawShape> // Tag dispatcher
+inline auto begin(RawShape& sh) -> decltype(begin(sh, Tag<RawShape>()))
+{
+ return begin(sh, Tag<RawShape>());
+}
+
+template<class RawShape>
+inline typename TContour<RawShape>::const_iterator
+cbegin(const RawShape& sh, const PolygonTag&)
+{
+ return cbegin(contour(sh), PathTag());
+}
+
+template<class RawShape> // Tag dispatcher
+inline auto cbegin(const RawShape& sh) -> decltype(cbegin(sh, Tag<RawShape>()))
+{
+ return cbegin(sh, Tag<RawShape>());
+}
+
+template<class RawShape>
+inline typename TContour<RawShape>::iterator
+end(RawShape& sh, const PolygonTag&)
+{
+ return end(contour(sh), PathTag());
+}
+
+template<class RawShape> // Tag dispatcher
+inline auto end(RawShape& sh) -> decltype(begin(sh, Tag<RawShape>()))
+{
+ return end(sh, Tag<RawShape>());
+}
+
+template<class RawShape>
+inline typename TContour<RawShape>::const_iterator
+cend(const RawShape& sh, const PolygonTag&)
+{
+ return cend(contour(sh), PathTag());
+}
+
+template<class RawShape> // Tag dispatcher
+inline auto cend(const RawShape& sh) -> decltype(cend(sh, Tag<RawShape>()))
+{
+ return cend(sh, Tag<RawShape>());
+}
+
+template<class It> std::reverse_iterator<It> _backward(It iter) {
+ return std::reverse_iterator<It>(iter);
+}
+
+template<class P> auto rbegin(P& p) -> decltype(_backward(end(p)))
+{
+ return _backward(end(p));
+}
+
+template<class P> auto rcbegin(const P& p) -> decltype(_backward(end(p)))
+{
+ return _backward(end(p));
+}
+
+template<class P> auto rend(P& p) -> decltype(_backward(begin(p)))
+{
+ return _backward(begin(p));
+}
+
+template<class P> auto rcend(const P& p) -> decltype(_backward(cbegin(p)))
+{
+ return _backward(cbegin(p));
+}
+
+template<class P> TPoint<P> front(const P& p) { return *shapelike::cbegin(p); }
+template<class P> TPoint<P> back (const P& p) {
+ return *backward(shapelike::cend(p));
+}
+
+// Optional, does nothing by default
+template<class RawShape>
+inline void reserve(RawShape& sh, size_t vertex_capacity, const PolygonTag&)
+{
+ reserve(contour(sh), vertex_capacity, PathTag());
+}
+
+template<class T> // Tag dispatcher
+inline void reserve(T& sh, size_t vertex_capacity) {
+ reserve(sh, vertex_capacity, Tag<T>());
+}
+
+template<class RawShape, class...Args>
+inline void addVertex(RawShape& sh, const PolygonTag&, Args...args)
+{
+ return addVertex(contour(sh), PathTag(), std::forward<Args>(args)...);
+}
+
+template<class RawShape, class...Args> // Tag dispatcher
+inline void addVertex(RawShape& sh, Args...args)
+{
+ return addVertex(sh, Tag<RawShape>(), std::forward<Args>(args)...);
+}
+
+template<class Box>
+inline Box boundingBox(const Box& box, const BoxTag& )
+{
+ return box;
+}
+
+template<class Circle>
+inline _Box<typename Circle::PointType> boundingBox(
+ const Circle& circ, const CircleTag&)
+{
+ using Point = typename Circle::PointType;
+ using Coord = TCoord<Point>;
+ Point pmin = {
+ static_cast<Coord>(getX(circ.center()) - circ.radius()),
+ static_cast<Coord>(getY(circ.center()) - circ.radius()) };
+
+ Point pmax = {
+ static_cast<Coord>(getX(circ.center()) + circ.radius()),
+ static_cast<Coord>(getY(circ.center()) + circ.radius()) };
+
+ return {pmin, pmax};
+}
+
+template<class S> // Dispatch function
+inline _Box<TPoint<S>> boundingBox(const S& sh)
+{
+ return boundingBox(sh, Tag<S>() );
+}
+
+template<class Box>
+inline double area(const Box& box, const BoxTag& )
+{
+ return box.area();
+}
+
+template<class Circle>
+inline double area(const Circle& circ, const CircleTag& )
+{
+ return circ.area();
+}
+
+template<class RawShape> // Dispatching function
+inline double area(const RawShape& sh)
+{
+ return area(sh, Tag<RawShape>());
+}
+
+template<class RawShapes>
+inline double area(const RawShapes& shapes, const MultiPolygonTag&)
+{
+ using RawShape = typename RawShapes::value_type;
+ return std::accumulate(shapes.begin(), shapes.end(), 0.0,
+ [](double a, const RawShape& b) {
+ return a += area(b);
+ });
+}
+
+template<class RawShape>
+inline auto convexHull(const RawShape& sh)
+ -> decltype(convexHull(sh, Tag<RawShape>())) // TODO: C++14 could deduce
+{
+ return convexHull(sh, Tag<RawShape>());
+}
+
+template<class RawShape>
+inline bool isInside(const TPoint<RawShape>& point,
+ const _Circle<TPoint<RawShape>>& circ)
+{
+ return pointlike::distance(point, circ.center()) < circ.radius();
+}
+
+template<class RawShape>
+inline bool isInside(const TPoint<RawShape>& point,
+ const _Box<TPoint<RawShape>>& box)
+{
+ auto px = getX(point);
+ auto py = getY(point);
+ auto minx = getX(box.minCorner());
+ auto miny = getY(box.minCorner());
+ auto maxx = getX(box.maxCorner());
+ auto maxy = getY(box.maxCorner());
+
+ return px > minx && px < maxx && py > miny && py < maxy;
+}
+
+template<class RawShape>
+inline bool isInside(const RawShape& sh,
+ const _Circle<TPoint<RawShape>>& circ)
+{
+ return std::all_of(cbegin(sh), cend(sh),
+ [&circ](const TPoint<RawShape>& p){
+ return isInside<RawShape>(p, circ);
+ });
+}
+
+template<class RawShape>
+inline bool isInside(const _Box<TPoint<RawShape>>& box,
+ const _Circle<TPoint<RawShape>>& circ)
+{
+ return isInside<RawShape>(box.minCorner(), circ) &&
+ isInside<RawShape>(box.maxCorner(), circ);
+}
+
+template<class RawShape>
+inline bool isInside(const _Box<TPoint<RawShape>>& ibb,
+ const _Box<TPoint<RawShape>>& box)
+{
+ auto iminX = getX(ibb.minCorner());
+ auto imaxX = getX(ibb.maxCorner());
+ auto iminY = getY(ibb.minCorner());
+ auto imaxY = getY(ibb.maxCorner());
+
+ auto minX = getX(box.minCorner());
+ auto maxX = getX(box.maxCorner());
+ auto minY = getY(box.minCorner());
+ auto maxY = getY(box.maxCorner());
+
+ return iminX > minX && imaxX < maxX && iminY > minY && imaxY < maxY;
+}
+
+template<class RawShape> // Potential O(1) implementation may exist
+inline TPoint<RawShape>& vertex(RawShape& sh, unsigned long idx,
+ const PolygonTag&)
+{
+ return *(shapelike::begin(contour(sh)) + idx);
+}
+
+template<class RawShape> // Potential O(1) implementation may exist
+inline TPoint<RawShape>& vertex(RawShape& sh, unsigned long idx,
+ const PathTag&)
+{
+ return *(shapelike::begin(sh) + idx);
+}
+
+template<class RawShape> // Potential O(1) implementation may exist
+inline TPoint<RawShape>& vertex(RawShape& sh, unsigned long idx)
+{
+ return vertex(sh, idx, Tag<RawShape>());
+}
+
+template<class RawShape> // Potential O(1) implementation may exist
+inline const TPoint<RawShape>& vertex(const RawShape& sh,
+ unsigned long idx,
+ const PolygonTag&)
+{
+ return *(shapelike::cbegin(contour(sh)) + idx);
+}
+
+template<class RawShape> // Potential O(1) implementation may exist
+inline const TPoint<RawShape>& vertex(const RawShape& sh,
+ unsigned long idx,
+ const PathTag&)
+{
+ return *(shapelike::cbegin(sh) + idx);
+}
+
+
+template<class RawShape> // Potential O(1) implementation may exist
+inline const TPoint<RawShape>& vertex(const RawShape& sh,
+ unsigned long idx)
+{
+ return vertex(sh, idx, Tag<RawShape>());
+}
+
+template<class RawShape>
+inline size_t contourVertexCount(const RawShape& sh)
+{
+ return shapelike::cend(sh) - shapelike::cbegin(sh);
+}
+
+template<class RawShape, class Fn>
+inline void foreachVertex(RawShape& sh, Fn fn, const PolygonTag&) {
+ foreachVertex(contour(sh), fn, PathTag());
+ for(auto& h : holes(sh)) foreachVertex(h, fn, PathTag());
+}
+
+template<class RawShape, class Fn>
+inline void foreachVertex(RawShape& sh, Fn fn) {
+ foreachVertex(sh, fn, Tag<RawShape>());
+}
+
+template<class Poly> inline bool isConvex(const Poly& sh, const PolygonTag&)
+{
+ bool convex = true;
+ convex &= isConvex(contour(sh), PathTag());
+ convex &= holeCount(sh) == 0;
+ return convex;
+}
+
+template<class RawShape> inline bool isConvex(const RawShape& sh) // dispatch
+{
+ return isConvex(sh, Tag<RawShape>());
+}
+
+}
+
+#define DECLARE_MAIN_TYPES(T) \
+ using Polygon = T; \
+ using Point = TPoint<T>; \
+ using Coord = TCoord<Point>; \
+ using Contour = TContour<T>; \
+ using Box = _Box<Point>; \
+ using Circle = _Circle<Point>; \
+ using Segment = _Segment<Point>; \
+ using Polygons = TMultiShape<T>
+
+}
+
+#endif // GEOMETRY_TRAITS_HPP
diff --git a/src/libnest2d/libnest2d/geometry_traits_nfp.hpp b/src/libnest2d/include/libnest2d/geometry_traits_nfp.hpp
index 2982454cd..cb0580ef4 100644
--- a/src/libnest2d/libnest2d/geometry_traits_nfp.hpp
+++ b/src/libnest2d/include/libnest2d/geometry_traits_nfp.hpp
@@ -22,13 +22,63 @@ inline bool _vsort(const TPoint<RawShape>& v1, const TPoint<RawShape>& v2)
return diff < 0;
}
+
+template<class EdgeList, class RawShape, class Vertex = TPoint<RawShape>>
+inline void buildPolygon(const EdgeList& edgelist,
+ RawShape& rpoly,
+ Vertex& top_nfp)
+{
+ namespace sl = shapelike;
+
+ auto& rsh = sl::contour(rpoly);
+
+ sl::reserve(rsh, 2*edgelist.size());
+
+ // Add the two vertices from the first edge into the final polygon.
+ sl::addVertex(rsh, edgelist.front().first());
+ sl::addVertex(rsh, edgelist.front().second());
+
+ // Sorting function for the nfp reference vertex search
+ auto& cmp = _vsort<RawShape>;
+
+ // the reference (rightmost top) vertex so far
+ top_nfp = *std::max_element(sl::cbegin(rsh), sl::cend(rsh), cmp );
+
+ auto tmp = std::next(sl::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();
+ Vertex p = eit->second() + d;
+
+ sl::addVertex(rsh, p);
+
+ // Set the new reference vertex
+ if(cmp(top_nfp, p)) top_nfp = p;
+
+ tmp = std::next(tmp);
+ }
+
+}
+
+template<class Container, class Iterator = typename Container::iterator>
+void advance(Iterator& it, Container& cont, bool direction)
+{
+ int dir = direction ? 1 : -1;
+ if(dir < 0 && it == cont.begin()) it = std::prev(cont.end());
+ else it += dir;
+ if(dir > 0 && it == cont.end()) it = cont.begin();
+}
+
}
/// A collection of static methods for handling the no fit polygon creation.
namespace nfp {
-//namespace sl = shapelike;
-//namespace pl = pointlike;
+const double BP2D_CONSTEXPR TwoPi = 2*Pi;
/// The complexity level of a polygon that an NFP implementation can handle.
enum class NfpLevel: unsigned {
@@ -60,7 +110,7 @@ using Shapes = TMultiShape<RawShape>;
*
* \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.
+ * polygons are disjunct than the resulting set will contain more polygons.
*/
template<class RawShapes>
inline RawShapes merge(const RawShapes& /*shc*/)
@@ -78,14 +128,14 @@ inline RawShapes merge(const RawShapes& /*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.
+ * polygons are disjunct than the resulting set will contain more polygons.
*/
template<class RawShape>
inline TMultiShape<RawShape> merge(const TMultiShape<RawShape>& shc,
const RawShape& sh)
{
auto m = nfp::merge(shc);
- m.push_back(sh);
+ m.emplace_back(sh);
return nfp::merge(m);
}
@@ -141,8 +191,8 @@ inline TPoint<RawShape> referenceVertex(const RawShape& sh)
* 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.
+ * Complexity should be no more than nlogn (std::sort) in the number of edges
+ * of the input polygons.
*
* \tparam RawShape the Polygon data type.
* \param sh The stationary polygon
@@ -196,33 +246,7 @@ inline NfpResult<RawShape> nfpConvexOnly(const RawShape& sh,
return e1.angleToXaxis() > e2.angleToXaxis();
});
- // Add the two vertices from the first edge into the final polygon.
- sl::addVertex(rsh, edgelist.front().first());
- sl::addVertex(rsh, edgelist.front().second());
-
- // Sorting function for the nfp reference vertex search
- auto& cmp = __nfp::_vsort<RawShape>;
-
- // the reference (rightmost top) vertex so far
- top_nfp = *std::max_element(sl::cbegin(rsh), sl::cend(rsh), cmp );
-
- auto tmp = std::next(sl::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();
- Vertex p = eit->second() + d;
-
- sl::addVertex(rsh, p);
-
- // Set the new reference vertex
- if(cmp(top_nfp, p)) top_nfp = p;
-
- tmp = std::next(tmp);
- }
+ __nfp::buildPolygon(edgelist, rsh, top_nfp);
return {rsh, top_nfp};
}
@@ -260,29 +284,53 @@ NfpResult<RawShape> nfpSimpleSimple(const RawShape& cstationary,
// the way it should be, than make my way around the orientations.
// Reverse the stationary contour to counter clockwise
- auto stcont = sl::getContour(cstationary);
- std::reverse(stcont.begin(), stcont.end());
+ auto stcont = sl::contour(cstationary);
+ {
+ std::reverse(sl::begin(stcont), sl::end(stcont));
+ stcont.pop_back();
+ auto it = std::min_element(sl::begin(stcont), sl::end(stcont),
+ [](const Vertex& v1, const Vertex& v2) {
+ return getY(v1) < getY(v2);
+ });
+ std::rotate(sl::begin(stcont), it, sl::end(stcont));
+ sl::addVertex(stcont, sl::front(stcont));
+ }
RawShape stationary;
- sl::getContour(stationary) = stcont;
+ sl::contour(stationary) = stcont;
// Reverse the orbiter contour to counter clockwise
- auto orbcont = sl::getContour(cother);
+ auto orbcont = sl::contour(cother);
+ {
+ std::reverse(orbcont.begin(), orbcont.end());
+
+ // Step 1: Make the orbiter reverse oriented
+
+ orbcont.pop_back();
+ auto it = std::min_element(orbcont.begin(), orbcont.end(),
+ [](const Vertex& v1, const Vertex& v2) {
+ return getY(v1) < getY(v2);
+ });
- std::reverse(orbcont.begin(), orbcont.end());
+ std::rotate(orbcont.begin(), it, orbcont.end());
+ orbcont.emplace_back(orbcont.front());
+
+ for(auto &v : orbcont) v = -v;
+
+ }
// Copy the orbiter (contour only), we will have to work on it
RawShape orbiter;
- sl::getContour(orbiter) = orbcont;
-
- // Step 1: Make the orbiter reverse oriented
- for(auto &v : sl::getContour(orbiter)) v = -v;
+ sl::contour(orbiter) = orbcont;
- // An egde with additional data for marking it
+ // An edge with additional data for marking it
struct MarkedEdge {
Edge e; Radians turn_angle = 0; bool is_turning_point = false;
MarkedEdge() = default;
MarkedEdge(const Edge& ed, Radians ta, bool tp):
e(ed), turn_angle(ta), is_turning_point(tp) {}
+
+ // debug
+ std::string label;
};
// Container for marked edges
@@ -291,71 +339,87 @@ NfpResult<RawShape> nfpSimpleSimple(const RawShape& cstationary,
EdgeList A, B;
// This is how an edge list is created from the polygons
- auto fillEdgeList = [](EdgeList& L, const RawShape& poly, int dir) {
+ auto fillEdgeList = [](EdgeList& L, const RawShape& ppoly, int dir) {
+ auto& poly = sl::contour(ppoly);
+
L.reserve(sl::contourVertexCount(poly));
- auto it = sl::cbegin(poly);
- auto nextit = std::next(it);
+ if(dir > 0) {
+ auto it = poly.begin();
+ auto nextit = std::next(it);
+
+ double turn_angle = 0;
+ bool is_turn_point = false;
+
+ while(nextit != poly.end()) {
+ L.emplace_back(Edge(*it, *nextit), turn_angle, is_turn_point);
+ it++; nextit++;
+ }
+ } else {
+ auto it = sl::rbegin(poly);
+ auto nextit = std::next(it);
- double turn_angle = 0;
- bool is_turn_point = false;
+ double turn_angle = 0;
+ bool is_turn_point = false;
- while(nextit != sl::cend(poly)) {
- L.emplace_back(Edge(*it, *nextit), turn_angle, is_turn_point);
- it++; nextit++;
+ while(nextit != sl::rend(poly)) {
+ L.emplace_back(Edge(*it, *nextit), turn_angle, is_turn_point);
+ it++; nextit++;
+ }
}
auto getTurnAngle = [](const Edge& e1, const Edge& e2) {
auto phi = e1.angleToXaxis();
auto phi_prev = e2.angleToXaxis();
- auto TwoPi = 2.0*Pi;
- if(phi > Pi) phi -= TwoPi;
- if(phi_prev > Pi) phi_prev -= TwoPi;
auto turn_angle = phi-phi_prev;
if(turn_angle > Pi) turn_angle -= TwoPi;
- return phi-phi_prev;
+ if(turn_angle < -Pi) turn_angle += TwoPi;
+ return turn_angle;
};
- if(dir > 0) {
- auto eit = L.begin();
- auto enext = std::next(eit);
-
- eit->turn_angle = getTurnAngle(L.front().e, L.back().e);
+ auto eit = L.begin();
+ auto enext = std::next(eit);
- while(enext != L.end()) {
- enext->turn_angle = getTurnAngle( enext->e, eit->e);
- enext->is_turning_point =
- signbit(enext->turn_angle) != signbit(eit->turn_angle);
- ++eit; ++enext;
- }
+ eit->turn_angle = getTurnAngle(L.front().e, L.back().e);
- L.front().is_turning_point = signbit(L.front().turn_angle) !=
- signbit(L.back().turn_angle);
- } else {
- std::cout << L.size() << std::endl;
-
- auto eit = L.rbegin();
- auto enext = std::next(eit);
-
- eit->turn_angle = getTurnAngle(L.back().e, L.front().e);
-
- while(enext != L.rend()) {
- enext->turn_angle = getTurnAngle(enext->e, eit->e);
- enext->is_turning_point =
- signbit(enext->turn_angle) != signbit(eit->turn_angle);
- std::cout << enext->is_turning_point << " " << enext->turn_angle << std::endl;
+ while(enext != L.end()) {
+ enext->turn_angle = getTurnAngle( enext->e, eit->e);
+ eit->is_turning_point =
+ signbit(enext->turn_angle) != signbit(eit->turn_angle);
+ ++eit; ++enext;
+ }
- ++eit; ++enext;
- }
+ L.back().is_turning_point = signbit(L.back().turn_angle) !=
+ signbit(L.front().turn_angle);
- L.back().is_turning_point = signbit(L.back().turn_angle) !=
- signbit(L.front().turn_angle);
- }
};
// Step 2: Fill the edgelists
fillEdgeList(A, stationary, 1);
- fillEdgeList(B, orbiter, -1);
+ fillEdgeList(B, orbiter, 1);
+
+ int i = 1;
+ for(MarkedEdge& me : A) {
+ std::cout << "a" << i << ":\n\t"
+ << getX(me.e.first()) << " " << getY(me.e.first()) << "\n\t"
+ << getX(me.e.second()) << " " << getY(me.e.second()) << "\n\t"
+ << "Turning point: " << (me.is_turning_point ? "yes" : "no")
+ << std::endl;
+
+ me.label = "a"; me.label += std::to_string(i);
+ i++;
+ }
+
+ i = 1;
+ for(MarkedEdge& me : B) {
+ std::cout << "b" << i << ":\n\t"
+ << getX(me.e.first()) << " " << getY(me.e.first()) << "\n\t"
+ << getX(me.e.second()) << " " << getY(me.e.second()) << "\n\t"
+ << "Turning point: " << (me.is_turning_point ? "yes" : "no")
+ << std::endl;
+ me.label = "b"; me.label += std::to_string(i);
+ i++;
+ }
// A reference to a marked edge that also knows its container
struct MarkedEdgeRef {
@@ -406,10 +470,8 @@ NfpResult<RawShape> nfpSimpleSimple(const RawShape& cstationary,
Bref.emplace_back( ref(me), ref(Bref) );
});
- struct EdgeGroup { typename EdgeRefList::const_iterator first, last; };
-
auto mink = [sortfn] // the Mink(Q, R, direction) sub-procedure
- (const EdgeGroup& Q, const EdgeGroup& R, bool positive)
+ (const EdgeRefList& Q, const EdgeRefList& R, bool positive)
{
// Step 1 "merge sort_list(Q) and sort_list(R) to form merge_list(Q,R)"
@@ -419,99 +481,198 @@ NfpResult<RawShape> nfpSimpleSimple(const RawShape& cstationary,
EdgeRefList merged;
EdgeRefList S, seq;
- merged.reserve((Q.last - Q.first) + (R.last - R.first));
+ merged.reserve(Q.size() + R.size());
- merged.insert(merged.end(), Q.first, Q.last);
- merged.insert(merged.end(), R.first, R.last);
- sort(merged.begin(), merged.end(), sortfn);
+ merged.insert(merged.end(), R.begin(), R.end());
+ std::stable_sort(merged.begin(), merged.end(), sortfn);
+ merged.insert(merged.end(), Q.begin(), Q.end());
+ std::stable_sort(merged.begin(), merged.end(), sortfn);
// Step 2 "set i = 1, k = 1, direction = 1, s1 = q1"
- // we dont use i, instead, q is an iterator into Q. k would be an index
+ // we don't use i, instead, q is an iterator into Q. k would be an index
// into the merged sequence but we use "it" as an iterator for that
// here we obtain references for the containers for later comparisons
- const auto& Rcont = R.first->container.get();
- const auto& Qcont = Q.first->container.get();
-
- // Set the intial direction
- Coord dir = positive? 1 : -1;
-
- // roughly i = 1 (so q = Q.first) and s1 = q1 so S[0] = q;
- auto q = Q.first;
- S.push_back(*q++);
-
- // Roughly step 3
- while(q != Q.last) {
- auto it = merged.begin();
- while(it != merged.end() && !(it->eq(*(Q.first))) ) {
- if(it->isFrom(Rcont)) {
- auto s = *it;
- s.dir = dir;
- S.push_back(s);
+ const auto& Rcont = R.begin()->container.get();
+ const auto& Qcont = Q.begin()->container.get();
+
+ // Set the initial direction
+ Coord dir = 1;
+
+ // roughly i = 1 (so q = Q.begin()) and s1 = q1 so S[0] = q;
+ if(positive) {
+ auto q = Q.begin();
+ S.emplace_back(*q);
+
+ // Roughly step 3
+
+ std::cout << "merged size: " << merged.size() << std::endl;
+ auto mit = merged.begin();
+ for(bool finish = false; !finish && q != Q.end();) {
+ ++q; // "Set i = i + 1"
+
+ while(!finish && mit != merged.end()) {
+ if(mit->isFrom(Rcont)) {
+ auto s = *mit;
+ s.dir = dir;
+ S.emplace_back(s);
+ }
+
+ if(mit->eq(*q)) {
+ S.emplace_back(*q);
+ if(mit->isTurningPoint()) dir = -dir;
+ if(q == Q.begin()) finish = true;
+ break;
+ }
+
+ mit += dir;
+ // __nfp::advance(mit, merged, dir > 0);
}
- if(it->eq(*q)) {
- S.push_back(*q);
- if(it->isTurningPoint()) dir = -dir;
- if(q != Q.first) it += dir;
+ }
+ } else {
+ auto q = Q.rbegin();
+ S.emplace_back(*q);
+
+ // Roughly step 3
+
+ std::cout << "merged size: " << merged.size() << std::endl;
+ auto mit = merged.begin();
+ for(bool finish = false; !finish && q != Q.rend();) {
+ ++q; // "Set i = i + 1"
+
+ while(!finish && mit != merged.end()) {
+ if(mit->isFrom(Rcont)) {
+ auto s = *mit;
+ s.dir = dir;
+ S.emplace_back(s);
+ }
+
+ if(mit->eq(*q)) {
+ S.emplace_back(*q);
+ S.back().dir = -1;
+ if(mit->isTurningPoint()) dir = -dir;
+ if(q == Q.rbegin()) finish = true;
+ break;
+ }
+
+ mit += dir;
+ // __nfp::advance(mit, merged, dir > 0);
}
- else it += dir;
}
- ++q; // "Set i = i + 1"
}
+
// Step 4:
// "Let starting edge r1 be in position si in sequence"
// whaaat? I guess this means the following:
- S[0] = *R.first;
auto it = S.begin();
+ while(!it->eq(*R.begin())) ++it;
// "Set j = 1, next = 2, direction = 1, seq1 = si"
- // we dont use j, seq is expanded dynamically.
- dir = 1; auto next = std::next(R.first);
+ // we don't use j, seq is expanded dynamically.
+ dir = 1;
+ auto next = std::next(R.begin()); seq.emplace_back(*it);
// Step 5:
// "If all si edges have been allocated to seqj" should mean that
// we loop until seq has equal size with S
- while(seq.size() < S.size()) {
+ auto send = it; //it == S.begin() ? it : std::prev(it);
+ while(it != S.end()) {
++it; if(it == S.end()) it = S.begin();
+ if(it == send) break;
if(it->isFrom(Qcont)) {
- seq.push_back(*it); // "If si is from Q, j = j + 1, seqj = si"
+ seq.emplace_back(*it); // "If si is from Q, j = j + 1, seqj = si"
// "If si is a turning point in Q,
// direction = - direction, next = next + direction"
- if(it->isTurningPoint()) { dir = -dir; next += dir; }
+ if(it->isTurningPoint()) {
+ dir = -dir;
+ next += dir;
+// __nfp::advance(next, R, dir > 0);
+ }
}
- if(it->eq(*next) && dir == next->dir) { // "If si = direction.rnext"
+ if(it->eq(*next) /*&& dir == next->dir*/) { // "If si = direction.rnext"
// "j = j + 1, seqj = si, next = next + direction"
- seq.push_back(*it); next += dir;
+ seq.emplace_back(*it);
+ next += dir;
+// __nfp::advance(next, R, dir > 0);
}
}
return seq;
};
- EdgeGroup R{ Bref.begin(), Bref.begin() }, Q{ Aref.begin(), Aref.end() };
- auto it = Bref.begin();
- bool orientation = true;
- EdgeRefList seqlist;
- seqlist.reserve(3*(Aref.size() + Bref.size()));
+ std::vector<EdgeRefList> seqlist;
+ seqlist.reserve(Bref.size());
+
+ EdgeRefList Bslope = Bref; // copy Bref, we will make a slope diagram
+
+ // make the slope diagram of B
+ std::sort(Bslope.begin(), Bslope.end(), sortfn);
+
+ auto slopeit = Bslope.begin(); // search for the first turning point
+ while(!slopeit->isTurningPoint() && slopeit != Bslope.end()) slopeit++;
+
+ if(slopeit == Bslope.end()) {
+ // no turning point means convex polygon.
+ seqlist.emplace_back(mink(Aref, Bref, true));
+ } else {
+ int dir = 1;
+
+ auto firstturn = Bref.begin();
+ while(!firstturn->eq(*slopeit)) ++firstturn;
+
+ assert(firstturn != Bref.end());
+
+ EdgeRefList bgroup; bgroup.reserve(Bref.size());
+ bgroup.emplace_back(*slopeit);
- while(it != Bref.end()) // This is step 3 and step 4 in one loop
- if(it->isTurningPoint()) {
- R = {R.last, it++};
- auto seq = mink(Q, R, orientation);
+ auto b_it = std::next(firstturn);
+ while(b_it != firstturn) {
+ if(b_it == Bref.end()) b_it = Bref.begin();
- // TODO step 6 (should be 5 shouldn't it?): linking edges from A
- // I don't get this step
+ while(!slopeit->eq(*b_it)) {
+ __nfp::advance(slopeit, Bslope, dir > 0);
+ }
+
+ if(!slopeit->isTurningPoint()) {
+ bgroup.emplace_back(*slopeit);
+ } else {
+ if(!bgroup.empty()) {
+ if(dir > 0) bgroup.emplace_back(*slopeit);
+ for(auto& me : bgroup) {
+ std::cout << me.eref.get().label << ", ";
+ }
+ std::cout << std::endl;
+ seqlist.emplace_back(mink(Aref, bgroup, dir == 1 ? true : false));
+ bgroup.clear();
+ if(dir < 0) bgroup.emplace_back(*slopeit);
+ } else {
+ bgroup.emplace_back(*slopeit);
+ }
+
+ dir *= -1;
+ }
+ ++b_it;
+ }
+ }
+
+// while(it != Bref.end()) // This is step 3 and step 4 in one loop
+// if(it->isTurningPoint()) {
+// R = {R.last, it++};
+// auto seq = mink(Q, R, orientation);
- seqlist.insert(seqlist.end(), seq.begin(), seq.end());
- orientation = !orientation;
- } else ++it;
+// // TODO step 6 (should be 5 shouldn't it?): linking edges from A
+// // I don't get this step
- if(seqlist.empty()) seqlist = mink(Q, {Bref.begin(), Bref.end()}, true);
+// seqlist.insert(seqlist.end(), seq.begin(), seq.end());
+// orientation = !orientation;
+// } else ++it;
+
+// if(seqlist.empty()) seqlist = mink(Q, {Bref.begin(), Bref.end()}, true);
// /////////////////////////////////////////////////////////////////////////
// Algorithm 2: breaking Minkowski sums into track line trips
@@ -523,8 +684,25 @@ NfpResult<RawShape> nfpSimpleSimple(const RawShape& cstationary,
// /////////////////////////////////////////////////////////////////////////
+ for(auto& seq : seqlist) {
+ std::cout << "seqlist size: " << seq.size() << std::endl;
+ for(auto& s : seq) {
+ std::cout << (s.dir > 0 ? "" : "-") << s.eref.get().label << ", ";
+ }
+ std::cout << std::endl;
+ }
+
+ auto& seq = seqlist.front();
+ RawShape rsh;
+ Vertex top_nfp;
+ std::vector<Edge> edgelist; edgelist.reserve(seq.size());
+ for(auto& s : seq) {
+ edgelist.emplace_back(s.eref.get().e);
+ }
+
+ __nfp::buildPolygon(edgelist, rsh, top_nfp);
- return Result(stationary, Vertex());
+ return Result(rsh, top_nfp);
}
// Specializable NFP implementation class. Specialize it if you have a faster
diff --git a/src/libnest2d/libnest2d/libnest2d.hpp b/src/libnest2d/include/libnest2d/libnest2d.hpp
index 8841d1b73..aac62e094 100644
--- a/src/libnest2d/libnest2d/libnest2d.hpp
+++ b/src/libnest2d/include/libnest2d/libnest2d.hpp
@@ -215,7 +215,7 @@ public:
switch(convexity_) {
case Convexity::UNCHECKED:
- ret = sl::isConvex<RawShape>(sl::getContour(transformedShape()));
+ ret = sl::isConvex(sl::contour(transformedShape()));
convexity_ = ret? Convexity::C_TRUE : Convexity::C_FALSE;
break;
case Convexity::C_TRUE: ret = true; break;
@@ -805,16 +805,16 @@ public:
class SConf = SelectionConfig>
Nester( TBinType&& bin,
Unit min_obj_distance = 0,
- PConf&& pconfig = PConf(),
- SConf&& sconfig = SConf()):
+ const PConf& pconfig = PConf(),
+ const SConf& sconfig = SConf()):
bin_(std::forward<TBinType>(bin)),
- pconfig_(std::forward<PlacementConfig>(pconfig)),
+ pconfig_(pconfig),
min_obj_distance_(min_obj_distance)
{
static_assert( std::is_same<TPItem, TSItem>::value,
"Incompatible placement and selection strategy!");
- selector_.configure(std::forward<SelectionConfig>(sconfig));
+ selector_.configure(sconfig);
}
void configure(const PlacementConfig& pconf) { pconfig_ = pconf; }
diff --git a/src/libnest2d/libnest2d/optimizer.hpp b/src/libnest2d/include/libnest2d/optimizer.hpp
index 90d2f2ff9..78e105598 100644
--- a/src/libnest2d/libnest2d/optimizer.hpp
+++ b/src/libnest2d/include/libnest2d/optimizer.hpp
@@ -105,6 +105,11 @@ struct StopCriteria {
/// Stop if this value or better is found.
double stop_score = std::nan("");
+ /// A predicate that if evaluates to true, the optimization should terminate
+ /// and the best result found prior to termination should be returned.
+ std::function<bool()> stop_condition = [] { return false; };
+
+ /// The max allowed number of iterations.
unsigned max_iterations = 0;
};
diff --git a/src/libnest2d/include/libnest2d/optimizers/nlopt/CMakeLists.txt b/src/libnest2d/include/libnest2d/optimizers/nlopt/CMakeLists.txt
new file mode 100644
index 000000000..5559ad645
--- /dev/null
+++ b/src/libnest2d/include/libnest2d/optimizers/nlopt/CMakeLists.txt
@@ -0,0 +1,61 @@
+find_package(NLopt 1.4)
+
+if(NOT NLopt_FOUND)
+ message(STATUS "NLopt not found so downloading "
+ "and automatic build is performed...")
+
+ include(DownloadProject)
+
+ if (CMAKE_VERSION VERSION_LESS 3.2)
+ set(UPDATE_DISCONNECTED_IF_AVAILABLE "")
+ else()
+ set(UPDATE_DISCONNECTED_IF_AVAILABLE "UPDATE_DISCONNECTED 1")
+ endif()
+
+ set(URL_NLOPT "https://github.com/stevengj/nlopt.git"
+ CACHE STRING "Location of the nlopt git repository")
+
+ # set(NLopt_DIR ${CMAKE_BINARY_DIR}/nlopt)
+ include(DownloadProject)
+ download_project( PROJ nlopt
+ GIT_REPOSITORY ${URL_NLOPT}
+ GIT_TAG v2.5.0
+ # CMAKE_CACHE_ARGS -DBUILD_SHARED_LIBS:BOOL=OFF -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE} -DCMAKE_INSTALL_PREFIX=${NLopt_DIR}
+ ${UPDATE_DISCONNECTED_IF_AVAILABLE}
+ )
+
+ set(SHARED_LIBS_STATE BUILD_SHARED_LIBS)
+ set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
+ set(NLOPT_PYTHON OFF CACHE BOOL "" FORCE)
+ set(NLOPT_OCTAVE OFF CACHE BOOL "" FORCE)
+ set(NLOPT_MATLAB OFF CACHE BOOL "" FORCE)
+ set(NLOPT_GUILE OFF CACHE BOOL "" FORCE)
+ set(NLOPT_SWIG OFF CACHE BOOL "" FORCE)
+ set(NLOPT_LINK_PYTHON OFF CACHE BOOL "" FORCE)
+
+ add_subdirectory(${nlopt_SOURCE_DIR} ${nlopt_BINARY_DIR})
+
+ set(NLopt_LIBS nlopt)
+ set(NLopt_INCLUDE_DIR ${nlopt_BINARY_DIR} ${nlopt_BINARY_DIR}/src/api)
+ set(SHARED_LIBS_STATE ${SHARED_STATE})
+
+ add_library(NloptOptimizer INTERFACE)
+ target_link_libraries(NloptOptimizer INTERFACE nlopt)
+ target_include_directories(NloptOptimizer INTERFACE ${NLopt_INCLUDE_DIR})
+
+else()
+ add_library(NloptOptimizer INTERFACE)
+ target_link_libraries(NloptOptimizer INTERFACE Nlopt::Nlopt)
+endif()
+
+target_sources( NloptOptimizer INTERFACE
+${CMAKE_CURRENT_SOURCE_DIR}/simplex.hpp
+${CMAKE_CURRENT_SOURCE_DIR}/subplex.hpp
+${CMAKE_CURRENT_SOURCE_DIR}/genetic.hpp
+${CMAKE_CURRENT_SOURCE_DIR}/nlopt_boilerplate.hpp
+)
+
+target_compile_definitions(NloptOptimizer INTERFACE LIBNEST2D_OPTIMIZER_NLOPT)
+
+# And finally plug the NloptOptimizer into libnest2d
+target_link_libraries(libnest2d INTERFACE NloptOptimizer)
diff --git a/src/libnest2d/libnest2d/optimizers/genetic.hpp b/src/libnest2d/include/libnest2d/optimizers/nlopt/genetic.hpp
index 276854a12..731ead554 100644
--- a/src/libnest2d/libnest2d/optimizers/genetic.hpp
+++ b/src/libnest2d/include/libnest2d/optimizers/nlopt/genetic.hpp
@@ -19,7 +19,8 @@ public:
template<>
struct OptimizerSubclass<Method::G_GENETIC> { using Type = GeneticOptimizer; };
-template<> TOptimizer<Method::G_GENETIC> GlobalOptimizer<Method::G_GENETIC>(
+template<>
+inline TOptimizer<Method::G_GENETIC> GlobalOptimizer<Method::G_GENETIC>(
Method localm, const StopCriteria& scr )
{
return GeneticOptimizer (scr).localMethod(localm);
diff --git a/src/libnest2d/libnest2d/optimizers/nlopt_boilerplate.hpp b/src/libnest2d/include/libnest2d/optimizers/nlopt/nlopt_boilerplate.hpp
index 1a0f06e02..286d176c5 100644
--- a/src/libnest2d/libnest2d/optimizers/nlopt_boilerplate.hpp
+++ b/src/libnest2d/include/libnest2d/optimizers/nlopt/nlopt_boilerplate.hpp
@@ -13,7 +13,7 @@
#include <libnest2d/optimizer.hpp>
#include <cassert>
-#include "libnest2d/metaloop.hpp"
+#include <libnest2d/utils/metaloop.hpp>
#include <utility>
@@ -100,7 +100,13 @@ protected:
std::vector<double>& /*grad*/,
void *data)
{
- auto fnptr = static_cast<remove_ref_t<Fn>*>(data);
+ using TData = std::pair<remove_ref_t<Fn>*, NloptOptimizer*>;
+ auto typeddata = static_cast<TData*>(data);
+
+ if(typeddata->second->stopcr_.stop_condition())
+ typeddata->second->opt_.force_stop();
+
+ auto fnptr = typeddata->first;
auto funval = std::tuple<Args...>();
// copy the obtained objectfunction arguments to the funval tuple.
@@ -155,17 +161,25 @@ protected:
// Take care of the initial values, copy them to initvals_
metaloop::apply(InitValFunc(*this), initvals);
+ std::pair<remove_ref_t<Func>*, NloptOptimizer*> data =
+ std::make_pair(&func, this);
+
switch(dir_) {
case OptDir::MIN:
- opt_.set_min_objective(optfunc<Func, Args...>, &func); break;
+ opt_.set_min_objective(optfunc<Func, Args...>, &data); break;
case OptDir::MAX:
- opt_.set_max_objective(optfunc<Func, Args...>, &func); break;
+ opt_.set_max_objective(optfunc<Func, Args...>, &data); break;
}
Result<Args...> result;
+ nlopt::result rescode;
- auto rescode = opt_.optimize(initvals_, result.score);
- result.resultcode = static_cast<ResultCodes>(rescode);
+ try {
+ rescode = opt_.optimize(initvals_, result.score);
+ result.resultcode = static_cast<ResultCodes>(rescode);
+ } catch( nlopt::forced_stop& ) {
+ result.resultcode = ResultCodes::FORCED_STOP;
+ }
metaloop::apply(ResultCopyFunc(*this), result.optimum);
diff --git a/src/libnest2d/libnest2d/optimizers/simplex.hpp b/src/libnest2d/include/libnest2d/optimizers/nlopt/simplex.hpp
index 78b09b89a..78b09b89a 100644
--- a/src/libnest2d/libnest2d/optimizers/simplex.hpp
+++ b/src/libnest2d/include/libnest2d/optimizers/nlopt/simplex.hpp
diff --git a/src/libnest2d/libnest2d/optimizers/subplex.hpp b/src/libnest2d/include/libnest2d/optimizers/nlopt/subplex.hpp
index 841b04057..841b04057 100644
--- a/src/libnest2d/libnest2d/optimizers/subplex.hpp
+++ b/src/libnest2d/include/libnest2d/optimizers/nlopt/subplex.hpp
diff --git a/src/libnest2d/include/libnest2d/optimizers/optimlib/CMakeLists.txt b/src/libnest2d/include/libnest2d/optimizers/optimlib/CMakeLists.txt
new file mode 100644
index 000000000..efbbd9cfb
--- /dev/null
+++ b/src/libnest2d/include/libnest2d/optimizers/optimlib/CMakeLists.txt
@@ -0,0 +1,5 @@
+find_package(Armadillo REQUIRED)
+
+add_library(OptimlibOptimizer INTERFACE)
+target_include_directories(OptimlibOptimizer INTERFACE ${ARMADILLO_INCLUDE_DIRS})
+target_link_libraries(OptimlibOptimizer INTERFACE ${ARMADILLO_LIBRARIES}) \ No newline at end of file
diff --git a/src/libnest2d/libnest2d/placers/bottomleftplacer.hpp b/src/libnest2d/include/libnest2d/placers/bottomleftplacer.hpp
index 18c27c40c..7f10be7d7 100644
--- a/src/libnest2d/libnest2d/placers/bottomleftplacer.hpp
+++ b/src/libnest2d/include/libnest2d/placers/bottomleftplacer.hpp
@@ -233,7 +233,8 @@ protected:
assert(pleft.vertexCount() > 0);
- auto trpleft = pleft.transformedShape();
+ auto trpleft_poly = pleft.transformedShape();
+ auto& trpleft = sl::contour(trpleft_poly);
auto first = sl::begin(trpleft);
auto next = first + 1;
auto endit = sl::end(trpleft);
@@ -355,8 +356,10 @@ protected:
auto start = std::min(topleft_it->first, bottomleft_it->first);
auto finish = std::max(topleft_it->first, bottomleft_it->first);
+ RawShape ret;
+
// the return shape
- RawShape rsh;
+ auto& rsh = sl::contour(ret);
// reserve for all vertices plus 2 for the left horizontal wall, 2 for
// the additional vertices for maintaning min object distance
@@ -401,7 +404,7 @@ protected:
// Close the polygon
sl::addVertex(rsh, topleft_vertex);
- return rsh;
+ return ret;
}
};
diff --git a/src/libnest2d/libnest2d/placers/nfpplacer.hpp b/src/libnest2d/include/libnest2d/placers/nfpplacer.hpp
index c86fb507e..14ed3d22c 100644
--- a/src/libnest2d/libnest2d/placers/nfpplacer.hpp
+++ b/src/libnest2d/include/libnest2d/placers/nfpplacer.hpp
@@ -15,11 +15,13 @@
#ifndef NDEBUG
#include <iostream>
#endif
+#include <libnest2d/geometry_traits_nfp.hpp>
+#include <libnest2d/optimizer.hpp>
+
#include "placer_boilerplate.hpp"
-#include "../geometry_traits_nfp.hpp"
-#include "libnest2d/optimizer.hpp"
-#include "tools/svgtools.hpp"
+// temporary
+//#include "../tools/svgtools.hpp"
#ifdef USE_TBB
#include <tbb/parallel_for.h>
@@ -55,7 +57,7 @@ inline void enumerate(
#elif defined(_OPENMP)
if((policy & std::launch::async) == std::launch::async) {
#pragma omp parallel for
- for(TN n = 0; n < N; n++) fn(*(from + n), n);
+ for(int n = 0; n < int(N); n++) fn(*(from + n), TN(n));
}
else {
for(TN n = 0; n < N; n++) fn(*(from + n), n);
@@ -72,19 +74,6 @@ inline void enumerate(
#endif
}
-class SpinLock {
- static std::atomic_flag locked;
-public:
- void lock() {
- while (locked.test_and_set(std::memory_order_acquire)) { ; }
- }
- void unlock() {
- locked.clear(std::memory_order_release);
- }
-};
-
-std::atomic_flag SpinLock::locked = ATOMIC_FLAG_INIT ;
-
}
namespace __itemhash {
@@ -101,7 +90,7 @@ Key hash(const _Item<S>& item) {
std::string ret;
auto& rhs = item.rawShape();
- auto& ctr = sl::getContour(rhs);
+ auto& ctr = sl::contour(rhs);
auto it = ctr.begin();
auto nx = std::next(it);
@@ -467,7 +456,7 @@ Circle minimizeCircle(const RawShape& sh) {
using Point = TPoint<RawShape>;
using Coord = TCoord<Point>;
- auto& ctr = sl::getContour(sh);
+ auto& ctr = sl::contour(sh);
if(ctr.empty()) return {{0, 0}, 0};
auto bb = sl::boundingBox(sh);
@@ -641,6 +630,23 @@ private:
Shapes nfps(items_.size());
const Item& trsh = itsh.first;
+ // /////////////////////////////////////////////////////////////////////
+ // TODO: this is a workaround and should be solved in Item with mutexes
+ // guarding the mutable members when writing them.
+ // /////////////////////////////////////////////////////////////////////
+ trsh.transformedShape();
+ trsh.referenceVertex();
+ trsh.rightmostTopVertex();
+ trsh.leftmostBottomVertex();
+
+ for(Item& itm : items_) {
+ itm.transformedShape();
+ itm.referenceVertex();
+ itm.rightmostTopVertex();
+ itm.leftmostBottomVertex();
+ }
+ // /////////////////////////////////////////////////////////////////////
+
__parallel::enumerate(items_.begin(), items_.end(),
[&nfps, &trsh](const Item& sh, size_t n)
{
@@ -651,14 +657,10 @@ private:
nfps[n] = subnfp_r.first;
});
-// for(auto& n : nfps) {
-// auto valid = sl::isValid(n);
-// if(!valid.first) std::cout << "Warning: " << valid.second << std::endl;
-// }
-
return nfp::merge(nfps);
}
+
template<class Level>
Shapes calcnfp( const ItemWithHash itsh, Level)
{ // Function for arbitrary level of nfp implementation
@@ -842,7 +844,11 @@ private:
bool can_pack = false;
double best_overfit = std::numeric_limits<double>::max();
- auto remlist = ItemGroup(remaining.from, remaining.to);
+ ItemGroup remlist;
+ if(remaining.valid) {
+ remlist.insert(remlist.end(), remaining.from, remaining.to);
+ }
+
size_t itemhash = __itemhash::hash(item);
if(items_.empty()) {
diff --git a/src/libnest2d/libnest2d/placers/placer_boilerplate.hpp b/src/libnest2d/include/libnest2d/placers/placer_boilerplate.hpp
index 0df1b8c91..9f940af4d 100644
--- a/src/libnest2d/libnest2d/placers/placer_boilerplate.hpp
+++ b/src/libnest2d/include/libnest2d/placers/placer_boilerplate.hpp
@@ -1,7 +1,7 @@
#ifndef PLACER_BOILERPLATE_HPP
#define PLACER_BOILERPLATE_HPP
-#include "../libnest2d.hpp"
+#include <libnest2d/libnest2d.hpp>
namespace libnest2d { namespace placers {
diff --git a/src/libnest2d/libnest2d/selections/djd_heuristic.hpp b/src/libnest2d/include/libnest2d/selections/djd_heuristic.hpp
index 39761f557..39761f557 100644
--- a/src/libnest2d/libnest2d/selections/djd_heuristic.hpp
+++ b/src/libnest2d/include/libnest2d/selections/djd_heuristic.hpp
diff --git a/src/libnest2d/libnest2d/selections/filler.hpp b/src/libnest2d/include/libnest2d/selections/filler.hpp
index 5f95a6eff..5f95a6eff 100644
--- a/src/libnest2d/libnest2d/selections/filler.hpp
+++ b/src/libnest2d/include/libnest2d/selections/filler.hpp
diff --git a/src/libnest2d/libnest2d/selections/firstfit.hpp b/src/libnest2d/include/libnest2d/selections/firstfit.hpp
index 6bb9c60e4..d25487d6b 100644
--- a/src/libnest2d/libnest2d/selections/firstfit.hpp
+++ b/src/libnest2d/include/libnest2d/selections/firstfit.hpp
@@ -1,7 +1,6 @@
#ifndef FIRSTFIT_HPP
#define FIRSTFIT_HPP
-#include "../libnest2d.hpp"
#include "selection_boilerplate.hpp"
namespace libnest2d { namespace selections {
diff --git a/src/libnest2d/libnest2d/selections/selection_boilerplate.hpp b/src/libnest2d/include/libnest2d/selections/selection_boilerplate.hpp
index cfb98a9c8..8351a99e7 100644
--- a/src/libnest2d/libnest2d/selections/selection_boilerplate.hpp
+++ b/src/libnest2d/include/libnest2d/selections/selection_boilerplate.hpp
@@ -1,8 +1,8 @@
#ifndef SELECTION_BOILERPLATE_HPP
#define SELECTION_BOILERPLATE_HPP
-#include "../libnest2d.hpp"
#include <atomic>
+#include <libnest2d/libnest2d.hpp>
namespace libnest2d { namespace selections {
diff --git a/src/libnest2d/libnest2d/boost_alg.hpp b/src/libnest2d/include/libnest2d/utils/boost_alg.hpp
index bb0403b06..c573edb47 100644
--- a/src/libnest2d/libnest2d/boost_alg.hpp
+++ b/src/libnest2d/include/libnest2d/utils/boost_alg.hpp
@@ -241,11 +241,11 @@ template<> struct tag<bp2d::PolygonImpl> {
template<> struct exterior_ring<bp2d::PolygonImpl> {
static inline bp2d::PathImpl& get(bp2d::PolygonImpl& p) {
- return libnest2d::shapelike::getContour(p);
+ return libnest2d::shapelike::contour(p);
}
static inline bp2d::PathImpl const& get(bp2d::PolygonImpl const& p) {
- return libnest2d::shapelike::getContour(p);
+ return libnest2d::shapelike::contour(p);
}
};
@@ -389,6 +389,14 @@ inline bp2d::Box boundingBox(const PolygonImpl& sh, const PolygonTag&)
}
template<>
+inline bp2d::Box boundingBox(const PathImpl& sh, const PolygonTag&)
+{
+ bp2d::Box b;
+ boost::geometry::envelope(sh, b);
+ return b;
+}
+
+template<>
inline bp2d::Box boundingBox<bp2d::Shapes>(const bp2d::Shapes& shapes,
const MultiPolygonTag&)
{
diff --git a/src/libnest2d/libnest2d/metaloop.hpp b/src/libnest2d/include/libnest2d/utils/metaloop.hpp
index d88988ba1..ac099ac46 100644
--- a/src/libnest2d/libnest2d/metaloop.hpp
+++ b/src/libnest2d/include/libnest2d/utils/metaloop.hpp
@@ -1,7 +1,7 @@
#ifndef METALOOP_HPP
#define METALOOP_HPP
-#include "common.hpp"
+#include <libnest2d/common.hpp>
#include <tuple>
#include <functional>
@@ -12,7 +12,7 @@ namespace libnest2d {
/* ************************************************************************** */
/**
- * \brief C++11 conformant implementation of the index_sequence type from C++14
+ * \brief C++11 compatible implementation of the index_sequence type from C++14
*/
template<size_t...Ints> struct index_sequence {
using value_type = size_t;
diff --git a/src/libnest2d/libnest2d/rotfinder.hpp b/src/libnest2d/include/libnest2d/utils/rotfinder.hpp
index 525fd8759..525fd8759 100644
--- a/src/libnest2d/libnest2d/rotfinder.hpp
+++ b/src/libnest2d/include/libnest2d/utils/rotfinder.hpp
diff --git a/src/libnest2d/libnest2d.h b/src/libnest2d/libnest2d.h
deleted file mode 100644
index bfd88f4f5..000000000
--- a/src/libnest2d/libnest2d.h
+++ /dev/null
@@ -1,42 +0,0 @@
-#ifndef LIBNEST2D_H
-#define LIBNEST2D_H
-
-// The type of backend should be set conditionally by the cmake configuriation
-// for now we set it statically to clipper backend
-#include <libnest2d/clipper_backend/clipper_backend.hpp>
-
-// We include the stock optimizers for local and global optimization
-#include <libnest2d/optimizers/subplex.hpp> // Local subplex for NfpPlacer
-#include <libnest2d/optimizers/genetic.hpp> // Genetic for min. bounding box
-
-#include <libnest2d/libnest2d.hpp>
-#include <libnest2d/placers/bottomleftplacer.hpp>
-#include <libnest2d/placers/nfpplacer.hpp>
-#include <libnest2d/selections/firstfit.hpp>
-#include <libnest2d/selections/filler.hpp>
-#include <libnest2d/selections/djd_heuristic.hpp>
-
-namespace libnest2d {
-
-using Point = PointImpl;
-using Coord = TCoord<PointImpl>;
-using Box = _Box<PointImpl>;
-using Segment = _Segment<PointImpl>;
-using Circle = _Circle<PointImpl>;
-
-using Item = _Item<PolygonImpl>;
-using Rectangle = _Rectangle<PolygonImpl>;
-
-using PackGroup = _PackGroup<PolygonImpl>;
-using IndexedPackGroup = _IndexedPackGroup<PolygonImpl>;
-
-using FillerSelection = selections::_FillerSelection<PolygonImpl>;
-using FirstFitSelection = selections::_FirstFitSelection<PolygonImpl>;
-using DJDHeuristic = selections::_DJDHeuristic<PolygonImpl>;
-
-using NfpPlacer = placers::_NofitPolyPlacer<PolygonImpl>;
-using BottomLeftPlacer = placers::_BottomLeftPlacer<PolygonImpl>;
-
-}
-
-#endif // LIBNEST2D_H
diff --git a/src/libnest2d/libnest2d/geometry_traits.hpp b/src/libnest2d/libnest2d/geometry_traits.hpp
deleted file mode 100644
index a78a03b3a..000000000
--- a/src/libnest2d/libnest2d/geometry_traits.hpp
+++ /dev/null
@@ -1,825 +0,0 @@
-#ifndef GEOMETRY_TRAITS_HPP
-#define GEOMETRY_TRAITS_HPP
-
-#include <string>
-#include <type_traits>
-#include <algorithm>
-#include <array>
-#include <vector>
-#include <numeric>
-#include <limits>
-#include <cmath>
-
-#include "common.hpp"
-
-namespace libnest2d {
-
-/// Getting the coordinate data type for a geometry class.
-template<class GeomClass> struct CoordType { using Type = long; };
-
-/// TCoord<GeomType> as shorthand for typename `CoordType<GeomType>::Type`.
-template<class GeomType>
-using TCoord = typename CoordType<remove_cvref_t<GeomType>>::Type;
-
-/// Getting the type of point structure used by a shape.
-template<class Sh> struct PointType { using Type = typename Sh::PointType; };
-
-/// TPoint<ShapeClass> as shorthand for `typename PointType<ShapeClass>::Type`.
-template<class Shape>
-using TPoint = typename PointType<remove_cvref_t<Shape>>::Type;
-
-/**
- * \brief A point pair base class for other point pairs (segment, box, ...).
- * \tparam RawPoint The actual point type to use.
- */
-template<class RawPoint>
-struct PointPair {
- RawPoint p1;
- RawPoint p2;
-};
-
-struct PolygonTag {};
-struct MultiPolygonTag {};
-struct BoxTag {};
-struct CircleTag {};
-
-template<class Shape> struct ShapeTag { using Type = typename Shape::Tag; };
-template<class S> using Tag = typename ShapeTag<S>::Type;
-
-template<class S> struct MultiShape { using Type = std::vector<S>; };
-template<class S> using TMultiShape = typename MultiShape<S>::Type;
-
-/**
- * \brief An abstraction of a box;
- */
-template<class RawPoint>
-class _Box: PointPair<RawPoint> {
- using PointPair<RawPoint>::p1;
- using PointPair<RawPoint>::p2;
-public:
-
- using Tag = BoxTag;
- using PointType = RawPoint;
-
- inline _Box() = default;
- inline _Box(const RawPoint& p, const RawPoint& pp):
- PointPair<RawPoint>({p, pp}) {}
-
- inline _Box(TCoord<RawPoint> width, TCoord<RawPoint> height):
- _Box(RawPoint{0, 0}, RawPoint{width, height}) {}
-
- inline const RawPoint& minCorner() const BP2D_NOEXCEPT { return p1; }
- inline const RawPoint& maxCorner() const BP2D_NOEXCEPT { return p2; }
-
- inline RawPoint& minCorner() BP2D_NOEXCEPT { return p1; }
- inline RawPoint& maxCorner() BP2D_NOEXCEPT { return p2; }
-
- inline TCoord<RawPoint> width() const BP2D_NOEXCEPT;
- inline TCoord<RawPoint> height() const BP2D_NOEXCEPT;
-
- inline RawPoint center() const BP2D_NOEXCEPT;
-
- inline double area() const BP2D_NOEXCEPT {
- return double(width()*height());
- }
-};
-
-template<class RawPoint>
-class _Circle {
- RawPoint center_;
- double radius_ = 0;
-public:
-
- using Tag = CircleTag;
- using PointType = RawPoint;
-
- _Circle() = default;
-
- _Circle(const RawPoint& center, double r): center_(center), radius_(r) {}
-
- inline const RawPoint& center() const BP2D_NOEXCEPT { return center_; }
- inline const void center(const RawPoint& c) { center_ = c; }
-
- inline double radius() const BP2D_NOEXCEPT { return radius_; }
- inline void radius(double r) { radius_ = r; }
-
- inline double area() const BP2D_NOEXCEPT {
- return 2.0*Pi*radius_*radius_;
- }
-};
-
-/**
- * \brief An abstraction of a directed line segment with two points.
- */
-template<class RawPoint>
-class _Segment: PointPair<RawPoint> {
- using PointPair<RawPoint>::p1;
- using PointPair<RawPoint>::p2;
- mutable Radians angletox_ = std::nan("");
-public:
-
- using PointType = RawPoint;
-
- inline _Segment() = default;
-
- inline _Segment(const RawPoint& p, const RawPoint& pp):
- PointPair<RawPoint>({p, pp}) {}
-
- /**
- * @brief Get the first point.
- * @return Returns the starting point.
- */
- inline const RawPoint& first() const BP2D_NOEXCEPT { return p1; }
-
- /**
- * @brief The end point.
- * @return Returns the end point of the segment.
- */
- inline const RawPoint& second() const BP2D_NOEXCEPT { return p2; }
-
- inline void first(const RawPoint& p) BP2D_NOEXCEPT
- {
- angletox_ = std::nan(""); p1 = p;
- }
-
- inline void second(const RawPoint& p) BP2D_NOEXCEPT {
- angletox_ = std::nan(""); p2 = p;
- }
-
- /// Returns the angle measured to the X (horizontal) axis.
- inline Radians angleToXaxis() const;
-
- /// The length of the segment in the measure of the coordinate system.
- inline double length();
-};
-
-// This struct serves almost as a namespace. The only difference is that is can
-// used in friend declarations.
-namespace pointlike {
-
- template<class RawPoint>
- inline TCoord<RawPoint> x(const RawPoint& p)
- {
- return p(0);
- }
-
- template<class RawPoint>
- inline TCoord<RawPoint> y(const RawPoint& p)
- {
- return p(1);
- }
-
- template<class RawPoint>
- inline TCoord<RawPoint>& x(RawPoint& p)
- {
- return p(0);
- }
-
- template<class RawPoint>
- inline TCoord<RawPoint>& y(RawPoint& p)
- {
- return p(1);
- }
-
- template<class RawPoint>
- inline double distance(const RawPoint& /*p1*/, const RawPoint& /*p2*/)
- {
- static_assert(always_false<RawPoint>::value,
- "PointLike::distance(point, point) unimplemented!");
- return 0;
- }
-
- template<class RawPoint>
- inline double distance(const RawPoint& /*p1*/,
- const _Segment<RawPoint>& /*s*/)
- {
- static_assert(always_false<RawPoint>::value,
- "PointLike::distance(point, segment) unimplemented!");
- return 0;
- }
-
- template<class RawPoint>
- inline std::pair<TCoord<RawPoint>, bool> horizontalDistance(
- const RawPoint& p, const _Segment<RawPoint>& s)
- {
- using Unit = TCoord<RawPoint>;
- auto x = pointlike::x(p), y = pointlike::y(p);
- auto x1 = pointlike::x(s.first()), y1 = pointlike::y(s.first());
- auto x2 = pointlike::x(s.second()), y2 = pointlike::y(s.second());
-
- TCoord<RawPoint> ret;
-
- if( (y < y1 && y < y2) || (y > y1 && y > y2) )
- return {0, false};
- if ((y == y1 && y == y2) && (x > x1 && x > x2))
- ret = std::min( x-x1, x -x2);
- else if( (y == y1 && y == y2) && (x < x1 && x < x2))
- ret = -std::min(x1 - x, x2 - x);
- else if(std::abs(y - y1) <= std::numeric_limits<Unit>::epsilon() &&
- std::abs(y - y2) <= std::numeric_limits<Unit>::epsilon())
- ret = 0;
- else
- ret = x - x1 + (x1 - x2)*(y1 - y)/(y1 - y2);
-
- return {ret, true};
- }
-
- template<class RawPoint>
- inline std::pair<TCoord<RawPoint>, bool> verticalDistance(
- const RawPoint& p, const _Segment<RawPoint>& s)
- {
- using Unit = TCoord<RawPoint>;
- auto x = pointlike::x(p), y = pointlike::y(p);
- auto x1 = pointlike::x(s.first()), y1 = pointlike::y(s.first());
- auto x2 = pointlike::x(s.second()), y2 = pointlike::y(s.second());
-
- TCoord<RawPoint> ret;
-
- if( (x < x1 && x < x2) || (x > x1 && x > x2) )
- return {0, false};
- if ((x == x1 && x == x2) && (y > y1 && y > y2))
- ret = std::min( y-y1, y -y2);
- else if( (x == x1 && x == x2) && (y < y1 && y < y2))
- ret = -std::min(y1 - y, y2 - y);
- else if(std::abs(x - x1) <= std::numeric_limits<Unit>::epsilon() &&
- std::abs(x - x2) <= std::numeric_limits<Unit>::epsilon())
- ret = 0;
- else
- ret = y - y1 + (y1 - y2)*(x1 - x)/(x1 - x2);
-
- return {ret, true};
- }
-}
-
-template<class RawPoint>
-TCoord<RawPoint> _Box<RawPoint>::width() const BP2D_NOEXCEPT
-{
- return pointlike::x(maxCorner()) - pointlike::x(minCorner());
-}
-
-template<class RawPoint>
-TCoord<RawPoint> _Box<RawPoint>::height() const BP2D_NOEXCEPT
-{
- return pointlike::y(maxCorner()) - pointlike::y(minCorner());
-}
-
-template<class RawPoint>
-TCoord<RawPoint> getX(const RawPoint& p) { return pointlike::x<RawPoint>(p); }
-
-template<class RawPoint>
-TCoord<RawPoint> getY(const RawPoint& p) { return pointlike::y<RawPoint>(p); }
-
-template<class RawPoint>
-void setX(RawPoint& p, const TCoord<RawPoint>& val)
-{
- pointlike::x<RawPoint>(p) = val;
-}
-
-template<class RawPoint>
-void setY(RawPoint& p, const TCoord<RawPoint>& val)
-{
- pointlike::y<RawPoint>(p) = val;
-}
-
-template<class RawPoint>
-inline Radians _Segment<RawPoint>::angleToXaxis() const
-{
- if(std::isnan(static_cast<double>(angletox_))) {
- TCoord<RawPoint> dx = getX(second()) - getX(first());
- TCoord<RawPoint> dy = getY(second()) - getY(first());
-
- double a = std::atan2(dy, dx);
- auto s = std::signbit(a);
-
- if(s) a += Pi_2;
- angletox_ = a;
- }
- return angletox_;
-}
-
-template<class RawPoint>
-inline double _Segment<RawPoint>::length()
-{
- return pointlike::distance(first(), second());
-}
-
-template<class RawPoint>
-inline RawPoint _Box<RawPoint>::center() const BP2D_NOEXCEPT {
- auto& minc = minCorner();
- auto& maxc = maxCorner();
-
- using Coord = TCoord<RawPoint>;
-
- RawPoint ret = { // No rounding here, we dont know if these are int coords
- static_cast<Coord>( (getX(minc) + getX(maxc))/2.0 ),
- static_cast<Coord>( (getY(minc) + getY(maxc))/2.0 )
- };
-
- return ret;
-}
-
-template<class RawShape>
-struct HolesContainer {
- using Type = std::vector<RawShape>;
-};
-
-template<class RawShape>
-using THolesContainer = typename HolesContainer<remove_cvref_t<RawShape>>::Type;
-
-template<class RawShape>
-struct CountourType {
- using Type = RawShape;
-};
-
-template<class RawShape>
-using TContour = typename CountourType<remove_cvref_t<RawShape>>::Type;
-
-enum class Orientation {
- CLOCKWISE,
- COUNTER_CLOCKWISE
-};
-
-template<class RawShape>
-struct OrientationType {
-
- // Default Polygon orientation that the library expects
- static const Orientation Value = Orientation::CLOCKWISE;
-};
-
-enum class Formats {
- WKT,
- SVG
-};
-
-// This struct serves as a namespace. The only difference is that it can be
-// used in friend declarations and can be aliased at class scope.
-namespace shapelike {
-
- template<class RawShape>
- using Shapes = TMultiShape<RawShape>;
-
- template<class RawShape>
- inline RawShape create(const TContour<RawShape>& contour,
- const THolesContainer<RawShape>& holes)
- {
- return RawShape(contour, holes);
- }
-
- template<class RawShape>
- inline RawShape create(TContour<RawShape>&& contour,
- THolesContainer<RawShape>&& holes)
- {
- return RawShape(contour, holes);
- }
-
- template<class RawShape>
- inline RawShape create(const TContour<RawShape>& contour)
- {
- return create<RawShape>(contour, {});
- }
-
- template<class RawShape>
- inline RawShape create(TContour<RawShape>&& contour)
- {
- return create<RawShape>(contour, {});
- }
-
- template<class RawShape>
- inline THolesContainer<RawShape>& holes(RawShape& /*sh*/)
- {
- static THolesContainer<RawShape> empty;
- return empty;
- }
-
- template<class RawShape>
- inline const THolesContainer<RawShape>& holes(const RawShape& /*sh*/)
- {
- static THolesContainer<RawShape> empty;
- return empty;
- }
-
- template<class RawShape>
- inline TContour<RawShape>& getHole(RawShape& sh, unsigned long idx)
- {
- return holes(sh)[idx];
- }
-
- template<class RawShape>
- inline const TContour<RawShape>& getHole(const RawShape& sh,
- unsigned long idx)
- {
- return holes(sh)[idx];
- }
-
- template<class RawShape>
- inline size_t holeCount(const RawShape& sh)
- {
- return holes(sh).size();
- }
-
- template<class RawShape>
- inline TContour<RawShape>& getContour(RawShape& sh)
- {
- return sh;
- }
-
- template<class RawShape>
- inline const TContour<RawShape>& getContour(const RawShape& sh)
- {
- return sh;
- }
-
- // Optional, does nothing by default
- template<class RawShape>
- inline void reserve(RawShape& /*sh*/, size_t /*vertex_capacity*/) {}
-
- template<class RawShape, class...Args>
- inline void addVertex(RawShape& sh, Args...args)
- {
- return getContour(sh).emplace_back(std::forward<Args>(args)...);
- }
-
- template<class RawShape>
- inline typename TContour<RawShape>::iterator begin(RawShape& sh)
- {
- return getContour(sh).begin();
- }
-
- template<class RawShape>
- inline typename TContour<RawShape>::iterator end(RawShape& sh)
- {
- return getContour(sh).end();
- }
-
- template<class RawShape>
- inline typename TContour<RawShape>::const_iterator
- cbegin(const RawShape& sh)
- {
- return getContour(sh).cbegin();
- }
-
- template<class RawShape>
- inline typename TContour<RawShape>::const_iterator cend(const RawShape& sh)
- {
- return getContour(sh).cend();
- }
-
- template<class RawShape>
- inline std::string toString(const RawShape& /*sh*/)
- {
- return "";
- }
-
- template<Formats, class RawShape>
- inline std::string serialize(const RawShape& /*sh*/, double /*scale*/=1)
- {
- static_assert(always_false<RawShape>::value,
- "ShapeLike::serialize() unimplemented!");
- return "";
- }
-
- template<Formats, class RawShape>
- inline void unserialize(RawShape& /*sh*/, const std::string& /*str*/)
- {
- static_assert(always_false<RawShape>::value,
- "ShapeLike::unserialize() unimplemented!");
- }
-
- template<class RawShape>
- inline double area(const RawShape& /*sh*/, const PolygonTag&)
- {
- static_assert(always_false<RawShape>::value,
- "ShapeLike::area() unimplemented!");
- return 0;
- }
-
- template<class RawShape>
- inline bool intersects(const RawShape& /*sh*/, const RawShape& /*sh*/)
- {
- static_assert(always_false<RawShape>::value,
- "ShapeLike::intersects() unimplemented!");
- return false;
- }
-
- template<class RawShape>
- inline bool isInside(const TPoint<RawShape>& /*point*/,
- const RawShape& /*shape*/)
- {
- static_assert(always_false<RawShape>::value,
- "ShapeLike::isInside(point, shape) unimplemented!");
- return false;
- }
-
- template<class RawShape>
- inline bool isInside(const RawShape& /*shape*/,
- const RawShape& /*shape*/)
- {
- static_assert(always_false<RawShape>::value,
- "ShapeLike::isInside(shape, shape) unimplemented!");
- return false;
- }
-
- template<class RawShape>
- inline bool touches( const RawShape& /*shape*/,
- const RawShape& /*shape*/)
- {
- static_assert(always_false<RawShape>::value,
- "ShapeLike::touches(shape, shape) unimplemented!");
- return false;
- }
-
- template<class RawShape>
- inline bool touches( const TPoint<RawShape>& /*point*/,
- const RawShape& /*shape*/)
- {
- static_assert(always_false<RawShape>::value,
- "ShapeLike::touches(point, shape) unimplemented!");
- return false;
- }
-
- template<class RawShape>
- inline _Box<TPoint<RawShape>> boundingBox(const RawShape& /*sh*/,
- const PolygonTag&)
- {
- static_assert(always_false<RawShape>::value,
- "ShapeLike::boundingBox(shape) unimplemented!");
- }
-
- template<class RawShapes>
- inline _Box<TPoint<typename RawShapes::value_type>>
- boundingBox(const RawShapes& /*sh*/, const MultiPolygonTag&)
- {
- static_assert(always_false<RawShapes>::value,
- "ShapeLike::boundingBox(shapes) unimplemented!");
- }
-
- template<class RawShape>
- inline RawShape convexHull(const RawShape& /*sh*/, const PolygonTag&)
- {
- static_assert(always_false<RawShape>::value,
- "ShapeLike::convexHull(shape) unimplemented!");
- return RawShape();
- }
-
- template<class RawShapes>
- inline typename RawShapes::value_type
- convexHull(const RawShapes& /*sh*/, const MultiPolygonTag&)
- {
- static_assert(always_false<RawShapes>::value,
- "ShapeLike::convexHull(shapes) unimplemented!");
- return typename RawShapes::value_type();
- }
-
- template<class RawShape>
- inline void rotate(RawShape& /*sh*/, const Radians& /*rads*/)
- {
- static_assert(always_false<RawShape>::value,
- "ShapeLike::rotate() unimplemented!");
- }
-
- template<class RawShape, class RawPoint>
- inline void translate(RawShape& /*sh*/, const RawPoint& /*offs*/)
- {
- static_assert(always_false<RawShape>::value,
- "ShapeLike::translate() unimplemented!");
- }
-
- template<class RawShape>
- inline void offset(RawShape& /*sh*/, TCoord<TPoint<RawShape>> /*distance*/)
- {
- dout() << "The current geometry backend does not support offsetting!\n";
- }
-
- template<class RawShape>
- inline std::pair<bool, std::string> isValid(const RawShape& /*sh*/)
- {
- return {false, "ShapeLike::isValid() unimplemented!"};
- }
-
- template<class RawShape>
- inline bool isConvex(const TContour<RawShape>& sh)
- {
- using Vertex = TPoint<RawShape>;
- 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
- // *************************************************************************
-
- template<class Box>
- inline Box boundingBox(const Box& box, const BoxTag& )
- {
- return box;
- }
-
- template<class Circle>
- inline _Box<typename Circle::PointType> boundingBox(
- const Circle& circ, const CircleTag&)
- {
- using Point = typename Circle::PointType;
- using Coord = TCoord<Point>;
- Point pmin = {
- static_cast<Coord>(getX(circ.center()) - circ.radius()),
- static_cast<Coord>(getY(circ.center()) - circ.radius()) };
-
- Point pmax = {
- static_cast<Coord>(getX(circ.center()) + circ.radius()),
- static_cast<Coord>(getY(circ.center()) + circ.radius()) };
-
- return {pmin, pmax};
- }
-
- template<class S> // Dispatch function
- inline _Box<TPoint<S>> boundingBox(const S& sh)
- {
- return boundingBox(sh, Tag<S>() );
- }
-
- template<class Box>
- inline double area(const Box& box, const BoxTag& )
- {
- return box.area();
- }
-
- template<class Circle>
- inline double area(const Circle& circ, const CircleTag& )
- {
- return circ.area();
- }
-
- template<class RawShape> // Dispatching function
- inline double area(const RawShape& sh)
- {
- return area(sh, Tag<RawShape>());
- }
-
- template<class RawShape>
- inline double area(const Shapes<RawShape>& shapes)
- {
- return std::accumulate(shapes.begin(), shapes.end(), 0.0,
- [](double a, const RawShape& b) {
- return a += area(b);
- });
- }
-
- template<class RawShape>
- inline auto convexHull(const RawShape& sh)
- -> decltype(convexHull(sh, Tag<RawShape>())) // TODO: C++14 could deduce
- {
- return convexHull(sh, Tag<RawShape>());
- }
-
- template<class RawShape>
- inline bool isInside(const TPoint<RawShape>& point,
- const _Circle<TPoint<RawShape>>& circ)
- {
- return pointlike::distance(point, circ.center()) < circ.radius();
- }
-
- template<class RawShape>
- inline bool isInside(const TPoint<RawShape>& point,
- const _Box<TPoint<RawShape>>& box)
- {
- auto px = getX(point);
- auto py = getY(point);
- auto minx = getX(box.minCorner());
- auto miny = getY(box.minCorner());
- auto maxx = getX(box.maxCorner());
- auto maxy = getY(box.maxCorner());
-
- return px > minx && px < maxx && py > miny && py < maxy;
- }
-
- template<class RawShape>
- inline bool isInside(const RawShape& sh,
- const _Circle<TPoint<RawShape>>& circ)
- {
- return std::all_of(cbegin(sh), cend(sh),
- [&circ](const TPoint<RawShape>& p){
- return isInside<RawShape>(p, circ);
- });
- }
-
- template<class RawShape>
- inline bool isInside(const _Box<TPoint<RawShape>>& box,
- const _Circle<TPoint<RawShape>>& circ)
- {
- return isInside<RawShape>(box.minCorner(), circ) &&
- isInside<RawShape>(box.maxCorner(), circ);
- }
-
- template<class RawShape>
- inline bool isInside(const _Box<TPoint<RawShape>>& ibb,
- const _Box<TPoint<RawShape>>& box)
- {
- auto iminX = getX(ibb.minCorner());
- auto imaxX = getX(ibb.maxCorner());
- auto iminY = getY(ibb.minCorner());
- auto imaxY = getY(ibb.maxCorner());
-
- auto minX = getX(box.minCorner());
- auto maxX = getX(box.maxCorner());
- auto minY = getY(box.minCorner());
- auto maxY = getY(box.maxCorner());
-
- return iminX > minX && imaxX < maxX && iminY > minY && imaxY < maxY;
- }
-
- template<class RawShape> // Potential O(1) implementation may exist
- inline TPoint<RawShape>& vertex(RawShape& sh, unsigned long idx)
- {
- return *(begin(sh) + idx);
- }
-
- template<class RawShape> // Potential O(1) implementation may exist
- inline const TPoint<RawShape>& vertex(const RawShape& sh,
- unsigned long idx)
- {
- return *(cbegin(sh) + idx);
- }
-
- template<class RawShape>
- inline size_t contourVertexCount(const RawShape& sh)
- {
- return cend(sh) - cbegin(sh);
- }
-
- template<class RawShape, class Fn>
- inline void foreachContourVertex(RawShape& sh, Fn fn) {
- for(auto it = begin(sh); it != end(sh); ++it) fn(*it);
- }
-
- template<class RawShape, class Fn>
- inline void foreachHoleVertex(RawShape& sh, Fn fn) {
- for(int i = 0; i < holeCount(sh); ++i) {
- auto& h = getHole(sh, i);
- for(auto it = begin(h); it != end(h); ++it) fn(*it);
- }
- }
-
- template<class RawShape, class Fn>
- inline void foreachContourVertex(const RawShape& sh, Fn fn) {
- for(auto it = cbegin(sh); it != cend(sh); ++it) fn(*it);
- }
-
- template<class RawShape, class Fn>
- inline void foreachHoleVertex(const RawShape& sh, Fn fn) {
- for(int i = 0; i < holeCount(sh); ++i) {
- auto& h = getHole(sh, i);
- for(auto it = cbegin(h); it != cend(h); ++it) fn(*it);
- }
- }
-
- template<class RawShape, class Fn>
- inline void foreachVertex(RawShape& sh, Fn fn) {
- foreachContourVertex(sh, fn);
- foreachHoleVertex(sh, fn);
- }
-
- template<class RawShape, class Fn>
- inline void foreachVertex(const RawShape& sh, Fn fn) {
- foreachContourVertex(sh, fn);
- foreachHoleVertex(sh, fn);
- }
-}
-
-#define DECLARE_MAIN_TYPES(T) \
- using Polygon = T; \
- using Point = TPoint<T>; \
- using Coord = TCoord<Point>; \
- using Contour = TContour<T>; \
- using Box = _Box<Point>; \
- using Circle = _Circle<Point>; \
- using Segment = _Segment<Point>; \
- using Polygons = TMultiShape<T>
-
-}
-
-#endif // GEOMETRY_TRAITS_HPP
diff --git a/src/libnest2d/tests/CMakeLists.txt b/src/libnest2d/tests/CMakeLists.txt
index 3777f3c56..fc3cd309d 100644
--- a/src/libnest2d/tests/CMakeLists.txt
+++ b/src/libnest2d/tests/CMakeLists.txt
@@ -3,7 +3,10 @@
find_package(GTest 1.7)
if(NOT GTEST_FOUND)
- message(STATUS "GTest not found so downloading...")
+ set(URL_GTEST "https://github.com/google/googletest.git"
+ CACHE STRING "Google test source code repository location.")
+
+ message(STATUS "GTest not found so downloading from ${URL_GTEST}")
# Go and download google test framework, integrate it with the build
set(GTEST_LIBS_TO_LINK gtest gtest_main)
@@ -15,7 +18,7 @@ if(NOT GTEST_FOUND)
include(DownloadProject)
download_project(PROJ googletest
- GIT_REPOSITORY https://github.com/google/googletest.git
+ GIT_REPOSITORY ${URL_GTEST}
GIT_TAG release-1.7.0
${UPDATE_DISCONNECTED_IF_AVAILABLE}
)
@@ -35,17 +38,18 @@ else()
set(GTEST_LIBS_TO_LINK ${GTEST_BOTH_LIBRARIES} Threads::Threads)
endif()
-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} )
+add_executable(tests_clipper_nlopt
+ test.cpp
+ ../tools/svgtools.hpp
+# ../tools/libnfpglue.hpp
+# ../tools/libnfpglue.cpp
+ printer_parts.h
+ printer_parts.cpp
+)
+
+target_link_libraries(tests_clipper_nlopt libnest2d ${GTEST_LIBS_TO_LINK} )
-target_include_directories(bp2d_tests PRIVATE BEFORE ${LIBNEST2D_HEADERS}
- ${GTEST_INCLUDE_DIRS})
+target_include_directories(tests_clipper_nlopt PRIVATE BEFORE
+ ${GTEST_INCLUDE_DIRS})
-add_test(libnest2d_tests bp2d_tests)
+add_test(libnest2d_tests tests_clipper_nlopt)
diff --git a/src/libnest2d/tests/test.cpp b/src/libnest2d/tests/test.cpp
index 323fb8d31..1c4daf4af 100644
--- a/src/libnest2d/tests/test.cpp
+++ b/src/libnest2d/tests/test.cpp
@@ -4,6 +4,7 @@
#include <libnest2d.h>
#include "printer_parts.h"
#include <libnest2d/geometry_traits_nfp.hpp>
+#include "../tools/svgtools.hpp"
//#include "../tools/libnfpglue.hpp"
//#include "../tools/nfp_svgnest_glue.hpp"
@@ -125,7 +126,7 @@ TEST(GeometryAlgorithms, boundingCircle) {
c = boundingCircle(part.transformedShape());
if(std::isnan(c.radius())) std::cout << "fail: radius is nan" << std::endl;
- else for(auto v : shapelike::getContour(part.transformedShape()) ) {
+ else for(auto v : shapelike::contour(part.transformedShape()) ) {
auto d = pointlike::distance(v, c.center());
if(d > c.radius() ) {
auto e = std::abs( 1.0 - d/c.radius());
@@ -791,10 +792,55 @@ TEST(GeometryAlgorithms, nfpConvexConvex) {
TEST(GeometryAlgorithms, nfpConcaveConcave) {
using namespace libnest2d;
-// Rectangle r1(10, 10);
-// Rectangle r2(20, 20);
-// auto result = Nfp::nfpSimpleSimple(r1.transformedShape(),
-// r2.transformedShape());
+ Item stationary = {
+ {
+ {207, 76},
+ {194, 117},
+ {206, 117},
+ {206, 104},
+ {218, 104},
+ {231, 117},
+ {231, 130},
+ {244, 130},
+ {230, 92},
+ {220, 92},
+ {220, 84},
+ {239, 76},
+ {207, 76}
+ },
+ {}
+ };
+
+ Item orbiter = {
+ {
+ {78, 76},
+ {90, 89},
+ {76, 124},
+ {101, 124},
+ {101, 100},
+ {141, 113},
+ {141, 124},
+ {168, 124},
+ {158, 115},
+ {158, 104},
+ {121, 88},
+ {121, 76},
+ {78, 76}
+ },
+ {}
+ };
+
+ Rectangle r1(10, 10);
+ Rectangle r2(20, 20);
+ auto result = nfp::nfpSimpleSimple(stationary.transformedShape(),
+ orbiter.transformedShape());
+
+ svg::SVGWriter<PolygonImpl>::Config conf;
+ conf.mm_in_coord_units = 1;
+ svg::SVGWriter<PolygonImpl> wr(conf);
+ wr.writeItem(Item(result.first));
+ wr.save("simplesimple.svg");
+
}
TEST(GeometryAlgorithms, pointOnPolygonContour) {
diff --git a/src/libnest2d/tools/benchmark.h b/src/libnest2d/tools/benchmark.h
deleted file mode 100644
index 19870b37b..000000000
--- a/src/libnest2d/tools/benchmark.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) Tamás Mészáros
- * 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 2
- * 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, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#ifndef INCLUDE_BENCHMARK_H_
-#define INCLUDE_BENCHMARK_H_
-
-#include <chrono>
-#include <ratio>
-
-/**
- * A class for doing benchmarks.
- */
-class Benchmark {
- typedef std::chrono::high_resolution_clock Clock;
- typedef Clock::duration Duration;
- typedef Clock::time_point TimePoint;
-
- TimePoint t1, t2;
- Duration d;
-
- inline double to_sec(Duration d) {
- return d.count() * double(Duration::period::num) / Duration::period::den;
- }
-
-public:
-
- /**
- * Measure time from the moment of this call.
- */
- void start() { t1 = Clock::now(); }
-
- /**
- * Measure time to the moment of this call.
- */
- void stop() { t2 = Clock::now(); }
-
- /**
- * Get the time elapsed between a start() end a stop() call.
- * @return Returns the elapsed time in seconds.
- */
- double getElapsedSec() { d = t2 - t1; return to_sec(d); }
-};
-
-
-#endif /* INCLUDE_BENCHMARK_H_ */
diff --git a/src/libnest2d/tools/libnfpglue.cpp b/src/libnest2d/tools/libnfpglue.cpp
deleted file mode 100644
index 31733acf9..000000000
--- a/src/libnest2d/tools/libnfpglue.cpp
+++ /dev/null
@@ -1,157 +0,0 @@
-//#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<long double>();
-#else
- long double diffv = diff.val();
-#endif
- if(std::abs(diffv) <=
- std::numeric_limits<Coord>::epsilon())
- return x1 < x2;
-
- return diff < 0;
-}
-
-TCoord<PointImpl> getX(const libnfporb::point_t& p) {
-#ifdef LIBNFP_USE_RATIONAL
- return p.x_.convert_to<TCoord<PointImpl>>();
-#else
- return static_cast<TCoord<PointImpl>>(std::round(p.x_.val()));
-#endif
-}
-
-TCoord<PointImpl> getY(const libnfporb::point_t& p) {
-#ifdef LIBNFP_USE_RATIONAL
- return p.y_.convert_to<TCoord<PointImpl>>();
-#else
- return static_cast<TCoord<PointImpl>>(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<long double>();
- auto py = p.y_.convert_to<long double>();
-#else
- long double px = p.x_.val();
- long double py = p.y_.val();
-#endif
- return {px*factor, py*factor};
-}
-
-}
-
-NfpR _nfp(const PolygonImpl &sh, const PolygonImpl &cother)
-{
- namespace sl = shapelike;
-
- NfpR 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 = sl::getContour(ret.first);
- 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 = sl::holes(ret.first);
- for(size_t hidx = 1; hidx < nfp.size(); ++hidx) {
- if(nfp[hidx].size() >= 3) {
- rholes.emplace_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());
- }
- }
-
- ret.second = nfp::referenceVertex(ret.first);
-
- } 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(sh, cother);
- }
-
- return ret;
-}
-
-NfpR nfp::NfpImpl<PolygonImpl, nfp::NfpLevel::CONVEX_ONLY>::operator()(
- const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother)
-{
- return _nfp(sh, cother);//nfpConvexOnly(sh, cother);
-}
-
-NfpR nfp::NfpImpl<PolygonImpl, nfp::NfpLevel::ONE_CONVEX>::operator()(
- const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother)
-{
- return _nfp(sh, cother);
-}
-
-NfpR nfp::NfpImpl<PolygonImpl, nfp::NfpLevel::BOTH_CONCAVE>::operator()(
- const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother)
-{
- return _nfp(sh, cother);
-}
-
-//PolygonImpl
-//Nfp::NfpImpl<PolygonImpl, NfpLevel::ONE_CONVEX_WITH_HOLES>::operator()(
-// const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother)
-//{
-// return _nfp(sh, cother);
-//}
-
-//PolygonImpl
-//Nfp::NfpImpl<PolygonImpl, NfpLevel::BOTH_CONCAVE_WITH_HOLES>::operator()(
-// const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother)
-//{
-// return _nfp(sh, cother);
-//}
-
-}
diff --git a/src/libnest2d/tools/libnfpglue.hpp b/src/libnest2d/tools/libnfpglue.hpp
deleted file mode 100644
index 1ff033cb9..000000000
--- a/src/libnest2d/tools/libnfpglue.hpp
+++ /dev/null
@@ -1,46 +0,0 @@
-#ifndef LIBNFPGLUE_HPP
-#define LIBNFPGLUE_HPP
-
-#include <libnest2d/clipper_backend/clipper_backend.hpp>
-
-namespace libnest2d {
-
-using NfpR = nfp::NfpResult<PolygonImpl>;
-
-NfpR _nfp(const PolygonImpl& sh, const PolygonImpl& cother);
-
-template<>
-struct nfp::NfpImpl<PolygonImpl, nfp::NfpLevel::CONVEX_ONLY> {
- NfpR operator()(const PolygonImpl& sh, const PolygonImpl& cother);
-};
-
-template<>
-struct nfp::NfpImpl<PolygonImpl, nfp::NfpLevel::ONE_CONVEX> {
- NfpR operator()(const PolygonImpl& sh, const PolygonImpl& cother);
-};
-
-template<>
-struct nfp::NfpImpl<PolygonImpl, nfp::NfpLevel::BOTH_CONCAVE> {
- NfpR operator()(const PolygonImpl& sh, const PolygonImpl& cother);
-};
-
-//template<>
-//struct Nfp::NfpImpl<PolygonImpl, NfpLevel::ONE_CONVEX_WITH_HOLES> {
-// NfpResult operator()(const PolygonImpl& sh, const PolygonImpl& cother);
-//};
-
-//template<>
-//struct Nfp::NfpImpl<PolygonImpl, NfpLevel::BOTH_CONCAVE_WITH_HOLES> {
-// NfpResult operator()(const PolygonImpl& sh, const PolygonImpl& cother);
-//};
-
-template<> struct nfp::MaxNfpLevel<PolygonImpl> {
- static const BP2D_CONSTEXPR NfpLevel value =
-// NfpLevel::CONVEX_ONLY;
- NfpLevel::BOTH_CONCAVE;
-};
-
-}
-
-
-#endif // LIBNFPGLUE_HPP
diff --git a/src/libnest2d/tools/libnfporb/LICENSE b/src/libnest2d/tools/libnfporb/LICENSE
deleted file mode 100644
index 94a9ed024..000000000
--- a/src/libnest2d/tools/libnfporb/LICENSE
+++ /dev/null
@@ -1,674 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
- 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.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- 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 <http://www.gnu.org/licenses/>.
-
-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:
-
- <program> Copyright (C) <year> <name of author>
- 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
-<http://www.gnu.org/licenses/>.
-
- 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
-<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/src/libnest2d/tools/libnfporb/ORIGIN b/src/libnest2d/tools/libnfporb/ORIGIN
deleted file mode 100644
index 788bfd9af..000000000
--- a/src/libnest2d/tools/libnfporb/ORIGIN
+++ /dev/null
@@ -1,2 +0,0 @@
-https://github.com/kallaballa/libnfp.git
-commit hash a5cf9f6a76ddab95567fccf629d4d099b60237d7 \ No newline at end of file
diff --git a/src/libnest2d/tools/libnfporb/README.md b/src/libnest2d/tools/libnfporb/README.md
deleted file mode 100644
index 9698972be..000000000
--- a/src/libnest2d/tools/libnfporb/README.md
+++ /dev/null
@@ -1,89 +0,0 @@
-[![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/src/libnest2d/tools/libnfporb/libnfporb.hpp b/src/libnest2d/tools/libnfporb/libnfporb.hpp
deleted file mode 100644
index 8cb34567e..000000000
--- a/src/libnest2d/tools/libnfporb/libnfporb.hpp
+++ /dev/null
@@ -1,1547 +0,0 @@
-#ifndef NFP_HPP_
-#define NFP_HPP_
-
-#include <iostream>
-#include <list>
-#include <string>
-#include <fstream>
-#include <streambuf>
-#include <vector>
-#include <set>
-#include <exception>
-#include <random>
-#include <limits>
-
-#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 <boost/multiprecision/gmp.hpp>
-#include <boost/multiprecision/number.hpp>
-#endif
-#include <boost/geometry.hpp>
-#include <boost/geometry/util/math.hpp>
-#include <boost/geometry/geometries/point_xy.hpp>
-#include <boost/geometry/geometries/polygon.hpp>
-#include <boost/geometry/geometries/linestring.hpp>
-#include <boost/geometry/io/svg/svg_mapper.hpp>
-#include <boost/geometry/algorithms/intersects.hpp>
-#include <boost/geometry/geometries/register/point.hpp>
-
-#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<long double>(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<long double>(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<long double>(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<long double>(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<long double>(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<libnfporb::LongDouble>
- {
- static const LIBNFP_CONSTEXPR bool is_specialized = true;
-
- static const LIBNFP_CONSTEXPR long double
- min() LIBNFP_NOEXCEPT { return std::numeric_limits<long double>::min(); }
-
- static LIBNFP_CONSTEXPR long double
- max() LIBNFP_NOEXCEPT { return std::numeric_limits<long double>::max(); }
-
-#if __cplusplus >= 201103L
- static LIBNFP_CONSTEXPR long double
- lowest() LIBNFP_NOEXCEPT { return -std::numeric_limits<long double>::lowest(); }
-#endif
-
- static const LIBNFP_CONSTEXPR int digits = std::numeric_limits<long double>::digits;
- static const LIBNFP_CONSTEXPR int digits10 = std::numeric_limits<long double>::digits10;
-#if __cplusplus >= 201103L
- static const LIBNFP_CONSTEXPR int max_digits10
- = std::numeric_limits<long double>::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<long double>::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<long double>::min_exponent;
- static const LIBNFP_CONSTEXPR int min_exponent10 = std::numeric_limits<long double>::min_exponent10;
- static const LIBNFP_CONSTEXPR int max_exponent = std::numeric_limits<long double>::max_exponent;
- static const LIBNFP_CONSTEXPR int max_exponent10 = std::numeric_limits<long double>::max_exponent10;
-
-
- static const LIBNFP_CONSTEXPR bool has_infinity = std::numeric_limits<long double>::has_infinity;
- static const LIBNFP_CONSTEXPR bool has_quiet_NaN = std::numeric_limits<long double>::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<long double>::has_denorm;
- static const LIBNFP_CONSTEXPR bool has_denorm_loss
- = std::numeric_limits<long double>::has_denorm_loss;
-
-
- static const LIBNFP_CONSTEXPR long double
- infinity() LIBNFP_NOEXCEPT { return std::numeric_limits<long double>::infinity(); }
-
- static const LIBNFP_CONSTEXPR long double
- quiet_NaN() LIBNFP_NOEXCEPT { return std::numeric_limits<long double>::quiet_NaN(); }
-
- static const LIBNFP_CONSTEXPR long double
- signaling_NaN() LIBNFP_NOEXCEPT { return std::numeric_limits<long double>::signaling_NaN(); }
-
-
- static const LIBNFP_CONSTEXPR long double
- denorm_min() LIBNFP_NOEXCEPT { return std::numeric_limits<long double>::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<long double>::traps;
- static const LIBNFP_CONSTEXPR bool tinyness_before =
- std::numeric_limits<long double>::tinyness_before;
- static const LIBNFP_CONSTEXPR float_round_style round_style =
- round_to_nearest;
- };
-}
-
-namespace boost {
-namespace numeric {
- template<>
- struct raw_converter<boost::numeric::conversion_traits<double, libnfporb::LongDouble>>
- {
- typedef boost::numeric::conversion_traits<double, libnfporb::LongDouble>::result_type result_type ;
- typedef boost::numeric::conversion_traits<double, libnfporb::LongDouble>::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<bm::gmp_rational, bm::et_off> 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<coord_t>::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<long double>() / bm::denominator(c).convert_to<long double>();
-}
-#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<point_t> 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<libnfporb::LongDouble>
-{
- 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<libnfporb::rational_t>
-{
- 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<libnfporb::LongDouble>
- {
- 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<libnfporb::LongDouble, false>
-{
- template<typename Policy>
- 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<libnfporb::LongDouble>::apply(lhs.val() - rhs.val()) <= policy.apply(lhs.val(), rhs.val()) * libnfporb::NFP_EPSILON;
- }
-};
-
-template <>
-struct smaller<libnfporb::LongDouble>
-{
- static inline bool apply(libnfporb::LongDouble const& lhs, libnfporb::LongDouble const& rhs)
- {
- if(lhs.val() == rhs.val() || bg::math::detail::abs<libnfporb::LongDouble>::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<LongDouble>::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<libnfporb::LongDouble>::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<point_t, false, true> polygon_t;
-typedef std::vector<polygon_t::ring_type> nfp_t;
-typedef bg::model::linestring<point_t> linestring_t;
-
-typedef polygon_t::ring_type::size_type psize_t;
-
-typedef bg::model::d2::point_xy<long double> pointf_t;
-typedef bg::model::segment<pointf_t> segmentf_t;
-typedef bg::model::polygon<pointf_t, false, true> 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<segment_t>& segments) {
- std::ofstream svg(filename.c_str());
-
- boost::geometry::svg_mapper<pointf_t> 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<pointf_t> 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<polygon_t> const& polygons) {
- std::ofstream svg(filename.c_str());
-
- boost::geometry::svg_mapper<pointf_t> 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<polygon_t> 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<pointf_t> 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<char>(t)),
- std::istreambuf_iterator<char>());
-
- str.pop_back();
- bg::read_wkt(str, p);
- bg::correct(p);
-}
-
-std::vector<psize_t> find_minimum_y(const polygon_t& p) {
- std::vector<psize_t> 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<psize_t> find_maximum_y(const polygon_t& p) {
- std::vector<psize_t> 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<psize_t>::max();
-}
-
-std::vector<TouchingPoint> findTouchingPoints(const polygon_t::ring_type& ringA, const polygon_t::ring_type& ringB) {
- std::vector<TouchingPoint> 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<coord_t, 2, 2> 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<point_t> 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<coord_t, 2, 2> 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<point_t> 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<TranslationVector> findFeasibleTranslationVectors(polygon_t::ring_type& ringA, polygon_t::ring_type& ringB, const std::vector<TouchingPoint>& touchers) {
- //use a set to automatically filter duplicate vectors
- std::vector<TranslationVector> potentialVectors;
- std::vector<std::pair<segment_t,segment_t>> 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<signed long>(touchers[i].A_ - 1);
- auto nextAindex = static_cast<signed long>(touchers[i].A_ + 1);
-
- prevAindex = (prevAindex < 0) ? static_cast<signed long>(ringA.size() - 2) : prevAindex; // loop
- nextAindex = (static_cast<psize_t>(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<signed long>(touchers[i].B_ - 1);
- auto nextBindex = static_cast<signed long>(touchers[i].B_ + 1);
-
- prevBindex = (prevBindex < 0) ? static_cast<signed long>(ringB.size() - 2) : prevBindex; // loop
- nextBindex = (static_cast<psize_t>(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<TranslationVector> 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<coord_t, 2, 2> 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<TranslationVector>& h, const TranslationVector& tv) {
- for(const auto& htv : h) {
- if(htv.vector_ == tv.vector_)
- return true;
- }
- return false;
-}
-
-TranslationVector getLongest(const std::vector<TranslationVector>& 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<TranslationVector>& tvs, const std::vector<TranslationVector>& history) {
- if(!history.empty()) {
- TranslationVector last = history.back();
- std::vector<TranslationVector> 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<psize_t>::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<psize_t>::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<psize_t>::max()) {
- throw std::runtime_error(
- "Internal error: Can't find later point of last edge");
- }
-
- std::vector<segment_t> 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<TranslationVector> 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<coord_t, 2, 2>(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<coord_t, 2, 2> 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<coord_t, 2, 2>(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<TranslationVector> 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<TouchingPoint> 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<TranslationVector> 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<coord_t, 2, 2>(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<psize_t> ptyaminI = find_minimum_y(pA);
- std::vector<psize_t> 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<coord_t, 2, 2>(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<coord_t, 2, 2> 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<coord_t, 2, 2> 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/src/libnest2d/tools/nfp_svgnest.hpp b/src/libnest2d/tools/nfp_svgnest.hpp
deleted file mode 100644
index ac5700c10..000000000
--- a/src/libnest2d/tools/nfp_svgnest.hpp
+++ /dev/null
@@ -1,1018 +0,0 @@
-#ifndef NFP_SVGNEST_HPP
-#define NFP_SVGNEST_HPP
-
-#include <limits>
-#include <unordered_map>
-
-#include <libnest2d/geometry_traits_nfp.hpp>
-
-namespace libnest2d {
-
-namespace __svgnest {
-
-using std::sqrt;
-using std::min;
-using std::max;
-using std::abs;
-using std::isnan;
-
-//template<class Coord> struct _Scale {
-// static const BP2D_CONSTEXPR long long Value = 1000000;
-//};
-
-template<class S> struct _alg {
- using Contour = TContour<S>;
- using Point = TPoint<S>;
- using iCoord = TCoord<Point>;
- using Coord = double;
- using Shapes = nfp::Shapes<S>;
-
- static const Coord TOL;
-
-#define dNAN std::nan("")
-
- struct Vector {
- Coord x = 0.0, y = 0.0;
- bool marked = false;
- Vector() = default;
- Vector(Coord X, Coord Y): x(X), y(Y) {}
- Vector(const Point& p): x(Coord(getX(p))), y(Coord(getY(p))) {}
- operator Point() const { return {iCoord(x), iCoord(y)}; }
- Vector& operator=(const Point& p) {
- x = getX(p), y = getY(p); return *this;
- }
- bool operator!=(const Vector& v) const {
- return v.x != x || v.y != y;
- }
- Vector(std::initializer_list<Coord> il):
- x(*il.begin()), y(*std::next(il.begin())) {}
- };
-
- static inline Coord x(const Point& p) { return Coord(getX(p)); }
- static inline Coord y(const Point& p) { return Coord(getY(p)); }
-
- static inline Coord x(const Vector& p) { return p.x; }
- static inline Coord y(const Vector& p) { return p.y; }
-
- class Cntr {
- std::vector<Vector> v_;
- public:
- Cntr(const Contour& c) {
- v_.reserve(c.size());
- std::transform(c.begin(), c.end(), std::back_inserter(v_),
- [](const Point& p) {
- return Vector(double(x(p)) / 1e6, double(y(p)) / 1e6);
- });
- std::reverse(v_.begin(), v_.end());
- v_.pop_back();
- }
- Cntr() = default;
-
- Coord offsetx = 0;
- Coord offsety = 0;
- size_t size() const { return v_.size(); }
- bool empty() const { return v_.empty(); }
- typename std::vector<Vector>::const_iterator cbegin() const { return v_.cbegin(); }
- typename std::vector<Vector>::const_iterator cend() const { return v_.cend(); }
- typename std::vector<Vector>::iterator begin() { return v_.begin(); }
- typename std::vector<Vector>::iterator end() { return v_.end(); }
- Vector& operator[](size_t idx) { return v_[idx]; }
- const Vector& operator[](size_t idx) const { return v_[idx]; }
- template<class...Args>
- void emplace_back(Args&&...args) {
- v_.emplace_back(std::forward<Args>(args)...);
- }
- template<class...Args>
- void push(Args&&...args) {
- v_.emplace_back(std::forward<Args>(args)...);
- }
- void clear() { v_.clear(); }
-
- operator Contour() const {
- Contour cnt;
- cnt.reserve(v_.size() + 1);
- std::transform(v_.begin(), v_.end(), std::back_inserter(cnt),
- [](const Vector& vertex) {
- return Point(iCoord(vertex.x) * 1000000, iCoord(vertex.y) * 1000000);
- });
- if(!cnt.empty()) cnt.emplace_back(cnt.front());
- S sh = shapelike::create<S>(cnt);
-
-// std::reverse(cnt.begin(), cnt.end());
- return shapelike::getContour(sh);
- }
- };
-
- inline static bool _almostEqual(Coord a, Coord b,
- Coord tolerance = TOL)
- {
- return std::abs(a - b) < tolerance;
- }
-
- // returns true if p lies on the line segment defined by AB,
- // but not at any endpoints may need work!
- static bool _onSegment(const Vector& A, const Vector& B, const Vector& p) {
-
- // vertical line
- if(_almostEqual(A.x, B.x) && _almostEqual(p.x, A.x)) {
- if(!_almostEqual(p.y, B.y) && !_almostEqual(p.y, A.y) &&
- p.y < max(B.y, A.y) && p.y > min(B.y, A.y)){
- return true;
- }
- else{
- return false;
- }
- }
-
- // horizontal line
- if(_almostEqual(A.y, B.y) && _almostEqual(p.y, A.y)){
- if(!_almostEqual(p.x, B.x) && !_almostEqual(p.x, A.x) &&
- p.x < max(B.x, A.x) && p.x > min(B.x, A.x)){
- return true;
- }
- else{
- return false;
- }
- }
-
- //range check
- if((p.x < A.x && p.x < B.x) || (p.x > A.x && p.x > B.x) ||
- (p.y < A.y && p.y < B.y) || (p.y > A.y && p.y > B.y))
- return false;
-
- // exclude end points
- if((_almostEqual(p.x, A.x) && _almostEqual(p.y, A.y)) ||
- (_almostEqual(p.x, B.x) && _almostEqual(p.y, B.y)))
- return false;
-
-
- double cross = (p.y - A.y) * (B.x - A.x) - (p.x - A.x) * (B.y - A.y);
-
- if(abs(cross) > TOL) return false;
-
- double dot = (p.x - A.x) * (B.x - A.x) + (p.y - A.y)*(B.y - A.y);
-
- if(dot < 0 || _almostEqual(dot, 0)) return false;
-
- double len2 = (B.x - A.x)*(B.x - A.x) + (B.y - A.y)*(B.y - A.y);
-
- if(dot > len2 || _almostEqual(dot, len2)) return false;
-
- return true;
- }
-
- // return true if point is in the polygon, false if outside, and null if exactly on a point or edge
- static int pointInPolygon(const Vector& point, const Cntr& polygon) {
- if(polygon.size() < 3){
- return 0;
- }
-
- bool inside = false;
- Coord offsetx = polygon.offsetx;
- Coord offsety = polygon.offsety;
-
- for (size_t i = 0, j = polygon.size() - 1; i < polygon.size(); j=i++) {
- auto xi = polygon[i].x + offsetx;
- auto yi = polygon[i].y + offsety;
- auto xj = polygon[j].x + offsetx;
- auto yj = polygon[j].y + offsety;
-
- if(_almostEqual(xi, point.x) && _almostEqual(yi, point.y)){
- return 0; // no result
- }
-
- if(_onSegment({xi, yi}, {xj, yj}, point)){
- return 0; // exactly on the segment
- }
-
- if(_almostEqual(xi, xj) && _almostEqual(yi, yj)){ // ignore very small lines
- continue;
- }
-
- bool intersect = ((yi > point.y) != (yj > point.y)) &&
- (point.x < (xj - xi) * (point.y - yi) / (yj - yi) + xi);
- if (intersect) inside = !inside;
- }
-
- return inside? 1 : -1;
- }
-
- static bool intersect(const Cntr& A, const Cntr& B){
- Contour a = A, b = B;
- return shapelike::intersects(shapelike::create<S>(a), shapelike::create<S>(b));
- }
-
- static Vector _normalizeVector(const Vector& v) {
- if(_almostEqual(v.x*v.x + v.y*v.y, Coord(1))){
- return Point(v); // given vector was already a unit vector
- }
- auto len = sqrt(v.x*v.x + v.y*v.y);
- auto inverse = 1/len;
-
- return { Coord(v.x*inverse), Coord(v.y*inverse) };
- }
-
- static double pointDistance( const Vector& p,
- const Vector& s1,
- const Vector& s2,
- Vector normal,
- bool infinite = false)
- {
- normal = _normalizeVector(normal);
-
- Vector dir = {
- normal.y,
- -normal.x
- };
-
- auto pdot = p.x*dir.x + p.y*dir.y;
- auto s1dot = s1.x*dir.x + s1.y*dir.y;
- auto s2dot = s2.x*dir.x + s2.y*dir.y;
-
- auto pdotnorm = p.x*normal.x + p.y*normal.y;
- auto s1dotnorm = s1.x*normal.x + s1.y*normal.y;
- auto s2dotnorm = s2.x*normal.x + s2.y*normal.y;
-
- if(!infinite){
- if (((pdot<s1dot || _almostEqual(pdot, s1dot)) &&
- (pdot<s2dot || _almostEqual(pdot, s2dot))) ||
- ((pdot>s1dot || _almostEqual(pdot, s1dot)) &&
- (pdot>s2dot || _almostEqual(pdot, s2dot))))
- {
- // dot doesn't collide with segment,
- // or lies directly on the vertex
- return dNAN;
- }
- if ((_almostEqual(pdot, s1dot) && _almostEqual(pdot, s2dot)) &&
- (pdotnorm>s1dotnorm && pdotnorm>s2dotnorm))
- {
- return min(pdotnorm - s1dotnorm, pdotnorm - s2dotnorm);
- }
- if ((_almostEqual(pdot, s1dot) && _almostEqual(pdot, s2dot)) &&
- (pdotnorm<s1dotnorm && pdotnorm<s2dotnorm)){
- return -min(s1dotnorm-pdotnorm, s2dotnorm-pdotnorm);
- }
- }
-
- return -(pdotnorm - s1dotnorm + (s1dotnorm - s2dotnorm)*(s1dot - pdot)
- / double(s1dot - s2dot));
- }
-
- static double segmentDistance( const Vector& A,
- const Vector& B,
- const Vector& E,
- const Vector& F,
- Vector direction)
- {
- Vector normal = {
- direction.y,
- -direction.x
- };
-
- Vector reverse = {
- -direction.x,
- -direction.y
- };
-
- auto dotA = A.x*normal.x + A.y*normal.y;
- auto dotB = B.x*normal.x + B.y*normal.y;
- auto dotE = E.x*normal.x + E.y*normal.y;
- auto dotF = F.x*normal.x + F.y*normal.y;
-
- auto crossA = A.x*direction.x + A.y*direction.y;
- auto crossB = B.x*direction.x + B.y*direction.y;
- auto crossE = E.x*direction.x + E.y*direction.y;
- auto crossF = F.x*direction.x + F.y*direction.y;
-
-// auto crossABmin = min(crossA, crossB);
-// auto crossABmax = max(crossA, crossB);
-
-// auto crossEFmax = max(crossE, crossF);
-// auto crossEFmin = min(crossE, crossF);
-
- auto ABmin = min(dotA, dotB);
- auto ABmax = max(dotA, dotB);
-
- auto EFmax = max(dotE, dotF);
- auto EFmin = min(dotE, dotF);
-
- // segments that will merely touch at one point
- if(_almostEqual(ABmax, EFmin, TOL) || _almostEqual(ABmin, EFmax,TOL)) {
- return dNAN;
- }
- // segments miss eachother completely
- if(ABmax < EFmin || ABmin > EFmax){
- return dNAN;
- }
-
- double overlap = 0;
-
- if((ABmax > EFmax && ABmin < EFmin) || (EFmax > ABmax && EFmin < ABmin))
- {
- overlap = 1;
- }
- else{
- auto minMax = min(ABmax, EFmax);
- auto maxMin = max(ABmin, EFmin);
-
- auto maxMax = max(ABmax, EFmax);
- auto minMin = min(ABmin, EFmin);
-
- overlap = (minMax-maxMin)/(maxMax-minMin);
- }
-
- auto crossABE = (E.y - A.y) * (B.x - A.x) - (E.x - A.x) * (B.y - A.y);
- auto crossABF = (F.y - A.y) * (B.x - A.x) - (F.x - A.x) * (B.y - A.y);
-
- // lines are colinear
- if(_almostEqual(crossABE,0) && _almostEqual(crossABF,0)){
-
- Vector ABnorm = {B.y-A.y, A.x-B.x};
- Vector EFnorm = {F.y-E.y, E.x-F.x};
-
- auto ABnormlength = sqrt(ABnorm.x*ABnorm.x + ABnorm.y*ABnorm.y);
- ABnorm.x /= ABnormlength;
- ABnorm.y /= ABnormlength;
-
- auto EFnormlength = sqrt(EFnorm.x*EFnorm.x + EFnorm.y*EFnorm.y);
- EFnorm.x /= EFnormlength;
- EFnorm.y /= EFnormlength;
-
- // segment normals must point in opposite directions
- if(abs(ABnorm.y * EFnorm.x - ABnorm.x * EFnorm.y) < TOL &&
- ABnorm.y * EFnorm.y + ABnorm.x * EFnorm.x < 0){
- // normal of AB segment must point in same direction as
- // given direction vector
- auto normdot = ABnorm.y * direction.y + ABnorm.x * direction.x;
- // the segments merely slide along eachother
- if(_almostEqual(normdot,0, TOL)){
- return dNAN;
- }
- if(normdot < 0){
- return 0.0;
- }
- }
- return dNAN;
- }
-
- std::vector<double> distances; distances.reserve(10);
-
- // coincident points
- if(_almostEqual(dotA, dotE)){
- distances.emplace_back(crossA-crossE);
- }
- else if(_almostEqual(dotA, dotF)){
- distances.emplace_back(crossA-crossF);
- }
- else if(dotA > EFmin && dotA < EFmax){
- auto d = pointDistance(A,E,F,reverse);
- if(!isnan(d) && _almostEqual(d, 0))
- { // A currently touches EF, but AB is moving away from EF
- auto dB = pointDistance(B,E,F,reverse,true);
- if(dB < 0 || _almostEqual(dB*overlap,0)){
- d = dNAN;
- }
- }
- if(!isnan(d)){
- distances.emplace_back(d);
- }
- }
-
- if(_almostEqual(dotB, dotE)){
- distances.emplace_back(crossB-crossE);
- }
- else if(_almostEqual(dotB, dotF)){
- distances.emplace_back(crossB-crossF);
- }
- else if(dotB > EFmin && dotB < EFmax){
- auto d = pointDistance(B,E,F,reverse);
-
- if(!isnan(d) && _almostEqual(d, 0))
- { // crossA>crossB A currently touches EF, but AB is moving away from EF
- double dA = pointDistance(A,E,F,reverse,true);
- if(dA < 0 || _almostEqual(dA*overlap,0)){
- d = dNAN;
- }
- }
- if(!isnan(d)){
- distances.emplace_back(d);
- }
- }
-
- if(dotE > ABmin && dotE < ABmax){
- auto d = pointDistance(E,A,B,direction);
- if(!isnan(d) && _almostEqual(d, 0))
- { // crossF<crossE A currently touches EF, but AB is moving away from EF
- double dF = pointDistance(F,A,B,direction, true);
- if(dF < 0 || _almostEqual(dF*overlap,0)){
- d = dNAN;
- }
- }
- if(!isnan(d)){
- distances.emplace_back(d);
- }
- }
-
- if(dotF > ABmin && dotF < ABmax){
- auto d = pointDistance(F,A,B,direction);
- if(!isnan(d) && _almostEqual(d, 0))
- { // && crossE<crossF A currently touches EF,
- // but AB is moving away from EF
- double dE = pointDistance(E,A,B,direction, true);
- if(dE < 0 || _almostEqual(dE*overlap,0)){
- d = dNAN;
- }
- }
- if(!isnan(d)){
- distances.emplace_back(d);
- }
- }
-
- if(distances.empty()){
- return dNAN;
- }
-
- return *std::min_element(distances.begin(), distances.end());
- }
-
- static double polygonSlideDistance( const Cntr& AA,
- const Cntr& BB,
- Vector direction,
- bool ignoreNegative)
- {
-// Vector A1, A2, B1, B2;
- Cntr A = AA;
- Cntr B = BB;
-
- Coord Aoffsetx = A.offsetx;
- Coord Boffsetx = B.offsetx;
- Coord Aoffsety = A.offsety;
- Coord Boffsety = B.offsety;
-
- // close the loop for polygons
- if(A[0] != A[A.size()-1]){
- A.emplace_back(AA[0]);
- }
-
- if(B[0] != B[B.size()-1]){
- B.emplace_back(BB[0]);
- }
-
- auto& edgeA = A;
- auto& edgeB = B;
-
- double distance = dNAN, d = dNAN;
-
- Vector dir = _normalizeVector(direction);
-
-// Vector normal = {
-// dir.y,
-// -dir.x
-// };
-
-// Vector reverse = {
-// -dir.x,
-// -dir.y,
-// };
-
- for(size_t i = 0; i < edgeB.size() - 1; i++){
- for(size_t j = 0; j < edgeA.size() - 1; j++){
- Vector A1 = {x(edgeA[j]) + Aoffsetx, y(edgeA[j]) + Aoffsety };
- Vector A2 = {x(edgeA[j+1]) + Aoffsetx, y(edgeA[j+1]) + Aoffsety};
- Vector B1 = {x(edgeB[i]) + Boffsetx, y(edgeB[i]) + Boffsety };
- Vector B2 = {x(edgeB[i+1]) + Boffsetx, y(edgeB[i+1]) + Boffsety};
-
- if((_almostEqual(A1.x, A2.x) && _almostEqual(A1.y, A2.y)) ||
- (_almostEqual(B1.x, B2.x) && _almostEqual(B1.y, B2.y))){
- continue; // ignore extremely small lines
- }
-
- d = segmentDistance(A1, A2, B1, B2, dir);
-
- if(!isnan(d) && (isnan(distance) || d < distance)){
- if(!ignoreNegative || d > 0 || _almostEqual(d, 0)){
- distance = d;
- }
- }
- }
- }
- return distance;
- }
-
- static double polygonProjectionDistance(const Cntr& AA,
- const Cntr& BB,
- Vector direction)
- {
- Cntr A = AA;
- Cntr B = BB;
-
- auto Boffsetx = B.offsetx;
- auto Boffsety = B.offsety;
- auto Aoffsetx = A.offsetx;
- auto Aoffsety = A.offsety;
-
- // close the loop for polygons
- if(A[0] != A[A.size()-1]){
- A.push(A[0]);
- }
-
- if(B[0] != B[B.size()-1]){
- B.push(B[0]);
- }
-
- auto& edgeA = A;
- auto& edgeB = B;
-
- double distance = dNAN, d;
-// Vector p, s1, s2;
-
- for(size_t i = 0; i < edgeB.size(); i++) {
- // the shortest/most negative projection of B onto A
- double minprojection = dNAN;
- Vector minp;
- for(size_t j = 0; j < edgeA.size() - 1; j++){
- Vector p = {x(edgeB[i]) + Boffsetx, y(edgeB[i]) + Boffsety };
- Vector s1 = {x(edgeA[j]) + Aoffsetx, y(edgeA[j]) + Aoffsety };
- Vector s2 = {x(edgeA[j+1]) + Aoffsetx, y(edgeA[j+1]) + Aoffsety };
-
- if(abs((s2.y-s1.y) * direction.x -
- (s2.x-s1.x) * direction.y) < TOL) continue;
-
- // project point, ignore edge boundaries
- d = pointDistance(p, s1, s2, direction);
-
- if(!isnan(d) && (isnan(minprojection) || d < minprojection)) {
- minprojection = d;
- minp = p;
- }
- }
-
- if(!isnan(minprojection) && (isnan(distance) ||
- minprojection > distance)){
- distance = minprojection;
- }
- }
-
- return distance;
- }
-
- static std::pair<bool, Vector> searchStartPoint(
- const Cntr& AA, const Cntr& BB, bool inside, const std::vector<Cntr>& NFP = {})
- {
- // clone arrays
- auto A = AA;
- auto B = BB;
-
-// // close the loop for polygons
-// if(A[0] != A[A.size()-1]){
-// A.push(A[0]);
-// }
-
-// if(B[0] != B[B.size()-1]){
-// B.push(B[0]);
-// }
-
- // returns true if point already exists in the given nfp
- auto inNfp = [](const Vector& p, const std::vector<Cntr>& nfp){
- if(nfp.empty()){
- return false;
- }
-
- for(size_t i=0; i < nfp.size(); i++){
- for(size_t j = 0; j< nfp[i].size(); j++){
- if(_almostEqual(p.x, nfp[i][j].x) &&
- _almostEqual(p.y, nfp[i][j].y)){
- return true;
- }
- }
- }
-
- return false;
- };
-
- for(size_t i = 0; i < A.size() - 1; i++){
- if(!A[i].marked) {
- A[i].marked = true;
- for(size_t j = 0; j < B.size(); j++){
- B.offsetx = A[i].x - B[j].x;
- B.offsety = A[i].y - B[j].y;
-
- int Binside = 0;
- for(size_t k = 0; k < B.size(); k++){
- int inpoly = pointInPolygon({B[k].x + B.offsetx, B[k].y + B.offsety}, A);
- if(inpoly != 0){
- Binside = inpoly;
- break;
- }
- }
-
- if(Binside == 0){ // A and B are the same
- return {false, {}};
- }
-
- auto startPoint = std::make_pair(true, Vector(B.offsetx, B.offsety));
- if(((Binside && inside) || (!Binside && !inside)) &&
- !intersect(A,B) && !inNfp(startPoint.second, NFP)){
- return startPoint;
- }
-
- // slide B along vector
- auto vx = A[i+1].x - A[i].x;
- auto vy = A[i+1].y - A[i].y;
-
- double d1 = polygonProjectionDistance(A,B,{vx, vy});
- double d2 = polygonProjectionDistance(B,A,{-vx, -vy});
-
- double d = dNAN;
-
- // todo: clean this up
- if(isnan(d1) && isnan(d2)){
- // nothin
- }
- else if(isnan(d1)){
- d = d2;
- }
- else if(isnan(d2)){
- d = d1;
- }
- else{
- d = min(d1,d2);
- }
-
- // only slide until no longer negative
- // todo: clean this up
- if(!isnan(d) && !_almostEqual(d,0) && d > 0){
-
- }
- else{
- continue;
- }
-
- auto vd2 = vx*vx + vy*vy;
-
- if(d*d < vd2 && !_almostEqual(d*d, vd2)){
- auto vd = sqrt(vx*vx + vy*vy);
- vx *= d/vd;
- vy *= d/vd;
- }
-
- B.offsetx += vx;
- B.offsety += vy;
-
- for(size_t k = 0; k < B.size(); k++){
- int inpoly = pointInPolygon({B[k].x + B.offsetx, B[k].y + B.offsety}, A);
- if(inpoly != 0){
- Binside = inpoly;
- break;
- }
- }
- startPoint = std::make_pair(true, Vector{B.offsetx, B.offsety});
- if(((Binside && inside) || (!Binside && !inside)) &&
- !intersect(A,B) && !inNfp(startPoint.second, NFP)){
- return startPoint;
- }
- }
- }
- }
-
- return {false, Vector(0, 0)};
- }
-
- static std::vector<Cntr> noFitPolygon(Cntr A,
- Cntr B,
- bool inside,
- bool searchEdges)
- {
- if(A.size() < 3 || B.size() < 3) {
- throw GeometryException(GeomErr::NFP);
- return {};
- }
-
- A.offsetx = 0;
- A.offsety = 0;
-
- long i = 0, j = 0;
-
- auto minA = y(A[0]);
- long minAindex = 0;
-
- auto maxB = y(B[0]);
- long maxBindex = 0;
-
- for(i = 1; i < A.size(); i++){
- A[i].marked = false;
- if(y(A[i]) < minA){
- minA = y(A[i]);
- minAindex = i;
- }
- }
-
- for(i = 1; i < B.size(); i++){
- B[i].marked = false;
- if(y(B[i]) > maxB){
- maxB = y(B[i]);
- maxBindex = i;
- }
- }
-
- std::pair<bool, Vector> startpoint;
-
- if(!inside){
- // shift B such that the bottom-most point of B is at the top-most
- // point of A. This guarantees an initial placement with no
- // intersections
- startpoint = { true,
- { x(A[minAindex]) - x(B[maxBindex]),
- y(A[minAindex]) - y(B[maxBindex]) }
- };
- }
- else {
- // no reliable heuristic for inside
- startpoint = searchStartPoint(A, B, true);
- }
-
- std::vector<Cntr> NFPlist;
-
- struct Touch {
- int type;
- long A;
- long B;
- Touch(int t, long a, long b): type(t), A(a), B(b) {}
- };
-
- while(startpoint.first) {
-
- B.offsetx = startpoint.second.x;
- B.offsety = startpoint.second.y;
-
- // maintain a list of touching points/edges
- std::vector<Touch> touching;
-
- struct V {
- Coord x, y;
- Vector *start, *end;
- operator bool() {
- return start != nullptr && end != nullptr;
- }
- operator Vector() const { return {x, y}; }
- } prevvector = {0, 0, nullptr, nullptr};
-
- Cntr NFP;
- NFP.emplace_back(x(B[0]) + B.offsetx, y(B[0]) + B.offsety);
-
- auto referencex = x(B[0]) + B.offsetx;
- auto referencey = y(B[0]) + B.offsety;
- auto startx = referencex;
- auto starty = referencey;
- unsigned counter = 0;
-
- // sanity check, prevent infinite loop
- while(counter < 10*(A.size() + B.size())){
- touching.clear();
-
- // find touching vertices/edges
- for(i = 0; i < A.size(); i++){
- long nexti = (i == A.size() - 1) ? 0 : i + 1;
- for(j = 0; j < B.size(); j++){
-
- long nextj = (j == B.size() - 1) ? 0 : j + 1;
-
- if( _almostEqual(A[i].x, B[j].x+B.offsetx) &&
- _almostEqual(A[i].y, B[j].y+B.offsety))
- {
- touching.emplace_back(0, i, j);
- }
- else if( _onSegment(
- A[i], A[nexti],
- { B[j].x+B.offsetx, B[j].y + B.offsety}) )
- {
- touching.emplace_back(1, nexti, j);
- }
- else if( _onSegment(
- {B[j].x+B.offsetx, B[j].y + B.offsety},
- {B[nextj].x+B.offsetx, B[nextj].y + B.offsety},
- A[i]) )
- {
- touching.emplace_back(2, i, nextj);
- }
- }
- }
-
- // generate translation vectors from touching vertices/edges
- std::vector<V> vectors;
- for(i=0; i < touching.size(); i++){
- auto& vertexA = A[touching[i].A];
- vertexA.marked = true;
-
- // adjacent A vertices
- auto prevAindex = touching[i].A - 1;
- auto nextAindex = touching[i].A + 1;
-
- prevAindex = (prevAindex < 0) ? A.size() - 1 : prevAindex; // loop
- nextAindex = (nextAindex >= A.size()) ? 0 : nextAindex; // loop
-
- auto& prevA = A[prevAindex];
- auto& nextA = A[nextAindex];
-
- // adjacent B vertices
- auto& vertexB = B[touching[i].B];
-
- auto prevBindex = touching[i].B-1;
- auto nextBindex = touching[i].B+1;
-
- prevBindex = (prevBindex < 0) ? B.size() - 1 : prevBindex; // loop
- nextBindex = (nextBindex >= B.size()) ? 0 : nextBindex; // loop
-
- auto& prevB = B[prevBindex];
- auto& nextB = B[nextBindex];
-
- if(touching[i].type == 0){
-
- V vA1 = {
- prevA.x - vertexA.x,
- prevA.y - vertexA.y,
- &vertexA,
- &prevA
- };
-
- V vA2 = {
- nextA.x - vertexA.x,
- nextA.y - vertexA.y,
- &vertexA,
- &nextA
- };
-
- // B vectors need to be inverted
- V vB1 = {
- vertexB.x - prevB.x,
- vertexB.y - prevB.y,
- &prevB,
- &vertexB
- };
-
- V vB2 = {
- vertexB.x - nextB.x,
- vertexB.y - nextB.y,
- &nextB,
- &vertexB
- };
-
- vectors.emplace_back(vA1);
- vectors.emplace_back(vA2);
- vectors.emplace_back(vB1);
- vectors.emplace_back(vB2);
- }
- else if(touching[i].type == 1){
- vectors.emplace_back(V{
- vertexA.x-(vertexB.x+B.offsetx),
- vertexA.y-(vertexB.y+B.offsety),
- &prevA,
- &vertexA
- });
-
- vectors.emplace_back(V{
- prevA.x-(vertexB.x+B.offsetx),
- prevA.y-(vertexB.y+B.offsety),
- &vertexA,
- &prevA
- });
- }
- else if(touching[i].type == 2){
- vectors.emplace_back(V{
- vertexA.x-(vertexB.x+B.offsetx),
- vertexA.y-(vertexB.y+B.offsety),
- &prevB,
- &vertexB
- });
-
- vectors.emplace_back(V{
- vertexA.x-(prevB.x+B.offsetx),
- vertexA.y-(prevB.y+B.offsety),
- &vertexB,
- &prevB
- });
- }
- }
-
- // TODO: there should be a faster way to reject vectors that
- // will cause immediate intersection. For now just check them all
-
- V translate = {0, 0, nullptr, nullptr};
- double maxd = 0;
-
- for(i = 0; i < vectors.size(); i++) {
- if(vectors[i].x == 0 && vectors[i].y == 0){
- continue;
- }
-
- // if this vector points us back to where we came from, ignore it.
- // ie cross product = 0, dot product < 0
- if(prevvector && vectors[i].y * prevvector.y + vectors[i].x * prevvector.x < 0){
-
- // compare magnitude with unit vectors
- double vectorlength = sqrt(vectors[i].x*vectors[i].x+vectors[i].y*vectors[i].y);
- Vector unitv = {Coord(vectors[i].x/vectorlength),
- Coord(vectors[i].y/vectorlength)};
-
- double prevlength = sqrt(prevvector.x*prevvector.x+prevvector.y*prevvector.y);
- Vector prevunit = { prevvector.x/prevlength, prevvector.y/prevlength};
-
- // we need to scale down to unit vectors to normalize vector length. Could also just do a tan here
- if(abs(unitv.y * prevunit.x - unitv.x * prevunit.y) < 0.0001){
- continue;
- }
- }
-
- V vi = vectors[i];
- double d = polygonSlideDistance(A, B, vi, true);
- double vecd2 = vectors[i].x*vectors[i].x + vectors[i].y*vectors[i].y;
-
- if(isnan(d) || d*d > vecd2){
- double vecd = sqrt(vectors[i].x*vectors[i].x + vectors[i].y*vectors[i].y);
- d = vecd;
- }
-
- if(!isnan(d) && d > maxd){
- maxd = d;
- translate = vectors[i];
- }
- }
-
- if(!translate || _almostEqual(maxd, 0))
- {
- // didn't close the loop, something went wrong here
- NFP.clear();
- break;
- }
-
- translate.start->marked = true;
- translate.end->marked = true;
-
- prevvector = translate;
-
- // trim
- double vlength2 = translate.x*translate.x + translate.y*translate.y;
- if(maxd*maxd < vlength2 && !_almostEqual(maxd*maxd, vlength2)){
- double scale = sqrt((maxd*maxd)/vlength2);
- translate.x *= scale;
- translate.y *= scale;
- }
-
- referencex += translate.x;
- referencey += translate.y;
-
- if(_almostEqual(referencex, startx) &&
- _almostEqual(referencey, starty)) {
- // we've made a full loop
- break;
- }
-
- // if A and B start on a touching horizontal line,
- // the end point may not be the start point
- bool looped = false;
- if(NFP.size() > 0) {
- for(i = 0; i < NFP.size() - 1; i++) {
- if(_almostEqual(referencex, NFP[i].x) &&
- _almostEqual(referencey, NFP[i].y)){
- looped = true;
- }
- }
- }
-
- if(looped){
- // we've made a full loop
- break;
- }
-
- NFP.emplace_back(referencex, referencey);
-
- B.offsetx += translate.x;
- B.offsety += translate.y;
-
- counter++;
- }
-
- if(NFP.size() > 0){
- NFPlist.emplace_back(NFP);
- }
-
- if(!searchEdges){
- // only get outer NFP or first inner NFP
- break;
- }
-
- startpoint =
- searchStartPoint(A, B, inside, NFPlist);
-
- }
-
- return NFPlist;
- }
-};
-
-template<class S> const double _alg<S>::TOL = std::pow(10, -9);
-
-}
-}
-
-#endif // NFP_SVGNEST_HPP
diff --git a/src/libnest2d/tools/nfp_svgnest_glue.hpp b/src/libnest2d/tools/nfp_svgnest_glue.hpp
deleted file mode 100644
index ea1fb4d07..000000000
--- a/src/libnest2d/tools/nfp_svgnest_glue.hpp
+++ /dev/null
@@ -1,75 +0,0 @@
-#ifndef NFP_SVGNEST_GLUE_HPP
-#define NFP_SVGNEST_GLUE_HPP
-
-#include "nfp_svgnest.hpp"
-
-#include <libnest2d/clipper_backend/clipper_backend.hpp>
-
-namespace libnest2d {
-
-namespace __svgnest {
-
-//template<> struct _Tol<double> {
-// static const BP2D_CONSTEXPR TCoord<PointImpl> Value = 1000000;
-//};
-
-}
-
-namespace nfp {
-
-using NfpR = NfpResult<PolygonImpl>;
-
-template<> struct NfpImpl<PolygonImpl, NfpLevel::CONVEX_ONLY> {
- NfpR operator()(const PolygonImpl& sh, const PolygonImpl& cother) {
-// return nfpConvexOnly(sh, cother);
- namespace sl = shapelike;
- using alg = __svgnest::_alg<PolygonImpl>;
-
- auto nfp_p = alg::noFitPolygon(sl::getContour(sh),
- sl::getContour(cother), false, false);
-
- PolygonImpl nfp_cntr;
- if(!nfp_p.empty()) nfp_cntr.Contour = nfp_p.front();
- return {nfp_cntr, referenceVertex(nfp_cntr)};
- }
-};
-
-template<> struct NfpImpl<PolygonImpl, NfpLevel::ONE_CONVEX> {
- NfpR operator()(const PolygonImpl& sh, const PolygonImpl& cother) {
-// return nfpConvexOnly(sh, cother);
- namespace sl = shapelike;
- using alg = __svgnest::_alg<PolygonImpl>;
-
- std::cout << "Itt vagyok" << std::endl;
- auto nfp_p = alg::noFitPolygon(sl::getContour(sh),
- sl::getContour(cother), false, false);
-
- PolygonImpl nfp_cntr;
- nfp_cntr.Contour = nfp_p.front();
- return {nfp_cntr, referenceVertex(nfp_cntr)};
- }
-};
-
-template<>
-struct NfpImpl<PolygonImpl, NfpLevel::BOTH_CONCAVE> {
- NfpR operator()(const PolygonImpl& sh, const PolygonImpl& cother) {
- namespace sl = shapelike;
- using alg = __svgnest::_alg<PolygonImpl>;
-
- auto nfp_p = alg::noFitPolygon(sl::getContour(sh),
- sl::getContour(cother), true, false);
-
- PolygonImpl nfp_cntr;
- nfp_cntr.Contour = nfp_p.front();
- return {nfp_cntr, referenceVertex(nfp_cntr)};
- }
-};
-
-template<> struct MaxNfpLevel<PolygonImpl> {
-// static const BP2D_CONSTEXPR NfpLevel value = NfpLevel::BOTH_CONCAVE;
- static const BP2D_CONSTEXPR NfpLevel value = NfpLevel::CONVEX_ONLY;
-};
-
-}}
-
-#endif // NFP_SVGNEST_GLUE_HPP
diff --git a/src/libnest2d/tools/svgtools.hpp b/src/libnest2d/tools/svgtools.hpp
index 776dd5a1a..e1ed1ad05 100644
--- a/src/libnest2d/tools/svgtools.hpp
+++ b/src/libnest2d/tools/svgtools.hpp
@@ -56,7 +56,7 @@ public:
auto d = static_cast<Coord>(
std::round(conf_.height*conf_.mm_in_coord_units) );
- auto& contour = shapelike::getContour(tsh);
+ auto& contour = shapelike::contour(tsh);
for(auto& v : contour) setY(v, -getY(v) + d);
auto& holes = shapelike::holes(tsh);