camlib.py 316 KB

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