Fixing nesting crash in debug mode.

Also commented out unnecessary bloat from AppController
This commit is contained in:
tamasmeszaros 2018-10-23 17:18:38 +02:00
parent bded28f888
commit 34e652b985
47 changed files with 1928 additions and 5547 deletions

View file

@ -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(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()
add_library(libnest2d INTERFACE)
set(SRC_DIR ${PROJECT_SOURCE_DIR}/include)
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
${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
)
set(LIBNEST2D_LIBRARIES "")
set(LIBNEST2D_HEADERS ${CMAKE_CURRENT_SOURCE_DIR})
if(LIBNEST2D_GEOMETRIES_BACKEND STREQUAL "clipper")
# Clipper backend is not enough on its own, it still needs some functions
# from Boost geometry
if(NOT Boost_INCLUDE_DIRS_FOUND)
find_package(Boost 1.58 REQUIRED)
# TODO automatic download of boost geometry headers
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)
target_link_libraries(libnest2d INTERFACE ${TBB_LIBRARIES})
else()
find_package(OpenMP QUIET)
include_directories(BEFORE ${CLIPPER_INCLUDE_DIRS})
include_directories(${Boost_INCLUDE_DIRS})
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)
add_subdirectory(${SRC_DIR}/libnest2d/backends/${LIBNEST2D_GEOMETRIES})
add_subdirectory(${SRC_DIR}/libnest2d/optimizers/${LIBNEST2D_OPTIMIZER})
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()
target_sources(libnest2d INTERFACE ${LIBNEST2D_SRCFILES})
target_include_directories(libnest2d INTERFACE ${SRC_DIR})
if(LIBNEST2D_UNITTESTS)
enable_testing()
add_subdirectory(tests)
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)
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
)
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})
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()

View file

@ -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)

View file

@ -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}
)

View file

@ -47,4 +47,12 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(Clipper
MARK_AS_ADVANCED(
CLIPPER_INCLUDE_DIRS
CLIPPER_LIBRARIES)
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()

View file

@ -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()
endif()

View file

@ -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 havent found, or
# dont 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()

View file

@ -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;
}

View file

@ -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

View file

@ -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)

View file

@ -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

View file

@ -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

View file

@ -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());
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::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;
sl::contour(orbiter) = orbcont;
// Step 1: Make the orbiter reverse oriented
for(auto &v : sl::getContour(orbiter)) v = -v;
// 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;
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 != 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;
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);
auto eit = L.begin();
auto enext = std::next(eit);
eit->turn_angle = getTurnAngle(L.front().e, L.back().e);
eit->turn_angle = getTurnAngle(L.front().e, L.back().e);
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;
}
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;
++eit; ++enext;
}
L.back().is_turning_point = signbit(L.back().turn_angle) !=
signbit(L.front().turn_angle);
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;
}
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();
const auto& Rcont = R.begin()->container.get();
const auto& Qcont = Q.begin()->container.get();
// Set the intial direction
Coord dir = positive? 1 : -1;
// Set the initial direction
Coord dir = 1;
// roughly i = 1 (so q = Q.first) and s1 = q1 so S[0] = q;
auto q = Q.first;
S.push_back(*q++);
// 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
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);
// 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);
}
}
} 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);
}
if(it->eq(*q)) {
S.push_back(*q);
if(it->isTurningPoint()) dir = -dir;
if(q != Q.first) it += dir;
}
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());
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);
EdgeRefList Bslope = Bref; // copy Bref, we will make a slope diagram
// TODO step 6 (should be 5 shouldn't it?): linking edges from A
// I don't get this step
// make the slope diagram of B
std::sort(Bslope.begin(), Bslope.end(), sortfn);
seqlist.insert(seqlist.end(), seq.begin(), seq.end());
orientation = !orientation;
} else ++it;
auto slopeit = Bslope.begin(); // search for the first turning point
while(!slopeit->isTurningPoint() && slopeit != Bslope.end()) slopeit++;
if(seqlist.empty()) seqlist = mink(Q, {Bref.begin(), Bref.end()}, true);
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);
auto b_it = std::next(firstturn);
while(b_it != firstturn) {
if(b_it == Bref.end()) b_it = Bref.begin();
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);
// // TODO step 6 (should be 5 shouldn't it?): linking edges from A
// // I don't get this step
// 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;
}
return Result(stationary, Vertex());
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(rsh, top_nfp);
}
// Specializable NFP implementation class. Specialize it if you have a faster

View file

@ -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; }

View file

@ -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;
};

View file

@ -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)

View file

@ -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);

View file

@ -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);

View file

@ -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})

View file

@ -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;
}
};

View file

@ -15,11 +15,13 @@
#ifndef NDEBUG
#include <iostream>
#endif
#include "placer_boilerplate.hpp"
#include "../geometry_traits_nfp.hpp"
#include "libnest2d/optimizer.hpp"
#include <libnest2d/geometry_traits_nfp.hpp>
#include <libnest2d/optimizer.hpp>
#include "tools/svgtools.hpp"
#include "placer_boilerplate.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()) {

