camlib.py 323 KB

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