camlib.py 282 KB

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