camlib.py 315 KB

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