Refactor folder (#10475)

Move many third-party components' source codes from the src folder to a new folder called deps_src. The goal is to make the code structure clearer and easier to navigate.
This commit is contained in:
SoftFever
2025-08-22 20:02:26 +08:00
committed by GitHub
parent 3808f7eb28
commit 883607e1d4
2083 changed files with 1163 additions and 19503 deletions

View File

@@ -0,0 +1,533 @@
#ifndef BOOST_ALG_HPP
#define BOOST_ALG_HPP
#ifndef DISABLE_BOOST_SERIALIZE
#include <sstream>
#endif
#ifdef __clang__
#undef _MSC_EXTENSIONS
#endif
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4244)
#pragma warning(disable: 4267)
#endif
#include <boost/geometry.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// this should be removed to not confuse the compiler
// #include "../libnest2d.hpp"
namespace bp2d {
using libnest2d::TCoord;
using libnest2d::PointImpl;
using Coord = TCoord<PointImpl>;
using libnest2d::PolygonImpl;
using libnest2d::PathImpl;
using libnest2d::Orientation;
using libnest2d::OrientationType;
using libnest2d::OrientationTypeV;
using libnest2d::ClosureType;
using libnest2d::Closure;
using libnest2d::ClosureTypeV;
using libnest2d::getX;
using libnest2d::getY;
using libnest2d::setX;
using libnest2d::setY;
using Box = libnest2d::_Box<PointImpl>;
using Segment = libnest2d::_Segment<PointImpl>;
using Shapes = libnest2d::nfp::Shapes<PolygonImpl>;
}
/**
* We have to make all the libnest2d geometry types available to boost. The real
* models of the geometries remain the same if a conforming model for libnest2d
* was defined by the library client. Boost is used only as an optional
* implementer of some algorithms that can be implemented by the model itself
* if a faster alternative exists.
*
* However, boost has its own type traits and we have to define the needed
* specializations to be able to use boost::geometry. This can be done with the
* already provided model.
*/
namespace boost {
namespace geometry {
namespace traits {
/* ************************************************************************** */
/* Point concept adaptaion ************************************************** */
/* ************************************************************************** */
template<> struct tag<bp2d::PointImpl> {
using type = point_tag;
};
template<> struct coordinate_type<bp2d::PointImpl> {
using type = bp2d::Coord;
};
template<> struct coordinate_system<bp2d::PointImpl> {
using type = cs::cartesian;
};
template<> struct dimension<bp2d::PointImpl>: boost::mpl::int_<2> {};
template<>
struct access<bp2d::PointImpl, 0 > {
static inline bp2d::Coord get(bp2d::PointImpl const& a) {
return libnest2d::getX(a);
}
static inline void set(bp2d::PointImpl& a,
bp2d::Coord const& value) {
libnest2d::setX(a, value);
}
};
template<>
struct access<bp2d::PointImpl, 1 > {
static inline bp2d::Coord get(bp2d::PointImpl const& a) {
return libnest2d::getY(a);
}
static inline void set(bp2d::PointImpl& a,
bp2d::Coord const& value) {
libnest2d::setY(a, value);
}
};
/* ************************************************************************** */
/* Box concept adaptaion **************************************************** */
/* ************************************************************************** */
template<> struct tag<bp2d::Box> {
using type = box_tag;
};
template<> struct point_type<bp2d::Box> {
using type = bp2d::PointImpl;
};
template<> struct indexed_access<bp2d::Box, min_corner, 0> {
static inline bp2d::Coord get(bp2d::Box const& box) {
return bp2d::getX(box.minCorner());
}
static inline void set(bp2d::Box &box, bp2d::Coord const& coord) {
bp2d::setX(box.minCorner(), coord);
}
};
template<> struct indexed_access<bp2d::Box, min_corner, 1> {
static inline bp2d::Coord get(bp2d::Box const& box) {
return bp2d::getY(box.minCorner());
}
static inline void set(bp2d::Box &box, bp2d::Coord const& coord) {
bp2d::setY(box.minCorner(), coord);
}
};
template<> struct indexed_access<bp2d::Box, max_corner, 0> {
static inline bp2d::Coord get(bp2d::Box const& box) {
return bp2d::getX(box.maxCorner());
}
static inline void set(bp2d::Box &box, bp2d::Coord const& coord) {
bp2d::setX(box.maxCorner(), coord);
}
};
template<> struct indexed_access<bp2d::Box, max_corner, 1> {
static inline bp2d::Coord get(bp2d::Box const& box) {
return bp2d::getY(box.maxCorner());
}
static inline void set(bp2d::Box &box, bp2d::Coord const& coord) {
bp2d::setY(box.maxCorner(), coord);
}
};
/* ************************************************************************** */
/* Segment concept adaptaion ************************************************ */
/* ************************************************************************** */
template<> struct tag<bp2d::Segment> {
using type = segment_tag;
};
template<> struct point_type<bp2d::Segment> {
using type = bp2d::PointImpl;
};
template<> struct indexed_access<bp2d::Segment, 0, 0> {
static inline bp2d::Coord get(bp2d::Segment const& seg) {
return bp2d::getX(seg.first());
}
static inline void set(bp2d::Segment &seg, bp2d::Coord const& coord) {
auto p = seg.first(); bp2d::setX(p, coord); seg.first(p);
}
};
template<> struct indexed_access<bp2d::Segment, 0, 1> {
static inline bp2d::Coord get(bp2d::Segment const& seg) {
return bp2d::getY(seg.first());
}
static inline void set(bp2d::Segment &seg, bp2d::Coord const& coord) {
auto p = seg.first(); bp2d::setY(p, coord); seg.first(p);
}
};
template<> struct indexed_access<bp2d::Segment, 1, 0> {
static inline bp2d::Coord get(bp2d::Segment const& seg) {
return bp2d::getX(seg.second());
}
static inline void set(bp2d::Segment &seg, bp2d::Coord const& coord) {
auto p = seg.second(); bp2d::setX(p, coord); seg.second(p);
}
};
template<> struct indexed_access<bp2d::Segment, 1, 1> {
static inline bp2d::Coord get(bp2d::Segment const& seg) {
return bp2d::getY(seg.second());
}
static inline void set(bp2d::Segment &seg, bp2d::Coord const& coord) {
auto p = seg.second(); bp2d::setY(p, coord); seg.second(p);
}
};
/* ************************************************************************** */
/* Polygon concept adaptation *********************************************** */
/* ************************************************************************** */
// Connversion between libnest2d::Orientation and order_selector ///////////////
template<bp2d::Orientation> struct ToBoostOrienation {};
template<>
struct ToBoostOrienation<bp2d::Orientation::CLOCKWISE> {
static const order_selector Value = clockwise;
};
template<>
struct ToBoostOrienation<bp2d::Orientation::COUNTER_CLOCKWISE> {
static const order_selector Value = counterclockwise;
};
template<bp2d::Closure> struct ToBoostClosure {};
template<> struct ToBoostClosure<bp2d::Closure::OPEN> {
static const constexpr closure_selector Value = closure_selector::open;
};
template<> struct ToBoostClosure<bp2d::Closure::CLOSED> {
static const constexpr closure_selector Value = closure_selector::closed;
};
// Ring implementation /////////////////////////////////////////////////////////
// Boost would refer to ClipperLib::Path (alias bp2d::PolygonImpl) as a ring
template<> struct tag<bp2d::PathImpl> {
using type = ring_tag;
};
template<> struct point_order<bp2d::PathImpl> {
static const order_selector value =
ToBoostOrienation<bp2d::OrientationTypeV<bp2d::PathImpl>>::Value;
};
// All our Paths should be closed for the bin packing application
template<> struct closure<bp2d::PathImpl> {
static const constexpr closure_selector value =
ToBoostClosure< bp2d::ClosureTypeV<bp2d::PathImpl> >::Value;
};
// Polygon implementation //////////////////////////////////////////////////////
template<> struct tag<bp2d::PolygonImpl> {
using type = polygon_tag;
};
template<> struct exterior_ring<bp2d::PolygonImpl> {
static inline bp2d::PathImpl& get(bp2d::PolygonImpl& p) {
return libnest2d::shapelike::contour(p);
}
static inline bp2d::PathImpl const& get(bp2d::PolygonImpl const& p) {
return libnest2d::shapelike::contour(p);
}
};
template<> struct ring_const_type<bp2d::PolygonImpl> {
using type = const bp2d::PathImpl&;
};
template<> struct ring_mutable_type<bp2d::PolygonImpl> {
using type = bp2d::PathImpl&;
};
template<> struct interior_const_type<bp2d::PolygonImpl> {
using type = const libnest2d::THolesContainer<bp2d::PolygonImpl>&;
};
template<> struct interior_mutable_type<bp2d::PolygonImpl> {
using type = libnest2d::THolesContainer<bp2d::PolygonImpl>&;
};
template<>
struct interior_rings<bp2d::PolygonImpl> {
static inline libnest2d::THolesContainer<bp2d::PolygonImpl>& get(
bp2d::PolygonImpl& p)
{
return libnest2d::shapelike::holes(p);
}
static inline const libnest2d::THolesContainer<bp2d::PolygonImpl>& get(
bp2d::PolygonImpl const& p)
{
return libnest2d::shapelike::holes(p);
}
};
/* ************************************************************************** */
/* MultiPolygon concept adaptation ****************************************** */
/* ************************************************************************** */
template<> struct tag<bp2d::Shapes> {
using type = multi_polygon_tag;
};
} // traits
} // geometry
// This is an addition to the ring implementation of Polygon concept
template<>
struct range_value<bp2d::PathImpl> {
using type = bp2d::PointImpl;
};
template<>
struct range_value<bp2d::Shapes> {
using type = bp2d::PolygonImpl;
};
} // boost
/* ************************************************************************** */
/* Algorithms *************************************************************** */
/* ************************************************************************** */
namespace libnest2d { // Now the algorithms that boost can provide...
//namespace pointlike {
//template<>
//inline double distance(const PointImpl& p1, const PointImpl& p2 )
//{
// return boost::geometry::distance(p1, p2);
//}
//template<>
//inline double distance(const PointImpl& p, const bp2d::Segment& seg )
//{
// return boost::geometry::distance(p, seg);
//}
//}
namespace shapelike {
// Tell libnest2d how to make string out of a ClipperPolygon object
template<>
inline bool intersects(const PathImpl& sh1, const PathImpl& sh2)
{
return boost::geometry::intersects(sh1, sh2);
}
// Tell libnest2d how to make string out of a ClipperPolygon object
template<>
inline bool intersects(const PolygonImpl& sh1, const PolygonImpl& sh2)
{
return boost::geometry::intersects(sh1, sh2);
}
// Tell libnest2d how to make string out of a ClipperPolygon object
template<>
inline bool intersects(const bp2d::Segment& s1, const bp2d::Segment& s2)
{
return boost::geometry::intersects(s1, s2);
}
#ifndef DISABLE_BOOST_AREA
template<>
inline double area(const PolygonImpl& shape, const PolygonTag&)
{
return boost::geometry::area(shape);
}
#endif
template<>
inline bool isInside(const PointImpl& point, const PolygonImpl& shape,
const PointTag&, const PolygonTag&)
{
return boost::geometry::within(point, shape);
}
template<>
inline bool isInside(const PolygonImpl& sh1, const PolygonImpl& sh2,
const PolygonTag&, const PolygonTag&)
{
return boost::geometry::within(sh1, sh2);
}
template<>
inline bool touches(const PolygonImpl& sh1, const PolygonImpl& sh2)
{
return boost::geometry::touches(sh1, sh2);
}
template<>
inline bool touches( const PointImpl& point, const PolygonImpl& shape)
{
return boost::geometry::touches(point, shape);
}
#ifndef DISABLE_BOOST_BOUNDING_BOX
template<>
inline bp2d::Box boundingBox(const PathImpl& sh, const PathTag&)
{
bp2d::Box b;
boost::geometry::envelope(sh, b);
return b;
}
template<>
inline bp2d::Box boundingBox<bp2d::Shapes>(const bp2d::Shapes& shapes,
const MultiPolygonTag&)
{
bp2d::Box b;
boost::geometry::envelope(shapes, b);
return b;
}
#endif
#ifndef DISABLE_BOOST_CONVEX_HULL
template<>
inline PathImpl convexHull(const PathImpl& sh, const PathTag&)
{
PathImpl ret;
boost::geometry::convex_hull(sh, ret);
return ret;
}
template<>
inline PolygonImpl convexHull(const TMultiShape<PolygonImpl>& shapes,
const MultiPolygonTag&)
{
PolygonImpl ret;
boost::geometry::convex_hull(shapes, ret);
return ret;
}
#endif
#ifndef DISABLE_BOOST_OFFSET
template<>
inline void offset(PolygonImpl& sh, bp2d::Coord distance)
{
PolygonImpl cpy = sh;
boost::geometry::buffer(cpy, sh, distance);
}
#endif
#ifndef DISABLE_BOOST_SERIALIZE
template<> inline std::string serialize<libnest2d::Formats::SVG>(
const PolygonImpl& sh, double scale, std::string fill, std::string stroke, float stroke_width)
{
std::stringstream ss;
std::string style = "fill: "+fill+"; stroke: "+stroke+"; stroke-width: "+std::to_string(stroke_width)+"px; ";
using namespace boost::geometry;
using Pointf = model::point<double, 2, cs::cartesian>;
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.emplace_back(std::move(hf));
}
Polygonf poly;
poly.outer() = ring;
poly.inners() = holes;
auto svg_data = boost::geometry::svg(poly, style);
ss << svg_data << std::endl;
return ss.str();
}
#endif
#ifndef DISABLE_BOOST_UNSERIALIZE
template<>
inline void unserialize<libnest2d::Formats::SVG>(
PolygonImpl& sh,
const std::string& str)
{
}
#endif
template<> inline std::pair<bool, std::string> isValid(const PolygonImpl& sh)
{
std::string message;
bool ret = boost::geometry::is_valid(sh, message);
return {ret, message};
}
}
namespace nfp {
#ifndef DISABLE_BOOST_NFP_MERGE
// Warning: I could not get boost union_ to work. Geometries will overlap.
template<>
inline bp2d::Shapes nfp::merge(const bp2d::Shapes& shapes,
const PolygonImpl& sh)
{
bp2d::Shapes retv;
boost::geometry::union_(shapes, sh, retv);
return retv;
}
template<>
inline bp2d::Shapes nfp::merge(const bp2d::Shapes& shapes)
{
bp2d::Shapes retv;
boost::geometry::union_(shapes, shapes.back(), retv);
return retv;
}
#endif
}
}
#endif // BOOST_ALG_HPP

