Change to firstfit selection because DJD needs further testing.

This commit is contained in:
tamasmeszaros 2018-07-16 16:07:29 +02:00
parent eefa1678db
commit 6bcd735655
31 changed files with 4317 additions and 826 deletions

View File

@ -724,29 +724,12 @@ add_custom_target(pot
# ##############################################################################
set(LIBNEST2D_UNITTESTS ON CACHE BOOL "Force generating unittests for libnest2d")
set(LIBNEST2D_BUILD_SHARED_LIB OFF CACHE BOOL "Disable build of shared lib.")
if(LIBNEST2D_UNITTESTS)
# If we want the libnest2d unit tests we need to build and executable with
# all the libslic3r dependencies. This is needed because the clipper library
# in the slic3r project is hacked so that it depends on the slic3r sources.
# Unfortunately, this implies that the test executable is also dependent on
# the libslic3r target.
# add_library(libslic3r_standalone STATIC ${LIBDIR}/libslic3r/utils.cpp)
# set(LIBNEST2D_TEST_LIBRARIES
# libslic3r libslic3r_standalone nowide libslic3r_gui admesh miniz
# ${Boost_LIBRARIES} clipper ${EXPAT_LIBRARIES} ${GLEW_LIBRARIES}
# polypartition poly2tri ${TBB_LIBRARIES} ${wxWidgets_LIBRARIES}
# ${CURL_LIBRARIES}
# )
endif()
add_subdirectory(${LIBDIR}/libnest2d)
target_include_directories(libslic3r PUBLIC BEFORE ${LIBNEST2D_INCLUDES})
# Add the binpack2d main sources and link them to libslic3r
target_link_libraries(libslic3r libnest2d_static)
message(STATUS "Libnest2D Libraries: ${LIBNEST2D_LIBRARIES}")
target_link_libraries(libslic3r ${LIBNEST2D_LIBRARIES})
# ##############################################################################
# Installation

View File

@ -5,8 +5,7 @@ project(Libnest2D)
enable_testing()
if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX)
# Update if necessary
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-long-long -pedantic")
# Update if necessary
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-long-long ")
endif()
@ -20,39 +19,37 @@ option(LIBNEST2D_UNITTESTS "If enabled, googletest framework will be downloaded
and the provided unit tests will be included in the build." OFF)
option(LIBNEST2D_BUILD_EXAMPLES "If enabled, examples will be built." OFF)
option(LIBNEST2D_BUILD_SHARED_LIB "Build shared library." ON)
#set(LIBNEST2D_GEOMETRIES_TARGET "" CACHE STRING
# "Build libnest2d with geometry classes implemented by the chosen target.")
#set(libnest2D_TEST_LIBRARIES "" CACHE STRING
# "Libraries needed to compile the test executable for libnest2d.")
set(LIBNEST2D_GEOMETRIES_BACKEND "clipper" CACHE STRING
"Build libnest2d with geometry classes implemented by the chosen backend.")
set(LIBNEST2D_OPTIMIZER_BACKEND "nlopt" CACHE STRING
"Build libnest2d with optimization features implemented by the chosen backend.")
set(LIBNEST2D_SRCFILES
libnest2d/libnest2d.hpp # Templates only
libnest2d.h # Exports ready made types using template arguments
libnest2d/geometry_traits.hpp
libnest2d/geometries_io.hpp
libnest2d/common.hpp
libnest2d/optimizer.hpp
libnest2d/placers/placer_boilerplate.hpp
libnest2d/placers/bottomleftplacer.hpp
libnest2d/placers/nfpplacer.hpp
libnest2d/geometries_nfp.hpp
libnest2d/selections/selection_boilerplate.hpp
libnest2d/selections/filler.hpp
libnest2d/selections/firstfit.hpp
libnest2d/selections/djd_heuristic.hpp
libnest2d/optimizers/simplex.hpp
libnest2d/optimizers/subplex.hpp
libnest2d/optimizers/genetic.hpp
libnest2d/optimizers/nlopt_boilerplate.hpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/libnest2d.hpp # Templates only
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d.h # Exports ready made types using template arguments
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/geometry_traits.hpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/common.hpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/optimizer.hpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/placers/placer_boilerplate.hpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/placers/bottomleftplacer.hpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/placers/nfpplacer.hpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/geometry_traits_nfp.hpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/selections/selection_boilerplate.hpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/selections/filler.hpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/selections/firstfit.hpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/selections/djd_heuristic.hpp
)
if((NOT LIBNEST2D_GEOMETRIES_TARGET) OR (LIBNEST2D_GEOMETRIES_TARGET STREQUAL ""))
message(STATUS "libnest2D backend is default")
set(LIBNEST2D_LIBRARIES "")
set(LIBNEST2D_HEADERS ${CMAKE_CURRENT_SOURCE_DIR})
if(LIBNEST2D_GEOMETRIES_BACKEND STREQUAL "clipper")
# Clipper backend is not enough on its own, it still needs some functions
# from Boost geometry
if(NOT Boost_INCLUDE_DIRS_FOUND)
find_package(Boost 1.58 REQUIRED)
# TODO automatic download of boost geometry headers
@ -60,56 +57,63 @@ if((NOT LIBNEST2D_GEOMETRIES_TARGET) OR (LIBNEST2D_GEOMETRIES_TARGET STREQUAL ""
add_subdirectory(libnest2d/clipper_backend)
set(LIBNEST2D_GEOMETRIES_TARGET ${CLIPPER_LIBRARIES})
include_directories(BEFORE ${CLIPPER_INCLUDE_DIRS})
include_directories(${Boost_INCLUDE_DIRS})
list(APPEND LIBNEST2D_SRCFILES libnest2d/clipper_backend/clipper_backend.cpp
libnest2d/clipper_backend/clipper_backend.hpp
libnest2d/boost_alg.hpp)
else()
message(STATUS "Libnest2D backend is: ${LIBNEST2D_GEOMETRIES_TARGET}")
list(APPEND LIBNEST2D_SRCFILES ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/clipper_backend/clipper_backend.cpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/clipper_backend/clipper_backend.hpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/boost_alg.hpp)
list(APPEND LIBNEST2D_LIBRARIES ${CLIPPER_LIBRARIES})
list(APPEND LIBNEST2D_HEADERS ${CLIPPER_INCLUDE_DIRS}
${Boost_INCLUDE_DIRS_FOUND})
endif()
message(STATUS "clipper lib is: ${LIBNEST2D_GEOMETRIES_TARGET}")
if(LIBNEST2D_OPTIMIZER_BACKEND STREQUAL "nlopt")
find_package(NLopt 1.4)
if(NOT NLopt_FOUND)
message(STATUS "NLopt not found so downloading "
"and automatic build is performed...")
include(DownloadNLopt)
endif()
find_package(Threads REQUIRED)
find_package(NLopt 1.4)
if(NOT NLopt_FOUND)
message(STATUS "NLopt not found so downloading and automatic build is performed...")
include(DownloadNLopt)
endif()
find_package(Threads REQUIRED)
add_library(libnest2d_static STATIC ${LIBNEST2D_SRCFILES} )
target_link_libraries(libnest2d_static PRIVATE ${LIBNEST2D_GEOMETRIES_TARGET} ${NLopt_LIBS})
target_include_directories(libnest2d_static PUBLIC ${CMAKE_SOURCE_DIR} ${NLopt_INCLUDE_DIR})
set_target_properties(libnest2d_static PROPERTIES PREFIX "")
if(LIBNEST2D_BUILD_SHARED_LIB)
add_library(libnest2d SHARED ${LIBNEST2D_SRCFILES} )
target_link_libraries(libnest2d PRIVATE ${LIBNEST2D_GEOMETRIES_TARGET} ${NLopt_LIBS})
target_include_directories(libnest2d PUBLIC ${CMAKE_SOURCE_DIR} ${NLopt_INCLUDE_DIR})
set_target_properties(libnest2d PROPERTIES PREFIX "")
list(APPEND LIBNEST2D_SRCFILES ${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/optimizers/simplex.hpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/optimizers/subplex.hpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/optimizers/genetic.hpp
${CMAKE_CURRENT_SOURCE_DIR}/libnest2d/optimizers/nlopt_boilerplate.hpp)
list(APPEND LIBNEST2D_LIBRARIES ${NLopt_LIBS} Threads::Threads)
list(APPEND LIBNEST2D_HEADERS ${NLopt_INCLUDE_DIR})
endif()
set(LIBNEST2D_HEADERS ${CMAKE_CURRENT_SOURCE_DIR})
get_directory_property(hasParent PARENT_DIRECTORY)
if(hasParent)
set(LIBNEST2D_INCLUDES ${CMAKE_CURRENT_SOURCE_DIR} PARENT_SCOPE)
endif()
# Currently we are outsourcing the non-convex NFP implementation from
# libnfporb and it needs libgmp to work
#find_package(GMP)
#if(GMP_FOUND)
# list(APPEND LIBNEST2D_LIBRARIES ${GMP_LIBRARIES})
# list(APPEND LIBNEST2D_HEADERS ${GMP_INCLUDE_DIR})
# add_definitions(-DLIBNFP_USE_RATIONAL)
#endif()
if(LIBNEST2D_UNITTESTS)
add_subdirectory(tests)
endif()
if(LIBNEST2D_BUILD_EXAMPLES)
add_executable(example tests/main.cpp
tests/svgtools.hpp
add_executable(example examples/main.cpp
# tools/libnfpglue.hpp
# tools/libnfpglue.cpp
tools/svgtools.hpp
tests/printer_parts.cpp
tests/printer_parts.h)
target_link_libraries(example libnest2d_static Threads::Threads)
target_include_directories(example PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
tests/printer_parts.h
${LIBNEST2D_SRCFILES})
target_link_libraries(example ${LIBNEST2D_LIBRARIES})
target_include_directories(example PUBLIC ${LIBNEST2D_HEADERS})
endif()
get_directory_property(hasParent PARENT_DIRECTORY)
if(hasParent)
set(LIBNEST2D_INCLUDES ${LIBNEST2D_HEADERS} PARENT_SCOPE)
set(LIBNEST2D_LIBRARIES ${LIBNEST2D_LIBRARIES} PARENT_SCOPE)
endif()

View File

@ -0,0 +1,35 @@
# Try to find the GMP libraries:
# GMP_FOUND - System has GMP lib
# GMP_INCLUDE_DIR - The GMP include directory
# GMP_LIBRARIES - Libraries needed to use GMP
if (GMP_INCLUDE_DIR AND GMP_LIBRARIES)
# Force search at every time, in case configuration changes
unset(GMP_INCLUDE_DIR CACHE)
unset(GMP_LIBRARIES CACHE)
endif (GMP_INCLUDE_DIR AND GMP_LIBRARIES)
find_path(GMP_INCLUDE_DIR NAMES gmp.h)
if(WIN32)
find_library(GMP_LIBRARIES NAMES libgmp.a gmp gmp.lib mpir mpir.lib)
else(WIN32)
if(STBIN)
message(STATUS "STBIN: ${STBIN}")
find_library(GMP_LIBRARIES NAMES libgmp.a gmp)
else(STBIN)
find_library(GMP_LIBRARIES NAMES libgmp.so gmp)
endif(STBIN)
endif(WIN32)
if(GMP_INCLUDE_DIR AND GMP_LIBRARIES)
set(GMP_FOUND TRUE)
endif(GMP_INCLUDE_DIR AND GMP_LIBRARIES)
if(GMP_FOUND)
message(STATUS "Configured GMP: ${GMP_LIBRARIES}")
else(GMP_FOUND)
message(STATUS "Could NOT find GMP")
endif(GMP_FOUND)
mark_as_advanced(GMP_INCLUDE_DIR GMP_LIBRARIES)

View File

@ -5,13 +5,11 @@
//#define DEBUG_EXPORT_NFP
#include <libnest2d.h>
#include <libnest2d/geometries_io.hpp>
#include "printer_parts.h"
#include "benchmark.h"
#include "svgtools.hpp"
//#include <libnest2d/optimizer.hpp>
//#include <libnest2d/optimizers/simplex.hpp>
#include "tests/printer_parts.h"
#include "tools/benchmark.h"
#include "tools/svgtools.hpp"
//#include "tools/libnfpglue.hpp"
using namespace libnest2d;
using ItemGroup = std::vector<std::reference_wrapper<Item>>;
@ -37,10 +35,22 @@ std::vector<Item>& stegoParts() {
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;
// const int SCALE = 1;
std::vector<Rectangle> rects = {
{80*SCALE, 80*SCALE},
{60*SCALE, 90*SCALE},
@ -506,38 +516,59 @@ void arrangeRectangles() {
},
};
std::vector<Item> proba = {
{
{ {0, 0}, {20, 20}, {40, 0}, {0, 0} }
},
{
{ {0, 100}, {50, 60}, {100, 100}, {50, 0}, {0, 100} }
},
};
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());
// input.insert(input.end(), proba.begin(), proba.end());
input.insert(input.end(), crasher.begin(), crasher.end());
Box bin(250*SCALE, 210*SCALE);
Coord min_obj_distance = 6*SCALE;
using Packer = Arranger<NfpPlacer, DJDHeuristic>;
using Placer = NfpPlacer;
using Packer = Arranger<Placer, FirstFitSelection>;
Packer arrange(bin, min_obj_distance);
Packer::PlacementConfig pconf;
pconf.alignment = NfpPlacer::Config::Alignment::CENTER;
pconf.alignment = Placer::Config::Alignment::CENTER;
pconf.rotations = {0.0/*, Pi/2.0, Pi, 3*Pi/2*/};
pconf.object_function = [&bin](NfpPlacer::Pile pile, double area,
pconf.object_function = [&bin](Placer::Pile pile, double area,
double norm, double penality) {
auto bb = ShapeLike::boundingBox(pile);
double score = (2*bb.width() + 2*bb.height()) / norm;
double diameter = PointLike::distance(bb.minCorner(),
bb.maxCorner());
// We will optimize to the diameter of the circle around the bounding
// box and use the norming factor to get rid of the physical dimensions
double score = diameter / norm;
// If it does not fit into the print bed we will beat it
// with a large penality
if(!NfpPlacer::wouldFit(bb, bin)) score = 2*penality - score;
return score;
};
Packer::SelectionConfig sconf;
sconf.allow_parallel = true;
sconf.force_parallel = true;
sconf.try_reverse_order = true;
// sconf.allow_parallel = false;
// sconf.force_parallel = false;
// sconf.try_reverse_order = true;
arrange.configure(pconf, sconf);
@ -610,10 +641,9 @@ void arrangeRectangles() {
svgw.save("out");
}
int main(void /*int argc, char **argv*/) {
arrangeRectangles();
// findDegenerateCase();
return EXIT_SUCCESS;
}

View File

@ -5,6 +5,10 @@
// 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/simplex.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>
@ -31,7 +35,9 @@ using DJDHeuristic = strategies::_DJDHeuristic<PolygonImpl>;
using NfpPlacer = strategies::_NofitPolyPlacer<PolygonImpl>;
using BottomLeftPlacer = strategies::_BottomLeftPlacer<PolygonImpl>;
using NofitPolyPlacer = strategies::_NofitPolyPlacer<PolygonImpl>;
//template<NfpLevel lvl = NfpLevel::BOTH_CONCAVE_WITH_HOLES>
//using NofitPolyPlacer = strategies::_NofitPolyPlacer<PolygonImpl, lvl>;
}

View File

@ -139,7 +139,7 @@ template<> struct indexed_access<bp2d::Box, max_corner, 1> {
};
/* ************************************************************************** */
/* Segement concept adaptaion *********************************************** */
/* Segment concept adaptaion ************************************************ */
/* ************************************************************************** */
template<> struct tag<bp2d::Segment> {
@ -461,21 +461,19 @@ inline bp2d::Shapes Nfp::merge(const bp2d::Shapes& shapes,
}
#endif
#ifndef DISABLE_BOOST_MINKOWSKI_ADD
template<>
inline PolygonImpl& Nfp::minkowskiAdd(PolygonImpl& sh,
const PolygonImpl& /*other*/)
{
return sh;
}
#endif
//#ifndef DISABLE_BOOST_MINKOWSKI_ADD
//template<>
//inline PolygonImpl& Nfp::minkowskiAdd(PolygonImpl& sh,
// const PolygonImpl& /*other*/)
//{
// return sh;
//}
//#endif
#ifndef DISABLE_BOOST_SERIALIZE
template<>
inline std::string ShapeLike::serialize<libnest2d::Formats::SVG>(
template<> inline std::string ShapeLike::serialize<libnest2d::Formats::SVG>(
const PolygonImpl& sh, double scale)
{
std::stringstream ss;
std::string style = "fill: none; stroke: black; stroke-width: 1px;";
@ -484,14 +482,27 @@ inline std::string ShapeLike::serialize<libnest2d::Formats::SVG>(
using Polygonf = model::polygon<Pointf>;
Polygonf::ring_type ring;
Polygonf::inner_container_type holes;
ring.reserve(ShapeLike::contourVertexCount(sh));
for(auto it = ShapeLike::cbegin(sh); it != ShapeLike::cend(sh); it++) {
auto& v = *it;
ring.emplace_back(getX(v)*scale, getY(v)*scale);
};
auto H = ShapeLike::holes(sh);
for(PathImpl& h : H ) {
Polygonf::ring_type hf;
for(auto it = h.begin(); it != h.end(); it++) {
auto& v = *it;
hf.emplace_back(getX(v)*scale, getY(v)*scale);
};
holes.push_back(hf);
}
Polygonf poly;
poly.outer() = ring;
poly.inners() = holes;
auto svg_data = boost::geometry::svg(poly, style);
ss << svg_data << std::endl;

View File

@ -1,112 +1,58 @@
#include "clipper_backend.hpp"
#include <atomic>
//#include "clipper_backend.hpp"
//#include <atomic>
namespace libnest2d {
//namespace libnest2d {
namespace {
//namespace {
class SpinLock {
std::atomic_flag& lck_;
public:
//class SpinLock {
// std::atomic_flag& lck_;
//public:
inline SpinLock(std::atomic_flag& flg): lck_(flg) {}
// inline SpinLock(std::atomic_flag& flg): lck_(flg) {}
inline void lock() {
while(lck_.test_and_set(std::memory_order_acquire)) {}
}
// inline void lock() {
// while(lck_.test_and_set(std::memory_order_acquire)) {}
// }
inline void unlock() { lck_.clear(std::memory_order_release); }
};
// inline void unlock() { lck_.clear(std::memory_order_release); }
//};
class HoleCache {
friend struct libnest2d::ShapeLike;
//class HoleCache {
// friend struct libnest2d::ShapeLike;
std::unordered_map< const PolygonImpl*, ClipperLib::Paths> map;
// std::unordered_map< const PolygonImpl*, ClipperLib::Paths> map;
ClipperLib::Paths& _getHoles(const PolygonImpl* p) {
static std::atomic_flag flg = ATOMIC_FLAG_INIT;
SpinLock lock(flg);
// ClipperLib::Paths& _getHoles(const PolygonImpl* p) {
// static std::atomic_flag flg = ATOMIC_FLAG_INIT;
// SpinLock lock(flg);
lock.lock();
ClipperLib::Paths& paths = map[p];
lock.unlock();
// lock.lock();
// ClipperLib::Paths& paths = map[p];
// lock.unlock();
if(paths.size() != p->Childs.size()) {
paths.reserve(p->Childs.size());
// if(paths.size() != p->Childs.size()) {
// paths.reserve(p->Childs.size());
for(auto np : p->Childs) {
paths.emplace_back(np->Contour);
}
}
// for(auto np : p->Childs) {
// paths.emplace_back(np->Contour);
// }
// }
return paths;
}
// return paths;
// }
ClipperLib::Paths& getHoles(PolygonImpl& p) {
return _getHoles(&p);
}
// ClipperLib::Paths& getHoles(PolygonImpl& p) {
// return _getHoles(&p);
// }
const ClipperLib::Paths& getHoles(const PolygonImpl& p) {
return _getHoles(&p);
}
};
}
// const ClipperLib::Paths& getHoles(const PolygonImpl& p) {
// return _getHoles(&p);
// }
//};
//}
HoleCache holeCache;
//HoleCache holeCache;
template<>
std::string ShapeLike::toString(const PolygonImpl& sh)
{
std::stringstream ss;
for(auto p : sh.Contour) {
ss << p.X << " " << p.Y << "\n";
}
return ss.str();
}
template<> PolygonImpl ShapeLike::create( const PathImpl& path )
{
PolygonImpl p;
p.Contour = path;
// Expecting that the coordinate system Y axis is positive in upwards
// direction
if(ClipperLib::Orientation(p.Contour)) {
// Not clockwise then reverse the b*tch
ClipperLib::ReversePath(p.Contour);
}
return p;
}
template<> PolygonImpl ShapeLike::create( PathImpl&& path )
{
PolygonImpl p;
p.Contour.swap(path);
// Expecting that the coordinate system Y axis is positive in upwards
// direction
if(ClipperLib::Orientation(p.Contour)) {
// Not clockwise then reverse the b*tch
ClipperLib::ReversePath(p.Contour);
}
return p;
}
template<>
const THolesContainer<PolygonImpl>& ShapeLike::holes(
const PolygonImpl& sh)
{
return holeCache.getHoles(sh);
}
template<>
THolesContainer<PolygonImpl>& ShapeLike::holes(PolygonImpl& sh) {
return holeCache.getHoles(sh);
}
}
//}

View File

@ -4,18 +4,36 @@
#include <sstream>
#include <unordered_map>
#include <cassert>
#include <vector>
#include <iostream>
#include "../geometry_traits.hpp"
#include "../geometries_nfp.hpp"
#include "../geometry_traits_nfp.hpp"
#include <clipper.hpp>
namespace ClipperLib {
using PointImpl = IntPoint;
using PolygonImpl = PolyNode;
using PathImpl = Path;
using HoleStore = std::vector<PathImpl>;
struct PolygonImpl {
PathImpl Contour;
HoleStore Holes;
inline PolygonImpl() {}
inline explicit PolygonImpl(const PathImpl& cont): Contour(cont) {}
inline explicit PolygonImpl(const HoleStore& holes):
Holes(holes) {}
inline PolygonImpl(const Path& cont, const HoleStore& holes):
Contour(cont), Holes(holes) {}
inline explicit PolygonImpl(PathImpl&& cont): Contour(std::move(cont)) {}
inline explicit PolygonImpl(HoleStore&& holes): Holes(std::move(holes)) {}
inline PolygonImpl(Path&& cont, HoleStore&& holes):
Contour(std::move(cont)), Holes(std::move(holes)) {}
};
inline PointImpl& operator +=(PointImpl& p, const PointImpl& pa ) {
// This could be done with SIMD
@ -53,11 +71,10 @@ inline PointImpl operator-(const PointImpl& p1, const PointImpl& p2) {
namespace libnest2d {
// Aliases for convinience
using PointImpl = ClipperLib::IntPoint;
using PolygonImpl = ClipperLib::PolyNode;
using PathImpl = ClipperLib::Path;
//extern HoleCache holeCache;
using ClipperLib::PointImpl;
using ClipperLib::PathImpl;
using ClipperLib::PolygonImpl;
using ClipperLib::HoleStore;
// Type of coordinate units used by Clipper
template<> struct CoordType<PointImpl> {
@ -124,12 +141,26 @@ inline double area(const PolygonImpl& sh) {
template<>
inline double area<Orientation::CLOCKWISE>(const PolygonImpl& sh) {
return -ClipperLib::Area(sh.Contour);
double a = 0;
std::for_each(sh.Holes.begin(), sh.Holes.end(), [&a](const PathImpl& h)
{
a -= ClipperLib::Area(h);
});
return -ClipperLib::Area(sh.Contour) + a;
}
template<>
inline double area<Orientation::COUNTER_CLOCKWISE>(const PolygonImpl& sh) {
return ClipperLib::Area(sh.Contour);
double a = 0;
std::for_each(sh.Holes.begin(), sh.Holes.end(), [&a](const PathImpl& h)
{
a += ClipperLib::Area(h);
});
return ClipperLib::Area(sh.Contour) + a;
}
}
@ -149,140 +180,85 @@ inline void ShapeLike::offset(PolygonImpl& sh, TCoord<PointImpl> distance) {
using ClipperLib::Paths;
// If the input is not at least a triangle, we can not do this algorithm
if(sh.Contour.size() <= 3) throw GeometryException(GeomErr::OFFSET);
if(sh.Contour.size() <= 3 ||
std::any_of(sh.Holes.begin(), sh.Holes.end(),
[](const PathImpl& p) { return p.size() <= 3; })
) throw GeometryException(GeomErr::OFFSET);
ClipperOffset offs;
Paths result;
offs.AddPath(sh.Contour, jtMiter, etClosedPolygon);
offs.AddPaths(sh.Holes, jtMiter, etClosedPolygon);
offs.Execute(result, static_cast<double>(distance));
// I dont know why does the offsetting revert the orientation and
// it removes the last vertex as well so boost will not have a closed
// polygon
// Offsetting reverts the orientation and also removes the last vertex
// so boost will not have a closed polygon.
if(result.size() != 1) throw GeometryException(GeomErr::OFFSET);
bool found_the_contour = false;
for(auto& r : result) {
if(ClipperLib::Orientation(r)) {
// We don't like if the offsetting generates more than one contour
// but throwing would be an overkill. Instead, we should warn the
// caller about the inability to create correct geometries
if(!found_the_contour) {
sh.Contour = r;
ClipperLib::ReversePath(sh.Contour);
sh.Contour.push_back(sh.Contour.front());
found_the_contour = true;
} else {
dout() << "Warning: offsetting result is invalid!";
/* TODO warning */
}
} else {
// TODO If there are multiple contours we can't be sure which hole
// belongs to the first contour. (But in this case the situation is
// bad enough to let it go...)
sh.Holes.push_back(r);
ClipperLib::ReversePath(sh.Holes.back());
sh.Holes.back().push_back(sh.Holes.back().front());
}
}
}
sh.Contour = result.front();
//template<> // TODO make it support holes if this method will ever be needed.
//inline PolygonImpl Nfp::minkowskiDiff(const PolygonImpl& sh,
// const PolygonImpl& other)
//{
// #define DISABLE_BOOST_MINKOWSKI_ADD
// recreate closed polygon
sh.Contour.push_back(sh.Contour.front());
// ClipperLib::Paths solution;
if(ClipperLib::Orientation(sh.Contour)) {
// Not clockwise then reverse the b*tch
ClipperLib::ReversePath(sh.Contour);
// ClipperLib::MinkowskiDiff(sh.Contour, other.Contour, solution);
// PolygonImpl ret;
// ret.Contour = solution.front();
// return sh;
//}
// Tell libnest2d how to make string out of a ClipperPolygon object
template<> inline std::string ShapeLike::toString(const PolygonImpl& sh) {
std::stringstream ss;
ss << "Contour {\n";
for(auto p : sh.Contour) {
ss << "\t" << p.X << " " << p.Y << "\n";
}
ss << "}\n";
for(auto& h : sh.Holes) {
ss << "Holes {\n";
for(auto p : h) {
ss << "\t{\n";
ss << "\t\t" << p.X << " " << p.Y << "\n";
ss << "\t}\n";
}
ss << "}\n";
}
return ss.str();
}
// TODO : make it convex hull right and faster than boost
//#define DISABLE_BOOST_CONVEX_HULL
//inline TCoord<PointImpl> cross( const PointImpl &O,
// const PointImpl &A,
// const PointImpl &B)
//{
// return (A.X - O.X) * (B.Y - O.Y) - (A.Y - O.Y) * (B.X - O.X);
//}
//template<>
//inline PolygonImpl ShapeLike::convexHull(const PolygonImpl& sh)
//{
// auto& P = sh.Contour;
// PolygonImpl ret;
// size_t n = P.size(), k = 0;
// if (n <= 3) return ret;
// auto& H = ret.Contour;
// H.resize(2*n);
// std::vector<unsigned> indices(P.size(), 0);
// std::iota(indices.begin(), indices.end(), 0);
// // Sort points lexicographically
// std::sort(indices.begin(), indices.end(), [&P](unsigned i1, unsigned i2){
// auto& p1 = P[i1], &p2 = P[i2];
// return p1.X < p2.X || (p1.X == p2.X && p1.Y < p2.Y);
// });
// // Build lower hull
// for (size_t i = 0; i < n; ++i) {
// while (k >= 2 && cross(H[k-2], H[k-1], P[i]) <= 0) k--;
// H[k++] = P[i];
// }
// // Build upper hull
// for (size_t i = n-1, t = k+1; i > 0; --i) {
// while (k >= t && cross(H[k-2], H[k-1], P[i-1]) <= 0) k--;
// H[k++] = P[i-1];
// }
// H.resize(k-1);
// return ret;
//}
//template<>
//inline PolygonImpl ShapeLike::convexHull(
// const ShapeLike::Shapes<PolygonImpl>& shapes)
//{
// PathImpl P;
// PolygonImpl ret;
// size_t n = 0, k = 0;
// for(auto& sh : shapes) { n += sh.Contour.size(); }
// P.reserve(n);
// for(auto& sh : shapes) { P.insert(P.end(),
// sh.Contour.begin(), sh.Contour.end()); }
// if (n <= 3) { ret.Contour = P; return ret; }
// auto& H = ret.Contour;
// H.resize(2*n);
// std::vector<unsigned> indices(P.size(), 0);
// std::iota(indices.begin(), indices.end(), 0);
// // Sort points lexicographically
// std::sort(indices.begin(), indices.end(), [&P](unsigned i1, unsigned i2){
// auto& p1 = P[i1], &p2 = P[i2];
// return p1.X < p2.X || (p1.X == p2.X && p1.Y < p2.Y);
// });
// // Build lower hull
// for (size_t i = 0; i < n; ++i) {
// while (k >= 2 && cross(H[k-2], H[k-1], P[i]) <= 0) k--;
// H[k++] = P[i];
// }
// // Build upper hull
// for (size_t i = n-1, t = k+1; i > 0; --i) {
// while (k >= t && cross(H[k-2], H[k-1], P[i-1]) <= 0) k--;
// H[k++] = P[i-1];
// }
// H.resize(k-1);
// return ret;
//}
template<>
inline PolygonImpl& Nfp::minkowskiAdd(PolygonImpl& sh,
const PolygonImpl& other)
{
#define DISABLE_BOOST_MINKOWSKI_ADD
ClipperLib::Paths solution;
ClipperLib::MinkowskiSum(sh.Contour, other.Contour, solution, true);
assert(solution.size() == 1);
sh.Contour = solution.front();
return sh;
}
// Tell binpack2d how to make string out of a ClipperPolygon object
template<> std::string ShapeLike::toString(const PolygonImpl& sh);
template<>
inline TVertexIterator<PolygonImpl> ShapeLike::begin(PolygonImpl& sh)
{
@ -313,34 +289,78 @@ template<> struct HolesContainer<PolygonImpl> {
using Type = ClipperLib::Paths;
};
template<> PolygonImpl ShapeLike::create( const PathImpl& path);
template<> inline PolygonImpl ShapeLike::create(const PathImpl& path,
const HoleStore& holes) {
PolygonImpl p;
p.Contour = path;
template<> PolygonImpl ShapeLike::create( PathImpl&& path);
// Expecting that the coordinate system Y axis is positive in upwards
// direction
if(ClipperLib::Orientation(p.Contour)) {
// Not clockwise then reverse the b*tch
ClipperLib::ReversePath(p.Contour);
}
template<>
const THolesContainer<PolygonImpl>& ShapeLike::holes(
const PolygonImpl& sh);
p.Holes = holes;
for(auto& h : p.Holes) {
if(!ClipperLib::Orientation(h)) {
ClipperLib::ReversePath(h);
}
}
template<>
THolesContainer<PolygonImpl>& ShapeLike::holes(PolygonImpl& sh);
template<>
inline TContour<PolygonImpl>& ShapeLike::getHole(PolygonImpl& sh,
unsigned long idx)
{
return sh.Childs[idx]->Contour;
return p;
}
template<>
inline const TContour<PolygonImpl>& ShapeLike::getHole(const PolygonImpl& sh,
unsigned long idx)
template<> inline PolygonImpl ShapeLike::create( PathImpl&& path,
HoleStore&& holes) {
PolygonImpl p;
p.Contour.swap(path);
// Expecting that the coordinate system Y axis is positive in upwards
// direction
if(ClipperLib::Orientation(p.Contour)) {
// Not clockwise then reverse the b*tch
ClipperLib::ReversePath(p.Contour);
}
p.Holes.swap(holes);
for(auto& h : p.Holes) {
if(!ClipperLib::Orientation(h)) {
ClipperLib::ReversePath(h);
}
}
return p;
}
template<> inline const THolesContainer<PolygonImpl>&
ShapeLike::holes(const PolygonImpl& sh)
{
return sh.Childs[idx]->Contour;
return sh.Holes;
}
template<> inline THolesContainer<PolygonImpl>&
ShapeLike::holes(PolygonImpl& sh)
{
return sh.Holes;
}
template<> inline TContour<PolygonImpl>&
ShapeLike::getHole(PolygonImpl& sh, unsigned long idx)
{
return sh.Holes[idx];
}
template<> inline const TContour<PolygonImpl>&
ShapeLike::getHole(const PolygonImpl& sh, unsigned long idx)
{
return sh.Holes[idx];
}
template<> inline size_t ShapeLike::holeCount(const PolygonImpl& sh)
{
return sh.Childs.size();
return sh.Holes.size();
}
template<> inline PathImpl& ShapeLike::getContour(PolygonImpl& sh)
@ -359,7 +379,7 @@ template<>
inline void ShapeLike::translate(PolygonImpl& sh, const PointImpl& offs)
{
for(auto& p : sh.Contour) { p += offs; }
for(auto& hole : sh.Childs) for(auto& p : hole->Contour) { p += offs; }
for(auto& hole : sh.Holes) for(auto& p : hole) { p += offs; }
}
#define DISABLE_BOOST_ROTATE
@ -368,69 +388,77 @@ inline void ShapeLike::rotate(PolygonImpl& sh, const Radians& rads)
{
using Coord = TCoord<PointImpl>;
auto cosa = rads.cos();//std::cos(rads);
auto sina = rads.sin(); //std::sin(rads);
auto cosa = rads.cos();
auto sina = rads.sin();
for(auto& p : sh.Contour) {
p = {
static_cast<Coord>(p.X * cosa - p.Y * sina),
static_cast<Coord>(p.X * sina + p.Y * cosa)
};
};
}
for(auto& hole : sh.Childs) for(auto& p : hole->Contour) {
for(auto& hole : sh.Holes) for(auto& p : hole) {
p = {
static_cast<Coord>(p.X * cosa - p.Y * sina),
static_cast<Coord>(p.X * sina + p.Y * cosa)
};
static_cast<Coord>(p.X * cosa - p.Y * sina),
static_cast<Coord>(p.X * sina + p.Y * cosa)
};
}
}
#define DISABLE_BOOST_NFP_MERGE
template<> inline
Nfp::Shapes<PolygonImpl> Nfp::merge(const Nfp::Shapes<PolygonImpl>& shapes,
const PolygonImpl& sh)
template<> inline Nfp::Shapes<PolygonImpl>
Nfp::merge(const Nfp::Shapes<PolygonImpl>& shapes, const PolygonImpl& sh)
{
Nfp::Shapes<PolygonImpl> retv;
ClipperLib::Clipper clipper;
ClipperLib::Clipper clipper(ClipperLib::ioReverseSolution);
bool closed = true;
#ifndef NDEBUG
#define _valid() valid =
bool closed = true;
bool valid = false;
#else
#define _valid()
#endif
_valid() clipper.AddPath(sh.Contour, ClipperLib::ptSubject, closed);
valid = clipper.AddPath(sh.Contour, ClipperLib::ptSubject, closed);
for(auto& hole : sh.Childs) {
_valid() clipper.AddPath(hole->Contour, ClipperLib::ptSubject, closed);
assert(valid);
for(auto& hole : sh.Holes) {
valid &= clipper.AddPath(hole, ClipperLib::ptSubject, closed);
}
for(auto& path : shapes) {
_valid() clipper.AddPath(path.Contour, ClipperLib::ptSubject, closed);
assert(valid);
for(auto& hole : path.Childs) {
_valid() clipper.AddPath(hole->Contour, ClipperLib::ptSubject, closed);
assert(valid);
valid &= clipper.AddPath(path.Contour, ClipperLib::ptSubject, closed);
for(auto& hole : path.Holes) {
valid &= clipper.AddPath(hole, ClipperLib::ptSubject, closed);
}
}
ClipperLib::Paths rret;
clipper.Execute(ClipperLib::ctUnion, rret, ClipperLib::pftNonZero);
retv.reserve(rret.size());
for(auto& p : rret) {
if(ClipperLib::Orientation(p)) {
// Not clockwise then reverse the b*tch
ClipperLib::ReversePath(p);
if(!valid) throw GeometryException(GeomErr::MERGE);
ClipperLib::PolyTree result;
clipper.Execute(ClipperLib::ctUnion, result, ClipperLib::pftNonZero);
retv.reserve(result.Total());
std::function<void(ClipperLib::PolyNode*, PolygonImpl&)> processHole;
auto processPoly = [&retv, &processHole](ClipperLib::PolyNode *pptr) {
PolygonImpl poly(pptr->Contour);
poly.Contour.push_back(poly.Contour.front());
for(auto h : pptr->Childs) { processHole(h, poly); }
retv.push_back(poly);
};
processHole = [&processPoly](ClipperLib::PolyNode *pptr, PolygonImpl& poly) {
poly.Holes.push_back(pptr->Contour);
poly.Holes.back().push_back(poly.Holes.back().front());
for(auto c : pptr->Childs) processPoly(c);
};
auto traverse = [&processPoly] (ClipperLib::PolyNode *node)
{
for(auto ch : node->Childs) {
processPoly(ch);
}
retv.emplace_back();
retv.back().Contour = p;
retv.back().Contour.emplace_back(p.front());
}
};
traverse(&result);
return retv;
}

View File

@ -18,7 +18,6 @@
#define BP2D_CONSTEXPR constexpr
#endif
/*
* Debugging output dout and derr definition
*/
@ -211,16 +210,16 @@ enum class GeomErr : std::size_t {
NFP
};
static const std::string ERROR_STR[] = {
"Offsetting could not be done! An invalid geometry may have been added."
"Error while merging geometries!"
"No fit polygon cannaot be calculated."
const std::string ERROR_STR[] = {
"Offsetting could not be done! An invalid geometry may have been added.",
"Error while merging geometries!",
"No fit polygon cannot be calculated."
};
class GeometryException: public std::exception {
virtual const char * errorstr(GeomErr errcode) const BP2D_NOEXCEPT {
return ERROR_STR[static_cast<std::size_t>(errcode)].c_str();
virtual const std::string& errorstr(GeomErr errcode) const BP2D_NOEXCEPT {
return ERROR_STR[static_cast<std::size_t>(errcode)];
}
GeomErr errcode_;
@ -231,7 +230,7 @@ public:
GeomErr errcode() const { return errcode_; }
virtual const char * what() const BP2D_NOEXCEPT override {
return errorstr(errcode_);
return errorstr(errcode_).c_str();
}
};

View File

@ -1,18 +0,0 @@
#ifndef GEOMETRIES_IO_HPP
#define GEOMETRIES_IO_HPP
#include "libnest2d.hpp"
#include <ostream>
namespace libnest2d {
template<class RawShape>
std::ostream& operator<<(std::ostream& stream, const _Item<RawShape>& sh) {
stream << sh.toString() << "\n";
return stream;
}
}
#endif // GEOMETRIES_IO_HPP

View File

@ -1,223 +0,0 @@
#ifndef GEOMETRIES_NOFITPOLYGON_HPP
#define GEOMETRIES_NOFITPOLYGON_HPP
#include "geometry_traits.hpp"
#include <algorithm>
#include <vector>
namespace libnest2d {
struct Nfp {
template<class RawShape>
using Shapes = typename ShapeLike::Shapes<RawShape>;
template<class RawShape>
static RawShape& minkowskiAdd(RawShape& sh, const RawShape& /*other*/)
{
static_assert(always_false<RawShape>::value,
"Nfp::minkowskiAdd() unimplemented!");
return sh;
}
template<class RawShape>
static Shapes<RawShape> merge(const Shapes<RawShape>& shc, const RawShape& sh)
{
static_assert(always_false<RawShape>::value,
"Nfp::merge(shapes, shape) unimplemented!");
}
template<class RawShape>
inline static TPoint<RawShape> referenceVertex(const RawShape& sh)
{
return rightmostUpVertex(sh);
}
template<class RawShape>
static TPoint<RawShape> leftmostDownVertex(const RawShape& sh) {
// find min x and min y vertex
auto it = std::min_element(ShapeLike::cbegin(sh), ShapeLike::cend(sh),
_vsort<RawShape>);
return *it;
}
template<class RawShape>
static TPoint<RawShape> rightmostUpVertex(const RawShape& sh) {
// find min x and min y vertex
auto it = std::max_element(ShapeLike::cbegin(sh), ShapeLike::cend(sh),
_vsort<RawShape>);
return *it;
}
template<class RawShape>
static RawShape noFitPolygon(const RawShape& sh, const RawShape& other) {
auto isConvex = [](const RawShape& sh) {
return true;
};
using Vertex = TPoint<RawShape>;
using Edge = _Segment<Vertex>;
auto nfpConvexConvex = [] (
const RawShape& sh,
const RawShape& cother)
{
RawShape other = cother;
// Make the other polygon counter-clockwise
std::reverse(ShapeLike::begin(other), ShapeLike::end(other));
RawShape rsh; // Final nfp placeholder
std::vector<Edge> edgelist;
auto cap = ShapeLike::contourVertexCount(sh) +
ShapeLike::contourVertexCount(other);
// Reserve the needed memory
edgelist.reserve(cap);
ShapeLike::reserve(rsh, static_cast<unsigned long>(cap));
{ // place all edges from sh into edgelist
auto first = ShapeLike::cbegin(sh);
auto next = first + 1;
auto endit = ShapeLike::cend(sh);
while(next != endit) edgelist.emplace_back(*(first++), *(next++));
}
{ // place all edges from other into edgelist
auto first = ShapeLike::cbegin(other);
auto next = first + 1;
auto endit = ShapeLike::cend(other);
while(next != endit) edgelist.emplace_back(*(first++), *(next++));
}
// Sort the edges by angle to X axis.
std::sort(edgelist.begin(), edgelist.end(),
[](const Edge& e1, const Edge& e2)
{
return e1.angleToXaxis() > e2.angleToXaxis();
});
// Add the two vertices from the first edge into the final polygon.
ShapeLike::addVertex(rsh, edgelist.front().first());
ShapeLike::addVertex(rsh, edgelist.front().second());
auto tmp = std::next(ShapeLike::begin(rsh));
// Construct final nfp by placing each edge to the end of the previous
for(auto eit = std::next(edgelist.begin());
eit != edgelist.end();
++eit)
{
auto d = *tmp - eit->first();
auto p = eit->second() + d;
ShapeLike::addVertex(rsh, p);
tmp = std::next(tmp);
}
// Now we have an nfp somewhere in the dark. We need to get it
// to the right position around the stationary shape.
// This is done by choosing the leftmost lowest vertex of the
// orbiting polygon to be touched with the rightmost upper
// vertex of the stationary polygon. In this configuration, the
// reference vertex of the orbiting polygon (which can be dragged around
// the nfp) will be its rightmost upper vertex that coincides with the
// rightmost upper vertex of the nfp. No proof provided other than Jonas
// Lindmark's reasoning about the reference vertex of nfp in his thesis
// ("No fit polygon problem" - section 2.1.9)
auto csh = sh; // Copy sh, we will sort the verices in the copy
auto& cmp = _vsort<RawShape>;
std::sort(ShapeLike::begin(csh), ShapeLike::end(csh), cmp);
std::sort(ShapeLike::begin(other), ShapeLike::end(other), cmp);
// leftmost lower vertex of the stationary polygon
auto& touch_sh = *(std::prev(ShapeLike::end(csh)));
// rightmost upper vertex of the orbiting polygon
auto& touch_other = *(ShapeLike::begin(other));
// Calculate the difference and move the orbiter to the touch position.
auto dtouch = touch_sh - touch_other;
auto top_other = *(std::prev(ShapeLike::end(other))) + dtouch;
// Get the righmost upper vertex of the nfp and move it to the RMU of
// the orbiter because they should coincide.
auto&& top_nfp = rightmostUpVertex(rsh);
auto dnfp = top_other - top_nfp;
std::for_each(ShapeLike::begin(rsh), ShapeLike::end(rsh),
[&dnfp](Vertex& v) { v+= dnfp; } );
return rsh;
};
RawShape rsh;
enum e_dispatch {
CONVEX_CONVEX,
CONCAVE_CONVEX,
CONVEX_CONCAVE,
CONCAVE_CONCAVE
};
int sel = isConvex(sh) ? CONVEX_CONVEX : CONCAVE_CONVEX;
sel += isConvex(other) ? CONVEX_CONVEX : CONVEX_CONCAVE;
switch(sel) {
case CONVEX_CONVEX:
rsh = nfpConvexConvex(sh, other); break;
case CONCAVE_CONVEX:
break;
case CONVEX_CONCAVE:
break;
case CONCAVE_CONCAVE:
break;
}
return rsh;
}
template<class RawShape>
static inline Shapes<RawShape> noFitPolygon(const Shapes<RawShape>& shapes,
const RawShape& other)
{
assert(shapes.size() >= 1);
auto shit = shapes.begin();
Shapes<RawShape> ret;
ret.emplace_back(noFitPolygon(*shit, other));
while(++shit != shapes.end()) ret = merge(ret, noFitPolygon(*shit, other));
return ret;
}
private:
// Do not specialize this...
template<class RawShape>
static inline bool _vsort(const TPoint<RawShape>& v1,
const TPoint<RawShape>& v2)
{
using Coord = TCoord<TPoint<RawShape>>;
Coord &&x1 = getX(v1), &&x2 = getX(v2), &&y1 = getY(v1), &&y2 = getY(v2);
auto diff = y1 - y2;
if(std::abs(diff) <= std::numeric_limits<Coord>::epsilon())
return x1 < x2;
return diff < 0;
}
};
}
#endif // GEOMETRIES_NOFITPOLYGON_HPP

View File

@ -328,23 +328,37 @@ enum class Formats {
SVG
};
// This struct serves as a namespace. The only difference is that is can be
// This struct serves as a namespace. The only difference is that it can be
// used in friend declarations.
struct ShapeLike {
template<class RawShape>
using Shapes = std::vector<RawShape>;
template<class RawShape>
static RawShape create(const TContour<RawShape>& contour,
const THolesContainer<RawShape>& holes)
{
return RawShape(contour, holes);
}
template<class RawShape>
static RawShape create(TContour<RawShape>&& contour,
THolesContainer<RawShape>&& holes)
{
return RawShape(contour, holes);
}
template<class RawShape>
static RawShape create(const TContour<RawShape>& contour)
{
return RawShape(contour);
return create<RawShape>(contour, {});
}
template<class RawShape>
static RawShape create(TContour<RawShape>&& contour)
{
return RawShape(contour);
return create<RawShape>(contour, {});
}
// Optional, does nothing by default
@ -551,10 +565,44 @@ struct ShapeLike {
}
template<class RawShape>
static std::pair<bool, std::string> isValid(const RawShape& /*sh*/) {
static std::pair<bool, std::string> isValid(const RawShape& /*sh*/)
{
return {false, "ShapeLike::isValid() unimplemented!"};
}
template<class RawShape>
static 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
// *************************************************************************

View File

@ -0,0 +1,258 @@
#ifndef GEOMETRIES_NOFITPOLYGON_HPP
#define GEOMETRIES_NOFITPOLYGON_HPP
#include "geometry_traits.hpp"
#include <algorithm>
#include <vector>
namespace libnest2d {
/// The complexity level of a polygon that an NFP implementation can handle.
enum class NfpLevel: unsigned {
CONVEX_ONLY,
ONE_CONVEX,
BOTH_CONCAVE,
ONE_CONVEX_WITH_HOLES,
BOTH_CONCAVE_WITH_HOLES
};
/// A collection of static methods for handling the no fit polygon creation.
struct Nfp {
// Shorthand for a pile of polygons
template<class RawShape>
using Shapes = typename ShapeLike::Shapes<RawShape>;
/// Minkowski addition (not used yet)
template<class RawShape>
static RawShape minkowskiDiff(const RawShape& sh, const RawShape& /*other*/)
{
return sh;
}
/**
* Merge a bunch of polygons with the specified additional polygon.
*
* \tparam RawShape the Polygon data type.
* \param shc The pile of polygons that will be unified with sh.
* \param sh A single polygon to unify with shc.
*
* \return A set of polygons that is the union of the input polygons. Note that
* mostly it will be a set containing only one big polygon but if the input
* polygons are disjuct than the resulting set will contain more polygons.
*/
template<class RawShape>
static Shapes<RawShape> merge(const Shapes<RawShape>& shc, const RawShape& sh)
{
static_assert(always_false<RawShape>::value,
"Nfp::merge(shapes, shape) unimplemented!");
}
/**
* A method to get a vertex from a polygon that always maintains a relative
* position to the coordinate system: It is always the rightmost top vertex.
*
* This way it does not matter in what order the vertices are stored, the
* reference will be always the same for the same polygon.
*/
template<class RawShape>
inline static TPoint<RawShape> referenceVertex(const RawShape& sh)
{
return rightmostUpVertex(sh);
}
/**
* Get the vertex of the polygon that is at the lowest values (bottom) in the Y
* axis and if there are more than one vertices on the same Y coordinate than
* the result will be the leftmost (with the highest X coordinate).
*/
template<class RawShape>
static TPoint<RawShape> leftmostDownVertex(const RawShape& sh)
{
// find min x and min y vertex
auto it = std::min_element(ShapeLike::cbegin(sh), ShapeLike::cend(sh),
_vsort<RawShape>);
return *it;
}
/**
* Get the vertex of the polygon that is at the highest values (top) in the Y
* axis and if there are more than one vertices on the same Y coordinate than
* the result will be the rightmost (with the lowest X coordinate).
*/
template<class RawShape>
static TPoint<RawShape> rightmostUpVertex(const RawShape& sh)
{
// find min x and min y vertex
auto it = std::max_element(ShapeLike::cbegin(sh), ShapeLike::cend(sh),
_vsort<RawShape>);
return *it;
}
/// Helper function to get the NFP
template<NfpLevel nfptype, class RawShape>
static RawShape noFitPolygon(const RawShape& sh, const RawShape& other)
{
NfpImpl<RawShape, nfptype> nfp;
return nfp(sh, other);
}
/**
* The "trivial" Cuninghame-Green implementation of NFP for convex polygons.
*
* You can use this even if you provide implementations for the more complex
* cases (Through specializing the the NfpImpl struct). Currently, no other
* cases are covered in the library.
*
* Complexity should be no more than linear in the number of edges of the input
* polygons.
*
* \tparam RawShape the Polygon data type.
* \param sh The stationary polygon
* \param cother The orbiting polygon
* \return Returns the NFP of the two input polygons which have to be strictly
* convex. The resulting NFP is proven to be convex as well in this case.
*
*/
template<class RawShape>
static RawShape nfpConvexOnly(const RawShape& sh, const RawShape& cother)
{
using Vertex = TPoint<RawShape>; using Edge = _Segment<Vertex>;
RawShape other = cother;
// Make the other polygon counter-clockwise
std::reverse(ShapeLike::begin(other), ShapeLike::end(other));
RawShape rsh; // Final nfp placeholder
std::vector<Edge> edgelist;
auto cap = ShapeLike::contourVertexCount(sh) +
ShapeLike::contourVertexCount(other);
// Reserve the needed memory
edgelist.reserve(cap);
ShapeLike::reserve(rsh, static_cast<unsigned long>(cap));
{ // place all edges from sh into edgelist
auto first = ShapeLike::cbegin(sh);
auto next = first + 1;
auto endit = ShapeLike::cend(sh);
while(next != endit) edgelist.emplace_back(*(first++), *(next++));
}
{ // place all edges from other into edgelist
auto first = ShapeLike::cbegin(other);
auto next = first + 1;
auto endit = ShapeLike::cend(other);
while(next != endit) edgelist.emplace_back(*(first++), *(next++));
}
// Sort the edges by angle to X axis.
std::sort(edgelist.begin(), edgelist.end(),
[](const Edge& e1, const Edge& e2)
{
return e1.angleToXaxis() > e2.angleToXaxis();
});
// Add the two vertices from the first edge into the final polygon.
ShapeLike::addVertex(rsh, edgelist.front().first());
ShapeLike::addVertex(rsh, edgelist.front().second());
auto tmp = std::next(ShapeLike::begin(rsh));
// Construct final nfp by placing each edge to the end of the previous
for(auto eit = std::next(edgelist.begin());
eit != edgelist.end();
++eit)
{
auto d = *tmp - eit->first();
auto p = eit->second() + d;
ShapeLike::addVertex(rsh, p);
tmp = std::next(tmp);
}
// Now we have an nfp somewhere in the dark. We need to get it
// to the right position around the stationary shape.
// This is done by choosing the leftmost lowest vertex of the
// orbiting polygon to be touched with the rightmost upper
// vertex of the stationary polygon. In this configuration, the
// reference vertex of the orbiting polygon (which can be dragged around
// the nfp) will be its rightmost upper vertex that coincides with the
// rightmost upper vertex of the nfp. No proof provided other than Jonas
// Lindmark's reasoning about the reference vertex of nfp in his thesis
// ("No fit polygon problem" - section 2.1.9)
auto csh = sh; // Copy sh, we will sort the verices in the copy
auto& cmp = _vsort<RawShape>;
std::sort(ShapeLike::begin(csh), ShapeLike::end(csh), cmp);
std::sort(ShapeLike::begin(other), ShapeLike::end(other), cmp);
// leftmost lower vertex of the stationary polygon
auto& touch_sh = *(std::prev(ShapeLike::end(csh)));
// rightmost upper vertex of the orbiting polygon
auto& touch_other = *(ShapeLike::begin(other));
// Calculate the difference and move the orbiter to the touch position.
auto dtouch = touch_sh - touch_other;
auto top_other = *(std::prev(ShapeLike::end(other))) + dtouch;
// Get the righmost upper vertex of the nfp and move it to the RMU of
// the orbiter because they should coincide.
auto&& top_nfp = rightmostUpVertex(rsh);
auto dnfp = top_other - top_nfp;
std::for_each(ShapeLike::begin(rsh), ShapeLike::end(rsh),
[&dnfp](Vertex& v) { v+= dnfp; } );
return rsh;
}
// Specializable NFP implementation class. Specialize it if you have a faster
// or better NFP implementation
template<class RawShape, NfpLevel nfptype>
struct NfpImpl {
RawShape operator()(const RawShape& sh, const RawShape& other) {
static_assert(nfptype == NfpLevel::CONVEX_ONLY,
"Nfp::noFitPolygon() unimplemented!");
// Libnest2D has a default implementation for convex polygons and will
// use it if feasible.
return nfpConvexOnly(sh, other);
}
};
template<class RawShape> struct MaxNfpLevel {
static const BP2D_CONSTEXPR NfpLevel value = NfpLevel::CONVEX_ONLY;
};
private:
// Do not specialize this...
template<class RawShape>
static inline bool _vsort(const TPoint<RawShape>& v1,
const TPoint<RawShape>& v2)
{
using Coord = TCoord<TPoint<RawShape>>;
Coord &&x1 = getX(v1), &&x2 = getX(v2), &&y1 = getY(v1), &&y2 = getY(v2);
auto diff = y1 - y2;
if(std::abs(diff) <= std::numeric_limits<Coord>::epsilon())
return x1 < x2;
return diff < 0;
}
};
}
#endif // GEOMETRIES_NOFITPOLYGON_HPP

View File

@ -9,9 +9,6 @@
#include <functional>
#include "geometry_traits.hpp"
//#include "optimizers/subplex.hpp"
//#include "optimizers/simplex.hpp"
#include "optimizers/genetic.hpp"
namespace libnest2d {
@ -52,6 +49,14 @@ class _Item {
mutable RawShape offset_cache_;
mutable bool offset_cache_valid_ = false;
enum class Convexity: char {
UNCHECKED,
TRUE,
FALSE
};
mutable Convexity convexity_ = Convexity::UNCHECKED;
public:
/// The type of the shape which was handed over as the template argument.
@ -101,11 +106,14 @@ public:
inline _Item(const std::initializer_list< Vertex >& il):
sh_(ShapeLike::create<RawShape>(il)) {}
inline _Item(const TContour<RawShape>& contour):
sh_(ShapeLike::create<RawShape>(contour)) {}
inline _Item(const TContour<RawShape>& contour,
const THolesContainer<RawShape>& holes = {}):
sh_(ShapeLike::create<RawShape>(contour, holes)) {}
inline _Item(TContour<RawShape>&& contour):
sh_(ShapeLike::create<RawShape>(std::move(contour))) {}
inline _Item(TContour<RawShape>&& contour,
THolesContainer<RawShape>&& holes):
sh_(ShapeLike::create<RawShape>(std::move(contour),
std::move(holes))) {}
/**
* @brief Convert the polygon to string representation. The format depends
@ -117,7 +125,7 @@ public:
return ShapeLike::toString(sh_);
}
/// Iterator tho the first vertex in the polygon.
/// Iterator tho the first contour vertex in the polygon.
inline Iterator begin() const
{
return ShapeLike::cbegin(sh_);
@ -129,7 +137,7 @@ public:
return ShapeLike::cbegin(sh_);
}
/// Iterator to the last element.
/// Iterator to the last contour vertex.
inline Iterator end() const
{
return ShapeLike::cend(sh_);
@ -165,8 +173,7 @@ public:
* @param idx The index of the requested vertex.
* @param v The new vertex data.
*/
inline void setVertex(unsigned long idx,
const Vertex& v )
inline void setVertex(unsigned long idx, const Vertex& v )
{
invalidateCache();
ShapeLike::vertex(sh_, idx) = v;
@ -191,11 +198,38 @@ public:
return ret;
}
inline bool isContourConvex() const {
bool ret = false;
switch(convexity_) {
case Convexity::UNCHECKED:
ret = ShapeLike::isConvex<RawShape>(ShapeLike::getContour(transformedShape()));
convexity_ = ret? Convexity::TRUE : Convexity::FALSE;
break;
case Convexity::TRUE: ret = true; break;
case Convexity::FALSE:;
}
return ret;
}
inline bool isHoleConvex(unsigned holeidx) const {
return false;
}
inline bool areHolesConvex() const {
return false;
}
/// The number of the outer ring vertices.
inline size_t vertexCount() const {
return ShapeLike::contourVertexCount(sh_);
}
inline size_t holeCount() const {
return ShapeLike::holeCount(sh_);
}
/**
* @brief isPointInside
* @param p
@ -262,7 +296,7 @@ public:
}
}
inline RawShape transformedShape() const
inline const RawShape& transformedShape() const
{
if(tr_cache_valid_) return tr_cache_;
@ -271,7 +305,7 @@ public:
if(has_translation_) ShapeLike::translate(cpy, translation_);
tr_cache_ = cpy; tr_cache_valid_ = true;
return cpy;
return tr_cache_;
}
inline operator RawShape() const
@ -327,6 +361,7 @@ private:
tr_cache_valid_ = false;
area_cache_valid_ = false;
offset_cache_valid_ = false;
convexity_ = Convexity::UNCHECKED;
}
};

View File

@ -5,9 +5,7 @@
#include <iostream>
#endif
#include "placer_boilerplate.hpp"
#include "../geometries_nfp.hpp"
#include <libnest2d/optimizers/subplex.hpp>
//#include <libnest2d/optimizers/genetic.hpp>
#include "../geometry_traits_nfp.hpp"
namespace libnest2d { namespace strategies {
@ -41,13 +39,13 @@ template<class RawShape> class EdgeCache {
using Coord = TCoord<Vertex>;
using Edge = _Segment<Vertex>;
enum Corners {
BOTTOM,
LEFT,
RIGHT,
TOP,
NUM_CORNERS
};
// enum Corners {
// BOTTOM,
// LEFT,
// RIGHT,
// TOP,
// NUM_CORNERS
// };
mutable std::vector<double> corners_;
@ -72,43 +70,49 @@ template<class RawShape> class EdgeCache {
void fetchCorners() const {
if(!corners_.empty()) return;
corners_ = std::vector<double>(NUM_CORNERS, 0.0);
corners_ = distances_;
for(auto& d : corners_) {
d /= full_distance_;
}
std::vector<unsigned> idx_ud(emap_.size(), 0);
std::vector<unsigned> idx_lr(emap_.size(), 0);
// corners_ = std::vector<double>(NUM_CORNERS, 0.0);
std::iota(idx_ud.begin(), idx_ud.end(), 0);
std::iota(idx_lr.begin(), idx_lr.end(), 0);
// std::vector<unsigned> idx_ud(emap_.size(), 0);
// std::vector<unsigned> idx_lr(emap_.size(), 0);
std::sort(idx_ud.begin(), idx_ud.end(),
[this](unsigned idx1, unsigned idx2)
{
const Vertex& v1 = emap_[idx1].first();
const Vertex& v2 = emap_[idx2].first();
auto diff = getY(v1) - getY(v2);
if(std::abs(diff) <= std::numeric_limits<Coord>::epsilon())
return getX(v1) < getX(v2);
// std::iota(idx_ud.begin(), idx_ud.end(), 0);
// std::iota(idx_lr.begin(), idx_lr.end(), 0);
return diff < 0;
});
// std::sort(idx_ud.begin(), idx_ud.end(),
// [this](unsigned idx1, unsigned idx2)
// {
// const Vertex& v1 = emap_[idx1].first();
// const Vertex& v2 = emap_[idx2].first();
std::sort(idx_lr.begin(), idx_lr.end(),
[this](unsigned idx1, unsigned idx2)
{
const Vertex& v1 = emap_[idx1].first();
const Vertex& v2 = emap_[idx2].first();
// auto diff = getY(v1) - getY(v2);
// if(std::abs(diff) <= std::numeric_limits<Coord>::epsilon())
// return getX(v1) < getX(v2);
auto diff = getX(v1) - getX(v2);
if(std::abs(diff) <= std::numeric_limits<Coord>::epsilon())
return getY(v1) < getY(v2);
// return diff < 0;
// });
return diff < 0;
});
// std::sort(idx_lr.begin(), idx_lr.end(),
// [this](unsigned idx1, unsigned idx2)
// {
// const Vertex& v1 = emap_[idx1].first();
// const Vertex& v2 = emap_[idx2].first();
corners_[BOTTOM] = distances_[idx_ud.front()]/full_distance_;
corners_[TOP] = distances_[idx_ud.back()]/full_distance_;
corners_[LEFT] = distances_[idx_lr.front()]/full_distance_;
corners_[RIGHT] = distances_[idx_lr.back()]/full_distance_;
// auto diff = getX(v1) - getX(v2);
// if(std::abs(diff) <= std::numeric_limits<Coord>::epsilon())
// return getY(v1) < getY(v2);
// return diff < 0;
// });
// corners_[BOTTOM] = distances_[idx_ud.front()]/full_distance_;
// corners_[TOP] = distances_[idx_ud.back()]/full_distance_;
// corners_[LEFT] = distances_[idx_lr.front()]/full_distance_;
// corners_[RIGHT] = distances_[idx_lr.back()]/full_distance_;
}
public:
@ -163,11 +167,11 @@ public:
inline double circumference() const BP2D_NOEXCEPT { return full_distance_; }
inline double corner(Corners c) const BP2D_NOEXCEPT {
assert(c < NUM_CORNERS);
fetchCorners();
return corners_[c];
}
// inline double corner(Corners c) const BP2D_NOEXCEPT {
// assert(c < NUM_CORNERS);
// fetchCorners();
// return corners_[c];
// }
inline const std::vector<double>& corners() const BP2D_NOEXCEPT {
fetchCorners();
@ -176,18 +180,21 @@ public:
};
// Nfp for a bunch of polygons. If the polygons are convex, the nfp calculated
// for trsh can be the union of nfp-s calculated with each polygon
template<NfpLevel lvl>
struct Lvl { static const NfpLevel value = lvl; };
template<class RawShape, class Container>
Nfp::Shapes<RawShape> nfp(const Container& polygons, const RawShape& trsh )
Nfp::Shapes<RawShape> nfp( const Container& polygons,
const _Item<RawShape>& trsh,
Lvl<NfpLevel::CONVEX_ONLY>)
{
using Item = _Item<RawShape>;
Nfp::Shapes<RawShape> nfps;
for(Item& sh : polygons) {
auto subnfp = Nfp::noFitPolygon(sh.transformedShape(),
trsh);
auto subnfp = Nfp::noFitPolygon<NfpLevel::CONVEX_ONLY>(
sh.transformedShape(), trsh.transformedShape());
#ifndef NDEBUG
auto vv = ShapeLike::isValid(sh.transformedShape());
assert(vv.first);
@ -202,6 +209,51 @@ Nfp::Shapes<RawShape> nfp(const Container& polygons, const RawShape& trsh )
return nfps;
}
template<class RawShape, class Container, class Level>
Nfp::Shapes<RawShape> nfp( const Container& polygons,
const _Item<RawShape>& trsh,
Level)
{
using Item = _Item<RawShape>;
Nfp::Shapes<RawShape> nfps, stationary;
for(Item& sh : polygons) {
stationary = Nfp::merge(stationary, sh.transformedShape());
}
std::cout << "pile size: " << stationary.size() << std::endl;
for(RawShape& sh : stationary) {
RawShape subnfp;
// if(sh.isContourConvex() && trsh.isContourConvex()) {
// subnfp = Nfp::noFitPolygon<NfpLevel::CONVEX_ONLY>(
// sh.transformedShape(), trsh.transformedShape());
// } else {
subnfp = Nfp::noFitPolygon<Level::value>( sh/*.transformedShape()*/,
trsh.transformedShape());
// }
// #ifndef NDEBUG
// auto vv = ShapeLike::isValid(sh.transformedShape());
// assert(vv.first);
// auto vnfp = ShapeLike::isValid(subnfp);
// assert(vnfp.first);
// #endif
// auto vnfp = ShapeLike::isValid(subnfp);
// if(!vnfp.first) {
// std::cout << vnfp.second << std::endl;
// std::cout << ShapeLike::toString(subnfp) << std::endl;
// }
nfps = Nfp::merge(nfps, subnfp);
}
return nfps;
}
template<class RawShape>
class _NofitPolyPlacer: public PlacerBoilerplate<_NofitPolyPlacer<RawShape>,
RawShape, _Box<TPoint<RawShape>>, NfpPConfig<RawShape>> {
@ -216,6 +268,8 @@ class _NofitPolyPlacer: public PlacerBoilerplate<_NofitPolyPlacer<RawShape>,
const double norm_;
const double penality_;
using MaxNfpLevel = Nfp::MaxNfpLevel<RawShape>;
public:
using Pile = const Nfp::Shapes<RawShape>&;
@ -275,7 +329,7 @@ public:
auto trsh = item.transformedShape();
nfps = nfp(items_, trsh);
nfps = nfp(items_, item, Lvl<MaxNfpLevel::value>());
auto iv = Nfp::referenceVertex(trsh);
auto startpos = item.translation();
@ -348,7 +402,7 @@ public:
stopcr.max_iterations = 1000;
stopcr.stoplimit = 0.01;
stopcr.type = opt::StopLimitType::RELATIVE;
opt::TOptimizer<opt::Method::L_SUBPLEX> solver(stopcr);
opt::TOptimizer<opt::Method::L_SIMPLEX> solver(stopcr);
double optimum = 0;
double best_score = penality_;
@ -386,14 +440,8 @@ public:
best_score = result.score;
optimum = std::get<0>(result.optimum);
}
} catch(std::exception&
#ifndef NDEBUG
e
#endif
) {
#ifndef NDEBUG
std::cerr << "ERROR " << e.what() << std::endl;
#endif
} catch(std::exception& e) {
derr() << "ERROR: " << e.what() << "\n";
}
});
}
@ -420,6 +468,10 @@ public:
}
~_NofitPolyPlacer() {
clearItems();
}
inline void clearItems() {
Nfp::Shapes<RawShape> m;
m.reserve(items_.size());
@ -458,6 +510,8 @@ public:
auto d = cb - ci;
for(Item& item : items_) item.translate(d);
Base::clearItems();
}
private:

View File

@ -180,6 +180,29 @@ public:
});
};
using ItemListIt = typename ItemList::iterator;
auto largestPiece = [](ItemListIt it, ItemList& not_packed) {
return it == not_packed.begin()? std::next(it) : not_packed.begin();
};
auto secondLargestPiece = [&largestPiece](ItemListIt it,
ItemList& not_packed) {
auto ret = std::next(largestPiece(it, not_packed));
return ret == it? std::next(ret) : ret;
};
auto smallestPiece = [](ItemListIt it, ItemList& not_packed) {
auto last = std::prev(not_packed.end());
return it == last? std::prev(it) : last;
};
auto secondSmallestPiece = [&smallestPiece](ItemListIt it,
ItemList& not_packed) {
auto ret = std::prev(smallestPiece(it, not_packed));
return ret == it? std::prev(ret) : ret;
};
auto tryOneByOne = // Subroutine to try adding items one by one.
[&bin_area]
(Placer& placer, ItemList& not_packed,
@ -208,31 +231,25 @@ public:
};
auto tryGroupsOfTwo = // Try adding groups of two items into the bin.
[&bin_area, &check_pair,
[&bin_area, &check_pair, &largestPiece, &smallestPiece,
try_reverse]
(Placer& placer, ItemList& not_packed,
double waste,
double& free_area,
double& filled_area)
{
double item_area = 0, largest_area = 0, smallest_area = 0;
double second_largest = 0, second_smallest = 0;
double item_area = 0;
const auto endit = not_packed.end();
if(not_packed.size() < 2)
return false; // No group of two items
else {
largest_area = not_packed.front().get().area();
double largest_area = not_packed.front().get().area();
auto itmp = not_packed.begin(); itmp++;
second_largest = itmp->get().area();
double second_largest = itmp->get().area();
if( free_area - second_largest - largest_area > waste)
return false; // If even the largest two items do not fill
// the bin to the desired waste than we can end here.
smallest_area = not_packed.back().get().area();
itmp = endit; std::advance(itmp, -2);
second_smallest = itmp->get().area();
}
bool ret = false;
@ -241,17 +258,12 @@ public:
std::vector<TPair> wrong_pairs;
double largest = second_largest;
double smallest= smallest_area;
while(it != endit && !ret && free_area -
(item_area = it->get().area()) - largest <= waste )
while(it != endit && !ret &&
free_area - (item_area = it->get().area()) -
largestPiece(it, not_packed)->get().area() <= waste)
{
// if this is the last element, the next smallest is the
// previous item
auto itmp = it; std::advance(itmp, 1);
if(itmp == endit) smallest = second_smallest;
if(item_area + smallest > free_area ) { it++; continue; }
if(item_area + smallestPiece(it, not_packed)->get().area() >
free_area ) { it++; continue; }
auto pr = placer.trypack(*it);
@ -300,8 +312,6 @@ public:
}
if(!ret) it++;
largest = largest_area;
}
if(ret) { not_packed.erase(it); not_packed.erase(it2); }
@ -311,6 +321,8 @@ public:
auto tryGroupsOfThree = // Try adding groups of three items.
[&bin_area,
&smallestPiece, &largestPiece,
&secondSmallestPiece, &secondLargestPiece,
&check_pair, &check_triplet, try_reverse]
(Placer& placer, ItemList& not_packed,
double waste,
@ -341,11 +353,8 @@ public:
// We need to determine in each iteration the largest, second
// largest, smallest and second smallest item in terms of area.
auto first = not_packed.begin();
Item& largest = it == first? *std::next(it) : *first;
auto second = std::next(first);
Item& second_largest = it == second ? *std::next(it) : *second;
Item& largest = *largestPiece(it, not_packed);
Item& second_largest = *secondLargestPiece(it, not_packed);
double area_of_two_largest =
largest.area() + second_largest.area();
@ -356,23 +365,22 @@ public:
break;
// Determine the area of the two smallest item.
auto last = std::prev(endit);
Item& smallest = it == last? *std::prev(it) : *last;
auto second_last = std::prev(last);
Item& second_smallest = it == second_last? *std::prev(it) :
*second_last;
Item& smallest = *smallestPiece(it, not_packed);
Item& second_smallest = *secondSmallestPiece(it, not_packed);
// Check if there is enough free area for the item and the two
// smallest item.
double area_of_two_smallest =
smallest.area() + second_smallest.area();
if(it->get().area() + area_of_two_smallest > free_area) {
it++; continue;
}
auto pr = placer.trypack(*it);
// Check for free area and try to pack the 1st item...
if(!pr || it->get().area() + area_of_two_smallest > free_area) {
it++; continue;
}
if(!pr) { it++; continue; }
it2 = not_packed.begin();
double rem2_area = free_area - largest.area();
@ -434,6 +442,8 @@ public:
check_triplet(wrong_triplets, *it, *it2, *it3))
{ it3++; continue; }
if(a3_sum > free_area) { it3++; continue; }
placer.accept(pr12); placer.accept(pr2);
bool can_pack3 = placer.pack(*it3);
@ -558,13 +568,12 @@ public:
&makeProgress]
(Placer& placer, ItemList& not_packed, size_t idx)
{
bool can_pack = true;
double filled_area = placer.filledArea();
double free_area = bin_area - filled_area;
double waste = .0;
bool lasttry = false;
while(!not_packed.empty() && can_pack) {
while(!not_packed.empty() ) {
{// Fill the bin up to INITIAL_FILL_PROPORTION of its capacity
auto it = not_packed.begin();
@ -585,29 +594,31 @@ public:
// try pieses one by one
while(tryOneByOne(placer, not_packed, waste, free_area,
filled_area)) {
waste = 0;
if(lasttry) std::cout << "Lasttry monopack" << std::endl;
waste = 0; lasttry = false;
makeProgress(placer, idx, 1);
}
// try groups of 2 pieses
while(tryGroupsOfTwo(placer, not_packed, waste, free_area,
filled_area)) {
waste = 0;
if(lasttry) std::cout << "Lasttry bipack" << std::endl;
waste = 0; lasttry = false;
makeProgress(placer, idx, 2);
}
// try groups of 3 pieses
while(tryGroupsOfThree(placer, not_packed, waste, free_area,
filled_area)) {
waste = 0;
makeProgress(placer, idx, 3);
}
// // try groups of 3 pieses
// while(tryGroupsOfThree(placer, not_packed, waste, free_area,
// filled_area)) {
// if(lasttry) std::cout << "Lasttry tripack" << std::endl;
// waste = 0; lasttry = false;
// makeProgress(placer, idx, 3);
// }
if(waste < free_area) waste += w;
else if(!not_packed.empty()) can_pack = false;
waste += w;
if(!lasttry && waste > free_area) lasttry = true;
else if(lasttry) break;
}
return can_pack;
};
size_t idx = 0;
@ -633,7 +644,7 @@ public:
};
// We will create jobs for each bin
std::vector<std::future<bool>> rets(bincount_guess);
std::vector<std::future<void>> rets(bincount_guess);
for(unsigned b = 0; b < bincount_guess; b++) { // launch the jobs
rets[b] = std::async(std::launch::async, job, b);

View File

@ -32,17 +32,20 @@ public:
{
store_.clear();
store_.reserve(last-first);
auto total = last-first;
store_.reserve(total);
packed_bins_.emplace_back();
auto makeProgress = [this](PlacementStrategyLike<TPlacer>& placer) {
auto makeProgress = [this, &total](
PlacementStrategyLike<TPlacer>& placer)
{
packed_bins_.back() = placer.getItems();
#ifndef NDEBUG
packed_bins_.back().insert(packed_bins_.back().end(),
placer.getDebugItems().begin(),
placer.getDebugItems().end());
#endif
this->progress_(packed_bins_.back().size());
this->progress_(--total);
};
std::copy(first, last, std::back_inserter(store_));
@ -64,7 +67,7 @@ public:
while(it != store_.end()) {
if(!placer.pack(*it)) {
if(packed_bins_.back().empty()) ++it;
makeProgress(placer);
// makeProgress(placer);
placer.clearItems();
packed_bins_.emplace_back();
} else {

View File

@ -49,24 +49,28 @@ public:
std::sort(store_.begin(), store_.end(), sortfunc);
auto total = last-first;
auto makeProgress = [this, &total](Placer& placer, size_t idx) {
packed_bins_[idx] = placer.getItems();
this->progress_(--total);
};
for(auto& item : store_ ) {
bool was_packed = false;
while(!was_packed) {
for(size_t j = 0; j < placers.size() && !was_packed; j++)
was_packed = placers[j].pack(item);
for(size_t j = 0; j < placers.size() && !was_packed; j++) {
if(was_packed = placers[j].pack(item))
makeProgress(placers[j], j);
}
if(!was_packed) {
placers.emplace_back(bin);
placers.back().configure(pconfig);
packed_bins_.emplace_back();
}
}
}
std::for_each(placers.begin(), placers.end(),
[this](Placer& placer){
packed_bins_.push_back(placer.getItems());
});
}
};

View File

@ -35,13 +35,17 @@ else()
set(GTEST_LIBS_TO_LINK ${GTEST_BOTH_LIBRARIES} Threads::Threads)
endif()
add_executable(bp2d_tests test.cpp svgtools.hpp printer_parts.h printer_parts.cpp)
target_link_libraries(bp2d_tests libnest2d_static ${GTEST_LIBS_TO_LINK} )
add_executable(bp2d_tests test.cpp
../tools/svgtools.hpp
# ../tools/libnfpglue.hpp
# ../tools/libnfpglue.cpp
printer_parts.h
printer_parts.cpp
${LIBNEST2D_SRCFILES}
)
target_link_libraries(bp2d_tests ${LIBNEST2D_LIBRARIES} ${GTEST_LIBS_TO_LINK} )
target_include_directories(bp2d_tests PRIVATE BEFORE ${LIBNEST2D_HEADERS}
${GTEST_INCLUDE_DIRS})
if(DEFINED LIBNEST2D_TEST_LIBRARIES)
target_link_libraries(bp2d_tests ${LIBNEST2D_TEST_LIBRARIES})
endif()
add_test(libnest2d_tests bp2d_tests)

View File

@ -2523,3 +2523,653 @@ const TestData STEGOSAUR_POLYGONS =
{84531845, 127391708},
},
};
const TestDataEx PRINTER_PART_POLYGONS_EX =
{
{
{
{533726562, 142141690},
{532359712, 143386134},
{530141290, 142155145},
{528649729, 160091460},
{533659500, 157607547},
{538669739, 160091454},
{537178168, 142155145},
{534959534, 143386102},
{533726562, 142141690},
},
{
},
},
{
{
{118305840, 11603332},
{118311095, 26616786},
{113311095, 26611146},
{109311095, 29604752},
{109300760, 44608489},
{109311095, 49631801},
{113300790, 52636806},
{118311095, 52636806},
{118308782, 103636810},
{223830940, 103636981},
{236845321, 90642174},
{236832882, 11630488},
{232825251, 11616786},
{210149075, 11616786},
{211308596, 13625149},
{209315325, 17080886},
{205326885, 17080886},
{203334352, 13629720},
{204493136, 11616786},
{118305840, 11603332},
},
{
},
},
{
{
{365619370, 111280336},
{365609100, 198818091},
{387109100, 198804367},
{387109100, 203279701},
{471129120, 203279688},
{471128689, 111283937},
{365619370, 111280336},
},
{
},
},
{
{
{479997525, 19177632},
{477473010, 21975778},
{475272613, 21969219},
{475267479, 32995796},
{477026388, 32995796},
{483041428, 22582411},
{482560272, 20318630},
{479997525, 19177632},
},
{
},
},
{
{
{476809080, 4972372},
{475267479, 4975778},
{475272613, 16002357},
{481018177, 18281994},
{482638044, 15466085},
{476809080, 4972372},
},
{
},
},
{
{
{424866064, 10276075},
{415113411, 10277960},
{411723180, 13685293},
{410473354, 18784347},
{382490868, 18784008},
{380996185, 17286945},
{380996185, 11278161},
{375976165, 11284347},
{375976165, 56389754},
{375169018, 57784347},
{371996185, 57784347},
{371996185, 53779177},
{364976165, 53784347},
{364969637, 56791976},
{369214608, 61054367},
{371474507, 61054367},
{371473155, 98298160},
{378476349, 105317193},
{407491306, 105307497},
{413509785, 99284903},
{413496185, 48304367},
{419496173, 48315719},
{422501887, 45292801},
{422500504, 39363184},
{420425079, 37284347},
{419476165, 43284347},
{413496185, 43284347},
{413497261, 30797428},
{418986175, 25308513},
{424005230, 25315076},
{428496185, 20815924},
{428512720, 13948847},
{424866064, 10276075},
},
{
},
},
{
{
{723893066, 37354349},
{717673034, 37370791},
{717673034, 44872138},
{715673034, 44867768},
{715673034, 46055353},
{699219526, 40066777},
{697880758, 37748547},
{691985477, 37748293},
{689014018, 42869257},
{691985477, 48016003},
{697575093, 48003007},
{715671494, 54589493},
{715656800, 87142158},
{759954611, 87142158},
{764193054, 82897328},
{764193054, 79872138},
{757173034, 79866968},
{757173034, 83872138},
{754419422, 83869509},
{753193054, 81739327},
{753193054, 37360571},
{723893066, 37354349},
},
{
},
},
{
{
{85607478, 4227596},
{61739211, 4230337},
{61739211, 13231393},
{58725066, 13231405},
{58721589, 27731406},
{58738375, 30262521},
{61739211, 30251413},
{61736212, 38251411},
{70759231, 38254724},
{70905600, 33317391},
{73749222, 31251468},
{76592843, 33317393},
{76739211, 38254516},
{86765007, 38251411},
{86759599, 4231393},
{85607478, 4227596},
},
{
},
},
{
{
{534839721, 53437770},
{534839721, 60849059},
{539898273, 63773857},
{545461140, 63757881},
{544859741, 53447836},
{541839721, 53437862},
{541710836, 56353878},
{540193984, 57229659},
{538859741, 53437862},
{534839721, 53437770},
},
{
},
},
{
{
{756086230, 136598477},
{732054387, 136605752},
{732052489, 172629505},
{756091994, 172627853},
{756086230, 136598477},
},
{
},
},
{
{
{100337034, 79731391},
{70296833, 79731391},
{70311095, 92263567},
{74329808, 96264260},
{96344976, 96257215},
{100344419, 92232243},
{100337034, 79731391},
},
{
},
},
{
{
{102331115, 44216643},
{67311095, 44217252},
{67311095, 69250964},
{74329808, 76264260},
{96334594, 76251411},
{103335261, 69241401},
{103345839, 44231404},
{102331115, 44216643},
},
{
},
},
{
{
{93849749, 109613798},
{91771666, 111698636},
{91772404, 174626800},
{96782902, 179645338},
{241790509, 179645349},
{246800716, 174626800},
{246802574, 111699755},
{243934250, 109616385},
{93849749, 109613798},
},
{
},
},
{
{
{15856630, 87966835},
{8414359, 91273170},
{5891847, 99010553},
{8403012, 104668172},
{13739106, 107763252},
{13739106, 116209175},
{17959116, 116219127},
{17959127, 107763252},
{23952579, 103855773},
{25806388, 96944174},
{22553953, 90543787},
{15856630, 87966835},
},
{
},
},
{
{
{503922805, 110421794},
{491110107, 123244292},
{479598157, 123244304},
{479601067, 149264312},
{494260327, 149265241},
{502929782, 157948320},
{506490250, 155806171},
{502950518, 155094962},
{507193172, 150852294},
{504364680, 148023895},
{535816833, 116571757},
{538656617, 119411542},
{542887886, 115157558},
{543594970, 118693080},
{545330008, 116966050},
{540309189, 110425901},
{503922805, 110421794},
},
{
},
},
{
{
{519310433, 62560296},
{515749982, 64702434},
{519289696, 65413661},
{515047062, 69656303},
{517875553, 72484703},
{486423431, 103936848},
{483595031, 101108448},
{479352325, 105351055},
{478645233, 101815525},
{476917724, 103520870},
{481923478, 110077233},
{518337308, 110084297},
{531130127, 97264312},
{542630127, 97281049},
{542639167, 71244292},
{527979906, 71243363},
{519310433, 62560296},
},
{
},
},
{
{
{528658425, 14775300},
{525975568, 24475413},
{522556814, 29181341},
{517517474, 32090757},
{511736147, 32698600},
{506200465, 30901018},
{501879743, 27011092},
{497782491, 14775300},
{492372374, 15588397},
{489384268, 20795320},
{491253082, 28537271},
{495185363, 34469052},
{495178475, 43927542},
{502032399, 55796416},
{524402581, 55807400},
{531706434, 44295318},
{531205383, 34469052},
{536679415, 23789946},
{535868173, 17264403},
{532873348, 15073849},
{528658425, 14775300},
},
{
},
},
{
{
{481122222, 166062916},
{478115710, 166824472},
{477103577, 169063247},
{477106058, 192070670},
{478623652, 194687013},
{525109130, 195083267},
{525117792, 198086965},
{535129140, 198091624},
{535129150, 195083267},
{539038502, 194940807},
{540865280, 193308821},
{541132038, 169100183},
{539614599, 166459484},
{481122222, 166062916},
},
{
},
},
{
{
{23771404, 13005453},
{24774973, 19182457},
{31971050, 18727127},
{32556286, 58337520},
{25390683, 58337566},
{25063762, 54707065},
{20168811, 54707252},
{20171550, 62917175},
{70810377, 202895528},
{74314421, 205588631},
{88674817, 205515176},
{91837376, 203083756},
{92280287, 199307207},
{40674807, 15904975},
{36849630, 13006690},
{23771404, 13005453},
},
{
},
},
{
{
{336421201, 2986256},
{331176570, 6498191},
{327552287, 5825511},
{324913825, 2988891},
{316226154, 2989990},
{313040282, 6275291},
{313040282, 23489990},
{307126391, 23490002},
{307140289, 25510010},
{313040282, 25510010},
{313040282, 28989990},
{307126391, 28990002},
{307140289, 31015515},
{313040282, 31010010},
{313040282, 35989990},
{304534809, 37529785},
{304524991, 73488855},
{308554680, 77518546},
{324040282, 77510010},
{324040295, 93025333},
{334574441, 93010010},
{334574441, 90989990},
{332560302, 90989990},
{332560302, 85010010},
{334560302, 85010010},
{334561237, 82010010},
{338540282, 82010010},
{339540282, 83760010},
{338540293, 93020012},
{348060655, 93014679},
{356564448, 84500000},
{356560555, 28989990},
{347334198, 29039989},
{347334198, 25510010},
{356510304, 25521084},
{356510315, 23478922},
{347560302, 23489990},
{347560302, 5775291},
{344874443, 2989990},
{336421201, 2986256},
},
{
},
},
{
{
{465152221, 31684687},
{457606880, 31688302},
{452659362, 35508617},
{449044605, 34734089},
{446478972, 31692751},
{437784814, 31692957},
{435521210, 33956565},
{435532195, 65697616},
{426028494, 65691361},
{426025938, 85049712},
{435532195, 95717636},
{435524445, 103754026},
{436995898, 105225463},
{447552204, 105226323},
{447552215, 103197497},
{444552215, 103197616},
{444552215, 99217636},
{452032195, 99217636},
{452032195, 105221758},
{465588513, 105225463},
{467059965, 103754026},
{467052215, 95717636},
{478053039, 84511285},
{478056214, 65697616},
{468552215, 65697616},
{468563959, 33957323},
{465152221, 31684687},
},
{
},
},
{
{
{764927063, 92658416},
{762115426, 94171595},
{762122741, 131696443},
{786415417, 132779578},
{793690904, 129904572},
{797383202, 124822853},
{798269157, 120142660},
{796710161, 114090278},
{793387498, 110215980},
{796094093, 103892242},
{794107594, 96994001},
{787445494, 92840355},
{764927063, 92658416},
},
{
},
},
{
{
{27496331, 123147467},
{3202195, 124246400},
{3203433, 205768600},
{20223453, 205775606},
{20223644, 163243606},
{31297341, 162189074},
{36789517, 155659691},
{36967183, 150566416},
{34468182, 145711036},
{38465496, 140400171},
{38952460, 132613091},
{34771593, 126022444},
{27496331, 123147467},
},
{
},
},
{
{
{797556553, 39197820},
{791313598, 39199767},
{789506233, 39864015},
{789522521, 48199767},
{775974570, 48195721},
{774022521, 50129235},
{774008720, 76258022},
{775974570, 78223833},
{789522521, 78219787},
{789522521, 86576919},
{797556547, 87221747},
{797556553, 39197820},
},
{
},
},
{
{
{676593113, 129820144},
{676565322, 164844636},
{701599609, 164858650},
{701599609, 129823260},
{676593113, 129820144},
},
{
},
},
{
{
{727646871, 93121321},
{709122741, 93122138},
{709122741, 125656310},
{718769809, 135145243},
{721622937, 135156111},
{724152429, 132626619},
{723734126, 112688301},
{725837154, 107378546},
{728976138, 104430846},
{735847924, 102664848},
{741289364, 104430846},
{745202882, 108599767},
{746590596, 114642158},
{751137173, 114644887},
{756151199, 109641674},
{756149037, 94634278},
{754642761, 93122138},
{727646871, 93121321},
},
{
},
},
{
{
{135915724, 185598906},
{131396265, 193419009},
{131399444, 197643260},
{140399444, 197636810},
{140399444, 199138818},
{157419464, 197643916},
{157422805, 193210743},
{153046747, 185604789},
{149044579, 185614655},
{147324399, 189850396},
{144168954, 191108901},
{141187892, 189479768},
{139917659, 185615382},
{135915724, 185598906},
},
{
},
},
{
{
{312619110, 154485844},
{309601817, 157488332},
{309599764, 203494810},
{313109244, 207010010},
{352900849, 207019221},
{359629120, 200302405},
{359638705, 159501827},
{354621096, 154487830},
{312619110, 154485844},
},
{
},
},
{
{
{313120315, 98984639},
{309609100, 102486971},
{309596977, 148492024},
{312591195, 151510010},
{354608772, 151524494},
{359629120, 146515788},
{359638123, 105715491},
{352907860, 98987790},
{313120315, 98984639},
},
{
},
},
{
{
{657746643, 86246732},
{651722477, 92270881},
{651720052, 131280884},
{653947196, 131280884},
{659746643, 125487816},
{659746643, 119273826},
{663742413, 112352691},
{671726623, 112352691},
{675733721, 119283349},
{684745297, 119298573},
{689758503, 114263168},
{689752066, 91272158},
{684746643, 86260871},
{657746643, 86246732},
},
{
},
},
{
{
{653940791, 39260871},
{651720052, 39260871},
{651726623, 78280611},
{657746631, 84295035},
{684746643, 84280891},
{689752066, 79269604},
{689746643, 56247942},
{684745283, 51243184},
{675733721, 51258413},
{671726623, 58189071},
{663742413, 58189071},
{659746643, 51267936},
{659746643, 45053950},
{653940791, 39260871},
},
{
},
},
{
{
{442365208, 3053303},
{436408500, 5694021},
{434342552, 11072741},
{436986326, 17009033},
{442365367, 19073360},
{448299202, 16431441},
{450365150, 11052721},
{448299202, 5694021},
{442365208, 3053303},
},
{
},
},
};

View File

@ -4,9 +4,37 @@
#include <vector>
#include <clipper.hpp>
#ifndef CLIPPER_BACKEND_HPP
namespace ClipperLib {
using PointImpl = IntPoint;
using PathImpl = Path;
using HoleStore = std::vector<PathImpl>;
struct PolygonImpl {
PathImpl Contour;
HoleStore Holes;
inline PolygonImpl() {}
inline explicit PolygonImpl(const PathImpl& cont): Contour(cont) {}
inline explicit PolygonImpl(const HoleStore& holes):
Holes(holes) {}
inline PolygonImpl(const Path& cont, const HoleStore& holes):
Contour(cont), Holes(holes) {}
inline explicit PolygonImpl(PathImpl&& cont): Contour(std::move(cont)) {}
inline explicit PolygonImpl(HoleStore&& holes): Holes(std::move(holes)) {}
inline PolygonImpl(Path&& cont, HoleStore&& holes):
Contour(std::move(cont)), Holes(std::move(holes)) {}
};
}
#endif
using TestData = std::vector<ClipperLib::Path>;
using TestDataEx = std::vector<ClipperLib::PolygonImpl>;
extern const TestData PRINTER_PART_POLYGONS;
extern const TestData STEGOSAUR_POLYGONS;
extern const TestDataEx PRINTER_PART_POLYGONS_EX;
#endif // PRINTER_PARTS_H

View File

@ -3,8 +3,8 @@
#include <libnest2d.h>
#include "printer_parts.h"
#include <libnest2d/geometries_io.hpp>
#include <libnest2d/geometries_nfp.hpp>
#include <libnest2d/geometry_traits_nfp.hpp>
//#include "../tools/libnfpglue.hpp"
std::vector<libnest2d::Item>& prusaParts() {
static std::vector<libnest2d::Item> ret;
@ -622,26 +622,65 @@ std::vector<ItemPair> nfp_testdata = {
}
};
}
std::vector<ItemPair> nfp_concave_testdata = {
{ // ItemPair
{
{
{533726, 142141},
{532359, 143386},
{530141, 142155},
{528649, 160091},
{533659, 157607},
{538669, 160091},
{537178, 142155},
{534959, 143386},
{533726, 142141},
}
},
{
{
{118305, 11603},
{118311, 26616},
{113311, 26611},
{109311, 29604},
{109300, 44608},
{109311, 49631},
{113300, 52636},
{118311, 52636},
{118308, 103636},
{223830, 103636},
{236845, 90642},
{236832, 11630},
{232825, 11616},
{210149, 11616},
{211308, 13625},
{209315, 17080},
{205326, 17080},
{203334, 13629},
{204493, 11616},
{118305, 11603},
}
},
}
};
TEST(GeometryAlgorithms, nfpConvexConvex) {
template<NfpLevel lvl, Coord SCALE>
void testNfp(const std::vector<ItemPair>& testdata) {
using namespace libnest2d;
const Coord SCALE = 1000000;
Box bin(210*SCALE, 250*SCALE);
int testcase = 0;
auto& exportfun = exportSVG<1, Box>;
auto& exportfun = exportSVG<SCALE, Box>;
auto onetest = [&](Item& orbiter, Item& stationary){
testcase++;
orbiter.translate({210*SCALE, 0});
auto&& nfp = Nfp::noFitPolygon(stationary.rawShape(),
orbiter.transformedShape());
auto&& nfp = Nfp::noFitPolygon<lvl>(stationary.rawShape(),
orbiter.transformedShape());
auto v = ShapeLike::isValid(nfp);
@ -667,11 +706,9 @@ TEST(GeometryAlgorithms, nfpConvexConvex) {
tmp.translate({dx, dy});
bool notinside = !tmp.isInside(stationary);
bool notintersecting = !Item::intersects(tmp, stationary) ||
Item::touches(tmp, stationary);
bool touching = Item::touches(tmp, stationary);
if(!(notinside && notintersecting)) {
if(!touching) {
std::vector<std::reference_wrapper<Item>> inp = {
std::ref(stationary), std::ref(tmp), std::ref(infp)
};
@ -679,23 +716,31 @@ TEST(GeometryAlgorithms, nfpConvexConvex) {
exportfun(inp, bin, testcase*i++);
}
ASSERT_TRUE(notintersecting);
ASSERT_TRUE(notinside);
ASSERT_TRUE(touching);
}
};
for(auto& td : nfp_testdata) {
for(auto& td : testdata) {
auto orbiter = td.orbiter;
auto stationary = td.stationary;
onetest(orbiter, stationary);
}
for(auto& td : nfp_testdata) {
for(auto& td : testdata) {
auto orbiter = td.stationary;
auto stationary = td.orbiter;
onetest(orbiter, stationary);
}
}
}
TEST(GeometryAlgorithms, nfpConvexConvex) {
testNfp<NfpLevel::CONVEX_ONLY, 1>(nfp_testdata);
}
//TEST(GeometryAlgorithms, nfpConcaveConcave) {
// testNfp<NfpLevel::BOTH_CONCAVE, 1000>(nfp_concave_testdata);
//}
TEST(GeometryAlgorithms, pointOnPolygonContour) {
using namespace libnest2d;
@ -718,6 +763,29 @@ TEST(GeometryAlgorithms, pointOnPolygonContour) {
}
}
TEST(GeometryAlgorithms, mergePileWithPolygon) {
using namespace libnest2d;
Rectangle rect1(10, 15);
Rectangle rect2(15, 15);
Rectangle rect3(20, 15);
rect2.translate({10, 0});
rect3.translate({25, 0});
ShapeLike::Shapes<PolygonImpl> pile;
pile.push_back(rect1.transformedShape());
pile.push_back(rect2.transformedShape());
auto result = Nfp::merge(pile, rect3.transformedShape());
ASSERT_EQ(result.size(), 1);
Rectangle ref(45, 15);
ASSERT_EQ(ShapeLike::area(result.front()), ref.area());
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();

View File

@ -0,0 +1,182 @@
//#ifndef NDEBUG
//#define NFP_DEBUG
//#endif
#include "libnfpglue.hpp"
#include "tools/libnfporb/libnfporb.hpp"
namespace libnest2d {
namespace {
inline bool vsort(const libnfporb::point_t& v1, const libnfporb::point_t& v2)
{
using Coord = libnfporb::coord_t;
Coord x1 = v1.x_, x2 = v2.x_, y1 = v1.y_, y2 = v2.y_;
auto diff = y1 - y2;
#ifdef LIBNFP_USE_RATIONAL
long double diffv = diff.convert_to<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 libnfporb::point_t(px*factor, py*factor);
}
}
PolygonImpl _nfp(const PolygonImpl &sh, const PolygonImpl &cother)
{
using Vertex = PointImpl;
PolygonImpl ret;
// try {
libnfporb::polygon_t pstat, porb;
boost::geometry::convert(sh, pstat);
boost::geometry::convert(cother, porb);
long double factor = 0.0000001;//libnfporb::NFP_EPSILON;
long double refactor = 1.0/factor;
for(auto& v : pstat.outer()) v = scale(v, factor);
// std::string message;
// boost::geometry::is_valid(pstat, message);
// std::cout << message << std::endl;
for(auto& h : pstat.inners()) for(auto& v : h) v = scale(v, factor);
for(auto& v : porb.outer()) v = scale(v, factor);
// message;
// boost::geometry::is_valid(porb, message);
// std::cout << message << std::endl;
for(auto& h : porb.inners()) for(auto& v : h) v = scale(v, factor);
// this can throw
auto nfp = libnfporb::generateNFP(pstat, porb, true);
auto &ct = ShapeLike::getContour(ret);
ct.reserve(nfp.front().size()+1);
for(auto v : nfp.front()) {
v = scale(v, refactor);
ct.emplace_back(getX(v), getY(v));
}
ct.push_back(ct.front());
std::reverse(ct.begin(), ct.end());
auto &rholes = ShapeLike::holes(ret);
for(size_t hidx = 1; hidx < nfp.size(); ++hidx) {
if(nfp[hidx].size() >= 3) {
rholes.push_back({});
auto& h = rholes.back();
h.reserve(nfp[hidx].size()+1);
for(auto& v : nfp[hidx]) {
v = scale(v, refactor);
h.emplace_back(getX(v), getY(v));
}
h.push_back(h.front());
std::reverse(h.begin(), h.end());
}
}
auto& cmp = vsort;
std::sort(pstat.outer().begin(), pstat.outer().end(), cmp);
std::sort(porb.outer().begin(), porb.outer().end(), cmp);
// leftmost lower vertex of the stationary polygon
auto& touch_sh = scale(pstat.outer().back(), refactor);
// rightmost upper vertex of the orbiting polygon
auto& touch_other = scale(porb.outer().front(), refactor);
// Calculate the difference and move the orbiter to the touch position.
auto dtouch = touch_sh - touch_other;
auto _top_other = scale(porb.outer().back(), refactor) + dtouch;
Vertex top_other(getX(_top_other), getY(_top_other));
// Get the righmost upper vertex of the nfp and move it to the RMU of
// the orbiter because they should coincide.
auto&& top_nfp = Nfp::rightmostUpVertex(ret);
auto dnfp = top_other - top_nfp;
std::for_each(ShapeLike::begin(ret), ShapeLike::end(ret),
[&dnfp](Vertex& v) { v+= dnfp; } );
for(auto& h : ShapeLike::holes(ret))
std::for_each( h.begin(), h.end(),
[&dnfp](Vertex& v) { v += dnfp; } );
// } catch(std::exception& e) {
// std::cout << "Error: " << e.what() << "\nTrying with convex hull..." << std::endl;
// auto ch_stat = ShapeLike::convexHull(sh);
// auto ch_orb = ShapeLike::convexHull(cother);
// ret = Nfp::nfpConvexOnly(ch_stat, ch_orb);
// }
return ret;
}
PolygonImpl Nfp::NfpImpl<PolygonImpl, NfpLevel::CONVEX_ONLY>::operator()(
const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother)
{
return _nfp(sh, cother);//nfpConvexOnly(sh, cother);
}
PolygonImpl Nfp::NfpImpl<PolygonImpl, NfpLevel::ONE_CONVEX>::operator()(
const PolygonImpl &sh, const ClipperLib::PolygonImpl &cother)
{
return _nfp(sh, cother);
}
PolygonImpl Nfp::NfpImpl<PolygonImpl, 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

@ -0,0 +1,44 @@
#ifndef LIBNFPGLUE_HPP
#define LIBNFPGLUE_HPP
#include <libnest2d/clipper_backend/clipper_backend.hpp>
namespace libnest2d {
PolygonImpl _nfp(const PolygonImpl& sh, const PolygonImpl& cother);
template<>
struct Nfp::NfpImpl<PolygonImpl, NfpLevel::CONVEX_ONLY> {
PolygonImpl operator()(const PolygonImpl& sh, const PolygonImpl& cother);
};
template<>
struct Nfp::NfpImpl<PolygonImpl, NfpLevel::ONE_CONVEX> {
PolygonImpl operator()(const PolygonImpl& sh, const PolygonImpl& cother);
};
template<>
struct Nfp::NfpImpl<PolygonImpl, NfpLevel::BOTH_CONCAVE> {
PolygonImpl operator()(const PolygonImpl& sh, const PolygonImpl& cother);
};
template<>
struct Nfp::NfpImpl<PolygonImpl, NfpLevel::ONE_CONVEX_WITH_HOLES> {
PolygonImpl operator()(const PolygonImpl& sh, const PolygonImpl& cother);
};
template<>
struct Nfp::NfpImpl<PolygonImpl, NfpLevel::BOTH_CONCAVE_WITH_HOLES> {
PolygonImpl operator()(const PolygonImpl& sh, const PolygonImpl& cother);
};
template<> struct Nfp::MaxNfpLevel<PolygonImpl> {
static const BP2D_CONSTEXPR NfpLevel value =
// NfpLevel::CONVEX_ONLY;
NfpLevel::BOTH_CONCAVE_WITH_HOLES;
};
}
#endif // LIBNFPGLUE_HPP

View File

@ -0,0 +1,674 @@
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

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

View File

@ -0,0 +1,89 @@
[![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0.en.html)
##### If you give me a real good reason i might be willing to give you permission to use it under a different license for a specific application. Real good reasons include the following (non-exhausive): the greater good, educational purpose and money :)
# libnfporb
Implementation of a robust no-fit polygon generation in a C++ library using an orbiting approach.
__Please note:__ The paper this implementation is based it on has several bad assumptions that required me to "improvise". That means the code doesn't reflect the paper anymore and is running way slower than expected. At the moment I'm working on implementing a new approach based on this paper (using minkowski sums): https://eprints.soton.ac.uk/36850/1/CORMSIS-05-05.pdf
## Description
The no-fit polygon optimization makes it possible to check for overlap (or non-overlapping touch) of two polygons with only 1 point in polygon check (by providing the set of non-overlapping placements).
This library implements the orbiting approach to generate the no-fit polygon: Given two polygons A and B, A is the stationary one and B the orbiting one, B is slid as tightly as possibly around the edges of polygon A. During the orbiting a chosen reference point is tracked. By tracking the movement of the reference point a third polygon can be generated: the no-fit polygon.
Once the no-fit polygon has been generated it can be used to test for overlap by only checking if the reference point is inside the NFP (overlap) outside the NFP (no overlap) or exactly on the edge of the NFP (touch).
### Examples:
The polygons:
![Start of NFP](/images/start.png?raw=true)
Orbiting:
![State 1](/images/next0.png?raw=true)
![State 2](/images/next1.png?raw=true)
![State 3](/images/next2.png?raw=true)
![State 4](/images/next3.png?raw=true)
![State 5](/images/next4.png?raw=true)
![State 6](/images/next5.png?raw=true)
![State 7](/images/next6.png?raw=true)
![State 8](/images/next7.png?raw=true)
![State 9](/images/next8.png?raw=true)
The resulting NFP is red:
![nfp](/images/nfp.png?raw=true)
Polygons can have concavities, holes, interlocks or might fit perfectly:
![concavities](/images/concavities.png?raw=true)
![hole](/images/hole.png?raw=true)
![interlock](/images/interlock.png?raw=true)
![jigsaw](/images/jigsaw.png?raw=true)
## The Approach
The approch of this library is highly inspired by the scientific paper [Complete and robust no-fit polygon generation
for the irregular stock cutting problem](https://pdfs.semanticscholar.org/e698/0dd78306ba7d5bb349d20c6d8f2e0aa61062.pdf) and by [Svgnest](http://svgnest.com)
Note that is wasn't completely possible to implement it as suggested in the paper because it had several shortcomings that prevent complete NFP generation on some of my test cases. Especially the termination criteria (reference point returns to first point of NFP) proved to be wrong (see: test-case rect). Also tracking of used edges can't be performed as suggested in the paper since there might be situations where no edge of A is traversed (see: test-case doublecon).
By default the library is using floating point as coordinate type but by defining the flag "LIBNFP_USE_RATIONAL" the library can be instructed to use infinite precision.
## Build
The library has two dependencies: [Boost Geometry](http://www.boost.org/doc/libs/1_65_1/libs/geometry/doc/html/index.html) and [libgmp](https://gmplib.org). You need to install those first before building. Note that building is only required for the examples. The library itself is header-only.
git clone https://github.com/kallaballa/libnfp.git
cd libnfp
make
sudo make install
## Code Example
```c++
//uncomment next line to use infinite precision (slow)
//#define LIBNFP_USE_RATIONAL
#include "../src/libnfp.hpp"
int main(int argc, char** argv) {
using namespace libnfp;
polygon_t pA;
polygon_t pB;
//read polygons from wkt files
read_wkt_polygon(argv[1], pA);
read_wkt_polygon(argv[2], pB);
//generate NFP of polygon A and polygon B and check the polygons for validity.
//When the third parameters is false validity check is skipped for a little performance increase
nfp_t nfp = generateNFP(pA, pB, true);
//write a svg containing pA, pB and NFP
write_svg("nfp.svg",{pA,pB},nfp);
return 0;
}
```
Run the example program:
examples/nfp data/crossing/A.wkt data/crossing/B.wkt

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,6 @@
#include <string>
#include <libnest2d.h>
#include <libnest2d/geometries_io.hpp>
namespace libnest2d { namespace svg {
@ -46,16 +45,19 @@ public:
void writeItem(const Item& item) {
if(svg_layers_.empty()) addLayer();
Item tsh(item.transformedShape());
if(conf_.origo_location == BOTTOMLEFT)
for(unsigned i = 0; i < tsh.vertexCount(); i++) {
auto v = tsh.vertex(i);
auto tsh = item.transformedShape();
if(conf_.origo_location == BOTTOMLEFT) {
auto d = static_cast<Coord>(
std::round(conf_.height*conf_.mm_in_coord_units) );
setY(v, -getY(v) + d);
tsh.setVertex(i, v);
auto& contour = ShapeLike::getContour(tsh);
for(auto& v : contour) setY(v, -getY(v) + d);
auto& holes = ShapeLike::holes(tsh);
for(auto& h : holes) for(auto& v : h) setY(v, -getY(v) + d);
}
currentLayer() += ShapeLike::serialize<Formats::SVG>(tsh.rawShape(),
currentLayer() += ShapeLike::serialize<Formats::SVG>(tsh,
1.0/conf_.mm_in_coord_units) + "\n";
}

View File

@ -9,7 +9,6 @@
#include <numeric>
#include <libnest2d.h>
#include <libnest2d/geometries_io.hpp>
#include <ClipperUtils.hpp>
#include "slic3r/GUI/GUI.hpp"
@ -412,7 +411,7 @@ ShapeData2D projectModelFromTop(const Slic3r::Model &model) {
for(auto objinst : objptr->instances) {
if(objinst) {
Slic3r::TriangleMesh tmpmesh = rmesh;
ClipperLib::PolyNode pn;
ClipperLib::PolygonImpl pn;
tmpmesh.scale(objinst->scaling_factor);
@ -553,25 +552,13 @@ bool arrange(Model &model, coordf_t dist, const Slic3r::BoundingBoxf* bb,
// Will use the DJD selection heuristic with the BottomLeft placement
// strategy
using Arranger = Arranger<NfpPlacer, DJDHeuristic>;
using Arranger = Arranger<NfpPlacer, FirstFitSelection>;
using PConf = Arranger::PlacementConfig;
using SConf = Arranger::SelectionConfig;
PConf pcfg; // Placement configuration
SConf scfg; // Selection configuration
// Try inserting groups of 2, and 3 items in all possible order.
scfg.try_reverse_order = false;
// If there are more items that could possibly fit into one bin,
// use multiple threads. (Potencially decreased pack efficiency)
scfg.allow_parallel = true;
// Use multiple threads whenever possible
scfg.force_parallel = false;
scfg.waste_increment = 0.01;
// Align the arranged pile into the center of the bin
pcfg.alignment = PConf::Alignment::CENTER;