View file

@ -1,7 +1,7 @@
#ifndef PLACER_BOILERPLATE_HPP
#define PLACER_BOILERPLATE_HPP
#include "../libnest2d.hpp"
#include <libnest2d/libnest2d.hpp>
namespace libnest2d { namespace placers {

View file

@ -1,7 +1,6 @@
#ifndef FIRSTFIT_HPP
#define FIRSTFIT_HPP
#include "../libnest2d.hpp"
#include "selection_boilerplate.hpp"
namespace libnest2d { namespace selections {

View file

@ -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 {

View file

@ -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);
}
};
@ -388,6 +388,14 @@ inline bp2d::Box boundingBox(const PolygonImpl& sh, const PolygonTag&)
return b;
}
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&)

View file

@ -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;

View file

@ -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

View file

@ -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

View file

@ -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_include_directories(bp2d_tests PRIVATE BEFORE ${LIBNEST2D_HEADERS}
${GTEST_INCLUDE_DIRS})
target_link_libraries(tests_clipper_nlopt libnest2d ${GTEST_LIBS_TO_LINK} )
add_test(libnest2d_tests bp2d_tests)
target_include_directories(tests_clipper_nlopt PRIVATE BEFORE
${GTEST_INCLUDE_DIRS})
add_test(libnest2d_tests tests_clipper_nlopt)

View file

@ -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) {

View file

@ -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_ */

View file

@ -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);
//}
}

View file

@ -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

View file

@ -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>.

View file

@ -1,2 +0,0 @@
https://github.com/kallaballa/libnfp.git
commit hash a5cf9f6a76ddab95567fccf629d4d099b60237d7

View file

@ -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

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -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

View file

@ -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);

View file