View File

@@ -0,0 +1,227 @@
#ifndef METALOOP_HPP
#define METALOOP_HPP
#include <libnest2d/common.hpp>
#include <tuple>
#include <functional>
namespace libnest2d {
/* ************************************************************************** */
/* C++14 std::index_sequence implementation: */
/* ************************************************************************** */
/**
* \brief C++11 compatible implementation of the index_sequence type from C++14
*/
template<size_t...Ints> struct index_sequence {
using value_type = size_t;
BP2D_CONSTEXPR value_type size() const { return sizeof...(Ints); }
};
// A Help structure to generate the integer list
template<size_t...Nseq> struct genSeq;
// Recursive template to generate the list
template<size_t I, size_t...Nseq> struct genSeq<I, Nseq...> {
// Type will contain a genSeq with Nseq appended by one element
using Type = typename genSeq< I - 1, I - 1, Nseq...>::Type;
};
// Terminating recursion
template <size_t ... Nseq> struct genSeq<0, Nseq...> {
// If I is zero, Type will contain index_sequence with the fuly generated
// integer list.
using Type = index_sequence<Nseq...>;
};
/// Helper alias to make an index sequence from 0 to N
template<size_t N> using make_index_sequence = typename genSeq<N>::Type;
/// Helper alias to make an index sequence for a parameter pack
template<class...Args>
using index_sequence_for = make_index_sequence<sizeof...(Args)>;
/* ************************************************************************** */
namespace opt {
using std::forward;
using std::tuple;
using std::get;
using std::tuple_element;
/**
* @brief Helper class to be able to loop over a parameter pack's elements.
*/
class metaloop {
// The implementation is based on partial struct template specializations.
// Basically we need a template type that is callable and takes an integer
// non-type template parameter which can be used to implement recursive calls.
//
// C++11 will not allow the usage of a plain template function that is why we
// use struct with overloaded call operator. At the same time C++11 prohibits
// partial template specialization with a non type parameter such as int. We
// need to wrap that in a type (see metaloop::Int).
/*
* A helper alias to create integer values wrapped as a type. It is necessary
* because a non type template parameter (such as int) would be prohibited in
* a partial specialization. Also for the same reason we have to use a class
* _Metaloop instead of a simple function as a functor. A function cannot be
* partially specialized in a way that is necessary for this trick.
*/
template<int N> using Int = std::integral_constant<int, N>;
/*
* Helper class to implement in-place functors.
*
* We want to be able to use inline functors like a lambda to keep the code
* as clear as possible.
*/
template<int N, class Fn> class MapFn {
Fn&& fn_;
public:
// It takes the real functor that can be specified in-place but only
// with C++14 because the second parameter's type will depend on the
// type of the parameter pack element that is processed. In C++14 we can
// specify this second parameter type as auto in the lambda parameter list.
inline MapFn(Fn&& fn): fn_(forward<Fn>(fn)) {}
template<class T> void operator ()(T&& pack_element) {
// We provide the index as the first parameter and the pack (or tuple)
// element as the second parameter to the functor.
fn_(N, forward<T>(pack_element));
}
};
/*
* Implementation of the template loop trick.
* We create a mechanism for looping over a parameter pack in compile time.
* \tparam Idx is the loop index which will be decremented at each recursion.
* \tparam Args The parameter pack that will be processed.
*
*/
template <typename Idx, class...Args>
class _MetaLoop {};
// Implementation for the first element of Args...
template <class...Args>
class _MetaLoop<Int<0>, Args...> {
public:
const static BP2D_CONSTEXPR int N = 0;
const static BP2D_CONSTEXPR int ARGNUM = sizeof...(Args)-1;
template<class Tup, class Fn>
void run( Tup&& valtup, Fn&& fn) {
MapFn<ARGNUM-N, Fn> {forward<Fn>(fn)} (get<ARGNUM-N>(valtup));
}
};
// Implementation for the N-th element of Args...
template <int N, class...Args>
class _MetaLoop<Int<N>, Args...> {
public:
const static BP2D_CONSTEXPR int ARGNUM = sizeof...(Args)-1;
template<class Tup, class Fn>
void run(Tup&& valtup, Fn&& fn) {
MapFn<ARGNUM-N, Fn> {forward<Fn>(fn)} (std::get<ARGNUM-N>(valtup));
// Recursive call to process the next element of Args
_MetaLoop<Int<N-1>, Args...> ().run(forward<Tup>(valtup),
forward<Fn>(fn));
}
};
/*
* Instantiation: We must instantiate the template with the last index because
* the generalized version calls the decremented instantiations recursively.
* Once the instantiation with the first index is called, the terminating
* version of run is called which does not call itself anymore.
*
* If you are utterly annoyed, at least you have learned a super crazy
* functional meta-programming pattern.
*/
template<class...Args>
using MetaLoop = _MetaLoop<Int<sizeof...(Args)-1>, Args...>;
public:
/**
* \brief The final usable function template.
*
* This is similar to what varags was on C but in compile time C++11.
* You can call:
* apply(<the mapping function>, <arbitrary number of arguments of any type>);
* For example:
*
* struct mapfunc {
* template<class T> void operator()(int N, T&& element) {
* std::cout << "The value of the parameter "<< N <<": "
* << element << std::endl;
* }
* };
*
* apply(mapfunc(), 'a', 10, 151.545);
*
* C++14:
* apply([](int N, auto&& element){
* std::cout << "The value of the parameter "<< N <<": "
* << element << std::endl;
* }, 'a', 10, 151.545);
*
* This yields the output:
* The value of the parameter 0: a
* The value of the parameter 1: 10
* The value of the parameter 2: 151.545
*
* As an addition, the function can be called with a tuple as the second
* parameter holding the arguments instead of a parameter pack.
*
*/
template<class...Args, class Fn>
inline static void apply(Fn&& fn, Args&&...args) {
MetaLoop<Args...>().run(tuple<Args&&...>(forward<Args>(args)...),
forward<Fn>(fn));
}
/// The version of apply with a tuple rvalue reference.
template<class...Args, class Fn>
inline static void apply(Fn&& fn, tuple<Args...>&& tup) {
MetaLoop<Args...>().run(std::move(tup), forward<Fn>(fn));
}
/// The version of apply with a tuple lvalue reference.
template<class...Args, class Fn>
inline static void apply(Fn&& fn, tuple<Args...>& tup) {
MetaLoop<Args...>().run(tup, forward<Fn>(fn));
}
/// The version of apply with a tuple const reference.
template<class...Args, class Fn>
inline static void apply(Fn&& fn, const tuple<Args...>& tup) {
MetaLoop<Args...>().run(tup, forward<Fn>(fn));
}
/**
* Call a function with its arguments encapsualted in a tuple.
*/
template<class Fn, class Tup, std::size_t...Is>
inline static auto
callFunWithTuple(Fn&& fn, Tup&& tup, index_sequence<Is...>) ->
decltype(fn(std::get<Is>(tup)...))
{
return fn(std::get<Is>(tup)...);
}
};
}
}
#endif // METALOOP_HPP

