camlib.py 332 KB

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