camlib.py 280 KB

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