View File

@@ -0,0 +1,372 @@
#ifndef ROTCALIPERS_HPP
#define ROTCALIPERS_HPP
#include <numeric>
#include <functional>
#include <array>
#include <cmath>
#include <libnest2d/geometry_traits.hpp>
namespace libnest2d {
template<class Pt, class Unit = TCompute<Pt>> class RotatedBox {
Pt axis_;
Unit bottom_ = Unit(0), right_ = Unit(0);
public:
RotatedBox() = default;
RotatedBox(const Pt& axis, Unit b, Unit r):
axis_(axis), bottom_(b), right_(r) {}
inline long double area() const {
long double asq = pl::magnsq<Pt, long double>(axis_);
return cast<long double>(bottom_) * cast<long double>(right_) / asq;
}
inline long double width() const {
return abs(bottom_) / std::sqrt(pl::magnsq<Pt, long double>(axis_));
}
inline long double height() const {
return abs(right_) / std::sqrt(pl::magnsq<Pt, long double>(axis_));
}
inline Unit bottom_extent() const { return bottom_; }
inline Unit right_extent() const { return right_; }
inline const Pt& axis() const { return axis_; }
inline Radians angleToX() const {
double ret = std::atan2(getY(axis_), getX(axis_));
auto s = std::signbit(ret);
if(s) ret += Pi_2;
return -ret;
}
};
template <class Poly, class Pt = TPoint<Poly>, class Unit = TCompute<Pt>>
Poly removeCollinearPoints(const Poly& sh, Unit eps = Unit(0))
{
Poly ret; sl::reserve(ret, sl::contourVertexCount(sh));
Pt eprev = *sl::cbegin(sh) - *std::prev(sl::cend(sh));
auto it = sl::cbegin(sh);
auto itx = std::next(it);
if(itx != sl::cend(sh)) while (it != sl::cend(sh))
{
Pt enext = *itx - *it;
auto dp = pl::dotperp<Pt, Unit>(eprev, enext);
if(abs(dp) > eps) sl::addVertex(ret, *it);
eprev = enext;
if (++itx == sl::cend(sh)) itx = sl::cbegin(sh);
++it;
}
return ret;
}
// The area of the bounding rectangle with the axis dir and support vertices
template<class Pt, class Unit = TCompute<Pt>, class R = TCompute<Pt>>
inline R rectarea(const Pt& w, // the axis
const Pt& vb, const Pt& vr,
const Pt& vt, const Pt& vl)
{
Unit a = pl::dot<Pt, Unit>(w, vr - vl);
Unit b = pl::dot<Pt, Unit>(-pl::perp(w), vt - vb);
R m = R(a) / pl::magnsq<Pt, Unit>(w);
m = m * b;
return m;
};
template<class Pt,
class Unit = TCompute<Pt>,
class R = TCompute<Pt>,
class It = typename std::vector<Pt>::const_iterator>
inline R rectarea(const Pt& w, const std::array<It, 4>& rect)
{
return rectarea<Pt, Unit, R>(w, *rect[0], *rect[1], *rect[2], *rect[3]);
}
template<class Pt, class Unit = TCompute<Pt>, class R = TCompute<Pt>>
inline R rectarea(const Pt& w, // the axis
const Unit& a,
const Unit& b)
{
R m = R(a) / pl::magnsq<Pt, Unit>(w);
m = m * b;
return m;
};
template<class R, class Pt, class Unit>
inline R rectarea(const RotatedBox<Pt, Unit> &rb)
{
return rectarea<Pt, Unit, R>(rb.axis(), rb.bottom_extent(), rb.right_extent());
};
// This function is only applicable to counter-clockwise oriented convex
// polygons where only two points can be collinear witch each other.
template <class RawShape,
class Unit = TCompute<RawShape>,
class Ratio = TCompute<RawShape>,
class VisitFn>
void rotcalipers(const RawShape& sh, VisitFn &&visitfn)
{
using Point = TPoint<RawShape>;
using Iterator = typename TContour<RawShape>::const_iterator;
using pointlike::dot; using pointlike::magnsq; using pointlike::perp;
// Get the first and the last vertex iterator
auto first = sl::cbegin(sh);
auto last = std::prev(sl::cend(sh));
// Check conditions and return undefined box if input is not sane.
if(last == first) return;
if(getX(*first) == getX(*last) && getY(*first) == getY(*last)) --last;
if(last - first < 2) return;
RawShape shcpy; // empty at this point
{
Point p = *first, q = *std::next(first), r = *last;
// Determine orientation from first 3 vertex (should be consistent)
Unit d = (Unit(getY(q)) - getY(p)) * (Unit(getX(r)) - getX(p)) -
(Unit(getX(q)) - getX(p)) * (Unit(getY(r)) - getY(p));
if(d > 0) {
// The polygon is clockwise. A flip is needed (for now)
sl::reserve(shcpy, last - first);
auto it = last; while(it != first) sl::addVertex(shcpy, *it--);
sl::addVertex(shcpy, *first);
first = sl::cbegin(shcpy); last = std::prev(sl::cend(shcpy));
}
}
// Cyclic iterator increment
auto inc = [&first, &last](Iterator& it) {
if(it == last) it = first; else ++it;
};
// Cyclic previous iterator
auto prev = [&first, &last](Iterator it) {
return it == first ? last : std::prev(it);
};
// Cyclic next iterator
auto next = [&first, &last](Iterator it) {
return it == last ? first : std::next(it);
};
// Establish initial (axis aligned) rectangle support verices by determining
// polygon extremes:
auto it = first;
Iterator minX = it, maxX = it, minY = it, maxY = it;
do { // Linear walk through the vertices and save the extreme positions
Point v = *it, d = v - *minX;
if(getX(d) < 0 || (getX(d) == 0 && getY(d) < 0)) minX = it;
d = v - *maxX;
if(getX(d) > 0 || (getX(d) == 0 && getY(d) > 0)) maxX = it;
d = v - *minY;
if(getY(d) < 0 || (getY(d) == 0 && getX(d) > 0)) minY = it;
d = v - *maxY;
if(getY(d) > 0 || (getY(d) == 0 && getX(d) < 0)) maxY = it;
} while(++it != std::next(last));
// Update the vertices defining the bounding rectangle. The rectangle with
// the smallest rotation is selected and the supporting vertices are
// returned in the 'rect' argument.
auto update = [&next, &inc]
(const Point& w, std::array<Iterator, 4>& rect)
{
Iterator B = rect[0], Bn = next(B);
Iterator R = rect[1], Rn = next(R);
Iterator T = rect[2], Tn = next(T);
Iterator L = rect[3], Ln = next(L);
Point b = *Bn - *B, r = *Rn - *R, t = *Tn - *T, l = *Ln - *L;
Point pw = perp(w);
using Pt = Point;
Unit dotwpb = dot<Pt, Unit>( w, b), dotwpr = dot<Pt, Unit>(-pw, r);
Unit dotwpt = dot<Pt, Unit>(-w, t), dotwpl = dot<Pt, Unit>( pw, l);
Unit dw = magnsq<Pt, Unit>(w);
std::array<Ratio, 4> angles;
angles[0] = (Ratio(dotwpb) / magnsq<Pt, Unit>(b)) * dotwpb;
angles[1] = (Ratio(dotwpr) / magnsq<Pt, Unit>(r)) * dotwpr;
angles[2] = (Ratio(dotwpt) / magnsq<Pt, Unit>(t)) * dotwpt;
angles[3] = (Ratio(dotwpl) / magnsq<Pt, Unit>(l)) * dotwpl;
using AngleIndex = std::pair<Ratio, size_t>;
std::vector<AngleIndex> A; A.reserve(4);
for (size_t i = 3, j = 0; j < 4; i = j++) {
if(rect[i] != rect[j] && angles[i] < dw) {
auto iv = std::make_pair(angles[i], i);
auto it = std::lower_bound(A.begin(), A.end(), iv,
[](const AngleIndex& ai,
const AngleIndex& aj)
{
return ai.first > aj.first;
});
A.insert(it, iv);
}
}
// The polygon is supposed to be a rectangle.
if(A.empty()) return false;
auto amin = A.front().first;
auto imin = A.front().second;
for(auto& a : A) if(a.first == amin) inc(rect[a.second]);
std::rotate(rect.begin(), rect.begin() + imin, rect.end());
return true;
};
Point w(1, 0);
std::array<Iterator, 4> rect = {minY, maxX, maxY, minX};
{
Unit a = dot<Point, Unit>(w, *rect[1] - *rect[3]);
Unit b = dot<Point, Unit>(-perp(w), *rect[2] - *rect[0]);
if (!visitfn(RotatedBox<Point, Unit>{w, a, b}))
return;
}
// An edge might be examined twice in which case the algorithm terminates.
size_t c = 0, count = last - first + 1;
std::vector<bool> edgemask(count, false);
while(c++ < count)
{
// Update the support vertices, if cannot be updated, break the cycle.
if(! update(w, rect)) break;
size_t eidx = size_t(rect[0] - first);
if(edgemask[eidx]) break;
edgemask[eidx] = true;
// get the unnormalized direction vector
w = *rect[0] - *prev(rect[0]);
Unit a = dot<Point, Unit>(w, *rect[1] - *rect[3]);
Unit b = dot<Point, Unit>(-perp(w), *rect[2] - *rect[0]);
if (!visitfn(RotatedBox<Point, Unit>{w, a, b}))
break;
}
}
// This function is only applicable to counter-clockwise oriented convex
// polygons where only two points can be collinear witch each other.
template <class S,
class Unit = TCompute<S>,
class Ratio = TCompute<S>>
RotatedBox<TPoint<S>, Unit> minAreaBoundingBox(const S& sh)
{
RotatedBox<TPoint<S>, Unit> minbox;
Ratio minarea = std::numeric_limits<Unit>::max();
auto minfn = [&minarea, &minbox](const RotatedBox<TPoint<S>, Unit> &rbox){
Ratio area = rectarea<Ratio>(rbox);
if (area <= minarea) {
minarea = area;
minbox = rbox;
}
return true; // continue search
};
rotcalipers<S, Unit, Ratio>(sh, minfn);
return minbox;
}
template <class RawShape> Radians minAreaBoundingBoxRotation(const RawShape& sh)
{
return minAreaBoundingBox(sh).angleToX();
}
// Function to find a rotation for a shape that makes it fit into a box.
//
// The method is based on finding a pair of rotations from the rotating calipers
// algorithm such that the aspect ratio is changing from being smaller than
// that of the target to being bigger or vice versa. So that the correct
// AR is somewhere between the obtained pair of angles. Then bisecting that
// interval is sufficient to find the correct angle.
//
// The argument eps is the absolute error limit for the searched angle interval.
template<class S, class Unit = TCompute<S>, class Ratio = TCompute<S>>
Radians fitIntoBoxRotation(const S &shape, const _Box<TPoint<S>> &box, Radians eps = 1e-4)
{
constexpr auto get_aspect_r = [](const auto &b) -> double {
return double(b.width()) / b.height();
};
auto aspect_r = get_aspect_r(box);
RotatedBox<TPoint<S>, Unit> prev_rbox;
Radians a_from = 0., a_to = 0.;
auto visitfn = [&](const RotatedBox<TPoint<S>, Unit> &rbox) {
bool lower_prev = get_aspect_r(prev_rbox) < aspect_r;
bool lower_current = get_aspect_r(rbox) < aspect_r;
if (lower_prev != lower_current) {
a_from = prev_rbox.angleToX();
a_to = rbox.angleToX();
return false;
}
return true;
};
rotcalipers<S, Unit, Ratio>(shape, visitfn);
auto rot_shape_bb = [&shape](Radians r) {
auto s = shape;
sl::rotate(s, r);
return sl::boundingBox(s);
};
auto rot_aspect_r = [&rot_shape_bb, &get_aspect_r](Radians r) {
return get_aspect_r(rot_shape_bb(r));
};
// Lets bisect the retrieved interval where the correct aspect ratio is.
double ar_from = rot_aspect_r(a_from);
auto would_fit = [&box](const _Box<TPoint<S>> &b) {
return b.width() < box.width() && b.height() < box.height();
};
Radians middle = (a_from + a_to) / 2.;
_Box<TPoint<S>> box_middle = rot_shape_bb(middle);
while (!would_fit(box_middle) && std::abs(a_to - a_from) > eps)
{
double ar_middle = get_aspect_r(box_middle);
if ((ar_from < aspect_r) != (ar_middle < aspect_r))
a_to = middle;
else
a_from = middle;
ar_from = rot_aspect_r(a_from);
middle = (a_from + a_to) / 2.;
box_middle = rot_shape_bb(middle);
}
return middle;
}
} // namespace libnest2d
#endif // ROTCALIPERS_HPP

