clipper.h 14 KB

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