@ -154,7 +154,7 @@ add_library(libslic3r STATIC
target_compile_definitions(libslic3r PUBLIC -DUSE_TBB ${PNG_DEFINITIONS})
target_include_directories(libslic3r PUBLIC ${CMAKE_CURRENT_BINARY_DIR} ${LIBNEST2D_INCLUDES} ${PNG_INCLUDE_DIRS})
target_link_libraries(libslic3r
${LIBNEST2D_LIBRARIES}
libnest2d
admesh
miniz
${Boost_LIBRARIES}

View file

@ -1,5 +1,7 @@
#include "AppController.hpp"
#include <slic3r/GUI/GUI.hpp>
#include <future>
#include <chrono>
#include <sstream>
@ -7,17 +9,12 @@
#include <thread>
#include <unordered_map>
#include <slic3r/GUI/GUI.hpp>
#include <ModelArrange.hpp>
#include <slic3r/GUI/PresetBundle.hpp>
#include <PrintConfig.hpp>
#include <Print.hpp>
#include <PrintExport.hpp>
#include <Geometry.hpp>
#include <Model.hpp>
#include <Utils.hpp>
#include "GUI/GUI_App.hpp"
#include <ModelArrange.hpp>
namespace Slic3r {
@ -140,119 +137,119 @@ public:
void PrintController::slice_to_png()
{
using Pointf3 = Vec3d;
// using Pointf3 = Vec3d;
auto ctl = GUI::get_appctl();
auto presetbundle = GUI::wxGetApp().preset_bundle;
// auto ctl = GUI::get_appctl();
// auto presetbundle = GUI::wxGetApp().preset_bundle;
assert(presetbundle);
// assert(presetbundle);
// FIXME: this crashes in command line mode
auto pt = presetbundle->printers.get_selected_preset().printer_technology();
if(pt != ptSLA) {
ctl->report_issue(IssueType::ERR, L("Printer technology is not SLA!"),
L("Error"));
return;
}
// // FIXME: this crashes in command line mode
// auto pt = presetbundle->printers.get_selected_preset().printer_technology();
// if(pt != ptSLA) {
// ctl->report_issue(IssueType::ERR, L("Printer technology is not SLA!"),
// L("Error"));
// return;
// }
auto conf = presetbundle->full_config();
conf.validate();
// auto conf = presetbundle->full_config();
// conf.validate();
auto exd = query_png_export_data(conf);
if(exd.zippath.empty()) return;
// auto exd = query_png_export_data(conf);
// if(exd.zippath.empty()) return;
Print *print = m_print;
// Print *print = m_print;
try {
print->apply_config(conf);
print->validate();
} catch(std::exception& e) {
ctl->report_issue(IssueType::ERR, e.what(), "Error");
return;
}
// try {
// print->apply_config(conf);
// print->validate();
// } catch(std::exception& e) {
// ctl->report_issue(IssueType::ERR, e.what(), "Error");
// return;
// }
// TODO: copy the model and work with the copy only
bool correction = false;
if(exd.corr_x != 1.0 || exd.corr_y != 1.0 || exd.corr_z != 1.0) {
correction = true;
// print->invalidate_all_steps();
// // TODO: copy the model and work with the copy only
// bool correction = false;
// if(exd.corr_x != 1.0 || exd.corr_y != 1.0 || exd.corr_z != 1.0) {
// correction = true;
//// print->invalidate_all_steps();
// for(auto po : print->objects) {
// po->model_object()->scale(
// Pointf3(exd.corr_x, exd.corr_y, exd.corr_z)
// );
// po->model_object()->invalidate_bounding_box();
// po->reload_model_instances();
// po->invalidate_all_steps();
//// for(auto po : print->objects) {
//// po->model_object()->scale(
//// Pointf3(exd.corr_x, exd.corr_y, exd.corr_z)
//// );
//// po->model_object()->invalidate_bounding_box();
//// po->reload_model_instances();
//// po->invalidate_all_steps();
//// }
// }
// // Turn back the correction scaling on the model.
// auto scale_back = [this, print, correction, exd]() {
// if(correction) { // scale the model back
//// print->invalidate_all_steps();
//// for(auto po : print->objects) {
//// po->model_object()->scale(
//// Pointf3(1.0/exd.corr_x, 1.0/exd.corr_y, 1.0/exd.corr_z)
//// );
//// po->model_object()->invalidate_bounding_box();
//// po->reload_model_instances();
//// po->invalidate_all_steps();
//// }
// }
}
// };
// Turn back the correction scaling on the model.
auto scale_back = [this, print, correction, exd]() {
if(correction) { // scale the model back
// print->invalidate_all_steps();
// for(auto po : print->objects) {
// po->model_object()->scale(
// Pointf3(1.0/exd.corr_x, 1.0/exd.corr_y, 1.0/exd.corr_z)
// );
// po->model_object()->invalidate_bounding_box();
// po->reload_model_instances();
// po->invalidate_all_steps();
// }
}
};
// auto print_bb = print->bounding_box();
// Vec2d punsc = unscale(print_bb.size());
auto print_bb = print->bounding_box();
Vec2d punsc = unscale(print_bb.size());
// // If the print does not fit into the print area we should cry about it.
// if(px(punsc) > exd.width_mm || py(punsc) > exd.height_mm) {
// std::stringstream ss;
// If the print does not fit into the print area we should cry about it.
if(px(punsc) > exd.width_mm || py(punsc) > exd.height_mm) {
std::stringstream ss;
// ss << L("Print will not fit and will be truncated!") << "\n"
// << L("Width needed: ") << px(punsc) << " mm\n"
// << L("Height needed: ") << py(punsc) << " mm\n";
ss << L("Print will not fit and will be truncated!") << "\n"
<< L("Width needed: ") << px(punsc) << " mm\n"
<< L("Height needed: ") << py(punsc) << " mm\n";
// if(!ctl->report_issue(IssueType::WARN_Q, ss.str(), L("Warning"))) {
// scale_back();
// return;
// }
// }
if(!ctl->report_issue(IssueType::WARN_Q, ss.str(), L("Warning"))) {
scale_back();
return;
}
}
// auto pri = ctl->create_progress_indicator(
// 200, L("Slicing to zipped png files..."));
auto pri = ctl->create_progress_indicator(
200, L("Slicing to zipped png files..."));
// pri->on_cancel([&print](){ print->cancel(); });
pri->on_cancel([&print](){ print->cancel(); });
// try {
// pri->update(0, L("Slicing..."));
// slice(pri);
// } catch (std::exception& e) {
// ctl->report_issue(IssueType::ERR, e.what(), L("Exception occurred"));
// scale_back();
// if(print->canceled()) print->restart();
// return;
// }
try {
pri->update(0, L("Slicing..."));
slice(pri);
} catch (std::exception& e) {
ctl->report_issue(IssueType::ERR, e.what(), L("Exception occurred"));
scale_back();
if(print->canceled()) print->restart();
return;
}
// auto initstate = unsigned(pri->state());
// print->set_status_callback([pri, initstate](int st, const std::string& msg)
// {
// pri->update(initstate + unsigned(st), msg);
// });
auto initstate = unsigned(pri->state());
print->set_status_callback([pri, initstate](int st, const std::string& msg)
{
pri->update(initstate + unsigned(st), msg);
});
// try {
// print_to<FilePrinterFormat::PNG, Zipper>( *print, exd.zippath,
// exd.width_mm, exd.height_mm,
// exd.width_px, exd.height_px,
// exd.exp_time_s, exd.exp_time_first_s);
try {
print_to<FilePrinterFormat::PNG, Zipper>( *print, exd.zippath,
exd.width_mm, exd.height_mm,
exd.width_px, exd.height_px,
exd.exp_time_s, exd.exp_time_first_s);
// } catch (std::exception& e) {
// ctl->report_issue(IssueType::ERR, e.what(), L("Exception occurred"));
// }
} catch (std::exception& e) {
ctl->report_issue(IssueType::ERR, e.what(), L("Exception occurred"));
}
scale_back();
if(print->canceled()) print->restart();
print->set_status_default();
// scale_back();
// if(print->canceled()) print->restart();
// print->set_status_default();
}
const PrintConfig &PrintController::config() const