1 /*******************************************************************************
2 *                                                                              *
3 * Author    :  Angus Johnson                                                   *
4 * Version   :  6.2.1                                                           *
5 * Date      :  31 October 2014                                                 *
6 * Website   :  http://www.angusj.com                                           *
7 * Copyright :  Angus Johnson 2010-2014                                         *
8 *                                                                              *
9 * License:                                                                     *
10 * Use, modification & distribution is subject to Boost Software License Ver 1. *
11 * http://www.boost.org/LICENSE_1_0.txt                                         *
12 *                                                                              *
13 * Attributions:                                                                *
14 * The code in this library is an extension of Bala Vatti's clipping algorithm: *
15 * "A generic solution to polygon clipping"                                     *
16 * Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63.             *
17 * http://portal.acm.org/citation.cfm?id=129906                                 *
18 *                                                                              *
19 * Computer graphics and geometric modeling: implementation and algorithms      *
20 * By Max K. Agoston                                                            *
21 * Springer; 1 edition (January 4, 2005)                                        *
22 * http://books.google.com/books?q=vatti+clipping+agoston                       *
23 *                                                                              *
24 * See also:                                                                    *
25 * "Polygon Offsetting by Computing Winding Numbers"                            *
26 * Paper no. DETC2005-85513 pp. 565-575                                         *
27 * ASME 2005 International Design Engineering Technical Conferences             *
28 * and Computers and Information in Engineering Conference (IDETC/CIE2005)      *
29 * September 24-28, 2005 , Long Beach, California, USA                          *
30 * http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf              *
31 *                                                                              *
32 *******************************************************************************/
33 
34 #ifndef clipper_hpp
35 #define clipper_hpp
36 
37 #define CLIPPER_VERSION "6.2.0"
38 
39 //use_int32: When enabled 32bit ints are used instead of 64bit ints. This
40 //improve performance but coordinate values are limited to the range +/- 46340
41 //#define use_int32
42 
43 //use_xyz: adds a Z member to IntPoint. Adds a minor cost to perfomance.
44 //#define use_xyz
45 
46 //use_lines: Enables line clipping. Adds a very minor cost to performance.
47 #define use_lines
48 
49 //use_deprecated: Enables temporary support for the obsolete functions
50 //#define use_deprecated
51 
52 #include <vector>
53 #include <set>
54 #include <stdexcept>
55 #include <cstring>
56 #include <cstdlib>
57 #include <ostream>
58 #include <functional>
59 #include <queue>
60 
61 namespace ClipperLib {
62 
63 enum ClipType { ctIntersection, ctUnion, ctDifference, ctXor };
64 enum PolyType { ptSubject, ptClip };
65 //By far the most widely used winding rules for polygon filling are
66 //EvenOdd & NonZero (GDI, GDI+, XLib, OpenGL, Cairo, AGG, Quartz, SVG, Gr32)
67 //Others rules include Positive, Negative and ABS_GTR_EQ_TWO (only in OpenGL)
68 //see http://glprogramming.com/red/chapter11.html
69 enum PolyFillType { pftEvenOdd, pftNonZero, pftPositive, pftNegative };
70 
71 #ifdef use_int32
72   typedef int cInt;
73   static cInt const loRange = 0x7FFF;
74   static cInt const hiRange = 0x7FFF;
75 #else
76   typedef signed long long cInt;
77   static cInt const loRange = 0x3FFFFFFF;
78   static cInt const hiRange = 0x3FFFFFFFFFFFFFFFLL;
79   typedef signed long long long64;     //used by Int128 class
80   typedef unsigned long long ulong64;
81 
82 #endif
83 
84 struct IntPoint {
85   cInt X;
86   cInt Y;
87 #ifdef use_xyz
88   cInt Z;
IntPointClipperLib::IntPoint89   IntPoint(cInt x = 0, cInt y = 0, cInt z = 0): X(x), Y(y), Z(z) {};
90 #else
IntPointClipperLib::IntPoint91   IntPoint(cInt x = 0, cInt y = 0): X(x), Y(y) {};
92 #endif
93 
operator ==(const IntPoint & a,const IntPoint & b)94   friend inline bool operator== (const IntPoint& a, const IntPoint& b)
95   {
96     return a.X == b.X && a.Y == b.Y;
97   }
operator !=(const IntPoint & a,const IntPoint & b)98   friend inline bool operator!= (const IntPoint& a, const IntPoint& b)
99   {
100     return a.X != b.X  || a.Y != b.Y;
101   }
102 };
103 //------------------------------------------------------------------------------
104 
105 typedef std::vector< IntPoint > Path;
106 typedef std::vector< Path > Paths;
107 
operator <<(Path & poly,const IntPoint & p)108 inline Path& operator <<(Path& poly, const IntPoint& p) {poly.push_back(p); return poly;}
operator <<(Paths & polys,const Path & p)109 inline Paths& operator <<(Paths& polys, const Path& p) {polys.push_back(p); return polys;}
110 
111 std::ostream& operator <<(std::ostream &s, const IntPoint &p);
112 std::ostream& operator <<(std::ostream &s, const Path &p);
113 std::ostream& operator <<(std::ostream &s, const Paths &p);
114 
115 struct DoublePoint
116 {
117   double X;
118   double Y;
DoublePointClipperLib::DoublePoint119   DoublePoint(double x = 0, double y = 0) : X(x), Y(y) {}
DoublePointClipperLib::DoublePoint120   DoublePoint(IntPoint ip) : X((double)ip.X), Y((double)ip.Y) {}
121 };
122 //------------------------------------------------------------------------------
123 
124 #ifdef use_xyz
125 typedef void (*ZFillCallback)(IntPoint& e1bot, IntPoint& e1top, IntPoint& e2bot, IntPoint& e2top, IntPoint& pt);
126 #endif
127 
128 enum InitOptions {ioReverseSolution = 1, ioStrictlySimple = 2, ioPreserveCollinear = 4};
129 enum JoinType {jtSquare, jtRound, jtMiter};
130 enum EndType {etClosedPolygon, etClosedLine, etOpenButt, etOpenSquare, etOpenRound};
131 
132 class PolyNode;
133 typedef std::vector< PolyNode* > PolyNodes;
134 
135 class PolyNode
136 {
137 public:
138     PolyNode();
~PolyNode()139     virtual ~PolyNode(){};
140     Path Contour;
141     PolyNodes Childs;
142     PolyNode* Parent;
143     PolyNode* GetNext() const;
144     bool IsHole() const;
145     bool IsOpen() const;
146     int ChildCount() const;
147 private:
148     unsigned Index; //node index in Parent.Childs
149     bool m_IsOpen;
150     JoinType m_jointype;
151     EndType m_endtype;
152     PolyNode* GetNextSiblingUp() const;
153     void AddChild(PolyNode& child);
154     friend class Clipper; //to access Index
155     friend class ClipperOffset;
156 };
157 
158 class PolyTree: public PolyNode
159 {
160 public:
~PolyTree()161     ~PolyTree(){Clear();};
162     PolyNode* GetFirst() const;
163     void Clear();
164     int Total() const;
165 private:
166     PolyNodes AllNodes;
167     friend class Clipper; //to access AllNodes
168 };
169 
170 bool Orientation(const Path &poly);
171 double Area(const Path &poly);
172 int PointInPolygon(const IntPoint &pt, const Path &path);
173 
174 void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType = pftEvenOdd);
175 void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType = pftEvenOdd);
176 void SimplifyPolygons(Paths &polys, PolyFillType fillType = pftEvenOdd);
177 
178 void CleanPolygon(const Path& in_poly, Path& out_poly, double distance = 1.415);
179 void CleanPolygon(Path& poly, double distance = 1.415);
180 void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance = 1.415);
181 void CleanPolygons(Paths& polys, double distance = 1.415);
182 
183 void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed);
184 void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed);
185 void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution);
186 
187 void PolyTreeToPaths(const PolyTree& polytree, Paths& paths);
188 void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths);
189 void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths);
190 
191 void ReversePath(Path& p);
192 void ReversePaths(Paths& p);
193 
194 struct IntRect { cInt left; cInt top; cInt right; cInt bottom; };
195 
196 //enums that are used internally ...
197 enum EdgeSide { esLeft = 1, esRight = 2};
198 
199 //forward declarations (for stuff used internally) ...
200 struct TEdge;
201 struct IntersectNode;
202 struct LocalMinimum;
203 struct Scanbeam;
204 struct OutPt;
205 struct OutRec;
206 struct Join;
207 
208 typedef std::vector < OutRec* > PolyOutList;
209 typedef std::vector < TEdge* > EdgeList;
210 typedef std::vector < Join* > JoinList;
211 typedef std::vector < IntersectNode* > IntersectList;
212 
213 //------------------------------------------------------------------------------
214 
215 //ClipperBase is the ancestor to the Clipper class. It should not be
216 //instantiated directly. This class simply abstracts the conversion of sets of
217 //polygon coordinates into edge objects that are stored in a LocalMinima list.
218 class ClipperBase
219 {
220 public:
221   ClipperBase();
222   virtual ~ClipperBase();
223   bool AddPath(const Path &pg, PolyType PolyTyp, bool Closed);
224   bool AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed);
225   virtual void Clear();
226   IntRect GetBounds();
PreserveCollinear()227   bool PreserveCollinear() {return m_PreserveCollinear;};
PreserveCollinear(bool value)228   void PreserveCollinear(bool value) {m_PreserveCollinear = value;};
229 protected:
230   void DisposeLocalMinimaList();
231   TEdge* AddBoundsToLML(TEdge *e, bool IsClosed);
232   void PopLocalMinima();
233   virtual void Reset();
234   TEdge* ProcessBound(TEdge* E, bool IsClockwise);
235   void DoMinimaLML(TEdge* E1, TEdge* E2, bool IsClosed);
236   TEdge* DescendToMin(TEdge *&E);
237   void AscendToMax(TEdge *&E, bool Appending, bool IsClosed);
238 
239   typedef std::vector<LocalMinimum> MinimaList;
240   MinimaList::iterator m_CurrentLM;
241   MinimaList           m_MinimaList;
242 
243   bool              m_UseFullRange;
244   EdgeList          m_edges;
245   bool             m_PreserveCollinear;
246   bool             m_HasOpenPaths;
247 };
248 //------------------------------------------------------------------------------
249 
250 class Clipper : public virtual ClipperBase
251 {
252 public:
253   Clipper(int initOptions = 0);
254   ~Clipper();
255   bool Execute(ClipType clipType,
256     Paths &solution,
257     PolyFillType subjFillType = pftEvenOdd,
258     PolyFillType clipFillType = pftEvenOdd);
259   bool Execute(ClipType clipType,
260     PolyTree &polytree,
261     PolyFillType subjFillType = pftEvenOdd,
262     PolyFillType clipFillType = pftEvenOdd);
ReverseSolution()263   bool ReverseSolution() {return m_ReverseOutput;};
ReverseSolution(bool value)264   void ReverseSolution(bool value) {m_ReverseOutput = value;};
StrictlySimple()265   bool StrictlySimple() {return m_StrictSimple;};
StrictlySimple(bool value)266   void StrictlySimple(bool value) {m_StrictSimple = value;};
267   //set the callback function for z value filling on intersections (otherwise Z is 0)
268 #ifdef use_xyz
269   void ZFillFunction(ZFillCallback zFillFunc);
270 #endif
271 protected:
272   void Reset();
273   virtual bool ExecuteInternal();
274 private:
275   PolyOutList       m_PolyOuts;
276   JoinList          m_Joins;
277   JoinList          m_GhostJoins;
278   IntersectList     m_IntersectList;
279   ClipType          m_ClipType;
280   typedef std::priority_queue<cInt> ScanbeamList;
281   ScanbeamList      m_Scanbeam;
282   TEdge           *m_ActiveEdges;
283   TEdge           *m_SortedEdges;
284   bool             m_ExecuteLocked;
285   PolyFillType     m_ClipFillType;
286   PolyFillType     m_SubjFillType;
287   bool             m_ReverseOutput;
288   bool             m_UsingPolyTree;
289   bool             m_StrictSimple;
290 #ifdef use_xyz
291   ZFillCallback   m_ZFill; //custom callback
292 #endif
293   void SetWindingCount(TEdge& edge);
294   bool IsEvenOddFillType(const TEdge& edge) const;
295   bool IsEvenOddAltFillType(const TEdge& edge) const;
296   void InsertScanbeam(const cInt Y);
297   cInt PopScanbeam();
298   void InsertLocalMinimaIntoAEL(const cInt botY);
299   void InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge);
300   void AddEdgeToSEL(TEdge *edge);
301   void CopyAELToSEL();
302   void DeleteFromSEL(TEdge *e);
303   void DeleteFromAEL(TEdge *e);
304   void UpdateEdgeIntoAEL(TEdge *&e);
305   void SwapPositionsInSEL(TEdge *edge1, TEdge *edge2);
306   bool IsContributing(const TEdge& edge) const;
307   bool IsTopHorz(const cInt XPos);
308   void SwapPositionsInAEL(TEdge *edge1, TEdge *edge2);
309   void DoMaxima(TEdge *e);
310   void ProcessHorizontals(bool IsTopOfScanbeam);
311   void ProcessHorizontal(TEdge *horzEdge, bool isTopOfScanbeam);
312   void AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
313   OutPt* AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
314   OutRec* GetOutRec(int idx);
315   void AppendPolygon(TEdge *e1, TEdge *e2);
316   void IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &pt);
317   OutRec* CreateOutRec();
318   OutPt* AddOutPt(TEdge *e, const IntPoint &pt);
319   void DisposeAllOutRecs();
320   void DisposeOutRec(PolyOutList::size_type index);
321   bool ProcessIntersections(const cInt topY);
322   void BuildIntersectList(const cInt topY);
323   void ProcessIntersectList();
324   void ProcessEdgesAtTopOfScanbeam(const cInt topY);
325   void BuildResult(Paths& polys);
326   void BuildResult2(PolyTree& polytree);
327   void SetHoleState(TEdge *e, OutRec *outrec);
328   void DisposeIntersectNodes();
329   bool FixupIntersectionOrder();
330   void FixupOutPolygon(OutRec &outrec);
331   bool IsHole(TEdge *e);
332   bool FindOwnerFromSplitRecs(OutRec &outRec, OutRec *&currOrfl);
333   void FixHoleLinkage(OutRec &outrec);
334   void AddJoin(OutPt *op1, OutPt *op2, const IntPoint offPt);
335   void ClearJoins();
336   void ClearGhostJoins();
337   void AddGhostJoin(OutPt *op, const IntPoint offPt);
338   bool JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2);
339   void JoinCommonEdges();
340   void DoSimplePolygons();
341   void FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec);
342   void FixupFirstLefts2(OutRec* OldOutRec, OutRec* NewOutRec);
343 #ifdef use_xyz
344   void SetZ(IntPoint& pt, TEdge& e1, TEdge& e2);
345 #endif
346 };
347 //------------------------------------------------------------------------------
348 
349 class ClipperOffset
350 {
351 public:
352   ClipperOffset(double miterLimit = 2.0, double roundPrecision = 0.25);
353   ~ClipperOffset();
354   void AddPath(const Path& path, JoinType joinType, EndType endType);
355   void AddPaths(const Paths& paths, JoinType joinType, EndType endType);
356   void Execute(Paths& solution, double delta);
357   void Execute(PolyTree& solution, double delta);
358   void Clear();
359   double MiterLimit;
360   double ArcTolerance;
361 private:
362   Paths m_destPolys;
363   Path m_srcPoly;
364   Path m_destPoly;
365   std::vector<DoublePoint> m_normals;
366   double m_delta, m_sinA, m_sin, m_cos;
367   double m_miterLim, m_StepsPerRad;
368   IntPoint m_lowest;
369   PolyNode m_polyNodes;
370 
371   void FixOrientations();
372   void DoOffset(double delta);
373   void OffsetPoint(int j, int& k, JoinType jointype);
374   void DoSquare(int j, int k);
375   void DoMiter(int j, int k, double r);
376   void DoRound(int j, int k);
377 };
378 //------------------------------------------------------------------------------
379 
380 class clipperException : public std::exception
381 {
382   public:
clipperException(const char * description)383     clipperException(const char* description): m_descr(description) {}
~clipperException()384     virtual ~clipperException() throw() {}
what() const385     virtual const char* what() const throw() {return m_descr.c_str();}
386   private:
387     std::string m_descr;
388 };
389 //------------------------------------------------------------------------------
390 
391 } //ClipperLib namespace
392 
393 #endif //clipper_hpp
394 
395 
396