camlib.py 226 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ########################################################## ##
  8. from PyQt5 import QtWidgets
  9. from io import StringIO
  10. import numpy as np
  11. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos, dot, float32, \
  12. transpose
  13. from numpy.linalg import solve, norm
  14. import re, sys, os, platform
  15. import math
  16. from copy import deepcopy
  17. import traceback
  18. from decimal import Decimal
  19. from rtree import index as rtindex
  20. from lxml import etree as ET
  21. # See: http://toblerity.org/shapely/manual.html
  22. from shapely.geometry import Polygon, LineString, Point, LinearRing, MultiLineString
  23. from shapely.geometry import MultiPoint, MultiPolygon
  24. from shapely.geometry import box as shply_box
  25. from shapely.ops import cascaded_union, unary_union, polygonize
  26. import shapely.affinity as affinity
  27. from shapely.wkt import loads as sloads
  28. from shapely.wkt import dumps as sdumps
  29. from shapely.geometry.base import BaseGeometry
  30. from shapely.geometry import shape
  31. # needed for legacy mode
  32. # Used for solid polygons in Matplotlib
  33. from descartes.patch import PolygonPatch
  34. import collections
  35. from collections import Iterable
  36. import rasterio
  37. from rasterio.features import shapes
  38. import ezdxf
  39. # TODO: Commented for FlatCAM packaging with cx_freeze
  40. # from scipy.spatial import KDTree, Delaunay
  41. # from scipy.spatial import Delaunay
  42. from flatcamParsers.ParseSVG import *
  43. from flatcamParsers.ParseDXF import *
  44. if platform.architecture()[0] == '64bit':
  45. from ortools.constraint_solver import pywrapcp
  46. from ortools.constraint_solver import routing_enums_pb2
  47. import logging
  48. import FlatCAMApp
  49. import gettext
  50. import FlatCAMTranslation as fcTranslate
  51. import builtins
  52. fcTranslate.apply_language('strings')
  53. log = logging.getLogger('base2')
  54. log.setLevel(logging.DEBUG)
  55. formatter = logging.Formatter('[%(levelname)s] %(message)s')
  56. handler = logging.StreamHandler()
  57. handler.setFormatter(formatter)
  58. log.addHandler(handler)
  59. if '_' not in builtins.__dict__:
  60. _ = gettext.gettext
  61. class ParseError(Exception):
  62. pass
  63. class ApertureMacro:
  64. """
  65. Syntax of aperture macros.
  66. <AM command>: AM<Aperture macro name>*<Macro content>
  67. <Macro content>: {{<Variable definition>*}{<Primitive>*}}
  68. <Variable definition>: $K=<Arithmetic expression>
  69. <Primitive>: <Primitive code>,<Modifier>{,<Modifier>}|<Comment>
  70. <Modifier>: $M|< Arithmetic expression>
  71. <Comment>: 0 <Text>
  72. """
  73. # ## Regular expressions
  74. am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  75. am2_re = re.compile(r'(.*)%$')
  76. amcomm_re = re.compile(r'^0(.*)')
  77. amprim_re = re.compile(r'^[1-9].*')
  78. amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
  79. def __init__(self, name=None):
  80. self.name = name
  81. self.raw = ""
  82. # ## These below are recomputed for every aperture
  83. # ## definition, in other words, are temporary variables.
  84. self.primitives = []
  85. self.locvars = {}
  86. self.geometry = None
  87. def to_dict(self):
  88. """
  89. Returns the object in a serializable form. Only the name and
  90. raw are required.
  91. :return: Dictionary representing the object. JSON ready.
  92. :rtype: dict
  93. """
  94. return {
  95. 'name': self.name,
  96. 'raw': self.raw
  97. }
  98. def from_dict(self, d):
  99. """
  100. Populates the object from a serial representation created
  101. with ``self.to_dict()``.
  102. :param d: Serial representation of an ApertureMacro object.
  103. :return: None
  104. """
  105. for attr in ['name', 'raw']:
  106. setattr(self, attr, d[attr])
  107. def parse_content(self):
  108. """
  109. Creates numerical lists for all primitives in the aperture
  110. macro (in ``self.raw``) by replacing all variables by their
  111. values iteratively and evaluating expressions. Results
  112. are stored in ``self.primitives``.
  113. :return: None
  114. """
  115. # Cleanup
  116. self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
  117. self.primitives = []
  118. # Separate parts
  119. parts = self.raw.split('*')
  120. # ### Every part in the macro ####
  121. for part in parts:
  122. # ## Comments. Ignored.
  123. match = ApertureMacro.amcomm_re.search(part)
  124. if match:
  125. continue
  126. # ## Variables
  127. # These are variables defined locally inside the macro. They can be
  128. # numerical constant or defind in terms of previously define
  129. # variables, which can be defined locally or in an aperture
  130. # definition. All replacements ocurr here.
  131. match = ApertureMacro.amvar_re.search(part)
  132. if match:
  133. var = match.group(1)
  134. val = match.group(2)
  135. # Replace variables in value
  136. for v in self.locvars:
  137. # replaced the following line with the next to fix Mentor custom apertures not parsed OK
  138. # val = re.sub((r'\$'+str(v)+r'(?![0-9a-zA-Z])'), str(self.locvars[v]), val)
  139. val = val.replace('$' + str(v), str(self.locvars[v]))
  140. # Make all others 0
  141. val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
  142. # Change x with *
  143. val = re.sub(r'[xX]', "*", val)
  144. # Eval() and store.
  145. self.locvars[var] = eval(val)
  146. continue
  147. # ## Primitives
  148. # Each is an array. The first identifies the primitive, while the
  149. # rest depend on the primitive. All are strings representing a
  150. # number and may contain variable definition. The values of these
  151. # variables are defined in an aperture definition.
  152. match = ApertureMacro.amprim_re.search(part)
  153. if match:
  154. # ## Replace all variables
  155. for v in self.locvars:
  156. # replaced the following line with the next to fix Mentor custom apertures not parsed OK
  157. # part = re.sub(r'\$' + str(v) + r'(?![0-9a-zA-Z])', str(self.locvars[v]), part)
  158. part = part.replace('$' + str(v), str(self.locvars[v]))
  159. # Make all others 0
  160. part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
  161. # Change x with *
  162. part = re.sub(r'[xX]', "*", part)
  163. # ## Store
  164. elements = part.split(",")
  165. self.primitives.append([eval(x) for x in elements])
  166. continue
  167. log.warning("Unknown syntax of aperture macro part: %s" % str(part))
  168. def append(self, data):
  169. """
  170. Appends a string to the raw macro.
  171. :param data: Part of the macro.
  172. :type data: str
  173. :return: None
  174. """
  175. self.raw += data
  176. @staticmethod
  177. def default2zero(n, mods):
  178. """
  179. Pads the ``mods`` list with zeros resulting in an
  180. list of length n.
  181. :param n: Length of the resulting list.
  182. :type n: int
  183. :param mods: List to be padded.
  184. :type mods: list
  185. :return: Zero-padded list.
  186. :rtype: list
  187. """
  188. x = [0.0] * n
  189. na = len(mods)
  190. x[0:na] = mods
  191. return x
  192. @staticmethod
  193. def make_circle(mods):
  194. """
  195. :param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
  196. :return:
  197. """
  198. pol, dia, x, y = ApertureMacro.default2zero(4, mods)
  199. return {"pol": int(pol), "geometry": Point(x, y).buffer(dia/2)}
  200. @staticmethod
  201. def make_vectorline(mods):
  202. """
  203. :param mods: (Exposure 0/1, Line width >= 0, X-start, Y-start, X-end, Y-end,
  204. rotation angle around origin in degrees)
  205. :return:
  206. """
  207. pol, width, xs, ys, xe, ye, angle = ApertureMacro.default2zero(7, mods)
  208. line = LineString([(xs, ys), (xe, ye)])
  209. box = line.buffer(width/2, cap_style=2)
  210. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  211. return {"pol": int(pol), "geometry": box_rotated}
  212. @staticmethod
  213. def make_centerline(mods):
  214. """
  215. :param mods: (Exposure 0/1, width >=0, height >=0, x-center, y-center,
  216. rotation angle around origin in degrees)
  217. :return:
  218. """
  219. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  220. box = shply_box(x-width/2, y-height/2, x+width/2, y+height/2)
  221. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  222. return {"pol": int(pol), "geometry": box_rotated}
  223. @staticmethod
  224. def make_lowerleftline(mods):
  225. """
  226. :param mods: (exposure 0/1, width >=0, height >=0, x-lowerleft, y-lowerleft,
  227. rotation angle around origin in degrees)
  228. :return:
  229. """
  230. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  231. box = shply_box(x, y, x+width, y+height)
  232. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  233. return {"pol": int(pol), "geometry": box_rotated}
  234. @staticmethod
  235. def make_outline(mods):
  236. """
  237. :param mods:
  238. :return:
  239. """
  240. pol = mods[0]
  241. n = mods[1]
  242. points = [(0, 0)]*(n+1)
  243. for i in range(n+1):
  244. points[i] = mods[2*i + 2:2*i + 4]
  245. angle = mods[2*n + 4]
  246. poly = Polygon(points)
  247. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  248. return {"pol": int(pol), "geometry": poly_rotated}
  249. @staticmethod
  250. def make_polygon(mods):
  251. """
  252. Note: Specs indicate that rotation is only allowed if the center
  253. (x, y) == (0, 0). I will tolerate breaking this rule.
  254. :param mods: (exposure 0/1, n_verts 3<=n<=12, x-center, y-center,
  255. diameter of circumscribed circle >=0, rotation angle around origin)
  256. :return:
  257. """
  258. pol, nverts, x, y, dia, angle = ApertureMacro.default2zero(6, mods)
  259. points = [(0, 0)]*nverts
  260. for i in range(nverts):
  261. points[i] = (x + 0.5 * dia * cos(2*pi * i/nverts),
  262. y + 0.5 * dia * sin(2*pi * i/nverts))
  263. poly = Polygon(points)
  264. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  265. return {"pol": int(pol), "geometry": poly_rotated}
  266. @staticmethod
  267. def make_moire(mods):
  268. """
  269. Note: Specs indicate that rotation is only allowed if the center
  270. (x, y) == (0, 0). I will tolerate breaking this rule.
  271. :param mods: (x-center, y-center, outer_dia_outer_ring, ring thickness,
  272. gap, max_rings, crosshair_thickness, crosshair_len, rotation
  273. angle around origin in degrees)
  274. :return:
  275. """
  276. x, y, dia, thickness, gap, nrings, cross_th, cross_len, angle = ApertureMacro.default2zero(9, mods)
  277. r = dia/2 - thickness/2
  278. result = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  279. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0) # Need a copy!
  280. i = 1 # Number of rings created so far
  281. # ## If the ring does not have an interior it means that it is
  282. # ## a disk. Then stop.
  283. while len(ring.interiors) > 0 and i < nrings:
  284. r -= thickness + gap
  285. if r <= 0:
  286. break
  287. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  288. result = cascaded_union([result, ring])
  289. i += 1
  290. # ## Crosshair
  291. hor = LineString([(x - cross_len, y), (x + cross_len, y)]).buffer(cross_th/2.0, cap_style=2)
  292. ver = LineString([(x, y-cross_len), (x, y + cross_len)]).buffer(cross_th/2.0, cap_style=2)
  293. result = cascaded_union([result, hor, ver])
  294. return {"pol": 1, "geometry": result}
  295. @staticmethod
  296. def make_thermal(mods):
  297. """
  298. Note: Specs indicate that rotation is only allowed if the center
  299. (x, y) == (0, 0). I will tolerate breaking this rule.
  300. :param mods: [x-center, y-center, diameter-outside, diameter-inside,
  301. gap-thickness, rotation angle around origin]
  302. :return:
  303. """
  304. x, y, dout, din, t, angle = ApertureMacro.default2zero(6, mods)
  305. ring = Point((x, y)).buffer(dout/2.0).difference(Point((x, y)).buffer(din/2.0))
  306. hline = LineString([(x - dout/2.0, y), (x + dout/2.0, y)]).buffer(t/2.0, cap_style=3)
  307. vline = LineString([(x, y - dout/2.0), (x, y + dout/2.0)]).buffer(t/2.0, cap_style=3)
  308. thermal = ring.difference(hline.union(vline))
  309. return {"pol": 1, "geometry": thermal}
  310. def make_geometry(self, modifiers):
  311. """
  312. Runs the macro for the given modifiers and generates
  313. the corresponding geometry.
  314. :param modifiers: Modifiers (parameters) for this macro
  315. :type modifiers: list
  316. :return: Shapely geometry
  317. :rtype: shapely.geometry.polygon
  318. """
  319. # ## Primitive makers
  320. makers = {
  321. "1": ApertureMacro.make_circle,
  322. "2": ApertureMacro.make_vectorline,
  323. "20": ApertureMacro.make_vectorline,
  324. "21": ApertureMacro.make_centerline,
  325. "22": ApertureMacro.make_lowerleftline,
  326. "4": ApertureMacro.make_outline,
  327. "5": ApertureMacro.make_polygon,
  328. "6": ApertureMacro.make_moire,
  329. "7": ApertureMacro.make_thermal
  330. }
  331. # ## Store modifiers as local variables
  332. modifiers = modifiers or []
  333. modifiers = [float(m) for m in modifiers]
  334. self.locvars = {}
  335. for i in range(0, len(modifiers)):
  336. self.locvars[str(i + 1)] = modifiers[i]
  337. # ## Parse
  338. self.primitives = [] # Cleanup
  339. self.geometry = Polygon()
  340. self.parse_content()
  341. # ## Make the geometry
  342. for primitive in self.primitives:
  343. # Make the primitive
  344. prim_geo = makers[str(int(primitive[0]))](primitive[1:])
  345. # Add it (according to polarity)
  346. # if self.geometry is None and prim_geo['pol'] == 1:
  347. # self.geometry = prim_geo['geometry']
  348. # continue
  349. if prim_geo['pol'] == 1:
  350. self.geometry = self.geometry.union(prim_geo['geometry'])
  351. continue
  352. if prim_geo['pol'] == 0:
  353. self.geometry = self.geometry.difference(prim_geo['geometry'])
  354. continue
  355. return self.geometry
  356. class Geometry(object):
  357. """
  358. Base geometry class.
  359. """
  360. defaults = {
  361. "units": 'in',
  362. "geo_steps_per_circle": 128
  363. }
  364. def __init__(self, geo_steps_per_circle=None):
  365. # Units (in or mm)
  366. self.units = self.app.defaults["units"]
  367. # Final geometry: MultiPolygon or list (of geometry constructs)
  368. self.solid_geometry = None
  369. # Final geometry: MultiLineString or list (of LineString or Points)
  370. self.follow_geometry = None
  371. # Attributes to be included in serialization
  372. self.ser_attrs = ["units", 'solid_geometry', 'follow_geometry']
  373. # Flattened geometry (list of paths only)
  374. self.flat_geometry = []
  375. # this is the calculated conversion factor when the file units are different than the ones in the app
  376. self.file_units_factor = 1
  377. # Index
  378. self.index = None
  379. self.geo_steps_per_circle = geo_steps_per_circle
  380. # variables to display the percentage of work done
  381. self.geo_len = 0
  382. self.old_disp_number = 0
  383. self.el_count = 0
  384. if self.app.is_legacy is False:
  385. self.temp_shapes = self.app.plotcanvas.new_shape_group()
  386. else:
  387. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  388. self.temp_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='camlib.geometry')
  389. # if geo_steps_per_circle is None:
  390. # geo_steps_per_circle = int(Geometry.defaults["geo_steps_per_circle"])
  391. # self.geo_steps_per_circle = geo_steps_per_circle
  392. def plot_temp_shapes(self, element, color='red'):
  393. try:
  394. for sub_el in element:
  395. self.plot_temp_shapes(sub_el)
  396. except TypeError: # Element is not iterable...
  397. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  398. self.temp_shapes.add(tolerance=float(self.app.defaults["global_tolerance"]),
  399. shape=element, color=color, visible=True, layer=0)
  400. def make_index(self):
  401. self.flatten()
  402. self.index = FlatCAMRTree()
  403. for i, g in enumerate(self.flat_geometry):
  404. self.index.insert(i, g)
  405. def add_circle(self, origin, radius):
  406. """
  407. Adds a circle to the object.
  408. :param origin: Center of the circle.
  409. :param radius: Radius of the circle.
  410. :return: None
  411. """
  412. if self.solid_geometry is None:
  413. self.solid_geometry = []
  414. if type(self.solid_geometry) is list:
  415. self.solid_geometry.append(Point(origin).buffer(
  416. radius, int(int(self.geo_steps_per_circle) / 4)))
  417. return
  418. try:
  419. self.solid_geometry = self.solid_geometry.union(Point(origin).buffer(
  420. radius, int(int(self.geo_steps_per_circle) / 4)))
  421. except Exception as e:
  422. log.error("Failed to run union on polygons. %s" % str(e))
  423. return
  424. def add_polygon(self, points):
  425. """
  426. Adds a polygon to the object (by union)
  427. :param points: The vertices of the polygon.
  428. :return: None
  429. """
  430. if self.solid_geometry is None:
  431. self.solid_geometry = []
  432. if type(self.solid_geometry) is list:
  433. self.solid_geometry.append(Polygon(points))
  434. return
  435. try:
  436. self.solid_geometry = self.solid_geometry.union(Polygon(points))
  437. except Exception as e:
  438. log.error("Failed to run union on polygons. %s" % str(e))
  439. return
  440. def add_polyline(self, points):
  441. """
  442. Adds a polyline to the object (by union)
  443. :param points: The vertices of the polyline.
  444. :return: None
  445. """
  446. if self.solid_geometry is None:
  447. self.solid_geometry = []
  448. if type(self.solid_geometry) is list:
  449. self.solid_geometry.append(LineString(points))
  450. return
  451. try:
  452. self.solid_geometry = self.solid_geometry.union(LineString(points))
  453. except Exception as e:
  454. log.error("Failed to run union on polylines. %s" % str(e))
  455. return
  456. def is_empty(self):
  457. if isinstance(self.solid_geometry, BaseGeometry):
  458. return self.solid_geometry.is_empty
  459. if isinstance(self.solid_geometry, list):
  460. return len(self.solid_geometry) == 0
  461. self.app.inform.emit('[ERROR_NOTCL] %s' %
  462. _("self.solid_geometry is neither BaseGeometry or list."))
  463. return
  464. def subtract_polygon(self, points):
  465. """
  466. Subtract polygon from the given object. This only operates on the paths in the original geometry,
  467. i.e. it converts polygons into paths.
  468. :param points: The vertices of the polygon.
  469. :return: none
  470. """
  471. if self.solid_geometry is None:
  472. self.solid_geometry = []
  473. # pathonly should be allways True, otherwise polygons are not subtracted
  474. flat_geometry = self.flatten(pathonly=True)
  475. log.debug("%d paths" % len(flat_geometry))
  476. polygon = Polygon(points)
  477. toolgeo = cascaded_union(polygon)
  478. diffs = []
  479. for target in flat_geometry:
  480. if type(target) == LineString or type(target) == LinearRing:
  481. diffs.append(target.difference(toolgeo))
  482. else:
  483. log.warning("Not implemented.")
  484. self.solid_geometry = cascaded_union(diffs)
  485. def bounds(self):
  486. """
  487. Returns coordinates of rectangular bounds
  488. of geometry: (xmin, ymin, xmax, ymax).
  489. """
  490. # fixed issue of getting bounds only for one level lists of objects
  491. # now it can get bounds for nested lists of objects
  492. log.debug("camlib.Geometry.bounds()")
  493. if self.solid_geometry is None:
  494. log.debug("solid_geometry is None")
  495. return 0, 0, 0, 0
  496. def bounds_rec(obj):
  497. if type(obj) is list:
  498. minx = Inf
  499. miny = Inf
  500. maxx = -Inf
  501. maxy = -Inf
  502. for k in obj:
  503. if type(k) is dict:
  504. for key in k:
  505. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  506. minx = min(minx, minx_)
  507. miny = min(miny, miny_)
  508. maxx = max(maxx, maxx_)
  509. maxy = max(maxy, maxy_)
  510. else:
  511. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  512. minx = min(minx, minx_)
  513. miny = min(miny, miny_)
  514. maxx = max(maxx, maxx_)
  515. maxy = max(maxy, maxy_)
  516. return minx, miny, maxx, maxy
  517. else:
  518. # it's a Shapely object, return it's bounds
  519. return obj.bounds
  520. if self.multigeo is True:
  521. minx_list = []
  522. miny_list = []
  523. maxx_list = []
  524. maxy_list = []
  525. for tool in self.tools:
  526. minx, miny, maxx, maxy = bounds_rec(self.tools[tool]['solid_geometry'])
  527. minx_list.append(minx)
  528. miny_list.append(miny)
  529. maxx_list.append(maxx)
  530. maxy_list.append(maxy)
  531. return(min(minx_list), min(miny_list), max(maxx_list), max(maxy_list))
  532. else:
  533. bounds_coords = bounds_rec(self.solid_geometry)
  534. return bounds_coords
  535. # try:
  536. # # from here: http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html
  537. # def flatten(l, ltypes=(list, tuple)):
  538. # ltype = type(l)
  539. # l = list(l)
  540. # i = 0
  541. # while i < len(l):
  542. # while isinstance(l[i], ltypes):
  543. # if not l[i]:
  544. # l.pop(i)
  545. # i -= 1
  546. # break
  547. # else:
  548. # l[i:i + 1] = l[i]
  549. # i += 1
  550. # return ltype(l)
  551. #
  552. # log.debug("Geometry->bounds()")
  553. # if self.solid_geometry is None:
  554. # log.debug("solid_geometry is None")
  555. # return 0, 0, 0, 0
  556. #
  557. # if type(self.solid_geometry) is list:
  558. # # TODO: This can be done faster. See comment from Shapely mailing lists.
  559. # if len(self.solid_geometry) == 0:
  560. # log.debug('solid_geometry is empty []')
  561. # return 0, 0, 0, 0
  562. # return cascaded_union(flatten(self.solid_geometry)).bounds
  563. # else:
  564. # return self.solid_geometry.bounds
  565. # except Exception as e:
  566. # self.app.inform.emit("[ERROR_NOTCL] Error cause: %s" % str(e))
  567. # log.debug("Geometry->bounds()")
  568. # if self.solid_geometry is None:
  569. # log.debug("solid_geometry is None")
  570. # return 0, 0, 0, 0
  571. #
  572. # if type(self.solid_geometry) is list:
  573. # # TODO: This can be done faster. See comment from Shapely mailing lists.
  574. # if len(self.solid_geometry) == 0:
  575. # log.debug('solid_geometry is empty []')
  576. # return 0, 0, 0, 0
  577. # return cascaded_union(self.solid_geometry).bounds
  578. # else:
  579. # return self.solid_geometry.bounds
  580. def find_polygon(self, point, geoset=None):
  581. """
  582. Find an object that object.contains(Point(point)) in
  583. poly, which can can be iterable, contain iterable of, or
  584. be itself an implementer of .contains().
  585. :param point: See description
  586. :param geoset: a polygon or list of polygons where to find if the param point is contained
  587. :return: Polygon containing point or None.
  588. """
  589. if geoset is None:
  590. geoset = self.solid_geometry
  591. try: # Iterable
  592. for sub_geo in geoset:
  593. p = self.find_polygon(point, geoset=sub_geo)
  594. if p is not None:
  595. return p
  596. except TypeError: # Non-iterable
  597. try: # Implements .contains()
  598. if isinstance(geoset, LinearRing):
  599. geoset = Polygon(geoset)
  600. if geoset.contains(Point(point)):
  601. return geoset
  602. except AttributeError: # Does not implement .contains()
  603. return None
  604. return None
  605. def get_interiors(self, geometry=None):
  606. interiors = []
  607. if geometry is None:
  608. geometry = self.solid_geometry
  609. # ## If iterable, expand recursively.
  610. try:
  611. for geo in geometry:
  612. interiors.extend(self.get_interiors(geometry=geo))
  613. # ## Not iterable, get the interiors if polygon.
  614. except TypeError:
  615. if type(geometry) == Polygon:
  616. interiors.extend(geometry.interiors)
  617. return interiors
  618. def get_exteriors(self, geometry=None):
  619. """
  620. Returns all exteriors of polygons in geometry. Uses
  621. ``self.solid_geometry`` if geometry is not provided.
  622. :param geometry: Shapely type or list or list of list of such.
  623. :return: List of paths constituting the exteriors
  624. of polygons in geometry.
  625. """
  626. exteriors = []
  627. if geometry is None:
  628. geometry = self.solid_geometry
  629. # ## If iterable, expand recursively.
  630. try:
  631. for geo in geometry:
  632. exteriors.extend(self.get_exteriors(geometry=geo))
  633. # ## Not iterable, get the exterior if polygon.
  634. except TypeError:
  635. if type(geometry) == Polygon:
  636. exteriors.append(geometry.exterior)
  637. return exteriors
  638. def flatten(self, geometry=None, reset=True, pathonly=False):
  639. """
  640. Creates a list of non-iterable linear geometry objects.
  641. Polygons are expanded into its exterior and interiors if specified.
  642. Results are placed in self.flat_geometry
  643. :param geometry: Shapely type or list or list of list of such.
  644. :param reset: Clears the contents of self.flat_geometry.
  645. :param pathonly: Expands polygons into linear elements.
  646. """
  647. if geometry is None:
  648. geometry = self.solid_geometry
  649. if reset:
  650. self.flat_geometry = []
  651. # ## If iterable, expand recursively.
  652. try:
  653. for geo in geometry:
  654. if geo is not None:
  655. self.flatten(geometry=geo,
  656. reset=False,
  657. pathonly=pathonly)
  658. # ## Not iterable, do the actual indexing and add.
  659. except TypeError:
  660. if pathonly and type(geometry) == Polygon:
  661. self.flat_geometry.append(geometry.exterior)
  662. self.flatten(geometry=geometry.interiors,
  663. reset=False,
  664. pathonly=True)
  665. else:
  666. self.flat_geometry.append(geometry)
  667. return self.flat_geometry
  668. # def make2Dstorage(self):
  669. #
  670. # self.flatten()
  671. #
  672. # def get_pts(o):
  673. # pts = []
  674. # if type(o) == Polygon:
  675. # g = o.exterior
  676. # pts += list(g.coords)
  677. # for i in o.interiors:
  678. # pts += list(i.coords)
  679. # else:
  680. # pts += list(o.coords)
  681. # return pts
  682. #
  683. # storage = FlatCAMRTreeStorage()
  684. # storage.get_points = get_pts
  685. # for shape in self.flat_geometry:
  686. # storage.insert(shape)
  687. # return storage
  688. # def flatten_to_paths(self, geometry=None, reset=True):
  689. # """
  690. # Creates a list of non-iterable linear geometry elements and
  691. # indexes them in rtree.
  692. #
  693. # :param geometry: Iterable geometry
  694. # :param reset: Wether to clear (True) or append (False) to self.flat_geometry
  695. # :return: self.flat_geometry, self.flat_geometry_rtree
  696. # """
  697. #
  698. # if geometry is None:
  699. # geometry = self.solid_geometry
  700. #
  701. # if reset:
  702. # self.flat_geometry = []
  703. #
  704. # # ## If iterable, expand recursively.
  705. # try:
  706. # for geo in geometry:
  707. # self.flatten_to_paths(geometry=geo, reset=False)
  708. #
  709. # # ## Not iterable, do the actual indexing and add.
  710. # except TypeError:
  711. # if type(geometry) == Polygon:
  712. # g = geometry.exterior
  713. # self.flat_geometry.append(g)
  714. #
  715. # # ## Add first and last points of the path to the index.
  716. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  717. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  718. #
  719. # for interior in geometry.interiors:
  720. # g = interior
  721. # self.flat_geometry.append(g)
  722. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  723. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  724. # else:
  725. # g = geometry
  726. # self.flat_geometry.append(g)
  727. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  728. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  729. #
  730. # return self.flat_geometry, self.flat_geometry_rtree
  731. def isolation_geometry(self, offset, iso_type=2, corner=None, follow=None, passes=0):
  732. """
  733. Creates contours around geometry at a given
  734. offset distance.
  735. :param offset: Offset distance.
  736. :type offset: float
  737. :param iso_type: type of isolation, can be 0 = exteriors or 1 = interiors or 2 = both (complete)
  738. :param corner: type of corner for the isolation: 0 = round; 1 = square; 2= beveled (line that connects the ends)
  739. :param follow: whether the geometry to be isolated is a follow_geometry
  740. :param passes: current pass out of possible multiple passes for which the isolation is done
  741. :return: The buffered geometry.
  742. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  743. """
  744. if self.app.abort_flag:
  745. # graceful abort requested by the user
  746. raise FlatCAMApp.GracefulException
  747. geo_iso = []
  748. if offset == 0:
  749. if follow:
  750. geo_iso = self.follow_geometry
  751. else:
  752. geo_iso = self.solid_geometry
  753. else:
  754. if follow:
  755. geo_iso = self.follow_geometry
  756. else:
  757. if isinstance(self.solid_geometry, list):
  758. temp_geo = cascaded_union(self.solid_geometry)
  759. else:
  760. temp_geo = self.solid_geometry
  761. # Remember: do not make a buffer for each element in the solid_geometry because it will cut into
  762. # other copper features
  763. # if corner is None:
  764. # geo_iso = temp_geo.buffer(offset, int(int(self.geo_steps_per_circle) / 4))
  765. # else:
  766. # geo_iso = temp_geo.buffer(offset, int(int(self.geo_steps_per_circle) / 4),
  767. # join_style=corner)
  768. # variables to display the percentage of work done
  769. geo_len = 0
  770. try:
  771. for pol in self.solid_geometry:
  772. geo_len += 1
  773. except TypeError:
  774. geo_len = 1
  775. disp_number = 0
  776. old_disp_number = 0
  777. pol_nr = 0
  778. # yet, it can be done by issuing an unary_union in the end, thus getting rid of the overlapping geo
  779. try:
  780. for pol in self.solid_geometry:
  781. if self.app.abort_flag:
  782. # graceful abort requested by the user
  783. raise FlatCAMApp.GracefulException
  784. if corner is None:
  785. geo_iso.append(pol.buffer(offset, int(int(self.geo_steps_per_circle) / 4)))
  786. else:
  787. geo_iso.append(pol.buffer(offset, int(int(self.geo_steps_per_circle) / 4)),
  788. join_style=corner)
  789. pol_nr += 1
  790. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  791. if old_disp_number < disp_number <= 100:
  792. self.app.proc_container.update_view_text(' %s %d: %d%%' %
  793. (_("Pass"), int(passes + 1), int(disp_number)))
  794. old_disp_number = disp_number
  795. except TypeError:
  796. # taking care of the case when the self.solid_geometry is just a single Polygon, not a list or a
  797. # MultiPolygon (not an iterable)
  798. if corner is None:
  799. geo_iso.append(self.solid_geometry.buffer(offset, int(int(self.geo_steps_per_circle) / 4)))
  800. else:
  801. geo_iso.append(self.solid_geometry.buffer(offset, int(int(self.geo_steps_per_circle) / 4)),
  802. join_style=corner)
  803. self.app.proc_container.update_view_text(' %s' % _("Buffering"))
  804. geo_iso = unary_union(geo_iso)
  805. self.app.proc_container.update_view_text('')
  806. # end of replaced block
  807. if follow:
  808. return geo_iso
  809. elif iso_type == 2:
  810. return geo_iso
  811. elif iso_type == 0:
  812. self.app.proc_container.update_view_text(' %s' % _("Get Exteriors"))
  813. return self.get_exteriors(geo_iso)
  814. elif iso_type == 1:
  815. self.app.proc_container.update_view_text(' %s' % _("Get Interiors"))
  816. return self.get_interiors(geo_iso)
  817. else:
  818. log.debug("Geometry.isolation_geometry() --> Type of isolation not supported")
  819. return "fail"
  820. def flatten_list(self, list):
  821. for item in list:
  822. if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
  823. yield from self.flatten_list(item)
  824. else:
  825. yield item
  826. def import_svg(self, filename, object_type=None, flip=True, units='MM'):
  827. """
  828. Imports shapes from an SVG file into the object's geometry.
  829. :param filename: Path to the SVG file.
  830. :type filename: str
  831. :param object_type: parameter passed further along
  832. :param flip: Flip the vertically.
  833. :type flip: bool
  834. :param units: FlatCAM units
  835. :return: None
  836. """
  837. # Parse into list of shapely objects
  838. svg_tree = ET.parse(filename)
  839. svg_root = svg_tree.getroot()
  840. # Change origin to bottom left
  841. # h = float(svg_root.get('height'))
  842. # w = float(svg_root.get('width'))
  843. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  844. geos = getsvggeo(svg_root, object_type)
  845. if flip:
  846. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  847. # Add to object
  848. if self.solid_geometry is None:
  849. self.solid_geometry = []
  850. if type(self.solid_geometry) is list:
  851. # self.solid_geometry.append(cascaded_union(geos))
  852. if type(geos) is list:
  853. self.solid_geometry += geos
  854. else:
  855. self.solid_geometry.append(geos)
  856. else: # It's shapely geometry
  857. # self.solid_geometry = cascaded_union([self.solid_geometry,
  858. # cascaded_union(geos)])
  859. self.solid_geometry = [self.solid_geometry, geos]
  860. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  861. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  862. geos_text = getsvgtext(svg_root, object_type, units=units)
  863. if geos_text is not None:
  864. geos_text_f = []
  865. if flip:
  866. # Change origin to bottom left
  867. for i in geos_text:
  868. _, minimy, _, maximy = i.bounds
  869. h2 = (maximy - minimy) * 0.5
  870. geos_text_f.append(translate(scale(i, 1.0, -1.0, origin=(0, 0)), yoff=(h + h2)))
  871. if geos_text_f:
  872. self.solid_geometry = self.solid_geometry + geos_text_f
  873. def import_dxf(self, filename, object_type=None, units='MM'):
  874. """
  875. Imports shapes from an DXF file into the object's geometry.
  876. :param filename: Path to the DXF file.
  877. :type filename: str
  878. :param units: Application units
  879. :type flip: str
  880. :return: None
  881. """
  882. # Parse into list of shapely objects
  883. dxf = ezdxf.readfile(filename)
  884. geos = getdxfgeo(dxf)
  885. # Add to object
  886. if self.solid_geometry is None:
  887. self.solid_geometry = []
  888. if type(self.solid_geometry) is list:
  889. if type(geos) is list:
  890. self.solid_geometry += geos
  891. else:
  892. self.solid_geometry.append(geos)
  893. else: # It's shapely geometry
  894. self.solid_geometry = [self.solid_geometry, geos]
  895. # flatten the self.solid_geometry list for import_dxf() to import DXF as Gerber
  896. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  897. if self.solid_geometry is not None:
  898. self.solid_geometry = cascaded_union(self.solid_geometry)
  899. else:
  900. return
  901. # commented until this function is ready
  902. # geos_text = getdxftext(dxf, object_type, units=units)
  903. # if geos_text is not None:
  904. # geos_text_f = []
  905. # self.solid_geometry = [self.solid_geometry, geos_text_f]
  906. def import_image(self, filename, flip=True, units='MM', dpi=96, mode='black', mask=[128, 128, 128, 128]):
  907. """
  908. Imports shapes from an IMAGE file into the object's geometry.
  909. :param filename: Path to the IMAGE file.
  910. :type filename: str
  911. :param flip: Flip the object vertically.
  912. :type flip: bool
  913. :param units: FlatCAM units
  914. :param dpi: dots per inch on the imported image
  915. :param mode: how to import the image: as 'black' or 'color'
  916. :param mask: level of detail for the import
  917. :return: None
  918. """
  919. scale_factor = 0.264583333
  920. if units.lower() == 'mm':
  921. scale_factor = 25.4 / dpi
  922. else:
  923. scale_factor = 1 / dpi
  924. geos = []
  925. unscaled_geos = []
  926. with rasterio.open(filename) as src:
  927. # if filename.lower().rpartition('.')[-1] == 'bmp':
  928. # red = green = blue = src.read(1)
  929. # print("BMP")
  930. # elif filename.lower().rpartition('.')[-1] == 'png':
  931. # red, green, blue, alpha = src.read()
  932. # elif filename.lower().rpartition('.')[-1] == 'jpg':
  933. # red, green, blue = src.read()
  934. red = green = blue = src.read(1)
  935. try:
  936. green = src.read(2)
  937. except Exception as e:
  938. pass
  939. try:
  940. blue = src.read(3)
  941. except Exception as e:
  942. pass
  943. if mode == 'black':
  944. mask_setting = red <= mask[0]
  945. total = red
  946. log.debug("Image import as monochrome.")
  947. else:
  948. mask_setting = (red <= mask[1]) + (green <= mask[2]) + (blue <= mask[3])
  949. total = np.zeros(red.shape, dtype=float32)
  950. for band in red, green, blue:
  951. total += band
  952. total /= 3
  953. log.debug("Image import as colored. Thresholds are: R = %s , G = %s, B = %s" %
  954. (str(mask[1]), str(mask[2]), str(mask[3])))
  955. for geom, val in shapes(total, mask=mask_setting):
  956. unscaled_geos.append(shape(geom))
  957. for g in unscaled_geos:
  958. geos.append(scale(g, scale_factor, scale_factor, origin=(0, 0)))
  959. if flip:
  960. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0))) for g in geos]
  961. # Add to object
  962. if self.solid_geometry is None:
  963. self.solid_geometry = []
  964. if type(self.solid_geometry) is list:
  965. # self.solid_geometry.append(cascaded_union(geos))
  966. if type(geos) is list:
  967. self.solid_geometry += geos
  968. else:
  969. self.solid_geometry.append(geos)
  970. else: # It's shapely geometry
  971. self.solid_geometry = [self.solid_geometry, geos]
  972. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  973. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  974. self.solid_geometry = cascaded_union(self.solid_geometry)
  975. # self.solid_geometry = MultiPolygon(self.solid_geometry)
  976. # self.solid_geometry = self.solid_geometry.buffer(0.00000001)
  977. # self.solid_geometry = self.solid_geometry.buffer(-0.00000001)
  978. def size(self):
  979. """
  980. Returns (width, height) of rectangular
  981. bounds of geometry.
  982. """
  983. if self.solid_geometry is None:
  984. log.warning("Solid_geometry not computed yet.")
  985. return 0
  986. bounds = self.bounds()
  987. return bounds[2] - bounds[0], bounds[3] - bounds[1]
  988. def get_empty_area(self, boundary=None):
  989. """
  990. Returns the complement of self.solid_geometry within
  991. the given boundary polygon. If not specified, it defaults to
  992. the rectangular bounding box of self.solid_geometry.
  993. """
  994. if boundary is None:
  995. boundary = self.solid_geometry.envelope
  996. return boundary.difference(self.solid_geometry)
  997. def clear_polygon(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  998. prog_plot=False):
  999. """
  1000. Creates geometry inside a polygon for a tool to cover
  1001. the whole area.
  1002. This algorithm shrinks the edges of the polygon and takes
  1003. the resulting edges as toolpaths.
  1004. :param polygon: Polygon to clear.
  1005. :param tooldia: Diameter of the tool.
  1006. :param steps_per_circle: number of linear segments to be used to approximate a circle
  1007. :param overlap: Overlap of toolpasses.
  1008. :param connect: Draw lines between disjoint segments to
  1009. minimize tool lifts.
  1010. :param contour: Paint around the edges. Inconsequential in
  1011. this painting method.
  1012. :param prog_plot: boolean; if Ture use the progressive plotting
  1013. :return:
  1014. """
  1015. # log.debug("camlib.clear_polygon()")
  1016. assert type(polygon) == Polygon or type(polygon) == MultiPolygon, \
  1017. "Expected a Polygon or MultiPolygon, got %s" % type(polygon)
  1018. # ## The toolpaths
  1019. # Index first and last points in paths
  1020. def get_pts(o):
  1021. return [o.coords[0], o.coords[-1]]
  1022. geoms = FlatCAMRTreeStorage()
  1023. geoms.get_points = get_pts
  1024. # Can only result in a Polygon or MultiPolygon
  1025. # NOTE: The resulting polygon can be "empty".
  1026. current = polygon.buffer((-tooldia / 1.999999), int(int(steps_per_circle) / 4))
  1027. if current.area == 0:
  1028. # Otherwise, trying to to insert current.exterior == None
  1029. # into the FlatCAMStorage will fail.
  1030. # print("Area is None")
  1031. return None
  1032. # current can be a MultiPolygon
  1033. try:
  1034. for p in current:
  1035. geoms.insert(p.exterior)
  1036. for i in p.interiors:
  1037. geoms.insert(i)
  1038. # Not a Multipolygon. Must be a Polygon
  1039. except TypeError:
  1040. geoms.insert(current.exterior)
  1041. for i in current.interiors:
  1042. geoms.insert(i)
  1043. while True:
  1044. if self.app.abort_flag:
  1045. # graceful abort requested by the user
  1046. raise FlatCAMApp.GracefulException
  1047. # provide the app with a way to process the GUI events when in a blocking loop
  1048. QtWidgets.QApplication.processEvents()
  1049. # Can only result in a Polygon or MultiPolygon
  1050. current = current.buffer(-tooldia * (1 - overlap), int(int(steps_per_circle) / 4))
  1051. if current.area > 0:
  1052. # current can be a MultiPolygon
  1053. try:
  1054. for p in current:
  1055. geoms.insert(p.exterior)
  1056. for i in p.interiors:
  1057. geoms.insert(i)
  1058. if prog_plot:
  1059. self.plot_temp_shapes(p)
  1060. # Not a Multipolygon. Must be a Polygon
  1061. except TypeError:
  1062. geoms.insert(current.exterior)
  1063. if prog_plot:
  1064. self.plot_temp_shapes(current.exterior)
  1065. for i in current.interiors:
  1066. geoms.insert(i)
  1067. if prog_plot:
  1068. self.plot_temp_shapes(i)
  1069. else:
  1070. log.debug("camlib.Geometry.clear_polygon() --> Current Area is zero")
  1071. break
  1072. if prog_plot:
  1073. self.temp_shapes.redraw()
  1074. # Optimization: Reduce lifts
  1075. if connect:
  1076. # log.debug("Reducing tool lifts...")
  1077. geoms = Geometry.paint_connect(geoms, polygon, tooldia, int(steps_per_circle))
  1078. return geoms
  1079. def clear_polygon2(self, polygon_to_clear, tooldia, steps_per_circle, seedpoint=None, overlap=0.15,
  1080. connect=True, contour=True, prog_plot=False):
  1081. """
  1082. Creates geometry inside a polygon for a tool to cover
  1083. the whole area.
  1084. This algorithm starts with a seed point inside the polygon
  1085. and draws circles around it. Arcs inside the polygons are
  1086. valid cuts. Finalizes by cutting around the inside edge of
  1087. the polygon.
  1088. :param polygon_to_clear: Shapely.geometry.Polygon
  1089. :param steps_per_circle: how many linear segments to use to approximate a circle
  1090. :param tooldia: Diameter of the tool
  1091. :param seedpoint: Shapely.geometry.Point or None
  1092. :param overlap: Tool fraction overlap bewteen passes
  1093. :param connect: Connect disjoint segment to minumize tool lifts
  1094. :param contour: Cut countour inside the polygon.
  1095. :return: List of toolpaths covering polygon.
  1096. :rtype: FlatCAMRTreeStorage | None
  1097. :param prog_plot: boolean; if True use the progressive plotting
  1098. """
  1099. # log.debug("camlib.clear_polygon2()")
  1100. # Current buffer radius
  1101. radius = tooldia / 2 * (1 - overlap)
  1102. # ## The toolpaths
  1103. # Index first and last points in paths
  1104. def get_pts(o):
  1105. return [o.coords[0], o.coords[-1]]
  1106. geoms = FlatCAMRTreeStorage()
  1107. geoms.get_points = get_pts
  1108. # Path margin
  1109. path_margin = polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle / 4))
  1110. if path_margin.is_empty or path_margin is None:
  1111. return
  1112. # Estimate good seedpoint if not provided.
  1113. if seedpoint is None:
  1114. seedpoint = path_margin.representative_point()
  1115. # Grow from seed until outside the box. The polygons will
  1116. # never have an interior, so take the exterior LinearRing.
  1117. while True:
  1118. if self.app.abort_flag:
  1119. # graceful abort requested by the user
  1120. raise FlatCAMApp.GracefulException
  1121. # provide the app with a way to process the GUI events when in a blocking loop
  1122. QtWidgets.QApplication.processEvents()
  1123. path = Point(seedpoint).buffer(radius, int(steps_per_circle / 4)).exterior
  1124. path = path.intersection(path_margin)
  1125. # Touches polygon?
  1126. if path.is_empty:
  1127. break
  1128. else:
  1129. # geoms.append(path)
  1130. # geoms.insert(path)
  1131. # path can be a collection of paths.
  1132. try:
  1133. for p in path:
  1134. geoms.insert(p)
  1135. if prog_plot:
  1136. self.plot_temp_shapes(p)
  1137. except TypeError:
  1138. geoms.insert(path)
  1139. if prog_plot:
  1140. self.plot_temp_shapes(path)
  1141. if prog_plot:
  1142. self.temp_shapes.redraw()
  1143. radius += tooldia * (1 - overlap)
  1144. # Clean inside edges (contours) of the original polygon
  1145. if contour:
  1146. outer_edges = [x.exterior for x in autolist(
  1147. polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle / 4)))]
  1148. inner_edges = []
  1149. # Over resulting polygons
  1150. for x in autolist(polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle / 4))):
  1151. for y in x.interiors: # Over interiors of each polygon
  1152. inner_edges.append(y)
  1153. # geoms += outer_edges + inner_edges
  1154. for g in outer_edges + inner_edges:
  1155. geoms.insert(g)
  1156. if prog_plot:
  1157. self.plot_temp_shapes(g)
  1158. if prog_plot:
  1159. self.temp_shapes.redraw()
  1160. # Optimization connect touching paths
  1161. # log.debug("Connecting paths...")
  1162. # geoms = Geometry.path_connect(geoms)
  1163. # Optimization: Reduce lifts
  1164. if connect:
  1165. # log.debug("Reducing tool lifts...")
  1166. geoms = Geometry.paint_connect(geoms, polygon_to_clear, tooldia, steps_per_circle)
  1167. return geoms
  1168. def clear_polygon3(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  1169. prog_plot=False):
  1170. """
  1171. Creates geometry inside a polygon for a tool to cover
  1172. the whole area.
  1173. This algorithm draws horizontal lines inside the polygon.
  1174. :param polygon: The polygon being painted.
  1175. :type polygon: shapely.geometry.Polygon
  1176. :param tooldia: Tool diameter.
  1177. :param steps_per_circle: how many linear segments to use to approximate a circle
  1178. :param overlap: Tool path overlap percentage.
  1179. :param connect: Connect lines to avoid tool lifts.
  1180. :param contour: Paint around the edges.
  1181. :param prog_plot: boolean; if to use the progressive plotting
  1182. :return:
  1183. """
  1184. # log.debug("camlib.clear_polygon3()")
  1185. # ## The toolpaths
  1186. # Index first and last points in paths
  1187. def get_pts(o):
  1188. return [o.coords[0], o.coords[-1]]
  1189. geoms = FlatCAMRTreeStorage()
  1190. geoms.get_points = get_pts
  1191. lines_trimmed = []
  1192. # Bounding box
  1193. left, bot, right, top = polygon.bounds
  1194. margin_poly = polygon.buffer(-tooldia / 1.99999999, (int(steps_per_circle)))
  1195. # First line
  1196. y = top - tooldia / 1.99999999
  1197. while y > bot + tooldia / 1.999999999:
  1198. if self.app.abort_flag:
  1199. # graceful abort requested by the user
  1200. raise FlatCAMApp.GracefulException
  1201. # provide the app with a way to process the GUI events when in a blocking loop
  1202. QtWidgets.QApplication.processEvents()
  1203. line = LineString([(left, y), (right, y)])
  1204. line = line.intersection(margin_poly)
  1205. lines_trimmed.append(line)
  1206. y -= tooldia * (1 - overlap)
  1207. if prog_plot:
  1208. self.plot_temp_shapes(line)
  1209. self.temp_shapes.redraw()
  1210. # Last line
  1211. y = bot + tooldia / 2
  1212. line = LineString([(left, y), (right, y)])
  1213. line = line.intersection(margin_poly)
  1214. for ll in line:
  1215. lines_trimmed.append(ll)
  1216. if prog_plot:
  1217. self.plot_temp_shapes(line)
  1218. # Combine
  1219. # linesgeo = unary_union(lines)
  1220. # Trim to the polygon
  1221. # margin_poly = polygon.buffer(-tooldia / 1.99999999, (int(steps_per_circle)))
  1222. # lines_trimmed = linesgeo.intersection(margin_poly)
  1223. if prog_plot:
  1224. self.temp_shapes.redraw()
  1225. lines_trimmed = unary_union(lines_trimmed)
  1226. # Add lines to storage
  1227. try:
  1228. for line in lines_trimmed:
  1229. geoms.insert(line)
  1230. except TypeError:
  1231. # in case lines_trimmed are not iterable (Linestring, LinearRing)
  1232. geoms.insert(lines_trimmed)
  1233. # Add margin (contour) to storage
  1234. if contour:
  1235. if isinstance(margin_poly, Polygon):
  1236. geoms.insert(margin_poly.exterior)
  1237. if prog_plot:
  1238. self.plot_temp_shapes(margin_poly.exterior)
  1239. for ints in margin_poly.interiors:
  1240. geoms.insert(ints)
  1241. if prog_plot:
  1242. self.plot_temp_shapes(ints)
  1243. elif isinstance(margin_poly, MultiPolygon):
  1244. for poly in margin_poly:
  1245. geoms.insert(poly.exterior)
  1246. if prog_plot:
  1247. self.plot_temp_shapes(poly.exterior)
  1248. for ints in poly.interiors:
  1249. geoms.insert(ints)
  1250. if prog_plot:
  1251. self.plot_temp_shapes(ints)
  1252. if prog_plot:
  1253. self.temp_shapes.redraw()
  1254. # Optimization: Reduce lifts
  1255. if connect:
  1256. # log.debug("Reducing tool lifts...")
  1257. geoms = Geometry.paint_connect(geoms, polygon, tooldia, steps_per_circle)
  1258. return geoms
  1259. def scale(self, xfactor, yfactor, point=None):
  1260. """
  1261. Scales all of the object's geometry by a given factor. Override
  1262. this method.
  1263. :param xfactor: Number by which to scale on X axis.
  1264. :type xfactor: float
  1265. :param yfactor: Number by which to scale on Y axis.
  1266. :type yfactor: float
  1267. :param point: point to be used as reference for scaling; a tuple
  1268. :return: None
  1269. :rtype: None
  1270. """
  1271. return
  1272. def offset(self, vect):
  1273. """
  1274. Offset the geometry by the given vector. Override this method.
  1275. :param vect: (x, y) vector by which to offset the object.
  1276. :type vect: tuple
  1277. :return: None
  1278. """
  1279. return
  1280. @staticmethod
  1281. def paint_connect(storage, boundary, tooldia, steps_per_circle, max_walk=None):
  1282. """
  1283. Connects paths that results in a connection segment that is
  1284. within the paint area. This avoids unnecessary tool lifting.
  1285. :param storage: Geometry to be optimized.
  1286. :type storage: FlatCAMRTreeStorage
  1287. :param boundary: Polygon defining the limits of the paintable area.
  1288. :type boundary: Polygon
  1289. :param tooldia: Tool diameter.
  1290. :rtype tooldia: float
  1291. :param steps_per_circle: how many linear segments to use to approximate a circle
  1292. :param max_walk: Maximum allowable distance without lifting tool.
  1293. :type max_walk: float or None
  1294. :return: Optimized geometry.
  1295. :rtype: FlatCAMRTreeStorage
  1296. """
  1297. # If max_walk is not specified, the maximum allowed is
  1298. # 10 times the tool diameter
  1299. max_walk = max_walk or 10 * tooldia
  1300. # Assuming geolist is a flat list of flat elements
  1301. # ## Index first and last points in paths
  1302. def get_pts(o):
  1303. return [o.coords[0], o.coords[-1]]
  1304. # storage = FlatCAMRTreeStorage()
  1305. # storage.get_points = get_pts
  1306. #
  1307. # for shape in geolist:
  1308. # if shape is not None: # TODO: This shouldn't have happened.
  1309. # # Make LlinearRings into linestrings otherwise
  1310. # # When chaining the coordinates path is messed up.
  1311. # storage.insert(LineString(shape))
  1312. # #storage.insert(shape)
  1313. # ## Iterate over geometry paths getting the nearest each time.
  1314. #optimized_paths = []
  1315. optimized_paths = FlatCAMRTreeStorage()
  1316. optimized_paths.get_points = get_pts
  1317. path_count = 0
  1318. current_pt = (0, 0)
  1319. pt, geo = storage.nearest(current_pt)
  1320. storage.remove(geo)
  1321. geo = LineString(geo)
  1322. current_pt = geo.coords[-1]
  1323. try:
  1324. while True:
  1325. path_count += 1
  1326. # log.debug("Path %d" % path_count)
  1327. pt, candidate = storage.nearest(current_pt)
  1328. storage.remove(candidate)
  1329. candidate = LineString(candidate)
  1330. # If last point in geometry is the nearest
  1331. # then reverse coordinates.
  1332. # but prefer the first one if last == first
  1333. if pt != candidate.coords[0] and pt == candidate.coords[-1]:
  1334. candidate.coords = list(candidate.coords)[::-1]
  1335. # Straight line from current_pt to pt.
  1336. # Is the toolpath inside the geometry?
  1337. walk_path = LineString([current_pt, pt])
  1338. walk_cut = walk_path.buffer(tooldia / 2, int(steps_per_circle / 4))
  1339. if walk_cut.within(boundary) and walk_path.length < max_walk:
  1340. # log.debug("Walk to path #%d is inside. Joining." % path_count)
  1341. # Completely inside. Append...
  1342. geo.coords = list(geo.coords) + list(candidate.coords)
  1343. # try:
  1344. # last = optimized_paths[-1]
  1345. # last.coords = list(last.coords) + list(geo.coords)
  1346. # except IndexError:
  1347. # optimized_paths.append(geo)
  1348. else:
  1349. # Have to lift tool. End path.
  1350. # log.debug("Path #%d not within boundary. Next." % path_count)
  1351. # optimized_paths.append(geo)
  1352. optimized_paths.insert(geo)
  1353. geo = candidate
  1354. current_pt = geo.coords[-1]
  1355. # Next
  1356. # pt, geo = storage.nearest(current_pt)
  1357. except StopIteration: # Nothing left in storage.
  1358. # pass
  1359. optimized_paths.insert(geo)
  1360. return optimized_paths
  1361. @staticmethod
  1362. def path_connect(storage, origin=(0, 0)):
  1363. """
  1364. Simplifies paths in the FlatCAMRTreeStorage storage by
  1365. connecting paths that touch on their enpoints.
  1366. :param storage: Storage containing the initial paths.
  1367. :rtype storage: FlatCAMRTreeStorage
  1368. :return: Simplified storage.
  1369. :rtype: FlatCAMRTreeStorage
  1370. """
  1371. log.debug("path_connect()")
  1372. # ## Index first and last points in paths
  1373. def get_pts(o):
  1374. return [o.coords[0], o.coords[-1]]
  1375. #
  1376. # storage = FlatCAMRTreeStorage()
  1377. # storage.get_points = get_pts
  1378. #
  1379. # for shape in pathlist:
  1380. # if shape is not None: # TODO: This shouldn't have happened.
  1381. # storage.insert(shape)
  1382. path_count = 0
  1383. pt, geo = storage.nearest(origin)
  1384. storage.remove(geo)
  1385. # optimized_geometry = [geo]
  1386. optimized_geometry = FlatCAMRTreeStorage()
  1387. optimized_geometry.get_points = get_pts
  1388. # optimized_geometry.insert(geo)
  1389. try:
  1390. while True:
  1391. path_count += 1
  1392. _, left = storage.nearest(geo.coords[0])
  1393. # If left touches geo, remove left from original
  1394. # storage and append to geo.
  1395. if type(left) == LineString:
  1396. if left.coords[0] == geo.coords[0]:
  1397. storage.remove(left)
  1398. geo.coords = list(geo.coords)[::-1] + list(left.coords)
  1399. continue
  1400. if left.coords[-1] == geo.coords[0]:
  1401. storage.remove(left)
  1402. geo.coords = list(left.coords) + list(geo.coords)
  1403. continue
  1404. if left.coords[0] == geo.coords[-1]:
  1405. storage.remove(left)
  1406. geo.coords = list(geo.coords) + list(left.coords)
  1407. continue
  1408. if left.coords[-1] == geo.coords[-1]:
  1409. storage.remove(left)
  1410. geo.coords = list(geo.coords) + list(left.coords)[::-1]
  1411. continue
  1412. _, right = storage.nearest(geo.coords[-1])
  1413. # If right touches geo, remove left from original
  1414. # storage and append to geo.
  1415. if type(right) == LineString:
  1416. if right.coords[0] == geo.coords[-1]:
  1417. storage.remove(right)
  1418. geo.coords = list(geo.coords) + list(right.coords)
  1419. continue
  1420. if right.coords[-1] == geo.coords[-1]:
  1421. storage.remove(right)
  1422. geo.coords = list(geo.coords) + list(right.coords)[::-1]
  1423. continue
  1424. if right.coords[0] == geo.coords[0]:
  1425. storage.remove(right)
  1426. geo.coords = list(geo.coords)[::-1] + list(right.coords)
  1427. continue
  1428. if right.coords[-1] == geo.coords[0]:
  1429. storage.remove(right)
  1430. geo.coords = list(left.coords) + list(geo.coords)
  1431. continue
  1432. # right is either a LinearRing or it does not connect
  1433. # to geo (nothing left to connect to geo), so we continue
  1434. # with right as geo.
  1435. storage.remove(right)
  1436. if type(right) == LinearRing:
  1437. optimized_geometry.insert(right)
  1438. else:
  1439. # Cannot extend geo any further. Put it away.
  1440. optimized_geometry.insert(geo)
  1441. # Continue with right.
  1442. geo = right
  1443. except StopIteration: # Nothing found in storage.
  1444. optimized_geometry.insert(geo)
  1445. # print path_count
  1446. log.debug("path_count = %d" % path_count)
  1447. return optimized_geometry
  1448. def convert_units(self, obj_units):
  1449. """
  1450. Converts the units of the object to ``units`` by scaling all
  1451. the geometry appropriately. This call ``scale()``. Don't call
  1452. it again in descendents.
  1453. :param units: "IN" or "MM"
  1454. :type units: str
  1455. :return: Scaling factor resulting from unit change.
  1456. :rtype: float
  1457. """
  1458. if obj_units.upper() == self.units.upper():
  1459. log.debug("camlib.Geometry.convert_units() --> Factor: 1")
  1460. return 1.0
  1461. if obj_units.upper() == "MM":
  1462. factor = 25.4
  1463. log.debug("camlib.Geometry.convert_units() --> Factor: 25.4")
  1464. elif obj_units.upper() == "IN":
  1465. factor = 1 / 25.4
  1466. log.debug("camlib.Geometry.convert_units() --> Factor: %s" % str(1 / 25.4))
  1467. else:
  1468. log.error("Unsupported units: %s" % str(obj_units))
  1469. log.debug("camlib.Geometry.convert_units() --> Factor: 1")
  1470. return 1.0
  1471. self.units = obj_units
  1472. self.scale(factor, factor)
  1473. self.file_units_factor = factor
  1474. return factor
  1475. def to_dict(self):
  1476. """
  1477. Returns a representation of the object as a dictionary.
  1478. Attributes to include are listed in ``self.ser_attrs``.
  1479. :return: A dictionary-encoded copy of the object.
  1480. :rtype: dict
  1481. """
  1482. d = {}
  1483. for attr in self.ser_attrs:
  1484. d[attr] = getattr(self, attr)
  1485. return d
  1486. def from_dict(self, d):
  1487. """
  1488. Sets object's attributes from a dictionary.
  1489. Attributes to include are listed in ``self.ser_attrs``.
  1490. This method will look only for only and all the
  1491. attributes in ``self.ser_attrs``. They must all
  1492. be present. Use only for deserializing saved
  1493. objects.
  1494. :param d: Dictionary of attributes to set in the object.
  1495. :type d: dict
  1496. :return: None
  1497. """
  1498. for attr in self.ser_attrs:
  1499. setattr(self, attr, d[attr])
  1500. def union(self):
  1501. """
  1502. Runs a cascaded union on the list of objects in
  1503. solid_geometry.
  1504. :return: None
  1505. """
  1506. self.solid_geometry = [cascaded_union(self.solid_geometry)]
  1507. def export_svg(self, scale_factor=0.00):
  1508. """
  1509. Exports the Geometry Object as a SVG Element
  1510. :return: SVG Element
  1511. """
  1512. # Make sure we see a Shapely Geometry class and not a list
  1513. if str(type(self)) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  1514. flat_geo = []
  1515. if self.multigeo:
  1516. for tool in self.tools:
  1517. flat_geo += self.flatten(self.tools[tool]['solid_geometry'])
  1518. geom = cascaded_union(flat_geo)
  1519. else:
  1520. geom = cascaded_union(self.flatten())
  1521. else:
  1522. geom = cascaded_union(self.flatten())
  1523. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  1524. # If 0 or less which is invalid then default to 0.05
  1525. # This value appears to work for zooming, and getting the output svg line width
  1526. # to match that viewed on screen with FlatCam
  1527. # MS: I choose a factor of 0.01 so the scale is right for PCB UV film
  1528. if scale_factor <= 0:
  1529. scale_factor = 0.01
  1530. # Convert to a SVG
  1531. svg_elem = geom.svg(scale_factor=scale_factor)
  1532. return svg_elem
  1533. def mirror(self, axis, point):
  1534. """
  1535. Mirrors the object around a specified axis passign through
  1536. the given point.
  1537. :param axis: "X" or "Y" indicates around which axis to mirror.
  1538. :type axis: str
  1539. :param point: [x, y] point belonging to the mirror axis.
  1540. :type point: list
  1541. :return: None
  1542. """
  1543. log.debug("camlib.Geometry.mirror()")
  1544. px, py = point
  1545. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1546. def mirror_geom(obj):
  1547. if type(obj) is list:
  1548. new_obj = []
  1549. for g in obj:
  1550. new_obj.append(mirror_geom(g))
  1551. return new_obj
  1552. else:
  1553. try:
  1554. self.el_count += 1
  1555. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1556. if self.old_disp_number < disp_number <= 100:
  1557. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1558. self.old_disp_number = disp_number
  1559. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  1560. except AttributeError:
  1561. return obj
  1562. try:
  1563. if self.multigeo is True:
  1564. for tool in self.tools:
  1565. # variables to display the percentage of work done
  1566. self.geo_len = 0
  1567. try:
  1568. for g in self.tools[tool]['solid_geometry']:
  1569. self.geo_len += 1
  1570. except TypeError:
  1571. self.geo_len = 1
  1572. self.old_disp_number = 0
  1573. self.el_count = 0
  1574. self.tools[tool]['solid_geometry'] = mirror_geom(self.tools[tool]['solid_geometry'])
  1575. else:
  1576. # variables to display the percentage of work done
  1577. self.geo_len = 0
  1578. try:
  1579. for g in self.solid_geometry:
  1580. self.geo_len += 1
  1581. except TypeError:
  1582. self.geo_len = 1
  1583. self.old_disp_number = 0
  1584. self.el_count = 0
  1585. self.solid_geometry = mirror_geom(self.solid_geometry)
  1586. self.app.inform.emit('[success] %s...' %
  1587. _('Object was mirrored'))
  1588. except AttributeError:
  1589. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1590. _("Failed to mirror. No object selected"))
  1591. self.app.proc_container.new_text = ''
  1592. def rotate(self, angle, point):
  1593. """
  1594. Rotate an object by an angle (in degrees) around the provided coordinates.
  1595. Parameters
  1596. ----------
  1597. The angle of rotation are specified in degrees (default). Positive angles are
  1598. counter-clockwise and negative are clockwise rotations.
  1599. The point of origin can be a keyword 'center' for the bounding box
  1600. center (default), 'centroid' for the geometry's centroid, a Point object
  1601. or a coordinate tuple (x0, y0).
  1602. See shapely manual for more information:
  1603. http://toblerity.org/shapely/manual.html#affine-transformations
  1604. """
  1605. log.debug("camlib.Geometry.rotate()")
  1606. px, py = point
  1607. def rotate_geom(obj):
  1608. if type(obj) is list:
  1609. new_obj = []
  1610. for g in obj:
  1611. new_obj.append(rotate_geom(g))
  1612. return new_obj
  1613. else:
  1614. try:
  1615. self.el_count += 1
  1616. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1617. if self.old_disp_number < disp_number <= 100:
  1618. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1619. self.old_disp_number = disp_number
  1620. return affinity.rotate(obj, angle, origin=(px, py))
  1621. except AttributeError:
  1622. return obj
  1623. try:
  1624. if self.multigeo is True:
  1625. for tool in self.tools:
  1626. # variables to display the percentage of work done
  1627. self.geo_len = 0
  1628. try:
  1629. for g in self.tools[tool]['solid_geometry']:
  1630. self.geo_len += 1
  1631. except TypeError:
  1632. self.geo_len = 1
  1633. self.old_disp_number = 0
  1634. self.el_count = 0
  1635. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'])
  1636. else:
  1637. # variables to display the percentage of work done
  1638. self.geo_len = 0
  1639. try:
  1640. for g in self.solid_geometry:
  1641. self.geo_len += 1
  1642. except TypeError:
  1643. self.geo_len = 1
  1644. self.old_disp_number = 0
  1645. self.el_count = 0
  1646. self.solid_geometry = rotate_geom(self.solid_geometry)
  1647. self.app.inform.emit('[success] %s...' %
  1648. _('Object was rotated'))
  1649. except AttributeError:
  1650. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1651. _("Failed to rotate. No object selected"))
  1652. self.app.proc_container.new_text = ''
  1653. def skew(self, angle_x, angle_y, point):
  1654. """
  1655. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1656. Parameters
  1657. ----------
  1658. angle_x, angle_y : float, float
  1659. The shear angle(s) for the x and y axes respectively. These can be
  1660. specified in either degrees (default) or radians by setting
  1661. use_radians=True.
  1662. point: tuple of coordinates (x,y)
  1663. See shapely manual for more information:
  1664. http://toblerity.org/shapely/manual.html#affine-transformations
  1665. """
  1666. log.debug("camlib.Geometry.skew()")
  1667. px, py = point
  1668. def skew_geom(obj):
  1669. if type(obj) is list:
  1670. new_obj = []
  1671. for g in obj:
  1672. new_obj.append(skew_geom(g))
  1673. return new_obj
  1674. else:
  1675. try:
  1676. self.el_count += 1
  1677. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1678. if self.old_disp_number < disp_number <= 100:
  1679. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1680. self.old_disp_number = disp_number
  1681. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1682. except AttributeError:
  1683. return obj
  1684. try:
  1685. if self.multigeo is True:
  1686. for tool in self.tools:
  1687. # variables to display the percentage of work done
  1688. self.geo_len = 0
  1689. try:
  1690. for g in self.tools[tool]['solid_geometry']:
  1691. self.geo_len += 1
  1692. except TypeError:
  1693. self.geo_len = 1
  1694. self.old_disp_number = 0
  1695. self.el_count = 0
  1696. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  1697. else:
  1698. # variables to display the percentage of work done
  1699. self.geo_len = 0
  1700. try:
  1701. for g in self.solid_geometry:
  1702. self.geo_len += 1
  1703. except TypeError:
  1704. self.geo_len = 1
  1705. self.old_disp_number = 0
  1706. self.el_count = 0
  1707. self.solid_geometry = skew_geom(self.solid_geometry)
  1708. self.app.inform.emit('[success] %s...' %
  1709. _('Object was skewed'))
  1710. except AttributeError:
  1711. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1712. _("Failed to skew. No object selected"))
  1713. self.app.proc_container.new_text = ''
  1714. # if type(self.solid_geometry) == list:
  1715. # self.solid_geometry = [affinity.skew(g, angle_x, angle_y, origin=(px, py))
  1716. # for g in self.solid_geometry]
  1717. # else:
  1718. # self.solid_geometry = affinity.skew(self.solid_geometry, angle_x, angle_y,
  1719. # origin=(px, py))
  1720. class AttrDict(dict):
  1721. def __init__(self, *args, **kwargs):
  1722. super(AttrDict, self).__init__(*args, **kwargs)
  1723. self.__dict__ = self
  1724. class CNCjob(Geometry):
  1725. """
  1726. Represents work to be done by a CNC machine.
  1727. *ATTRIBUTES*
  1728. * ``gcode_parsed`` (list): Each is a dictionary:
  1729. ===================== =========================================
  1730. Key Value
  1731. ===================== =========================================
  1732. geom (Shapely.LineString) Tool path (XY plane)
  1733. kind (string) "AB", A is "T" (travel) or
  1734. "C" (cut). B is "F" (fast) or "S" (slow).
  1735. ===================== =========================================
  1736. """
  1737. defaults = {
  1738. "global_zdownrate": None,
  1739. "pp_geometry_name":'default',
  1740. "pp_excellon_name":'default',
  1741. "excellon_optimization_type": "B",
  1742. }
  1743. def __init__(self,
  1744. units="in", kind="generic", tooldia=0.0,
  1745. z_cut=-0.002, z_move=0.1,
  1746. feedrate=3.0, feedrate_z=3.0, feedrate_rapid=3.0, feedrate_probe=3.0,
  1747. pp_geometry_name='default', pp_excellon_name='default',
  1748. depthpercut=0.1,z_pdepth=-0.02,
  1749. spindlespeed=None, spindledir='CW', dwell=True, dwelltime=1000,
  1750. toolchangez=0.787402, toolchange_xy=[0.0, 0.0],
  1751. endz=2.0,
  1752. segx=None,
  1753. segy=None,
  1754. steps_per_circle=None):
  1755. # Used when parsing G-code arcs
  1756. self.steps_per_circle = int(self.app.defaults['cncjob_steps_per_circle'])
  1757. Geometry.__init__(self, geo_steps_per_circle=self.steps_per_circle)
  1758. self.kind = kind
  1759. self.origin_kind = None
  1760. self.units = units
  1761. self.z_cut = z_cut
  1762. self.tool_offset = {}
  1763. self.z_move = z_move
  1764. self.feedrate = feedrate
  1765. self.z_feedrate = feedrate_z
  1766. self.feedrate_rapid = feedrate_rapid
  1767. self.tooldia = tooldia
  1768. self.z_toolchange = toolchangez
  1769. self.xy_toolchange = toolchange_xy
  1770. self.toolchange_xy_type = None
  1771. self.toolC = tooldia
  1772. self.z_end = endz
  1773. self.z_depthpercut = depthpercut
  1774. self.unitcode = {"IN": "G20", "MM": "G21"}
  1775. self.feedminutecode = "G94"
  1776. # self.absolutecode = "G90"
  1777. # self.incrementalcode = "G91"
  1778. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  1779. self.gcode = ""
  1780. self.gcode_parsed = None
  1781. self.pp_geometry_name = pp_geometry_name
  1782. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  1783. self.pp_excellon_name = pp_excellon_name
  1784. self.pp_excellon = self.app.postprocessors[self.pp_excellon_name]
  1785. self.pp_solderpaste_name = None
  1786. # Controls if the move from Z_Toolchange to Z_Move is done fast with G0 or normally with G1
  1787. self.f_plunge = None
  1788. # Controls if the move from Z_Cutto Z_Move is done fast with G0 or G1 until zero and then G0 to Z_move
  1789. self.f_retract = None
  1790. # how much depth the probe can probe before error
  1791. self.z_pdepth = z_pdepth if z_pdepth else None
  1792. # the feedrate(speed) with which the probel travel while probing
  1793. self.feedrate_probe = feedrate_probe if feedrate_probe else None
  1794. self.spindlespeed = spindlespeed
  1795. self.spindledir = spindledir
  1796. self.dwell = dwell
  1797. self.dwelltime = dwelltime
  1798. self.segx = float(segx) if segx is not None else 0.0
  1799. self.segy = float(segy) if segy is not None else 0.0
  1800. self.input_geometry_bounds = None
  1801. self.oldx = None
  1802. self.oldy = None
  1803. self.tool = 0.0
  1804. # here store the travelled distance
  1805. self.travel_distance = 0.0
  1806. # here store the routing time
  1807. self.routing_time = 0.0
  1808. # used for creating drill CCode geometry; will be updated in the generate_from_excellon_by_tool()
  1809. self.exc_drills = None
  1810. self.exc_tools = None
  1811. # search for toolchange parameters in the Toolchange Custom Code
  1812. self.re_toolchange_custom = re.compile(r'(%[a-zA-Z0-9\-_]+%)')
  1813. # search for toolchange code: M6
  1814. self.re_toolchange = re.compile(r'^\s*(M6)$')
  1815. # Attributes to be included in serialization
  1816. # Always append to it because it carries contents
  1817. # from Geometry.
  1818. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'z_toolchange', 'feedrate', 'z_feedrate', 'feedrate_rapid',
  1819. 'tooldia', 'gcode', 'input_geometry_bounds', 'gcode_parsed', 'steps_per_circle',
  1820. 'z_depthpercut', 'spindlespeed', 'dwell', 'dwelltime']
  1821. @property
  1822. def postdata(self):
  1823. return self.__dict__
  1824. def convert_units(self, units):
  1825. log.debug("camlib.CNCJob.convert_units()")
  1826. factor = Geometry.convert_units(self, units)
  1827. self.z_cut = float(self.z_cut) * factor
  1828. self.z_move *= factor
  1829. self.feedrate *= factor
  1830. self.z_feedrate *= factor
  1831. self.feedrate_rapid *= factor
  1832. self.tooldia *= factor
  1833. self.z_toolchange *= factor
  1834. self.z_end *= factor
  1835. self.z_depthpercut = float(self.z_depthpercut) * factor
  1836. return factor
  1837. def doformat(self, fun, **kwargs):
  1838. return self.doformat2(fun, **kwargs) + "\n"
  1839. def doformat2(self, fun, **kwargs):
  1840. attributes = AttrDict()
  1841. attributes.update(self.postdata)
  1842. attributes.update(kwargs)
  1843. try:
  1844. returnvalue = fun(attributes)
  1845. return returnvalue
  1846. except Exception as e:
  1847. self.app.log.error('Exception occurred within a postprocessor: ' + traceback.format_exc())
  1848. return ''
  1849. def parse_custom_toolchange_code(self, data):
  1850. text = data
  1851. match_list = self.re_toolchange_custom.findall(text)
  1852. if match_list:
  1853. for match in match_list:
  1854. command = match.strip('%')
  1855. try:
  1856. value = getattr(self, command)
  1857. except AttributeError:
  1858. self.app.inform.emit('[ERROR] %s: %s' %
  1859. (_("There is no such parameter"), str(match)))
  1860. log.debug("CNCJob.parse_custom_toolchange_code() --> AttributeError ")
  1861. return 'fail'
  1862. text = text.replace(match, str(value))
  1863. return text
  1864. def optimized_travelling_salesman(self, points, start=None):
  1865. """
  1866. As solving the problem in the brute force way is too slow,
  1867. this function implements a simple heuristic: always
  1868. go to the nearest city.
  1869. Even if this algorithm is extremely simple, it works pretty well
  1870. giving a solution only about 25%% longer than the optimal one (cit. Wikipedia),
  1871. and runs very fast in O(N^2) time complexity.
  1872. >>> optimized_travelling_salesman([[i,j] for i in range(5) for j in range(5)])
  1873. [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], [2, 0], [2, 1], [2, 2],
  1874. [2, 3], [2, 4], [3, 4], [3, 3], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
  1875. >>> optimized_travelling_salesman([[0,0],[10,0],[6,0]])
  1876. [[0, 0], [6, 0], [10, 0]]
  1877. """
  1878. if start is None:
  1879. start = points[0]
  1880. must_visit = points
  1881. path = [start]
  1882. # must_visit.remove(start)
  1883. while must_visit:
  1884. nearest = min(must_visit, key=lambda x: distance(path[-1], x))
  1885. path.append(nearest)
  1886. must_visit.remove(nearest)
  1887. return path
  1888. def generate_from_excellon_by_tool(
  1889. self, exobj, tools="all", drillz = 3.0,
  1890. toolchange=False, toolchangez=0.1, toolchangexy='',
  1891. endz=2.0, startz=None,
  1892. excellon_optimization_type='B'):
  1893. """
  1894. Creates gcode for this object from an Excellon object
  1895. for the specified tools.
  1896. :param exobj: Excellon object to process
  1897. :type exobj: Excellon
  1898. :param tools: Comma separated tool names
  1899. :type: tools: str
  1900. :param drillz: drill Z depth
  1901. :type drillz: float
  1902. :param toolchange: Use tool change sequence between tools.
  1903. :type toolchange: bool
  1904. :param toolchangez: Height at which to perform the tool change.
  1905. :type toolchangez: float
  1906. :param toolchangexy: Toolchange X,Y position
  1907. :type toolchangexy: String containing 2 floats separated by comma
  1908. :param startz: Z position just before starting the job
  1909. :type startz: float
  1910. :param endz: final Z position to move to at the end of the CNC job
  1911. :type endz: float
  1912. :param excellon_optimization_type: Single character that defines which drill re-ordering optimisation algorithm
  1913. is to be used: 'M' for meta-heuristic and 'B' for basic
  1914. :type excellon_optimization_type: string
  1915. :return: None
  1916. :rtype: None
  1917. """
  1918. # create a local copy of the exobj.drills so it can be used for creating drill CCode geometry
  1919. self.exc_drills = deepcopy(exobj.drills)
  1920. self.exc_tools = deepcopy(exobj.tools)
  1921. if drillz > 0:
  1922. self.app.inform.emit('[WARNING] %s' %
  1923. _("The Cut Z parameter has positive value. "
  1924. "It is the depth value to drill into material.\n"
  1925. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  1926. "therefore the app will convert the value to negative. "
  1927. "Check the resulting CNC code (Gcode etc)."))
  1928. self.z_cut = -drillz
  1929. elif drillz == 0:
  1930. self.app.inform.emit('[WARNING] %s: %s' %
  1931. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  1932. exobj.options['name']))
  1933. return 'fail'
  1934. else:
  1935. self.z_cut = drillz
  1936. self.z_toolchange = toolchangez
  1937. try:
  1938. if toolchangexy == '':
  1939. self.xy_toolchange = None
  1940. else:
  1941. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  1942. if len(self.xy_toolchange) < 2:
  1943. self.app.inform.emit('[ERROR]%s' %
  1944. _("The Toolchange X,Y field in Edit -> Preferences has to be "
  1945. "in the format (x, y) \nbut now there is only one value, not two. "))
  1946. return 'fail'
  1947. except Exception as e:
  1948. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> %s" % str(e))
  1949. pass
  1950. self.startz = startz
  1951. self.z_end = endz
  1952. self.pp_excellon = self.app.postprocessors[self.pp_excellon_name]
  1953. p = self.pp_excellon
  1954. log.debug("Creating CNC Job from Excellon...")
  1955. # Tools
  1956. # sort the tools list by the second item in tuple (here we have a dict with diameter of the tool)
  1957. # so we actually are sorting the tools by diameter
  1958. #sorted_tools = sorted(exobj.tools.items(), key=lambda t1: t1['C'])
  1959. sort = []
  1960. for k, v in list(exobj.tools.items()):
  1961. sort.append((k, v.get('C')))
  1962. sorted_tools = sorted(sort,key=lambda t1: t1[1])
  1963. if tools == "all":
  1964. tools = [i[0] for i in sorted_tools] # we get a array of ordered tools
  1965. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1966. else:
  1967. selected_tools = [x.strip() for x in tools.split(",")] # we strip spaces and also separate the tools by ','
  1968. selected_tools = [t1 for t1 in selected_tools if t1 in selected_tools]
  1969. # Create a sorted list of selected tools from the sorted_tools list
  1970. tools = [i for i, j in sorted_tools for k in selected_tools if i == k]
  1971. log.debug("Tools selected and sorted are: %s" % str(tools))
  1972. self.app.inform.emit(_("Creating a list of points to drill..."))
  1973. # Points (Group by tool)
  1974. points = {}
  1975. for drill in exobj.drills:
  1976. if self.app.abort_flag:
  1977. # graceful abort requested by the user
  1978. raise FlatCAMApp.GracefulException
  1979. if drill['tool'] in tools:
  1980. try:
  1981. points[drill['tool']].append(drill['point'])
  1982. except KeyError:
  1983. points[drill['tool']] = [drill['point']]
  1984. #log.debug("Found %d drills." % len(points))
  1985. self.gcode = []
  1986. self.f_plunge = self.app.defaults["excellon_f_plunge"]
  1987. self.f_retract = self.app.defaults["excellon_f_retract"]
  1988. # Initialization
  1989. gcode = self.doformat(p.start_code)
  1990. gcode += self.doformat(p.feedrate_code)
  1991. if toolchange is False:
  1992. if self.xy_toolchange is not None:
  1993. gcode += self.doformat(p.lift_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  1994. gcode += self.doformat(p.startz_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  1995. else:
  1996. gcode += self.doformat(p.lift_code, x=0.0, y=0.0)
  1997. gcode += self.doformat(p.startz_code, x=0.0, y=0.0)
  1998. # Distance callback
  1999. class CreateDistanceCallback(object):
  2000. """Create callback to calculate distances between points."""
  2001. def __init__(self):
  2002. """Initialize distance array."""
  2003. locations = create_data_array()
  2004. size = len(locations)
  2005. self.matrix = {}
  2006. for from_node in range(size):
  2007. self.matrix[from_node] = {}
  2008. for to_node in range(size):
  2009. if from_node == to_node:
  2010. self.matrix[from_node][to_node] = 0
  2011. else:
  2012. x1 = locations[from_node][0]
  2013. y1 = locations[from_node][1]
  2014. x2 = locations[to_node][0]
  2015. y2 = locations[to_node][1]
  2016. self.matrix[from_node][to_node] = distance_euclidian(x1, y1, x2, y2)
  2017. # def Distance(self, from_node, to_node):
  2018. # return int(self.matrix[from_node][to_node])
  2019. def Distance(self, from_index, to_index):
  2020. # Convert from routing variable Index to distance matrix NodeIndex.
  2021. from_node = manager.IndexToNode(from_index)
  2022. to_node = manager.IndexToNode(to_index)
  2023. return self.matrix[from_node][to_node]
  2024. # Create the data.
  2025. def create_data_array():
  2026. locations = []
  2027. for point in points[tool]:
  2028. locations.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  2029. return locations
  2030. if self.xy_toolchange is not None:
  2031. self.oldx = self.xy_toolchange[0]
  2032. self.oldy = self.xy_toolchange[1]
  2033. else:
  2034. self.oldx = 0.0
  2035. self.oldy = 0.0
  2036. measured_distance = 0.0
  2037. measured_down_distance = 0.0
  2038. measured_up_to_zero_distance = 0.0
  2039. measured_lift_distance = 0.0
  2040. self.app.inform.emit('%s...' %
  2041. _("Starting G-Code"))
  2042. current_platform = platform.architecture()[0]
  2043. if current_platform == '64bit':
  2044. used_excellon_optimization_type = excellon_optimization_type
  2045. if used_excellon_optimization_type == 'M':
  2046. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  2047. if exobj.drills:
  2048. for tool in tools:
  2049. self.tool=tool
  2050. self.postdata['toolC'] = exobj.tools[tool]["C"]
  2051. self.tooldia = exobj.tools[tool]["C"]
  2052. if self.app.abort_flag:
  2053. # graceful abort requested by the user
  2054. raise FlatCAMApp.GracefulException
  2055. # ###############################################
  2056. # ############ Create the data. #################
  2057. # ###############################################
  2058. node_list = []
  2059. locations = create_data_array()
  2060. tsp_size = len(locations)
  2061. num_routes = 1 # The number of routes, which is 1 in the TSP.
  2062. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  2063. depot = 0
  2064. # Create routing model.
  2065. if tsp_size > 0:
  2066. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  2067. routing = pywrapcp.RoutingModel(manager)
  2068. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  2069. search_parameters.local_search_metaheuristic = (
  2070. routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
  2071. # Set search time limit in milliseconds.
  2072. if float(self.app.defaults["excellon_search_time"]) != 0:
  2073. search_parameters.time_limit.seconds = int(
  2074. float(self.app.defaults["excellon_search_time"]))
  2075. else:
  2076. search_parameters.time_limit.seconds = 3
  2077. # Callback to the distance function. The callback takes two
  2078. # arguments (the from and to node indices) and returns the distance between them.
  2079. dist_between_locations = CreateDistanceCallback()
  2080. dist_callback = dist_between_locations.Distance
  2081. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  2082. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  2083. # Solve, returns a solution if any.
  2084. assignment = routing.SolveWithParameters(search_parameters)
  2085. if assignment:
  2086. # Solution cost.
  2087. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  2088. # Inspect solution.
  2089. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  2090. route_number = 0
  2091. node = routing.Start(route_number)
  2092. start_node = node
  2093. while not routing.IsEnd(node):
  2094. if self.app.abort_flag:
  2095. # graceful abort requested by the user
  2096. raise FlatCAMApp.GracefulException
  2097. node_list.append(node)
  2098. node = assignment.Value(routing.NextVar(node))
  2099. else:
  2100. log.warning('No solution found.')
  2101. else:
  2102. log.warning('Specify an instance greater than 0.')
  2103. # ############################################# ##
  2104. # Only if tool has points.
  2105. if tool in points:
  2106. if self.app.abort_flag:
  2107. # graceful abort requested by the user
  2108. raise FlatCAMApp.GracefulException
  2109. # Tool change sequence (optional)
  2110. if toolchange:
  2111. gcode += self.doformat(p.toolchange_code,toolchangexy=(self.oldx, self.oldy))
  2112. gcode += self.doformat(p.spindle_code) # Spindle start
  2113. if self.dwell is True:
  2114. gcode += self.doformat(p.dwell_code) # Dwell time
  2115. else:
  2116. gcode += self.doformat(p.spindle_code)
  2117. if self.dwell is True:
  2118. gcode += self.doformat(p.dwell_code) # Dwell time
  2119. if self.units == 'MM':
  2120. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  2121. else:
  2122. current_tooldia = float('%.4f' % float(exobj.tools[tool]["C"]))
  2123. self.app.inform.emit(
  2124. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2125. str(current_tooldia),
  2126. str(self.units))
  2127. )
  2128. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  2129. # because the values for Z offset are created in build_ui()
  2130. try:
  2131. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  2132. except KeyError:
  2133. z_offset = 0
  2134. self.z_cut += z_offset
  2135. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2136. if self.coordinates_type == "G90":
  2137. # Drillling! for Absolute coordinates type G90
  2138. # variables to display the percentage of work done
  2139. geo_len = len(node_list)
  2140. disp_number = 0
  2141. old_disp_number = 0
  2142. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2143. loc_nr = 0
  2144. for k in node_list:
  2145. if self.app.abort_flag:
  2146. # graceful abort requested by the user
  2147. raise FlatCAMApp.GracefulException
  2148. locx = locations[k][0]
  2149. locy = locations[k][1]
  2150. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2151. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2152. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2153. if self.f_retract is False:
  2154. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2155. measured_up_to_zero_distance += abs(self.z_cut)
  2156. measured_lift_distance += abs(self.z_move)
  2157. else:
  2158. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2159. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2160. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  2161. self.oldx = locx
  2162. self.oldy = locy
  2163. loc_nr += 1
  2164. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2165. if old_disp_number < disp_number <= 100:
  2166. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2167. old_disp_number = disp_number
  2168. else:
  2169. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  2170. _('G91 coordinates not implemented'))
  2171. return 'fail'
  2172. else:
  2173. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  2174. "The loaded Excellon file has no drills ...")
  2175. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  2176. _('The loaded Excellon file has no drills'))
  2177. return 'fail'
  2178. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  2179. if used_excellon_optimization_type == 'B':
  2180. log.debug("Using OR-Tools Basic drill path optimization.")
  2181. if exobj.drills:
  2182. for tool in tools:
  2183. if self.app.abort_flag:
  2184. # graceful abort requested by the user
  2185. raise FlatCAMApp.GracefulException
  2186. self.tool=tool
  2187. self.postdata['toolC']=exobj.tools[tool]["C"]
  2188. self.tooldia = exobj.tools[tool]["C"]
  2189. # ############################################# ##
  2190. node_list = []
  2191. locations = create_data_array()
  2192. tsp_size = len(locations)
  2193. num_routes = 1 # The number of routes, which is 1 in the TSP.
  2194. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  2195. depot = 0
  2196. # Create routing model.
  2197. if tsp_size > 0:
  2198. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  2199. routing = pywrapcp.RoutingModel(manager)
  2200. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  2201. # Callback to the distance function. The callback takes two
  2202. # arguments (the from and to node indices) and returns the distance between them.
  2203. dist_between_locations = CreateDistanceCallback()
  2204. dist_callback = dist_between_locations.Distance
  2205. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  2206. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  2207. # Solve, returns a solution if any.
  2208. assignment = routing.SolveWithParameters(search_parameters)
  2209. if assignment:
  2210. # Solution cost.
  2211. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  2212. # Inspect solution.
  2213. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  2214. route_number = 0
  2215. node = routing.Start(route_number)
  2216. start_node = node
  2217. while not routing.IsEnd(node):
  2218. node_list.append(node)
  2219. node = assignment.Value(routing.NextVar(node))
  2220. else:
  2221. log.warning('No solution found.')
  2222. else:
  2223. log.warning('Specify an instance greater than 0.')
  2224. # ############################################# ##
  2225. # Only if tool has points.
  2226. if tool in points:
  2227. if self.app.abort_flag:
  2228. # graceful abort requested by the user
  2229. raise FlatCAMApp.GracefulException
  2230. # Tool change sequence (optional)
  2231. if toolchange:
  2232. gcode += self.doformat(p.toolchange_code,toolchangexy=(self.oldx, self.oldy))
  2233. gcode += self.doformat(p.spindle_code) # Spindle start)
  2234. if self.dwell is True:
  2235. gcode += self.doformat(p.dwell_code) # Dwell time
  2236. else:
  2237. gcode += self.doformat(p.spindle_code)
  2238. if self.dwell is True:
  2239. gcode += self.doformat(p.dwell_code) # Dwell time
  2240. if self.units == 'MM':
  2241. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  2242. else:
  2243. current_tooldia = float('%.4f' % float(exobj.tools[tool]["C"]))
  2244. self.app.inform.emit(
  2245. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2246. str(current_tooldia),
  2247. str(self.units))
  2248. )
  2249. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  2250. # because the values for Z offset are created in build_ui()
  2251. try:
  2252. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  2253. except KeyError:
  2254. z_offset = 0
  2255. self.z_cut += z_offset
  2256. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2257. if self.coordinates_type == "G90":
  2258. # Drillling! for Absolute coordinates type G90
  2259. # variables to display the percentage of work done
  2260. geo_len = len(node_list)
  2261. disp_number = 0
  2262. old_disp_number = 0
  2263. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2264. loc_nr = 0
  2265. for k in node_list:
  2266. if self.app.abort_flag:
  2267. # graceful abort requested by the user
  2268. raise FlatCAMApp.GracefulException
  2269. locx = locations[k][0]
  2270. locy = locations[k][1]
  2271. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2272. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2273. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2274. if self.f_retract is False:
  2275. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2276. measured_up_to_zero_distance += abs(self.z_cut)
  2277. measured_lift_distance += abs(self.z_move)
  2278. else:
  2279. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2280. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2281. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  2282. self.oldx = locx
  2283. self.oldy = locy
  2284. loc_nr += 1
  2285. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2286. if old_disp_number < disp_number <= 100:
  2287. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2288. old_disp_number = disp_number
  2289. else:
  2290. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  2291. _('G91 coordinates not implemented'))
  2292. return 'fail'
  2293. else:
  2294. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  2295. "The loaded Excellon file has no drills ...")
  2296. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  2297. _('The loaded Excellon file has no drills'))
  2298. return 'fail'
  2299. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  2300. else:
  2301. used_excellon_optimization_type = 'T'
  2302. if used_excellon_optimization_type == 'T':
  2303. log.debug("Using Travelling Salesman drill path optimization.")
  2304. for tool in tools:
  2305. if self.app.abort_flag:
  2306. # graceful abort requested by the user
  2307. raise FlatCAMApp.GracefulException
  2308. if exobj.drills:
  2309. self.tool = tool
  2310. self.postdata['toolC'] = exobj.tools[tool]["C"]
  2311. self.tooldia = exobj.tools[tool]["C"]
  2312. # Only if tool has points.
  2313. if tool in points:
  2314. if self.app.abort_flag:
  2315. # graceful abort requested by the user
  2316. raise FlatCAMApp.GracefulException
  2317. # Tool change sequence (optional)
  2318. if toolchange:
  2319. gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  2320. gcode += self.doformat(p.spindle_code) # Spindle start)
  2321. if self.dwell is True:
  2322. gcode += self.doformat(p.dwell_code) # Dwell time
  2323. else:
  2324. gcode += self.doformat(p.spindle_code)
  2325. if self.dwell is True:
  2326. gcode += self.doformat(p.dwell_code) # Dwell time
  2327. if self.units == 'MM':
  2328. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  2329. else:
  2330. current_tooldia = float('%.4f' % float(exobj.tools[tool]["C"]))
  2331. self.app.inform.emit(
  2332. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2333. str(current_tooldia),
  2334. str(self.units))
  2335. )
  2336. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  2337. # because the values for Z offset are created in build_ui()
  2338. try:
  2339. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  2340. except KeyError:
  2341. z_offset = 0
  2342. self.z_cut += z_offset
  2343. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2344. if self.coordinates_type == "G90":
  2345. # Drillling! for Absolute coordinates type G90
  2346. altPoints = []
  2347. for point in points[tool]:
  2348. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  2349. node_list = self.optimized_travelling_salesman(altPoints)
  2350. # variables to display the percentage of work done
  2351. geo_len = len(node_list)
  2352. disp_number = 0
  2353. old_disp_number = 0
  2354. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2355. loc_nr = 0
  2356. for point in node_list:
  2357. if self.app.abort_flag:
  2358. # graceful abort requested by the user
  2359. raise FlatCAMApp.GracefulException
  2360. gcode += self.doformat(p.rapid_code, x=point[0], y=point[1])
  2361. gcode += self.doformat(p.down_code, x=point[0], y=point[1])
  2362. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2363. if self.f_retract is False:
  2364. gcode += self.doformat(p.up_to_zero_code, x=point[0], y=point[1])
  2365. measured_up_to_zero_distance += abs(self.z_cut)
  2366. measured_lift_distance += abs(self.z_move)
  2367. else:
  2368. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2369. gcode += self.doformat(p.lift_code, x=point[0], y=point[1])
  2370. measured_distance += abs(distance_euclidian(point[0], point[1], self.oldx, self.oldy))
  2371. self.oldx = point[0]
  2372. self.oldy = point[1]
  2373. loc_nr += 1
  2374. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2375. if old_disp_number < disp_number <= 100:
  2376. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2377. old_disp_number = disp_number
  2378. else:
  2379. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  2380. _('G91 coordinates not implemented'))
  2381. return 'fail'
  2382. else:
  2383. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  2384. "The loaded Excellon file has no drills ...")
  2385. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  2386. _('The loaded Excellon file has no drills'))
  2387. return 'fail'
  2388. log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  2389. gcode += self.doformat(p.spindle_stop_code) # Spindle stop
  2390. gcode += self.doformat(p.end_code, x=0, y=0)
  2391. measured_distance += abs(distance_euclidian(self.oldx, self.oldy, 0, 0))
  2392. log.debug("The total travel distance including travel to end position is: %s" %
  2393. str(measured_distance) + '\n')
  2394. self.travel_distance = measured_distance
  2395. # I use the value of self.feedrate_rapid for the feadrate in case of the measure_lift_distance and for
  2396. # traveled_time because it is not always possible to determine the feedrate that the CNC machine uses
  2397. # for G0 move (the fastest speed available to the CNC router). Although self.feedrate_rapids is used only with
  2398. # Marlin postprocessor and derivatives.
  2399. self.routing_time = (measured_down_distance + measured_up_to_zero_distance) / self.feedrate
  2400. lift_time = measured_lift_distance / self.feedrate_rapid
  2401. traveled_time = measured_distance / self.feedrate_rapid
  2402. self.routing_time += lift_time + traveled_time
  2403. self.gcode = gcode
  2404. self.app.inform.emit(_("Finished G-Code generation..."))
  2405. return 'OK'
  2406. def generate_from_multitool_geometry(self, geometry, append=True,
  2407. tooldia=None, offset=0.0, tolerance=0, z_cut=1.0, z_move=2.0,
  2408. feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  2409. spindlespeed=None, spindledir='CW', dwell=False, dwelltime=1.0,
  2410. multidepth=False, depthpercut=None,
  2411. toolchange=False, toolchangez=1.0, toolchangexy="0.0, 0.0", extracut=False,
  2412. startz=None, endz=2.0, pp_geometry_name=None, tool_no=1):
  2413. """
  2414. Algorithm to generate from multitool Geometry.
  2415. Algorithm description:
  2416. ----------------------
  2417. Uses RTree to find the nearest path to follow.
  2418. :param geometry:
  2419. :param append:
  2420. :param tooldia:
  2421. :param tolerance:
  2422. :param multidepth: If True, use multiple passes to reach
  2423. the desired depth.
  2424. :param depthpercut: Maximum depth in each pass.
  2425. :param extracut: Adds (or not) an extra cut at the end of each path
  2426. overlapping the first point in path to ensure complete copper removal
  2427. :return: GCode - string
  2428. """
  2429. log.debug("Generate_from_multitool_geometry()")
  2430. temp_solid_geometry = []
  2431. if offset != 0.0:
  2432. for it in geometry:
  2433. # if the geometry is a closed shape then create a Polygon out of it
  2434. if isinstance(it, LineString):
  2435. c = it.coords
  2436. if c[0] == c[-1]:
  2437. it = Polygon(it)
  2438. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  2439. else:
  2440. temp_solid_geometry = geometry
  2441. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  2442. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  2443. log.debug("%d paths" % len(flat_geometry))
  2444. self.tooldia = float(tooldia) if tooldia else None
  2445. self.z_cut = float(z_cut) if z_cut else None
  2446. self.z_move = float(z_move) if z_move else None
  2447. self.feedrate = float(feedrate) if feedrate else None
  2448. self.z_feedrate = float(feedrate_z) if feedrate_z else None
  2449. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else None
  2450. self.spindlespeed = int(spindlespeed) if spindlespeed else None
  2451. self.spindledir = spindledir
  2452. self.dwell = dwell
  2453. self.dwelltime = float(dwelltime) if dwelltime else None
  2454. self.startz = float(startz) if startz else None
  2455. self.z_end = float(endz) if endz else None
  2456. self.z_depthpercut = float(depthpercut) if depthpercut else None
  2457. self.multidepth = multidepth
  2458. self.z_toolchange = float(toolchangez) if toolchangez else None
  2459. # it servers in the postprocessor file
  2460. self.tool = tool_no
  2461. try:
  2462. if toolchangexy == '':
  2463. self.xy_toolchange = None
  2464. else:
  2465. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  2466. if len(self.xy_toolchange) < 2:
  2467. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  2468. "in the format (x, y) \n"
  2469. "but now there is only one value, not two."))
  2470. return 'fail'
  2471. except Exception as e:
  2472. log.debug("camlib.CNCJob.generate_from_multitool_geometry() --> %s" % str(e))
  2473. pass
  2474. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  2475. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  2476. if self.z_cut is None:
  2477. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2478. _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  2479. "other parameters."))
  2480. return 'fail'
  2481. if self.z_cut > 0:
  2482. self.app.inform.emit('[WARNING] %s' %
  2483. _("The Cut Z parameter has positive value. "
  2484. "It is the depth value to cut into material.\n"
  2485. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  2486. "therefore the app will convert the value to negative."
  2487. "Check the resulting CNC code (Gcode etc)."))
  2488. self.z_cut = -self.z_cut
  2489. elif self.z_cut == 0:
  2490. self.app.inform.emit('[WARNING] %s: %s' %
  2491. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  2492. self.options['name']))
  2493. return 'fail'
  2494. # made sure that depth_per_cut is no more then the z_cut
  2495. if abs(self.z_cut) < self.z_depthpercut:
  2496. self.z_depthpercut = abs(self.z_cut)
  2497. if self.z_move is None:
  2498. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2499. _("Travel Z parameter is None or zero."))
  2500. return 'fail'
  2501. if self.z_move < 0:
  2502. self.app.inform.emit('[WARNING] %s' %
  2503. _("The Travel Z parameter has negative value. "
  2504. "It is the height value to travel between cuts.\n"
  2505. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  2506. "therefore the app will convert the value to positive."
  2507. "Check the resulting CNC code (Gcode etc)."))
  2508. self.z_move = -self.z_move
  2509. elif self.z_move == 0:
  2510. self.app.inform.emit('[WARNING] %s: %s' %
  2511. (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  2512. self.options['name']))
  2513. return 'fail'
  2514. # ## Index first and last points in paths
  2515. # What points to index.
  2516. def get_pts(o):
  2517. return [o.coords[0], o.coords[-1]]
  2518. # Create the indexed storage.
  2519. storage = FlatCAMRTreeStorage()
  2520. storage.get_points = get_pts
  2521. # Store the geometry
  2522. log.debug("Indexing geometry before generating G-Code...")
  2523. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  2524. for shape in flat_geometry:
  2525. if self.app.abort_flag:
  2526. # graceful abort requested by the user
  2527. raise FlatCAMApp.GracefulException
  2528. if shape is not None: # TODO: This shouldn't have happened.
  2529. storage.insert(shape)
  2530. # self.input_geometry_bounds = geometry.bounds()
  2531. if not append:
  2532. self.gcode = ""
  2533. # tell postprocessor the number of tool (for toolchange)
  2534. self.tool = tool_no
  2535. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  2536. # given under the name 'toolC'
  2537. self.postdata['toolC'] = self.tooldia
  2538. # Initial G-Code
  2539. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  2540. p = self.pp_geometry
  2541. self.gcode = self.doformat(p.start_code)
  2542. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  2543. if toolchange is False:
  2544. self.gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  2545. self.gcode += self.doformat(p.startz_code, x=0, y=0)
  2546. if toolchange:
  2547. # if "line_xyz" in self.pp_geometry_name:
  2548. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2549. # else:
  2550. # self.gcode += self.doformat(p.toolchange_code)
  2551. self.gcode += self.doformat(p.toolchange_code)
  2552. if 'laser' not in self.pp_geometry_name:
  2553. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2554. else:
  2555. # for laser this will disable the laser
  2556. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  2557. if self.dwell is True:
  2558. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2559. else:
  2560. if 'laser' not in self.pp_geometry_name:
  2561. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2562. if self.dwell is True:
  2563. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2564. total_travel = 0.0
  2565. total_cut = 0.0
  2566. # ## Iterate over geometry paths getting the nearest each time.
  2567. log.debug("Starting G-Code...")
  2568. self.app.inform.emit(_("Starting G-Code..."))
  2569. path_count = 0
  2570. current_pt = (0, 0)
  2571. # variables to display the percentage of work done
  2572. geo_len = len(flat_geometry)
  2573. disp_number = 0
  2574. old_disp_number = 0
  2575. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  2576. if self.units == 'MM':
  2577. current_tooldia = float('%.2f' % float(self.tooldia))
  2578. else:
  2579. current_tooldia = float('%.4f' % float(self.tooldia))
  2580. self.app.inform.emit(
  2581. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2582. str(current_tooldia),
  2583. str(self.units))
  2584. )
  2585. pt, geo = storage.nearest(current_pt)
  2586. try:
  2587. while True:
  2588. if self.app.abort_flag:
  2589. # graceful abort requested by the user
  2590. raise FlatCAMApp.GracefulException
  2591. path_count += 1
  2592. # Remove before modifying, otherwise deletion will fail.
  2593. storage.remove(geo)
  2594. # If last point in geometry is the nearest but prefer the first one if last point == first point
  2595. # then reverse coordinates.
  2596. if pt != geo.coords[0] and pt == geo.coords[-1]:
  2597. geo.coords = list(geo.coords)[::-1]
  2598. # ---------- Single depth/pass --------
  2599. if not multidepth:
  2600. # calculate the cut distance
  2601. total_cut = total_cut + geo.length
  2602. self.gcode += self.create_gcode_single_pass(geo, extracut, tolerance, old_point=current_pt)
  2603. # --------- Multi-pass ---------
  2604. else:
  2605. # calculate the cut distance
  2606. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  2607. nr_cuts = 0
  2608. depth = abs(self.z_cut)
  2609. while depth > 0:
  2610. nr_cuts += 1
  2611. depth -= float(self.z_depthpercut)
  2612. total_cut += (geo.length * nr_cuts)
  2613. self.gcode += self.create_gcode_multi_pass(geo, extracut, tolerance,
  2614. postproc=p, old_point=current_pt)
  2615. # calculate the total distance
  2616. total_travel = total_travel + abs(distance(pt1=current_pt, pt2=pt))
  2617. current_pt = geo.coords[-1]
  2618. pt, geo = storage.nearest(current_pt) # Next
  2619. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  2620. if old_disp_number < disp_number <= 100:
  2621. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2622. old_disp_number = disp_number
  2623. except StopIteration: # Nothing found in storage.
  2624. pass
  2625. log.debug("Finished G-Code... %s paths traced." % path_count)
  2626. # add move to end position
  2627. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  2628. self.travel_distance += total_travel + total_cut
  2629. self.routing_time += total_cut / self.feedrate
  2630. # Finish
  2631. self.gcode += self.doformat(p.spindle_stop_code)
  2632. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  2633. self.gcode += self.doformat(p.end_code, x=0, y=0)
  2634. self.app.inform.emit('%s... %s %s.' %
  2635. (_("Finished G-Code generation"),
  2636. str(path_count),
  2637. _("paths traced")
  2638. )
  2639. )
  2640. return self.gcode
  2641. def generate_from_geometry_2(
  2642. self, geometry, append=True,
  2643. tooldia=None, offset=0.0, tolerance=0,
  2644. z_cut=1.0, z_move=2.0,
  2645. feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  2646. spindlespeed=None, spindledir='CW', dwell=False, dwelltime=1.0,
  2647. multidepth=False, depthpercut=None,
  2648. toolchange=False, toolchangez=1.0, toolchangexy="0.0, 0.0",
  2649. extracut=False, startz=None, endz=2.0,
  2650. pp_geometry_name=None, tool_no=1):
  2651. """
  2652. Second algorithm to generate from Geometry.
  2653. Algorithm description:
  2654. ----------------------
  2655. Uses RTree to find the nearest path to follow.
  2656. :param geometry:
  2657. :param append:
  2658. :param tooldia:
  2659. :param tolerance:
  2660. :param multidepth: If True, use multiple passes to reach
  2661. the desired depth.
  2662. :param depthpercut: Maximum depth in each pass.
  2663. :param extracut: Adds (or not) an extra cut at the end of each path
  2664. overlapping the first point in path to ensure complete copper removal
  2665. :return: None
  2666. """
  2667. if not isinstance(geometry, Geometry):
  2668. self.app.inform.emit('[ERROR] %s: %s' %
  2669. (_("Expected a Geometry, got"), type(geometry)))
  2670. return 'fail'
  2671. log.debug("Generate_from_geometry_2()")
  2672. # if solid_geometry is empty raise an exception
  2673. if not geometry.solid_geometry:
  2674. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2675. _("Trying to generate a CNC Job "
  2676. "from a Geometry object without solid_geometry."))
  2677. temp_solid_geometry = []
  2678. def bounds_rec(obj):
  2679. if type(obj) is list:
  2680. minx = Inf
  2681. miny = Inf
  2682. maxx = -Inf
  2683. maxy = -Inf
  2684. for k in obj:
  2685. if type(k) is dict:
  2686. for key in k:
  2687. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  2688. minx = min(minx, minx_)
  2689. miny = min(miny, miny_)
  2690. maxx = max(maxx, maxx_)
  2691. maxy = max(maxy, maxy_)
  2692. else:
  2693. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2694. minx = min(minx, minx_)
  2695. miny = min(miny, miny_)
  2696. maxx = max(maxx, maxx_)
  2697. maxy = max(maxy, maxy_)
  2698. return minx, miny, maxx, maxy
  2699. else:
  2700. # it's a Shapely object, return it's bounds
  2701. return obj.bounds
  2702. if offset != 0.0:
  2703. offset_for_use = offset
  2704. if offset < 0:
  2705. a, b, c, d = bounds_rec(geometry.solid_geometry)
  2706. # if the offset is less than half of the total length or less than half of the total width of the
  2707. # solid geometry it's obvious we can't do the offset
  2708. if -offset > ((c - a) / 2) or -offset > ((d - b) / 2):
  2709. self.app.inform.emit('[ERROR_NOTCL] %s' % _(
  2710. "The Tool Offset value is too negative to use "
  2711. "for the current_geometry.\n"
  2712. "Raise the value (in module) and try again."))
  2713. return 'fail'
  2714. # hack: make offset smaller by 0.0000000001 which is insignificant difference but allow the job
  2715. # to continue
  2716. elif -offset == ((c - a) / 2) or -offset == ((d - b) / 2):
  2717. offset_for_use = offset - 0.0000000001
  2718. for it in geometry.solid_geometry:
  2719. # if the geometry is a closed shape then create a Polygon out of it
  2720. if isinstance(it, LineString):
  2721. c = it.coords
  2722. if c[0] == c[-1]:
  2723. it = Polygon(it)
  2724. temp_solid_geometry.append(it.buffer(offset_for_use, join_style=2))
  2725. else:
  2726. temp_solid_geometry = geometry.solid_geometry
  2727. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  2728. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  2729. log.debug("%d paths" % len(flat_geometry))
  2730. try:
  2731. self.tooldia = float(tooldia) if tooldia else None
  2732. except ValueError:
  2733. self.tooldia = [float(el) for el in tooldia.split(',') if el != ''] if tooldia else None
  2734. self.z_cut = float(z_cut) if z_cut else None
  2735. self.z_move = float(z_move) if z_move else None
  2736. self.feedrate = float(feedrate) if feedrate else None
  2737. self.z_feedrate = float(feedrate_z) if feedrate_z else None
  2738. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else None
  2739. self.spindlespeed = int(spindlespeed) if spindlespeed else None
  2740. self.spindledir = spindledir
  2741. self.dwell = dwell
  2742. self.dwelltime = float(dwelltime) if dwelltime else None
  2743. self.startz = float(startz) if startz else None
  2744. self.z_end = float(endz) if endz else None
  2745. self.z_depthpercut = float(depthpercut) if depthpercut else None
  2746. self.multidepth = multidepth
  2747. self.z_toolchange = float(toolchangez) if toolchangez else None
  2748. try:
  2749. if toolchangexy == '':
  2750. self.xy_toolchange = None
  2751. else:
  2752. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  2753. if len(self.xy_toolchange) < 2:
  2754. self.app.inform.emit('[ERROR] %s' %
  2755. _("The Toolchange X,Y field in Edit -> Preferences has to be "
  2756. "in the format (x, y) \nbut now there is only one value, not two. "))
  2757. return 'fail'
  2758. except Exception as e:
  2759. log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  2760. pass
  2761. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  2762. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  2763. if self.z_cut is None:
  2764. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2765. _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  2766. "other parameters."))
  2767. return 'fail'
  2768. if self.z_cut > 0:
  2769. self.app.inform.emit('[WARNING] %s' %
  2770. _("The Cut Z parameter has positive value. "
  2771. "It is the depth value to cut into material.\n"
  2772. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  2773. "therefore the app will convert the value to negative."
  2774. "Check the resulting CNC code (Gcode etc)."))
  2775. self.z_cut = -self.z_cut
  2776. elif self.z_cut == 0:
  2777. self.app.inform.emit('[WARNING] %s: %s' %
  2778. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  2779. geometry.options['name']))
  2780. return 'fail'
  2781. if self.z_move is None:
  2782. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2783. _("Travel Z parameter is None or zero."))
  2784. return 'fail'
  2785. if self.z_move < 0:
  2786. self.app.inform.emit('[WARNING] %s' %
  2787. _("The Travel Z parameter has negative value. "
  2788. "It is the height value to travel between cuts.\n"
  2789. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  2790. "therefore the app will convert the value to positive."
  2791. "Check the resulting CNC code (Gcode etc)."))
  2792. self.z_move = -self.z_move
  2793. elif self.z_move == 0:
  2794. self.app.inform.emit('[WARNING] %s: %s' %
  2795. (_("The Z Travel parameter is zero. "
  2796. "This is dangerous, skipping file"), self.options['name']))
  2797. return 'fail'
  2798. # made sure that depth_per_cut is no more then the z_cut
  2799. if abs(self.z_cut) < self.z_depthpercut:
  2800. self.z_depthpercut = abs(self.z_cut)
  2801. # ## Index first and last points in paths
  2802. # What points to index.
  2803. def get_pts(o):
  2804. return [o.coords[0], o.coords[-1]]
  2805. # Create the indexed storage.
  2806. storage = FlatCAMRTreeStorage()
  2807. storage.get_points = get_pts
  2808. # Store the geometry
  2809. log.debug("Indexing geometry before generating G-Code...")
  2810. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  2811. for shape in flat_geometry:
  2812. if self.app.abort_flag:
  2813. # graceful abort requested by the user
  2814. raise FlatCAMApp.GracefulException
  2815. if shape is not None: # TODO: This shouldn't have happened.
  2816. storage.insert(shape)
  2817. if not append:
  2818. self.gcode = ""
  2819. # tell postprocessor the number of tool (for toolchange)
  2820. self.tool = tool_no
  2821. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  2822. # given under the name 'toolC'
  2823. self.postdata['toolC'] = self.tooldia
  2824. # Initial G-Code
  2825. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  2826. p = self.pp_geometry
  2827. self.oldx = 0.0
  2828. self.oldy = 0.0
  2829. self.gcode = self.doformat(p.start_code)
  2830. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  2831. if toolchange is False:
  2832. self.gcode += self.doformat(p.lift_code, x=self.oldx , y=self.oldy ) # Move (up) to travel height
  2833. self.gcode += self.doformat(p.startz_code, x=self.oldx , y=self.oldy )
  2834. if toolchange:
  2835. # if "line_xyz" in self.pp_geometry_name:
  2836. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2837. # else:
  2838. # self.gcode += self.doformat(p.toolchange_code)
  2839. self.gcode += self.doformat(p.toolchange_code)
  2840. if 'laser' not in self.pp_geometry_name:
  2841. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2842. else:
  2843. # for laser this will disable the laser
  2844. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  2845. if self.dwell is True:
  2846. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2847. else:
  2848. if 'laser' not in self.pp_geometry_name:
  2849. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2850. if self.dwell is True:
  2851. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2852. total_travel = 0.0
  2853. total_cut = 0.0
  2854. # Iterate over geometry paths getting the nearest each time.
  2855. log.debug("Starting G-Code...")
  2856. self.app.inform.emit(_("Starting G-Code..."))
  2857. # variables to display the percentage of work done
  2858. geo_len = len(flat_geometry)
  2859. disp_number = 0
  2860. old_disp_number = 0
  2861. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  2862. if self.units == 'MM':
  2863. current_tooldia = float('%.2f' % float(self.tooldia))
  2864. else:
  2865. current_tooldia = float('%.4f' % float(self.tooldia))
  2866. self.app.inform.emit(
  2867. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2868. str(current_tooldia),
  2869. str(self.units))
  2870. )
  2871. path_count = 0
  2872. current_pt = (0, 0)
  2873. pt, geo = storage.nearest(current_pt)
  2874. try:
  2875. while True:
  2876. if self.app.abort_flag:
  2877. # graceful abort requested by the user
  2878. raise FlatCAMApp.GracefulException
  2879. path_count += 1
  2880. # Remove before modifying, otherwise deletion will fail.
  2881. storage.remove(geo)
  2882. # If last point in geometry is the nearest but prefer the first one if last point == first point
  2883. # then reverse coordinates.
  2884. if pt != geo.coords[0] and pt == geo.coords[-1]:
  2885. geo.coords = list(geo.coords)[::-1]
  2886. # ---------- Single depth/pass --------
  2887. if not multidepth:
  2888. # calculate the cut distance
  2889. total_cut += geo.length
  2890. self.gcode += self.create_gcode_single_pass(geo, extracut, tolerance, old_point=current_pt)
  2891. # --------- Multi-pass ---------
  2892. else:
  2893. # calculate the cut distance
  2894. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  2895. nr_cuts = 0
  2896. depth = abs(self.z_cut)
  2897. while depth > 0:
  2898. nr_cuts += 1
  2899. depth -= float(self.z_depthpercut)
  2900. total_cut += (geo.length * nr_cuts)
  2901. self.gcode += self.create_gcode_multi_pass(geo, extracut, tolerance,
  2902. postproc=p, old_point=current_pt)
  2903. # calculate the travel distance
  2904. total_travel += abs(distance(pt1=current_pt, pt2=pt))
  2905. current_pt = geo.coords[-1]
  2906. pt, geo = storage.nearest(current_pt) # Next
  2907. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  2908. if old_disp_number < disp_number <= 100:
  2909. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2910. old_disp_number = disp_number
  2911. except StopIteration: # Nothing found in storage.
  2912. pass
  2913. log.debug("Finishing G-Code... %s paths traced." % path_count)
  2914. # add move to end position
  2915. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  2916. self.travel_distance += total_travel + total_cut
  2917. self.routing_time += total_cut / self.feedrate
  2918. # Finish
  2919. self.gcode += self.doformat(p.spindle_stop_code)
  2920. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  2921. self.gcode += self.doformat(p.end_code, x=0, y=0)
  2922. self.app.inform.emit('%s... %s %s' %
  2923. (_("Finished G-Code generation"),
  2924. str(path_count),
  2925. _(" paths traced.")
  2926. )
  2927. )
  2928. return self.gcode
  2929. def generate_gcode_from_solderpaste_geo(self, **kwargs):
  2930. """
  2931. Algorithm to generate from multitool Geometry.
  2932. Algorithm description:
  2933. ----------------------
  2934. Uses RTree to find the nearest path to follow.
  2935. :return: Gcode string
  2936. """
  2937. log.debug("Generate_from_solderpaste_geometry()")
  2938. # ## Index first and last points in paths
  2939. # What points to index.
  2940. def get_pts(o):
  2941. return [o.coords[0], o.coords[-1]]
  2942. self.gcode = ""
  2943. if not kwargs:
  2944. log.debug("camlib.generate_from_solderpaste_geo() --> No tool in the solderpaste geometry.")
  2945. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2946. _("There is no tool data in the SolderPaste geometry."))
  2947. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  2948. # given under the name 'toolC'
  2949. self.postdata['z_start'] = kwargs['data']['tools_solderpaste_z_start']
  2950. self.postdata['z_dispense'] = kwargs['data']['tools_solderpaste_z_dispense']
  2951. self.postdata['z_stop'] = kwargs['data']['tools_solderpaste_z_stop']
  2952. self.postdata['z_travel'] = kwargs['data']['tools_solderpaste_z_travel']
  2953. self.postdata['z_toolchange'] = kwargs['data']['tools_solderpaste_z_toolchange']
  2954. self.postdata['xy_toolchange'] = kwargs['data']['tools_solderpaste_xy_toolchange']
  2955. self.postdata['frxy'] = kwargs['data']['tools_solderpaste_frxy']
  2956. self.postdata['frz'] = kwargs['data']['tools_solderpaste_frz']
  2957. self.postdata['frz_dispense'] = kwargs['data']['tools_solderpaste_frz_dispense']
  2958. self.postdata['speedfwd'] = kwargs['data']['tools_solderpaste_speedfwd']
  2959. self.postdata['dwellfwd'] = kwargs['data']['tools_solderpaste_dwellfwd']
  2960. self.postdata['speedrev'] = kwargs['data']['tools_solderpaste_speedrev']
  2961. self.postdata['dwellrev'] = kwargs['data']['tools_solderpaste_dwellrev']
  2962. self.postdata['pp_solderpaste_name'] = kwargs['data']['tools_solderpaste_pp']
  2963. self.postdata['toolC'] = kwargs['tooldia']
  2964. self.pp_solderpaste_name = kwargs['data']['tools_solderpaste_pp'] if kwargs['data']['tools_solderpaste_pp'] \
  2965. else self.app.defaults['tools_solderpaste_pp']
  2966. p = self.app.postprocessors[self.pp_solderpaste_name]
  2967. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  2968. flat_geometry = self.flatten(kwargs['solid_geometry'], pathonly=True)
  2969. log.debug("%d paths" % len(flat_geometry))
  2970. # Create the indexed storage.
  2971. storage = FlatCAMRTreeStorage()
  2972. storage.get_points = get_pts
  2973. # Store the geometry
  2974. log.debug("Indexing geometry before generating G-Code...")
  2975. for shape in flat_geometry:
  2976. if shape is not None:
  2977. storage.insert(shape)
  2978. # Initial G-Code
  2979. self.gcode = self.doformat(p.start_code)
  2980. self.gcode += self.doformat(p.spindle_off_code)
  2981. self.gcode += self.doformat(p.toolchange_code)
  2982. # ## Iterate over geometry paths getting the nearest each time.
  2983. log.debug("Starting SolderPaste G-Code...")
  2984. path_count = 0
  2985. current_pt = (0, 0)
  2986. # variables to display the percentage of work done
  2987. geo_len = len(flat_geometry)
  2988. disp_number = 0
  2989. old_disp_number = 0
  2990. pt, geo = storage.nearest(current_pt)
  2991. try:
  2992. while True:
  2993. if self.app.abort_flag:
  2994. # graceful abort requested by the user
  2995. raise FlatCAMApp.GracefulException
  2996. path_count += 1
  2997. # Remove before modifying, otherwise deletion will fail.
  2998. storage.remove(geo)
  2999. # If last point in geometry is the nearest but prefer the first one if last point == first point
  3000. # then reverse coordinates.
  3001. if pt != geo.coords[0] and pt == geo.coords[-1]:
  3002. geo.coords = list(geo.coords)[::-1]
  3003. self.gcode += self.create_soldepaste_gcode(geo, p=p, old_point=current_pt)
  3004. current_pt = geo.coords[-1]
  3005. pt, geo = storage.nearest(current_pt) # Next
  3006. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  3007. if old_disp_number < disp_number <= 100:
  3008. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3009. old_disp_number = disp_number
  3010. except StopIteration: # Nothing found in storage.
  3011. pass
  3012. log.debug("Finishing SolderPste G-Code... %s paths traced." % path_count)
  3013. self.app.inform.emit('%s... %s %s' %
  3014. (_("Finished SolderPste G-Code generation"),
  3015. str(path_count),
  3016. _("paths traced.")
  3017. )
  3018. )
  3019. # Finish
  3020. self.gcode += self.doformat(p.lift_code)
  3021. self.gcode += self.doformat(p.end_code)
  3022. return self.gcode
  3023. def create_soldepaste_gcode(self, geometry, p, old_point=(0, 0)):
  3024. gcode = ''
  3025. path = geometry.coords
  3026. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3027. if self.coordinates_type == "G90":
  3028. # For Absolute coordinates type G90
  3029. first_x = path[0][0]
  3030. first_y = path[0][1]
  3031. else:
  3032. # For Incremental coordinates type G91
  3033. first_x = path[0][0] - old_point[0]
  3034. first_y = path[0][1] - old_point[1]
  3035. if type(geometry) == LineString or type(geometry) == LinearRing:
  3036. # Move fast to 1st point
  3037. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  3038. # Move down to cutting depth
  3039. gcode += self.doformat(p.z_feedrate_code)
  3040. gcode += self.doformat(p.down_z_start_code)
  3041. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  3042. gcode += self.doformat(p.dwell_fwd_code)
  3043. gcode += self.doformat(p.feedrate_z_dispense_code)
  3044. gcode += self.doformat(p.lift_z_dispense_code)
  3045. gcode += self.doformat(p.feedrate_xy_code)
  3046. # Cutting...
  3047. prev_x = first_x
  3048. prev_y = first_y
  3049. for pt in path[1:]:
  3050. if self.coordinates_type == "G90":
  3051. # For Absolute coordinates type G90
  3052. next_x = pt[0]
  3053. next_y = pt[1]
  3054. else:
  3055. # For Incremental coordinates type G91
  3056. next_x = pt[0] - prev_x
  3057. next_y = pt[1] - prev_y
  3058. gcode += self.doformat(p.linear_code, x=next_x, y=next_y) # Linear motion to point
  3059. prev_x = next_x
  3060. prev_y = next_y
  3061. # Up to travelling height.
  3062. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  3063. gcode += self.doformat(p.spindle_rev_code)
  3064. gcode += self.doformat(p.down_z_stop_code)
  3065. gcode += self.doformat(p.spindle_off_code)
  3066. gcode += self.doformat(p.dwell_rev_code)
  3067. gcode += self.doformat(p.z_feedrate_code)
  3068. gcode += self.doformat(p.lift_code)
  3069. elif type(geometry) == Point:
  3070. gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  3071. gcode += self.doformat(p.feedrate_z_dispense_code)
  3072. gcode += self.doformat(p.down_z_start_code)
  3073. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  3074. gcode += self.doformat(p.dwell_fwd_code)
  3075. gcode += self.doformat(p.lift_z_dispense_code)
  3076. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  3077. gcode += self.doformat(p.spindle_rev_code)
  3078. gcode += self.doformat(p.spindle_off_code)
  3079. gcode += self.doformat(p.down_z_stop_code)
  3080. gcode += self.doformat(p.dwell_rev_code)
  3081. gcode += self.doformat(p.z_feedrate_code)
  3082. gcode += self.doformat(p.lift_code)
  3083. return gcode
  3084. def create_gcode_single_pass(self, geometry, extracut, tolerance, old_point=(0, 0)):
  3085. # G-code. Note: self.linear2gcode() and self.point2gcode() will lower and raise the tool every time.
  3086. gcode_single_pass = ''
  3087. if type(geometry) == LineString or type(geometry) == LinearRing:
  3088. if extracut is False:
  3089. gcode_single_pass = self.linear2gcode(geometry, tolerance=tolerance, old_point=old_point)
  3090. else:
  3091. if geometry.is_ring:
  3092. gcode_single_pass = self.linear2gcode_extra(geometry, tolerance=tolerance, old_point=old_point)
  3093. else:
  3094. gcode_single_pass = self.linear2gcode(geometry, tolerance=tolerance, old_point=old_point)
  3095. elif type(geometry) == Point:
  3096. gcode_single_pass = self.point2gcode(geometry)
  3097. else:
  3098. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  3099. return
  3100. return gcode_single_pass
  3101. def create_gcode_multi_pass(self, geometry, extracut, tolerance, postproc, old_point=(0, 0)):
  3102. gcode_multi_pass = ''
  3103. if isinstance(self.z_cut, Decimal):
  3104. z_cut = self.z_cut
  3105. else:
  3106. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  3107. if self.z_depthpercut is None:
  3108. self.z_depthpercut = z_cut
  3109. elif not isinstance(self.z_depthpercut, Decimal):
  3110. self.z_depthpercut = Decimal(self.z_depthpercut).quantize(Decimal('0.000000001'))
  3111. depth = 0
  3112. reverse = False
  3113. while depth > z_cut:
  3114. # Increase depth. Limit to z_cut.
  3115. depth -= self.z_depthpercut
  3116. if depth < z_cut:
  3117. depth = z_cut
  3118. # Cut at specific depth and do not lift the tool.
  3119. # Note: linear2gcode() will use G00 to move to the first point in the path, but it should be already
  3120. # at the first point if the tool is down (in the material). So, an extra G00 should show up but
  3121. # is inconsequential.
  3122. if type(geometry) == LineString or type(geometry) == LinearRing:
  3123. if extracut is False:
  3124. gcode_multi_pass += self.linear2gcode(geometry, tolerance=tolerance, z_cut=depth, up=False,
  3125. old_point=old_point)
  3126. else:
  3127. if geometry.is_ring:
  3128. gcode_multi_pass += self.linear2gcode_extra(geometry, tolerance=tolerance, z_cut=depth,
  3129. up=False, old_point=old_point)
  3130. else:
  3131. gcode_multi_pass += self.linear2gcode(geometry, tolerance=tolerance, z_cut=depth, up=False,
  3132. old_point=old_point)
  3133. # Ignore multi-pass for points.
  3134. elif type(geometry) == Point:
  3135. gcode_multi_pass += self.point2gcode(geometry, old_point=old_point)
  3136. break # Ignoring ...
  3137. else:
  3138. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  3139. # Reverse coordinates if not a loop so we can continue cutting without returning to the beginning.
  3140. if type(geometry) == LineString:
  3141. geometry.coords = list(geometry.coords)[::-1]
  3142. reverse = True
  3143. # If geometry is reversed, revert.
  3144. if reverse:
  3145. if type(geometry) == LineString:
  3146. geometry.coords = list(geometry.coords)[::-1]
  3147. # Lift the tool
  3148. gcode_multi_pass += self.doformat(postproc.lift_code, x=old_point[0], y=old_point[1])
  3149. return gcode_multi_pass
  3150. def codes_split(self, gline):
  3151. """
  3152. Parses a line of G-Code such as "G01 X1234 Y987" into
  3153. a dictionary: {'G': 1.0, 'X': 1234.0, 'Y': 987.0}
  3154. :param gline: G-Code line string
  3155. :return: Dictionary with parsed line.
  3156. """
  3157. command = {}
  3158. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  3159. match_z = re.search(r"^Z(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  3160. if match_z:
  3161. command['G'] = 0
  3162. command['X'] = float(match_z.group(1).replace(" ", "")) * 0.025
  3163. command['Y'] = float(match_z.group(2).replace(" ", "")) * 0.025
  3164. command['Z'] = float(match_z.group(3).replace(" ", "")) * 0.025
  3165. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  3166. match_pa = re.search(r"^PA(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  3167. if match_pa:
  3168. command['G'] = 0
  3169. command['X'] = float(match_pa.group(1).replace(" ", ""))
  3170. command['Y'] = float(match_pa.group(2).replace(" ", ""))
  3171. match_pen = re.search(r"^(P[U|D])", gline)
  3172. if match_pen:
  3173. if match_pen.group(1) == 'PU':
  3174. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  3175. # therefore the move is of kind T (travel)
  3176. command['Z'] = 1
  3177. else:
  3178. command['Z'] = 0
  3179. elif 'grbl_laser' in self.pp_excellon_name or 'grbl_laser' in self.pp_geometry_name or \
  3180. (self.pp_solderpaste_name is not None and 'Paste' in self.pp_solderpaste_name):
  3181. match_lsr = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  3182. if match_lsr:
  3183. command['X'] = float(match_lsr.group(1).replace(" ", ""))
  3184. command['Y'] = float(match_lsr.group(2).replace(" ", ""))
  3185. match_lsr_pos = re.search(r"^(M0[3|5])", gline)
  3186. if match_lsr_pos:
  3187. if 'M05' in match_lsr_pos.group(1):
  3188. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  3189. # therefore the move is of kind T (travel)
  3190. command['Z'] = 1
  3191. else:
  3192. command['Z'] = 0
  3193. elif self.pp_solderpaste_name is not None:
  3194. if 'Paste' in self.pp_solderpaste_name:
  3195. match_paste = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  3196. if match_paste:
  3197. command['X'] = float(match_paste.group(1).replace(" ", ""))
  3198. command['Y'] = float(match_paste.group(2).replace(" ", ""))
  3199. else:
  3200. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  3201. while match:
  3202. command[match.group(1)] = float(match.group(2).replace(" ", ""))
  3203. gline = gline[match.end():]
  3204. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  3205. return command
  3206. def gcode_parse(self):
  3207. """
  3208. G-Code parser (from self.gcode). Generates dictionary with
  3209. single-segment LineString's and "kind" indicating cut or travel,
  3210. fast or feedrate speed.
  3211. """
  3212. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  3213. # Results go here
  3214. geometry = []
  3215. # Last known instruction
  3216. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  3217. # Current path: temporary storage until tool is
  3218. # lifted or lowered.
  3219. if self.toolchange_xy_type == "excellon":
  3220. if self.app.defaults["excellon_toolchangexy"] == '':
  3221. pos_xy = [0, 0]
  3222. else:
  3223. pos_xy = [float(eval(a)) for a in self.app.defaults["excellon_toolchangexy"].split(",")]
  3224. else:
  3225. if self.app.defaults["geometry_toolchangexy"] == '':
  3226. pos_xy = [0, 0]
  3227. else:
  3228. pos_xy = [float(eval(a)) for a in self.app.defaults["geometry_toolchangexy"].split(",")]
  3229. path = [pos_xy]
  3230. # path = [(0, 0)]
  3231. # Process every instruction
  3232. for line in StringIO(self.gcode):
  3233. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  3234. return "fail"
  3235. gobj = self.codes_split(line)
  3236. # ## Units
  3237. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  3238. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  3239. continue
  3240. # ## Changing height
  3241. if 'Z' in gobj:
  3242. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  3243. pass
  3244. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  3245. pass
  3246. elif 'laser' in self.pp_excellon_name or 'laser' in self.pp_geometry_name:
  3247. pass
  3248. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  3249. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  3250. pass
  3251. else:
  3252. log.warning("Non-orthogonal motion: From %s" % str(current))
  3253. log.warning(" To: %s" % str(gobj))
  3254. current['Z'] = gobj['Z']
  3255. # Store the path into geometry and reset path
  3256. if len(path) > 1:
  3257. geometry.append({"geom": LineString(path),
  3258. "kind": kind})
  3259. path = [path[-1]] # Start with the last point of last path.
  3260. # create the geometry for the holes created when drilling Excellon drills
  3261. if self.origin_kind == 'excellon':
  3262. if current['Z'] < 0:
  3263. current_drill_point_coords = (float('%.4f' % current['X']), float('%.4f' % current['Y']))
  3264. # find the drill diameter knowing the drill coordinates
  3265. for pt_dict in self.exc_drills:
  3266. point_in_dict_coords = (float('%.4f' % pt_dict['point'].x),
  3267. float('%.4f' % pt_dict['point'].y))
  3268. if point_in_dict_coords == current_drill_point_coords:
  3269. tool = pt_dict['tool']
  3270. dia = self.exc_tools[tool]['C']
  3271. kind = ['C', 'F']
  3272. geometry.append({"geom": Point(current_drill_point_coords).
  3273. buffer(dia/2).exterior,
  3274. "kind": kind})
  3275. break
  3276. if 'G' in gobj:
  3277. current['G'] = int(gobj['G'])
  3278. if 'X' in gobj or 'Y' in gobj:
  3279. if 'X' in gobj:
  3280. x = gobj['X']
  3281. # current['X'] = x
  3282. else:
  3283. x = current['X']
  3284. if 'Y' in gobj:
  3285. y = gobj['Y']
  3286. else:
  3287. y = current['Y']
  3288. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  3289. if current['Z'] > 0:
  3290. kind[0] = 'T'
  3291. if current['G'] > 0:
  3292. kind[1] = 'S'
  3293. if current['G'] in [0, 1]: # line
  3294. path.append((x, y))
  3295. arcdir = [None, None, "cw", "ccw"]
  3296. if current['G'] in [2, 3]: # arc
  3297. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  3298. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  3299. start = arctan2(-gobj['J'], -gobj['I'])
  3300. stop = arctan2(-center[1] + y, -center[0] + x)
  3301. path += arc(center, radius, start, stop, arcdir[current['G']], int(self.steps_per_circle / 4))
  3302. # Update current instruction
  3303. for code in gobj:
  3304. current[code] = gobj[code]
  3305. # There might not be a change in height at the
  3306. # end, therefore, see here too if there is
  3307. # a final path.
  3308. if len(path) > 1:
  3309. geometry.append({"geom": LineString(path),
  3310. "kind": kind})
  3311. self.gcode_parsed = geometry
  3312. return geometry
  3313. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  3314. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  3315. # alpha={"T": 0.3, "C": 1.0}):
  3316. # """
  3317. # Creates a Matplotlib figure with a plot of the
  3318. # G-code job.
  3319. # """
  3320. # if tooldia is None:
  3321. # tooldia = self.tooldia
  3322. #
  3323. # fig = Figure(dpi=dpi)
  3324. # ax = fig.add_subplot(111)
  3325. # ax.set_aspect(1)
  3326. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  3327. # ax.set_xlim(xmin-margin, xmax+margin)
  3328. # ax.set_ylim(ymin-margin, ymax+margin)
  3329. #
  3330. # if tooldia == 0:
  3331. # for geo in self.gcode_parsed:
  3332. # linespec = '--'
  3333. # linecolor = color[geo['kind'][0]][1]
  3334. # if geo['kind'][0] == 'C':
  3335. # linespec = 'k-'
  3336. # x, y = geo['geom'].coords.xy
  3337. # ax.plot(x, y, linespec, color=linecolor)
  3338. # else:
  3339. # for geo in self.gcode_parsed:
  3340. # poly = geo['geom'].buffer(tooldia/2.0)
  3341. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  3342. # edgecolor=color[geo['kind'][0]][1],
  3343. # alpha=alpha[geo['kind'][0]], zorder=2)
  3344. # ax.add_patch(patch)
  3345. #
  3346. # return fig
  3347. def plot2(self, tooldia=None, dpi=75, margin=0.1, gcode_parsed=None,
  3348. color={"T": ["#F0E24D4C", "#B5AB3A4C"], "C": ["#5E6CFFFF", "#4650BDFF"]},
  3349. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005, obj=None, visible=False, kind='all'):
  3350. """
  3351. Plots the G-code job onto the given axes.
  3352. :param tooldia: Tool diameter.
  3353. :param dpi: Not used!
  3354. :param margin: Not used!
  3355. :param color: Color specification.
  3356. :param alpha: Transparency specification.
  3357. :param tool_tolerance: Tolerance when drawing the toolshape.
  3358. :param obj
  3359. :param visible
  3360. :param kind
  3361. :return: None
  3362. """
  3363. # units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3364. gcode_parsed = gcode_parsed if gcode_parsed else self.gcode_parsed
  3365. path_num = 0
  3366. if tooldia is None:
  3367. tooldia = self.tooldia
  3368. # this should be unlikely unless when upstream the tooldia is a tuple made by one dia and a comma like (2.4,)
  3369. if isinstance(tooldia, list):
  3370. tooldia = tooldia[0] if tooldia[0] is not None else self.tooldia
  3371. if tooldia == 0:
  3372. for geo in gcode_parsed:
  3373. if kind == 'all':
  3374. obj.add_shape(shape=geo['geom'], color=color[geo['kind'][0]][1], visible=visible)
  3375. elif kind == 'travel':
  3376. if geo['kind'][0] == 'T':
  3377. obj.add_shape(shape=geo['geom'], color=color['T'][1], visible=visible)
  3378. elif kind == 'cut':
  3379. if geo['kind'][0] == 'C':
  3380. obj.add_shape(shape=geo['geom'], color=color['C'][1], visible=visible)
  3381. else:
  3382. text = []
  3383. pos = []
  3384. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3385. if self.coordinates_type == "G90":
  3386. # For Absolute coordinates type G90
  3387. for geo in gcode_parsed:
  3388. if geo['kind'][0] == 'T':
  3389. current_position = geo['geom'].coords[0]
  3390. if current_position not in pos:
  3391. pos.append(current_position)
  3392. path_num += 1
  3393. text.append(str(path_num))
  3394. current_position = geo['geom'].coords[-1]
  3395. if current_position not in pos:
  3396. pos.append(current_position)
  3397. path_num += 1
  3398. text.append(str(path_num))
  3399. # plot the geometry of Excellon objects
  3400. if self.origin_kind == 'excellon':
  3401. try:
  3402. poly = Polygon(geo['geom'])
  3403. except ValueError:
  3404. # if the geos are travel lines it will enter into Exception
  3405. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3406. poly = poly.simplify(tool_tolerance)
  3407. else:
  3408. # plot the geometry of any objects other than Excellon
  3409. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3410. poly = poly.simplify(tool_tolerance)
  3411. if kind == 'all':
  3412. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  3413. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  3414. elif kind == 'travel':
  3415. if geo['kind'][0] == 'T':
  3416. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  3417. visible=visible, layer=2)
  3418. elif kind == 'cut':
  3419. if geo['kind'][0] == 'C':
  3420. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  3421. visible=visible, layer=1)
  3422. else:
  3423. # For Incremental coordinates type G91
  3424. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3425. _('G91 coordinates not implemented ...'))
  3426. for geo in gcode_parsed:
  3427. if geo['kind'][0] == 'T':
  3428. current_position = geo['geom'].coords[0]
  3429. if current_position not in pos:
  3430. pos.append(current_position)
  3431. path_num += 1
  3432. text.append(str(path_num))
  3433. current_position = geo['geom'].coords[-1]
  3434. if current_position not in pos:
  3435. pos.append(current_position)
  3436. path_num += 1
  3437. text.append(str(path_num))
  3438. # plot the geometry of Excellon objects
  3439. if self.origin_kind == 'excellon':
  3440. try:
  3441. poly = Polygon(geo['geom'])
  3442. except ValueError:
  3443. # if the geos are travel lines it will enter into Exception
  3444. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3445. poly = poly.simplify(tool_tolerance)
  3446. else:
  3447. # plot the geometry of any objects other than Excellon
  3448. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3449. poly = poly.simplify(tool_tolerance)
  3450. if kind == 'all':
  3451. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  3452. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  3453. elif kind == 'travel':
  3454. if geo['kind'][0] == 'T':
  3455. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  3456. visible=visible, layer=2)
  3457. elif kind == 'cut':
  3458. if geo['kind'][0] == 'C':
  3459. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  3460. visible=visible, layer=1)
  3461. # current_x = gcode_parsed[0]['geom'].coords[0][0]
  3462. # current_y = gcode_parsed[0]['geom'].coords[0][1]
  3463. # old_pos = (
  3464. # current_x,
  3465. # current_y
  3466. # )
  3467. #
  3468. # for geo in gcode_parsed:
  3469. # if geo['kind'][0] == 'T':
  3470. # current_position = (
  3471. # geo['geom'].coords[0][0] + old_pos[0],
  3472. # geo['geom'].coords[0][1] + old_pos[1]
  3473. # )
  3474. # if current_position not in pos:
  3475. # pos.append(current_position)
  3476. # path_num += 1
  3477. # text.append(str(path_num))
  3478. #
  3479. # delta = (
  3480. # geo['geom'].coords[-1][0] - geo['geom'].coords[0][0],
  3481. # geo['geom'].coords[-1][1] - geo['geom'].coords[0][1]
  3482. # )
  3483. # current_position = (
  3484. # current_position[0] + geo['geom'].coords[-1][0],
  3485. # current_position[1] + geo['geom'].coords[-1][1]
  3486. # )
  3487. # if current_position not in pos:
  3488. # pos.append(current_position)
  3489. # path_num += 1
  3490. # text.append(str(path_num))
  3491. #
  3492. # # plot the geometry of Excellon objects
  3493. # if self.origin_kind == 'excellon':
  3494. # if isinstance(geo['geom'], Point):
  3495. # # if geo is Point
  3496. # current_position = (
  3497. # current_position[0] + geo['geom'].x,
  3498. # current_position[1] + geo['geom'].y
  3499. # )
  3500. # poly = Polygon(Point(current_position))
  3501. # elif isinstance(geo['geom'], LineString):
  3502. # # if the geos are travel lines (LineStrings)
  3503. # new_line_pts = []
  3504. # old_line_pos = deepcopy(current_position)
  3505. # for p in list(geo['geom'].coords):
  3506. # current_position = (
  3507. # current_position[0] + p[0],
  3508. # current_position[1] + p[1]
  3509. # )
  3510. # new_line_pts.append(current_position)
  3511. # old_line_pos = p
  3512. # new_line = LineString(new_line_pts)
  3513. #
  3514. # poly = new_line.buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3515. # poly = poly.simplify(tool_tolerance)
  3516. # else:
  3517. # # plot the geometry of any objects other than Excellon
  3518. # new_line_pts = []
  3519. # old_line_pos = deepcopy(current_position)
  3520. # for p in list(geo['geom'].coords):
  3521. # current_position = (
  3522. # current_position[0] + p[0],
  3523. # current_position[1] + p[1]
  3524. # )
  3525. # new_line_pts.append(current_position)
  3526. # old_line_pos = p
  3527. # new_line = LineString(new_line_pts)
  3528. #
  3529. # poly = new_line.buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3530. # poly = poly.simplify(tool_tolerance)
  3531. #
  3532. # old_pos = deepcopy(current_position)
  3533. #
  3534. # if kind == 'all':
  3535. # obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  3536. # visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  3537. # elif kind == 'travel':
  3538. # if geo['kind'][0] == 'T':
  3539. # obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  3540. # visible=visible, layer=2)
  3541. # elif kind == 'cut':
  3542. # if geo['kind'][0] == 'C':
  3543. # obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  3544. # visible=visible, layer=1)
  3545. try:
  3546. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  3547. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  3548. color=self.app.defaults["cncjob_annotation_fontcolor"])
  3549. except Exception as e:
  3550. pass
  3551. def create_geometry(self):
  3552. # TODO: This takes forever. Too much data?
  3553. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  3554. return self.solid_geometry
  3555. # code snippet added by Lei Zheng in a rejected pull request on FlatCAM https://bitbucket.org/realthunder/
  3556. def segment(self, coords):
  3557. """
  3558. break long linear lines to make it more auto level friendly
  3559. """
  3560. if len(coords) < 2 or self.segx <= 0 and self.segy <= 0:
  3561. return list(coords)
  3562. path = [coords[0]]
  3563. # break the line in either x or y dimension only
  3564. def linebreak_single(line, dim, dmax):
  3565. if dmax <= 0:
  3566. return None
  3567. if line[1][dim] > line[0][dim]:
  3568. sign = 1.0
  3569. d = line[1][dim] - line[0][dim]
  3570. else:
  3571. sign = -1.0
  3572. d = line[0][dim] - line[1][dim]
  3573. if d > dmax:
  3574. # make sure we don't make any new lines too short
  3575. if d > dmax * 2:
  3576. dd = dmax
  3577. else:
  3578. dd = d / 2
  3579. other = dim ^ 1
  3580. return (line[0][dim] + dd * sign, line[0][other] + \
  3581. dd * (line[1][other] - line[0][other]) / d)
  3582. return None
  3583. # recursively breaks down a given line until it is within the
  3584. # required step size
  3585. def linebreak(line):
  3586. pt_new = linebreak_single(line, 0, self.segx)
  3587. if pt_new is None:
  3588. pt_new2 = linebreak_single(line, 1, self.segy)
  3589. else:
  3590. pt_new2 = linebreak_single((line[0], pt_new), 1, self.segy)
  3591. if pt_new2 is not None:
  3592. pt_new = pt_new2[::-1]
  3593. if pt_new is None:
  3594. path.append(line[1])
  3595. else:
  3596. path.append(pt_new)
  3597. linebreak((pt_new, line[1]))
  3598. for pt in coords[1:]:
  3599. linebreak((path[-1], pt))
  3600. return path
  3601. def linear2gcode(self, linear, tolerance=0, down=True, up=True,
  3602. z_cut=None, z_move=None, zdownrate=None,
  3603. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  3604. """
  3605. Generates G-code to cut along the linear feature.
  3606. :param linear: The path to cut along.
  3607. :type: Shapely.LinearRing or Shapely.Linear String
  3608. :param tolerance: All points in the simplified object will be within the
  3609. tolerance distance of the original geometry.
  3610. :type tolerance: float
  3611. :param feedrate: speed for cut on X - Y plane
  3612. :param feedrate_z: speed for cut on Z plane
  3613. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  3614. :return: G-code to cut along the linear feature.
  3615. :rtype: str
  3616. """
  3617. if z_cut is None:
  3618. z_cut = self.z_cut
  3619. if z_move is None:
  3620. z_move = self.z_move
  3621. #
  3622. # if zdownrate is None:
  3623. # zdownrate = self.zdownrate
  3624. if feedrate is None:
  3625. feedrate = self.feedrate
  3626. if feedrate_z is None:
  3627. feedrate_z = self.z_feedrate
  3628. if feedrate_rapid is None:
  3629. feedrate_rapid = self.feedrate_rapid
  3630. # Simplify paths?
  3631. if tolerance > 0:
  3632. target_linear = linear.simplify(tolerance)
  3633. else:
  3634. target_linear = linear
  3635. gcode = ""
  3636. # path = list(target_linear.coords)
  3637. path = self.segment(target_linear.coords)
  3638. p = self.pp_geometry
  3639. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3640. if self.coordinates_type == "G90":
  3641. # For Absolute coordinates type G90
  3642. first_x = path[0][0]
  3643. first_y = path[0][1]
  3644. else:
  3645. # For Incremental coordinates type G91
  3646. first_x = path[0][0] - old_point[0]
  3647. first_y = path[0][1] - old_point[1]
  3648. # Move fast to 1st point
  3649. if not cont:
  3650. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  3651. # Move down to cutting depth
  3652. if down:
  3653. # Different feedrate for vertical cut?
  3654. gcode += self.doformat(p.z_feedrate_code)
  3655. # gcode += self.doformat(p.feedrate_code)
  3656. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  3657. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  3658. # Cutting...
  3659. prev_x = first_x
  3660. prev_y = first_y
  3661. for pt in path[1:]:
  3662. if self.app.abort_flag:
  3663. # graceful abort requested by the user
  3664. raise FlatCAMApp.GracefulException
  3665. if self.coordinates_type == "G90":
  3666. # For Absolute coordinates type G90
  3667. next_x = pt[0]
  3668. next_y = pt[1]
  3669. else:
  3670. # For Incremental coordinates type G91
  3671. # next_x = pt[0] - prev_x
  3672. # next_y = pt[1] - prev_y
  3673. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3674. _('G91 coordinates not implemented ...'))
  3675. next_x = pt[0]
  3676. next_y = pt[1]
  3677. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  3678. prev_x = pt[0]
  3679. prev_y = pt[1]
  3680. # Up to travelling height.
  3681. if up:
  3682. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # Stop cutting
  3683. return gcode
  3684. def linear2gcode_extra(self, linear, tolerance=0, down=True, up=True,
  3685. z_cut=None, z_move=None, zdownrate=None,
  3686. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  3687. """
  3688. Generates G-code to cut along the linear feature.
  3689. :param linear: The path to cut along.
  3690. :type: Shapely.LinearRing or Shapely.Linear String
  3691. :param tolerance: All points in the simplified object will be within the
  3692. tolerance distance of the original geometry.
  3693. :type tolerance: float
  3694. :param feedrate: speed for cut on X - Y plane
  3695. :param feedrate_z: speed for cut on Z plane
  3696. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  3697. :return: G-code to cut along the linear feature.
  3698. :rtype: str
  3699. """
  3700. if z_cut is None:
  3701. z_cut = self.z_cut
  3702. if z_move is None:
  3703. z_move = self.z_move
  3704. #
  3705. # if zdownrate is None:
  3706. # zdownrate = self.zdownrate
  3707. if feedrate is None:
  3708. feedrate = self.feedrate
  3709. if feedrate_z is None:
  3710. feedrate_z = self.z_feedrate
  3711. if feedrate_rapid is None:
  3712. feedrate_rapid = self.feedrate_rapid
  3713. # Simplify paths?
  3714. if tolerance > 0:
  3715. target_linear = linear.simplify(tolerance)
  3716. else:
  3717. target_linear = linear
  3718. gcode = ""
  3719. path = list(target_linear.coords)
  3720. p = self.pp_geometry
  3721. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3722. if self.coordinates_type == "G90":
  3723. # For Absolute coordinates type G90
  3724. first_x = path[0][0]
  3725. first_y = path[0][1]
  3726. else:
  3727. # For Incremental coordinates type G91
  3728. first_x = path[0][0] - old_point[0]
  3729. first_y = path[0][1] - old_point[1]
  3730. # Move fast to 1st point
  3731. if not cont:
  3732. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  3733. # Move down to cutting depth
  3734. if down:
  3735. # Different feedrate for vertical cut?
  3736. if self.z_feedrate is not None:
  3737. gcode += self.doformat(p.z_feedrate_code)
  3738. # gcode += self.doformat(p.feedrate_code)
  3739. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  3740. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  3741. else:
  3742. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut) # Start cutting
  3743. # Cutting...
  3744. prev_x = first_x
  3745. prev_y = first_y
  3746. for pt in path[1:]:
  3747. if self.app.abort_flag:
  3748. # graceful abort requested by the user
  3749. raise FlatCAMApp.GracefulException
  3750. if self.coordinates_type == "G90":
  3751. # For Absolute coordinates type G90
  3752. next_x = pt[0]
  3753. next_y = pt[1]
  3754. else:
  3755. # For Incremental coordinates type G91
  3756. # For Incremental coordinates type G91
  3757. # next_x = pt[0] - prev_x
  3758. # next_y = pt[1] - prev_y
  3759. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3760. _('G91 coordinates not implemented ...'))
  3761. next_x = pt[0]
  3762. next_y = pt[1]
  3763. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  3764. prev_x = pt[0]
  3765. prev_y = pt[1]
  3766. # this line is added to create an extra cut over the first point in patch
  3767. # to make sure that we remove the copper leftovers
  3768. # Linear motion to the 1st point in the cut path
  3769. if self.coordinates_type == "G90":
  3770. # For Absolute coordinates type G90
  3771. last_x = path[1][0]
  3772. last_y = path[1][1]
  3773. else:
  3774. # For Incremental coordinates type G91
  3775. last_x = path[1][0] - first_x
  3776. last_y = path[1][1] - first_y
  3777. gcode += self.doformat(p.linear_code, x=last_x, y=last_y)
  3778. # Up to travelling height.
  3779. if up:
  3780. gcode += self.doformat(p.lift_code, x=last_x, y=last_y, z_move=z_move) # Stop cutting
  3781. return gcode
  3782. def point2gcode(self, point, old_point=(0, 0)):
  3783. gcode = ""
  3784. if self.app.abort_flag:
  3785. # graceful abort requested by the user
  3786. raise FlatCAMApp.GracefulException
  3787. path = list(point.coords)
  3788. p = self.pp_geometry
  3789. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3790. if self.coordinates_type == "G90":
  3791. # For Absolute coordinates type G90
  3792. first_x = path[0][0]
  3793. first_y = path[0][1]
  3794. else:
  3795. # For Incremental coordinates type G91
  3796. # first_x = path[0][0] - old_point[0]
  3797. # first_y = path[0][1] - old_point[1]
  3798. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3799. _('G91 coordinates not implemented ...'))
  3800. first_x = path[0][0]
  3801. first_y = path[0][1]
  3802. gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  3803. if self.z_feedrate is not None:
  3804. gcode += self.doformat(p.z_feedrate_code)
  3805. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut = self.z_cut)
  3806. gcode += self.doformat(p.feedrate_code)
  3807. else:
  3808. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut = self.z_cut) # Start cutting
  3809. gcode += self.doformat(p.lift_code, x=first_x, y=first_y) # Stop cutting
  3810. return gcode
  3811. def export_svg(self, scale_factor=0.00):
  3812. """
  3813. Exports the CNC Job as a SVG Element
  3814. :scale_factor: float
  3815. :return: SVG Element string
  3816. """
  3817. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  3818. # If not specified then try and use the tool diameter
  3819. # This way what is on screen will match what is outputed for the svg
  3820. # This is quite a useful feature for svg's used with visicut
  3821. if scale_factor <= 0:
  3822. scale_factor = self.options['tooldia'] / 2
  3823. # If still 0 then default to 0.05
  3824. # This value appears to work for zooming, and getting the output svg line width
  3825. # to match that viewed on screen with FlatCam
  3826. if scale_factor == 0:
  3827. scale_factor = 0.01
  3828. # Separate the list of cuts and travels into 2 distinct lists
  3829. # This way we can add different formatting / colors to both
  3830. cuts = []
  3831. travels = []
  3832. for g in self.gcode_parsed:
  3833. if self.app.abort_flag:
  3834. # graceful abort requested by the user
  3835. raise FlatCAMApp.GracefulException
  3836. if g['kind'][0] == 'C': cuts.append(g)
  3837. if g['kind'][0] == 'T': travels.append(g)
  3838. # Used to determine the overall board size
  3839. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  3840. # Convert the cuts and travels into single geometry objects we can render as svg xml
  3841. if travels:
  3842. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  3843. if self.app.abort_flag:
  3844. # graceful abort requested by the user
  3845. raise FlatCAMApp.GracefulException
  3846. if cuts:
  3847. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  3848. # Render the SVG Xml
  3849. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  3850. # It's better to have the travels sitting underneath the cuts for visicut
  3851. svg_elem = ""
  3852. if travels:
  3853. svg_elem = travelsgeom.svg(scale_factor=scale_factor, stroke_color="#F0E24D")
  3854. if cuts:
  3855. svg_elem += cutsgeom.svg(scale_factor=scale_factor, stroke_color="#5E6CFF")
  3856. return svg_elem
  3857. def bounds(self):
  3858. """
  3859. Returns coordinates of rectangular bounds
  3860. of geometry: (xmin, ymin, xmax, ymax).
  3861. """
  3862. # fixed issue of getting bounds only for one level lists of objects
  3863. # now it can get bounds for nested lists of objects
  3864. log.debug("camlib.CNCJob.bounds()")
  3865. def bounds_rec(obj):
  3866. if type(obj) is list:
  3867. minx = Inf
  3868. miny = Inf
  3869. maxx = -Inf
  3870. maxy = -Inf
  3871. for k in obj:
  3872. if type(k) is dict:
  3873. for key in k:
  3874. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  3875. minx = min(minx, minx_)
  3876. miny = min(miny, miny_)
  3877. maxx = max(maxx, maxx_)
  3878. maxy = max(maxy, maxy_)
  3879. else:
  3880. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3881. minx = min(minx, minx_)
  3882. miny = min(miny, miny_)
  3883. maxx = max(maxx, maxx_)
  3884. maxy = max(maxy, maxy_)
  3885. return minx, miny, maxx, maxy
  3886. else:
  3887. # it's a Shapely object, return it's bounds
  3888. return obj.bounds
  3889. if self.multitool is False:
  3890. log.debug("CNCJob->bounds()")
  3891. if self.solid_geometry is None:
  3892. log.debug("solid_geometry is None")
  3893. return 0, 0, 0, 0
  3894. bounds_coords = bounds_rec(self.solid_geometry)
  3895. else:
  3896. minx = Inf
  3897. miny = Inf
  3898. maxx = -Inf
  3899. maxy = -Inf
  3900. for k, v in self.cnc_tools.items():
  3901. minx = Inf
  3902. miny = Inf
  3903. maxx = -Inf
  3904. maxy = -Inf
  3905. try:
  3906. for k in v['solid_geometry']:
  3907. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3908. minx = min(minx, minx_)
  3909. miny = min(miny, miny_)
  3910. maxx = max(maxx, maxx_)
  3911. maxy = max(maxy, maxy_)
  3912. except TypeError:
  3913. minx_, miny_, maxx_, maxy_ = bounds_rec(v['solid_geometry'])
  3914. minx = min(minx, minx_)
  3915. miny = min(miny, miny_)
  3916. maxx = max(maxx, maxx_)
  3917. maxy = max(maxy, maxy_)
  3918. bounds_coords = minx, miny, maxx, maxy
  3919. return bounds_coords
  3920. # TODO This function should be replaced at some point with a "real" function. Until then it's an ugly hack ...
  3921. def scale(self, xfactor, yfactor=None, point=None):
  3922. """
  3923. Scales all the geometry on the XY plane in the object by the
  3924. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  3925. not altered.
  3926. :param factor: Number by which to scale the object.
  3927. :type factor: float
  3928. :param point: the (x,y) coords for the point of origin of scale
  3929. :type tuple of floats
  3930. :return: None
  3931. :rtype: None
  3932. """
  3933. log.debug("camlib.CNCJob.scale()")
  3934. if yfactor is None:
  3935. yfactor = xfactor
  3936. if point is None:
  3937. px = 0
  3938. py = 0
  3939. else:
  3940. px, py = point
  3941. def scale_g(g):
  3942. """
  3943. :param g: 'g' parameter it's a gcode string
  3944. :return: scaled gcode string
  3945. """
  3946. temp_gcode = ''
  3947. header_start = False
  3948. header_stop = False
  3949. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3950. lines = StringIO(g)
  3951. for line in lines:
  3952. # this changes the GCODE header ---- UGLY HACK
  3953. if "TOOL DIAMETER" in line or "Feedrate:" in line:
  3954. header_start = True
  3955. if "G20" in line or "G21" in line:
  3956. header_start = False
  3957. header_stop = True
  3958. if header_start is True:
  3959. header_stop = False
  3960. if "in" in line:
  3961. if units == 'MM':
  3962. line = line.replace("in", "mm")
  3963. if "mm" in line:
  3964. if units == 'IN':
  3965. line = line.replace("mm", "in")
  3966. # find any float number in header (even multiple on the same line) and convert it
  3967. numbers_in_header = re.findall(self.g_nr_re, line)
  3968. if numbers_in_header:
  3969. for nr in numbers_in_header:
  3970. new_nr = float(nr) * xfactor
  3971. # replace the updated string
  3972. line = line.replace(nr, ('%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_nr))
  3973. )
  3974. # this scales all the X and Y and Z and F values and also the Tool Dia in the toolchange message
  3975. if header_stop is True:
  3976. if "G20" in line:
  3977. if units == 'MM':
  3978. line = line.replace("G20", "G21")
  3979. if "G21" in line:
  3980. if units == 'IN':
  3981. line = line.replace("G21", "G20")
  3982. # find the X group
  3983. match_x = self.g_x_re.search(line)
  3984. if match_x:
  3985. if match_x.group(1) is not None:
  3986. new_x = float(match_x.group(1)[1:]) * xfactor
  3987. # replace the updated string
  3988. line = line.replace(
  3989. match_x.group(1),
  3990. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  3991. )
  3992. # find the Y group
  3993. match_y = self.g_y_re.search(line)
  3994. if match_y:
  3995. if match_y.group(1) is not None:
  3996. new_y = float(match_y.group(1)[1:]) * yfactor
  3997. line = line.replace(
  3998. match_y.group(1),
  3999. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  4000. )
  4001. # find the Z group
  4002. match_z = self.g_z_re.search(line)
  4003. if match_z:
  4004. if match_z.group(1) is not None:
  4005. new_z = float(match_z.group(1)[1:]) * xfactor
  4006. line = line.replace(
  4007. match_z.group(1),
  4008. 'Z%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_z)
  4009. )
  4010. # find the F group
  4011. match_f = self.g_f_re.search(line)
  4012. if match_f:
  4013. if match_f.group(1) is not None:
  4014. new_f = float(match_f.group(1)[1:]) * xfactor
  4015. line = line.replace(
  4016. match_f.group(1),
  4017. 'F%.*f' % (self.app.defaults["cncjob_fr_decimals"], new_f)
  4018. )
  4019. # find the T group (tool dia on toolchange)
  4020. match_t = self.g_t_re.search(line)
  4021. if match_t:
  4022. if match_t.group(1) is not None:
  4023. new_t = float(match_t.group(1)[1:]) * xfactor
  4024. line = line.replace(
  4025. match_t.group(1),
  4026. '= %.*f' % (self.app.defaults["cncjob_coords_decimals"], new_t)
  4027. )
  4028. temp_gcode += line
  4029. lines.close()
  4030. header_stop = False
  4031. return temp_gcode
  4032. if self.multitool is False:
  4033. # offset Gcode
  4034. self.gcode = scale_g(self.gcode)
  4035. # variables to display the percentage of work done
  4036. self.geo_len = 0
  4037. try:
  4038. for g in self.gcode_parsed:
  4039. self.geo_len += 1
  4040. except TypeError:
  4041. self.geo_len = 1
  4042. self.old_disp_number = 0
  4043. self.el_count = 0
  4044. # scale geometry
  4045. for g in self.gcode_parsed:
  4046. try:
  4047. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  4048. except AttributeError:
  4049. return g['geom']
  4050. self.el_count += 1
  4051. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4052. if self.old_disp_number < disp_number <= 100:
  4053. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4054. self.old_disp_number = disp_number
  4055. self.create_geometry()
  4056. else:
  4057. for k, v in self.cnc_tools.items():
  4058. # scale Gcode
  4059. v['gcode'] = scale_g(v['gcode'])
  4060. # variables to display the percentage of work done
  4061. self.geo_len = 0
  4062. try:
  4063. for g in v['gcode_parsed']:
  4064. self.geo_len += 1
  4065. except TypeError:
  4066. self.geo_len = 1
  4067. self.old_disp_number = 0
  4068. self.el_count = 0
  4069. # scale gcode_parsed
  4070. for g in v['gcode_parsed']:
  4071. try:
  4072. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  4073. except AttributeError:
  4074. return g['geom']
  4075. self.el_count += 1
  4076. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4077. if self.old_disp_number < disp_number <= 100:
  4078. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4079. self.old_disp_number = disp_number
  4080. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  4081. self.create_geometry()
  4082. self.app.proc_container.new_text = ''
  4083. def offset(self, vect):
  4084. """
  4085. Offsets all the geometry on the XY plane in the object by the
  4086. given vector.
  4087. Offsets all the GCODE on the XY plane in the object by the
  4088. given vector.
  4089. g_offsetx_re, g_offsety_re, multitool, cnnc_tools are attributes of FlatCAMCNCJob class in camlib
  4090. :param vect: (x, y) offset vector.
  4091. :type vect: tuple
  4092. :return: None
  4093. """
  4094. log.debug("camlib.CNCJob.offset()")
  4095. dx, dy = vect
  4096. def offset_g(g):
  4097. """
  4098. :param g: 'g' parameter it's a gcode string
  4099. :return: offseted gcode string
  4100. """
  4101. temp_gcode = ''
  4102. lines = StringIO(g)
  4103. for line in lines:
  4104. # find the X group
  4105. match_x = self.g_x_re.search(line)
  4106. if match_x:
  4107. if match_x.group(1) is not None:
  4108. # get the coordinate and add X offset
  4109. new_x = float(match_x.group(1)[1:]) + dx
  4110. # replace the updated string
  4111. line = line.replace(
  4112. match_x.group(1),
  4113. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  4114. )
  4115. match_y = self.g_y_re.search(line)
  4116. if match_y:
  4117. if match_y.group(1) is not None:
  4118. new_y = float(match_y.group(1)[1:]) + dy
  4119. line = line.replace(
  4120. match_y.group(1),
  4121. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  4122. )
  4123. temp_gcode += line
  4124. lines.close()
  4125. return temp_gcode
  4126. if self.multitool is False:
  4127. # offset Gcode
  4128. self.gcode = offset_g(self.gcode)
  4129. # variables to display the percentage of work done
  4130. self.geo_len = 0
  4131. try:
  4132. for g in self.gcode_parsed:
  4133. self.geo_len += 1
  4134. except TypeError:
  4135. self.geo_len = 1
  4136. self.old_disp_number = 0
  4137. self.el_count = 0
  4138. # offset geometry
  4139. for g in self.gcode_parsed:
  4140. try:
  4141. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  4142. except AttributeError:
  4143. return g['geom']
  4144. self.el_count += 1
  4145. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4146. if self.old_disp_number < disp_number <= 100:
  4147. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4148. self.old_disp_number = disp_number
  4149. self.create_geometry()
  4150. else:
  4151. for k, v in self.cnc_tools.items():
  4152. # offset Gcode
  4153. v['gcode'] = offset_g(v['gcode'])
  4154. # variables to display the percentage of work done
  4155. self.geo_len = 0
  4156. try:
  4157. for g in v['gcode_parsed']:
  4158. self.geo_len += 1
  4159. except TypeError:
  4160. self.geo_len = 1
  4161. self.old_disp_number = 0
  4162. self.el_count = 0
  4163. # offset gcode_parsed
  4164. for g in v['gcode_parsed']:
  4165. try:
  4166. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  4167. except AttributeError:
  4168. return g['geom']
  4169. self.el_count += 1
  4170. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4171. if self.old_disp_number < disp_number <= 100:
  4172. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4173. self.old_disp_number = disp_number
  4174. # for the bounding box
  4175. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  4176. self.app.proc_container.new_text = ''
  4177. def mirror(self, axis, point):
  4178. """
  4179. Mirror the geometrys of an object by an given axis around the coordinates of the 'point'
  4180. :param angle:
  4181. :param point: tupple of coordinates (x,y)
  4182. :return:
  4183. """
  4184. log.debug("camlib.CNCJob.mirror()")
  4185. px, py = point
  4186. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  4187. # variables to display the percentage of work done
  4188. self.geo_len = 0
  4189. try:
  4190. for g in self.gcode_parsed:
  4191. self.geo_len += 1
  4192. except TypeError:
  4193. self.geo_len = 1
  4194. self.old_disp_number = 0
  4195. self.el_count = 0
  4196. for g in self.gcode_parsed:
  4197. try:
  4198. g['geom'] = affinity.scale(g['geom'], xscale, yscale, origin=(px, py))
  4199. except AttributeError:
  4200. return g['geom']
  4201. self.el_count += 1
  4202. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4203. if self.old_disp_number < disp_number <= 100:
  4204. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4205. self.old_disp_number = disp_number
  4206. self.create_geometry()
  4207. self.app.proc_container.new_text = ''
  4208. def skew(self, angle_x, angle_y, point):
  4209. """
  4210. Shear/Skew the geometries of an object by angles along x and y dimensions.
  4211. Parameters
  4212. ----------
  4213. angle_x, angle_y : float, float
  4214. The shear angle(s) for the x and y axes respectively. These can be
  4215. specified in either degrees (default) or radians by setting
  4216. use_radians=True.
  4217. point: tupple of coordinates (x,y)
  4218. See shapely manual for more information:
  4219. http://toblerity.org/shapely/manual.html#affine-transformations
  4220. """
  4221. log.debug("camlib.CNCJob.skew()")
  4222. px, py = point
  4223. # variables to display the percentage of work done
  4224. self.geo_len = 0
  4225. try:
  4226. for g in self.gcode_parsed:
  4227. self.geo_len += 1
  4228. except TypeError:
  4229. self.geo_len = 1
  4230. self.old_disp_number = 0
  4231. self.el_count = 0
  4232. for g in self.gcode_parsed:
  4233. try:
  4234. g['geom'] = affinity.skew(g['geom'], angle_x, angle_y, origin=(px, py))
  4235. except AttributeError:
  4236. return g['geom']
  4237. self.el_count += 1
  4238. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4239. if self.old_disp_number < disp_number <= 100:
  4240. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4241. self.old_disp_number = disp_number
  4242. self.create_geometry()
  4243. self.app.proc_container.new_text = ''
  4244. def rotate(self, angle, point):
  4245. """
  4246. Rotate the geometrys of an object by an given angle around the coordinates of the 'point'
  4247. :param angle:
  4248. :param point: tupple of coordinates (x,y)
  4249. :return:
  4250. """
  4251. log.debug("camlib.CNCJob.rotate()")
  4252. px, py = point
  4253. # variables to display the percentage of work done
  4254. self.geo_len = 0
  4255. try:
  4256. for g in self.gcode_parsed:
  4257. self.geo_len += 1
  4258. except TypeError:
  4259. self.geo_len = 1
  4260. self.old_disp_number = 0
  4261. self.el_count = 0
  4262. for g in self.gcode_parsed:
  4263. try:
  4264. g['geom'] = affinity.rotate(g['geom'], angle, origin=(px, py))
  4265. except AttributeError:
  4266. return g['geom']
  4267. self.el_count += 1
  4268. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4269. if self.old_disp_number < disp_number <= 100:
  4270. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4271. self.old_disp_number = disp_number
  4272. self.create_geometry()
  4273. self.app.proc_container.new_text = ''
  4274. def get_bounds(geometry_list):
  4275. xmin = Inf
  4276. ymin = Inf
  4277. xmax = -Inf
  4278. ymax = -Inf
  4279. for gs in geometry_list:
  4280. try:
  4281. gxmin, gymin, gxmax, gymax = gs.bounds()
  4282. xmin = min([xmin, gxmin])
  4283. ymin = min([ymin, gymin])
  4284. xmax = max([xmax, gxmax])
  4285. ymax = max([ymax, gymax])
  4286. except:
  4287. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  4288. return [xmin, ymin, xmax, ymax]
  4289. def arc(center, radius, start, stop, direction, steps_per_circ):
  4290. """
  4291. Creates a list of point along the specified arc.
  4292. :param center: Coordinates of the center [x, y]
  4293. :type center: list
  4294. :param radius: Radius of the arc.
  4295. :type radius: float
  4296. :param start: Starting angle in radians
  4297. :type start: float
  4298. :param stop: End angle in radians
  4299. :type stop: float
  4300. :param direction: Orientation of the arc, "CW" or "CCW"
  4301. :type direction: string
  4302. :param steps_per_circ: Number of straight line segments to
  4303. represent a circle.
  4304. :type steps_per_circ: int
  4305. :return: The desired arc, as list of tuples
  4306. :rtype: list
  4307. """
  4308. # TODO: Resolution should be established by maximum error from the exact arc.
  4309. da_sign = {"cw": -1.0, "ccw": 1.0}
  4310. points = []
  4311. if direction == "ccw" and stop <= start:
  4312. stop += 2 * pi
  4313. if direction == "cw" and stop >= start:
  4314. stop -= 2 * pi
  4315. angle = abs(stop - start)
  4316. # angle = stop-start
  4317. steps = max([int(ceil(angle / (2 * pi) * steps_per_circ)), 2])
  4318. delta_angle = da_sign[direction] * angle * 1.0 / steps
  4319. for i in range(steps + 1):
  4320. theta = start + delta_angle * i
  4321. points.append((center[0] + radius * cos(theta), center[1] + radius * sin(theta)))
  4322. return points
  4323. def arc2(p1, p2, center, direction, steps_per_circ):
  4324. r = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  4325. start = arctan2(p1[1] - center[1], p1[0] - center[0])
  4326. stop = arctan2(p2[1] - center[1], p2[0] - center[0])
  4327. return arc(center, r, start, stop, direction, steps_per_circ)
  4328. def arc_angle(start, stop, direction):
  4329. if direction == "ccw" and stop <= start:
  4330. stop += 2 * pi
  4331. if direction == "cw" and stop >= start:
  4332. stop -= 2 * pi
  4333. angle = abs(stop - start)
  4334. return angle
  4335. # def find_polygon(poly, point):
  4336. # """
  4337. # Find an object that object.contains(Point(point)) in
  4338. # poly, which can can be iterable, contain iterable of, or
  4339. # be itself an implementer of .contains().
  4340. #
  4341. # :param poly: See description
  4342. # :return: Polygon containing point or None.
  4343. # """
  4344. #
  4345. # if poly is None:
  4346. # return None
  4347. #
  4348. # try:
  4349. # for sub_poly in poly:
  4350. # p = find_polygon(sub_poly, point)
  4351. # if p is not None:
  4352. # return p
  4353. # except TypeError:
  4354. # try:
  4355. # if poly.contains(Point(point)):
  4356. # return poly
  4357. # except AttributeError:
  4358. # return None
  4359. #
  4360. # return None
  4361. def to_dict(obj):
  4362. """
  4363. Makes the following types into serializable form:
  4364. * ApertureMacro
  4365. * BaseGeometry
  4366. :param obj: Shapely geometry.
  4367. :type obj: BaseGeometry
  4368. :return: Dictionary with serializable form if ``obj`` was
  4369. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  4370. """
  4371. if isinstance(obj, ApertureMacro):
  4372. return {
  4373. "__class__": "ApertureMacro",
  4374. "__inst__": obj.to_dict()
  4375. }
  4376. if isinstance(obj, BaseGeometry):
  4377. return {
  4378. "__class__": "Shply",
  4379. "__inst__": sdumps(obj)
  4380. }
  4381. return obj
  4382. def dict2obj(d):
  4383. """
  4384. Default deserializer.
  4385. :param d: Serializable dictionary representation of an object
  4386. to be reconstructed.
  4387. :return: Reconstructed object.
  4388. """
  4389. if '__class__' in d and '__inst__' in d:
  4390. if d['__class__'] == "Shply":
  4391. return sloads(d['__inst__'])
  4392. if d['__class__'] == "ApertureMacro":
  4393. am = ApertureMacro()
  4394. am.from_dict(d['__inst__'])
  4395. return am
  4396. return d
  4397. else:
  4398. return d
  4399. # def plotg(geo, solid_poly=False, color="black"):
  4400. # try:
  4401. # __ = iter(geo)
  4402. # except:
  4403. # geo = [geo]
  4404. #
  4405. # for g in geo:
  4406. # if type(g) == Polygon:
  4407. # if solid_poly:
  4408. # patch = PolygonPatch(g,
  4409. # facecolor="#BBF268",
  4410. # edgecolor="#006E20",
  4411. # alpha=0.75,
  4412. # zorder=2)
  4413. # ax = subplot(111)
  4414. # ax.add_patch(patch)
  4415. # else:
  4416. # x, y = g.exterior.coords.xy
  4417. # plot(x, y, color=color)
  4418. # for ints in g.interiors:
  4419. # x, y = ints.coords.xy
  4420. # plot(x, y, color=color)
  4421. # continue
  4422. #
  4423. # if type(g) == LineString or type(g) == LinearRing:
  4424. # x, y = g.coords.xy
  4425. # plot(x, y, color=color)
  4426. # continue
  4427. #
  4428. # if type(g) == Point:
  4429. # x, y = g.coords.xy
  4430. # plot(x, y, 'o')
  4431. # continue
  4432. #
  4433. # try:
  4434. # __ = iter(g)
  4435. # plotg(g, color=color)
  4436. # except:
  4437. # log.error("Cannot plot: " + str(type(g)))
  4438. # continue
  4439. # def alpha_shape(points, alpha):
  4440. # """
  4441. # Compute the alpha shape (concave hull) of a set of points.
  4442. #
  4443. # @param points: Iterable container of points.
  4444. # @param alpha: alpha value to influence the gooeyness of the border. Smaller
  4445. # numbers don't fall inward as much as larger numbers. Too large,
  4446. # and you lose everything!
  4447. # """
  4448. # if len(points) < 4:
  4449. # # When you have a triangle, there is no sense in computing an alpha
  4450. # # shape.
  4451. # return MultiPoint(list(points)).convex_hull
  4452. #
  4453. # def add_edge(edges, edge_points, coords, i, j):
  4454. # """Add a line between the i-th and j-th points, if not in the list already"""
  4455. # if (i, j) in edges or (j, i) in edges:
  4456. # # already added
  4457. # return
  4458. # edges.add( (i, j) )
  4459. # edge_points.append(coords[ [i, j] ])
  4460. #
  4461. # coords = np.array([point.coords[0] for point in points])
  4462. #
  4463. # tri = Delaunay(coords)
  4464. # edges = set()
  4465. # edge_points = []
  4466. # # loop over triangles:
  4467. # # ia, ib, ic = indices of corner points of the triangle
  4468. # for ia, ib, ic in tri.vertices:
  4469. # pa = coords[ia]
  4470. # pb = coords[ib]
  4471. # pc = coords[ic]
  4472. #
  4473. # # Lengths of sides of triangle
  4474. # a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
  4475. # b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
  4476. # c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
  4477. #
  4478. # # Semiperimeter of triangle
  4479. # s = (a + b + c)/2.0
  4480. #
  4481. # # Area of triangle by Heron's formula
  4482. # area = math.sqrt(s*(s-a)*(s-b)*(s-c))
  4483. # circum_r = a*b*c/(4.0*area)
  4484. #
  4485. # # Here's the radius filter.
  4486. # #print circum_r
  4487. # if circum_r < 1.0/alpha:
  4488. # add_edge(edges, edge_points, coords, ia, ib)
  4489. # add_edge(edges, edge_points, coords, ib, ic)
  4490. # add_edge(edges, edge_points, coords, ic, ia)
  4491. #
  4492. # m = MultiLineString(edge_points)
  4493. # triangles = list(polygonize(m))
  4494. # return cascaded_union(triangles), edge_points
  4495. # def voronoi(P):
  4496. # """
  4497. # Returns a list of all edges of the voronoi diagram for the given input points.
  4498. # """
  4499. # delauny = Delaunay(P)
  4500. # triangles = delauny.points[delauny.vertices]
  4501. #
  4502. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  4503. # long_lines_endpoints = []
  4504. #
  4505. # lineIndices = []
  4506. # for i, triangle in enumerate(triangles):
  4507. # circum_center = circum_centers[i]
  4508. # for j, neighbor in enumerate(delauny.neighbors[i]):
  4509. # if neighbor != -1:
  4510. # lineIndices.append((i, neighbor))
  4511. # else:
  4512. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  4513. # ps = np.array((ps[1], -ps[0]))
  4514. #
  4515. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  4516. # di = middle - triangle[j]
  4517. #
  4518. # ps /= np.linalg.norm(ps)
  4519. # di /= np.linalg.norm(di)
  4520. #
  4521. # if np.dot(di, ps) < 0.0:
  4522. # ps *= -1000.0
  4523. # else:
  4524. # ps *= 1000.0
  4525. #
  4526. # long_lines_endpoints.append(circum_center + ps)
  4527. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  4528. #
  4529. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  4530. #
  4531. # # filter out any duplicate lines
  4532. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  4533. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  4534. # lineIndicesUnique = np.unique(lineIndicesTupled)
  4535. #
  4536. # return vertices, lineIndicesUnique
  4537. #
  4538. #
  4539. # def triangle_csc(pts):
  4540. # rows, cols = pts.shape
  4541. #
  4542. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  4543. # [np.ones((1, rows)), np.zeros((1, 1))]])
  4544. #
  4545. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  4546. # x = np.linalg.solve(A,b)
  4547. # bary_coords = x[:-1]
  4548. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  4549. #
  4550. #
  4551. # def voronoi_cell_lines(points, vertices, lineIndices):
  4552. # """
  4553. # Returns a mapping from a voronoi cell to its edges.
  4554. #
  4555. # :param points: shape (m,2)
  4556. # :param vertices: shape (n,2)
  4557. # :param lineIndices: shape (o,2)
  4558. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  4559. # """
  4560. # kd = KDTree(points)
  4561. #
  4562. # cells = collections.defaultdict(list)
  4563. # for i1, i2 in lineIndices:
  4564. # v1, v2 = vertices[i1], vertices[i2]
  4565. # mid = (v1+v2)/2
  4566. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  4567. # cells[p1Idx].append((i1, i2))
  4568. # cells[p2Idx].append((i1, i2))
  4569. #
  4570. # return cells
  4571. #
  4572. #
  4573. # def voronoi_edges2polygons(cells):
  4574. # """
  4575. # Transforms cell edges into polygons.
  4576. #
  4577. # :param cells: as returned from voronoi_cell_lines
  4578. # :rtype: dict point index -> list of vertex indices which form a polygon
  4579. # """
  4580. #
  4581. # # first, close the outer cells
  4582. # for pIdx, lineIndices_ in cells.items():
  4583. # dangling_lines = []
  4584. # for i1, i2 in lineIndices_:
  4585. # p = (i1, i2)
  4586. # connections = filter(lambda k: p != k and
  4587. # (p[0] == k[0] or p[0] == k[1] or p[1] == k[0] or p[1] == k[1]), lineIndices_)
  4588. # # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and
  4589. # (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  4590. # assert 1 <= len(connections) <= 2
  4591. # if len(connections) == 1:
  4592. # dangling_lines.append((i1, i2))
  4593. # assert len(dangling_lines) in [0, 2]
  4594. # if len(dangling_lines) == 2:
  4595. # (i11, i12), (i21, i22) = dangling_lines
  4596. # s = (i11, i12)
  4597. # t = (i21, i22)
  4598. #
  4599. # # determine which line ends are unconnected
  4600. # connected = filter(lambda k: k != s and (k[0] == s[0] or k[1] == s[0]), lineIndices_)
  4601. # # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  4602. # i11Unconnected = len(connected) == 0
  4603. #
  4604. # connected = filter(lambda k: k != t and (k[0] == t[0] or k[1] == t[0]), lineIndices_)
  4605. # # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  4606. # i21Unconnected = len(connected) == 0
  4607. #
  4608. # startIdx = i11 if i11Unconnected else i12
  4609. # endIdx = i21 if i21Unconnected else i22
  4610. #
  4611. # cells[pIdx].append((startIdx, endIdx))
  4612. #
  4613. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  4614. # polys = dict()
  4615. # for pIdx, lineIndices_ in cells.items():
  4616. # # get a directed graph which contains both directions and arbitrarily follow one of both
  4617. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  4618. # directedGraphMap = collections.defaultdict(list)
  4619. # for (i1, i2) in directedGraph:
  4620. # directedGraphMap[i1].append(i2)
  4621. # orderedEdges = []
  4622. # currentEdge = directedGraph[0]
  4623. # while len(orderedEdges) < len(lineIndices_):
  4624. # i1 = currentEdge[1]
  4625. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  4626. # nextEdge = (i1, i2)
  4627. # orderedEdges.append(nextEdge)
  4628. # currentEdge = nextEdge
  4629. #
  4630. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  4631. #
  4632. # return polys
  4633. #
  4634. #
  4635. # def voronoi_polygons(points):
  4636. # """
  4637. # Returns the voronoi polygon for each input point.
  4638. #
  4639. # :param points: shape (n,2)
  4640. # :rtype: list of n polygons where each polygon is an array of vertices
  4641. # """
  4642. # vertices, lineIndices = voronoi(points)
  4643. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  4644. # polys = voronoi_edges2polygons(cells)
  4645. # polylist = []
  4646. # for i in range(len(points)):
  4647. # poly = vertices[np.asarray(polys[i])]
  4648. # polylist.append(poly)
  4649. # return polylist
  4650. #
  4651. #
  4652. # class Zprofile:
  4653. # def __init__(self):
  4654. #
  4655. # # data contains lists of [x, y, z]
  4656. # self.data = []
  4657. #
  4658. # # Computed voronoi polygons (shapely)
  4659. # self.polygons = []
  4660. # pass
  4661. #
  4662. # # def plot_polygons(self):
  4663. # # axes = plt.subplot(1, 1, 1)
  4664. # #
  4665. # # plt.axis([-0.05, 1.05, -0.05, 1.05])
  4666. # #
  4667. # # for poly in self.polygons:
  4668. # # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  4669. # # axes.add_patch(p)
  4670. #
  4671. # def init_from_csv(self, filename):
  4672. # pass
  4673. #
  4674. # def init_from_string(self, zpstring):
  4675. # pass
  4676. #
  4677. # def init_from_list(self, zplist):
  4678. # self.data = zplist
  4679. #
  4680. # def generate_polygons(self):
  4681. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  4682. #
  4683. # def normalize(self, origin):
  4684. # pass
  4685. #
  4686. # def paste(self, path):
  4687. # """
  4688. # Return a list of dictionaries containing the parts of the original
  4689. # path and their z-axis offset.
  4690. # """
  4691. #
  4692. # # At most one region/polygon will contain the path
  4693. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  4694. #
  4695. # if len(containing) > 0:
  4696. # return [{"path": path, "z": self.data[containing[0]][2]}]
  4697. #
  4698. # # All region indexes that intersect with the path
  4699. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  4700. #
  4701. # return [{"path": path.intersection(self.polygons[i]),
  4702. # "z": self.data[i][2]} for i in crossing]
  4703. def autolist(obj):
  4704. try:
  4705. __ = iter(obj)
  4706. return obj
  4707. except TypeError:
  4708. return [obj]
  4709. def three_point_circle(p1, p2, p3):
  4710. """
  4711. Computes the center and radius of a circle from
  4712. 3 points on its circumference.
  4713. :param p1: Point 1
  4714. :param p2: Point 2
  4715. :param p3: Point 3
  4716. :return: center, radius
  4717. """
  4718. # Midpoints
  4719. a1 = (p1 + p2) / 2.0
  4720. a2 = (p2 + p3) / 2.0
  4721. # Normals
  4722. b1 = dot((p2 - p1), array([[0, -1], [1, 0]], dtype=float32))
  4723. b2 = dot((p3 - p2), array([[0, 1], [-1, 0]], dtype=float32))
  4724. # Params
  4725. try:
  4726. T = solve(transpose(array([-b1, b2])), a1 - a2)
  4727. except Exception as e:
  4728. log.debug("camlib.three_point_circle() --> %s" % str(e))
  4729. return
  4730. # Center
  4731. center = a1 + b1 * T[0]
  4732. # Radius
  4733. radius = np.linalg.norm(center - p1)
  4734. return center, radius, T[0]
  4735. def distance(pt1, pt2):
  4736. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  4737. def distance_euclidian(x1, y1, x2, y2):
  4738. return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  4739. class FlatCAMRTree(object):
  4740. """
  4741. Indexes geometry (Any object with "cooords" property containing
  4742. a list of tuples with x, y values). Objects are indexed by
  4743. all their points by default. To index by arbitrary points,
  4744. override self.points2obj.
  4745. """
  4746. def __init__(self):
  4747. # Python RTree Index
  4748. self.rti = rtindex.Index()
  4749. # ## Track object-point relationship
  4750. # Each is list of points in object.
  4751. self.obj2points = []
  4752. # Index is index in rtree, value is index of
  4753. # object in obj2points.
  4754. self.points2obj = []
  4755. self.get_points = lambda go: go.coords
  4756. def grow_obj2points(self, idx):
  4757. """
  4758. Increases the size of self.obj2points to fit
  4759. idx + 1 items.
  4760. :param idx: Index to fit into list.
  4761. :return: None
  4762. """
  4763. if len(self.obj2points) > idx:
  4764. # len == 2, idx == 1, ok.
  4765. return
  4766. else:
  4767. # len == 2, idx == 2, need 1 more.
  4768. # range(2, 3)
  4769. for i in range(len(self.obj2points), idx + 1):
  4770. self.obj2points.append([])
  4771. def insert(self, objid, obj):
  4772. self.grow_obj2points(objid)
  4773. self.obj2points[objid] = []
  4774. for pt in self.get_points(obj):
  4775. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  4776. self.obj2points[objid].append(len(self.points2obj))
  4777. self.points2obj.append(objid)
  4778. def remove_obj(self, objid, obj):
  4779. # Use all ptids to delete from index
  4780. for i, pt in enumerate(self.get_points(obj)):
  4781. try:
  4782. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  4783. except IndexError:
  4784. pass
  4785. def nearest(self, pt):
  4786. """
  4787. Will raise StopIteration if no items are found.
  4788. :param pt:
  4789. :return:
  4790. """
  4791. return next(self.rti.nearest(pt, objects=True))
  4792. class FlatCAMRTreeStorage(FlatCAMRTree):
  4793. """
  4794. Just like FlatCAMRTree it indexes geometry, but also serves
  4795. as storage for the geometry.
  4796. """
  4797. def __init__(self):
  4798. # super(FlatCAMRTreeStorage, self).__init__()
  4799. super().__init__()
  4800. self.objects = []
  4801. # Optimization attempt!
  4802. self.indexes = {}
  4803. def insert(self, obj):
  4804. self.objects.append(obj)
  4805. idx = len(self.objects) - 1
  4806. # Note: Shapely objects are not hashable any more, althought
  4807. # there seem to be plans to re-introduce the feature in
  4808. # version 2.0. For now, we will index using the object's id,
  4809. # but it's important to remember that shapely geometry is
  4810. # mutable, ie. it can be modified to a totally different shape
  4811. # and continue to have the same id.
  4812. # self.indexes[obj] = idx
  4813. self.indexes[id(obj)] = idx
  4814. # super(FlatCAMRTreeStorage, self).insert(idx, obj)
  4815. super().insert(idx, obj)
  4816. # @profile
  4817. def remove(self, obj):
  4818. # See note about self.indexes in insert().
  4819. # objidx = self.indexes[obj]
  4820. objidx = self.indexes[id(obj)]
  4821. # Remove from list
  4822. self.objects[objidx] = None
  4823. # Remove from index
  4824. self.remove_obj(objidx, obj)
  4825. def get_objects(self):
  4826. return (o for o in self.objects if o is not None)
  4827. def nearest(self, pt):
  4828. """
  4829. Returns the nearest matching points and the object
  4830. it belongs to.
  4831. :param pt: Query point.
  4832. :return: (match_x, match_y), Object owner of
  4833. matching point.
  4834. :rtype: tuple
  4835. """
  4836. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  4837. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  4838. # class myO:
  4839. # def __init__(self, coords):
  4840. # self.coords = coords
  4841. #
  4842. #
  4843. # def test_rti():
  4844. #
  4845. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  4846. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  4847. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  4848. #
  4849. # os = [o1, o2]
  4850. #
  4851. # idx = FlatCAMRTree()
  4852. #
  4853. # for o in range(len(os)):
  4854. # idx.insert(o, os[o])
  4855. #
  4856. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4857. #
  4858. # idx.remove_obj(0, o1)
  4859. #
  4860. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4861. #
  4862. # idx.remove_obj(1, o2)
  4863. #
  4864. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4865. #
  4866. #
  4867. # def test_rtis():
  4868. #
  4869. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  4870. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  4871. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  4872. #
  4873. # os = [o1, o2]
  4874. #
  4875. # idx = FlatCAMRTreeStorage()
  4876. #
  4877. # for o in range(len(os)):
  4878. # idx.insert(os[o])
  4879. #
  4880. # #os = None
  4881. # #o1 = None
  4882. # #o2 = None
  4883. #
  4884. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4885. #
  4886. # idx.remove(idx.nearest((2,0))[1])
  4887. #
  4888. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4889. #
  4890. # idx.remove(idx.nearest((0,0))[1])
  4891. #
  4892. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]