camlib.py 252 KB

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