camlib.py 318 KB

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