Revert "Update to Clipper2 1.2+"

This reverts commit 560717de76.
This commit is contained in:
Seth Hillbrand 2023-03-24 12:30:11 -07:00
parent 1fa993303d
commit 4b3709b96b
10 changed files with 4962 additions and 5274 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 2 March 2023 *
* Date : 26 October 2022 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2023 *
* Copyright : Angus Johnson 2010-2022 *
* Purpose : This is the main polygon clipping module *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -10,18 +10,19 @@
#ifndef CLIPPER_ENGINE_H
#define CLIPPER_ENGINE_H
constexpr auto CLIPPER2_VERSION = "1.2.1";
#define CLIPPER2_VERSION "1.0.6"
#include <cstdlib>
#include <iostream>
#include <queue>
#include <stdexcept>
#include <vector>
#include <functional>
#include <numeric>
#include <memory>
#include "clipper.core.h"
#ifdef None
#undef None
#endif
namespace Clipper2Lib {
struct Scanline;
@ -30,13 +31,12 @@ namespace Clipper2Lib {
struct Vertex;
struct LocalMinima;
struct OutRec;
struct HorzSegment;
struct Joiner;
//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
@ -64,7 +64,7 @@ namespace Clipper2Lib {
OutPt* next = nullptr;
OutPt* prev = nullptr;
OutRec* outrec;
HorzSegment* horz = nullptr;
Joiner* joiner = nullptr;
OutPt(const Point64& pt_, OutRec* outrec_): pt(pt_), outrec(outrec_) {
next = this;
@ -86,20 +86,15 @@ 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;
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_
};
~OutRec() { if (splits) delete splits; };
};
///////////////////////////////////////////////////////////////////
@ -131,7 +126,6 @@ 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 {
@ -146,24 +140,11 @@ 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) {}
};
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) { }
pt(pt_), edge1(e1), edge2(e2)
{
}
};
#ifdef USINGZ
@ -174,11 +155,6 @@ 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 {
@ -191,21 +167,21 @@ namespace Clipper2Lib {
bool using_polytree_ = false;
Active* actives_ = nullptr;
Active *sel_ = nullptr;
LocalMinimaList minima_list_; //pointers in case of memory reallocs
LocalMinimaList::iterator current_locmin_iter_;
Joiner *horz_joiners_ = nullptr;
std::vector<LocalMinima*> minima_list_; //pointers in case of memory reallocs
std::vector<LocalMinima*>::iterator current_locmin_iter_;
std::vector<Vertex*> vertex_lists_;
std::priority_queue<int64_t> scanline_list_;
IntersectNodeList intersect_nodes_;
HorzSegmentList horz_seg_list_;
std::vector<HorzJoin> horz_join_list_;
std::vector<IntersectNode> intersect_nodes_;
std::vector<Joiner*> joiner_list_; //pointers in case of memory reallocs
void Reset();
inline void InsertScanline(int64_t y);
inline bool PopScanline(int64_t &y);
inline bool PopLocalMinima(int64_t y, LocalMinima*& local_minima);
void InsertScanline(int64_t y);
bool PopScanline(int64_t &y);
bool PopLocalMinima(int64_t y, LocalMinima *&local_minima);
void DisposeAllOutRecs();
void DisposeVerticesAndLocalMinima();
void DeleteEdges(Active*& e);
inline void AddLocMin(Vertex &vert, PathType polytype, bool is_open);
void AddLocMin(Vertex &vert, PathType polytype, bool is_open);
bool IsContributingClosed(const Active &e) const;
inline bool IsContributingOpen(const Active &e) const;
void SetWindCountForClosedPathEdge(Active &edge);
@ -224,40 +200,38 @@ 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 Vertex* max_vertex,
bool ResetHorzDirection(const Active &horz, const Active *max_pair,
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);
void DoSplitOp(OutRec* outRec, OutPt* splitOp);
inline void AddTrialHorzJoin(OutPt* op);
void ConvertHorzSegsToJoins();
void ProcessHorzJoins();
void Split(Active& e, const Point64& pt);
inline void CheckJoinLeft(Active& e,
const Point64& pt, bool check_curr_x = false);
inline void CheckJoinRight(Active& e,
const Point64& pt, bool check_curr_x = false);
OutPt* DoSplitOp(OutPt* outRecOp, OutPt* splitOp);
Joiner* GetHorzTrialParent(const OutPt* op);
bool OutPtInTrialHorzList(OutPt* op);
void SafeDisposeOutPts(OutPt*& op);
void SafeDeleteOutPtJoiners(OutPt* op);
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);
protected:
int error_code_ = 0;
bool has_open_paths_ = false;
bool succeeded_ = true;
OutRecList outrec_list_; //pointers in case list memory reallocated
std::vector<OutRec*> outrec_list_; //pointers in case list memory reallocated
bool ExecuteInternal(ClipType ct, FillRule ft, bool use_polytrees);
void CleanCollinear(OutRec* outrec);
bool CheckBounds(OutRec* outrec);
void RecursiveCheckOwners(OutRec* outrec, PolyPath* polypath);
void DeepCheckOwners(OutRec* outrec, PolyPath* polypath);
bool DeepCheckOwner(OutRec* outrec, OutRec* owner);
#ifdef USINGZ
ZCallback64 zCallback_ = nullptr;
void SetZ(const Active& e1, const Active& e2, Point64& pt);
@ -267,13 +241,9 @@ namespace Clipper2Lib {
void AddPaths(const Paths64& paths, PathType polytype, bool is_open);
public:
virtual ~ClipperBase();
int ErrorCode() { return error_code_; };
bool PreserveCollinear = true;
bool ReverseSolution = false;
void Clear();
#ifdef USINGZ
int64_t DefaultZ = 0;
#endif
};
// PolyPath / PolyTree --------------------------------------------------------
@ -288,7 +258,7 @@ namespace Clipper2Lib {
PolyPath* parent_;
public:
PolyPath(PolyPath* parent = nullptr): parent_(parent){}
virtual ~PolyPath() {};
virtual ~PolyPath() { Clear(); };
//https://en.cppreference.com/w/cpp/language/rule_of_three
PolyPath(const PolyPath&) = delete;
PolyPath& operator=(const PolyPath&) = delete;
@ -303,56 +273,49 @@ namespace Clipper2Lib {
virtual PolyPath* AddChild(const Path64& path) = 0;
virtual void Clear() = 0;
virtual void Clear() {};
virtual size_t Count() const { return 0; }
const PolyPath* Parent() const { return parent_; }
bool IsHole() const
{
unsigned lvl = Level();
//Even levels except level 0
return lvl && !(lvl & 1);
const PolyPath* pp = parent_;
bool is_hole = pp;
while (pp) {
is_hole = !is_hole;
pp = pp->parent_;
}
return is_hole;
}
};
typedef typename std::vector<std::unique_ptr<PolyPath64>> PolyPath64List;
typedef typename std::vector<std::unique_ptr<PolyPathD>> PolyPathDList;
class PolyPath64 : public PolyPath {
private:
PolyPath64List childs_;
std::vector<PolyPath64*> childs_;
Path64 polygon_;
typedef typename std::vector<PolyPath64*>::const_iterator pp64_itor;
public:
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(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(); }
PolyPath64* AddChild(const Path64& path) override
{
auto p = std::make_unique<PolyPath64>(this);
auto* result = childs_.emplace_back(std::move(p)).get();
PolyPath64* result = new PolyPath64(this);
childs_.push_back(result);
result->polygon_ = path;
return result;
}
void Clear() override
{
for (PolyPath64* child : childs_)
{
child->Clear();
delete child;
}
childs_.resize(0);
}
@ -361,58 +324,78 @@ namespace Clipper2Lib {
return childs_.size();
}
const Path64& Polygon() const { return polygon_; };
const Path64 Polygon() const { return polygon_; };
double Area() const
{
return std::accumulate(childs_.cbegin(), childs_.cend(),
Clipper2Lib::Area<int64_t>(polygon_),
[](double a, const auto& child) {return a + child->Area(); });
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;
}
};
class PolyPathD : public PolyPath {
private:
PolyPathDList childs_;
std::vector<PolyPathD*> childs_;
double inv_scale_;
PathD polygon_;
typedef typename std::vector<PolyPathD*>::const_iterator ppD_itor;
public:
explicit PolyPathD(PolyPathD* parent = nullptr) : PolyPath(parent)
PolyPathD(PolyPathD* parent = nullptr) : PolyPath(parent)
{
inv_scale_ = parent ? parent->inv_scale_ : 1.0;
}
~PolyPathD() {
childs_.resize(0);
}
const PolyPathD* operator [] (size_t index) const
PolyPathD* operator [] (size_t index)
{
return childs_[index].get();
return static_cast<PolyPathD*>(childs_[index]);
}
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(); }
ppD_itor begin() const { return childs_.cbegin(); }
ppD_itor end() const { return childs_.cend(); }
void SetInvScale(double value) { inv_scale_ = value; }
double InvScale() { return inv_scale_; }
PolyPathD* AddChild(const Path64& path) override
{
int error_code = 0;
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_, error_code);
PolyPathD* result = new PolyPathD(this);
childs_.push_back(result);
result->polygon_ = ScalePath<double, int64_t>(path, inv_scale_);
return result;
}
void Clear() override
{
for (const PolyPathD* child : childs_) delete child;
childs_.resize(0);
}
@ -421,13 +404,14 @@ namespace Clipper2Lib {
return childs_.size();
}
const PathD& Polygon() const { return polygon_; };
const PathD Polygon() const { return polygon_; };
double Area() const
{
return std::accumulate(childs_.begin(), childs_.end(),
Clipper2Lib::Area<double>(polygon_),
[](double a, const auto& child) {return a + child->Area(); });
double result = Clipper2Lib::Area<double>(polygon_);
for (const PolyPathD* child : childs_)
result += child->Area();
return result;
}
};
@ -496,23 +480,19 @@ namespace Clipper2Lib {
private:
double scale_ = 1.0, invScale_ = 1.0;
#ifdef USINGZ
ZCallbackD zCallbackD_ = nullptr;
ZCallbackD zCallback_ = nullptr;
#endif
void BuildPathsD(PathsD& solutionClosed, PathsD* solutionOpen);
void BuildTreeD(PolyPathD& polytree, PathsD& open_paths);
public:
explicit ClipperD(int precision = 2) : ClipperBase()
{
CheckPrecision(precision, error_code_);
// 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);
scale_ = std::pow(10, precision);
invScale_ = 1 / scale_;
}
#ifdef USINGZ
void SetZCallback(ZCallbackD cb) { zCallbackD_ = cb; };
void SetZCallback(ZCallbackD cb) { zCallback_ = cb; };
void ZCB(const Point64& e1bot, const Point64& e1top,
const Point64& e2bot, const Point64& e2top, Point64& pt)
@ -526,13 +506,13 @@ namespace Clipper2Lib {
PointD e1t = PointD(e1top) * invScale_;
PointD e2b = PointD(e2bot) * invScale_;
PointD e2t = PointD(e2top) * invScale_;
zCallbackD_(e1b,e1t, e2b, e2t, tmp);
zCallback_(e1b,e1t, e2b, e2t, tmp);
pt.z = tmp.z; // only update 'z'
};
void CheckCallback()
{
if(zCallbackD_)
if(zCallback_)
// if the user defined float point callback has been assigned
// then assign the proxy callback function
ClipperBase::zCallback_ =
@ -547,17 +527,17 @@ namespace Clipper2Lib {
void AddSubject(const PathsD& subjects)
{
AddPaths(ScalePaths<int64_t, double>(subjects, scale_, error_code_), PathType::Subject, false);
AddPaths(ScalePaths<int64_t, double>(subjects, scale_), PathType::Subject, false);
}
void AddOpenSubject(const PathsD& open_subjects)
{
AddPaths(ScalePaths<int64_t, double>(open_subjects, scale_, error_code_), PathType::Subject, true);
AddPaths(ScalePaths<int64_t, double>(open_subjects, scale_), PathType::Subject, true);
}
void AddClip(const PathsD& clips)
{
AddPaths(ScalePaths<int64_t, double>(clips, scale_, error_code_), PathType::Clip, false);
AddPaths(ScalePaths<int64_t, double>(clips, scale_), PathType::Clip, false);
}
bool Execute(ClipType clip_type, FillRule fill_rule, PathsD& closed_paths)

View File

@ -1,23 +1,23 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 12 February 2023 *
* Date : 28 October 2022 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2023 *
* Copyright : Angus Johnson 2010-2022 *
* Purpose : This module exports the Clipper2 Library (ie DLL/so) *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
// The exported functions below refer to simple structures that
// can be understood across multiple languages. Consequently
// Path64, PathD, Polytree64 etc are converted from C++ classes
// Path64, PathD, Polytree64 etc are converted from 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' should be 0, with one exception explained below.)
// __________________________________
// pairs. ('y' must always be 0.)
//__________________________________
// |counter|coord1|coord2|...|coordN|
// |N ,0 |x1, y1|x2, y2|...|xN, yN|
// __________________________________
@ -25,15 +25,19 @@
// 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 with 'y' (not 'x')
// containing the number of paths that follow. ('x' = 0).
// path' has a single x,y coord pair where 'y' contains
// the number of paths that follow (and with 'x' always 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 these structures don't need to be explained here.
// 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.
#ifndef CLIPPER2_EXPORT_H
#define CLIPPER2_EXPORT_H
@ -97,80 +101,6 @@ 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, bool convex_only = false);
EXTERN_DLL_EXPORT CPathsD RectClipD(const CRectD& rect,
const CPathsD paths, int precision = 2, bool convex_only = false);
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);
@ -184,14 +114,17 @@ inline PathD ConvertCPathD(const CPathD& p);
inline PathsD ConvertCPathsD(const CPathsD& pp);
// the following function avoid multiple conversions
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 CPathD CreateCPathD(const Path64& p, double scale);
inline CPathsD CreateCPathsD(const Paths64& 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;
@ -235,7 +168,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, bool reverse_solution)
bool preserve_collinear = true, bool reverse_solution = false)
{
if (cliptype > static_cast<uint8_t>(ClipType::Xor)) return -4;
if (fillrule > static_cast<uint8_t>(FillRule::Negative)) return -3;
@ -262,7 +195,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, bool reverse_solution)
bool preserve_collinear = true, bool reverse_solution = false)
{
if (cliptype > static_cast<uint8_t>(ClipType::Xor)) return -4;
if (fillrule > static_cast<uint8_t>(FillRule::Negative)) return -3;
@ -289,8 +222,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,
bool preserve_collinear, bool reverse_solution)
CPathsD& solution, CPathsD& solution_open, int precision = 2,
bool preserve_collinear = true, bool reverse_solution = false)
{
if (precision < -8 || precision > 8) return -5;
if (cliptype > static_cast<uint8_t>(ClipType::Xor)) return -4;
@ -321,8 +254,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,
bool preserve_collinear, bool reverse_solution)
CPolyTreeD*& solution, CPathsD& solution_open, int precision = 2,
bool preserve_collinear = true, bool reverse_solution = false)
{
if (precision < -8 || precision > 8) return -5;
if (cliptype > static_cast<uint8_t>(ClipType::Xor)) return -4;
@ -352,56 +285,84 @@ EXTERN_DLL_EXPORT int BooleanOpPtD(uint8_t cliptype,
}
EXTERN_DLL_EXPORT CPaths64 InflatePaths64(const CPaths64 paths,
double delta, uint8_t jointype, uint8_t endtype, double miter_limit,
double arc_tolerance, bool reverse_solution)
double delta, uint8_t jt, uint8_t et, double miter_limit = 2.0,
double arc_tolerance = 0.0, bool reverse_solution = false)
{
Paths64 pp;
pp = ConvertCPaths64(paths);
ClipperOffset clip_offset( miter_limit,
arc_tolerance, reverse_solution);
clip_offset.AddPaths(pp, JoinType(jointype), EndType(endtype));
clip_offset.AddPaths(pp, JoinType(jt), EndType(et));
Paths64 result = clip_offset.Execute(delta);
return CreateCPaths64(result);
}
EXTERN_DLL_EXPORT CPathsD InflatePathsD(const CPathsD paths,
double delta, uint8_t jointype, uint8_t endtype,
int precision, double miter_limit,
double arc_tolerance, bool reverse_solution)
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)
{
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(jointype), EndType(endtype));
clip_offset.AddPaths(pp, JoinType(jt), EndType(et));
Paths64 result = clip_offset.Execute(delta * scale);
return CreateCPathsD(result, 1/scale);
}
EXTERN_DLL_EXPORT CPaths64 RectClip64(const CRect64& rect,
const CPaths64 paths, bool convex_only)
const CPaths64 paths)
{
log(rect.left);
log(rect.right);
if (CRectIsEmpty(rect) || !paths) return nullptr;
Rect64 r64 = CRectToRect(rect);
class RectClip rc(r64);
Paths64 pp = ConvertCPaths64(paths);
Paths64 result = rc.Execute(pp, convex_only);
Paths64 result;
result.reserve(pp.size());
for (const Path64& p : pp)
{
Rect64 pathRec = Bounds(p);
if (!r64.Intersects(pathRec)) continue;
if (r64.Contains(pathRec))
result.push_back(p);
else
{
Path64 p2 = rc.Execute(p);
if (!p2.empty()) result.push_back(std::move(p2));
}
}
return CreateCPaths64(result);
}
EXTERN_DLL_EXPORT CPathsD RectClipD(const CRectD& rect,
const CPathsD paths, int precision, bool convex_only)
const CPathsD paths, int precision = 2)
{
if (CRectIsEmpty(rect) || !paths) return nullptr;
if (precision < -8 || precision > 8) return nullptr;
const double scale = std::pow(10, precision);
RectD r = CRectToRect(rect);
Rect64 rec = ScaleRect<int64_t, double>(r, scale);
Rect64 r = ScaleRect<int64_t, double>(CRectToRect(rect), scale);
Paths64 pp = ConvertCPathsD(paths, scale);
class RectClip rc(rec);
Paths64 result = rc.Execute(pp, convex_only);
class RectClip rc(r);
Paths64 result;
result.reserve(pp.size());
for (const Path64& p : pp)
{
Rect64 pathRec = Bounds(p);
if (!r.Intersects(pathRec)) continue;
if (r.Contains(pathRec))
result.push_back(p);
else
{
Path64 p2 = rc.Execute(p);
if (!p2.empty()) result.push_back(std::move(p2));
}
}
return CreateCPathsD(result, 1/scale);
}
@ -412,27 +373,58 @@ EXTERN_DLL_EXPORT CPaths64 RectClipLines64(const CRect64& rect,
Rect64 r = CRectToRect(rect);
class RectClipLines rcl (r);
Paths64 pp = ConvertCPaths64(paths);
Paths64 result = rcl.Execute(pp);
Paths64 result;
result.reserve(pp.size());
for (const Path64& p : pp)
{
Rect64 pathRec = Bounds(p);
if (!r.Intersects(pathRec)) continue;
if (r.Contains(pathRec))
result.push_back(p);
else
{
Paths64 pp2 = rcl.Execute(p);
if (!pp2.empty())
result.insert(result.end(), pp2.begin(), pp2.end());
}
}
return CreateCPaths64(result);
}
EXTERN_DLL_EXPORT CPathsD RectClipLinesD(const CRectD& rect,
const CPathsD paths, int precision)
const CPathsD paths, int precision = 2)
{
Paths64 result;
if (CRectIsEmpty(rect) || !paths) return nullptr;
if (precision < -8 || precision > 8) return nullptr;
const double scale = std::pow(10, precision);
Rect64 r = ScaleRect<int64_t, double>(CRectToRect(rect), scale);
class RectClipLines rcl(r);
Paths64 pp = ConvertCPathsD(paths, scale);
Paths64 result = rcl.Execute(pp);
result.reserve(pp.size());
for (const Path64& p : pp)
{
Rect64 pathRec = Bounds(p);
if (!r.Intersects(pathRec)) continue;
if (r.Contains(pathRec))
result.push_back(p);
else
{
Paths64 pp2 = rcl.Execute(p);
if (pp2.empty()) continue;
result.insert(result.end(), pp2.begin(), pp2.end());
}
}
return CreateCPathsD(result, 1/scale);
}
inline CPath64 CreateCPath64(size_t cnt1, size_t cnt2)
{
// allocates memory for CPath64, fills in the counter, and
// returns the structure ready to be filled with path data
// create a dummy counter path
CPath64 result = new int64_t[2 + cnt1 *2];
result[0] = cnt1;
result[1] = cnt2;
@ -441,8 +433,6 @@ 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);
@ -479,8 +469,6 @@ 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
@ -517,8 +505,7 @@ inline Paths64 ConvertCPaths64(const CPaths64& pp)
inline CPathD CreateCPathD(size_t cnt1, size_t cnt2)
{
// allocates memory for CPathD, fills in the counter, and
// returns the structure ready to be filled with path data
// create a dummy path counter
CPathD result = new double[2 + cnt1 * 2];
result[0] = static_cast<double>(cnt1);
result[1] = static_cast<double>(cnt2);
@ -527,8 +514,6 @@ 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);
@ -636,8 +621,6 @@ 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);
@ -653,8 +636,6 @@ 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)
@ -672,17 +653,17 @@ inline CPathsD CreateCPathsD(const Paths64& pp, double scale)
}
inline void InitCPolyPath64(CPolyTree64* cpt,
bool is_hole, const std::unique_ptr <PolyPath64>& pp)
bool is_hole, const PolyPath64* pp)
{
cpt->polygon = CreateCPath64(pp->Polygon());
cpt->is_hole = is_hole;
size_t child_cnt = pp->Count();
cpt->child_count = static_cast<uint32_t>(child_cnt);
cpt->child_count = child_cnt;
cpt->childs = nullptr;
if (!child_cnt) return;
cpt->childs = new CPolyPath64[child_cnt];
CPolyPath64* child = cpt->childs;
for (const std::unique_ptr <PolyPath64>& pp_child : *pp)
for (const PolyPath64* pp_child : *pp)
InitCPolyPath64(child++, !is_hole, pp_child);
}
@ -693,11 +674,11 @@ inline CPolyTree64* CreateCPolyTree64(const PolyTree64& pt)
result->is_hole = false;
size_t child_cnt = pt.Count();
result->childs = nullptr;
result->child_count = static_cast<uint32_t>(child_cnt);
result->child_count = child_cnt;
if (!child_cnt) return result;
result->childs = new CPolyPath64[child_cnt];
CPolyPath64* child = result->childs;
for (const std::unique_ptr <PolyPath64>& pp : pt)
for (const PolyPath64* pp : pt)
InitCPolyPath64(child++, true, pp);
return result;
}
@ -720,17 +701,17 @@ EXTERN_DLL_EXPORT void DisposeExportedCPolyTree64(CPolyTree64*& cpt)
}
inline void InitCPolyPathD(CPolyTreeD* cpt,
bool is_hole, const std::unique_ptr <PolyPath64>& pp, double scale)
bool is_hole, const PolyPath64* pp, double scale)
{
cpt->polygon = CreateCPathD(pp->Polygon(), scale);
cpt->is_hole = is_hole;
size_t child_cnt = pp->Count();
cpt->child_count = static_cast<uint32_t>(child_cnt);
cpt->child_count = child_cnt;
cpt->childs = nullptr;
if (!child_cnt) return;
cpt->childs = new CPolyPathD[child_cnt];
CPolyPathD* child = cpt->childs;
for (const std::unique_ptr <PolyPath64>& pp_child : *pp)
for (const PolyPath64* pp_child : *pp)
InitCPolyPathD(child++, !is_hole, pp_child, scale);
}
@ -745,7 +726,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 std::unique_ptr <PolyPath64>& pp : pt)
for (const PolyPath64* pp : pt)
InitCPolyPathD(child++, true, pp, scale);
return result;
}

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 9 February 2023 *
* Date : 26 October 2022 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2023 *
* Copyright : Angus Johnson 2010-2022 *
* Purpose : This module provides a simple interface to the Clipper Library *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -11,7 +11,6 @@
#define CLIPPER_H
#include <cstdlib>
#include <type_traits>
#include <vector>
#include "clipper.core.h"
@ -22,6 +21,21 @@
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)(),
(std::numeric_limits<int64_t>::lowest)(),
(std::numeric_limits<int64_t>::lowest)());
static const RectD MaxInvalidRectD = RectD(
(std::numeric_limits<double>::max)(),
(std::numeric_limits<double>::max)(),
(std::numeric_limits<double>::lowest)(),
(std::numeric_limits<double>::lowest)());
inline Paths64 BooleanOp(ClipType cliptype, FillRule fillrule,
const Paths64& subjects, const Paths64& clips)
{
@ -44,13 +58,12 @@ namespace Clipper2Lib {
}
inline PathsD BooleanOp(ClipType cliptype, FillRule fillrule,
const PathsD& subjects, const PathsD& clips, int precision = 2)
const PathsD& subjects, const PathsD& clips, int decimal_prec = 2)
{
int error_code = 0;
CheckPrecision(precision, error_code);
if (decimal_prec > 8 || decimal_prec < -8)
throw Clipper2Exception(precision_error);
PathsD result;
if (error_code) return result;
ClipperD clipper(precision);
ClipperD clipper(decimal_prec);
clipper.AddSubject(subjects);
clipper.AddClip(clips);
clipper.Execute(cliptype, fillrule, result);
@ -59,13 +72,12 @@ namespace Clipper2Lib {
inline void BooleanOp(ClipType cliptype, FillRule fillrule,
const PathsD& subjects, const PathsD& clips,
PolyTreeD& polytree, int precision = 2)
PolyTreeD& polytree, int decimal_prec = 2)
{
polytree.Clear();
int error_code = 0;
CheckPrecision(precision, error_code);
if (error_code) return;
ClipperD clipper(precision);
if (decimal_prec > 8 || decimal_prec < -8)
throw Clipper2Exception(precision_error);
PathsD result;
ClipperD clipper(decimal_prec);
clipper.AddSubject(subjects);
clipper.AddClip(clips);
clipper.Execute(cliptype, fillrule, polytree);
@ -100,13 +112,12 @@ namespace Clipper2Lib {
return result;
}
inline PathsD Union(const PathsD& subjects, FillRule fillrule, int precision = 2)
inline PathsD Union(const PathsD& subjects, FillRule fillrule, int decimal_prec = 2)
{
if (decimal_prec > 8 || decimal_prec < -8)
throw Clipper2Exception(precision_error);
PathsD result;
int error_code = 0;
CheckPrecision(precision, error_code);
if (error_code) return result;
ClipperD clipper(precision);
ClipperD clipper(decimal_prec);
clipper.AddSubject(subjects);
clipper.Execute(ClipType::Union, fillrule, result);
return result;
@ -133,40 +144,31 @@ namespace Clipper2Lib {
}
inline Paths64 InflatePaths(const Paths64& paths, double delta,
JoinType jt, EndType et, double miter_limit = 2.0,
double arc_tolerance = 0.0)
JoinType jt, EndType et, double miter_limit = 2.0)
{
if (!delta) return paths;
ClipperOffset clip_offset(miter_limit, arc_tolerance);
ClipperOffset clip_offset(miter_limit);
clip_offset.AddPaths(paths, jt, et);
Paths64 solution;
clip_offset.Execute(delta, solution);
return solution;
return clip_offset.Execute(delta);
}
inline PathsD InflatePaths(const PathsD& paths, double delta,
JoinType jt, EndType et, double miter_limit = 2.0,
int precision = 2, double arc_tolerance = 0.0)
JoinType jt, EndType et, double miter_limit = 2.0, double precision = 2)
{
int error_code = 0;
CheckPrecision(precision, error_code);
if (!delta) return paths;
if (error_code) return PathsD();
if (precision < -8 || precision > 8)
throw Clipper2Exception(precision_error);
const double scale = std::pow(10, precision);
ClipperOffset clip_offset(miter_limit, arc_tolerance);
clip_offset.AddPaths(ScalePaths<int64_t,double>(paths, scale, error_code), jt, et);
if (error_code) return PathsD();
Paths64 solution;
clip_offset.Execute(delta * scale, solution);
return ScalePaths<double, int64_t>(solution, 1 / scale, error_code);
ClipperOffset clip_offset(miter_limit);
clip_offset.AddPaths(ScalePaths<int64_t,double>(paths, scale), jt, et);
Paths64 tmp = clip_offset.Execute(delta * scale);
return ScalePaths<double, int64_t>(tmp, 1 / scale);
}
inline Path64 TranslatePath(const Path64& path, int64_t dx, int64_t dy)
{
Path64 result;
result.reserve(path.size());
std::transform(path.begin(), path.end(), back_inserter(result),
[dx, dy](const auto& pt) { return Point64(pt.x + dx, pt.y +dy); });
for (const Point64& pt : path)
result.push_back(Point64(pt.x + dx, pt.y + dy));
return result;
}
@ -174,8 +176,8 @@ namespace Clipper2Lib {
{
PathD result;
result.reserve(path.size());
std::transform(path.begin(), path.end(), back_inserter(result),
[dx, dy](const auto& pt) { return PointD(pt.x + dx, pt.y + dy); });
for (const PointD& pt : path)
result.push_back(PointD(pt.x + dx, pt.y + dy));
return result;
}
@ -183,8 +185,8 @@ namespace Clipper2Lib {
{
Paths64 result;
result.reserve(paths.size());
std::transform(paths.begin(), paths.end(), back_inserter(result),
[dx, dy](const auto& path) { return TranslatePath(path, dx, dy); });
for (const Path64& path : paths)
result.push_back(TranslatePath(path, dx, dy));
return result;
}
@ -192,79 +194,220 @@ namespace Clipper2Lib {
{
PathsD result;
result.reserve(paths.size());
std::transform(paths.begin(), paths.end(), back_inserter(result),
[dx, dy](const auto& path) { return TranslatePath(path, dx, dy); });
for (const PathD& path : paths)
result.push_back(TranslatePath(path, dx, dy));
return result;
}
inline Paths64 RectClip(const Rect64& rect,
const Paths64& paths, bool convex_only = false)
inline Rect64 Bounds(const Path64& path)
{
Rect64 rec = MaxInvalidRect64;
for (const Point64& pt : path)
{
if (pt.x < rec.left) rec.left = pt.x;
if (pt.x > rec.right) rec.right = pt.x;
if (pt.y < rec.top) rec.top = pt.y;
if (pt.y > rec.bottom) rec.bottom = pt.y;
}
if (rec.IsEmpty()) return Rect64();
return rec;
}
inline Rect64 Bounds(const Paths64& paths)
{
Rect64 rec = MaxInvalidRect64;
for (const Path64& path : paths)
for (const Point64& pt : path)
{
if (pt.x < rec.left) rec.left = pt.x;
if (pt.x > rec.right) rec.right = pt.x;
if (pt.y < rec.top) rec.top = pt.y;
if (pt.y > rec.bottom) rec.bottom = pt.y;
}
if (rec.IsEmpty()) return Rect64();
return rec;
}
inline RectD Bounds(const PathD& path)
{
RectD rec = MaxInvalidRectD;
for (const PointD& pt : path)
{
if (pt.x < rec.left) rec.left = pt.x;
if (pt.x > rec.right) rec.right = pt.x;
if (pt.y < rec.top) rec.top = pt.y;
if (pt.y > rec.bottom) rec.bottom = pt.y;
}
if (rec.IsEmpty()) return RectD();
return rec;
}
inline RectD Bounds(const PathsD& paths)
{
RectD rec = MaxInvalidRectD;
for (const PathD& path : paths)
for (const PointD& pt : path)
{
if (pt.x < rec.left) rec.left = pt.x;
if (pt.x > rec.right) rec.right = pt.x;
if (pt.y < rec.top) rec.top = pt.y;
if (pt.y > rec.bottom) rec.bottom = pt.y;
}
if (rec.IsEmpty()) return RectD();
return rec;
}
inline Path64 ClipRect(const Rect64& rect, const Path64& path)
{
if (rect.IsEmpty() || path.empty()) return Path64();
Rect64 pathRec = Bounds(path);
if (!rect.Intersects(pathRec)) return Path64();
if (rect.Contains(pathRec)) return path;
class RectClip rc(rect);
return rc.Execute(path);
}
inline Paths64 ClipRect(const Rect64& rect, const Paths64& paths)
{
if (rect.IsEmpty() || paths.empty()) return Paths64();
class RectClip rc(rect);
return rc.Execute(paths, convex_only);
Paths64 result;
result.reserve(paths.size());
for (const Path64& p : paths)
{
Rect64 pathRec = Bounds(p);
if (!rect.Intersects(pathRec))
continue;
else if (rect.Contains(pathRec))
result.push_back(p);
else
{
Path64 p2 = rc.Execute(p);
if (!p2.empty()) result.push_back(std::move(p2));
}
}
return result;
}
inline Paths64 RectClip(const Rect64& rect,
const Path64& path, bool convex_only = false)
inline PathD ClipRect(const RectD& rect, const PathD& path, int precision = 2)
{
if (rect.IsEmpty() || path.empty()) return Paths64();
class RectClip rc(rect);
return rc.Execute(Paths64{ path }, convex_only);
}
inline PathsD RectClip(const RectD& rect,
const PathsD& paths, bool convex_only = false, int precision = 2)
{
if (rect.IsEmpty() || paths.empty()) return PathsD();
int error_code = 0;
CheckPrecision(precision, error_code);
if (error_code) return PathsD();
if (rect.IsEmpty() || path.empty() ||
!rect.Contains(Bounds(path))) return PathD();
if (precision < -8 || precision > 8)
throw Clipper2Exception(precision_error);
const double scale = std::pow(10, precision);
Rect64 r = ScaleRect<int64_t, double>(rect, scale);
class RectClip rc(r);
Paths64 pp = ScalePaths<int64_t, double>(paths, scale, error_code);
if (error_code) return PathsD(); // ie: error_code result is lost
return ScalePaths<double, int64_t>(
rc.Execute(pp, convex_only), 1 / scale, error_code);
Path64 p = ScalePath<int64_t, double>(path, scale);
return ScalePath<double, int64_t>(rc.Execute(p), 1 / scale);
}
inline PathsD RectClip(const RectD& rect,
const PathD& path, bool convex_only = false, int precision = 2)
inline PathsD ClipRect(const RectD& rect, const PathsD& paths, int precision = 2)
{
return RectClip(rect, PathsD{ path }, convex_only, precision);
if (rect.IsEmpty() || paths.empty()) return PathsD();
if (precision < -8 || precision > 8)
throw Clipper2Exception(precision_error);
const double scale = std::pow(10, precision);
Rect64 r = ScaleRect<int64_t, double>(rect, scale);
class RectClip rc(r);
PathsD result;
result.reserve(paths.size());
for (const PathD& path : paths)
{
RectD pathRec = Bounds(path);
if (!rect.Intersects(pathRec))
continue;
else if (rect.Contains(pathRec))
result.push_back(path);
else
{
Path64 p = ScalePath<int64_t, double>(path, scale);
p = rc.Execute(p);
if (!p.empty())
result.push_back(ScalePath<double, int64_t>(p, 1 / scale));
}
}
return result;
}
inline Paths64 RectClipLines(const Rect64& rect, const Paths64& lines)
inline Paths64 ClipLinesRect(const Rect64& rect, const Path64& path)
{
if (rect.IsEmpty() || lines.empty()) return Paths64();
Paths64 result;
if (rect.IsEmpty() || path.empty()) return result;
Rect64 pathRec = Bounds(path);
if (!rect.Intersects(pathRec)) return result;
if (rect.Contains(pathRec))
{
result.push_back(path);
return result;
}
class RectClipLines rcl(rect);
return rcl.Execute(lines);
return rcl.Execute(path);
}
inline Paths64 RectClipLines(const Rect64& rect, const Path64& line)
inline Paths64 ClipLinesRect(const Rect64& rect, const Paths64& paths)
{
return RectClipLines(rect, Paths64{ line });
Paths64 result;
if (rect.IsEmpty() || paths.empty()) return result;
class RectClipLines rcl(rect);
for (const Path64& p : paths)
{
Rect64 pathRec = Bounds(p);
if (!rect.Intersects(pathRec))
continue;
else if (rect.Contains(pathRec))
result.push_back(p);
else
{
Paths64 pp = rcl.Execute(p);
if (!pp.empty())
result.insert(result.end(), pp.begin(), pp.end());
}
}
return result;
}
inline PathsD RectClipLines(const RectD& rect, const PathD& line, int precision = 2)
inline PathsD ClipLinesRect(const RectD& rect, const PathD& path, int precision = 2)
{
return RectClip(rect, PathsD{ line }, precision);
}
inline PathsD RectClipLines(const RectD& rect, const PathsD& lines, int precision = 2)
{
if (rect.IsEmpty() || lines.empty()) return PathsD();
int error_code = 0;
CheckPrecision(precision, error_code);
if (error_code) return PathsD();
if (rect.IsEmpty() || path.empty() ||
!rect.Contains(Bounds(path))) return PathsD();
if (precision < -8 || precision > 8)
throw Clipper2Exception(precision_error);
const double scale = std::pow(10, precision);
Rect64 r = ScaleRect<int64_t, double>(rect, scale);
class RectClipLines rcl(r);
Paths64 p = ScalePaths<int64_t, double>(lines, scale, error_code);
if (error_code) return PathsD();
p = rcl.Execute(p);
return ScalePaths<double, int64_t>(p, 1 / scale, error_code);
Path64 p = ScalePath<int64_t, double>(path, scale);
return ScalePaths<double, int64_t>(rcl.Execute(p), 1 / scale);
}
inline PathsD ClipLinesRect(const RectD& rect, const PathsD& paths, int precision = 2)
{
PathsD result;
if (rect.IsEmpty() || paths.empty()) return result;
if (precision < -8 || precision > 8)
throw Clipper2Exception(precision_error);
const double scale = std::pow(10, precision);
Rect64 r = ScaleRect<int64_t, double>(rect, scale);
class RectClipLines rcl(r);
result.reserve(paths.size());
for (const PathD& path : paths)
{
RectD pathRec = Bounds(path);
if (!rect.Intersects(pathRec))
continue;
else if (rect.Contains(pathRec))
result.push_back(path);
else
{
Path64 p = ScalePath<int64_t, double>(path, scale);
Paths64 pp = rcl.Execute(p);
if (pp.empty()) continue;
PathsD ppd = ScalePaths<double, int64_t>(pp, 1 / scale);
result.insert(result.end(), ppd.begin(), ppd.end());
}
}
return result;
}
namespace details
@ -273,219 +416,179 @@ namespace Clipper2Lib {
inline void PolyPathToPaths64(const PolyPath64& polypath, Paths64& paths)
{
paths.push_back(polypath.Polygon());
for (const auto& child : polypath)
PolyPathToPaths64(*child, paths);
for (const PolyPath* child : polypath)
PolyPathToPaths64(*(PolyPath64*)(child), paths);
}
inline void PolyPathToPathsD(const PolyPathD& polypath, PathsD& paths)
{
paths.push_back(polypath.Polygon());
for (const auto& child : polypath)
PolyPathToPathsD(*child, paths);
for (const PolyPath* child : polypath)
PolyPathToPathsD(*(PolyPathD*)(child), paths);
}
inline bool PolyPath64ContainsChildren(const PolyPath64& pp)
{
for (const auto& child : pp)
for (auto ch : pp)
{
// 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;
PolyPath64* child = (PolyPath64*)ch;
for (const Point64& pt : child->Polygon())
{
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 (PointInPolygon(pt, pp.Polygon()) == PointInPolygonResult::IsOutside)
return false;
if (child->Count() > 0 && !PolyPath64ContainsChildren(*child))
return false;
}
return true;
}
static void OutlinePolyPath(std::ostream& os,
bool isHole, size_t count, const std::string& preamble)
inline bool GetInt(std::string::const_iterator& iter, const
std::string::const_iterator& end_iter, int64_t& val)
{
std::string plural = (count == 1) ? "." : "s.";
if (isHole)
val = 0;
bool is_neg = *iter == '-';
if (is_neg) ++iter;
std::string::const_iterator start_iter = iter;
while (iter != end_iter &&
((*iter >= '0') && (*iter <= '9')))
{
if (count)
os << preamble << "+- Hole with " << count <<
" nested polygon" << plural << std::endl;
else
os << preamble << "+- Hole" << std::endl;
val = val * 10 + (static_cast<int64_t>(*iter++) - '0');
}
else
if (is_neg) val = -val;
return (iter != start_iter);
}
inline bool GetFloat(std::string::const_iterator& iter, const
std::string::const_iterator& end_iter, double& val)
{
if (count)
os << preamble << "+- Polygon with " << count <<
" hole" << plural << std::endl;
else
os << preamble << "+- Polygon" << std::endl;
val = 0;
bool is_neg = *iter == '-';
if (is_neg) ++iter;
int dec_pos = 1;
const std::string::const_iterator start_iter = iter;
while (iter != end_iter && (*iter == '.' ||
((*iter >= '0') && (*iter <= '9'))))
{
if (*iter == '.')
{
if (dec_pos != 1) break;
dec_pos = 0;
++iter;
continue;
}
if (dec_pos != 1) --dec_pos;
val = val * 10 + ((int64_t)(*iter++) - '0');
}
if (iter == start_iter || dec_pos == 0) return false;
if (dec_pos < 0)
val *= std::pow(10, dec_pos);
if (is_neg)
val *= -1;
return true;
}
inline void SkipWhiteSpace(std::string::const_iterator& iter,
const std::string::const_iterator& end_iter)
{
while (iter != end_iter && *iter <= ' ') ++iter;
}
inline void SkipSpacesWithOptionalComma(std::string::const_iterator& iter,
const std::string::const_iterator& end_iter)
{
bool comma_seen = false;
while (iter != end_iter)
{
if (*iter == ' ') ++iter;
else if (*iter == ',')
{
if (comma_seen) return; // don't skip 2 commas!
comma_seen = true;
++iter;
}
else return;
}
}
static void OutlinePolyPath64(std::ostream& os, const PolyPath64& pp,
std::string preamble, bool last_child)
inline bool has_one_match(const char c, char* chrs)
{
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);
}
while (*chrs > 0 && c != *chrs) ++chrs;
if (!*chrs) return false;
*chrs = ' '; // only match once per char
return true;
}
static void OutlinePolyPathD(std::ostream& os, const PolyPathD& pp,
std::string preamble, bool last_child)
inline void SkipUserDefinedChars(std::string::const_iterator& iter,
const std::string::const_iterator& end_iter, const std::string& skip_chars)
{
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);
}
const size_t MAX_CHARS = 16;
char buff[MAX_CHARS] = {0};
std::copy(skip_chars.cbegin(), skip_chars.cend(), &buff[0]);
while (iter != end_iter &&
(*iter <= ' ' || has_one_match(*iter, buff))) ++iter;
return;
}
} // 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 (const auto& child : polytree)
details::PolyPathToPaths64(*child, result);
for (auto child : polytree)
details::PolyPathToPaths64(*(PolyPath64*)(child), result);
return result;
}
inline PathsD PolyTreeToPathsD(const PolyTreeD& polytree)
{
PathsD result;
for (const auto& child : polytree)
details::PolyPathToPathsD(*child, result);
for (auto child : polytree)
details::PolyPathToPathsD(*(PolyPathD*)(child), result);
return result;
}
inline bool CheckPolytreeFullyContainsChildren(const PolyTree64& polytree)
{
for (const auto& child : polytree)
for (auto child : polytree)
if (child->Count() > 0 &&
!details::PolyPath64ContainsChildren(*child))
!details::PolyPath64ContainsChildren(*(PolyPath64*)(child)))
return false;
return true;
}
namespace details {
template<typename T, typename U>
inline constexpr void MakePathGeneric(const T list, size_t size,
std::vector<U>& result)
inline Path64 MakePath(const std::string& s)
{
for (size_t i = 0; i < size; ++i)
#ifdef USINGZ
result[i / 2] = U{list[i], list[++i], 0};
#else
result[i / 2] = U{list[i], list[++i]};
#endif
const std::string skip_chars = " ,(){}[]";
Path64 result;
std::string::const_iterator s_iter = s.cbegin();
details::SkipUserDefinedChars(s_iter, s.cend(), skip_chars);
while (s_iter != s.cend())
{
int64_t y = 0, x = 0;
if (!details::GetInt(s_iter, s.cend(), x)) break;
details::SkipSpacesWithOptionalComma(s_iter, s.cend());
if (!details::GetInt(s_iter, s.cend(), y)) break;
result.push_back(Point64(x, y));
details::SkipUserDefinedChars(s_iter, s.cend(), skip_chars);
}
} // end details namespace
template<typename T,
typename std::enable_if<
std::is_integral<T>::value &&
!std::is_same<char, T>::value, bool
>::type = true>
inline Path64 MakePath(const std::vector<T>& list)
{
const auto size = list.size() - list.size() % 2;
if (list.size() != size)
DoError(non_pair_error_i); // non-fatal without exception handling
Path64 result(size / 2); // else ignores unpaired value
details::MakePathGeneric(list, size, result);
return result;
}
template<typename T, std::size_t N,
typename std::enable_if<
std::is_integral<T>::value &&
!std::is_same<char, T>::value, bool
>::type = true>
inline Path64 MakePath(const T(&list)[N])
inline PathD MakePathD(const std::string& s)
{
// Make the compiler error on unpaired value (i.e. no runtime effects).
static_assert(N % 2 == 0, "MakePath requires an even number of arguments");
Path64 result(N / 2);
details::MakePathGeneric(list, N, result);
return result;
const std::string skip_chars = " ,(){}[]";
PathD result;
std::string::const_iterator s_iter = s.cbegin();
details::SkipUserDefinedChars(s_iter, s.cend(), skip_chars);
while (s_iter != s.cend())
{
double y = 0, x = 0;
if (!details::GetFloat(s_iter, s.cend(), x)) break;
details::SkipSpacesWithOptionalComma(s_iter, s.cend());
if (!details::GetFloat(s_iter, s.cend(), y)) break;
result.push_back(PointD(x, y));
details::SkipUserDefinedChars(s_iter, s.cend(), skip_chars);
}
template<typename T,
typename std::enable_if<
std::is_arithmetic<T>::value &&
!std::is_same<char, T>::value, bool
>::type = true>
inline PathD MakePathD(const std::vector<T>& list)
{
const auto size = list.size() - list.size() % 2;
if (list.size() != size)
DoError(non_pair_error_i); // non-fatal without exception handling
PathD result(size / 2); // else ignores unpaired value
details::MakePathGeneric(list, size, result);
return result;
}
template<typename T, std::size_t N,
typename std::enable_if<
std::is_arithmetic<T>::value &&
!std::is_same<char, T>::value, bool
>::type = true>
inline PathD MakePathD(const T(&list)[N])
{
// Make the compiler error on unpaired value (i.e. no runtime effects).
static_assert(N % 2 == 0, "MakePath requires an even number of arguments");
PathD result(N / 2);
details::MakePathGeneric(list, N, result);
return result;
}
@ -538,14 +641,12 @@ namespace Clipper2Lib {
inline PathD TrimCollinear(const PathD& path, int precision, bool is_open_path = false)
{
int error_code = 0;
CheckPrecision(precision, error_code);
if (error_code) return PathD();
if (precision > 8 || precision < -8)
throw Clipper2Exception(precision_error);
const double scale = std::pow(10, precision);
Path64 p = ScalePath<int64_t, double>(path, scale, error_code);
if (error_code) return PathD();
Path64 p = ScalePath<int64_t, double>(path, scale);
p = TrimCollinear(p, is_open_path);
return ScalePath<double, int64_t>(p, 1/scale, error_code);
return ScalePath<double, int64_t>(p, 1/scale);
}
template <typename T>
@ -620,108 +721,6 @@ namespace Clipper2Lib {
return Sqr(a * d - c * b) / (c * c + d * d);
}
inline size_t GetNext(size_t current, size_t high,
const std::vector<bool>& flags)
{
++current;
while (current <= high && flags[current]) ++current;
if (current <= high) return current;
current = 0;
while (flags[current]) ++current;
return current;
}
inline size_t GetPrior(size_t current, size_t high,
const std::vector<bool>& flags)
{
if (current == 0) current = high;
else --current;
while (current > 0 && flags[current]) --current;
if (!flags[current]) return current;
current = high;
while (flags[current]) --current;
return current;
}
template <typename T>
inline Path<T> SimplifyPath(const Path<T> path,
double epsilon, bool isOpenPath = false)
{
const size_t len = path.size(), high = len -1;
const double epsSqr = Sqr(epsilon);
if (len < 4) return Path<T>(path);
std::vector<bool> flags(len);
std::vector<double> distSqr(len);
size_t prior = high, curr = 0, start, next, prior2, next2;
if (isOpenPath)
{
distSqr[0] = MAX_DBL;
distSqr[high] = MAX_DBL;
}
else
{
distSqr[0] = PerpendicDistFromLineSqrd(path[0], path[high], path[1]);
distSqr[high] = PerpendicDistFromLineSqrd(path[high], path[0], path[high - 1]);
}
for (size_t i = 1; i < high; ++i)
distSqr[i] = PerpendicDistFromLineSqrd(path[i], path[i - 1], path[i + 1]);
for (;;)
{
if (distSqr[curr] > epsSqr)
{
start = curr;
do
{
curr = GetNext(curr, high, flags);
} while (curr != start && distSqr[curr] > epsSqr);
if (curr == start) break;
}
prior = GetPrior(curr, high, flags);
next = GetNext(curr, high, flags);
if (next == prior) break;
if (distSqr[next] < distSqr[curr])
{
flags[next] = true;
next = GetNext(next, high, flags);
next2 = GetNext(next, high, flags);
distSqr[curr] = PerpendicDistFromLineSqrd(path[curr], path[prior], path[next]);
if (next != high || !isOpenPath)
distSqr[next] = PerpendicDistFromLineSqrd(path[next], path[curr], path[next2]);
curr = next;
}
else
{
flags[curr] = true;
curr = next;
next = GetNext(next, high, flags);
prior2 = GetPrior(prior, high, flags);
distSqr[curr] = PerpendicDistFromLineSqrd(path[curr], path[prior], path[next]);
if (prior != 0 || !isOpenPath)
distSqr[prior] = PerpendicDistFromLineSqrd(path[prior], path[prior2], path[curr]);
}
}
Path<T> result;
result.reserve(len);
for (typename Path<T>::size_type i = 0; i < len; ++i)
if (!flags[i]) result.push_back(path[i]);
return result;
}
template <typename T>
inline Paths<T> SimplifyPaths(const Paths<T> paths,
double epsilon, bool isOpenPath = false)
{
Paths<T> result;
result.reserve(paths.size());
for (const auto& path : paths)
result.push_back(SimplifyPath(path, epsilon, isOpenPath));
return result;
}
template <typename T>
inline void RDP(const Path<T> path, std::size_t begin,
std::size_t end, double epsSqrd, std::vector<bool>& flags)
@ -765,9 +764,8 @@ namespace Clipper2Lib {
{
Paths<T> result;
result.reserve(paths.size());
std::transform(paths.begin(), paths.end(), back_inserter(result),
[epsilon](const auto& path)
{ return RamerDouglasPeucker<T>(path, epsilon); });
for (const Path<T>& path : paths)
result.push_back(RamerDouglasPeucker<T>(path, epsilon));
return result;
}

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 28 January 2023 *
* Date : 15 October 2022 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2023 *
* Copyright : Angus Johnson 2010-2022 *
* Purpose : Minkowski Sum and Difference *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -92,12 +92,11 @@ namespace Clipper2Lib
inline PathsD MinkowskiSum(const PathD& pattern, const PathD& path, bool isClosed, int decimalPlaces = 2)
{
int error_code = 0;
double scale = pow(10, decimalPlaces);
Path64 pat64 = ScalePath<int64_t, double>(pattern, scale, error_code);
Path64 path64 = ScalePath<int64_t, double>(path, scale, error_code);
Path64 pat64 = ScalePath<int64_t, double>(pattern, scale);
Path64 path64 = ScalePath<int64_t, double>(path, scale);
Paths64 tmp = detail::Union(detail::Minkowski(pat64, path64, true, isClosed), FillRule::NonZero);
return ScalePaths<double, int64_t>(tmp, 1 / scale, error_code);
return ScalePaths<double, int64_t>(tmp, 1 / scale);
}
inline Paths64 MinkowskiDiff(const Path64& pattern, const Path64& path, bool isClosed)
@ -107,12 +106,11 @@ namespace Clipper2Lib
inline PathsD MinkowskiDiff(const PathD& pattern, const PathD& path, bool isClosed, int decimalPlaces = 2)
{
int error_code = 0;
double scale = pow(10, decimalPlaces);
Path64 pat64 = ScalePath<int64_t, double>(pattern, scale, error_code);
Path64 path64 = ScalePath<int64_t, double>(path, scale, error_code);
Path64 pat64 = ScalePath<int64_t, double>(pattern, scale);
Path64 path64 = ScalePath<int64_t, double>(path, scale);
Paths64 tmp = detail::Union(detail::Minkowski(pat64, path64, false, isClosed), FillRule::NonZero);
return ScalePaths<double, int64_t>(tmp, 1 / scale, error_code);
return ScalePaths<double, int64_t>(tmp, 1 / scale);
}
} // Clipper2Lib namespace

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 19 March 2023 *
* Date : 15 October 2022 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2023 *
* Copyright : Angus Johnson 2010-2022 *
* Purpose : Path Offset (Inflate/Shrink) *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -11,7 +11,6 @@
#define CLIPPER_OFFSET_H_
#include "clipper.core.h"
#include "clipper.engine.h"
namespace Clipper2Lib {
@ -24,57 +23,47 @@ enum class EndType {Polygon, Joined, Butt, Square, Round};
//Joined : offsets both sides of a path, with joined ends
//Polygon: offsets only one side of a closed path
class ClipperOffset {
private:
class Group {
public:
Paths64 paths_in;
Paths64 paths_out;
Path64 path;
bool is_reversed = false;
JoinType join_type;
EndType end_type;
Paths64 paths_in_;
Paths64 paths_out_;
Path64 path_;
bool is_reversed_ = false;
JoinType join_type_;
EndType end_type_;
Group(const Paths64& paths, JoinType join_type, EndType end_type) :
paths_in(paths), join_type(join_type), end_type(end_type) {}
paths_in_(paths), join_type_(join_type), end_type_(end_type) {}
};
int error_code_ = 0;
double delta_ = 0.0;
double group_delta_ = 0.0;
double abs_group_delta_ = 0.0;
double temp_lim_ = 0.0;
double steps_per_rad_ = 0.0;
double step_sin_ = 0.0;
double step_cos_ = 0.0;
PathD norms;
Paths64 solution;
std::vector<Group> groups_;
JoinType join_type_ = JoinType::Square;
EndType end_type_ = EndType::Polygon;
double miter_limit_ = 0.0;
double arc_tolerance_ = 0.0;
bool merge_groups_ = true;
bool preserve_collinear_ = false;
bool reverse_solution_ = false;
#if USINGZ
ZCallback64 zCallback64_ = nullptr;
#endif
void DoSquare(Group& group, const Path64& path, size_t j, size_t k);
void DoMiter(Group& group, const Path64& path, size_t j, size_t k, double cos_a);
void DoRound(Group& group, const Path64& path, size_t j, size_t k, double angle);
void BuildNormals(const Path64& path);
void OffsetPolygon(Group& group, Path64& path);
void OffsetOpenJoined(Group& group, Path64& path);
void OffsetOpenPath(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 DoGroupOffset(Group &group);
void ExecuteInternal(double delta);
void DoGroupOffset(Group &group, double delta);
public:
explicit ClipperOffset(double miter_limit = 2.0,
ClipperOffset(double miter_limit = 2.0,
double arc_tolerance = 0.0,
bool preserve_collinear = false,
bool reverse_solution = false) :
@ -84,13 +73,13 @@ public:
~ClipperOffset() { Clear(); };
int ErrorCode() { return error_code_; };
void AddPath(const Path64& path, JoinType jt_, EndType et_);
void AddPaths(const Paths64& paths, JoinType jt_, EndType et_);
void AddPath(const PathD &p, JoinType jt_, EndType et_);
void AddPaths(const PathsD &p, JoinType jt_, EndType et_);
void Clear() { groups_.clear(); norms.clear(); };
void Execute(double delta, Paths64& paths);
void Execute(double delta, PolyTree64& polytree);
Paths64 Execute(double delta);
double MiterLimit() const { return miter_limit_; }
void MiterLimit(double miter_limit) { miter_limit_ = miter_limit; }
@ -99,15 +88,19 @@ public:
double ArcTolerance() const { return arc_tolerance_; }
void ArcTolerance(double arc_tolerance) { arc_tolerance_ = arc_tolerance; }
//MergeGroups: A path group is one or more paths added via the AddPath or
//AddPaths methods. By default these path groups will be offset
//independently of other groups and this may cause overlaps (intersections).
//However, when MergeGroups is enabled, any overlapping offsets will be
//merged (via a clipping union operation) to remove overlaps.
bool MergeGroups() const { return merge_groups_; }
void MergeGroups(bool merge_groups) { merge_groups_ = merge_groups; }
bool PreserveCollinear() const { return preserve_collinear_; }
void PreserveCollinear(bool preserve_collinear){preserve_collinear_ = preserve_collinear;}
bool ReverseSolution() const { return reverse_solution_; }
void ReverseSolution(bool reverse_solution) {reverse_solution_ = reverse_solution;}
#if USINGZ
void SetZCallback(ZCallback64 cb) { zCallback64_ = cb; }
#endif
};
}

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 9 February 2023 *
* Date : 26 October 2022 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2023 *
* Copyright : Angus Johnson 2010-2022 *
* Purpose : FAST rectangular clipping *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -12,7 +12,6 @@
#include <cstdlib>
#include <vector>
#include <queue>
#include "clipper.h"
#include "clipper.core.h"
@ -21,61 +20,30 @@ namespace Clipper2Lib
enum class Location { Left, Top, Right, Bottom, Inside };
class OutPt2;
typedef std::vector<OutPt2*> OutPt2List;
class OutPt2 {
public:
Point64 pt;
size_t owner_idx;
OutPt2List* edge;
OutPt2* next;
OutPt2* prev;
};
//------------------------------------------------------------------------------
// RectClip
//------------------------------------------------------------------------------
class RectClip {
private:
void ExecuteInternal(const Path64& path);
Path64 GetPath(OutPt2*& op);
protected:
const Rect64 rect_;
const Path64 rect_as_path_;
const Point64 rect_mp_;
Rect64 path_bounds_;
std::deque<OutPt2> op_container_;
OutPt2List results_; // each path can be broken into multiples
OutPt2List edges_[8]; // clockwise and counter-clockwise
const Point64 mp_;
const Path64 rectPath_;
Path64 result_;
std::vector<Location> start_locs_;
void CheckEdges();
void TidyEdges(int idx, OutPt2List& cw, OutPt2List& ccw);
void GetNextLocation(const Path64& path,
Location& loc, int& i, int highI);
OutPt2* Add(Point64 pt, bool start_new = false);
void AddCorner(Location prev, Location curr);
void AddCorner(Location& loc, bool isClockwise);
public:
explicit RectClip(const Rect64& rect) :
RectClip(const Rect64& rect) :
rect_(rect),
rect_as_path_(rect.AsPath()),
rect_mp_(rect.MidPoint()) {}
Paths64 Execute(const Paths64& paths, bool convex_only = false);
mp_(rect.MidPoint()),
rectPath_(rect.AsPath()) {}
Path64 Execute(const Path64& path);
};
//------------------------------------------------------------------------------
// RectClipLines
//------------------------------------------------------------------------------
class RectClipLines : public RectClip {
private:
void ExecuteInternal(const Path64& path);
Path64 GetPath(OutPt2*& op);
public:
explicit RectClipLines(const Rect64& rect) : RectClip(rect) {};
Paths64 Execute(const Paths64& paths);
RectClipLines(const Rect64& rect) : RectClip(rect) {};
Paths64 Execute(const Path64& path);
};
} // Clipper2Lib namespace

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 19 March 2023 *
* Date : 15 October 2022 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2023 *
* Copyright : Angus Johnson 2010-2022 *
* Purpose : Path Offset (Inflate/Shrink) *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -20,38 +20,20 @@ const double floating_point_tolerance = 1e-12;
// Miscellaneous methods
//------------------------------------------------------------------------------
void GetBoundsAndLowestPolyIdx(const Paths64& paths, Rect64& r, int & idx)
Paths64::size_type GetLowestPolygonIdx(const Paths64& paths)
{
idx = -1;
r = MaxInvalidRect64;
int64_t lpx = 0;
for (int i = 0; i < static_cast<int>(paths.size()); ++i)
Paths64::size_type result = 0;
Point64 lp = Point64(static_cast<int64_t>(0),
std::numeric_limits<int64_t>::min());
for (Paths64::size_type i = 0 ; i < paths.size(); ++i)
for (const Point64& p : paths[i])
{
if (p.y >= r.bottom)
{
if (p.y > r.bottom || p.x < lpx)
{
idx = i;
lpx = p.x;
r.bottom = p.y;
if (p.y < lp.y || (p.y == lp.y && p.x >= lp.x)) continue;
result = i;
lp = p;
}
}
else if (p.y < r.top) r.top = p.y;
if (p.x > r.right) r.right = p.x;
else if (p.x < r.left) r.left = p.x;
}
//if (idx < 0) r = Rect64(0, 0, 0, 0);
//if (r.top == INT64_MIN) r.bottom = r.top;
//if (r.left == INT64_MIN) r.left = r.right;
}
bool IsSafeOffset(const Rect64& r, double abs_delta)
{
return r.left > min_coord + abs_delta &&
r.right < max_coord - abs_delta &&
r.top > min_coord + abs_delta &&
r.bottom < max_coord - abs_delta;
return result;
}
PointD GetUnitNormal(const Point64& pt1, const Point64& pt2)
@ -98,32 +80,12 @@ inline bool IsClosedPath(EndType et)
inline Point64 GetPerpendic(const Point64& pt, const PointD& norm, double delta)
{
#if USINGZ
return Point64(pt.x + norm.x * delta, pt.y + norm.y * delta, pt.z);
#else
return Point64(pt.x + norm.x * delta, pt.y + norm.y * delta);
#endif
}
inline PointD GetPerpendicD(const Point64& pt, const PointD& norm, double delta)
{
#if USINGZ
return PointD(pt.x + norm.x * delta, pt.y + norm.y * delta, pt.z);
#else
return PointD(pt.x + norm.x * delta, pt.y + norm.y * delta);
#endif
}
inline void NegatePath(PathD& path)
{
for (PointD& pt : path)
{
pt.x = -pt.x;
pt.y = -pt.y;
#if USINGZ
pt.z = pt.z;
#endif
}
}
//------------------------------------------------------------------------------
@ -143,6 +105,19 @@ void ClipperOffset::AddPaths(const Paths64 &paths, JoinType jt_, EndType et_)
groups_.push_back(Group(paths, jt_, et_));
}
void ClipperOffset::AddPath(const Clipper2Lib::PathD& path, JoinType jt_, EndType et_)
{
PathsD paths;
paths.push_back(path);
AddPaths(paths, jt_, et_);
}
void ClipperOffset::AddPaths(const PathsD& paths, JoinType jt_, EndType et_)
{
if (paths.size() == 0) return;
groups_.push_back(Group(PathsDToPaths64(paths), jt_, et_));
}
void ClipperOffset::BuildNormals(const Path64& path)
{
norms.clear();
@ -156,20 +131,12 @@ void ClipperOffset::BuildNormals(const Path64& path)
inline PointD TranslatePoint(const PointD& pt, double dx, double dy)
{
#if USINGZ
return PointD(pt.x + dx, pt.y + dy, pt.z);
#else
return PointD(pt.x + dx, pt.y + dy);
#endif
}
inline PointD ReflectPoint(const PointD& pt, const PointD& pivot)
{
#if USINGZ
return PointD(pivot.x + (pivot.x - pt.x), pivot.y + (pivot.y - pt.y), pt.z);
#else
return PointD(pivot.x + (pivot.x - pt.x), pivot.y + (pivot.y - pt.y));
#endif
}
PointD IntersectPoint(const PointD& pt1a, const PointD& pt1b,
@ -223,69 +190,47 @@ void ClipperOffset::DoSquare(Group& group, const Path64& path, size_t j, size_t
{
PointD pt4 = PointD(pt3.x + vec.x * group_delta_, pt3.y + vec.y * group_delta_);
PointD pt = IntersectPoint(pt1, pt2, pt3, pt4);
#if USINGZ
pt.z = ptQ.z;
#endif
//get the second intersect point through reflecion
group.path.push_back(Point64(ReflectPoint(pt, ptQ)));
group.path.push_back(Point64(pt));
group.path_.push_back(Point64(ReflectPoint(pt, ptQ)));
group.path_.push_back(Point64(pt));
}
else
{
PointD pt4 = GetPerpendicD(path[j], norms[k], group_delta_);
PointD pt = IntersectPoint(pt1, pt2, pt3, pt4);
#if USINGZ
pt.z = ptQ.z;
#endif
group.path.push_back(Point64(pt));
group.path_.push_back(Point64(pt));
//get the second intersect point through reflecion
group.path.push_back(Point64(ReflectPoint(pt, ptQ)));
group.path_.push_back(Point64(ReflectPoint(pt, ptQ)));
}
}
void ClipperOffset::DoMiter(Group& group, const Path64& path, size_t j, size_t k, double cos_a)
{
double q = group_delta_ / (cos_a + 1);
#if USINGZ
group.path.push_back(Point64(
path[j].x + (norms[k].x + norms[j].x) * q,
path[j].y + (norms[k].y + norms[j].y) * q,
path[j].z));
#else
group.path.push_back(Point64(
group.path_.push_back(Point64(
path[j].x + (norms[k].x + norms[j].x) * q,
path[j].y + (norms[k].y + norms[j].y) * q));
#endif
}
void ClipperOffset::DoRound(Group& group, const Path64& path, size_t j, size_t k, double angle)
{
//even though angle may be negative this is a convex join
Point64 pt = path[j];
PointD offsetVec = PointD(norms[k].x * group_delta_, norms[k].y * group_delta_);
int steps = static_cast<int>(std::ceil(steps_per_rad_ * std::abs(angle)));
double step_sin = std::sin(angle / steps);
double step_cos = std::cos(angle / steps);
if (j == k) offsetVec.Negate();
#if USINGZ
group.path.push_back(Point64(pt.x + offsetVec.x, pt.y + offsetVec.y, pt.z));
#else
group.path.push_back(Point64(pt.x + offsetVec.x, pt.y + offsetVec.y));
#endif
if (angle > -PI + 0.01) // avoid 180deg concave
{
int steps = std::max(2, static_cast<int>(
std::ceil(steps_per_rad_ * std::abs(angle)))); // #448
for (int i = 1; i < steps; ++i) // ie 1 less than steps
{
offsetVec = PointD(offsetVec.x * step_cos_ - step_sin_ * offsetVec.y,
offsetVec.x * step_sin_ + offsetVec.y * step_cos_);
#if USINGZ
group.path.push_back(Point64(pt.x + offsetVec.x, pt.y + offsetVec.y, pt.z));
#else
group.path.push_back(Point64(pt.x + offsetVec.x, pt.y + offsetVec.y));
#endif
PointD pt2 = PointD(norms[k].x * group_delta_, norms[k].y * group_delta_);
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++)
{
pt2 = PointD(pt2.x * step_cos - step_sin * pt2.y,
pt2.x * step_sin + pt2.y * step_cos);
group.path_.push_back(Point64(pt.x + pt2.x, pt.y + pt2.y));
}
}
group.path.push_back(GetPerpendic(path[j], norms[j], group_delta_));
group.path_.push_back(GetPerpendic(path[j], norms[j], group_delta_));
}
void ClipperOffset::OffsetPoint(Group& group, Path64& path, size_t j, size_t& k)
@ -303,22 +248,27 @@ 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;
if (cos_a > 0.99) // almost straight - less than 8 degrees
bool almostNoAngle = AlmostZero(sin_a) && cos_a > 0;
// when there's almost no angle of deviation or it's concave
if (almostNoAngle || (sin_a * group_delta_ < 0))
{
group.path.push_back(GetPerpendic(path[j], norms[k], group_delta_));
if (cos_a < 0.9998) // greater than 1 degree (#424)
group.path.push_back(GetPerpendic(path[j], norms[j], group_delta_)); // (#418)
}
else if (cos_a > -0.99 && (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)
{
// is concave
group.path.push_back(GetPerpendic(path[j], norms[k], group_delta_));
// this extra point is the only (simple) way to ensure that
// path reversals are fully cleaned with the trailing clipper
group.path.push_back(path[j]); // (#405)
group.path.push_back(GetPerpendic(path[j], norms[j], group_delta_));
// when concave add an extra vertex to ensure neat clipping
if (!almostNoAngle) group.path_.push_back(path[j]);
group.path_.push_back(p2);
}
else if (join_type_ == JoinType::Round)
}
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)
{
@ -332,49 +282,38 @@ void ClipperOffset::OffsetPoint(Group& group, Path64& path, size_t j, size_t& k)
DoMiter(group, path, j, k, cos_a);
else
DoSquare(group, path, j, k);
}
k = j;
}
void ClipperOffset::OffsetPolygon(Group& group, Path64& path)
{
group.path_.clear();
for (Path64::size_type i = 0, j = path.size() -1; i < path.size(); j = i, ++i)
OffsetPoint(group, path, i, j);
group.paths_out.push_back(group.path);
group.paths_out_.push_back(group.path_);
}
void ClipperOffset::OffsetOpenJoined(Group& group, Path64& path)
{
OffsetPolygon(group, path);
std::reverse(path.begin(), path.end());
//rebuild normals // BuildNormals(path);
std::reverse(norms.begin(), norms.end());
norms.push_back(norms[0]);
norms.erase(norms.begin());
NegatePath(norms);
group.path.clear();
BuildNormals(path);
OffsetPolygon(group, path);
}
void ClipperOffset::OffsetOpenPath(Group& group, Path64& path)
void ClipperOffset::OffsetOpenPath(Group& group, Path64& path, EndType end_type)
{
group.path_.clear();
// do the line start cap
switch (end_type_)
switch (end_type)
{
case EndType::Butt:
#if USINGZ
group.path.push_back(Point64(
path[0].x - norms[0].x * group_delta_,
path[0].y - norms[0].y * group_delta_,
path[0].z));
#else
group.path.push_back(Point64(
group.path_.push_back(Point64(
path[0].x - norms[0].x * group_delta_,
path[0].y - norms[0].y * group_delta_));
#endif
group.path.push_back(GetPerpendic(path[0], norms[0], group_delta_));
group.path_.push_back(GetPerpendic(path[0], norms[0], group_delta_));
break;
case EndType::Round:
DoRound(group, path, 0,0, PI);
@ -396,20 +335,13 @@ void ClipperOffset::OffsetOpenPath(Group& group, Path64& path)
norms[0] = norms[highI];
// do the line end cap
switch (end_type_)
switch (end_type)
{
case EndType::Butt:
#if USINGZ
group.path.push_back(Point64(
path[highI].x - norms[highI].x * group_delta_,
path[highI].y - norms[highI].y * group_delta_,
path[highI].z));
#else
group.path.push_back(Point64(
group.path_.push_back(Point64(
path[highI].x - norms[highI].x * group_delta_,
path[highI].y - norms[highI].y * group_delta_));
#endif
group.path.push_back(GetPerpendic(path[highI], norms[highI], group_delta_));
group.path_.push_back(GetPerpendic(path[highI], norms[highI], group_delta_));
break;
case EndType::Round:
DoRound(group, path, highI, highI, PI);
@ -421,198 +353,133 @@ void ClipperOffset::OffsetOpenPath(Group& group, Path64& path)
for (size_t i = highI, k = 0; i > 0; --i)
OffsetPoint(group, path, i, k);
group.paths_out.push_back(group.path);
group.paths_out_.push_back(group.path_);
}
void ClipperOffset::DoGroupOffset(Group& group)
void ClipperOffset::DoGroupOffset(Group& group, double delta)
{
Rect64 r;
int idx = -1;
if (group.end_type_ != EndType::Polygon) delta = std::abs(delta) * 0.5;
bool isClosedPaths = IsClosedPath(group.end_type_);
if (isClosedPaths)
{
//the lowermost polygon must be an outer polygon. So we can use that as the
//designated orientation for outer polygons (needed for tidy-up clipping)
GetBoundsAndLowestPolyIdx(group.paths_in, r, idx);
if (idx < 0) return;
if (group.end_type == EndType::Polygon)
{
double area = Area(group.paths_in[idx]);
//if (area == 0) return; // probably unhelpful (#430)
group.is_reversed = (area < 0);
if (group.is_reversed) group_delta_ = -delta_;
else group_delta_ = delta_;
Paths64::size_type lowestIdx = GetLowestPolygonIdx(group.paths_in_);
// nb: don't use the default orientation here ...
double area = Area(group.paths_in_[lowestIdx]);
if (area == 0) return;
group.is_reversed_ = (area < 0);
if (group.is_reversed_) delta = -delta;
}
else
{
group.is_reversed = false;
group_delta_ = std::abs(delta_) * 0.5;
}
abs_group_delta_ = std::fabs(group_delta_);
group.is_reversed_ = false;
// do range checking
if (!IsSafeOffset(r, abs_group_delta_))
group_delta_ = delta;
abs_group_delta_ = std::abs(group_delta_);
join_type_ = group.join_type_;
double arcTol = (arc_tolerance_ > floating_point_tolerance ? arc_tolerance_
: std::log10(2 + abs_group_delta_) * default_arc_tolerance); // empirically derived
//calculate a sensible number of steps (for 360 deg for the given offset
if (group.join_type_ == JoinType::Round || group.end_type_ == EndType::Round)
{
DoError(range_error_i);
error_code_ |= range_error_i;
return;
steps_per_rad_ = PI / std::acos(1 - arcTol / abs_group_delta_) / (PI *2);
}
join_type_ = group.join_type;
end_type_ = group.end_type;
//calculate a sensible number of steps (for 360 deg for the given offset
if (group.join_type == JoinType::Round || group.end_type == EndType::Round)
{
// arcTol - when arc_tolerance_ is undefined (0), the amount of
// curve imprecision that's allowed is based on the size of the
// offset (delta). Obviously very large offsets will almost always
// require much less precision. See also offset_triginometry2.svg
double arcTol = (arc_tolerance_ > floating_point_tolerance ?
std::min(abs_group_delta_, arc_tolerance_) :
std::log10(2 + abs_group_delta_) * default_arc_tolerance);
double steps_per_360 = PI / std::acos(1 - arcTol / abs_group_delta_);
if (steps_per_360 > abs_group_delta_ * PI)
steps_per_360 = abs_group_delta_ * PI; //ie avoids excessive precision
step_sin_ = std::sin(2 * PI / steps_per_360);
step_cos_ = std::cos(2 * PI / steps_per_360);
if (group_delta_ < 0.0) step_sin_ = -step_sin_;
steps_per_rad_ = steps_per_360 / (2 *PI);
}
bool is_joined =
(end_type_ == EndType::Polygon) ||
(end_type_ == EndType::Joined);
bool is_closed_path = IsClosedPath(group.end_type_);
Paths64::const_iterator path_iter;
for(path_iter = group.paths_in.cbegin(); path_iter != group.paths_in.cend(); ++path_iter)
for(path_iter = group.paths_in_.cbegin(); path_iter != group.paths_in_.cend(); ++path_iter)
{
Path64 path = StripDuplicates(*path_iter, is_joined);
Path64 path = StripDuplicates(*path_iter, is_closed_path);
Path64::size_type cnt = path.size();
if (cnt == 0 || ((cnt < 3) && group.end_type == EndType::Polygon))
continue;
if (cnt == 0) continue;
group.path.clear();
if (cnt == 1) // single point - only valid with open paths
{
if (group_delta_ < 1) continue;
group.path_ = Path64();
//single vertex so build a circle or square ...
if (group.join_type == JoinType::Round)
if (group.join_type_ == JoinType::Round)
{
double radius = abs_group_delta_;
group.path = Ellipse(path[0], radius, radius);
#if USINGZ
for (auto& p : group.path) p.z = path[0].z;
#endif
group.path_ = Ellipse(path[0], radius, radius);
}
else
{
int d = (int)std::ceil(abs_group_delta_);
r = Rect64(path[0].x - d, path[0].y - d, path[0].x + d, path[0].y + d);
group.path = r.AsPath();
#if USINGZ
for (auto& p : group.path) p.z = path[0].z;
#endif
Rect64 r = Rect64(path[0].x - d, path[0].y - d, path[0].x + d, path[0].y + d);
group.path_ = r.AsPath();
}
group.paths_out.push_back(group.path);
group.paths_out_.push_back(group.path_);
}
else
{
if ((cnt == 2) && (group.end_type == EndType::Joined))
{
if (group.join_type == JoinType::Round)
end_type_ = EndType::Round;
else
end_type_ = EndType::Square;
BuildNormals(path);
if (group.end_type_ == EndType::Polygon) OffsetPolygon(group, path);
else if (group.end_type_ == EndType::Joined) OffsetOpenJoined(group, path);
else OffsetOpenPath(group, path, group.end_type_);
}
}
BuildNormals(path);
if (end_type_ == EndType::Polygon) OffsetPolygon(group, path);
else if (end_type_ == EndType::Joined) OffsetOpenJoined(group, path);
else OffsetOpenPath(group, path);
if (!merge_groups_)
{
//clean up self-intersections ...
Clipper64 c;
c.PreserveCollinear = false;
//the solution should retain the orientation of the input
c.ReverseSolution = reverse_solution_ != group.is_reversed_;
c.AddSubject(group.paths_out_);
if (group.is_reversed_)
c.Execute(ClipType::Union, FillRule::Negative, group.paths_out_);
else
c.Execute(ClipType::Union, FillRule::Positive, group.paths_out_);
}
}
solution.reserve(solution.size() + group.paths_out.size());
copy(group.paths_out.begin(), group.paths_out.end(), back_inserter(solution));
group.paths_out.clear();
solution.reserve(solution.size() + group.paths_out_.size());
copy(group.paths_out_.begin(), group.paths_out_.end(), back_inserter(solution));
group.paths_out_.clear();
}
void ClipperOffset::ExecuteInternal(double delta)
Paths64 ClipperOffset::Execute(double delta)
{
error_code_ = 0;
solution.clear();
if (groups_.size() == 0) return;
if (std::abs(delta) < 0.5)
if (std::abs(delta) < default_arc_tolerance)
{
for (const Group& group : groups_)
{
solution.reserve(solution.size() + group.paths_in.size());
copy(group.paths_in.begin(), group.paths_in.end(), back_inserter(solution));
solution.reserve(solution.size() + group.paths_in_.size());
copy(group.paths_in_.begin(), group.paths_in_.end(), back_inserter(solution));
}
return solution;
}
else
{
temp_lim_ = (miter_limit_ <= 1) ?
2.0 :
2.0 / (miter_limit_ * miter_limit_);
delta_ = delta;
std::vector<Group>::iterator git;
for (git = groups_.begin(); git != groups_.end(); ++git)
std::vector<Group>::iterator groups_iter;
for (groups_iter = groups_.begin();
groups_iter != groups_.end(); ++groups_iter)
{
DoGroupOffset(*git);
if (!error_code_) continue; // all OK
solution.clear();
DoGroupOffset(*groups_iter, delta);
}
}
}
void ClipperOffset::Execute(double delta, Paths64& paths)
{
paths.clear();
ExecuteInternal(delta);
if (!solution.size()) return;
if (merge_groups_ && groups_.size() > 0)
{
//clean up self-intersections ...
Clipper64 c;
c.PreserveCollinear = false;
//the solution should retain the orientation of the input
c.ReverseSolution = reverse_solution_ != groups_[0].is_reversed;
#if USINGZ
if (zCallback64_) {
c.SetZCallback(zCallback64_);
}
#endif
c.ReverseSolution = reverse_solution_ != groups_[0].is_reversed_;
c.AddSubject(solution);
if (groups_[0].is_reversed)
c.Execute(ClipType::Union, FillRule::Negative, paths);
if (groups_[0].is_reversed_)
c.Execute(ClipType::Union, FillRule::Negative, solution);
else
c.Execute(ClipType::Union, FillRule::Positive, paths);
}
void ClipperOffset::Execute(double delta, PolyTree64& polytree)
{
polytree.Clear();
ExecuteInternal(delta);
if (!solution.size()) return;
//clean up self-intersections ...
Clipper64 c;
c.PreserveCollinear = false;
//the solution should retain the orientation of the input
c.ReverseSolution = reverse_solution_ != groups_[0].is_reversed;
#if USINGZ
if (zCallback64_) {
c.SetZCallback(zCallback64_);
c.Execute(ClipType::Union, FillRule::Positive, solution);
}
#endif
c.AddSubject(solution);
if (groups_[0].is_reversed)
c.Execute(ClipType::Union, FillRule::Negative, polytree);
else
c.Execute(ClipType::Union, FillRule::Positive, polytree);
return solution;
}
} // namespace

View File

@ -1,8 +1,8 @@
/*******************************************************************************
* Author : Angus Johnson *
* Date : 14 February 2023 *
* Date : 26 October 2022 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2023 *
* Copyright : Angus Johnson 2010-2022 *
* Purpose : FAST rectangular clipping *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
@ -17,22 +17,15 @@ namespace Clipper2Lib {
// Miscellaneous methods
//------------------------------------------------------------------------------
inline bool Path1ContainsPath2(const Path64& path1, const Path64& path2)
inline PointInPolygonResult Path1ContainsPath2(Path64 path1, Path64 path2)
{
int io_count = 0;
// precondition: no (significant) overlap
for (const Point64& pt : path2)
PointInPolygonResult result = PointInPolygonResult::IsOn;
for(const Point64& pt : path2)
{
PointInPolygonResult pip = PointInPolygon(pt, path1);
switch (pip)
{
case PointInPolygonResult::IsOutside: ++io_count; break;
case PointInPolygonResult::IsInside: --io_count; break;
default: continue;
result = PointInPolygon(pt, path1);
if (result != PointInPolygonResult::IsOn) break;
}
if (std::abs(io_count) > 1) break;
}
return io_count <= 0;
return result;
}
inline bool GetLocation(const Rect64& rec,
@ -66,6 +59,39 @@ 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)
{
@ -75,16 +101,16 @@ namespace Clipper2Lib {
{
case Location::Left:
if (SegmentsIntersect(p, p2, rectPath[0], rectPath[3], true))
GetIntersectPoint(p, p2, rectPath[0], rectPath[3], ip);
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[3]);
else if (p.y < rectPath[0].y &&
SegmentsIntersect(p, p2, rectPath[0], rectPath[1], true))
{
GetIntersectPoint(p, p2, rectPath[0], rectPath[1], ip);
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[1]);
loc = Location::Top;
}
else if (SegmentsIntersect(p, p2, rectPath[2], rectPath[3], true))
{
GetIntersectPoint(p, p2, rectPath[2], rectPath[3], ip);
ip = GetIntersectPoint64(p, p2, rectPath[2], rectPath[3]);
loc = Location::Bottom;
}
else return false;
@ -92,17 +118,17 @@ namespace Clipper2Lib {
case Location::Top:
if (SegmentsIntersect(p, p2, rectPath[0], rectPath[1], true))
GetIntersectPoint(p, p2, rectPath[0], rectPath[1], ip);
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[1]);
else if (p.x < rectPath[0].x &&
SegmentsIntersect(p, p2, rectPath[0], rectPath[3], true))
{
GetIntersectPoint(p, p2, rectPath[0], rectPath[3], ip);
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[3]);
loc = Location::Left;
}
else if (p.x > rectPath[1].x &&
SegmentsIntersect(p, p2, rectPath[1], rectPath[2], true))
{
GetIntersectPoint(p, p2, rectPath[1], rectPath[2], ip);
ip = GetIntersectPoint64(p, p2, rectPath[1], rectPath[2]);
loc = Location::Right;
}
else return false;
@ -110,16 +136,16 @@ namespace Clipper2Lib {
case Location::Right:
if (SegmentsIntersect(p, p2, rectPath[1], rectPath[2], true))
GetIntersectPoint(p, p2, rectPath[1], rectPath[2], ip);
ip = GetIntersectPoint64(p, p2, rectPath[1], rectPath[2]);
else if (p.y < rectPath[0].y &&
SegmentsIntersect(p, p2, rectPath[0], rectPath[1], true))
{
GetIntersectPoint(p, p2, rectPath[0], rectPath[1], ip);
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[1]);
loc = Location::Top;
}
else if (SegmentsIntersect(p, p2, rectPath[2], rectPath[3], true))
{
GetIntersectPoint(p, p2, rectPath[2], rectPath[3], ip);
ip = GetIntersectPoint64(p, p2, rectPath[2], rectPath[3]);
loc = Location::Bottom;
}
else return false;
@ -127,17 +153,17 @@ namespace Clipper2Lib {
case Location::Bottom:
if (SegmentsIntersect(p, p2, rectPath[2], rectPath[3], true))
GetIntersectPoint(p, p2, rectPath[2], rectPath[3], ip);
ip = GetIntersectPoint64(p, p2, rectPath[2], rectPath[3]);
else if (p.x < rectPath[3].x &&
SegmentsIntersect(p, p2, rectPath[0], rectPath[3], true))
{
GetIntersectPoint(p, p2, rectPath[0], rectPath[3], ip);
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[3]);
loc = Location::Left;
}
else if (p.x > rectPath[2].x &&
SegmentsIntersect(p, p2, rectPath[1], rectPath[2], true))
{
GetIntersectPoint(p, p2, rectPath[1], rectPath[2], ip);
ip = GetIntersectPoint64(p, p2, rectPath[1], rectPath[2]);
loc = Location::Right;
}
else return false;
@ -146,27 +172,28 @@ namespace Clipper2Lib {
default: // loc == rInside
if (SegmentsIntersect(p, p2, rectPath[0], rectPath[3], true))
{
GetIntersectPoint(p, p2, rectPath[0], rectPath[3], ip);
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[3]);
loc = Location::Left;
}
else if (SegmentsIntersect(p, p2, rectPath[0], rectPath[1], true))
{
GetIntersectPoint(p, p2, rectPath[0], rectPath[1], ip);
ip = GetIntersectPoint64(p, p2, rectPath[0], rectPath[1]);
loc = Location::Top;
}
else if (SegmentsIntersect(p, p2, rectPath[1], rectPath[2], true))
{
GetIntersectPoint(p, p2, rectPath[1], rectPath[2], ip);
ip = GetIntersectPoint64(p, p2, rectPath[1], rectPath[2]);
loc = Location::Right;
}
else if (SegmentsIntersect(p, p2, rectPath[2], rectPath[3], true))
{
GetIntersectPoint(p, p2, rectPath[2], rectPath[3], ip);
ip = GetIntersectPoint64(p, p2, rectPath[2], rectPath[3]);
loc = Location::Bottom;
}
else return false;
break;
}
return true;
}
@ -187,7 +214,7 @@ namespace Clipper2Lib {
}
inline bool IsClockwise(Location prev, Location curr,
const Point64& prev_pt, const Point64& curr_pt, const Point64& rect_mp)
Point64 prev_pt, Point64 curr_pt, Point64 rect_mp)
{
if (AreOpposites(prev, curr))
return CrossProduct(prev_pt, rect_mp, curr_pt) < 0;
@ -195,142 +222,29 @@ namespace Clipper2Lib {
return HeadingClockwise(prev, curr);
}
inline OutPt2* UnlinkOp(OutPt2* op)
{
if (op->next == op) return nullptr;
op->prev->next = op->next;
op->next->prev = op->prev;
return op->next;
}
inline OutPt2* UnlinkOpBack(OutPt2* op)
{
if (op->next == op) return nullptr;
op->prev->next = op->next;
op->next->prev = op->prev;
return op->prev;
}
inline uint32_t GetEdgesForPt(const Point64& pt, const Rect64& rec)
{
uint32_t result = 0;
if (pt.x == rec.left) result = 1;
else if (pt.x == rec.right) result = 4;
if (pt.y == rec.top) result += 2;
else if (pt.y == rec.bottom) result += 8;
return result;
}
inline bool IsHeadingClockwise(const Point64& pt1, const Point64& pt2, int edgeIdx)
{
switch (edgeIdx)
{
case 0: return pt2.y < pt1.y;
case 1: return pt2.x > pt1.x;
case 2: return pt2.y > pt1.y;
default: return pt2.x < pt1.x;
}
}
inline bool HasHorzOverlap(const Point64& left1, const Point64& right1,
const Point64& left2, const Point64& right2)
{
return (left1.x < right2.x) && (right1.x > left2.x);
}
inline bool HasVertOverlap(const Point64& top1, const Point64& bottom1,
const Point64& top2, const Point64& bottom2)
{
return (top1.y < bottom2.y) && (bottom1.y > top2.y);
}
inline void AddToEdge(OutPt2List& edge, OutPt2* op)
{
if (op->edge) return;
op->edge = &edge;
edge.push_back(op);
}
inline void UncoupleEdge(OutPt2* op)
{
if (!op->edge) return;
for (size_t i = 0; i < op->edge->size(); ++i)
{
OutPt2* op2 = (*op->edge)[i];
if (op2 == op)
{
(*op->edge)[i] = nullptr;
break;
}
}
op->edge = nullptr;
}
inline void SetNewOwner(OutPt2* op, size_t new_idx)
{
op->owner_idx = new_idx;
OutPt2* op2 = op->next;
while (op2 != op)
{
op2->owner_idx = new_idx;
op2 = op2->next;
}
}
//----------------------------------------------------------------------------
// RectClip64
//----------------------------------------------------------------------------
OutPt2* RectClip::Add(Point64 pt, bool start_new)
{
// this method is only called by InternalExecute.
// Later splitting & rejoining won't create additional op's,
// though they will change the (non-storage) results_ count.
int curr_idx = static_cast<int>(results_.size()) - 1;
OutPt2* result;
if (curr_idx < 0 || start_new)
{
result = &op_container_.emplace_back(OutPt2());
result->pt = pt;
result->next = result;
result->prev = result;
results_.push_back(result);
}
else
{
OutPt2* prevOp = results_[curr_idx];
if (prevOp->pt == pt) return prevOp;
result = &op_container_.emplace_back(OutPt2());
result->owner_idx = curr_idx;
result->pt = pt;
result->next = prevOp->next;
prevOp->next->prev = result;
prevOp->next = result;
result->prev = prevOp;
results_[curr_idx] = result;
}
return result;
}
void RectClip::AddCorner(Location prev, Location curr)
{
if (HeadingClockwise(prev, curr))
Add(rect_as_path_[static_cast<int>(prev)]);
result_.push_back(rectPath_[static_cast<int>(prev)]);
else
Add(rect_as_path_[static_cast<int>(curr)]);
result_.push_back(rectPath_[static_cast<int>(curr)]);
}
void RectClip::AddCorner(Location& loc, bool isClockwise)
{
if (isClockwise)
{
Add(rect_as_path_[static_cast<int>(loc)]);
result_.push_back(rectPath_[static_cast<int>(loc)]);
loc = GetAdjacentLocation(loc, true);
}
else
{
loc = GetAdjacentLocation(loc, false);
Add(rect_as_path_[static_cast<int>(loc)]);
result_.push_back(rectPath_[static_cast<int>(loc)]);
}
}
@ -382,15 +296,19 @@ namespace Clipper2Lib {
else if (path[i].x > rect_.right) loc = Location::Right;
else if (path[i].y > rect_.bottom) loc = Location::Bottom;
else if (path[i].y < rect_.top) loc = Location::Top;
else { Add(path[i]); ++i; continue; }
else { result_.push_back(path[i]); ++i; continue; }
break; //inner loop
}
break;
} //switch
}
void RectClip::ExecuteInternal(const Path64& path)
Path64 RectClip::Execute(const Path64& path)
{
if (rect_.IsEmpty() || path.size() < 3) return Path64();
result_.clear();
start_locs_.clear();
int i = 0, highI = static_cast<int>(path.size()) - 1;
Location prev = Location::Inside, loc;
Location crossing_loc = Location::Inside;
@ -399,16 +317,11 @@ namespace Clipper2Lib {
{
i = highI - 1;
while (i >= 0 && !GetLocation(rect_, path[i], prev)) --i;
if (i < 0)
{
// all of path must be inside fRect
for (const auto& pt : path) Add(pt);
return;
}
if (i < 0) return path;
if (prev == Location::Inside) loc = Location::Inside;
i = 0;
}
Location startingLoc = loc;
Location starting_loc = loc;
///////////////////////////////////////////////////
while (i <= highI)
@ -420,18 +333,16 @@ namespace Clipper2Lib {
if (i > highI) break;
Point64 ip, ip2;
Point64 prev_pt = (i) ?
path[static_cast<size_t>(i - 1)] :
path[highI];
Point64 prev_pt = (i) ? path[static_cast<size_t>(i - 1)] : path[highI];
crossing_loc = loc;
if (!GetIntersection(rect_as_path_,
path[i], prev_pt, crossing_loc, ip))
if (!GetIntersection(rectPath_, path[i], prev_pt, crossing_loc, ip))
{
// ie remaining outside
if (crossing_prev == Location::Inside)
{
bool isClockw = IsClockwise(prev, loc, prev_pt, path[i], rect_mp_);
bool isClockw = IsClockwise(prev, loc, prev_pt, path[i], mp_);
do {
start_locs_.push_back(prev);
prev = GetAdjacentLocation(prev, isClockw);
@ -440,7 +351,7 @@ namespace Clipper2Lib {
}
else if (prev != Location::Inside && prev != loc)
{
bool isClockw = IsClockwise(prev, loc, prev_pt, path[i], rect_mp_);
bool isClockw = IsClockwise(prev, loc, prev_pt, path[i], mp_);
do {
AddCorner(prev, isClockw);
} while (prev != loc);
@ -462,7 +373,7 @@ namespace Clipper2Lib {
}
else if (prev != crossing_loc)
{
bool isClockw = IsClockwise(prev, crossing_loc, prev_pt, path[i], rect_mp_);
bool isClockw = IsClockwise(prev, crossing_loc, prev_pt, path[i], mp_);
do {
AddCorner(prev, isClockw);
} while (prev != crossing_loc);
@ -473,7 +384,7 @@ namespace Clipper2Lib {
// passing right through rect. 'ip' here will be the second
// intersect pt but we'll also need the first intersect pt (ip2)
loc = prev;
GetIntersection(rect_as_path_, prev_pt, path[i], loc, ip2);
GetIntersection(rectPath_, prev_pt, path[i], loc, ip2);
if (crossing_prev != Location::Inside)
AddCorner(crossing_prev, loc);
@ -484,7 +395,7 @@ namespace Clipper2Lib {
}
loc = crossing_loc;
Add(ip2);
result_.push_back(ip2);
if (ip == ip2)
{
// it's very likely that path[i] is on rect
@ -501,33 +412,23 @@ namespace Clipper2Lib {
first_cross_ = crossing_loc;
}
Add(ip);
result_.push_back(ip);
} //while i <= highI
///////////////////////////////////////////////////
if (first_cross_ == Location::Inside)
{
// path never intersects
if (startingLoc != Location::Inside)
{
// path is outside rect
// but being outside, it still may not contain rect
if (path_bounds_.Contains(rect_) &&
Path1ContainsPath2(path, rect_as_path_))
{
// yep, the path does fully contain rect
// so add rect to the solution
for (size_t j = 0; j < 4; ++j)
{
Add(rect_as_path_[j]);
// we may well need to do some splitting later, so
AddToEdge(edges_[j * 2], results_[0]);
if (starting_loc == Location::Inside) return path;
Rect64 tmp_rect = Bounds(path);
if (tmp_rect.Contains(rect_) &&
Path1ContainsPath2(path, rectPath_) !=
PointInPolygonResult::IsOutside) return rectPath_;
else
return Path64();
}
}
}
}
else if (loc != Location::Inside &&
if (loc != Location::Inside &&
(loc != first_cross_ || start_locs_.size() > 2))
{
if (start_locs_.size() > 0)
@ -544,375 +445,54 @@ namespace Clipper2Lib {
if (loc != first_cross_)
AddCorner(loc, HeadingClockwise(loc, first_cross_));
}
}
void RectClip::CheckEdges()
if (result_.size() < 3) return Path64();
// tidy up duplicates and collinear segments
Path64 res;
res.reserve(result_.size());
size_t k = 0; highI = static_cast<int>(result_.size()) - 1;
Point64 prev_pt = result_[highI];
res.push_back(result_[0]);
Path64::const_iterator cit;
for (cit = result_.cbegin() + 1; cit != result_.cend(); ++cit)
{
for (size_t i = 0; i < results_.size(); ++i)
if (CrossProduct(prev_pt, res[k], *cit))
{
OutPt2* op = results_[i];
if (!op) continue;
OutPt2* op2 = op;
do
{
if (!CrossProduct(op2->prev->pt,
op2->pt, op2->next->pt))
{
if (op2 == op)
{
op2 = UnlinkOpBack(op2);
if (!op2) break;
op = op2->prev;
prev_pt = res[k++];
res.push_back(*cit);
}
else
{
op2 = UnlinkOpBack(op2);
if (!op2) break;
}
}
else
op2 = op2->next;
} while (op2 != op);
if (!op2)
{
results_[i] = nullptr;
continue;
}
results_[i] = op; // safety first
uint32_t edgeSet1 = GetEdgesForPt(op->prev->pt, rect_);
op2 = op;
do
{
uint32_t edgeSet2 = GetEdgesForPt(op2->pt, rect_);
if (edgeSet2 && !op2->edge)
{
uint32_t combinedSet = (edgeSet1 & edgeSet2);
for (int j = 0; j < 4; ++j)
{
if (combinedSet & (1 << j))
{
if (IsHeadingClockwise(op2->prev->pt, op2->pt, j))
AddToEdge(edges_[j * 2], op2);
else
AddToEdge(edges_[j * 2 + 1], op2);
}
}
}
edgeSet1 = edgeSet2;
op2 = op2->next;
} while (op2 != op);
}
res[k] = *cit;
}
void RectClip::TidyEdges(int idx, OutPt2List& cw, OutPt2List& ccw)
{
if (ccw.empty()) return;
bool isHorz = ((idx == 1) || (idx == 3));
bool cwIsTowardLarger = ((idx == 1) || (idx == 2));
size_t i = 0, j = 0;
OutPt2* p1, * p2, * p1a, * p2a, * op, * op2;
while (i < cw.size())
{
p1 = cw[i];
if (!p1 || p1->next == p1->prev)
{
cw[i++]->edge = nullptr;
j = 0;
continue;
if (k < 2) return Path64();
// and a final check for collinearity
else if (!CrossProduct(res[0], res[k - 1], res[k])) res.pop_back();
return res;
}
size_t jLim = ccw.size();
while (j < jLim &&
(!ccw[j] || ccw[j]->next == ccw[j]->prev)) ++j;
if (j == jLim)
{
++i;
j = 0;
continue;
}
if (cwIsTowardLarger)
{
// p1 >>>> p1a;
// p2 <<<< p2a;
p1 = cw[i]->prev;
p1a = cw[i];
p2 = ccw[j];
p2a = ccw[j]->prev;
}
else
{
// p1 <<<< p1a;
// p2 >>>> p2a;
p1 = cw[i];
p1a = cw[i]->prev;
p2 = ccw[j]->prev;
p2a = ccw[j];
}
if ((isHorz && !HasHorzOverlap(p1->pt, p1a->pt, p2->pt, p2a->pt)) ||
(!isHorz && !HasVertOverlap(p1->pt, p1a->pt, p2->pt, p2a->pt)))
{
++j;
continue;
}
// to get here we're either splitting or rejoining
bool isRejoining = cw[i]->owner_idx != ccw[j]->owner_idx;
if (isRejoining)
{
results_[p2->owner_idx] = nullptr;
SetNewOwner(p2, p1->owner_idx);
}
// do the split or re-join
if (cwIsTowardLarger)
{
// p1 >> | >> p1a;
// p2 << | << p2a;
p1->next = p2;
p2->prev = p1;
p1a->prev = p2a;
p2a->next = p1a;
}
else
{
// p1 << | << p1a;
// p2 >> | >> p2a;
p1->prev = p2;
p2->next = p1;
p1a->next = p2a;
p2a->prev = p1a;
}
if (!isRejoining)
{
size_t new_idx = results_.size();
results_.push_back(p1a);
SetNewOwner(p1a, new_idx);
}
if (cwIsTowardLarger)
{
op = p2;
op2 = p1a;
}
else
{
op = p1;
op2 = p2a;
}
results_[op->owner_idx] = op;
results_[op2->owner_idx] = op2;
// and now lots of work to get ready for the next loop
bool opIsLarger, op2IsLarger;
if (isHorz) // X
{
opIsLarger = op->pt.x > op->prev->pt.x;
op2IsLarger = op2->pt.x > op2->prev->pt.x;
}
else // Y
{
opIsLarger = op->pt.y > op->prev->pt.y;
op2IsLarger = op2->pt.y > op2->prev->pt.y;
}
if ((op->next == op->prev) ||
(op->pt == op->prev->pt))
{
if (op2IsLarger == cwIsTowardLarger)
{
cw[i] = op2;
ccw[j++] = nullptr;
}
else
{
ccw[j] = op2;
cw[i++] = nullptr;
}
}
else if ((op2->next == op2->prev) ||
(op2->pt == op2->prev->pt))
{
if (opIsLarger == cwIsTowardLarger)
{
cw[i] = op;
ccw[j++] = nullptr;
}
else
{
ccw[j] = op;
cw[i++] = nullptr;
}
}
else if (opIsLarger == op2IsLarger)
{
if (opIsLarger == cwIsTowardLarger)
{
cw[i] = op;
UncoupleEdge(op2);
AddToEdge(cw, op2);
ccw[j++] = nullptr;
}
else
{
cw[i++] = nullptr;
ccw[j] = op2;
UncoupleEdge(op);
AddToEdge(ccw, op);
j = 0;
}
}
else
{
if (opIsLarger == cwIsTowardLarger)
cw[i] = op;
else
ccw[j] = op;
if (op2IsLarger == cwIsTowardLarger)
cw[i] = op2;
else
ccw[j] = op2;
}
}
}
Path64 RectClip::GetPath(OutPt2*& op)
{
if (!op || op->next == op->prev) return Path64();
OutPt2* op2 = op->next;
while (op2 && op2 != op)
{
if (CrossProduct(op2->prev->pt,
op2->pt, op2->next->pt) == 0)
{
op = op2->prev;
op2 = UnlinkOp(op2);
}
else
op2 = op2->next;
}
op = op2; // needed for op cleanup
if (!op2) return Path64();
Path64 result;
result.push_back(op->pt);
op2 = op->next;
while (op2 != op)
{
result.push_back(op2->pt);
op2 = op2->next;
}
return result;
}
Paths64 RectClip::Execute(const Paths64& paths, bool convex_only)
Paths64 RectClipLines::Execute(const Path64& path)
{
result_.clear();
Paths64 result;
if (rect_.IsEmpty()) return result;
for (const auto& path : paths)
{
if (path.size() < 3) continue;
path_bounds_ = GetBounds(path);
if (!rect_.Intersects(path_bounds_))
continue; // the path must be completely outside rect_
else if (rect_.Contains(path_bounds_))
{
// the path must be completely inside rect_
result.push_back(path);
continue;
}
ExecuteInternal(path);
if (!convex_only)
{
CheckEdges();
for (int i = 0; i < 4; ++i)
TidyEdges(i, edges_[i * 2], edges_[i * 2 + 1]);
}
for (OutPt2*& op : results_)
{
Path64 tmp = GetPath(op);
if (!tmp.empty())
result.emplace_back(tmp);
}
//clean up after every loop
op_container_ = std::deque<OutPt2>();
results_.clear();
for (OutPt2List edge : edges_) edge.clear();
start_locs_.clear();
}
return result;
}
//------------------------------------------------------------------------------
// RectClipLines
//------------------------------------------------------------------------------
Paths64 RectClipLines::Execute(const Paths64& paths)
{
Paths64 result;
if (rect_.IsEmpty()) return result;
for (const auto& path : paths)
{
if (path.size() < 2) continue;
Rect64 pathrec = GetBounds(path);
if (!rect_.Intersects(pathrec)) continue;
ExecuteInternal(path);
for (OutPt2*& op : results_)
{
Path64 tmp = GetPath(op);
if (!tmp.empty())
result.emplace_back(tmp);
}
results_.clear();
op_container_ = std::deque<OutPt2>();
start_locs_.clear();
}
return result;
}
void RectClipLines::ExecuteInternal(const Path64& path)
{
if (rect_.IsEmpty() || path.size() < 2) return;
results_.clear();
op_container_ = std::deque<OutPt2>();
start_locs_.clear();
if (rect_.IsEmpty() || path.size() == 0) return result;
int i = 1, highI = static_cast<int>(path.size()) - 1;
Location prev = Location::Inside, loc;
Location crossing_loc;
Location crossing_loc = Location::Inside;
if (!GetLocation(rect_, path[0], loc))
{
while (i <= highI && !GetLocation(rect_, path[i], prev)) ++i;
if (i > highI)
{
// all of path must be inside fRect
for (const auto& pt : path) Add(pt);
return;
if (i > highI) {
result.push_back(path);
return result;
}
if (prev == Location::Inside) loc = Location::Inside;
i = 1;
}
if (loc == Location::Inside) Add(path[0]);
if (loc == Location::Inside) result_.push_back(path[0]);
///////////////////////////////////////////////////
while (i <= highI)
@ -924,8 +504,7 @@ namespace Clipper2Lib {
Point64 prev_pt = path[static_cast<size_t>(i - 1)];
crossing_loc = loc;
if (!GetIntersection(rect_as_path_,
path[i], prev_pt, crossing_loc, ip))
if (!GetIntersection(rectPath_, path[i], prev_pt, crossing_loc, ip))
{
// ie remaining outside
++i;
@ -938,38 +517,30 @@ namespace Clipper2Lib {
if (loc == Location::Inside) // path must be entering rect
{
Add(ip, true);
result_.push_back(ip);
}
else if (prev != Location::Inside)
{
// passing right through rect. 'ip' here will be the second
// intersect pt but we'll also need the first intersect pt (ip2)
crossing_loc = prev;
GetIntersection(rect_as_path_,
prev_pt, path[i], crossing_loc, ip2);
Add(ip2, true);
Add(ip);
GetIntersection(rectPath_, prev_pt, path[i], crossing_loc, ip2);
result_.push_back(ip2);
result_.push_back(ip);
result.push_back(result_);
result_.clear();
}
else // path must be exiting rect
{
Add(ip);
result_.push_back(ip);
result.push_back(result_);
result_.clear();
}
} //while i <= highI
///////////////////////////////////////////////////
}
Path64 RectClipLines::GetPath(OutPt2*& op)
{
Path64 result;
if (!op || op == op->next) return result;
op = op->next; // starting at path beginning
result.push_back(op->pt);
OutPt2 *op2 = op->next;
while (op2 != op)
{
result.push_back(op2->pt);
op2 = op2->next;
}
if (result_.size() > 1)
result.push_back(result_);
return result;
}