camlib.py 263 KB

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