View File

@@ -0,0 +1,41 @@
#ifndef ROTFINDER_HPP
#define ROTFINDER_HPP
#include <libnest2d/libnest2d.hpp>
#include <libnest2d/optimizer.hpp>
#include <iterator>
namespace libnest2d {
template<class RawShape>
Radians findBestRotation(_Item<RawShape>& item) {
opt::StopCriteria stopcr;
stopcr.absolute_score_difference = 0.01;
stopcr.max_iterations = 10000;
opt::TOptimizer<opt::Method::G_GENETIC> solver(stopcr);
auto orig_rot = item.rotation();
auto result = solver.optimize_min([&item, &orig_rot](Radians rot){
item.rotation(orig_rot + rot);
auto bb = item.boundingBox();
return std::sqrt(bb.height()*bb.width());
}, opt::initvals(Radians(0)), opt::bound<Radians>(-Pi/2, Pi/2));
item.rotation(orig_rot);
return std::get<0>(result.optimum);
}
template<class Iterator>
void findMinimumBoundingBoxRotations(Iterator from, Iterator to) {
using V = typename std::iterator_traits<Iterator>::value_type;
std::for_each(from, to, [](V& item){
Radians rot = findBestRotation(item);
item.rotate(rot);
});
}
}
#endif // ROTFINDER_HPP