camlib.py 320 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903
  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. # store the file units here:
  1756. gerber_units = 'IN'
  1757. # this is for temporary storage of geometry until it is added to poly_buffer
  1758. geo = None
  1759. # Polygons are stored here until there is a change in polarity.
  1760. # Only then they are combined via cascaded_union and added or
  1761. # subtracted from solid_geometry. This is ~100 times faster than
  1762. # applying a union for every new polygon.
  1763. poly_buffer = []
  1764. # made True when the LPC command is encountered in Gerber parsing
  1765. # it allows adding data into the clear_geometry key of the self.apertures[aperture] dict
  1766. self.is_lpc = False
  1767. # store here the follow geometry
  1768. follow_buffer = []
  1769. last_path_aperture = None
  1770. current_aperture = None
  1771. # 1,2 or 3 from "G01", "G02" or "G03"
  1772. current_interpolation_mode = None
  1773. # 1 or 2 from "D01" or "D02"
  1774. # Note this is to support deprecated Gerber not putting
  1775. # an operation code at the end of every coordinate line.
  1776. current_operation_code = None
  1777. # Current coordinates
  1778. current_x = None
  1779. current_y = None
  1780. previous_x = None
  1781. previous_y = None
  1782. current_d = None
  1783. # Absolute or Relative/Incremental coordinates
  1784. # Not implemented
  1785. absolute = True
  1786. # How to interpret circular interpolation: SINGLE or MULTI
  1787. quadrant_mode = None
  1788. # Indicates we are parsing an aperture macro
  1789. current_macro = None
  1790. # Indicates the current polarity: D-Dark, C-Clear
  1791. current_polarity = 'D'
  1792. # If a region is being defined
  1793. making_region = False
  1794. #### Parsing starts here ####
  1795. line_num = 0
  1796. gline = ""
  1797. try:
  1798. for gline in glines:
  1799. line_num += 1
  1800. self.source_file += gline + '\n'
  1801. ### Cleanup
  1802. gline = gline.strip(' \r\n')
  1803. # log.debug("Line=%3s %s" % (line_num, gline))
  1804. #### Ignored lines
  1805. ## Comments
  1806. match = self.comm_re.search(gline)
  1807. if match:
  1808. continue
  1809. ### Polarity change
  1810. # Example: %LPD*% or %LPC*%
  1811. # If polarity changes, creates geometry from current
  1812. # buffer, then adds or subtracts accordingly.
  1813. match = self.lpol_re.search(gline)
  1814. if match:
  1815. new_polarity = match.group(1)
  1816. if len(path) > 1 and current_polarity != new_polarity:
  1817. # finish the current path and add it to the storage
  1818. # --- Buffered ----
  1819. width = self.apertures[last_path_aperture]["size"]
  1820. geo = LineString(path)
  1821. if not geo.is_empty:
  1822. follow_buffer.append(geo)
  1823. try:
  1824. self.apertures[last_path_aperture]['follow_geometry'].append(geo)
  1825. except KeyError:
  1826. self.apertures[last_path_aperture]['follow_geometry'] = []
  1827. self.apertures[last_path_aperture]['follow_geometry'].append(geo)
  1828. geo = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  1829. if not geo.is_empty:
  1830. poly_buffer.append(geo)
  1831. if self.is_lpc is True:
  1832. try:
  1833. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  1834. except KeyError:
  1835. self.apertures[last_path_aperture]['clear_geometry'] = []
  1836. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  1837. else:
  1838. try:
  1839. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  1840. except KeyError:
  1841. self.apertures[last_path_aperture]['solid_geometry'] = []
  1842. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  1843. path = [path[-1]]
  1844. # --- Apply buffer ---
  1845. # If added for testing of bug #83
  1846. # TODO: Remove when bug fixed
  1847. if len(poly_buffer) > 0:
  1848. if current_polarity == 'D':
  1849. self.is_lpc = True
  1850. # self.follow_geometry = self.follow_geometry.union(cascaded_union(follow_buffer))
  1851. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  1852. else:
  1853. self.is_lpc = False
  1854. # self.follow_geometry = self.follow_geometry.difference(cascaded_union(follow_buffer))
  1855. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  1856. # follow_buffer = []
  1857. poly_buffer = []
  1858. current_polarity = new_polarity
  1859. continue
  1860. ### Number format
  1861. # Example: %FSLAX24Y24*%
  1862. # TODO: This is ignoring most of the format. Implement the rest.
  1863. match = self.fmt_re.search(gline)
  1864. if match:
  1865. absolute = {'A': 'Absolute', 'I': 'Relative'}[match.group(2)]
  1866. self.gerber_zeros = match.group(1)
  1867. self.int_digits = int(match.group(3))
  1868. self.frac_digits = int(match.group(4))
  1869. log.debug("Gerber format found. (%s) " % str(gline))
  1870. log.debug(
  1871. "Gerber format found. Gerber zeros = %s (L-omit leading zeros, T-omit trailing zeros, "
  1872. "D-no zero supression)" % self.gerber_zeros)
  1873. log.debug("Gerber format found. Coordinates type = %s (Absolute or Relative)" % absolute)
  1874. continue
  1875. ### Mode (IN/MM)
  1876. # Example: %MOIN*%
  1877. match = self.mode_re.search(gline)
  1878. if match:
  1879. gerber_units = match.group(1)
  1880. log.debug("Gerber units found = %s" % gerber_units)
  1881. # Changed for issue #80
  1882. self.convert_units(match.group(1))
  1883. continue
  1884. ### Combined Number format and Mode --- Allegro does this
  1885. match = self.fmt_re_alt.search(gline)
  1886. if match:
  1887. absolute = {'A': 'Absolute', 'I': 'Relative'}[match.group(2)]
  1888. self.gerber_zeros = match.group(1)
  1889. self.int_digits = int(match.group(3))
  1890. self.frac_digits = int(match.group(4))
  1891. log.debug("Gerber format found. (%s) " % str(gline))
  1892. log.debug(
  1893. "Gerber format found. Gerber zeros = %s (L-omit leading zeros, T-omit trailing zeros, "
  1894. "D-no zero suppression)" % self.gerber_zeros)
  1895. log.debug("Gerber format found. Coordinates type = %s (Absolute or Relative)" % absolute)
  1896. gerber_units = match.group(1)
  1897. log.debug("Gerber units found = %s" % gerber_units)
  1898. # Changed for issue #80
  1899. self.convert_units(match.group(5))
  1900. continue
  1901. ### Search for OrCAD way for having Number format
  1902. match = self.fmt_re_orcad.search(gline)
  1903. if match:
  1904. if match.group(1) is not None:
  1905. if match.group(1) == 'G74':
  1906. quadrant_mode = 'SINGLE'
  1907. elif match.group(1) == 'G75':
  1908. quadrant_mode = 'MULTI'
  1909. absolute = {'A': 'Absolute', 'I': 'Relative'}[match.group(3)]
  1910. self.gerber_zeros = match.group(2)
  1911. self.int_digits = int(match.group(4))
  1912. self.frac_digits = int(match.group(5))
  1913. log.debug("Gerber format found. (%s) " % str(gline))
  1914. log.debug(
  1915. "Gerber format found. Gerber zeros = %s (L-omit leading zeros, T-omit trailing zeros, "
  1916. "D-no zerosuppressionn)" % self.gerber_zeros)
  1917. log.debug("Gerber format found. Coordinates type = %s (Absolute or Relative)" % absolute)
  1918. gerber_units = match.group(1)
  1919. log.debug("Gerber units found = %s" % gerber_units)
  1920. # Changed for issue #80
  1921. self.convert_units(match.group(5))
  1922. continue
  1923. ### Units (G70/1) OBSOLETE
  1924. match = self.units_re.search(gline)
  1925. if match:
  1926. obs_gerber_units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  1927. log.warning("Gerber obsolete units found = %s" % obs_gerber_units)
  1928. # Changed for issue #80
  1929. self.convert_units({'0': 'IN', '1': 'MM'}[match.group(1)])
  1930. continue
  1931. ### Absolute/relative coordinates G90/1 OBSOLETE
  1932. match = self.absrel_re.search(gline)
  1933. if match:
  1934. absolute = {'0': "Absolute", '1': "Relative"}[match.group(1)]
  1935. log.warning("Gerber obsolete coordinates type found = %s (Absolute or Relative) " % absolute)
  1936. continue
  1937. ### Aperture Macros
  1938. # Having this at the beginning will slow things down
  1939. # but macros can have complicated statements than could
  1940. # be caught by other patterns.
  1941. if current_macro is None: # No macro started yet
  1942. match = self.am1_re.search(gline)
  1943. # Start macro if match, else not an AM, carry on.
  1944. if match:
  1945. log.debug("Starting macro. Line %d: %s" % (line_num, gline))
  1946. current_macro = match.group(1)
  1947. self.aperture_macros[current_macro] = ApertureMacro(name=current_macro)
  1948. if match.group(2): # Append
  1949. self.aperture_macros[current_macro].append(match.group(2))
  1950. if match.group(3): # Finish macro
  1951. #self.aperture_macros[current_macro].parse_content()
  1952. current_macro = None
  1953. log.debug("Macro complete in 1 line.")
  1954. continue
  1955. else: # Continue macro
  1956. log.debug("Continuing macro. Line %d." % line_num)
  1957. match = self.am2_re.search(gline)
  1958. if match: # Finish macro
  1959. log.debug("End of macro. Line %d." % line_num)
  1960. self.aperture_macros[current_macro].append(match.group(1))
  1961. #self.aperture_macros[current_macro].parse_content()
  1962. current_macro = None
  1963. else: # Append
  1964. self.aperture_macros[current_macro].append(gline)
  1965. continue
  1966. ### Aperture definitions %ADD...
  1967. match = self.ad_re.search(gline)
  1968. if match:
  1969. log.info("Found aperture definition. Line %d: %s" % (line_num, gline))
  1970. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  1971. continue
  1972. ### Operation code alone
  1973. # Operation code alone, usually just D03 (Flash)
  1974. # self.opcode_re = re.compile(r'^D0?([123])\*$')
  1975. match = self.opcode_re.search(gline)
  1976. if match:
  1977. current_operation_code = int(match.group(1))
  1978. current_d = current_operation_code
  1979. if current_operation_code == 3:
  1980. ## --- Buffered ---
  1981. try:
  1982. log.debug("Bare op-code %d." % current_operation_code)
  1983. # flash = Gerber.create_flash_geometry(Point(path[-1]),
  1984. # self.apertures[current_aperture])
  1985. flash = Gerber.create_flash_geometry(
  1986. Point(current_x, current_y), self.apertures[current_aperture],
  1987. int(self.steps_per_circle))
  1988. if not flash.is_empty:
  1989. poly_buffer.append(flash)
  1990. if self.is_lpc is True:
  1991. try:
  1992. self.apertures[current_aperture]['clear_geometry'].append(flash)
  1993. except KeyError:
  1994. self.apertures[current_aperture]['clear_geometry'] = []
  1995. self.apertures[current_aperture]['clear_geometry'].append(flash)
  1996. else:
  1997. try:
  1998. self.apertures[current_aperture]['solid_geometry'].append(flash)
  1999. except KeyError:
  2000. self.apertures[current_aperture]['solid_geometry'] = []
  2001. self.apertures[current_aperture]['solid_geometry'].append(flash)
  2002. except IndexError:
  2003. log.warning("Line %d: %s -> Nothing there to flash!" % (line_num, gline))
  2004. continue
  2005. ### Tool/aperture change
  2006. # Example: D12*
  2007. match = self.tool_re.search(gline)
  2008. if match:
  2009. current_aperture = match.group(1)
  2010. log.debug("Line %d: Aperture change to (%s)" % (line_num, match.group(1)))
  2011. # If the aperture value is zero then make it something quite small but with a non-zero value
  2012. # so it can be processed by FlatCAM.
  2013. # But first test to see if the aperture type is "aperture macro". In that case
  2014. # we should not test for "size" key as it does not exist in this case.
  2015. if self.apertures[current_aperture]["type"] is not "AM":
  2016. if self.apertures[current_aperture]["size"] == 0:
  2017. self.apertures[current_aperture]["size"] = 1e-12
  2018. log.debug(self.apertures[current_aperture])
  2019. # Take care of the current path with the previous tool
  2020. if len(path) > 1:
  2021. if self.apertures[last_path_aperture]["type"] == 'R':
  2022. # do nothing because 'R' type moving aperture is none at once
  2023. pass
  2024. else:
  2025. # --- Buffered ----
  2026. width = self.apertures[last_path_aperture]["size"]
  2027. geo = LineString(path)
  2028. if not geo.is_empty:
  2029. follow_buffer.append(geo)
  2030. try:
  2031. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2032. except KeyError:
  2033. self.apertures[current_aperture]['follow_geometry'] = []
  2034. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2035. geo = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  2036. if not geo.is_empty:
  2037. poly_buffer.append(geo)
  2038. if self.is_lpc is True:
  2039. try:
  2040. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  2041. except KeyError:
  2042. self.apertures[last_path_aperture]['clear_geometry'] = []
  2043. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  2044. else:
  2045. try:
  2046. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  2047. except KeyError:
  2048. self.apertures[last_path_aperture]['solid_geometry'] = []
  2049. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  2050. path = [path[-1]]
  2051. continue
  2052. ### G36* - Begin region
  2053. if self.regionon_re.search(gline):
  2054. if len(path) > 1:
  2055. # Take care of what is left in the path
  2056. ## --- Buffered ---
  2057. width = self.apertures[last_path_aperture]["size"]
  2058. geo = LineString(path)
  2059. if not geo.is_empty:
  2060. follow_buffer.append(geo)
  2061. try:
  2062. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2063. except KeyError:
  2064. self.apertures[current_aperture]['follow_geometry'] = []
  2065. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2066. geo = LineString(path).buffer(width/1.999, int(self.steps_per_circle / 4))
  2067. if not geo.is_empty:
  2068. poly_buffer.append(geo)
  2069. if self.is_lpc is True:
  2070. try:
  2071. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  2072. except KeyError:
  2073. self.apertures[last_path_aperture]['clear_geometry'] = []
  2074. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  2075. else:
  2076. try:
  2077. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  2078. except KeyError:
  2079. self.apertures[last_path_aperture]['solid_geometry'] = []
  2080. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  2081. path = [path[-1]]
  2082. making_region = True
  2083. continue
  2084. ### G37* - End region
  2085. if self.regionoff_re.search(gline):
  2086. making_region = False
  2087. # if D02 happened before G37 we now have a path with 1 element only so we have to add the current
  2088. # geo to the poly_buffer otherwise we loose it
  2089. if current_operation_code == 2:
  2090. if geo:
  2091. if not geo.is_empty:
  2092. follow_buffer.append(geo)
  2093. try:
  2094. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2095. except KeyError:
  2096. self.apertures[current_aperture]['follow_geometry'] = []
  2097. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2098. poly_buffer.append(geo)
  2099. if self.is_lpc is True:
  2100. try:
  2101. self.apertures[current_aperture]['clear_geometry'].append(geo)
  2102. except KeyError:
  2103. self.apertures[current_aperture]['clear_geometry'] = []
  2104. self.apertures[current_aperture]['clear_geometry'].append(geo)
  2105. else:
  2106. try:
  2107. self.apertures[current_aperture]['solid_geometry'].append(geo)
  2108. except KeyError:
  2109. self.apertures[current_aperture]['solid_geometry'] = []
  2110. self.apertures[current_aperture]['solid_geometry'].append(geo)
  2111. continue
  2112. # Only one path defines region?
  2113. # This can happen if D02 happened before G37 and
  2114. # is not and error.
  2115. if len(path) < 3:
  2116. # print "ERROR: Path contains less than 3 points:"
  2117. # print path
  2118. # print "Line (%d): " % line_num, gline
  2119. # path = []
  2120. #path = [[current_x, current_y]]
  2121. continue
  2122. # For regions we may ignore an aperture that is None
  2123. # self.regions.append({"polygon": Polygon(path),
  2124. # "aperture": last_path_aperture})
  2125. # --- Buffered ---
  2126. region = Polygon()
  2127. if not region.is_empty:
  2128. follow_buffer.append(region)
  2129. try:
  2130. self.apertures[current_aperture]['follow_geometry'].append(region)
  2131. except KeyError:
  2132. self.apertures[current_aperture]['follow_geometry'] = []
  2133. self.apertures[current_aperture]['follow_geometry'].append(region)
  2134. region = Polygon(path)
  2135. if not region.is_valid:
  2136. region = region.buffer(0, int(self.steps_per_circle / 4))
  2137. if not region.is_empty:
  2138. poly_buffer.append(region)
  2139. # we do this for the case that a region is done without having defined any aperture
  2140. # Allegro does that
  2141. if current_aperture:
  2142. used_aperture = current_aperture
  2143. elif last_path_aperture:
  2144. used_aperture = last_path_aperture
  2145. else:
  2146. if '0' not in self.apertures:
  2147. self.apertures['0'] = {}
  2148. self.apertures['0']['type'] = 'REG'
  2149. self.apertures['0']['solid_geometry'] = []
  2150. used_aperture = '0'
  2151. if self.is_lpc is True:
  2152. try:
  2153. self.apertures[used_aperture]['clear_geometry'].append(region)
  2154. except KeyError:
  2155. self.apertures[used_aperture]['clear_geometry'] = []
  2156. self.apertures[used_aperture]['clear_geometry'].append(region)
  2157. else:
  2158. try:
  2159. self.apertures[used_aperture]['solid_geometry'].append(region)
  2160. except KeyError:
  2161. self.apertures[used_aperture]['solid_geometry'] = []
  2162. self.apertures[used_aperture]['solid_geometry'].append(region)
  2163. path = [[current_x, current_y]] # Start new path
  2164. continue
  2165. ### G01/2/3* - Interpolation mode change
  2166. # Can occur along with coordinates and operation code but
  2167. # sometimes by itself (handled here).
  2168. # Example: G01*
  2169. match = self.interp_re.search(gline)
  2170. if match:
  2171. current_interpolation_mode = int(match.group(1))
  2172. continue
  2173. ### G01 - Linear interpolation plus flashes
  2174. # Operation code (D0x) missing is deprecated... oh well I will support it.
  2175. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  2176. match = self.lin_re.search(gline)
  2177. if match:
  2178. # Dxx alone?
  2179. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  2180. # try:
  2181. # current_operation_code = int(match.group(4))
  2182. # except:
  2183. # pass # A line with just * will match too.
  2184. # continue
  2185. # NOTE: Letting it continue allows it to react to the
  2186. # operation code.
  2187. # Parse coordinates
  2188. if match.group(2) is not None:
  2189. linear_x = parse_gerber_number(match.group(2),
  2190. self.int_digits, self.frac_digits, self.gerber_zeros)
  2191. current_x = linear_x
  2192. else:
  2193. linear_x = current_x
  2194. if match.group(3) is not None:
  2195. linear_y = parse_gerber_number(match.group(3),
  2196. self.int_digits, self.frac_digits, self.gerber_zeros)
  2197. current_y = linear_y
  2198. else:
  2199. linear_y = current_y
  2200. # Parse operation code
  2201. if match.group(4) is not None:
  2202. current_operation_code = int(match.group(4))
  2203. # Pen down: add segment
  2204. if current_operation_code == 1:
  2205. # if linear_x or linear_y are None, ignore those
  2206. if linear_x is not None and linear_y is not None:
  2207. # only add the point if it's a new one otherwise skip it (harder to process)
  2208. if path[-1] != [linear_x, linear_y]:
  2209. path.append([linear_x, linear_y])
  2210. if making_region is False:
  2211. # if the aperture is rectangle then add a rectangular shape having as parameters the
  2212. # coordinates of the start and end point and also the width and height
  2213. # of the 'R' aperture
  2214. try:
  2215. if self.apertures[current_aperture]["type"] == 'R':
  2216. width = self.apertures[current_aperture]['width']
  2217. height = self.apertures[current_aperture]['height']
  2218. minx = min(path[0][0], path[1][0]) - width / 2
  2219. maxx = max(path[0][0], path[1][0]) + width / 2
  2220. miny = min(path[0][1], path[1][1]) - height / 2
  2221. maxy = max(path[0][1], path[1][1]) + height / 2
  2222. log.debug("Coords: %s - %s - %s - %s" % (minx, miny, maxx, maxy))
  2223. geo = shply_box(minx, miny, maxx, maxy)
  2224. poly_buffer.append(geo)
  2225. if self.is_lpc is True:
  2226. try:
  2227. self.apertures[current_aperture]['clear_geometry'].append(geo)
  2228. except KeyError:
  2229. self.apertures[current_aperture]['clear_geometry'] = []
  2230. self.apertures[current_aperture]['clear_geometry'].append(geo)
  2231. else:
  2232. try:
  2233. self.apertures[current_aperture]['solid_geometry'].append(geo)
  2234. except KeyError:
  2235. self.apertures[current_aperture]['solid_geometry'] = []
  2236. self.apertures[current_aperture]['solid_geometry'].append(geo)
  2237. except:
  2238. pass
  2239. last_path_aperture = current_aperture
  2240. # we do this for the case that a region is done without having defined any aperture
  2241. # Allegro does that
  2242. if last_path_aperture is None:
  2243. if '0' not in self.apertures:
  2244. self.apertures['0'] = {}
  2245. self.apertures['0']['type'] = 'REG'
  2246. self.apertures['0']['solid_geometry'] = []
  2247. last_path_aperture = '0'
  2248. else:
  2249. self.app.inform.emit(_("[WARNING] Coordinates missing, line ignored: %s") % str(gline))
  2250. self.app.inform.emit(_("[WARNING_NOTCL] GERBER file might be CORRUPT. Check the file !!!"))
  2251. elif current_operation_code == 2:
  2252. if len(path) > 1:
  2253. geo = None
  2254. # --- BUFFERED ---
  2255. # this treats the case when we are storing geometry as paths only
  2256. if making_region:
  2257. # we do this for the case that a region is done without having defined any aperture
  2258. # Allegro does that
  2259. if last_path_aperture is None:
  2260. if '0' not in self.apertures:
  2261. self.apertures['0'] = {}
  2262. self.apertures['0']['type'] = 'REG'
  2263. self.apertures['0']['solid_geometry'] = []
  2264. last_path_aperture = '0'
  2265. geo = Polygon()
  2266. else:
  2267. geo = LineString(path)
  2268. try:
  2269. if self.apertures[last_path_aperture]["type"] != 'R':
  2270. if not geo.is_empty:
  2271. follow_buffer.append(geo)
  2272. try:
  2273. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2274. except KeyError:
  2275. self.apertures[current_aperture]['follow_geometry'] = []
  2276. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2277. except Exception as e:
  2278. log.debug("camlib.Gerber.parse_lines() --> %s" % str(e))
  2279. if not geo.is_empty:
  2280. follow_buffer.append(geo)
  2281. try:
  2282. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2283. except KeyError:
  2284. self.apertures[current_aperture]['follow_geometry'] = []
  2285. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2286. # this treats the case when we are storing geometry as solids
  2287. if making_region:
  2288. # we do this for the case that a region is done without having defined any aperture
  2289. # Allegro does that
  2290. if last_path_aperture is None:
  2291. if '0' not in self.apertures:
  2292. self.apertures['0'] = {}
  2293. self.apertures['0']['type'] = 'REG'
  2294. self.apertures['0']['solid_geometry'] = []
  2295. last_path_aperture = '0'
  2296. elem = [linear_x, linear_y]
  2297. if elem != path[-1]:
  2298. path.append([linear_x, linear_y])
  2299. try:
  2300. geo = Polygon(path)
  2301. except ValueError:
  2302. log.warning("Problem %s %s" % (gline, line_num))
  2303. self.app.inform.emit(_("[ERROR] Region does not have enough points. "
  2304. "File will be processed but there are parser errors. "
  2305. "Line number: %s") % str(line_num))
  2306. else:
  2307. if last_path_aperture is None:
  2308. log.warning("No aperture defined for curent path. (%d)" % line_num)
  2309. width = self.apertures[last_path_aperture]["size"] # TODO: WARNING this should fail!
  2310. geo = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  2311. try:
  2312. if self.apertures[last_path_aperture]["type"] != 'R':
  2313. if not geo.is_empty:
  2314. poly_buffer.append(geo)
  2315. if self.is_lpc is True:
  2316. try:
  2317. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  2318. except KeyError:
  2319. self.apertures[last_path_aperture]['clear_geometry'] = []
  2320. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  2321. else:
  2322. try:
  2323. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  2324. except KeyError:
  2325. self.apertures[last_path_aperture]['solid_geometry'] = []
  2326. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  2327. except Exception as e:
  2328. log.debug("camlib.Gerber.parse_lines() --> %s" % str(e))
  2329. poly_buffer.append(geo)
  2330. if self.is_lpc is True:
  2331. try:
  2332. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  2333. except KeyError:
  2334. self.apertures[last_path_aperture]['clear_geometry'] = []
  2335. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  2336. else:
  2337. try:
  2338. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  2339. except KeyError:
  2340. self.apertures[last_path_aperture]['solid_geometry'] = []
  2341. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  2342. # if linear_x or linear_y are None, ignore those
  2343. if linear_x is not None and linear_y is not None:
  2344. path = [[linear_x, linear_y]] # Start new path
  2345. else:
  2346. self.app.inform.emit(_("[WARNING] Coordinates missing, line ignored: %s") % str(gline))
  2347. self.app.inform.emit(_("[WARNING_NOTCL] GERBER file might be CORRUPT. Check the file !!!"))
  2348. # Flash
  2349. # Not allowed in region mode.
  2350. elif current_operation_code == 3:
  2351. # Create path draw so far.
  2352. if len(path) > 1:
  2353. # --- Buffered ----
  2354. # this treats the case when we are storing geometry as paths
  2355. geo = LineString(path)
  2356. if not geo.is_empty:
  2357. try:
  2358. if self.apertures[last_path_aperture]["type"] != 'R':
  2359. follow_buffer.append(geo)
  2360. try:
  2361. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2362. except KeyError:
  2363. self.apertures[current_aperture]['follow_geometry'] = []
  2364. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2365. except:
  2366. follow_buffer.append(geo)
  2367. try:
  2368. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2369. except KeyError:
  2370. self.apertures[current_aperture]['follow_geometry'] = []
  2371. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2372. # this treats the case when we are storing geometry as solids
  2373. width = self.apertures[last_path_aperture]["size"]
  2374. geo = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  2375. if not geo.is_empty:
  2376. try:
  2377. if self.apertures[last_path_aperture]["type"] != 'R':
  2378. poly_buffer.append(geo)
  2379. if self.is_lpc is True:
  2380. try:
  2381. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  2382. except KeyError:
  2383. self.apertures[last_path_aperture]['clear_geometry'] = []
  2384. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  2385. else:
  2386. try:
  2387. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  2388. except KeyError:
  2389. self.apertures[last_path_aperture]['solid_geometry'] = []
  2390. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  2391. except:
  2392. poly_buffer.append(geo)
  2393. if self.is_lpc is True:
  2394. try:
  2395. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  2396. except KeyError:
  2397. self.apertures[last_path_aperture]['clear_geometry'] = []
  2398. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  2399. else:
  2400. try:
  2401. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  2402. except KeyError:
  2403. self.apertures[last_path_aperture]['solid_geometry'] = []
  2404. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  2405. # Reset path starting point
  2406. path = [[linear_x, linear_y]]
  2407. # --- BUFFERED ---
  2408. # Draw the flash
  2409. # this treats the case when we are storing geometry as paths
  2410. geo_flash = Point([linear_x, linear_y])
  2411. follow_buffer.append(geo_flash)
  2412. try:
  2413. self.apertures[current_aperture]['follow_geometry'].append(geo_flash)
  2414. except KeyError:
  2415. self.apertures[current_aperture]['follow_geometry'] = []
  2416. self.apertures[current_aperture]['follow_geometry'].append(geo_flash)
  2417. # this treats the case when we are storing geometry as solids
  2418. flash = Gerber.create_flash_geometry(
  2419. Point( [linear_x, linear_y]),
  2420. self.apertures[current_aperture],
  2421. int(self.steps_per_circle)
  2422. )
  2423. if not flash.is_empty:
  2424. poly_buffer.append(flash)
  2425. if self.is_lpc is True:
  2426. try:
  2427. self.apertures[current_aperture]['clear_geometry'].append(flash)
  2428. except KeyError:
  2429. self.apertures[current_aperture]['clear_geometry'] = []
  2430. self.apertures[current_aperture]['clear_geometry'].append(flash)
  2431. else:
  2432. try:
  2433. self.apertures[current_aperture]['solid_geometry'].append(flash)
  2434. except KeyError:
  2435. self.apertures[current_aperture]['solid_geometry'] = []
  2436. self.apertures[current_aperture]['solid_geometry'].append(flash)
  2437. # maybe those lines are not exactly needed but it is easier to read the program as those coordinates
  2438. # are used in case that circular interpolation is encountered within the Gerber file
  2439. current_x = linear_x
  2440. current_y = linear_y
  2441. # log.debug("Line_number=%3s X=%s Y=%s (%s)" % (line_num, linear_x, linear_y, gline))
  2442. continue
  2443. ### G74/75* - Single or multiple quadrant arcs
  2444. match = self.quad_re.search(gline)
  2445. if match:
  2446. if match.group(1) == '4':
  2447. quadrant_mode = 'SINGLE'
  2448. else:
  2449. quadrant_mode = 'MULTI'
  2450. continue
  2451. ### G02/3 - Circular interpolation
  2452. # 2-clockwise, 3-counterclockwise
  2453. # Ex. format: G03 X0 Y50 I-50 J0 where the X, Y coords are the coords of the End Point
  2454. match = self.circ_re.search(gline)
  2455. if match:
  2456. arcdir = [None, None, "cw", "ccw"]
  2457. mode, circular_x, circular_y, i, j, d = match.groups()
  2458. try:
  2459. circular_x = parse_gerber_number(circular_x,
  2460. self.int_digits, self.frac_digits, self.gerber_zeros)
  2461. except:
  2462. circular_x = current_x
  2463. try:
  2464. circular_y = parse_gerber_number(circular_y,
  2465. self.int_digits, self.frac_digits, self.gerber_zeros)
  2466. except:
  2467. circular_y = current_y
  2468. # According to Gerber specification i and j are not modal, which means that when i or j are missing,
  2469. # they are to be interpreted as being zero
  2470. try:
  2471. i = parse_gerber_number(i, self.int_digits, self.frac_digits, self.gerber_zeros)
  2472. except:
  2473. i = 0
  2474. try:
  2475. j = parse_gerber_number(j, self.int_digits, self.frac_digits, self.gerber_zeros)
  2476. except:
  2477. j = 0
  2478. if quadrant_mode is None:
  2479. log.error("Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num)
  2480. log.error(gline)
  2481. continue
  2482. if mode is None and current_interpolation_mode not in [2, 3]:
  2483. log.error("Found arc without circular interpolation mode defined. (%d)" % line_num)
  2484. log.error(gline)
  2485. continue
  2486. elif mode is not None:
  2487. current_interpolation_mode = int(mode)
  2488. # Set operation code if provided
  2489. try:
  2490. current_operation_code = int(d)
  2491. current_d = current_operation_code
  2492. except:
  2493. current_operation_code = current_d
  2494. # Nothing created! Pen Up.
  2495. if current_operation_code == 2:
  2496. log.warning("Arc with D2. (%d)" % line_num)
  2497. if len(path) > 1:
  2498. if last_path_aperture is None:
  2499. log.warning("No aperture defined for curent path. (%d)" % line_num)
  2500. # --- BUFFERED ---
  2501. width = self.apertures[last_path_aperture]["size"]
  2502. # this treats the case when we are storing geometry as paths
  2503. geo = LineString(path)
  2504. if not geo.is_empty:
  2505. follow_buffer.append(geo)
  2506. try:
  2507. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2508. except KeyError:
  2509. self.apertures[current_aperture]['follow_geometry'] = []
  2510. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2511. # this treats the case when we are storing geometry as solids
  2512. buffered = LineString(path).buffer(width / 1.999, int(self.steps_per_circle))
  2513. if not buffered.is_empty:
  2514. poly_buffer.append(buffered)
  2515. if self.is_lpc is True:
  2516. try:
  2517. self.apertures[last_path_aperture]['clear_geometry'].append(buffered)
  2518. except KeyError:
  2519. self.apertures[last_path_aperture]['clear_geometry'] = []
  2520. self.apertures[last_path_aperture]['clear_geometry'].append(buffered)
  2521. else:
  2522. try:
  2523. self.apertures[last_path_aperture]['solid_geometry'].append(buffered)
  2524. except KeyError:
  2525. self.apertures[last_path_aperture]['solid_geometry'] = []
  2526. self.apertures[last_path_aperture]['solid_geometry'].append(buffered)
  2527. current_x = circular_x
  2528. current_y = circular_y
  2529. path = [[current_x, current_y]] # Start new path
  2530. continue
  2531. # Flash should not happen here
  2532. if current_operation_code == 3:
  2533. log.error("Trying to flash within arc. (%d)" % line_num)
  2534. continue
  2535. if quadrant_mode == 'MULTI':
  2536. center = [i + current_x, j + current_y]
  2537. radius = sqrt(i ** 2 + j ** 2)
  2538. start = arctan2(-j, -i) # Start angle
  2539. # Numerical errors might prevent start == stop therefore
  2540. # we check ahead of time. This should result in a
  2541. # 360 degree arc.
  2542. if current_x == circular_x and current_y == circular_y:
  2543. stop = start
  2544. else:
  2545. stop = arctan2(-center[1] + circular_y, -center[0] + circular_x) # Stop angle
  2546. this_arc = arc(center, radius, start, stop,
  2547. arcdir[current_interpolation_mode],
  2548. int(self.steps_per_circle))
  2549. # The last point in the computed arc can have
  2550. # numerical errors. The exact final point is the
  2551. # specified (x, y). Replace.
  2552. this_arc[-1] = (circular_x, circular_y)
  2553. # Last point in path is current point
  2554. # current_x = this_arc[-1][0]
  2555. # current_y = this_arc[-1][1]
  2556. current_x, current_y = circular_x, circular_y
  2557. # Append
  2558. path += this_arc
  2559. last_path_aperture = current_aperture
  2560. continue
  2561. if quadrant_mode == 'SINGLE':
  2562. center_candidates = [
  2563. [i + current_x, j + current_y],
  2564. [-i + current_x, j + current_y],
  2565. [i + current_x, -j + current_y],
  2566. [-i + current_x, -j + current_y]
  2567. ]
  2568. valid = False
  2569. log.debug("I: %f J: %f" % (i, j))
  2570. for center in center_candidates:
  2571. radius = sqrt(i ** 2 + j ** 2)
  2572. # Make sure radius to start is the same as radius to end.
  2573. radius2 = sqrt((center[0] - circular_x) ** 2 + (center[1] - circular_y) ** 2)
  2574. if radius2 < radius * 0.95 or radius2 > radius * 1.05:
  2575. continue # Not a valid center.
  2576. # Correct i and j and continue as with multi-quadrant.
  2577. i = center[0] - current_x
  2578. j = center[1] - current_y
  2579. start = arctan2(-j, -i) # Start angle
  2580. stop = arctan2(-center[1] + circular_y, -center[0] + circular_x) # Stop angle
  2581. angle = abs(arc_angle(start, stop, arcdir[current_interpolation_mode]))
  2582. log.debug("ARC START: %f, %f CENTER: %f, %f STOP: %f, %f" %
  2583. (current_x, current_y, center[0], center[1], circular_x, circular_y))
  2584. log.debug("START Ang: %f, STOP Ang: %f, DIR: %s, ABS: %.12f <= %.12f: %s" %
  2585. (start * 180 / pi, stop * 180 / pi, arcdir[current_interpolation_mode],
  2586. angle * 180 / pi, pi / 2 * 180 / pi, angle <= (pi + 1e-6) / 2))
  2587. if angle <= (pi + 1e-6) / 2:
  2588. log.debug("########## ACCEPTING ARC ############")
  2589. this_arc = arc(center, radius, start, stop,
  2590. arcdir[current_interpolation_mode],
  2591. int(self.steps_per_circle))
  2592. # Replace with exact values
  2593. this_arc[-1] = (circular_x, circular_y)
  2594. # current_x = this_arc[-1][0]
  2595. # current_y = this_arc[-1][1]
  2596. current_x, current_y = circular_x, circular_y
  2597. path += this_arc
  2598. last_path_aperture = current_aperture
  2599. valid = True
  2600. break
  2601. if valid:
  2602. continue
  2603. else:
  2604. log.warning("Invalid arc in line %d." % line_num)
  2605. ## EOF
  2606. match = self.eof_re.search(gline)
  2607. if match:
  2608. continue
  2609. ### Line did not match any pattern. Warn user.
  2610. log.warning("Line ignored (%d): %s" % (line_num, gline))
  2611. if len(path) > 1:
  2612. # In case that G01 (moving) aperture is rectangular, there is no need to still create
  2613. # another geo since we already created a shapely box using the start and end coordinates found in
  2614. # path variable. We do it only for other apertures than 'R' type
  2615. if self.apertures[last_path_aperture]["type"] == 'R':
  2616. pass
  2617. else:
  2618. # EOF, create shapely LineString if something still in path
  2619. ## --- Buffered ---
  2620. # this treats the case when we are storing geometry as paths
  2621. geo = LineString(path)
  2622. if not geo.is_empty:
  2623. follow_buffer.append(geo)
  2624. try:
  2625. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2626. except KeyError:
  2627. self.apertures[current_aperture]['follow_geometry'] = []
  2628. self.apertures[current_aperture]['follow_geometry'].append(geo)
  2629. # this treats the case when we are storing geometry as solids
  2630. width = self.apertures[last_path_aperture]["size"]
  2631. geo = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  2632. if not geo.is_empty:
  2633. poly_buffer.append(geo)
  2634. if self.is_lpc is True:
  2635. try:
  2636. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  2637. except KeyError:
  2638. self.apertures[last_path_aperture]['clear_geometry'] = []
  2639. self.apertures[last_path_aperture]['clear_geometry'].append(geo)
  2640. else:
  2641. try:
  2642. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  2643. except KeyError:
  2644. self.apertures[last_path_aperture]['solid_geometry'] = []
  2645. self.apertures[last_path_aperture]['solid_geometry'].append(geo)
  2646. # TODO: make sure to keep track of units changes because right now it seems to happen in a weird way
  2647. # find out the conversion factor used to convert inside the self.apertures keys: size, width, height
  2648. file_units = gerber_units if gerber_units else 'IN'
  2649. app_units = self.app.defaults['units']
  2650. conversion_factor = 25.4 if file_units == 'IN' else (1/25.4) if file_units != app_units else 1
  2651. # first check if we have any clear_geometry (LPC) and if yes then we need to substract it
  2652. # from the apertures solid_geometry
  2653. temp_geo = []
  2654. for apid in self.apertures:
  2655. if 'clear_geometry' in self.apertures[apid]:
  2656. clear_geo = MultiPolygon(self.apertures[apid]['clear_geometry'])
  2657. for solid_geo in self.apertures[apid]['solid_geometry']:
  2658. if clear_geo.intersects(solid_geo):
  2659. res_geo = solid_geo.difference(clear_geo)
  2660. temp_geo.append(res_geo)
  2661. else:
  2662. temp_geo.append(solid_geo)
  2663. self.apertures[apid]['solid_geometry'] = deepcopy(temp_geo)
  2664. self.apertures[apid].pop('clear_geometry', None)
  2665. for k, v in self.apertures[apid].items():
  2666. if k == 'size' or k == 'width' or k == 'height':
  2667. self.apertures[apid][k] = v * conversion_factor
  2668. # --- Apply buffer ---
  2669. # this treats the case when we are storing geometry as paths
  2670. self.follow_geometry = follow_buffer
  2671. # this treats the case when we are storing geometry as solids
  2672. log.warning("Joining %d polygons." % len(poly_buffer))
  2673. if len(poly_buffer) == 0:
  2674. log.error("Object is not Gerber file or empty. Aborting Object creation.")
  2675. return
  2676. if self.use_buffer_for_union:
  2677. log.debug("Union by buffer...")
  2678. new_poly = MultiPolygon(poly_buffer)
  2679. new_poly = new_poly.buffer(0.00000001)
  2680. new_poly = new_poly.buffer(-0.00000001)
  2681. log.warning("Union(buffer) done.")
  2682. else:
  2683. log.debug("Union by union()...")
  2684. new_poly = cascaded_union(poly_buffer)
  2685. new_poly = new_poly.buffer(0, int(self.steps_per_circle / 4))
  2686. log.warning("Union done.")
  2687. if current_polarity == 'D':
  2688. self.solid_geometry = self.solid_geometry.union(new_poly)
  2689. else:
  2690. self.solid_geometry = self.solid_geometry.difference(new_poly)
  2691. except Exception as err:
  2692. ex_type, ex, tb = sys.exc_info()
  2693. traceback.print_tb(tb)
  2694. #print traceback.format_exc()
  2695. log.error("Gerber PARSING FAILED. Line %d: %s" % (line_num, gline))
  2696. loc = 'Gerber Line #%d Gerber Line Content: %s\n' % (line_num, gline) + repr(err)
  2697. self.app.inform.emit(_("[ERROR]Gerber Parser ERROR.\n%s:") % loc)
  2698. @staticmethod
  2699. def create_flash_geometry(location, aperture, steps_per_circle=None):
  2700. # log.debug('Flashing @%s, Aperture: %s' % (location, aperture))
  2701. if steps_per_circle is None:
  2702. steps_per_circle = 64
  2703. if type(location) == list:
  2704. location = Point(location)
  2705. if aperture['type'] == 'C': # Circles
  2706. return location.buffer(aperture['size'] / 2, int(steps_per_circle / 4))
  2707. if aperture['type'] == 'R': # Rectangles
  2708. loc = location.coords[0]
  2709. width = aperture['width']
  2710. height = aperture['height']
  2711. minx = loc[0] - width / 2
  2712. maxx = loc[0] + width / 2
  2713. miny = loc[1] - height / 2
  2714. maxy = loc[1] + height / 2
  2715. return shply_box(minx, miny, maxx, maxy)
  2716. if aperture['type'] == 'O': # Obround
  2717. loc = location.coords[0]
  2718. width = aperture['width']
  2719. height = aperture['height']
  2720. if width > height:
  2721. p1 = Point(loc[0] + 0.5 * (width - height), loc[1])
  2722. p2 = Point(loc[0] - 0.5 * (width - height), loc[1])
  2723. c1 = p1.buffer(height * 0.5, int(steps_per_circle / 4))
  2724. c2 = p2.buffer(height * 0.5, int(steps_per_circle / 4))
  2725. else:
  2726. p1 = Point(loc[0], loc[1] + 0.5 * (height - width))
  2727. p2 = Point(loc[0], loc[1] - 0.5 * (height - width))
  2728. c1 = p1.buffer(width * 0.5, int(steps_per_circle / 4))
  2729. c2 = p2.buffer(width * 0.5, int(steps_per_circle / 4))
  2730. return cascaded_union([c1, c2]).convex_hull
  2731. if aperture['type'] == 'P': # Regular polygon
  2732. loc = location.coords[0]
  2733. diam = aperture['diam']
  2734. n_vertices = aperture['nVertices']
  2735. points = []
  2736. for i in range(0, n_vertices):
  2737. x = loc[0] + 0.5 * diam * (cos(2 * pi * i / n_vertices))
  2738. y = loc[1] + 0.5 * diam * (sin(2 * pi * i / n_vertices))
  2739. points.append((x, y))
  2740. ply = Polygon(points)
  2741. if 'rotation' in aperture:
  2742. ply = affinity.rotate(ply, aperture['rotation'])
  2743. return ply
  2744. if aperture['type'] == 'AM': # Aperture Macro
  2745. loc = location.coords[0]
  2746. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  2747. if flash_geo.is_empty:
  2748. log.warning("Empty geometry for Aperture Macro: %s" % str(aperture['macro'].name))
  2749. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  2750. log.warning("Unknown aperture type: %s" % aperture['type'])
  2751. return None
  2752. def create_geometry(self):
  2753. """
  2754. Geometry from a Gerber file is made up entirely of polygons.
  2755. Every stroke (linear or circular) has an aperture which gives
  2756. it thickness. Additionally, aperture strokes have non-zero area,
  2757. and regions naturally do as well.
  2758. :rtype : None
  2759. :return: None
  2760. """
  2761. pass
  2762. # self.buffer_paths()
  2763. #
  2764. # self.fix_regions()
  2765. #
  2766. # self.do_flashes()
  2767. #
  2768. # self.solid_geometry = cascaded_union(self.buffered_paths +
  2769. # [poly['polygon'] for poly in self.regions] +
  2770. # self.flash_geometry)
  2771. def get_bounding_box(self, margin=0.0, rounded=False):
  2772. """
  2773. Creates and returns a rectangular polygon bounding at a distance of
  2774. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  2775. can optionally have rounded corners of radius equal to margin.
  2776. :param margin: Distance to enlarge the rectangular bounding
  2777. box in both positive and negative, x and y axes.
  2778. :type margin: float
  2779. :param rounded: Wether or not to have rounded corners.
  2780. :type rounded: bool
  2781. :return: The bounding box.
  2782. :rtype: Shapely.Polygon
  2783. """
  2784. bbox = self.solid_geometry.envelope.buffer(margin)
  2785. if not rounded:
  2786. bbox = bbox.envelope
  2787. return bbox
  2788. def bounds(self):
  2789. """
  2790. Returns coordinates of rectangular bounds
  2791. of Gerber geometry: (xmin, ymin, xmax, ymax).
  2792. """
  2793. # fixed issue of getting bounds only for one level lists of objects
  2794. # now it can get bounds for nested lists of objects
  2795. log.debug("Gerber->bounds()")
  2796. if self.solid_geometry is None:
  2797. log.debug("solid_geometry is None")
  2798. return 0, 0, 0, 0
  2799. def bounds_rec(obj):
  2800. if type(obj) is list and type(obj) is not MultiPolygon:
  2801. minx = Inf
  2802. miny = Inf
  2803. maxx = -Inf
  2804. maxy = -Inf
  2805. for k in obj:
  2806. if type(k) is dict:
  2807. for key in k:
  2808. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  2809. minx = min(minx, minx_)
  2810. miny = min(miny, miny_)
  2811. maxx = max(maxx, maxx_)
  2812. maxy = max(maxy, maxy_)
  2813. else:
  2814. if not k.is_empty:
  2815. try:
  2816. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2817. except Exception as e:
  2818. log.debug("camlib.Gerber.bounds() --> %s" % str(e))
  2819. return
  2820. minx = min(minx, minx_)
  2821. miny = min(miny, miny_)
  2822. maxx = max(maxx, maxx_)
  2823. maxy = max(maxy, maxy_)
  2824. return minx, miny, maxx, maxy
  2825. else:
  2826. # it's a Shapely object, return it's bounds
  2827. return obj.bounds
  2828. bounds_coords = bounds_rec(self.solid_geometry)
  2829. return bounds_coords
  2830. def scale(self, xfactor, yfactor=None, point=None):
  2831. """
  2832. Scales the objects' geometry on the XY plane by a given factor.
  2833. These are:
  2834. * ``buffered_paths``
  2835. * ``flash_geometry``
  2836. * ``solid_geometry``
  2837. * ``regions``
  2838. NOTE:
  2839. Does not modify the data used to create these elements. If these
  2840. are recreated, the scaling will be lost. This behavior was modified
  2841. because of the complexity reached in this class.
  2842. :param factor: Number by which to scale.
  2843. :type factor: float
  2844. :rtype : None
  2845. """
  2846. log.debug("camlib.Gerber.scale()")
  2847. try:
  2848. xfactor = float(xfactor)
  2849. except:
  2850. self.app.inform.emit(_("[ERROR_NOTCL] Scale factor has to be a number: integer or float."))
  2851. return
  2852. if yfactor is None:
  2853. yfactor = xfactor
  2854. else:
  2855. try:
  2856. yfactor = float(yfactor)
  2857. except:
  2858. self.app.inform.emit(_("[ERROR_NOTCL] Scale factor has to be a number: integer or float."))
  2859. return
  2860. if point is None:
  2861. px = 0
  2862. py = 0
  2863. else:
  2864. px, py = point
  2865. def scale_geom(obj):
  2866. if type(obj) is list:
  2867. new_obj = []
  2868. for g in obj:
  2869. new_obj.append(scale_geom(g))
  2870. return new_obj
  2871. else:
  2872. return affinity.scale(obj, xfactor,
  2873. yfactor, origin=(px, py))
  2874. self.solid_geometry = scale_geom(self.solid_geometry)
  2875. self.follow_geometry = scale_geom(self.follow_geometry)
  2876. # we need to scale the geometry stored in the Gerber apertures, too
  2877. try:
  2878. for apid in self.apertures:
  2879. self.apertures[apid]['solid_geometry'] = scale_geom(self.apertures[apid]['solid_geometry'])
  2880. except Exception as e:
  2881. log.debug('FlatCAMGeometry.scale() --> %s' % str(e))
  2882. self.app.inform.emit(_("[success] Gerber Scale done."))
  2883. ## solid_geometry ???
  2884. # It's a cascaded union of objects.
  2885. # self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  2886. # factor, origin=(0, 0))
  2887. # # Now buffered_paths, flash_geometry and solid_geometry
  2888. # self.create_geometry()
  2889. def offset(self, vect):
  2890. """
  2891. Offsets the objects' geometry on the XY plane by a given vector.
  2892. These are:
  2893. * ``buffered_paths``
  2894. * ``flash_geometry``
  2895. * ``solid_geometry``
  2896. * ``regions``
  2897. NOTE:
  2898. Does not modify the data used to create these elements. If these
  2899. are recreated, the scaling will be lost. This behavior was modified
  2900. because of the complexity reached in this class.
  2901. :param vect: (x, y) offset vector.
  2902. :type vect: tuple
  2903. :return: None
  2904. """
  2905. try:
  2906. dx, dy = vect
  2907. except TypeError:
  2908. self.app.inform.emit(_("[ERROR_NOTCL] An (x,y) pair of values are needed. "
  2909. "Probable you entered only one value in the Offset field."))
  2910. return
  2911. def offset_geom(obj):
  2912. if type(obj) is list:
  2913. new_obj = []
  2914. for g in obj:
  2915. new_obj.append(offset_geom(g))
  2916. return new_obj
  2917. else:
  2918. return affinity.translate(obj, xoff=dx, yoff=dy)
  2919. ## Solid geometry
  2920. self.solid_geometry = offset_geom(self.solid_geometry)
  2921. self.follow_geometry = offset_geom(self.follow_geometry)
  2922. # we need to offset the geometry stored in the Gerber apertures, too
  2923. try:
  2924. for apid in self.apertures:
  2925. self.apertures[apid]['solid_geometry'] = offset_geom(self.apertures[apid]['solid_geometry'])
  2926. except Exception as e:
  2927. log.debug('FlatCAMGeometry.offset() --> %s' % str(e))
  2928. self.app.inform.emit(_("[success] Gerber Offset done."))
  2929. def mirror(self, axis, point):
  2930. """
  2931. Mirrors the object around a specified axis passing through
  2932. the given point. What is affected:
  2933. * ``buffered_paths``
  2934. * ``flash_geometry``
  2935. * ``solid_geometry``
  2936. * ``regions``
  2937. NOTE:
  2938. Does not modify the data used to create these elements. If these
  2939. are recreated, the scaling will be lost. This behavior was modified
  2940. because of the complexity reached in this class.
  2941. :param axis: "X" or "Y" indicates around which axis to mirror.
  2942. :type axis: str
  2943. :param point: [x, y] point belonging to the mirror axis.
  2944. :type point: list
  2945. :return: None
  2946. """
  2947. px, py = point
  2948. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  2949. def mirror_geom(obj):
  2950. if type(obj) is list:
  2951. new_obj = []
  2952. for g in obj:
  2953. new_obj.append(mirror_geom(g))
  2954. return new_obj
  2955. else:
  2956. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  2957. self.solid_geometry = mirror_geom(self.solid_geometry)
  2958. self.follow_geometry = mirror_geom(self.follow_geometry)
  2959. # we need to mirror the geometry stored in the Gerber apertures, too
  2960. try:
  2961. for apid in self.apertures:
  2962. self.apertures[apid]['solid_geometry'] = mirror_geom(self.apertures[apid]['solid_geometry'])
  2963. except Exception as e:
  2964. log.debug('FlatCAMGeometry.mirror() --> %s' % str(e))
  2965. # It's a cascaded union of objects.
  2966. # self.solid_geometry = affinity.scale(self.solid_geometry,
  2967. # xscale, yscale, origin=(px, py))
  2968. def skew(self, angle_x, angle_y, point):
  2969. """
  2970. Shear/Skew the geometries of an object by angles along x and y dimensions.
  2971. Parameters
  2972. ----------
  2973. xs, ys : float, float
  2974. The shear angle(s) for the x and y axes respectively. These can be
  2975. specified in either degrees (default) or radians by setting
  2976. use_radians=True.
  2977. See shapely manual for more information:
  2978. http://toblerity.org/shapely/manual.html#affine-transformations
  2979. """
  2980. px, py = point
  2981. def skew_geom(obj):
  2982. if type(obj) is list:
  2983. new_obj = []
  2984. for g in obj:
  2985. new_obj.append(skew_geom(g))
  2986. return new_obj
  2987. else:
  2988. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  2989. self.solid_geometry = skew_geom(self.solid_geometry)
  2990. self.follow_geometry = skew_geom(self.follow_geometry)
  2991. # we need to skew the geometry stored in the Gerber apertures, too
  2992. try:
  2993. for apid in self.apertures:
  2994. self.apertures[apid]['solid_geometry'] = skew_geom(self.apertures[apid]['solid_geometry'])
  2995. except Exception as e:
  2996. log.debug('FlatCAMGeometry.skew() --> %s' % str(e))
  2997. # self.solid_geometry = affinity.skew(self.solid_geometry, angle_x, angle_y, origin=(px, py))
  2998. def rotate(self, angle, point):
  2999. """
  3000. Rotate an object by a given angle around given coords (point)
  3001. :param angle:
  3002. :param point:
  3003. :return:
  3004. """
  3005. px, py = point
  3006. def rotate_geom(obj):
  3007. if type(obj) is list:
  3008. new_obj = []
  3009. for g in obj:
  3010. new_obj.append(rotate_geom(g))
  3011. return new_obj
  3012. else:
  3013. return affinity.rotate(obj, angle, origin=(px, py))
  3014. self.solid_geometry = rotate_geom(self.solid_geometry)
  3015. self.follow_geometry = rotate_geom(self.follow_geometry)
  3016. # we need to rotate the geometry stored in the Gerber apertures, too
  3017. try:
  3018. for apid in self.apertures:
  3019. self.apertures[apid]['solid_geometry'] = rotate_geom(self.apertures[apid]['solid_geometry'])
  3020. except Exception as e:
  3021. log.debug('FlatCAMGeometry.rotate() --> %s' % str(e))
  3022. # self.solid_geometry = affinity.rotate(self.solid_geometry, angle, origin=(px, py))
  3023. class Excellon(Geometry):
  3024. """
  3025. *ATTRIBUTES*
  3026. * ``tools`` (dict): The key is the tool name and the value is
  3027. a dictionary specifying the tool:
  3028. ================ ====================================
  3029. Key Value
  3030. ================ ====================================
  3031. C Diameter of the tool
  3032. solid_geometry Geometry list for each tool
  3033. Others Not supported (Ignored).
  3034. ================ ====================================
  3035. * ``drills`` (list): Each is a dictionary:
  3036. ================ ====================================
  3037. Key Value
  3038. ================ ====================================
  3039. point (Shapely.Point) Where to drill
  3040. tool (str) A key in ``tools``
  3041. ================ ====================================
  3042. * ``slots`` (list): Each is a dictionary
  3043. ================ ====================================
  3044. Key Value
  3045. ================ ====================================
  3046. start (Shapely.Point) Start point of the slot
  3047. stop (Shapely.Point) Stop point of the slot
  3048. tool (str) A key in ``tools``
  3049. ================ ====================================
  3050. """
  3051. defaults = {
  3052. "zeros": "L",
  3053. "excellon_format_upper_mm": '3',
  3054. "excellon_format_lower_mm": '3',
  3055. "excellon_format_upper_in": '2',
  3056. "excellon_format_lower_in": '4',
  3057. "excellon_units": 'INCH',
  3058. "geo_steps_per_circle": '64'
  3059. }
  3060. def __init__(self, zeros=None, excellon_format_upper_mm=None, excellon_format_lower_mm=None,
  3061. excellon_format_upper_in=None, excellon_format_lower_in=None, excellon_units=None,
  3062. geo_steps_per_circle=None):
  3063. """
  3064. The constructor takes no parameters.
  3065. :return: Excellon object.
  3066. :rtype: Excellon
  3067. """
  3068. if geo_steps_per_circle is None:
  3069. geo_steps_per_circle = int(Excellon.defaults['geo_steps_per_circle'])
  3070. self.geo_steps_per_circle = int(geo_steps_per_circle)
  3071. Geometry.__init__(self, geo_steps_per_circle=int(geo_steps_per_circle))
  3072. # dictionary to store tools, see above for description
  3073. self.tools = {}
  3074. # list to store the drills, see above for description
  3075. self.drills = []
  3076. # self.slots (list) to store the slots; each is a dictionary
  3077. self.slots = []
  3078. self.source_file = ''
  3079. # it serve to flag if a start routing or a stop routing was encountered
  3080. # if a stop is encounter and this flag is still 0 (so there is no stop for a previous start) issue error
  3081. self.routing_flag = 1
  3082. self.match_routing_start = None
  3083. self.match_routing_stop = None
  3084. self.num_tools = [] # List for keeping the tools sorted
  3085. self.index_per_tool = {} # Dictionary to store the indexed points for each tool
  3086. ## IN|MM -> Units are inherited from Geometry
  3087. #self.units = units
  3088. # Trailing "T" or leading "L" (default)
  3089. #self.zeros = "T"
  3090. self.zeros = zeros or self.defaults["zeros"]
  3091. self.zeros_found = self.zeros
  3092. self.units_found = self.units
  3093. # this will serve as a default if the Excellon file has no info regarding of tool diameters (this info may be
  3094. # in another file like for PCB WIzard ECAD software
  3095. self.toolless_diam = 1.0
  3096. # signal that the Excellon file has no tool diameter informations and the tools have bogus (random) diameter
  3097. self.diameterless = False
  3098. # Excellon format
  3099. self.excellon_format_upper_in = excellon_format_upper_in or self.defaults["excellon_format_upper_in"]
  3100. self.excellon_format_lower_in = excellon_format_lower_in or self.defaults["excellon_format_lower_in"]
  3101. self.excellon_format_upper_mm = excellon_format_upper_mm or self.defaults["excellon_format_upper_mm"]
  3102. self.excellon_format_lower_mm = excellon_format_lower_mm or self.defaults["excellon_format_lower_mm"]
  3103. self.excellon_units = excellon_units or self.defaults["excellon_units"]
  3104. # detected Excellon format is stored here:
  3105. self.excellon_format = None
  3106. # Attributes to be included in serialization
  3107. # Always append to it because it carries contents
  3108. # from Geometry.
  3109. self.ser_attrs += ['tools', 'drills', 'zeros', 'excellon_format_upper_mm', 'excellon_format_lower_mm',
  3110. 'excellon_format_upper_in', 'excellon_format_lower_in', 'excellon_units', 'slots',
  3111. 'source_file']
  3112. #### Patterns ####
  3113. # Regex basics:
  3114. # ^ - beginning
  3115. # $ - end
  3116. # *: 0 or more, +: 1 or more, ?: 0 or 1
  3117. # M48 - Beginning of Part Program Header
  3118. self.hbegin_re = re.compile(r'^M48$')
  3119. # ;HEADER - Beginning of Allegro Program Header
  3120. self.allegro_hbegin_re = re.compile(r'\;\s*(HEADER)')
  3121. # M95 or % - End of Part Program Header
  3122. # NOTE: % has different meaning in the body
  3123. self.hend_re = re.compile(r'^(?:M95|%)$')
  3124. # FMAT Excellon format
  3125. # Ignored in the parser
  3126. #self.fmat_re = re.compile(r'^FMAT,([12])$')
  3127. # Uunits and possible Excellon zeros and possible Excellon format
  3128. # INCH uses 6 digits
  3129. # METRIC uses 5/6
  3130. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?,?(\d*\.\d+)?.*$')
  3131. # Tool definition/parameters (?= is look-ahead
  3132. # NOTE: This might be an overkill!
  3133. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  3134. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  3135. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  3136. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  3137. self.toolset_re = re.compile(r'^T(\d+)(?=.*C,?(\d*\.?\d*))?' +
  3138. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  3139. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  3140. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  3141. self.detect_gcode_re = re.compile(r'^G2([01])$')
  3142. # Tool select
  3143. # Can have additional data after tool number but
  3144. # is ignored if present in the header.
  3145. # Warning: This will match toolset_re too.
  3146. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  3147. self.toolsel_re = re.compile(r'^T(\d+)')
  3148. # Headerless toolset
  3149. # self.toolset_hl_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))')
  3150. self.toolset_hl_re = re.compile(r'^T(\d+)(?:.?C(\d+\.?\d*))?')
  3151. # Comment
  3152. self.comm_re = re.compile(r'^;(.*)$')
  3153. # Absolute/Incremental G90/G91
  3154. self.absinc_re = re.compile(r'^G9([01])$')
  3155. # Modes of operation
  3156. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  3157. self.modes_re = re.compile(r'^G0([012345])')
  3158. # Measuring mode
  3159. # 1-metric, 2-inch
  3160. self.meas_re = re.compile(r'^M7([12])$')
  3161. # Coordinates
  3162. # self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  3163. # self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  3164. coordsperiod_re_string = r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]'
  3165. self.coordsperiod_re = re.compile(coordsperiod_re_string)
  3166. coordsnoperiod_re_string = r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]'
  3167. self.coordsnoperiod_re = re.compile(coordsnoperiod_re_string)
  3168. # Slots parsing
  3169. slots_re_string = r'^([^G]+)G85(.*)$'
  3170. self.slots_re = re.compile(slots_re_string)
  3171. # R - Repeat hole (# times, X offset, Y offset)
  3172. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  3173. # Various stop/pause commands
  3174. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  3175. # Allegro Excellon format support
  3176. self.tool_units_re = re.compile(r'(\;\s*Holesize \d+.\s*\=\s*(\d+.\d+).*(MILS|MM))')
  3177. # Altium Excellon format support
  3178. # it's a comment like this: ";FILE_FORMAT=2:5"
  3179. self.altium_format = re.compile(r'^;\s*(?:FILE_FORMAT)?(?:Format)?[=|:]\s*(\d+)[:|.](\d+).*$')
  3180. # Parse coordinates
  3181. self.leadingzeros_re = re.compile(r'^[-\+]?(0*)(\d*)')
  3182. # Repeating command
  3183. self.repeat_re = re.compile(r'R(\d+)')
  3184. def parse_file(self, filename=None, file_obj=None):
  3185. """
  3186. Reads the specified file as array of lines as
  3187. passes it to ``parse_lines()``.
  3188. :param filename: The file to be read and parsed.
  3189. :type filename: str
  3190. :return: None
  3191. """
  3192. if file_obj:
  3193. estr = file_obj
  3194. else:
  3195. if filename is None:
  3196. return "fail"
  3197. efile = open(filename, 'r')
  3198. estr = efile.readlines()
  3199. efile.close()
  3200. try:
  3201. self.parse_lines(estr)
  3202. except:
  3203. return "fail"
  3204. def parse_lines(self, elines):
  3205. """
  3206. Main Excellon parser.
  3207. :param elines: List of strings, each being a line of Excellon code.
  3208. :type elines: list
  3209. :return: None
  3210. """
  3211. # State variables
  3212. current_tool = ""
  3213. in_header = False
  3214. headerless = False
  3215. current_x = None
  3216. current_y = None
  3217. slot_current_x = None
  3218. slot_current_y = None
  3219. name_tool = 0
  3220. allegro_warning = False
  3221. line_units_found = False
  3222. repeating_x = 0
  3223. repeating_y = 0
  3224. repeat = 0
  3225. line_units = ''
  3226. #### Parsing starts here ####
  3227. line_num = 0 # Line number
  3228. eline = ""
  3229. try:
  3230. for eline in elines:
  3231. line_num += 1
  3232. # log.debug("%3d %s" % (line_num, str(eline)))
  3233. self.source_file += eline
  3234. # Cleanup lines
  3235. eline = eline.strip(' \r\n')
  3236. # Excellon files and Gcode share some extensions therefore if we detect G20 or G21 it's GCODe
  3237. # and we need to exit from here
  3238. if self.detect_gcode_re.search(eline):
  3239. log.warning("This is GCODE mark: %s" % eline)
  3240. self.app.inform.emit(_('[ERROR_NOTCL] This is GCODE mark: %s') % eline)
  3241. return
  3242. # Header Begin (M48) #
  3243. if self.hbegin_re.search(eline):
  3244. in_header = True
  3245. log.warning("Found start of the header: %s" % eline)
  3246. continue
  3247. # Allegro Header Begin (;HEADER) #
  3248. if self.allegro_hbegin_re.search(eline):
  3249. in_header = True
  3250. allegro_warning = True
  3251. log.warning("Found ALLEGRO start of the header: %s" % eline)
  3252. continue
  3253. # Search for Header End #
  3254. # Since there might be comments in the header that include header end char (% or M95)
  3255. # we ignore the lines starting with ';' that contains such header end chars because it is not a
  3256. # real header end.
  3257. if self.comm_re.search(eline):
  3258. match = self.tool_units_re.search(eline)
  3259. if match:
  3260. if line_units_found is False:
  3261. line_units_found = True
  3262. line_units = match.group(3)
  3263. self.convert_units({"MILS": "IN", "MM": "MM"}[line_units])
  3264. log.warning("Type of Allegro UNITS found inline in comments: %s" % line_units)
  3265. if match.group(2):
  3266. name_tool += 1
  3267. if line_units == 'MILS':
  3268. spec = {"C": (float(match.group(2)) / 1000)}
  3269. self.tools[str(name_tool)] = spec
  3270. log.debug(" Tool definition: %s %s" % (name_tool, spec))
  3271. else:
  3272. spec = {"C": float(match.group(2))}
  3273. self.tools[str(name_tool)] = spec
  3274. log.debug(" Tool definition: %s %s" % (name_tool, spec))
  3275. spec['solid_geometry'] = []
  3276. continue
  3277. # search for Altium Excellon Format / Sprint Layout who is included as a comment
  3278. match = self.altium_format.search(eline)
  3279. if match:
  3280. self.excellon_format_upper_mm = match.group(1)
  3281. self.excellon_format_lower_mm = match.group(2)
  3282. self.excellon_format_upper_in = match.group(1)
  3283. self.excellon_format_lower_in = match.group(2)
  3284. log.warning("Altium Excellon format preset found in comments: %s:%s" %
  3285. (match.group(1), match.group(2)))
  3286. continue
  3287. else:
  3288. log.warning("Line ignored, it's a comment: %s" % eline)
  3289. else:
  3290. if self.hend_re.search(eline):
  3291. if in_header is False or bool(self.tools) is False:
  3292. log.warning("Found end of the header but there is no header: %s" % eline)
  3293. log.warning("The only useful data in header are tools, units and format.")
  3294. log.warning("Therefore we will create units and format based on defaults.")
  3295. headerless = True
  3296. try:
  3297. self.convert_units({"INCH": "IN", "METRIC": "MM"}[self.excellon_units])
  3298. except Exception as e:
  3299. log.warning("Units could not be converted: %s" % str(e))
  3300. in_header = False
  3301. # for Allegro type of Excellons we reset name_tool variable so we can reuse it for toolchange
  3302. if allegro_warning is True:
  3303. name_tool = 0
  3304. log.warning("Found end of the header: %s" % eline)
  3305. continue
  3306. ## Alternative units format M71/M72
  3307. # Supposed to be just in the body (yes, the body)
  3308. # but some put it in the header (PADS for example).
  3309. # Will detect anywhere. Occurrence will change the
  3310. # object's units.
  3311. match = self.meas_re.match(eline)
  3312. if match:
  3313. #self.units = {"1": "MM", "2": "IN"}[match.group(1)]
  3314. # Modified for issue #80
  3315. self.convert_units({"1": "MM", "2": "IN"}[match.group(1)])
  3316. log.debug(" Units: %s" % self.units)
  3317. if self.units == 'MM':
  3318. log.warning("Excellon format preset is: %s" % self.excellon_format_upper_mm + \
  3319. ':' + str(self.excellon_format_lower_mm))
  3320. else:
  3321. log.warning("Excellon format preset is: %s" % self.excellon_format_upper_in + \
  3322. ':' + str(self.excellon_format_lower_in))
  3323. continue
  3324. #### Body ####
  3325. if not in_header:
  3326. ## Tool change ##
  3327. match = self.toolsel_re.search(eline)
  3328. if match:
  3329. current_tool = str(int(match.group(1)))
  3330. log.debug("Tool change: %s" % current_tool)
  3331. if bool(headerless):
  3332. match = self.toolset_hl_re.search(eline)
  3333. if match:
  3334. name = str(int(match.group(1)))
  3335. try:
  3336. diam = float(match.group(2))
  3337. except:
  3338. # it's possible that tool definition has only tool number and no diameter info
  3339. # (those could be in another file like PCB Wizard do)
  3340. # then match.group(2) = None and float(None) will create the exception
  3341. # the bellow construction is so each tool will have a slightly different diameter
  3342. # starting with a default value, to allow Excellon editing after that
  3343. self.diameterless = True
  3344. self.app.inform.emit(_("[WARNING] No tool diameter info's. See shell.\n"
  3345. "A tool change event: T%s was found but the Excellon file "
  3346. "have no informations regarding the tool "
  3347. "diameters therefore the application will try to load it by "
  3348. "using some 'fake' diameters.\nThe user needs to edit the "
  3349. "resulting Excellon object and change the diameters to "
  3350. "reflect the real diameters.") % current_tool)
  3351. if self.excellon_units == 'MM':
  3352. diam = self.toolless_diam + (int(current_tool) - 1) / 100
  3353. else:
  3354. diam = (self.toolless_diam + (int(current_tool) - 1) / 100) / 25.4
  3355. spec = {
  3356. "C": diam,
  3357. }
  3358. spec['solid_geometry'] = []
  3359. self.tools[name] = spec
  3360. log.debug(" Tool definition out of header: %s %s" % (name, spec))
  3361. continue
  3362. ## Allegro Type Tool change ##
  3363. if allegro_warning is True:
  3364. match = self.absinc_re.search(eline)
  3365. match1 = self.stop_re.search(eline)
  3366. if match or match1:
  3367. name_tool += 1
  3368. current_tool = str(name_tool)
  3369. log.debug(" Tool change for Allegro type of Excellon: %s" % current_tool)
  3370. continue
  3371. ## Slots parsing for drilled slots (contain G85)
  3372. # a Excellon drilled slot line may look like this:
  3373. # X01125Y0022244G85Y0027756
  3374. match = self.slots_re.search(eline)
  3375. if match:
  3376. # signal that there are milling slots operations
  3377. self.defaults['excellon_drills'] = False
  3378. # the slot start coordinates group is to the left of G85 command (group(1) )
  3379. # the slot stop coordinates group is to the right of G85 command (group(2) )
  3380. start_coords_match = match.group(1)
  3381. stop_coords_match = match.group(2)
  3382. # Slot coordinates without period ##
  3383. # get the coordinates for slot start and for slot stop into variables
  3384. start_coords_noperiod = self.coordsnoperiod_re.search(start_coords_match)
  3385. stop_coords_noperiod = self.coordsnoperiod_re.search(stop_coords_match)
  3386. if start_coords_noperiod:
  3387. try:
  3388. slot_start_x = self.parse_number(start_coords_noperiod.group(1))
  3389. slot_current_x = slot_start_x
  3390. except TypeError:
  3391. slot_start_x = slot_current_x
  3392. except:
  3393. return
  3394. try:
  3395. slot_start_y = self.parse_number(start_coords_noperiod.group(2))
  3396. slot_current_y = slot_start_y
  3397. except TypeError:
  3398. slot_start_y = slot_current_y
  3399. except:
  3400. return
  3401. try:
  3402. slot_stop_x = self.parse_number(stop_coords_noperiod.group(1))
  3403. slot_current_x = slot_stop_x
  3404. except TypeError:
  3405. slot_stop_x = slot_current_x
  3406. except:
  3407. return
  3408. try:
  3409. slot_stop_y = self.parse_number(stop_coords_noperiod.group(2))
  3410. slot_current_y = slot_stop_y
  3411. except TypeError:
  3412. slot_stop_y = slot_current_y
  3413. except:
  3414. return
  3415. if (slot_start_x is None or slot_start_y is None or
  3416. slot_stop_x is None or slot_stop_y is None):
  3417. log.error("Slots are missing some or all coordinates.")
  3418. continue
  3419. # we have a slot
  3420. log.debug('Parsed a slot with coordinates: ' + str([slot_start_x,
  3421. slot_start_y, slot_stop_x,
  3422. slot_stop_y]))
  3423. # store current tool diameter as slot diameter
  3424. slot_dia = 0.05
  3425. try:
  3426. slot_dia = float(self.tools[current_tool]['C'])
  3427. except:
  3428. pass
  3429. log.debug(
  3430. 'Milling/Drilling slot with tool %s, diam=%f' % (
  3431. current_tool,
  3432. slot_dia
  3433. )
  3434. )
  3435. self.slots.append(
  3436. {
  3437. 'start': Point(slot_start_x, slot_start_y),
  3438. 'stop': Point(slot_stop_x, slot_stop_y),
  3439. 'tool': current_tool
  3440. }
  3441. )
  3442. continue
  3443. # Slot coordinates with period: Use literally. ##
  3444. # get the coordinates for slot start and for slot stop into variables
  3445. start_coords_period = self.coordsperiod_re.search(start_coords_match)
  3446. stop_coords_period = self.coordsperiod_re.search(stop_coords_match)
  3447. if start_coords_period:
  3448. try:
  3449. slot_start_x = float(start_coords_period.group(1))
  3450. slot_current_x = slot_start_x
  3451. except TypeError:
  3452. slot_start_x = slot_current_x
  3453. except:
  3454. return
  3455. try:
  3456. slot_start_y = float(start_coords_period.group(2))
  3457. slot_current_y = slot_start_y
  3458. except TypeError:
  3459. slot_start_y = slot_current_y
  3460. except:
  3461. return
  3462. try:
  3463. slot_stop_x = float(stop_coords_period.group(1))
  3464. slot_current_x = slot_stop_x
  3465. except TypeError:
  3466. slot_stop_x = slot_current_x
  3467. except:
  3468. return
  3469. try:
  3470. slot_stop_y = float(stop_coords_period.group(2))
  3471. slot_current_y = slot_stop_y
  3472. except TypeError:
  3473. slot_stop_y = slot_current_y
  3474. except:
  3475. return
  3476. if (slot_start_x is None or slot_start_y is None or
  3477. slot_stop_x is None or slot_stop_y is None):
  3478. log.error("Slots are missing some or all coordinates.")
  3479. continue
  3480. # we have a slot
  3481. log.debug('Parsed a slot with coordinates: ' + str([slot_start_x,
  3482. slot_start_y, slot_stop_x, slot_stop_y]))
  3483. # store current tool diameter as slot diameter
  3484. slot_dia = 0.05
  3485. try:
  3486. slot_dia = float(self.tools[current_tool]['C'])
  3487. except:
  3488. pass
  3489. log.debug(
  3490. 'Milling/Drilling slot with tool %s, diam=%f' % (
  3491. current_tool,
  3492. slot_dia
  3493. )
  3494. )
  3495. self.slots.append(
  3496. {
  3497. 'start': Point(slot_start_x, slot_start_y),
  3498. 'stop': Point(slot_stop_x, slot_stop_y),
  3499. 'tool': current_tool
  3500. }
  3501. )
  3502. continue
  3503. ## Coordinates without period ##
  3504. match = self.coordsnoperiod_re.search(eline)
  3505. if match:
  3506. matchr = self.repeat_re.search(eline)
  3507. if matchr:
  3508. repeat = int(matchr.group(1))
  3509. try:
  3510. x = self.parse_number(match.group(1))
  3511. repeating_x = current_x
  3512. current_x = x
  3513. except TypeError:
  3514. x = current_x
  3515. repeating_x = 0
  3516. except:
  3517. return
  3518. try:
  3519. y = self.parse_number(match.group(2))
  3520. repeating_y = current_y
  3521. current_y = y
  3522. except TypeError:
  3523. y = current_y
  3524. repeating_y = 0
  3525. except:
  3526. return
  3527. if x is None or y is None:
  3528. log.error("Missing coordinates")
  3529. continue
  3530. ## Excellon Routing parse
  3531. if len(re.findall("G00", eline)) > 0:
  3532. self.match_routing_start = 'G00'
  3533. # signal that there are milling slots operations
  3534. self.defaults['excellon_drills'] = False
  3535. self.routing_flag = 0
  3536. slot_start_x = x
  3537. slot_start_y = y
  3538. continue
  3539. if self.routing_flag == 0:
  3540. if len(re.findall("G01", eline)) > 0:
  3541. self.match_routing_stop = 'G01'
  3542. # signal that there are milling slots operations
  3543. self.defaults['excellon_drills'] = False
  3544. self.routing_flag = 1
  3545. slot_stop_x = x
  3546. slot_stop_y = y
  3547. self.slots.append(
  3548. {
  3549. 'start': Point(slot_start_x, slot_start_y),
  3550. 'stop': Point(slot_stop_x, slot_stop_y),
  3551. 'tool': current_tool
  3552. }
  3553. )
  3554. continue
  3555. if self.match_routing_start is None and self.match_routing_stop is None:
  3556. if repeat == 0:
  3557. # signal that there are drill operations
  3558. self.defaults['excellon_drills'] = True
  3559. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  3560. else:
  3561. coordx = x
  3562. coordy = y
  3563. while repeat > 0:
  3564. if repeating_x:
  3565. coordx = (repeat * x) + repeating_x
  3566. if repeating_y:
  3567. coordy = (repeat * y) + repeating_y
  3568. self.drills.append({'point': Point((coordx, coordy)), 'tool': current_tool})
  3569. repeat -= 1
  3570. repeating_x = repeating_y = 0
  3571. # log.debug("{:15} {:8} {:8}".format(eline, x, y))
  3572. continue
  3573. ## Coordinates with period: Use literally. ##
  3574. match = self.coordsperiod_re.search(eline)
  3575. if match:
  3576. matchr = self.repeat_re.search(eline)
  3577. if matchr:
  3578. repeat = int(matchr.group(1))
  3579. if match:
  3580. # signal that there are drill operations
  3581. self.defaults['excellon_drills'] = True
  3582. try:
  3583. x = float(match.group(1))
  3584. repeating_x = current_x
  3585. current_x = x
  3586. except TypeError:
  3587. x = current_x
  3588. repeating_x = 0
  3589. try:
  3590. y = float(match.group(2))
  3591. repeating_y = current_y
  3592. current_y = y
  3593. except TypeError:
  3594. y = current_y
  3595. repeating_y = 0
  3596. if x is None or y is None:
  3597. log.error("Missing coordinates")
  3598. continue
  3599. ## Excellon Routing parse
  3600. if len(re.findall("G00", eline)) > 0:
  3601. self.match_routing_start = 'G00'
  3602. # signal that there are milling slots operations
  3603. self.defaults['excellon_drills'] = False
  3604. self.routing_flag = 0
  3605. slot_start_x = x
  3606. slot_start_y = y
  3607. continue
  3608. if self.routing_flag == 0:
  3609. if len(re.findall("G01", eline)) > 0:
  3610. self.match_routing_stop = 'G01'
  3611. # signal that there are milling slots operations
  3612. self.defaults['excellon_drills'] = False
  3613. self.routing_flag = 1
  3614. slot_stop_x = x
  3615. slot_stop_y = y
  3616. self.slots.append(
  3617. {
  3618. 'start': Point(slot_start_x, slot_start_y),
  3619. 'stop': Point(slot_stop_x, slot_stop_y),
  3620. 'tool': current_tool
  3621. }
  3622. )
  3623. continue
  3624. if self.match_routing_start is None and self.match_routing_stop is None:
  3625. # signal that there are drill operations
  3626. if repeat == 0:
  3627. # signal that there are drill operations
  3628. self.defaults['excellon_drills'] = True
  3629. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  3630. else:
  3631. coordx = x
  3632. coordy = y
  3633. while repeat > 0:
  3634. if repeating_x:
  3635. coordx = (repeat * x) + repeating_x
  3636. if repeating_y:
  3637. coordy = (repeat * y) + repeating_y
  3638. self.drills.append({'point': Point((coordx, coordy)), 'tool': current_tool})
  3639. repeat -= 1
  3640. repeating_x = repeating_y = 0
  3641. # log.debug("{:15} {:8} {:8}".format(eline, x, y))
  3642. continue
  3643. #### Header ####
  3644. if in_header:
  3645. ## Tool definitions ##
  3646. match = self.toolset_re.search(eline)
  3647. if match:
  3648. name = str(int(match.group(1)))
  3649. spec = {
  3650. "C": float(match.group(2)),
  3651. # "F": float(match.group(3)),
  3652. # "S": float(match.group(4)),
  3653. # "B": float(match.group(5)),
  3654. # "H": float(match.group(6)),
  3655. # "Z": float(match.group(7))
  3656. }
  3657. spec['solid_geometry'] = []
  3658. self.tools[name] = spec
  3659. log.debug(" Tool definition: %s %s" % (name, spec))
  3660. continue
  3661. ## Units and number format ##
  3662. match = self.units_re.match(eline)
  3663. if match:
  3664. self.units_found = match.group(1)
  3665. self.zeros = match.group(2) # "T" or "L". Might be empty
  3666. self.excellon_format = match.group(3)
  3667. if self.excellon_format:
  3668. upper = len(self.excellon_format.partition('.')[0])
  3669. lower = len(self.excellon_format.partition('.')[2])
  3670. if self.units == 'MM':
  3671. self.excellon_format_upper_mm = upper
  3672. self.excellon_format_lower_mm = lower
  3673. else:
  3674. self.excellon_format_upper_in = upper
  3675. self.excellon_format_lower_in = lower
  3676. # Modified for issue #80
  3677. self.convert_units({"INCH": "IN", "METRIC": "MM"}[self.units_found])
  3678. # log.warning(" Units/Format: %s %s" % (self.units, self.zeros))
  3679. log.warning("Units: %s" % self.units)
  3680. if self.units == 'MM':
  3681. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_mm) +
  3682. ':' + str(self.excellon_format_lower_mm))
  3683. else:
  3684. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_in) +
  3685. ':' + str(self.excellon_format_lower_in))
  3686. log.warning("Type of zeros found inline: %s" % self.zeros)
  3687. continue
  3688. # Search for units type again it might be alone on the line
  3689. if "INCH" in eline:
  3690. line_units = "INCH"
  3691. # Modified for issue #80
  3692. self.convert_units({"INCH": "IN", "METRIC": "MM"}[line_units])
  3693. log.warning("Type of UNITS found inline: %s" % line_units)
  3694. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_in) +
  3695. ':' + str(self.excellon_format_lower_in))
  3696. # TODO: not working
  3697. #FlatCAMApp.App.inform.emit("Detected INLINE: %s" % str(eline))
  3698. continue
  3699. elif "METRIC" in eline:
  3700. line_units = "METRIC"
  3701. # Modified for issue #80
  3702. self.convert_units({"INCH": "IN", "METRIC": "MM"}[line_units])
  3703. log.warning("Type of UNITS found inline: %s" % line_units)
  3704. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_mm) +
  3705. ':' + str(self.excellon_format_lower_mm))
  3706. # TODO: not working
  3707. #FlatCAMApp.App.inform.emit("Detected INLINE: %s" % str(eline))
  3708. continue
  3709. # Search for zeros type again because it might be alone on the line
  3710. match = re.search(r'[LT]Z',eline)
  3711. if match:
  3712. self.zeros = match.group()
  3713. log.warning("Type of zeros found: %s" % self.zeros)
  3714. continue
  3715. ## Units and number format outside header##
  3716. match = self.units_re.match(eline)
  3717. if match:
  3718. self.units_found = match.group(1)
  3719. self.zeros = match.group(2) # "T" or "L". Might be empty
  3720. self.excellon_format = match.group(3)
  3721. if self.excellon_format:
  3722. upper = len(self.excellon_format.partition('.')[0])
  3723. lower = len(self.excellon_format.partition('.')[2])
  3724. if self.units == 'MM':
  3725. self.excellon_format_upper_mm = upper
  3726. self.excellon_format_lower_mm = lower
  3727. else:
  3728. self.excellon_format_upper_in = upper
  3729. self.excellon_format_lower_in = lower
  3730. # Modified for issue #80
  3731. self.convert_units({"INCH": "IN", "METRIC": "MM"}[self.units_found])
  3732. # log.warning(" Units/Format: %s %s" % (self.units, self.zeros))
  3733. log.warning("Units: %s" % self.units)
  3734. if self.units == 'MM':
  3735. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_mm) +
  3736. ':' + str(self.excellon_format_lower_mm))
  3737. else:
  3738. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_in) +
  3739. ':' + str(self.excellon_format_lower_in))
  3740. log.warning("Type of zeros found outside header, inline: %s" % self.zeros)
  3741. log.warning("UNITS found outside header")
  3742. continue
  3743. log.warning("Line ignored: %s" % eline)
  3744. # make sure that since we are in headerless mode, we convert the tools only after the file parsing
  3745. # is finished since the tools definitions are spread in the Excellon body. We use as units the value
  3746. # from self.defaults['excellon_units']
  3747. log.info("Zeros: %s, Units %s." % (self.zeros, self.units))
  3748. except Exception as e:
  3749. log.error("Excellon PARSING FAILED. Line %d: %s" % (line_num, eline))
  3750. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  3751. msg += _('[ERROR] Excellon Parser error.\nParsing Failed. Line {l_nr}: {line}\n').format(l_nr=line_num, line=eline)
  3752. msg += traceback.format_exc()
  3753. self.app.inform.emit(msg)
  3754. return "fail"
  3755. def parse_number(self, number_str):
  3756. """
  3757. Parses coordinate numbers without period.
  3758. :param number_str: String representing the numerical value.
  3759. :type number_str: str
  3760. :return: Floating point representation of the number
  3761. :rtype: float
  3762. """
  3763. match = self.leadingzeros_re.search(number_str)
  3764. nr_length = len(match.group(1)) + len(match.group(2))
  3765. try:
  3766. if self.zeros == "L" or self.zeros == "LZ":
  3767. # With leading zeros, when you type in a coordinate,
  3768. # the leading zeros must always be included. Trailing zeros
  3769. # are unneeded and may be left off. The CNC-7 will automatically add them.
  3770. # r'^[-\+]?(0*)(\d*)'
  3771. # 6 digits are divided by 10^4
  3772. # If less than size digits, they are automatically added,
  3773. # 5 digits then are divided by 10^3 and so on.
  3774. if self.units.lower() == "in":
  3775. result = float(number_str) / (10 ** (float(nr_length) - float(self.excellon_format_upper_in)))
  3776. else:
  3777. result = float(number_str) / (10 ** (float(nr_length) - float(self.excellon_format_upper_mm)))
  3778. return result
  3779. else: # Trailing
  3780. # You must show all zeros to the right of the number and can omit
  3781. # all zeros to the left of the number. The CNC-7 will count the number
  3782. # of digits you typed and automatically fill in the missing zeros.
  3783. ## flatCAM expects 6digits
  3784. # flatCAM expects the number of digits entered into the defaults
  3785. if self.units.lower() == "in": # Inches is 00.0000
  3786. result = float(number_str) / (10 ** (float(self.excellon_format_lower_in)))
  3787. else: # Metric is 000.000
  3788. result = float(number_str) / (10 ** (float(self.excellon_format_lower_mm)))
  3789. return result
  3790. except Exception as e:
  3791. log.error("Aborted. Operation could not be completed due of %s" % str(e))
  3792. return
  3793. def create_geometry(self):
  3794. """
  3795. Creates circles of the tool diameter at every point
  3796. specified in ``self.drills``. Also creates geometries (polygons)
  3797. for the slots as specified in ``self.slots``
  3798. All the resulting geometry is stored into self.solid_geometry list.
  3799. The list self.solid_geometry has 2 elements: first is a dict with the drills geometry,
  3800. and second element is another similar dict that contain the slots geometry.
  3801. Each dict has as keys the tool diameters and as values lists with Shapely objects, the geometries
  3802. ================ ====================================
  3803. Key Value
  3804. ================ ====================================
  3805. tool_diameter list of (Shapely.Point) Where to drill
  3806. ================ ====================================
  3807. :return: None
  3808. """
  3809. self.solid_geometry = []
  3810. try:
  3811. # clear the solid_geometry in self.tools
  3812. for tool in self.tools:
  3813. self.tools[tool]['solid_geometry'][:] = []
  3814. for drill in self.drills:
  3815. # poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  3816. if drill['tool'] is '':
  3817. self.app.inform.emit(_("[WARNING] Excellon.create_geometry() -> a drill location was skipped "
  3818. "due of not having a tool associated.\n"
  3819. "Check the resulting GCode."))
  3820. log.debug("Excellon.create_geometry() -> a drill location was skipped "
  3821. "due of not having a tool associated")
  3822. continue
  3823. tooldia = self.tools[drill['tool']]['C']
  3824. poly = drill['point'].buffer(tooldia / 2.0, int(int(self.geo_steps_per_circle) / 4))
  3825. # self.solid_geometry.append(poly)
  3826. self.tools[drill['tool']]['solid_geometry'].append(poly)
  3827. for slot in self.slots:
  3828. slot_tooldia = self.tools[slot['tool']]['C']
  3829. start = slot['start']
  3830. stop = slot['stop']
  3831. lines_string = LineString([start, stop])
  3832. poly = lines_string.buffer(slot_tooldia / 2.0, int(int(self.geo_steps_per_circle) / 4))
  3833. # self.solid_geometry.append(poly)
  3834. self.tools[slot['tool']]['solid_geometry'].append(poly)
  3835. except Exception as e:
  3836. log.debug("Excellon geometry creation failed due of ERROR: %s" % str(e))
  3837. return "fail"
  3838. # drill_geometry = {}
  3839. # slot_geometry = {}
  3840. #
  3841. # def insertIntoDataStruct(dia, drill_geo, aDict):
  3842. # if not dia in aDict:
  3843. # aDict[dia] = [drill_geo]
  3844. # else:
  3845. # aDict[dia].append(drill_geo)
  3846. #
  3847. # for tool in self.tools:
  3848. # tooldia = self.tools[tool]['C']
  3849. # for drill in self.drills:
  3850. # if drill['tool'] == tool:
  3851. # poly = drill['point'].buffer(tooldia / 2.0)
  3852. # insertIntoDataStruct(tooldia, poly, drill_geometry)
  3853. #
  3854. # for tool in self.tools:
  3855. # slot_tooldia = self.tools[tool]['C']
  3856. # for slot in self.slots:
  3857. # if slot['tool'] == tool:
  3858. # start = slot['start']
  3859. # stop = slot['stop']
  3860. # lines_string = LineString([start, stop])
  3861. # poly = lines_string.buffer(slot_tooldia/2.0, self.geo_steps_per_circle)
  3862. # insertIntoDataStruct(slot_tooldia, poly, drill_geometry)
  3863. #
  3864. # self.solid_geometry = [drill_geometry, slot_geometry]
  3865. def bounds(self):
  3866. """
  3867. Returns coordinates of rectangular bounds
  3868. of Gerber geometry: (xmin, ymin, xmax, ymax).
  3869. """
  3870. # fixed issue of getting bounds only for one level lists of objects
  3871. # now it can get bounds for nested lists of objects
  3872. log.debug("Excellon() -> bounds()")
  3873. # if self.solid_geometry is None:
  3874. # log.debug("solid_geometry is None")
  3875. # return 0, 0, 0, 0
  3876. def bounds_rec(obj):
  3877. if type(obj) is list:
  3878. minx = Inf
  3879. miny = Inf
  3880. maxx = -Inf
  3881. maxy = -Inf
  3882. for k in obj:
  3883. if type(k) is dict:
  3884. for key in k:
  3885. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  3886. minx = min(minx, minx_)
  3887. miny = min(miny, miny_)
  3888. maxx = max(maxx, maxx_)
  3889. maxy = max(maxy, maxy_)
  3890. else:
  3891. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3892. minx = min(minx, minx_)
  3893. miny = min(miny, miny_)
  3894. maxx = max(maxx, maxx_)
  3895. maxy = max(maxy, maxy_)
  3896. return minx, miny, maxx, maxy
  3897. else:
  3898. # it's a Shapely object, return it's bounds
  3899. return obj.bounds
  3900. minx_list = []
  3901. miny_list = []
  3902. maxx_list = []
  3903. maxy_list = []
  3904. for tool in self.tools:
  3905. minx, miny, maxx, maxy = bounds_rec(self.tools[tool]['solid_geometry'])
  3906. minx_list.append(minx)
  3907. miny_list.append(miny)
  3908. maxx_list.append(maxx)
  3909. maxy_list.append(maxy)
  3910. return (min(minx_list), min(miny_list), max(maxx_list), max(maxy_list))
  3911. def convert_units(self, units):
  3912. """
  3913. This function first convert to the the units found in the Excellon file but it converts tools that
  3914. are not there yet so it has no effect other than it signal that the units are the ones in the file.
  3915. On object creation, in new_object(), true conversion is done because this is done at the end of the
  3916. Excellon file parsing, the tools are inside and self.tools is really converted from the units found
  3917. inside the file to the FlatCAM units.
  3918. Kind of convolute way to make the conversion and it is based on the assumption that the Excellon file
  3919. will have detected the units before the tools are parsed and stored in self.tools
  3920. :param units:
  3921. :type str: IN or MM
  3922. :return:
  3923. """
  3924. factor = Geometry.convert_units(self, units)
  3925. # Tools
  3926. for tname in self.tools:
  3927. self.tools[tname]["C"] *= factor
  3928. self.create_geometry()
  3929. return factor
  3930. def scale(self, xfactor, yfactor=None, point=None):
  3931. """
  3932. Scales geometry on the XY plane in the object by a given factor.
  3933. Tool sizes, feedrates an Z-plane dimensions are untouched.
  3934. :param factor: Number by which to scale the object.
  3935. :type factor: float
  3936. :return: None
  3937. :rtype: NOne
  3938. """
  3939. if yfactor is None:
  3940. yfactor = xfactor
  3941. if point is None:
  3942. px = 0
  3943. py = 0
  3944. else:
  3945. px, py = point
  3946. def scale_geom(obj):
  3947. if type(obj) is list:
  3948. new_obj = []
  3949. for g in obj:
  3950. new_obj.append(scale_geom(g))
  3951. return new_obj
  3952. else:
  3953. return affinity.scale(obj, xfactor,
  3954. yfactor, origin=(px, py))
  3955. # Drills
  3956. for drill in self.drills:
  3957. drill['point'] = affinity.scale(drill['point'], xfactor, yfactor, origin=(px, py))
  3958. # scale solid_geometry
  3959. for tool in self.tools:
  3960. self.tools[tool]['solid_geometry'] = scale_geom(self.tools[tool]['solid_geometry'])
  3961. # Slots
  3962. for slot in self.slots:
  3963. slot['stop'] = affinity.scale(slot['stop'], xfactor, yfactor, origin=(px, py))
  3964. slot['start'] = affinity.scale(slot['start'], xfactor, yfactor, origin=(px, py))
  3965. self.create_geometry()
  3966. def offset(self, vect):
  3967. """
  3968. Offsets geometry on the XY plane in the object by a given vector.
  3969. :param vect: (x, y) offset vector.
  3970. :type vect: tuple
  3971. :return: None
  3972. """
  3973. dx, dy = vect
  3974. def offset_geom(obj):
  3975. if type(obj) is list:
  3976. new_obj = []
  3977. for g in obj:
  3978. new_obj.append(offset_geom(g))
  3979. return new_obj
  3980. else:
  3981. return affinity.translate(obj, xoff=dx, yoff=dy)
  3982. # Drills
  3983. for drill in self.drills:
  3984. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  3985. # offset solid_geometry
  3986. for tool in self.tools:
  3987. self.tools[tool]['solid_geometry'] = offset_geom(self.tools[tool]['solid_geometry'])
  3988. # Slots
  3989. for slot in self.slots:
  3990. slot['stop'] = affinity.translate(slot['stop'], xoff=dx, yoff=dy)
  3991. slot['start'] = affinity.translate(slot['start'],xoff=dx, yoff=dy)
  3992. # Recreate geometry
  3993. self.create_geometry()
  3994. def mirror(self, axis, point):
  3995. """
  3996. :param axis: "X" or "Y" indicates around which axis to mirror.
  3997. :type axis: str
  3998. :param point: [x, y] point belonging to the mirror axis.
  3999. :type point: list
  4000. :return: None
  4001. """
  4002. px, py = point
  4003. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  4004. def mirror_geom(obj):
  4005. if type(obj) is list:
  4006. new_obj = []
  4007. for g in obj:
  4008. new_obj.append(mirror_geom(g))
  4009. return new_obj
  4010. else:
  4011. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  4012. # Modify data
  4013. # Drills
  4014. for drill in self.drills:
  4015. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  4016. # mirror solid_geometry
  4017. for tool in self.tools:
  4018. self.tools[tool]['solid_geometry'] = mirror_geom(self.tools[tool]['solid_geometry'])
  4019. # Slots
  4020. for slot in self.slots:
  4021. slot['stop'] = affinity.scale(slot['stop'], xscale, yscale, origin=(px, py))
  4022. slot['start'] = affinity.scale(slot['start'], xscale, yscale, origin=(px, py))
  4023. # Recreate geometry
  4024. self.create_geometry()
  4025. def skew(self, angle_x=None, angle_y=None, point=None):
  4026. """
  4027. Shear/Skew the geometries of an object by angles along x and y dimensions.
  4028. Tool sizes, feedrates an Z-plane dimensions are untouched.
  4029. Parameters
  4030. ----------
  4031. xs, ys : float, float
  4032. The shear angle(s) for the x and y axes respectively. These can be
  4033. specified in either degrees (default) or radians by setting
  4034. use_radians=True.
  4035. See shapely manual for more information:
  4036. http://toblerity.org/shapely/manual.html#affine-transformations
  4037. """
  4038. if angle_x is None:
  4039. angle_x = 0.0
  4040. if angle_y is None:
  4041. angle_y = 0.0
  4042. def skew_geom(obj):
  4043. if type(obj) is list:
  4044. new_obj = []
  4045. for g in obj:
  4046. new_obj.append(skew_geom(g))
  4047. return new_obj
  4048. else:
  4049. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  4050. if point is None:
  4051. px, py = 0, 0
  4052. # Drills
  4053. for drill in self.drills:
  4054. drill['point'] = affinity.skew(drill['point'], angle_x, angle_y,
  4055. origin=(px, py))
  4056. # skew solid_geometry
  4057. for tool in self.tools:
  4058. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  4059. # Slots
  4060. for slot in self.slots:
  4061. slot['stop'] = affinity.skew(slot['stop'], angle_x, angle_y, origin=(px, py))
  4062. slot['start'] = affinity.skew(slot['start'], angle_x, angle_y, origin=(px, py))
  4063. else:
  4064. px, py = point
  4065. # Drills
  4066. for drill in self.drills:
  4067. drill['point'] = affinity.skew(drill['point'], angle_x, angle_y,
  4068. origin=(px, py))
  4069. # skew solid_geometry
  4070. for tool in self.tools:
  4071. self.tools[tool]['solid_geometry'] = skew_geom( self.tools[tool]['solid_geometry'])
  4072. # Slots
  4073. for slot in self.slots:
  4074. slot['stop'] = affinity.skew(slot['stop'], angle_x, angle_y, origin=(px, py))
  4075. slot['start'] = affinity.skew(slot['start'], angle_x, angle_y, origin=(px, py))
  4076. self.create_geometry()
  4077. def rotate(self, angle, point=None):
  4078. """
  4079. Rotate the geometry of an object by an angle around the 'point' coordinates
  4080. :param angle:
  4081. :param point: tuple of coordinates (x, y)
  4082. :return:
  4083. """
  4084. def rotate_geom(obj, origin=None):
  4085. if type(obj) is list:
  4086. new_obj = []
  4087. for g in obj:
  4088. new_obj.append(rotate_geom(g))
  4089. return new_obj
  4090. else:
  4091. if origin:
  4092. return affinity.rotate(obj, angle, origin=origin)
  4093. else:
  4094. return affinity.rotate(obj, angle, origin=(px, py))
  4095. if point is None:
  4096. # Drills
  4097. for drill in self.drills:
  4098. drill['point'] = affinity.rotate(drill['point'], angle, origin='center')
  4099. # rotate solid_geometry
  4100. for tool in self.tools:
  4101. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'], origin='center')
  4102. # Slots
  4103. for slot in self.slots:
  4104. slot['stop'] = affinity.rotate(slot['stop'], angle, origin='center')
  4105. slot['start'] = affinity.rotate(slot['start'], angle, origin='center')
  4106. else:
  4107. px, py = point
  4108. # Drills
  4109. for drill in self.drills:
  4110. drill['point'] = affinity.rotate(drill['point'], angle, origin=(px, py))
  4111. # rotate solid_geometry
  4112. for tool in self.tools:
  4113. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'])
  4114. # Slots
  4115. for slot in self.slots:
  4116. slot['stop'] = affinity.rotate(slot['stop'], angle, origin=(px, py))
  4117. slot['start'] = affinity.rotate(slot['start'], angle, origin=(px, py))
  4118. self.create_geometry()
  4119. class AttrDict(dict):
  4120. def __init__(self, *args, **kwargs):
  4121. super(AttrDict, self).__init__(*args, **kwargs)
  4122. self.__dict__ = self
  4123. class CNCjob(Geometry):
  4124. """
  4125. Represents work to be done by a CNC machine.
  4126. *ATTRIBUTES*
  4127. * ``gcode_parsed`` (list): Each is a dictionary:
  4128. ===================== =========================================
  4129. Key Value
  4130. ===================== =========================================
  4131. geom (Shapely.LineString) Tool path (XY plane)
  4132. kind (string) "AB", A is "T" (travel) or
  4133. "C" (cut). B is "F" (fast) or "S" (slow).
  4134. ===================== =========================================
  4135. """
  4136. defaults = {
  4137. "global_zdownrate": None,
  4138. "pp_geometry_name":'default',
  4139. "pp_excellon_name":'default',
  4140. "excellon_optimization_type": "B",
  4141. "steps_per_circle": 64
  4142. }
  4143. def __init__(self,
  4144. units="in", kind="generic", tooldia=0.0,
  4145. z_cut=-0.002, z_move=0.1,
  4146. feedrate=3.0, feedrate_z=3.0, feedrate_rapid=3.0, feedrate_probe=3.0,
  4147. pp_geometry_name='default', pp_excellon_name='default',
  4148. depthpercut=0.1,z_pdepth=-0.02,
  4149. spindlespeed=None, dwell=True, dwelltime=1000,
  4150. toolchangez=0.787402, toolchange_xy=[0.0, 0.0],
  4151. endz=2.0,
  4152. segx=None,
  4153. segy=None,
  4154. steps_per_circle=None):
  4155. # Used when parsing G-code arcs
  4156. if steps_per_circle is None:
  4157. steps_per_circle = int(CNCjob.defaults["steps_per_circle"])
  4158. self.steps_per_circle = int(steps_per_circle)
  4159. Geometry.__init__(self, geo_steps_per_circle=int(steps_per_circle))
  4160. self.kind = kind
  4161. self.origin_kind = None
  4162. self.units = units
  4163. self.z_cut = z_cut
  4164. self.tool_offset = {}
  4165. self.z_move = z_move
  4166. self.feedrate = feedrate
  4167. self.z_feedrate = feedrate_z
  4168. self.feedrate_rapid = feedrate_rapid
  4169. self.tooldia = tooldia
  4170. self.z_toolchange = toolchangez
  4171. self.xy_toolchange = toolchange_xy
  4172. self.toolchange_xy_type = None
  4173. self.toolC = tooldia
  4174. self.z_end = endz
  4175. self.z_depthpercut = depthpercut
  4176. self.unitcode = {"IN": "G20", "MM": "G21"}
  4177. self.feedminutecode = "G94"
  4178. self.absolutecode = "G90"
  4179. self.gcode = ""
  4180. self.gcode_parsed = None
  4181. self.pp_geometry_name = pp_geometry_name
  4182. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  4183. self.pp_excellon_name = pp_excellon_name
  4184. self.pp_excellon = self.app.postprocessors[self.pp_excellon_name]
  4185. self.pp_solderpaste_name = None
  4186. # Controls if the move from Z_Toolchange to Z_Move is done fast with G0 or normally with G1
  4187. self.f_plunge = None
  4188. # Controls if the move from Z_Cutto Z_Move is done fast with G0 or G1 until zero and then G0 to Z_move
  4189. self.f_retract = None
  4190. # how much depth the probe can probe before error
  4191. self.z_pdepth = z_pdepth if z_pdepth else None
  4192. # the feedrate(speed) with which the probel travel while probing
  4193. self.feedrate_probe = feedrate_probe if feedrate_probe else None
  4194. self.spindlespeed = spindlespeed
  4195. self.dwell = dwell
  4196. self.dwelltime = dwelltime
  4197. self.segx = float(segx) if segx is not None else 0.0
  4198. self.segy = float(segy) if segy is not None else 0.0
  4199. self.input_geometry_bounds = None
  4200. self.oldx = None
  4201. self.oldy = None
  4202. self.tool = 0.0
  4203. # used for creating drill CCode geometry; will be updated in the generate_from_excellon_by_tool()
  4204. self.exc_drills = None
  4205. self.exc_tools = None
  4206. # search for toolchange parameters in the Toolchange Custom Code
  4207. self.re_toolchange_custom = re.compile(r'(%[a-zA-Z0-9\-_]+%)')
  4208. # search for toolchange code: M6
  4209. self.re_toolchange = re.compile(r'^\s*(M6)$')
  4210. # Attributes to be included in serialization
  4211. # Always append to it because it carries contents
  4212. # from Geometry.
  4213. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'z_toolchange', 'feedrate', 'z_feedrate', 'feedrate_rapid',
  4214. 'tooldia', 'gcode', 'input_geometry_bounds', 'gcode_parsed', 'steps_per_circle',
  4215. 'z_depthpercut', 'spindlespeed', 'dwell', 'dwelltime']
  4216. @property
  4217. def postdata(self):
  4218. return self.__dict__
  4219. def convert_units(self, units):
  4220. factor = Geometry.convert_units(self, units)
  4221. log.debug("CNCjob.convert_units()")
  4222. self.z_cut = float(self.z_cut) * factor
  4223. self.z_move *= factor
  4224. self.feedrate *= factor
  4225. self.z_feedrate *= factor
  4226. self.feedrate_rapid *= factor
  4227. self.tooldia *= factor
  4228. self.z_toolchange *= factor
  4229. self.z_end *= factor
  4230. self.z_depthpercut = float(self.z_depthpercut) * factor
  4231. return factor
  4232. def doformat(self, fun, **kwargs):
  4233. return self.doformat2(fun, **kwargs) + "\n"
  4234. def doformat2(self, fun, **kwargs):
  4235. attributes = AttrDict()
  4236. attributes.update(self.postdata)
  4237. attributes.update(kwargs)
  4238. try:
  4239. returnvalue = fun(attributes)
  4240. return returnvalue
  4241. except Exception as e:
  4242. self.app.log.error('Exception occurred within a postprocessor: ' + traceback.format_exc())
  4243. return ''
  4244. def parse_custom_toolchange_code(self, data):
  4245. text = data
  4246. match_list = self.re_toolchange_custom.findall(text)
  4247. if match_list:
  4248. for match in match_list:
  4249. command = match.strip('%')
  4250. try:
  4251. value = getattr(self, command)
  4252. except AttributeError:
  4253. self.app.inform.emit(_("[ERROR] There is no such parameter: %s") % str(match))
  4254. log.debug("CNCJob.parse_custom_toolchange_code() --> AttributeError ")
  4255. return 'fail'
  4256. text = text.replace(match, str(value))
  4257. return text
  4258. def optimized_travelling_salesman(self, points, start=None):
  4259. """
  4260. As solving the problem in the brute force way is too slow,
  4261. this function implements a simple heuristic: always
  4262. go to the nearest city.
  4263. Even if this algorithm is extremely simple, it works pretty well
  4264. giving a solution only about 25% longer than the optimal one (cit. Wikipedia),
  4265. and runs very fast in O(N^2) time complexity.
  4266. >>> optimized_travelling_salesman([[i,j] for i in range(5) for j in range(5)])
  4267. [[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],
  4268. [2, 3], [2, 4], [3, 4], [3, 3], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
  4269. >>> optimized_travelling_salesman([[0,0],[10,0],[6,0]])
  4270. [[0, 0], [6, 0], [10, 0]]
  4271. """
  4272. if start is None:
  4273. start = points[0]
  4274. must_visit = points
  4275. path = [start]
  4276. # must_visit.remove(start)
  4277. while must_visit:
  4278. nearest = min(must_visit, key=lambda x: distance(path[-1], x))
  4279. path.append(nearest)
  4280. must_visit.remove(nearest)
  4281. return path
  4282. def generate_from_excellon_by_tool(self, exobj, tools="all", drillz = 3.0,
  4283. toolchange=False, toolchangez=0.1, toolchangexy='',
  4284. endz=2.0, startz=None,
  4285. excellon_optimization_type='B'):
  4286. """
  4287. Creates gcode for this object from an Excellon object
  4288. for the specified tools.
  4289. :param exobj: Excellon object to process
  4290. :type exobj: Excellon
  4291. :param tools: Comma separated tool names
  4292. :type: tools: str
  4293. :param drillz: drill Z depth
  4294. :type drillz: float
  4295. :param toolchange: Use tool change sequence between tools.
  4296. :type toolchange: bool
  4297. :param toolchangez: Height at which to perform the tool change.
  4298. :type toolchangez: float
  4299. :param toolchangexy: Toolchange X,Y position
  4300. :type toolchangexy: String containing 2 floats separated by comma
  4301. :param startz: Z position just before starting the job
  4302. :type startz: float
  4303. :param endz: final Z position to move to at the end of the CNC job
  4304. :type endz: float
  4305. :param excellon_optimization_type: Single character that defines which drill re-ordering optimisation algorithm
  4306. is to be used: 'M' for meta-heuristic and 'B' for basic
  4307. :type excellon_optimization_type: string
  4308. :return: None
  4309. :rtype: None
  4310. """
  4311. # create a local copy of the exobj.drills so it can be used for creating drill CCode geometry
  4312. self.exc_drills = deepcopy(exobj.drills)
  4313. self.exc_tools = deepcopy(exobj.tools)
  4314. if drillz > 0:
  4315. self.app.inform.emit(_("[WARNING] The Cut Z parameter has positive value. "
  4316. "It is the depth value to drill into material.\n"
  4317. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4318. "therefore the app will convert the value to negative. "
  4319. "Check the resulting CNC code (Gcode etc)."))
  4320. self.z_cut = -drillz
  4321. elif drillz == 0:
  4322. self.app.inform.emit(_("[WARNING] The Cut Z parameter is zero. "
  4323. "There will be no cut, skipping %s file") % exobj.options['name'])
  4324. return 'fail'
  4325. else:
  4326. self.z_cut = drillz
  4327. self.z_toolchange = toolchangez
  4328. try:
  4329. if toolchangexy == '':
  4330. self.xy_toolchange = None
  4331. else:
  4332. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  4333. if len(self.xy_toolchange) < 2:
  4334. self.app.inform.emit(_("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  4335. "in the format (x, y) \nbut now there is only one value, not two. "))
  4336. return 'fail'
  4337. except Exception as e:
  4338. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> %s" % str(e))
  4339. pass
  4340. self.startz = startz
  4341. self.z_end = endz
  4342. self.pp_excellon = self.app.postprocessors[self.pp_excellon_name]
  4343. p = self.pp_excellon
  4344. log.debug("Creating CNC Job from Excellon...")
  4345. # Tools
  4346. # sort the tools list by the second item in tuple (here we have a dict with diameter of the tool)
  4347. # so we actually are sorting the tools by diameter
  4348. #sorted_tools = sorted(exobj.tools.items(), key=lambda t1: t1['C'])
  4349. sort = []
  4350. for k, v in list(exobj.tools.items()):
  4351. sort.append((k, v.get('C')))
  4352. sorted_tools = sorted(sort,key=lambda t1: t1[1])
  4353. if tools == "all":
  4354. tools = [i[0] for i in sorted_tools] # we get a array of ordered tools
  4355. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  4356. else:
  4357. selected_tools = [x.strip() for x in tools.split(",")] # we strip spaces and also separate the tools by ','
  4358. selected_tools = [t1 for t1 in selected_tools if t1 in selected_tools]
  4359. # Create a sorted list of selected tools from the sorted_tools list
  4360. tools = [i for i, j in sorted_tools for k in selected_tools if i == k]
  4361. log.debug("Tools selected and sorted are: %s" % str(tools))
  4362. # Points (Group by tool)
  4363. points = {}
  4364. for drill in exobj.drills:
  4365. if drill['tool'] in tools:
  4366. try:
  4367. points[drill['tool']].append(drill['point'])
  4368. except KeyError:
  4369. points[drill['tool']] = [drill['point']]
  4370. #log.debug("Found %d drills." % len(points))
  4371. self.gcode = []
  4372. self.f_plunge = self.app.defaults["excellon_f_plunge"]
  4373. self.f_retract = self.app.defaults["excellon_f_retract"]
  4374. # Initialization
  4375. gcode = self.doformat(p.start_code)
  4376. gcode += self.doformat(p.feedrate_code)
  4377. if toolchange is False:
  4378. if self.xy_toolchange is not None:
  4379. gcode += self.doformat(p.lift_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4380. gcode += self.doformat(p.startz_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4381. else:
  4382. gcode += self.doformat(p.lift_code, x=0.0, y=0.0)
  4383. gcode += self.doformat(p.startz_code, x=0.0, y=0.0)
  4384. # Distance callback
  4385. class CreateDistanceCallback(object):
  4386. """Create callback to calculate distances between points."""
  4387. def __init__(self):
  4388. """Initialize distance array."""
  4389. locations = create_data_array()
  4390. size = len(locations)
  4391. self.matrix = {}
  4392. for from_node in range(size):
  4393. self.matrix[from_node] = {}
  4394. for to_node in range(size):
  4395. if from_node == to_node:
  4396. self.matrix[from_node][to_node] = 0
  4397. else:
  4398. x1 = locations[from_node][0]
  4399. y1 = locations[from_node][1]
  4400. x2 = locations[to_node][0]
  4401. y2 = locations[to_node][1]
  4402. self.matrix[from_node][to_node] = distance_euclidian(x1, y1, x2, y2)
  4403. def Distance(self, from_node, to_node):
  4404. return int(self.matrix[from_node][to_node])
  4405. # Create the data.
  4406. def create_data_array():
  4407. locations = []
  4408. for point in points[tool]:
  4409. locations.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  4410. return locations
  4411. if self.xy_toolchange is not None:
  4412. self.oldx = self.xy_toolchange[0]
  4413. self.oldy = self.xy_toolchange[1]
  4414. else:
  4415. self.oldx = 0.0
  4416. self.oldy = 0.0
  4417. measured_distance = 0
  4418. current_platform = platform.architecture()[0]
  4419. if current_platform == '64bit':
  4420. if excellon_optimization_type == 'M':
  4421. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  4422. if exobj.drills:
  4423. for tool in tools:
  4424. self.tool=tool
  4425. self.postdata['toolC'] = exobj.tools[tool]["C"]
  4426. self.tooldia = exobj.tools[tool]["C"]
  4427. ################################################
  4428. # Create the data.
  4429. node_list = []
  4430. locations = create_data_array()
  4431. tsp_size = len(locations)
  4432. num_routes = 1 # The number of routes, which is 1 in the TSP.
  4433. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  4434. depot = 0
  4435. # Create routing model.
  4436. if tsp_size > 0:
  4437. routing = pywrapcp.RoutingModel(tsp_size, num_routes, depot)
  4438. search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()
  4439. search_parameters.local_search_metaheuristic = (
  4440. routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
  4441. # Set search time limit in milliseconds.
  4442. if float(self.app.defaults["excellon_search_time"]) != 0:
  4443. search_parameters.time_limit_ms = int(
  4444. float(self.app.defaults["excellon_search_time"]) * 1000)
  4445. else:
  4446. search_parameters.time_limit_ms = 3000
  4447. # Callback to the distance function. The callback takes two
  4448. # arguments (the from and to node indices) and returns the distance between them.
  4449. dist_between_locations = CreateDistanceCallback()
  4450. dist_callback = dist_between_locations.Distance
  4451. routing.SetArcCostEvaluatorOfAllVehicles(dist_callback)
  4452. # Solve, returns a solution if any.
  4453. assignment = routing.SolveWithParameters(search_parameters)
  4454. if assignment:
  4455. # Solution cost.
  4456. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  4457. # Inspect solution.
  4458. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  4459. route_number = 0
  4460. node = routing.Start(route_number)
  4461. start_node = node
  4462. while not routing.IsEnd(node):
  4463. node_list.append(node)
  4464. node = assignment.Value(routing.NextVar(node))
  4465. else:
  4466. log.warning('No solution found.')
  4467. else:
  4468. log.warning('Specify an instance greater than 0.')
  4469. ################################################
  4470. # Only if tool has points.
  4471. if tool in points:
  4472. # Tool change sequence (optional)
  4473. if toolchange:
  4474. gcode += self.doformat(p.toolchange_code,toolchangexy=(self.oldx, self.oldy))
  4475. gcode += self.doformat(p.spindle_code) # Spindle start
  4476. if self.dwell is True:
  4477. gcode += self.doformat(p.dwell_code) # Dwell time
  4478. else:
  4479. gcode += self.doformat(p.spindle_code)
  4480. if self.dwell is True:
  4481. gcode += self.doformat(p.dwell_code) # Dwell time
  4482. if self.units == 'MM':
  4483. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  4484. else:
  4485. current_tooldia = float('%.3f' % float(exobj.tools[tool]["C"]))
  4486. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  4487. # because the values for Z offset are created in build_ui()
  4488. try:
  4489. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  4490. except KeyError:
  4491. z_offset = 0
  4492. self.z_cut += z_offset
  4493. # Drillling!
  4494. for k in node_list:
  4495. locx = locations[k][0]
  4496. locy = locations[k][1]
  4497. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  4498. gcode += self.doformat(p.down_code, x=locx, y=locy)
  4499. if self.f_retract is False:
  4500. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  4501. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  4502. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  4503. self.oldx = locx
  4504. self.oldy = locy
  4505. else:
  4506. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  4507. "The loaded Excellon file has no drills ...")
  4508. self.app.inform.emit(_('[ERROR_NOTCL] The loaded Excellon file has no drills ...'))
  4509. return 'fail'
  4510. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  4511. elif excellon_optimization_type == 'B':
  4512. log.debug("Using OR-Tools Basic drill path optimization.")
  4513. if exobj.drills:
  4514. for tool in tools:
  4515. self.tool=tool
  4516. self.postdata['toolC']=exobj.tools[tool]["C"]
  4517. self.tooldia = exobj.tools[tool]["C"]
  4518. ################################################
  4519. node_list = []
  4520. locations = create_data_array()
  4521. tsp_size = len(locations)
  4522. num_routes = 1 # The number of routes, which is 1 in the TSP.
  4523. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  4524. depot = 0
  4525. # Create routing model.
  4526. if tsp_size > 0:
  4527. routing = pywrapcp.RoutingModel(tsp_size, num_routes, depot)
  4528. search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()
  4529. # Callback to the distance function. The callback takes two
  4530. # arguments (the from and to node indices) and returns the distance between them.
  4531. dist_between_locations = CreateDistanceCallback()
  4532. dist_callback = dist_between_locations.Distance
  4533. routing.SetArcCostEvaluatorOfAllVehicles(dist_callback)
  4534. # Solve, returns a solution if any.
  4535. assignment = routing.SolveWithParameters(search_parameters)
  4536. if assignment:
  4537. # Solution cost.
  4538. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  4539. # Inspect solution.
  4540. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  4541. route_number = 0
  4542. node = routing.Start(route_number)
  4543. start_node = node
  4544. while not routing.IsEnd(node):
  4545. node_list.append(node)
  4546. node = assignment.Value(routing.NextVar(node))
  4547. else:
  4548. log.warning('No solution found.')
  4549. else:
  4550. log.warning('Specify an instance greater than 0.')
  4551. ################################################
  4552. # Only if tool has points.
  4553. if tool in points:
  4554. # Tool change sequence (optional)
  4555. if toolchange:
  4556. gcode += self.doformat(p.toolchange_code,toolchangexy=(self.oldx, self.oldy))
  4557. gcode += self.doformat(p.spindle_code) # Spindle start)
  4558. if self.dwell is True:
  4559. gcode += self.doformat(p.dwell_code) # Dwell time
  4560. else:
  4561. gcode += self.doformat(p.spindle_code)
  4562. if self.dwell is True:
  4563. gcode += self.doformat(p.dwell_code) # Dwell time
  4564. if self.units == 'MM':
  4565. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  4566. else:
  4567. current_tooldia = float('%.3f' % float(exobj.tools[tool]["C"]))
  4568. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  4569. # because the values for Z offset are created in build_ui()
  4570. try:
  4571. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  4572. except KeyError:
  4573. z_offset = 0
  4574. self.z_cut += z_offset
  4575. # Drillling!
  4576. for k in node_list:
  4577. locx = locations[k][0]
  4578. locy = locations[k][1]
  4579. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  4580. gcode += self.doformat(p.down_code, x=locx, y=locy)
  4581. if self.f_retract is False:
  4582. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  4583. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  4584. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  4585. self.oldx = locx
  4586. self.oldy = locy
  4587. else:
  4588. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  4589. "The loaded Excellon file has no drills ...")
  4590. self.app.inform.emit(_('[ERROR_NOTCL] The loaded Excellon file has no drills ...'))
  4591. return 'fail'
  4592. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  4593. else:
  4594. self.app.inform.emit(_("[ERROR_NOTCL] Wrong optimization type selected."))
  4595. return 'fail'
  4596. else:
  4597. log.debug("Using Travelling Salesman drill path optimization.")
  4598. for tool in tools:
  4599. if exobj.drills:
  4600. self.tool = tool
  4601. self.postdata['toolC'] = exobj.tools[tool]["C"]
  4602. self.tooldia = exobj.tools[tool]["C"]
  4603. # Only if tool has points.
  4604. if tool in points:
  4605. # Tool change sequence (optional)
  4606. if toolchange:
  4607. gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  4608. gcode += self.doformat(p.spindle_code) # Spindle start)
  4609. if self.dwell is True:
  4610. gcode += self.doformat(p.dwell_code) # Dwell time
  4611. else:
  4612. gcode += self.doformat(p.spindle_code)
  4613. if self.dwell is True:
  4614. gcode += self.doformat(p.dwell_code) # Dwell time
  4615. if self.units == 'MM':
  4616. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  4617. else:
  4618. current_tooldia = float('%.3f' % float(exobj.tools[tool]["C"]))
  4619. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  4620. # because the values for Z offset are created in build_ui()
  4621. try:
  4622. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  4623. except KeyError:
  4624. z_offset = 0
  4625. self.z_cut += z_offset
  4626. # Drillling!
  4627. altPoints = []
  4628. for point in points[tool]:
  4629. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  4630. for point in self.optimized_travelling_salesman(altPoints):
  4631. gcode += self.doformat(p.rapid_code, x=point[0], y=point[1])
  4632. gcode += self.doformat(p.down_code, x=point[0], y=point[1])
  4633. if self.f_retract is False:
  4634. gcode += self.doformat(p.up_to_zero_code, x=point[0], y=point[1])
  4635. gcode += self.doformat(p.lift_code, x=point[0], y=point[1])
  4636. measured_distance += abs(distance_euclidian(point[0], point[1], self.oldx, self.oldy))
  4637. self.oldx = point[0]
  4638. self.oldy = point[1]
  4639. else:
  4640. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  4641. "The loaded Excellon file has no drills ...")
  4642. self.app.inform.emit(_('[ERROR_NOTCL] The loaded Excellon file has no drills ...'))
  4643. return 'fail'
  4644. log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  4645. gcode += self.doformat(p.spindle_stop_code) # Spindle stop
  4646. gcode += self.doformat(p.end_code, x=0, y=0)
  4647. measured_distance += abs(distance_euclidian(self.oldx, self.oldy, 0, 0))
  4648. log.debug("The total travel distance including travel to end position is: %s" %
  4649. str(measured_distance) + '\n')
  4650. self.travel_distance = measured_distance
  4651. self.gcode = gcode
  4652. return 'OK'
  4653. def generate_from_multitool_geometry(self, geometry, append=True,
  4654. tooldia=None, offset=0.0, tolerance=0, z_cut=1.0, z_move=2.0,
  4655. feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  4656. spindlespeed=None, dwell=False, dwelltime=1.0,
  4657. multidepth=False, depthpercut=None,
  4658. toolchange=False, toolchangez=1.0, toolchangexy="0.0, 0.0", extracut=False,
  4659. startz=None, endz=2.0, pp_geometry_name=None, tool_no=1):
  4660. """
  4661. Algorithm to generate from multitool Geometry.
  4662. Algorithm description:
  4663. ----------------------
  4664. Uses RTree to find the nearest path to follow.
  4665. :param geometry:
  4666. :param append:
  4667. :param tooldia:
  4668. :param tolerance:
  4669. :param multidepth: If True, use multiple passes to reach
  4670. the desired depth.
  4671. :param depthpercut: Maximum depth in each pass.
  4672. :param extracut: Adds (or not) an extra cut at the end of each path
  4673. overlapping the first point in path to ensure complete copper removal
  4674. :return: GCode - string
  4675. """
  4676. log.debug("Generate_from_multitool_geometry()")
  4677. temp_solid_geometry = []
  4678. if offset != 0.0:
  4679. for it in geometry:
  4680. # if the geometry is a closed shape then create a Polygon out of it
  4681. if isinstance(it, LineString):
  4682. c = it.coords
  4683. if c[0] == c[-1]:
  4684. it = Polygon(it)
  4685. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  4686. else:
  4687. temp_solid_geometry = geometry
  4688. ## Flatten the geometry. Only linear elements (no polygons) remain.
  4689. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  4690. log.debug("%d paths" % len(flat_geometry))
  4691. self.tooldia = float(tooldia) if tooldia else None
  4692. self.z_cut = float(z_cut) if z_cut else None
  4693. self.z_move = float(z_move) if z_move else None
  4694. self.feedrate = float(feedrate) if feedrate else None
  4695. self.z_feedrate = float(feedrate_z) if feedrate_z else None
  4696. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else None
  4697. self.spindlespeed = int(spindlespeed) if spindlespeed else None
  4698. self.dwell = dwell
  4699. self.dwelltime = float(dwelltime) if dwelltime else None
  4700. self.startz = float(startz) if startz else None
  4701. self.z_end = float(endz) if endz else None
  4702. self.z_depthpercut = float(depthpercut) if depthpercut else None
  4703. self.multidepth = multidepth
  4704. self.z_toolchange = float(toolchangez) if toolchangez else None
  4705. # it servers in the postprocessor file
  4706. self.tool = tool_no
  4707. try:
  4708. if toolchangexy == '':
  4709. self.xy_toolchange = None
  4710. else:
  4711. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  4712. if len(self.xy_toolchange) < 2:
  4713. self.app.inform.emit(_("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  4714. "in the format (x, y) \nbut now there is only one value, not two. "))
  4715. return 'fail'
  4716. except Exception as e:
  4717. log.debug("camlib.CNCJob.generate_from_multitool_geometry() --> %s" % str(e))
  4718. pass
  4719. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  4720. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4721. if self.z_cut is None:
  4722. self.app.inform.emit(_("[ERROR_NOTCL] Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4723. "other parameters."))
  4724. return 'fail'
  4725. if self.z_cut > 0:
  4726. self.app.inform.emit(_("[WARNING] The Cut Z parameter has positive value. "
  4727. "It is the depth value to cut into material.\n"
  4728. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4729. "therefore the app will convert the value to negative."
  4730. "Check the resulting CNC code (Gcode etc)."))
  4731. self.z_cut = -self.z_cut
  4732. elif self.z_cut == 0:
  4733. self.app.inform.emit(_("[WARNING] The Cut Z parameter is zero. "
  4734. "There will be no cut, skipping %s file") % self.options['name'])
  4735. return 'fail'
  4736. if self.z_move is None:
  4737. self.app.inform.emit(_("[ERROR_NOTCL] Travel Z parameter is None or zero."))
  4738. return 'fail'
  4739. if self.z_move < 0:
  4740. self.app.inform.emit(_("[WARNING] The Travel Z parameter has negative value. "
  4741. "It is the height value to travel between cuts.\n"
  4742. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4743. "therefore the app will convert the value to positive."
  4744. "Check the resulting CNC code (Gcode etc)."))
  4745. self.z_move = -self.z_move
  4746. elif self.z_move == 0:
  4747. self.app.inform.emit(_("[WARNING] The Z Travel parameter is zero. "
  4748. "This is dangerous, skipping %s file") % self.options['name'])
  4749. return 'fail'
  4750. ## Index first and last points in paths
  4751. # What points to index.
  4752. def get_pts(o):
  4753. return [o.coords[0], o.coords[-1]]
  4754. # Create the indexed storage.
  4755. storage = FlatCAMRTreeStorage()
  4756. storage.get_points = get_pts
  4757. # Store the geometry
  4758. log.debug("Indexing geometry before generating G-Code...")
  4759. for shape in flat_geometry:
  4760. if shape is not None: # TODO: This shouldn't have happened.
  4761. storage.insert(shape)
  4762. # self.input_geometry_bounds = geometry.bounds()
  4763. if not append:
  4764. self.gcode = ""
  4765. # tell postprocessor the number of tool (for toolchange)
  4766. self.tool = tool_no
  4767. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  4768. # given under the name 'toolC'
  4769. self.postdata['toolC'] = self.tooldia
  4770. # Initial G-Code
  4771. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  4772. p = self.pp_geometry
  4773. self.gcode = self.doformat(p.start_code)
  4774. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4775. if toolchange is False:
  4776. self.gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  4777. self.gcode += self.doformat(p.startz_code, x=0, y=0)
  4778. if toolchange:
  4779. # if "line_xyz" in self.pp_geometry_name:
  4780. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4781. # else:
  4782. # self.gcode += self.doformat(p.toolchange_code)
  4783. self.gcode += self.doformat(p.toolchange_code)
  4784. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4785. if self.dwell is True:
  4786. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4787. else:
  4788. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4789. if self.dwell is True:
  4790. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4791. ## Iterate over geometry paths getting the nearest each time.
  4792. log.debug("Starting G-Code...")
  4793. path_count = 0
  4794. current_pt = (0, 0)
  4795. pt, geo = storage.nearest(current_pt)
  4796. try:
  4797. while True:
  4798. path_count += 1
  4799. # Remove before modifying, otherwise deletion will fail.
  4800. storage.remove(geo)
  4801. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4802. # then reverse coordinates.
  4803. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4804. geo.coords = list(geo.coords)[::-1]
  4805. #---------- Single depth/pass --------
  4806. if not multidepth:
  4807. self.gcode += self.create_gcode_single_pass(geo, extracut, tolerance)
  4808. #--------- Multi-pass ---------
  4809. else:
  4810. self.gcode += self.create_gcode_multi_pass(geo, extracut, tolerance,
  4811. postproc=p, current_point=current_pt)
  4812. current_pt = geo.coords[-1]
  4813. pt, geo = storage.nearest(current_pt) # Next
  4814. except StopIteration: # Nothing found in storage.
  4815. pass
  4816. log.debug("Finishing G-Code... %s paths traced." % path_count)
  4817. # Finish
  4818. self.gcode += self.doformat(p.spindle_stop_code)
  4819. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4820. self.gcode += self.doformat(p.end_code, x=0, y=0)
  4821. return self.gcode
  4822. def generate_from_geometry_2(self, geometry, append=True,
  4823. tooldia=None, offset=0.0, tolerance=0,
  4824. z_cut=1.0, z_move=2.0,
  4825. feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  4826. spindlespeed=None, dwell=False, dwelltime=1.0,
  4827. multidepth=False, depthpercut=None,
  4828. toolchange=False, toolchangez=1.0, toolchangexy="0.0, 0.0",
  4829. extracut=False, startz=None, endz=2.0,
  4830. pp_geometry_name=None, tool_no=1):
  4831. """
  4832. Second algorithm to generate from Geometry.
  4833. Algorithm description:
  4834. ----------------------
  4835. Uses RTree to find the nearest path to follow.
  4836. :param geometry:
  4837. :param append:
  4838. :param tooldia:
  4839. :param tolerance:
  4840. :param multidepth: If True, use multiple passes to reach
  4841. the desired depth.
  4842. :param depthpercut: Maximum depth in each pass.
  4843. :param extracut: Adds (or not) an extra cut at the end of each path
  4844. overlapping the first point in path to ensure complete copper removal
  4845. :return: None
  4846. """
  4847. if not isinstance(geometry, Geometry):
  4848. self.app.inform.emit(_("[ERROR]Expected a Geometry, got %s") % type(geometry))
  4849. return 'fail'
  4850. log.debug("Generate_from_geometry_2()")
  4851. # if solid_geometry is empty raise an exception
  4852. if not geometry.solid_geometry:
  4853. self.app.inform.emit(_("[ERROR_NOTCL] Trying to generate a CNC Job "
  4854. "from a Geometry object without solid_geometry."))
  4855. temp_solid_geometry = []
  4856. def bounds_rec(obj):
  4857. if type(obj) is list:
  4858. minx = Inf
  4859. miny = Inf
  4860. maxx = -Inf
  4861. maxy = -Inf
  4862. for k in obj:
  4863. if type(k) is dict:
  4864. for key in k:
  4865. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  4866. minx = min(minx, minx_)
  4867. miny = min(miny, miny_)
  4868. maxx = max(maxx, maxx_)
  4869. maxy = max(maxy, maxy_)
  4870. else:
  4871. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  4872. minx = min(minx, minx_)
  4873. miny = min(miny, miny_)
  4874. maxx = max(maxx, maxx_)
  4875. maxy = max(maxy, maxy_)
  4876. return minx, miny, maxx, maxy
  4877. else:
  4878. # it's a Shapely object, return it's bounds
  4879. return obj.bounds
  4880. if offset != 0.0:
  4881. offset_for_use = offset
  4882. if offset <0:
  4883. a, b, c, d = bounds_rec(geometry.solid_geometry)
  4884. # if the offset is less than half of the total length or less than half of the total width of the
  4885. # solid geometry it's obvious we can't do the offset
  4886. if -offset > ((c - a) / 2) or -offset > ((d - b) / 2):
  4887. self.app.inform.emit(_("[ERROR_NOTCL] The Tool Offset value is too negative to use "
  4888. "for the current_geometry.\n"
  4889. "Raise the value (in module) and try again."))
  4890. return 'fail'
  4891. # hack: make offset smaller by 0.0000000001 which is insignificant difference but allow the job
  4892. # to continue
  4893. elif -offset == ((c - a) / 2) or -offset == ((d - b) / 2):
  4894. offset_for_use = offset - 0.0000000001
  4895. for it in geometry.solid_geometry:
  4896. # if the geometry is a closed shape then create a Polygon out of it
  4897. if isinstance(it, LineString):
  4898. c = it.coords
  4899. if c[0] == c[-1]:
  4900. it = Polygon(it)
  4901. temp_solid_geometry.append(it.buffer(offset_for_use, join_style=2))
  4902. else:
  4903. temp_solid_geometry = geometry.solid_geometry
  4904. ## Flatten the geometry. Only linear elements (no polygons) remain.
  4905. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  4906. log.debug("%d paths" % len(flat_geometry))
  4907. self.tooldia = float(tooldia) if tooldia else None
  4908. self.z_cut = float(z_cut) if z_cut else None
  4909. self.z_move = float(z_move) if z_move else None
  4910. self.feedrate = float(feedrate) if feedrate else None
  4911. self.z_feedrate = float(feedrate_z) if feedrate_z else None
  4912. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else None
  4913. self.spindlespeed = int(spindlespeed) if spindlespeed else None
  4914. self.dwell = dwell
  4915. self.dwelltime = float(dwelltime) if dwelltime else None
  4916. self.startz = float(startz) if startz else None
  4917. self.z_end = float(endz) if endz else None
  4918. self.z_depthpercut = float(depthpercut) if depthpercut else None
  4919. self.multidepth = multidepth
  4920. self.z_toolchange = float(toolchangez) if toolchangez else None
  4921. try:
  4922. if toolchangexy == '':
  4923. self.xy_toolchange = None
  4924. else:
  4925. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  4926. if len(self.xy_toolchange) < 2:
  4927. self.app.inform.emit(_("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  4928. "in the format (x, y) \nbut now there is only one value, not two. "))
  4929. return 'fail'
  4930. except Exception as e:
  4931. log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  4932. pass
  4933. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  4934. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4935. if self.z_cut is None:
  4936. self.app.inform.emit(_("[ERROR_NOTCL] Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4937. "other parameters."))
  4938. return 'fail'
  4939. if self.z_cut > 0:
  4940. self.app.inform.emit(_("[WARNING] The Cut Z parameter has positive value. "
  4941. "It is the depth value to cut into material.\n"
  4942. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4943. "therefore the app will convert the value to negative."
  4944. "Check the resulting CNC code (Gcode etc)."))
  4945. self.z_cut = -self.z_cut
  4946. elif self.z_cut == 0:
  4947. self.app.inform.emit(_("[WARNING] The Cut Z parameter is zero. "
  4948. "There will be no cut, skipping %s file") % geometry.options['name'])
  4949. return 'fail'
  4950. if self.z_move is None:
  4951. self.app.inform.emit(_("[ERROR_NOTCL] Travel Z parameter is None or zero."))
  4952. return 'fail'
  4953. if self.z_move < 0:
  4954. self.app.inform.emit(_("[WARNING] The Travel Z parameter has negative value. "
  4955. "It is the height value to travel between cuts.\n"
  4956. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4957. "therefore the app will convert the value to positive."
  4958. "Check the resulting CNC code (Gcode etc)."))
  4959. self.z_move = -self.z_move
  4960. elif self.z_move == 0:
  4961. self.app.inform.emit(_("[WARNING] The Z Travel parameter is zero. "
  4962. "This is dangerous, skipping %s file") % self.options['name'])
  4963. return 'fail'
  4964. ## Index first and last points in paths
  4965. # What points to index.
  4966. def get_pts(o):
  4967. return [o.coords[0], o.coords[-1]]
  4968. # Create the indexed storage.
  4969. storage = FlatCAMRTreeStorage()
  4970. storage.get_points = get_pts
  4971. # Store the geometry
  4972. log.debug("Indexing geometry before generating G-Code...")
  4973. for shape in flat_geometry:
  4974. if shape is not None: # TODO: This shouldn't have happened.
  4975. storage.insert(shape)
  4976. # self.input_geometry_bounds = geometry.bounds()
  4977. if not append:
  4978. self.gcode = ""
  4979. # tell postprocessor the number of tool (for toolchange)
  4980. self.tool = tool_no
  4981. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  4982. # given under the name 'toolC'
  4983. self.postdata['toolC'] = self.tooldia
  4984. # Initial G-Code
  4985. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  4986. p = self.pp_geometry
  4987. self.oldx = 0.0
  4988. self.oldy = 0.0
  4989. self.gcode = self.doformat(p.start_code)
  4990. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4991. if toolchange is False:
  4992. self.gcode += self.doformat(p.lift_code, x=self.oldx , y=self.oldy ) # Move (up) to travel height
  4993. self.gcode += self.doformat(p.startz_code, x=self.oldx , y=self.oldy )
  4994. if toolchange:
  4995. # if "line_xyz" in self.pp_geometry_name:
  4996. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4997. # else:
  4998. # self.gcode += self.doformat(p.toolchange_code)
  4999. self.gcode += self.doformat(p.toolchange_code)
  5000. self.gcode += self.doformat(p.spindle_code) # Spindle start
  5001. if self.dwell is True:
  5002. self.gcode += self.doformat(p.dwell_code) # Dwell time
  5003. else:
  5004. self.gcode += self.doformat(p.spindle_code) # Spindle start
  5005. if self.dwell is True:
  5006. self.gcode += self.doformat(p.dwell_code) # Dwell time
  5007. ## Iterate over geometry paths getting the nearest each time.
  5008. log.debug("Starting G-Code...")
  5009. path_count = 0
  5010. current_pt = (0, 0)
  5011. pt, geo = storage.nearest(current_pt)
  5012. try:
  5013. while True:
  5014. path_count += 1
  5015. # Remove before modifying, otherwise deletion will fail.
  5016. storage.remove(geo)
  5017. # If last point in geometry is the nearest but prefer the first one if last point == first point
  5018. # then reverse coordinates.
  5019. if pt != geo.coords[0] and pt == geo.coords[-1]:
  5020. geo.coords = list(geo.coords)[::-1]
  5021. #---------- Single depth/pass --------
  5022. if not multidepth:
  5023. self.gcode += self.create_gcode_single_pass(geo, extracut, tolerance)
  5024. #--------- Multi-pass ---------
  5025. else:
  5026. self.gcode += self.create_gcode_multi_pass(geo, extracut, tolerance,
  5027. postproc=p, current_point=current_pt)
  5028. current_pt = geo.coords[-1]
  5029. pt, geo = storage.nearest(current_pt) # Next
  5030. except StopIteration: # Nothing found in storage.
  5031. pass
  5032. log.debug("Finishing G-Code... %s paths traced." % path_count)
  5033. # Finish
  5034. self.gcode += self.doformat(p.spindle_stop_code)
  5035. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  5036. self.gcode += self.doformat(p.end_code, x=0, y=0)
  5037. return self.gcode
  5038. def generate_gcode_from_solderpaste_geo(self, **kwargs):
  5039. """
  5040. Algorithm to generate from multitool Geometry.
  5041. Algorithm description:
  5042. ----------------------
  5043. Uses RTree to find the nearest path to follow.
  5044. :return: Gcode string
  5045. """
  5046. log.debug("Generate_from_solderpaste_geometry()")
  5047. ## Index first and last points in paths
  5048. # What points to index.
  5049. def get_pts(o):
  5050. return [o.coords[0], o.coords[-1]]
  5051. self.gcode = ""
  5052. if not kwargs:
  5053. log.debug("camlib.generate_from_solderpaste_geo() --> No tool in the solderpaste geometry.")
  5054. self.app.inform.emit(_("[ERROR_NOTCL] There is no tool data in the SolderPaste geometry."))
  5055. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  5056. # given under the name 'toolC'
  5057. self.postdata['z_start'] = kwargs['data']['tools_solderpaste_z_start']
  5058. self.postdata['z_dispense'] = kwargs['data']['tools_solderpaste_z_dispense']
  5059. self.postdata['z_stop'] = kwargs['data']['tools_solderpaste_z_stop']
  5060. self.postdata['z_travel'] = kwargs['data']['tools_solderpaste_z_travel']
  5061. self.postdata['z_toolchange'] = kwargs['data']['tools_solderpaste_z_toolchange']
  5062. self.postdata['xy_toolchange'] = kwargs['data']['tools_solderpaste_xy_toolchange']
  5063. self.postdata['frxy'] = kwargs['data']['tools_solderpaste_frxy']
  5064. self.postdata['frz'] = kwargs['data']['tools_solderpaste_frz']
  5065. self.postdata['frz_dispense'] = kwargs['data']['tools_solderpaste_frz_dispense']
  5066. self.postdata['speedfwd'] = kwargs['data']['tools_solderpaste_speedfwd']
  5067. self.postdata['dwellfwd'] = kwargs['data']['tools_solderpaste_dwellfwd']
  5068. self.postdata['speedrev'] = kwargs['data']['tools_solderpaste_speedrev']
  5069. self.postdata['dwellrev'] = kwargs['data']['tools_solderpaste_dwellrev']
  5070. self.postdata['pp_solderpaste_name'] = kwargs['data']['tools_solderpaste_pp']
  5071. self.postdata['toolC'] = kwargs['tooldia']
  5072. self.pp_solderpaste_name = kwargs['data']['tools_solderpaste_pp'] if kwargs['data']['tools_solderpaste_pp'] \
  5073. else self.app.defaults['tools_solderpaste_pp']
  5074. p = self.app.postprocessors[self.pp_solderpaste_name]
  5075. ## Flatten the geometry. Only linear elements (no polygons) remain.
  5076. flat_geometry = self.flatten(kwargs['solid_geometry'], pathonly=True)
  5077. log.debug("%d paths" % len(flat_geometry))
  5078. # Create the indexed storage.
  5079. storage = FlatCAMRTreeStorage()
  5080. storage.get_points = get_pts
  5081. # Store the geometry
  5082. log.debug("Indexing geometry before generating G-Code...")
  5083. for shape in flat_geometry:
  5084. if shape is not None:
  5085. storage.insert(shape)
  5086. # Initial G-Code
  5087. self.gcode = self.doformat(p.start_code)
  5088. self.gcode += self.doformat(p.spindle_off_code)
  5089. self.gcode += self.doformat(p.toolchange_code)
  5090. ## Iterate over geometry paths getting the nearest each time.
  5091. log.debug("Starting SolderPaste G-Code...")
  5092. path_count = 0
  5093. current_pt = (0, 0)
  5094. pt, geo = storage.nearest(current_pt)
  5095. try:
  5096. while True:
  5097. path_count += 1
  5098. # Remove before modifying, otherwise deletion will fail.
  5099. storage.remove(geo)
  5100. # If last point in geometry is the nearest but prefer the first one if last point == first point
  5101. # then reverse coordinates.
  5102. if pt != geo.coords[0] and pt == geo.coords[-1]:
  5103. geo.coords = list(geo.coords)[::-1]
  5104. self.gcode += self.create_soldepaste_gcode(geo, p=p)
  5105. current_pt = geo.coords[-1]
  5106. pt, geo = storage.nearest(current_pt) # Next
  5107. except StopIteration: # Nothing found in storage.
  5108. pass
  5109. log.debug("Finishing SolderPste G-Code... %s paths traced." % path_count)
  5110. # Finish
  5111. self.gcode += self.doformat(p.lift_code)
  5112. self.gcode += self.doformat(p.end_code)
  5113. return self.gcode
  5114. def create_soldepaste_gcode(self, geometry, p):
  5115. gcode = ''
  5116. path = geometry.coords
  5117. if type(geometry) == LineString or type(geometry) == LinearRing:
  5118. # Move fast to 1st point
  5119. gcode += self.doformat(p.rapid_code, x=path[0][0], y=path[0][1]) # Move to first point
  5120. # Move down to cutting depth
  5121. gcode += self.doformat(p.z_feedrate_code)
  5122. gcode += self.doformat(p.down_z_start_code)
  5123. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  5124. gcode += self.doformat(p.dwell_fwd_code)
  5125. gcode += self.doformat(p.z_feedrate_dispense_code)
  5126. gcode += self.doformat(p.lift_z_dispense_code)
  5127. gcode += self.doformat(p.feedrate_xy_code)
  5128. # Cutting...
  5129. for pt in path[1:]:
  5130. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1]) # Linear motion to point
  5131. # Up to travelling height.
  5132. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  5133. gcode += self.doformat(p.spindle_rev_code)
  5134. gcode += self.doformat(p.down_z_stop_code)
  5135. gcode += self.doformat(p.spindle_off_code)
  5136. gcode += self.doformat(p.dwell_rev_code)
  5137. gcode += self.doformat(p.z_feedrate_code)
  5138. gcode += self.doformat(p.lift_code)
  5139. elif type(geometry) == Point:
  5140. gcode += self.doformat(p.linear_code, x=path[0][0], y=path[0][1]) # Move to first point
  5141. gcode += self.doformat(p.z_feedrate_dispense_code)
  5142. gcode += self.doformat(p.down_z_start_code)
  5143. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  5144. gcode += self.doformat(p.dwell_fwd_code)
  5145. gcode += self.doformat(p.lift_z_dispense_code)
  5146. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  5147. gcode += self.doformat(p.spindle_rev_code)
  5148. gcode += self.doformat(p.spindle_off_code)
  5149. gcode += self.doformat(p.down_z_stop_code)
  5150. gcode += self.doformat(p.dwell_rev_code)
  5151. gcode += self.doformat(p.z_feedrate_code)
  5152. gcode += self.doformat(p.lift_code)
  5153. return gcode
  5154. def create_gcode_single_pass(self, geometry, extracut, tolerance):
  5155. # G-code. Note: self.linear2gcode() and self.point2gcode() will lower and raise the tool every time.
  5156. gcode_single_pass = ''
  5157. if type(geometry) == LineString or type(geometry) == LinearRing:
  5158. if extracut is False:
  5159. gcode_single_pass = self.linear2gcode(geometry, tolerance=tolerance)
  5160. else:
  5161. if geometry.is_ring:
  5162. gcode_single_pass = self.linear2gcode_extra(geometry, tolerance=tolerance)
  5163. else:
  5164. gcode_single_pass = self.linear2gcode(geometry, tolerance=tolerance)
  5165. elif type(geometry) == Point:
  5166. gcode_single_pass = self.point2gcode(geometry)
  5167. else:
  5168. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  5169. return
  5170. return gcode_single_pass
  5171. def create_gcode_multi_pass(self, geometry, extracut, tolerance, postproc, current_point):
  5172. gcode_multi_pass = ''
  5173. if isinstance(self.z_cut, Decimal):
  5174. z_cut = self.z_cut
  5175. else:
  5176. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  5177. if self.z_depthpercut is None:
  5178. self.z_depthpercut = z_cut
  5179. elif not isinstance(self.z_depthpercut, Decimal):
  5180. self.z_depthpercut = Decimal(self.z_depthpercut).quantize(Decimal('0.000000001'))
  5181. depth = 0
  5182. reverse = False
  5183. while depth > z_cut:
  5184. # Increase depth. Limit to z_cut.
  5185. depth -= self.z_depthpercut
  5186. if depth < z_cut:
  5187. depth = z_cut
  5188. # Cut at specific depth and do not lift the tool.
  5189. # Note: linear2gcode() will use G00 to move to the first point in the path, but it should be already
  5190. # at the first point if the tool is down (in the material). So, an extra G00 should show up but
  5191. # is inconsequential.
  5192. if type(geometry) == LineString or type(geometry) == LinearRing:
  5193. if extracut is False:
  5194. gcode_multi_pass += self.linear2gcode(geometry, tolerance=tolerance, z_cut=depth, up=False)
  5195. else:
  5196. if geometry.is_ring:
  5197. gcode_multi_pass += self.linear2gcode_extra(geometry, tolerance=tolerance, z_cut=depth, up=False)
  5198. else:
  5199. gcode_multi_pass += self.linear2gcode(geometry, tolerance=tolerance, z_cut=depth, up=False)
  5200. # Ignore multi-pass for points.
  5201. elif type(geometry) == Point:
  5202. gcode_multi_pass += self.point2gcode(geometry)
  5203. break # Ignoring ...
  5204. else:
  5205. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  5206. # Reverse coordinates if not a loop so we can continue cutting without returning to the beginning.
  5207. if type(geometry) == LineString:
  5208. geometry.coords = list(geometry.coords)[::-1]
  5209. reverse = True
  5210. # If geometry is reversed, revert.
  5211. if reverse:
  5212. if type(geometry) == LineString:
  5213. geometry.coords = list(geometry.coords)[::-1]
  5214. # Lift the tool
  5215. gcode_multi_pass += self.doformat(postproc.lift_code, x=current_point[0], y=current_point[1])
  5216. return gcode_multi_pass
  5217. def codes_split(self, gline):
  5218. """
  5219. Parses a line of G-Code such as "G01 X1234 Y987" into
  5220. a dictionary: {'G': 1.0, 'X': 1234.0, 'Y': 987.0}
  5221. :param gline: G-Code line string
  5222. :return: Dictionary with parsed line.
  5223. """
  5224. command = {}
  5225. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5226. match_z = re.search(r"^Z(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  5227. if match_z:
  5228. command['G'] = 0
  5229. command['X'] = float(match_z.group(1).replace(" ", "")) * 0.025
  5230. command['Y'] = float(match_z.group(2).replace(" ", "")) * 0.025
  5231. command['Z'] = float(match_z.group(3).replace(" ", "")) * 0.025
  5232. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  5233. match_pa = re.search(r"^PA(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  5234. if match_pa:
  5235. command['G'] = 0
  5236. command['X'] = float(match_pa.group(1).replace(" ", ""))
  5237. command['Y'] = float(match_pa.group(2).replace(" ", ""))
  5238. match_pen = re.search(r"^(P[U|D])", gline)
  5239. if match_pen:
  5240. if match_pen.group(1) == 'PU':
  5241. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  5242. # therefore the move is of kind T (travel)
  5243. command['Z'] = 1
  5244. else:
  5245. command['Z'] = 0
  5246. elif 'grbl_laser' in self.pp_excellon_name or 'grbl_laser' in self.pp_geometry_name or \
  5247. (self.pp_solderpaste_name is not None and 'Paste' in self.pp_solderpaste_name):
  5248. match_lsr = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  5249. if match_lsr:
  5250. command['X'] = float(match_lsr.group(1).replace(" ", ""))
  5251. command['Y'] = float(match_lsr.group(2).replace(" ", ""))
  5252. match_lsr_pos = re.search(r"^(M0[3|5])", gline)
  5253. if match_lsr_pos:
  5254. if match_lsr_pos.group(1) == 'M05':
  5255. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  5256. # therefore the move is of kind T (travel)
  5257. command['Z'] = 1
  5258. else:
  5259. command['Z'] = 0
  5260. elif self.pp_solderpaste_name is not None:
  5261. if 'Paste' in self.pp_solderpaste_name:
  5262. match_paste = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  5263. if match_paste:
  5264. command['X'] = float(match_paste.group(1).replace(" ", ""))
  5265. command['Y'] = float(match_paste.group(2).replace(" ", ""))
  5266. else:
  5267. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  5268. while match:
  5269. command[match.group(1)] = float(match.group(2).replace(" ", ""))
  5270. gline = gline[match.end():]
  5271. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  5272. return command
  5273. def gcode_parse(self):
  5274. """
  5275. G-Code parser (from self.gcode). Generates dictionary with
  5276. single-segment LineString's and "kind" indicating cut or travel,
  5277. fast or feedrate speed.
  5278. """
  5279. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5280. # Results go here
  5281. geometry = []
  5282. # Last known instruction
  5283. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  5284. # Current path: temporary storage until tool is
  5285. # lifted or lowered.
  5286. if self.toolchange_xy_type == "excellon":
  5287. if self.app.defaults["excellon_toolchangexy"] == '':
  5288. pos_xy = [0, 0]
  5289. else:
  5290. pos_xy = [float(eval(a)) for a in self.app.defaults["excellon_toolchangexy"].split(",")]
  5291. else:
  5292. if self.app.defaults["geometry_toolchangexy"] == '':
  5293. pos_xy = [0, 0]
  5294. else:
  5295. pos_xy = [float(eval(a)) for a in self.app.defaults["geometry_toolchangexy"].split(",")]
  5296. path = [pos_xy]
  5297. # path = [(0, 0)]
  5298. # Process every instruction
  5299. for line in StringIO(self.gcode):
  5300. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  5301. return "fail"
  5302. gobj = self.codes_split(line)
  5303. ## Units
  5304. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  5305. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  5306. continue
  5307. ## Changing height
  5308. if 'Z' in gobj:
  5309. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5310. pass
  5311. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  5312. pass
  5313. elif 'grbl_laser' in self.pp_excellon_name or 'grbl_laser' in self.pp_geometry_name:
  5314. pass
  5315. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  5316. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  5317. pass
  5318. else:
  5319. log.warning("Non-orthogonal motion: From %s" % str(current))
  5320. log.warning(" To: %s" % str(gobj))
  5321. current['Z'] = gobj['Z']
  5322. # Store the path into geometry and reset path
  5323. if len(path) > 1:
  5324. geometry.append({"geom": LineString(path),
  5325. "kind": kind})
  5326. path = [path[-1]] # Start with the last point of last path.
  5327. # create the geometry for the holes created when drilling Excellon drills
  5328. if self.origin_kind == 'excellon':
  5329. if current['Z'] < 0:
  5330. current_drill_point_coords = (float('%.4f' % current['X']), float('%.4f' % current['Y']))
  5331. # find the drill diameter knowing the drill coordinates
  5332. for pt_dict in self.exc_drills:
  5333. point_in_dict_coords = (float('%.4f' % pt_dict['point'].x),
  5334. float('%.4f' % pt_dict['point'].y))
  5335. if point_in_dict_coords == current_drill_point_coords:
  5336. tool = pt_dict['tool']
  5337. dia = self.exc_tools[tool]['C']
  5338. kind = ['C', 'F']
  5339. geometry.append({"geom": Point(current_drill_point_coords).
  5340. buffer(dia/2).exterior,
  5341. "kind": kind})
  5342. break
  5343. if 'G' in gobj:
  5344. current['G'] = int(gobj['G'])
  5345. if 'X' in gobj or 'Y' in gobj:
  5346. # TODO: I think there is a problem here, current['X] (and the rest of current[...] are not initialized
  5347. if 'X' in gobj:
  5348. x = gobj['X']
  5349. # current['X'] = x
  5350. else:
  5351. x = current['X']
  5352. if 'Y' in gobj:
  5353. y = gobj['Y']
  5354. else:
  5355. y = current['Y']
  5356. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5357. if current['Z'] > 0:
  5358. kind[0] = 'T'
  5359. if current['G'] > 0:
  5360. kind[1] = 'S'
  5361. if current['G'] in [0, 1]: # line
  5362. path.append((x, y))
  5363. arcdir = [None, None, "cw", "ccw"]
  5364. if current['G'] in [2, 3]: # arc
  5365. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  5366. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  5367. start = arctan2(-gobj['J'], -gobj['I'])
  5368. stop = arctan2(-center[1] + y, -center[0] + x)
  5369. path += arc(center, radius, start, stop,
  5370. arcdir[current['G']],
  5371. int(self.steps_per_circle / 4))
  5372. # Update current instruction
  5373. for code in gobj:
  5374. current[code] = gobj[code]
  5375. # There might not be a change in height at the
  5376. # end, therefore, see here too if there is
  5377. # a final path.
  5378. if len(path) > 1:
  5379. geometry.append({"geom": LineString(path),
  5380. "kind": kind})
  5381. self.gcode_parsed = geometry
  5382. return geometry
  5383. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  5384. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  5385. # alpha={"T": 0.3, "C": 1.0}):
  5386. # """
  5387. # Creates a Matplotlib figure with a plot of the
  5388. # G-code job.
  5389. # """
  5390. # if tooldia is None:
  5391. # tooldia = self.tooldia
  5392. #
  5393. # fig = Figure(dpi=dpi)
  5394. # ax = fig.add_subplot(111)
  5395. # ax.set_aspect(1)
  5396. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  5397. # ax.set_xlim(xmin-margin, xmax+margin)
  5398. # ax.set_ylim(ymin-margin, ymax+margin)
  5399. #
  5400. # if tooldia == 0:
  5401. # for geo in self.gcode_parsed:
  5402. # linespec = '--'
  5403. # linecolor = color[geo['kind'][0]][1]
  5404. # if geo['kind'][0] == 'C':
  5405. # linespec = 'k-'
  5406. # x, y = geo['geom'].coords.xy
  5407. # ax.plot(x, y, linespec, color=linecolor)
  5408. # else:
  5409. # for geo in self.gcode_parsed:
  5410. # poly = geo['geom'].buffer(tooldia/2.0)
  5411. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  5412. # edgecolor=color[geo['kind'][0]][1],
  5413. # alpha=alpha[geo['kind'][0]], zorder=2)
  5414. # ax.add_patch(patch)
  5415. #
  5416. # return fig
  5417. def plot2(self, tooldia=None, dpi=75, margin=0.1, gcode_parsed=None,
  5418. color={"T": ["#F0E24D4C", "#B5AB3A4C"], "C": ["#5E6CFFFF", "#4650BDFF"]},
  5419. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005, obj=None, visible=False, kind='all'):
  5420. """
  5421. Plots the G-code job onto the given axes.
  5422. :param tooldia: Tool diameter.
  5423. :param dpi: Not used!
  5424. :param margin: Not used!
  5425. :param color: Color specification.
  5426. :param alpha: Transparency specification.
  5427. :param tool_tolerance: Tolerance when drawing the toolshape.
  5428. :return: None
  5429. """
  5430. gcode_parsed = gcode_parsed if gcode_parsed else self.gcode_parsed
  5431. path_num = 0
  5432. if tooldia is None:
  5433. tooldia = self.tooldia
  5434. if tooldia == 0:
  5435. for geo in gcode_parsed:
  5436. if kind == 'all':
  5437. obj.add_shape(shape=geo['geom'], color=color[geo['kind'][0]][1], visible=visible)
  5438. elif kind == 'travel':
  5439. if geo['kind'][0] == 'T':
  5440. obj.add_shape(shape=geo['geom'], color=color['T'][1], visible=visible)
  5441. elif kind == 'cut':
  5442. if geo['kind'][0] == 'C':
  5443. obj.add_shape(shape=geo['geom'], color=color['C'][1], visible=visible)
  5444. else:
  5445. text = []
  5446. pos = []
  5447. for geo in gcode_parsed:
  5448. path_num += 1
  5449. text.append(str(path_num))
  5450. pos.append(geo['geom'].coords[0])
  5451. # plot the geometry of Excellon objects
  5452. if self.origin_kind == 'excellon':
  5453. try:
  5454. poly = Polygon(geo['geom'])
  5455. except ValueError:
  5456. # if the geos are travel lines it will enter into Exception
  5457. poly = geo['geom'].buffer(tooldia / 2.0).simplify(tool_tolerance)
  5458. else:
  5459. # plot the geometry of any objects other than Excellon
  5460. poly = geo['geom'].buffer(tooldia / 2.0).simplify(tool_tolerance)
  5461. if kind == 'all':
  5462. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  5463. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  5464. elif kind == 'travel':
  5465. if geo['kind'][0] == 'T':
  5466. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  5467. visible=visible, layer=2)
  5468. elif kind == 'cut':
  5469. if geo['kind'][0] == 'C':
  5470. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  5471. visible=visible, layer=1)
  5472. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'])
  5473. def create_geometry(self):
  5474. # TODO: This takes forever. Too much data?
  5475. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  5476. return self.solid_geometry
  5477. # code snippet added by Lei Zheng in a rejected pull request on FlatCAM https://bitbucket.org/realthunder/
  5478. def segment(self, coords):
  5479. """
  5480. break long linear lines to make it more auto level friendly
  5481. """
  5482. if len(coords) < 2 or self.segx <= 0 and self.segy <= 0:
  5483. return list(coords)
  5484. path = [coords[0]]
  5485. # break the line in either x or y dimension only
  5486. def linebreak_single(line, dim, dmax):
  5487. if dmax <= 0:
  5488. return None
  5489. if line[1][dim] > line[0][dim]:
  5490. sign = 1.0
  5491. d = line[1][dim] - line[0][dim]
  5492. else:
  5493. sign = -1.0
  5494. d = line[0][dim] - line[1][dim]
  5495. if d > dmax:
  5496. # make sure we don't make any new lines too short
  5497. if d > dmax * 2:
  5498. dd = dmax
  5499. else:
  5500. dd = d / 2
  5501. other = dim ^ 1
  5502. return (line[0][dim] + dd * sign, line[0][other] + \
  5503. dd * (line[1][other] - line[0][other]) / d)
  5504. return None
  5505. # recursively breaks down a given line until it is within the
  5506. # required step size
  5507. def linebreak(line):
  5508. pt_new = linebreak_single(line, 0, self.segx)
  5509. if pt_new is None:
  5510. pt_new2 = linebreak_single(line, 1, self.segy)
  5511. else:
  5512. pt_new2 = linebreak_single((line[0], pt_new), 1, self.segy)
  5513. if pt_new2 is not None:
  5514. pt_new = pt_new2[::-1]
  5515. if pt_new is None:
  5516. path.append(line[1])
  5517. else:
  5518. path.append(pt_new)
  5519. linebreak((pt_new, line[1]))
  5520. for pt in coords[1:]:
  5521. linebreak((path[-1], pt))
  5522. return path
  5523. def linear2gcode(self, linear, tolerance=0, down=True, up=True,
  5524. z_cut=None, z_move=None, zdownrate=None,
  5525. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False):
  5526. """
  5527. Generates G-code to cut along the linear feature.
  5528. :param linear: The path to cut along.
  5529. :type: Shapely.LinearRing or Shapely.Linear String
  5530. :param tolerance: All points in the simplified object will be within the
  5531. tolerance distance of the original geometry.
  5532. :type tolerance: float
  5533. :param feedrate: speed for cut on X - Y plane
  5534. :param feedrate_z: speed for cut on Z plane
  5535. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  5536. :return: G-code to cut along the linear feature.
  5537. :rtype: str
  5538. """
  5539. if z_cut is None:
  5540. z_cut = self.z_cut
  5541. if z_move is None:
  5542. z_move = self.z_move
  5543. #
  5544. # if zdownrate is None:
  5545. # zdownrate = self.zdownrate
  5546. if feedrate is None:
  5547. feedrate = self.feedrate
  5548. if feedrate_z is None:
  5549. feedrate_z = self.z_feedrate
  5550. if feedrate_rapid is None:
  5551. feedrate_rapid = self.feedrate_rapid
  5552. # Simplify paths?
  5553. if tolerance > 0:
  5554. target_linear = linear.simplify(tolerance)
  5555. else:
  5556. target_linear = linear
  5557. gcode = ""
  5558. # path = list(target_linear.coords)
  5559. path = self.segment(target_linear.coords)
  5560. p = self.pp_geometry
  5561. # Move fast to 1st point
  5562. if not cont:
  5563. gcode += self.doformat(p.rapid_code, x=path[0][0], y=path[0][1]) # Move to first point
  5564. # Move down to cutting depth
  5565. if down:
  5566. # Different feedrate for vertical cut?
  5567. gcode += self.doformat(p.z_feedrate_code)
  5568. # gcode += self.doformat(p.feedrate_code)
  5569. gcode += self.doformat(p.down_code, x=path[0][0], y=path[0][1], z_cut=z_cut)
  5570. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5571. # Cutting...
  5572. for pt in path[1:]:
  5573. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1], z=z_cut) # Linear motion to point
  5574. # Up to travelling height.
  5575. if up:
  5576. gcode += self.doformat(p.lift_code, x=pt[0], y=pt[1], z_move=z_move) # Stop cutting
  5577. return gcode
  5578. def linear2gcode_extra(self, linear, tolerance=0, down=True, up=True,
  5579. z_cut=None, z_move=None, zdownrate=None,
  5580. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False):
  5581. """
  5582. Generates G-code to cut along the linear feature.
  5583. :param linear: The path to cut along.
  5584. :type: Shapely.LinearRing or Shapely.Linear String
  5585. :param tolerance: All points in the simplified object will be within the
  5586. tolerance distance of the original geometry.
  5587. :type tolerance: float
  5588. :param feedrate: speed for cut on X - Y plane
  5589. :param feedrate_z: speed for cut on Z plane
  5590. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  5591. :return: G-code to cut along the linear feature.
  5592. :rtype: str
  5593. """
  5594. if z_cut is None:
  5595. z_cut = self.z_cut
  5596. if z_move is None:
  5597. z_move = self.z_move
  5598. #
  5599. # if zdownrate is None:
  5600. # zdownrate = self.zdownrate
  5601. if feedrate is None:
  5602. feedrate = self.feedrate
  5603. if feedrate_z is None:
  5604. feedrate_z = self.z_feedrate
  5605. if feedrate_rapid is None:
  5606. feedrate_rapid = self.feedrate_rapid
  5607. # Simplify paths?
  5608. if tolerance > 0:
  5609. target_linear = linear.simplify(tolerance)
  5610. else:
  5611. target_linear = linear
  5612. gcode = ""
  5613. path = list(target_linear.coords)
  5614. p = self.pp_geometry
  5615. # Move fast to 1st point
  5616. if not cont:
  5617. gcode += self.doformat(p.rapid_code, x=path[0][0], y=path[0][1]) # Move to first point
  5618. # Move down to cutting depth
  5619. if down:
  5620. # Different feedrate for vertical cut?
  5621. if self.z_feedrate is not None:
  5622. gcode += self.doformat(p.z_feedrate_code)
  5623. # gcode += self.doformat(p.feedrate_code)
  5624. gcode += self.doformat(p.down_code, x=path[0][0], y=path[0][1], z_cut=z_cut)
  5625. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5626. else:
  5627. gcode += self.doformat(p.down_code, x=path[0][0], y=path[0][1], z_cut=z_cut) # Start cutting
  5628. # Cutting...
  5629. for pt in path[1:]:
  5630. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1], z=z_cut) # Linear motion to point
  5631. # this line is added to create an extra cut over the first point in patch
  5632. # to make sure that we remove the copper leftovers
  5633. gcode += self.doformat(p.linear_code, x=path[1][0], y=path[1][1]) # Linear motion to the 1st point in the cut path
  5634. # Up to travelling height.
  5635. if up:
  5636. gcode += self.doformat(p.lift_code, x=path[1][0], y=path[1][1], z_move=z_move) # Stop cutting
  5637. return gcode
  5638. def point2gcode(self, point):
  5639. gcode = ""
  5640. path = list(point.coords)
  5641. p = self.pp_geometry
  5642. gcode += self.doformat(p.linear_code, x=path[0][0], y=path[0][1]) # Move to first point
  5643. if self.z_feedrate is not None:
  5644. gcode += self.doformat(p.z_feedrate_code)
  5645. gcode += self.doformat(p.down_code, x=path[0][0], y=path[0][1], z_cut = self.z_cut)
  5646. gcode += self.doformat(p.feedrate_code)
  5647. else:
  5648. gcode += self.doformat(p.down_code, x=path[0][0], y=path[0][1], z_cut = self.z_cut) # Start cutting
  5649. gcode += self.doformat(p.lift_code, x=path[0][0], y=path[0][1]) # Stop cutting
  5650. return gcode
  5651. def export_svg(self, scale_factor=0.00):
  5652. """
  5653. Exports the CNC Job as a SVG Element
  5654. :scale_factor: float
  5655. :return: SVG Element string
  5656. """
  5657. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  5658. # If not specified then try and use the tool diameter
  5659. # This way what is on screen will match what is outputed for the svg
  5660. # This is quite a useful feature for svg's used with visicut
  5661. if scale_factor <= 0:
  5662. scale_factor = self.options['tooldia'] / 2
  5663. # If still 0 then default to 0.05
  5664. # This value appears to work for zooming, and getting the output svg line width
  5665. # to match that viewed on screen with FlatCam
  5666. if scale_factor == 0:
  5667. scale_factor = 0.01
  5668. # Separate the list of cuts and travels into 2 distinct lists
  5669. # This way we can add different formatting / colors to both
  5670. cuts = []
  5671. travels = []
  5672. for g in self.gcode_parsed:
  5673. if g['kind'][0] == 'C': cuts.append(g)
  5674. if g['kind'][0] == 'T': travels.append(g)
  5675. # Used to determine the overall board size
  5676. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  5677. # Convert the cuts and travels into single geometry objects we can render as svg xml
  5678. if travels:
  5679. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  5680. if cuts:
  5681. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  5682. # Render the SVG Xml
  5683. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  5684. # It's better to have the travels sitting underneath the cuts for visicut
  5685. svg_elem = ""
  5686. if travels:
  5687. svg_elem = travelsgeom.svg(scale_factor=scale_factor, stroke_color="#F0E24D")
  5688. if cuts:
  5689. svg_elem += cutsgeom.svg(scale_factor=scale_factor, stroke_color="#5E6CFF")
  5690. return svg_elem
  5691. def bounds(self):
  5692. """
  5693. Returns coordinates of rectangular bounds
  5694. of geometry: (xmin, ymin, xmax, ymax).
  5695. """
  5696. # fixed issue of getting bounds only for one level lists of objects
  5697. # now it can get bounds for nested lists of objects
  5698. def bounds_rec(obj):
  5699. if type(obj) is list:
  5700. minx = Inf
  5701. miny = Inf
  5702. maxx = -Inf
  5703. maxy = -Inf
  5704. for k in obj:
  5705. if type(k) is dict:
  5706. for key in k:
  5707. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  5708. minx = min(minx, minx_)
  5709. miny = min(miny, miny_)
  5710. maxx = max(maxx, maxx_)
  5711. maxy = max(maxy, maxy_)
  5712. else:
  5713. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  5714. minx = min(minx, minx_)
  5715. miny = min(miny, miny_)
  5716. maxx = max(maxx, maxx_)
  5717. maxy = max(maxy, maxy_)
  5718. return minx, miny, maxx, maxy
  5719. else:
  5720. # it's a Shapely object, return it's bounds
  5721. return obj.bounds
  5722. if self.multitool is False:
  5723. log.debug("CNCJob->bounds()")
  5724. if self.solid_geometry is None:
  5725. log.debug("solid_geometry is None")
  5726. return 0, 0, 0, 0
  5727. bounds_coords = bounds_rec(self.solid_geometry)
  5728. else:
  5729. for k, v in self.cnc_tools.items():
  5730. minx = Inf
  5731. miny = Inf
  5732. maxx = -Inf
  5733. maxy = -Inf
  5734. try:
  5735. for k in v['solid_geometry']:
  5736. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  5737. minx = min(minx, minx_)
  5738. miny = min(miny, miny_)
  5739. maxx = max(maxx, maxx_)
  5740. maxy = max(maxy, maxy_)
  5741. except TypeError:
  5742. minx_, miny_, maxx_, maxy_ = bounds_rec(v['solid_geometry'])
  5743. minx = min(minx, minx_)
  5744. miny = min(miny, miny_)
  5745. maxx = max(maxx, maxx_)
  5746. maxy = max(maxy, maxy_)
  5747. bounds_coords = minx, miny, maxx, maxy
  5748. return bounds_coords
  5749. # TODO This function should be replaced at some point with a "real" function. Until then it's an ugly hack ...
  5750. def scale(self, xfactor, yfactor=None, point=None):
  5751. """
  5752. Scales all the geometry on the XY plane in the object by the
  5753. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  5754. not altered.
  5755. :param factor: Number by which to scale the object.
  5756. :type factor: float
  5757. :param point: the (x,y) coords for the point of origin of scale
  5758. :type tuple of floats
  5759. :return: None
  5760. :rtype: None
  5761. """
  5762. if yfactor is None:
  5763. yfactor = xfactor
  5764. if point is None:
  5765. px = 0
  5766. py = 0
  5767. else:
  5768. px, py = point
  5769. def scale_g(g):
  5770. """
  5771. :param g: 'g' parameter it's a gcode string
  5772. :return: scaled gcode string
  5773. """
  5774. temp_gcode = ''
  5775. header_start = False
  5776. header_stop = False
  5777. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5778. lines = StringIO(g)
  5779. for line in lines:
  5780. # this changes the GCODE header ---- UGLY HACK
  5781. if "TOOL DIAMETER" in line or "Feedrate:" in line:
  5782. header_start = True
  5783. if "G20" in line or "G21" in line:
  5784. header_start = False
  5785. header_stop = True
  5786. if header_start is True:
  5787. header_stop = False
  5788. if "in" in line:
  5789. if units == 'MM':
  5790. line = line.replace("in", "mm")
  5791. if "mm" in line:
  5792. if units == 'IN':
  5793. line = line.replace("mm", "in")
  5794. # find any float number in header (even multiple on the same line) and convert it
  5795. numbers_in_header = re.findall(self.g_nr_re, line)
  5796. if numbers_in_header:
  5797. for nr in numbers_in_header:
  5798. new_nr = float(nr) * xfactor
  5799. # replace the updated string
  5800. line = line.replace(nr, ('%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_nr))
  5801. )
  5802. # this scales all the X and Y and Z and F values and also the Tool Dia in the toolchange message
  5803. if header_stop is True:
  5804. if "G20" in line:
  5805. if units == 'MM':
  5806. line = line.replace("G20", "G21")
  5807. if "G21" in line:
  5808. if units == 'IN':
  5809. line = line.replace("G21", "G20")
  5810. # find the X group
  5811. match_x = self.g_x_re.search(line)
  5812. if match_x:
  5813. if match_x.group(1) is not None:
  5814. new_x = float(match_x.group(1)[1:]) * xfactor
  5815. # replace the updated string
  5816. line = line.replace(
  5817. match_x.group(1),
  5818. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  5819. )
  5820. # find the Y group
  5821. match_y = self.g_y_re.search(line)
  5822. if match_y:
  5823. if match_y.group(1) is not None:
  5824. new_y = float(match_y.group(1)[1:]) * yfactor
  5825. line = line.replace(
  5826. match_y.group(1),
  5827. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  5828. )
  5829. # find the Z group
  5830. match_z = self.g_z_re.search(line)
  5831. if match_z:
  5832. if match_z.group(1) is not None:
  5833. new_z = float(match_z.group(1)[1:]) * xfactor
  5834. line = line.replace(
  5835. match_z.group(1),
  5836. 'Z%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_z)
  5837. )
  5838. # find the F group
  5839. match_f = self.g_f_re.search(line)
  5840. if match_f:
  5841. if match_f.group(1) is not None:
  5842. new_f = float(match_f.group(1)[1:]) * xfactor
  5843. line = line.replace(
  5844. match_f.group(1),
  5845. 'F%.*f' % (self.app.defaults["cncjob_fr_decimals"], new_f)
  5846. )
  5847. # find the T group (tool dia on toolchange)
  5848. match_t = self.g_t_re.search(line)
  5849. if match_t:
  5850. if match_t.group(1) is not None:
  5851. new_t = float(match_t.group(1)[1:]) * xfactor
  5852. line = line.replace(
  5853. match_t.group(1),
  5854. '= %.*f' % (self.app.defaults["cncjob_coords_decimals"], new_t)
  5855. )
  5856. temp_gcode += line
  5857. lines.close()
  5858. header_stop = False
  5859. return temp_gcode
  5860. if self.multitool is False:
  5861. # offset Gcode
  5862. self.gcode = scale_g(self.gcode)
  5863. # offset geometry
  5864. for g in self.gcode_parsed:
  5865. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  5866. self.create_geometry()
  5867. else:
  5868. for k, v in self.cnc_tools.items():
  5869. # scale Gcode
  5870. v['gcode'] = scale_g(v['gcode'])
  5871. # scale gcode_parsed
  5872. for g in v['gcode_parsed']:
  5873. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  5874. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  5875. self.create_geometry()
  5876. def offset(self, vect):
  5877. """
  5878. Offsets all the geometry on the XY plane in the object by the
  5879. given vector.
  5880. Offsets all the GCODE on the XY plane in the object by the
  5881. given vector.
  5882. g_offsetx_re, g_offsety_re, multitool, cnnc_tools are attributes of FlatCAMCNCJob class in camlib
  5883. :param vect: (x, y) offset vector.
  5884. :type vect: tuple
  5885. :return: None
  5886. """
  5887. dx, dy = vect
  5888. def offset_g(g):
  5889. """
  5890. :param g: 'g' parameter it's a gcode string
  5891. :return: offseted gcode string
  5892. """
  5893. temp_gcode = ''
  5894. lines = StringIO(g)
  5895. for line in lines:
  5896. # find the X group
  5897. match_x = self.g_x_re.search(line)
  5898. if match_x:
  5899. if match_x.group(1) is not None:
  5900. # get the coordinate and add X offset
  5901. new_x = float(match_x.group(1)[1:]) + dx
  5902. # replace the updated string
  5903. line = line.replace(
  5904. match_x.group(1),
  5905. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  5906. )
  5907. match_y = self.g_y_re.search(line)
  5908. if match_y:
  5909. if match_y.group(1) is not None:
  5910. new_y = float(match_y.group(1)[1:]) + dy
  5911. line = line.replace(
  5912. match_y.group(1),
  5913. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  5914. )
  5915. temp_gcode += line
  5916. lines.close()
  5917. return temp_gcode
  5918. if self.multitool is False:
  5919. # offset Gcode
  5920. self.gcode = offset_g(self.gcode)
  5921. # offset geometry
  5922. for g in self.gcode_parsed:
  5923. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  5924. self.create_geometry()
  5925. else:
  5926. for k, v in self.cnc_tools.items():
  5927. # offset Gcode
  5928. v['gcode'] = offset_g(v['gcode'])
  5929. # offset gcode_parsed
  5930. for g in v['gcode_parsed']:
  5931. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  5932. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  5933. def mirror(self, axis, point):
  5934. """
  5935. Mirror the geometrys of an object by an given axis around the coordinates of the 'point'
  5936. :param angle:
  5937. :param point: tupple of coordinates (x,y)
  5938. :return:
  5939. """
  5940. px, py = point
  5941. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  5942. for g in self.gcode_parsed:
  5943. g['geom'] = affinity.scale(g['geom'], xscale, yscale, origin=(px, py))
  5944. self.create_geometry()
  5945. def skew(self, angle_x, angle_y, point):
  5946. """
  5947. Shear/Skew the geometries of an object by angles along x and y dimensions.
  5948. Parameters
  5949. ----------
  5950. angle_x, angle_y : float, float
  5951. The shear angle(s) for the x and y axes respectively. These can be
  5952. specified in either degrees (default) or radians by setting
  5953. use_radians=True.
  5954. point: tupple of coordinates (x,y)
  5955. See shapely manual for more information:
  5956. http://toblerity.org/shapely/manual.html#affine-transformations
  5957. """
  5958. px, py = point
  5959. for g in self.gcode_parsed:
  5960. g['geom'] = affinity.skew(g['geom'], angle_x, angle_y,
  5961. origin=(px, py))
  5962. self.create_geometry()
  5963. def rotate(self, angle, point):
  5964. """
  5965. Rotate the geometrys of an object by an given angle around the coordinates of the 'point'
  5966. :param angle:
  5967. :param point: tupple of coordinates (x,y)
  5968. :return:
  5969. """
  5970. px, py = point
  5971. for g in self.gcode_parsed:
  5972. g['geom'] = affinity.rotate(g['geom'], angle, origin=(px, py))
  5973. self.create_geometry()
  5974. def get_bounds(geometry_list):
  5975. xmin = Inf
  5976. ymin = Inf
  5977. xmax = -Inf
  5978. ymax = -Inf
  5979. #print "Getting bounds of:", str(geometry_set)
  5980. for gs in geometry_list:
  5981. try:
  5982. gxmin, gymin, gxmax, gymax = gs.bounds()
  5983. xmin = min([xmin, gxmin])
  5984. ymin = min([ymin, gymin])
  5985. xmax = max([xmax, gxmax])
  5986. ymax = max([ymax, gymax])
  5987. except:
  5988. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  5989. return [xmin, ymin, xmax, ymax]
  5990. def arc(center, radius, start, stop, direction, steps_per_circ):
  5991. """
  5992. Creates a list of point along the specified arc.
  5993. :param center: Coordinates of the center [x, y]
  5994. :type center: list
  5995. :param radius: Radius of the arc.
  5996. :type radius: float
  5997. :param start: Starting angle in radians
  5998. :type start: float
  5999. :param stop: End angle in radians
  6000. :type stop: float
  6001. :param direction: Orientation of the arc, "CW" or "CCW"
  6002. :type direction: string
  6003. :param steps_per_circ: Number of straight line segments to
  6004. represent a circle.
  6005. :type steps_per_circ: int
  6006. :return: The desired arc, as list of tuples
  6007. :rtype: list
  6008. """
  6009. # TODO: Resolution should be established by maximum error from the exact arc.
  6010. da_sign = {"cw": -1.0, "ccw": 1.0}
  6011. points = []
  6012. if direction == "ccw" and stop <= start:
  6013. stop += 2 * pi
  6014. if direction == "cw" and stop >= start:
  6015. stop -= 2 * pi
  6016. angle = abs(stop - start)
  6017. #angle = stop-start
  6018. steps = max([int(ceil(angle / (2 * pi) * steps_per_circ)), 2])
  6019. delta_angle = da_sign[direction] * angle * 1.0 / steps
  6020. for i in range(steps + 1):
  6021. theta = start + delta_angle * i
  6022. points.append((center[0] + radius * cos(theta), center[1] + radius * sin(theta)))
  6023. return points
  6024. def arc2(p1, p2, center, direction, steps_per_circ):
  6025. r = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  6026. start = arctan2(p1[1] - center[1], p1[0] - center[0])
  6027. stop = arctan2(p2[1] - center[1], p2[0] - center[0])
  6028. return arc(center, r, start, stop, direction, steps_per_circ)
  6029. def arc_angle(start, stop, direction):
  6030. if direction == "ccw" and stop <= start:
  6031. stop += 2 * pi
  6032. if direction == "cw" and stop >= start:
  6033. stop -= 2 * pi
  6034. angle = abs(stop - start)
  6035. return angle
  6036. # def find_polygon(poly, point):
  6037. # """
  6038. # Find an object that object.contains(Point(point)) in
  6039. # poly, which can can be iterable, contain iterable of, or
  6040. # be itself an implementer of .contains().
  6041. #
  6042. # :param poly: See description
  6043. # :return: Polygon containing point or None.
  6044. # """
  6045. #
  6046. # if poly is None:
  6047. # return None
  6048. #
  6049. # try:
  6050. # for sub_poly in poly:
  6051. # p = find_polygon(sub_poly, point)
  6052. # if p is not None:
  6053. # return p
  6054. # except TypeError:
  6055. # try:
  6056. # if poly.contains(Point(point)):
  6057. # return poly
  6058. # except AttributeError:
  6059. # return None
  6060. #
  6061. # return None
  6062. def to_dict(obj):
  6063. """
  6064. Makes the following types into serializable form:
  6065. * ApertureMacro
  6066. * BaseGeometry
  6067. :param obj: Shapely geometry.
  6068. :type obj: BaseGeometry
  6069. :return: Dictionary with serializable form if ``obj`` was
  6070. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  6071. """
  6072. if isinstance(obj, ApertureMacro):
  6073. return {
  6074. "__class__": "ApertureMacro",
  6075. "__inst__": obj.to_dict()
  6076. }
  6077. if isinstance(obj, BaseGeometry):
  6078. return {
  6079. "__class__": "Shply",
  6080. "__inst__": sdumps(obj)
  6081. }
  6082. return obj
  6083. def dict2obj(d):
  6084. """
  6085. Default deserializer.
  6086. :param d: Serializable dictionary representation of an object
  6087. to be reconstructed.
  6088. :return: Reconstructed object.
  6089. """
  6090. if '__class__' in d and '__inst__' in d:
  6091. if d['__class__'] == "Shply":
  6092. return sloads(d['__inst__'])
  6093. if d['__class__'] == "ApertureMacro":
  6094. am = ApertureMacro()
  6095. am.from_dict(d['__inst__'])
  6096. return am
  6097. return d
  6098. else:
  6099. return d
  6100. # def plotg(geo, solid_poly=False, color="black"):
  6101. # try:
  6102. # _ = iter(geo)
  6103. # except:
  6104. # geo = [geo]
  6105. #
  6106. # for g in geo:
  6107. # if type(g) == Polygon:
  6108. # if solid_poly:
  6109. # patch = PolygonPatch(g,
  6110. # facecolor="#BBF268",
  6111. # edgecolor="#006E20",
  6112. # alpha=0.75,
  6113. # zorder=2)
  6114. # ax = subplot(111)
  6115. # ax.add_patch(patch)
  6116. # else:
  6117. # x, y = g.exterior.coords.xy
  6118. # plot(x, y, color=color)
  6119. # for ints in g.interiors:
  6120. # x, y = ints.coords.xy
  6121. # plot(x, y, color=color)
  6122. # continue
  6123. #
  6124. # if type(g) == LineString or type(g) == LinearRing:
  6125. # x, y = g.coords.xy
  6126. # plot(x, y, color=color)
  6127. # continue
  6128. #
  6129. # if type(g) == Point:
  6130. # x, y = g.coords.xy
  6131. # plot(x, y, 'o')
  6132. # continue
  6133. #
  6134. # try:
  6135. # _ = iter(g)
  6136. # plotg(g, color=color)
  6137. # except:
  6138. # log.error("Cannot plot: " + str(type(g)))
  6139. # continue
  6140. def parse_gerber_number(strnumber, int_digits, frac_digits, zeros):
  6141. """
  6142. Parse a single number of Gerber coordinates.
  6143. :param strnumber: String containing a number in decimal digits
  6144. from a coordinate data block, possibly with a leading sign.
  6145. :type strnumber: str
  6146. :param int_digits: Number of digits used for the integer
  6147. part of the number
  6148. :type frac_digits: int
  6149. :param frac_digits: Number of digits used for the fractional
  6150. part of the number
  6151. :type frac_digits: int
  6152. :param zeros: If 'L', leading zeros are removed and trailing zeros are kept. Same situation for 'D' when
  6153. no zero suppression is done. If 'T', is in reverse.
  6154. :type zeros: str
  6155. :return: The number in floating point.
  6156. :rtype: float
  6157. """
  6158. ret_val = None
  6159. if zeros == 'L' or zeros == 'D':
  6160. ret_val = int(strnumber) * (10 ** (-frac_digits))
  6161. if zeros == 'T':
  6162. int_val = int(strnumber)
  6163. ret_val = (int_val * (10 ** ((int_digits + frac_digits) - len(strnumber)))) * (10 ** (-frac_digits))
  6164. return ret_val
  6165. def alpha_shape(points, alpha):
  6166. """
  6167. Compute the alpha shape (concave hull) of a set of points.
  6168. @param points: Iterable container of points.
  6169. @param alpha: alpha value to influence the gooeyness of the border. Smaller
  6170. numbers don't fall inward as much as larger numbers. Too large,
  6171. and you lose everything!
  6172. """
  6173. if len(points) < 4:
  6174. # When you have a triangle, there is no sense in computing an alpha
  6175. # shape.
  6176. return MultiPoint(list(points)).convex_hull
  6177. def add_edge(edges, edge_points, coords, i, j):
  6178. """Add a line between the i-th and j-th points, if not in the list already"""
  6179. if (i, j) in edges or (j, i) in edges:
  6180. # already added
  6181. return
  6182. edges.add( (i, j) )
  6183. edge_points.append(coords[ [i, j] ])
  6184. coords = np.array([point.coords[0] for point in points])
  6185. tri = Delaunay(coords)
  6186. edges = set()
  6187. edge_points = []
  6188. # loop over triangles:
  6189. # ia, ib, ic = indices of corner points of the triangle
  6190. for ia, ib, ic in tri.vertices:
  6191. pa = coords[ia]
  6192. pb = coords[ib]
  6193. pc = coords[ic]
  6194. # Lengths of sides of triangle
  6195. a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
  6196. b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
  6197. c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
  6198. # Semiperimeter of triangle
  6199. s = (a + b + c)/2.0
  6200. # Area of triangle by Heron's formula
  6201. area = math.sqrt(s*(s-a)*(s-b)*(s-c))
  6202. circum_r = a*b*c/(4.0*area)
  6203. # Here's the radius filter.
  6204. #print circum_r
  6205. if circum_r < 1.0/alpha:
  6206. add_edge(edges, edge_points, coords, ia, ib)
  6207. add_edge(edges, edge_points, coords, ib, ic)
  6208. add_edge(edges, edge_points, coords, ic, ia)
  6209. m = MultiLineString(edge_points)
  6210. triangles = list(polygonize(m))
  6211. return cascaded_union(triangles), edge_points
  6212. # def voronoi(P):
  6213. # """
  6214. # Returns a list of all edges of the voronoi diagram for the given input points.
  6215. # """
  6216. # delauny = Delaunay(P)
  6217. # triangles = delauny.points[delauny.vertices]
  6218. #
  6219. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  6220. # long_lines_endpoints = []
  6221. #
  6222. # lineIndices = []
  6223. # for i, triangle in enumerate(triangles):
  6224. # circum_center = circum_centers[i]
  6225. # for j, neighbor in enumerate(delauny.neighbors[i]):
  6226. # if neighbor != -1:
  6227. # lineIndices.append((i, neighbor))
  6228. # else:
  6229. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  6230. # ps = np.array((ps[1], -ps[0]))
  6231. #
  6232. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  6233. # di = middle - triangle[j]
  6234. #
  6235. # ps /= np.linalg.norm(ps)
  6236. # di /= np.linalg.norm(di)
  6237. #
  6238. # if np.dot(di, ps) < 0.0:
  6239. # ps *= -1000.0
  6240. # else:
  6241. # ps *= 1000.0
  6242. #
  6243. # long_lines_endpoints.append(circum_center + ps)
  6244. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  6245. #
  6246. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  6247. #
  6248. # # filter out any duplicate lines
  6249. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  6250. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  6251. # lineIndicesUnique = np.unique(lineIndicesTupled)
  6252. #
  6253. # return vertices, lineIndicesUnique
  6254. #
  6255. #
  6256. # def triangle_csc(pts):
  6257. # rows, cols = pts.shape
  6258. #
  6259. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  6260. # [np.ones((1, rows)), np.zeros((1, 1))]])
  6261. #
  6262. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  6263. # x = np.linalg.solve(A,b)
  6264. # bary_coords = x[:-1]
  6265. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  6266. #
  6267. #
  6268. # def voronoi_cell_lines(points, vertices, lineIndices):
  6269. # """
  6270. # Returns a mapping from a voronoi cell to its edges.
  6271. #
  6272. # :param points: shape (m,2)
  6273. # :param vertices: shape (n,2)
  6274. # :param lineIndices: shape (o,2)
  6275. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  6276. # """
  6277. # kd = KDTree(points)
  6278. #
  6279. # cells = collections.defaultdict(list)
  6280. # for i1, i2 in lineIndices:
  6281. # v1, v2 = vertices[i1], vertices[i2]
  6282. # mid = (v1+v2)/2
  6283. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  6284. # cells[p1Idx].append((i1, i2))
  6285. # cells[p2Idx].append((i1, i2))
  6286. #
  6287. # return cells
  6288. #
  6289. #
  6290. # def voronoi_edges2polygons(cells):
  6291. # """
  6292. # Transforms cell edges into polygons.
  6293. #
  6294. # :param cells: as returned from voronoi_cell_lines
  6295. # :rtype: dict point index -> list of vertex indices which form a polygon
  6296. # """
  6297. #
  6298. # # first, close the outer cells
  6299. # for pIdx, lineIndices_ in cells.items():
  6300. # dangling_lines = []
  6301. # for i1, i2 in lineIndices_:
  6302. # p = (i1, i2)
  6303. # 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_)
  6304. # # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  6305. # assert 1 <= len(connections) <= 2
  6306. # if len(connections) == 1:
  6307. # dangling_lines.append((i1, i2))
  6308. # assert len(dangling_lines) in [0, 2]
  6309. # if len(dangling_lines) == 2:
  6310. # (i11, i12), (i21, i22) = dangling_lines
  6311. # s = (i11, i12)
  6312. # t = (i21, i22)
  6313. #
  6314. # # determine which line ends are unconnected
  6315. # connected = filter(lambda k: k != s and (k[0] == s[0] or k[1] == s[0]), lineIndices_)
  6316. # # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  6317. # i11Unconnected = len(connected) == 0
  6318. #
  6319. # connected = filter(lambda k: k != t and (k[0] == t[0] or k[1] == t[0]), lineIndices_)
  6320. # # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  6321. # i21Unconnected = len(connected) == 0
  6322. #
  6323. # startIdx = i11 if i11Unconnected else i12
  6324. # endIdx = i21 if i21Unconnected else i22
  6325. #
  6326. # cells[pIdx].append((startIdx, endIdx))
  6327. #
  6328. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  6329. # polys = dict()
  6330. # for pIdx, lineIndices_ in cells.items():
  6331. # # get a directed graph which contains both directions and arbitrarily follow one of both
  6332. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  6333. # directedGraphMap = collections.defaultdict(list)
  6334. # for (i1, i2) in directedGraph:
  6335. # directedGraphMap[i1].append(i2)
  6336. # orderedEdges = []
  6337. # currentEdge = directedGraph[0]
  6338. # while len(orderedEdges) < len(lineIndices_):
  6339. # i1 = currentEdge[1]
  6340. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  6341. # nextEdge = (i1, i2)
  6342. # orderedEdges.append(nextEdge)
  6343. # currentEdge = nextEdge
  6344. #
  6345. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  6346. #
  6347. # return polys
  6348. #
  6349. #
  6350. # def voronoi_polygons(points):
  6351. # """
  6352. # Returns the voronoi polygon for each input point.
  6353. #
  6354. # :param points: shape (n,2)
  6355. # :rtype: list of n polygons where each polygon is an array of vertices
  6356. # """
  6357. # vertices, lineIndices = voronoi(points)
  6358. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  6359. # polys = voronoi_edges2polygons(cells)
  6360. # polylist = []
  6361. # for i in range(len(points)):
  6362. # poly = vertices[np.asarray(polys[i])]
  6363. # polylist.append(poly)
  6364. # return polylist
  6365. #
  6366. #
  6367. # class Zprofile:
  6368. # def __init__(self):
  6369. #
  6370. # # data contains lists of [x, y, z]
  6371. # self.data = []
  6372. #
  6373. # # Computed voronoi polygons (shapely)
  6374. # self.polygons = []
  6375. # pass
  6376. #
  6377. # # def plot_polygons(self):
  6378. # # axes = plt.subplot(1, 1, 1)
  6379. # #
  6380. # # plt.axis([-0.05, 1.05, -0.05, 1.05])
  6381. # #
  6382. # # for poly in self.polygons:
  6383. # # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  6384. # # axes.add_patch(p)
  6385. #
  6386. # def init_from_csv(self, filename):
  6387. # pass
  6388. #
  6389. # def init_from_string(self, zpstring):
  6390. # pass
  6391. #
  6392. # def init_from_list(self, zplist):
  6393. # self.data = zplist
  6394. #
  6395. # def generate_polygons(self):
  6396. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  6397. #
  6398. # def normalize(self, origin):
  6399. # pass
  6400. #
  6401. # def paste(self, path):
  6402. # """
  6403. # Return a list of dictionaries containing the parts of the original
  6404. # path and their z-axis offset.
  6405. # """
  6406. #
  6407. # # At most one region/polygon will contain the path
  6408. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  6409. #
  6410. # if len(containing) > 0:
  6411. # return [{"path": path, "z": self.data[containing[0]][2]}]
  6412. #
  6413. # # All region indexes that intersect with the path
  6414. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  6415. #
  6416. # return [{"path": path.intersection(self.polygons[i]),
  6417. # "z": self.data[i][2]} for i in crossing]
  6418. def autolist(obj):
  6419. try:
  6420. _ = iter(obj)
  6421. return obj
  6422. except TypeError:
  6423. return [obj]
  6424. def three_point_circle(p1, p2, p3):
  6425. """
  6426. Computes the center and radius of a circle from
  6427. 3 points on its circumference.
  6428. :param p1: Point 1
  6429. :param p2: Point 2
  6430. :param p3: Point 3
  6431. :return: center, radius
  6432. """
  6433. # Midpoints
  6434. a1 = (p1 + p2) / 2.0
  6435. a2 = (p2 + p3) / 2.0
  6436. # Normals
  6437. b1 = dot((p2 - p1), array([[0, -1], [1, 0]], dtype=float32))
  6438. b2 = dot((p3 - p2), array([[0, 1], [-1, 0]], dtype=float32))
  6439. # Params
  6440. try:
  6441. T = solve(transpose(array([-b1, b2])), a1 - a2)
  6442. except Exception as e:
  6443. log.debug("camlib.three_point_circle() --> %s" % str(e))
  6444. return
  6445. # Center
  6446. center = a1 + b1 * T[0]
  6447. # Radius
  6448. radius = np.linalg.norm(center - p1)
  6449. return center, radius, T[0]
  6450. def distance(pt1, pt2):
  6451. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  6452. def distance_euclidian(x1, y1, x2, y2):
  6453. return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  6454. class FlatCAMRTree(object):
  6455. """
  6456. Indexes geometry (Any object with "cooords" property containing
  6457. a list of tuples with x, y values). Objects are indexed by
  6458. all their points by default. To index by arbitrary points,
  6459. override self.points2obj.
  6460. """
  6461. def __init__(self):
  6462. # Python RTree Index
  6463. self.rti = rtindex.Index()
  6464. ## Track object-point relationship
  6465. # Each is list of points in object.
  6466. self.obj2points = []
  6467. # Index is index in rtree, value is index of
  6468. # object in obj2points.
  6469. self.points2obj = []
  6470. self.get_points = lambda go: go.coords
  6471. def grow_obj2points(self, idx):
  6472. """
  6473. Increases the size of self.obj2points to fit
  6474. idx + 1 items.
  6475. :param idx: Index to fit into list.
  6476. :return: None
  6477. """
  6478. if len(self.obj2points) > idx:
  6479. # len == 2, idx == 1, ok.
  6480. return
  6481. else:
  6482. # len == 2, idx == 2, need 1 more.
  6483. # range(2, 3)
  6484. for i in range(len(self.obj2points), idx + 1):
  6485. self.obj2points.append([])
  6486. def insert(self, objid, obj):
  6487. self.grow_obj2points(objid)
  6488. self.obj2points[objid] = []
  6489. for pt in self.get_points(obj):
  6490. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  6491. self.obj2points[objid].append(len(self.points2obj))
  6492. self.points2obj.append(objid)
  6493. def remove_obj(self, objid, obj):
  6494. # Use all ptids to delete from index
  6495. for i, pt in enumerate(self.get_points(obj)):
  6496. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  6497. def nearest(self, pt):
  6498. """
  6499. Will raise StopIteration if no items are found.
  6500. :param pt:
  6501. :return:
  6502. """
  6503. return next(self.rti.nearest(pt, objects=True))
  6504. class FlatCAMRTreeStorage(FlatCAMRTree):
  6505. """
  6506. Just like FlatCAMRTree it indexes geometry, but also serves
  6507. as storage for the geometry.
  6508. """
  6509. def __init__(self):
  6510. # super(FlatCAMRTreeStorage, self).__init__()
  6511. super().__init__()
  6512. self.objects = []
  6513. # Optimization attempt!
  6514. self.indexes = {}
  6515. def insert(self, obj):
  6516. self.objects.append(obj)
  6517. idx = len(self.objects) - 1
  6518. # Note: Shapely objects are not hashable any more, althought
  6519. # there seem to be plans to re-introduce the feature in
  6520. # version 2.0. For now, we will index using the object's id,
  6521. # but it's important to remember that shapely geometry is
  6522. # mutable, ie. it can be modified to a totally different shape
  6523. # and continue to have the same id.
  6524. # self.indexes[obj] = idx
  6525. self.indexes[id(obj)] = idx
  6526. # super(FlatCAMRTreeStorage, self).insert(idx, obj)
  6527. super().insert(idx, obj)
  6528. #@profile
  6529. def remove(self, obj):
  6530. # See note about self.indexes in insert().
  6531. # objidx = self.indexes[obj]
  6532. objidx = self.indexes[id(obj)]
  6533. # Remove from list
  6534. self.objects[objidx] = None
  6535. # Remove from index
  6536. self.remove_obj(objidx, obj)
  6537. def get_objects(self):
  6538. return (o for o in self.objects if o is not None)
  6539. def nearest(self, pt):
  6540. """
  6541. Returns the nearest matching points and the object
  6542. it belongs to.
  6543. :param pt: Query point.
  6544. :return: (match_x, match_y), Object owner of
  6545. matching point.
  6546. :rtype: tuple
  6547. """
  6548. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  6549. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  6550. # class myO:
  6551. # def __init__(self, coords):
  6552. # self.coords = coords
  6553. #
  6554. #
  6555. # def test_rti():
  6556. #
  6557. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  6558. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  6559. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  6560. #
  6561. # os = [o1, o2]
  6562. #
  6563. # idx = FlatCAMRTree()
  6564. #
  6565. # for o in range(len(os)):
  6566. # idx.insert(o, os[o])
  6567. #
  6568. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6569. #
  6570. # idx.remove_obj(0, o1)
  6571. #
  6572. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6573. #
  6574. # idx.remove_obj(1, o2)
  6575. #
  6576. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6577. #
  6578. #
  6579. # def test_rtis():
  6580. #
  6581. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  6582. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  6583. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  6584. #
  6585. # os = [o1, o2]
  6586. #
  6587. # idx = FlatCAMRTreeStorage()
  6588. #
  6589. # for o in range(len(os)):
  6590. # idx.insert(os[o])
  6591. #
  6592. # #os = None
  6593. # #o1 = None
  6594. # #o2 = None
  6595. #
  6596. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6597. #
  6598. # idx.remove(idx.nearest((2,0))[1])
  6599. #
  6600. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6601. #
  6602. # idx.remove(idx.nearest((0,0))[1])
  6603. #
  6604. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]