camlib.py 248 KB

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