clipper.cpp 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637
  1. /*******************************************************************************
  2. * *
  3. * Author : Angus Johnson *
  4. * Version : 6.4.2 *
  5. * Date : 27 February 2017 *
  6. * Website : http://www.angusj.com *
  7. * Copyright : Angus Johnson 2010-2017 *
  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. * *
  35. * This is a translation of the Delphi Clipper library and the naming style *
  36. * used has retained a Delphi flavour. *
  37. * *
  38. *******************************************************************************/
  39. #include "clipper.hpp"
  40. #include <cmath>
  41. #include <vector>
  42. #include <algorithm>
  43. #include <stdexcept>
  44. #include <cstring>
  45. #include <cstdlib>
  46. #include <ostream>
  47. #include <functional>
  48. namespace ClipperLib {
  49. static double const pi = 3.141592653589793238;
  50. static double const two_pi = pi *2;
  51. static double const def_arc_tolerance = 0.25;
  52. enum Direction { dRightToLeft, dLeftToRight };
  53. static int const Unassigned = -1; //edge not currently 'owning' a solution
  54. static int const Skip = -2; //edge that would otherwise close a path
  55. #define HORIZONTAL (-1.0E+40)
  56. #define TOLERANCE (1.0e-20)
  57. #define NEAR_ZERO(val) (((val) > -TOLERANCE) && ((val) < TOLERANCE))
  58. struct TEdge {
  59. IntPoint Bot;
  60. IntPoint Curr; //current (updated for every new scanbeam)
  61. IntPoint Top;
  62. double Dx;
  63. PolyType PolyTyp;
  64. EdgeSide Side; //side only refers to current side of solution poly
  65. int WindDelta; //1 or -1 depending on winding direction
  66. int WindCnt;
  67. int WindCnt2; //winding count of the opposite polytype
  68. int OutIdx;
  69. TEdge *Next;
  70. TEdge *Prev;
  71. TEdge *NextInLML;
  72. TEdge *NextInAEL;
  73. TEdge *PrevInAEL;
  74. TEdge *NextInSEL;
  75. TEdge *PrevInSEL;
  76. };
  77. struct IntersectNode {
  78. TEdge *Edge1;
  79. TEdge *Edge2;
  80. IntPoint Pt;
  81. };
  82. struct LocalMinimum {
  83. cInt Y;
  84. TEdge *LeftBound;
  85. TEdge *RightBound;
  86. };
  87. struct OutPt;
  88. //OutRec: contains a path in the clipping solution. Edges in the AEL will
  89. //carry a pointer to an OutRec when they are part of the clipping solution.
  90. struct OutRec {
  91. int Idx;
  92. bool IsHole;
  93. bool IsOpen;
  94. OutRec *FirstLeft; //see comments in clipper.pas
  95. PolyNode *PolyNd;
  96. OutPt *Pts;
  97. OutPt *BottomPt;
  98. };
  99. struct OutPt {
  100. int Idx;
  101. IntPoint Pt;
  102. OutPt *Next;
  103. OutPt *Prev;
  104. };
  105. struct Join {
  106. OutPt *OutPt1;
  107. OutPt *OutPt2;
  108. IntPoint OffPt;
  109. };
  110. struct LocMinSorter
  111. {
  112. inline bool operator()(const LocalMinimum& locMin1, const LocalMinimum& locMin2)
  113. {
  114. return locMin2.Y < locMin1.Y;
  115. }
  116. };
  117. //------------------------------------------------------------------------------
  118. //------------------------------------------------------------------------------
  119. inline cInt Round(double val)
  120. {
  121. if ((val < 0)) return static_cast<cInt>(val - 0.5);
  122. else return static_cast<cInt>(val + 0.5);
  123. }
  124. //------------------------------------------------------------------------------
  125. inline cInt Abs(cInt val)
  126. {
  127. return val < 0 ? -val : val;
  128. }
  129. //------------------------------------------------------------------------------
  130. // PolyTree methods ...
  131. //------------------------------------------------------------------------------
  132. void PolyTree::Clear()
  133. {
  134. for (PolyNodes::size_type i = 0; i < AllNodes.size(); ++i)
  135. delete AllNodes[i];
  136. AllNodes.resize(0);
  137. Childs.resize(0);
  138. }
  139. //------------------------------------------------------------------------------
  140. PolyNode* PolyTree::GetFirst() const
  141. {
  142. if (!Childs.empty())
  143. return Childs[0];
  144. else
  145. return 0;
  146. }
  147. //------------------------------------------------------------------------------
  148. int PolyTree::Total() const
  149. {
  150. int result = (int)AllNodes.size();
  151. //with negative offsets, ignore the hidden outer polygon ...
  152. if (result > 0 && Childs[0] != AllNodes[0]) result--;
  153. return result;
  154. }
  155. //------------------------------------------------------------------------------
  156. // PolyNode methods ...
  157. //------------------------------------------------------------------------------
  158. PolyNode::PolyNode(): Parent(0), Index(0), m_IsOpen(false)
  159. {
  160. }
  161. //------------------------------------------------------------------------------
  162. int PolyNode::ChildCount() const
  163. {
  164. return (int)Childs.size();
  165. }
  166. //------------------------------------------------------------------------------
  167. void PolyNode::AddChild(PolyNode& child)
  168. {
  169. unsigned cnt = (unsigned)Childs.size();
  170. Childs.push_back(&child);
  171. child.Parent = this;
  172. child.Index = cnt;
  173. }
  174. //------------------------------------------------------------------------------
  175. PolyNode* PolyNode::GetNext() const
  176. {
  177. if (!Childs.empty())
  178. return Childs[0];
  179. else
  180. return GetNextSiblingUp();
  181. }
  182. //------------------------------------------------------------------------------
  183. PolyNode* PolyNode::GetNextSiblingUp() const
  184. {
  185. if (!Parent) //protects against PolyTree.GetNextSiblingUp()
  186. return 0;
  187. else if (Index == Parent->Childs.size() - 1)
  188. return Parent->GetNextSiblingUp();
  189. else
  190. return Parent->Childs[Index + 1];
  191. }
  192. //------------------------------------------------------------------------------
  193. bool PolyNode::IsHole() const
  194. {
  195. bool result = true;
  196. PolyNode* node = Parent;
  197. while (node)
  198. {
  199. result = !result;
  200. node = node->Parent;
  201. }
  202. return result;
  203. }
  204. //------------------------------------------------------------------------------
  205. bool PolyNode::IsOpen() const
  206. {
  207. return m_IsOpen;
  208. }
  209. //------------------------------------------------------------------------------
  210. #ifndef use_int32
  211. //------------------------------------------------------------------------------
  212. // Int128 class (enables safe math on signed 64bit integers)
  213. // eg Int128 val1((long64)9223372036854775807); //ie 2^63 -1
  214. // Int128 val2((long64)9223372036854775807);
  215. // Int128 val3 = val1 * val2;
  216. // val3.AsString => "85070591730234615847396907784232501249" (8.5e+37)
  217. //------------------------------------------------------------------------------
  218. class Int128
  219. {
  220. public:
  221. ulong64 lo;
  222. long64 hi;
  223. Int128(long64 _lo = 0)
  224. {
  225. lo = (ulong64)_lo;
  226. if (_lo < 0) hi = -1; else hi = 0;
  227. }
  228. Int128(const Int128 &val): lo(val.lo), hi(val.hi){}
  229. Int128(const long64& _hi, const ulong64& _lo): lo(_lo), hi(_hi){}
  230. Int128& operator = (const Int128 &val)
  231. {
  232. lo = val.lo;
  233. hi = val.hi;
  234. return *this;
  235. }
  236. Int128& operator = (const long64 &val)
  237. {
  238. lo = (ulong64)val;
  239. if (val < 0) hi = -1; else hi = 0;
  240. return *this;
  241. }
  242. bool operator == (const Int128 &val) const
  243. {return (hi == val.hi && lo == val.lo);}
  244. bool operator != (const Int128 &val) const
  245. { return !(*this == val);}
  246. bool operator > (const Int128 &val) const
  247. {
  248. if (hi != val.hi)
  249. return hi > val.hi;
  250. else
  251. return lo > val.lo;
  252. }
  253. bool operator < (const Int128 &val) const
  254. {
  255. if (hi != val.hi)
  256. return hi < val.hi;
  257. else
  258. return lo < val.lo;
  259. }
  260. bool operator >= (const Int128 &val) const
  261. { return !(*this < val);}
  262. bool operator <= (const Int128 &val) const
  263. { return !(*this > val);}
  264. Int128& operator += (const Int128 &rhs)
  265. {
  266. hi += rhs.hi;
  267. lo += rhs.lo;
  268. if (lo < rhs.lo) hi++;
  269. return *this;
  270. }
  271. Int128 operator + (const Int128 &rhs) const
  272. {
  273. Int128 result(*this);
  274. result+= rhs;
  275. return result;
  276. }
  277. Int128& operator -= (const Int128 &rhs)
  278. {
  279. *this += -rhs;
  280. return *this;
  281. }
  282. Int128 operator - (const Int128 &rhs) const
  283. {
  284. Int128 result(*this);
  285. result -= rhs;
  286. return result;
  287. }
  288. Int128 operator-() const //unary negation
  289. {
  290. if (lo == 0)
  291. return Int128(-hi, 0);
  292. else
  293. return Int128(~hi, ~lo + 1);
  294. }
  295. operator double() const
  296. {
  297. const double shift64 = 18446744073709551616.0; //2^64
  298. if (hi < 0)
  299. {
  300. if (lo == 0) return (double)hi * shift64;
  301. else return -(double)(~lo + ~hi * shift64);
  302. }
  303. else
  304. return (double)(lo + hi * shift64);
  305. }
  306. };
  307. //------------------------------------------------------------------------------
  308. Int128 Int128Mul (long64 lhs, long64 rhs)
  309. {
  310. bool negate = (lhs < 0) != (rhs < 0);
  311. if (lhs < 0) lhs = -lhs;
  312. ulong64 int1Hi = ulong64(lhs) >> 32;
  313. ulong64 int1Lo = ulong64(lhs & 0xFFFFFFFF);
  314. if (rhs < 0) rhs = -rhs;
  315. ulong64 int2Hi = ulong64(rhs) >> 32;
  316. ulong64 int2Lo = ulong64(rhs & 0xFFFFFFFF);
  317. //nb: see comments in clipper.pas
  318. ulong64 a = int1Hi * int2Hi;
  319. ulong64 b = int1Lo * int2Lo;
  320. ulong64 c = int1Hi * int2Lo + int1Lo * int2Hi;
  321. Int128 tmp;
  322. tmp.hi = long64(a + (c >> 32));
  323. tmp.lo = long64(c << 32);
  324. tmp.lo += long64(b);
  325. if (tmp.lo < b) tmp.hi++;
  326. if (negate) tmp = -tmp;
  327. return tmp;
  328. };
  329. #endif
  330. //------------------------------------------------------------------------------
  331. // Miscellaneous global functions
  332. //------------------------------------------------------------------------------
  333. bool Orientation(const Path &poly)
  334. {
  335. return Area(poly) >= 0;
  336. }
  337. //------------------------------------------------------------------------------
  338. double Area(const Path &poly)
  339. {
  340. int size = (int)poly.size();
  341. if (size < 3) return 0;
  342. double a = 0;
  343. for (int i = 0, j = size -1; i < size; ++i)
  344. {
  345. a += ((double)poly[j].X + poly[i].X) * ((double)poly[j].Y - poly[i].Y);
  346. j = i;
  347. }
  348. return -a * 0.5;
  349. }
  350. //------------------------------------------------------------------------------
  351. double Area(const OutPt *op)
  352. {
  353. const OutPt *startOp = op;
  354. if (!op) return 0;
  355. double a = 0;
  356. do {
  357. a += (double)(op->Prev->Pt.X + op->Pt.X) * (double)(op->Prev->Pt.Y - op->Pt.Y);
  358. op = op->Next;
  359. } while (op != startOp);
  360. return a * 0.5;
  361. }
  362. //------------------------------------------------------------------------------
  363. double Area(const OutRec &outRec)
  364. {
  365. return Area(outRec.Pts);
  366. }
  367. //------------------------------------------------------------------------------
  368. bool PointIsVertex(const IntPoint &Pt, OutPt *pp)
  369. {
  370. OutPt *pp2 = pp;
  371. do
  372. {
  373. if (pp2->Pt == Pt) return true;
  374. pp2 = pp2->Next;
  375. }
  376. while (pp2 != pp);
  377. return false;
  378. }
  379. //------------------------------------------------------------------------------
  380. //See "The Point in Polygon Problem for Arbitrary Polygons" by Hormann & Agathos
  381. //http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.5498&rep=rep1&type=pdf
  382. int PointInPolygon(const IntPoint &pt, const Path &path)
  383. {
  384. //returns 0 if false, +1 if true, -1 if pt ON polygon boundary
  385. int result = 0;
  386. size_t cnt = path.size();
  387. if (cnt < 3) return 0;
  388. IntPoint ip = path[0];
  389. for(size_t i = 1; i <= cnt; ++i)
  390. {
  391. IntPoint ipNext = (i == cnt ? path[0] : path[i]);
  392. if (ipNext.Y == pt.Y)
  393. {
  394. if ((ipNext.X == pt.X) || (ip.Y == pt.Y &&
  395. ((ipNext.X > pt.X) == (ip.X < pt.X)))) return -1;
  396. }
  397. if ((ip.Y < pt.Y) != (ipNext.Y < pt.Y))
  398. {
  399. if (ip.X >= pt.X)
  400. {
  401. if (ipNext.X > pt.X) result = 1 - result;
  402. else
  403. {
  404. double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) -
  405. (double)(ipNext.X - pt.X) * (ip.Y - pt.Y);
  406. if (!d) return -1;
  407. if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;
  408. }
  409. } else
  410. {
  411. if (ipNext.X > pt.X)
  412. {
  413. double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) -
  414. (double)(ipNext.X - pt.X) * (ip.Y - pt.Y);
  415. if (!d) return -1;
  416. if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;
  417. }
  418. }
  419. }
  420. ip = ipNext;
  421. }
  422. return result;
  423. }
  424. //------------------------------------------------------------------------------
  425. int PointInPolygon (const IntPoint &pt, OutPt *op)
  426. {
  427. //returns 0 if false, +1 if true, -1 if pt ON polygon boundary
  428. int result = 0;
  429. OutPt* startOp = op;
  430. for(;;)
  431. {
  432. if (op->Next->Pt.Y == pt.Y)
  433. {
  434. if ((op->Next->Pt.X == pt.X) || (op->Pt.Y == pt.Y &&
  435. ((op->Next->Pt.X > pt.X) == (op->Pt.X < pt.X)))) return -1;
  436. }
  437. if ((op->Pt.Y < pt.Y) != (op->Next->Pt.Y < pt.Y))
  438. {
  439. if (op->Pt.X >= pt.X)
  440. {
  441. if (op->Next->Pt.X > pt.X) result = 1 - result;
  442. else
  443. {
  444. double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) -
  445. (double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);
  446. if (!d) return -1;
  447. if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;
  448. }
  449. } else
  450. {
  451. if (op->Next->Pt.X > pt.X)
  452. {
  453. double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) -
  454. (double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);
  455. if (!d) return -1;
  456. if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;
  457. }
  458. }
  459. }
  460. op = op->Next;
  461. if (startOp == op) break;
  462. }
  463. return result;
  464. }
  465. //------------------------------------------------------------------------------
  466. bool Poly2ContainsPoly1(OutPt *OutPt1, OutPt *OutPt2)
  467. {
  468. OutPt* op = OutPt1;
  469. do
  470. {
  471. //nb: PointInPolygon returns 0 if false, +1 if true, -1 if pt on polygon
  472. int res = PointInPolygon(op->Pt, OutPt2);
  473. if (res >= 0) return res > 0;
  474. op = op->Next;
  475. }
  476. while (op != OutPt1);
  477. return true;
  478. }
  479. //----------------------------------------------------------------------
  480. bool SlopesEqual(const TEdge &e1, const TEdge &e2, bool UseFullInt64Range)
  481. {
  482. #ifndef use_int32
  483. if (UseFullInt64Range)
  484. return Int128Mul(e1.Top.Y - e1.Bot.Y, e2.Top.X - e2.Bot.X) ==
  485. Int128Mul(e1.Top.X - e1.Bot.X, e2.Top.Y - e2.Bot.Y);
  486. else
  487. #endif
  488. return (e1.Top.Y - e1.Bot.Y) * (e2.Top.X - e2.Bot.X) ==
  489. (e1.Top.X - e1.Bot.X) * (e2.Top.Y - e2.Bot.Y);
  490. }
  491. //------------------------------------------------------------------------------
  492. bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
  493. const IntPoint pt3, bool UseFullInt64Range)
  494. {
  495. #ifndef use_int32
  496. if (UseFullInt64Range)
  497. return Int128Mul(pt1.Y-pt2.Y, pt2.X-pt3.X) == Int128Mul(pt1.X-pt2.X, pt2.Y-pt3.Y);
  498. else
  499. #endif
  500. return (pt1.Y-pt2.Y)*(pt2.X-pt3.X) == (pt1.X-pt2.X)*(pt2.Y-pt3.Y);
  501. }
  502. //------------------------------------------------------------------------------
  503. bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
  504. const IntPoint pt3, const IntPoint pt4, bool UseFullInt64Range)
  505. {
  506. #ifndef use_int32
  507. if (UseFullInt64Range)
  508. return Int128Mul(pt1.Y-pt2.Y, pt3.X-pt4.X) == Int128Mul(pt1.X-pt2.X, pt3.Y-pt4.Y);
  509. else
  510. #endif
  511. return (pt1.Y-pt2.Y)*(pt3.X-pt4.X) == (pt1.X-pt2.X)*(pt3.Y-pt4.Y);
  512. }
  513. //------------------------------------------------------------------------------
  514. inline bool IsHorizontal(TEdge &e)
  515. {
  516. return e.Dx == HORIZONTAL;
  517. }
  518. //------------------------------------------------------------------------------
  519. inline double GetDx(const IntPoint pt1, const IntPoint pt2)
  520. {
  521. return (pt1.Y == pt2.Y) ?
  522. HORIZONTAL : (double)(pt2.X - pt1.X) / (pt2.Y - pt1.Y);
  523. }
  524. //---------------------------------------------------------------------------
  525. inline void SetDx(TEdge &e)
  526. {
  527. cInt dy = (e.Top.Y - e.Bot.Y);
  528. if (dy == 0) e.Dx = HORIZONTAL;
  529. else e.Dx = (double)(e.Top.X - e.Bot.X) / dy;
  530. }
  531. //---------------------------------------------------------------------------
  532. inline void SwapSides(TEdge &Edge1, TEdge &Edge2)
  533. {
  534. EdgeSide Side = Edge1.Side;
  535. Edge1.Side = Edge2.Side;
  536. Edge2.Side = Side;
  537. }
  538. //------------------------------------------------------------------------------
  539. inline void SwapPolyIndexes(TEdge &Edge1, TEdge &Edge2)
  540. {
  541. int OutIdx = Edge1.OutIdx;
  542. Edge1.OutIdx = Edge2.OutIdx;
  543. Edge2.OutIdx = OutIdx;
  544. }
  545. //------------------------------------------------------------------------------
  546. inline cInt TopX(TEdge &edge, const cInt currentY)
  547. {
  548. return ( currentY == edge.Top.Y ) ?
  549. edge.Top.X : edge.Bot.X + Round(edge.Dx *(currentY - edge.Bot.Y));
  550. }
  551. //------------------------------------------------------------------------------
  552. void IntersectPoint(TEdge &Edge1, TEdge &Edge2, IntPoint &ip)
  553. {
  554. #ifdef use_xyz
  555. ip.Z = 0;
  556. #endif
  557. double b1, b2;
  558. if (Edge1.Dx == Edge2.Dx)
  559. {
  560. ip.Y = Edge1.Curr.Y;
  561. ip.X = TopX(Edge1, ip.Y);
  562. return;
  563. }
  564. else if (Edge1.Dx == 0)
  565. {
  566. ip.X = Edge1.Bot.X;
  567. if (IsHorizontal(Edge2))
  568. ip.Y = Edge2.Bot.Y;
  569. else
  570. {
  571. b2 = Edge2.Bot.Y - (Edge2.Bot.X / Edge2.Dx);
  572. ip.Y = Round(ip.X / Edge2.Dx + b2);
  573. }
  574. }
  575. else if (Edge2.Dx == 0)
  576. {
  577. ip.X = Edge2.Bot.X;
  578. if (IsHorizontal(Edge1))
  579. ip.Y = Edge1.Bot.Y;
  580. else
  581. {
  582. b1 = Edge1.Bot.Y - (Edge1.Bot.X / Edge1.Dx);
  583. ip.Y = Round(ip.X / Edge1.Dx + b1);
  584. }
  585. }
  586. else
  587. {
  588. b1 = Edge1.Bot.X - Edge1.Bot.Y * Edge1.Dx;
  589. b2 = Edge2.Bot.X - Edge2.Bot.Y * Edge2.Dx;
  590. double q = (b2-b1) / (Edge1.Dx - Edge2.Dx);
  591. ip.Y = Round(q);
  592. if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))
  593. ip.X = Round(Edge1.Dx * q + b1);
  594. else
  595. ip.X = Round(Edge2.Dx * q + b2);
  596. }
  597. if (ip.Y < Edge1.Top.Y || ip.Y < Edge2.Top.Y)
  598. {
  599. if (Edge1.Top.Y > Edge2.Top.Y)
  600. ip.Y = Edge1.Top.Y;
  601. else
  602. ip.Y = Edge2.Top.Y;
  603. if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))
  604. ip.X = TopX(Edge1, ip.Y);
  605. else
  606. ip.X = TopX(Edge2, ip.Y);
  607. }
  608. //finally, don't allow 'ip' to be BELOW curr.Y (ie bottom of scanbeam) ...
  609. if (ip.Y > Edge1.Curr.Y)
  610. {
  611. ip.Y = Edge1.Curr.Y;
  612. //use the more vertical edge to derive X ...
  613. if (std::fabs(Edge1.Dx) > std::fabs(Edge2.Dx))
  614. ip.X = TopX(Edge2, ip.Y); else
  615. ip.X = TopX(Edge1, ip.Y);
  616. }
  617. }
  618. //------------------------------------------------------------------------------
  619. void ReversePolyPtLinks(OutPt *pp)
  620. {
  621. if (!pp) return;
  622. OutPt *pp1, *pp2;
  623. pp1 = pp;
  624. do {
  625. pp2 = pp1->Next;
  626. pp1->Next = pp1->Prev;
  627. pp1->Prev = pp2;
  628. pp1 = pp2;
  629. } while( pp1 != pp );
  630. }
  631. //------------------------------------------------------------------------------
  632. void DisposeOutPts(OutPt*& pp)
  633. {
  634. if (pp == 0) return;
  635. pp->Prev->Next = 0;
  636. while( pp )
  637. {
  638. OutPt *tmpPp = pp;
  639. pp = pp->Next;
  640. delete tmpPp;
  641. }
  642. }
  643. //------------------------------------------------------------------------------
  644. inline void InitEdge(TEdge* e, TEdge* eNext, TEdge* ePrev, const IntPoint& Pt)
  645. {
  646. *e = {};
  647. //std::memset(e, 0, sizeof(TEdge));
  648. e->Next = eNext;
  649. e->Prev = ePrev;
  650. e->Curr = Pt;
  651. e->OutIdx = Unassigned;
  652. }
  653. //------------------------------------------------------------------------------
  654. void InitEdge2(TEdge& e, PolyType Pt)
  655. {
  656. if (e.Curr.Y >= e.Next->Curr.Y)
  657. {
  658. e.Bot = e.Curr;
  659. e.Top = e.Next->Curr;
  660. } else
  661. {
  662. e.Top = e.Curr;
  663. e.Bot = e.Next->Curr;
  664. }
  665. SetDx(e);
  666. e.PolyTyp = Pt;
  667. }
  668. //------------------------------------------------------------------------------
  669. TEdge* RemoveEdge(TEdge* e)
  670. {
  671. //removes e from double_linked_list (but without removing from memory)
  672. e->Prev->Next = e->Next;
  673. e->Next->Prev = e->Prev;
  674. TEdge* result = e->Next;
  675. e->Prev = 0; //flag as removed (see ClipperBase.Clear)
  676. return result;
  677. }
  678. //------------------------------------------------------------------------------
  679. inline void ReverseHorizontal(TEdge &e)
  680. {
  681. //swap horizontal edges' Top and Bottom x's so they follow the natural
  682. //progression of the bounds - ie so their xbots will align with the
  683. //adjoining lower edge. [Helpful in the ProcessHorizontal() method.]
  684. std::swap(e.Top.X, e.Bot.X);
  685. #ifdef use_xyz
  686. std::swap(e.Top.Z, e.Bot.Z);
  687. #endif
  688. }
  689. //------------------------------------------------------------------------------
  690. void SwapPoints(IntPoint &pt1, IntPoint &pt2)
  691. {
  692. IntPoint tmp = pt1;
  693. pt1 = pt2;
  694. pt2 = tmp;
  695. }
  696. //------------------------------------------------------------------------------
  697. bool GetOverlapSegment(IntPoint pt1a, IntPoint pt1b, IntPoint pt2a,
  698. IntPoint pt2b, IntPoint &pt1, IntPoint &pt2)
  699. {
  700. //precondition: segments are Collinear.
  701. if (Abs(pt1a.X - pt1b.X) > Abs(pt1a.Y - pt1b.Y))
  702. {
  703. if (pt1a.X > pt1b.X) SwapPoints(pt1a, pt1b);
  704. if (pt2a.X > pt2b.X) SwapPoints(pt2a, pt2b);
  705. if (pt1a.X > pt2a.X) pt1 = pt1a; else pt1 = pt2a;
  706. if (pt1b.X < pt2b.X) pt2 = pt1b; else pt2 = pt2b;
  707. return pt1.X < pt2.X;
  708. } else
  709. {
  710. if (pt1a.Y < pt1b.Y) SwapPoints(pt1a, pt1b);
  711. if (pt2a.Y < pt2b.Y) SwapPoints(pt2a, pt2b);
  712. if (pt1a.Y < pt2a.Y) pt1 = pt1a; else pt1 = pt2a;
  713. if (pt1b.Y > pt2b.Y) pt2 = pt1b; else pt2 = pt2b;
  714. return pt1.Y > pt2.Y;
  715. }
  716. }
  717. //------------------------------------------------------------------------------
  718. bool FirstIsBottomPt(const OutPt* btmPt1, const OutPt* btmPt2)
  719. {
  720. OutPt *p = btmPt1->Prev;
  721. while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Prev;
  722. double dx1p = std::fabs(GetDx(btmPt1->Pt, p->Pt));
  723. p = btmPt1->Next;
  724. while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Next;
  725. double dx1n = std::fabs(GetDx(btmPt1->Pt, p->Pt));
  726. p = btmPt2->Prev;
  727. while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Prev;
  728. double dx2p = std::fabs(GetDx(btmPt2->Pt, p->Pt));
  729. p = btmPt2->Next;
  730. while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Next;
  731. double dx2n = std::fabs(GetDx(btmPt2->Pt, p->Pt));
  732. if (std::max(dx1p, dx1n) == std::max(dx2p, dx2n) &&
  733. std::min(dx1p, dx1n) == std::min(dx2p, dx2n))
  734. return Area(btmPt1) > 0; //if otherwise identical use orientation
  735. else
  736. return (dx1p >= dx2p && dx1p >= dx2n) || (dx1n >= dx2p && dx1n >= dx2n);
  737. }
  738. //------------------------------------------------------------------------------
  739. OutPt* GetBottomPt(OutPt *pp)
  740. {
  741. OutPt* dups = 0;
  742. OutPt* p = pp->Next;
  743. while (p != pp)
  744. {
  745. if (p->Pt.Y > pp->Pt.Y)
  746. {
  747. pp = p;
  748. dups = 0;
  749. }
  750. else if (p->Pt.Y == pp->Pt.Y && p->Pt.X <= pp->Pt.X)
  751. {
  752. if (p->Pt.X < pp->Pt.X)
  753. {
  754. dups = 0;
  755. pp = p;
  756. } else
  757. {
  758. if (p->Next != pp && p->Prev != pp) dups = p;
  759. }
  760. }
  761. p = p->Next;
  762. }
  763. if (dups)
  764. {
  765. //there appears to be at least 2 vertices at BottomPt so ...
  766. while (dups != p)
  767. {
  768. if (!FirstIsBottomPt(p, dups)) pp = dups;
  769. dups = dups->Next;
  770. while (dups->Pt != pp->Pt) dups = dups->Next;
  771. }
  772. }
  773. return pp;
  774. }
  775. //------------------------------------------------------------------------------
  776. bool Pt2IsBetweenPt1AndPt3(const IntPoint pt1,
  777. const IntPoint pt2, const IntPoint pt3)
  778. {
  779. if ((pt1 == pt3) || (pt1 == pt2) || (pt3 == pt2))
  780. return false;
  781. else if (pt1.X != pt3.X)
  782. return (pt2.X > pt1.X) == (pt2.X < pt3.X);
  783. else
  784. return (pt2.Y > pt1.Y) == (pt2.Y < pt3.Y);
  785. }
  786. //------------------------------------------------------------------------------
  787. bool HorzSegmentsOverlap(cInt seg1a, cInt seg1b, cInt seg2a, cInt seg2b)
  788. {
  789. if (seg1a > seg1b) std::swap(seg1a, seg1b);
  790. if (seg2a > seg2b) std::swap(seg2a, seg2b);
  791. return (seg1a < seg2b) && (seg2a < seg1b);
  792. }
  793. //------------------------------------------------------------------------------
  794. // ClipperBase class methods ...
  795. //------------------------------------------------------------------------------
  796. ClipperBase::ClipperBase() //constructor
  797. {
  798. m_CurrentLM = m_MinimaList.begin(); //begin() == end() here
  799. m_UseFullRange = false;
  800. }
  801. //------------------------------------------------------------------------------
  802. ClipperBase::~ClipperBase() //destructor
  803. {
  804. Clear();
  805. }
  806. //------------------------------------------------------------------------------
  807. void RangeTest(const IntPoint& Pt, bool& useFullRange)
  808. {
  809. if (useFullRange)
  810. {
  811. if (Pt.X > hiRange || Pt.Y > hiRange || -Pt.X > hiRange || -Pt.Y > hiRange)
  812. throw clipperException("Coordinate outside allowed range");
  813. }
  814. else if (Pt.X > loRange|| Pt.Y > loRange || -Pt.X > loRange || -Pt.Y > loRange)
  815. {
  816. useFullRange = true;
  817. RangeTest(Pt, useFullRange);
  818. }
  819. }
  820. //------------------------------------------------------------------------------
  821. TEdge* FindNextLocMin(TEdge* E)
  822. {
  823. for (;;)
  824. {
  825. while (E->Bot != E->Prev->Bot || E->Curr == E->Top) E = E->Next;
  826. if (!IsHorizontal(*E) && !IsHorizontal(*E->Prev)) break;
  827. while (IsHorizontal(*E->Prev)) E = E->Prev;
  828. TEdge* E2 = E;
  829. while (IsHorizontal(*E)) E = E->Next;
  830. if (E->Top.Y == E->Prev->Bot.Y) continue; //ie just an intermediate horz.
  831. if (E2->Prev->Bot.X < E->Bot.X) E = E2;
  832. break;
  833. }
  834. return E;
  835. }
  836. //------------------------------------------------------------------------------
  837. TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward)
  838. {
  839. TEdge *Result = E;
  840. TEdge *Horz = 0;
  841. if (E->OutIdx == Skip)
  842. {
  843. //if edges still remain in the current bound beyond the skip edge then
  844. //create another LocMin and call ProcessBound once more
  845. if (NextIsForward)
  846. {
  847. while (E->Top.Y == E->Next->Bot.Y) E = E->Next;
  848. //don't include top horizontals when parsing a bound a second time,
  849. //they will be contained in the opposite bound ...
  850. while (E != Result && IsHorizontal(*E)) E = E->Prev;
  851. }
  852. else
  853. {
  854. while (E->Top.Y == E->Prev->Bot.Y) E = E->Prev;
  855. while (E != Result && IsHorizontal(*E)) E = E->Next;
  856. }
  857. if (E == Result)
  858. {
  859. if (NextIsForward) Result = E->Next;
  860. else Result = E->Prev;
  861. }
  862. else
  863. {
  864. //there are more edges in the bound beyond result starting with E
  865. if (NextIsForward)
  866. E = Result->Next;
  867. else
  868. E = Result->Prev;
  869. MinimaList::value_type locMin;
  870. locMin.Y = E->Bot.Y;
  871. locMin.LeftBound = 0;
  872. locMin.RightBound = E;
  873. E->WindDelta = 0;
  874. Result = ProcessBound(E, NextIsForward);
  875. m_MinimaList.push_back(locMin);
  876. }
  877. return Result;
  878. }
  879. TEdge *EStart;
  880. if (IsHorizontal(*E))
  881. {
  882. //We need to be careful with open paths because this may not be a
  883. //true local minima (ie E may be following a skip edge).
  884. //Also, consecutive horz. edges may start heading left before going right.
  885. if (NextIsForward)
  886. EStart = E->Prev;
  887. else
  888. EStart = E->Next;
  889. if (IsHorizontal(*EStart)) //ie an adjoining horizontal skip edge
  890. {
  891. if (EStart->Bot.X != E->Bot.X && EStart->Top.X != E->Bot.X)
  892. ReverseHorizontal(*E);
  893. }
  894. else if (EStart->Bot.X != E->Bot.X)
  895. ReverseHorizontal(*E);
  896. }
  897. EStart = E;
  898. if (NextIsForward)
  899. {
  900. while (Result->Top.Y == Result->Next->Bot.Y && Result->Next->OutIdx != Skip)
  901. Result = Result->Next;
  902. if (IsHorizontal(*Result) && Result->Next->OutIdx != Skip)
  903. {
  904. //nb: at the top of a bound, horizontals are added to the bound
  905. //only when the preceding edge attaches to the horizontal's left vertex
  906. //unless a Skip edge is encountered when that becomes the top divide
  907. Horz = Result;
  908. while (IsHorizontal(*Horz->Prev)) Horz = Horz->Prev;
  909. if (Horz->Prev->Top.X > Result->Next->Top.X) Result = Horz->Prev;
  910. }
  911. while (E != Result)
  912. {
  913. E->NextInLML = E->Next;
  914. if (IsHorizontal(*E) && E != EStart &&
  915. E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);
  916. E = E->Next;
  917. }
  918. if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Prev->Top.X)
  919. ReverseHorizontal(*E);
  920. Result = Result->Next; //move to the edge just beyond current bound
  921. } else
  922. {
  923. while (Result->Top.Y == Result->Prev->Bot.Y && Result->Prev->OutIdx != Skip)
  924. Result = Result->Prev;
  925. if (IsHorizontal(*Result) && Result->Prev->OutIdx != Skip)
  926. {
  927. Horz = Result;
  928. while (IsHorizontal(*Horz->Next)) Horz = Horz->Next;
  929. if (Horz->Next->Top.X == Result->Prev->Top.X ||
  930. Horz->Next->Top.X > Result->Prev->Top.X) Result = Horz->Next;
  931. }
  932. while (E != Result)
  933. {
  934. E->NextInLML = E->Prev;
  935. if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X)
  936. ReverseHorizontal(*E);
  937. E = E->Prev;
  938. }
  939. if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X)
  940. ReverseHorizontal(*E);
  941. Result = Result->Prev; //move to the edge just beyond current bound
  942. }
  943. return Result;
  944. }
  945. //------------------------------------------------------------------------------
  946. bool ClipperBase::AddPath(const Path &pg, PolyType PolyTyp, bool Closed)
  947. {
  948. #ifdef use_lines
  949. if (!Closed && PolyTyp == ptClip)
  950. throw clipperException("AddPath: Open paths must be subject.");
  951. #else
  952. if (!Closed)
  953. throw clipperException("AddPath: Open paths have been disabled.");
  954. #endif
  955. int highI = (int)pg.size() -1;
  956. if (Closed) while (highI > 0 && (pg[highI] == pg[0])) --highI;
  957. while (highI > 0 && (pg[highI] == pg[highI -1])) --highI;
  958. if ((Closed && highI < 2) || (!Closed && highI < 1)) return false;
  959. //create a new edge array ...
  960. TEdge *edges = new TEdge [highI +1];
  961. bool IsFlat = true;
  962. //1. Basic (first) edge initialization ...
  963. try
  964. {
  965. edges[1].Curr = pg[1];
  966. RangeTest(pg[0], m_UseFullRange);
  967. RangeTest(pg[highI], m_UseFullRange);
  968. InitEdge(&edges[0], &edges[1], &edges[highI], pg[0]);
  969. InitEdge(&edges[highI], &edges[0], &edges[highI-1], pg[highI]);
  970. for (int i = highI - 1; i >= 1; --i)
  971. {
  972. RangeTest(pg[i], m_UseFullRange);
  973. InitEdge(&edges[i], &edges[i+1], &edges[i-1], pg[i]);
  974. }
  975. }
  976. catch(...)
  977. {
  978. delete [] edges;
  979. throw; //range test fails
  980. }
  981. TEdge *eStart = &edges[0];
  982. //2. Remove duplicate vertices, and (when closed) collinear edges ...
  983. TEdge *E = eStart, *eLoopStop = eStart;
  984. for (;;)
  985. {
  986. //nb: allows matching start and end points when not Closed ...
  987. if (E->Curr == E->Next->Curr && (Closed || E->Next != eStart))
  988. {
  989. if (E == E->Next) break;
  990. if (E == eStart) eStart = E->Next;
  991. E = RemoveEdge(E);
  992. eLoopStop = E;
  993. continue;
  994. }
  995. if (E->Prev == E->Next)
  996. break; //only two vertices
  997. else if (Closed &&
  998. SlopesEqual(E->Prev->Curr, E->Curr, E->Next->Curr, m_UseFullRange) &&
  999. (!m_PreserveCollinear ||
  1000. !Pt2IsBetweenPt1AndPt3(E->Prev->Curr, E->Curr, E->Next->Curr)))
  1001. {
  1002. //Collinear edges are allowed for open paths but in closed paths
  1003. //the default is to merge adjacent collinear edges into a single edge.
  1004. //However, if the PreserveCollinear property is enabled, only overlapping
  1005. //collinear edges (ie spikes) will be removed from closed paths.
  1006. if (E == eStart) eStart = E->Next;
  1007. E = RemoveEdge(E);
  1008. E = E->Prev;
  1009. eLoopStop = E;
  1010. continue;
  1011. }
  1012. E = E->Next;
  1013. if ((E == eLoopStop) || (!Closed && E->Next == eStart)) break;
  1014. }
  1015. if ((!Closed && (E == E->Next)) || (Closed && (E->Prev == E->Next)))
  1016. {
  1017. delete [] edges;
  1018. return false;
  1019. }
  1020. if (!Closed)
  1021. {
  1022. m_HasOpenPaths = true;
  1023. eStart->Prev->OutIdx = Skip;
  1024. }
  1025. //3. Do second stage of edge initialization ...
  1026. E = eStart;
  1027. do
  1028. {
  1029. InitEdge2(*E, PolyTyp);
  1030. E = E->Next;
  1031. if (IsFlat && E->Curr.Y != eStart->Curr.Y) IsFlat = false;
  1032. }
  1033. while (E != eStart);
  1034. //4. Finally, add edge bounds to LocalMinima list ...
  1035. //Totally flat paths must be handled differently when adding them
  1036. //to LocalMinima list to avoid endless loops etc ...
  1037. if (IsFlat)
  1038. {
  1039. if (Closed)
  1040. {
  1041. delete [] edges;
  1042. return false;
  1043. }
  1044. E->Prev->OutIdx = Skip;
  1045. MinimaList::value_type locMin;
  1046. locMin.Y = E->Bot.Y;
  1047. locMin.LeftBound = 0;
  1048. locMin.RightBound = E;
  1049. locMin.RightBound->Side = esRight;
  1050. locMin.RightBound->WindDelta = 0;
  1051. for (;;)
  1052. {
  1053. if (E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);
  1054. if (E->Next->OutIdx == Skip) break;
  1055. E->NextInLML = E->Next;
  1056. E = E->Next;
  1057. }
  1058. m_MinimaList.push_back(locMin);
  1059. m_edges.push_back(edges);
  1060. return true;
  1061. }
  1062. m_edges.push_back(edges);
  1063. bool leftBoundIsForward;
  1064. TEdge* EMin = 0;
  1065. //workaround to avoid an endless loop in the while loop below when
  1066. //open paths have matching start and end points ...
  1067. if (E->Prev->Bot == E->Prev->Top) E = E->Next;
  1068. for (;;)
  1069. {
  1070. E = FindNextLocMin(E);
  1071. if (E == EMin) break;
  1072. else if (!EMin) EMin = E;
  1073. //E and E.Prev now share a local minima (left aligned if horizontal).
  1074. //Compare their slopes to find which starts which bound ...
  1075. MinimaList::value_type locMin;
  1076. locMin.Y = E->Bot.Y;
  1077. if (E->Dx < E->Prev->Dx)
  1078. {
  1079. locMin.LeftBound = E->Prev;
  1080. locMin.RightBound = E;
  1081. leftBoundIsForward = false; //Q.nextInLML = Q.prev
  1082. } else
  1083. {
  1084. locMin.LeftBound = E;
  1085. locMin.RightBound = E->Prev;
  1086. leftBoundIsForward = true; //Q.nextInLML = Q.next
  1087. }
  1088. if (!Closed) locMin.LeftBound->WindDelta = 0;
  1089. else if (locMin.LeftBound->Next == locMin.RightBound)
  1090. locMin.LeftBound->WindDelta = -1;
  1091. else locMin.LeftBound->WindDelta = 1;
  1092. locMin.RightBound->WindDelta = -locMin.LeftBound->WindDelta;
  1093. E = ProcessBound(locMin.LeftBound, leftBoundIsForward);
  1094. if (E->OutIdx == Skip) E = ProcessBound(E, leftBoundIsForward);
  1095. TEdge* E2 = ProcessBound(locMin.RightBound, !leftBoundIsForward);
  1096. if (E2->OutIdx == Skip) E2 = ProcessBound(E2, !leftBoundIsForward);
  1097. if (locMin.LeftBound->OutIdx == Skip)
  1098. locMin.LeftBound = 0;
  1099. else if (locMin.RightBound->OutIdx == Skip)
  1100. locMin.RightBound = 0;
  1101. m_MinimaList.push_back(locMin);
  1102. if (!leftBoundIsForward) E = E2;
  1103. }
  1104. return true;
  1105. }
  1106. //------------------------------------------------------------------------------
  1107. bool ClipperBase::AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed)
  1108. {
  1109. bool result = false;
  1110. for (Paths::size_type i = 0; i < ppg.size(); ++i)
  1111. if (AddPath(ppg[i], PolyTyp, Closed)) result = true;
  1112. return result;
  1113. }
  1114. //------------------------------------------------------------------------------
  1115. void ClipperBase::Clear()
  1116. {
  1117. DisposeLocalMinimaList();
  1118. for (EdgeList::size_type i = 0; i < m_edges.size(); ++i)
  1119. {
  1120. TEdge* edges = m_edges[i];
  1121. delete [] edges;
  1122. }
  1123. m_edges.clear();
  1124. m_UseFullRange = false;
  1125. m_HasOpenPaths = false;
  1126. }
  1127. //------------------------------------------------------------------------------
  1128. void ClipperBase::Reset()
  1129. {
  1130. m_CurrentLM = m_MinimaList.begin();
  1131. if (m_CurrentLM == m_MinimaList.end()) return; //ie nothing to process
  1132. std::sort(m_MinimaList.begin(), m_MinimaList.end(), LocMinSorter());
  1133. m_Scanbeam = ScanbeamList(); //clears/resets priority_queue
  1134. //reset all edges ...
  1135. for (MinimaList::iterator lm = m_MinimaList.begin(); lm != m_MinimaList.end(); ++lm)
  1136. {
  1137. InsertScanbeam(lm->Y);
  1138. TEdge* e = lm->LeftBound;
  1139. if (e)
  1140. {
  1141. e->Curr = e->Bot;
  1142. e->Side = esLeft;
  1143. e->OutIdx = Unassigned;
  1144. }
  1145. e = lm->RightBound;
  1146. if (e)
  1147. {
  1148. e->Curr = e->Bot;
  1149. e->Side = esRight;
  1150. e->OutIdx = Unassigned;
  1151. }
  1152. }
  1153. m_ActiveEdges = 0;
  1154. m_CurrentLM = m_MinimaList.begin();
  1155. }
  1156. //------------------------------------------------------------------------------
  1157. void ClipperBase::DisposeLocalMinimaList()
  1158. {
  1159. m_MinimaList.clear();
  1160. m_CurrentLM = m_MinimaList.begin();
  1161. }
  1162. //------------------------------------------------------------------------------
  1163. bool ClipperBase::PopLocalMinima(cInt Y, const LocalMinimum *&locMin)
  1164. {
  1165. if (m_CurrentLM == m_MinimaList.end() || (*m_CurrentLM).Y != Y) return false;
  1166. locMin = &(*m_CurrentLM);
  1167. ++m_CurrentLM;
  1168. return true;
  1169. }
  1170. //------------------------------------------------------------------------------
  1171. IntRect ClipperBase::GetBounds()
  1172. {
  1173. IntRect result;
  1174. MinimaList::iterator lm = m_MinimaList.begin();
  1175. if (lm == m_MinimaList.end())
  1176. {
  1177. result.left = result.top = result.right = result.bottom = 0;
  1178. return result;
  1179. }
  1180. result.left = lm->LeftBound->Bot.X;
  1181. result.top = lm->LeftBound->Bot.Y;
  1182. result.right = lm->LeftBound->Bot.X;
  1183. result.bottom = lm->LeftBound->Bot.Y;
  1184. while (lm != m_MinimaList.end())
  1185. {
  1186. //todo - needs fixing for open paths
  1187. result.bottom = std::max(result.bottom, lm->LeftBound->Bot.Y);
  1188. TEdge* e = lm->LeftBound;
  1189. for (;;) {
  1190. TEdge* bottomE = e;
  1191. while (e->NextInLML)
  1192. {
  1193. if (e->Bot.X < result.left) result.left = e->Bot.X;
  1194. if (e->Bot.X > result.right) result.right = e->Bot.X;
  1195. e = e->NextInLML;
  1196. }
  1197. result.left = std::min(result.left, e->Bot.X);
  1198. result.right = std::max(result.right, e->Bot.X);
  1199. result.left = std::min(result.left, e->Top.X);
  1200. result.right = std::max(result.right, e->Top.X);
  1201. result.top = std::min(result.top, e->Top.Y);
  1202. if (bottomE == lm->LeftBound) e = lm->RightBound;
  1203. else break;
  1204. }
  1205. ++lm;
  1206. }
  1207. return result;
  1208. }
  1209. //------------------------------------------------------------------------------
  1210. void ClipperBase::InsertScanbeam(const cInt Y)
  1211. {
  1212. m_Scanbeam.push(Y);
  1213. }
  1214. //------------------------------------------------------------------------------
  1215. bool ClipperBase::PopScanbeam(cInt &Y)
  1216. {
  1217. if (m_Scanbeam.empty()) return false;
  1218. Y = m_Scanbeam.top();
  1219. m_Scanbeam.pop();
  1220. while (!m_Scanbeam.empty() && Y == m_Scanbeam.top()) { m_Scanbeam.pop(); } // Pop duplicates.
  1221. return true;
  1222. }
  1223. //------------------------------------------------------------------------------
  1224. void ClipperBase::DisposeAllOutRecs(){
  1225. for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
  1226. DisposeOutRec(i);
  1227. m_PolyOuts.clear();
  1228. }
  1229. //------------------------------------------------------------------------------
  1230. void ClipperBase::DisposeOutRec(PolyOutList::size_type index)
  1231. {
  1232. OutRec *outRec = m_PolyOuts[index];
  1233. if (outRec->Pts) DisposeOutPts(outRec->Pts);
  1234. delete outRec;
  1235. m_PolyOuts[index] = 0;
  1236. }
  1237. //------------------------------------------------------------------------------
  1238. void ClipperBase::DeleteFromAEL(TEdge *e)
  1239. {
  1240. TEdge* AelPrev = e->PrevInAEL;
  1241. TEdge* AelNext = e->NextInAEL;
  1242. if (!AelPrev && !AelNext && (e != m_ActiveEdges)) return; //already deleted
  1243. if (AelPrev) AelPrev->NextInAEL = AelNext;
  1244. else m_ActiveEdges = AelNext;
  1245. if (AelNext) AelNext->PrevInAEL = AelPrev;
  1246. e->NextInAEL = 0;
  1247. e->PrevInAEL = 0;
  1248. }
  1249. //------------------------------------------------------------------------------
  1250. OutRec* ClipperBase::CreateOutRec()
  1251. {
  1252. OutRec* result = new OutRec;
  1253. result->IsHole = false;
  1254. result->IsOpen = false;
  1255. result->FirstLeft = 0;
  1256. result->Pts = 0;
  1257. result->BottomPt = 0;
  1258. result->PolyNd = 0;
  1259. m_PolyOuts.push_back(result);
  1260. result->Idx = (int)m_PolyOuts.size() - 1;
  1261. return result;
  1262. }
  1263. //------------------------------------------------------------------------------
  1264. void ClipperBase::SwapPositionsInAEL(TEdge *Edge1, TEdge *Edge2)
  1265. {
  1266. //check that one or other edge hasn't already been removed from AEL ...
  1267. if (Edge1->NextInAEL == Edge1->PrevInAEL ||
  1268. Edge2->NextInAEL == Edge2->PrevInAEL) return;
  1269. if (Edge1->NextInAEL == Edge2)
  1270. {
  1271. TEdge* Next = Edge2->NextInAEL;
  1272. if (Next) Next->PrevInAEL = Edge1;
  1273. TEdge* Prev = Edge1->PrevInAEL;
  1274. if (Prev) Prev->NextInAEL = Edge2;
  1275. Edge2->PrevInAEL = Prev;
  1276. Edge2->NextInAEL = Edge1;
  1277. Edge1->PrevInAEL = Edge2;
  1278. Edge1->NextInAEL = Next;
  1279. }
  1280. else if (Edge2->NextInAEL == Edge1)
  1281. {
  1282. TEdge* Next = Edge1->NextInAEL;
  1283. if (Next) Next->PrevInAEL = Edge2;
  1284. TEdge* Prev = Edge2->PrevInAEL;
  1285. if (Prev) Prev->NextInAEL = Edge1;
  1286. Edge1->PrevInAEL = Prev;
  1287. Edge1->NextInAEL = Edge2;
  1288. Edge2->PrevInAEL = Edge1;
  1289. Edge2->NextInAEL = Next;
  1290. }
  1291. else
  1292. {
  1293. TEdge* Next = Edge1->NextInAEL;
  1294. TEdge* Prev = Edge1->PrevInAEL;
  1295. Edge1->NextInAEL = Edge2->NextInAEL;
  1296. if (Edge1->NextInAEL) Edge1->NextInAEL->PrevInAEL = Edge1;
  1297. Edge1->PrevInAEL = Edge2->PrevInAEL;
  1298. if (Edge1->PrevInAEL) Edge1->PrevInAEL->NextInAEL = Edge1;
  1299. Edge2->NextInAEL = Next;
  1300. if (Edge2->NextInAEL) Edge2->NextInAEL->PrevInAEL = Edge2;
  1301. Edge2->PrevInAEL = Prev;
  1302. if (Edge2->PrevInAEL) Edge2->PrevInAEL->NextInAEL = Edge2;
  1303. }
  1304. if (!Edge1->PrevInAEL) m_ActiveEdges = Edge1;
  1305. else if (!Edge2->PrevInAEL) m_ActiveEdges = Edge2;
  1306. }
  1307. //------------------------------------------------------------------------------
  1308. void ClipperBase::UpdateEdgeIntoAEL(TEdge *&e)
  1309. {
  1310. if (!e->NextInLML)
  1311. throw clipperException("UpdateEdgeIntoAEL: invalid call");
  1312. e->NextInLML->OutIdx = e->OutIdx;
  1313. TEdge* AelPrev = e->PrevInAEL;
  1314. TEdge* AelNext = e->NextInAEL;
  1315. if (AelPrev) AelPrev->NextInAEL = e->NextInLML;
  1316. else m_ActiveEdges = e->NextInLML;
  1317. if (AelNext) AelNext->PrevInAEL = e->NextInLML;
  1318. e->NextInLML->Side = e->Side;
  1319. e->NextInLML->WindDelta = e->WindDelta;
  1320. e->NextInLML->WindCnt = e->WindCnt;
  1321. e->NextInLML->WindCnt2 = e->WindCnt2;
  1322. e = e->NextInLML;
  1323. e->Curr = e->Bot;
  1324. e->PrevInAEL = AelPrev;
  1325. e->NextInAEL = AelNext;
  1326. if (!IsHorizontal(*e)) InsertScanbeam(e->Top.Y);
  1327. }
  1328. //------------------------------------------------------------------------------
  1329. bool ClipperBase::LocalMinimaPending()
  1330. {
  1331. return (m_CurrentLM != m_MinimaList.end());
  1332. }
  1333. //------------------------------------------------------------------------------
  1334. // TClipper methods ...
  1335. //------------------------------------------------------------------------------
  1336. Clipper::Clipper(int initOptions) : ClipperBase() //constructor
  1337. {
  1338. m_ExecuteLocked = false;
  1339. m_UseFullRange = false;
  1340. m_ReverseOutput = ((initOptions & ioReverseSolution) != 0);
  1341. m_StrictSimple = ((initOptions & ioStrictlySimple) != 0);
  1342. m_PreserveCollinear = ((initOptions & ioPreserveCollinear) != 0);
  1343. m_HasOpenPaths = false;
  1344. #ifdef use_xyz
  1345. m_ZFill = 0;
  1346. #endif
  1347. }
  1348. //------------------------------------------------------------------------------
  1349. #ifdef use_xyz
  1350. void Clipper::ZFillFunction(ZFillCallback zFillFunc)
  1351. {
  1352. m_ZFill = zFillFunc;
  1353. }
  1354. //------------------------------------------------------------------------------
  1355. #endif
  1356. bool Clipper::Execute(ClipType clipType, Paths &solution, PolyFillType fillType)
  1357. {
  1358. return Execute(clipType, solution, fillType, fillType);
  1359. }
  1360. //------------------------------------------------------------------------------
  1361. bool Clipper::Execute(ClipType clipType, PolyTree &polytree, PolyFillType fillType)
  1362. {
  1363. return Execute(clipType, polytree, fillType, fillType);
  1364. }
  1365. //------------------------------------------------------------------------------
  1366. bool Clipper::Execute(ClipType clipType, Paths &solution,
  1367. PolyFillType subjFillType, PolyFillType clipFillType)
  1368. {
  1369. if( m_ExecuteLocked ) return false;
  1370. if (m_HasOpenPaths)
  1371. throw clipperException("Error: PolyTree struct is needed for open path clipping.");
  1372. m_ExecuteLocked = true;
  1373. solution.resize(0);
  1374. m_SubjFillType = subjFillType;
  1375. m_ClipFillType = clipFillType;
  1376. m_ClipType = clipType;
  1377. m_UsingPolyTree = false;
  1378. bool succeeded = ExecuteInternal();
  1379. if (succeeded) BuildResult(solution);
  1380. DisposeAllOutRecs();
  1381. m_ExecuteLocked = false;
  1382. return succeeded;
  1383. }
  1384. //------------------------------------------------------------------------------
  1385. bool Clipper::Execute(ClipType clipType, PolyTree& polytree,
  1386. PolyFillType subjFillType, PolyFillType clipFillType)
  1387. {
  1388. if( m_ExecuteLocked ) return false;
  1389. m_ExecuteLocked = true;
  1390. m_SubjFillType = subjFillType;
  1391. m_ClipFillType = clipFillType;
  1392. m_ClipType = clipType;
  1393. m_UsingPolyTree = true;
  1394. bool succeeded = ExecuteInternal();
  1395. if (succeeded) BuildResult2(polytree);
  1396. DisposeAllOutRecs();
  1397. m_ExecuteLocked = false;
  1398. return succeeded;
  1399. }
  1400. //------------------------------------------------------------------------------
  1401. void Clipper::FixHoleLinkage(OutRec &outrec)
  1402. {
  1403. //skip OutRecs that (a) contain outermost polygons or
  1404. //(b) already have the correct owner/child linkage ...
  1405. if (!outrec.FirstLeft ||
  1406. (outrec.IsHole != outrec.FirstLeft->IsHole &&
  1407. outrec.FirstLeft->Pts)) return;
  1408. OutRec* orfl = outrec.FirstLeft;
  1409. while (orfl && ((orfl->IsHole == outrec.IsHole) || !orfl->Pts))
  1410. orfl = orfl->FirstLeft;
  1411. outrec.FirstLeft = orfl;
  1412. }
  1413. //------------------------------------------------------------------------------
  1414. bool Clipper::ExecuteInternal()
  1415. {
  1416. bool succeeded = true;
  1417. try {
  1418. Reset();
  1419. m_Maxima = MaximaList();
  1420. m_SortedEdges = 0;
  1421. succeeded = true;
  1422. cInt botY = 0, topY = 0;
  1423. if (!PopScanbeam(botY)) return false;
  1424. InsertLocalMinimaIntoAEL(botY);
  1425. while (PopScanbeam(topY) || LocalMinimaPending())
  1426. {
  1427. ProcessHorizontals();
  1428. ClearGhostJoins();
  1429. if (!ProcessIntersections(topY))
  1430. {
  1431. succeeded = false;
  1432. break;
  1433. }
  1434. ProcessEdgesAtTopOfScanbeam(topY);
  1435. botY = topY;
  1436. InsertLocalMinimaIntoAEL(botY);
  1437. }
  1438. }
  1439. catch(...)
  1440. {
  1441. succeeded = false;
  1442. }
  1443. if (succeeded)
  1444. {
  1445. //fix orientations ...
  1446. for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
  1447. {
  1448. OutRec *outRec = m_PolyOuts[i];
  1449. if (!outRec->Pts || outRec->IsOpen) continue;
  1450. if ((outRec->IsHole ^ m_ReverseOutput) == (Area(*outRec) > 0))
  1451. ReversePolyPtLinks(outRec->Pts);
  1452. }
  1453. if (!m_Joins.empty()) JoinCommonEdges();
  1454. //unfortunately FixupOutPolygon() must be done after JoinCommonEdges()
  1455. for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
  1456. {
  1457. OutRec *outRec = m_PolyOuts[i];
  1458. if (!outRec->Pts) continue;
  1459. if (outRec->IsOpen)
  1460. FixupOutPolyline(*outRec);
  1461. else
  1462. FixupOutPolygon(*outRec);
  1463. }
  1464. if (m_StrictSimple) DoSimplePolygons();
  1465. }
  1466. ClearJoins();
  1467. ClearGhostJoins();
  1468. return succeeded;
  1469. }
  1470. //------------------------------------------------------------------------------
  1471. void Clipper::SetWindingCount(TEdge &edge)
  1472. {
  1473. TEdge *e = edge.PrevInAEL;
  1474. //find the edge of the same polytype that immediately preceeds 'edge' in AEL
  1475. while (e && ((e->PolyTyp != edge.PolyTyp) || (e->WindDelta == 0))) e = e->PrevInAEL;
  1476. if (!e)
  1477. {
  1478. if (edge.WindDelta == 0)
  1479. {
  1480. PolyFillType pft = (edge.PolyTyp == ptSubject ? m_SubjFillType : m_ClipFillType);
  1481. edge.WindCnt = (pft == pftNegative ? -1 : 1);
  1482. }
  1483. else
  1484. edge.WindCnt = edge.WindDelta;
  1485. edge.WindCnt2 = 0;
  1486. e = m_ActiveEdges; //ie get ready to calc WindCnt2
  1487. }
  1488. else if (edge.WindDelta == 0 && m_ClipType != ctUnion)
  1489. {
  1490. edge.WindCnt = 1;
  1491. edge.WindCnt2 = e->WindCnt2;
  1492. e = e->NextInAEL; //ie get ready to calc WindCnt2
  1493. }
  1494. else if (IsEvenOddFillType(edge))
  1495. {
  1496. //EvenOdd filling ...
  1497. if (edge.WindDelta == 0)
  1498. {
  1499. //are we inside a subj polygon ...
  1500. bool Inside = true;
  1501. TEdge *e2 = e->PrevInAEL;
  1502. while (e2)
  1503. {
  1504. if (e2->PolyTyp == e->PolyTyp && e2->WindDelta != 0)
  1505. Inside = !Inside;
  1506. e2 = e2->PrevInAEL;
  1507. }
  1508. edge.WindCnt = (Inside ? 0 : 1);
  1509. }
  1510. else
  1511. {
  1512. edge.WindCnt = edge.WindDelta;
  1513. }
  1514. edge.WindCnt2 = e->WindCnt2;
  1515. e = e->NextInAEL; //ie get ready to calc WindCnt2
  1516. }
  1517. else
  1518. {
  1519. //nonZero, Positive or Negative filling ...
  1520. if (e->WindCnt * e->WindDelta < 0)
  1521. {
  1522. //prev edge is 'decreasing' WindCount (WC) toward zero
  1523. //so we're outside the previous polygon ...
  1524. if (Abs(e->WindCnt) > 1)
  1525. {
  1526. //outside prev poly but still inside another.
  1527. //when reversing direction of prev poly use the same WC
  1528. if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;
  1529. //otherwise continue to 'decrease' WC ...
  1530. else edge.WindCnt = e->WindCnt + edge.WindDelta;
  1531. }
  1532. else
  1533. //now outside all polys of same polytype so set own WC ...
  1534. edge.WindCnt = (edge.WindDelta == 0 ? 1 : edge.WindDelta);
  1535. } else
  1536. {
  1537. //prev edge is 'increasing' WindCount (WC) away from zero
  1538. //so we're inside the previous polygon ...
  1539. if (edge.WindDelta == 0)
  1540. edge.WindCnt = (e->WindCnt < 0 ? e->WindCnt - 1 : e->WindCnt + 1);
  1541. //if wind direction is reversing prev then use same WC
  1542. else if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;
  1543. //otherwise add to WC ...
  1544. else edge.WindCnt = e->WindCnt + edge.WindDelta;
  1545. }
  1546. edge.WindCnt2 = e->WindCnt2;
  1547. e = e->NextInAEL; //ie get ready to calc WindCnt2
  1548. }
  1549. //update WindCnt2 ...
  1550. if (IsEvenOddAltFillType(edge))
  1551. {
  1552. //EvenOdd filling ...
  1553. while (e != &edge)
  1554. {
  1555. if (e->WindDelta != 0)
  1556. edge.WindCnt2 = (edge.WindCnt2 == 0 ? 1 : 0);
  1557. e = e->NextInAEL;
  1558. }
  1559. } else
  1560. {
  1561. //nonZero, Positive or Negative filling ...
  1562. while ( e != &edge )
  1563. {
  1564. edge.WindCnt2 += e->WindDelta;
  1565. e = e->NextInAEL;
  1566. }
  1567. }
  1568. }
  1569. //------------------------------------------------------------------------------
  1570. bool Clipper::IsEvenOddFillType(const TEdge& edge) const
  1571. {
  1572. if (edge.PolyTyp == ptSubject)
  1573. return m_SubjFillType == pftEvenOdd; else
  1574. return m_ClipFillType == pftEvenOdd;
  1575. }
  1576. //------------------------------------------------------------------------------
  1577. bool Clipper::IsEvenOddAltFillType(const TEdge& edge) const
  1578. {
  1579. if (edge.PolyTyp == ptSubject)
  1580. return m_ClipFillType == pftEvenOdd; else
  1581. return m_SubjFillType == pftEvenOdd;
  1582. }
  1583. //------------------------------------------------------------------------------
  1584. bool Clipper::IsContributing(const TEdge& edge) const
  1585. {
  1586. PolyFillType pft, pft2;
  1587. if (edge.PolyTyp == ptSubject)
  1588. {
  1589. pft = m_SubjFillType;
  1590. pft2 = m_ClipFillType;
  1591. } else
  1592. {
  1593. pft = m_ClipFillType;
  1594. pft2 = m_SubjFillType;
  1595. }
  1596. switch(pft)
  1597. {
  1598. case pftEvenOdd:
  1599. //return false if a subj line has been flagged as inside a subj polygon
  1600. if (edge.WindDelta == 0 && edge.WindCnt != 1) return false;
  1601. break;
  1602. case pftNonZero:
  1603. if (Abs(edge.WindCnt) != 1) return false;
  1604. break;
  1605. case pftPositive:
  1606. if (edge.WindCnt != 1) return false;
  1607. break;
  1608. default: //pftNegative
  1609. if (edge.WindCnt != -1) return false;
  1610. }
  1611. switch(m_ClipType)
  1612. {
  1613. case ctIntersection:
  1614. switch(pft2)
  1615. {
  1616. case pftEvenOdd:
  1617. case pftNonZero:
  1618. return (edge.WindCnt2 != 0);
  1619. case pftPositive:
  1620. return (edge.WindCnt2 > 0);
  1621. default:
  1622. return (edge.WindCnt2 < 0);
  1623. }
  1624. break;
  1625. case ctUnion:
  1626. switch(pft2)
  1627. {
  1628. case pftEvenOdd:
  1629. case pftNonZero:
  1630. return (edge.WindCnt2 == 0);
  1631. case pftPositive:
  1632. return (edge.WindCnt2 <= 0);
  1633. default:
  1634. return (edge.WindCnt2 >= 0);
  1635. }
  1636. break;
  1637. case ctDifference:
  1638. if (edge.PolyTyp == ptSubject)
  1639. switch(pft2)
  1640. {
  1641. case pftEvenOdd:
  1642. case pftNonZero:
  1643. return (edge.WindCnt2 == 0);
  1644. case pftPositive:
  1645. return (edge.WindCnt2 <= 0);
  1646. default:
  1647. return (edge.WindCnt2 >= 0);
  1648. }
  1649. else
  1650. switch(pft2)
  1651. {
  1652. case pftEvenOdd:
  1653. case pftNonZero:
  1654. return (edge.WindCnt2 != 0);
  1655. case pftPositive:
  1656. return (edge.WindCnt2 > 0);
  1657. default:
  1658. return (edge.WindCnt2 < 0);
  1659. }
  1660. break;
  1661. case ctXor:
  1662. if (edge.WindDelta == 0) //XOr always contributing unless open
  1663. switch(pft2)
  1664. {
  1665. case pftEvenOdd:
  1666. case pftNonZero:
  1667. return (edge.WindCnt2 == 0);
  1668. case pftPositive:
  1669. return (edge.WindCnt2 <= 0);
  1670. default:
  1671. return (edge.WindCnt2 >= 0);
  1672. }
  1673. else
  1674. return true;
  1675. break;
  1676. default:
  1677. return true;
  1678. }
  1679. }
  1680. //------------------------------------------------------------------------------
  1681. OutPt* Clipper::AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)
  1682. {
  1683. OutPt* result;
  1684. TEdge *e, *prevE;
  1685. if (IsHorizontal(*e2) || ( e1->Dx > e2->Dx ))
  1686. {
  1687. result = AddOutPt(e1, Pt);
  1688. e2->OutIdx = e1->OutIdx;
  1689. e1->Side = esLeft;
  1690. e2->Side = esRight;
  1691. e = e1;
  1692. if (e->PrevInAEL == e2)
  1693. prevE = e2->PrevInAEL;
  1694. else
  1695. prevE = e->PrevInAEL;
  1696. } else
  1697. {
  1698. result = AddOutPt(e2, Pt);
  1699. e1->OutIdx = e2->OutIdx;
  1700. e1->Side = esRight;
  1701. e2->Side = esLeft;
  1702. e = e2;
  1703. if (e->PrevInAEL == e1)
  1704. prevE = e1->PrevInAEL;
  1705. else
  1706. prevE = e->PrevInAEL;
  1707. }
  1708. if (prevE && prevE->OutIdx >= 0 && prevE->Top.Y < Pt.Y && e->Top.Y < Pt.Y)
  1709. {
  1710. cInt xPrev = TopX(*prevE, Pt.Y);
  1711. cInt xE = TopX(*e, Pt.Y);
  1712. if (xPrev == xE && (e->WindDelta != 0) && (prevE->WindDelta != 0) &&
  1713. SlopesEqual(IntPoint(xPrev, Pt.Y), prevE->Top, IntPoint(xE, Pt.Y), e->Top, m_UseFullRange))
  1714. {
  1715. OutPt* outPt = AddOutPt(prevE, Pt);
  1716. AddJoin(result, outPt, e->Top);
  1717. }
  1718. }
  1719. return result;
  1720. }
  1721. //------------------------------------------------------------------------------
  1722. void Clipper::AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)
  1723. {
  1724. AddOutPt( e1, Pt );
  1725. if (e2->WindDelta == 0) AddOutPt(e2, Pt);
  1726. if( e1->OutIdx == e2->OutIdx )
  1727. {
  1728. e1->OutIdx = Unassigned;
  1729. e2->OutIdx = Unassigned;
  1730. }
  1731. else if (e1->OutIdx < e2->OutIdx)
  1732. AppendPolygon(e1, e2);
  1733. else
  1734. AppendPolygon(e2, e1);
  1735. }
  1736. //------------------------------------------------------------------------------
  1737. void Clipper::AddEdgeToSEL(TEdge *edge)
  1738. {
  1739. //SEL pointers in PEdge are reused to build a list of horizontal edges.
  1740. //However, we don't need to worry about order with horizontal edge processing.
  1741. if( !m_SortedEdges )
  1742. {
  1743. m_SortedEdges = edge;
  1744. edge->PrevInSEL = 0;
  1745. edge->NextInSEL = 0;
  1746. }
  1747. else
  1748. {
  1749. edge->NextInSEL = m_SortedEdges;
  1750. edge->PrevInSEL = 0;
  1751. m_SortedEdges->PrevInSEL = edge;
  1752. m_SortedEdges = edge;
  1753. }
  1754. }
  1755. //------------------------------------------------------------------------------
  1756. bool Clipper::PopEdgeFromSEL(TEdge *&edge)
  1757. {
  1758. if (!m_SortedEdges) return false;
  1759. edge = m_SortedEdges;
  1760. DeleteFromSEL(m_SortedEdges);
  1761. return true;
  1762. }
  1763. //------------------------------------------------------------------------------
  1764. void Clipper::CopyAELToSEL()
  1765. {
  1766. TEdge* e = m_ActiveEdges;
  1767. m_SortedEdges = e;
  1768. while ( e )
  1769. {
  1770. e->PrevInSEL = e->PrevInAEL;
  1771. e->NextInSEL = e->NextInAEL;
  1772. e = e->NextInAEL;
  1773. }
  1774. }
  1775. //------------------------------------------------------------------------------
  1776. void Clipper::AddJoin(OutPt *op1, OutPt *op2, const IntPoint OffPt)
  1777. {
  1778. Join* j = new Join;
  1779. j->OutPt1 = op1;
  1780. j->OutPt2 = op2;
  1781. j->OffPt = OffPt;
  1782. m_Joins.push_back(j);
  1783. }
  1784. //------------------------------------------------------------------------------
  1785. void Clipper::ClearJoins()
  1786. {
  1787. for (JoinList::size_type i = 0; i < m_Joins.size(); i++)
  1788. delete m_Joins[i];
  1789. m_Joins.resize(0);
  1790. }
  1791. //------------------------------------------------------------------------------
  1792. void Clipper::ClearGhostJoins()
  1793. {
  1794. for (JoinList::size_type i = 0; i < m_GhostJoins.size(); i++)
  1795. delete m_GhostJoins[i];
  1796. m_GhostJoins.resize(0);
  1797. }
  1798. //------------------------------------------------------------------------------
  1799. void Clipper::AddGhostJoin(OutPt *op, const IntPoint OffPt)
  1800. {
  1801. Join* j = new Join;
  1802. j->OutPt1 = op;
  1803. j->OutPt2 = 0;
  1804. j->OffPt = OffPt;
  1805. m_GhostJoins.push_back(j);
  1806. }
  1807. //------------------------------------------------------------------------------
  1808. void Clipper::InsertLocalMinimaIntoAEL(const cInt botY)
  1809. {
  1810. const LocalMinimum *lm;
  1811. while (PopLocalMinima(botY, lm))
  1812. {
  1813. TEdge* lb = lm->LeftBound;
  1814. TEdge* rb = lm->RightBound;
  1815. OutPt *Op1 = 0;
  1816. if (!lb)
  1817. {
  1818. //nb: don't insert LB into either AEL or SEL
  1819. InsertEdgeIntoAEL(rb, 0);
  1820. SetWindingCount(*rb);
  1821. if (IsContributing(*rb))
  1822. Op1 = AddOutPt(rb, rb->Bot);
  1823. }
  1824. else if (!rb)
  1825. {
  1826. InsertEdgeIntoAEL(lb, 0);
  1827. SetWindingCount(*lb);
  1828. if (IsContributing(*lb))
  1829. Op1 = AddOutPt(lb, lb->Bot);
  1830. InsertScanbeam(lb->Top.Y);
  1831. }
  1832. else
  1833. {
  1834. InsertEdgeIntoAEL(lb, 0);
  1835. InsertEdgeIntoAEL(rb, lb);
  1836. SetWindingCount( *lb );
  1837. rb->WindCnt = lb->WindCnt;
  1838. rb->WindCnt2 = lb->WindCnt2;
  1839. if (IsContributing(*lb))
  1840. Op1 = AddLocalMinPoly(lb, rb, lb->Bot);
  1841. InsertScanbeam(lb->Top.Y);
  1842. }
  1843. if (rb)
  1844. {
  1845. if (IsHorizontal(*rb))
  1846. {
  1847. AddEdgeToSEL(rb);
  1848. if (rb->NextInLML)
  1849. InsertScanbeam(rb->NextInLML->Top.Y);
  1850. }
  1851. else InsertScanbeam( rb->Top.Y );
  1852. }
  1853. if (!lb || !rb) continue;
  1854. //if any output polygons share an edge, they'll need joining later ...
  1855. if (Op1 && IsHorizontal(*rb) &&
  1856. m_GhostJoins.size() > 0 && (rb->WindDelta != 0))
  1857. {
  1858. for (JoinList::size_type i = 0; i < m_GhostJoins.size(); ++i)
  1859. {
  1860. Join* jr = m_GhostJoins[i];
  1861. //if the horizontal Rb and a 'ghost' horizontal overlap, then convert
  1862. //the 'ghost' join to a real join ready for later ...
  1863. if (HorzSegmentsOverlap(jr->OutPt1->Pt.X, jr->OffPt.X, rb->Bot.X, rb->Top.X))
  1864. AddJoin(jr->OutPt1, Op1, jr->OffPt);
  1865. }
  1866. }
  1867. if (lb->OutIdx >= 0 && lb->PrevInAEL &&
  1868. lb->PrevInAEL->Curr.X == lb->Bot.X &&
  1869. lb->PrevInAEL->OutIdx >= 0 &&
  1870. SlopesEqual(lb->PrevInAEL->Bot, lb->PrevInAEL->Top, lb->Curr, lb->Top, m_UseFullRange) &&
  1871. (lb->WindDelta != 0) && (lb->PrevInAEL->WindDelta != 0))
  1872. {
  1873. OutPt *Op2 = AddOutPt(lb->PrevInAEL, lb->Bot);
  1874. AddJoin(Op1, Op2, lb->Top);
  1875. }
  1876. if(lb->NextInAEL != rb)
  1877. {
  1878. if (rb->OutIdx >= 0 && rb->PrevInAEL->OutIdx >= 0 &&
  1879. SlopesEqual(rb->PrevInAEL->Curr, rb->PrevInAEL->Top, rb->Curr, rb->Top, m_UseFullRange) &&
  1880. (rb->WindDelta != 0) && (rb->PrevInAEL->WindDelta != 0))
  1881. {
  1882. OutPt *Op2 = AddOutPt(rb->PrevInAEL, rb->Bot);
  1883. AddJoin(Op1, Op2, rb->Top);
  1884. }
  1885. TEdge* e = lb->NextInAEL;
  1886. if (e)
  1887. {
  1888. while( e != rb )
  1889. {
  1890. //nb: For calculating winding counts etc, IntersectEdges() assumes
  1891. //that param1 will be to the Right of param2 ABOVE the intersection ...
  1892. IntersectEdges(rb , e , lb->Curr); //order important here
  1893. e = e->NextInAEL;
  1894. }
  1895. }
  1896. }
  1897. }
  1898. }
  1899. //------------------------------------------------------------------------------
  1900. void Clipper::DeleteFromSEL(TEdge *e)
  1901. {
  1902. TEdge* SelPrev = e->PrevInSEL;
  1903. TEdge* SelNext = e->NextInSEL;
  1904. if( !SelPrev && !SelNext && (e != m_SortedEdges) ) return; //already deleted
  1905. if( SelPrev ) SelPrev->NextInSEL = SelNext;
  1906. else m_SortedEdges = SelNext;
  1907. if( SelNext ) SelNext->PrevInSEL = SelPrev;
  1908. e->NextInSEL = 0;
  1909. e->PrevInSEL = 0;
  1910. }
  1911. //------------------------------------------------------------------------------
  1912. #ifdef use_xyz
  1913. void Clipper::SetZ(IntPoint& pt, TEdge& e1, TEdge& e2)
  1914. {
  1915. if (pt.Z != 0 || !m_ZFill) return;
  1916. else if (pt == e1.Bot) pt.Z = e1.Bot.Z;
  1917. else if (pt == e1.Top) pt.Z = e1.Top.Z;
  1918. else if (pt == e2.Bot) pt.Z = e2.Bot.Z;
  1919. else if (pt == e2.Top) pt.Z = e2.Top.Z;
  1920. else (*m_ZFill)(e1.Bot, e1.Top, e2.Bot, e2.Top, pt);
  1921. }
  1922. //------------------------------------------------------------------------------
  1923. #endif
  1924. void Clipper::IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &Pt)
  1925. {
  1926. bool e1Contributing = ( e1->OutIdx >= 0 );
  1927. bool e2Contributing = ( e2->OutIdx >= 0 );
  1928. #ifdef use_xyz
  1929. SetZ(Pt, *e1, *e2);
  1930. #endif
  1931. #ifdef use_lines
  1932. //if either edge is on an OPEN path ...
  1933. if (e1->WindDelta == 0 || e2->WindDelta == 0)
  1934. {
  1935. //ignore subject-subject open path intersections UNLESS they
  1936. //are both open paths, AND they are both 'contributing maximas' ...
  1937. if (e1->WindDelta == 0 && e2->WindDelta == 0) return;
  1938. //if intersecting a subj line with a subj poly ...
  1939. else if (e1->PolyTyp == e2->PolyTyp &&
  1940. e1->WindDelta != e2->WindDelta && m_ClipType == ctUnion)
  1941. {
  1942. if (e1->WindDelta == 0)
  1943. {
  1944. if (e2Contributing)
  1945. {
  1946. AddOutPt(e1, Pt);
  1947. if (e1Contributing) e1->OutIdx = Unassigned;
  1948. }
  1949. }
  1950. else
  1951. {
  1952. if (e1Contributing)
  1953. {
  1954. AddOutPt(e2, Pt);
  1955. if (e2Contributing) e2->OutIdx = Unassigned;
  1956. }
  1957. }
  1958. }
  1959. else if (e1->PolyTyp != e2->PolyTyp)
  1960. {
  1961. //toggle subj open path OutIdx on/off when Abs(clip.WndCnt) == 1 ...
  1962. if ((e1->WindDelta == 0) && abs(e2->WindCnt) == 1 &&
  1963. (m_ClipType != ctUnion || e2->WindCnt2 == 0))
  1964. {
  1965. AddOutPt(e1, Pt);
  1966. if (e1Contributing) e1->OutIdx = Unassigned;
  1967. }
  1968. else if ((e2->WindDelta == 0) && (abs(e1->WindCnt) == 1) &&
  1969. (m_ClipType != ctUnion || e1->WindCnt2 == 0))
  1970. {
  1971. AddOutPt(e2, Pt);
  1972. if (e2Contributing) e2->OutIdx = Unassigned;
  1973. }
  1974. }
  1975. return;
  1976. }
  1977. #endif
  1978. //update winding counts...
  1979. //assumes that e1 will be to the Right of e2 ABOVE the intersection
  1980. if ( e1->PolyTyp == e2->PolyTyp )
  1981. {
  1982. if ( IsEvenOddFillType( *e1) )
  1983. {
  1984. int oldE1WindCnt = e1->WindCnt;
  1985. e1->WindCnt = e2->WindCnt;
  1986. e2->WindCnt = oldE1WindCnt;
  1987. } else
  1988. {
  1989. if (e1->WindCnt + e2->WindDelta == 0 ) e1->WindCnt = -e1->WindCnt;
  1990. else e1->WindCnt += e2->WindDelta;
  1991. if ( e2->WindCnt - e1->WindDelta == 0 ) e2->WindCnt = -e2->WindCnt;
  1992. else e2->WindCnt -= e1->WindDelta;
  1993. }
  1994. } else
  1995. {
  1996. if (!IsEvenOddFillType(*e2)) e1->WindCnt2 += e2->WindDelta;
  1997. else e1->WindCnt2 = ( e1->WindCnt2 == 0 ) ? 1 : 0;
  1998. if (!IsEvenOddFillType(*e1)) e2->WindCnt2 -= e1->WindDelta;
  1999. else e2->WindCnt2 = ( e2->WindCnt2 == 0 ) ? 1 : 0;
  2000. }
  2001. PolyFillType e1FillType, e2FillType, e1FillType2, e2FillType2;
  2002. if (e1->PolyTyp == ptSubject)
  2003. {
  2004. e1FillType = m_SubjFillType;
  2005. e1FillType2 = m_ClipFillType;
  2006. } else
  2007. {
  2008. e1FillType = m_ClipFillType;
  2009. e1FillType2 = m_SubjFillType;
  2010. }
  2011. if (e2->PolyTyp == ptSubject)
  2012. {
  2013. e2FillType = m_SubjFillType;
  2014. e2FillType2 = m_ClipFillType;
  2015. } else
  2016. {
  2017. e2FillType = m_ClipFillType;
  2018. e2FillType2 = m_SubjFillType;
  2019. }
  2020. cInt e1Wc, e2Wc;
  2021. switch (e1FillType)
  2022. {
  2023. case pftPositive: e1Wc = e1->WindCnt; break;
  2024. case pftNegative: e1Wc = -e1->WindCnt; break;
  2025. default: e1Wc = Abs(e1->WindCnt);
  2026. }
  2027. switch(e2FillType)
  2028. {
  2029. case pftPositive: e2Wc = e2->WindCnt; break;
  2030. case pftNegative: e2Wc = -e2->WindCnt; break;
  2031. default: e2Wc = Abs(e2->WindCnt);
  2032. }
  2033. if ( e1Contributing && e2Contributing )
  2034. {
  2035. if ((e1Wc != 0 && e1Wc != 1) || (e2Wc != 0 && e2Wc != 1) ||
  2036. (e1->PolyTyp != e2->PolyTyp && m_ClipType != ctXor) )
  2037. {
  2038. AddLocalMaxPoly(e1, e2, Pt);
  2039. }
  2040. else
  2041. {
  2042. AddOutPt(e1, Pt);
  2043. AddOutPt(e2, Pt);
  2044. SwapSides( *e1 , *e2 );
  2045. SwapPolyIndexes( *e1 , *e2 );
  2046. }
  2047. }
  2048. else if ( e1Contributing )
  2049. {
  2050. if (e2Wc == 0 || e2Wc == 1)
  2051. {
  2052. AddOutPt(e1, Pt);
  2053. SwapSides(*e1, *e2);
  2054. SwapPolyIndexes(*e1, *e2);
  2055. }
  2056. }
  2057. else if ( e2Contributing )
  2058. {
  2059. if (e1Wc == 0 || e1Wc == 1)
  2060. {
  2061. AddOutPt(e2, Pt);
  2062. SwapSides(*e1, *e2);
  2063. SwapPolyIndexes(*e1, *e2);
  2064. }
  2065. }
  2066. else if ( (e1Wc == 0 || e1Wc == 1) && (e2Wc == 0 || e2Wc == 1))
  2067. {
  2068. //neither edge is currently contributing ...
  2069. cInt e1Wc2, e2Wc2;
  2070. switch (e1FillType2)
  2071. {
  2072. case pftPositive: e1Wc2 = e1->WindCnt2; break;
  2073. case pftNegative : e1Wc2 = -e1->WindCnt2; break;
  2074. default: e1Wc2 = Abs(e1->WindCnt2);
  2075. }
  2076. switch (e2FillType2)
  2077. {
  2078. case pftPositive: e2Wc2 = e2->WindCnt2; break;
  2079. case pftNegative: e2Wc2 = -e2->WindCnt2; break;
  2080. default: e2Wc2 = Abs(e2->WindCnt2);
  2081. }
  2082. if (e1->PolyTyp != e2->PolyTyp)
  2083. {
  2084. AddLocalMinPoly(e1, e2, Pt);
  2085. }
  2086. else if (e1Wc == 1 && e2Wc == 1)
  2087. switch( m_ClipType ) {
  2088. case ctIntersection:
  2089. if (e1Wc2 > 0 && e2Wc2 > 0)
  2090. AddLocalMinPoly(e1, e2, Pt);
  2091. break;
  2092. case ctUnion:
  2093. if ( e1Wc2 <= 0 && e2Wc2 <= 0 )
  2094. AddLocalMinPoly(e1, e2, Pt);
  2095. break;
  2096. case ctDifference:
  2097. if (((e1->PolyTyp == ptClip) && (e1Wc2 > 0) && (e2Wc2 > 0)) ||
  2098. ((e1->PolyTyp == ptSubject) && (e1Wc2 <= 0) && (e2Wc2 <= 0)))
  2099. AddLocalMinPoly(e1, e2, Pt);
  2100. break;
  2101. case ctXor:
  2102. AddLocalMinPoly(e1, e2, Pt);
  2103. }
  2104. else
  2105. SwapSides( *e1, *e2 );
  2106. }
  2107. }
  2108. //------------------------------------------------------------------------------
  2109. void Clipper::SetHoleState(TEdge *e, OutRec *outrec)
  2110. {
  2111. TEdge *e2 = e->PrevInAEL;
  2112. TEdge *eTmp = 0;
  2113. while (e2)
  2114. {
  2115. if (e2->OutIdx >= 0 && e2->WindDelta != 0)
  2116. {
  2117. if (!eTmp) eTmp = e2;
  2118. else if (eTmp->OutIdx == e2->OutIdx) eTmp = 0;
  2119. }
  2120. e2 = e2->PrevInAEL;
  2121. }
  2122. if (!eTmp)
  2123. {
  2124. outrec->FirstLeft = 0;
  2125. outrec->IsHole = false;
  2126. }
  2127. else
  2128. {
  2129. outrec->FirstLeft = m_PolyOuts[eTmp->OutIdx];
  2130. outrec->IsHole = !outrec->FirstLeft->IsHole;
  2131. }
  2132. }
  2133. //------------------------------------------------------------------------------
  2134. OutRec* GetLowermostRec(OutRec *outRec1, OutRec *outRec2)
  2135. {
  2136. //work out which polygon fragment has the correct hole state ...
  2137. if (!outRec1->BottomPt)
  2138. outRec1->BottomPt = GetBottomPt(outRec1->Pts);
  2139. if (!outRec2->BottomPt)
  2140. outRec2->BottomPt = GetBottomPt(outRec2->Pts);
  2141. OutPt *OutPt1 = outRec1->BottomPt;
  2142. OutPt *OutPt2 = outRec2->BottomPt;
  2143. if (OutPt1->Pt.Y > OutPt2->Pt.Y) return outRec1;
  2144. else if (OutPt1->Pt.Y < OutPt2->Pt.Y) return outRec2;
  2145. else if (OutPt1->Pt.X < OutPt2->Pt.X) return outRec1;
  2146. else if (OutPt1->Pt.X > OutPt2->Pt.X) return outRec2;
  2147. else if (OutPt1->Next == OutPt1) return outRec2;
  2148. else if (OutPt2->Next == OutPt2) return outRec1;
  2149. else if (FirstIsBottomPt(OutPt1, OutPt2)) return outRec1;
  2150. else return outRec2;
  2151. }
  2152. //------------------------------------------------------------------------------
  2153. bool OutRec1RightOfOutRec2(OutRec* outRec1, OutRec* outRec2)
  2154. {
  2155. do
  2156. {
  2157. outRec1 = outRec1->FirstLeft;
  2158. if (outRec1 == outRec2) return true;
  2159. } while (outRec1);
  2160. return false;
  2161. }
  2162. //------------------------------------------------------------------------------
  2163. OutRec* Clipper::GetOutRec(int Idx)
  2164. {
  2165. OutRec* outrec = m_PolyOuts[Idx];
  2166. while (outrec != m_PolyOuts[outrec->Idx])
  2167. outrec = m_PolyOuts[outrec->Idx];
  2168. return outrec;
  2169. }
  2170. //------------------------------------------------------------------------------
  2171. void Clipper::AppendPolygon(TEdge *e1, TEdge *e2)
  2172. {
  2173. //get the start and ends of both output polygons ...
  2174. OutRec *outRec1 = m_PolyOuts[e1->OutIdx];
  2175. OutRec *outRec2 = m_PolyOuts[e2->OutIdx];
  2176. OutRec *holeStateRec;
  2177. if (OutRec1RightOfOutRec2(outRec1, outRec2))
  2178. holeStateRec = outRec2;
  2179. else if (OutRec1RightOfOutRec2(outRec2, outRec1))
  2180. holeStateRec = outRec1;
  2181. else
  2182. holeStateRec = GetLowermostRec(outRec1, outRec2);
  2183. //get the start and ends of both output polygons and
  2184. //join e2 poly onto e1 poly and delete pointers to e2 ...
  2185. OutPt* p1_lft = outRec1->Pts;
  2186. OutPt* p1_rt = p1_lft->Prev;
  2187. OutPt* p2_lft = outRec2->Pts;
  2188. OutPt* p2_rt = p2_lft->Prev;
  2189. //join e2 poly onto e1 poly and delete pointers to e2 ...
  2190. if( e1->Side == esLeft )
  2191. {
  2192. if( e2->Side == esLeft )
  2193. {
  2194. //z y x a b c
  2195. ReversePolyPtLinks(p2_lft);
  2196. p2_lft->Next = p1_lft;
  2197. p1_lft->Prev = p2_lft;
  2198. p1_rt->Next = p2_rt;
  2199. p2_rt->Prev = p1_rt;
  2200. outRec1->Pts = p2_rt;
  2201. } else
  2202. {
  2203. //x y z a b c
  2204. p2_rt->Next = p1_lft;
  2205. p1_lft->Prev = p2_rt;
  2206. p2_lft->Prev = p1_rt;
  2207. p1_rt->Next = p2_lft;
  2208. outRec1->Pts = p2_lft;
  2209. }
  2210. } else
  2211. {
  2212. if( e2->Side == esRight )
  2213. {
  2214. //a b c z y x
  2215. ReversePolyPtLinks(p2_lft);
  2216. p1_rt->Next = p2_rt;
  2217. p2_rt->Prev = p1_rt;
  2218. p2_lft->Next = p1_lft;
  2219. p1_lft->Prev = p2_lft;
  2220. } else
  2221. {
  2222. //a b c x y z
  2223. p1_rt->Next = p2_lft;
  2224. p2_lft->Prev = p1_rt;
  2225. p1_lft->Prev = p2_rt;
  2226. p2_rt->Next = p1_lft;
  2227. }
  2228. }
  2229. outRec1->BottomPt = 0;
  2230. if (holeStateRec == outRec2)
  2231. {
  2232. if (outRec2->FirstLeft != outRec1)
  2233. outRec1->FirstLeft = outRec2->FirstLeft;
  2234. outRec1->IsHole = outRec2->IsHole;
  2235. }
  2236. outRec2->Pts = 0;
  2237. outRec2->BottomPt = 0;
  2238. outRec2->FirstLeft = outRec1;
  2239. int OKIdx = e1->OutIdx;
  2240. int ObsoleteIdx = e2->OutIdx;
  2241. e1->OutIdx = Unassigned; //nb: safe because we only get here via AddLocalMaxPoly
  2242. e2->OutIdx = Unassigned;
  2243. TEdge* e = m_ActiveEdges;
  2244. while( e )
  2245. {
  2246. if( e->OutIdx == ObsoleteIdx )
  2247. {
  2248. e->OutIdx = OKIdx;
  2249. e->Side = e1->Side;
  2250. break;
  2251. }
  2252. e = e->NextInAEL;
  2253. }
  2254. outRec2->Idx = outRec1->Idx;
  2255. }
  2256. //------------------------------------------------------------------------------
  2257. OutPt* Clipper::AddOutPt(TEdge *e, const IntPoint &pt)
  2258. {
  2259. if( e->OutIdx < 0 )
  2260. {
  2261. OutRec *outRec = CreateOutRec();
  2262. outRec->IsOpen = (e->WindDelta == 0);
  2263. OutPt* newOp = new OutPt;
  2264. outRec->Pts = newOp;
  2265. newOp->Idx = outRec->Idx;
  2266. newOp->Pt = pt;
  2267. newOp->Next = newOp;
  2268. newOp->Prev = newOp;
  2269. if (!outRec->IsOpen)
  2270. SetHoleState(e, outRec);
  2271. e->OutIdx = outRec->Idx;
  2272. return newOp;
  2273. } else
  2274. {
  2275. OutRec *outRec = m_PolyOuts[e->OutIdx];
  2276. //OutRec.Pts is the 'Left-most' point & OutRec.Pts.Prev is the 'Right-most'
  2277. OutPt* op = outRec->Pts;
  2278. bool ToFront = (e->Side == esLeft);
  2279. if (ToFront && (pt == op->Pt)) return op;
  2280. else if (!ToFront && (pt == op->Prev->Pt)) return op->Prev;
  2281. OutPt* newOp = new OutPt;
  2282. newOp->Idx = outRec->Idx;
  2283. newOp->Pt = pt;
  2284. newOp->Next = op;
  2285. newOp->Prev = op->Prev;
  2286. newOp->Prev->Next = newOp;
  2287. op->Prev = newOp;
  2288. if (ToFront) outRec->Pts = newOp;
  2289. return newOp;
  2290. }
  2291. }
  2292. //------------------------------------------------------------------------------
  2293. OutPt* Clipper::GetLastOutPt(TEdge *e)
  2294. {
  2295. OutRec *outRec = m_PolyOuts[e->OutIdx];
  2296. if (e->Side == esLeft)
  2297. return outRec->Pts;
  2298. else
  2299. return outRec->Pts->Prev;
  2300. }
  2301. //------------------------------------------------------------------------------
  2302. void Clipper::ProcessHorizontals()
  2303. {
  2304. TEdge* horzEdge;
  2305. while (PopEdgeFromSEL(horzEdge))
  2306. ProcessHorizontal(horzEdge);
  2307. }
  2308. //------------------------------------------------------------------------------
  2309. inline bool IsMinima(TEdge *e)
  2310. {
  2311. return e && (e->Prev->NextInLML != e) && (e->Next->NextInLML != e);
  2312. }
  2313. //------------------------------------------------------------------------------
  2314. inline bool IsMaxima(TEdge *e, const cInt Y)
  2315. {
  2316. return e && e->Top.Y == Y && !e->NextInLML;
  2317. }
  2318. //------------------------------------------------------------------------------
  2319. inline bool IsIntermediate(TEdge *e, const cInt Y)
  2320. {
  2321. return e->Top.Y == Y && e->NextInLML;
  2322. }
  2323. //------------------------------------------------------------------------------
  2324. TEdge *GetMaximaPair(TEdge *e)
  2325. {
  2326. if ((e->Next->Top == e->Top) && !e->Next->NextInLML)
  2327. return e->Next;
  2328. else if ((e->Prev->Top == e->Top) && !e->Prev->NextInLML)
  2329. return e->Prev;
  2330. else return 0;
  2331. }
  2332. //------------------------------------------------------------------------------
  2333. TEdge *GetMaximaPairEx(TEdge *e)
  2334. {
  2335. //as GetMaximaPair() but returns 0 if MaxPair isn't in AEL (unless it's horizontal)
  2336. TEdge* result = GetMaximaPair(e);
  2337. if (result && (result->OutIdx == Skip ||
  2338. (result->NextInAEL == result->PrevInAEL && !IsHorizontal(*result)))) return 0;
  2339. return result;
  2340. }
  2341. //------------------------------------------------------------------------------
  2342. void Clipper::SwapPositionsInSEL(TEdge *Edge1, TEdge *Edge2)
  2343. {
  2344. if( !( Edge1->NextInSEL ) && !( Edge1->PrevInSEL ) ) return;
  2345. if( !( Edge2->NextInSEL ) && !( Edge2->PrevInSEL ) ) return;
  2346. if( Edge1->NextInSEL == Edge2 )
  2347. {
  2348. TEdge* Next = Edge2->NextInSEL;
  2349. if( Next ) Next->PrevInSEL = Edge1;
  2350. TEdge* Prev = Edge1->PrevInSEL;
  2351. if( Prev ) Prev->NextInSEL = Edge2;
  2352. Edge2->PrevInSEL = Prev;
  2353. Edge2->NextInSEL = Edge1;
  2354. Edge1->PrevInSEL = Edge2;
  2355. Edge1->NextInSEL = Next;
  2356. }
  2357. else if( Edge2->NextInSEL == Edge1 )
  2358. {
  2359. TEdge* Next = Edge1->NextInSEL;
  2360. if( Next ) Next->PrevInSEL = Edge2;
  2361. TEdge* Prev = Edge2->PrevInSEL;
  2362. if( Prev ) Prev->NextInSEL = Edge1;
  2363. Edge1->PrevInSEL = Prev;
  2364. Edge1->NextInSEL = Edge2;
  2365. Edge2->PrevInSEL = Edge1;
  2366. Edge2->NextInSEL = Next;
  2367. }
  2368. else
  2369. {
  2370. TEdge* Next = Edge1->NextInSEL;
  2371. TEdge* Prev = Edge1->PrevInSEL;
  2372. Edge1->NextInSEL = Edge2->NextInSEL;
  2373. if( Edge1->NextInSEL ) Edge1->NextInSEL->PrevInSEL = Edge1;
  2374. Edge1->PrevInSEL = Edge2->PrevInSEL;
  2375. if( Edge1->PrevInSEL ) Edge1->PrevInSEL->NextInSEL = Edge1;
  2376. Edge2->NextInSEL = Next;
  2377. if( Edge2->NextInSEL ) Edge2->NextInSEL->PrevInSEL = Edge2;
  2378. Edge2->PrevInSEL = Prev;
  2379. if( Edge2->PrevInSEL ) Edge2->PrevInSEL->NextInSEL = Edge2;
  2380. }
  2381. if( !Edge1->PrevInSEL ) m_SortedEdges = Edge1;
  2382. else if( !Edge2->PrevInSEL ) m_SortedEdges = Edge2;
  2383. }
  2384. //------------------------------------------------------------------------------
  2385. TEdge* GetNextInAEL(TEdge *e, Direction dir)
  2386. {
  2387. return dir == dLeftToRight ? e->NextInAEL : e->PrevInAEL;
  2388. }
  2389. //------------------------------------------------------------------------------
  2390. void GetHorzDirection(TEdge& HorzEdge, Direction& Dir, cInt& Left, cInt& Right)
  2391. {
  2392. if (HorzEdge.Bot.X < HorzEdge.Top.X)
  2393. {
  2394. Left = HorzEdge.Bot.X;
  2395. Right = HorzEdge.Top.X;
  2396. Dir = dLeftToRight;
  2397. } else
  2398. {
  2399. Left = HorzEdge.Top.X;
  2400. Right = HorzEdge.Bot.X;
  2401. Dir = dRightToLeft;
  2402. }
  2403. }
  2404. //------------------------------------------------------------------------
  2405. /*******************************************************************************
  2406. * Notes: Horizontal edges (HEs) at scanline intersections (ie at the Top or *
  2407. * Bottom of a scanbeam) are processed as if layered. The order in which HEs *
  2408. * are processed doesn't matter. HEs intersect with other HE Bot.Xs only [#] *
  2409. * (or they could intersect with Top.Xs only, ie EITHER Bot.Xs OR Top.Xs), *
  2410. * and with other non-horizontal edges [*]. Once these intersections are *
  2411. * processed, intermediate HEs then 'promote' the Edge above (NextInLML) into *
  2412. * the AEL. These 'promoted' edges may in turn intersect [%] with other HEs. *
  2413. *******************************************************************************/
  2414. void Clipper::ProcessHorizontal(TEdge *horzEdge)
  2415. {
  2416. Direction dir;
  2417. cInt horzLeft, horzRight;
  2418. bool IsOpen = (horzEdge->WindDelta == 0);
  2419. GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);
  2420. TEdge* eLastHorz = horzEdge, *eMaxPair = 0;
  2421. while (eLastHorz->NextInLML && IsHorizontal(*eLastHorz->NextInLML))
  2422. eLastHorz = eLastHorz->NextInLML;
  2423. if (!eLastHorz->NextInLML)
  2424. eMaxPair = GetMaximaPair(eLastHorz);
  2425. MaximaList::const_iterator maxIt;
  2426. MaximaList::const_reverse_iterator maxRit;
  2427. if (m_Maxima.size() > 0)
  2428. {
  2429. //get the first maxima in range (X) ...
  2430. if (dir == dLeftToRight)
  2431. {
  2432. maxIt = m_Maxima.begin();
  2433. while (maxIt != m_Maxima.end() && *maxIt <= horzEdge->Bot.X) maxIt++;
  2434. if (maxIt != m_Maxima.end() && *maxIt >= eLastHorz->Top.X)
  2435. maxIt = m_Maxima.end();
  2436. }
  2437. else
  2438. {
  2439. maxRit = m_Maxima.rbegin();
  2440. while (maxRit != m_Maxima.rend() && *maxRit > horzEdge->Bot.X) maxRit++;
  2441. if (maxRit != m_Maxima.rend() && *maxRit <= eLastHorz->Top.X)
  2442. maxRit = m_Maxima.rend();
  2443. }
  2444. }
  2445. OutPt* op1 = 0;
  2446. for (;;) //loop through consec. horizontal edges
  2447. {
  2448. bool IsLastHorz = (horzEdge == eLastHorz);
  2449. TEdge* e = GetNextInAEL(horzEdge, dir);
  2450. while(e)
  2451. {
  2452. //this code block inserts extra coords into horizontal edges (in output
  2453. //polygons) whereever maxima touch these horizontal edges. This helps
  2454. //'simplifying' polygons (ie if the Simplify property is set).
  2455. if (m_Maxima.size() > 0)
  2456. {
  2457. if (dir == dLeftToRight)
  2458. {
  2459. while (maxIt != m_Maxima.end() && *maxIt < e->Curr.X)
  2460. {
  2461. if (horzEdge->OutIdx >= 0 && !IsOpen)
  2462. AddOutPt(horzEdge, IntPoint(*maxIt, horzEdge->Bot.Y));
  2463. maxIt++;
  2464. }
  2465. }
  2466. else
  2467. {
  2468. while (maxRit != m_Maxima.rend() && *maxRit > e->Curr.X)
  2469. {
  2470. if (horzEdge->OutIdx >= 0 && !IsOpen)
  2471. AddOutPt(horzEdge, IntPoint(*maxRit, horzEdge->Bot.Y));
  2472. maxRit++;
  2473. }
  2474. }
  2475. };
  2476. if ((dir == dLeftToRight && e->Curr.X > horzRight) ||
  2477. (dir == dRightToLeft && e->Curr.X < horzLeft)) break;
  2478. //Also break if we've got to the end of an intermediate horizontal edge ...
  2479. //nb: Smaller Dx's are to the right of larger Dx's ABOVE the horizontal.
  2480. if (e->Curr.X == horzEdge->Top.X && horzEdge->NextInLML &&
  2481. e->Dx < horzEdge->NextInLML->Dx) break;
  2482. if (horzEdge->OutIdx >= 0 && !IsOpen) //note: may be done multiple times
  2483. {
  2484. #ifdef use_xyz
  2485. if (dir == dLeftToRight) SetZ(e->Curr, *horzEdge, *e);
  2486. else SetZ(e->Curr, *e, *horzEdge);
  2487. #endif
  2488. op1 = AddOutPt(horzEdge, e->Curr);
  2489. TEdge* eNextHorz = m_SortedEdges;
  2490. while (eNextHorz)
  2491. {
  2492. if (eNextHorz->OutIdx >= 0 &&
  2493. HorzSegmentsOverlap(horzEdge->Bot.X,
  2494. horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))
  2495. {
  2496. OutPt* op2 = GetLastOutPt(eNextHorz);
  2497. AddJoin(op2, op1, eNextHorz->Top);
  2498. }
  2499. eNextHorz = eNextHorz->NextInSEL;
  2500. }
  2501. AddGhostJoin(op1, horzEdge->Bot);
  2502. }
  2503. //OK, so far we're still in range of the horizontal Edge but make sure
  2504. //we're at the last of consec. horizontals when matching with eMaxPair
  2505. if(e == eMaxPair && IsLastHorz)
  2506. {
  2507. if (horzEdge->OutIdx >= 0)
  2508. AddLocalMaxPoly(horzEdge, eMaxPair, horzEdge->Top);
  2509. DeleteFromAEL(horzEdge);
  2510. DeleteFromAEL(eMaxPair);
  2511. return;
  2512. }
  2513. if(dir == dLeftToRight)
  2514. {
  2515. IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);
  2516. IntersectEdges(horzEdge, e, Pt);
  2517. }
  2518. else
  2519. {
  2520. IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);
  2521. IntersectEdges( e, horzEdge, Pt);
  2522. }
  2523. TEdge* eNext = GetNextInAEL(e, dir);
  2524. SwapPositionsInAEL( horzEdge, e );
  2525. e = eNext;
  2526. } //end while(e)
  2527. //Break out of loop if HorzEdge.NextInLML is not also horizontal ...
  2528. if (!horzEdge->NextInLML || !IsHorizontal(*horzEdge->NextInLML)) break;
  2529. UpdateEdgeIntoAEL(horzEdge);
  2530. if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Bot);
  2531. GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);
  2532. } //end for (;;)
  2533. if (horzEdge->OutIdx >= 0 && !op1)
  2534. {
  2535. op1 = GetLastOutPt(horzEdge);
  2536. TEdge* eNextHorz = m_SortedEdges;
  2537. while (eNextHorz)
  2538. {
  2539. if (eNextHorz->OutIdx >= 0 &&
  2540. HorzSegmentsOverlap(horzEdge->Bot.X,
  2541. horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))
  2542. {
  2543. OutPt* op2 = GetLastOutPt(eNextHorz);
  2544. AddJoin(op2, op1, eNextHorz->Top);
  2545. }
  2546. eNextHorz = eNextHorz->NextInSEL;
  2547. }
  2548. AddGhostJoin(op1, horzEdge->Top);
  2549. }
  2550. if (horzEdge->NextInLML)
  2551. {
  2552. if(horzEdge->OutIdx >= 0)
  2553. {
  2554. op1 = AddOutPt( horzEdge, horzEdge->Top);
  2555. UpdateEdgeIntoAEL(horzEdge);
  2556. if (horzEdge->WindDelta == 0) return;
  2557. //nb: HorzEdge is no longer horizontal here
  2558. TEdge* ePrev = horzEdge->PrevInAEL;
  2559. TEdge* eNext = horzEdge->NextInAEL;
  2560. if (ePrev && ePrev->Curr.X == horzEdge->Bot.X &&
  2561. ePrev->Curr.Y == horzEdge->Bot.Y && ePrev->WindDelta != 0 &&
  2562. (ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&
  2563. SlopesEqual(*horzEdge, *ePrev, m_UseFullRange)))
  2564. {
  2565. OutPt* op2 = AddOutPt(ePrev, horzEdge->Bot);
  2566. AddJoin(op1, op2, horzEdge->Top);
  2567. }
  2568. else if (eNext && eNext->Curr.X == horzEdge->Bot.X &&
  2569. eNext->Curr.Y == horzEdge->Bot.Y && eNext->WindDelta != 0 &&
  2570. eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&
  2571. SlopesEqual(*horzEdge, *eNext, m_UseFullRange))
  2572. {
  2573. OutPt* op2 = AddOutPt(eNext, horzEdge->Bot);
  2574. AddJoin(op1, op2, horzEdge->Top);
  2575. }
  2576. }
  2577. else
  2578. UpdateEdgeIntoAEL(horzEdge);
  2579. }
  2580. else
  2581. {
  2582. if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Top);
  2583. DeleteFromAEL(horzEdge);
  2584. }
  2585. }
  2586. //------------------------------------------------------------------------------
  2587. bool Clipper::ProcessIntersections(const cInt topY)
  2588. {
  2589. if( !m_ActiveEdges ) return true;
  2590. try {
  2591. BuildIntersectList(topY);
  2592. size_t IlSize = m_IntersectList.size();
  2593. if (IlSize == 0) return true;
  2594. if (IlSize == 1 || FixupIntersectionOrder()) ProcessIntersectList();
  2595. else return false;
  2596. }
  2597. catch(...)
  2598. {
  2599. m_SortedEdges = 0;
  2600. DisposeIntersectNodes();
  2601. throw clipperException("ProcessIntersections error");
  2602. }
  2603. m_SortedEdges = 0;
  2604. return true;
  2605. }
  2606. //------------------------------------------------------------------------------
  2607. void Clipper::DisposeIntersectNodes()
  2608. {
  2609. for (size_t i = 0; i < m_IntersectList.size(); ++i )
  2610. delete m_IntersectList[i];
  2611. m_IntersectList.clear();
  2612. }
  2613. //------------------------------------------------------------------------------
  2614. void Clipper::BuildIntersectList(const cInt topY)
  2615. {
  2616. if ( !m_ActiveEdges ) return;
  2617. //prepare for sorting ...
  2618. TEdge* e = m_ActiveEdges;
  2619. m_SortedEdges = e;
  2620. while( e )
  2621. {
  2622. e->PrevInSEL = e->PrevInAEL;
  2623. e->NextInSEL = e->NextInAEL;
  2624. e->Curr.X = TopX( *e, topY );
  2625. e = e->NextInAEL;
  2626. }
  2627. //bubblesort ...
  2628. bool isModified;
  2629. do
  2630. {
  2631. isModified = false;
  2632. e = m_SortedEdges;
  2633. while( e->NextInSEL )
  2634. {
  2635. TEdge *eNext = e->NextInSEL;
  2636. IntPoint Pt;
  2637. if(e->Curr.X > eNext->Curr.X)
  2638. {
  2639. IntersectPoint(*e, *eNext, Pt);
  2640. if (Pt.Y < topY) Pt = IntPoint(TopX(*e, topY), topY);
  2641. IntersectNode * newNode = new IntersectNode;
  2642. newNode->Edge1 = e;
  2643. newNode->Edge2 = eNext;
  2644. newNode->Pt = Pt;
  2645. m_IntersectList.push_back(newNode);
  2646. SwapPositionsInSEL(e, eNext);
  2647. isModified = true;
  2648. }
  2649. else
  2650. e = eNext;
  2651. }
  2652. if( e->PrevInSEL ) e->PrevInSEL->NextInSEL = 0;
  2653. else break;
  2654. }
  2655. while ( isModified );
  2656. m_SortedEdges = 0; //important
  2657. }
  2658. //------------------------------------------------------------------------------
  2659. void Clipper::ProcessIntersectList()
  2660. {
  2661. for (size_t i = 0; i < m_IntersectList.size(); ++i)
  2662. {
  2663. IntersectNode* iNode = m_IntersectList[i];
  2664. {
  2665. IntersectEdges( iNode->Edge1, iNode->Edge2, iNode->Pt);
  2666. SwapPositionsInAEL( iNode->Edge1 , iNode->Edge2 );
  2667. }
  2668. delete iNode;
  2669. }
  2670. m_IntersectList.clear();
  2671. }
  2672. //------------------------------------------------------------------------------
  2673. bool IntersectListSort(IntersectNode* node1, IntersectNode* node2)
  2674. {
  2675. return node2->Pt.Y < node1->Pt.Y;
  2676. }
  2677. //------------------------------------------------------------------------------
  2678. inline bool EdgesAdjacent(const IntersectNode &inode)
  2679. {
  2680. return (inode.Edge1->NextInSEL == inode.Edge2) ||
  2681. (inode.Edge1->PrevInSEL == inode.Edge2);
  2682. }
  2683. //------------------------------------------------------------------------------
  2684. bool Clipper::FixupIntersectionOrder()
  2685. {
  2686. //pre-condition: intersections are sorted Bottom-most first.
  2687. //Now it's crucial that intersections are made only between adjacent edges,
  2688. //so to ensure this the order of intersections may need adjusting ...
  2689. CopyAELToSEL();
  2690. std::sort(m_IntersectList.begin(), m_IntersectList.end(), IntersectListSort);
  2691. size_t cnt = m_IntersectList.size();
  2692. for (size_t i = 0; i < cnt; ++i)
  2693. {
  2694. if (!EdgesAdjacent(*m_IntersectList[i]))
  2695. {
  2696. size_t j = i + 1;
  2697. while (j < cnt && !EdgesAdjacent(*m_IntersectList[j])) j++;
  2698. if (j == cnt) return false;
  2699. std::swap(m_IntersectList[i], m_IntersectList[j]);
  2700. }
  2701. SwapPositionsInSEL(m_IntersectList[i]->Edge1, m_IntersectList[i]->Edge2);
  2702. }
  2703. return true;
  2704. }
  2705. //------------------------------------------------------------------------------
  2706. void Clipper::DoMaxima(TEdge *e)
  2707. {
  2708. TEdge* eMaxPair = GetMaximaPairEx(e);
  2709. if (!eMaxPair)
  2710. {
  2711. if (e->OutIdx >= 0)
  2712. AddOutPt(e, e->Top);
  2713. DeleteFromAEL(e);
  2714. return;
  2715. }
  2716. TEdge* eNext = e->NextInAEL;
  2717. while(eNext && eNext != eMaxPair)
  2718. {
  2719. IntersectEdges(e, eNext, e->Top);
  2720. SwapPositionsInAEL(e, eNext);
  2721. eNext = e->NextInAEL;
  2722. }
  2723. if(e->OutIdx == Unassigned && eMaxPair->OutIdx == Unassigned)
  2724. {
  2725. DeleteFromAEL(e);
  2726. DeleteFromAEL(eMaxPair);
  2727. }
  2728. else if( e->OutIdx >= 0 && eMaxPair->OutIdx >= 0 )
  2729. {
  2730. if (e->OutIdx >= 0) AddLocalMaxPoly(e, eMaxPair, e->Top);
  2731. DeleteFromAEL(e);
  2732. DeleteFromAEL(eMaxPair);
  2733. }
  2734. #ifdef use_lines
  2735. else if (e->WindDelta == 0)
  2736. {
  2737. if (e->OutIdx >= 0)
  2738. {
  2739. AddOutPt(e, e->Top);
  2740. e->OutIdx = Unassigned;
  2741. }
  2742. DeleteFromAEL(e);
  2743. if (eMaxPair->OutIdx >= 0)
  2744. {
  2745. AddOutPt(eMaxPair, e->Top);
  2746. eMaxPair->OutIdx = Unassigned;
  2747. }
  2748. DeleteFromAEL(eMaxPair);
  2749. }
  2750. #endif
  2751. else throw clipperException("DoMaxima error");
  2752. }
  2753. //------------------------------------------------------------------------------
  2754. void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY)
  2755. {
  2756. TEdge* e = m_ActiveEdges;
  2757. while( e )
  2758. {
  2759. //1. process maxima, treating them as if they're 'bent' horizontal edges,
  2760. // but exclude maxima with horizontal edges. nb: e can't be a horizontal.
  2761. bool IsMaximaEdge = IsMaxima(e, topY);
  2762. if(IsMaximaEdge)
  2763. {
  2764. TEdge* eMaxPair = GetMaximaPairEx(e);
  2765. IsMaximaEdge = (!eMaxPair || !IsHorizontal(*eMaxPair));
  2766. }
  2767. if(IsMaximaEdge)
  2768. {
  2769. if (m_StrictSimple) m_Maxima.push_back(e->Top.X);
  2770. TEdge* ePrev = e->PrevInAEL;
  2771. DoMaxima(e);
  2772. if( !ePrev ) e = m_ActiveEdges;
  2773. else e = ePrev->NextInAEL;
  2774. }
  2775. else
  2776. {
  2777. //2. promote horizontal edges, otherwise update Curr.X and Curr.Y ...
  2778. if (IsIntermediate(e, topY) && IsHorizontal(*e->NextInLML))
  2779. {
  2780. UpdateEdgeIntoAEL(e);
  2781. if (e->OutIdx >= 0)
  2782. AddOutPt(e, e->Bot);
  2783. AddEdgeToSEL(e);
  2784. }
  2785. else
  2786. {
  2787. e->Curr.X = TopX( *e, topY );
  2788. e->Curr.Y = topY;
  2789. #ifdef use_xyz
  2790. e->Curr.Z = topY == e->Top.Y ? e->Top.Z : (topY == e->Bot.Y ? e->Bot.Z : 0);
  2791. #endif
  2792. }
  2793. //When StrictlySimple and 'e' is being touched by another edge, then
  2794. //make sure both edges have a vertex here ...
  2795. if (m_StrictSimple)
  2796. {
  2797. TEdge* ePrev = e->PrevInAEL;
  2798. if ((e->OutIdx >= 0) && (e->WindDelta != 0) && ePrev && (ePrev->OutIdx >= 0) &&
  2799. (ePrev->Curr.X == e->Curr.X) && (ePrev->WindDelta != 0))
  2800. {
  2801. IntPoint pt = e->Curr;
  2802. #ifdef use_xyz
  2803. SetZ(pt, *ePrev, *e);
  2804. #endif
  2805. OutPt* op = AddOutPt(ePrev, pt);
  2806. OutPt* op2 = AddOutPt(e, pt);
  2807. AddJoin(op, op2, pt); //StrictlySimple (type-3) join
  2808. }
  2809. }
  2810. e = e->NextInAEL;
  2811. }
  2812. }
  2813. //3. Process horizontals at the Top of the scanbeam ...
  2814. m_Maxima.sort();
  2815. ProcessHorizontals();
  2816. m_Maxima.clear();
  2817. //4. Promote intermediate vertices ...
  2818. e = m_ActiveEdges;
  2819. while(e)
  2820. {
  2821. if(IsIntermediate(e, topY))
  2822. {
  2823. OutPt* op = 0;
  2824. if( e->OutIdx >= 0 )
  2825. op = AddOutPt(e, e->Top);
  2826. UpdateEdgeIntoAEL(e);
  2827. //if output polygons share an edge, they'll need joining later ...
  2828. TEdge* ePrev = e->PrevInAEL;
  2829. TEdge* eNext = e->NextInAEL;
  2830. if (ePrev && ePrev->Curr.X == e->Bot.X &&
  2831. ePrev->Curr.Y == e->Bot.Y && op &&
  2832. ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&
  2833. SlopesEqual(e->Curr, e->Top, ePrev->Curr, ePrev->Top, m_UseFullRange) &&
  2834. (e->WindDelta != 0) && (ePrev->WindDelta != 0))
  2835. {
  2836. OutPt* op2 = AddOutPt(ePrev, e->Bot);
  2837. AddJoin(op, op2, e->Top);
  2838. }
  2839. else if (eNext && eNext->Curr.X == e->Bot.X &&
  2840. eNext->Curr.Y == e->Bot.Y && op &&
  2841. eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&
  2842. SlopesEqual(e->Curr, e->Top, eNext->Curr, eNext->Top, m_UseFullRange) &&
  2843. (e->WindDelta != 0) && (eNext->WindDelta != 0))
  2844. {
  2845. OutPt* op2 = AddOutPt(eNext, e->Bot);
  2846. AddJoin(op, op2, e->Top);
  2847. }
  2848. }
  2849. e = e->NextInAEL;
  2850. }
  2851. }
  2852. //------------------------------------------------------------------------------
  2853. void Clipper::FixupOutPolyline(OutRec &outrec)
  2854. {
  2855. OutPt *pp = outrec.Pts;
  2856. OutPt *lastPP = pp->Prev;
  2857. while (pp != lastPP)
  2858. {
  2859. pp = pp->Next;
  2860. if (pp->Pt == pp->Prev->Pt)
  2861. {
  2862. if (pp == lastPP) lastPP = pp->Prev;
  2863. OutPt *tmpPP = pp->Prev;
  2864. tmpPP->Next = pp->Next;
  2865. pp->Next->Prev = tmpPP;
  2866. delete pp;
  2867. pp = tmpPP;
  2868. }
  2869. }
  2870. if (pp == pp->Prev)
  2871. {
  2872. DisposeOutPts(pp);
  2873. outrec.Pts = 0;
  2874. return;
  2875. }
  2876. }
  2877. //------------------------------------------------------------------------------
  2878. void Clipper::FixupOutPolygon(OutRec &outrec)
  2879. {
  2880. //FixupOutPolygon() - removes duplicate points and simplifies consecutive
  2881. //parallel edges by removing the middle vertex.
  2882. OutPt *lastOK = 0;
  2883. outrec.BottomPt = 0;
  2884. OutPt *pp = outrec.Pts;
  2885. bool preserveCol = m_PreserveCollinear || m_StrictSimple;
  2886. for (;;)
  2887. {
  2888. if (pp->Prev == pp || pp->Prev == pp->Next)
  2889. {
  2890. DisposeOutPts(pp);
  2891. outrec.Pts = 0;
  2892. return;
  2893. }
  2894. //test for duplicate points and collinear edges ...
  2895. if ((pp->Pt == pp->Next->Pt) || (pp->Pt == pp->Prev->Pt) ||
  2896. (SlopesEqual(pp->Prev->Pt, pp->Pt, pp->Next->Pt, m_UseFullRange) &&
  2897. (!preserveCol || !Pt2IsBetweenPt1AndPt3(pp->Prev->Pt, pp->Pt, pp->Next->Pt))))
  2898. {
  2899. lastOK = 0;
  2900. OutPt *tmp = pp;
  2901. pp->Prev->Next = pp->Next;
  2902. pp->Next->Prev = pp->Prev;
  2903. pp = pp->Prev;
  2904. delete tmp;
  2905. }
  2906. else if (pp == lastOK) break;
  2907. else
  2908. {
  2909. if (!lastOK) lastOK = pp;
  2910. pp = pp->Next;
  2911. }
  2912. }
  2913. outrec.Pts = pp;
  2914. }
  2915. //------------------------------------------------------------------------------
  2916. int PointCount(OutPt *Pts)
  2917. {
  2918. if (!Pts) return 0;
  2919. int result = 0;
  2920. OutPt* p = Pts;
  2921. do
  2922. {
  2923. result++;
  2924. p = p->Next;
  2925. }
  2926. while (p != Pts);
  2927. return result;
  2928. }
  2929. //------------------------------------------------------------------------------
  2930. void Clipper::BuildResult(Paths &polys)
  2931. {
  2932. polys.reserve(m_PolyOuts.size());
  2933. for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
  2934. {
  2935. if (!m_PolyOuts[i]->Pts) continue;
  2936. Path pg;
  2937. OutPt* p = m_PolyOuts[i]->Pts->Prev;
  2938. int cnt = PointCount(p);
  2939. if (cnt < 2) continue;
  2940. pg.reserve(cnt);
  2941. for (int j = 0; j < cnt; ++j)
  2942. {
  2943. pg.push_back(p->Pt);
  2944. p = p->Prev;
  2945. }
  2946. polys.push_back(pg);
  2947. }
  2948. }
  2949. //------------------------------------------------------------------------------
  2950. void Clipper::BuildResult2(PolyTree& polytree)
  2951. {
  2952. polytree.Clear();
  2953. polytree.AllNodes.reserve(m_PolyOuts.size());
  2954. //add each output polygon/contour to polytree ...
  2955. for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)
  2956. {
  2957. OutRec* outRec = m_PolyOuts[i];
  2958. int cnt = PointCount(outRec->Pts);
  2959. if ((outRec->IsOpen && cnt < 2) || (!outRec->IsOpen && cnt < 3)) continue;
  2960. FixHoleLinkage(*outRec);
  2961. PolyNode* pn = new PolyNode();
  2962. //nb: polytree takes ownership of all the PolyNodes
  2963. polytree.AllNodes.push_back(pn);
  2964. outRec->PolyNd = pn;
  2965. pn->Parent = 0;
  2966. pn->Index = 0;
  2967. pn->Contour.reserve(cnt);
  2968. OutPt *op = outRec->Pts->Prev;
  2969. for (int j = 0; j < cnt; j++)
  2970. {
  2971. pn->Contour.push_back(op->Pt);
  2972. op = op->Prev;
  2973. }
  2974. }
  2975. //fixup PolyNode links etc ...
  2976. polytree.Childs.reserve(m_PolyOuts.size());
  2977. for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)
  2978. {
  2979. OutRec* outRec = m_PolyOuts[i];
  2980. if (!outRec->PolyNd) continue;
  2981. if (outRec->IsOpen)
  2982. {
  2983. outRec->PolyNd->m_IsOpen = true;
  2984. polytree.AddChild(*outRec->PolyNd);
  2985. }
  2986. else if (outRec->FirstLeft && outRec->FirstLeft->PolyNd)
  2987. outRec->FirstLeft->PolyNd->AddChild(*outRec->PolyNd);
  2988. else
  2989. polytree.AddChild(*outRec->PolyNd);
  2990. }
  2991. }
  2992. //------------------------------------------------------------------------------
  2993. void SwapIntersectNodes(IntersectNode &int1, IntersectNode &int2)
  2994. {
  2995. //just swap the contents (because fIntersectNodes is a single-linked-list)
  2996. IntersectNode inode = int1; //gets a copy of Int1
  2997. int1.Edge1 = int2.Edge1;
  2998. int1.Edge2 = int2.Edge2;
  2999. int1.Pt = int2.Pt;
  3000. int2.Edge1 = inode.Edge1;
  3001. int2.Edge2 = inode.Edge2;
  3002. int2.Pt = inode.Pt;
  3003. }
  3004. //------------------------------------------------------------------------------
  3005. inline bool E2InsertsBeforeE1(TEdge &e1, TEdge &e2)
  3006. {
  3007. if (e2.Curr.X == e1.Curr.X)
  3008. {
  3009. if (e2.Top.Y > e1.Top.Y)
  3010. return e2.Top.X < TopX(e1, e2.Top.Y);
  3011. else return e1.Top.X > TopX(e2, e1.Top.Y);
  3012. }
  3013. else return e2.Curr.X < e1.Curr.X;
  3014. }
  3015. //------------------------------------------------------------------------------
  3016. bool GetOverlap(const cInt a1, const cInt a2, const cInt b1, const cInt b2,
  3017. cInt& Left, cInt& Right)
  3018. {
  3019. if (a1 < a2)
  3020. {
  3021. if (b1 < b2) {Left = std::max(a1,b1); Right = std::min(a2,b2);}
  3022. else {Left = std::max(a1,b2); Right = std::min(a2,b1);}
  3023. }
  3024. else
  3025. {
  3026. if (b1 < b2) {Left = std::max(a2,b1); Right = std::min(a1,b2);}
  3027. else {Left = std::max(a2,b2); Right = std::min(a1,b1);}
  3028. }
  3029. return Left < Right;
  3030. }
  3031. //------------------------------------------------------------------------------
  3032. inline void UpdateOutPtIdxs(OutRec& outrec)
  3033. {
  3034. OutPt* op = outrec.Pts;
  3035. do
  3036. {
  3037. op->Idx = outrec.Idx;
  3038. op = op->Prev;
  3039. }
  3040. while(op != outrec.Pts);
  3041. }
  3042. //------------------------------------------------------------------------------
  3043. void Clipper::InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge)
  3044. {
  3045. if(!m_ActiveEdges)
  3046. {
  3047. edge->PrevInAEL = 0;
  3048. edge->NextInAEL = 0;
  3049. m_ActiveEdges = edge;
  3050. }
  3051. else if(!startEdge && E2InsertsBeforeE1(*m_ActiveEdges, *edge))
  3052. {
  3053. edge->PrevInAEL = 0;
  3054. edge->NextInAEL = m_ActiveEdges;
  3055. m_ActiveEdges->PrevInAEL = edge;
  3056. m_ActiveEdges = edge;
  3057. }
  3058. else
  3059. {
  3060. if(!startEdge) startEdge = m_ActiveEdges;
  3061. while(startEdge->NextInAEL &&
  3062. !E2InsertsBeforeE1(*startEdge->NextInAEL , *edge))
  3063. startEdge = startEdge->NextInAEL;
  3064. edge->NextInAEL = startEdge->NextInAEL;
  3065. if(startEdge->NextInAEL) startEdge->NextInAEL->PrevInAEL = edge;
  3066. edge->PrevInAEL = startEdge;
  3067. startEdge->NextInAEL = edge;
  3068. }
  3069. }
  3070. //----------------------------------------------------------------------
  3071. OutPt* DupOutPt(OutPt* outPt, bool InsertAfter)
  3072. {
  3073. OutPt* result = new OutPt;
  3074. result->Pt = outPt->Pt;
  3075. result->Idx = outPt->Idx;
  3076. if (InsertAfter)
  3077. {
  3078. result->Next = outPt->Next;
  3079. result->Prev = outPt;
  3080. outPt->Next->Prev = result;
  3081. outPt->Next = result;
  3082. }
  3083. else
  3084. {
  3085. result->Prev = outPt->Prev;
  3086. result->Next = outPt;
  3087. outPt->Prev->Next = result;
  3088. outPt->Prev = result;
  3089. }
  3090. return result;
  3091. }
  3092. //------------------------------------------------------------------------------
  3093. bool JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b,
  3094. const IntPoint Pt, bool DiscardLeft)
  3095. {
  3096. Direction Dir1 = (op1->Pt.X > op1b->Pt.X ? dRightToLeft : dLeftToRight);
  3097. Direction Dir2 = (op2->Pt.X > op2b->Pt.X ? dRightToLeft : dLeftToRight);
  3098. if (Dir1 == Dir2) return false;
  3099. //When DiscardLeft, we want Op1b to be on the Left of Op1, otherwise we
  3100. //want Op1b to be on the Right. (And likewise with Op2 and Op2b.)
  3101. //So, to facilitate this while inserting Op1b and Op2b ...
  3102. //when DiscardLeft, make sure we're AT or RIGHT of Pt before adding Op1b,
  3103. //otherwise make sure we're AT or LEFT of Pt. (Likewise with Op2b.)
  3104. if (Dir1 == dLeftToRight)
  3105. {
  3106. while (op1->Next->Pt.X <= Pt.X &&
  3107. op1->Next->Pt.X >= op1->Pt.X && op1->Next->Pt.Y == Pt.Y)
  3108. op1 = op1->Next;
  3109. if (DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;
  3110. op1b = DupOutPt(op1, !DiscardLeft);
  3111. if (op1b->Pt != Pt)
  3112. {
  3113. op1 = op1b;
  3114. op1->Pt = Pt;
  3115. op1b = DupOutPt(op1, !DiscardLeft);
  3116. }
  3117. }
  3118. else
  3119. {
  3120. while (op1->Next->Pt.X >= Pt.X &&
  3121. op1->Next->Pt.X <= op1->Pt.X && op1->Next->Pt.Y == Pt.Y)
  3122. op1 = op1->Next;
  3123. if (!DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;
  3124. op1b = DupOutPt(op1, DiscardLeft);
  3125. if (op1b->Pt != Pt)
  3126. {
  3127. op1 = op1b;
  3128. op1->Pt = Pt;
  3129. op1b = DupOutPt(op1, DiscardLeft);
  3130. }
  3131. }
  3132. if (Dir2 == dLeftToRight)
  3133. {
  3134. while (op2->Next->Pt.X <= Pt.X &&
  3135. op2->Next->Pt.X >= op2->Pt.X && op2->Next->Pt.Y == Pt.Y)
  3136. op2 = op2->Next;
  3137. if (DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;
  3138. op2b = DupOutPt(op2, !DiscardLeft);
  3139. if (op2b->Pt != Pt)
  3140. {
  3141. op2 = op2b;
  3142. op2->Pt = Pt;
  3143. op2b = DupOutPt(op2, !DiscardLeft);
  3144. };
  3145. } else
  3146. {
  3147. while (op2->Next->Pt.X >= Pt.X &&
  3148. op2->Next->Pt.X <= op2->Pt.X && op2->Next->Pt.Y == Pt.Y)
  3149. op2 = op2->Next;
  3150. if (!DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;
  3151. op2b = DupOutPt(op2, DiscardLeft);
  3152. if (op2b->Pt != Pt)
  3153. {
  3154. op2 = op2b;
  3155. op2->Pt = Pt;
  3156. op2b = DupOutPt(op2, DiscardLeft);
  3157. };
  3158. };
  3159. if ((Dir1 == dLeftToRight) == DiscardLeft)
  3160. {
  3161. op1->Prev = op2;
  3162. op2->Next = op1;
  3163. op1b->Next = op2b;
  3164. op2b->Prev = op1b;
  3165. }
  3166. else
  3167. {
  3168. op1->Next = op2;
  3169. op2->Prev = op1;
  3170. op1b->Prev = op2b;
  3171. op2b->Next = op1b;
  3172. }
  3173. return true;
  3174. }
  3175. //------------------------------------------------------------------------------
  3176. bool Clipper::JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2)
  3177. {
  3178. OutPt *op1 = j->OutPt1, *op1b;
  3179. OutPt *op2 = j->OutPt2, *op2b;
  3180. //There are 3 kinds of joins for output polygons ...
  3181. //1. Horizontal joins where Join.OutPt1 & Join.OutPt2 are vertices anywhere
  3182. //along (horizontal) collinear edges (& Join.OffPt is on the same horizontal).
  3183. //2. Non-horizontal joins where Join.OutPt1 & Join.OutPt2 are at the same
  3184. //location at the Bottom of the overlapping segment (& Join.OffPt is above).
  3185. //3. StrictSimple joins where edges touch but are not collinear and where
  3186. //Join.OutPt1, Join.OutPt2 & Join.OffPt all share the same point.
  3187. bool isHorizontal = (j->OutPt1->Pt.Y == j->OffPt.Y);
  3188. if (isHorizontal && (j->OffPt == j->OutPt1->Pt) &&
  3189. (j->OffPt == j->OutPt2->Pt))
  3190. {
  3191. //Strictly Simple join ...
  3192. if (outRec1 != outRec2) return false;
  3193. op1b = j->OutPt1->Next;
  3194. while (op1b != op1 && (op1b->Pt == j->OffPt))
  3195. op1b = op1b->Next;
  3196. bool reverse1 = (op1b->Pt.Y > j->OffPt.Y);
  3197. op2b = j->OutPt2->Next;
  3198. while (op2b != op2 && (op2b->Pt == j->OffPt))
  3199. op2b = op2b->Next;
  3200. bool reverse2 = (op2b->Pt.Y > j->OffPt.Y);
  3201. if (reverse1 == reverse2) return false;
  3202. if (reverse1)
  3203. {
  3204. op1b = DupOutPt(op1, false);
  3205. op2b = DupOutPt(op2, true);
  3206. op1->Prev = op2;
  3207. op2->Next = op1;
  3208. op1b->Next = op2b;
  3209. op2b->Prev = op1b;
  3210. j->OutPt1 = op1;
  3211. j->OutPt2 = op1b;
  3212. return true;
  3213. } else
  3214. {
  3215. op1b = DupOutPt(op1, true);
  3216. op2b = DupOutPt(op2, false);
  3217. op1->Next = op2;
  3218. op2->Prev = op1;
  3219. op1b->Prev = op2b;
  3220. op2b->Next = op1b;
  3221. j->OutPt1 = op1;
  3222. j->OutPt2 = op1b;
  3223. return true;
  3224. }
  3225. }
  3226. else if (isHorizontal)
  3227. {
  3228. //treat horizontal joins differently to non-horizontal joins since with
  3229. //them we're not yet sure where the overlapping is. OutPt1.Pt & OutPt2.Pt
  3230. //may be anywhere along the horizontal edge.
  3231. op1b = op1;
  3232. while (op1->Prev->Pt.Y == op1->Pt.Y && op1->Prev != op1b && op1->Prev != op2)
  3233. op1 = op1->Prev;
  3234. while (op1b->Next->Pt.Y == op1b->Pt.Y && op1b->Next != op1 && op1b->Next != op2)
  3235. op1b = op1b->Next;
  3236. if (op1b->Next == op1 || op1b->Next == op2) return false; //a flat 'polygon'
  3237. op2b = op2;
  3238. while (op2->Prev->Pt.Y == op2->Pt.Y && op2->Prev != op2b && op2->Prev != op1b)
  3239. op2 = op2->Prev;
  3240. while (op2b->Next->Pt.Y == op2b->Pt.Y && op2b->Next != op2 && op2b->Next != op1)
  3241. op2b = op2b->Next;
  3242. if (op2b->Next == op2 || op2b->Next == op1) return false; //a flat 'polygon'
  3243. cInt Left, Right;
  3244. //Op1 --> Op1b & Op2 --> Op2b are the extremites of the horizontal edges
  3245. if (!GetOverlap(op1->Pt.X, op1b->Pt.X, op2->Pt.X, op2b->Pt.X, Left, Right))
  3246. return false;
  3247. //DiscardLeftSide: when overlapping edges are joined, a spike will created
  3248. //which needs to be cleaned up. However, we don't want Op1 or Op2 caught up
  3249. //on the discard Side as either may still be needed for other joins ...
  3250. IntPoint Pt;
  3251. bool DiscardLeftSide;
  3252. if (op1->Pt.X >= Left && op1->Pt.X <= Right)
  3253. {
  3254. Pt = op1->Pt; DiscardLeftSide = (op1->Pt.X > op1b->Pt.X);
  3255. }
  3256. else if (op2->Pt.X >= Left&& op2->Pt.X <= Right)
  3257. {
  3258. Pt = op2->Pt; DiscardLeftSide = (op2->Pt.X > op2b->Pt.X);
  3259. }
  3260. else if (op1b->Pt.X >= Left && op1b->Pt.X <= Right)
  3261. {
  3262. Pt = op1b->Pt; DiscardLeftSide = op1b->Pt.X > op1->Pt.X;
  3263. }
  3264. else
  3265. {
  3266. Pt = op2b->Pt; DiscardLeftSide = (op2b->Pt.X > op2->Pt.X);
  3267. }
  3268. j->OutPt1 = op1; j->OutPt2 = op2;
  3269. return JoinHorz(op1, op1b, op2, op2b, Pt, DiscardLeftSide);
  3270. } else
  3271. {
  3272. //nb: For non-horizontal joins ...
  3273. // 1. Jr.OutPt1.Pt.Y == Jr.OutPt2.Pt.Y
  3274. // 2. Jr.OutPt1.Pt > Jr.OffPt.Y
  3275. //make sure the polygons are correctly oriented ...
  3276. op1b = op1->Next;
  3277. while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Next;
  3278. bool Reverse1 = ((op1b->Pt.Y > op1->Pt.Y) ||
  3279. !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange));
  3280. if (Reverse1)
  3281. {
  3282. op1b = op1->Prev;
  3283. while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Prev;
  3284. if ((op1b->Pt.Y > op1->Pt.Y) ||
  3285. !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)) return false;
  3286. };
  3287. op2b = op2->Next;
  3288. while ((op2b->Pt == op2->Pt) && (op2b != op2))op2b = op2b->Next;
  3289. bool Reverse2 = ((op2b->Pt.Y > op2->Pt.Y) ||
  3290. !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange));
  3291. if (Reverse2)
  3292. {
  3293. op2b = op2->Prev;
  3294. while ((op2b->Pt == op2->Pt) && (op2b != op2)) op2b = op2b->Prev;
  3295. if ((op2b->Pt.Y > op2->Pt.Y) ||
  3296. !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)) return false;
  3297. }
  3298. if ((op1b == op1) || (op2b == op2) || (op1b == op2b) ||
  3299. ((outRec1 == outRec2) && (Reverse1 == Reverse2))) return false;
  3300. if (Reverse1)
  3301. {
  3302. op1b = DupOutPt(op1, false);
  3303. op2b = DupOutPt(op2, true);
  3304. op1->Prev = op2;
  3305. op2->Next = op1;
  3306. op1b->Next = op2b;
  3307. op2b->Prev = op1b;
  3308. j->OutPt1 = op1;
  3309. j->OutPt2 = op1b;
  3310. return true;
  3311. } else
  3312. {
  3313. op1b = DupOutPt(op1, true);
  3314. op2b = DupOutPt(op2, false);
  3315. op1->Next = op2;
  3316. op2->Prev = op1;
  3317. op1b->Prev = op2b;
  3318. op2b->Next = op1b;
  3319. j->OutPt1 = op1;
  3320. j->OutPt2 = op1b;
  3321. return true;
  3322. }
  3323. }
  3324. }
  3325. //----------------------------------------------------------------------
  3326. static OutRec* ParseFirstLeft(OutRec* FirstLeft)
  3327. {
  3328. while (FirstLeft && !FirstLeft->Pts)
  3329. FirstLeft = FirstLeft->FirstLeft;
  3330. return FirstLeft;
  3331. }
  3332. //------------------------------------------------------------------------------
  3333. void Clipper::FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec)
  3334. {
  3335. //tests if NewOutRec contains the polygon before reassigning FirstLeft
  3336. for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
  3337. {
  3338. OutRec* outRec = m_PolyOuts[i];
  3339. OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
  3340. if (outRec->Pts && firstLeft == OldOutRec)
  3341. {
  3342. if (Poly2ContainsPoly1(outRec->Pts, NewOutRec->Pts))
  3343. outRec->FirstLeft = NewOutRec;
  3344. }
  3345. }
  3346. }
  3347. //----------------------------------------------------------------------
  3348. void Clipper::FixupFirstLefts2(OutRec* InnerOutRec, OutRec* OuterOutRec)
  3349. {
  3350. //A polygon has split into two such that one is now the inner of the other.
  3351. //It's possible that these polygons now wrap around other polygons, so check
  3352. //every polygon that's also contained by OuterOutRec's FirstLeft container
  3353. //(including 0) to see if they've become inner to the new inner polygon ...
  3354. OutRec* orfl = OuterOutRec->FirstLeft;
  3355. for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
  3356. {
  3357. OutRec* outRec = m_PolyOuts[i];
  3358. if (!outRec->Pts || outRec == OuterOutRec || outRec == InnerOutRec)
  3359. continue;
  3360. OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
  3361. if (firstLeft != orfl && firstLeft != InnerOutRec && firstLeft != OuterOutRec)
  3362. continue;
  3363. if (Poly2ContainsPoly1(outRec->Pts, InnerOutRec->Pts))
  3364. outRec->FirstLeft = InnerOutRec;
  3365. else if (Poly2ContainsPoly1(outRec->Pts, OuterOutRec->Pts))
  3366. outRec->FirstLeft = OuterOutRec;
  3367. else if (outRec->FirstLeft == InnerOutRec || outRec->FirstLeft == OuterOutRec)
  3368. outRec->FirstLeft = orfl;
  3369. }
  3370. }
  3371. //----------------------------------------------------------------------
  3372. void Clipper::FixupFirstLefts3(OutRec* OldOutRec, OutRec* NewOutRec)
  3373. {
  3374. //reassigns FirstLeft WITHOUT testing if NewOutRec contains the polygon
  3375. for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
  3376. {
  3377. OutRec* outRec = m_PolyOuts[i];
  3378. OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
  3379. if (outRec->Pts && firstLeft == OldOutRec)
  3380. outRec->FirstLeft = NewOutRec;
  3381. }
  3382. }
  3383. //----------------------------------------------------------------------
  3384. void Clipper::JoinCommonEdges()
  3385. {
  3386. for (JoinList::size_type i = 0; i < m_Joins.size(); i++)
  3387. {
  3388. Join* join = m_Joins[i];
  3389. OutRec *outRec1 = GetOutRec(join->OutPt1->Idx);
  3390. OutRec *outRec2 = GetOutRec(join->OutPt2->Idx);
  3391. if (!outRec1->Pts || !outRec2->Pts) continue;
  3392. if (outRec1->IsOpen || outRec2->IsOpen) continue;
  3393. //get the polygon fragment with the correct hole state (FirstLeft)
  3394. //before calling JoinPoints() ...
  3395. OutRec *holeStateRec;
  3396. if (outRec1 == outRec2) holeStateRec = outRec1;
  3397. else if (OutRec1RightOfOutRec2(outRec1, outRec2)) holeStateRec = outRec2;
  3398. else if (OutRec1RightOfOutRec2(outRec2, outRec1)) holeStateRec = outRec1;
  3399. else holeStateRec = GetLowermostRec(outRec1, outRec2);
  3400. if (!JoinPoints(join, outRec1, outRec2)) continue;
  3401. if (outRec1 == outRec2)
  3402. {
  3403. //instead of joining two polygons, we've just created a new one by
  3404. //splitting one polygon into two.
  3405. outRec1->Pts = join->OutPt1;
  3406. outRec1->BottomPt = 0;
  3407. outRec2 = CreateOutRec();
  3408. outRec2->Pts = join->OutPt2;
  3409. //update all OutRec2.Pts Idx's ...
  3410. UpdateOutPtIdxs(*outRec2);
  3411. if (Poly2ContainsPoly1(outRec2->Pts, outRec1->Pts))
  3412. {
  3413. //outRec1 contains outRec2 ...
  3414. outRec2->IsHole = !outRec1->IsHole;
  3415. outRec2->FirstLeft = outRec1;
  3416. if (m_UsingPolyTree) FixupFirstLefts2(outRec2, outRec1);
  3417. if ((outRec2->IsHole ^ m_ReverseOutput) == (Area(*outRec2) > 0))
  3418. ReversePolyPtLinks(outRec2->Pts);
  3419. } else if (Poly2ContainsPoly1(outRec1->Pts, outRec2->Pts))
  3420. {
  3421. //outRec2 contains outRec1 ...
  3422. outRec2->IsHole = outRec1->IsHole;
  3423. outRec1->IsHole = !outRec2->IsHole;
  3424. outRec2->FirstLeft = outRec1->FirstLeft;
  3425. outRec1->FirstLeft = outRec2;
  3426. if (m_UsingPolyTree) FixupFirstLefts2(outRec1, outRec2);
  3427. if ((outRec1->IsHole ^ m_ReverseOutput) == (Area(*outRec1) > 0))
  3428. ReversePolyPtLinks(outRec1->Pts);
  3429. }
  3430. else
  3431. {
  3432. //the 2 polygons are completely separate ...
  3433. outRec2->IsHole = outRec1->IsHole;
  3434. outRec2->FirstLeft = outRec1->FirstLeft;
  3435. //fixup FirstLeft pointers that may need reassigning to OutRec2
  3436. if (m_UsingPolyTree) FixupFirstLefts1(outRec1, outRec2);
  3437. }
  3438. } else
  3439. {
  3440. //joined 2 polygons together ...
  3441. outRec2->Pts = 0;
  3442. outRec2->BottomPt = 0;
  3443. outRec2->Idx = outRec1->Idx;
  3444. outRec1->IsHole = holeStateRec->IsHole;
  3445. if (holeStateRec == outRec2)
  3446. outRec1->FirstLeft = outRec2->FirstLeft;
  3447. outRec2->FirstLeft = outRec1;
  3448. if (m_UsingPolyTree) FixupFirstLefts3(outRec2, outRec1);
  3449. }
  3450. }
  3451. }
  3452. //------------------------------------------------------------------------------
  3453. // ClipperOffset support functions ...
  3454. //------------------------------------------------------------------------------
  3455. DoublePoint GetUnitNormal(const IntPoint &pt1, const IntPoint &pt2)
  3456. {
  3457. if(pt2.X == pt1.X && pt2.Y == pt1.Y)
  3458. return DoublePoint(0, 0);
  3459. double Dx = (double)(pt2.X - pt1.X);
  3460. double dy = (double)(pt2.Y - pt1.Y);
  3461. double f = 1 *1.0/ std::sqrt( Dx*Dx + dy*dy );
  3462. Dx *= f;
  3463. dy *= f;
  3464. return DoublePoint(dy, -Dx);
  3465. }
  3466. //------------------------------------------------------------------------------
  3467. // ClipperOffset class
  3468. //------------------------------------------------------------------------------
  3469. ClipperOffset::ClipperOffset(double miterLimit, double arcTolerance)
  3470. {
  3471. this->MiterLimit = miterLimit;
  3472. this->ArcTolerance = arcTolerance;
  3473. m_lowest.X = -1;
  3474. }
  3475. //------------------------------------------------------------------------------
  3476. ClipperOffset::~ClipperOffset()
  3477. {
  3478. Clear();
  3479. }
  3480. //------------------------------------------------------------------------------
  3481. void ClipperOffset::Clear()
  3482. {
  3483. for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
  3484. delete m_polyNodes.Childs[i];
  3485. m_polyNodes.Childs.clear();
  3486. m_lowest.X = -1;
  3487. }
  3488. //------------------------------------------------------------------------------
  3489. void ClipperOffset::AddPath(const Path& path, JoinType joinType, EndType endType)
  3490. {
  3491. int highI = (int)path.size() - 1;
  3492. if (highI < 0) return;
  3493. PolyNode* newNode = new PolyNode();
  3494. newNode->m_jointype = joinType;
  3495. newNode->m_endtype = endType;
  3496. //strip duplicate points from path and also get index to the lowest point ...
  3497. if (endType == etClosedLine || endType == etClosedPolygon)
  3498. while (highI > 0 && path[0] == path[highI]) highI--;
  3499. newNode->Contour.reserve(highI + 1);
  3500. newNode->Contour.push_back(path[0]);
  3501. int j = 0, k = 0;
  3502. for (int i = 1; i <= highI; i++)
  3503. if (newNode->Contour[j] != path[i])
  3504. {
  3505. j++;
  3506. newNode->Contour.push_back(path[i]);
  3507. if (path[i].Y > newNode->Contour[k].Y ||
  3508. (path[i].Y == newNode->Contour[k].Y &&
  3509. path[i].X < newNode->Contour[k].X)) k = j;
  3510. }
  3511. if (endType == etClosedPolygon && j < 2)
  3512. {
  3513. delete newNode;
  3514. return;
  3515. }
  3516. m_polyNodes.AddChild(*newNode);
  3517. //if this path's lowest pt is lower than all the others then update m_lowest
  3518. if (endType != etClosedPolygon) return;
  3519. if (m_lowest.X < 0)
  3520. m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);
  3521. else
  3522. {
  3523. IntPoint ip = m_polyNodes.Childs[(int)m_lowest.X]->Contour[(int)m_lowest.Y];
  3524. if (newNode->Contour[k].Y > ip.Y ||
  3525. (newNode->Contour[k].Y == ip.Y &&
  3526. newNode->Contour[k].X < ip.X))
  3527. m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);
  3528. }
  3529. }
  3530. //------------------------------------------------------------------------------
  3531. void ClipperOffset::AddPaths(const Paths& paths, JoinType joinType, EndType endType)
  3532. {
  3533. for (Paths::size_type i = 0; i < paths.size(); ++i)
  3534. AddPath(paths[i], joinType, endType);
  3535. }
  3536. //------------------------------------------------------------------------------
  3537. void ClipperOffset::FixOrientations()
  3538. {
  3539. //fixup orientations of all closed paths if the orientation of the
  3540. //closed path with the lowermost vertex is wrong ...
  3541. if (m_lowest.X >= 0 &&
  3542. !Orientation(m_polyNodes.Childs[(int)m_lowest.X]->Contour))
  3543. {
  3544. for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
  3545. {
  3546. PolyNode& node = *m_polyNodes.Childs[i];
  3547. if (node.m_endtype == etClosedPolygon ||
  3548. (node.m_endtype == etClosedLine && Orientation(node.Contour)))
  3549. ReversePath(node.Contour);
  3550. }
  3551. } else
  3552. {
  3553. for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
  3554. {
  3555. PolyNode& node = *m_polyNodes.Childs[i];
  3556. if (node.m_endtype == etClosedLine && !Orientation(node.Contour))
  3557. ReversePath(node.Contour);
  3558. }
  3559. }
  3560. }
  3561. //------------------------------------------------------------------------------
  3562. void ClipperOffset::Execute(Paths& solution, double delta)
  3563. {
  3564. solution.clear();
  3565. FixOrientations();
  3566. DoOffset(delta);
  3567. //now clean up 'corners' ...
  3568. Clipper clpr;
  3569. clpr.AddPaths(m_destPolys, ptSubject, true);
  3570. if (delta > 0)
  3571. {
  3572. clpr.Execute(ctUnion, solution, pftPositive, pftPositive);
  3573. }
  3574. else
  3575. {
  3576. IntRect r = clpr.GetBounds();
  3577. Path outer(4);
  3578. outer[0] = IntPoint(r.left - 10, r.bottom + 10);
  3579. outer[1] = IntPoint(r.right + 10, r.bottom + 10);
  3580. outer[2] = IntPoint(r.right + 10, r.top - 10);
  3581. outer[3] = IntPoint(r.left - 10, r.top - 10);
  3582. clpr.AddPath(outer, ptSubject, true);
  3583. clpr.ReverseSolution(true);
  3584. clpr.Execute(ctUnion, solution, pftNegative, pftNegative);
  3585. if (solution.size() > 0) solution.erase(solution.begin());
  3586. }
  3587. }
  3588. //------------------------------------------------------------------------------
  3589. void ClipperOffset::Execute(PolyTree& solution, double delta)
  3590. {
  3591. solution.Clear();
  3592. FixOrientations();
  3593. DoOffset(delta);
  3594. //now clean up 'corners' ...
  3595. Clipper clpr;
  3596. clpr.AddPaths(m_destPolys, ptSubject, true);
  3597. if (delta > 0)
  3598. {
  3599. clpr.Execute(ctUnion, solution, pftPositive, pftPositive);
  3600. }
  3601. else
  3602. {
  3603. IntRect r = clpr.GetBounds();
  3604. Path outer(4);
  3605. outer[0] = IntPoint(r.left - 10, r.bottom + 10);
  3606. outer[1] = IntPoint(r.right + 10, r.bottom + 10);
  3607. outer[2] = IntPoint(r.right + 10, r.top - 10);
  3608. outer[3] = IntPoint(r.left - 10, r.top - 10);
  3609. clpr.AddPath(outer, ptSubject, true);
  3610. clpr.ReverseSolution(true);
  3611. clpr.Execute(ctUnion, solution, pftNegative, pftNegative);
  3612. //remove the outer PolyNode rectangle ...
  3613. if (solution.ChildCount() == 1 && solution.Childs[0]->ChildCount() > 0)
  3614. {
  3615. PolyNode* outerNode = solution.Childs[0];
  3616. solution.Childs.reserve(outerNode->ChildCount());
  3617. solution.Childs[0] = outerNode->Childs[0];
  3618. solution.Childs[0]->Parent = outerNode->Parent;
  3619. for (int i = 1; i < outerNode->ChildCount(); ++i)
  3620. solution.AddChild(*outerNode->Childs[i]);
  3621. }
  3622. else
  3623. solution.Clear();
  3624. }
  3625. }
  3626. //------------------------------------------------------------------------------
  3627. void ClipperOffset::DoOffset(double delta)
  3628. {
  3629. m_destPolys.clear();
  3630. m_delta = delta;
  3631. //if Zero offset, just copy any CLOSED polygons to m_p and return ...
  3632. if (NEAR_ZERO(delta))
  3633. {
  3634. m_destPolys.reserve(m_polyNodes.ChildCount());
  3635. for (int i = 0; i < m_polyNodes.ChildCount(); i++)
  3636. {
  3637. PolyNode& node = *m_polyNodes.Childs[i];
  3638. if (node.m_endtype == etClosedPolygon)
  3639. m_destPolys.push_back(node.Contour);
  3640. }
  3641. return;
  3642. }
  3643. //see offset_triginometry3.svg in the documentation folder ...
  3644. if (MiterLimit > 2) m_miterLim = 2/(MiterLimit * MiterLimit);
  3645. else m_miterLim = 0.5;
  3646. double y;
  3647. if (ArcTolerance <= 0.0) y = def_arc_tolerance;
  3648. else if (ArcTolerance > std::fabs(delta) * def_arc_tolerance)
  3649. y = std::fabs(delta) * def_arc_tolerance;
  3650. else y = ArcTolerance;
  3651. //see offset_triginometry2.svg in the documentation folder ...
  3652. double steps = pi / std::acos(1 - y / std::fabs(delta));
  3653. if (steps > std::fabs(delta) * pi)
  3654. steps = std::fabs(delta) * pi; //ie excessive precision check
  3655. m_sin = std::sin(two_pi / steps);
  3656. m_cos = std::cos(two_pi / steps);
  3657. m_StepsPerRad = steps / two_pi;
  3658. if (delta < 0.0) m_sin = -m_sin;
  3659. m_destPolys.reserve(m_polyNodes.ChildCount() * 2);
  3660. for (int i = 0; i < m_polyNodes.ChildCount(); i++)
  3661. {
  3662. PolyNode& node = *m_polyNodes.Childs[i];
  3663. m_srcPoly = node.Contour;
  3664. int len = (int)m_srcPoly.size();
  3665. if (len == 0 || (delta <= 0 && (len < 3 || node.m_endtype != etClosedPolygon)))
  3666. continue;
  3667. m_destPoly.clear();
  3668. if (len == 1)
  3669. {
  3670. if (node.m_jointype == jtRound)
  3671. {
  3672. double X = 1.0, Y = 0.0;
  3673. for (cInt j = 1; j <= steps; j++)
  3674. {
  3675. m_destPoly.push_back(IntPoint(
  3676. Round(m_srcPoly[0].X + X * delta),
  3677. Round(m_srcPoly[0].Y + Y * delta)));
  3678. double X2 = X;
  3679. X = X * m_cos - m_sin * Y;
  3680. Y = X2 * m_sin + Y * m_cos;
  3681. }
  3682. }
  3683. else
  3684. {
  3685. double X = -1.0, Y = -1.0;
  3686. for (int j = 0; j < 4; ++j)
  3687. {
  3688. m_destPoly.push_back(IntPoint(
  3689. Round(m_srcPoly[0].X + X * delta),
  3690. Round(m_srcPoly[0].Y + Y * delta)));
  3691. if (X < 0) X = 1;
  3692. else if (Y < 0) Y = 1;
  3693. else X = -1;
  3694. }
  3695. }
  3696. m_destPolys.push_back(m_destPoly);
  3697. continue;
  3698. }
  3699. //build m_normals ...
  3700. m_normals.clear();
  3701. m_normals.reserve(len);
  3702. for (int j = 0; j < len - 1; ++j)
  3703. m_normals.push_back(GetUnitNormal(m_srcPoly[j], m_srcPoly[j + 1]));
  3704. if (node.m_endtype == etClosedLine || node.m_endtype == etClosedPolygon)
  3705. m_normals.push_back(GetUnitNormal(m_srcPoly[len - 1], m_srcPoly[0]));
  3706. else
  3707. m_normals.push_back(DoublePoint(m_normals[len - 2]));
  3708. if (node.m_endtype == etClosedPolygon)
  3709. {
  3710. int k = len - 1;
  3711. for (int j = 0; j < len; ++j)
  3712. OffsetPoint(j, k, node.m_jointype);
  3713. m_destPolys.push_back(m_destPoly);
  3714. }
  3715. else if (node.m_endtype == etClosedLine)
  3716. {
  3717. int k = len - 1;
  3718. for (int j = 0; j < len; ++j)
  3719. OffsetPoint(j, k, node.m_jointype);
  3720. m_destPolys.push_back(m_destPoly);
  3721. m_destPoly.clear();
  3722. //re-build m_normals ...
  3723. DoublePoint n = m_normals[len -1];
  3724. for (int j = len - 1; j > 0; j--)
  3725. m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);
  3726. m_normals[0] = DoublePoint(-n.X, -n.Y);
  3727. k = 0;
  3728. for (int j = len - 1; j >= 0; j--)
  3729. OffsetPoint(j, k, node.m_jointype);
  3730. m_destPolys.push_back(m_destPoly);
  3731. }
  3732. else
  3733. {
  3734. int k = 0;
  3735. for (int j = 1; j < len - 1; ++j)
  3736. OffsetPoint(j, k, node.m_jointype);
  3737. IntPoint pt1;
  3738. if (node.m_endtype == etOpenButt)
  3739. {
  3740. int j = len - 1;
  3741. pt1 = IntPoint((cInt)Round(m_srcPoly[j].X + m_normals[j].X *
  3742. delta), (cInt)Round(m_srcPoly[j].Y + m_normals[j].Y * delta));
  3743. m_destPoly.push_back(pt1);
  3744. pt1 = IntPoint((cInt)Round(m_srcPoly[j].X - m_normals[j].X *
  3745. delta), (cInt)Round(m_srcPoly[j].Y - m_normals[j].Y * delta));
  3746. m_destPoly.push_back(pt1);
  3747. }
  3748. else
  3749. {
  3750. int j = len - 1;
  3751. k = len - 2;
  3752. m_sinA = 0;
  3753. m_normals[j] = DoublePoint(-m_normals[j].X, -m_normals[j].Y);
  3754. if (node.m_endtype == etOpenSquare)
  3755. DoSquare(j, k);
  3756. else
  3757. DoRound(j, k);
  3758. }
  3759. //re-build m_normals ...
  3760. for (int j = len - 1; j > 0; j--)
  3761. m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);
  3762. m_normals[0] = DoublePoint(-m_normals[1].X, -m_normals[1].Y);
  3763. k = len - 1;
  3764. for (int j = k - 1; j > 0; --j) OffsetPoint(j, k, node.m_jointype);
  3765. if (node.m_endtype == etOpenButt)
  3766. {
  3767. pt1 = IntPoint((cInt)Round(m_srcPoly[0].X - m_normals[0].X * delta),
  3768. (cInt)Round(m_srcPoly[0].Y - m_normals[0].Y * delta));
  3769. m_destPoly.push_back(pt1);
  3770. pt1 = IntPoint((cInt)Round(m_srcPoly[0].X + m_normals[0].X * delta),
  3771. (cInt)Round(m_srcPoly[0].Y + m_normals[0].Y * delta));
  3772. m_destPoly.push_back(pt1);
  3773. }
  3774. else
  3775. {
  3776. k = 1;
  3777. m_sinA = 0;
  3778. if (node.m_endtype == etOpenSquare)
  3779. DoSquare(0, 1);
  3780. else
  3781. DoRound(0, 1);
  3782. }
  3783. m_destPolys.push_back(m_destPoly);
  3784. }
  3785. }
  3786. }
  3787. //------------------------------------------------------------------------------
  3788. void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype)
  3789. {
  3790. //cross product ...
  3791. m_sinA = (m_normals[k].X * m_normals[j].Y - m_normals[j].X * m_normals[k].Y);
  3792. if (std::fabs(m_sinA * m_delta) < 1.0)
  3793. {
  3794. //dot product ...
  3795. double cosA = (m_normals[k].X * m_normals[j].X + m_normals[j].Y * m_normals[k].Y );
  3796. if (cosA > 0) // angle => 0 degrees
  3797. {
  3798. m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),
  3799. Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));
  3800. return;
  3801. }
  3802. //else angle => 180 degrees
  3803. }
  3804. else if (m_sinA > 1.0) m_sinA = 1.0;
  3805. else if (m_sinA < -1.0) m_sinA = -1.0;
  3806. if (m_sinA * m_delta < 0)
  3807. {
  3808. m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),
  3809. Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));
  3810. m_destPoly.push_back(m_srcPoly[j]);
  3811. m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[j].X * m_delta),
  3812. Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));
  3813. }
  3814. else
  3815. switch (jointype)
  3816. {
  3817. case jtMiter:
  3818. {
  3819. double r = 1 + (m_normals[j].X * m_normals[k].X +
  3820. m_normals[j].Y * m_normals[k].Y);
  3821. if (r >= m_miterLim) DoMiter(j, k, r); else DoSquare(j, k);
  3822. break;
  3823. }
  3824. case jtSquare: DoSquare(j, k); break;
  3825. case jtRound: DoRound(j, k); break;
  3826. }
  3827. k = j;
  3828. }
  3829. //------------------------------------------------------------------------------
  3830. void ClipperOffset::DoSquare(int j, int k)
  3831. {
  3832. double dx = std::tan(std::atan2(m_sinA,
  3833. m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4);
  3834. m_destPoly.push_back(IntPoint(
  3835. Round(m_srcPoly[j].X + m_delta * (m_normals[k].X - m_normals[k].Y * dx)),
  3836. Round(m_srcPoly[j].Y + m_delta * (m_normals[k].Y + m_normals[k].X * dx))));
  3837. m_destPoly.push_back(IntPoint(
  3838. Round(m_srcPoly[j].X + m_delta * (m_normals[j].X + m_normals[j].Y * dx)),
  3839. Round(m_srcPoly[j].Y + m_delta * (m_normals[j].Y - m_normals[j].X * dx))));
  3840. }
  3841. //------------------------------------------------------------------------------
  3842. void ClipperOffset::DoMiter(int j, int k, double r)
  3843. {
  3844. double q = m_delta / r;
  3845. m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + (m_normals[k].X + m_normals[j].X) * q),
  3846. Round(m_srcPoly[j].Y + (m_normals[k].Y + m_normals[j].Y) * q)));
  3847. }
  3848. //------------------------------------------------------------------------------
  3849. void ClipperOffset::DoRound(int j, int k)
  3850. {
  3851. double a = std::atan2(m_sinA,
  3852. m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y);
  3853. int steps = std::max((int)Round(m_StepsPerRad * std::fabs(a)), 1);
  3854. double X = m_normals[k].X, Y = m_normals[k].Y, X2;
  3855. for (int i = 0; i < steps; ++i)
  3856. {
  3857. m_destPoly.push_back(IntPoint(
  3858. Round(m_srcPoly[j].X + X * m_delta),
  3859. Round(m_srcPoly[j].Y + Y * m_delta)));
  3860. X2 = X;
  3861. X = X * m_cos - m_sin * Y;
  3862. Y = X2 * m_sin + Y * m_cos;
  3863. }
  3864. m_destPoly.push_back(IntPoint(
  3865. Round(m_srcPoly[j].X + m_normals[j].X * m_delta),
  3866. Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));
  3867. }
  3868. //------------------------------------------------------------------------------
  3869. // Miscellaneous public functions
  3870. //------------------------------------------------------------------------------
  3871. void Clipper::DoSimplePolygons()
  3872. {
  3873. PolyOutList::size_type i = 0;
  3874. while (i < m_PolyOuts.size())
  3875. {
  3876. OutRec* outrec = m_PolyOuts[i++];
  3877. OutPt* op = outrec->Pts;
  3878. if (!op || outrec->IsOpen) continue;
  3879. do //for each Pt in Polygon until duplicate found do ...
  3880. {
  3881. OutPt* op2 = op->Next;
  3882. while (op2 != outrec->Pts)
  3883. {
  3884. if ((op->Pt == op2->Pt) && op2->Next != op && op2->Prev != op)
  3885. {
  3886. //split the polygon into two ...
  3887. OutPt* op3 = op->Prev;
  3888. OutPt* op4 = op2->Prev;
  3889. op->Prev = op4;
  3890. op4->Next = op;
  3891. op2->Prev = op3;
  3892. op3->Next = op2;
  3893. outrec->Pts = op;
  3894. OutRec* outrec2 = CreateOutRec();
  3895. outrec2->Pts = op2;
  3896. UpdateOutPtIdxs(*outrec2);
  3897. if (Poly2ContainsPoly1(outrec2->Pts, outrec->Pts))
  3898. {
  3899. //OutRec2 is contained by OutRec1 ...
  3900. outrec2->IsHole = !outrec->IsHole;
  3901. outrec2->FirstLeft = outrec;
  3902. if (m_UsingPolyTree) FixupFirstLefts2(outrec2, outrec);
  3903. }
  3904. else
  3905. if (Poly2ContainsPoly1(outrec->Pts, outrec2->Pts))
  3906. {
  3907. //OutRec1 is contained by OutRec2 ...
  3908. outrec2->IsHole = outrec->IsHole;
  3909. outrec->IsHole = !outrec2->IsHole;
  3910. outrec2->FirstLeft = outrec->FirstLeft;
  3911. outrec->FirstLeft = outrec2;
  3912. if (m_UsingPolyTree) FixupFirstLefts2(outrec, outrec2);
  3913. }
  3914. else
  3915. {
  3916. //the 2 polygons are separate ...
  3917. outrec2->IsHole = outrec->IsHole;
  3918. outrec2->FirstLeft = outrec->FirstLeft;
  3919. if (m_UsingPolyTree) FixupFirstLefts1(outrec, outrec2);
  3920. }
  3921. op2 = op; //ie get ready for the Next iteration
  3922. }
  3923. op2 = op2->Next;
  3924. }
  3925. op = op->Next;
  3926. }
  3927. while (op != outrec->Pts);
  3928. }
  3929. }
  3930. //------------------------------------------------------------------------------
  3931. void ReversePath(Path& p)
  3932. {
  3933. std::reverse(p.begin(), p.end());
  3934. }
  3935. //------------------------------------------------------------------------------
  3936. void ReversePaths(Paths& p)
  3937. {
  3938. for (Paths::size_type i = 0; i < p.size(); ++i)
  3939. ReversePath(p[i]);
  3940. }
  3941. //------------------------------------------------------------------------------
  3942. void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType)
  3943. {
  3944. Clipper c;
  3945. c.StrictlySimple(true);
  3946. c.AddPath(in_poly, ptSubject, true);
  3947. c.Execute(ctUnion, out_polys, fillType, fillType);
  3948. }
  3949. //------------------------------------------------------------------------------
  3950. void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType)
  3951. {
  3952. Clipper c;
  3953. c.StrictlySimple(true);
  3954. c.AddPaths(in_polys, ptSubject, true);
  3955. c.Execute(ctUnion, out_polys, fillType, fillType);
  3956. }
  3957. //------------------------------------------------------------------------------
  3958. void SimplifyPolygons(Paths &polys, PolyFillType fillType)
  3959. {
  3960. SimplifyPolygons(polys, polys, fillType);
  3961. }
  3962. //------------------------------------------------------------------------------
  3963. inline double DistanceSqrd(const IntPoint& pt1, const IntPoint& pt2)
  3964. {
  3965. double Dx = ((double)pt1.X - pt2.X);
  3966. double dy = ((double)pt1.Y - pt2.Y);
  3967. return (Dx*Dx + dy*dy);
  3968. }
  3969. //------------------------------------------------------------------------------
  3970. double DistanceFromLineSqrd(
  3971. const IntPoint& pt, const IntPoint& ln1, const IntPoint& ln2)
  3972. {
  3973. //The equation of a line in general form (Ax + By + C = 0)
  3974. //given 2 points (x_1, y_1) & (x_2, y_2) is ...
  3975. //(y_1 - y_2)x + (x_2 - x_1)y - (y_1 - y_2)x_1 - (x_2 - x_1)y_1 = 0
  3976. //A = (y_1 - y_2); B = (x_2 - x_1); C = - (y_1 - y_2)x_1 - (x_2 - x_1)y_1
  3977. //perpendicular distance of point (x_0, y_0) = |Ax_0 + By_0 + C| / Sqrt(A^2 + B^2)
  3978. //see http://en.wikipedia.org/wiki/Perpendicular_distance
  3979. double A = double(ln1.Y - ln2.Y);
  3980. double B = double(ln2.X - ln1.X);
  3981. double C = A * ln1.X + B * ln1.Y;
  3982. C = A * pt.X + B * pt.Y - C;
  3983. return (C * C) / (A * A + B * B);
  3984. }
  3985. //---------------------------------------------------------------------------
  3986. bool SlopesNearCollinear(const IntPoint& pt1,
  3987. const IntPoint& pt2, const IntPoint& pt3, double distSqrd)
  3988. {
  3989. //this function is more accurate when the point that's geometrically
  3990. //between the other 2 points is the one that's tested for distance.
  3991. //ie makes it more likely to pick up 'spikes' ...
  3992. if (Abs(pt1.X - pt2.X) > Abs(pt1.Y - pt2.Y))
  3993. {
  3994. if ((pt1.X > pt2.X) == (pt1.X < pt3.X))
  3995. return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;
  3996. else if ((pt2.X > pt1.X) == (pt2.X < pt3.X))
  3997. return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;
  3998. else
  3999. return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;
  4000. }
  4001. else
  4002. {
  4003. if ((pt1.Y > pt2.Y) == (pt1.Y < pt3.Y))
  4004. return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;
  4005. else if ((pt2.Y > pt1.Y) == (pt2.Y < pt3.Y))
  4006. return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;
  4007. else
  4008. return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;
  4009. }
  4010. }
  4011. //------------------------------------------------------------------------------
  4012. bool PointsAreClose(IntPoint pt1, IntPoint pt2, double distSqrd)
  4013. {
  4014. double Dx = (double)pt1.X - pt2.X;
  4015. double dy = (double)pt1.Y - pt2.Y;
  4016. return ((Dx * Dx) + (dy * dy) <= distSqrd);
  4017. }
  4018. //------------------------------------------------------------------------------
  4019. OutPt* ExcludeOp(OutPt* op)
  4020. {
  4021. OutPt* result = op->Prev;
  4022. result->Next = op->Next;
  4023. op->Next->Prev = result;
  4024. result->Idx = 0;
  4025. return result;
  4026. }
  4027. //------------------------------------------------------------------------------
  4028. void CleanPolygon(const Path& in_poly, Path& out_poly, double distance)
  4029. {
  4030. //distance = proximity in units/pixels below which vertices
  4031. //will be stripped. Default ~= sqrt(2).
  4032. size_t size = in_poly.size();
  4033. if (size == 0)
  4034. {
  4035. out_poly.clear();
  4036. return;
  4037. }
  4038. OutPt* outPts = new OutPt[size];
  4039. for (size_t i = 0; i < size; ++i)
  4040. {
  4041. outPts[i].Pt = in_poly[i];
  4042. outPts[i].Next = &outPts[(i + 1) % size];
  4043. outPts[i].Next->Prev = &outPts[i];
  4044. outPts[i].Idx = 0;
  4045. }
  4046. double distSqrd = distance * distance;
  4047. OutPt* op = &outPts[0];
  4048. while (op->Idx == 0 && op->Next != op->Prev)
  4049. {
  4050. if (PointsAreClose(op->Pt, op->Prev->Pt, distSqrd))
  4051. {
  4052. op = ExcludeOp(op);
  4053. size--;
  4054. }
  4055. else if (PointsAreClose(op->Prev->Pt, op->Next->Pt, distSqrd))
  4056. {
  4057. ExcludeOp(op->Next);
  4058. op = ExcludeOp(op);
  4059. size -= 2;
  4060. }
  4061. else if (SlopesNearCollinear(op->Prev->Pt, op->Pt, op->Next->Pt, distSqrd))
  4062. {
  4063. op = ExcludeOp(op);
  4064. size--;
  4065. }
  4066. else
  4067. {
  4068. op->Idx = 1;
  4069. op = op->Next;
  4070. }
  4071. }
  4072. if (size < 3) size = 0;
  4073. out_poly.resize(size);
  4074. for (size_t i = 0; i < size; ++i)
  4075. {
  4076. out_poly[i] = op->Pt;
  4077. op = op->Next;
  4078. }
  4079. delete [] outPts;
  4080. }
  4081. //------------------------------------------------------------------------------
  4082. void CleanPolygon(Path& poly, double distance)
  4083. {
  4084. CleanPolygon(poly, poly, distance);
  4085. }
  4086. //------------------------------------------------------------------------------
  4087. void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance)
  4088. {
  4089. out_polys.resize(in_polys.size());
  4090. for (Paths::size_type i = 0; i < in_polys.size(); ++i)
  4091. CleanPolygon(in_polys[i], out_polys[i], distance);
  4092. }
  4093. //------------------------------------------------------------------------------
  4094. void CleanPolygons(Paths& polys, double distance)
  4095. {
  4096. CleanPolygons(polys, polys, distance);
  4097. }
  4098. //------------------------------------------------------------------------------
  4099. void Minkowski(const Path& poly, const Path& path,
  4100. Paths& solution, bool isSum, bool isClosed)
  4101. {
  4102. int delta = (isClosed ? 1 : 0);
  4103. size_t polyCnt = poly.size();
  4104. size_t pathCnt = path.size();
  4105. Paths pp;
  4106. pp.reserve(pathCnt);
  4107. if (isSum)
  4108. for (size_t i = 0; i < pathCnt; ++i)
  4109. {
  4110. Path p;
  4111. p.reserve(polyCnt);
  4112. for (size_t j = 0; j < poly.size(); ++j)
  4113. p.push_back(IntPoint(path[i].X + poly[j].X, path[i].Y + poly[j].Y));
  4114. pp.push_back(p);
  4115. }
  4116. else
  4117. for (size_t i = 0; i < pathCnt; ++i)
  4118. {
  4119. Path p;
  4120. p.reserve(polyCnt);
  4121. for (size_t j = 0; j < poly.size(); ++j)
  4122. p.push_back(IntPoint(path[i].X - poly[j].X, path[i].Y - poly[j].Y));
  4123. pp.push_back(p);
  4124. }
  4125. solution.clear();
  4126. solution.reserve((pathCnt + delta) * (polyCnt + 1));
  4127. for (size_t i = 0; i < pathCnt - 1 + delta; ++i)
  4128. for (size_t j = 0; j < polyCnt; ++j)
  4129. {
  4130. Path quad;
  4131. quad.reserve(4);
  4132. quad.push_back(pp[i % pathCnt][j % polyCnt]);
  4133. quad.push_back(pp[(i + 1) % pathCnt][j % polyCnt]);
  4134. quad.push_back(pp[(i + 1) % pathCnt][(j + 1) % polyCnt]);
  4135. quad.push_back(pp[i % pathCnt][(j + 1) % polyCnt]);
  4136. if (!Orientation(quad)) ReversePath(quad);
  4137. solution.push_back(quad);
  4138. }
  4139. }
  4140. //------------------------------------------------------------------------------
  4141. void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed)
  4142. {
  4143. Minkowski(pattern, path, solution, true, pathIsClosed);
  4144. Clipper c;
  4145. c.AddPaths(solution, ptSubject, true);
  4146. c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
  4147. }
  4148. //------------------------------------------------------------------------------
  4149. void TranslatePath(const Path& input, Path& output, const IntPoint delta)
  4150. {
  4151. //precondition: input != output
  4152. output.resize(input.size());
  4153. for (size_t i = 0; i < input.size(); ++i)
  4154. output[i] = IntPoint(input[i].X + delta.X, input[i].Y + delta.Y);
  4155. }
  4156. //------------------------------------------------------------------------------
  4157. void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed)
  4158. {
  4159. Clipper c;
  4160. for (size_t i = 0; i < paths.size(); ++i)
  4161. {
  4162. Paths tmp;
  4163. Minkowski(pattern, paths[i], tmp, true, pathIsClosed);
  4164. c.AddPaths(tmp, ptSubject, true);
  4165. if (pathIsClosed)
  4166. {
  4167. Path tmp2;
  4168. TranslatePath(paths[i], tmp2, pattern[0]);
  4169. c.AddPath(tmp2, ptClip, true);
  4170. }
  4171. }
  4172. c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
  4173. }
  4174. //------------------------------------------------------------------------------
  4175. void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution)
  4176. {
  4177. Minkowski(poly1, poly2, solution, false, true);
  4178. Clipper c;
  4179. c.AddPaths(solution, ptSubject, true);
  4180. c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
  4181. }
  4182. //------------------------------------------------------------------------------
  4183. enum NodeType {ntAny, ntOpen, ntClosed};
  4184. void AddPolyNodeToPaths(const PolyNode& polynode, NodeType nodetype, Paths& paths)
  4185. {
  4186. bool match = true;
  4187. if (nodetype == ntClosed) match = !polynode.IsOpen();
  4188. else if (nodetype == ntOpen) return;
  4189. if (!polynode.Contour.empty() && match)
  4190. paths.push_back(polynode.Contour);
  4191. for (int i = 0; i < polynode.ChildCount(); ++i)
  4192. AddPolyNodeToPaths(*polynode.Childs[i], nodetype, paths);
  4193. }
  4194. //------------------------------------------------------------------------------
  4195. void PolyTreeToPaths(const PolyTree& polytree, Paths& paths)
  4196. {
  4197. paths.resize(0);
  4198. paths.reserve(polytree.Total());
  4199. AddPolyNodeToPaths(polytree, ntAny, paths);
  4200. }
  4201. //------------------------------------------------------------------------------
  4202. void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths)
  4203. {
  4204. paths.resize(0);
  4205. paths.reserve(polytree.Total());
  4206. AddPolyNodeToPaths(polytree, ntClosed, paths);
  4207. }
  4208. //------------------------------------------------------------------------------
  4209. void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths)
  4210. {
  4211. paths.resize(0);
  4212. paths.reserve(polytree.Total());
  4213. //Open paths are top level only, so ...
  4214. for (int i = 0; i < polytree.ChildCount(); ++i)
  4215. if (polytree.Childs[i]->IsOpen())
  4216. paths.push_back(polytree.Childs[i]->Contour);
  4217. }
  4218. //------------------------------------------------------------------------------
  4219. std::ostream& operator <<(std::ostream &s, const IntPoint &p)
  4220. {
  4221. s << "(" << p.X << "," << p.Y << ")";
  4222. return s;
  4223. }
  4224. //------------------------------------------------------------------------------
  4225. std::ostream& operator <<(std::ostream &s, const Path &p)
  4226. {
  4227. if (p.empty()) return s;
  4228. Path::size_type last = p.size() -1;
  4229. for (Path::size_type i = 0; i < last; i++)
  4230. s << "(" << p[i].X << "," << p[i].Y << "), ";
  4231. s << "(" << p[last].X << "," << p[last].Y << ")\n";
  4232. return s;
  4233. }
  4234. //------------------------------------------------------------------------------
  4235. std::ostream& operator <<(std::ostream &s, const Paths &p)
  4236. {
  4237. for (Paths::size_type i = 0; i < p.size(); i++)
  4238. s << p[i];
  4239. s << "\n";
  4240. return s;
  4241. }
  4242. //------------------------------------------------------------------------------
  4243. } //ClipperLib namespace