暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

clipper.cs 164KB

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