camlib.py 324 KB

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