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