camlib.py 245 KB

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