Clipper2 1.1.0 (#1037)

This commit is contained in:
aismann 2023-01-25 09:08:59 +01:00 committed by GitHub
parent d760315432
commit e6d2970f63
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 3953 additions and 4290 deletions

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 26 October 2022 *
* Date : 23 January 2023 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2022 *
* Copyright : Angus Johnson 2010-2023 *
* Purpose : This is the main polygon clipping module *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -10,13 +10,16 @@
#ifndef CLIPPER_ENGINE_H
#define CLIPPER_ENGINE_H
#define CLIPPER2_VERSION "1.0.6"
constexpr auto CLIPPER2_VERSION = "1.1.0";
#include <cstdlib>
#include <iostream>
#include <queue>
#include <stdexcept>
#include <vector>
#include <functional>
#include <numeric>
#include <memory>
#include "clipper.core.h"
namespace Clipper2Lib {
@ -27,12 +30,13 @@ namespace Clipper2Lib {
struct Vertex;
struct LocalMinima;
struct OutRec;
struct Joiner;
struct HorzSegment;
//Note: all clipping operations except for Difference are commutative.
enum class ClipType { None, Intersection, Union, Difference, Xor };
enum class PathType { Subject, Clip };
enum class JoinWith { None, Left, Right };
enum class VertexFlags : uint32_t {
None = 0, OpenStart = 1, OpenEnd = 2, LocalMax = 4, LocalMin = 8
@ -43,7 +47,7 @@ namespace Clipper2Lib {
return (enum VertexFlags)(uint32_t(a) & uint32_t(b));
}
constexpr enum VertexFlags operator |(enum VertexFlags a, enum VertexFlags b)
constexpr enum VertexFlags operator |(enum VertexFlags a, enum VertexFlags b)
{
return (enum VertexFlags)(uint32_t(a) | uint32_t(b));
}
@ -60,7 +64,7 @@ namespace Clipper2Lib {
OutPt* next = nullptr;
OutPt* prev = nullptr;
OutRec* outrec;
Joiner* joiner = nullptr;
HorzSegment* horz = nullptr;
OutPt(const Point64& pt_, OutRec* outrec_): pt(pt_), outrec(outrec_) {
next = this;
@ -82,15 +86,20 @@ namespace Clipper2Lib {
struct OutRec {
size_t idx = 0;
OutRec* owner = nullptr;
OutRecList* splits = nullptr;
Active* front_edge = nullptr;
Active* back_edge = nullptr;
OutPt* pts = nullptr;
PolyPath* polypath = nullptr;
OutRecList* splits = nullptr;
Rect64 bounds = {};
Path64 path;
bool is_open = false;
~OutRec() { if (splits) delete splits; };
bool horz_done = false;
~OutRec() {
if (splits) delete splits;
// nb: don't delete the split pointers
// as these are owned by ClipperBase's outrec_list_
};
};
///////////////////////////////////////////////////////////////////
@ -122,6 +131,7 @@ namespace Clipper2Lib {
Vertex* vertex_top = nullptr;
LocalMinima* local_min = nullptr; // the bottom of an edge 'bound' (also Vatti)
bool is_left_bound = false;
JoinWith join_with = JoinWith::None;
};
struct LocalMinima {
@ -136,11 +146,24 @@ namespace Clipper2Lib {
Point64 pt;
Active* edge1;
Active* edge2;
IntersectNode() : pt(Point64(0, 0)), edge1(NULL), edge2(NULL) {}
IntersectNode() : pt(Point64(0,0)), edge1(NULL), edge2(NULL) {}
IntersectNode(Active* e1, Active* e2, Point64& pt_) :
pt(pt_), edge1(e1), edge2(e2)
{
}
pt(pt_), edge1(e1), edge2(e2) {}
};
struct HorzSegment {
OutPt* left_op;
OutPt* right_op = nullptr;
bool left_to_right = true;
HorzSegment() : left_op(nullptr) { }
explicit HorzSegment(OutPt* op) : left_op(op) { }
};
struct HorzJoin {
OutPt* op1 = nullptr;
OutPt* op2 = nullptr;
HorzJoin() {};
explicit HorzJoin(OutPt* ltr, OutPt* rtl) : op1(ltr), op2(rtl) { }
};
#ifdef USINGZ
@ -151,6 +174,11 @@ namespace Clipper2Lib {
const PointD& e2bot, const PointD& e2top, PointD& pt)> ZCallbackD;
#endif
typedef std::vector<HorzSegment> HorzSegmentList;
typedef std::unique_ptr<LocalMinima> LocalMinima_ptr;
typedef std::vector<LocalMinima_ptr> LocalMinimaList;
typedef std::vector<IntersectNode> IntersectNodeList;
// ClipperBase -------------------------------------------------------------
class ClipperBase {
@ -163,17 +191,17 @@ namespace Clipper2Lib {
bool using_polytree_ = false;
Active* actives_ = nullptr;
Active *sel_ = nullptr;
Joiner *horz_joiners_ = nullptr;
std::vector<LocalMinima*> minima_list_; //pointers in case of memory reallocs
std::vector<LocalMinima*>::iterator current_locmin_iter_;
LocalMinimaList minima_list_; //pointers in case of memory reallocs
LocalMinimaList::iterator current_locmin_iter_;
std::vector<Vertex*> vertex_lists_;
std::priority_queue<int64_t> scanline_list_;
std::vector<IntersectNode> intersect_nodes_;
std::vector<Joiner*> joiner_list_; //pointers in case of memory reallocs
IntersectNodeList intersect_nodes_;
HorzSegmentList horz_seg_list_;
std::vector<HorzJoin> horz_join_list_;
void Reset();
void InsertScanline(int64_t y);
bool PopScanline(int64_t &y);
bool PopLocalMinima(int64_t y, LocalMinima *&local_minima);
bool PopLocalMinima(int64_t y, LocalMinima*& local_minima);
void DisposeAllOutRecs();
void DisposeVerticesAndLocalMinima();
void DeleteEdges(Active*& e);
@ -196,38 +224,37 @@ namespace Clipper2Lib {
bool BuildIntersectList(const int64_t top_y);
void ProcessIntersectList();
void SwapPositionsInAEL(Active& edge1, Active& edge2);
OutRec* NewOutRec();
OutPt* AddOutPt(const Active &e, const Point64& pt);
OutPt* AddLocalMinPoly(Active &e1, Active &e2,
const Point64& pt, bool is_new = false);
OutPt* AddLocalMaxPoly(Active &e1, Active &e2, const Point64& pt);
void DoHorizontal(Active &horz);
bool ResetHorzDirection(const Active &horz, const Active *max_pair,
bool ResetHorzDirection(const Active &horz, const Vertex* max_vertex,
int64_t &horz_left, int64_t &horz_right);
void DoTopOfScanbeam(const int64_t top_y);
Active *DoMaxima(Active &e);
void JoinOutrecPaths(Active &e1, Active &e2);
void CompleteSplit(OutPt* op1, OutPt* op2, OutRec& outrec);
bool ValidateClosedPathEx(OutPt*& outrec);
void CleanCollinear(OutRec* outrec);
void FixSelfIntersects(OutRec* outrec);
OutPt* DoSplitOp(OutPt* outRecOp, OutPt* splitOp);
Joiner* GetHorzTrialParent(const OutPt* op);
bool OutPtInTrialHorzList(OutPt* op);
void SafeDisposeOutPts(OutPt*& op);
void SafeDeleteOutPtJoiners(OutPt* op);
void DoSplitOp(OutRec* outRec, OutPt* splitOp);
void AddTrialHorzJoin(OutPt* op);
void DeleteTrialHorzJoin(OutPt* op);
void ConvertHorzTrialsToJoins();
void AddJoin(OutPt* op1, OutPt* op2);
void DeleteJoin(Joiner* joiner);
void ProcessJoinerList();
OutRec* ProcessJoin(Joiner* joiner);
void ConvertHorzSegsToJoins();
void ProcessHorzJoins();
void Split(Active& e, const Point64& pt);
void CheckJoinLeft(Active& e, const Point64& pt);
void CheckJoinRight(Active& e, const Point64& pt);
protected:
bool has_open_paths_ = false;
bool succeeded_ = true;
std::vector<OutRec*> outrec_list_; //pointers in case list memory reallocated
OutRecList outrec_list_; //pointers in case list memory reallocated
bool ExecuteInternal(ClipType ct, FillRule ft, bool use_polytrees);
bool DeepCheckOwner(OutRec* outrec, OutRec* owner);
void CleanCollinear(OutRec* outrec);
bool CheckBounds(OutRec* outrec);
void RecursiveCheckOwners(OutRec* outrec, PolyPath* polypath);
void DeepCheckOwners(OutRec* outrec, PolyPath* polypath);
#ifdef USINGZ
ZCallback64 zCallback_ = nullptr;
void SetZ(const Active& e1, const Active& e2, Point64& pt);
@ -240,6 +267,9 @@ namespace Clipper2Lib {
bool PreserveCollinear = true;
bool ReverseSolution = false;
void Clear();
#ifdef USINGZ
int64_t DefaultZ = 0;
#endif
};
// PolyPath / PolyTree --------------------------------------------------------
@ -254,7 +284,7 @@ namespace Clipper2Lib {
PolyPath* parent_;
public:
PolyPath(PolyPath* parent = nullptr): parent_(parent){}
virtual ~PolyPath() { Clear(); };
virtual ~PolyPath() {};
//https://en.cppreference.com/w/cpp/language/rule_of_three
PolyPath(const PolyPath&) = delete;
PolyPath& operator=(const PolyPath&) = delete;
@ -269,141 +299,130 @@ namespace Clipper2Lib {
virtual PolyPath* AddChild(const Path64& path) = 0;
virtual void Clear() {};
virtual void Clear() = 0;
virtual size_t Count() const { return 0; }
const PolyPath* Parent() const { return parent_; }
bool IsHole() const
{
const PolyPath* pp = parent_;
bool is_hole = pp;
while (pp) {
is_hole = !is_hole;
pp = pp->parent_;
}
return is_hole;
}
unsigned lvl = Level();
//Even levels except level 0
return lvl && !(lvl & 1);
}
};
typedef typename std::vector<std::unique_ptr<PolyPath64>> PolyPath64List;
typedef typename std::vector<std::unique_ptr<PolyPathD>> PolyPathDList;
class PolyPath64 : public PolyPath {
private:
std::vector<PolyPath64*> childs_;
PolyPath64List childs_;
Path64 polygon_;
typedef typename std::vector<PolyPath64*>::const_iterator pp64_itor;
public:
PolyPath64(PolyPath64* parent = nullptr) : PolyPath(parent) {}
PolyPath64* operator [] (size_t index) { return static_cast<PolyPath64*>(childs_[index]); }
pp64_itor begin() const { return childs_.cbegin(); }
pp64_itor end() const { return childs_.cend(); }
explicit PolyPath64(PolyPath64* parent = nullptr) : PolyPath(parent) {}
~PolyPath64() {
childs_.resize(0);
}
const PolyPath64* operator [] (size_t index) const
{
return childs_[index].get();
}
const PolyPath64* Child(size_t index) const
{
return childs_[index].get();
}
PolyPath64List::const_iterator begin() const { return childs_.cbegin(); }
PolyPath64List::const_iterator end() const { return childs_.cend(); }
PolyPath64* AddChild(const Path64& path) override
{
PolyPath64* result = new PolyPath64(this);
childs_.push_back(result);
auto p = std::make_unique<PolyPath64>(this);
auto* result = childs_.emplace_back(std::move(p)).get();
result->polygon_ = path;
return result;
}
void Clear() override
{
for (const PolyPath64* child : childs_) delete child;
childs_.resize(0);
}
size_t Count() const override
size_t Count() const override
{
return childs_.size();
}
const Path64 Polygon() const { return polygon_; };
const Path64& Polygon() const { return polygon_; };
double Area() const
{
double result = Clipper2Lib::Area<int64_t>(polygon_);
for (const PolyPath64* child : childs_)
result += child->Area();
return result;
}
friend std::ostream& operator << (std::ostream& outstream, const PolyPath64& polypath)
{
const size_t level_indent = 4;
const size_t coords_per_line = 4;
const size_t last_on_line = coords_per_line - 1;
unsigned level = polypath.Level();
if (level > 0)
{
std::string level_padding;
level_padding.insert(0, (level - 1) * level_indent, ' ');
std::string caption = polypath.IsHole() ? "Hole " : "Outer Polygon ";
std::string childs = polypath.Count() == 1 ? " child" : " children";
outstream << level_padding.c_str() << caption << "with " << polypath.Count() << childs << std::endl;
outstream << level_padding;
size_t i = 0, highI = polypath.Polygon().size() - 1;
for (; i < highI; ++i)
{
outstream << polypath.Polygon()[i] << ' ';
if ((i % coords_per_line) == last_on_line)
outstream << std::endl << level_padding;
}
if (highI > 0) outstream << polypath.Polygon()[i];
outstream << std::endl;
}
for (auto child : polypath)
outstream << *child;
return outstream;
return std::accumulate(childs_.cbegin(), childs_.cend(),
Clipper2Lib::Area<int64_t>(polygon_),
[](double a, const auto& child) {return a + child->Area(); });
}
};
class PolyPathD : public PolyPath {
private:
std::vector<PolyPathD*> childs_;
PolyPathDList childs_;
double inv_scale_;
PathD polygon_;
typedef typename std::vector<PolyPathD*>::const_iterator ppD_itor;
public:
PolyPathD(PolyPathD* parent = nullptr) : PolyPath(parent)
explicit PolyPathD(PolyPathD* parent = nullptr) : PolyPath(parent)
{
inv_scale_ = parent ? parent->inv_scale_ : 1.0;
}
PolyPathD* operator [] (size_t index)
{
return static_cast<PolyPathD*>(childs_[index]);
~PolyPathD() {
childs_.resize(0);
}
ppD_itor begin() const { return childs_.cbegin(); }
ppD_itor end() const { return childs_.cend(); }
const PolyPathD* operator [] (size_t index) const
{
return childs_[index].get();
}
const PolyPathD* Child(size_t index) const
{
return childs_[index].get();
}
PolyPathDList::const_iterator begin() const { return childs_.cbegin(); }
PolyPathDList::const_iterator end() const { return childs_.cend(); }
void SetInvScale(double value) { inv_scale_ = value; }
double InvScale() { return inv_scale_; }
PolyPathD* AddChild(const Path64& path) override
{
PolyPathD* result = new PolyPathD(this);
childs_.push_back(result);
auto p = std::make_unique<PolyPathD>(this);
PolyPathD* result = childs_.emplace_back(std::move(p)).get();
result->polygon_ = ScalePath<double, int64_t>(path, inv_scale_);
return result;
}
void Clear() override
{
for (const PolyPathD* child : childs_) delete child;
childs_.resize(0);
}
size_t Count() const override
size_t Count() const override
{
return childs_.size();
}
const PathD Polygon() const { return polygon_; };
const PathD& Polygon() const { return polygon_; };
double Area() const
{
double result = Clipper2Lib::Area<double>(polygon_);
for (const PolyPathD* child : childs_)
result += child->Area();
return result;
return std::accumulate(childs_.begin(), childs_.end(),
Clipper2Lib::Area<double>(polygon_),
[](double a, const auto& child) {return a + child->Area(); });
}
};
@ -443,7 +462,7 @@ namespace Clipper2Lib {
closed_paths.clear();
open_paths.clear();
if (ExecuteInternal(clip_type, fill_rule, false))
BuildPaths64(closed_paths, &open_paths);
BuildPaths64(closed_paths, &open_paths);
CleanUp();
return succeeded_;
}
@ -472,19 +491,23 @@ namespace Clipper2Lib {
private:
double scale_ = 1.0, invScale_ = 1.0;
#ifdef USINGZ
ZCallbackD zCallback_ = nullptr;
ZCallbackD zCallbackD_ = nullptr;
#endif
void BuildPathsD(PathsD& solutionClosed, PathsD* solutionOpen);
void BuildTreeD(PolyPathD& polytree, PathsD& open_paths);
public:
explicit ClipperD(int precision = 2) : ClipperBase()
{
scale_ = std::pow(10, precision);
CheckPrecision(precision);
// to optimize scaling / descaling precision
// set the scale to a power of double's radix (2) (#25)
scale_ = std::pow(std::numeric_limits<double>::radix,
std::ilogb(std::pow(10, precision)) + 1);
invScale_ = 1 / scale_;
}
#ifdef USINGZ
void SetZCallback(ZCallbackD cb) { zCallback_ = cb; };
void SetZCallback(ZCallbackD cb) { zCallbackD_ = cb; };
void ZCB(const Point64& e1bot, const Point64& e1top,
const Point64& e2bot, const Point64& e2top, Point64& pt)
@ -498,13 +521,13 @@ namespace Clipper2Lib {
PointD e1t = PointD(e1top) * invScale_;
PointD e2b = PointD(e2bot) * invScale_;
PointD e2t = PointD(e2top) * invScale_;
zCallback_(e1b,e1t, e2b, e2t, tmp);
zCallbackD_(e1b,e1t, e2b, e2t, tmp);
pt.z = tmp.z; // only update 'z'
};
void CheckCallback()
{
if(zCallback_)
if(zCallbackD_)
// if the user defined float point callback has been assigned
// then assign the proxy callback function
ClipperBase::zCallback_ =

View File

@ -1,6 +1,6 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 28 October 2022 *
* Date : 11 December 2022 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2022 *
* Purpose : This module exports the Clipper2 Library (ie DLL/so) *
@ -9,15 +9,15 @@
// The exported functions below refer to simple structures that
// can be understood across multiple languages. Consequently
// Path64, PathD, Polytree64 etc are converted from classes
// Path64, PathD, Polytree64 etc are converted from C++ classes
// (std::vector<> etc) into the following data structures:
//
// CPath64 (int64_t*) & CPathD (double_t*):
// Path64 and PathD are converted into arrays of x,y coordinates.
// However in these arrays the first x,y coordinate pair is a
// counter with 'x' containing the number of following coordinate
// pairs. ('y' must always be 0.)
//__________________________________
// pairs. ('y' should be 0, with one exception explained below.)
// __________________________________
// |counter|coord1|coord2|...|coordN|
// |N ,0 |x1, y1|x2, y2|...|xN, yN|
// __________________________________
@ -25,19 +25,15 @@
// CPaths64 (int64_t**) & CPathsD (double_t**):
// These are arrays of pointers to CPath64 and CPathD where
// the first pointer is to a 'counter path'. This 'counter
// path' has a single x,y coord pair where 'y' contains
// the number of paths that follow (and with 'x' always 0).
// path' has a single x,y coord pair with 'y' (not 'x')
// containing the number of paths that follow. ('x' = 0).
// _______________________________
// |counter|path1|path2|...|pathN|
// |addr0 |addr1|addr2|...|addrN| (*addr0[0]=0; *addr0[1]=N)
// _______________________________
//
// The structures of CPolytree64 and CPolytreeD are defined
// below and they don't need to be repeated or explained here.
//
// Finally, the pointer structures created and exported through
// these functions can't safely be destroyed externally, so
// a number of 'dispose functions are also exported.
// below and these structures don't need to be explained here.
#ifndef CLIPPER2_EXPORT_H
#define CLIPPER2_EXPORT_H
@ -62,7 +58,7 @@ typedef struct CPolyPath64 {
uint32_t is_hole;
uint32_t child_count;
CPolyPath64* childs;
}
}
CPolyTree64;
typedef struct CPolyPathD {
@ -70,7 +66,7 @@ typedef struct CPolyPathD {
uint32_t is_hole;
uint32_t child_count;
CPolyPathD* childs;
}
}
CPolyTreeD;
template <typename T>
@ -101,6 +97,80 @@ inline Rect<T> CRectToRect(const CRect<T>& rect)
return result;
}
#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)
//////////////////////////////////////////////////////
// EXPORTED FUNCTION DEFINITIONS
//////////////////////////////////////////////////////
EXTERN_DLL_EXPORT const char* Version();
// Some of the functions below will return data in the various CPath
// and CPolyTree structures which are pointers to heap allocated
// memory. Eventually this memory will need to be released with one
// of the following 'DisposeExported' functions. (This may be the
// only safe way to release this memory since the executable
// accessing these exported functions may use a memory manager that
// allocates and releases heap memory in a different way. Also,
// CPath structures that have been constructed by the executable
// should not be destroyed using these 'DisposeExported' functions.)
EXTERN_DLL_EXPORT void DisposeExportedCPath64(CPath64 p);
EXTERN_DLL_EXPORT void DisposeExportedCPaths64(CPaths64& pp);
EXTERN_DLL_EXPORT void DisposeExportedCPathD(CPathD p);
EXTERN_DLL_EXPORT void DisposeExportedCPathsD(CPathsD& pp);
EXTERN_DLL_EXPORT void DisposeExportedCPolyTree64(CPolyTree64*& cpt);
EXTERN_DLL_EXPORT void DisposeExportedCPolyTreeD(CPolyTreeD*& cpt);
// Boolean clipping:
// cliptype: None=0, Intersection=1, Union=2, Difference=3, Xor=4
// fillrule: EvenOdd=0, NonZero=1, Positive=2, Negative=3
EXTERN_DLL_EXPORT int BooleanOp64(uint8_t cliptype,
uint8_t fillrule, const CPaths64 subjects,
const CPaths64 subjects_open, const CPaths64 clips,
CPaths64& solution, CPaths64& solution_open,
bool preserve_collinear = true, bool reverse_solution = false);
EXTERN_DLL_EXPORT int BooleanOpPt64(uint8_t cliptype,
uint8_t fillrule, const CPaths64 subjects,
const CPaths64 subjects_open, const CPaths64 clips,
CPolyTree64*& solution, CPaths64& solution_open,
bool preserve_collinear = true, bool reverse_solution = false);
EXTERN_DLL_EXPORT int BooleanOpD(uint8_t cliptype,
uint8_t fillrule, const CPathsD subjects,
const CPathsD subjects_open, const CPathsD clips,
CPathsD& solution, CPathsD& solution_open, int precision = 2,
bool preserve_collinear = true, bool reverse_solution = false);
EXTERN_DLL_EXPORT int BooleanOpPtD(uint8_t cliptype,
uint8_t fillrule, const CPathsD subjects,
const CPathsD subjects_open, const CPathsD clips,
CPolyTreeD*& solution, CPathsD& solution_open, int precision = 2,
bool preserve_collinear = true, bool reverse_solution = false);
// Polygon offsetting (inflate/deflate):
// jointype: Square=0, Round=1, Miter=2
// endtype: Polygon=0, Joined=1, Butt=2, Square=3, Round=4
EXTERN_DLL_EXPORT CPaths64 InflatePaths64(const CPaths64 paths,
double delta, uint8_t jointype, uint8_t endtype,
double miter_limit = 2.0, double arc_tolerance = 0.0,
bool reverse_solution = false);
EXTERN_DLL_EXPORT CPathsD InflatePathsD(const CPathsD paths,
double delta, uint8_t jointype, uint8_t endtype,
int precision = 2, double miter_limit = 2.0,
double arc_tolerance = 0.0, bool reverse_solution = false);
// RectClip & RectClipLines:
EXTERN_DLL_EXPORT CPaths64 RectClip64(const CRect64& rect,
const CPaths64 paths);
EXTERN_DLL_EXPORT CPathsD RectClipD(const CRectD& rect,
const CPathsD paths, int precision = 2);
EXTERN_DLL_EXPORT CPaths64 RectClipLines64(const CRect64& rect,
const CPaths64 paths);
EXTERN_DLL_EXPORT CPathsD RectClipLinesD(const CRectD& rect,
const CPathsD paths, int precision = 2);
//////////////////////////////////////////////////////
// INTERNAL FUNCTIONS
//////////////////////////////////////////////////////
inline CPath64 CreateCPath64(size_t cnt1, size_t cnt2);
inline CPath64 CreateCPath64(const Path64& p);
inline CPaths64 CreateCPaths64(const Paths64& pp);
@ -114,17 +184,14 @@ inline PathD ConvertCPathD(const CPathD& p);
inline PathsD ConvertCPathsD(const CPathsD& pp);
// the following function avoid multiple conversions
inline Path64 ConvertCPathD(const CPathD& p, double scale);
inline Paths64 ConvertCPathsD(const CPathsD& pp, double scale);
inline CPathD CreateCPathD(const Path64& p, double scale);
inline CPathsD CreateCPathsD(const Paths64& pp, double scale);
inline Path64 ConvertCPathD(const CPathD& p, double scale);
inline Paths64 ConvertCPathsD(const CPathsD& pp, double scale);
inline CPolyTree64* CreateCPolyTree64(const PolyTree64& pt);
inline CPolyTreeD* CreateCPolyTreeD(const PolyTree64& pt, double scale);
#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)
EXTERN_DLL_EXPORT const char* Version()
{
return CLIPPER2_VERSION;
@ -168,7 +235,7 @@ EXTERN_DLL_EXPORT int BooleanOp64(uint8_t cliptype,
uint8_t fillrule, const CPaths64 subjects,
const CPaths64 subjects_open, const CPaths64 clips,
CPaths64& solution, CPaths64& solution_open,
bool preserve_collinear = true, bool reverse_solution = false)
bool preserve_collinear, bool reverse_solution)
{
if (cliptype > static_cast<uint8_t>(ClipType::Xor)) return -4;
if (fillrule > static_cast<uint8_t>(FillRule::Negative)) return -3;
@ -195,7 +262,7 @@ EXTERN_DLL_EXPORT int BooleanOpPt64(uint8_t cliptype,
uint8_t fillrule, const CPaths64 subjects,
const CPaths64 subjects_open, const CPaths64 clips,
CPolyTree64*& solution, CPaths64& solution_open,
bool preserve_collinear = true, bool reverse_solution = false)
bool preserve_collinear, bool reverse_solution)
{
if (cliptype > static_cast<uint8_t>(ClipType::Xor)) return -4;
if (fillrule > static_cast<uint8_t>(FillRule::Negative)) return -3;
@ -222,8 +289,8 @@ EXTERN_DLL_EXPORT int BooleanOpPt64(uint8_t cliptype,
EXTERN_DLL_EXPORT int BooleanOpD(uint8_t cliptype,
uint8_t fillrule, const CPathsD subjects,
const CPathsD subjects_open, const CPathsD clips,
CPathsD& solution, CPathsD& solution_open, int precision = 2,
bool preserve_collinear = true, bool reverse_solution = false)
CPathsD& solution, CPathsD& solution_open, int precision,
bool preserve_collinear, bool reverse_solution)
{
if (precision < -8 || precision > 8) return -5;
if (cliptype > static_cast<uint8_t>(ClipType::Xor)) return -4;
@ -254,8 +321,8 @@ EXTERN_DLL_EXPORT int BooleanOpD(uint8_t cliptype,
EXTERN_DLL_EXPORT int BooleanOpPtD(uint8_t cliptype,
uint8_t fillrule, const CPathsD subjects,
const CPathsD subjects_open, const CPathsD clips,
CPolyTreeD*& solution, CPathsD& solution_open, int precision = 2,
bool preserve_collinear = true, bool reverse_solution = false)
CPolyTreeD*& solution, CPathsD& solution_open, int precision,
bool preserve_collinear, bool reverse_solution)
{
if (precision < -8 || precision > 8) return -5;
if (cliptype > static_cast<uint8_t>(ClipType::Xor)) return -4;
@ -285,29 +352,29 @@ EXTERN_DLL_EXPORT int BooleanOpPtD(uint8_t cliptype,
}
EXTERN_DLL_EXPORT CPaths64 InflatePaths64(const CPaths64 paths,
double delta, uint8_t jt, uint8_t et, double miter_limit = 2.0,
double arc_tolerance = 0.0, bool reverse_solution = false)
double delta, uint8_t jointype, uint8_t endtype, double miter_limit,
double arc_tolerance, bool reverse_solution)
{
Paths64 pp;
pp = ConvertCPaths64(paths);
ClipperOffset clip_offset( miter_limit,
arc_tolerance, reverse_solution);
clip_offset.AddPaths(pp, JoinType(jt), EndType(et));
clip_offset.AddPaths(pp, JoinType(jointype), EndType(endtype));
Paths64 result = clip_offset.Execute(delta);
return CreateCPaths64(result);
}
EXTERN_DLL_EXPORT CPathsD InflatePathsD(const CPathsD paths,
double delta, uint8_t jt, uint8_t et,
double precision = 2, double miter_limit = 2.0,
double arc_tolerance = 0.0, bool reverse_solution = false)
double delta, uint8_t jointype, uint8_t endtype,
int precision, double miter_limit,
double arc_tolerance, bool reverse_solution)
{
if (precision < -8 || precision > 8 || !paths) return nullptr;
const double scale = std::pow(10, precision);
ClipperOffset clip_offset(miter_limit, arc_tolerance, reverse_solution);
Paths64 pp = ConvertCPathsD(paths, scale);
clip_offset.AddPaths(pp, JoinType(jt), EndType(et));
clip_offset.AddPaths(pp, JoinType(jointype), EndType(endtype));
Paths64 result = clip_offset.Execute(delta * scale);
return CreateCPathsD(result, 1/scale);
}
@ -315,8 +382,6 @@ EXTERN_DLL_EXPORT CPathsD InflatePathsD(const CPathsD paths,
EXTERN_DLL_EXPORT CPaths64 RectClip64(const CRect64& rect,
const CPaths64 paths)
{
log(rect.left);
log(rect.right);
if (CRectIsEmpty(rect) || !paths) return nullptr;
Rect64 r64 = CRectToRect(rect);
class RectClip rc(r64);
@ -340,7 +405,7 @@ EXTERN_DLL_EXPORT CPaths64 RectClip64(const CRect64& rect,
}
EXTERN_DLL_EXPORT CPathsD RectClipD(const CRectD& rect,
const CPathsD paths, int precision = 2)
const CPathsD paths, int precision)
{
if (CRectIsEmpty(rect) || !paths) return nullptr;
if (precision < -8 || precision > 8) return nullptr;
@ -394,7 +459,7 @@ EXTERN_DLL_EXPORT CPaths64 RectClipLines64(const CRect64& rect,
}
EXTERN_DLL_EXPORT CPathsD RectClipLinesD(const CRectD& rect,
const CPathsD paths, int precision = 2)
const CPathsD paths, int precision)
{
Paths64 result;
if (CRectIsEmpty(rect) || !paths) return nullptr;
@ -424,7 +489,8 @@ EXTERN_DLL_EXPORT CPathsD RectClipLinesD(const CRectD& rect,
inline CPath64 CreateCPath64(size_t cnt1, size_t cnt2)
{
// create a dummy counter path
// allocates memory for CPath64, fills in the counter, and
// returns the structure ready to be filled with path data
CPath64 result = new int64_t[2 + cnt1 *2];
result[0] = cnt1;
result[1] = cnt2;
@ -433,6 +499,8 @@ inline CPath64 CreateCPath64(size_t cnt1, size_t cnt2)
inline CPath64 CreateCPath64(const Path64& p)
{
// allocates memory for CPath64, fills the counter
// and returns the memory filled with path data
size_t cnt = p.size();
if (!cnt) return nullptr;
CPath64 result = CreateCPath64(cnt, 0);
@ -469,6 +537,8 @@ inline Path64 ConvertCPath64(const CPath64& p)
inline CPaths64 CreateCPaths64(const Paths64& pp)
{
// allocates memory for multiple CPath64 and
// and returns this memory filled with path data
size_t cnt = pp.size(), cnt2 = cnt;
// don't allocate space for empty paths
@ -505,7 +575,8 @@ inline Paths64 ConvertCPaths64(const CPaths64& pp)
inline CPathD CreateCPathD(size_t cnt1, size_t cnt2)
{
// create a dummy path counter
// allocates memory for CPathD, fills in the counter, and
// returns the structure ready to be filled with path data
CPathD result = new double[2 + cnt1 * 2];
result[0] = static_cast<double>(cnt1);
result[1] = static_cast<double>(cnt2);
@ -514,6 +585,8 @@ inline CPathD CreateCPathD(size_t cnt1, size_t cnt2)
inline CPathD CreateCPathD(const PathD& p)
{
// allocates memory for CPath, fills the counter
// and returns the memory fills with path data
size_t cnt = p.size();
if (!cnt) return nullptr;
CPathD result = CreateCPathD(cnt, 0);
@ -621,6 +694,8 @@ inline Paths64 ConvertCPathsD(const CPathsD& pp, double scale)
inline CPathD CreateCPathD(const Path64& p, double scale)
{
// allocates memory for CPathD, fills in the counter, and
// returns the structure filled with *scaled* path data
size_t cnt = p.size();
if (!cnt) return nullptr;
CPathD result = CreateCPathD(cnt, 0);
@ -636,6 +711,8 @@ inline CPathD CreateCPathD(const Path64& p, double scale)
inline CPathsD CreateCPathsD(const Paths64& pp, double scale)
{
// allocates memory for *multiple* CPathD, and
// returns the structure filled with scaled path data
size_t cnt = pp.size(), cnt2 = cnt;
// don't allocate space for empty paths
for (size_t i = 0; i < cnt; ++i)
@ -653,17 +730,17 @@ inline CPathsD CreateCPathsD(const Paths64& pp, double scale)
}
inline void InitCPolyPath64(CPolyTree64* cpt,
bool is_hole, const PolyPath64* pp)
bool is_hole, const std::unique_ptr <PolyPath64>& pp)
{
cpt->polygon = CreateCPath64(pp->Polygon());
cpt->is_hole = is_hole;
size_t child_cnt = pp->Count();
cpt->child_count = child_cnt;
cpt->child_count = static_cast<uint32_t>(child_cnt);
cpt->childs = nullptr;
if (!child_cnt) return;
cpt->childs = new CPolyPath64[child_cnt];
CPolyPath64* child = cpt->childs;
for (const PolyPath64* pp_child : *pp)
for (const std::unique_ptr <PolyPath64>& pp_child : *pp)
InitCPolyPath64(child++, !is_hole, pp_child);
}
@ -674,11 +751,11 @@ inline CPolyTree64* CreateCPolyTree64(const PolyTree64& pt)
result->is_hole = false;
size_t child_cnt = pt.Count();
result->childs = nullptr;
result->child_count = child_cnt;
result->child_count = static_cast<uint32_t>(child_cnt);
if (!child_cnt) return result;
result->childs = new CPolyPath64[child_cnt];
CPolyPath64* child = result->childs;
for (const PolyPath64* pp : pt)
for (const std::unique_ptr <PolyPath64>& pp : pt)
InitCPolyPath64(child++, true, pp);
return result;
}
@ -701,17 +778,17 @@ EXTERN_DLL_EXPORT void DisposeExportedCPolyTree64(CPolyTree64*& cpt)
}
inline void InitCPolyPathD(CPolyTreeD* cpt,
bool is_hole, const PolyPath64* pp, double scale)
bool is_hole, const std::unique_ptr <PolyPath64>& pp, double scale)
{
cpt->polygon = CreateCPathD(pp->Polygon(), scale);
cpt->is_hole = is_hole;
size_t child_cnt = pp->Count();
cpt->child_count = child_cnt;
cpt->child_count = static_cast<uint32_t>(child_cnt);
cpt->childs = nullptr;
if (!child_cnt) return;
cpt->childs = new CPolyPathD[child_cnt];
CPolyPathD* child = cpt->childs;
for (const PolyPath64* pp_child : *pp)
for (const std::unique_ptr <PolyPath64>& pp_child : *pp)
InitCPolyPathD(child++, !is_hole, pp_child, scale);
}
@ -726,7 +803,7 @@ inline CPolyTreeD* CreateCPolyTreeD(const PolyTree64& pt, double scale)
if (!child_cnt) return result;
result->childs = new CPolyPathD[child_cnt];
CPolyPathD* child = result->childs;
for (const PolyPath64* pp : pt)
for (const std::unique_ptr <PolyPath64>& pp : pt)
InitCPolyPathD(child++, true, pp, scale);
return result;
}

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 26 October 2022 *
* Date : 23 January 2023 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2022 *
* Copyright : Angus Johnson 2010-2023 *
* Purpose : This module provides a simple interface to the Clipper Library *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -21,9 +21,6 @@
namespace Clipper2Lib {
static const char* precision_error =
"Precision exceeds the permitted range";
static const Rect64 MaxInvalidRect64 = Rect64(
(std::numeric_limits<int64_t>::max)(),
(std::numeric_limits<int64_t>::max)(),
@ -60,8 +57,7 @@ namespace Clipper2Lib {
inline PathsD BooleanOp(ClipType cliptype, FillRule fillrule,
const PathsD& subjects, const PathsD& clips, int decimal_prec = 2)
{
if (decimal_prec > 8 || decimal_prec < -8)
throw Clipper2Exception(precision_error);
CheckPrecision(decimal_prec);
PathsD result;
ClipperD clipper(decimal_prec);
clipper.AddSubject(subjects);
@ -74,8 +70,7 @@ namespace Clipper2Lib {
const PathsD& subjects, const PathsD& clips,
PolyTreeD& polytree, int decimal_prec = 2)
{
if (decimal_prec > 8 || decimal_prec < -8)
throw Clipper2Exception(precision_error);
CheckPrecision(decimal_prec);
PathsD result;
ClipperD clipper(decimal_prec);
clipper.AddSubject(subjects);
@ -114,8 +109,7 @@ namespace Clipper2Lib {
inline PathsD Union(const PathsD& subjects, FillRule fillrule, int decimal_prec = 2)
{
if (decimal_prec > 8 || decimal_prec < -8)
throw Clipper2Exception(precision_error);
CheckPrecision(decimal_prec);
PathsD result;
ClipperD clipper(decimal_prec);
clipper.AddSubject(subjects);
@ -152,10 +146,9 @@ namespace Clipper2Lib {
}
inline PathsD InflatePaths(const PathsD& paths, double delta,
JoinType jt, EndType et, double miter_limit = 2.0, double precision = 2)
JoinType jt, EndType et, double miter_limit = 2.0, int precision = 2)
{
if (precision < -8 || precision > 8)
throw Clipper2Exception(precision_error);
CheckPrecision(precision);
const double scale = std::pow(10, precision);
ClipperOffset clip_offset(miter_limit);
clip_offset.AddPaths(ScalePaths<int64_t,double>(paths, scale), jt, et);
@ -167,8 +160,8 @@ namespace Clipper2Lib {
{
Path64 result;
result.reserve(path.size());
for (const Point64& pt : path)
result.push_back(Point64(pt.x + dx, pt.y + dy));
std::transform(path.begin(), path.end(), back_inserter(result),
[dx, dy](const auto& pt) { return Point64(pt.x + dx, pt.y +dy); });
return result;
}
@ -176,8 +169,8 @@ namespace Clipper2Lib {
{
PathD result;
result.reserve(path.size());
for (const PointD& pt : path)
result.push_back(PointD(pt.x + dx, pt.y + dy));
std::transform(path.begin(), path.end(), back_inserter(result),
[dx, dy](const auto& pt) { return PointD(pt.x + dx, pt.y + dy); });
return result;
}
@ -185,8 +178,8 @@ namespace Clipper2Lib {
{
Paths64 result;
result.reserve(paths.size());
for (const Path64& path : paths)
result.push_back(TranslatePath(path, dx, dy));
std::transform(paths.begin(), paths.end(), back_inserter(result),
[dx, dy](const auto& path) { return TranslatePath(path, dx, dy); });
return result;
}
@ -194,8 +187,8 @@ namespace Clipper2Lib {
{
PathsD result;
result.reserve(paths.size());
for (const PathD& path : paths)
result.push_back(TranslatePath(path, dx, dy));
std::transform(paths.begin(), paths.end(), back_inserter(result),
[dx, dy](const auto& path) { return TranslatePath(path, dx, dy); });
return result;
}
@ -294,8 +287,7 @@ namespace Clipper2Lib {
{
if (rect.IsEmpty() || path.empty() ||
!rect.Contains(Bounds(path))) return PathD();
if (precision < -8 || precision > 8)
throw Clipper2Exception(precision_error);
CheckPrecision(precision);
const double scale = std::pow(10, precision);
Rect64 r = ScaleRect<int64_t, double>(rect, scale);
class RectClip rc(r);
@ -306,8 +298,7 @@ namespace Clipper2Lib {
inline PathsD RectClip(const RectD& rect, const PathsD& paths, int precision = 2)
{
if (rect.IsEmpty() || paths.empty()) return PathsD();
if (precision < -8 || precision > 8)
throw Clipper2Exception(precision_error);
CheckPrecision(precision);
const double scale = std::pow(10, precision);
Rect64 r = ScaleRect<int64_t, double>(rect, scale);
class RectClip rc(r);
@ -372,8 +363,7 @@ namespace Clipper2Lib {
{
if (rect.IsEmpty() || path.empty() ||
!rect.Contains(Bounds(path))) return PathsD();
if (precision < -8 || precision > 8)
throw Clipper2Exception(precision_error);
CheckPrecision(precision);
const double scale = std::pow(10, precision);
Rect64 r = ScaleRect<int64_t, double>(rect, scale);
class RectClipLines rcl(r);
@ -385,8 +375,7 @@ namespace Clipper2Lib {
{
PathsD result;
if (rect.IsEmpty() || paths.empty()) return result;
if (precision < -8 || precision > 8)
throw Clipper2Exception(precision_error);
CheckPrecision(precision);
const double scale = std::pow(10, precision);
Rect64 r = ScaleRect<int64_t, double>(rect, scale);
class RectClipLines rcl(r);
@ -416,25 +405,43 @@ namespace Clipper2Lib {
inline void PolyPathToPaths64(const PolyPath64& polypath, Paths64& paths)
{
paths.push_back(polypath.Polygon());
for (const PolyPath* child : polypath)
PolyPathToPaths64(*(PolyPath64*)(child), paths);
for (const auto& child : polypath)
PolyPathToPaths64(*child, paths);
}
inline void PolyPathToPathsD(const PolyPathD& polypath, PathsD& paths)
{
paths.push_back(polypath.Polygon());
for (const PolyPath* child : polypath)
PolyPathToPathsD(*(PolyPathD*)(child), paths);
for (const auto& child : polypath)
PolyPathToPathsD(*child, paths);
}
inline bool PolyPath64ContainsChildren(const PolyPath64& pp)
{
for (auto ch : pp)
for (const auto& child : pp)
{
PolyPath64* child = (PolyPath64*)ch;
// return false if this child isn't fully contained by its parent
// the following algorithm is a bit too crude, and doesn't account
// for rounding errors. A better algorithm is to return false when
// consecutive vertices are found outside the parent's polygon.
//const Path64& path = pp.Polygon();
//if (std::any_of(child->Polygon().cbegin(), child->Polygon().cend(),
// [path](const auto& pt) {return (PointInPolygon(pt, path) ==
// PointInPolygonResult::IsOutside); })) return false;
int outsideCnt = 0;
for (const Point64& pt : child->Polygon())
if (PointInPolygon(pt, pp.Polygon()) == PointInPolygonResult::IsOutside)
return false;
{
PointInPolygonResult result = PointInPolygon(pt, pp.Polygon());
if (result == PointInPolygonResult::IsInside) --outsideCnt;
else if (result == PointInPolygonResult::IsOutside) ++outsideCnt;
if (outsideCnt > 1) return false;
else if (outsideCnt < -1) break;
}
// now check any nested children too
if (child->Count() > 0 && !PolyPath64ContainsChildren(*child))
return false;
}
@ -529,29 +536,101 @@ namespace Clipper2Lib {
return;
}
static void OutlinePolyPath(std::ostream& os,
bool isHole, size_t count, const std::string& preamble)
{
std::string plural = (count == 1) ? "." : "s.";
if (isHole)
{
if (count)
os << preamble << "+- Hole with " << count <<
" nested polygon" << plural << std::endl;
else
os << preamble << "+- Hole" << std::endl;
}
else
{
if (count)
os << preamble << "+- Polygon with " << count <<
" nested hole" << plural << std::endl;
else
os << preamble << "+- Polygon" << std::endl;
}
}
static void OutlinePolyPath64(std::ostream& os, const PolyPath64& pp,
std::string preamble, bool last_child)
{
OutlinePolyPath(os, pp.IsHole(), pp.Count(), preamble);
preamble += (!last_child) ? "| " : " ";
if (pp.Count())
{
PolyPath64List::const_iterator it = pp.begin();
for (; it < pp.end() - 1; ++it)
OutlinePolyPath64(os, **it, preamble, false);
OutlinePolyPath64(os, **it, preamble, true);
}
}
static void OutlinePolyPathD(std::ostream& os, const PolyPathD& pp,
std::string preamble, bool last_child)
{
OutlinePolyPath(os, pp.IsHole(), pp.Count(), preamble);
preamble += (!last_child) ? "| " : " ";
if (pp.Count())
{
PolyPathDList::const_iterator it = pp.begin();
for (; it < pp.end() - 1; ++it)
OutlinePolyPathD(os, **it, preamble, false);
OutlinePolyPathD(os, **it, preamble, true);
}
}
} // end details namespace
inline std::ostream& operator<< (std::ostream& os, const PolyTree64& pp)
{
PolyPath64List::const_iterator it = pp.begin();
for (; it < pp.end() - 1; ++it)
details::OutlinePolyPath64(os, **it, " ", false);
details::OutlinePolyPath64(os, **it, " ", true);
os << std::endl << std::endl;
if (!pp.Level()) os << std::endl;
return os;
}
inline std::ostream& operator<< (std::ostream& os, const PolyTreeD& pp)
{
PolyPathDList::const_iterator it = pp.begin();
for (; it < pp.end() - 1; ++it)
details::OutlinePolyPathD(os, **it, " ", false);
details::OutlinePolyPathD(os, **it, " ", true);
os << std::endl << std::endl;
if (!pp.Level()) os << std::endl;
return os;
}
inline Paths64 PolyTreeToPaths64(const PolyTree64& polytree)
{
Paths64 result;
for (auto child : polytree)
details::PolyPathToPaths64(*(PolyPath64*)(child), result);
for (const auto& child : polytree)
details::PolyPathToPaths64(*child, result);
return result;
}
inline PathsD PolyTreeToPathsD(const PolyTreeD& polytree)
{
PathsD result;
for (auto child : polytree)
details::PolyPathToPathsD(*(PolyPathD*)(child), result);
for (const auto& child : polytree)
details::PolyPathToPathsD(*child, result);
return result;
}
inline bool CheckPolytreeFullyContainsChildren(const PolyTree64& polytree)
{
for (auto child : polytree)
for (const auto& child : polytree)
if (child->Count() > 0 &&
!details::PolyPath64ContainsChildren(*(PolyPath64*)(child)))
!details::PolyPath64ContainsChildren(*child))
return false;
return true;
}
@ -641,8 +720,7 @@ namespace Clipper2Lib {
inline PathD TrimCollinear(const PathD& path, int precision, bool is_open_path = false)
{
if (precision > 8 || precision < -8)
throw Clipper2Exception(precision_error);
CheckPrecision(precision);
const double scale = std::pow(10, precision);
Path64 p = ScalePath<int64_t, double>(path, scale);
p = TrimCollinear(p, is_open_path);
@ -764,8 +842,9 @@ namespace Clipper2Lib {
{
Paths<T> result;
result.reserve(paths.size());
for (const Path<T>& path : paths)
result.push_back(RamerDouglasPeucker<T>(path, epsilon));
std::transform(paths.begin(), paths.end(), back_inserter(result),
[epsilon](const auto& path)
{ return RamerDouglasPeucker<T>(path, epsilon); });
return result;
}

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 15 October 2022 *
* Date : 21 January 2023 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2022 *
* Copyright : Angus Johnson 2010-2023 *
* Purpose : Path Offset (Inflate/Shrink) *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -216,7 +216,7 @@ void ClipperOffset::DoRound(Group& group, const Path64& path, size_t j, size_t k
{
//even though angle may be negative this is a convex join
Point64 pt = path[j];
int steps = static_cast<int>(std::ceil(steps_per_rad_ * std::abs(angle)));
int steps = static_cast<int>(std::floor(steps_per_rad_ * std::abs(angle)));
double step_sin = std::sin(angle / steps);
double step_cos = std::cos(angle / steps);
@ -224,7 +224,7 @@ void ClipperOffset::DoRound(Group& group, const Path64& path, size_t j, size_t k
if (j == k) pt2.Negate();
group.path_.push_back(Point64(pt.x + pt2.x, pt.y + pt2.y));
for (int i = 0; i < steps; i++)
for (int i = 0; i < steps; ++i)
{
pt2 = PointD(pt2.x * step_cos - step_sin * pt2.y,
pt2.x * step_sin + pt2.y * step_cos);
@ -233,7 +233,8 @@ void ClipperOffset::DoRound(Group& group, const Path64& path, size_t j, size_t k
group.path_.push_back(GetPerpendic(path[j], norms[j], group_delta_));
}
void ClipperOffset::OffsetPoint(Group& group, Path64& path, size_t j, size_t& k)
void ClipperOffset::OffsetPoint(Group& group,
Path64& path, size_t j, size_t& k, bool reversing)
{
// Let A = change in angle where edges join
// A == 0: ie no change in angle (flat join)
@ -248,26 +249,20 @@ void ClipperOffset::OffsetPoint(Group& group, Path64& path, size_t j, size_t& k)
if (sin_a > 1.0) sin_a = 1.0;
else if (sin_a < -1.0) sin_a = -1.0;
bool almostNoAngle = AlmostZero(sin_a) && cos_a > 0;
bool almostNoAngle = AlmostZero(cos_a - 1);
bool is180DegSpike = AlmostZero(cos_a + 1) && reversing;
// when there's almost no angle of deviation or it's concave
if (almostNoAngle || (sin_a * group_delta_ < 0))
if (almostNoAngle || is180DegSpike || (sin_a * group_delta_ < 0))
{
Point64 p1 = Point64(
path[j].x + norms[k].x * group_delta_,
path[j].y + norms[k].y * group_delta_);
Point64 p2 = Point64(
path[j].x + norms[j].x * group_delta_,
path[j].y + norms[j].y * group_delta_);
group.path_.push_back(p1);
if (p1 != p2)
{
// when concave add an extra vertex to ensure neat clipping
if (!almostNoAngle) group.path_.push_back(path[j]);
group.path_.push_back(p2);
}
//almost no angle or concave
group.path_.push_back(GetPerpendic(path[j], norms[k], group_delta_));
// create a simple self-intersection that will be cleaned up later
if (!almostNoAngle) group.path_.push_back(path[j]);
group.path_.push_back(GetPerpendic(path[j], norms[j], group_delta_));
}
else // it's convex
else
{
// it's convex
if (join_type_ == JoinType::Round)
DoRound(group, path, j, k, std::atan2(sin_a, cos_a));
else if (join_type_ == JoinType::Miter)
@ -352,7 +347,7 @@ void ClipperOffset::OffsetOpenPath(Group& group, Path64& path, EndType end_type)
}
for (size_t i = highI, k = 0; i > 0; --i)
OffsetPoint(group, path, i, k);
OffsetPoint(group, path, i, k, true);
group.paths_out_.push_back(group.path_);
}
@ -472,7 +467,6 @@ Paths64 ClipperOffset::Execute(double delta)
c.PreserveCollinear = false;
//the solution should retain the orientation of the input
c.ReverseSolution = reverse_solution_ != groups_[0].is_reversed_;
c.AddSubject(solution);
if (groups_[0].is_reversed_)
c.Execute(ClipType::Union, FillRule::Negative, solution);

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 15 October 2022 *
* Date : 21 January 2023 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2022 *
* Copyright : Angus Johnson 2010-2023 *
* Purpose : Path Offset (Inflate/Shrink) *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -60,10 +60,11 @@ private:
void OffsetPolygon(Group& group, Path64& path);
void OffsetOpenJoined(Group& group, Path64& path);
void OffsetOpenPath(Group& group, Path64& path, EndType endType);
void OffsetPoint(Group& group, Path64& path, size_t j, size_t& k);
void OffsetPoint(Group& group, Path64& path,
size_t j, size_t& k, bool reversing = false);
void DoGroupOffset(Group &group, double delta);
public:
ClipperOffset(double miter_limit = 2.0,
explicit ClipperOffset(double miter_limit = 2.0,
double arc_tolerance = 0.0,
bool preserve_collinear = false,
bool reverse_solution = false) :

View File

@ -1,6 +1,6 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 26 October 2022 *
* Date : 14 January 2023 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2022 *
* Purpose : FAST rectangular clipping *
@ -17,7 +17,7 @@ namespace Clipper2Lib {
// Miscellaneous methods
//------------------------------------------------------------------------------
inline PointInPolygonResult Path1ContainsPath2(Path64 path1, Path64 path2)
inline PointInPolygonResult Path1ContainsPath2(const Path64& path1, const Path64& path2)
{
PointInPolygonResult result = PointInPolygonResult::IsOn;
for(const Point64& pt : path2)
@ -59,39 +59,6 @@ namespace Clipper2Lib {
return true;
}
Point64 GetIntersectPoint64(const Point64& ln1a, const Point64& ln1b,
const Point64& ln2a, const Point64& ln2b)
{
// see http://astronomy.swin.edu.au/~pbourke/geometry/lineline2d/
if (ln1b.x == ln1a.x)
{
if (ln2b.x == ln2a.x) return Point64(); // parallel lines
double m2 = static_cast<double>(ln2b.y - ln2a.y) / (ln2b.x - ln2a.x);
double b2 = ln2a.y - m2 * ln2a.x;
return Point64(ln1a.x, static_cast<int64_t>(std::round(m2 * ln1a.x + b2)));
}
else if (ln2b.x == ln2a.x)
{
double m1 = static_cast<double>(ln1b.y - ln1a.y) / (ln1b.x - ln1a.x);
double b1 = ln1a.y - m1 * ln1a.x;
return Point64(ln2a.x, static_cast<int64_t>(std::round(m1 * ln2a.x + b1)));
}
else
{
double m1 = static_cast<double>(ln1b.y - ln1a.y) / (ln1b.x - ln1a.x);
double b1 = ln1a.y - m1 * ln1a.x;
double m2 = static_cast<double>(ln2b.y - ln2a.y) / (ln2b.x - ln2a.x);
double b2 = ln2a.y - m2 * ln2a.x;
if (std::fabs(m1 - m2) > 1.0E-15)
{
double x = (b2 - b1) / (m1 - m2);
return Point64(x, m1 * x + b1);
}
else
return Point64((ln1a.x + ln1b.x) * 0.5, (ln1a.y + ln1b.y) * 0.5);
}
}
inline bool GetIntersection(const Path64& rectPath,
const Point64& p, const Point64& p2, Location& loc, Point64& ip)
{
@ -101,16 +68,16 @@ namespace Clipper2Lib {
{
case Location::Left:
if (SegmentsIntersect(p, p2, rectPath[0], rectPath[3], true))
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[3], ip);
else if (p.y < rectPath[0].y &&
SegmentsIntersect(p, p2, rectPath[0], rectPath[1], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[1]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[1], ip);
loc = Location::Top;
}
else if (SegmentsIntersect(p, p2, rectPath[2], rectPath[3], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[2], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[2], rectPath[3], ip);
loc = Location::Bottom;
}
else return false;
@ -118,17 +85,17 @@ namespace Clipper2Lib {
case Location::Top:
if (SegmentsIntersect(p, p2, rectPath[0], rectPath[1], true))
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[1]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[1], ip);
else if (p.x < rectPath[0].x &&
SegmentsIntersect(p, p2, rectPath[0], rectPath[3], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[3], ip);
loc = Location::Left;
}
else if (p.x > rectPath[1].x &&
SegmentsIntersect(p, p2, rectPath[1], rectPath[2], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[1], rectPath[2]);
GetIntersectPoint(p, p2, rectPath[1], rectPath[2], ip);
loc = Location::Right;
}
else return false;
@ -136,16 +103,16 @@ namespace Clipper2Lib {
case Location::Right:
if (SegmentsIntersect(p, p2, rectPath[1], rectPath[2], true))
ip = GetIntersectPoint64(p, p2, rectPath[1], rectPath[2]);
GetIntersectPoint(p, p2, rectPath[1], rectPath[2], ip);
else if (p.y < rectPath[0].y &&
SegmentsIntersect(p, p2, rectPath[0], rectPath[1], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[1]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[1], ip);
loc = Location::Top;
}
else if (SegmentsIntersect(p, p2, rectPath[2], rectPath[3], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[2], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[2], rectPath[3], ip);
loc = Location::Bottom;
}
else return false;
@ -153,17 +120,17 @@ namespace Clipper2Lib {
case Location::Bottom:
if (SegmentsIntersect(p, p2, rectPath[2], rectPath[3], true))
ip = GetIntersectPoint64(p, p2, rectPath[2], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[2], rectPath[3], ip);
else if (p.x < rectPath[3].x &&
SegmentsIntersect(p, p2, rectPath[0], rectPath[3], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[3], ip);
loc = Location::Left;
}
else if (p.x > rectPath[2].x &&
SegmentsIntersect(p, p2, rectPath[1], rectPath[2], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[1], rectPath[2]);
GetIntersectPoint(p, p2, rectPath[1], rectPath[2], ip);
loc = Location::Right;
}
else return false;
@ -172,28 +139,27 @@ namespace Clipper2Lib {
default: // loc == rInside
if (SegmentsIntersect(p, p2, rectPath[0], rectPath[3], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[3], ip);
loc = Location::Left;
}
else if (SegmentsIntersect(p, p2, rectPath[0], rectPath[1], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[1]);
GetIntersectPoint(p, p2, rectPath[0], rectPath[1], ip);
loc = Location::Top;
}
else if (SegmentsIntersect(p, p2, rectPath[1], rectPath[2], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[1], rectPath[2]);
GetIntersectPoint(p, p2, rectPath[1], rectPath[2], ip);
loc = Location::Right;
}
else if (SegmentsIntersect(p, p2, rectPath[2], rectPath[3], true))
{
ip = GetIntersectPoint64(p, p2, rectPath[2], rectPath[3]);
GetIntersectPoint(p, p2, rectPath[2], rectPath[3], ip);
loc = Location::Bottom;
}
else return false;
break;
}
return true;
}
@ -214,7 +180,7 @@ namespace Clipper2Lib {
}
inline bool IsClockwise(Location prev, Location curr,
Point64 prev_pt, Point64 curr_pt, Point64 rect_mp)
const Point64& prev_pt, const Point64& curr_pt, const Point64& rect_mp)
{
if (AreOpposites(prev, curr))
return CrossProduct(prev_pt, rect_mp, curr_pt) < 0;
@ -481,7 +447,7 @@ namespace Clipper2Lib {
int i = 1, highI = static_cast<int>(path.size()) - 1;
Location prev = Location::Inside, loc;
Location crossing_loc = Location::Inside;
Location crossing_loc;
if (!GetLocation(rect_, path[0], loc))
{
while (i <= highI && !GetLocation(rect_, path[i], prev)) ++i;

View File

@ -33,7 +33,7 @@ namespace Clipper2Lib
void AddCorner(Location prev, Location curr);
void AddCorner(Location& loc, bool isClockwise);
public:
RectClip(const Rect64& rect) :
explicit RectClip(const Rect64& rect) :
rect_(rect),
mp_(rect.MidPoint()),
rectPath_(rect.AsPath()) {}
@ -42,7 +42,7 @@ namespace Clipper2Lib
class RectClipLines : public RectClip {
public:
RectClipLines(const Rect64& rect) : RectClip(rect) {};
explicit RectClipLines(const Rect64& rect) : RectClip(rect) {};
Paths64 Execute(const Path64& path);
};