mainwindow.cpp 329 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815
  1. //##########################################################################
  2. //# #
  3. //# CLOUDCOMPARE #
  4. //# #
  5. //# This program is free software; you can redistribute it and/or modify #
  6. //# it under the terms of the GNU General Public License as published by #
  7. //# the Free Software Foundation; version 2 or later of the License. #
  8. //# #
  9. //# This program is distributed in the hope that it will be useful, #
  10. //# but WITHOUT ANY WARRANTY; without even the implied warranty of #
  11. //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
  12. //# GNU General Public License for more details. #
  13. //# #
  14. //# COPYRIGHT: EDF R&D / TELECOM ParisTech (ENST-TSI) #
  15. //# #
  16. //##########################################################################
  17. #include "mainwindow.h"
  18. //CCCoreLib Includes
  19. #include <CloudSamplingTools.h>
  20. #include <Delaunay2dMesh.h>
  21. #include <Jacobi.h>
  22. #include <MeshSamplingTools.h>
  23. #include <NormalDistribution.h>
  24. #include <ParallelSort.h>
  25. #include <PointCloud.h>
  26. #include <ScalarFieldTools.h>
  27. #include <StatisticalTestingTools.h>
  28. #include <WeibullDistribution.h>
  29. //for tests
  30. #include <ChamferDistanceTransform.h>
  31. #include <SaitoSquaredDistanceTransform.h>
  32. //qCC_db
  33. #include <cc2DLabel.h>
  34. #include <cc2DViewportObject.h>
  35. #include <cc2DViewportLabel.h>
  36. #include <ccCameraSensor.h>
  37. #include <ccColorScalesManager.h>
  38. #include <ccCylinder.h>
  39. #include <ccFacet.h>
  40. #include <ccFileUtils.h>
  41. #include <ccGBLSensor.h>
  42. #include <ccImage.h>
  43. #include <ccKdTree.h>
  44. #include <ccPlane.h>
  45. #include <ccProgressDialog.h>
  46. #include <ccQuadric.h>
  47. #include <ccSphere.h>
  48. #include <ccSubMesh.h>
  49. //qCC_io
  50. #include <ccShiftAndScaleCloudDlg.h>
  51. #include <BinFilter.h>
  52. #include <AsciiFilter.h>
  53. #include <DepthMapFileFilter.h>
  54. //QCC_glWindow
  55. #include <ccGLWindowInterface.h>
  56. #include <ccRenderingTools.h>
  57. //local includes
  58. #include "ccConsole.h"
  59. #include "ccEntityAction.h"
  60. #include "ccHistogramWindow.h"
  61. #include "ccInnerRect2DFinder.h"
  62. //common
  63. #include <ccPickingHub.h>
  64. //common dialogs
  65. #include <ccCameraParamEditDlg.h>
  66. #include <ccDisplaySettingsDlg.h>
  67. #include <ccPickOneElementDlg.h>
  68. #include <ccStereoModeDlg.h>
  69. //dialogs
  70. #include "ccAboutDialog.h"
  71. #include "ccAdjustZoomDlg.h"
  72. #include "ccAlignDlg.h"
  73. #include "ccApplication.h"
  74. #include "ccApplyTransformationDlg.h"
  75. #include "ccAskThreeDoubleValuesDlg.h"
  76. #include "ccBoundingBoxEditorDlg.h"
  77. #include "ccCamSensorProjectionDlg.h"
  78. #include "ccClippingBoxTool.h"
  79. #include "ccColorFromScalarDlg.h"
  80. #include "ccColorScaleEditorDlg.h"
  81. #include "ccComparisonDlg.h"
  82. #include "ccPrimitiveDistanceDlg.h"
  83. #include "ccFilterByValueDlg.h"
  84. #include "ccGBLSensorProjectionDlg.h"
  85. #include "ccGeomFeaturesDlg.h"
  86. #include "ccGraphicalSegmentationTool.h"
  87. #include "ccGraphicalTransformationTool.h"
  88. #include "ccItemSelectionDlg.h"
  89. #include "ccLabelingDlg.h"
  90. #include "ccMatchScalesDlg.h"
  91. #include "ccNoiseFilterDlg.h"
  92. #include "ccOrderChoiceDlg.h"
  93. #include "ccPlaneEditDlg.h"
  94. #include "ccPointListPickingDlg.h"
  95. #include "ccPointPairRegistrationDlg.h"
  96. #include "ccPointPropertiesDlg.h"
  97. #include "ccPrimitiveFactoryDlg.h"
  98. #include "ccPtsSamplingDlg.h"
  99. #include "ccRasterizeTool.h"
  100. #include "ccRegistrationDlg.h"
  101. #include "ccRenderToFileDlg.h"
  102. #include "ccScaleDlg.h"
  103. #include "ccSectionExtractionTool.h"
  104. #include "ccSensorComputeDistancesDlg.h"
  105. #include "ccSensorComputeScatteringAnglesDlg.h"
  106. #include "ccSORFilterDlg.h"
  107. #include "ccSubsamplingDlg.h"
  108. #include "ccTracePolylineTool.h"
  109. #include "ccTranslationManager.h"
  110. #include "ccUnrollDlg.h"
  111. #include "ccVolumeCalcTool.h"
  112. #include "ccWaveformDialog.h"
  113. #include "ccEntitySelectionDlg.h"
  114. #include "ccSmoothPolylineDlg.h"
  115. //other
  116. #include "ccCropTool.h"
  117. #include "ccPersistentSettings.h"
  118. #include "ccRecentFiles.h"
  119. #include "ccRegistrationTools.h"
  120. #include "ccUtils.h"
  121. #include "db_tree/ccDBRoot.h"
  122. #include "pluginManager/ccPluginUIManager.h"
  123. #include "ccGlFilter.h"
  124. //3D mouse handler
  125. #ifdef CC_3DXWARE_SUPPORT
  126. #include "cc3DMouseManager.h"
  127. #endif
  128. //Gamepads
  129. #ifdef CC_GAMEPAD_SUPPORT
  130. #include "ccGamepadManager.h"
  131. #endif
  132. //Qt
  133. #include <QClipboard>
  134. #include <QGLShader>
  135. //Qt UI files
  136. #include <ui_distanceMapDlg.h>
  137. #include <ui_globalShiftSettingsDlg.h>
  138. #include <ui_mainWindow.h>
  139. //System
  140. #include <iostream>
  141. #include <random>
  142. //global static pointer (as there should only be one instance of MainWindow!)
  143. static MainWindow* s_instance = nullptr;
  144. //default file filter separator
  145. static const QString s_fileFilterSeparator(";;");
  146. enum PickingOperation { NO_PICKING_OPERATION,
  147. PICKING_ROTATION_CENTER,
  148. PICKING_LEVEL_POINTS,
  149. };
  150. static ccGLWindowInterface* s_pickingWindow = nullptr;
  151. static PickingOperation s_currentPickingOperation = NO_PICKING_OPERATION;
  152. static std::vector<cc2DLabel*> s_levelLabels;
  153. static ccPointCloud* s_levelMarkersCloud = nullptr;
  154. static ccHObject* s_levelEntity = nullptr;
  155. static QFileDialog::Options CCFileDialogOptions()
  156. {
  157. //dialog options
  158. QFileDialog::Options dialogOptions = QFileDialog::Options();
  159. dialogOptions |= QFileDialog::DontResolveSymlinks;
  160. if (!ccOptions::Instance().useNativeDialogs)
  161. {
  162. dialogOptions |= QFileDialog::DontUseNativeDialog;
  163. }
  164. return dialogOptions;
  165. }
  166. MainWindow::MainWindow()
  167. : m_UI( new Ui::MainWindow )
  168. , m_ccRoot(nullptr)
  169. , m_uiFrozen(false)
  170. , m_recentFiles(new ccRecentFiles(this))
  171. , m_3DMouseManager(nullptr)
  172. , m_gamepadManager(nullptr)
  173. , m_viewModePopupButton(nullptr)
  174. , m_pivotVisibilityPopupButton(nullptr)
  175. , m_firstShow(true)
  176. , m_pickingHub(nullptr)
  177. , m_cpeDlg(nullptr)
  178. , m_gsTool(nullptr)
  179. , m_tplTool(nullptr)
  180. , m_seTool(nullptr)
  181. , m_transTool(nullptr)
  182. , m_clipTool(nullptr)
  183. , m_compDlg(nullptr)
  184. , m_ppDlg(nullptr)
  185. , m_plpDlg(nullptr)
  186. , m_pprDlg(nullptr)
  187. , m_pfDlg(nullptr)
  188. {
  189. m_UI->setupUi( this );
  190. setWindowTitle(QStringLiteral("CloudCompare v") + ccApp->versionLongStr(false));
  191. m_pluginUIManager = new ccPluginUIManager( this, this );
  192. ccTranslationManager::Get().populateMenu( m_UI->menuLanguage, ccApp->translationPath() );
  193. #ifdef Q_OS_MAC
  194. m_UI->actionAbout->setMenuRole( QAction::AboutRole );
  195. m_UI->actionAboutPlugins->setMenuRole( QAction::ApplicationSpecificRole );
  196. m_UI->actionFullScreen->setText( tr( "Enter Full Screen" ) );
  197. m_UI->actionFullScreen->setShortcut( QKeySequence( Qt::CTRL + Qt::META + Qt::Key_F ) );
  198. #endif
  199. // Set up dynamic menus
  200. m_UI->menuFile->insertMenu(m_UI->actionSave, m_recentFiles->menu());
  201. //Console
  202. ccConsole::Init(m_UI->consoleWidget, this, this);
  203. m_UI->actionEnableQtWarnings->setChecked(ccConsole::QtMessagesEnabled());
  204. //advanced widgets not handled by QDesigner
  205. {
  206. //view mode pop-up menu
  207. {
  208. m_viewModePopupButton = new QToolButton();
  209. QMenu* menu = new QMenu(m_viewModePopupButton);
  210. menu->addAction(m_UI->actionSetOrthoView);
  211. menu->addAction(m_UI->actionSetCenteredPerspectiveView);
  212. menu->addAction(m_UI->actionSetViewerPerspectiveView);
  213. m_viewModePopupButton->setMenu(menu);
  214. m_viewModePopupButton->setPopupMode(QToolButton::InstantPopup);
  215. m_viewModePopupButton->setToolTip(tr("Set current view mode"));
  216. m_viewModePopupButton->setStatusTip(m_viewModePopupButton->toolTip());
  217. m_UI->toolBarView->insertWidget(m_UI->actionZoomAndCenter, m_viewModePopupButton);
  218. m_viewModePopupButton->setEnabled(false);
  219. }
  220. //pivot center pop-up menu
  221. {
  222. m_pivotVisibilityPopupButton = new QToolButton();
  223. QMenu* menu = new QMenu(m_pivotVisibilityPopupButton);
  224. menu->addAction(m_UI->actionSetPivotAlwaysOn);
  225. menu->addAction(m_UI->actionSetPivotRotationOnly);
  226. menu->addAction(m_UI->actionSetPivotOff);
  227. m_pivotVisibilityPopupButton->setMenu(menu);
  228. m_pivotVisibilityPopupButton->setPopupMode(QToolButton::InstantPopup);
  229. m_pivotVisibilityPopupButton->setToolTip(tr("Set pivot visibility"));
  230. m_pivotVisibilityPopupButton->setStatusTip(m_pivotVisibilityPopupButton->toolTip());
  231. m_UI->toolBarView->insertWidget(m_UI->actionZoomAndCenter,m_pivotVisibilityPopupButton);
  232. m_pivotVisibilityPopupButton->setEnabled(false);
  233. }
  234. }
  235. //tabifyDockWidget(DockableDBTree,DockableProperties);
  236. //db-tree
  237. {
  238. m_ccRoot = new ccDBRoot(m_UI->dbTreeView, m_UI->propertiesTreeView, this);
  239. connect(m_ccRoot, &ccDBRoot::selectionChanged, this, &MainWindow::updateUIWithSelection, Qt::QueuedConnection);
  240. connect(m_ccRoot, &ccDBRoot::dbIsEmpty, this, [=]() { updateUIWithSelection(); updateMenus(); }, Qt::QueuedConnection); //we don't call updateUI because there's no need to update the properties dialog
  241. connect(m_ccRoot, &ccDBRoot::dbIsNotEmptyAnymore, this, [=]() { updateUIWithSelection(); updateMenus(); }, Qt::QueuedConnection); //we don't call updateUI because there's no need to update the properties dialog
  242. }
  243. //MDI Area
  244. {
  245. m_mdiArea = new QMdiArea(this);
  246. setCentralWidget(m_mdiArea);
  247. connect(m_mdiArea, &QMdiArea::subWindowActivated, this, &MainWindow::updateMenus);
  248. connect(m_mdiArea, &QMdiArea::subWindowActivated, this, &MainWindow::on3DViewActivated);
  249. m_mdiArea->installEventFilter(this);
  250. }
  251. //picking hub
  252. {
  253. m_pickingHub = new ccPickingHub(this, this);
  254. connect(m_mdiArea, &QMdiArea::subWindowActivated, m_pickingHub, &ccPickingHub::onActiveWindowChanged);
  255. }
  256. // restore the state of the 'auto-restore' menu entry
  257. // (do that before connecting the actions)
  258. {
  259. QSettings settings;
  260. bool doNotAutoRestoreGeometry = settings.value(ccPS::DoNotRestoreWindowGeometry(), !m_UI->actionRestoreWindowOnStartup->isChecked()).toBool();
  261. m_UI->actionRestoreWindowOnStartup->setChecked(!doNotAutoRestoreGeometry);
  262. }
  263. connectActions();
  264. new3DView();
  265. setupInputDevices();
  266. freezeUI(false);
  267. updateUI();
  268. QMainWindow::statusBar()->showMessage(tr("Ready"));
  269. #ifdef CC_CORE_LIB_USES_TBB
  270. ccConsole::Print( QStringLiteral( "[TBB] Using Intel's Threading Building Blocks %1" )
  271. .arg( QString( TBB_VERSION ) ) );
  272. #endif
  273. ccConsole::Print(tr("CloudCompare started!"));
  274. }
  275. MainWindow::~MainWindow()
  276. {
  277. destroyInputDevices();
  278. cancelPreviousPickingOperation(false); //just in case
  279. assert(m_ccRoot && m_mdiArea);
  280. m_ccRoot->disconnect();
  281. m_mdiArea->disconnect();
  282. //we don't want any other dialog/function to use the following structures
  283. ccDBRoot* ccRoot = m_ccRoot;
  284. m_ccRoot = nullptr;
  285. //remove all entities from 3D views before quitting to avoid any side-effect
  286. //(this won't be done automatically since we've just reset m_ccRoot)
  287. ccRoot->getRootEntity()->setDisplay_recursive(nullptr);
  288. for (int i = 0; i < getGLWindowCount(); ++i)
  289. {
  290. getGLWindow(i)->setSceneDB(nullptr);
  291. }
  292. m_cpeDlg = nullptr;
  293. m_gsTool = nullptr;
  294. m_seTool = nullptr;
  295. m_transTool = nullptr;
  296. m_clipTool = nullptr;
  297. m_compDlg = nullptr;
  298. m_ppDlg = nullptr;
  299. m_plpDlg = nullptr;
  300. m_pprDlg = nullptr;
  301. m_pfDlg = nullptr;
  302. //release all 'overlay' dialogs
  303. while (!m_mdiDialogs.empty())
  304. {
  305. ccMDIDialogs mdiDialog = m_mdiDialogs.back();
  306. m_mdiDialogs.pop_back();
  307. mdiDialog.dialog->disconnect();
  308. mdiDialog.dialog->stop(false);
  309. mdiDialog.dialog->setParent(nullptr);
  310. delete mdiDialog.dialog;
  311. }
  312. //m_mdiDialogs.clear();
  313. m_mdiArea->closeAllSubWindows();
  314. if (ccRoot)
  315. {
  316. delete ccRoot;
  317. ccRoot = nullptr;
  318. }
  319. delete m_UI;
  320. m_UI = nullptr;
  321. ccConsole::ReleaseInstance(false); //if we flush the console, it will try to display the console window while we are destroying everything!
  322. }
  323. void MainWindow::initPlugins( )
  324. {
  325. m_pluginUIManager->init();
  326. // Set up dynamic tool bars
  327. addToolBar( Qt::RightToolBarArea, m_pluginUIManager->glFiltersToolbar() );
  328. addToolBar( Qt::RightToolBarArea, m_pluginUIManager->mainPluginToolbar() );
  329. for ( QToolBar *toolbar : m_pluginUIManager->additionalPluginToolbars() )
  330. {
  331. addToolBar( Qt::TopToolBarArea, toolbar );
  332. }
  333. // Set up dynamic menus
  334. m_UI->menubar->insertMenu( m_UI->menu3DViews->menuAction(), m_pluginUIManager->pluginMenu() );
  335. m_UI->menuDisplay->insertMenu( m_UI->menuActiveScalarField->menuAction(), m_pluginUIManager->shaderAndFilterMenu() );
  336. m_UI->menuToolbars->addAction( m_pluginUIManager->actionShowMainPluginToolbar() );
  337. m_UI->menuToolbars->addAction( m_pluginUIManager->actionShowGLFilterToolbar() );
  338. }
  339. void MainWindow::doEnableQtWarnings(bool state)
  340. {
  341. ccConsole::EnableQtMessages(state);
  342. }
  343. void MainWindow::increasePointSize()
  344. {
  345. //active window?
  346. ccGLWindowInterface* win = getActiveGLWindow();
  347. if (win)
  348. {
  349. win->setPointSize(win->getViewportParameters().defaultPointSize + 1);
  350. win->redraw();
  351. }
  352. }
  353. void MainWindow::decreasePointSize()
  354. {
  355. //active window?
  356. ccGLWindowInterface* win = getActiveGLWindow();
  357. if (win)
  358. {
  359. win->setPointSize(win->getViewportParameters().defaultPointSize - 1);
  360. win->redraw();
  361. }
  362. }
  363. void MainWindow::setupInputDevices()
  364. {
  365. #ifdef CC_3DXWARE_SUPPORT
  366. m_3DMouseManager = new cc3DMouseManager( this, this );
  367. m_UI->menuFile->insertMenu(m_UI->actionCloseAll, m_3DMouseManager->menu());
  368. #endif
  369. #ifdef CC_GAMEPAD_SUPPORT
  370. m_gamepadManager = new ccGamepadManager( this, this );
  371. m_UI->menuFile->insertMenu(m_UI->actionCloseAll, m_gamepadManager->menu());
  372. #endif
  373. #if defined(CC_3DXWARE_SUPPORT) || defined(CC_GAMEPAD_SUPPORT)
  374. m_UI->menuFile->insertSeparator(m_UI->actionCloseAll);
  375. #endif
  376. }
  377. void MainWindow::destroyInputDevices()
  378. {
  379. #ifdef CC_GAMEPAD_SUPPORT
  380. delete m_gamepadManager;
  381. m_gamepadManager = nullptr;
  382. #endif
  383. #ifdef CC_3DXWARE_SUPPORT
  384. delete m_3DMouseManager;
  385. m_3DMouseManager = nullptr;
  386. #endif
  387. }
  388. void MainWindow::connectActions()
  389. {
  390. assert(m_ccRoot);
  391. assert(m_mdiArea);
  392. //Keyboard shortcuts
  393. //'A': toggles selected items activation
  394. connect(m_UI->actionToggleActivation, &QAction::triggered, this, [=]() {
  395. toggleSelectedEntitiesProperty( ccEntityAction::TOGGLE_PROPERTY::ACTIVE );
  396. });
  397. //'V': toggles selected items visibility
  398. connect(m_UI->actionToggleVisibility, &QAction::triggered, this, [=]() {
  399. toggleSelectedEntitiesProperty( ccEntityAction::TOGGLE_PROPERTY::VISIBLE );
  400. });
  401. //'N': toggles selected items normals visibility
  402. connect(m_UI->actionToggleNormals, &QAction::triggered, this, [=]() {
  403. toggleSelectedEntitiesProperty( ccEntityAction::TOGGLE_PROPERTY::NORMALS );
  404. });
  405. //'C': toggles selected items colors visibility
  406. connect(m_UI->actionToggleColors, &QAction::triggered, this, [=]() {
  407. toggleSelectedEntitiesProperty( ccEntityAction::TOGGLE_PROPERTY::COLOR );
  408. });
  409. //'S': toggles selected items SF visibility
  410. connect(m_UI->actionToggleSF, &QAction::triggered, this, [=]() {
  411. toggleSelectedEntitiesProperty( ccEntityAction::TOGGLE_PROPERTY::SCALAR_FIELD );
  412. });
  413. //'D': toggles selected items '3D name' visibility
  414. connect(m_UI->actionToggleShowName, &QAction::triggered, this, [=]() {
  415. toggleSelectedEntitiesProperty( ccEntityAction::TOGGLE_PROPERTY::NAME );
  416. });
  417. //'M': toggles selected items materials/textures visibility
  418. connect(m_UI->actionToggleMaterials, &QAction::triggered, this, [=]() {
  419. toggleSelectedEntitiesProperty( ccEntityAction::TOGGLE_PROPERTY::MATERIAL );
  420. });
  421. //TODO... but not ready yet ;)
  422. m_UI->actionLoadShader->setVisible(false);
  423. m_UI->actionDeleteShader->setVisible(false);
  424. m_UI->actionKMeans->setVisible(false);
  425. m_UI->actionFrontPropagation->setVisible(false);
  426. /*** MAIN MENU ***/
  427. //"File" menu
  428. connect(m_UI->actionOpen, &QAction::triggered, this, &MainWindow::doActionLoadFile);
  429. connect(m_UI->actionSave, &QAction::triggered, this, &MainWindow::doActionSaveFile);
  430. connect(m_UI->actionSaveProject, &QAction::triggered, this, &MainWindow::doActionSaveProject);
  431. connect(m_UI->actionGlobalShiftSettings, &QAction::triggered, this, &MainWindow::doActionGlobalShiftSeetings);
  432. connect(m_UI->actionPrimitiveFactory, &QAction::triggered, this, &MainWindow::doShowPrimitiveFactory);
  433. connect(m_UI->actionCloseAll, &QAction::triggered, this, &MainWindow::closeAll);
  434. connect(m_UI->actionQuit, &QAction::triggered, this, &QWidget::close);
  435. //"Edit > Colors" menu
  436. connect(m_UI->actionSetUniqueColor, &QAction::triggered, this, &MainWindow::doActionSetUniqueColor);
  437. connect(m_UI->actionSetColorGradient, &QAction::triggered, this, &MainWindow::doActionSetColorGradient);
  438. connect(m_UI->actionChangeColorLevels, &QAction::triggered, this, &MainWindow::doActionChangeColorLevels);
  439. connect(m_UI->actionColorize, &QAction::triggered, this, &MainWindow::doActionColorize);
  440. connect(m_UI->actionRGBToGreyScale, &QAction::triggered, this, &MainWindow::doActionRGBToGreyScale);
  441. connect(m_UI->actionInterpolateColors, &QAction::triggered, this, &MainWindow::doActionInterpolateColors);
  442. connect(m_UI->actionEnhanceRGBWithIntensities, &QAction::triggered, this, &MainWindow::doActionEnhanceRGBWithIntensities);
  443. connect(m_UI->actionColorFromScalarField, &QAction::triggered, this, &MainWindow::doActionColorFromScalars);
  444. connect(m_UI->actionClearColor, &QAction::triggered, this, [=]() {
  445. clearSelectedEntitiesProperty( ccEntityAction::CLEAR_PROPERTY::COLORS );
  446. });
  447. connect(m_UI->actionRGBGaussianFilter, &QAction::triggered, this, &MainWindow::doActionRGBGaussianFilter);
  448. connect(m_UI->actionRGBBilateralFilter, &QAction::triggered, this, &MainWindow::doActionRGBBilateralFilter);
  449. connect(m_UI->actionRGBMeanFilter, &QAction::triggered, this, &MainWindow::doActionRGBMeanFilter);
  450. connect(m_UI->actionRGBMedianFilter, &QAction::triggered, this, &MainWindow::doActionRGBMedianFilter);
  451. //"Edit > Normals" menu
  452. connect(m_UI->actionComputeNormals, &QAction::triggered, this, &MainWindow::doActionComputeNormals);
  453. connect(m_UI->actionInvertNormals, &QAction::triggered, this, &MainWindow::doActionInvertNormals);
  454. connect(m_UI->actionConvertNormalToHSV, &QAction::triggered, this, &MainWindow::doActionConvertNormalsToHSV);
  455. connect(m_UI->actionConvertNormalToDipDir, &QAction::triggered, this, &MainWindow::doActionConvertNormalsToDipDir);
  456. connect(m_UI->actionExportNormalToSF, &QAction::triggered, this, &MainWindow::doActionExportNormalToSF);
  457. connect(m_UI->actionSetSFsAsNormal, &QAction::triggered, this, &MainWindow::doActionSetSFsAsNormal);
  458. connect(m_UI->actionOrientNormalsMST, &QAction::triggered, this, &MainWindow::doActionOrientNormalsMST);
  459. connect(m_UI->actionOrientNormalsFM, &QAction::triggered, this, &MainWindow::doActionOrientNormalsFM);
  460. connect(m_UI->actionShiftPointsAlongNormals, &QAction::triggered, this, &MainWindow::doActionShiftPointsAlongNormals);
  461. connect(m_UI->actionClearNormals, &QAction::triggered, this, [=]() {
  462. clearSelectedEntitiesProperty( ccEntityAction::CLEAR_PROPERTY::NORMALS );
  463. });
  464. //"Edit > Octree" menu
  465. connect(m_UI->actionComputeOctree, &QAction::triggered, this, &MainWindow::doActionComputeOctree);
  466. connect(m_UI->actionResampleWithOctree, &QAction::triggered, this, &MainWindow::doActionResampleWithOctree);
  467. //"Edit > Grid" menu
  468. connect(m_UI->actionDeleteScanGrid, &QAction::triggered, this, &MainWindow::doActionDeleteScanGrids);
  469. //"Edit > Cloud" menu
  470. connect(m_UI->actionCreateSinglePointCloud, &QAction::triggered, this, &MainWindow::createSinglePointCloud);
  471. connect(m_UI->actionPasteCloudFromClipboard, &QAction::triggered, this, &MainWindow::createPointCloudFromClipboard);
  472. //the 'Paste from clipboard' tool depends on the clipboard state
  473. {
  474. const QClipboard* clipboard = QApplication::clipboard();
  475. assert(clipboard);
  476. m_UI->actionPasteCloudFromClipboard->setEnabled(clipboard->mimeData()->hasText());
  477. connect(clipboard, &QClipboard::dataChanged, [&]() { m_UI->actionPasteCloudFromClipboard->setEnabled(clipboard->mimeData()->hasText()); });
  478. }
  479. //"Edit > Mesh" menu
  480. connect(m_UI->actionComputeMeshAA, &QAction::triggered, this, &MainWindow::doActionComputeMeshAA);
  481. connect(m_UI->actionComputeMeshLS, &QAction::triggered, this, &MainWindow::doActionComputeMeshLS);
  482. connect(m_UI->actionMeshTwoPolylines, &QAction::triggered, this, &MainWindow::doMeshTwoPolylines);
  483. connect(m_UI->actionMeshScanGrids, &QAction::triggered, this, &MainWindow::doActionMeshScanGrids);
  484. connect(m_UI->actionConvertTextureToColor, &QAction::triggered, this, &MainWindow::doActionConvertTextureToColor);
  485. connect(m_UI->actionSamplePointsOnMesh, &QAction::triggered, this, &MainWindow::doActionSamplePointsOnMesh);
  486. connect(m_UI->actionSmoothMeshLaplacian, &QAction::triggered, this, &MainWindow::doActionSmoothMeshLaplacian);
  487. connect(m_UI->actionSubdivideMesh, &QAction::triggered, this, &MainWindow::doActionSubdivideMesh);
  488. connect(m_UI->actionFlipMeshTriangles, &QAction::triggered, this, &MainWindow::doActionFlipMeshTriangles);
  489. connect(m_UI->actionMeasureMeshSurface, &QAction::triggered, this, &MainWindow::doActionMeasureMeshSurface);
  490. connect(m_UI->actionMeasureMeshVolume, &QAction::triggered, this, &MainWindow::doActionMeasureMeshVolume);
  491. connect(m_UI->actionFlagMeshVertices, &QAction::triggered, this, &MainWindow::doActionFlagMeshVertices);
  492. //"Edit > Mesh > Scalar Field" menu
  493. connect(m_UI->actionSmoothMeshSF, &QAction::triggered, this, &MainWindow::doActionSmoothMeshSF);
  494. connect(m_UI->actionEnhanceMeshSF, &QAction::triggered, this, &MainWindow::doActionEnhanceMeshSF);
  495. //"Edit > Polyline" menu
  496. connect(m_UI->actionSamplePointsOnPolyline, &QAction::triggered, this, &MainWindow::doActionSamplePointsOnPolyline);
  497. connect(m_UI->actionSmoothPolyline, &QAction::triggered, this, &MainWindow::doActionSmoohPolyline);
  498. //"Edit > Plane" menu
  499. connect(m_UI->actionCreatePlane, &QAction::triggered, this, &MainWindow::doActionCreatePlane);
  500. connect(m_UI->actionEditPlane, &QAction::triggered, this, &MainWindow::doActionEditPlane);
  501. connect(m_UI->actionFlipPlane, &QAction::triggered, this, &MainWindow::doActionFlipPlane);
  502. connect(m_UI->actionComparePlanes, &QAction::triggered, this, &MainWindow::doActionComparePlanes);
  503. //"Edit > Sensor > Ground-Based lidar" menu
  504. connect(m_UI->actionShowDepthBuffer, &QAction::triggered, this, &MainWindow::doActionShowDepthBuffer);
  505. connect(m_UI->actionExportDepthBuffer, &QAction::triggered, this, &MainWindow::doActionExportDepthBuffer);
  506. connect(m_UI->actionComputePointsVisibility, &QAction::triggered, this, &MainWindow::doActionComputePointsVisibility);
  507. //"Edit > Sensor" menu
  508. connect(m_UI->actionCreateGBLSensor, &QAction::triggered, this, &MainWindow::doActionCreateGBLSensor);
  509. connect(m_UI->actionCreateCameraSensor, &QAction::triggered, this, &MainWindow::doActionCreateCameraSensor);
  510. connect(m_UI->actionModifySensor, &QAction::triggered, this, &MainWindow::doActionModifySensor);
  511. connect(m_UI->actionProjectUncertainty, &QAction::triggered, this, &MainWindow::doActionProjectUncertainty);
  512. connect(m_UI->actionCheckPointsInsideFrustum, &QAction::triggered, this, &MainWindow::doActionCheckPointsInsideFrustum);
  513. connect(m_UI->actionComputeDistancesFromSensor, &QAction::triggered, this, &MainWindow::doActionComputeDistancesFromSensor);
  514. connect(m_UI->actionComputeScatteringAngles, &QAction::triggered, this, &MainWindow::doActionComputeScatteringAngles);
  515. connect(m_UI->actionViewFromSensor, &QAction::triggered, this, &MainWindow::doActionSetViewFromSensor);
  516. //"Edit > Scalar fields" menu
  517. connect(m_UI->actionShowHistogram, &QAction::triggered, this, &MainWindow::showSelectedEntitiesHistogram);
  518. connect(m_UI->actionComputeStatParams, &QAction::triggered, this, &MainWindow::doActionComputeStatParams);
  519. connect(m_UI->actionSFGradient, &QAction::triggered, this, &MainWindow::doActionSFGradient);
  520. connect(m_UI->actionGaussianFilter, &QAction::triggered, this, &MainWindow::doActionSFGaussianFilter);
  521. connect(m_UI->actionBilateralFilter, &QAction::triggered, this, &MainWindow::doActionSFBilateralFilter);
  522. connect(m_UI->actionFilterByValue, &QAction::triggered, this, &MainWindow::doActionFilterByValue);
  523. connect(m_UI->actionAddConstantSF, &QAction::triggered, this, &MainWindow::doActionAddConstantSF);
  524. connect(m_UI->actionAddClassificationSF, &QAction::triggered, this, &MainWindow::doActionAddClassificationSF);
  525. connect(m_UI->actionScalarFieldArithmetic, &QAction::triggered, this, &MainWindow::doActionScalarFieldArithmetic);
  526. connect(m_UI->actionScalarFieldFromColor, &QAction::triggered, this, &MainWindow::doActionScalarFieldFromColor);
  527. connect(m_UI->actionConvertToRGB, &QAction::triggered, this, &MainWindow::doActionSFConvertToRGB);
  528. connect(m_UI->actionConvertToRandomRGB, &QAction::triggered, this, &MainWindow::doActionSFConvertToRandomRGB);
  529. connect(m_UI->actionRenameSF, &QAction::triggered, this, &MainWindow::doActionRenameSF);
  530. connect(m_UI->actionOpenColorScalesManager, &QAction::triggered, this, &MainWindow::doActionOpenColorScalesManager);
  531. connect(m_UI->actionAddIdField, &QAction::triggered, this, &MainWindow::doActionAddIdField);
  532. connect(m_UI->actionSplitCloudUsingSF, &QAction::triggered, this, &MainWindow::doActionSplitCloudUsingSF);
  533. connect(m_UI->actionSetSFAsCoord, &QAction::triggered, this, &MainWindow::doActionSetSFAsCoord);
  534. connect(m_UI->actionInterpolateSFs, &QAction::triggered, this, &MainWindow::doActionInterpolateScalarFields);
  535. connect(m_UI->actionDeleteScalarField, &QAction::triggered, this, [=]() {
  536. clearSelectedEntitiesProperty( ccEntityAction::CLEAR_PROPERTY::CURRENT_SCALAR_FIELD );
  537. });
  538. connect(m_UI->actionDeleteAllSF, &QAction::triggered, this, [=]() {
  539. clearSelectedEntitiesProperty( ccEntityAction::CLEAR_PROPERTY::ALL_SCALAR_FIELDS );
  540. });
  541. //"Edit > Waveform" menu
  542. connect(m_UI->actionShowWaveDialog, &QAction::triggered, this, &MainWindow::doActionShowWaveDialog);
  543. connect(m_UI->actionCompressFWFData, &QAction::triggered, this, &MainWindow::doActionCompressFWFData);
  544. //"Edit" menu
  545. connect(m_UI->actionClone, &QAction::triggered, this, &MainWindow::doActionClone);
  546. connect(m_UI->actionMerge, &QAction::triggered, this, &MainWindow::doActionMerge);
  547. connect(m_UI->actionApplyTransformation, &QAction::triggered, this, &MainWindow::doActionApplyTransformation);
  548. connect(m_UI->actionApplyScale, &QAction::triggered, this, &MainWindow::doActionApplyScale);
  549. connect(m_UI->actionTranslateRotate, &QAction::triggered, this, &MainWindow::activateTranslateRotateMode);
  550. connect(m_UI->actionSegment, &QAction::triggered, this, &MainWindow::activateSegmentationMode);
  551. connect(m_UI->actionTracePolyline, &QAction::triggered, this, &MainWindow::activateTracePolylineMode);
  552. connect(m_UI->actionCrop, &QAction::triggered, this, &MainWindow::doActionCrop);
  553. connect(m_UI->actionEditGlobalShiftAndScale, &QAction::triggered, this, &MainWindow::doActionEditGlobalShiftAndScale);
  554. connect(m_UI->actionSubsample, &QAction::triggered, this, &MainWindow::doActionSubsample);
  555. connect(m_UI->actionDelete, &QAction::triggered, m_ccRoot, &ccDBRoot::deleteSelectedEntities);
  556. //"Tools > Clean" menu
  557. connect(m_UI->actionSORFilter, &QAction::triggered, this, &MainWindow::doActionSORFilter);
  558. connect(m_UI->actionNoiseFilter, &QAction::triggered, this, &MainWindow::doActionFilterNoise);
  559. //"Tools > Projection" menu
  560. connect(m_UI->actionUnroll, &QAction::triggered, this, &MainWindow::doActionUnroll);
  561. connect(m_UI->actionRasterize, &QAction::triggered, this, &MainWindow::doActionRasterize);
  562. connect(m_UI->actionConvertPolylinesToMesh, &QAction::triggered, this, &MainWindow::doConvertPolylinesToMesh);
  563. //connect(m_UI->actionCreateSurfaceBetweenTwoPolylines, &QAction::triggered, this, &MainWindow::doMeshTwoPolylines); //DGM: already connected to actionMeshTwoPolylines
  564. connect(m_UI->actionExportCoordToSF, &QAction::triggered, this, &MainWindow::doActionExportCoordToSF);
  565. //"Tools > Registration" menu
  566. connect(m_UI->actionMatchBBCenters, &QAction::triggered, this, &MainWindow::doActionMatchBBCenters);
  567. connect(m_UI->actionMatchScales, &QAction::triggered, this, &MainWindow::doActionMatchScales);
  568. connect(m_UI->actionRegister, &QAction::triggered, this, &MainWindow::doActionRegister);
  569. connect(m_UI->actionPointPairsAlign, &QAction::triggered, this, &MainWindow::activateRegisterPointPairTool);
  570. connect(m_UI->actionBBCenterToOrigin, &QAction::triggered, this, &MainWindow::doActionMoveBBCenterToOrigin);
  571. connect(m_UI->actionBBMinCornerToOrigin, &QAction::triggered, this, &MainWindow::doActionMoveBBMinCornerToOrigin);
  572. connect(m_UI->actionBBMaxCornerToOrigin, &QAction::triggered, this, &MainWindow::doActionMoveBBMaxCornerToOrigin);
  573. //"Tools > Distances" menu
  574. connect(m_UI->actionCloudCloudDist, &QAction::triggered, this, &MainWindow::doActionCloudCloudDist);
  575. connect(m_UI->actionCloudMeshDist, &QAction::triggered, this, &MainWindow::doActionCloudMeshDist);
  576. connect(m_UI->actionCloudPrimitiveDist, &QAction::triggered, this, &MainWindow::doActionCloudPrimitiveDist);
  577. connect(m_UI->actionCPS, &QAction::triggered, this, &MainWindow::doActionComputeCPS);
  578. //"Tools > Volume" menu
  579. connect(m_UI->actionCompute2HalfDimVolume, &QAction::triggered, this, &MainWindow::doCompute2HalfDimVolume);
  580. //"Tools > Statistics" menu
  581. connect(m_UI->actionComputeStatParams2, &QAction::triggered, this, &MainWindow::doActionComputeStatParams); //duplicated action --> we can't use the same otherwise we get an ugly console warning on Linux :(
  582. connect(m_UI->actionStatisticalTest, &QAction::triggered, this, &MainWindow::doActionStatisticalTest);
  583. //"Tools > Segmentation" menu
  584. connect(m_UI->actionLabelConnectedComponents, &QAction::triggered, this, &MainWindow::doActionLabelConnectedComponents);
  585. connect(m_UI->actionKMeans, &QAction::triggered, this, &MainWindow::doActionKMeans);
  586. connect(m_UI->actionFrontPropagation, &QAction::triggered, this, &MainWindow::doActionFrontPropagation);
  587. connect(m_UI->actionCrossSection, &QAction::triggered, this, &MainWindow::activateClippingBoxMode);
  588. connect(m_UI->actionExtractSections, &QAction::triggered, this, &MainWindow::activateSectionExtractionMode);
  589. //"Tools > Fit" menu
  590. connect(m_UI->actionFitPlane, &QAction::triggered, this, &MainWindow::doActionFitPlane);
  591. connect(m_UI->actionFitSphere, &QAction::triggered, this, &MainWindow::doActionFitSphere);
  592. connect(m_UI->actionFitCircle, &QAction::triggered, this, &MainWindow::doActionFitCircle);
  593. connect(m_UI->actionFitFacet, &QAction::triggered, this, &MainWindow::doActionFitFacet);
  594. connect(m_UI->actionFitQuadric, &QAction::triggered, this, &MainWindow::doActionFitQuadric);
  595. //"Tools > Batch export" menu
  596. connect(m_UI->actionExportCloudInfo, &QAction::triggered, this, &MainWindow::doActionExportCloudInfo);
  597. connect(m_UI->actionExportPlaneInfo, &QAction::triggered, this, &MainWindow::doActionExportPlaneInfo);
  598. //"Tools > Other" menu
  599. connect(m_UI->actionComputeGeometricFeature, &QAction::triggered, this, &MainWindow::doComputeGeometricFeature);
  600. connect(m_UI->actionRemoveDuplicatePoints, &QAction::triggered, this, &MainWindow::doRemoveDuplicatePoints);
  601. //"Tools"
  602. connect(m_UI->actionLevel, &QAction::triggered, this, &MainWindow::doLevel);
  603. connect(m_UI->actionPointListPicking, &QAction::triggered, this, &MainWindow::activatePointListPickingMode);
  604. connect(m_UI->actionPointPicking, &QAction::triggered, this, &MainWindow::activatePointPickingMode);
  605. //"Tools > Sand box (research)" menu
  606. connect(m_UI->actionComputeKdTree, &QAction::triggered, this, &MainWindow::doActionComputeKdTree);
  607. connect(m_UI->actionDistanceMap, &QAction::triggered, this, &MainWindow::doActionComputeDistanceMap);
  608. connect(m_UI->actionDistanceToBestFitQuadric3D, &QAction::triggered, this, &MainWindow::doActionComputeDistToBestFitQuadric3D);
  609. connect(m_UI->actionComputeBestFitBB, &QAction::triggered, this, &MainWindow::doComputeBestFitBB);
  610. connect(m_UI->actionAlign, &QAction::triggered, this, &MainWindow::doAction4pcsRegister); //Aurelien BEY le 13/11/2008
  611. connect(m_UI->actionSNETest, &QAction::triggered, this, &MainWindow::doSphericalNeighbourhoodExtractionTest);
  612. connect(m_UI->actionCNETest, &QAction::triggered, this, &MainWindow::doCylindricalNeighbourhoodExtractionTest);
  613. connect(m_UI->actionFindBiggestInnerRectangle, &QAction::triggered, this, &MainWindow::doActionFindBiggestInnerRectangle);
  614. connect(m_UI->actionCreateCloudFromEntCenters, &QAction::triggered, this, &MainWindow::doActionCreateCloudFromEntCenters);
  615. connect(m_UI->actionComputeBestICPRmsMatrix, &QAction::triggered, this, &MainWindow::doActionComputeBestICPRmsMatrix);
  616. //"Display" menu
  617. connect(m_UI->actionFullScreen, &QAction::toggled, this, &MainWindow::toggleFullScreen);
  618. connect(m_UI->actionExclusiveFullScreen, &QAction::toggled, this, &MainWindow::toggleExclusiveFullScreen);
  619. connect(m_UI->actionRefresh, &QAction::triggered, this, &MainWindow::refreshAll);
  620. connect(m_UI->actionTestFrameRate, &QAction::triggered, this, &MainWindow::testFrameRate);
  621. connect(m_UI->actionToggleCenteredPerspective, &QAction::triggered, this, &MainWindow::toggleActiveWindowCenteredPerspective);
  622. connect(m_UI->actionToggleViewerBasedPerspective, &QAction::triggered, this, &MainWindow::toggleActiveWindowViewerBasedPerspective);
  623. connect(m_UI->actionShowCursor3DCoordinates, &QAction::toggled, this, &MainWindow::toggleActiveWindowShowCursorCoords);
  624. connect(m_UI->actionLockRotationAxis, &QAction::triggered, this, &MainWindow::toggleLockRotationAxis);
  625. connect(m_UI->actionEnterBubbleViewMode, &QAction::triggered, this, &MainWindow::doActionEnableBubbleViewMode);
  626. connect(m_UI->actionEditCamera, &QAction::triggered, this, &MainWindow::doActionEditCamera);
  627. connect(m_UI->actionAdjustZoom, &QAction::triggered, this, &MainWindow::doActionAdjustZoom);
  628. connect(m_UI->actionSaveViewportAsObject, &QAction::triggered, this, &MainWindow::doActionSaveViewportAsCamera);
  629. //"Display > Lights & Materials" menu
  630. connect(m_UI->actionDisplaySettings, &QAction::triggered, this, &MainWindow::showDisplaySettings);
  631. connect(m_UI->actionToggleSunLight, &QAction::triggered, this, &MainWindow::toggleActiveWindowSunLight);
  632. connect(m_UI->actionToggleCustomLight, &QAction::triggered, this, &MainWindow::toggleActiveWindowCustomLight);
  633. connect(m_UI->actionRenderToFile, &QAction::triggered, this, &MainWindow::doActionRenderToFile);
  634. //"Display > Shaders & filters" menu
  635. connect(m_UI->actionLoadShader, &QAction::triggered, this, &MainWindow::doActionLoadShader);
  636. connect(m_UI->actionDeleteShader, &QAction::triggered, this, &MainWindow::doActionDeleteShader);
  637. //"Display > Active SF" menu
  638. connect(m_UI->actionToggleActiveSFColorScale, &QAction::triggered, this, &MainWindow::doActionToggleActiveSFColorScale);
  639. connect(m_UI->actionShowActiveSFPrevious, &QAction::triggered, this, &MainWindow::doActionShowActiveSFPrevious);
  640. connect(m_UI->actionShowActiveSFNext, &QAction::triggered, this, &MainWindow::doActionShowActiveSFNext);
  641. //"Display" menu
  642. connect(m_UI->actionResetGUIElementsPos, &QAction::triggered, this, &MainWindow::doActionResetGUIElementsPos);
  643. connect(m_UI->actionRestoreWindowOnStartup, &QAction::toggled, this, &MainWindow::doActionToggleRestoreWindowOnStartup);
  644. connect(m_UI->actionResetAllVBOs, &QAction::triggered, this, &MainWindow::doActionResetAllVBOs);
  645. //"3D Views" menu
  646. connect(m_UI->menu3DViews, &QMenu::aboutToShow, this, &MainWindow::update3DViewsMenu);
  647. connect(m_UI->actionNew3DView, &QAction::triggered, this, &MainWindow::new3DView);
  648. connect(m_UI->actionZoomIn, &QAction::triggered, this, &MainWindow::zoomIn);
  649. connect(m_UI->actionZoomOut, &QAction::triggered, this, &MainWindow::zoomOut);
  650. connect(m_UI->actionClose3DView, &QAction::triggered, m_mdiArea, &QMdiArea::closeActiveSubWindow);
  651. connect(m_UI->actionCloseAll3DViews, &QAction::triggered, m_mdiArea, &QMdiArea::closeAllSubWindows);
  652. connect(m_UI->actionTile3DViews, &QAction::triggered, m_mdiArea, &QMdiArea::tileSubWindows);
  653. connect(m_UI->actionCascade3DViews, &QAction::triggered, m_mdiArea, &QMdiArea::cascadeSubWindows);
  654. connect(m_UI->actionNext3DView, &QAction::triggered, m_mdiArea, &QMdiArea::activateNextSubWindow);
  655. connect(m_UI->actionPrevious3DView, &QAction::triggered, m_mdiArea, &QMdiArea::activatePreviousSubWindow);
  656. //"About" menu entry
  657. connect(m_UI->actionHelp, &QAction::triggered, this, &MainWindow::doActionShowHelpDialog);
  658. connect(m_UI->actionAboutPlugins, &QAction::triggered, m_pluginUIManager, &ccPluginUIManager::showAboutDialog);
  659. connect(m_UI->actionEnableQtWarnings, &QAction::toggled, this, &MainWindow::doEnableQtWarnings);
  660. connect(m_UI->actionAbout, &QAction::triggered, this, [this] () {
  661. ccAboutDialog* aboutDialog = new ccAboutDialog(this);
  662. aboutDialog->exec();
  663. });
  664. /*** Toolbars ***/
  665. //View toolbar
  666. connect(m_UI->actionGlobalZoom, &QAction::triggered, this, &MainWindow::setGlobalZoom);
  667. connect(m_UI->actionPickRotationCenter, &QAction::triggered, this, &MainWindow::doPickRotationCenter);
  668. connect(m_UI->actionZoomAndCenter, &QAction::triggered, this, &MainWindow::zoomOnSelectedEntities);
  669. connect(m_UI->actionSetPivotAlwaysOn, &QAction::triggered, this, &MainWindow::setPivotAlwaysOn);
  670. connect(m_UI->actionSetPivotRotationOnly, &QAction::triggered, this, &MainWindow::setPivotRotationOnly);
  671. connect(m_UI->actionSetPivotOff, &QAction::triggered, this, &MainWindow::setPivotOff);
  672. connect(m_UI->actionSetOrthoView, &QAction::triggered, this, [this] () {
  673. setOrthoView( getActiveGLWindow() );
  674. });
  675. connect(m_UI->actionSetCenteredPerspectiveView, &QAction::triggered, this, [this] () {
  676. setCenteredPerspectiveView( getActiveGLWindow() );
  677. });
  678. connect(m_UI->actionSetViewerPerspectiveView, &QAction::triggered, this, [this] () {
  679. setViewerPerspectiveView( getActiveGLWindow() );
  680. });
  681. connect(m_UI->actionEnableStereo, &QAction::toggled, this, &MainWindow::toggleActiveWindowStereoVision);
  682. connect(m_UI->actionAutoPickRotationCenter, &QAction::toggled, this, &MainWindow::toggleActiveWindowAutoPickRotCenter);
  683. connect(m_UI->actionSetViewTop, &QAction::triggered, this, [=]() { setView( CC_TOP_VIEW ); });
  684. connect(m_UI->actionSetViewBottom, &QAction::triggered, this, [=]() { setView( CC_BOTTOM_VIEW ); });
  685. connect(m_UI->actionSetViewFront, &QAction::triggered, this, [=]() { setView( CC_FRONT_VIEW ); });
  686. connect(m_UI->actionSetViewBack, &QAction::triggered, this, [=]() { setView( CC_BACK_VIEW ); });
  687. connect(m_UI->actionSetViewLeft, &QAction::triggered, this, [=]() { setView( CC_LEFT_VIEW ); });
  688. connect(m_UI->actionSetViewRight, &QAction::triggered, this, [=]() { setView( CC_RIGHT_VIEW ); });
  689. connect(m_UI->actionSetViewIso1, &QAction::triggered, this, [=]() { setView( CC_ISO_VIEW_1 ); });
  690. connect(m_UI->actionSetViewIso2, &QAction::triggered, this, [=]() { setView( CC_ISO_VIEW_2 ); });
  691. //hidden
  692. connect(m_UI->actionEnableVisualDebugTraces, &QAction::triggered, this, &MainWindow::toggleVisualDebugTraces);
  693. }
  694. void MainWindow::doActionColorize()
  695. {
  696. doActionSetColor(true);
  697. }
  698. void MainWindow::doActionSetUniqueColor()
  699. {
  700. doActionSetColor(false);
  701. }
  702. void MainWindow::doActionSetColor(bool colorize)
  703. {
  704. if ( !ccEntityAction::setColor(m_selectedEntities, colorize, this) )
  705. return;
  706. refreshAll();
  707. updateUI();
  708. }
  709. void MainWindow::doActionRGBToGreyScale()
  710. {
  711. if ( !ccEntityAction::rgbToGreyScale( m_selectedEntities ) )
  712. return;
  713. refreshAll();
  714. }
  715. void MainWindow::doActionSetColorGradient()
  716. {
  717. if ( !ccEntityAction::setColorGradient(m_selectedEntities, this) )
  718. return;
  719. refreshAll();
  720. updateUI();
  721. }
  722. void MainWindow::doActionChangeColorLevels()
  723. {
  724. ccEntityAction::changeColorLevels(m_selectedEntities, this);
  725. }
  726. void MainWindow::doActionInterpolateColors()
  727. {
  728. if ( !ccEntityAction::interpolateColors(m_selectedEntities, this) )
  729. return;
  730. refreshAll();
  731. updateUI();
  732. }
  733. void MainWindow::doActionInterpolateScalarFields()
  734. {
  735. if (!ccEntityAction::interpolateSFs(m_selectedEntities, this))
  736. return;
  737. refreshAll();
  738. updateUI();
  739. }
  740. void MainWindow::doActionEnhanceRGBWithIntensities()
  741. {
  742. if (!ccEntityAction::enhanceRGBWithIntensities(m_selectedEntities, this))
  743. return;
  744. refreshAll();
  745. }
  746. void MainWindow::doActionColorFromScalars()
  747. {
  748. for (ccHObject *entity : getSelectedEntities())
  749. {
  750. //for "real" point clouds only
  751. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(entity);
  752. if (cloud)
  753. {
  754. //create color from scalar dialogue
  755. ccColorFromScalarDlg* cfsDlg = new ccColorFromScalarDlg(this, cloud);
  756. cfsDlg->setAttribute(Qt::WA_DeleteOnClose, true);
  757. cfsDlg->show();
  758. }
  759. }
  760. }
  761. void MainWindow::doActionInvertNormals()
  762. {
  763. if ( !ccEntityAction::invertNormals(m_selectedEntities) )
  764. return;
  765. refreshAll();
  766. }
  767. void MainWindow::doActionConvertNormalsToDipDir()
  768. {
  769. if ( !ccEntityAction::convertNormalsTo( m_selectedEntities,
  770. ccEntityAction::NORMAL_CONVERSION_DEST::DIP_DIR_SFS) )
  771. {
  772. return;
  773. }
  774. refreshAll();
  775. updateUI();
  776. }
  777. void MainWindow::doActionConvertNormalsToHSV()
  778. {
  779. if ( !ccEntityAction::convertNormalsTo( m_selectedEntities,
  780. ccEntityAction::NORMAL_CONVERSION_DEST::HSV_COLORS) )
  781. {
  782. return;
  783. }
  784. refreshAll();
  785. updateUI();
  786. }
  787. static double s_kdTreeMaxErrorPerCell = 0.1;
  788. void MainWindow::doActionComputeKdTree()
  789. {
  790. ccGenericPointCloud* cloud = nullptr;
  791. if ( haveOneSelection() )
  792. {
  793. ccHObject* ent = m_selectedEntities.front();
  794. bool lockedVertices;
  795. cloud = ccHObjectCaster::ToGenericPointCloud(ent, &lockedVertices);
  796. if (lockedVertices)
  797. {
  798. ccUtils::DisplayLockedVerticesWarning(ent->getName(), true);
  799. return;
  800. }
  801. }
  802. if (!cloud)
  803. {
  804. ccLog::Error(tr("Selected one and only one point cloud or mesh!"));
  805. return;
  806. }
  807. bool ok;
  808. s_kdTreeMaxErrorPerCell = QInputDialog::getDouble(this, tr("Compute Kd-tree"), tr("Max error per leaf cell:"), s_kdTreeMaxErrorPerCell, 1.0e-6, 1.0e6, 6, &ok);
  809. if (!ok)
  810. return;
  811. ccProgressDialog pDlg(true, this);
  812. //computation
  813. QElapsedTimer eTimer;
  814. eTimer.start();
  815. ccKdTree* kdtree = new ccKdTree(cloud);
  816. if (kdtree->build(s_kdTreeMaxErrorPerCell, CCCoreLib::DistanceComputationTools::MAX_DIST_95_PERCENT, 4, 1000, &pDlg))
  817. {
  818. qint64 elapsedTime_ms = eTimer.elapsed();
  819. ccConsole::Print("[doActionComputeKdTree] Timing: %2.3f s", elapsedTime_ms / 1.0e3);
  820. cloud->setEnabled(true); //for mesh vertices!
  821. cloud->addChild(kdtree);
  822. kdtree->setDisplay(cloud->getDisplay());
  823. kdtree->setVisible(true);
  824. kdtree->prepareDisplayForRefresh();
  825. #ifdef QT_DEBUG
  826. kdtree->convertCellIndexToSF();
  827. #else
  828. kdtree->convertCellIndexToRandomColor();
  829. #endif
  830. addToDB(kdtree);
  831. refreshAll();
  832. updateUI();
  833. }
  834. else
  835. {
  836. ccLog::Error(tr("An error occurred"));
  837. delete kdtree;
  838. kdtree = nullptr;
  839. }
  840. }
  841. void MainWindow::doActionComputeOctree()
  842. {
  843. if ( !ccEntityAction::computeOctree(m_selectedEntities, this) )
  844. return;
  845. refreshAll();
  846. updateUI();
  847. }
  848. void MainWindow::doActionResampleWithOctree()
  849. {
  850. bool ok;
  851. int pointCount = QInputDialog::getInt(this, tr("Resample with octree"), tr("Points (approx.)"), 1000000, 1, INT_MAX, 100000, &ok);
  852. if (!ok)
  853. return;
  854. ccProgressDialog pDlg(false, this);
  855. pDlg.setAutoClose(false);
  856. assert(pointCount > 0);
  857. unsigned aimedPoints = static_cast<unsigned>(pointCount);
  858. bool errors = false;
  859. for ( ccHObject *entity : getSelectedEntities() )
  860. {
  861. ccPointCloud* cloud = nullptr;
  862. /*if (ent->isKindOf(CC_TYPES::MESH)) //TODO
  863. cloud = ccHObjectCaster::ToGenericMesh(ent)->getAssociatedCloud();
  864. else */
  865. if (entity->isKindOf(CC_TYPES::POINT_CLOUD))
  866. {
  867. cloud = static_cast<ccPointCloud*>(entity);
  868. }
  869. if (cloud)
  870. {
  871. ccOctree::Shared octree = cloud->getOctree();
  872. if (!octree)
  873. {
  874. octree = cloud->computeOctree(&pDlg);
  875. if (!octree)
  876. {
  877. ccConsole::Error(tr("Could not compute octree for cloud '%1'").arg(cloud->getName()));
  878. continue;
  879. }
  880. }
  881. cloud->setEnabled(false);
  882. QElapsedTimer eTimer;
  883. eTimer.start();
  884. CCCoreLib::GenericIndexedCloud* result = CCCoreLib::CloudSamplingTools::resampleCloudWithOctree
  885. (
  886. cloud,
  887. aimedPoints,
  888. CCCoreLib::CloudSamplingTools::CELL_GRAVITY_CENTER,
  889. &pDlg,
  890. octree.data()
  891. );
  892. if (result)
  893. {
  894. ccConsole::Print("[ResampleWithOctree] Timing: %3.2f s.", eTimer.elapsed() / 1.0e3);
  895. ccPointCloud* newCloud = ccPointCloud::From(result, cloud);
  896. delete result;
  897. result = nullptr;
  898. if (newCloud)
  899. {
  900. addToDB(newCloud);
  901. newCloud->setDisplay(cloud->getDisplay());
  902. newCloud->prepareDisplayForRefresh();
  903. }
  904. else
  905. {
  906. errors = true;
  907. }
  908. }
  909. }
  910. }
  911. if (errors)
  912. ccLog::Error(tr("[ResampleWithOctree] Errors occurred during the process, result may be incomplete"));
  913. refreshAll();
  914. }
  915. void MainWindow::doActionApplyTransformation()
  916. {
  917. ccApplyTransformationDlg dlg(this);
  918. if (!dlg.exec())
  919. return;
  920. bool applyToGlobal = false;
  921. ccGLMatrixd transMat = dlg.getTransformation(applyToGlobal);
  922. applyTransformation(transMat, applyToGlobal);
  923. }
  924. ccHObject::Container MainWindow::getTopLevelSelectedEntities() const
  925. {
  926. ccHObject::Container topLevelSelectedEntities;
  927. for (size_t i = 0; i < m_selectedEntities.size(); ++i)
  928. {
  929. ccHObject* entity = m_selectedEntities[i];
  930. bool hasParentsInselection = false;
  931. for (size_t j = 0; j < m_selectedEntities.size(); ++j)
  932. {
  933. if (i == j)
  934. continue;
  935. ccHObject* otherEntity = m_selectedEntities[j];
  936. if (otherEntity->isAncestorOf(entity))
  937. {
  938. hasParentsInselection = true;
  939. break;
  940. }
  941. }
  942. if (!hasParentsInselection)
  943. {
  944. topLevelSelectedEntities.push_back(entity);
  945. }
  946. }
  947. return topLevelSelectedEntities;
  948. }
  949. void MainWindow::applyTransformation(const ccGLMatrixd& mat, bool applyToGlobal)
  950. {
  951. //if the transformation is partly converted to global shift/scale
  952. bool autoApplyPreviousGlobalShiftAndScale = false;
  953. double previousScale = 1.0;
  954. CCVector3d previousShift(0, 0, 0);
  955. //we don't want any entity that would be the children of other selected entities
  956. ccHObject::Container selectedEntities = getTopLevelSelectedEntities();
  957. for (ccHObject* entity : selectedEntities) //warning, getSelectedEntites may change during this loop!
  958. {
  959. ccGLMatrixd transMat = mat;
  960. if (applyToGlobal && nullptr != dynamic_cast<ccShiftedObject*>(entity))
  961. {
  962. // the user wants to apply the transformation to the global coordinates
  963. ccShiftedObject* shiftedEntity = static_cast<ccShiftedObject*>(entity);
  964. CCVector3d globalShift = shiftedEntity->getGlobalShift();
  965. double globalScale = shiftedEntity->getGlobalScale();
  966. // we compute the impact to the local coordinate system without changing the
  967. // current Global Shift & Scale parameters (for now)
  968. // Here is the formula, assuming:
  969. // - the Global Shift is Ts
  970. // - the Global scale is Sc
  971. // - the transformation is (R, T)
  972. // - the Global point coordinates Pg are derived from the local ones Pl with: Pg = Pl/Sc - Ts
  973. // Therefore, Pg' = R * Pg + T
  974. // i.e. Pg' = R.(Pl/Sc - Ts) + T
  975. // i.e. Pg' = (R.Pl)/Sc - R.Ts + T
  976. // i.e. Pg' = (R.Pl)/Sc - R.Ts + T + Ts - Ts
  977. // i.e. Pg' = (R.Pl + Sc.[Ts - R.Ts + T])/Sc - Ts
  978. // i.e. Pl' = Sc.[Ts -R.Ts + T]
  979. // i.e. the translation of the 'local' coordinate system is: Sc.[T + Ts - R.Ts]
  980. CCVector3d rotatedGlobalShift = globalShift;
  981. mat.applyRotation(rotatedGlobalShift);
  982. CCVector3d localTranslation = globalScale * (globalShift - rotatedGlobalShift + mat.getTranslationAsVec3D());
  983. // we switch to a local transformation matrix
  984. transMat.setTranslation(localTranslation);
  985. }
  986. //we don't test primitives (it's always ok while the 'vertices lock' test would fail)
  987. if (!entity->isKindOf(CC_TYPES::PRIMITIVE))
  988. {
  989. //specific test for locked vertices
  990. bool lockedVertices;
  991. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(entity, &lockedVertices);
  992. if (cloud)
  993. {
  994. if (lockedVertices)
  995. {
  996. ccUtils::DisplayLockedVerticesWarning(entity->getName(), haveOneSelection());
  997. continue;
  998. }
  999. //test if the translated cloud coordinates were already "too large"
  1000. //(in which case we won't bother the user about the fact that the transformed cloud coordinates will be too large...)
  1001. ccBBox localBBox = entity->getOwnBB();
  1002. CCVector3d Pl = localBBox.minCorner();
  1003. double Dl = localBBox.getDiagNormd();
  1004. //if the cloud is alright
  1005. if ( !ccGlobalShiftManager::NeedShift(Pl)
  1006. && !ccGlobalShiftManager::NeedRescale(Dl) )
  1007. {
  1008. //test if the translated cloud (local) coordinates are too large
  1009. ccBBox transformedLocalBox = entity->getOwnBB() * transMat;
  1010. CCVector3d transformedPl = transformedLocalBox.minCorner();
  1011. double transformedDl = transformedLocalBox.getDiagNormd();
  1012. bool needShift = ccGlobalShiftManager::NeedShift(transformedPl) || ccGlobalShiftManager::NeedRescale(transformedDl);
  1013. if (needShift)
  1014. {
  1015. //existing shift information
  1016. CCVector3d globalShift = cloud->getGlobalShift();
  1017. double globalScale = cloud->getGlobalScale();
  1018. //we compute the global coordinates and scale of the reference point (= the min corner of the bounding-box)
  1019. CCVector3d Pg = cloud->toGlobal3d(transformedPl);
  1020. double Dg = transformedDl / globalScale;
  1021. //let's try to find better Global Shift and Scale values
  1022. CCVector3d newShift(0.0, 0.0, 0.0);
  1023. double newScale = 1.0;
  1024. bool updateShiftAndscale = false;
  1025. //should we try to use the previous Global Shift and Scale values?
  1026. if (autoApplyPreviousGlobalShiftAndScale)
  1027. {
  1028. if ( !ccGlobalShiftManager::NeedShift(Pg + previousShift)
  1029. && !ccGlobalShiftManager::NeedRescale(Dg * previousScale))
  1030. {
  1031. newScale = previousScale;
  1032. newShift = previousShift;
  1033. needShift = false;
  1034. updateShiftAndscale = true;
  1035. }
  1036. }
  1037. //if we still need to define new Global Shift and Scale
  1038. if (needShift)
  1039. {
  1040. //ask the user the right values!
  1041. ccShiftAndScaleCloudDlg sasDlg(transformedPl, transformedDl, Pg, Dg, this);
  1042. sasDlg.showApplyAllButton(selectedEntities.size() > 1);
  1043. sasDlg.showTitle(true);
  1044. sasDlg.setKeepGlobalPos(true);
  1045. sasDlg.showKeepGlobalPosCheckbox(false); //we don't want the user to mess with this!
  1046. sasDlg.showPreserveShiftOnSave(true);
  1047. //add "original" entry
  1048. int index = sasDlg.addShiftInfo(ccGlobalShiftManager::ShiftInfo(tr("Original"), globalShift, globalScale));
  1049. //add "previous" entry (if any)
  1050. if (autoApplyPreviousGlobalShiftAndScale)
  1051. {
  1052. index = sasDlg.addShiftInfo(ccGlobalShiftManager::ShiftInfo(tr("Previous"), previousShift, previousScale));
  1053. }
  1054. //add "last" entries (if any)
  1055. int matchingIndex = -1;
  1056. const auto& previousEntries = ccGlobalShiftManager::GetLast();
  1057. for (const ccGlobalShiftManager::ShiftInfo& shiftInfo : previousEntries)
  1058. {
  1059. index = sasDlg.addShiftInfo(shiftInfo);
  1060. if (matchingIndex < 0)
  1061. {
  1062. if ( !ccGlobalShiftManager::NeedShift(Pg + shiftInfo.shift)
  1063. && !ccGlobalShiftManager::NeedRescale(Dg * shiftInfo.scale) )
  1064. {
  1065. matchingIndex = index;
  1066. }
  1067. }
  1068. }
  1069. //if no good solution was found...
  1070. if (matchingIndex < 0)
  1071. {
  1072. //add a "suggested" entry
  1073. CCVector3d suggestedShift = ccGlobalShiftManager::BestShift(Pg);
  1074. double suggestedScale = ccGlobalShiftManager::BestScale(Dg);
  1075. matchingIndex = sasDlg.addShiftInfo(ccGlobalShiftManager::ShiftInfo(tr("Suggested"), suggestedShift, suggestedScale));
  1076. }
  1077. sasDlg.setCurrentProfile(matchingIndex);
  1078. if (sasDlg.exec())
  1079. {
  1080. newScale = sasDlg.getScale();
  1081. newShift = sasDlg.getShift();
  1082. needShift = false;
  1083. updateShiftAndscale = true;
  1084. //store the shift for next time!
  1085. ccGlobalShiftManager::StoreShift(newShift, newScale);
  1086. if (sasDlg.applyAll())
  1087. {
  1088. autoApplyPreviousGlobalShiftAndScale = true;
  1089. previousScale = newScale;
  1090. previousShift = newShift;
  1091. }
  1092. }
  1093. else if (sasDlg.cancelled())
  1094. {
  1095. ccLog::Warning(tr("[ApplyTransformation] Process cancelled by user"));
  1096. return;
  1097. }
  1098. else
  1099. {
  1100. // the user did not want to change the shift & scale
  1101. }
  1102. }
  1103. if (updateShiftAndscale)
  1104. {
  1105. assert(!needShift);
  1106. //get the relative modification to existing global shift/scale info
  1107. assert(globalScale != 0);
  1108. double scaleChange = newScale / globalScale;
  1109. CCVector3d shiftChange = newShift - globalShift;
  1110. if (scaleChange != 1.0 || shiftChange.norm2() != 0)
  1111. {
  1112. //apply translation as global shift
  1113. cloud->setGlobalShift(newShift);
  1114. cloud->setGlobalScale(newScale);
  1115. ccLog::Warning(tr("[ApplyTransformation] Cloud '%1' global shift/scale information has been updated: shift = (%2,%3,%4) / scale = %5").arg(cloud->getName()).arg(newShift.x).arg(newShift.y).arg(newShift.z).arg(newScale));
  1116. transMat.scaleRotation(scaleChange);
  1117. transMat.setTranslation(transMat.getTranslationAsVec3D() + newScale * shiftChange);
  1118. }
  1119. }
  1120. }
  1121. }
  1122. }
  1123. }
  1124. //we temporarily detach the entity, as it may undergo
  1125. //'severe' modifications (octree deletion, etc.) --> see ccHObject::applyRigidTransformation
  1126. ccHObjectContext objContext = removeObjectTemporarilyFromDBTree(entity);
  1127. entity->setGLTransformation(ccGLMatrix(transMat.data()));
  1128. //DGM FIXME: we only test the entity own bounding box (and we update its shift & scale info) but we apply the transformation to all its children?!
  1129. entity->applyGLTransformation_recursive();
  1130. entity->prepareDisplayForRefresh_recursive();
  1131. putObjectBackIntoDBTree(entity, objContext);
  1132. if (applyToGlobal)
  1133. {
  1134. ccLog::Print(tr("[ApplyTransformation] Transformation matrix applied to the local coordinates of %1:").arg(entity->getName()));
  1135. ccLog::Print(transMat.toString(12, ' ')); //full precision
  1136. }
  1137. }
  1138. if (!applyToGlobal)
  1139. {
  1140. ccLog::Print(tr("[ApplyTransformation] Applied transformation matrix:"));
  1141. }
  1142. else
  1143. {
  1144. ccLog::Print(tr("[ApplyTransformation] Global transformation matrix:"));
  1145. }
  1146. ccLog::Print(mat.toString(12, ' ')); //full precision
  1147. ccLog::Print(tr("Hint: you can copy a transformation matrix (CTRL+C) and apply it - or its inverse - to another entity with the 'Edit > Apply transformation' tool"));
  1148. //reselect previously selected entities!
  1149. if (m_ccRoot)
  1150. m_ccRoot->selectEntities(selectedEntities);
  1151. zoomOnSelectedEntities();
  1152. refreshAll();
  1153. }
  1154. void MainWindow::doActionApplyScale()
  1155. {
  1156. ccScaleDlg dlg(this);
  1157. if (!dlg.exec())
  1158. return;
  1159. dlg.saveState();
  1160. //save values for next time
  1161. CCVector3d scales = dlg.getScales();
  1162. bool keepInPlace = dlg.keepInPlace();
  1163. bool rescaleGlobalShift = dlg.rescaleGlobalShift();
  1164. //we must backup 'm_selectedEntities' as removeObjectTemporarilyFromDBTree can modify it!
  1165. ccHObject::Container selectedEntities = m_selectedEntities;
  1166. //first check that all coordinates are kept 'small'
  1167. std::vector< std::pair<ccHObject*, ccGenericPointCloud*> > candidates;
  1168. {
  1169. bool testBigCoordinates = true;
  1170. for (ccHObject *entity : selectedEntities) //warning, getSelectedEntites may change during this loop!
  1171. {
  1172. bool lockedVertices;
  1173. //try to get the underlying cloud (or the vertices set for a mesh)
  1174. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(entity, &lockedVertices);
  1175. //otherwise we can look if the selected entity is a polyline
  1176. if (!cloud && entity->isA(CC_TYPES::POLY_LINE))
  1177. {
  1178. cloud = dynamic_cast<ccGenericPointCloud*>(static_cast<ccPolyline*>(entity)->getAssociatedCloud());
  1179. if (!cloud || cloud->isAncestorOf(entity))
  1180. {
  1181. lockedVertices = true;
  1182. }
  1183. }
  1184. if (!cloud || !cloud->isKindOf(CC_TYPES::POINT_CLOUD))
  1185. {
  1186. ccLog::Warning(tr("[Apply scale] Entity '%1' can't be scaled this way").arg(entity->getName()));
  1187. continue;
  1188. }
  1189. if (lockedVertices)
  1190. {
  1191. ccUtils::DisplayLockedVerticesWarning(entity->getName(), haveOneSelection());
  1192. continue;
  1193. }
  1194. CCVector3 C(0, 0, 0);
  1195. if (keepInPlace)
  1196. {
  1197. C = cloud->getOwnBB().getCenter();
  1198. }
  1199. //we must check that the resulting cloud coordinates are not too big
  1200. if (testBigCoordinates)
  1201. {
  1202. ccBBox bbox = cloud->getOwnBB();
  1203. CCVector3 bbMin = bbox.minCorner();
  1204. CCVector3 bbMax = bbox.maxCorner();
  1205. double maxx = std::max(std::abs(bbMin.x), std::abs(bbMax.x));
  1206. double maxy = std::max(std::abs(bbMin.y), std::abs(bbMax.y));
  1207. double maxz = std::max(std::abs(bbMin.z), std::abs(bbMax.z));
  1208. const double maxCoord = ccGlobalShiftManager::MaxCoordinateAbsValue();
  1209. bool oldCoordsWereTooBig = ( maxx > maxCoord
  1210. || maxy > maxCoord
  1211. || maxz > maxCoord );
  1212. if (!oldCoordsWereTooBig)
  1213. {
  1214. maxx = std::max(std::abs((bbMin.x - C.x) * scales.x + C.x), std::abs((bbMax.x - C.x) * scales.x + C.x));
  1215. maxy = std::max(std::abs((bbMin.y - C.y) * scales.y + C.y), std::abs((bbMax.y - C.y) * scales.y + C.y));
  1216. maxz = std::max(std::abs((bbMin.z - C.z) * scales.z + C.z), std::abs((bbMax.z - C.z) * scales.z + C.z));
  1217. bool newCoordsAreTooBig = ( maxx > maxCoord
  1218. || maxy > maxCoord
  1219. || maxz > maxCoord );
  1220. if (newCoordsAreTooBig)
  1221. {
  1222. if (QMessageBox::question(
  1223. this,
  1224. tr("Big coordinates"),
  1225. tr("Resutling coordinates will be too big (original precision may be lost!). Proceed anyway?"),
  1226. QMessageBox::Yes,
  1227. QMessageBox::No) == QMessageBox::Yes)
  1228. {
  1229. //ok, we won't test anymore and proceed
  1230. testBigCoordinates = false;
  1231. }
  1232. else
  1233. {
  1234. //we stop the process
  1235. return;
  1236. }
  1237. }
  1238. }
  1239. }
  1240. assert(cloud);
  1241. candidates.emplace_back(entity, cloud);
  1242. }
  1243. }
  1244. if (candidates.empty())
  1245. {
  1246. ccConsole::Warning(tr("[Apply scale] No eligible entities (point clouds or meshes) were selected!"));
  1247. return;
  1248. }
  1249. //now do the real scaling work
  1250. {
  1251. for ( auto& candidate : candidates )
  1252. {
  1253. ccHObject* ent = candidate.first;
  1254. ccGenericPointCloud* cloud = candidate.second;
  1255. CCVector3 C(0, 0, 0);
  1256. if (keepInPlace)
  1257. {
  1258. C = cloud->getOwnBB().getCenter();
  1259. }
  1260. //we temporarily detach the entity, as it may undergo
  1261. //'severe' modifications (octree deletion, etc.) --> see ccPointCloud::scale
  1262. ccHObjectContext objContext = removeObjectTemporarilyFromDBTree(cloud);
  1263. cloud->scale( static_cast<PointCoordinateType>(scales.x),
  1264. static_cast<PointCoordinateType>(scales.y),
  1265. static_cast<PointCoordinateType>(scales.z),
  1266. C );
  1267. putObjectBackIntoDBTree(cloud, objContext);
  1268. cloud->prepareDisplayForRefresh_recursive();
  1269. //don't forget the 'global shift'!
  1270. //DGM: but not the global scale!
  1271. if (rescaleGlobalShift)
  1272. {
  1273. const CCVector3d& shift = cloud->getGlobalShift();
  1274. cloud->setGlobalShift( CCVector3d( shift.x*scales.x,
  1275. shift.y*scales.y,
  1276. shift.z*scales.z) );
  1277. }
  1278. //specific case for polyline vertices
  1279. if (cloud->getParent() && cloud->getParent()->isA(CC_TYPES::POLY_LINE))
  1280. {
  1281. ccPolyline* poly = static_cast<ccPolyline*>(cloud->getParent());
  1282. if (poly->getAssociatedCloud() == cloud)
  1283. {
  1284. poly->invalidateBoundingBox();
  1285. }
  1286. }
  1287. ent->prepareDisplayForRefresh_recursive();
  1288. }
  1289. }
  1290. //reselect previously selected entities!
  1291. if (m_ccRoot)
  1292. m_ccRoot->selectEntities(selectedEntities);
  1293. if (!keepInPlace)
  1294. zoomOnSelectedEntities();
  1295. refreshAll();
  1296. updateUI();
  1297. }
  1298. void MainWindow::doActionEditGlobalShiftAndScale()
  1299. {
  1300. //get the global shift/scale info and bounding box of all selected clouds
  1301. std::vector< std::pair<ccShiftedObject*, ccHObject*> > shiftedEntities;
  1302. CCVector3d Pl(0, 0, 0);
  1303. double Dl = 1.0;
  1304. CCVector3d Pg(0, 0, 0);
  1305. double Dg = 1.0;
  1306. //shift and scale (if unique)
  1307. CCVector3d shift(0, 0, 0);
  1308. double scale = 1.0;
  1309. {
  1310. bool uniqueShift = true;
  1311. bool uniqueScale = true;
  1312. ccBBox localBB;
  1313. //sadly we don't have a double-typed bounding box class yet ;)
  1314. CCVector3d globalBBmin(0, 0, 0);
  1315. CCVector3d globalBBmax(0, 0, 0);
  1316. for ( ccHObject *entity : getSelectedEntities() )
  1317. {
  1318. bool lockedVertices;
  1319. ccShiftedObject* shifted = ccHObjectCaster::ToShifted(entity, &lockedVertices);
  1320. if (!shifted)
  1321. {
  1322. continue;
  1323. }
  1324. //for (unlocked) entities only
  1325. if (lockedVertices)
  1326. {
  1327. //get the vertices
  1328. ccGenericPointCloud* vertices = nullptr;
  1329. //if it's a mesh
  1330. if (entity->isKindOf(CC_TYPES::MESH))
  1331. {
  1332. vertices = static_cast<ccGenericMesh*>(entity)->getAssociatedCloud();
  1333. }
  1334. else if (entity->isKindOf(CC_TYPES::POLY_LINE))
  1335. {
  1336. vertices = dynamic_cast<ccGenericPointCloud*>(static_cast<ccPolyline*>(entity)->getAssociatedCloud());
  1337. }
  1338. if (!vertices || !entity->isAncestorOf(vertices))
  1339. {
  1340. ccUtils::DisplayLockedVerticesWarning(entity->getName(), haveOneSelection());
  1341. continue;
  1342. }
  1343. entity = vertices;
  1344. }
  1345. CCVector3 Al = entity->getOwnBB().minCorner();
  1346. CCVector3 Bl = entity->getOwnBB().maxCorner();
  1347. CCVector3d Ag = shifted->toGlobal3d<PointCoordinateType>(Al);
  1348. CCVector3d Bg = shifted->toGlobal3d<PointCoordinateType>(Bl);
  1349. //update local BB
  1350. localBB.add(Al);
  1351. localBB.add(Bl);
  1352. //update global BB
  1353. if (shiftedEntities.empty())
  1354. {
  1355. globalBBmin = Ag;
  1356. globalBBmax = Bg;
  1357. shift = shifted->getGlobalShift();
  1358. uniqueScale = shifted->getGlobalScale();
  1359. }
  1360. else
  1361. {
  1362. globalBBmin = CCVector3d( std::min(globalBBmin.x, Ag.x),
  1363. std::min(globalBBmin.y, Ag.y),
  1364. std::min(globalBBmin.z, Ag.z) );
  1365. globalBBmax = CCVector3d( std::max(globalBBmax.x, Bg.x),
  1366. std::max(globalBBmax.y, Bg.y),
  1367. std::max(globalBBmax.z, Bg.z) );
  1368. if (uniqueShift)
  1369. {
  1370. uniqueShift = CCCoreLib::LessThanEpsilon((shifted->getGlobalShift() - shift).norm());
  1371. }
  1372. if (uniqueScale)
  1373. {
  1374. uniqueScale = CCCoreLib::LessThanEpsilon(std::abs(shifted->getGlobalScale() - scale));
  1375. }
  1376. }
  1377. shiftedEntities.emplace_back(shifted, entity);
  1378. }
  1379. Pg = globalBBmin;
  1380. Dg = (globalBBmax - globalBBmin).norm();
  1381. Pl = localBB.minCorner();
  1382. Dl = (localBB.maxCorner() - localBB.minCorner()).normd();
  1383. if (!uniqueShift)
  1384. shift = Pl - Pg;
  1385. if (!uniqueScale)
  1386. scale = Dg / Dl;
  1387. }
  1388. if (shiftedEntities.empty())
  1389. {
  1390. return;
  1391. }
  1392. ccShiftAndScaleCloudDlg sasDlg(Pl, Dl, Pg, Dg, this);
  1393. sasDlg.showApplyAllButton(shiftedEntities.size() > 1);
  1394. sasDlg.showApplyButton(shiftedEntities.size() == 1);
  1395. sasDlg.showNoButton(false);
  1396. sasDlg.setShiftFieldsPrecision(6);
  1397. //add "original" entry
  1398. int index = sasDlg.addShiftInfo(ccGlobalShiftManager::ShiftInfo(tr("Original"), shift, scale));
  1399. sasDlg.setCurrentProfile(index);
  1400. //add "last" entries (if any)
  1401. sasDlg.addShiftInfo(ccGlobalShiftManager::GetLast());
  1402. if (!sasDlg.exec())
  1403. return;
  1404. shift = sasDlg.getShift();
  1405. scale = sasDlg.getScale();
  1406. bool preserveGlobalPos = sasDlg.keepGlobalPos();
  1407. ccLog::Print(tr("[Global Shift/Scale] New shift: (%1, %2, %3)").arg(shift.x).arg(shift.y).arg(shift.z));
  1408. ccLog::Print(tr("[Global Shift/Scale] New scale: %1").arg(scale));
  1409. //apply new shift
  1410. {
  1411. for ( auto &entity : shiftedEntities )
  1412. {
  1413. ccShiftedObject* shifted = entity.first;
  1414. ccHObject* ent = entity.second;
  1415. if (preserveGlobalPos)
  1416. {
  1417. //to preserve the global position of the cloud, we may have to translate and/or rescale the cloud
  1418. CCVector3d Ql = ent->getOwnBB().minCorner();
  1419. CCVector3d Qg = shifted->toGlobal3d(Ql);
  1420. CCVector3d Ql2 = Qg * scale + shift;
  1421. CCVector3d T = Ql2 - Ql;
  1422. assert(shifted->getGlobalScale() > 0);
  1423. double scaleCoef = scale / shifted->getGlobalScale();
  1424. if ( CCCoreLib::GreaterThanEpsilon( T.norm() )
  1425. || CCCoreLib::GreaterThanEpsilon( std::abs(scaleCoef - 1.0) ) )
  1426. {
  1427. ccGLMatrix transMat;
  1428. transMat.toIdentity();
  1429. transMat.scaleRotation(static_cast<float>(scaleCoef));
  1430. transMat.setTranslation(T);
  1431. //DGM FIXME: we only test the entity own bounding box (and we update its shift & scale info) but we apply the transformation to all its children?!
  1432. ent->applyGLTransformation_recursive(&transMat);
  1433. ent->prepareDisplayForRefresh_recursive();
  1434. ccLog::Warning(tr("[Global Shift/Scale] To preserve its original position, the entity '%1' has been translated of (%2 ; %3 ; %4) and rescaled of a factor %5")
  1435. .arg(ent->getName())
  1436. .arg(T.x)
  1437. .arg(T.y)
  1438. .arg(T.z)
  1439. .arg(scaleCoef));
  1440. }
  1441. }
  1442. shifted->setGlobalShift(shift);
  1443. shifted->setGlobalScale(scale);
  1444. }
  1445. }
  1446. refreshAll();
  1447. updateUI();
  1448. }
  1449. void MainWindow::doComputeBestFitBB()
  1450. {
  1451. if (QMessageBox::warning( this,
  1452. tr("This method is for test purpose only"),
  1453. tr("Cloud(s) are going to be rotated while still displayed in their previous position! Proceed?"),
  1454. QMessageBox::Yes | QMessageBox::No,
  1455. QMessageBox::No ) != QMessageBox::Yes)
  1456. {
  1457. return;
  1458. }
  1459. //backup selected entities as removeObjectTemporarilyFromDBTree can modify them
  1460. ccHObject::Container selectedEntities = getSelectedEntities();
  1461. for (ccHObject *entity : selectedEntities) //warning, getSelectedEntites may change during this loop!
  1462. {
  1463. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(entity);
  1464. if (cloud && cloud->isA(CC_TYPES::POINT_CLOUD)) // TODO
  1465. {
  1466. CCCoreLib::Neighbourhood Yk(cloud);
  1467. CCCoreLib::SquareMatrixd covMat = Yk.computeCovarianceMatrix();
  1468. if (covMat.isValid())
  1469. {
  1470. CCCoreLib::SquareMatrixd eigVectors;
  1471. std::vector<double> eigValues;
  1472. if (CCCoreLib::Jacobi<double>::ComputeEigenValuesAndVectors(covMat, eigVectors, eigValues, true))
  1473. {
  1474. CCCoreLib::Jacobi<double>::SortEigenValuesAndVectors(eigVectors, eigValues);
  1475. ccGLMatrix trans;
  1476. GLfloat* rotMat = trans.data();
  1477. for (unsigned j = 0; j < 3; ++j)
  1478. {
  1479. double u[3];
  1480. CCCoreLib::Jacobi<double>::GetEigenVector(eigVectors, j, u);
  1481. CCVector3 v(static_cast<PointCoordinateType>(u[0]),
  1482. static_cast<PointCoordinateType>(u[1]),
  1483. static_cast<PointCoordinateType>(u[2]));
  1484. v.normalize();
  1485. rotMat[j*4] = static_cast<float>(v.x);
  1486. rotMat[j*4+1] = static_cast<float>(v.y);
  1487. rotMat[j*4+2] = static_cast<float>(v.z);
  1488. }
  1489. const CCVector3* G = Yk.getGravityCenter();
  1490. assert(G);
  1491. trans.shiftRotationCenter(*G);
  1492. cloud->setGLTransformation(trans);
  1493. trans.invert();
  1494. //we temporarily detach the entity, as it may undergo
  1495. //'severe' modifications (octree deletion, etc.) --> see ccPointCloud::applyRigidTransformation
  1496. ccHObjectContext objContext = removeObjectTemporarilyFromDBTree(cloud);
  1497. static_cast<ccPointCloud*>(cloud)->applyRigidTransformation(trans);
  1498. putObjectBackIntoDBTree(cloud,objContext);
  1499. entity->prepareDisplayForRefresh_recursive();
  1500. }
  1501. }
  1502. }
  1503. }
  1504. refreshAll();
  1505. }
  1506. void MainWindow::doActionFlagMeshVertices()
  1507. {
  1508. bool errors = false;
  1509. bool success = false;
  1510. for ( ccHObject *entity : getSelectedEntities() )
  1511. {
  1512. if (entity->isKindOf(CC_TYPES::MESH))
  1513. {
  1514. ccGenericMesh* mesh = ccHObjectCaster::ToGenericMesh(entity);
  1515. ccPointCloud* vertices = ccHObjectCaster::ToPointCloud(mesh ? mesh->getAssociatedCloud() : nullptr);
  1516. if (mesh && vertices)
  1517. {
  1518. //prepare a new scalar field
  1519. int sfIdx = vertices->getScalarFieldIndexByName(CC_DEFAULT_MESH_VERT_FLAGS_SF_NAME);
  1520. if (sfIdx < 0)
  1521. {
  1522. sfIdx = vertices->addScalarField(CC_DEFAULT_MESH_VERT_FLAGS_SF_NAME);
  1523. if (sfIdx < 0)
  1524. {
  1525. ccConsole::Warning(tr("Not enough memory to flag the vertices of mesh '%1'!").arg(mesh->getName()));
  1526. errors = true;
  1527. continue;
  1528. }
  1529. }
  1530. CCCoreLib::ScalarField* flags = vertices->getScalarField(sfIdx);
  1531. CCCoreLib::MeshSamplingTools::EdgeConnectivityStats stats;
  1532. if (CCCoreLib::MeshSamplingTools::flagMeshVerticesByType(mesh,flags,&stats))
  1533. {
  1534. vertices->setCurrentDisplayedScalarField(sfIdx);
  1535. ccScalarField* sf = vertices->getCurrentDisplayedScalarField();
  1536. if (sf)
  1537. {
  1538. sf->setColorScale(ccColorScalesManager::GetDefaultScale(ccColorScalesManager::VERTEX_QUALITY));
  1539. //sf->setColorRampSteps(3); //ugly :(
  1540. }
  1541. vertices->showSF(true);
  1542. mesh->showSF(true);
  1543. mesh->prepareDisplayForRefresh_recursive();
  1544. success = true;
  1545. //display stats in the Console as well
  1546. ccConsole::Print(tr("[Mesh Quality] Mesh '%1' edges: %2 total (normal: %3 / on hole borders: %4 / non-manifold: %5)").arg(entity->getName()).arg(stats.edgesCount).arg(stats.edgesSharedByTwo).arg(stats.edgesNotShared).arg(stats.edgesSharedByMore));
  1547. }
  1548. else
  1549. {
  1550. vertices->deleteScalarField(sfIdx);
  1551. sfIdx = -1;
  1552. ccConsole::Warning(tr("Not enough memory to flag the vertices of mesh '%1'!").arg(mesh->getName()));
  1553. errors = true;
  1554. }
  1555. }
  1556. else
  1557. {
  1558. assert(false);
  1559. }
  1560. }
  1561. }
  1562. refreshAll();
  1563. updateUI();
  1564. if (success)
  1565. {
  1566. //display reminder
  1567. forceConsoleDisplay();
  1568. ccConsole::Print(tr("[Mesh Quality] SF flags: %1 (NORMAL) / %2 (BORDER) / (%3) NON-MANIFOLD").arg(CCCoreLib::MeshSamplingTools::VERTEX_NORMAL).arg(CCCoreLib::MeshSamplingTools::VERTEX_BORDER).arg(CCCoreLib::MeshSamplingTools::VERTEX_NON_MANIFOLD));
  1569. }
  1570. if (errors)
  1571. {
  1572. ccConsole::Error(tr("Error(s) occurred! Check the console..."));
  1573. }
  1574. }
  1575. void MainWindow::doActionMeasureMeshVolume()
  1576. {
  1577. for ( ccHObject *entity : getSelectedEntities() )
  1578. {
  1579. if (entity->isKindOf(CC_TYPES::MESH))
  1580. {
  1581. ccMesh* mesh = ccHObjectCaster::ToMesh(entity);
  1582. if (mesh)
  1583. {
  1584. //we compute the mesh volume
  1585. double V = CCCoreLib::MeshSamplingTools::computeMeshVolume(mesh);
  1586. //we force the console to display itself
  1587. forceConsoleDisplay();
  1588. ccConsole::Print(tr("[Mesh Volume] Mesh '%1': V=%2 (cube units)").arg(entity->getName()).arg(V));
  1589. //check that the mesh is closed
  1590. CCCoreLib::MeshSamplingTools::EdgeConnectivityStats stats;
  1591. if (CCCoreLib::MeshSamplingTools::computeMeshEdgesConnectivity(mesh, stats))
  1592. {
  1593. if (stats.edgesNotShared != 0)
  1594. {
  1595. ccConsole::Warning(tr("[Mesh Volume] The above volume might be invalid (mesh has holes)"));
  1596. }
  1597. else if (stats.edgesSharedByMore != 0)
  1598. {
  1599. ccConsole::Warning(tr("[Mesh Volume] The above volume might be invalid (mesh has non-manifold edges)"));
  1600. }
  1601. }
  1602. else
  1603. {
  1604. ccConsole::Warning(tr("[Mesh Volume] The above volume might be invalid (not enough memory to check if the mesh is closed)"));
  1605. }
  1606. }
  1607. else
  1608. {
  1609. assert(false);
  1610. }
  1611. }
  1612. }
  1613. }
  1614. void MainWindow::doActionMeasureMeshSurface()
  1615. {
  1616. for ( ccHObject *entity : getSelectedEntities() )
  1617. {
  1618. if (entity->isKindOf(CC_TYPES::MESH))
  1619. {
  1620. ccGenericMesh* mesh = ccHObjectCaster::ToGenericMesh(entity);
  1621. if (mesh)
  1622. {
  1623. double S = CCCoreLib::MeshSamplingTools::computeMeshArea(mesh);
  1624. //we force the console to display itself
  1625. forceConsoleDisplay();
  1626. ccConsole::Print(tr("[Mesh Surface] Mesh '%1': S=%2 (square units)").arg(entity->getName()).arg(S));
  1627. if (mesh->size())
  1628. {
  1629. ccConsole::Print(tr("[Mesh Surface] Average triangle surface: %1 (square units)").arg(S / double(mesh->size())));
  1630. }
  1631. }
  1632. else
  1633. {
  1634. assert(false);
  1635. }
  1636. }
  1637. }
  1638. }
  1639. void MainWindow::doActionComputeDistancesFromSensor()
  1640. {
  1641. //we support more than just one sensor in selection
  1642. if (!haveSelection())
  1643. {
  1644. ccConsole::Error(tr("Select at least one sensor"));
  1645. return;
  1646. }
  1647. //start dialog
  1648. ccSensorComputeDistancesDlg cdDlg(this);
  1649. if (!cdDlg.exec())
  1650. return;
  1651. for ( ccHObject *entity : getSelectedEntities() )
  1652. {
  1653. ccSensor* sensor = ccHObjectCaster::ToSensor( entity );
  1654. assert(sensor);
  1655. if (!sensor)
  1656. continue; //skip this entity
  1657. //get associated cloud
  1658. ccHObject* defaultCloud = sensor->getParent() && sensor->getParent()->isA(CC_TYPES::POINT_CLOUD) ? sensor->getParent() : nullptr;
  1659. ccPointCloud* cloud = askUserToSelectACloud(defaultCloud, tr("Select a cloud on which to project the uncertainty:"));
  1660. if (!cloud)
  1661. {
  1662. return;
  1663. }
  1664. //sensor center
  1665. CCVector3 sensorCenter;
  1666. if (!sensor->getActiveAbsoluteCenter(sensorCenter))
  1667. return;
  1668. //squared required?
  1669. bool squared = cdDlg.computeSquaredDistances();
  1670. //set up a new scalar field
  1671. const char* defaultRangesSFname = squared ? CC_DEFAULT_SQUARED_RANGES_SF_NAME : CC_DEFAULT_RANGES_SF_NAME;
  1672. int sfIdx = cloud->getScalarFieldIndexByName(defaultRangesSFname);
  1673. if (sfIdx < 0)
  1674. {
  1675. sfIdx = cloud->addScalarField(defaultRangesSFname);
  1676. if (sfIdx < 0)
  1677. {
  1678. ccConsole::Error(tr("Not enough memory!"));
  1679. return;
  1680. }
  1681. }
  1682. CCCoreLib::ScalarField* distances = cloud->getScalarField(sfIdx);
  1683. for (unsigned i = 0; i < cloud->size(); ++i)
  1684. {
  1685. const CCVector3* P = cloud->getPoint(i);
  1686. ScalarType s = static_cast<ScalarType>(squared ? (*P-sensorCenter).norm2() : (*P-sensorCenter).norm());
  1687. distances->setValue(i, s);
  1688. }
  1689. distances->computeMinAndMax();
  1690. cloud->setCurrentDisplayedScalarField(sfIdx);
  1691. cloud->showSF(true);
  1692. cloud->prepareDisplayForRefresh_recursive();
  1693. }
  1694. refreshAll();
  1695. updateUI();
  1696. }
  1697. void MainWindow::doActionComputeScatteringAngles()
  1698. {
  1699. //there should be only one sensor in current selection!
  1700. if (!haveOneSelection() || !m_selectedEntities.front()->isKindOf(CC_TYPES::GBL_SENSOR))
  1701. {
  1702. ccConsole::Error(tr("Select one and only one GBL sensor!"));
  1703. return;
  1704. }
  1705. ccSensor* sensor = ccHObjectCaster::ToSensor(m_selectedEntities.front());
  1706. assert(sensor);
  1707. //sensor center
  1708. CCVector3 sensorCenter;
  1709. if (!sensor->getActiveAbsoluteCenter(sensorCenter))
  1710. return;
  1711. //get associated cloud
  1712. ccHObject* defaultCloud = sensor->getParent() && sensor->getParent()->isA(CC_TYPES::POINT_CLOUD) ? sensor->getParent() : nullptr;
  1713. ccPointCloud* cloud = askUserToSelectACloud(defaultCloud, tr("Select a cloud on which to project the uncertainty:"));
  1714. if (!cloud)
  1715. {
  1716. return;
  1717. }
  1718. if (!cloud->hasNormals())
  1719. {
  1720. ccConsole::Error(tr("The cloud must have normals!"));
  1721. return;
  1722. }
  1723. ccSensorComputeScatteringAnglesDlg cdDlg(this);
  1724. if (!cdDlg.exec())
  1725. return;
  1726. bool toDegreeFlag = cdDlg.anglesInDegrees();
  1727. //prepare a new scalar field
  1728. const char* defaultScatAnglesSFname = toDegreeFlag ? CC_DEFAULT_DEG_SCATTERING_ANGLES_SF_NAME : CC_DEFAULT_RAD_SCATTERING_ANGLES_SF_NAME;
  1729. int sfIdx = cloud->getScalarFieldIndexByName(defaultScatAnglesSFname);
  1730. if (sfIdx < 0)
  1731. {
  1732. sfIdx = cloud->addScalarField(defaultScatAnglesSFname);
  1733. if (sfIdx < 0)
  1734. {
  1735. ccConsole::Error(tr("Not enough memory!"));
  1736. return;
  1737. }
  1738. }
  1739. CCCoreLib::ScalarField* angles = cloud->getScalarField(sfIdx);
  1740. //perform computations
  1741. for (unsigned i = 0; i < cloud->size(); ++i)
  1742. {
  1743. //the point position
  1744. const CCVector3* P = cloud->getPoint(i);
  1745. //build the ray
  1746. CCVector3 ray = *P - sensorCenter;
  1747. ray.normalize();
  1748. //get the current normal
  1749. CCVector3 normal(cloud->getPointNormal(i));
  1750. //normal.normalize(); //should already be the case!
  1751. //compute the angle
  1752. PointCoordinateType cosTheta = ray.dot(normal);
  1753. ScalarType theta = std::acos(std::min(std::abs(cosTheta), 1.0f));
  1754. if (toDegreeFlag)
  1755. {
  1756. theta = CCCoreLib::RadiansToDegrees( theta );
  1757. }
  1758. angles->setValue(i,theta);
  1759. }
  1760. angles->computeMinAndMax();
  1761. cloud->setCurrentDisplayedScalarField(sfIdx);
  1762. cloud->showSF(true);
  1763. cloud->prepareDisplayForRefresh_recursive();
  1764. refreshAll();
  1765. updateUI();
  1766. }
  1767. void MainWindow::doActionSetViewFromSensor()
  1768. {
  1769. //there should be only one sensor in current selection!
  1770. if (!haveOneSelection() || !m_selectedEntities.front()->isKindOf(CC_TYPES::SENSOR))
  1771. {
  1772. ccConsole::Error(tr("Select one and only one sensor!"));
  1773. return;
  1774. }
  1775. ccSensor* sensor = ccHObjectCaster::ToSensor(m_selectedEntities.front());
  1776. assert(sensor);
  1777. //try to find the associated window
  1778. ccGenericGLDisplay* win = sensor->getDisplay();
  1779. if (!win)
  1780. {
  1781. //get associated cloud
  1782. ccPointCloud * cloud = ccHObjectCaster::ToPointCloud(sensor->getParent());
  1783. if (cloud)
  1784. win = cloud->getDisplay();
  1785. }
  1786. if (sensor->applyViewport(win))
  1787. {
  1788. ccConsole::Print(tr("[DoActionSetViewFromSensor] Viewport applied"));
  1789. }
  1790. }
  1791. void MainWindow::doActionCreateGBLSensor()
  1792. {
  1793. ccGBLSensorProjectionDlg spDlg(this);
  1794. spDlg.initWithPrevious();
  1795. if (!spDlg.exec())
  1796. return;
  1797. spDlg.saveForNextTime();
  1798. //We create the corresponding sensor for each input cloud (in a perfect world, there should be only one ;)
  1799. for ( ccHObject *entity : getSelectedEntities() )
  1800. {
  1801. if (entity->isKindOf(CC_TYPES::POINT_CLOUD))
  1802. {
  1803. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(entity);
  1804. //we create a new sensor
  1805. ccGBLSensor* sensor = new ccGBLSensor();
  1806. //we init its parameters with the dialog
  1807. spDlg.updateGBLSensor(sensor);
  1808. //we compute projection
  1809. if (sensor->computeAutoParameters(cloud))
  1810. {
  1811. cloud->addChild(sensor);
  1812. //we try to guess the sensor relative size (dirty)
  1813. ccBBox bb = cloud->getOwnBB();
  1814. double diag = bb.getDiagNorm();
  1815. if (diag < 1.0)
  1816. sensor->setGraphicScale(static_cast<PointCoordinateType>(1.0e-3));
  1817. else if (diag > 10000.0)
  1818. sensor->setGraphicScale(static_cast<PointCoordinateType>(1.0e3));
  1819. //we display depth buffer
  1820. int errorCode;
  1821. if (sensor->computeDepthBuffer(cloud,errorCode))
  1822. {
  1823. ccRenderingTools::ShowDepthBuffer(sensor,this);
  1824. }
  1825. else
  1826. {
  1827. ccConsole::Error(ccGBLSensor::GetErrorString(errorCode));
  1828. }
  1829. ////DGM: test
  1830. //{
  1831. // //add positions
  1832. // const unsigned count = 1000;
  1833. // const PointCoordinateType R = 100;
  1834. // const PointCoordinateType dh = 100;
  1835. // for (unsigned i=0; i<1000; ++i)
  1836. // {
  1837. // float angle = (float)i/(float)count * 6 * M_PI;
  1838. // float X = R * cos(angle);
  1839. // float Y = R * sin(angle);
  1840. // float Z = (float)i/(float)count * dh;
  1841. // ccIndexedTransformation trans;
  1842. // trans.initFromParameters(-angle,CCVector3(0,0,1),CCVector3(X,Y,Z));
  1843. // sensor->addPosition(trans,i);
  1844. // }
  1845. //}
  1846. //set position
  1847. //ccIndexedTransformation trans;
  1848. //sensor->addPosition(trans,0);
  1849. ccGLWindowInterface* win = static_cast<ccGLWindowInterface*>(cloud->getDisplay());
  1850. if (win)
  1851. {
  1852. sensor->setDisplay_recursive(win);
  1853. sensor->setVisible(true);
  1854. ccBBox box = cloud->getOwnBB();
  1855. win->updateConstellationCenterAndZoom(&box);
  1856. }
  1857. addToDB(sensor);
  1858. }
  1859. else
  1860. {
  1861. ccLog::Error(tr("Failed to create sensor"));
  1862. delete sensor;
  1863. sensor = nullptr;
  1864. }
  1865. }
  1866. }
  1867. updateUI();
  1868. }
  1869. void MainWindow::doActionCreateCameraSensor()
  1870. {
  1871. //we create the camera sensor
  1872. ccCameraSensor* sensor = new ccCameraSensor();
  1873. ccHObject* ent = nullptr;
  1874. if (haveSelection())
  1875. {
  1876. assert(haveOneSelection());
  1877. ent = m_selectedEntities.front();
  1878. }
  1879. //we try to guess the sensor relative size (dirty)
  1880. if (ent && ent->isKindOf(CC_TYPES::POINT_CLOUD))
  1881. {
  1882. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(ent);
  1883. ccBBox bb = cloud->getOwnBB();
  1884. double diag = bb.getDiagNorm();
  1885. if (diag < 1.0)
  1886. sensor->setGraphicScale(static_cast<PointCoordinateType>(1.0e-3));
  1887. else if (diag > 10000.0)
  1888. sensor->setGraphicScale(static_cast<PointCoordinateType>(1.0e3));
  1889. //set position
  1890. ccIndexedTransformation trans;
  1891. sensor->addPosition(trans, 0);
  1892. }
  1893. ccCamSensorProjectionDlg spDlg(this);
  1894. //spDlg.initWithCamSensor(sensor); //DGM: we'd better leave the default parameters of the dialog!
  1895. if (!spDlg.exec())
  1896. {
  1897. delete sensor;
  1898. return;
  1899. }
  1900. spDlg.updateCamSensor(sensor);
  1901. ccGLWindowInterface* win = nullptr;
  1902. if (ent)
  1903. {
  1904. ent->addChild(sensor);
  1905. win = static_cast<ccGLWindowInterface*>(ent->getDisplay());
  1906. }
  1907. else
  1908. {
  1909. win = getActiveGLWindow();
  1910. }
  1911. if (win)
  1912. {
  1913. sensor->setDisplay(win);
  1914. sensor->setVisible(true);
  1915. if (ent)
  1916. {
  1917. ccBBox box = ent->getOwnBB();
  1918. win->updateConstellationCenterAndZoom(&box);
  1919. }
  1920. }
  1921. addToDB(sensor);
  1922. updateUI();
  1923. }
  1924. void MainWindow::doActionModifySensor()
  1925. {
  1926. //there should be only one point cloud with sensor in current selection!
  1927. if (!haveOneSelection() || !m_selectedEntities.front()->isKindOf(CC_TYPES::SENSOR))
  1928. {
  1929. ccConsole::Error(tr("Select one and only one sensor!"));
  1930. return;
  1931. }
  1932. ccSensor* sensor = static_cast<ccSensor*>(m_selectedEntities.front());
  1933. //Ground based laser sensors
  1934. if (sensor->isA(CC_TYPES::GBL_SENSOR))
  1935. {
  1936. ccGBLSensor* gbl = static_cast<ccGBLSensor*>(sensor);
  1937. ccGBLSensorProjectionDlg spDlg(this);
  1938. spDlg.initWithGBLSensor(gbl);
  1939. if (!spDlg.exec())
  1940. return;
  1941. //we update its parameters
  1942. spDlg.updateGBLSensor(gbl);
  1943. //we re-project the associated cloud (if any)
  1944. if (gbl->getParent() && gbl->getParent()->isKindOf(CC_TYPES::POINT_CLOUD))
  1945. {
  1946. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(gbl->getParent());
  1947. int errorCode;
  1948. if (gbl->computeDepthBuffer(cloud,errorCode))
  1949. {
  1950. //we display depth buffer
  1951. ccRenderingTools::ShowDepthBuffer(gbl,this);
  1952. }
  1953. else
  1954. {
  1955. ccConsole::Error(ccGBLSensor::GetErrorString(errorCode));
  1956. }
  1957. }
  1958. else
  1959. {
  1960. //ccConsole::Warning(tr("Internal error: sensor ('%1') parent is not a point cloud!").arg(sensor->getName()));
  1961. }
  1962. }
  1963. //Camera sensors
  1964. else if (sensor->isA(CC_TYPES::CAMERA_SENSOR))
  1965. {
  1966. ccCameraSensor* cam = static_cast<ccCameraSensor*>(sensor);
  1967. ccCamSensorProjectionDlg spDlg(this);
  1968. spDlg.initWithCamSensor(cam);
  1969. if (!spDlg.exec())
  1970. return;
  1971. //we update its parameters
  1972. spDlg.updateCamSensor(cam);
  1973. }
  1974. else
  1975. {
  1976. ccConsole::Error(tr("Can't modify this kind of sensor!"));
  1977. return;
  1978. }
  1979. if (sensor->isVisible() && sensor->isEnabled())
  1980. {
  1981. sensor->prepareDisplayForRefresh();
  1982. refreshAll();
  1983. }
  1984. updateUI();
  1985. }
  1986. void MainWindow::doActionProjectUncertainty()
  1987. {
  1988. //there should only be one sensor in the current selection!
  1989. if (!haveOneSelection() || !m_selectedEntities.front()->isKindOf(CC_TYPES::CAMERA_SENSOR))
  1990. {
  1991. ccConsole::Error(tr("Select one and only one camera (projective) sensor!"));
  1992. return;
  1993. }
  1994. ccCameraSensor* sensor = ccHObjectCaster::ToCameraSensor(m_selectedEntities.front());
  1995. if (!sensor)
  1996. {
  1997. assert(false);
  1998. return;
  1999. }
  2000. const ccCameraSensor::LensDistortionParameters::Shared& distParams = sensor->getDistortionParameters();
  2001. if (!distParams || distParams->getModel() != ccCameraSensor::BROWN_DISTORTION)
  2002. {
  2003. ccLog::Error(tr("Sensor has no associated uncertainty model! (Brown, etc.)"));
  2004. return;
  2005. }
  2006. //we need a cloud to project the uncertainty on!
  2007. ccHObject* defaultCloud = sensor->getParent() && sensor->getParent()->isA(CC_TYPES::POINT_CLOUD) ? sensor->getParent() : nullptr;
  2008. ccPointCloud* pointCloud = askUserToSelectACloud(defaultCloud, tr("Select a cloud on which to project the uncertainty:"));
  2009. if (!pointCloud)
  2010. {
  2011. return;
  2012. }
  2013. CCCoreLib::ReferenceCloud points(pointCloud);
  2014. if (!points.reserve(pointCloud->size()))
  2015. {
  2016. ccConsole::Error(tr("Not enough memory!"));
  2017. return;
  2018. }
  2019. points.addPointIndex(0,pointCloud->size());
  2020. // compute uncertainty
  2021. std::vector< Vector3Tpl<ScalarType> > accuracy;
  2022. if (!sensor->computeUncertainty(&points, accuracy/*, false*/))
  2023. {
  2024. ccConsole::Error(tr("Not enough memory!"));
  2025. return;
  2026. }
  2027. /////////////
  2028. // SIGMA D //
  2029. /////////////
  2030. const char dimChar[3] = {'x','y','z'};
  2031. for (unsigned d = 0; d < 3; ++d)
  2032. {
  2033. // add scalar field
  2034. QString sfName = tr("[%1] Uncertainty (%2)").arg(sensor->getName()).arg(dimChar[d]);
  2035. int sfIdx = pointCloud->getScalarFieldIndexByName(sfName.toStdString());
  2036. if (sfIdx < 0)
  2037. sfIdx = pointCloud->addScalarField(sfName.toStdString());
  2038. if (sfIdx < 0)
  2039. {
  2040. ccLog::Error(tr("An error occurred! (see console)"));
  2041. return;
  2042. }
  2043. // fill scalar field
  2044. CCCoreLib::ScalarField* sf = pointCloud->getScalarField(sfIdx);
  2045. assert(sf);
  2046. if (sf)
  2047. {
  2048. unsigned count = static_cast<unsigned>(accuracy.size());
  2049. assert(count == pointCloud->size());
  2050. for (unsigned i = 0; i < count; i++)
  2051. sf->setValue(i, accuracy[i].u[d]);
  2052. sf->computeMinAndMax();
  2053. }
  2054. }
  2055. /////////////////
  2056. // SIGMA TOTAL //
  2057. /////////////////
  2058. // add scalar field
  2059. {
  2060. QString sfName = tr("[%1] Uncertainty (3D)").arg(sensor->getName());
  2061. int sfIdx = pointCloud->getScalarFieldIndexByName(sfName.toStdString());
  2062. if (sfIdx < 0)
  2063. sfIdx = pointCloud->addScalarField(sfName.toStdString());
  2064. if (sfIdx < 0)
  2065. {
  2066. ccLog::Error(tr("An error occurred! (see console)"));
  2067. return;
  2068. }
  2069. // fill scalar field
  2070. CCCoreLib::ScalarField* sf = pointCloud->getScalarField(sfIdx);
  2071. assert(sf);
  2072. if (sf)
  2073. {
  2074. unsigned count = static_cast<unsigned>(accuracy.size());
  2075. assert(count == pointCloud->size());
  2076. for (unsigned i = 0; i < count; i++)
  2077. sf->setValue(i, accuracy[i].norm());
  2078. sf->computeMinAndMax();
  2079. }
  2080. pointCloud->showSF(true);
  2081. pointCloud->setCurrentDisplayedScalarField(sfIdx);
  2082. pointCloud->prepareDisplayForRefresh();
  2083. }
  2084. refreshAll();
  2085. }
  2086. void MainWindow::doActionCheckPointsInsideFrustum()
  2087. {
  2088. //there should be only one camera sensor in the current selection!
  2089. if (!haveOneSelection() || !m_selectedEntities.front()->isKindOf(CC_TYPES::CAMERA_SENSOR))
  2090. {
  2091. ccConsole::Error(tr("Select one and only one camera sensor!"));
  2092. return;
  2093. }
  2094. ccCameraSensor* sensor = ccHObjectCaster::ToCameraSensor(m_selectedEntities.front());
  2095. if (!sensor)
  2096. return;
  2097. //we need a cloud to filter!
  2098. ccHObject* defaultCloud = sensor->getParent() && sensor->getParent()->isA(CC_TYPES::POINT_CLOUD) ? sensor->getParent() : nullptr;
  2099. ccPointCloud* pointCloud = askUserToSelectACloud(defaultCloud, tr("Select a cloud to filter:"));
  2100. if (!pointCloud)
  2101. {
  2102. return;
  2103. }
  2104. //comupte/get the point cloud's octree
  2105. ccOctree::Shared octree = pointCloud->getOctree();
  2106. if (!octree)
  2107. {
  2108. octree = pointCloud->computeOctree();
  2109. if (!octree)
  2110. {
  2111. ccConsole::Error(tr("Failed to compute the octree!"));
  2112. return;
  2113. }
  2114. }
  2115. assert(octree);
  2116. // filter octree then project the points
  2117. std::vector<unsigned> inCameraFrustum;
  2118. if (!octree->intersectWithFrustum(sensor, inCameraFrustum))
  2119. {
  2120. ccConsole::Error(tr("Failed to intersect sensor frustum with octree!"));
  2121. }
  2122. else
  2123. {
  2124. // scalar field
  2125. const char sfName[] = "Frustum visibility";
  2126. int sfIdx = pointCloud->getScalarFieldIndexByName(sfName);
  2127. if (inCameraFrustum.empty())
  2128. {
  2129. ccConsole::Error(tr("No point fell inside the frustum!"));
  2130. if (sfIdx >= 0)
  2131. pointCloud->deleteScalarField(sfIdx);
  2132. }
  2133. else
  2134. {
  2135. if (sfIdx < 0)
  2136. sfIdx = pointCloud->addScalarField(sfName);
  2137. if (sfIdx < 0)
  2138. {
  2139. ccLog::Error(tr("Failed to allocate memory for output scalar field!"));
  2140. return;
  2141. }
  2142. CCCoreLib::ScalarField* sf = pointCloud->getScalarField(sfIdx);
  2143. assert(sf);
  2144. if (sf)
  2145. {
  2146. sf->fill(0);
  2147. const ScalarType c_insideValue = static_cast<ScalarType>(1);
  2148. for ( unsigned index : inCameraFrustum )
  2149. {
  2150. sf->setValue(index, c_insideValue);
  2151. }
  2152. sf->computeMinAndMax();
  2153. pointCloud->setCurrentDisplayedScalarField(sfIdx);
  2154. pointCloud->showSF(true);
  2155. pointCloud->redrawDisplay();
  2156. }
  2157. }
  2158. }
  2159. updateUI();
  2160. }
  2161. void MainWindow::doActionShowDepthBuffer()
  2162. {
  2163. if (!haveSelection())
  2164. return;
  2165. for ( ccHObject *entity : getSelectedEntities() )
  2166. {
  2167. if (entity->isKindOf(CC_TYPES::GBL_SENSOR))
  2168. {
  2169. ccGBLSensor* sensor = static_cast<ccGBLSensor*>(m_selectedEntities.front());
  2170. if (sensor->getDepthBuffer().zBuff.empty())
  2171. {
  2172. //look for depending cloud
  2173. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(entity->getParent());
  2174. if (cloud)
  2175. {
  2176. //force depth buffer computation
  2177. int errorCode;
  2178. if (!sensor->computeDepthBuffer(cloud, errorCode))
  2179. {
  2180. ccConsole::Error(ccGBLSensor::GetErrorString(errorCode));
  2181. }
  2182. }
  2183. else
  2184. {
  2185. ccConsole::Error(tr("Internal error: sensor ('%1') parent is not a point cloud!").arg(sensor->getName()));
  2186. return;
  2187. }
  2188. }
  2189. ccRenderingTools::ShowDepthBuffer(sensor, this);
  2190. }
  2191. }
  2192. }
  2193. void MainWindow::doActionExportDepthBuffer()
  2194. {
  2195. if (!haveSelection())
  2196. return;
  2197. //persistent settings
  2198. QSettings settings;
  2199. settings.beginGroup(ccPS::SaveFile());
  2200. QString currentPath = settings.value(ccPS::CurrentPath(), ccFileUtils::defaultDocPath()).toString();
  2201. QString filename = QFileDialog::getSaveFileName(this,
  2202. tr("Select output file"),
  2203. currentPath,
  2204. DepthMapFileFilter::GetFileFilter(),
  2205. nullptr,
  2206. CCFileDialogOptions()
  2207. );
  2208. if (filename.isEmpty())
  2209. {
  2210. //process cancelled by user
  2211. return;
  2212. }
  2213. //save last saving location
  2214. settings.setValue(ccPS::CurrentPath(),QFileInfo(filename).absolutePath());
  2215. settings.endGroup();
  2216. ccHObject* toSave = nullptr;
  2217. bool multEntities = false;
  2218. if (haveOneSelection())
  2219. {
  2220. toSave = m_selectedEntities.front();
  2221. }
  2222. else
  2223. {
  2224. toSave = new ccHObject("Temp Group");
  2225. for ( ccHObject *entity : getSelectedEntities() )
  2226. {
  2227. toSave->addChild(entity,ccHObject::DP_NONE);
  2228. }
  2229. multEntities = true;
  2230. }
  2231. DepthMapFileFilter::SaveParameters parameters;
  2232. {
  2233. parameters.alwaysDisplaySaveDialog = true;
  2234. }
  2235. CC_FILE_ERROR result = DepthMapFileFilter().saveToFile(toSave, filename, parameters);
  2236. if (result != CC_FERR_NO_ERROR)
  2237. {
  2238. FileIOFilter::DisplayErrorMessage(result, tr("saving"), filename);
  2239. }
  2240. else
  2241. {
  2242. ccLog::Print(tr("[I/O] File '%1' saved successfully").arg(filename));
  2243. }
  2244. if (multEntities)
  2245. {
  2246. delete toSave;
  2247. toSave = nullptr;
  2248. }
  2249. }
  2250. void MainWindow::doActionComputePointsVisibility()
  2251. {
  2252. //there should be only one camera sensor in the current selection!
  2253. if (!haveOneSelection() || !m_selectedEntities.front()->isKindOf(CC_TYPES::GBL_SENSOR))
  2254. {
  2255. ccConsole::Error(tr("Select one and only one GBL/TLS sensor!"));
  2256. return;
  2257. }
  2258. ccGBLSensor* sensor = ccHObjectCaster::ToGBLSensor(m_selectedEntities.front());
  2259. if (!sensor)
  2260. return;
  2261. //we need a cloud to filter!
  2262. ccHObject* defaultCloud = sensor->getParent() && sensor->getParent()->isA(CC_TYPES::POINT_CLOUD) ? sensor->getParent() : nullptr;
  2263. ccPointCloud* pointCloud = askUserToSelectACloud(defaultCloud, tr("Select a cloud to filter:"));
  2264. if (!pointCloud)
  2265. {
  2266. return;
  2267. }
  2268. if (sensor->getDepthBuffer().zBuff.empty())
  2269. {
  2270. if (defaultCloud)
  2271. {
  2272. //the sensor has no depth buffer, we'll ask the user if he wants to compute it first
  2273. if (QMessageBox::warning( this,
  2274. tr("Depth buffer"),
  2275. tr("Sensor has no depth buffer: do you want to compute it now?"),
  2276. QMessageBox::Yes | QMessageBox::No,
  2277. QMessageBox::Yes ) == QMessageBox::No)
  2278. {
  2279. //we can stop then...
  2280. return;
  2281. }
  2282. int errorCode;
  2283. if (sensor->computeDepthBuffer(static_cast<ccPointCloud*>(defaultCloud), errorCode))
  2284. {
  2285. ccRenderingTools::ShowDepthBuffer(sensor, this);
  2286. }
  2287. else
  2288. {
  2289. ccConsole::Error(ccGBLSensor::GetErrorString(errorCode));
  2290. return;
  2291. }
  2292. }
  2293. else
  2294. {
  2295. ccConsole::Error(tr("Sensor has no depth buffer (and no associated cloud?)"));
  2296. return;
  2297. }
  2298. }
  2299. // scalar field
  2300. const char sfName[] = "Sensor visibility";
  2301. int sfIdx = pointCloud->getScalarFieldIndexByName(sfName);
  2302. if (sfIdx < 0)
  2303. sfIdx = pointCloud->addScalarField(sfName);
  2304. if (sfIdx < 0)
  2305. {
  2306. ccLog::Error(tr("Failed to allocate memory for output scalar field!"));
  2307. return;
  2308. }
  2309. CCCoreLib::ScalarField* sf = pointCloud->getScalarField(sfIdx);
  2310. assert(sf);
  2311. if (sf)
  2312. {
  2313. sf->fill(0);
  2314. //progress bar
  2315. ccProgressDialog pdlg(true);
  2316. CCCoreLib::NormalizedProgress nprogress(&pdlg,pointCloud->size());
  2317. pdlg.setMethodTitle(tr("Compute visibility"));
  2318. pdlg.setInfo(tr("Points: %L1").arg( pointCloud->size() ));
  2319. pdlg.start();
  2320. QApplication::processEvents();
  2321. for (unsigned i = 0; i < pointCloud->size(); i++)
  2322. {
  2323. const CCVector3* P = pointCloud->getPoint(i);
  2324. unsigned char visibility = sensor->checkVisibility(*P);
  2325. ScalarType visValue = static_cast<ScalarType>(visibility);
  2326. sf->setValue(i, visValue);
  2327. if (!nprogress.oneStep())
  2328. {
  2329. //cancelled by user
  2330. pointCloud->deleteScalarField(sfIdx);
  2331. sf = nullptr;
  2332. break;
  2333. }
  2334. }
  2335. if (sf)
  2336. {
  2337. sf->computeMinAndMax();
  2338. pointCloud->setCurrentDisplayedScalarField(sfIdx);
  2339. pointCloud->showSF(true);
  2340. ccConsole::Print(tr("Visibility computed for cloud '%1'").arg(pointCloud->getName()));
  2341. ccConsole::Print(tr("\tVisible = %1").arg(CCCoreLib::POINT_VISIBLE));
  2342. ccConsole::Print(tr("\tHidden = %1").arg(CCCoreLib::POINT_HIDDEN));
  2343. ccConsole::Print(tr("\tOut of range = %1").arg(CCCoreLib::POINT_OUT_OF_RANGE));
  2344. ccConsole::Print(tr("\tOut of fov = %1").arg(CCCoreLib::POINT_OUT_OF_FOV));
  2345. }
  2346. pointCloud->redrawDisplay();
  2347. }
  2348. updateUI();
  2349. }
  2350. void MainWindow::doActionConvertTextureToColor()
  2351. {
  2352. if ( !ccEntityAction::convertTextureToColor(m_selectedEntities, this) )
  2353. return;
  2354. refreshAll();
  2355. updateUI();
  2356. }
  2357. void MainWindow::doActionSamplePointsOnMesh()
  2358. {
  2359. static unsigned s_ptsSamplingCount = 1000000;
  2360. static double s_ptsSamplingDensity = 10.0;
  2361. static bool s_ptsSampleNormals = true;
  2362. static bool s_useDensity = false;
  2363. ccPtsSamplingDlg dlg(this);
  2364. //restore last parameters
  2365. dlg.setPointsNumber(s_ptsSamplingCount);
  2366. dlg.setDensityValue(s_ptsSamplingDensity);
  2367. dlg.setGenerateNormals(s_ptsSampleNormals);
  2368. dlg.setUseDensity(s_useDensity);
  2369. if (!dlg.exec())
  2370. return;
  2371. ccProgressDialog pDlg(false, this);
  2372. pDlg.setAutoClose(false);
  2373. bool withNormals = dlg.generateNormals();
  2374. bool withRGB = dlg.interpolateRGB();
  2375. bool withTexture = dlg.interpolateTexture();
  2376. s_useDensity = dlg.useDensity();
  2377. s_ptsSamplingCount = dlg.getPointsNumber();
  2378. s_ptsSamplingDensity = dlg.getDensityValue();
  2379. s_ptsSampleNormals = withNormals;
  2380. bool errors = false;
  2381. for ( ccHObject *entity : getSelectedEntities() )
  2382. {
  2383. if (!entity->isKindOf(CC_TYPES::MESH))
  2384. continue;
  2385. ccGenericMesh* mesh = ccHObjectCaster::ToGenericMesh(entity);
  2386. assert(mesh);
  2387. ccPointCloud* cloud = mesh->samplePoints( s_useDensity,
  2388. s_useDensity ? s_ptsSamplingDensity : s_ptsSamplingCount,
  2389. withNormals,
  2390. withRGB,
  2391. withTexture,
  2392. &pDlg );
  2393. if (cloud)
  2394. {
  2395. addToDB(cloud);
  2396. }
  2397. else
  2398. {
  2399. errors = true;
  2400. }
  2401. }
  2402. if (errors)
  2403. ccLog::Error(tr("[doActionSamplePointsOnMesh] Errors occurred during the process! Result may be incomplete!"));
  2404. refreshAll();
  2405. }
  2406. void MainWindow::doActionSamplePointsOnPolyline()
  2407. {
  2408. static unsigned s_ptsSamplingCount = 1000;
  2409. static double s_ptsSamplingDensity = 10.0;
  2410. static bool s_useDensity = false;
  2411. ccPtsSamplingDlg dlg(this);
  2412. //restore last parameters
  2413. dlg.setPointsNumber(s_ptsSamplingCount);
  2414. dlg.setDensityValue(s_ptsSamplingDensity);
  2415. dlg.setUseDensity(s_useDensity);
  2416. dlg.optionsFrame->setVisible(false);
  2417. if (!dlg.exec())
  2418. return;
  2419. s_ptsSamplingCount = dlg.getPointsNumber();
  2420. s_ptsSamplingDensity = dlg.getDensityValue();
  2421. s_useDensity = dlg.useDensity();
  2422. bool errors = false;
  2423. for (ccHObject *entity : getSelectedEntities())
  2424. {
  2425. if (!entity->isKindOf(CC_TYPES::POLY_LINE))
  2426. continue;
  2427. ccPolyline* poly = ccHObjectCaster::ToPolyline(entity);
  2428. assert(poly);
  2429. ccPointCloud* cloud = poly->samplePoints( s_useDensity,
  2430. s_useDensity ? s_ptsSamplingDensity : s_ptsSamplingCount,
  2431. true);
  2432. if (cloud)
  2433. {
  2434. addToDB(cloud);
  2435. }
  2436. else
  2437. {
  2438. errors = true;
  2439. }
  2440. }
  2441. if (errors)
  2442. {
  2443. ccLog::Error(tr("[DoActionSamplePointsOnPolyline] Errors occurred during the process! Result may be incomplete!"));
  2444. }
  2445. refreshAll();
  2446. }
  2447. void MainWindow::doActionSmoohPolyline()
  2448. {
  2449. static int s_iterationCount = 5;
  2450. static double s_ratio = 0.25;
  2451. ccSmoothPolylineDialog dlg(this);
  2452. //restore last parameters
  2453. dlg.setIerationCount(s_iterationCount);
  2454. dlg.setRatio(s_ratio);
  2455. if (!dlg.exec())
  2456. return;
  2457. s_iterationCount = dlg.getIerationCount();
  2458. s_ratio = dlg.getRatio();
  2459. bool errors = false;
  2460. ccHObject::Container selectedEntities = getSelectedEntities();
  2461. m_ccRoot->unselectAllEntities();
  2462. for (ccHObject *entity : selectedEntities)
  2463. {
  2464. if (!entity->isKindOf(CC_TYPES::POLY_LINE))
  2465. continue;
  2466. ccPolyline* poly = ccHObjectCaster::ToPolyline(entity);
  2467. assert(poly);
  2468. ccPolyline* smoothPoly = poly->smoothChaikin(s_ratio, static_cast<unsigned>(s_iterationCount));
  2469. if (smoothPoly)
  2470. {
  2471. if (poly->getParent())
  2472. {
  2473. poly->getParent()->addChild(smoothPoly);
  2474. }
  2475. poly->setEnabled(false);
  2476. addToDB(smoothPoly);
  2477. m_ccRoot->selectEntity(smoothPoly, true);
  2478. }
  2479. else
  2480. {
  2481. errors = true;
  2482. }
  2483. }
  2484. if (errors)
  2485. {
  2486. ccLog::Error(tr("[DoActionSmoohPolyline] Errors occurred during the process! Result may be incomplete!"));
  2487. }
  2488. refreshAll();
  2489. }
  2490. void MainWindow::doRemoveDuplicatePoints()
  2491. {
  2492. if (!haveSelection())
  2493. return;
  2494. bool first = true;
  2495. //persistent setting(s)
  2496. QSettings settings;
  2497. settings.beginGroup(ccPS::DuplicatePointsGroup());
  2498. double minDistanceBetweenPoints = settings.value(ccPS::DuplicatePointsMinDist(),1.0e-12).toDouble();
  2499. bool ok;
  2500. minDistanceBetweenPoints = QInputDialog::getDouble(this, tr("Remove duplicate points"), tr("Min distance between points:"), minDistanceBetweenPoints, 0, 1.0e8, 12, &ok);
  2501. if (!ok)
  2502. return;
  2503. //save parameter
  2504. settings.setValue(ccPS::DuplicatePointsMinDist(), minDistanceBetweenPoints);
  2505. ccProgressDialog pDlg(true, this);
  2506. pDlg.setAutoClose(false);
  2507. ccHObject::Container selectedEntities = getSelectedEntities(); //we have to use a local copy: 'unselectAllEntities' and 'selectEntity' will change the set of currently selected entities!
  2508. for (ccHObject* entity : selectedEntities)
  2509. {
  2510. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(entity);
  2511. if (cloud)
  2512. {
  2513. ccPointCloud* filteredCloud = cloud->removeDuplicatePoints(minDistanceBetweenPoints, &pDlg);
  2514. if (!filteredCloud)
  2515. {
  2516. ccConsole::Error(tr("Process failed (see Console)"));
  2517. break;
  2518. }
  2519. if (filteredCloud != cloud) // otherwise the cloud has no duplicate point
  2520. {
  2521. filteredCloud->prepareDisplayForRefresh();
  2522. addToDB(filteredCloud);
  2523. if (first)
  2524. {
  2525. m_ccRoot->unselectAllEntities();
  2526. first = false;
  2527. }
  2528. cloud->setEnabled(false);
  2529. m_ccRoot->selectEntity(filteredCloud, true);
  2530. }
  2531. }
  2532. }
  2533. if (!first)
  2534. {
  2535. ccConsole::Warning(tr("Previously selected entities (sources) have been hidden!"));
  2536. }
  2537. refreshAll();
  2538. }
  2539. void MainWindow::doActionFilterByValue()
  2540. {
  2541. typedef std::pair<ccHObject*, ccPointCloud*> EntityAndVerticesType;
  2542. std::vector<EntityAndVerticesType> toFilter;
  2543. for ( ccHObject *entity : getSelectedEntities() )
  2544. {
  2545. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(entity);
  2546. if (cloud && cloud->isA(CC_TYPES::POINT_CLOUD))
  2547. {
  2548. ccPointCloud* pc = static_cast<ccPointCloud*>(cloud);
  2549. //la methode est activee sur le champ scalaire affiche
  2550. CCCoreLib::ScalarField* sf = pc->getCurrentDisplayedScalarField();
  2551. if (sf)
  2552. {
  2553. toFilter.emplace_back(entity,pc);
  2554. }
  2555. else
  2556. {
  2557. ccConsole::Warning(tr("Entity [%1] has no active scalar field!").arg(entity->getName()));
  2558. }
  2559. }
  2560. }
  2561. if (toFilter.empty())
  2562. return;
  2563. double minVald = 0.0;
  2564. double maxVald = 1.0;
  2565. //compute min and max "displayed" scalar values of currently selected
  2566. //entities (the ones with an active scalar field only!)
  2567. {
  2568. for (size_t i = 0; i < toFilter.size(); ++i)
  2569. {
  2570. ccScalarField* sf = toFilter[i].second->getCurrentDisplayedScalarField();
  2571. assert(sf);
  2572. if (i == 0)
  2573. {
  2574. minVald = static_cast<double>(sf->displayRange().start());
  2575. maxVald = static_cast<double>(sf->displayRange().stop());
  2576. }
  2577. else
  2578. {
  2579. if (minVald > static_cast<double>(sf->displayRange().start()))
  2580. minVald = static_cast<double>(sf->displayRange().start());
  2581. if (maxVald < static_cast<double>(sf->displayRange().stop()))
  2582. maxVald = static_cast<double>(sf->displayRange().stop());
  2583. }
  2584. }
  2585. }
  2586. ccFilterByValueDlg dlg(minVald, maxVald, -1.0e9, 1.0e9, this);
  2587. if (!dlg.exec())
  2588. return;
  2589. ccFilterByValueDlg::Mode mode = dlg.mode();
  2590. assert(mode != ccFilterByValueDlg::CANCEL);
  2591. ScalarType minVal = static_cast<ScalarType>(dlg.minDoubleSpinBox->value());
  2592. ScalarType maxVal = static_cast<ScalarType>(dlg.maxDoubleSpinBox->value());
  2593. ccHObject::Container results;
  2594. {
  2595. for ( auto &item : toFilter )
  2596. {
  2597. ccHObject* ent = item.first;
  2598. ccPointCloud* pc = item.second;
  2599. //we set as output (OUT) the currently displayed scalar field
  2600. int outSfIdx = pc->getCurrentDisplayedScalarFieldIndex();
  2601. assert(outSfIdx >= 0);
  2602. pc->setCurrentOutScalarField(outSfIdx);
  2603. ccHObject* resultInside = nullptr;
  2604. ccHObject* resultOutside = nullptr;
  2605. if (ent->isKindOf(CC_TYPES::MESH))
  2606. {
  2607. pc->hidePointsByScalarValue(minVal, maxVal);
  2608. if (ent->isA(CC_TYPES::MESH)/*|| ent->isKindOf(CC_TYPES::PRIMITIVE)*/) //TODO
  2609. resultInside = ccHObjectCaster::ToMesh(ent)->createNewMeshFromSelection(false, nullptr, true);
  2610. else if (ent->isA(CC_TYPES::SUB_MESH))
  2611. resultInside = ccHObjectCaster::ToSubMesh(ent)->createNewSubMeshFromSelection(false);
  2612. if (resultInside == ent)
  2613. {
  2614. //specific case: all triangles were selected, nothing to do
  2615. ccLog::Warning(QString("Mesh %1 is fully inside the specified range").arg(ent->getName()));
  2616. resultInside = nullptr;
  2617. }
  2618. else if (mode == ccFilterByValueDlg::SPLIT)
  2619. {
  2620. pc->invertVisibilityArray();
  2621. if (ent->isA(CC_TYPES::MESH)/*|| ent->isKindOf(CC_TYPES::PRIMITIVE)*/) //TODO
  2622. resultOutside = ccHObjectCaster::ToMesh(ent)->createNewMeshFromSelection(false, nullptr, true);
  2623. else if (ent->isA(CC_TYPES::SUB_MESH))
  2624. resultOutside = ccHObjectCaster::ToSubMesh(ent)->createNewSubMeshFromSelection(false);
  2625. if (resultOutside == ent)
  2626. {
  2627. //specific case: all triangles were selected, nothing to do
  2628. ccLog::Warning(QString("Mesh %1 is fully outside the specified range").arg(ent->getName()));
  2629. ent->setEnabled(false);
  2630. ent->prepareDisplayForRefresh();
  2631. delete resultInside; // we don't need it
  2632. resultInside = nullptr;
  2633. resultOutside = nullptr;
  2634. }
  2635. }
  2636. pc->unallocateVisibilityArray();
  2637. }
  2638. else if (ent->isKindOf(CC_TYPES::POINT_CLOUD))
  2639. {
  2640. //shortcut, as we know here that the point cloud is a "ccPointCloud"
  2641. resultInside = pc->filterPointsByScalarValue(minVal, maxVal, false);
  2642. if (resultInside == ent)
  2643. {
  2644. //specific case: all points were selected, nothing to do
  2645. ccLog::Warning(QString("Cloud %1 is fully inside the specified range").arg(ent->getName()));
  2646. resultInside = nullptr;
  2647. }
  2648. else if (mode == ccFilterByValueDlg::SPLIT)
  2649. {
  2650. resultOutside = pc->filterPointsByScalarValue(minVal, maxVal, true);
  2651. if (resultOutside == ent)
  2652. {
  2653. //specific case: all points were selected, nothing to do
  2654. ccLog::Warning(QString("Cloud %1 is fully outside the specified range").arg(ent->getName()));
  2655. ent->setEnabled(false);
  2656. ent->prepareDisplayForRefresh();
  2657. delete resultInside;
  2658. resultInside = nullptr;
  2659. resultOutside = nullptr;
  2660. }
  2661. }
  2662. }
  2663. if (resultInside)
  2664. {
  2665. ent->setEnabled(false);
  2666. resultInside->setDisplay(ent->getDisplay());
  2667. resultInside->prepareDisplayForRefresh();
  2668. addToDB(resultInside);
  2669. results.push_back(resultInside);
  2670. }
  2671. if (resultOutside)
  2672. {
  2673. ent->setEnabled(false);
  2674. resultOutside->setDisplay(ent->getDisplay());
  2675. resultOutside->prepareDisplayForRefresh();
  2676. resultOutside->setName(resultOutside->getName() + ".outside");
  2677. addToDB(resultOutside);
  2678. results.push_back(resultOutside);
  2679. }
  2680. }
  2681. }
  2682. if (!results.empty())
  2683. {
  2684. ccConsole::Warning(tr("Previously selected entities (sources) have been hidden!"));
  2685. if (m_ccRoot)
  2686. {
  2687. m_ccRoot->selectEntities(results);
  2688. }
  2689. }
  2690. refreshAll();
  2691. }
  2692. void MainWindow::doActionSFConvertToRandomRGB()
  2693. {
  2694. if ( !ccEntityAction::sfConvertToRandomRGB(m_selectedEntities, this) )
  2695. return;
  2696. refreshAll();
  2697. updateUI();
  2698. }
  2699. void MainWindow::doActionSFConvertToRGB()
  2700. {
  2701. if ( !ccEntityAction::sfConvertToRGB(m_selectedEntities, this) )
  2702. return;
  2703. refreshAll();
  2704. updateUI();
  2705. }
  2706. void MainWindow::doActionToggleActiveSFColorScale()
  2707. {
  2708. doApplyActiveSFAction(0);
  2709. }
  2710. void MainWindow::doActionShowActiveSFPrevious()
  2711. {
  2712. doApplyActiveSFAction(1);
  2713. }
  2714. void MainWindow::doActionShowActiveSFNext()
  2715. {
  2716. doApplyActiveSFAction(2);
  2717. }
  2718. void MainWindow::doApplyActiveSFAction(int action)
  2719. {
  2720. if (!haveOneSelection())
  2721. {
  2722. if (haveSelection())
  2723. {
  2724. ccConsole::Error(tr("Select only one cloud or one mesh!"));
  2725. }
  2726. return;
  2727. }
  2728. ccHObject* ent = m_selectedEntities.front();
  2729. bool lockedVertices;
  2730. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(ent,&lockedVertices);
  2731. //for "real" point clouds only
  2732. if (!cloud)
  2733. return;
  2734. if (lockedVertices && !ent->isAncestorOf(cloud))
  2735. {
  2736. //see ccPropertiesTreeDelegate::fillWithMesh
  2737. ccUtils::DisplayLockedVerticesWarning(ent->getName(),true);
  2738. return;
  2739. }
  2740. assert(cloud);
  2741. int sfIdx = cloud->getCurrentDisplayedScalarFieldIndex();
  2742. switch (action)
  2743. {
  2744. case 0: //Toggle SF color scale
  2745. if (sfIdx >= 0)
  2746. {
  2747. cloud->showSFColorsScale(!cloud->sfColorScaleShown());
  2748. cloud->prepareDisplayForRefresh();
  2749. }
  2750. else
  2751. ccConsole::Warning(tr("No active scalar field on entity '%1'").arg(ent->getName()));
  2752. break;
  2753. case 1: //Activate previous SF
  2754. if (sfIdx >= 0)
  2755. {
  2756. cloud->setCurrentDisplayedScalarField(sfIdx-1);
  2757. cloud->prepareDisplayForRefresh();
  2758. }
  2759. break;
  2760. case 2: //Activate next SF
  2761. if (sfIdx+1 < static_cast<int>(cloud->getNumberOfScalarFields()))
  2762. {
  2763. cloud->setCurrentDisplayedScalarField(sfIdx+1);
  2764. cloud->prepareDisplayForRefresh();
  2765. }
  2766. break;
  2767. }
  2768. refreshAll();
  2769. updateUI();
  2770. }
  2771. void MainWindow::doActionRenameSF()
  2772. {
  2773. if ( !ccEntityAction::sfRename(m_selectedEntities, this) )
  2774. return;
  2775. updateUI();
  2776. }
  2777. void MainWindow::doActionOpenColorScalesManager()
  2778. {
  2779. ccColorScaleEditorDialog cseDlg(ccColorScalesManager::GetUniqueInstance(), this, ccColorScale::Shared(nullptr), this);
  2780. if (cseDlg.exec())
  2781. {
  2782. //save current scale manager state to persistent settings
  2783. ccColorScalesManager::GetUniqueInstance()->toPersistentSettings();
  2784. }
  2785. updateUI();
  2786. }
  2787. void MainWindow::doActionAddIdField()
  2788. {
  2789. if (!ccEntityAction::sfAddIdField(m_selectedEntities))
  2790. {
  2791. return;
  2792. }
  2793. refreshAll();
  2794. updateUI();
  2795. }
  2796. void MainWindow::doActionSplitCloudUsingSF()
  2797. {
  2798. if (!ccEntityAction::sfSplitCloud(m_selectedEntities, this))
  2799. return;
  2800. refreshAll();
  2801. updateUI();
  2802. }
  2803. void MainWindow::doActionRGBGaussianFilter()
  2804. {
  2805. ccPointCloud::RgbFilterOptions(filterParams);
  2806. filterParams.filterType = ccPointCloud::RGB_FILTER_TYPES::GAUSSIAN;
  2807. if (!ccEntityAction::rgbGaussianFilter(m_selectedEntities, filterParams, this))
  2808. return;
  2809. refreshAll();
  2810. updateUI();
  2811. }
  2812. void MainWindow::doActionRGBBilateralFilter()
  2813. {
  2814. ccPointCloud::RgbFilterOptions(filterParams);
  2815. filterParams.filterType = ccPointCloud::RGB_FILTER_TYPES::BILATERAL;
  2816. if (!ccEntityAction::rgbGaussianFilter(m_selectedEntities, filterParams, this))
  2817. return;
  2818. refreshAll();
  2819. updateUI();
  2820. }
  2821. void MainWindow::doActionRGBMeanFilter()
  2822. {
  2823. ccPointCloud::RgbFilterOptions(filterParams);
  2824. filterParams.filterType = ccPointCloud::RGB_FILTER_TYPES::MEAN;
  2825. if (!ccEntityAction::rgbGaussianFilter(m_selectedEntities, filterParams, this))
  2826. return;
  2827. refreshAll();
  2828. updateUI();
  2829. }
  2830. void MainWindow::doActionRGBMedianFilter()
  2831. {
  2832. ccPointCloud::RgbFilterOptions(filterParams);
  2833. filterParams.filterType = ccPointCloud::RGB_FILTER_TYPES::MEDIAN;
  2834. if (!ccEntityAction::rgbGaussianFilter(m_selectedEntities, filterParams, this))
  2835. return;
  2836. refreshAll();
  2837. updateUI();
  2838. }
  2839. void MainWindow::doActionSFGaussianFilter()
  2840. {
  2841. ccPointCloud::RgbFilterOptions(filterParams);
  2842. filterParams.filterType = ccPointCloud::RGB_FILTER_TYPES::GAUSSIAN;
  2843. if ( !ccEntityAction::sfGaussianFilter(m_selectedEntities, filterParams, this) )
  2844. return;
  2845. refreshAll();
  2846. updateUI();
  2847. }
  2848. void MainWindow::doActionSFBilateralFilter()
  2849. {
  2850. ccPointCloud::RgbFilterOptions(filterParams);
  2851. filterParams.filterType = ccPointCloud::RGB_FILTER_TYPES::BILATERAL;
  2852. if ( !ccEntityAction::sfGaussianFilter(m_selectedEntities, filterParams, this) )
  2853. return;
  2854. refreshAll();
  2855. updateUI();
  2856. }
  2857. void MainWindow::doActionSmoothMeshSF()
  2858. {
  2859. if ( !ccEntityAction::processMeshSF(m_selectedEntities, ccMesh::SMOOTH_MESH_SF, this) )
  2860. return;
  2861. refreshAll();
  2862. updateUI();
  2863. }
  2864. void MainWindow::doActionEnhanceMeshSF()
  2865. {
  2866. if ( !ccEntityAction::processMeshSF(m_selectedEntities, ccMesh::ENHANCE_MESH_SF, this) )
  2867. return;
  2868. refreshAll();
  2869. updateUI();
  2870. }
  2871. static double s_subdivideMaxArea = 1.0;
  2872. void MainWindow::doActionSubdivideMesh()
  2873. {
  2874. bool ok;
  2875. s_subdivideMaxArea = QInputDialog::getDouble(this, tr("Subdivide mesh"), tr("Max area per triangle:"), s_subdivideMaxArea, 1e-6, 1e6, 8, &ok);
  2876. if (!ok)
  2877. return;
  2878. //ccProgressDialog pDlg(true, this);
  2879. //pDlg.setAutoClose(false);
  2880. bool warningIssued = false;
  2881. for ( ccHObject *entity : getSelectedEntities() )
  2882. {
  2883. if (entity->isKindOf(CC_TYPES::MESH))
  2884. {
  2885. //single mesh?
  2886. if (entity->isA(CC_TYPES::MESH))
  2887. {
  2888. ccMesh* mesh = static_cast<ccMesh*>(entity);
  2889. ccMesh* subdividedMesh = nullptr;
  2890. try
  2891. {
  2892. subdividedMesh = mesh->subdivide(static_cast<PointCoordinateType>(s_subdivideMaxArea));
  2893. }
  2894. catch(...)
  2895. {
  2896. ccLog::Error(tr("[Subdivide] An error occurred while trying to subdivide mesh '%1' (not enough memory?)").arg(mesh->getName()));
  2897. }
  2898. if (subdividedMesh)
  2899. {
  2900. subdividedMesh->setName(QString("%1.subdivided(S<%2)").arg(mesh->getName()).arg(s_subdivideMaxArea));
  2901. subdividedMesh->setDisplay(mesh->getDisplay());
  2902. mesh->redrawDisplay();
  2903. mesh->setEnabled(false);
  2904. addToDB(subdividedMesh);
  2905. }
  2906. else
  2907. {
  2908. ccConsole::Warning(tr("[Subdivide] Failed to subdivide mesh '%1' (not enough memory?)").arg(mesh->getName()));
  2909. }
  2910. }
  2911. else if (!warningIssued)
  2912. {
  2913. ccLog::Warning(tr("[Subdivide] Works only on real meshes!"));
  2914. warningIssued = true;
  2915. }
  2916. }
  2917. }
  2918. refreshAll();
  2919. updateUI();
  2920. }
  2921. void MainWindow::doActionFlipMeshTriangles()
  2922. {
  2923. bool warningIssued = false;
  2924. for (ccHObject *entity : getSelectedEntities())
  2925. {
  2926. if (entity->isKindOf(CC_TYPES::MESH))
  2927. {
  2928. //single mesh?
  2929. if (entity->isA(CC_TYPES::MESH))
  2930. {
  2931. ccMesh* mesh = static_cast<ccMesh*>(entity);
  2932. mesh->flipTriangles();
  2933. mesh->prepareDisplayForRefresh();
  2934. }
  2935. else if (!warningIssued)
  2936. {
  2937. ccLog::Warning(tr("[Flip triangles] Works only on real meshes!"));
  2938. warningIssued = true;
  2939. }
  2940. }
  2941. }
  2942. refreshAll();
  2943. }
  2944. void MainWindow::doActionSmoothMeshLaplacian()
  2945. {
  2946. static unsigned s_laplacianSmooth_nbIter = 20;
  2947. static double s_laplacianSmooth_factor = 0.2;
  2948. bool ok;
  2949. s_laplacianSmooth_nbIter = QInputDialog::getInt(this, tr("Smooth mesh"), tr("Iterations:"), s_laplacianSmooth_nbIter, 1, 1000, 1, &ok);
  2950. if (!ok)
  2951. return;
  2952. s_laplacianSmooth_factor = QInputDialog::getDouble(this, tr("Smooth mesh"), tr("Smoothing factor:"), s_laplacianSmooth_factor, 0, 100, 3, &ok);
  2953. if (!ok)
  2954. return;
  2955. ccProgressDialog pDlg(true, this);
  2956. pDlg.setAutoClose(false);
  2957. for ( ccHObject *entity : getSelectedEntities() )
  2958. {
  2959. if (entity->isA(CC_TYPES::MESH) || entity->isA(CC_TYPES::PRIMITIVE)) //FIXME: can we really do this with primitives?
  2960. {
  2961. ccMesh* mesh = ccHObjectCaster::ToMesh(entity);
  2962. if (mesh->laplacianSmooth( s_laplacianSmooth_nbIter,
  2963. static_cast<PointCoordinateType>(s_laplacianSmooth_factor),
  2964. &pDlg) )
  2965. {
  2966. mesh->prepareDisplayForRefresh_recursive();
  2967. }
  2968. else
  2969. {
  2970. ccConsole::Warning(tr("Failed to apply Laplacian smoothing to mesh '%1'").arg(mesh->getName()));
  2971. }
  2972. }
  2973. }
  2974. refreshAll();
  2975. updateUI();
  2976. }
  2977. // helper for doActionMerge
  2978. void AddToRemoveList(ccHObject* toRemove, ccHObject::Container& toBeRemovedList)
  2979. {
  2980. // is a parent or sibling already in the "toBeRemoved" list?
  2981. size_t count = toBeRemovedList.size();
  2982. for (size_t j = 0; j < count;)
  2983. {
  2984. if (toBeRemovedList[j]->isAncestorOf(toRemove))
  2985. {
  2986. // nothing to do, we already have an ancestor
  2987. return;
  2988. }
  2989. else if (toRemove->isAncestorOf(toBeRemovedList[j]))
  2990. {
  2991. // we don't need to keep the children
  2992. toBeRemovedList[j] = toBeRemovedList.back();
  2993. toBeRemovedList.pop_back();
  2994. count--;
  2995. }
  2996. else
  2997. {
  2998. // forward
  2999. ++j;
  3000. }
  3001. }
  3002. toBeRemovedList.push_back(toRemove);
  3003. }
  3004. void MainWindow::doActionMerge()
  3005. {
  3006. //let's look for clouds or meshes (warning: we don't mix them)
  3007. std::vector<ccPointCloud*> clouds;
  3008. std::vector<ccMesh*> meshes;
  3009. try
  3010. {
  3011. for (ccHObject* entity : getSelectedEntities())
  3012. {
  3013. if (!entity)
  3014. {
  3015. continue;
  3016. }
  3017. if (entity->isA(CC_TYPES::POINT_CLOUD))
  3018. {
  3019. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(entity);
  3020. clouds.push_back(cloud);
  3021. // check whether this cloud is an ancestor of the first cloud in the selection
  3022. if (clouds.size() > 1)
  3023. {
  3024. if (clouds.back()->isAncestorOf(clouds.front()))
  3025. {
  3026. // this way we are sure that the first cloud is not below any other cloud
  3027. std::swap(clouds.front(), clouds.back());
  3028. }
  3029. }
  3030. }
  3031. else if (entity->isKindOf(CC_TYPES::MESH))
  3032. {
  3033. ccMesh* mesh = ccHObjectCaster::ToMesh(entity);
  3034. //this is a purely theoretical test for now!
  3035. if (mesh && mesh->getAssociatedCloud() && mesh->getAssociatedCloud()->isA(CC_TYPES::POINT_CLOUD))
  3036. {
  3037. meshes.push_back(mesh);
  3038. }
  3039. else
  3040. {
  3041. ccConsole::Warning(tr("Only meshes with standard vertices are handled for now! Can't merge entity '%1'...").arg(entity->getName()));
  3042. }
  3043. }
  3044. else
  3045. {
  3046. ccConsole::Warning(tr("Entity '%1' is neither a cloud nor a mesh, can't merge it!").arg(entity->getName()));
  3047. }
  3048. }
  3049. }
  3050. catch (const std::bad_alloc&)
  3051. {
  3052. ccLog::Error(tr("Not enough memory!"));
  3053. return;
  3054. }
  3055. if (clouds.empty() && meshes.empty())
  3056. {
  3057. ccLog::Error(tr("Select only clouds or meshes!"));
  3058. return;
  3059. }
  3060. if (!clouds.empty() && !meshes.empty())
  3061. {
  3062. ccLog::Error(tr("Can't mix point clouds and meshes!"));
  3063. }
  3064. //merge clouds?
  3065. if (!clouds.empty())
  3066. {
  3067. //we deselect all selected entities (as most of them are going to disappear)
  3068. if (m_ccRoot)
  3069. {
  3070. m_ccRoot->unselectAllEntities();
  3071. assert(!haveSelection());
  3072. //m_selectedEntities.clear();
  3073. }
  3074. //we will remove the useless clouds/meshes later
  3075. ccHObject::Container toBeRemoved;
  3076. ccPointCloud* firstCloud = nullptr;
  3077. ccHObjectContext firstCloudContext;
  3078. //whether to generate the 'original cloud index' scalar field or not
  3079. CCCoreLib::ScalarField* ocIndexSF = nullptr;
  3080. size_t cloudIndex = 0;
  3081. //compute total size of the final cloud
  3082. unsigned totalSize = 0;
  3083. for (size_t i = 0; i < clouds.size(); ++i)
  3084. {
  3085. totalSize += clouds[i]->size();
  3086. }
  3087. for (size_t i = 0; i < clouds.size(); ++i)
  3088. {
  3089. ccPointCloud* pc = clouds[i];
  3090. if (!firstCloud)
  3091. {
  3092. //we don't delete the first cloud (we'll merge the other one 'inside' it
  3093. firstCloud = pc;
  3094. //we still have to temporarily detach the first cloud, as it may undergo
  3095. //'severe' modifications (octree deletion, etc.) --> see ccPointCloud::operator +=
  3096. firstCloudContext = removeObjectTemporarilyFromDBTree(firstCloud);
  3097. //reserve the final required number of points
  3098. if (!firstCloud->reserve(totalSize))
  3099. {
  3100. ccConsole::Error(tr("Not enough memory!"));
  3101. break;
  3102. }
  3103. if (QMessageBox::question(this, tr("Original cloud index"), tr("Do you want to generate a scalar field with the original cloud index?")) == QMessageBox::Yes)
  3104. {
  3105. int sfIdx = pc->getScalarFieldIndexByName(CC_ORIGINAL_CLOUD_INDEX_SF_NAME);
  3106. if (sfIdx < 0)
  3107. {
  3108. sfIdx = pc->addScalarField(CC_ORIGINAL_CLOUD_INDEX_SF_NAME);
  3109. }
  3110. if (sfIdx < 0)
  3111. {
  3112. ccConsole::Error(tr("Couldn't allocate a new scalar field for storing the original cloud index! Try to free some memory ..."));
  3113. return;
  3114. }
  3115. else
  3116. {
  3117. ocIndexSF = pc->getScalarField(sfIdx);
  3118. if (ocIndexSF)
  3119. {
  3120. ocIndexSF->fill(0);
  3121. firstCloud->setCurrentDisplayedScalarField(sfIdx);
  3122. }
  3123. }
  3124. }
  3125. }
  3126. else
  3127. {
  3128. unsigned countBefore = firstCloud->size();
  3129. unsigned countAdded = pc->size();
  3130. firstCloud->append(pc, countBefore, false, false); //append without recalculating SF min/max
  3131. //success?
  3132. if (firstCloud->size() == countBefore + countAdded)
  3133. {
  3134. firstCloud->prepareDisplayForRefresh_recursive();
  3135. ccHObject* toRemove = nullptr;
  3136. //if the entity to remove is inside a group with a unique child, we can remove the group as well
  3137. ccHObject* parent = pc->getParent();
  3138. if (parent && parent->isA(CC_TYPES::HIERARCHY_OBJECT) && parent->getChildrenNumber() == 1 && parent != firstCloudContext.parent)
  3139. toRemove = parent;
  3140. else
  3141. toRemove = pc;
  3142. AddToRemoveList(toRemove, toBeRemoved);
  3143. if (ocIndexSF)
  3144. {
  3145. ScalarType index = static_cast<ScalarType>(++cloudIndex);
  3146. for (unsigned i = 0; i < countAdded; ++i)
  3147. {
  3148. ocIndexSF->setValue(countBefore + i, index);
  3149. }
  3150. }
  3151. }
  3152. else
  3153. {
  3154. ccConsole::Error(tr("Fusion failed! (not enough memory?)"));
  3155. break;
  3156. }
  3157. pc = nullptr;
  3158. }
  3159. }
  3160. //compute min and max once after all appends are done
  3161. if (firstCloud)
  3162. {
  3163. for (unsigned i = 0; i < firstCloud->getNumberOfScalarFields(); i++)
  3164. {
  3165. firstCloud->getScalarField(i)->computeMinAndMax();
  3166. }
  3167. if (ocIndexSF)
  3168. {
  3169. firstCloud->showSF(true);
  3170. }
  3171. }
  3172. //something to remove?
  3173. for (ccHObject* toRemove : toBeRemoved)
  3174. {
  3175. if (firstCloud->isAncestorOf(toRemove))
  3176. {
  3177. // we cannot call 'removeElement' on a child of the first cloud, as it's temporarily detached from the DB tree!
  3178. if (toRemove->getParent())
  3179. toRemove->getParent()->removeChild(toRemove);
  3180. else
  3181. delete toRemove;
  3182. }
  3183. else
  3184. {
  3185. m_ccRoot->removeElement(toRemove);
  3186. }
  3187. }
  3188. toBeRemoved.clear();
  3189. //eventually we can put back the first cloud in DB
  3190. if (firstCloud)
  3191. {
  3192. putObjectBackIntoDBTree(firstCloud, firstCloudContext);
  3193. if (m_ccRoot)
  3194. m_ccRoot->selectEntity(firstCloud);
  3195. }
  3196. }
  3197. //merge meshes?
  3198. else if (!meshes.empty())
  3199. {
  3200. bool createSubMeshes = true;
  3201. //createSubMeshes = (QMessageBox::question(this, tr("Create sub-meshes"), tr("Do you want to create sub-mesh entities corresponding to each source mesh? (requires more memory)"), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes);
  3202. //meshes are merged
  3203. ccPointCloud* baseVertices = new ccPointCloud("vertices");
  3204. ccMesh* baseMesh = new ccMesh(baseVertices);
  3205. baseMesh->setName("Merged mesh");
  3206. baseMesh->addChild(baseVertices);
  3207. baseVertices->setEnabled(false);
  3208. for (ccMesh *mesh : meshes)
  3209. {
  3210. //if (mesh->isA(CC_TYPES::PRIMITIVE))
  3211. //{
  3212. // mesh = mesh->ccMesh::cloneMesh(); //we want a clone of the mesh part, not the primitive!
  3213. //}
  3214. if (!baseMesh->merge(mesh, createSubMeshes))
  3215. {
  3216. ccConsole::Error(tr("Fusion failed! (not enough memory?)"));
  3217. break;
  3218. }
  3219. }
  3220. baseMesh->setDisplay_recursive(meshes.front()->getDisplay());
  3221. baseMesh->setVisible(true);
  3222. addToDB(baseMesh);
  3223. if (m_ccRoot)
  3224. m_ccRoot->selectEntity(baseMesh);
  3225. }
  3226. refreshAll();
  3227. updateUI();
  3228. }
  3229. void MainWindow::zoomOn(ccHObject* object)
  3230. {
  3231. ccGLWindowInterface* win = static_cast<ccGLWindowInterface*>(object->getDisplay());
  3232. if (win)
  3233. {
  3234. ccBBox box = object->getDisplayBB_recursive(false,win);
  3235. win->updateConstellationCenterAndZoom(&box);
  3236. }
  3237. }
  3238. void MainWindow::doActionRegister()
  3239. {
  3240. if ( m_selectedEntities.size() != 2
  3241. || (!m_selectedEntities.front()->isKindOf(CC_TYPES::POINT_CLOUD) && !m_selectedEntities.front()->isKindOf(CC_TYPES::MESH))
  3242. || (!m_selectedEntities.back()->isKindOf(CC_TYPES::POINT_CLOUD) && !m_selectedEntities.back()->isKindOf(CC_TYPES::MESH)) )
  3243. {
  3244. ccConsole::Error(tr("Select 2 point clouds or meshes!"));
  3245. return;
  3246. }
  3247. ccHObject* data = static_cast<ccHObject*>(m_selectedEntities.front());
  3248. ccHObject* model = static_cast<ccHObject*>(m_selectedEntities.back());
  3249. if (data->isKindOf(CC_TYPES::MESH) && model->isKindOf(CC_TYPES::POINT_CLOUD))
  3250. {
  3251. //by default, prefer the mesh as the reference
  3252. std::swap(data, model);
  3253. }
  3254. ccRegistrationDlg rDlg(data, model, this);
  3255. if (!rDlg.exec())
  3256. return;
  3257. //model and data order may have changed!
  3258. model = rDlg.getModelEntity();
  3259. data = rDlg.getDataEntity();
  3260. double minRMSDecrease = rDlg.getMinRMSDecrease();
  3261. if (std::isnan(minRMSDecrease))
  3262. {
  3263. ccLog::Error(tr("Invalid minimum RMS decrease value"));
  3264. return;
  3265. }
  3266. if (minRMSDecrease < ccRegistrationDlg::GetAbsoluteMinRMSDecrease())
  3267. {
  3268. minRMSDecrease = ccRegistrationDlg::GetAbsoluteMinRMSDecrease();
  3269. ccLog::Error(tr("Minimum RMS decrease value is too small.\n%1 will be used instead (numerical accuracy limit).").arg(minRMSDecrease, 0, 'E', 1));
  3270. rDlg.setMinRMSDecrease(minRMSDecrease);
  3271. }
  3272. CCCoreLib::ICPRegistrationTools::Parameters parameters;
  3273. {
  3274. parameters.convType = rDlg.getConvergenceMethod();
  3275. parameters.minRMSDecrease = minRMSDecrease;
  3276. parameters.nbMaxIterations = rDlg.getMaxIterationCount();
  3277. parameters.adjustScale = rDlg.adjustScale();
  3278. parameters.filterOutFarthestPoints = rDlg.removeFarthestPoints();
  3279. parameters.samplingLimit = rDlg.randomSamplingLimit();
  3280. parameters.finalOverlapRatio = rDlg.getFinalOverlap() / 100.0;
  3281. parameters.transformationFilters = rDlg.getTransformationFilters();
  3282. parameters.maxThreadCount = rDlg.getMaxThreadCount();
  3283. parameters.useC2MSignedDistances = rDlg.useC2MSignedDistances(parameters.robustC2MSignedDistances);
  3284. parameters.normalsMatching = rDlg.normalsMatchingOption();
  3285. }
  3286. bool useDataSFAsWeights = rDlg.useDataSFAsWeights();
  3287. bool useModelSFAsWeights = rDlg.useModelSFAsWeights();
  3288. //semi-persistent storage (for next call)
  3289. rDlg.saveParameters();
  3290. ccGLMatrix transMat;
  3291. double finalError = 0.0;
  3292. double finalScale = 1.0;
  3293. unsigned finalPointCount = 0;
  3294. if (ccRegistrationTools::ICP( data,
  3295. model,
  3296. transMat,
  3297. finalScale,
  3298. finalError,
  3299. finalPointCount,
  3300. parameters,
  3301. useDataSFAsWeights,
  3302. useModelSFAsWeights,
  3303. this))
  3304. {
  3305. QString rmsString = tr("Final RMS*: %1 (computed on %2 points)").arg(finalError).arg(finalPointCount);
  3306. QString rmsDisclaimerString = tr("(* RMS is potentially weighted, depending on the selected options)");
  3307. ccLog::Print(QString("[Register] ") + rmsString);
  3308. ccLog::Print(QString("[Register] ") + rmsDisclaimerString);
  3309. QStringList summary;
  3310. summary << rmsString;
  3311. summary << rmsDisclaimerString;
  3312. summary << "----------------";
  3313. //transformation matrix
  3314. {
  3315. summary << "Transformation matrix";
  3316. summary << transMat.toString(3, '\t'); //low precision, just for display
  3317. summary << "----------------";
  3318. ccLog::Print(tr("[Register] Applied transformation matrix:"));
  3319. ccLog::Print(transMat.toString(12, ' ')); //full precision
  3320. ccLog::Print(tr("Hint: copy it (CTRL+C) and apply it - or its inverse - on any entity with the 'Edit > Apply transformation' tool"));
  3321. }
  3322. if (parameters.adjustScale)
  3323. {
  3324. QString scaleString = tr("Scale: %1 (already integrated in above matrix!)").arg(finalScale);
  3325. ccLog::Warning(QString("[Register] ") + scaleString);
  3326. summary << scaleString;
  3327. }
  3328. else
  3329. {
  3330. ccLog::Print(tr("[Register] Scale: fixed (1.0)"));
  3331. summary << tr("Scale: fixed (1.0)");
  3332. }
  3333. //overlap
  3334. summary << "----------------";
  3335. QString overlapString = tr("Theoretical overlap: %1%").arg(static_cast<int>(parameters.finalOverlapRatio * 100));
  3336. ccLog::Print(QString("[Register] ") + overlapString);
  3337. summary << overlapString;
  3338. summary << "----------------";
  3339. summary << tr("This report has been output to Console (F8)");
  3340. //cloud to move
  3341. ccGenericPointCloud* pc = nullptr;
  3342. if (data->isKindOf(CC_TYPES::POINT_CLOUD))
  3343. {
  3344. pc = ccHObjectCaster::ToGenericPointCloud(data);
  3345. }
  3346. else if (data->isKindOf(CC_TYPES::MESH))
  3347. {
  3348. ccGenericMesh* mesh = ccHObjectCaster::ToGenericMesh(data);
  3349. pc = mesh->getAssociatedCloud();
  3350. //warning: point cloud is locked!
  3351. if (pc->isLocked())
  3352. {
  3353. pc = nullptr;
  3354. //we ask the user about cloning the 'data' mesh
  3355. QMessageBox::StandardButton result = QMessageBox::question( this,
  3356. tr("Registration"),
  3357. tr("Data mesh vertices are locked (they may be shared with other meshes): Do you wish to clone this mesh to apply transformation?"),
  3358. QMessageBox::Ok | QMessageBox::Cancel,
  3359. QMessageBox::Ok);
  3360. //continue process?
  3361. if (result == QMessageBox::Ok)
  3362. {
  3363. ccGenericMesh* newMesh = nullptr;
  3364. if (mesh->isA(CC_TYPES::MESH))
  3365. newMesh = static_cast<ccMesh*>(mesh)->cloneMesh();
  3366. else
  3367. {
  3368. //FIXME TODO
  3369. ccLog::Error(tr("Doesn't work on sub-meshes yet!"));
  3370. }
  3371. if (newMesh)
  3372. {
  3373. newMesh->setDisplay(data->getDisplay());
  3374. addToDB(newMesh);
  3375. data = newMesh;
  3376. pc = newMesh->getAssociatedCloud();
  3377. }
  3378. else
  3379. {
  3380. ccLog::Error(tr("Failed to clone 'data' mesh! (not enough memory?)"));
  3381. }
  3382. }
  3383. }
  3384. }
  3385. //if we managed to get a point cloud to move!
  3386. if (pc)
  3387. {
  3388. //we temporarily detach cloud, as it may undergo
  3389. //'severe' modifications (octree deletion, etc.) --> see ccPointCloud::applyRigidTransformation
  3390. ccHObjectContext objContext = removeObjectTemporarilyFromDBTree(pc);
  3391. // check if the 'model' entity is a child of the 'data' one (would be strange, but can still happen!)
  3392. bool modelIsChildOfData = data->isAncestorOf(model);
  3393. if (modelIsChildOfData)
  3394. {
  3395. if (pc->getChildrenNumber() != 0)
  3396. {
  3397. ccLog::Warning(tr("[ICP] The reference entity is a child of the aligned one! CC will move only the aligned entity, and not its children"));
  3398. }
  3399. pc->applyRigidTransformation(transMat);
  3400. }
  3401. else
  3402. {
  3403. // we can safely apply the transformation to all the children
  3404. pc->applyGLTransformation_recursive(&transMat);
  3405. }
  3406. putObjectBackIntoDBTree(pc, objContext);
  3407. //don't forget to update mesh bounding box also!
  3408. if (data->isKindOf(CC_TYPES::MESH))
  3409. {
  3410. ccHObjectCaster::ToGenericMesh(data)->refreshBB();
  3411. }
  3412. //don't forget global shift
  3413. ccGenericPointCloud* refPC = ccHObjectCaster::ToGenericPointCloud(model);
  3414. if (refPC)
  3415. {
  3416. if (refPC->isShifted())
  3417. {
  3418. const CCVector3d& Pshift = refPC->getGlobalShift();
  3419. double scale = refPC->getGlobalScale();
  3420. pc->setGlobalShift(Pshift);
  3421. pc->setGlobalScale(scale);
  3422. ccLog::Warning(tr("[ICP] Aligned entity global shift has been updated to match the reference: (%1,%2,%3) [x%4]").arg(Pshift.x).arg(Pshift.y).arg(Pshift.z).arg(scale));
  3423. ccGLMatrixd transMatD(transMat.data());
  3424. transMatD.scale(1.0 / scale);
  3425. transMatD.setTranslation(transMatD.getTranslationAsVec3D() - Pshift);
  3426. ccLog::Print("[ICP] Transformation to global coordinates:");
  3427. ccLog::Print(transMatD.toString(12, ' ')); //full precision
  3428. }
  3429. else if (pc->isShifted()) //we'll ask the user first before dropping the shift information on the aligned cloud
  3430. {
  3431. if (QMessageBox::question(this, tr("Drop shift information?"), tr("Aligned entity is shifted but reference cloud is not: drop global shift information?"), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
  3432. {
  3433. pc->setGlobalShift(0, 0, 0);
  3434. pc->setGlobalScale(1.0);
  3435. ccLog::Warning(tr("[ICP] Aligned entity global shift has been reset to match the reference!"));
  3436. }
  3437. }
  3438. }
  3439. data->prepareDisplayForRefresh_recursive();
  3440. data->setName(data->getName() + QString(".registered"));
  3441. zoomOn(data);
  3442. }
  3443. //pop-up summary
  3444. QMessageBox::information(this, tr("Registration info"), summary.join("\n"));
  3445. forceConsoleDisplay();
  3446. }
  3447. refreshAll();
  3448. updateUI();
  3449. }
  3450. //Aurelien BEY le 13/11/2008 : ajout de la fonction permettant de traiter la fonctionnalite de recalage grossier
  3451. void MainWindow::doAction4pcsRegister()
  3452. {
  3453. if (QMessageBox::warning( this,
  3454. tr("Work in progress"),
  3455. tr("This method is still under development: are you sure you want to use it? (a crash may likely happen)"),
  3456. QMessageBox::Yes,QMessageBox::No) == QMessageBox::No )
  3457. return;
  3458. if (m_selectedEntities.size() != 2)
  3459. {
  3460. ccConsole::Error(tr("Select 2 point clouds!"));
  3461. return;
  3462. }
  3463. if (!m_selectedEntities.front()->isKindOf(CC_TYPES::POINT_CLOUD) ||
  3464. !m_selectedEntities.back()->isKindOf(CC_TYPES::POINT_CLOUD))
  3465. {
  3466. ccConsole::Error(tr("Select 2 point clouds!"));
  3467. return;
  3468. }
  3469. ccGenericPointCloud* data = ccHObjectCaster::ToGenericPointCloud(m_selectedEntities.back());
  3470. ccGenericPointCloud* model = ccHObjectCaster::ToGenericPointCloud(m_selectedEntities.front());
  3471. ccAlignDlg aDlg(data, model);
  3472. if (!aDlg.exec())
  3473. {
  3474. return;
  3475. }
  3476. // model = aDlg.getModelObject();
  3477. data = aDlg.getDataObject();
  3478. //Take the correct number of points among the clouds
  3479. CCCoreLib::ReferenceCloud* subModel = aDlg.getSampledModel();
  3480. CCCoreLib::ReferenceCloud* subData = aDlg.getSampledData();
  3481. if (!subModel || !subData)
  3482. {
  3483. delete subModel;
  3484. delete subData;
  3485. assert(false);
  3486. return;
  3487. }
  3488. unsigned nbMaxCandidates = aDlg.isNumberOfCandidatesLimited() ? aDlg.getMaxNumberOfCandidates() : 0;
  3489. ccProgressDialog pDlg(true, this);
  3490. CCCoreLib::PointProjectionTools::Transformation transform;
  3491. if (CCCoreLib::FPCSRegistrationTools::RegisterClouds( subModel,
  3492. subData,
  3493. transform,
  3494. static_cast<ScalarType>(aDlg.getDelta()),
  3495. static_cast<ScalarType>(aDlg.getDelta()/2),
  3496. static_cast<PointCoordinateType>(aDlg.getOverlap()),
  3497. aDlg.getNbTries(),
  3498. 5000,
  3499. &pDlg,
  3500. nbMaxCandidates))
  3501. {
  3502. //output resulting transformation matrix
  3503. {
  3504. ccGLMatrix transMat = FromCCLibMatrix<double, float>(transform.R, transform.T);
  3505. forceConsoleDisplay();
  3506. ccConsole::Print(tr("[Align] Resulting matrix:"));
  3507. ccConsole::Print(transMat.toString(12, ' ')); //full precision
  3508. ccConsole::Print(tr("Hint: copy it (CTRL+C) and apply it - or its inverse - on any entity with the 'Edit > Apply transformation' tool"));
  3509. }
  3510. ccPointCloud* newDataCloud = data->isA(CC_TYPES::POINT_CLOUD) ? static_cast<ccPointCloud*>(data)->cloneThis() : ccPointCloud::From(data, data);
  3511. if (data->getParent())
  3512. {
  3513. data->getParent()->addChild(newDataCloud);
  3514. }
  3515. newDataCloud->setName(data->getName() + QString(".registered"));
  3516. transform.apply(*newDataCloud);
  3517. newDataCloud->invalidateBoundingBox(); //invalidate bb
  3518. newDataCloud->setDisplay(data->getDisplay());
  3519. newDataCloud->prepareDisplayForRefresh();
  3520. zoomOn(newDataCloud);
  3521. addToDB(newDataCloud);
  3522. data->setEnabled(false);
  3523. data->prepareDisplayForRefresh_recursive();
  3524. }
  3525. else
  3526. {
  3527. ccConsole::Warning(tr("[Align] Registration failed!"));
  3528. }
  3529. delete subModel;
  3530. subModel = nullptr;
  3531. delete subData;
  3532. subData = nullptr;
  3533. refreshAll();
  3534. updateUI();
  3535. }
  3536. void MainWindow::doActionSubsample()
  3537. {
  3538. //find candidates
  3539. std::vector<ccPointCloud*> clouds;
  3540. unsigned maxPointCount = 0;
  3541. double maxCloudRadius = 0;
  3542. ScalarType sfMin = CCCoreLib::NAN_VALUE;
  3543. ScalarType sfMax = CCCoreLib::NAN_VALUE;
  3544. {
  3545. for ( ccHObject* entity : getSelectedEntities() )
  3546. {
  3547. if (entity->isA(CC_TYPES::POINT_CLOUD))
  3548. {
  3549. ccPointCloud* cloud = static_cast<ccPointCloud*>(entity);
  3550. clouds.push_back(cloud);
  3551. maxPointCount = std::max<unsigned>(maxPointCount, cloud->size());
  3552. maxCloudRadius = std::max<double>(maxCloudRadius, cloud->getOwnBB().getDiagNorm());
  3553. //we also look for the min and max sf values
  3554. ccScalarField* sf = cloud->getCurrentDisplayedScalarField();
  3555. if (sf)
  3556. {
  3557. if (!ccScalarField::ValidValue(sfMin) || sfMin > sf->getMin())
  3558. sfMin = sf->getMin();
  3559. if (!ccScalarField::ValidValue(sfMax) || sfMax < sf->getMax())
  3560. sfMax = sf->getMax();
  3561. }
  3562. }
  3563. }
  3564. }
  3565. if (clouds.empty())
  3566. {
  3567. ccConsole::Error(tr("Select at least one point cloud!"));
  3568. return;
  3569. }
  3570. //Display dialog
  3571. ccSubsamplingDlg sDlg(maxPointCount, maxCloudRadius, this);
  3572. sDlg.loadFromPersistentSettings();
  3573. bool hasValidSF = ccScalarField::ValidValue(sfMin) && ccScalarField::ValidValue(sfMax);
  3574. if (hasValidSF)
  3575. {
  3576. sDlg.enableSFModulation(sfMin, sfMax);
  3577. }
  3578. if (!sDlg.exec())
  3579. {
  3580. return;
  3581. }
  3582. sDlg.saveToPersistentSettings();
  3583. //process clouds
  3584. ccHObject::Container resultingClouds;
  3585. {
  3586. ccProgressDialog pDlg(false, this);
  3587. pDlg.setAutoClose(false);
  3588. pDlg.setMethodTitle(tr("Subsampling"));
  3589. bool errors = false;
  3590. QElapsedTimer eTimer;
  3591. eTimer.start();
  3592. for (size_t i = 0; i < clouds.size(); ++i)
  3593. {
  3594. ccPointCloud* cloud = clouds[i];
  3595. CCCoreLib::ReferenceCloud* sampledCloud = sDlg.getSampledCloud(cloud,&pDlg);
  3596. if (!sampledCloud)
  3597. {
  3598. ccConsole::Warning(tr("[Subsampling] Failed to subsample cloud '%1'!").arg(cloud->getName()));
  3599. errors = true;
  3600. continue;
  3601. }
  3602. int warnings = 0;
  3603. ccPointCloud* newPointCloud = cloud->partialClone(sampledCloud, &warnings);
  3604. delete sampledCloud;
  3605. sampledCloud = nullptr;
  3606. if (newPointCloud)
  3607. {
  3608. newPointCloud->setName(cloud->getName() + QString(".subsampled"));
  3609. newPointCloud->copyGlobalShiftAndScale(*cloud);
  3610. newPointCloud->setDisplay(cloud->getDisplay());
  3611. newPointCloud->prepareDisplayForRefresh();
  3612. if (cloud->getParent())
  3613. cloud->getParent()->addChild(newPointCloud);
  3614. cloud->setEnabled(false);
  3615. addToDB(newPointCloud);
  3616. newPointCloud->prepareDisplayForRefresh();
  3617. resultingClouds.push_back(newPointCloud);
  3618. if (warnings)
  3619. {
  3620. ccLog::Warning(tr("[Subsampling] Not enough memory: colors, normals or scalar fields may be missing!"));
  3621. errors = true;
  3622. }
  3623. }
  3624. else
  3625. {
  3626. ccLog::Error(tr("Not enough memory!"));
  3627. break;
  3628. }
  3629. }
  3630. ccLog::Print("[Subsampling] Timing: %3.3f s.",eTimer.elapsed()/1000.0);
  3631. if (errors)
  3632. {
  3633. ccLog::Error(tr("Errors occurred (see console)"));
  3634. }
  3635. }
  3636. if (m_ccRoot)
  3637. m_ccRoot->selectEntities(resultingClouds);
  3638. refreshAll();
  3639. updateUI();
  3640. }
  3641. void MainWindow::doActionStatisticalTest()
  3642. {
  3643. if ( !ccEntityAction::statisticalTest(m_selectedEntities, this ) )
  3644. return;
  3645. refreshAll();
  3646. updateUI();
  3647. }
  3648. void MainWindow::doActionComputeStatParams()
  3649. {
  3650. ccEntityAction::computeStatParams(m_selectedEntities, this );
  3651. }
  3652. struct ComponentIndexAndSize
  3653. {
  3654. unsigned index;
  3655. unsigned size;
  3656. ComponentIndexAndSize(unsigned i, unsigned s) : index(i), size(s) {}
  3657. static bool DescendingCompOperator(const ComponentIndexAndSize& a, const ComponentIndexAndSize& b)
  3658. {
  3659. return a.size > b.size;
  3660. }
  3661. };
  3662. void MainWindow::createComponentsClouds(ccGenericPointCloud* cloud,
  3663. CCCoreLib::ReferenceCloudContainer& components,
  3664. unsigned minPointsPerComponent,
  3665. bool randomColors,
  3666. bool selectComponents,
  3667. bool sortBysize/*=true*/)
  3668. {
  3669. if (!cloud || components.empty())
  3670. return;
  3671. std::vector<ComponentIndexAndSize> sortedIndexes;
  3672. std::vector<ComponentIndexAndSize>* _sortedIndexes = nullptr;
  3673. if (sortBysize)
  3674. {
  3675. try
  3676. {
  3677. sortedIndexes.reserve(components.size());
  3678. }
  3679. catch (const std::bad_alloc&)
  3680. {
  3681. ccLog::Warning(tr("[CreateComponentsClouds] Not enough memory to sort components by size!"));
  3682. sortBysize = false;
  3683. }
  3684. if (sortBysize) //still ok?
  3685. {
  3686. unsigned compCount = static_cast<unsigned>(components.size());
  3687. for (unsigned i = 0; i < compCount; ++i)
  3688. {
  3689. sortedIndexes.emplace_back(i, components[i]->size());
  3690. }
  3691. ParallelSort(sortedIndexes.begin(), sortedIndexes.end(), ComponentIndexAndSize::DescendingCompOperator);
  3692. _sortedIndexes = &sortedIndexes;
  3693. }
  3694. }
  3695. //we create "real" point clouds for all input components
  3696. {
  3697. ccPointCloud* pc = cloud->isA(CC_TYPES::POINT_CLOUD) ? static_cast<ccPointCloud*>(cloud) : nullptr;
  3698. //we create a new group to store all CCs
  3699. ccHObject* ccGroup = new ccHObject(cloud->getName() + QString(" [CCs]"));
  3700. //for each component
  3701. for (size_t i = 0; i < components.size(); ++i)
  3702. {
  3703. CCCoreLib::ReferenceCloud* compIndexes = _sortedIndexes ? components[_sortedIndexes->at(i).index] : components[i];
  3704. //if it has enough points
  3705. if (compIndexes->size() >= minPointsPerComponent)
  3706. {
  3707. //we create a new entity
  3708. ccPointCloud* compCloud = (pc ? pc->partialClone(compIndexes) : ccPointCloud::From(compIndexes));
  3709. if (compCloud)
  3710. {
  3711. //shall we colorize it with random color?
  3712. if (randomColors)
  3713. {
  3714. ccColor::Rgb col = ccColor::Generator::Random();
  3715. compCloud->setColor(col);
  3716. compCloud->showColors(true);
  3717. compCloud->showSF(false);
  3718. }
  3719. //'shift on load' information
  3720. if (pc)
  3721. {
  3722. compCloud->copyGlobalShiftAndScale(*pc);
  3723. }
  3724. compCloud->setVisible(true);
  3725. compCloud->setName(QString("CC#%1").arg(ccGroup->getChildrenNumber()));
  3726. //we add new CC to group
  3727. ccGroup->addChild(compCloud);
  3728. if (selectComponents && m_ccRoot)
  3729. m_ccRoot->selectEntity(compCloud, true);
  3730. }
  3731. else
  3732. {
  3733. ccConsole::Warning(tr("[CreateComponentsClouds] Failed to create component #%1! (not enough memory)").arg(ccGroup->getChildrenNumber() + 1));
  3734. }
  3735. }
  3736. delete compIndexes;
  3737. compIndexes = nullptr;
  3738. }
  3739. components.clear();
  3740. if (ccGroup->getChildrenNumber() == 0)
  3741. {
  3742. ccConsole::Error(tr("No component was created! Check the minimum size..."));
  3743. delete ccGroup;
  3744. ccGroup = nullptr;
  3745. }
  3746. else
  3747. {
  3748. ccGroup->setDisplay(cloud->getDisplay());
  3749. addToDB(ccGroup);
  3750. ccConsole::Print(tr("[CreateComponentsClouds] %1 component(s) were created from cloud '%2'").arg(ccGroup->getChildrenNumber()).arg(cloud->getName()));
  3751. }
  3752. cloud->prepareDisplayForRefresh();
  3753. //auto-hide original cloud
  3754. if (ccGroup)
  3755. {
  3756. cloud->setEnabled(false);
  3757. ccConsole::Warning(tr("[CreateComponentsClouds] Original cloud has been automatically hidden"));
  3758. }
  3759. }
  3760. }
  3761. void MainWindow::doActionLabelConnectedComponents()
  3762. {
  3763. //keep only the point clouds!
  3764. std::vector<ccGenericPointCloud*> clouds;
  3765. {
  3766. for ( ccHObject *entity : getSelectedEntities() )
  3767. {
  3768. if (entity->isKindOf(CC_TYPES::POINT_CLOUD))
  3769. clouds.push_back(ccHObjectCaster::ToGenericPointCloud(entity));
  3770. }
  3771. }
  3772. size_t count = clouds.size();
  3773. if (count == 0)
  3774. return;
  3775. static int s_octreeLevel = 8;
  3776. static unsigned s_minComponentSize = 10;
  3777. static bool s_randomColors = false;
  3778. ccLabelingDlg dlg(this);
  3779. if (count == 1)
  3780. dlg.octreeLevelSpinBox->setCloud(clouds.front());
  3781. dlg.setOctreeLevel(s_octreeLevel);
  3782. dlg.setMinPointsNb(s_minComponentSize);
  3783. dlg.setRandomColors(s_randomColors);
  3784. if (!dlg.exec())
  3785. return;
  3786. s_octreeLevel = dlg.getOctreeLevel();
  3787. s_minComponentSize = static_cast<unsigned>(std::max(0, dlg.getMinPointsNb()));
  3788. s_randomColors = dlg.randomColors();
  3789. ccProgressDialog pDlg(false, this);
  3790. pDlg.setAutoClose(false);
  3791. //we unselect all entities as we are going to automatically select the created components
  3792. //(otherwise the user won't perceive the change!)
  3793. if (m_ccRoot)
  3794. {
  3795. m_ccRoot->unselectAllEntities();
  3796. }
  3797. for ( ccGenericPointCloud *cloud : clouds )
  3798. {
  3799. if (cloud && cloud->isA(CC_TYPES::POINT_CLOUD))
  3800. {
  3801. ccPointCloud* pc = static_cast<ccPointCloud*>(cloud);
  3802. ccOctree::Shared theOctree = cloud->getOctree();
  3803. if (!theOctree)
  3804. {
  3805. ccProgressDialog pOctreeDlg(true, this);
  3806. theOctree = cloud->computeOctree(&pOctreeDlg);
  3807. if (!theOctree)
  3808. {
  3809. ccConsole::Error(tr("Couldn't compute octree for cloud '%1'!").arg(cloud->getName()));
  3810. break;
  3811. }
  3812. }
  3813. //we create/activate CCs label scalar field
  3814. int sfIdx = pc->getScalarFieldIndexByName(CC_CONNECTED_COMPONENTS_DEFAULT_LABEL_NAME);
  3815. if (sfIdx < 0)
  3816. {
  3817. sfIdx = pc->addScalarField(CC_CONNECTED_COMPONENTS_DEFAULT_LABEL_NAME);
  3818. }
  3819. if (sfIdx < 0)
  3820. {
  3821. ccConsole::Error(tr("Couldn't allocate a new scalar field for computing CC labels! Try to free some memory ..."));
  3822. break;
  3823. }
  3824. pc->setCurrentScalarField(sfIdx);
  3825. //we try to label all CCs
  3826. CCCoreLib::ReferenceCloudContainer components;
  3827. int componentCount = CCCoreLib::AutoSegmentationTools::labelConnectedComponents(cloud,
  3828. static_cast<unsigned char>(s_octreeLevel),
  3829. false,
  3830. &pDlg,
  3831. theOctree.data());
  3832. if (componentCount >= 0)
  3833. {
  3834. //if successful, we extract each CC (stored in "components")
  3835. //safety test
  3836. int realComponentCount = 0;
  3837. {
  3838. for (size_t i = 0; i < components.size(); ++i)
  3839. {
  3840. if (components[i]->size() >= s_minComponentSize)
  3841. {
  3842. ++realComponentCount;
  3843. }
  3844. }
  3845. }
  3846. if (realComponentCount > 500)
  3847. {
  3848. //too many components
  3849. if (QMessageBox::warning(this, tr("Many components"), tr("Do you really expect up to %1 components?\n(this may take a lot of time to process and display)").arg(realComponentCount), QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
  3850. {
  3851. //cancel
  3852. pc->deleteScalarField(sfIdx);
  3853. if (pc->getNumberOfScalarFields() != 0)
  3854. {
  3855. pc->setCurrentDisplayedScalarField(static_cast<int>(pc->getNumberOfScalarFields()) - 1);
  3856. }
  3857. else
  3858. {
  3859. pc->showSF(false);
  3860. }
  3861. pc->prepareDisplayForRefresh();
  3862. continue;
  3863. }
  3864. }
  3865. pc->getCurrentInScalarField()->computeMinAndMax();
  3866. if (!CCCoreLib::AutoSegmentationTools::extractConnectedComponents(cloud, components))
  3867. {
  3868. ccConsole::Warning(tr("[DoActionLabelConnectedComponents] Something went wrong while extracting CCs from cloud %1...").arg(cloud->getName()));
  3869. }
  3870. }
  3871. else
  3872. {
  3873. ccConsole::Warning(tr("[DoActionLabelConnectedComponents] Something went wrong while extracting CCs from cloud %1...").arg(cloud->getName()));
  3874. }
  3875. //we delete the CCs label scalar field (we don't need it anymore)
  3876. pc->deleteScalarField(sfIdx);
  3877. sfIdx = -1;
  3878. //we create "real" point clouds for all CCs
  3879. if (!components.empty())
  3880. {
  3881. createComponentsClouds(cloud, components, s_minComponentSize, s_randomColors, true);
  3882. }
  3883. }
  3884. }
  3885. refreshAll();
  3886. updateUI();
  3887. }
  3888. void MainWindow::doActionSetSFAsCoord()
  3889. {
  3890. if (!ccEntityAction::sfSetAsCoord(m_selectedEntities, this))
  3891. {
  3892. return;
  3893. }
  3894. zoomOnSelectedEntities();
  3895. updateUI();
  3896. }
  3897. void MainWindow::doActionExportCoordToSF()
  3898. {
  3899. if (!ccEntityAction::exportCoordToSF(m_selectedEntities, this))
  3900. {
  3901. return;
  3902. }
  3903. refreshAll();
  3904. updateUI();
  3905. }
  3906. void MainWindow::doActionExportNormalToSF()
  3907. {
  3908. if (!ccEntityAction::exportNormalToSF(m_selectedEntities, this))
  3909. {
  3910. return;
  3911. }
  3912. refreshAll();
  3913. updateUI();
  3914. }
  3915. void MainWindow::doActionSetSFsAsNormal()
  3916. {
  3917. if (!haveOneSelection())
  3918. {
  3919. if (haveSelection())
  3920. ccConsole::Error(tr("Select only one cloud or one mesh!"));
  3921. return;
  3922. }
  3923. ccHObject* ent = m_selectedEntities.front();
  3924. if (!ccEntityAction::setSFsAsNormal(ent, this))
  3925. {
  3926. return;
  3927. }
  3928. refreshAll();
  3929. updateUI();
  3930. }
  3931. void MainWindow::doMeshTwoPolylines()
  3932. {
  3933. if (m_selectedEntities.size() != 2)
  3934. return;
  3935. ccPolyline* p1 = ccHObjectCaster::ToPolyline(m_selectedEntities.front());
  3936. ccPolyline* p2 = ccHObjectCaster::ToPolyline(m_selectedEntities.back());
  3937. if (!p1 || !p2)
  3938. {
  3939. ccConsole::Error(tr("Select 2 and only 2 polylines"));
  3940. return;
  3941. }
  3942. //Ask the user how the 2D projection should be computed
  3943. bool useViewingDir = false;
  3944. CCVector3 viewingDir(0, 0, 0);
  3945. if (p1->getDisplay())
  3946. {
  3947. useViewingDir = (QMessageBox::question(this, tr("Projection method"), tr("Use best fit plane (yes) or the current viewing direction (no)"), QMessageBox::Yes, QMessageBox::No) == QMessageBox::No);
  3948. if (useViewingDir)
  3949. {
  3950. viewingDir = -p1->getDisplay()->getViewportParameters().getViewDir().toPC();
  3951. }
  3952. }
  3953. ccMesh* mesh = ccMesh::TriangulateTwoPolylines(p1, p2, useViewingDir ? &viewingDir : nullptr);
  3954. if (mesh)
  3955. {
  3956. addToDB(mesh);
  3957. if (mesh->computePerVertexNormals())
  3958. {
  3959. mesh->showNormals(true);
  3960. }
  3961. else
  3962. {
  3963. ccLog::Warning(tr("[Mesh two polylines] Failed to compute normals!"));
  3964. }
  3965. if (mesh->getDisplay())
  3966. {
  3967. mesh->getDisplay()->redraw();
  3968. }
  3969. }
  3970. else
  3971. {
  3972. ccLog::Error(tr("Failed to create mesh (see Console)"));
  3973. forceConsoleDisplay();
  3974. }
  3975. }
  3976. void MainWindow::doConvertPolylinesToMesh()
  3977. {
  3978. if (!haveSelection())
  3979. return;
  3980. std::vector<ccPolyline*> polylines;
  3981. try
  3982. {
  3983. if (haveOneSelection() && m_selectedEntities.back()->isA(CC_TYPES::HIERARCHY_OBJECT))
  3984. {
  3985. ccHObject* obj = m_selectedEntities.back();
  3986. for (unsigned i = 0; i < obj->getChildrenNumber(); ++i)
  3987. {
  3988. if (obj->getChild(i)->isA(CC_TYPES::POLY_LINE))
  3989. polylines.push_back(static_cast<ccPolyline*>(obj->getChild(i)));
  3990. }
  3991. }
  3992. else
  3993. {
  3994. for ( ccHObject *entity : getSelectedEntities() )
  3995. {
  3996. if (entity->isA(CC_TYPES::POLY_LINE))
  3997. {
  3998. polylines.push_back(static_cast<ccPolyline*>(entity));
  3999. }
  4000. }
  4001. }
  4002. }
  4003. catch (const std::bad_alloc&)
  4004. {
  4005. ccConsole::Error(tr("Not enough memory!"));
  4006. return;
  4007. }
  4008. if (polylines.empty())
  4009. {
  4010. ccConsole::Error(tr("Select a group of polylines or multiple polylines (contour plot)!"));
  4011. return;
  4012. }
  4013. ccPickOneElementDlg poeDlg(tr("Projection dimension"), tr("Contour plot to mesh"), this);
  4014. poeDlg.addElement("X");
  4015. poeDlg.addElement("Y");
  4016. poeDlg.addElement("Z");
  4017. poeDlg.setDefaultIndex(2);
  4018. if (!poeDlg.exec())
  4019. return;
  4020. int dim = poeDlg.getSelectedIndex();
  4021. assert(dim >= 0 && dim < 3);
  4022. const unsigned char Z = static_cast<unsigned char>(dim);
  4023. const unsigned char X = (Z == 2 ? 0 : Z + 1);
  4024. const unsigned char Y = (X == 2 ? 0 : X + 1);
  4025. //number of segments
  4026. unsigned segmentCount = 0;
  4027. unsigned vertexCount = 0;
  4028. {
  4029. for ( ccPolyline *poly : polylines )
  4030. {
  4031. if (poly)
  4032. {
  4033. //count the total number of vertices and segments
  4034. vertexCount += poly->size();
  4035. segmentCount += poly->segmentCount();
  4036. }
  4037. }
  4038. }
  4039. if (segmentCount < 2)
  4040. {
  4041. //not enough points/segments
  4042. ccLog::Error(tr("Not enough segments!"));
  4043. return;
  4044. }
  4045. //we assume we link with CGAL now (if not the call to Delaunay2dMesh::buildMesh will fail anyway)
  4046. std::vector<CCVector2> points2D;
  4047. std::vector<int> segments2D;
  4048. try
  4049. {
  4050. points2D.reserve(vertexCount);
  4051. segments2D.reserve(segmentCount * 2);
  4052. }
  4053. catch (const std::bad_alloc&)
  4054. {
  4055. //not enough memory
  4056. ccLog::Error(tr("Not enough memory!"));
  4057. return;
  4058. }
  4059. //fill arrays
  4060. {
  4061. for ( ccPolyline *poly : polylines )
  4062. {
  4063. if (poly == nullptr)
  4064. continue;
  4065. unsigned vertCount = poly->size();
  4066. int vertIndex0 = static_cast<int>(points2D.size());
  4067. bool closed = poly->isClosed();
  4068. for (unsigned v = 0; v < vertCount; ++v)
  4069. {
  4070. const CCVector3* P = poly->getPoint(v);
  4071. int vertIndex = static_cast<int>(points2D.size());
  4072. points2D.push_back(CCVector2(P->u[X], P->u[Y]));
  4073. if (v + 1 < vertCount)
  4074. {
  4075. segments2D.push_back(vertIndex);
  4076. segments2D.push_back(vertIndex + 1);
  4077. }
  4078. else if (closed)
  4079. {
  4080. segments2D.push_back(vertIndex);
  4081. segments2D.push_back(vertIndex0);
  4082. }
  4083. }
  4084. }
  4085. assert(points2D.size() == vertexCount);
  4086. assert(segments2D.size() == segmentCount * 2);
  4087. }
  4088. CCCoreLib::Delaunay2dMesh* delaunayMesh = new CCCoreLib::Delaunay2dMesh;
  4089. std::string errorStr;
  4090. if (!delaunayMesh->buildMesh(points2D, segments2D, errorStr))
  4091. {
  4092. ccLog::Error( tr("Third party library error: %1").arg( QString::fromStdString( errorStr ) ) );
  4093. delete delaunayMesh;
  4094. return;
  4095. }
  4096. ccPointCloud* vertices = new ccPointCloud("vertices");
  4097. if (!vertices->reserve(vertexCount))
  4098. {
  4099. //not enough memory
  4100. ccLog::Error(tr("Not enough memory!"));
  4101. delete vertices;
  4102. delete delaunayMesh;
  4103. return;
  4104. }
  4105. //fill vertices cloud
  4106. {
  4107. for ( ccPolyline *poly : polylines )
  4108. {
  4109. unsigned vertCount = poly->size();
  4110. for (unsigned v = 0; v < vertCount; ++v)
  4111. {
  4112. const CCVector3* P = poly->getPoint(v);
  4113. vertices->addPoint(*P);
  4114. }
  4115. }
  4116. delaunayMesh->linkMeshWith(vertices, false);
  4117. }
  4118. #ifdef QT_DEBUG
  4119. //Test delaunay output
  4120. {
  4121. unsigned vertCount = vertices->size();
  4122. for (unsigned i = 0; i < delaunayMesh->size(); ++i)
  4123. {
  4124. const CCCoreLib::VerticesIndexes* tsi = delaunayMesh->getTriangleVertIndexes(i);
  4125. assert(tsi->i1 < vertCount && tsi->i2 < vertCount && tsi->i3 < vertCount);
  4126. }
  4127. }
  4128. #endif
  4129. ccMesh* mesh = new ccMesh(delaunayMesh, vertices);
  4130. if (mesh->size() != delaunayMesh->size())
  4131. {
  4132. //not enough memory (error will be issued later)
  4133. delete mesh;
  4134. mesh = nullptr;
  4135. }
  4136. //don't need this anymore
  4137. delete delaunayMesh;
  4138. delaunayMesh = nullptr;
  4139. if (mesh)
  4140. {
  4141. mesh->addChild(vertices);
  4142. mesh->setVisible(true);
  4143. vertices->setEnabled(false);
  4144. addToDB(mesh);
  4145. if (mesh->computePerVertexNormals())
  4146. {
  4147. mesh->showNormals(true);
  4148. }
  4149. else
  4150. {
  4151. ccLog::Warning(tr("[Contour plot to mesh] Failed to compute normals!"));
  4152. }
  4153. if (mesh->getDisplay())
  4154. {
  4155. mesh->getDisplay()->redraw();
  4156. }
  4157. //global shift & scale (we copy it from the first polyline by default)
  4158. mesh->copyGlobalShiftAndScale(*polylines.front());
  4159. }
  4160. else
  4161. {
  4162. ccLog::Error(tr("Not enough memory!"));
  4163. delete vertices;
  4164. vertices = nullptr;
  4165. }
  4166. }
  4167. void MainWindow::doCompute2HalfDimVolume()
  4168. {
  4169. if (m_selectedEntities.empty() || m_selectedEntities.size() > 2)
  4170. {
  4171. ccConsole::Error(tr("Select one or two point clouds!"));
  4172. return;
  4173. }
  4174. ccGenericPointCloud* cloud1 = nullptr;
  4175. {
  4176. ccHObject* ent = m_selectedEntities.front();
  4177. if (!ent->isKindOf(CC_TYPES::POINT_CLOUD) )
  4178. {
  4179. ccConsole::Error(tr("Select point clouds only!"));
  4180. return;
  4181. }
  4182. else
  4183. {
  4184. cloud1 = ccHObjectCaster::ToGenericPointCloud(ent);
  4185. }
  4186. }
  4187. ccGenericPointCloud* cloud2 = nullptr;
  4188. if (m_selectedEntities.size() > 1)
  4189. {
  4190. ccHObject* ent = m_selectedEntities[1];
  4191. if (!ent->isKindOf(CC_TYPES::POINT_CLOUD) )
  4192. {
  4193. ccConsole::Error(tr("Select point clouds only!"));
  4194. return;
  4195. }
  4196. else
  4197. {
  4198. cloud2 = ccHObjectCaster::ToGenericPointCloud(ent);
  4199. }
  4200. }
  4201. ccVolumeCalcTool calcVolumeTool(cloud1, cloud2, this);
  4202. calcVolumeTool.exec();
  4203. }
  4204. void MainWindow::doActionRasterize()
  4205. {
  4206. if (!haveOneSelection())
  4207. {
  4208. ccConsole::Error(tr("Select only one point cloud!"));
  4209. return;
  4210. }
  4211. ccHObject* ent = m_selectedEntities.front();
  4212. if (!ent->isKindOf(CC_TYPES::POINT_CLOUD) )
  4213. {
  4214. ccConsole::Error(tr("Select a point cloud!"));
  4215. return;
  4216. }
  4217. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(ent);
  4218. ccRasterizeTool rasterizeTool(cloud, this);
  4219. rasterizeTool.exec();
  4220. }
  4221. void MainWindow::doActionDeleteScanGrids()
  4222. {
  4223. //look for clouds with scan grids
  4224. for ( ccHObject *entity : getSelectedEntities() )
  4225. {
  4226. if (!entity || !entity->isA(CC_TYPES::POINT_CLOUD))
  4227. {
  4228. continue;
  4229. }
  4230. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(entity);
  4231. assert(cloud);
  4232. if(cloud->gridCount() > 0)
  4233. {
  4234. cloud->removeGrids();
  4235. }
  4236. }
  4237. refreshAll();
  4238. updateUI();
  4239. }
  4240. void MainWindow::doActionMeshScanGrids()
  4241. {
  4242. //ask the user for the min angle (inside triangles)
  4243. static double s_meshMinTriangleAngle_deg = 1.0;
  4244. {
  4245. bool ok = true;
  4246. double minAngle_deg = QInputDialog::getDouble(this, tr("Triangulate"), tr("Min triangle angle (in degrees)"), s_meshMinTriangleAngle_deg, 0, 90.0, 3, &ok);
  4247. if (!ok)
  4248. return;
  4249. s_meshMinTriangleAngle_deg = minAngle_deg;
  4250. }
  4251. //look for clouds with scan grids
  4252. for ( ccHObject *entity : getSelectedEntities() )
  4253. {
  4254. if (!entity || !entity->isA(CC_TYPES::POINT_CLOUD))
  4255. {
  4256. continue;
  4257. }
  4258. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(entity);
  4259. assert(cloud);
  4260. for (size_t i = 0; i < cloud->gridCount(); ++i)
  4261. {
  4262. ccPointCloud::Grid::Shared grid = cloud->grid(i);
  4263. if (!grid)
  4264. {
  4265. assert(false);
  4266. continue;
  4267. }
  4268. ccMesh* gridMesh = cloud->triangulateGrid(*grid, s_meshMinTriangleAngle_deg);
  4269. if (gridMesh)
  4270. {
  4271. cloud->addChild(gridMesh);
  4272. cloud->setVisible(false); //hide the cloud
  4273. gridMesh->setDisplay(cloud->getDisplay());
  4274. addToDB(gridMesh, false, true, false, false);
  4275. gridMesh->prepareDisplayForRefresh();
  4276. }
  4277. }
  4278. }
  4279. refreshAll();
  4280. updateUI();
  4281. }
  4282. void MainWindow::doActionComputeMeshAA()
  4283. {
  4284. doActionComputeMesh(CCCoreLib::DELAUNAY_2D_AXIS_ALIGNED);
  4285. }
  4286. void MainWindow::doActionComputeMeshLS()
  4287. {
  4288. doActionComputeMesh(CCCoreLib::DELAUNAY_2D_BEST_LS_PLANE);
  4289. }
  4290. void MainWindow::doActionComputeMesh(CCCoreLib::TRIANGULATION_TYPES type)
  4291. {
  4292. //ask the user for the max edge length
  4293. static double s_meshMaxEdgeLength = 0.0;
  4294. {
  4295. bool ok = true;
  4296. double maxEdgeLength = QInputDialog::getDouble(this, tr("Triangulate"), tr("Max edge length (0 = no limit)"), s_meshMaxEdgeLength, 0, 1.0e9, 8, &ok);
  4297. if (!ok)
  4298. return;
  4299. s_meshMaxEdgeLength = maxEdgeLength;
  4300. }
  4301. //select candidates
  4302. ccHObject::Container clouds;
  4303. bool hadNormals = false;
  4304. {
  4305. for ( ccHObject *entity : getSelectedEntities() )
  4306. {
  4307. if (entity->isKindOf(CC_TYPES::POINT_CLOUD))
  4308. {
  4309. clouds.push_back(entity);
  4310. if (entity->isA(CC_TYPES::POINT_CLOUD))
  4311. {
  4312. hadNormals |= static_cast<ccPointCloud*>(entity)->hasNormals();
  4313. }
  4314. }
  4315. }
  4316. }
  4317. //if the cloud(s) already had normals, ask the use if wants to update them or keep them as is (can look strange!)
  4318. bool updateNormals = false;
  4319. if (hadNormals)
  4320. {
  4321. updateNormals = (QMessageBox::question( this,
  4322. tr("Keep old normals?"),
  4323. tr("Cloud(s) already have normals. Do you want to update them (yes) or keep the old ones (no)?"),
  4324. QMessageBox::Yes,
  4325. QMessageBox::No ) == QMessageBox::Yes);
  4326. }
  4327. ccProgressDialog pDlg(false, this);
  4328. pDlg.setAutoClose(false);
  4329. pDlg.setWindowTitle(tr("Triangulation"));
  4330. pDlg.setInfo(tr("Triangulation in progress..."));
  4331. pDlg.setRange(0, 0);
  4332. pDlg.show();
  4333. QApplication::processEvents();
  4334. bool errors = false;
  4335. for (size_t i = 0; i < clouds.size(); ++i)
  4336. {
  4337. ccHObject* ent = clouds[i];
  4338. assert(ent->isKindOf(CC_TYPES::POINT_CLOUD));
  4339. //compute mesh
  4340. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(ent);
  4341. ccMesh* mesh = ccMesh::Triangulate( cloud,
  4342. type,
  4343. updateNormals,
  4344. static_cast<PointCoordinateType>(s_meshMaxEdgeLength),
  4345. 2 //XY plane by default
  4346. );
  4347. if (mesh)
  4348. {
  4349. cloud->setVisible(false); //can't disable the cloud as the resulting mesh will be its child!
  4350. cloud->addChild(mesh);
  4351. cloud->prepareDisplayForRefresh_recursive();
  4352. addToDB(mesh);
  4353. if (i == 0)
  4354. {
  4355. m_ccRoot->selectEntity(mesh); //auto-select first element
  4356. }
  4357. }
  4358. else
  4359. {
  4360. errors = true;
  4361. }
  4362. }
  4363. if (errors)
  4364. {
  4365. ccConsole::Error(tr("Error(s) occurred! See the Console messages"));
  4366. }
  4367. refreshAll();
  4368. updateUI();
  4369. }
  4370. void MainWindow::doActionFitQuadric()
  4371. {
  4372. bool errors = false;
  4373. //for all selected entities
  4374. for ( ccHObject *entity : getSelectedEntities() )
  4375. {
  4376. //look for clouds
  4377. if (entity->isKindOf(CC_TYPES::POINT_CLOUD))
  4378. {
  4379. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(entity);
  4380. double rms = 0.0;
  4381. ccQuadric* quadric = ccQuadric::Fit(cloud, &rms);
  4382. if (quadric)
  4383. {
  4384. cloud->addChild(quadric);
  4385. quadric->setName(QString("Quadric (%1)").arg(cloud->getName()));
  4386. quadric->setDisplay(cloud->getDisplay());
  4387. quadric->prepareDisplayForRefresh();
  4388. quadric->copyGlobalShiftAndScale(*cloud);
  4389. addToDB(quadric);
  4390. ccConsole::Print(tr("[DoActionFitQuadric] Quadric local coordinate system:"));
  4391. ccConsole::Print(quadric->getTransformation().toString(12,' ')); //full precision
  4392. ccConsole::Print(tr("[DoActionFitQuadric] Quadric equation (in local coordinate system): ") + quadric->getEquationString());
  4393. ccConsole::Print(QString("[DoActionFitQuadric] RMS: %1").arg(rms));
  4394. #if 0
  4395. //test: project the input cloud on the quadric
  4396. if (cloud->isA(CC_TYPES::POINT_CLOUD))
  4397. {
  4398. ccPointCloud* newCloud = static_cast<ccPointCloud*>(cloud)->cloneThis();
  4399. if (newCloud)
  4400. {
  4401. const PointCoordinateType* eq = quadric->getEquationCoefs();
  4402. const Tuple3ub& dims = quadric->getEquationDims();
  4403. const unsigned char dX = dims.x;
  4404. const unsigned char dY = dims.y;
  4405. const unsigned char dZ = dims.z;
  4406. const ccGLMatrix& trans = quadric->getTransformation();
  4407. ccGLMatrix invTrans = trans.inverse();
  4408. for (unsigned i=0; i<newCloud->size(); ++i)
  4409. {
  4410. CCVector3* P = const_cast<CCVector3*>(newCloud->getPoint(i));
  4411. CCVector3 Q = invTrans * (*P);
  4412. Q.u[dZ] = eq[0] + eq[1]*Q.u[dX] + eq[2]*Q.u[dY] + eq[3]*Q.u[dX]*Q.u[dX] + eq[4]*Q.u[dX]*Q.u[dY] + eq[5]*Q.u[dY]*Q.u[dY];
  4413. *P = trans * Q;
  4414. }
  4415. newCloud->invalidateBoundingBox();
  4416. newCloud->setName(newCloud->getName() + ".projection_on_quadric");
  4417. addToDB(newCloud);
  4418. }
  4419. }
  4420. #endif
  4421. }
  4422. else
  4423. {
  4424. ccConsole::Warning(tr("Failed to compute quadric on cloud '%1'").arg(cloud->getName()));
  4425. errors = true;
  4426. }
  4427. }
  4428. }
  4429. if (errors)
  4430. {
  4431. ccConsole::Error(tr("Error(s) occurred: see console"));
  4432. }
  4433. refreshAll();
  4434. }
  4435. void MainWindow::doActionComputeDistanceMap()
  4436. {
  4437. static unsigned steps = 128;
  4438. static double margin = 0.0;
  4439. static bool filterRange = false;
  4440. static double range[2] = { 0.0, 1.0 };
  4441. //show dialog
  4442. {
  4443. QDialog dialog(this);
  4444. Ui_DistanceMapDialog ui;
  4445. ui.setupUi(&dialog);
  4446. ui.stepsSpinBox->setValue(static_cast<int>(steps));
  4447. ui.marginDoubleSpinBox->setValue(margin);
  4448. ui.rangeCheckBox->setChecked(filterRange);
  4449. ui.minDistDoubleSpinBox->setValue(range[0]);
  4450. ui.maxDistDoubleSpinBox->setValue(range[1]);
  4451. if (!dialog.exec())
  4452. {
  4453. return;
  4454. }
  4455. steps = static_cast<unsigned>(ui.stepsSpinBox->value());
  4456. margin = ui.marginDoubleSpinBox->value();
  4457. filterRange = ui.rangeCheckBox->isChecked();
  4458. range[0] = ui.minDistDoubleSpinBox->value();
  4459. range[1] = ui.maxDistDoubleSpinBox->value();
  4460. }
  4461. ccProgressDialog pDlg(true, this);
  4462. pDlg.setAutoClose(false);
  4463. for ( ccHObject *entity : getSelectedEntities() )
  4464. {
  4465. if (!entity->isKindOf(CC_TYPES::MESH) && !entity->isKindOf(CC_TYPES::POINT_CLOUD))
  4466. {
  4467. //non handled entity type
  4468. continue;
  4469. }
  4470. //CCCoreLib::ChamferDistanceTransform cdt;
  4471. CCCoreLib::SaitoSquaredDistanceTransform cdt;
  4472. if (!cdt.initGrid(Tuple3ui(steps, steps, steps)))
  4473. {
  4474. //not enough memory
  4475. ccLog::Error(tr("Not enough memory!"));
  4476. return;
  4477. }
  4478. ccBBox box = entity->getOwnBB();
  4479. PointCoordinateType largestDim = box.getMaxBoxDim() + static_cast<PointCoordinateType>(margin);
  4480. CCVector3 minCorner = box.getCenter() - CCVector3(1, 1, 1) * (largestDim / 2);
  4481. PointCoordinateType cellDim = largestDim / steps + std::numeric_limits<PointCoordinateType>::epsilon(); //to avoid rounding issues when projecting triangles or points inside the grid
  4482. bool result = false;
  4483. if (entity->isKindOf(CC_TYPES::MESH))
  4484. {
  4485. ccMesh* mesh = static_cast<ccMesh*>(entity);
  4486. result = cdt.initDT(mesh, cellDim, minCorner, &pDlg);
  4487. }
  4488. else
  4489. {
  4490. ccGenericPointCloud* cloud = static_cast<ccGenericPointCloud*>(entity);
  4491. result = cdt.initDT(cloud, cellDim, minCorner, &pDlg);
  4492. }
  4493. if (!result)
  4494. {
  4495. ccLog::Error(tr("Not enough memory!"));
  4496. return;
  4497. }
  4498. //cdt.propagateDistance(CHAMFER_345, &pDlg);
  4499. cdt.propagateDistance(&pDlg);
  4500. //convert the grid to a cloud
  4501. ccPointCloud* gridCloud = new ccPointCloud(entity->getName() + QString(".distance_grid(%1)").arg(steps));
  4502. {
  4503. unsigned pointCount = steps*steps*steps;
  4504. if (!gridCloud->reserve(pointCount))
  4505. {
  4506. ccLog::Error(tr("Not enough memory!"));
  4507. delete gridCloud;
  4508. return;
  4509. }
  4510. ccScalarField* sf = new ccScalarField("DT values");
  4511. if (!sf->reserveSafe(pointCount))
  4512. {
  4513. ccLog::Error(tr("Not enough memory!"));
  4514. delete gridCloud;
  4515. sf->release();
  4516. return;
  4517. }
  4518. for (unsigned i = 0; i < steps; ++i)
  4519. {
  4520. for (unsigned j = 0; j < steps; ++j)
  4521. {
  4522. for (unsigned k = 0; k < steps; ++k)
  4523. {
  4524. ScalarType d = std::sqrt(static_cast<ScalarType>(cdt.getValue(i, j, k))) * cellDim;
  4525. if (!filterRange || (d >= range[0] && d <= range[1]))
  4526. {
  4527. gridCloud->addPoint(minCorner + CCVector3(i + 0.5, j + 0.5, k + 0.5) * cellDim);
  4528. sf->addElement(d);
  4529. }
  4530. }
  4531. }
  4532. }
  4533. sf->computeMinAndMax();
  4534. int sfIdx = gridCloud->addScalarField(sf);
  4535. if (gridCloud->size() == 0)
  4536. {
  4537. ccLog::Warning(tr("[DistanceMap] Cloud '%1': no point falls inside the specified range").arg(entity->getName()));
  4538. delete gridCloud;
  4539. gridCloud = nullptr;
  4540. }
  4541. else
  4542. {
  4543. gridCloud->setCurrentDisplayedScalarField(sfIdx);
  4544. gridCloud->showSF(true);
  4545. gridCloud->setDisplay(entity->getDisplay());
  4546. gridCloud->shrinkToFit();
  4547. entity->prepareDisplayForRefresh();
  4548. addToDB(gridCloud);
  4549. }
  4550. }
  4551. }
  4552. refreshAll();
  4553. }
  4554. void MainWindow::doActionComputeDistToBestFitQuadric3D()
  4555. {
  4556. bool ok = true;
  4557. int steps = QInputDialog::getInt(this, tr("Distance to best fit quadric (3D)"), tr("Steps (per dim.)"), 50, 10, 10000, 10, &ok);
  4558. if (!ok)
  4559. return;
  4560. for ( ccHObject *entity : getSelectedEntities() )
  4561. {
  4562. if (entity->isKindOf(CC_TYPES::POINT_CLOUD))
  4563. {
  4564. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(entity);
  4565. CCCoreLib::Neighbourhood Yk(cloud);
  4566. double Q[10];
  4567. if (Yk.compute3DQuadric(Q))
  4568. {
  4569. const double& a = Q[0];
  4570. const double& b = Q[1];
  4571. const double& c = Q[2];
  4572. const double& e = Q[3];
  4573. const double& f = Q[4];
  4574. const double& g = Q[5];
  4575. const double& l = Q[6];
  4576. const double& m = Q[7];
  4577. const double& n = Q[8];
  4578. const double& d = Q[9];
  4579. //gravity center
  4580. const CCVector3* G = Yk.getGravityCenter();
  4581. if (!G)
  4582. {
  4583. ccConsole::Warning(tr("Failed to get the center of gravity of cloud '%1'!").arg(cloud->getName()));
  4584. continue;
  4585. }
  4586. const ccBBox bbox = cloud->getOwnBB();
  4587. PointCoordinateType maxDim = bbox.getMaxBoxDim();
  4588. CCVector3 C = bbox.getCenter();
  4589. //Sample points on a cube and compute for each of them the distance to the Quadric
  4590. ccPointCloud* newCloud = new ccPointCloud();
  4591. if (!newCloud->reserve(steps*steps*steps))
  4592. {
  4593. ccConsole::Error(tr("Not enough memory!"));
  4594. }
  4595. const char defaultSFName[] = "Dist. to 3D quadric";
  4596. int sfIdx = newCloud->getScalarFieldIndexByName(defaultSFName);
  4597. if (sfIdx < 0)
  4598. sfIdx = newCloud->addScalarField(defaultSFName);
  4599. if (sfIdx < 0)
  4600. {
  4601. ccConsole::Error(tr("Couldn't allocate a new scalar field for computing distances! Try to free some memory ..."));
  4602. delete newCloud;
  4603. continue;
  4604. }
  4605. ccScalarField* sf = static_cast<ccScalarField*>(newCloud->getScalarField(sfIdx));
  4606. assert(sf);
  4607. for (int x = 0; x < steps; ++x)
  4608. {
  4609. CCVector3 P;
  4610. P.x = C.x + maxDim * (static_cast<PointCoordinateType>(x) / static_cast<PointCoordinateType>(steps - 1) - CCCoreLib::PC_ONE / 2);
  4611. for (int y = 0; y < steps; ++y)
  4612. {
  4613. P.y = C.y + maxDim * (static_cast<PointCoordinateType>(y) / static_cast<PointCoordinateType>(steps - 1) - CCCoreLib::PC_ONE / 2);
  4614. for (int z = 0; z < steps; ++z)
  4615. {
  4616. P.z = C.z + maxDim * (static_cast<PointCoordinateType>(z) / static_cast<PointCoordinateType>(steps - 1) - CCCoreLib::PC_ONE / 2);
  4617. newCloud->addPoint(P);
  4618. //compute distance to quadric
  4619. CCVector3 Pc = P-*G;
  4620. ScalarType dist = static_cast<ScalarType>( a*Pc.x*Pc.x + b*Pc.y*Pc.y + c*Pc.z*Pc.z
  4621. + e*Pc.x*Pc.y + f*Pc.y*Pc.z + g*Pc.x*Pc.z
  4622. + l*Pc.x + m*Pc.y + n*Pc.z + d);
  4623. sf->addElement(dist);
  4624. }
  4625. }
  4626. }
  4627. if (sf)
  4628. {
  4629. sf->computeMinAndMax();
  4630. newCloud->setCurrentDisplayedScalarField(sfIdx);
  4631. newCloud->showSF(true);
  4632. }
  4633. newCloud->setName(tr("Distance map to 3D quadric"));
  4634. newCloud->setDisplay(cloud->getDisplay());
  4635. newCloud->prepareDisplayForRefresh();
  4636. addToDB(newCloud);
  4637. }
  4638. else
  4639. {
  4640. ccConsole::Warning(tr("Failed to compute 3D quadric on cloud '%1'").arg(cloud->getName()));
  4641. }
  4642. }
  4643. }
  4644. refreshAll();
  4645. }
  4646. void MainWindow::doActionComputeCPS()
  4647. {
  4648. if (m_selectedEntities.size() != 2)
  4649. {
  4650. ccConsole::Error(tr("Select 2 point clouds!"));
  4651. return;
  4652. }
  4653. if (!m_selectedEntities.front()->isKindOf(CC_TYPES::POINT_CLOUD) ||
  4654. !m_selectedEntities.back()->isKindOf(CC_TYPES::POINT_CLOUD))
  4655. {
  4656. ccConsole::Error(tr("Select 2 point clouds!"));
  4657. return;
  4658. }
  4659. ccOrderChoiceDlg dlg( m_selectedEntities.front(), tr("Compared"),
  4660. m_selectedEntities.back(), tr("Reference"),
  4661. this );
  4662. if (!dlg.exec())
  4663. return;
  4664. ccGenericPointCloud* compCloud = ccHObjectCaster::ToGenericPointCloud(dlg.getFirstEntity());
  4665. ccGenericPointCloud* srcCloud = ccHObjectCaster::ToGenericPointCloud(dlg.getSecondEntity());
  4666. if (!compCloud->isA(CC_TYPES::POINT_CLOUD)) //TODO
  4667. {
  4668. ccConsole::Error(tr("Compared cloud must be a real point cloud!"));
  4669. return;
  4670. }
  4671. ccPointCloud* cmpPC = static_cast<ccPointCloud*>(compCloud);
  4672. static const char DEFAULT_CPS_TEMP_SF_NAME[] = "CPS temporary";
  4673. int sfIdx = cmpPC->getScalarFieldIndexByName(DEFAULT_CPS_TEMP_SF_NAME);
  4674. if (sfIdx < 0)
  4675. sfIdx = cmpPC->addScalarField(DEFAULT_CPS_TEMP_SF_NAME);
  4676. if (sfIdx < 0)
  4677. {
  4678. ccConsole::Error(tr("Couldn't allocate a new scalar field for computing distances! Try to free some memory ..."));
  4679. return;
  4680. }
  4681. cmpPC->setCurrentScalarField(sfIdx);
  4682. if (!cmpPC->enableScalarField())
  4683. {
  4684. ccConsole::Error(tr("Not enough memory!"));
  4685. return;
  4686. }
  4687. //cmpPC->forEach(CCCoreLib::ScalarFieldTools::SetScalarValueToNaN); //now done by default by computeCloud2CloudDistances
  4688. CCCoreLib::ReferenceCloud CPSet(srcCloud);
  4689. ccProgressDialog pDlg(true, this);
  4690. CCCoreLib::DistanceComputationTools::Cloud2CloudDistancesComputationParams params;
  4691. params.CPSet = &CPSet;
  4692. int result = CCCoreLib::DistanceComputationTools::computeCloud2CloudDistances(compCloud, srcCloud, params, &pDlg);
  4693. cmpPC->deleteScalarField(sfIdx);
  4694. if (result >= 0)
  4695. {
  4696. ccPointCloud* newCloud = nullptr;
  4697. //if the source cloud is a "true" cloud, the extracted CPS
  4698. //will also get its attributes
  4699. newCloud = srcCloud->isA(CC_TYPES::POINT_CLOUD) ? static_cast<ccPointCloud*>(srcCloud)->partialClone(&CPSet) : ccPointCloud::From(&CPSet, srcCloud);
  4700. newCloud->setName(QString("[%1]->CPSet(%2)").arg(srcCloud->getName(), compCloud->getName()));
  4701. newCloud->setDisplay(compCloud->getDisplay());
  4702. newCloud->prepareDisplayForRefresh();
  4703. addToDB(newCloud);
  4704. //we hide the source cloud (for a clearer display)
  4705. srcCloud->setEnabled(false);
  4706. srcCloud->prepareDisplayForRefresh();
  4707. }
  4708. refreshAll();
  4709. }
  4710. void MainWindow::doActionComputeNormals()
  4711. {
  4712. if ( !ccEntityAction::computeNormals(m_selectedEntities, this) )
  4713. return;
  4714. refreshAll();
  4715. updateUI();
  4716. }
  4717. void MainWindow::doActionOrientNormalsMST()
  4718. {
  4719. if ( !ccEntityAction::orientNormalsMST(m_selectedEntities, this) )
  4720. return;
  4721. refreshAll();
  4722. updateUI();
  4723. }
  4724. void MainWindow::doActionOrientNormalsFM()
  4725. {
  4726. if ( !ccEntityAction::orientNormalsFM(m_selectedEntities, this) )
  4727. return;
  4728. refreshAll();
  4729. updateUI();
  4730. }
  4731. void MainWindow::doActionShiftPointsAlongNormals()
  4732. {
  4733. std::vector<ccPointCloud*> candidates;
  4734. for (ccHObject* entity : m_selectedEntities)
  4735. {
  4736. if (entity && entity->isA(CC_TYPES::POINT_CLOUD))
  4737. {
  4738. ccPointCloud* pc = static_cast<ccPointCloud*>(entity);
  4739. if (pc->hasNormals())
  4740. {
  4741. candidates.push_back(pc);
  4742. }
  4743. }
  4744. }
  4745. if (candidates.empty())
  4746. {
  4747. ccConsole::Error(QObject::tr("Select at least one point cloud with normals"));
  4748. return;
  4749. }
  4750. // ask the user to define the shift value
  4751. static double s_shift = 0.0;
  4752. bool ok = false;
  4753. double shift = QInputDialog::getDouble(this, tr("Shift along normals"), tr("Shift quantity"), s_shift, -1.0e6, 1.0e6, 6, &ok);
  4754. if (!ok)
  4755. {
  4756. return;
  4757. }
  4758. // remember for next time
  4759. s_shift = shift;
  4760. for (ccPointCloud* pc : candidates)
  4761. {
  4762. pc->shiftPointsAlongNormals(static_cast<PointCoordinateType>(shift));
  4763. pc->prepareDisplayForRefresh();
  4764. }
  4765. refreshAll();
  4766. }
  4767. void MainWindow::doActionFindBiggestInnerRectangle()
  4768. {
  4769. if (!haveSelection())
  4770. return;
  4771. ccHObject* entity = haveOneSelection() ? m_selectedEntities.front() : nullptr;
  4772. if (!entity || !entity->isKindOf(CC_TYPES::POINT_CLOUD))
  4773. {
  4774. ccConsole::Error(tr("Select one point cloud!"));
  4775. return;
  4776. }
  4777. bool ok;
  4778. static int s_innerRectDim = 2;
  4779. int dim = QInputDialog::getInt(this, tr("Dimension"), tr("Orthogonal dim (X=0 / Y=1 / Z=2)"), s_innerRectDim, 0, 2, 1, &ok);
  4780. if (!ok)
  4781. return;
  4782. s_innerRectDim = dim;
  4783. ccGenericPointCloud* cloud = static_cast<ccGenericPointCloud*>(entity);
  4784. ccBox* box = ccInnerRect2DFinder().process(cloud,static_cast<unsigned char>(dim));
  4785. if (box)
  4786. {
  4787. cloud->addChild(box);
  4788. box->setVisible(true);
  4789. box->setDisplay(cloud->getDisplay());
  4790. box->setDisplay(cloud->getDisplay());
  4791. addToDB(box);
  4792. }
  4793. updateUI();
  4794. }
  4795. void MainWindow::doActionFastRegistration(FastRegistrationMode mode)
  4796. {
  4797. //we need at least 1 entity
  4798. if (m_selectedEntities.empty())
  4799. return;
  4800. //we must backup 'm_selectedEntities' as removeObjectTemporarilyFromDBTree can modify it!
  4801. ccHObject::Container selectedEntities = m_selectedEntities;
  4802. for (ccHObject *entity : selectedEntities)
  4803. {
  4804. ccBBox box = entity->getBB_recursive();
  4805. CCVector3 T; //translation
  4806. switch (mode)
  4807. {
  4808. case MoveBBCenterToOrigin:
  4809. T = -box.getCenter();
  4810. break;
  4811. case MoveBBMinCornerToOrigin:
  4812. T = -box.minCorner();
  4813. break;
  4814. case MoveBBMaxCornerToOrigin:
  4815. T = -box.maxCorner();
  4816. break;
  4817. default:
  4818. assert(false);
  4819. return;
  4820. }
  4821. //transformation (used only for translation)
  4822. ccGLMatrix glTrans;
  4823. glTrans.setTranslation(T);
  4824. forceConsoleDisplay();
  4825. ccConsole::Print(tr("[Synchronize] Transformation matrix (%1):").arg(entity->getName()));
  4826. ccConsole::Print(glTrans.toString(12, ' ')); //full precision
  4827. ccConsole::Print(tr("Hint: copy it (CTRL+C) and apply it - or its inverse - on any entity with the 'Edit > Apply transformation' tool"));
  4828. //we temporarily detach the entity, as it may undergo
  4829. //'severe' modifications (octree deletion, etc.) --> see ccHObject::applyGLTransformation
  4830. ccHObjectContext objContext = removeObjectTemporarilyFromDBTree(entity);
  4831. entity->applyGLTransformation_recursive(&glTrans);
  4832. putObjectBackIntoDBTree(entity, objContext);
  4833. entity->prepareDisplayForRefresh_recursive();
  4834. }
  4835. //reselect previously selected entities!
  4836. if (m_ccRoot)
  4837. m_ccRoot->selectEntities(selectedEntities);
  4838. zoomOnSelectedEntities();
  4839. updateUI();
  4840. }
  4841. void MainWindow::doActionMatchBBCenters()
  4842. {
  4843. //we need at least 2 entities
  4844. if (m_selectedEntities.size() < 2)
  4845. return;
  4846. //we must backup 'm_selectedEntities' as removeObjectTemporarilyFromDBTree can modify it!
  4847. ccHObject::Container selectedEntities = m_selectedEntities;
  4848. //by default, we take the first entity as reference
  4849. //TODO: maybe the user would like to select the reference himself ;)
  4850. ccHObject* refEnt = selectedEntities[0];
  4851. CCVector3 refCenter = refEnt->getBB_recursive().getCenter();
  4852. for (ccHObject *entity : selectedEntities) //warning, getSelectedEntites may change during this loop!
  4853. {
  4854. CCVector3 center = entity->getBB_recursive().getCenter();
  4855. CCVector3 T = refCenter-center;
  4856. //transformation (used only for translation)
  4857. ccGLMatrix glTrans;
  4858. glTrans += T;
  4859. forceConsoleDisplay();
  4860. ccConsole::Print(tr("[Synchronize] Transformation matrix (%1 --> %2):").arg(entity->getName(),selectedEntities[0]->getName()));
  4861. ccConsole::Print(glTrans.toString(12,' ')); //full precision
  4862. ccConsole::Print(tr("Hint: copy it (CTRL+C) and apply it - or its inverse - on any entity with the 'Edit > Apply transformation' tool"));
  4863. //we temporarily detach the entity, as it may undergo
  4864. //'severe' modifications (octree deletion, etc.) --> see ccHObject::applyGLTransformation
  4865. ccHObjectContext objContext = removeObjectTemporarilyFromDBTree(entity);
  4866. entity->applyGLTransformation_recursive(&glTrans);
  4867. putObjectBackIntoDBTree(entity, objContext);
  4868. entity->prepareDisplayForRefresh_recursive();
  4869. }
  4870. //reselect previously selected entities!
  4871. if (m_ccRoot)
  4872. m_ccRoot->selectEntities(selectedEntities);
  4873. zoomOnSelectedEntities();
  4874. updateUI();
  4875. }
  4876. //semi-persistent parameters
  4877. static ccLibAlgorithms::ScaleMatchingAlgorithm s_msAlgorithm = ccLibAlgorithms::PCA_MAX_DIM;
  4878. static double s_msRmsDiff = 1.0e-5;
  4879. static int s_msFinalOverlap = 100;
  4880. void MainWindow::doActionMatchScales()
  4881. {
  4882. //we need at least 2 entities
  4883. if (m_selectedEntities.size() < 2)
  4884. return;
  4885. //we must select the point clouds and meshes
  4886. ccHObject::Container selectedEntities;
  4887. try
  4888. {
  4889. for ( ccHObject *entity : getSelectedEntities() )
  4890. {
  4891. if ( entity->isKindOf(CC_TYPES::POINT_CLOUD)
  4892. || entity->isKindOf(CC_TYPES::MESH))
  4893. {
  4894. selectedEntities.push_back(entity);
  4895. }
  4896. }
  4897. }
  4898. catch (const std::bad_alloc&)
  4899. {
  4900. ccConsole::Error(tr("Not enough memory!"));
  4901. return;
  4902. }
  4903. ccMatchScalesDlg msDlg(selectedEntities, 0, this);
  4904. msDlg.setSelectedAlgorithm(s_msAlgorithm);
  4905. msDlg.rmsDifferenceLineEdit->setText(QString::number(s_msRmsDiff, 'e', 1));
  4906. msDlg.overlapSpinBox->setValue(s_msFinalOverlap);
  4907. if (!msDlg.exec())
  4908. return;
  4909. //save semi-persistent parameters
  4910. s_msAlgorithm = msDlg.getSelectedAlgorithm();
  4911. if (s_msAlgorithm == ccLibAlgorithms::ICP_SCALE)
  4912. {
  4913. s_msRmsDiff = msDlg.rmsDifferenceLineEdit->text().toDouble();
  4914. s_msFinalOverlap = msDlg.overlapSpinBox->value();
  4915. }
  4916. ccLibAlgorithms::ApplyScaleMatchingAlgorithm( s_msAlgorithm,
  4917. selectedEntities,
  4918. s_msRmsDiff,
  4919. s_msFinalOverlap,
  4920. msDlg.getSelectedIndex(),
  4921. this);
  4922. //reselect previously selected entities!
  4923. if (m_ccRoot)
  4924. m_ccRoot->selectEntities(selectedEntities);
  4925. refreshAll();
  4926. updateUI();
  4927. }
  4928. void MainWindow::doActionSORFilter()
  4929. {
  4930. ccSORFilterDlg sorDlg(this);
  4931. //set semi-persistent/dynamic parameters
  4932. static int s_sorFilterKnn = 6;
  4933. static double s_sorFilterNSigma = 1.0;
  4934. sorDlg.setKNN(s_sorFilterKnn);
  4935. sorDlg.setNSigma(s_sorFilterNSigma);
  4936. if (!sorDlg.exec())
  4937. {
  4938. return;
  4939. }
  4940. //update semi-persistent/dynamic parameters
  4941. s_sorFilterKnn = sorDlg.KNN();
  4942. s_sorFilterNSigma = sorDlg.nSigma();
  4943. ccProgressDialog pDlg(true, this);
  4944. pDlg.setAutoClose(false);
  4945. bool firstCloud = true;
  4946. ccHObject::Container selectedEntities = getSelectedEntities(); //we have to use a local copy: 'selectEntity' will change the set of currently selected entities!
  4947. for (ccHObject* entity : selectedEntities)
  4948. {
  4949. //specific test for locked vertices
  4950. bool lockedVertices;
  4951. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(entity, &lockedVertices);
  4952. if (!cloud)
  4953. {
  4954. continue;
  4955. }
  4956. if (lockedVertices)
  4957. {
  4958. ccUtils::DisplayLockedVerticesWarning(entity->getName(), haveOneSelection());
  4959. continue;
  4960. }
  4961. //computation
  4962. CCCoreLib::ReferenceCloud* selection = CCCoreLib::CloudSamplingTools::sorFilter(cloud,
  4963. s_sorFilterKnn,
  4964. s_sorFilterNSigma,
  4965. cloud->getOctree().data(),
  4966. &pDlg);
  4967. if (selection)
  4968. {
  4969. if (selection->size() == cloud->size())
  4970. {
  4971. ccLog::Warning(tr("[DoActionSORFilter] No points were removed from cloud '%1'").arg(cloud->getName()));
  4972. }
  4973. else
  4974. {
  4975. ccPointCloud* cleanCloud = cloud->partialClone(selection);
  4976. if (cleanCloud)
  4977. {
  4978. cleanCloud->setName(cloud->getName() + QString(".clean"));
  4979. cleanCloud->setDisplay(cloud->getDisplay());
  4980. if (cloud->getParent())
  4981. cloud->getParent()->addChild(cleanCloud);
  4982. addToDB(cleanCloud);
  4983. cloud->setEnabled(false);
  4984. if (firstCloud)
  4985. {
  4986. ccConsole::Warning(tr("Previously selected entities (sources) have been hidden!"));
  4987. firstCloud = false;
  4988. m_ccRoot->selectEntity(cleanCloud, true);
  4989. }
  4990. }
  4991. else
  4992. {
  4993. ccConsole::Warning(tr("[DoActionSORFilter] Not enough memory to create a clean version of cloud '%1'!").arg(cloud->getName()));
  4994. }
  4995. }
  4996. delete selection;
  4997. selection = nullptr;
  4998. }
  4999. else
  5000. {
  5001. //no points fall inside selection!
  5002. ccConsole::Warning(tr("[DoActionSORFilter] Failed to apply the noise filter to cloud '%1'! (not enough memory?)").arg(cloud->getName()));
  5003. }
  5004. }
  5005. refreshAll();
  5006. updateUI();
  5007. }
  5008. void MainWindow::doActionFilterNoise()
  5009. {
  5010. double kernelRadius = ccLibAlgorithms::GetDefaultCloudKernelSize(m_selectedEntities);
  5011. ccNoiseFilterDlg noiseDlg(this);
  5012. //set semi-persistent/dynamic parameters
  5013. static bool s_noiseFilterUseKnn = false;
  5014. static int s_noiseFilterKnn = 6;
  5015. static bool s_noiseFilterUseAbsError = false;
  5016. static double s_noiseFilterAbsError = 1.0;
  5017. static double s_noiseFilterNSigma = 1.0;
  5018. static bool s_noiseFilterRemoveIsolatedPoints = false;
  5019. noiseDlg.radiusDoubleSpinBox->setValue(kernelRadius);
  5020. noiseDlg.knnSpinBox->setValue(s_noiseFilterKnn);
  5021. noiseDlg.nSigmaDoubleSpinBox->setValue(s_noiseFilterNSigma);
  5022. noiseDlg.absErrorDoubleSpinBox->setValue(s_noiseFilterAbsError);
  5023. noiseDlg.removeIsolatedPointsCheckBox->setChecked(s_noiseFilterRemoveIsolatedPoints);
  5024. if (s_noiseFilterUseAbsError)
  5025. noiseDlg.absErrorRadioButton->setChecked(true);
  5026. else
  5027. noiseDlg.relativeRadioButton->setChecked(true);
  5028. if (s_noiseFilterUseKnn)
  5029. noiseDlg.knnRadioButton->setChecked(true);
  5030. else
  5031. noiseDlg.radiusRadioButton->setChecked(true);
  5032. if (!noiseDlg.exec())
  5033. return;
  5034. //update semi-persistent/dynamic parameters
  5035. kernelRadius = noiseDlg.radiusDoubleSpinBox->value();
  5036. s_noiseFilterUseKnn = noiseDlg.knnRadioButton->isChecked();
  5037. s_noiseFilterKnn = noiseDlg.knnSpinBox->value();
  5038. s_noiseFilterUseAbsError = noiseDlg.absErrorRadioButton->isChecked();
  5039. s_noiseFilterNSigma = noiseDlg.nSigmaDoubleSpinBox->value();
  5040. s_noiseFilterAbsError = noiseDlg.absErrorDoubleSpinBox->value();
  5041. s_noiseFilterRemoveIsolatedPoints = noiseDlg.removeIsolatedPointsCheckBox->isChecked();
  5042. ccProgressDialog pDlg(true, this);
  5043. pDlg.setAutoClose(false);
  5044. bool firstCloud = true;
  5045. ccHObject::Container selectedEntities = getSelectedEntities(); //we have to use a local copy: and 'selectEntity' will change the set of currently selected entities!
  5046. for ( ccHObject *entity : selectedEntities )
  5047. {
  5048. //specific test for locked vertices
  5049. bool lockedVertices;
  5050. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(entity, &lockedVertices);
  5051. if (!cloud)
  5052. {
  5053. continue;
  5054. }
  5055. if (lockedVertices)
  5056. {
  5057. ccUtils::DisplayLockedVerticesWarning(entity->getName(), haveOneSelection());
  5058. continue;
  5059. }
  5060. //computation
  5061. CCCoreLib::ReferenceCloud* selection = CCCoreLib::CloudSamplingTools::noiseFilter( cloud,
  5062. static_cast<PointCoordinateType>(kernelRadius),
  5063. s_noiseFilterNSigma,
  5064. s_noiseFilterRemoveIsolatedPoints,
  5065. s_noiseFilterUseKnn,
  5066. s_noiseFilterKnn,
  5067. s_noiseFilterUseAbsError,
  5068. s_noiseFilterAbsError,
  5069. cloud->getOctree().data(),
  5070. &pDlg);
  5071. if (selection)
  5072. {
  5073. if (selection->size() == cloud->size())
  5074. {
  5075. ccLog::Warning(tr("[DoActionFilterNoise] No points were removed from cloud '%1'").arg(cloud->getName()));
  5076. }
  5077. else
  5078. {
  5079. ccPointCloud* cleanCloud = cloud->partialClone(selection);
  5080. if (cleanCloud)
  5081. {
  5082. cleanCloud->setName(cloud->getName() + QString(".clean"));
  5083. cleanCloud->setDisplay(cloud->getDisplay());
  5084. if (cloud->getParent())
  5085. cloud->getParent()->addChild(cleanCloud);
  5086. addToDB(cleanCloud);
  5087. cloud->setEnabled(false);
  5088. if (firstCloud)
  5089. {
  5090. ccConsole::Warning(tr("Previously selected entities (sources) have been hidden!"));
  5091. firstCloud = false;
  5092. m_ccRoot->selectEntity(cleanCloud, true);
  5093. }
  5094. }
  5095. else
  5096. {
  5097. ccConsole::Warning(tr("[DoActionFilterNoise] Not enough memory to create a clean version of cloud '%1'!").arg(cloud->getName()));
  5098. }
  5099. }
  5100. delete selection;
  5101. selection = nullptr;
  5102. }
  5103. else
  5104. {
  5105. //no points fall inside selection!
  5106. ccConsole::Warning(tr("[DoActionFilterNoise] Failed to apply the noise filter to cloud '%1'! (not enough memory?)").arg(cloud->getName()));
  5107. }
  5108. }
  5109. refreshAll();
  5110. updateUI();
  5111. }
  5112. void MainWindow::doActionUnroll()
  5113. {
  5114. //there should be only one point cloud or one mesh!
  5115. if (!haveOneSelection())
  5116. {
  5117. ccConsole::Error(tr("Select one and only one entity!"));
  5118. return;
  5119. }
  5120. //if selected entity is a mesh, the method will be applied to its vertices
  5121. bool lockedVertices;
  5122. ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(m_selectedEntities.front(), &lockedVertices);
  5123. if (lockedVertices)
  5124. {
  5125. ccUtils::DisplayLockedVerticesWarning(m_selectedEntities.front()->getName(), true);
  5126. return;
  5127. }
  5128. //for "real" point clouds only
  5129. if (!cloud || !cloud->isA(CC_TYPES::POINT_CLOUD))
  5130. {
  5131. ccConsole::Error(tr("Method can't be applied on locked vertices or virtual point clouds!"));
  5132. return;
  5133. }
  5134. ccPointCloud* pc = static_cast<ccPointCloud*>(cloud);
  5135. ccUnrollDlg unrollDlg(m_ccRoot ? m_ccRoot->getRootEntity() : nullptr, this);
  5136. unrollDlg.fromPersistentSettings();
  5137. if (!unrollDlg.exec())
  5138. return;
  5139. unrollDlg.toPersistentSettings();
  5140. ccPointCloud::UnrollMode mode = unrollDlg.getType();
  5141. PointCoordinateType radius = static_cast<PointCoordinateType>(unrollDlg.getRadius());
  5142. CCVector3d axisDir = unrollDlg.getAxis();
  5143. bool exportDeviationSF = unrollDlg.exportDeviationSF();
  5144. bool arbitraryOutputCS = unrollDlg.useArbitraryOutputCS();
  5145. CCVector3 center = unrollDlg.getAxisPosition();
  5146. //let's rock unroll ;)
  5147. ccProgressDialog pDlg(true, this);
  5148. double startAngle_deg = 0.0;
  5149. double stopAngle_deg = 360.0;
  5150. unrollDlg.getAngleRange(startAngle_deg, stopAngle_deg);
  5151. if (startAngle_deg >= stopAngle_deg)
  5152. {
  5153. QMessageBox::critical(this, tr("Error"), tr("Invalid angular range"));
  5154. return;
  5155. }
  5156. ccPointCloud* output = nullptr;
  5157. switch (mode)
  5158. {
  5159. case ccPointCloud::CYLINDER:
  5160. {
  5161. ccPointCloud::UnrollCylinderParams params;
  5162. params.radius = radius;
  5163. params.axisDir = CCVector3::fromArray(axisDir.u);
  5164. if (unrollDlg.isAxisPositionAuto())
  5165. {
  5166. center = pc->getOwnBB().getCenter();
  5167. }
  5168. params.center = center;
  5169. output = pc->unroll(mode, &params, exportDeviationSF, startAngle_deg, stopAngle_deg, arbitraryOutputCS, &pDlg);
  5170. }
  5171. break;
  5172. case ccPointCloud::CONE_CONICAL:
  5173. case ccPointCloud::CONE_CYLINDRICAL_FIXED_RADIUS:
  5174. case ccPointCloud::CONE_CYLINDRICAL_ADAPTIVE_RADIUS:
  5175. {
  5176. ccPointCloud::UnrollConeParams params;
  5177. params.radius = (mode == ccPointCloud::CONE_CYLINDRICAL_FIXED_RADIUS ? radius : 0);
  5178. params.apex = center;
  5179. params.coneAngle_deg = unrollDlg.getConeHalfAngle();
  5180. params.axisDir = CCVector3::fromArray(axisDir.u);
  5181. params.spanRatio = unrollDlg.getConicalProjSpanRatio();
  5182. output = pc->unroll(mode, &params, exportDeviationSF, startAngle_deg, stopAngle_deg, arbitraryOutputCS, &pDlg);
  5183. }
  5184. break;
  5185. default:
  5186. assert(false);
  5187. break;
  5188. }
  5189. if (output)
  5190. {
  5191. if (m_selectedEntities.front()->isA(CC_TYPES::MESH))
  5192. {
  5193. ccMesh* mesh = ccHObjectCaster::ToMesh(m_selectedEntities.front());
  5194. mesh->setEnabled(false);
  5195. ccConsole::Warning(tr("[Unroll] Original mesh has been automatically hidden"));
  5196. ccMesh* outputMesh = mesh->cloneMesh(output);
  5197. outputMesh->addChild(output);
  5198. addToDB(outputMesh, true, true, false, true);
  5199. outputMesh->setEnabled(true);
  5200. outputMesh->setVisible(true);
  5201. }
  5202. else
  5203. {
  5204. pc->setEnabled(false);
  5205. ccConsole::Warning(tr("[Unroll] Original cloud has been automatically hidden"));
  5206. if (pc->getParent())
  5207. {
  5208. pc->getParent()->addChild(output);
  5209. }
  5210. addToDB(output, true, true, false, true);
  5211. }
  5212. updateUI();
  5213. }
  5214. }
  5215. ccGLWindowInterface* MainWindow::getActiveGLWindow()
  5216. {
  5217. if (!m_mdiArea)
  5218. {
  5219. return nullptr;
  5220. }
  5221. QMdiSubWindow *activeSubWindow = m_mdiArea->activeSubWindow();
  5222. if (activeSubWindow)
  5223. {
  5224. return ccGLWindowInterface::FromWidget(activeSubWindow->widget());
  5225. }
  5226. else
  5227. {
  5228. QList<QMdiSubWindow*> subWindowList = m_mdiArea->subWindowList();
  5229. if (!subWindowList.isEmpty())
  5230. {
  5231. return ccGLWindowInterface::FromWidget(subWindowList[0]->widget());
  5232. }
  5233. }
  5234. return nullptr;
  5235. }
  5236. QMdiSubWindow* MainWindow::getMDISubWindow(ccGLWindowInterface* win)
  5237. {
  5238. QList<QMdiSubWindow*> subWindowList = m_mdiArea->subWindowList();
  5239. for (int i = 0; i < subWindowList.size(); ++i)
  5240. {
  5241. if (ccGLWindowInterface::FromWidget(subWindowList[i]->widget()) == win)
  5242. return subWindowList[i];
  5243. }
  5244. //not found!
  5245. return nullptr;
  5246. }
  5247. ccGLWindowInterface* MainWindow::getGLWindow(int index) const
  5248. {
  5249. QList<QMdiSubWindow*> subWindowList = m_mdiArea->subWindowList();
  5250. if (index >= 0 && index < subWindowList.size())
  5251. {
  5252. ccGLWindowInterface* win = ccGLWindowInterface::FromWidget(subWindowList[index]->widget());
  5253. assert(win);
  5254. return win;
  5255. }
  5256. else
  5257. {
  5258. assert(false);
  5259. return nullptr;
  5260. }
  5261. }
  5262. int MainWindow::getGLWindowCount() const
  5263. {
  5264. return m_mdiArea ? m_mdiArea->subWindowList().size() : 0;
  5265. }
  5266. void MainWindow::zoomIn()
  5267. {
  5268. ccGLWindowInterface* win = MainWindow::getActiveGLWindow();
  5269. if (win)
  5270. {
  5271. //we simulate a real wheel event
  5272. win->onWheelEvent(15.0f);
  5273. }
  5274. }
  5275. void MainWindow::zoomOut()
  5276. {
  5277. ccGLWindowInterface* win = MainWindow::getActiveGLWindow();
  5278. if (win)
  5279. {
  5280. //we simulate a real wheel event
  5281. win->onWheelEvent(-15.0f);
  5282. }
  5283. }
  5284. ccGLWindowInterface* MainWindow::new3DViewInternal( bool allowEntitySelection )
  5285. {
  5286. assert(m_ccRoot && m_mdiArea);
  5287. QWidget* viewWidget = nullptr;
  5288. ccGLWindowInterface* view3D = nullptr;
  5289. createGLWindow(view3D, viewWidget);
  5290. if (!viewWidget || !view3D)
  5291. {
  5292. ccLog::Error(tr("Failed to create the 3D view"));
  5293. assert(false);
  5294. return nullptr;
  5295. }
  5296. //restore options
  5297. {
  5298. QSettings settings;
  5299. bool autoPickRotationCenter = settings.value(ccPS::AutoPickRotationCenter(), true).toBool();
  5300. view3D->setAutoPickPivotAtCenter(autoPickRotationCenter);
  5301. }
  5302. viewWidget->setMinimumSize(400, 300);
  5303. m_mdiArea->addSubWindow(viewWidget);
  5304. if ( allowEntitySelection )
  5305. {
  5306. connect(view3D->signalEmitter(), &ccGLWindowSignalEmitter::entitySelectionChanged, this, [=] (ccHObject *entity) {
  5307. m_ccRoot->selectEntity( entity );
  5308. });
  5309. connect(view3D->signalEmitter(), &ccGLWindowSignalEmitter::entitiesSelectionChanged, this, [=] (std::unordered_set<int> entities){
  5310. m_ccRoot->selectEntities( entities );
  5311. });
  5312. }
  5313. //'echo' mode
  5314. connect(view3D->signalEmitter(), &ccGLWindowSignalEmitter::mouseWheelRotated, this, &MainWindow::echoMouseWheelRotate);
  5315. connect(view3D->signalEmitter(), &ccGLWindowSignalEmitter::viewMatRotated, this, &MainWindow::echoBaseViewMatRotation);
  5316. connect(view3D->signalEmitter(), &ccGLWindowSignalEmitter::cameraPosChanged, this, &MainWindow::echoCameraPosChanged);
  5317. connect(view3D->signalEmitter(), &ccGLWindowSignalEmitter::pivotPointChanged, this, &MainWindow::echoPivotPointChanged);
  5318. connect(view3D->signalEmitter(), &ccGLWindowSignalEmitter::aboutToClose, this, &MainWindow::prepareWindowDeletion);
  5319. connect(view3D->signalEmitter(), &ccGLWindowSignalEmitter::filesDropped, this, &MainWindow::addToDBAuto, Qt::QueuedConnection); //DGM: we don't want to block the 'dropEvent' method of ccGLWindow instances!
  5320. connect(view3D->signalEmitter(), &ccGLWindowSignalEmitter::newLabel, this, &MainWindow::handleNewLabel);
  5321. connect(view3D->signalEmitter(), &ccGLWindowSignalEmitter::exclusiveFullScreenToggled, this, &MainWindow::onExclusiveFullScreenToggled);
  5322. if (m_pickingHub)
  5323. {
  5324. //we must notify the picking hub as well if the window is destroyed
  5325. connect(view3D->signalEmitter(), &ccGLWindowSignalEmitter::aboutToClose, m_pickingHub, &ccPickingHub::onActiveWindowDeleted);
  5326. }
  5327. view3D->setSceneDB(m_ccRoot->getRootEntity());
  5328. viewWidget->setAttribute(Qt::WA_DeleteOnClose);
  5329. m_ccRoot->updatePropertiesView();
  5330. QMainWindow::statusBar()->showMessage(tr("New 3D View"), 2000);
  5331. viewWidget->showMaximized();
  5332. viewWidget->update();
  5333. return view3D;
  5334. }
  5335. void MainWindow::prepareWindowDeletion(ccGLWindowInterface* glWindow)
  5336. {
  5337. if (!m_ccRoot)
  5338. return;
  5339. if (glWindow)
  5340. {
  5341. m_ccRoot->hidePropertiesView();
  5342. m_ccRoot->getRootEntity()->removeFromDisplay_recursive(glWindow);
  5343. m_ccRoot->updatePropertiesView();
  5344. }
  5345. else
  5346. {
  5347. assert(false);
  5348. }
  5349. }
  5350. static bool s_autoSaveGuiElementPos = true;
  5351. void MainWindow::doActionResetGUIElementsPos()
  5352. {
  5353. //show the user it will be maximized
  5354. showMaximized();
  5355. QSettings settings;
  5356. settings.remove(ccPS::MainWinGeom());
  5357. settings.remove(ccPS::MainWinState());
  5358. QMessageBox::information( this,
  5359. tr("Restart"),
  5360. tr("To finish the process, you'll have to close and restart CloudCompare") );
  5361. //to avoid saving them right away!
  5362. s_autoSaveGuiElementPos = false;
  5363. }
  5364. void MainWindow::doActionToggleRestoreWindowOnStartup(bool state)
  5365. {
  5366. QSettings settings;
  5367. settings.setValue(ccPS::DoNotRestoreWindowGeometry(), !state);
  5368. }
  5369. void MainWindow::doActionResetAllVBOs()
  5370. {
  5371. ccHObject::Container clouds;
  5372. m_ccRoot->getRootEntity()->filterChildren(clouds, true, CC_TYPES::POINT_CLOUD, true);
  5373. size_t releasedSize = 0;
  5374. for (ccHObject* entity : clouds)
  5375. {
  5376. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(entity);
  5377. if (cloud)
  5378. {
  5379. releasedSize += cloud->vboSize();
  5380. cloud->releaseVBOs();
  5381. }
  5382. }
  5383. if (releasedSize != 0)
  5384. {
  5385. ccLog::Print(tr("All VBOs have been released (%1 Mb)").arg(releasedSize / static_cast<double>(1 << 20), 0, 'f', 2));
  5386. if (ccGui::Parameters().useVBOs)
  5387. {
  5388. ccLog::Warning(tr("You might want to disable the 'use VBOs' option in the Display Settings to keep the GPU memory empty"));
  5389. }
  5390. }
  5391. else
  5392. {
  5393. ccLog::Print(tr("No VBO allocated"));
  5394. }
  5395. }
  5396. void MainWindow::restoreGUIElementsPos()
  5397. {
  5398. QSettings settings;
  5399. QVariant previousState = settings.value(ccPS::MainWinState());
  5400. if (previousState.isValid())
  5401. {
  5402. restoreState(previousState.toByteArray());
  5403. }
  5404. QVariant previousGeometry;
  5405. if (!settings.value(ccPS::DoNotRestoreWindowGeometry(), false).toBool())
  5406. {
  5407. previousGeometry = settings.value(ccPS::MainWinGeom());
  5408. }
  5409. if (previousGeometry.isValid())
  5410. {
  5411. restoreGeometry(previousGeometry.toByteArray());
  5412. }
  5413. else
  5414. {
  5415. showMaximized();
  5416. }
  5417. if (isFullScreen())
  5418. {
  5419. m_UI->actionFullScreen->blockSignals(true);
  5420. m_UI->actionFullScreen->setChecked(true);
  5421. m_UI->actionFullScreen->blockSignals(false);
  5422. }
  5423. }
  5424. void MainWindow::showEvent(QShowEvent* event)
  5425. {
  5426. if (m_firstShow)
  5427. {
  5428. restoreGUIElementsPos();
  5429. m_firstShow = false;
  5430. }
  5431. QMainWindow::showEvent(event);
  5432. }
  5433. void MainWindow::closeEvent(QCloseEvent* event)
  5434. {
  5435. const ccOptions &opts = ccOptions::Instance();
  5436. // If we don't have anything displayed, then just close...
  5437. if (!opts.confirmQuit || (m_ccRoot && (m_ccRoot->getRootEntity()->getChildrenNumber() == 0)))
  5438. {
  5439. event->accept();
  5440. }
  5441. else // ...otherwise confirm
  5442. {
  5443. QMessageBox message_box( QMessageBox::Question,
  5444. tr("Quit"),
  5445. tr("Are you sure you want to quit?"),
  5446. QMessageBox::NoButton,
  5447. this);
  5448. message_box.addButton(QMessageBox::Button::Yes);
  5449. message_box.addButton(tr("Yes, don't ask again"), QMessageBox::ButtonRole::YesRole);
  5450. message_box.addButton(QMessageBox::Button::No);
  5451. message_box.exec();
  5452. switch (message_box.buttons().indexOf(message_box.clickedButton())) {
  5453. case 1: // Yes, don't ask again
  5454. {
  5455. ccOptions optsCopied = opts;
  5456. optsCopied.confirmQuit = false;
  5457. optsCopied.toPersistentSettings();
  5458. Q_FALLTHROUGH(); // Fallthrough to the yes case, to accept the event
  5459. }
  5460. case 0: // Yes
  5461. event->accept();
  5462. break;
  5463. case 2: // No
  5464. default:
  5465. event->ignore();
  5466. }
  5467. }
  5468. if (s_autoSaveGuiElementPos)
  5469. {
  5470. saveGUIElementsPos();
  5471. }
  5472. }
  5473. void MainWindow::saveGUIElementsPos()
  5474. {
  5475. //save the state as settings
  5476. QSettings settings;
  5477. settings.setValue(ccPS::MainWinGeom(), saveGeometry());
  5478. settings.setValue(ccPS::MainWinState(), saveState());
  5479. }
  5480. void MainWindow::moveEvent(QMoveEvent* event)
  5481. {
  5482. QMainWindow::moveEvent(event);
  5483. updateOverlayDialogsPlacement();
  5484. }
  5485. void MainWindow::resizeEvent(QResizeEvent* event)
  5486. {
  5487. QMainWindow::resizeEvent(event);
  5488. updateOverlayDialogsPlacement();
  5489. }
  5490. void MainWindow::registerOverlayDialog(ccOverlayDialog* dlg, Qt::Corner pos)
  5491. {
  5492. //check for existence
  5493. for (ccMDIDialogs& mdi : m_mdiDialogs)
  5494. {
  5495. if (mdi.dialog == dlg)
  5496. {
  5497. //we only update its position in this case
  5498. mdi.position = pos;
  5499. repositionOverlayDialog(mdi);
  5500. return;
  5501. }
  5502. }
  5503. //otherwise we add it to DB
  5504. m_mdiDialogs.push_back(ccMDIDialogs(dlg, pos));
  5505. //automatically update the dialog placement when its shown
  5506. connect(dlg, &ccOverlayDialog::shown, this, [=]()
  5507. {
  5508. //check for existence
  5509. for (ccMDIDialogs& mdi : m_mdiDialogs)
  5510. {
  5511. if (mdi.dialog == dlg)
  5512. {
  5513. repositionOverlayDialog(mdi);
  5514. break;
  5515. }
  5516. }
  5517. });
  5518. repositionOverlayDialog(m_mdiDialogs.back());
  5519. }
  5520. void MainWindow::unregisterOverlayDialog(ccOverlayDialog* dialog)
  5521. {
  5522. for (std::vector<ccMDIDialogs>::iterator it = m_mdiDialogs.begin(); it != m_mdiDialogs.end(); ++it)
  5523. {
  5524. if (it->dialog == dialog)
  5525. {
  5526. m_mdiDialogs.erase(it);
  5527. break;
  5528. }
  5529. }
  5530. }
  5531. bool MainWindow::eventFilter(QObject *obj, QEvent *event)
  5532. {
  5533. switch (event->type())
  5534. {
  5535. case QEvent::Resize:
  5536. case QEvent::Move:
  5537. updateOverlayDialogsPlacement();
  5538. break;
  5539. default:
  5540. //nothing to do
  5541. break;
  5542. }
  5543. // standard event processing
  5544. return QObject::eventFilter(obj, event);
  5545. }
  5546. void MainWindow::keyPressEvent(QKeyEvent *event)
  5547. {
  5548. switch (event->key())
  5549. {
  5550. case Qt::Key_Escape:
  5551. {
  5552. if ( s_pickingWindow != nullptr )
  5553. {
  5554. cancelPreviousPickingOperation( true );
  5555. }
  5556. break;
  5557. }
  5558. default:
  5559. QMainWindow::keyPressEvent(event);
  5560. }
  5561. }
  5562. void MainWindow::updateOverlayDialogsPlacement()
  5563. {
  5564. for (ccMDIDialogs& mdiDlg : m_mdiDialogs)
  5565. {
  5566. repositionOverlayDialog(mdiDlg);
  5567. }
  5568. }
  5569. void MainWindow::repositionOverlayDialog(ccMDIDialogs& mdiDlg)
  5570. {
  5571. if (!mdiDlg.dialog || !mdiDlg.dialog->isVisible() || !m_mdiArea)
  5572. return;
  5573. int dx = 0;
  5574. int dy = 0;
  5575. static const int margin = 5;
  5576. switch (mdiDlg.position)
  5577. {
  5578. case Qt::TopLeftCorner:
  5579. dx = margin;
  5580. dy = margin;
  5581. break;
  5582. case Qt::TopRightCorner:
  5583. dx = std::max(margin, m_mdiArea->width() - mdiDlg.dialog->width() - margin);
  5584. dy = margin;
  5585. break;
  5586. case Qt::BottomLeftCorner:
  5587. dx = margin;
  5588. dy = std::max(margin, m_mdiArea->height() - mdiDlg.dialog->height() - margin);
  5589. break;
  5590. case Qt::BottomRightCorner:
  5591. dx = std::max(margin, m_mdiArea->width() - mdiDlg.dialog->width() - margin);
  5592. dy = std::max(margin, m_mdiArea->height() - mdiDlg.dialog->height() - margin);
  5593. break;
  5594. }
  5595. //show();
  5596. mdiDlg.dialog->move(m_mdiArea->mapToGlobal(QPoint(dx, dy)));
  5597. mdiDlg.dialog->raise();
  5598. }
  5599. void MainWindow::toggleVisualDebugTraces()
  5600. {
  5601. ccGLWindowInterface* win = getActiveGLWindow();
  5602. if (win)
  5603. {
  5604. win->toggleDebugTrace();
  5605. win->redraw(false, false);
  5606. }
  5607. }
  5608. void MainWindow::toggleFullScreen(bool state)
  5609. {
  5610. if (state)
  5611. showFullScreen();
  5612. else
  5613. showNormal();
  5614. #ifdef Q_OS_MAC
  5615. if ( state )
  5616. {
  5617. m_UI->actionFullScreen->setText( tr( "Exit Full Screen" ) );
  5618. }
  5619. else
  5620. {
  5621. m_UI->actionFullScreen->setText( tr( "Enter Full Screen" ) );
  5622. }
  5623. #endif
  5624. }
  5625. void MainWindow::toggleExclusiveFullScreen(bool state)
  5626. {
  5627. ccGLWindowInterface* win = getActiveGLWindow();
  5628. if (win)
  5629. {
  5630. win->toggleExclusiveFullScreen(state);
  5631. }
  5632. }
  5633. void MainWindow::doActionShowHelpDialog()
  5634. {
  5635. QMessageBox messageBox;
  5636. messageBox.setTextFormat(Qt::RichText);
  5637. messageBox.setWindowTitle("Documentation");
  5638. messageBox.setText("Please look at the <a href='http://www.cloudcompare.org/doc/wiki'>wiki</a>");
  5639. messageBox.setStandardButtons(QMessageBox::Ok);
  5640. messageBox.exec();
  5641. }
  5642. void MainWindow::freezeUI(bool state)
  5643. {
  5644. //freeze standard plugins
  5645. m_UI->toolBarMainTools->setDisabled(state);
  5646. m_UI->toolBarSFTools->setDisabled(state);
  5647. m_pluginUIManager->mainPluginToolbar()->setDisabled(state);
  5648. //freeze plugin toolbars
  5649. for ( QToolBar *toolbar : m_pluginUIManager->additionalPluginToolbars() )
  5650. {
  5651. toolbar->setDisabled(state);
  5652. }
  5653. m_UI->DockableDBTree->setDisabled(state);
  5654. m_UI->menubar->setDisabled(state);
  5655. if (state)
  5656. {
  5657. m_UI->menuEdit->setDisabled(true);
  5658. m_UI->menuTools->setDisabled(true);
  5659. }
  5660. else
  5661. {
  5662. updateMenus();
  5663. }
  5664. m_uiFrozen = state;
  5665. }
  5666. void MainWindow::activateRegisterPointPairTool()
  5667. {
  5668. if (!haveSelection())
  5669. {
  5670. ccConsole::Error(tr("Select at least one entity (point cloud or mesh)!"));
  5671. return;
  5672. }
  5673. ccHObject::Container alignedEntities;
  5674. ccHObject::Container refEntities;
  5675. try
  5676. {
  5677. ccHObject::Container entities;
  5678. entities.reserve(m_selectedEntities.size());
  5679. for (ccHObject* entity : m_selectedEntities)
  5680. {
  5681. //for now, we only handle clouds or meshes
  5682. if (entity->isKindOf(CC_TYPES::POINT_CLOUD) || entity->isKindOf(CC_TYPES::MESH))
  5683. {
  5684. entities.push_back(entity);
  5685. }
  5686. }
  5687. if (entities.empty())
  5688. {
  5689. ccConsole::Error("Select at least one entity (point cloud or mesh)!");
  5690. return;
  5691. }
  5692. else if (entities.size() == 1)
  5693. {
  5694. alignedEntities = entities;
  5695. }
  5696. else
  5697. {
  5698. std::vector<int> indexes;
  5699. if (!ccEntitySelectionDialog::SelectEntities(entities, indexes, this, tr("Select to-be-aligned entities")))
  5700. {
  5701. //process cancelled by the user
  5702. return;
  5703. }
  5704. //add the selected indexes as 'aligned' entities
  5705. alignedEntities.reserve(indexes.size());
  5706. for (size_t i = 0; i < indexes.size(); ++i)
  5707. {
  5708. alignedEntities.push_back(entities[indexes[i]]);
  5709. }
  5710. //add the others as 'reference' entities
  5711. assert(indexes.size() <= entities.size());
  5712. refEntities.reserve(entities.size() - indexes.size());
  5713. for (size_t i = 0; i < entities.size(); ++i)
  5714. {
  5715. if (std::find(indexes.begin(), indexes.end(), i) == indexes.end())
  5716. {
  5717. refEntities.push_back(entities[i]);
  5718. }
  5719. }
  5720. }
  5721. }
  5722. catch (const std::bad_alloc&)
  5723. {
  5724. ccLog::Error(tr("Not enough memory"));
  5725. return;
  5726. }
  5727. if (alignedEntities.empty())
  5728. {
  5729. ccLog::Error(tr("No to-be-aligned entity selected"));
  5730. return;
  5731. }
  5732. //deselect all entities
  5733. if (m_ccRoot)
  5734. {
  5735. m_ccRoot->unselectAllEntities();
  5736. }
  5737. ccGLWindowInterface* win = new3DView();
  5738. if (!win)
  5739. {
  5740. ccLog::Error(tr("[PointPairRegistration] Failed to create dedicated 3D view!"));
  5741. return;
  5742. }
  5743. //we disable all windows
  5744. disableAllBut(win);
  5745. if (!m_pprDlg)
  5746. {
  5747. m_pprDlg = new ccPointPairRegistrationDlg(m_pickingHub, this, this);
  5748. connect(m_pprDlg, &ccOverlayDialog::processFinished, this, &MainWindow::deactivateRegisterPointPairTool);
  5749. registerOverlayDialog(m_pprDlg, Qt::TopRightCorner);
  5750. }
  5751. if (!m_pprDlg->init(win, alignedEntities, &refEntities))
  5752. {
  5753. deactivateRegisterPointPairTool(false);
  5754. }
  5755. freezeUI(true);
  5756. if (!m_pprDlg->start())
  5757. deactivateRegisterPointPairTool(false);
  5758. else
  5759. updateOverlayDialogsPlacement();
  5760. }
  5761. void MainWindow::deactivateRegisterPointPairTool(bool state)
  5762. {
  5763. if (m_pprDlg)
  5764. m_pprDlg->clear();
  5765. //we enable all GL windows
  5766. enableAll();
  5767. QList<QMdiSubWindow*> subWindowList = m_mdiArea->subWindowList();
  5768. if (!subWindowList.isEmpty())
  5769. subWindowList.first()->showMaximized();
  5770. freezeUI(false);
  5771. updateUI();
  5772. setGlobalZoom();
  5773. }
  5774. void MainWindow::activateSectionExtractionMode()
  5775. {
  5776. if (!haveSelection())
  5777. return;
  5778. if (!m_seTool)
  5779. {
  5780. m_seTool = new ccSectionExtractionTool(this);
  5781. connect(m_seTool, &ccOverlayDialog::processFinished, this, &MainWindow::deactivateSectionExtractionMode);
  5782. registerOverlayDialog(m_seTool, Qt::TopRightCorner);
  5783. }
  5784. //add clouds
  5785. ccGLWindowInterface* firstDisplay = nullptr;
  5786. {
  5787. unsigned validCount = 0;
  5788. for (ccHObject *entity : getSelectedEntities())
  5789. {
  5790. if (entity->isKindOf(CC_TYPES::POINT_CLOUD))
  5791. {
  5792. if (m_seTool->addCloud(static_cast<ccGenericPointCloud*>(entity)))
  5793. {
  5794. if (!firstDisplay && entity->getDisplay())
  5795. {
  5796. firstDisplay = static_cast<ccGLWindowInterface*>(entity->getDisplay());
  5797. }
  5798. ++validCount;
  5799. }
  5800. }
  5801. }
  5802. if (validCount == 0)
  5803. {
  5804. ccConsole::Error(tr("No cloud in selection!"));
  5805. return;
  5806. }
  5807. }
  5808. //deselect all entities
  5809. if (m_ccRoot)
  5810. {
  5811. m_ccRoot->unselectAllEntities();
  5812. }
  5813. ccGLWindowInterface* win = new3DViewInternal(false);
  5814. if (!win)
  5815. {
  5816. ccLog::Error(tr("[SectionExtraction] Failed to create dedicated 3D view!"));
  5817. return;
  5818. }
  5819. if (firstDisplay && firstDisplay->getGlFilter())
  5820. {
  5821. win->setGlFilter(firstDisplay->getGlFilter()->clone());
  5822. }
  5823. m_seTool->linkWith(win);
  5824. freezeUI(true);
  5825. m_UI->toolBarView->setDisabled(true);
  5826. //we disable all other windows
  5827. disableAllBut(win);
  5828. if (!m_seTool->start())
  5829. deactivateSectionExtractionMode(false);
  5830. else
  5831. updateOverlayDialogsPlacement();
  5832. }
  5833. void MainWindow::deactivateSectionExtractionMode(bool state)
  5834. {
  5835. if (m_seTool)
  5836. m_seTool->removeAllEntities();
  5837. //we enable all GL windows
  5838. enableAll();
  5839. QList<QMdiSubWindow*> subWindowList = m_mdiArea->subWindowList();
  5840. if (!subWindowList.isEmpty())
  5841. subWindowList[0]->showMaximized();
  5842. freezeUI(false);
  5843. m_UI->toolBarView->setDisabled(false);
  5844. updateUI();
  5845. ccGLWindowInterface* win = getActiveGLWindow();
  5846. if (win)
  5847. win->redraw();
  5848. }
  5849. void MainWindow::activateSegmentationMode()
  5850. {
  5851. ccGLWindowInterface* win = getActiveGLWindow();
  5852. if (!win)
  5853. return;
  5854. if (!haveSelection())
  5855. return;
  5856. if (!m_gsTool)
  5857. {
  5858. m_gsTool = new ccGraphicalSegmentationTool(this);
  5859. connect(m_gsTool, &ccOverlayDialog::processFinished, this, &MainWindow::deactivateSegmentationMode);
  5860. registerOverlayDialog(m_gsTool, Qt::TopRightCorner);
  5861. }
  5862. m_gsTool->linkWith(win);
  5863. for ( ccHObject *entity : getSelectedEntities() )
  5864. {
  5865. m_gsTool->addEntity(entity);
  5866. }
  5867. if (m_gsTool->getNumberOfValidEntities() == 0)
  5868. {
  5869. ccConsole::Error(tr("No segmentable entity in active window!"));
  5870. return;
  5871. }
  5872. freezeUI(true);
  5873. m_UI->toolBarView->setDisabled(false);
  5874. //we disable all other windows
  5875. disableAllBut(win);
  5876. if (!m_gsTool->start())
  5877. deactivateSegmentationMode(false);
  5878. else
  5879. updateOverlayDialogsPlacement();
  5880. }
  5881. void MainWindow::deactivateSegmentationMode(bool state)
  5882. {
  5883. if (!m_gsTool)
  5884. {
  5885. assert(false);
  5886. return;
  5887. }
  5888. bool deleteHiddenParts = false;
  5889. //shall we apply segmentation?
  5890. if (state)
  5891. {
  5892. ccHObject::Container result;
  5893. m_gsTool->applySegmentation(this, result);
  5894. if (m_ccRoot)
  5895. {
  5896. m_ccRoot->selectEntities(result);
  5897. }
  5898. }
  5899. else
  5900. {
  5901. m_gsTool->removeAllEntities();
  5902. }
  5903. //we enable all GL windows
  5904. enableAll();
  5905. freezeUI(false);
  5906. updateUI();
  5907. ccGLWindowInterface* win = getActiveGLWindow();
  5908. if (win)
  5909. {
  5910. win->redraw();
  5911. }
  5912. }
  5913. void MainWindow::activateTracePolylineMode()
  5914. {
  5915. ccGLWindowInterface* win = getActiveGLWindow();
  5916. if (!win)
  5917. {
  5918. return;
  5919. }
  5920. if (!m_tplTool)
  5921. {
  5922. m_tplTool = new ccTracePolylineTool(m_pickingHub, this);
  5923. connect(m_tplTool, &ccOverlayDialog::processFinished, this, &MainWindow::deactivateTracePolylineMode);
  5924. registerOverlayDialog(m_tplTool, Qt::TopRightCorner);
  5925. }
  5926. m_tplTool->linkWith(win);
  5927. freezeUI(true);
  5928. m_UI->toolBarView->setDisabled(false);
  5929. //we disable all other windows
  5930. disableAllBut(win);
  5931. if (!m_tplTool->start())
  5932. deactivateTracePolylineMode(false);
  5933. else
  5934. updateOverlayDialogsPlacement();
  5935. }
  5936. void MainWindow::deactivateTracePolylineMode(bool)
  5937. {
  5938. //we enable all GL windows
  5939. enableAll();
  5940. freezeUI(false);
  5941. updateUI();
  5942. ccGLWindowInterface* win = getActiveGLWindow();
  5943. if (win)
  5944. {
  5945. win->redraw();
  5946. }
  5947. }
  5948. void MainWindow::activatePointListPickingMode()
  5949. {
  5950. ccGLWindowInterface* win = getActiveGLWindow();
  5951. if (!win)
  5952. return;
  5953. //there should be only one point cloud in current selection!
  5954. if (!haveOneSelection())
  5955. {
  5956. ccConsole::Error(tr("Select one and only one entity!"));
  5957. return;
  5958. }
  5959. ccHObject* entity = m_selectedEntities.front();
  5960. if (!entity->isKindOf(CC_TYPES::POINT_CLOUD) && !entity->isKindOf(CC_TYPES::MESH))
  5961. {
  5962. ccConsole::Error(tr("Select a cloud or a mesh"));
  5963. return;
  5964. }
  5965. if (!entity->isVisible() || !entity->isEnabled())
  5966. {
  5967. ccConsole::Error(tr("Entity must be visible!"));
  5968. return;
  5969. }
  5970. if (!m_plpDlg)
  5971. {
  5972. m_plpDlg = new ccPointListPickingDlg(m_pickingHub, this);
  5973. connect(m_plpDlg, &ccOverlayDialog::processFinished, this, &MainWindow::deactivatePointListPickingMode);
  5974. registerOverlayDialog(m_plpDlg, Qt::TopRightCorner);
  5975. }
  5976. //DGM: we must update marker size spin box value (as it may have changed by the user with the "display dialog")
  5977. m_plpDlg->markerSizeSpinBox->setValue(win->getDisplayParameters().labelMarkerSize);
  5978. m_plpDlg->linkWith(win);
  5979. m_plpDlg->linkWithEntity(entity);
  5980. freezeUI(true);
  5981. //we disable all other windows
  5982. disableAllBut(win);
  5983. if (!m_plpDlg->start())
  5984. deactivatePointListPickingMode(false);
  5985. else
  5986. updateOverlayDialogsPlacement();
  5987. }
  5988. void MainWindow::deactivatePointListPickingMode(bool state)
  5989. {
  5990. if (m_plpDlg)
  5991. {
  5992. m_plpDlg->linkWithEntity(nullptr);
  5993. }
  5994. //we enable all GL windows
  5995. enableAll();
  5996. freezeUI(false);
  5997. updateUI();
  5998. }
  5999. void MainWindow::activatePointPickingMode()
  6000. {
  6001. ccGLWindowInterface* win = getActiveGLWindow();
  6002. if (!win)
  6003. {
  6004. return;
  6005. }
  6006. if (m_ccRoot)
  6007. {
  6008. m_ccRoot->unselectAllEntities(); //we don't want any entity selected (especially existing labels!)
  6009. }
  6010. if (!m_ppDlg)
  6011. {
  6012. m_ppDlg = new ccPointPropertiesDlg(m_pickingHub, this);
  6013. connect(m_ppDlg, &ccOverlayDialog::processFinished, this, &MainWindow::deactivatePointPickingMode);
  6014. connect(m_ppDlg, &ccPointPropertiesDlg::newLabel, this, &MainWindow::handleNewLabel);
  6015. registerOverlayDialog(m_ppDlg, Qt::TopRightCorner);
  6016. }
  6017. m_ppDlg->linkWith(win);
  6018. freezeUI(true);
  6019. //we disable all other windows
  6020. disableAllBut(win);
  6021. if (!m_ppDlg->start())
  6022. deactivatePointPickingMode(false);
  6023. else
  6024. updateOverlayDialogsPlacement();
  6025. }
  6026. void MainWindow::deactivatePointPickingMode(bool state)
  6027. {
  6028. //if (m_ppDlg)
  6029. // m_ppDlg->linkWith(nullptr);
  6030. //we enable all GL windows
  6031. enableAll();
  6032. freezeUI(false);
  6033. updateUI();
  6034. redrawAll();
  6035. }
  6036. void MainWindow::activateClippingBoxMode()
  6037. {
  6038. if ( !haveSelection() )
  6039. {
  6040. return;
  6041. }
  6042. ccGLWindowInterface* win = getActiveGLWindow();
  6043. if (!win)
  6044. {
  6045. return;
  6046. }
  6047. if (!m_clipTool)
  6048. {
  6049. m_clipTool = new ccClippingBoxTool(this);
  6050. connect(m_clipTool, &ccOverlayDialog::processFinished, this, &MainWindow::deactivateClippingBoxMode);
  6051. }
  6052. m_clipTool->linkWith(win);
  6053. ccHObject::Container selectedEntities = getSelectedEntities(); //we have to use a local copy: 'unselectEntity' will change the set of currently selected entities!
  6054. for (ccHObject *entity : selectedEntities)
  6055. {
  6056. if (m_clipTool->addAssociatedEntity(entity))
  6057. {
  6058. //automatically deselect the entity (to avoid seeing its bounding box ;)
  6059. m_ccRoot->unselectEntity(entity);
  6060. }
  6061. }
  6062. if (m_clipTool->getNumberOfAssociatedEntity() == 0)
  6063. {
  6064. m_clipTool->close();
  6065. return;
  6066. }
  6067. if (m_clipTool->start())
  6068. {
  6069. registerOverlayDialog(m_clipTool, Qt::TopRightCorner);
  6070. freezeUI(true);
  6071. updateOverlayDialogsPlacement();
  6072. //deactivate all other GL windows
  6073. disableAllBut(win);
  6074. }
  6075. else
  6076. {
  6077. ccConsole::Error(tr("Unexpected error!")); //indeed...
  6078. }
  6079. }
  6080. void MainWindow::deactivateClippingBoxMode(bool state)
  6081. {
  6082. //we reactivate all GL windows
  6083. enableAll();
  6084. freezeUI(false);
  6085. updateUI();
  6086. }
  6087. void MainWindow::activateTranslateRotateMode()
  6088. {
  6089. if (!haveSelection())
  6090. return;
  6091. ccGLWindowInterface* win = getActiveGLWindow();
  6092. if (!win)
  6093. return;
  6094. if (!m_transTool)
  6095. m_transTool = new ccGraphicalTransformationTool(this);
  6096. assert(m_transTool->getNumberOfValidEntities() == 0);
  6097. m_transTool->linkWith(win);
  6098. bool rejectedEntities = false;
  6099. for ( ccHObject *entity : getSelectedEntities() )
  6100. {
  6101. if (!m_transTool->addEntity(entity))
  6102. rejectedEntities = true;
  6103. }
  6104. if (m_transTool->getNumberOfValidEntities() == 0)
  6105. {
  6106. ccConsole::Error(tr("No entity eligible for manual transformation! (see console)"));
  6107. return;
  6108. }
  6109. else if (rejectedEntities)
  6110. {
  6111. ccConsole::Error(tr("Some entities were ignored! (see console)"));
  6112. }
  6113. //try to activate "moving mode" in current GL window
  6114. if (m_transTool->start())
  6115. {
  6116. connect(m_transTool, &ccOverlayDialog::processFinished, this, &MainWindow::deactivateTranslateRotateMode);
  6117. registerOverlayDialog(m_transTool, Qt::TopRightCorner);
  6118. freezeUI(true);
  6119. updateOverlayDialogsPlacement();
  6120. //deactivate all other GL windows
  6121. disableAllBut(win);
  6122. }
  6123. else
  6124. {
  6125. ccConsole::Error(tr("Unexpected error!")); //indeed...
  6126. }
  6127. }
  6128. void MainWindow::deactivateTranslateRotateMode(bool state)
  6129. {
  6130. if (m_transTool)
  6131. {
  6132. //reselect previously selected entities!
  6133. if (state && m_ccRoot)
  6134. {
  6135. const ccHObject& transformedSet = m_transTool->getValidEntities();
  6136. try
  6137. {
  6138. ccHObject::Container transformedEntities;
  6139. transformedEntities.resize(transformedSet.getChildrenNumber());
  6140. for (unsigned i = 0; i < transformedSet.getChildrenNumber(); ++i)
  6141. {
  6142. transformedEntities[i] = transformedSet.getChild(i);
  6143. }
  6144. m_ccRoot->selectEntities(transformedEntities);
  6145. }
  6146. catch (const std::bad_alloc&)
  6147. {
  6148. //not enough memory (nothing to do)
  6149. }
  6150. }
  6151. //m_transTool->close();
  6152. }
  6153. //we reactivate all GL windows
  6154. enableAll();
  6155. freezeUI(false);
  6156. updateUI();
  6157. }
  6158. void MainWindow::testFrameRate()
  6159. {
  6160. ccGLWindowInterface* win = getActiveGLWindow();
  6161. if (win)
  6162. win->startFrameRateTest();
  6163. }
  6164. void MainWindow::showDisplaySettings()
  6165. {
  6166. ccDisplaySettingsDlg displayOptionsDlg(this);
  6167. connect(&displayOptionsDlg, &ccDisplaySettingsDlg::aspectHasChanged, this, [=] () { redrawAll(); });
  6168. displayOptionsDlg.exec();
  6169. disconnect(&displayOptionsDlg);
  6170. }
  6171. void MainWindow::doActionRenderToFile()
  6172. {
  6173. ccGLWindowInterface* win = getActiveGLWindow();
  6174. if (!win)
  6175. return;
  6176. ccRenderToFileDlg rtfDlg(win->glWidth(), win->glHeight(), this);
  6177. if (rtfDlg.exec())
  6178. {
  6179. QApplication::processEvents();
  6180. win->renderToFile(rtfDlg.getFilename(), rtfDlg.getZoom(), rtfDlg.dontScalePoints(), rtfDlg.renderOverlayItems());
  6181. }
  6182. }
  6183. void MainWindow::doActionEditCamera()
  6184. {
  6185. //current active MDI area
  6186. QMdiSubWindow* qWin = m_mdiArea->activeSubWindow();
  6187. if (!qWin)
  6188. return;
  6189. if (!m_cpeDlg)
  6190. {
  6191. m_cpeDlg = new ccCameraParamEditDlg(qWin, m_pickingHub);
  6192. //m_cpeDlg->makeFrameless(); //does not work on linux
  6193. connect(m_mdiArea, &QMdiArea::subWindowActivated,
  6194. m_cpeDlg, qOverload<QMdiSubWindow*>(&ccCameraParamEditDlg::linkWith));
  6195. registerOverlayDialog(m_cpeDlg, Qt::BottomLeftCorner);
  6196. }
  6197. m_cpeDlg->linkWith(qWin);
  6198. m_cpeDlg->start();
  6199. updateOverlayDialogsPlacement();
  6200. }
  6201. void MainWindow::doActionAdjustZoom()
  6202. {
  6203. //current active MDI area
  6204. ccGLWindowInterface* win = getActiveGLWindow();
  6205. if (!win)
  6206. return;
  6207. const ccViewportParameters& params = win->getViewportParameters();
  6208. if (params.perspectiveView)
  6209. {
  6210. ccConsole::Error(tr("Orthographic mode only!"));
  6211. return;
  6212. }
  6213. ccAdjustZoomDlg azDlg(win, this);
  6214. if (!azDlg.exec())
  6215. return;
  6216. //apply new focal
  6217. double focalDist = azDlg.getFocalDistance();
  6218. win->setFocalDistance(focalDist);
  6219. win->redraw();
  6220. }
  6221. static unsigned s_viewportIndex = 0;
  6222. void MainWindow::doActionSaveViewportAsCamera()
  6223. {
  6224. ccGLWindowInterface* win = getActiveGLWindow();
  6225. if (!win)
  6226. return;
  6227. cc2DViewportObject* viewportObject = new cc2DViewportObject(QString("Viewport #%1").arg(++s_viewportIndex));
  6228. viewportObject->setParameters(win->getViewportParameters());
  6229. viewportObject->setDisplay(win);
  6230. // Save the custom light position as well
  6231. {
  6232. bool customLightEnabled = win->customLightEnabled();
  6233. CCVector3f customLightPos = win->getCustomLightPosition();
  6234. viewportObject->setMetaData("CustomLightEnabled", customLightEnabled);
  6235. viewportObject->setMetaData("CustomLightPosX", customLightPos.x);
  6236. viewportObject->setMetaData("CustomLightPosY", customLightPos.y);
  6237. viewportObject->setMetaData("CustomLightPosZ", customLightPos.z);
  6238. }
  6239. addToDB(viewportObject);
  6240. }
  6241. void MainWindow::zoomOnSelectedEntities()
  6242. {
  6243. ccGLWindowInterface* win = nullptr;
  6244. ccHObject tempGroup("TempGroup");
  6245. size_t selNum = m_selectedEntities.size();
  6246. for (size_t i = 0; i < selNum; ++i)
  6247. {
  6248. ccHObject *entity = m_selectedEntities[i];
  6249. if (i == 0 || !win)
  6250. {
  6251. //take the first valid window as reference
  6252. win = static_cast<ccGLWindowInterface*>(entity->getDisplay());
  6253. }
  6254. if (win)
  6255. {
  6256. if (entity->getDisplay() == win)
  6257. {
  6258. tempGroup.addChild(entity,ccHObject::DP_NONE);
  6259. }
  6260. else if (entity->getDisplay() != nullptr)
  6261. {
  6262. ccLog::Error(tr("All selected entities must be displayed in the same 3D view!"));
  6263. return;
  6264. }
  6265. }
  6266. }
  6267. if (tempGroup.getChildrenNumber() != 0)
  6268. {
  6269. ccBBox box = tempGroup.getDisplayBB_recursive(false, win);
  6270. if (!box.isValid())
  6271. {
  6272. ccLog::Warning(tr("Selected entities have no valid bounding-box!"));
  6273. }
  6274. else
  6275. {
  6276. if ( win != nullptr )
  6277. {
  6278. win->updateConstellationCenterAndZoom(&box);
  6279. }
  6280. }
  6281. }
  6282. refreshAll();
  6283. }
  6284. void MainWindow::setGlobalZoom()
  6285. {
  6286. ccGLWindowInterface* win = getActiveGLWindow();
  6287. if (win)
  6288. win->zoomGlobal();
  6289. }
  6290. void MainWindow::setPivotAlwaysOn()
  6291. {
  6292. ccGLWindowInterface* win = getActiveGLWindow();
  6293. if (win)
  6294. {
  6295. win->setPivotVisibility(ccGLWindowInterface::PIVOT_ALWAYS_SHOW);
  6296. win->redraw();
  6297. //update pop-up menu 'top' icon
  6298. if (m_pivotVisibilityPopupButton)
  6299. m_pivotVisibilityPopupButton->setIcon(m_UI->actionSetPivotAlwaysOn->icon());
  6300. }
  6301. }
  6302. void MainWindow::setPivotRotationOnly()
  6303. {
  6304. ccGLWindowInterface* win = getActiveGLWindow();
  6305. if (win)
  6306. {
  6307. win->setPivotVisibility(ccGLWindowInterface::PIVOT_SHOW_ON_MOVE);
  6308. win->redraw();
  6309. //update pop-up menu 'top' icon
  6310. if (m_pivotVisibilityPopupButton)
  6311. m_pivotVisibilityPopupButton->setIcon(m_UI->actionSetPivotRotationOnly->icon());
  6312. }
  6313. }
  6314. void MainWindow::setPivotOff()
  6315. {
  6316. ccGLWindowInterface* win = getActiveGLWindow();
  6317. if (win)
  6318. {
  6319. win->setPivotVisibility(ccGLWindowInterface::PIVOT_HIDE);
  6320. win->redraw();
  6321. //update pop-up menu 'top' icon
  6322. if (m_pivotVisibilityPopupButton)
  6323. m_pivotVisibilityPopupButton->setIcon(m_UI->actionSetPivotOff->icon());
  6324. }
  6325. }
  6326. void MainWindow::setOrthoView(ccGLWindowInterface* win)
  6327. {
  6328. if (win)
  6329. {
  6330. if (!checkStereoMode(win))
  6331. {
  6332. return;
  6333. }
  6334. win->setPerspectiveState(false, true);
  6335. win->redraw();
  6336. //update pop-up menu 'top' icon
  6337. if (m_viewModePopupButton)
  6338. m_viewModePopupButton->setIcon(m_UI->actionSetOrthoView->icon());
  6339. if (m_pivotVisibilityPopupButton)
  6340. m_pivotVisibilityPopupButton->setEnabled(true);
  6341. }
  6342. }
  6343. void MainWindow::setCenteredPerspectiveView(ccGLWindowInterface* win, bool autoRedraw/*=true*/)
  6344. {
  6345. if (win)
  6346. {
  6347. win->setPerspectiveState(true, true);
  6348. if (autoRedraw)
  6349. win->redraw();
  6350. //update pop-up menu 'top' icon
  6351. if (m_viewModePopupButton)
  6352. m_viewModePopupButton->setIcon(m_UI->actionSetCenteredPerspectiveView->icon());
  6353. if (m_pivotVisibilityPopupButton)
  6354. m_pivotVisibilityPopupButton->setEnabled(true);
  6355. }
  6356. }
  6357. void MainWindow::setViewerPerspectiveView(ccGLWindowInterface* win)
  6358. {
  6359. if (win)
  6360. {
  6361. win->setPerspectiveState(true,false);
  6362. win->redraw();
  6363. //update pop-up menu 'top' icon
  6364. if (m_viewModePopupButton)
  6365. m_viewModePopupButton->setIcon(m_UI->actionSetViewerPerspectiveView->icon());
  6366. if (m_pivotVisibilityPopupButton)
  6367. m_pivotVisibilityPopupButton->setEnabled(false);
  6368. }
  6369. }
  6370. void MainWindow::enablePickingOperation(ccGLWindowInterface* win, QString message)
  6371. {
  6372. if (!win)
  6373. {
  6374. assert(false);
  6375. return;
  6376. }
  6377. assert(m_pickingHub);
  6378. if (!m_pickingHub->addListener(this))
  6379. {
  6380. ccLog::Error(tr("Can't start the picking mechanism (another tool is already using it)"));
  6381. return;
  6382. }
  6383. //specific case: we prevent the 'point-pair based alignment' tool to process the picked point!
  6384. //if (m_pprDlg)
  6385. // m_pprDlg->pause(true);
  6386. s_pickingWindow = win;
  6387. win->displayNewMessage(message, ccGLWindowInterface::LOWER_LEFT_MESSAGE, true, 24 * 3600);
  6388. win->redraw(true, false);
  6389. freezeUI(true);
  6390. }
  6391. void MainWindow::cancelPreviousPickingOperation(bool aborted)
  6392. {
  6393. if (!s_pickingWindow)
  6394. return;
  6395. switch(s_currentPickingOperation)
  6396. {
  6397. case PICKING_ROTATION_CENTER:
  6398. //nothing to do
  6399. break;
  6400. case PICKING_LEVEL_POINTS:
  6401. if (s_levelMarkersCloud)
  6402. {
  6403. s_pickingWindow->removeFromOwnDB(s_levelMarkersCloud);
  6404. delete s_levelMarkersCloud;
  6405. s_levelMarkersCloud = nullptr;
  6406. }
  6407. break;
  6408. default:
  6409. assert(false);
  6410. break;
  6411. }
  6412. if (aborted)
  6413. {
  6414. s_pickingWindow->displayNewMessage(QString(), ccGLWindowInterface::LOWER_LEFT_MESSAGE); //clear previous messages
  6415. s_pickingWindow->displayNewMessage(tr("Picking operation aborted"), ccGLWindowInterface::LOWER_LEFT_MESSAGE);
  6416. }
  6417. s_pickingWindow->redraw(false);
  6418. //specific case: we allow the 'point-pair based alignment' tool to process the picked point!
  6419. if (m_pprDlg)
  6420. m_pprDlg->pause(false);
  6421. freezeUI(false);
  6422. m_pickingHub->removeListener(this);
  6423. s_pickingWindow = nullptr;
  6424. s_currentPickingOperation = NO_PICKING_OPERATION;
  6425. }
  6426. void MainWindow::onItemPicked(const PickedItem& pi)
  6427. {
  6428. if (!s_pickingWindow || !m_pickingHub)
  6429. {
  6430. return;
  6431. }
  6432. if (!pi.entity)
  6433. {
  6434. return;
  6435. }
  6436. if (m_pickingHub->activeWindow() != s_pickingWindow)
  6437. {
  6438. ccLog::Warning(tr("The point was picked in the wrong window"));
  6439. return;
  6440. }
  6441. CCVector3 pickedPoint = pi.P3D;
  6442. switch(s_currentPickingOperation)
  6443. {
  6444. case PICKING_LEVEL_POINTS:
  6445. {
  6446. //we only accept points picked on the right entity!
  6447. //if (obj != s_levelEntity)
  6448. //{
  6449. // ccLog::Warning(tr("[Level] Only points picked on '%1' are considered!").arg(s_levelEntity->getName()));
  6450. // return;
  6451. //}
  6452. if (!s_levelMarkersCloud)
  6453. {
  6454. assert(false);
  6455. cancelPreviousPickingOperation(true);
  6456. }
  6457. for (unsigned i = 0; i < s_levelMarkersCloud->size(); ++i)
  6458. {
  6459. const CCVector3* P = s_levelMarkersCloud->getPoint(i);
  6460. if ((pickedPoint - *P).norm() < 1.0e-6)
  6461. {
  6462. ccLog::Warning(tr("[Level] Point is too close from the others!"));
  6463. return;
  6464. }
  6465. }
  6466. //add the corresponding marker
  6467. s_levelMarkersCloud->addPoint(pickedPoint);
  6468. unsigned markerCount = s_levelMarkersCloud->size();
  6469. cc2DLabel* label = new cc2DLabel();
  6470. label->addPickedPoint(s_levelMarkersCloud, markerCount - 1);
  6471. label->setName(QString("P#%1").arg(markerCount));
  6472. label->setDisplayedIn2D(false);
  6473. label->setDisplay(s_pickingWindow);
  6474. label->setVisible(true);
  6475. s_levelMarkersCloud->addChild(label);
  6476. s_pickingWindow->redraw();
  6477. if (markerCount == 3)
  6478. {
  6479. //we have enough points!
  6480. const CCVector3* A = s_levelMarkersCloud->getPoint(0);
  6481. const CCVector3* B = s_levelMarkersCloud->getPoint(1);
  6482. const CCVector3* C = s_levelMarkersCloud->getPoint(2);
  6483. CCVector3 X = *B - *A;
  6484. CCVector3 Y = *C - *A;
  6485. CCVector3 Z = X.cross(Y);
  6486. //we choose 'Z' so that it points 'upward' relatively to the camera (assuming the user will be looking from the top)
  6487. CCVector3d viewDir = s_pickingWindow->getViewportParameters().getViewDir();
  6488. if (Z.toDouble().dot(viewDir) > 0)
  6489. {
  6490. Z = -Z;
  6491. }
  6492. Y = Z.cross(X);
  6493. X.normalize();
  6494. Y.normalize();
  6495. Z.normalize();
  6496. ccGLMatrixd trans;
  6497. {
  6498. double* mat = trans.data();
  6499. mat[0] = X.x; mat[4] = X.y; mat[8] = X.z; mat[12] = 0.0;
  6500. mat[1] = Y.x; mat[5] = Y.y; mat[9] = Y.z; mat[13] = 0.0;
  6501. mat[2] = Z.x; mat[6] = Z.y; mat[10] = Z.z; mat[14] = 0.0;
  6502. mat[3] = 0.0; mat[7] = 0.0; mat[11] = 0.0; mat[15] = 1.0;
  6503. }
  6504. CCVector3d T = -A->toDouble();
  6505. trans.apply(T);
  6506. T += *A;
  6507. trans.setTranslation(T);
  6508. assert(haveOneSelection() && m_selectedEntities.front() == s_levelEntity);
  6509. applyTransformation(trans, false);
  6510. //clear message
  6511. s_pickingWindow->displayNewMessage(QString(), ccGLWindowInterface::LOWER_LEFT_MESSAGE, false); //clear previous message
  6512. s_pickingWindow->setView(CC_TOP_VIEW);
  6513. }
  6514. else
  6515. {
  6516. //we need more points!
  6517. return;
  6518. }
  6519. }
  6520. //we use the next 'case' entry (PICKING_ROTATION_CENTER) to redefine the rotation center as well!
  6521. assert(s_levelMarkersCloud && s_levelMarkersCloud->size() != 0);
  6522. pickedPoint = *s_levelMarkersCloud->getPoint(0);
  6523. //break;
  6524. case PICKING_ROTATION_CENTER:
  6525. {
  6526. CCVector3d newPivot = pickedPoint;
  6527. //specific case: transformation tool is enabled
  6528. if (m_transTool && m_transTool->started())
  6529. {
  6530. m_transTool->setRotationCenter(newPivot);
  6531. const unsigned& precision = s_pickingWindow->getDisplayParameters().displayedNumPrecision;
  6532. s_pickingWindow->displayNewMessage(QString(), ccGLWindowInterface::LOWER_LEFT_MESSAGE, false); //clear previous message
  6533. s_pickingWindow->displayNewMessage(QString("Point (%1 ; %2 ; %3) set as rotation center for interactive transformation")
  6534. .arg(pickedPoint.x, 0, 'f', precision)
  6535. .arg(pickedPoint.y, 0, 'f', precision)
  6536. .arg(pickedPoint.z, 0, 'f', precision),
  6537. ccGLWindowInterface::LOWER_LEFT_MESSAGE, true);
  6538. }
  6539. else
  6540. {
  6541. const ccViewportParameters& params = s_pickingWindow->getViewportParameters();
  6542. if (!params.perspectiveView || params.objectCenteredView)
  6543. {
  6544. //apply current GL transformation (if any)
  6545. pi.entity->getGLTransformation().apply(newPivot);
  6546. s_pickingWindow->setPivotPoint(newPivot, true, true);
  6547. }
  6548. }
  6549. //s_pickingWindow->redraw(); //already called by 'cancelPreviousPickingOperation' (see below)
  6550. }
  6551. break;
  6552. default:
  6553. assert(false);
  6554. break;
  6555. }
  6556. cancelPreviousPickingOperation(false);
  6557. }
  6558. void MainWindow::doLevel()
  6559. {
  6560. //picking operation already in progress
  6561. if (s_pickingWindow)
  6562. {
  6563. if (s_currentPickingOperation == PICKING_LEVEL_POINTS)
  6564. {
  6565. cancelPreviousPickingOperation(true);
  6566. }
  6567. else
  6568. {
  6569. ccConsole::Error(tr("Stop the other picking operation first!"));
  6570. }
  6571. return;
  6572. }
  6573. ccGLWindowInterface* win = getActiveGLWindow();
  6574. if (!win)
  6575. {
  6576. ccConsole::Error(tr("No active 3D view!"));
  6577. return;
  6578. }
  6579. if (!haveOneSelection())
  6580. {
  6581. ccConsole::Error(tr("Select an entity!"));
  6582. return;
  6583. }
  6584. //create markers cloud
  6585. assert(!s_levelMarkersCloud);
  6586. {
  6587. s_levelMarkersCloud = new ccPointCloud("Level points");
  6588. if (!s_levelMarkersCloud->reserve(3))
  6589. {
  6590. ccConsole::Error(tr("Not enough memory!"));
  6591. return;
  6592. }
  6593. win->addToOwnDB(s_levelMarkersCloud);
  6594. }
  6595. s_levelEntity = m_selectedEntities.front();
  6596. s_levelLabels.clear();
  6597. s_currentPickingOperation = PICKING_LEVEL_POINTS;
  6598. enablePickingOperation(win, tr("Pick three points on the floor plane (click the Level button or press Escape to cancel)"));
  6599. }
  6600. void MainWindow::doPickRotationCenter()
  6601. {
  6602. //picking operation already in progress
  6603. if (s_pickingWindow)
  6604. {
  6605. if (s_currentPickingOperation == PICKING_ROTATION_CENTER)
  6606. {
  6607. cancelPreviousPickingOperation(true);
  6608. }
  6609. else
  6610. {
  6611. ccConsole::Error(tr("Stop the other picking operation first!"));
  6612. }
  6613. return;
  6614. }
  6615. ccGLWindowInterface* win = getActiveGLWindow();
  6616. if (!win)
  6617. {
  6618. ccConsole::Error(tr("No active 3D view!"));
  6619. return;
  6620. }
  6621. bool objectCentered = true;
  6622. bool perspectiveEnabled = win->getPerspectiveState(objectCentered);
  6623. if (perspectiveEnabled && !objectCentered)
  6624. {
  6625. ccLog::Error(tr("Perspective mode is viewer-centered: can't use a point as rotation center!"));
  6626. return;
  6627. }
  6628. s_currentPickingOperation = PICKING_ROTATION_CENTER;
  6629. enablePickingOperation(win, tr("Pick a point to be used as rotation center (click on icon again to cancel)"));
  6630. }
  6631. ccPointCloud* MainWindow::askUserToSelectACloud(ccHObject* defaultCloudEntity/*=nullptr*/, QString inviteMessage/*=QString()*/)
  6632. {
  6633. ccHObject::Container clouds;
  6634. m_ccRoot->getRootEntity()->filterChildren(clouds, true, CC_TYPES::POINT_CLOUD, true);
  6635. if (clouds.empty())
  6636. {
  6637. ccConsole::Error(tr("No cloud in database!"));
  6638. return nullptr;
  6639. }
  6640. //default selected index
  6641. int selectedIndex = 0;
  6642. if (defaultCloudEntity)
  6643. {
  6644. for (size_t i = 1; i < clouds.size(); ++i)
  6645. {
  6646. if (clouds[i] == defaultCloudEntity)
  6647. {
  6648. selectedIndex = static_cast<int>(i);
  6649. break;
  6650. }
  6651. }
  6652. }
  6653. //ask the user to choose a cloud
  6654. {
  6655. selectedIndex = ccItemSelectionDlg::SelectEntity(clouds, selectedIndex, this, inviteMessage);
  6656. if (selectedIndex < 0)
  6657. return nullptr;
  6658. }
  6659. assert(selectedIndex >= 0 && static_cast<size_t>(selectedIndex) < clouds.size());
  6660. return ccHObjectCaster::ToPointCloud(clouds[selectedIndex]);
  6661. }
  6662. void MainWindow::toggleSelectedEntitiesProperty( ccEntityAction::TOGGLE_PROPERTY property )
  6663. {
  6664. if ( !ccEntityAction::toggleProperty( m_selectedEntities, property ) )
  6665. {
  6666. return;
  6667. }
  6668. refreshAll();
  6669. updateUI();
  6670. }
  6671. void MainWindow::clearSelectedEntitiesProperty( ccEntityAction::CLEAR_PROPERTY property )
  6672. {
  6673. if ( !ccEntityAction::clearProperty( m_selectedEntities, property, this ) )
  6674. {
  6675. return;
  6676. }
  6677. refreshAll();
  6678. updateUI();
  6679. }
  6680. void MainWindow::setView( CC_VIEW_ORIENTATION view )
  6681. {
  6682. ccGLWindowInterface* win = getActiveGLWindow();
  6683. if (win)
  6684. {
  6685. win->setView(view);
  6686. }
  6687. }
  6688. void MainWindow::spawnHistogramDialog(const std::vector<unsigned>& histoValues, double minVal, double maxVal, QString title, QString xAxisLabel)
  6689. {
  6690. ccHistogramWindowDlg* hDlg = new ccHistogramWindowDlg(this);
  6691. hDlg->setAttribute(Qt::WA_DeleteOnClose, true);
  6692. hDlg->setWindowTitle(tr("Histogram"));
  6693. ccHistogramWindow* histogram = hDlg->window();
  6694. {
  6695. histogram->setTitle(title);
  6696. histogram->fromBinArray(histoValues, minVal, maxVal);
  6697. histogram->setAxisLabels(xAxisLabel, tr("Count"));
  6698. histogram->refresh();
  6699. }
  6700. hDlg->show();
  6701. }
  6702. void MainWindow::showSelectedEntitiesHistogram()
  6703. {
  6704. for ( ccHObject *entity : getSelectedEntities() )
  6705. {
  6706. //for "real" point clouds only
  6707. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud( entity );
  6708. if (cloud)
  6709. {
  6710. //we display the histogram of the current scalar field
  6711. ccScalarField* sf = static_cast<ccScalarField*>(cloud->getCurrentDisplayedScalarField());
  6712. if (sf)
  6713. {
  6714. ccHistogramWindowDlg* hDlg = new ccHistogramWindowDlg(this);
  6715. hDlg->setAttribute(Qt::WA_DeleteOnClose, true);
  6716. hDlg->setWindowTitle(tr("Histogram [%1]").arg(cloud->getName()));
  6717. ccHistogramWindow* histogram = hDlg->window();
  6718. {
  6719. unsigned numberOfPoints = cloud->size();
  6720. unsigned numberOfClasses = static_cast<unsigned>(sqrt(static_cast<double>(numberOfPoints)));
  6721. //we take the 'nearest' multiple of 4
  6722. numberOfClasses &= (~3);
  6723. numberOfClasses = std::max<unsigned>(4, numberOfClasses);
  6724. numberOfClasses = std::min<unsigned>(256, numberOfClasses);
  6725. histogram->setTitle(tr("%1 (%2 values) ").arg(QString::fromStdString(sf->getName())).arg(numberOfPoints));
  6726. bool showNaNValuesInGrey = sf->areNaNValuesShownInGrey();
  6727. histogram->fromSF(sf, numberOfClasses, true, showNaNValuesInGrey);
  6728. histogram->setAxisLabels(QString::fromStdString(sf->getName()), tr("Count"));
  6729. histogram->refresh();
  6730. }
  6731. hDlg->show();
  6732. }
  6733. }
  6734. }
  6735. }
  6736. void MainWindow::doActionCrop()
  6737. {
  6738. //find candidates
  6739. std::vector<ccHObject*> candidates;
  6740. ccBBox baseBB;
  6741. {
  6742. const ccHObject::Container& selectedEntities = getSelectedEntities();
  6743. for ( ccHObject *entity : selectedEntities )
  6744. {
  6745. if ( entity->isA(CC_TYPES::POINT_CLOUD)
  6746. || entity->isKindOf(CC_TYPES::MESH) )
  6747. {
  6748. candidates.push_back(entity);
  6749. baseBB += entity->getOwnBB();
  6750. }
  6751. }
  6752. }
  6753. if (candidates.empty())
  6754. {
  6755. ccConsole::Warning(tr("[Crop] No eligible candidate found!"));
  6756. return;
  6757. }
  6758. ccBoundingBoxEditorDlg bbeDlg(false, false, this);
  6759. bbeDlg.setBaseBBox(baseBB, false);
  6760. bbeDlg.showInclusionWarning(false);
  6761. bbeDlg.setWindowTitle("Crop");
  6762. if (!bbeDlg.exec())
  6763. {
  6764. //process cancelled by user
  6765. return;
  6766. }
  6767. //deselect all entities
  6768. if (m_ccRoot)
  6769. {
  6770. m_ccRoot->unselectAllEntities();
  6771. }
  6772. //cropping box
  6773. ccBBox box = bbeDlg.getBox();
  6774. //process cloud/meshes
  6775. bool errors = false;
  6776. bool successes = false;
  6777. {
  6778. for ( ccHObject *entity : candidates )
  6779. {
  6780. ccHObject* croppedEnt = ccCropTool::Crop(entity, box, true);
  6781. if (croppedEnt)
  6782. {
  6783. croppedEnt->setName(entity->getName() + QString(".cropped"));
  6784. croppedEnt->setDisplay(entity->getDisplay());
  6785. croppedEnt->prepareDisplayForRefresh();
  6786. if (entity->getParent())
  6787. entity->getParent()->addChild(croppedEnt);
  6788. entity->setEnabled(false);
  6789. addToDB(croppedEnt);
  6790. //select output entity
  6791. m_ccRoot->selectEntity(croppedEnt, true);
  6792. successes = true;
  6793. }
  6794. else
  6795. {
  6796. errors = true;
  6797. }
  6798. }
  6799. }
  6800. if (successes)
  6801. ccLog::Warning(tr("[Crop] Selected entities have been hidden"));
  6802. if (errors)
  6803. ccLog::Error(tr("Error(s) occurred! See the Console"));
  6804. refreshAll();
  6805. updateUI();
  6806. }
  6807. void MainWindow::doActionClone()
  6808. {
  6809. ccHObject* lastClone = nullptr;
  6810. for ( ccHObject *entity : getSelectedEntities() )
  6811. {
  6812. ccHObject* clone = nullptr;
  6813. if (entity->isKindOf(CC_TYPES::POINT_CLOUD))
  6814. {
  6815. clone = ccHObjectCaster::ToGenericPointCloud(entity)->clone();
  6816. if (!clone)
  6817. {
  6818. ccConsole::Error(tr("An error occurred while cloning cloud %1").arg(entity->getName()));
  6819. }
  6820. }
  6821. else if (entity->isKindOf(CC_TYPES::PRIMITIVE))
  6822. {
  6823. clone = static_cast<ccGenericPrimitive*>(entity)->clone();
  6824. if (!clone)
  6825. {
  6826. ccConsole::Error(tr("An error occurred while cloning primitive %1").arg(entity->getName()));
  6827. }
  6828. }
  6829. else if (entity->isA(CC_TYPES::MESH))
  6830. {
  6831. clone = ccHObjectCaster::ToMesh(entity)->cloneMesh();
  6832. if (!clone)
  6833. {
  6834. ccConsole::Error(tr("An error occurred while cloning mesh %1").arg(entity->getName()));
  6835. }
  6836. }
  6837. else if (entity->isA(CC_TYPES::POLY_LINE))
  6838. {
  6839. clone = ccHObjectCaster::ToPolyline(entity)->clone();
  6840. if (!clone)
  6841. {
  6842. ccConsole::Error(tr("An error occurred while cloning polyline %1").arg(entity->getName()));
  6843. }
  6844. }
  6845. else if (entity->isA(CC_TYPES::FACET))
  6846. {
  6847. clone = ccHObjectCaster::ToFacet(entity);
  6848. if (!clone)
  6849. {
  6850. ccConsole::Error(tr("An error occurred while cloning facet %1").arg(entity->getName()));
  6851. }
  6852. }
  6853. else if (entity->isA(CC_TYPES::CAMERA_SENSOR))
  6854. {
  6855. ccCameraSensor* camera = ccHObjectCaster::ToCameraSensor(entity);
  6856. if (camera)
  6857. {
  6858. clone = new ccCameraSensor(*camera);
  6859. if (camera->getParent())
  6860. {
  6861. camera->getParent()->addChild(clone);
  6862. }
  6863. }
  6864. if (!clone)
  6865. {
  6866. ccConsole::Error(tr("An error occurred while cloning camera sensor %1").arg(entity->getName()));
  6867. }
  6868. }
  6869. else if (entity->isA(CC_TYPES::GBL_SENSOR))
  6870. {
  6871. ccGBLSensor* sensor = ccHObjectCaster::ToGBLSensor(entity);
  6872. if (sensor)
  6873. {
  6874. clone = new ccGBLSensor(*sensor);
  6875. if (sensor->getParent())
  6876. {
  6877. sensor->getParent()->addChild(clone);
  6878. }
  6879. }
  6880. if (!clone)
  6881. {
  6882. ccConsole::Error(tr("An error occurred while cloning GBL sensor %1").arg(entity->getName()));
  6883. }
  6884. }
  6885. else if (entity->isA(CC_TYPES::IMAGE))
  6886. {
  6887. ccImage* image = ccHObjectCaster::ToImage(entity);
  6888. if (image)
  6889. {
  6890. clone = new ccImage(*image);
  6891. if (image->getParent())
  6892. {
  6893. image->getParent()->addChild(clone);
  6894. }
  6895. }
  6896. if (!clone)
  6897. {
  6898. ccConsole::Error(tr("An error occurred while cloning image %1").arg(entity->getName()));
  6899. }
  6900. }
  6901. else if (entity->isA(CC_TYPES::LABEL_2D))
  6902. {
  6903. cc2DLabel* label = ccHObjectCaster::To2DLabel(entity);
  6904. if (label)
  6905. {
  6906. clone = new cc2DLabel(*label, true);
  6907. if (label->getParent())
  6908. {
  6909. label->getParent()->addChild(clone);
  6910. }
  6911. }
  6912. if (!clone)
  6913. {
  6914. ccConsole::Error(tr("An error occurred while cloning label %1").arg(entity->getName()));
  6915. }
  6916. }
  6917. else if (entity->isA(CC_TYPES::VIEWPORT_2D_OBJECT))
  6918. {
  6919. cc2DViewportObject* viewport = ccHObjectCaster::To2DViewportObject(entity);
  6920. if (viewport)
  6921. {
  6922. clone = new cc2DViewportObject(*viewport);
  6923. if (viewport->getParent())
  6924. {
  6925. viewport->getParent()->addChild(clone);
  6926. }
  6927. }
  6928. if (!clone)
  6929. {
  6930. ccConsole::Error(tr("An error occurred while cloning viewport %1").arg(entity->getName()));
  6931. }
  6932. }
  6933. else if (entity->isA(CC_TYPES::VIEWPORT_2D_LABEL))
  6934. {
  6935. cc2DViewportLabel* viewportLabel = ccHObjectCaster::To2DViewportLabel(entity);
  6936. if (viewportLabel)
  6937. {
  6938. clone = new cc2DViewportLabel(*viewportLabel);
  6939. if (viewportLabel->getParent())
  6940. {
  6941. viewportLabel->getParent()->addChild(clone);
  6942. }
  6943. }
  6944. if (!clone)
  6945. {
  6946. ccConsole::Error(tr("An error occurred while cloning viewport %1").arg(entity->getName()));
  6947. }
  6948. }
  6949. else
  6950. {
  6951. ccLog::Warning(tr("Entity '%1' can't be cloned (type not supported yet!)").arg(entity->getName()));
  6952. }
  6953. if (clone)
  6954. {
  6955. //copy GL transformation history
  6956. clone->setGLTransformationHistory(entity->getGLTransformationHistory());
  6957. //copy display
  6958. clone->setDisplay(entity->getDisplay());
  6959. addToDB(clone);
  6960. lastClone = clone;
  6961. }
  6962. }
  6963. if (lastClone && m_ccRoot)
  6964. {
  6965. m_ccRoot->selectEntity(lastClone);
  6966. }
  6967. updateUI();
  6968. }
  6969. void MainWindow::doActionAddConstantSF()
  6970. {
  6971. if (!haveOneSelection())
  6972. {
  6973. if (haveSelection())
  6974. ccConsole::Error(tr("Select only one cloud or one mesh!"));
  6975. return;
  6976. }
  6977. ccHObject* ent = m_selectedEntities.front();
  6978. bool lockedVertices;
  6979. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(ent, &lockedVertices);
  6980. //for "real" point clouds only
  6981. if (!cloud)
  6982. {
  6983. return;
  6984. }
  6985. if (lockedVertices && !ent->isAncestorOf(cloud))
  6986. {
  6987. ccUtils::DisplayLockedVerticesWarning(ent->getName(),true);
  6988. return;
  6989. }
  6990. QString defaultName = "Constant";
  6991. unsigned trys = 1;
  6992. while (cloud->getScalarFieldIndexByName(defaultName.toStdString()) >= 0 || trys > 99)
  6993. {
  6994. defaultName = tr("Constant #%1").arg(++trys);
  6995. }
  6996. //ask for a name
  6997. bool ok;
  6998. QString sfName = QInputDialog::getText(this, tr("New SF name"), tr("SF name (must be unique)"), QLineEdit::Normal, defaultName, &ok);
  6999. if (!ok)
  7000. return;
  7001. if (ccEntityAction::sfAddConstant(cloud, sfName, false, this))
  7002. {
  7003. updateUI();
  7004. cloud->redrawDisplay();
  7005. }
  7006. }
  7007. void MainWindow::doActionAddClassificationSF()
  7008. {
  7009. if (!haveOneSelection())
  7010. {
  7011. if (haveSelection())
  7012. ccConsole::Error(tr("Select only one cloud or one mesh!"));
  7013. return;
  7014. }
  7015. ccHObject* ent = m_selectedEntities.front();
  7016. bool lockedVertices;
  7017. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(ent, &lockedVertices);
  7018. //for "real" point clouds only
  7019. if (!cloud)
  7020. {
  7021. return;
  7022. }
  7023. if (lockedVertices && !ent->isAncestorOf(cloud))
  7024. {
  7025. ccUtils::DisplayLockedVerticesWarning(ent->getName(), true);
  7026. return;
  7027. }
  7028. if (ccEntityAction::sfAddConstant(cloud, "Classification", true, this))
  7029. {
  7030. updateUI();
  7031. cloud->redrawDisplay();
  7032. }
  7033. }
  7034. void MainWindow::doActionScalarFieldFromColor()
  7035. {
  7036. if ( !ccEntityAction::sfFromColor(m_selectedEntities, this) )
  7037. return;
  7038. refreshAll();
  7039. updateUI();
  7040. }
  7041. void MainWindow::doActionScalarFieldArithmetic()
  7042. {
  7043. if ( !ccEntityAction::sfArithmetic(m_selectedEntities, this) )
  7044. return;
  7045. refreshAll();
  7046. updateUI();
  7047. }
  7048. void MainWindow::doActionFitSphere()
  7049. {
  7050. double outliersRatio = 0.5;
  7051. double confidence = 0.99;
  7052. ccProgressDialog pDlg(true, this);
  7053. pDlg.setAutoClose(false);
  7054. for ( ccHObject *entity : getSelectedEntities() )
  7055. {
  7056. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(entity);
  7057. if (!cloud)
  7058. continue;
  7059. CCVector3 center;
  7060. PointCoordinateType radius = 0;
  7061. double rms = std::numeric_limits<double>::quiet_NaN();
  7062. if (CCCoreLib::GeometricalAnalysisTools::DetectSphereRobust(cloud,
  7063. outliersRatio,
  7064. center,
  7065. radius,
  7066. rms,
  7067. &pDlg,
  7068. confidence) != CCCoreLib::GeometricalAnalysisTools::NoError)
  7069. {
  7070. ccLog::Warning(tr("[Fit sphere] Failed to fit a sphere on cloud '%1'").arg(cloud->getName()));
  7071. continue;
  7072. }
  7073. ccLog::Print(tr("[Fit sphere] Cloud '%1': center (%2,%3,%4) - radius = %5 [RMS = %6]")
  7074. .arg(cloud->getName())
  7075. .arg(center.x)
  7076. .arg(center.y)
  7077. .arg(center.z)
  7078. .arg(radius)
  7079. .arg(rms));
  7080. ccGLMatrix trans;
  7081. trans.setTranslation(center);
  7082. ccSphere* sphere = new ccSphere(radius, &trans, tr("Sphere r=%1").arg(radius));
  7083. cloud->addChild(sphere);
  7084. //sphere->setDisplay(cloud->getDisplay());
  7085. sphere->prepareDisplayForRefresh();
  7086. sphere->copyGlobalShiftAndScale(*cloud);
  7087. sphere->setMetaData("RMS", rms);
  7088. addToDB(sphere, false, false, false);
  7089. }
  7090. refreshAll();
  7091. }
  7092. void MainWindow::doActionFitCircle()
  7093. {
  7094. ccProgressDialog pDlg(true, this);
  7095. pDlg.setAutoClose(false);
  7096. for (ccHObject* entity : getSelectedEntities())
  7097. {
  7098. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(entity);
  7099. if (!cloud)
  7100. continue;
  7101. CCVector3 center;
  7102. CCVector3 normal;
  7103. PointCoordinateType radius = 0;
  7104. double rms = std::numeric_limits<double>::quiet_NaN();
  7105. if (CCCoreLib::GeometricalAnalysisTools::DetectCircle( cloud,
  7106. center,
  7107. normal,
  7108. radius,
  7109. rms,
  7110. &pDlg) != CCCoreLib::GeometricalAnalysisTools::NoError)
  7111. {
  7112. ccLog::Warning(tr("[Fit circle] Failed to fit a circle on cloud '%1'").arg(cloud->getName()));
  7113. continue;
  7114. }
  7115. ccLog::Print(tr("[Fit circle] Cloud '%1': center (%2,%3,%4) - radius = %5 [RMS = %6]")
  7116. .arg(cloud->getName())
  7117. .arg(center.x)
  7118. .arg(center.y)
  7119. .arg(center.z)
  7120. .arg(radius)
  7121. .arg(rms));
  7122. ccLog::Print(tr("[Fit circle] Normal (%1,%2,%3)")
  7123. .arg(normal.x)
  7124. .arg(normal.y)
  7125. .arg(normal.z));
  7126. // create the circle representation as a polyline
  7127. ccPolyline* circle = ccPolyline::Circle(CCVector3(0, 0, 0), radius, 128);
  7128. if (circle)
  7129. {
  7130. circle->setName(QObject::tr("Circle r=%1").arg(radius));
  7131. cloud->addChild(circle);
  7132. circle->prepareDisplayForRefresh();
  7133. circle->copyGlobalShiftAndScale(*cloud);
  7134. circle->setMetaData("RMS", rms);
  7135. ccGLMatrix trans = ccGLMatrix::FromToRotation(CCVector3(0, 0, 1), normal);
  7136. trans.setTranslation(center);
  7137. circle->applyGLTransformation_recursive(&trans);
  7138. addToDB(circle, false, false, false);
  7139. }
  7140. }
  7141. refreshAll();
  7142. }
  7143. void MainWindow::doActionFitPlane()
  7144. {
  7145. doComputePlaneOrientation(false);
  7146. }
  7147. void MainWindow::doActionFitFacet()
  7148. {
  7149. doComputePlaneOrientation(true);
  7150. }
  7151. void MainWindow::doComputePlaneOrientation(bool fitFacet)
  7152. {
  7153. if (!haveSelection())
  7154. return;
  7155. double maxEdgeLength = 0.0;
  7156. if (fitFacet)
  7157. {
  7158. bool ok = true;
  7159. static double s_polygonMaxEdgeLength = 0.0;
  7160. maxEdgeLength = QInputDialog::getDouble(this, tr("Fit facet"), tr("Max edge length (0 = no limit)"), s_polygonMaxEdgeLength, 0, 1.0e9, 8, &ok);
  7161. if (!ok)
  7162. return;
  7163. s_polygonMaxEdgeLength = maxEdgeLength;
  7164. }
  7165. ccHObject::Container selectedEntities = getSelectedEntities(); //warning, getSelectedEntites may change during this loop!
  7166. bool firstEntity = true;
  7167. for (ccHObject *entity : selectedEntities)
  7168. {
  7169. ccShiftedObject* shifted = nullptr;
  7170. CCCoreLib::GenericIndexedCloudPersist* cloud = nullptr;
  7171. if (entity->isKindOf(CC_TYPES::POLY_LINE))
  7172. {
  7173. ccPolyline* poly = ccHObjectCaster::ToPolyline(entity);
  7174. cloud = static_cast<CCCoreLib::GenericIndexedCloudPersist*>(poly);
  7175. shifted = poly;
  7176. }
  7177. else
  7178. {
  7179. ccGenericPointCloud* gencloud = ccHObjectCaster::ToGenericPointCloud(entity);
  7180. if (gencloud)
  7181. {
  7182. cloud = static_cast<CCCoreLib::GenericIndexedCloudPersist*>(gencloud);
  7183. shifted = gencloud;
  7184. }
  7185. }
  7186. if (cloud)
  7187. {
  7188. double rms = 0.0;
  7189. CCVector3 C;
  7190. CCVector3 N;
  7191. ccHObject* plane = nullptr;
  7192. if (fitFacet)
  7193. {
  7194. ccFacet* facet = ccFacet::Create(cloud, static_cast<PointCoordinateType>(maxEdgeLength));
  7195. if (facet)
  7196. {
  7197. plane = static_cast<ccHObject*>(facet);
  7198. N = facet->getNormal();
  7199. C = facet->getCenter();
  7200. rms = facet->getRMS();
  7201. //manually copy shift & scale info!
  7202. if (shifted)
  7203. {
  7204. ccPolyline* contour = facet->getContour();
  7205. if (contour)
  7206. {
  7207. contour->copyGlobalShiftAndScale(*shifted);
  7208. }
  7209. ccMesh* polygon = facet->getPolygon();
  7210. if (polygon)
  7211. {
  7212. polygon->copyGlobalShiftAndScale(*shifted);
  7213. }
  7214. ccPointCloud* points = facet->getOriginPoints();
  7215. if (points)
  7216. {
  7217. points->copyGlobalShiftAndScale(*shifted);
  7218. }
  7219. }
  7220. }
  7221. }
  7222. else
  7223. {
  7224. ccPlane* pPlane = ccPlane::Fit(cloud, &rms);
  7225. if (pPlane)
  7226. {
  7227. plane = static_cast<ccHObject*>(pPlane);
  7228. N = pPlane->getNormal();
  7229. C = *CCCoreLib::Neighbourhood(cloud).getGravityCenter();
  7230. pPlane->enableStippling(true);
  7231. if (shifted)
  7232. {
  7233. pPlane->copyGlobalShiftAndScale(*shifted);
  7234. }
  7235. }
  7236. }
  7237. //as all information appears in Console...
  7238. forceConsoleDisplay();
  7239. if (plane)
  7240. {
  7241. ccConsole::Print(tr("[Orientation] Entity '%1'").arg(entity->getName()));
  7242. ccConsole::Print(tr("\t- plane fitting RMS: %1").arg(rms));
  7243. //We always consider the normal with a positive 'Z' by default!
  7244. if (N.z < 0.0)
  7245. N *= -1.0;
  7246. ccConsole::Print(tr("\t- normal: (%1, %2, %3)").arg(N.x).arg(N.y).arg(N.z));
  7247. //we compute strike & dip by the way
  7248. PointCoordinateType dip = 0.0f;
  7249. PointCoordinateType dipDir = 0.0f;
  7250. ccNormalVectors::ConvertNormalToDipAndDipDir(N, dip, dipDir);
  7251. QString dipAndDipDirStr = ccNormalVectors::ConvertDipAndDipDirToString(dip, dipDir);
  7252. ccConsole::Print(QString("\t- %1").arg(dipAndDipDirStr));
  7253. //hack: output the transformation matrix that would make this normal points towards +Z
  7254. ccGLMatrix makeZPosMatrix = ccGLMatrix::FromToRotation(N, CCVector3(0, 0, CCCoreLib::PC_ONE));
  7255. CCVector3 Gt = C;
  7256. makeZPosMatrix.applyRotation(Gt);
  7257. makeZPosMatrix.setTranslation(C-Gt);
  7258. ccConsole::Print(tr("[Orientation] A matrix that would make this plane horizontal (normal towards Z+) is:"));
  7259. ccConsole::Print(makeZPosMatrix.toString(12,' ')); //full precision
  7260. ccConsole::Print(tr("[Orientation] You can copy this matrix values (CTRL+C) and paste them in the 'Apply transformation tool' dialog"));
  7261. plane->setName(dipAndDipDirStr);
  7262. plane->applyGLTransformation_recursive(); //not yet in DB
  7263. plane->setVisible(true);
  7264. plane->setSelectionBehavior(ccHObject::SELECTION_FIT_BBOX);
  7265. entity->addChild(plane);
  7266. plane->setDisplay(entity->getDisplay());
  7267. plane->prepareDisplayForRefresh_recursive();
  7268. addToDB(plane);
  7269. if (firstEntity)
  7270. {
  7271. m_ccRoot->unselectAllEntities();
  7272. m_ccRoot->selectEntity(plane);
  7273. }
  7274. }
  7275. else
  7276. {
  7277. ccConsole::Warning(tr("Failed to fit a plane/facet on entity '%1'").arg(entity->getName()));
  7278. }
  7279. }
  7280. }
  7281. refreshAll();
  7282. updateUI();
  7283. }
  7284. void MainWindow::doShowPrimitiveFactory()
  7285. {
  7286. if (!m_pfDlg)
  7287. m_pfDlg = new ccPrimitiveFactoryDlg(this);
  7288. m_pfDlg->setModal(false);
  7289. m_pfDlg->setWindowModality(Qt::NonModal);
  7290. m_pfDlg->show();
  7291. }
  7292. void MainWindow::doComputeGeometricFeature()
  7293. {
  7294. static ccLibAlgorithms::GeomCharacteristicSet s_selectedCharacteristics;
  7295. static CCVector3 s_upDir(0, 0, 1);
  7296. static bool s_upDirDefined = false;
  7297. ccGeomFeaturesDlg gfDlg(this);
  7298. double radius = ccLibAlgorithms::GetDefaultCloudKernelSize(m_selectedEntities);
  7299. gfDlg.setRadius(radius);
  7300. // restore semi-persistent parameters
  7301. gfDlg.setSelectedFeatures(s_selectedCharacteristics);
  7302. if (s_upDirDefined)
  7303. {
  7304. gfDlg.setUpDirection(s_upDir);
  7305. }
  7306. if (!gfDlg.exec())
  7307. return;
  7308. radius = gfDlg.getRadius();
  7309. if (!gfDlg.getSelectedFeatures(s_selectedCharacteristics))
  7310. {
  7311. ccLog::Error(tr("Not enough memory!"));
  7312. return;
  7313. }
  7314. CCVector3* upDir = gfDlg.getUpDirection();
  7315. // remember semi-persistent parameters
  7316. s_upDirDefined = (upDir != nullptr);
  7317. if (s_upDirDefined)
  7318. {
  7319. s_upDir = *upDir;
  7320. }
  7321. ccLibAlgorithms::ComputeGeomCharacteristics(s_selectedCharacteristics, static_cast<PointCoordinateType>(radius), m_selectedEntities, upDir, this);
  7322. refreshAll();
  7323. updateUI();
  7324. }
  7325. void MainWindow::doActionSFGradient()
  7326. {
  7327. if (!ccLibAlgorithms::ApplyCCLibAlgorithm(ccLibAlgorithms::CCLIB_ALGO_SF_GRADIENT, m_selectedEntities, this))
  7328. return;
  7329. refreshAll();
  7330. updateUI();
  7331. }
  7332. void MainWindow::doSphericalNeighbourhoodExtractionTest()
  7333. {
  7334. size_t selNum = m_selectedEntities.size();
  7335. if (selNum < 1)
  7336. return;
  7337. //spherical neighborhood extraction radius
  7338. double sphereRadius = ccLibAlgorithms::GetDefaultCloudKernelSize(m_selectedEntities);
  7339. if (sphereRadius < 0)
  7340. {
  7341. ccConsole::Error(tr("Invalid kernel size!"));
  7342. return;
  7343. }
  7344. bool ok;
  7345. double val = QInputDialog::getDouble(this, tr("SNE test"), tr("Radius:"), sphereRadius, DBL_MIN, 1.0e9, 8, &ok);
  7346. if (!ok)
  7347. return;
  7348. sphereRadius = val;
  7349. QString sfName = tr("Spherical extraction test (%1)").arg(sphereRadius);
  7350. ccProgressDialog pDlg(true, this);
  7351. pDlg.setAutoClose(false);
  7352. for (size_t i = 0; i < selNum; ++i)
  7353. {
  7354. //we only process clouds
  7355. if (!m_selectedEntities[i]->isA(CC_TYPES::POINT_CLOUD))
  7356. {
  7357. continue;
  7358. }
  7359. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(m_selectedEntities[i]);
  7360. int sfIdx = cloud->getScalarFieldIndexByName(sfName.toStdString());
  7361. if (sfIdx < 0)
  7362. sfIdx = cloud->addScalarField(sfName.toStdString());
  7363. if (sfIdx < 0)
  7364. {
  7365. ccConsole::Error(tr("Failed to create scalar field on cloud '%1' (not enough memory?)").arg(cloud->getName()));
  7366. return;
  7367. }
  7368. ccOctree::Shared octree = cloud->getOctree();
  7369. if (!octree)
  7370. {
  7371. pDlg.reset();
  7372. pDlg.show();
  7373. octree = cloud->computeOctree(&pDlg);
  7374. if (!octree)
  7375. {
  7376. ccConsole::Error(tr("Couldn't compute octree for cloud '%1'!").arg(cloud->getName()));
  7377. return;
  7378. }
  7379. }
  7380. CCCoreLib::ScalarField* sf = cloud->getScalarField(sfIdx);
  7381. sf->fill(CCCoreLib::NAN_VALUE);
  7382. cloud->setCurrentScalarField(sfIdx);
  7383. QElapsedTimer eTimer;
  7384. eTimer.start();
  7385. size_t extractedPoints = 0;
  7386. unsigned char level = octree->findBestLevelForAGivenNeighbourhoodSizeExtraction(static_cast<PointCoordinateType>(sphereRadius));
  7387. std::random_device rd; // non-deterministic generator
  7388. std::mt19937 gen(rd()); // to seed mersenne twister.
  7389. std::uniform_int_distribution<unsigned> dist(0, cloud->size() - 1);
  7390. const unsigned samples = 1000;
  7391. for (unsigned j = 0; j < samples; ++j)
  7392. {
  7393. unsigned randIndex = dist(gen);
  7394. CCCoreLib::DgmOctree::NeighboursSet neighbours;
  7395. octree->getPointsInSphericalNeighbourhood( *cloud->getPoint(randIndex),
  7396. static_cast<PointCoordinateType>(sphereRadius),
  7397. neighbours,
  7398. level );
  7399. size_t neihgboursCount = neighbours.size();
  7400. extractedPoints += neihgboursCount;
  7401. for (size_t k = 0; k < neihgboursCount; ++k)
  7402. {
  7403. cloud->setPointScalarValue(neighbours[k].pointIndex, static_cast<ScalarType>(sqrt(neighbours[k].squareDistd)));
  7404. }
  7405. }
  7406. ccConsole::Print(tr("[SNE_TEST] Mean extraction time = %1 ms (radius = %2, mean (neighbours) = %3)").arg(eTimer.elapsed()).arg(sphereRadius).arg(extractedPoints / static_cast<double>(samples), 0, 'f', 1));
  7407. sf->computeMinAndMax();
  7408. cloud->setCurrentDisplayedScalarField(sfIdx);
  7409. cloud->showSF(true);
  7410. cloud->prepareDisplayForRefresh();
  7411. }
  7412. refreshAll();
  7413. updateUI();
  7414. }
  7415. void MainWindow::doCylindricalNeighbourhoodExtractionTest()
  7416. {
  7417. bool ok;
  7418. double radius = QInputDialog::getDouble(this, tr("CNE Test"), tr("radius"), 0.02, 1.0e-6, 1.0e6, 6, &ok);
  7419. if (!ok)
  7420. return;
  7421. double height = QInputDialog::getDouble(this, tr("CNE Test"), tr("height"), 0.05, 1.0e-6, 1.0e6, 6, &ok);
  7422. if (!ok)
  7423. return;
  7424. ccPointCloud* cloud = new ccPointCloud(tr("cube"));
  7425. const unsigned ptsCount = 1000000;
  7426. if (!cloud->reserve(ptsCount))
  7427. {
  7428. ccConsole::Error(tr("Not enough memory!"));
  7429. delete cloud;
  7430. return;
  7431. }
  7432. //fill a unit cube with random points
  7433. {
  7434. std::random_device rd; // non-deterministic generator
  7435. std::mt19937 gen(rd()); // to seed mersenne twister.
  7436. std::uniform_real_distribution<double> dist(0, 1);
  7437. for (unsigned i = 0; i < ptsCount; ++i)
  7438. {
  7439. CCVector3 P(dist(gen),
  7440. dist(gen),
  7441. dist(gen));
  7442. cloud->addPoint(P);
  7443. }
  7444. }
  7445. //get/Add scalar field
  7446. static const char DEFAULT_CNE_TEST_TEMP_SF_NAME[] = "CNE test";
  7447. int sfIdx = cloud->getScalarFieldIndexByName(DEFAULT_CNE_TEST_TEMP_SF_NAME);
  7448. if (sfIdx < 0)
  7449. sfIdx = cloud->addScalarField(DEFAULT_CNE_TEST_TEMP_SF_NAME);
  7450. if (sfIdx < 0)
  7451. {
  7452. ccConsole::Error(tr("Not enough memory!"));
  7453. delete cloud;
  7454. return;
  7455. }
  7456. cloud->setCurrentScalarField(sfIdx);
  7457. //reset scalar field
  7458. cloud->getScalarField(sfIdx)->fill(CCCoreLib::NAN_VALUE);
  7459. ccProgressDialog pDlg(true, this);
  7460. ccOctree::Shared octree = cloud->computeOctree(&pDlg);
  7461. if (octree)
  7462. {
  7463. QElapsedTimer subTimer;
  7464. subTimer.start();
  7465. unsigned long long extractedPoints = 0;
  7466. unsigned char level = octree->findBestLevelForAGivenNeighbourhoodSizeExtraction(static_cast<PointCoordinateType>(2.5*radius)); //2.5 = empirical
  7467. const unsigned samples = 1000;
  7468. std::random_device rd; // non-deterministic generator
  7469. std::mt19937 gen(rd()); // to seed mersenne twister.
  7470. std::uniform_real_distribution<PointCoordinateType> distAngle(0, static_cast<PointCoordinateType>(2 * M_PI));
  7471. std::uniform_int_distribution<unsigned> distIndex(0, ptsCount - 1);
  7472. for (unsigned j = 0; j < samples; ++j)
  7473. {
  7474. //generate random normal vector
  7475. CCVector3 dir(0, 0, 1);
  7476. {
  7477. ccGLMatrix rot;
  7478. rot.initFromParameters(distAngle(gen),
  7479. distAngle(gen),
  7480. distAngle(gen),
  7481. CCVector3(0, 0, 0));
  7482. rot.applyRotation(dir);
  7483. }
  7484. unsigned randIndex = distIndex(gen);
  7485. CCCoreLib::DgmOctree::CylindricalNeighbourhood cn;
  7486. cn.center = *cloud->getPoint(randIndex);
  7487. cn.dir = dir;
  7488. cn.level = level;
  7489. cn.radius = static_cast<PointCoordinateType>(radius);
  7490. cn.maxHalfLength = static_cast<PointCoordinateType>(height / 2);
  7491. octree->getPointsInCylindricalNeighbourhood(cn);
  7492. //octree->getPointsInSphericalNeighbourhood(*cloud->getPoint(randIndex),radius,neighbours,level);
  7493. size_t neihgboursCount = cn.neighbours.size();
  7494. extractedPoints += static_cast<unsigned long long>(neihgboursCount);
  7495. for (size_t k = 0; k < neihgboursCount; ++k)
  7496. {
  7497. cloud->setPointScalarValue(cn.neighbours[k].pointIndex, static_cast<ScalarType>(sqrt(cn.neighbours[k].squareDistd)));
  7498. }
  7499. }
  7500. ccConsole::Print(tr("[CNE_TEST] Mean extraction time = %1 ms (radius = %2, height = %3, mean (neighbours) = %4))").arg(subTimer.elapsed()).arg(radius).arg(height).arg(static_cast<double>(extractedPoints) / samples, 0, 'f', 1));
  7501. }
  7502. else
  7503. {
  7504. ccConsole::Error(tr("Failed to compute octree!"));
  7505. }
  7506. ccScalarField* sf = static_cast<ccScalarField*>(cloud->getScalarField(sfIdx));
  7507. sf->computeMinAndMax();
  7508. sf->showNaNValuesInGrey(false);
  7509. cloud->setCurrentDisplayedScalarField(sfIdx);
  7510. cloud->showSF(true);
  7511. addToDB(cloud);
  7512. refreshAll();
  7513. updateUI();
  7514. }
  7515. void MainWindow::doActionCreateCloudFromEntCenters()
  7516. {
  7517. size_t selNum = getSelectedEntities().size();
  7518. ccPointCloud* centers = new ccPointCloud(tr("centers"));
  7519. if (!centers->reserve(static_cast<unsigned>(selNum)))
  7520. {
  7521. ccLog::Error(tr("Not enough memory!"));
  7522. delete centers;
  7523. centers = nullptr;
  7524. return;
  7525. }
  7526. //look for clouds
  7527. {
  7528. for ( ccHObject *entity : getSelectedEntities() )
  7529. {
  7530. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(entity);
  7531. if (cloud == nullptr)
  7532. {
  7533. continue;
  7534. }
  7535. centers->addPoint(cloud->getOwnBB().getCenter());
  7536. //we display the cloud in the same window as the first (selected) cloud we encounter
  7537. if (!centers->getDisplay())
  7538. {
  7539. centers->setDisplay(cloud->getDisplay());
  7540. }
  7541. }
  7542. }
  7543. if (centers->size() == 0)
  7544. {
  7545. ccLog::Error(tr("No cloud in selection?!"));
  7546. delete centers;
  7547. centers = nullptr;
  7548. }
  7549. else
  7550. {
  7551. centers->resize(centers->size());
  7552. centers->setPointSize(10);
  7553. centers->setVisible(true);
  7554. addToDB(centers);
  7555. }
  7556. }
  7557. void MainWindow::doActionComputeBestICPRmsMatrix()
  7558. {
  7559. //look for clouds
  7560. std::vector<ccPointCloud*> clouds;
  7561. try
  7562. {
  7563. for ( ccHObject *entity : getSelectedEntities() )
  7564. {
  7565. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(entity);
  7566. if (cloud)
  7567. {
  7568. clouds.push_back(cloud);
  7569. }
  7570. }
  7571. }
  7572. catch (const std::bad_alloc&)
  7573. {
  7574. ccLog::Error(tr("Not enough memory!"));
  7575. return;
  7576. }
  7577. size_t cloudCount = clouds.size();
  7578. if (cloudCount < 2)
  7579. {
  7580. ccLog::Error(tr("Need at least two clouds!"));
  7581. return;
  7582. }
  7583. //init matrices
  7584. std::vector<double> rmsMatrix;
  7585. std::vector<ccGLMatrix> matrices;
  7586. std::vector< std::pair<double, double> > matrixAngles;
  7587. try
  7588. {
  7589. rmsMatrix.resize(cloudCount*cloudCount, 0);
  7590. //init all possible transformations
  7591. static const double angularStep_deg = 45.0;
  7592. unsigned phiSteps = static_cast<unsigned>(360.0 / angularStep_deg);
  7593. assert(CCCoreLib::LessThanEpsilon(std::abs(360.0 - phiSteps * angularStep_deg)));
  7594. unsigned thetaSteps = static_cast<unsigned>(180.0 / angularStep_deg);
  7595. assert(CCCoreLib::LessThanEpsilon(std::abs(180.0 - thetaSteps * angularStep_deg)));
  7596. unsigned rotCount = phiSteps * (thetaSteps - 1) + 2;
  7597. matrices.reserve(rotCount);
  7598. matrixAngles.reserve(rotCount);
  7599. for (unsigned j = 0; j <= thetaSteps; ++j)
  7600. {
  7601. //we want to cover the full [0-180] interval! ([-90;90] in fact)
  7602. double theta_deg = j * angularStep_deg - 90.0;
  7603. for (unsigned i = 0; i < phiSteps; ++i)
  7604. {
  7605. double phi_deg = i * angularStep_deg;
  7606. ccGLMatrix trans;
  7607. trans.initFromParameters( static_cast<float>( CCCoreLib::DegreesToRadians( phi_deg ) ),
  7608. static_cast<float>( CCCoreLib::DegreesToRadians( theta_deg ) ),
  7609. 0,
  7610. CCVector3(0,0,0) );
  7611. matrices.push_back(trans);
  7612. matrixAngles.push_back( std::pair<double,double>(phi_deg,theta_deg) );
  7613. //for poles, no need to rotate!
  7614. if (j == 0 || j == thetaSteps)
  7615. break;
  7616. }
  7617. }
  7618. }
  7619. catch (const std::bad_alloc&)
  7620. {
  7621. ccLog::Error(tr("Not enough memory!"));
  7622. return;
  7623. }
  7624. //let's start!
  7625. {
  7626. ccProgressDialog pDlg(true, this);
  7627. pDlg.setMethodTitle(tr("Testing all possible positions"));
  7628. pDlg.setInfo(tr("%1 clouds and %2 positions").arg(cloudCount).arg(matrices.size()));
  7629. CCCoreLib::NormalizedProgress nProgress(&pDlg, static_cast<unsigned>(((cloudCount*(cloudCount - 1)) / 2)*matrices.size()));
  7630. pDlg.start();
  7631. QApplication::processEvents();
  7632. //#define TEST_GENERATION
  7633. #ifdef TEST_GENERATION
  7634. ccPointCloud* testSphere = new ccPointCloud();
  7635. testSphere->reserve(matrices.size());
  7636. #endif
  7637. for (size_t i = 0; i < cloudCount - 1; ++i)
  7638. {
  7639. ccPointCloud* A = clouds[i];
  7640. A->computeOctree();
  7641. for (size_t j = i + 1; j < cloudCount; ++j)
  7642. {
  7643. ccGLMatrix transBToZero;
  7644. transBToZero.toIdentity();
  7645. transBToZero.setTranslation(-clouds[j]->getOwnBB().getCenter());
  7646. ccGLMatrix transFromZeroToA;
  7647. transFromZeroToA.toIdentity();
  7648. transFromZeroToA.setTranslation(A->getOwnBB().getCenter());
  7649. #ifndef TEST_GENERATION
  7650. double minRMS = -1.0;
  7651. int bestMatrixIndex = -1;
  7652. ccPointCloud* bestB = nullptr;
  7653. #endif
  7654. for (size_t k = 0; k < matrices.size(); ++k)
  7655. {
  7656. ccPointCloud* B = clouds[j]->cloneThis();
  7657. if (!B)
  7658. {
  7659. ccLog::Error(tr("Not enough memory!"));
  7660. return;
  7661. }
  7662. ccGLMatrix BtoA = transFromZeroToA * matrices[k] * transBToZero;
  7663. B->applyRigidTransformation(BtoA);
  7664. #ifndef TEST_GENERATION
  7665. double finalRMS = 0.0;
  7666. unsigned finalPointCount = 0;
  7667. CCCoreLib::ICPRegistrationTools::RESULT_TYPE result;
  7668. CCCoreLib::ICPRegistrationTools::ScaledTransformation registerTrans;
  7669. CCCoreLib::ICPRegistrationTools::Parameters params;
  7670. {
  7671. params.convType = CCCoreLib::ICPRegistrationTools::MAX_ERROR_CONVERGENCE;
  7672. params.minRMSDecrease = 1.0e-6;
  7673. }
  7674. result = CCCoreLib::ICPRegistrationTools::Register(A, nullptr, B, params, registerTrans, finalRMS, finalPointCount);
  7675. if (result >= CCCoreLib::ICPRegistrationTools::ICP_ERROR)
  7676. {
  7677. delete B;
  7678. if (bestB)
  7679. delete bestB;
  7680. ccLog::Error(tr("An error occurred while performing ICP!"));
  7681. return;
  7682. }
  7683. if (minRMS < 0 || finalRMS < minRMS)
  7684. {
  7685. minRMS = finalRMS;
  7686. bestMatrixIndex = static_cast<int>(k);
  7687. std::swap(bestB, B);
  7688. }
  7689. if (B)
  7690. {
  7691. delete B;
  7692. B = nullptr;
  7693. }
  7694. #else
  7695. addToDB(B);
  7696. //Test sphere
  7697. CCVector3 Y(0,1,0);
  7698. matrices[k].apply(Y);
  7699. testSphere->addPoint(Y);
  7700. #endif
  7701. if (!nProgress.oneStep())
  7702. {
  7703. //process cancelled by user
  7704. return;
  7705. }
  7706. }
  7707. #ifndef TEST_GENERATION
  7708. if (bestMatrixIndex >= 0)
  7709. {
  7710. assert(bestB);
  7711. ccHObject* group = new ccHObject(tr("Best case #%1 / #%2 - RMS = %3").arg(i+1).arg(j+1).arg(minRMS));
  7712. group->addChild(bestB);
  7713. group->setDisplay_recursive(A->getDisplay());
  7714. addToDB(group);
  7715. ccLog::Print(tr("[DoActionComputeBestICPRmsMatrix] Comparison #%1 / #%2: min RMS = %3 (phi = %4 / theta = %5 deg.)").arg(i+1).arg(j+1).arg(minRMS).arg(matrixAngles[bestMatrixIndex].first).arg(matrixAngles[bestMatrixIndex].second));
  7716. }
  7717. else
  7718. {
  7719. assert(!bestB);
  7720. ccLog::Warning(tr("[DoActionComputeBestICPRmsMatrix] Comparison #%1 / #%2: INVALID").arg(i+1).arg(j+1));
  7721. }
  7722. rmsMatrix[i*cloudCount + j] = minRMS;
  7723. #else
  7724. addToDB(testSphere);
  7725. i = cloudCount;
  7726. break;
  7727. #endif
  7728. }
  7729. }
  7730. }
  7731. //export result as a CSV file
  7732. #ifdef TEST_GENERATION
  7733. if (false)
  7734. #endif
  7735. {
  7736. //persistent settings
  7737. QSettings settings;
  7738. settings.beginGroup(ccPS::SaveFile());
  7739. QString currentPath = settings.value(ccPS::CurrentPath(), ccFileUtils::defaultDocPath()).toString();
  7740. QString outputFilename = QFileDialog::getSaveFileName( this,
  7741. tr("Select output file"),
  7742. currentPath,
  7743. "*.csv",
  7744. nullptr,
  7745. CCFileDialogOptions());
  7746. if (outputFilename.isEmpty())
  7747. return;
  7748. QFile fp(outputFilename);
  7749. if (fp.open(QFile::Text | QFile::WriteOnly))
  7750. {
  7751. QTextStream stream(&fp);
  7752. //header
  7753. {
  7754. stream << "RMS";
  7755. for ( ccPointCloud *cloud : clouds )
  7756. {
  7757. stream << ';';
  7758. stream << cloud->getName();
  7759. }
  7760. stream << endl;
  7761. }
  7762. //rows
  7763. for (size_t j = 0; j < cloudCount; ++j)
  7764. {
  7765. stream << clouds[j]->getName();
  7766. stream << ';';
  7767. for (size_t i = 0; i < cloudCount; ++i)
  7768. {
  7769. stream << rmsMatrix[j*cloudCount+i];
  7770. stream << ';';
  7771. }
  7772. stream << endl;
  7773. }
  7774. ccLog::Print(tr("[DoActionComputeBestICPRmsMatrix] Job done"));
  7775. }
  7776. else
  7777. {
  7778. ccLog::Error(tr("Failed to save output file?!"));
  7779. }
  7780. }
  7781. }
  7782. void MainWindow::doActionExportPlaneInfo()
  7783. {
  7784. ccHObject::Container planes;
  7785. const ccHObject::Container& selectedEntities = getSelectedEntities();
  7786. if (selectedEntities.size() == 1 && selectedEntities.front()->isA(CC_TYPES::HIERARCHY_OBJECT))
  7787. {
  7788. //a group
  7789. selectedEntities.front()->filterChildren(planes, true, CC_TYPES::PLANE, false);
  7790. }
  7791. else
  7792. {
  7793. for (ccHObject* ent : selectedEntities)
  7794. {
  7795. if (ent->isKindOf(CC_TYPES::PLANE))
  7796. {
  7797. //a single plane
  7798. planes.push_back(static_cast<ccPlane*>(ent));
  7799. }
  7800. }
  7801. }
  7802. if (planes.size() == 0)
  7803. {
  7804. ccLog::Error(tr("No plane in selection"));
  7805. return;
  7806. }
  7807. //persistent settings
  7808. QSettings settings;
  7809. settings.beginGroup(ccPS::SaveFile());
  7810. QString currentPath = settings.value(ccPS::CurrentPath(), ccFileUtils::defaultDocPath()).toString();
  7811. QString outputFilename = QFileDialog::getSaveFileName( this,
  7812. tr("Select output file"),
  7813. currentPath,
  7814. "*.csv",
  7815. nullptr,
  7816. CCFileDialogOptions());
  7817. if (outputFilename.isEmpty())
  7818. {
  7819. //process cancelled by the user
  7820. return;
  7821. }
  7822. QFile csvFile(outputFilename);
  7823. if (!csvFile.open(QFile::WriteOnly | QFile::Text))
  7824. {
  7825. ccConsole::Error(tr("Failed to open file for writing! (check file permissions)"));
  7826. return;
  7827. }
  7828. //save last saving location
  7829. settings.setValue(ccPS::CurrentPath(), QFileInfo(outputFilename).absolutePath());
  7830. settings.endGroup();
  7831. //write CSV header
  7832. QTextStream csvStream(&csvFile);
  7833. csvStream << "Name;";
  7834. csvStream << "Width;";
  7835. csvStream << "Height;";
  7836. csvStream << "Cx;";
  7837. csvStream << "Cy;";
  7838. csvStream << "Cz;";
  7839. csvStream << "Nx;";
  7840. csvStream << "Ny;";
  7841. csvStream << "Nz;";
  7842. csvStream << "Dip;";
  7843. csvStream << "Dip dir;";
  7844. csvStream << endl;
  7845. QChar separator(';');
  7846. //write one line per plane
  7847. for (ccHObject* ent : planes)
  7848. {
  7849. ccPlane* plane = static_cast<ccPlane*>(ent);
  7850. CCVector3 C = plane->getOwnBB().getCenter();
  7851. CCVector3 N = plane->getNormal();
  7852. PointCoordinateType dip_deg = 0;
  7853. PointCoordinateType dipDir_deg = 0;
  7854. ccNormalVectors::ConvertNormalToDipAndDipDir(N, dip_deg, dipDir_deg);
  7855. csvStream << plane->getName() << separator; //Name
  7856. csvStream << plane->getXWidth() << separator; //Width
  7857. csvStream << plane->getYWidth() << separator; //Height
  7858. csvStream << C.x << separator; //Cx
  7859. csvStream << C.y << separator; //Cy
  7860. csvStream << C.z << separator; //Cz
  7861. csvStream << N.x << separator; //Nx
  7862. csvStream << N.y << separator; //Ny
  7863. csvStream << N.z << separator; //Nz
  7864. csvStream << dip_deg << separator; //Dip
  7865. csvStream << dipDir_deg << separator; //Dip direction
  7866. csvStream << endl;
  7867. }
  7868. ccConsole::Print(tr("[I/O] File '%1' successfully saved (%2 plane(s))").arg(outputFilename).arg(planes.size()));
  7869. csvFile.close();
  7870. }
  7871. void MainWindow::doActionExportCloudInfo()
  7872. {
  7873. //look for clouds
  7874. ccHObject::Container clouds;
  7875. const ccHObject::Container& selectedEntities = getSelectedEntities();
  7876. if (selectedEntities.size() == 1 && selectedEntities.front()->isA(CC_TYPES::HIERARCHY_OBJECT))
  7877. {
  7878. //a group
  7879. selectedEntities.front()->filterChildren(clouds, true, CC_TYPES::POINT_CLOUD, true);
  7880. }
  7881. else
  7882. {
  7883. for (ccHObject* entity : selectedEntities)
  7884. {
  7885. ccPointCloud* cloud = ccHObjectCaster::ToPointCloud(entity);
  7886. if (cloud)
  7887. {
  7888. clouds.push_back(cloud);
  7889. }
  7890. }
  7891. }
  7892. if (clouds.empty())
  7893. {
  7894. ccConsole::Error(tr("Select at least one point cloud!"));
  7895. return;
  7896. }
  7897. //persistent settings
  7898. QSettings settings;
  7899. settings.beginGroup(ccPS::SaveFile());
  7900. QString currentPath = settings.value(ccPS::CurrentPath(), ccFileUtils::defaultDocPath()).toString();
  7901. QString outputFilename = QFileDialog::getSaveFileName( this,
  7902. tr("Select output file"),
  7903. currentPath,
  7904. "*.csv",
  7905. nullptr,
  7906. CCFileDialogOptions());
  7907. if (outputFilename.isEmpty())
  7908. {
  7909. //process cancelled by the user
  7910. return;
  7911. }
  7912. QFile csvFile(outputFilename);
  7913. if (!csvFile.open(QFile::WriteOnly | QFile::Text))
  7914. {
  7915. ccConsole::Error(tr("Failed to open file for writing! (check file permissions)"));
  7916. return;
  7917. }
  7918. //save last saving location
  7919. settings.setValue(ccPS::CurrentPath(), QFileInfo(outputFilename).absolutePath());
  7920. settings.endGroup();
  7921. //determine the maximum number of SFs
  7922. unsigned maxSFCount = 0;
  7923. for (ccHObject* entity : clouds)
  7924. {
  7925. maxSFCount = std::max<unsigned>(maxSFCount, static_cast<ccPointCloud*>(entity)->getNumberOfScalarFields());
  7926. }
  7927. //write CSV header
  7928. QTextStream csvStream(&csvFile);
  7929. csvStream << "Name;";
  7930. csvStream << "Points;";
  7931. csvStream << "meanX;";
  7932. csvStream << "meanY;";
  7933. csvStream << "meanZ;";
  7934. {
  7935. for (unsigned i = 0; i < maxSFCount; ++i)
  7936. {
  7937. QString sfIndex = QString("SF#%1").arg(i + 1);
  7938. csvStream << sfIndex << " name;";
  7939. csvStream << sfIndex << " valid values;";
  7940. csvStream << sfIndex << " mean;";
  7941. csvStream << sfIndex << " std.dev.;";
  7942. csvStream << sfIndex << " sum;";
  7943. }
  7944. }
  7945. csvStream << endl;
  7946. //write one line per cloud
  7947. {
  7948. for (ccHObject* entity : clouds)
  7949. {
  7950. ccPointCloud* cloud = static_cast<ccPointCloud*>(entity);
  7951. CCVector3 G = *CCCoreLib::Neighbourhood(cloud).getGravityCenter();
  7952. csvStream << cloud->getName() << ';' /*"Name;"*/;
  7953. csvStream << cloud->size() << ';' /*"Points;"*/;
  7954. csvStream << G.x << ';' /*"meanX;"*/;
  7955. csvStream << G.y << ';' /*"meanY;"*/;
  7956. csvStream << G.z << ';' /*"meanZ;"*/;
  7957. for (unsigned j = 0; j < cloud->getNumberOfScalarFields(); ++j)
  7958. {
  7959. CCCoreLib::ScalarField* sf = cloud->getScalarField(j);
  7960. csvStream << QString::fromStdString(sf->getName()) << ';' /*"SF name;"*/;
  7961. unsigned validCount = 0;
  7962. double sfSum = 0.0;
  7963. double sfSum2 = 0.0;
  7964. for (unsigned k = 0; k < sf->currentSize(); ++k)
  7965. {
  7966. const ScalarType& val = sf->getValue(k);
  7967. if (CCCoreLib::ScalarField::ValidValue(val))
  7968. {
  7969. ++validCount;
  7970. sfSum += val;
  7971. sfSum2 += static_cast<double>(val)*val;
  7972. }
  7973. }
  7974. csvStream << validCount << ';' /*"SF valid values;"*/;
  7975. if (validCount)
  7976. {
  7977. double mean = sfSum / validCount;
  7978. csvStream << mean << ';' /*"SF mean;"*/;
  7979. csvStream << sqrt(std::abs(sfSum2 / validCount - mean * mean)) << ';' /*"SF std.dev.;"*/;
  7980. }
  7981. else
  7982. {
  7983. csvStream << "N/A;" /*"SF mean;"*/;
  7984. csvStream << "N/A;" /*"SF std.dev.;"*/;
  7985. }
  7986. csvStream << sfSum << ';' /*"SF sum;"*/;
  7987. }
  7988. csvStream << endl;
  7989. }
  7990. }
  7991. ccConsole::Print(tr("[I/O] File '%1' successfully saved (%2 cloud(s))").arg(outputFilename).arg(clouds.size()));
  7992. csvFile.close();
  7993. }
  7994. void MainWindow::doActionCloudCloudDist()
  7995. {
  7996. if (getSelectedEntities().size() != 2)
  7997. {
  7998. ccConsole::Error(tr("Select 2 point clouds!"));
  7999. return;
  8000. }
  8001. if (!m_selectedEntities.front()->isKindOf(CC_TYPES::POINT_CLOUD) ||
  8002. !m_selectedEntities.back()->isKindOf(CC_TYPES::POINT_CLOUD))
  8003. {
  8004. ccConsole::Error(tr("Select 2 point clouds!"));
  8005. return;
  8006. }
  8007. ccOrderChoiceDlg dlg( m_selectedEntities.front(), tr("Compared"),
  8008. m_selectedEntities.back(), tr("Reference"),
  8009. this );
  8010. if (!dlg.exec())
  8011. return;
  8012. ccGenericPointCloud* compCloud = ccHObjectCaster::ToGenericPointCloud(dlg.getFirstEntity());
  8013. ccGenericPointCloud* refCloud = ccHObjectCaster::ToGenericPointCloud(dlg.getSecondEntity());
  8014. //assert(!m_compDlg);
  8015. if (m_compDlg)
  8016. delete m_compDlg;
  8017. m_compDlg = new ccComparisonDlg(compCloud, refCloud, ccComparisonDlg::CLOUDCLOUD_DIST, this);
  8018. if (!m_compDlg->initDialog())
  8019. {
  8020. ccConsole::Error(tr("Failed to initialize comparison dialog"));
  8021. delete m_compDlg;
  8022. m_compDlg = nullptr;
  8023. return;
  8024. }
  8025. connect(m_compDlg, &QDialog::finished, this, &MainWindow::deactivateComparisonMode);
  8026. m_compDlg->show();
  8027. //cDlg.setModal(false);
  8028. //cDlg.exec();
  8029. freezeUI(true);
  8030. }
  8031. void MainWindow::doActionCloudMeshDist()
  8032. {
  8033. if (getSelectedEntities().size() != 2)
  8034. {
  8035. ccConsole::Error(tr("Select 2 entities!"));
  8036. return;
  8037. }
  8038. bool isMesh[2]{ false,false };
  8039. unsigned meshNum = 0;
  8040. unsigned cloudNum = 0;
  8041. for (unsigned i = 0; i < 2; ++i)
  8042. {
  8043. if (m_selectedEntities[i]->isKindOf(CC_TYPES::MESH))
  8044. {
  8045. ++meshNum;
  8046. isMesh[i] = true;
  8047. }
  8048. else if (m_selectedEntities[i]->isKindOf(CC_TYPES::POINT_CLOUD))
  8049. {
  8050. ++cloudNum;
  8051. }
  8052. }
  8053. if (meshNum == 0)
  8054. {
  8055. ccConsole::Error(tr("Select at least one mesh!"));
  8056. return;
  8057. }
  8058. else if (meshNum + cloudNum < 2)
  8059. {
  8060. ccConsole::Error(tr("Select one mesh and one cloud or two meshes!"));
  8061. return;
  8062. }
  8063. ccHObject* compEnt = nullptr;
  8064. ccGenericMesh* refMesh = nullptr;
  8065. if (meshNum == 1)
  8066. {
  8067. compEnt = m_selectedEntities[isMesh[0] ? 1 : 0];
  8068. refMesh = ccHObjectCaster::ToGenericMesh(m_selectedEntities[isMesh[0] ? 0 : 1]);
  8069. if (refMesh->isKindOf(CC_TYPES::PRIMITIVE))
  8070. {
  8071. static bool DontShowPrimitiveDistWarning = false;
  8072. if (!DontShowPrimitiveDistWarning)
  8073. {
  8074. QMessageBox::StandardButton answer = QMessageBox::warning(
  8075. this,
  8076. tr("Distance to primitive"),
  8077. tr("Computing distances to a primitive is faster and more accurate with the 'Tools > Distances > Cloud / Primitive Dist.' tool.\nDo you want to use this other tool instead?"),
  8078. QMessageBox::Yes | QMessageBox::No | QMessageBox::NoToAll,
  8079. QMessageBox::Yes
  8080. );
  8081. if (answer == QMessageBox::Yes)
  8082. {
  8083. return doActionCloudPrimitiveDist();
  8084. }
  8085. else if (answer == QMessageBox::NoToAll)
  8086. {
  8087. DontShowPrimitiveDistWarning = true;
  8088. }
  8089. }
  8090. }
  8091. }
  8092. else
  8093. {
  8094. ccOrderChoiceDlg dlg( m_selectedEntities.front(), tr("Compared"),
  8095. m_selectedEntities.back(), tr("Reference"),
  8096. this );
  8097. if (!dlg.exec())
  8098. return;
  8099. compEnt = dlg.getFirstEntity();
  8100. refMesh = ccHObjectCaster::ToGenericMesh(dlg.getSecondEntity());
  8101. }
  8102. //assert(!m_compDlg);
  8103. if (m_compDlg)
  8104. delete m_compDlg;
  8105. m_compDlg = new ccComparisonDlg(compEnt, refMesh, ccComparisonDlg::CLOUDMESH_DIST, this);
  8106. if (!m_compDlg->initDialog())
  8107. {
  8108. ccConsole::Error(tr("Failed to initialize comparison dialog"));
  8109. delete m_compDlg;
  8110. m_compDlg = nullptr;
  8111. return;
  8112. }
  8113. connect(m_compDlg, &QDialog::finished, this, &MainWindow::deactivateComparisonMode);
  8114. m_compDlg->show();
  8115. freezeUI(true);
  8116. }
  8117. void MainWindow::doActionCloudPrimitiveDist()
  8118. {
  8119. ccHObject::Container clouds;
  8120. ccHObject* refEntity = nullptr;
  8121. for (ccHObject* entity : getSelectedEntities())
  8122. {
  8123. if (entity->isKindOf(CC_TYPES::PRIMITIVE) || entity->isA(CC_TYPES::POLY_LINE))
  8124. {
  8125. if (entity->isA(CC_TYPES::PLANE) ||
  8126. entity->isA(CC_TYPES::SPHERE) ||
  8127. entity->isA(CC_TYPES::CYLINDER) ||
  8128. entity->isA(CC_TYPES::CONE) ||
  8129. entity->isA(CC_TYPES::BOX) ||
  8130. entity->isA(CC_TYPES::POLY_LINE))
  8131. {
  8132. if (!refEntity)
  8133. {
  8134. // first primitive encountered
  8135. refEntity = entity;
  8136. }
  8137. else
  8138. {
  8139. ccConsole::Error(tr("Select only one primitive (Plane/Box/Sphere/Cylinder/Cone) or polyline"));
  8140. return;
  8141. }
  8142. }
  8143. }
  8144. else if (entity->isKindOf(CC_TYPES::POINT_CLOUD))
  8145. {
  8146. clouds.push_back(entity);
  8147. }
  8148. }
  8149. if (!refEntity)
  8150. {
  8151. ccConsole::Error(tr("Select one prmitive (Plane/Box/Sphere/Cylinder/Cone) or a polyline"));
  8152. return;
  8153. }
  8154. if (clouds.empty())
  8155. {
  8156. ccConsole::Error(tr("Select at least one cloud"));
  8157. return;
  8158. }
  8159. ccPrimitiveDistanceDlg pDD{ this };
  8160. static bool s_treatPlanesAsBounded = false;
  8161. static bool s_signedDist = true;
  8162. static bool s_flipNormals = false;
  8163. if (refEntity->isA(CC_TYPES::PLANE))
  8164. {
  8165. pDD.treatPlanesAsBoundedCheckBox->setEnabled(true);
  8166. pDD.treatPlanesAsBoundedCheckBox->setChecked(s_treatPlanesAsBounded);
  8167. }
  8168. else
  8169. {
  8170. pDD.treatPlanesAsBoundedCheckBox->setEnabled(false);
  8171. }
  8172. pDD.flipNormalsCheckBox->setChecked(s_flipNormals);
  8173. pDD.signedDistCheckBox->setChecked(s_signedDist);
  8174. if (!refEntity->isA(CC_TYPES::POLY_LINE))
  8175. {
  8176. if (!pDD.exec())
  8177. {
  8178. return;
  8179. }
  8180. }
  8181. s_signedDist = pDD.signedDistances();
  8182. s_flipNormals = pDD.flipNormals();
  8183. s_treatPlanesAsBounded = pDD.treatPlanesAsBounded();
  8184. size_t errorCount = 0;
  8185. for (auto &cloud : clouds)
  8186. {
  8187. ccPointCloud* compEnt = ccHObjectCaster::ToPointCloud(cloud);
  8188. int sfIdx = compEnt->getScalarFieldIndexByName(CC_TEMP_DISTANCES_DEFAULT_SF_NAME);
  8189. if (sfIdx < 0)
  8190. {
  8191. //we need to create a new scalar field
  8192. sfIdx = compEnt->addScalarField(CC_TEMP_DISTANCES_DEFAULT_SF_NAME);
  8193. if (sfIdx < 0)
  8194. {
  8195. ccLog::Warning(tr("[Compute Primitive Distances] [Cloud: %1] Couldn't allocate a new scalar field for computing distances! Try to free some memory ...").arg(compEnt->getName()));
  8196. ++errorCount;
  8197. continue;
  8198. }
  8199. }
  8200. compEnt->setCurrentScalarField(sfIdx);
  8201. if (!compEnt->enableScalarField())
  8202. {
  8203. ccLog::Warning(tr("[Compute Primitive Distances] [Cloud: %1] Not enough memory").arg(compEnt->getName()));
  8204. ++errorCount;
  8205. continue;
  8206. }
  8207. compEnt->forEach(CCCoreLib::ScalarFieldTools::SetScalarValueToNaN);
  8208. int returnCode = 0;
  8209. QString errString = tr("[Compute Primitive Distances] Cloud to %1 distance computation failed (error code = %2)");
  8210. switch (refEntity->getClassID())
  8211. {
  8212. case CC_TYPES::SPHERE:
  8213. {
  8214. if (!(returnCode = CCCoreLib::DistanceComputationTools::computeCloud2SphereEquation(compEnt, refEntity->getOwnBB().getCenter(), static_cast<ccSphere*>(refEntity)->getRadius(), s_signedDist)))
  8215. ccConsole::Error(errString.arg(tr("Sphere")).arg(returnCode));
  8216. break;
  8217. }
  8218. case CC_TYPES::PLANE:
  8219. {
  8220. ccPlane* plane = static_cast<ccPlane*>(refEntity);
  8221. if (s_treatPlanesAsBounded)
  8222. {
  8223. CCCoreLib::SquareMatrix rotationTransform(plane->getTransformation().data(), true);
  8224. if (!(returnCode = CCCoreLib::DistanceComputationTools::computeCloud2RectangleEquation(compEnt, plane->getXWidth(), plane->getYWidth(), rotationTransform, plane->getCenter(), s_signedDist)))
  8225. {
  8226. ccConsole::Warning(errString.arg(tr("Bounded Plane")).arg(returnCode));
  8227. ++errorCount;
  8228. }
  8229. }
  8230. else
  8231. {
  8232. if (!(returnCode = CCCoreLib::DistanceComputationTools::computeCloud2PlaneEquation(compEnt, static_cast<ccPlane*>(refEntity)->getEquation(), s_signedDist)))
  8233. {
  8234. ccConsole::Warning(errString.arg(tr("Infinite Plane")).arg(returnCode));
  8235. ++errorCount;
  8236. }
  8237. }
  8238. break;
  8239. }
  8240. case CC_TYPES::CYLINDER:
  8241. {
  8242. if (!(returnCode = CCCoreLib::DistanceComputationTools::computeCloud2CylinderEquation(compEnt, static_cast<ccCylinder*>(refEntity)->getBottomCenter(), static_cast<ccCylinder*>(refEntity)->getTopCenter(), static_cast<ccCylinder*>(refEntity)->getBottomRadius(), s_signedDist)))
  8243. {
  8244. ccConsole::Warning(errString.arg(tr("Cylinder")).arg(returnCode));
  8245. ++errorCount;
  8246. }
  8247. break;
  8248. }
  8249. case CC_TYPES::CONE:
  8250. {
  8251. if (!(returnCode = CCCoreLib::DistanceComputationTools::computeCloud2ConeEquation(compEnt, static_cast<ccCone*>(refEntity)->getLargeCenter(), static_cast<ccCone*>(refEntity)->getSmallCenter(), static_cast<ccCone*>(refEntity)->getLargeRadius(), static_cast<ccCone*>(refEntity)->getSmallRadius(), s_signedDist)))
  8252. {
  8253. ccConsole::Warning(errString.arg(tr("Cone")).arg(returnCode));
  8254. ++errorCount;
  8255. }
  8256. break;
  8257. }
  8258. case CC_TYPES::BOX:
  8259. {
  8260. const ccGLMatrix& glTransform = refEntity->getGLTransformationHistory();
  8261. CCCoreLib::SquareMatrix rotationTransform(glTransform.data(), true);
  8262. CCVector3 boxCenter = glTransform.getColumnAsVec3D(3);
  8263. if (!(returnCode = CCCoreLib::DistanceComputationTools::computeCloud2BoxEquation(compEnt, static_cast<ccBox*>(refEntity)->getDimensions(), rotationTransform, boxCenter, s_signedDist)))
  8264. {
  8265. ccConsole::Warning(errString.arg(tr("Box")).arg(returnCode));
  8266. ++errorCount;
  8267. }
  8268. break;
  8269. }
  8270. case CC_TYPES::POLY_LINE:
  8271. {
  8272. ccPolyline* line = static_cast<ccPolyline*>(refEntity);
  8273. returnCode = CCCoreLib::DistanceComputationTools::computeCloud2PolylineEquation(compEnt, line);
  8274. if (!returnCode)
  8275. {
  8276. ccConsole::Warning(errString.arg(tr("Polyline")).arg(returnCode));
  8277. ++errorCount;
  8278. }
  8279. break;
  8280. }
  8281. default:
  8282. {
  8283. ccConsole::Error(tr("Unsupported primitive type")); //Shouldn't ever reach here...
  8284. return;
  8285. }
  8286. }
  8287. QString sfName(CC_CLOUD2PRIMITIVE_DISTANCES_DEFAULT_SF_NAME);
  8288. if (!refEntity->isKindOf(CC_TYPES::POLY_LINE))
  8289. {
  8290. if (s_signedDist)
  8291. {
  8292. sfName = CC_CLOUD2PRIMITIVE_SIGNED_DISTANCES_DEFAULT_SF_NAME;
  8293. }
  8294. if (s_flipNormals)
  8295. {
  8296. compEnt->forEach(CCCoreLib::ScalarFieldTools::SetScalarValueInverted);
  8297. sfName += "[-]";
  8298. }
  8299. }
  8300. int _sfIdx = compEnt->getScalarFieldIndexByName(sfName.toStdString());
  8301. if (_sfIdx >= 0)
  8302. {
  8303. compEnt->deleteScalarField(_sfIdx);
  8304. //we update sfIdx because indexes are all messed up after deletion
  8305. sfIdx = compEnt->getScalarFieldIndexByName(CC_TEMP_DISTANCES_DEFAULT_SF_NAME);
  8306. }
  8307. compEnt->renameScalarField(sfIdx, sfName.toStdString());
  8308. ccScalarField* sf = static_cast<ccScalarField*>(compEnt->getScalarField(sfIdx));
  8309. if (sf)
  8310. {
  8311. ScalarType mean;
  8312. ScalarType variance;
  8313. sf->computeMinAndMax();
  8314. sf->computeMeanAndVariance(mean, &variance);
  8315. ccLog::Print(tr("[Compute Primitive Distances] [Primitive: %1] [Cloud: %2] [%3] Mean distance = %4 / std deviation = %5")
  8316. .arg(refEntity->getName())
  8317. .arg(compEnt->getName())
  8318. .arg(sfName)
  8319. .arg(mean)
  8320. .arg(sqrt(variance)));
  8321. }
  8322. compEnt->setCurrentDisplayedScalarField(sfIdx);
  8323. compEnt->showSF(sfIdx >= 0);
  8324. compEnt->prepareDisplayForRefresh_recursive();
  8325. }
  8326. if (errorCount != 0)
  8327. {
  8328. ccLog::Error(tr("%1 error(s) occurred: refer to the Console (F8)").arg(errorCount));
  8329. }
  8330. MainWindow::UpdateUI();
  8331. MainWindow::RefreshAllGLWindow(false);
  8332. }
  8333. void MainWindow::deactivateComparisonMode(int result)
  8334. {
  8335. //DGM: a bug apperead with recent changes (from CC or QT?)
  8336. //which prevent us from deleting the dialog right away...
  8337. //(it seems that QT has not yet finished the dialog closing
  8338. //when the 'finished' signal is sent).
  8339. //if(m_compDlg)
  8340. // delete m_compDlg;
  8341. //m_compDlg = 0;
  8342. //if the comparison is a success, we select only the compared entity
  8343. if (m_compDlg && result == QDialog::Accepted && m_ccRoot)
  8344. {
  8345. ccHObject* compEntity = m_compDlg->getComparedEntity();
  8346. if (compEntity)
  8347. {
  8348. m_ccRoot->selectEntity(compEntity);
  8349. }
  8350. }
  8351. freezeUI(false);
  8352. updateUI();
  8353. }
  8354. void MainWindow::toggleActiveWindowSunLight()
  8355. {
  8356. ccGLWindowInterface* win = getActiveGLWindow();
  8357. if (win)
  8358. {
  8359. win->toggleSunLight();
  8360. win->redraw(false);
  8361. }
  8362. }
  8363. void MainWindow::toggleActiveWindowCustomLight()
  8364. {
  8365. ccGLWindowInterface* win = getActiveGLWindow();
  8366. if (win)
  8367. {
  8368. win->toggleCustomLight();
  8369. win->redraw(false);
  8370. }
  8371. }
  8372. void MainWindow::toggleActiveWindowAutoPickRotCenter(bool state)
  8373. {
  8374. ccGLWindowInterface* win = getActiveGLWindow();
  8375. if (win)
  8376. {
  8377. win->setAutoPickPivotAtCenter(state);
  8378. //save the option
  8379. {
  8380. QSettings settings;
  8381. settings.setValue(ccPS::AutoPickRotationCenter(), state);
  8382. }
  8383. }
  8384. }
  8385. void MainWindow::toggleActiveWindowShowCursorCoords(bool state)
  8386. {
  8387. ccGLWindowInterface* win = getActiveGLWindow();
  8388. if (win)
  8389. {
  8390. win->showCursorCoordinates(state);
  8391. }
  8392. }
  8393. void MainWindow::toggleActiveWindowStereoVision(bool state)
  8394. {
  8395. ccGLWindowInterface* win = getActiveGLWindow();
  8396. if (win)
  8397. {
  8398. bool isActive = win->stereoModeIsEnabled();
  8399. if (isActive == state)
  8400. {
  8401. //nothing to do
  8402. return;
  8403. }
  8404. if (isActive)
  8405. {
  8406. win->disableStereoMode();
  8407. if ( win->getStereoParams().glassType == ccGLWindowInterface::StereoParams::NVIDIA_VISION
  8408. || win->getStereoParams().glassType == ccGLWindowInterface::StereoParams::GENERIC_STEREO_DISPLAY)
  8409. {
  8410. //disable (exclusive) full screen
  8411. m_UI->actionExclusiveFullScreen->setChecked(false);
  8412. }
  8413. }
  8414. else
  8415. {
  8416. //display a parameters dialog
  8417. ccStereoModeDlg smDlg(this);
  8418. smDlg.setParameters(win->getStereoParams());
  8419. if (!smDlg.exec())
  8420. {
  8421. //cancelled by the user
  8422. m_UI->actionEnableStereo->blockSignals(true);
  8423. m_UI->actionEnableStereo->setChecked(false);
  8424. m_UI->actionEnableStereo->blockSignals(false);
  8425. return;
  8426. }
  8427. ccGLWindowInterface::StereoParams params = smDlg.getParameters();
  8428. ccLog::WarningDebug("Stereo strength: " + QString::number(params.stereoStrength));
  8429. if (!ccGLWindowInterface::StereoSupported() && !params.isAnaglyph())
  8430. {
  8431. ccLog::Error(tr("It seems your graphic card doesn't support Quad Buffered Stereo rendering"));
  8432. //activation of the stereo mode failed: cancel selection
  8433. m_UI->actionEnableStereo->blockSignals(true);
  8434. m_UI->actionEnableStereo->setChecked(false);
  8435. m_UI->actionEnableStereo->blockSignals(false);
  8436. return;
  8437. }
  8438. //force perspective state!
  8439. if (!win->getViewportParameters().perspectiveView)
  8440. {
  8441. setCenteredPerspectiveView(win, false);
  8442. }
  8443. if ( params.glassType == ccGLWindowInterface::StereoParams::NVIDIA_VISION
  8444. || params.glassType == ccGLWindowInterface::StereoParams::GENERIC_STEREO_DISPLAY)
  8445. {
  8446. //force (exclusive) full screen
  8447. m_UI->actionExclusiveFullScreen->setChecked(true);
  8448. }
  8449. if (smDlg.updateFOV())
  8450. {
  8451. //set the right FOV
  8452. double fov_deg = 2 * CCCoreLib::RadiansToDegrees( std::atan(params.screenWidth_mm / (2.0 * params.screenDistance_mm)) );
  8453. ccLog::Print(tr("[Stereo] F.O.V. forced to %1 deg.").arg(fov_deg));
  8454. win->setFov(fov_deg);
  8455. }
  8456. if (!win->enableStereoMode(params))
  8457. {
  8458. if ( params.glassType == ccGLWindowInterface::StereoParams::NVIDIA_VISION
  8459. || params.glassType == ccGLWindowInterface::StereoParams::GENERIC_STEREO_DISPLAY)
  8460. {
  8461. //disable (exclusive) full screen
  8462. m_UI->actionExclusiveFullScreen->setChecked(false);
  8463. }
  8464. //activation of the stereo mode failed: cancel selection
  8465. m_UI->actionEnableStereo->blockSignals(true);
  8466. m_UI->actionEnableStereo->setChecked(false);
  8467. m_UI->actionEnableStereo->blockSignals(false);
  8468. }
  8469. }
  8470. win->redraw();
  8471. }
  8472. }
  8473. bool MainWindow::checkStereoMode(ccGLWindowInterface* win)
  8474. {
  8475. assert(win);
  8476. if (win && win->getViewportParameters().perspectiveView && win->stereoModeIsEnabled())
  8477. {
  8478. ccGLWindowInterface::StereoParams params = win->getStereoParams();
  8479. bool wasExclusiveFullScreen = win->exclusiveFullScreen();
  8480. if (wasExclusiveFullScreen)
  8481. {
  8482. win->toggleExclusiveFullScreen(false);
  8483. }
  8484. win->disableStereoMode();
  8485. if (QMessageBox::question( this,
  8486. tr("Stereo mode"),
  8487. tr("Stereo-mode only works in perspective mode. Do you want to disable it?"),
  8488. QMessageBox::Yes,
  8489. QMessageBox::No) == QMessageBox::No )
  8490. {
  8491. if (wasExclusiveFullScreen)
  8492. {
  8493. win->toggleExclusiveFullScreen(true);
  8494. win->enableStereoMode(params);
  8495. }
  8496. return false;
  8497. }
  8498. else
  8499. {
  8500. if (win == getActiveGLWindow())
  8501. {
  8502. m_UI->actionEnableStereo->setChecked(false);
  8503. }
  8504. else
  8505. {
  8506. assert(false);
  8507. m_UI->actionEnableStereo->blockSignals(true);
  8508. m_UI->actionEnableStereo->setChecked(false);
  8509. m_UI->actionEnableStereo->blockSignals(false);
  8510. }
  8511. }
  8512. }
  8513. return true;
  8514. }
  8515. void MainWindow::toggleActiveWindowCenteredPerspective()
  8516. {
  8517. ccGLWindowInterface* win = getActiveGLWindow();
  8518. if (win)
  8519. {
  8520. const ccViewportParameters& params = win->getViewportParameters();
  8521. if (params.perspectiveView && params.objectCenteredView && !checkStereoMode(win)) //we need to check this only if we are already in object-centered perspective mode
  8522. {
  8523. return;
  8524. }
  8525. win->togglePerspective(true);
  8526. win->redraw(false);
  8527. updateViewModePopUpMenu(win);
  8528. updatePivotVisibilityPopUpMenu(win);
  8529. }
  8530. }
  8531. void MainWindow::toggleActiveWindowViewerBasedPerspective()
  8532. {
  8533. ccGLWindowInterface* win = getActiveGLWindow();
  8534. if (win)
  8535. {
  8536. const ccViewportParameters& params = win->getViewportParameters();
  8537. if (params.perspectiveView && !params.objectCenteredView && !checkStereoMode(win)) //we need to check this only if we are already in viewer-based perspective mode
  8538. {
  8539. return;
  8540. }
  8541. win->togglePerspective(false);
  8542. win->redraw(false);
  8543. updateViewModePopUpMenu(win);
  8544. updatePivotVisibilityPopUpMenu(win);
  8545. }
  8546. }
  8547. void MainWindow::createSinglePointCloud()
  8548. {
  8549. // ask the user to input the point coordinates
  8550. static CCVector3d s_lastPoint(0, 0, 0);
  8551. static size_t s_lastPointIndex = 0;
  8552. ccAskThreeDoubleValuesDlg axisDlg("x", "y", "z", -1.0e12, 1.0e12, s_lastPoint.x, s_lastPoint.y, s_lastPoint.z, 4, tr("Point coordinates"), this);
  8553. if (axisDlg.buttonBox->button(QDialogButtonBox::Ok))
  8554. axisDlg.buttonBox->button(QDialogButtonBox::Ok)->setFocus();
  8555. if (!axisDlg.exec())
  8556. return;
  8557. s_lastPoint.x = axisDlg.doubleSpinBox1->value();
  8558. s_lastPoint.y = axisDlg.doubleSpinBox2->value();
  8559. s_lastPoint.z = axisDlg.doubleSpinBox3->value();
  8560. // create the cloud
  8561. ccPointCloud* cloud = new ccPointCloud();
  8562. if (!cloud->reserve(1))
  8563. {
  8564. delete cloud;
  8565. ccLog::Error(tr("Not enough memory!"));
  8566. return;
  8567. }
  8568. cloud->setName(tr("Point #%1").arg(++s_lastPointIndex));
  8569. cloud->addPoint(s_lastPoint.toPC());
  8570. cloud->setPointSize(5);
  8571. // add it to the DB tree
  8572. addToDB(cloud, true, true, true, true);
  8573. // select it
  8574. m_ccRoot->unselectAllEntities();
  8575. setSelectedInDB(cloud, true);
  8576. }
  8577. void MainWindow::createPointCloudFromClipboard()
  8578. {
  8579. const QClipboard* clipboard = QApplication::clipboard();
  8580. assert(clipboard);
  8581. const QMimeData* mimeData = clipboard->mimeData();
  8582. if (!mimeData)
  8583. {
  8584. ccLog::Warning(tr("Clipboard is empty"));
  8585. return;
  8586. }
  8587. if (!mimeData->hasText())
  8588. {
  8589. ccLog::Error("ASCII/text data expected");
  8590. return;
  8591. }
  8592. // try to convert the data to a point cloud
  8593. FileIOFilter::LoadParameters parameters;
  8594. {
  8595. parameters.alwaysDisplayLoadDialog = true;
  8596. parameters.shiftHandlingMode = ccGlobalShiftManager::DIALOG_IF_NECESSARY;
  8597. parameters.parentWidget = this;
  8598. }
  8599. ccHObject container;
  8600. QByteArray data = mimeData->data("text/plain");
  8601. CC_FILE_ERROR result = AsciiFilter().loadAsciiData(data, tr("Clipboard"), container, parameters);
  8602. if (result != CC_FERR_NO_ERROR)
  8603. {
  8604. FileIOFilter::DisplayErrorMessage(result, tr("loading"), tr("from the clipboard"));
  8605. return;
  8606. }
  8607. // we only expect clouds
  8608. ccHObject::Container clouds;
  8609. if (container.filterChildren(clouds, true, CC_TYPES::POINT_CLOUD) == 0)
  8610. {
  8611. assert(false);
  8612. ccLog::Error(tr("No cloud loaded"));
  8613. return;
  8614. }
  8615. // detach the clouds from the loading container
  8616. for (ccHObject* cloud : clouds)
  8617. {
  8618. if (cloud)
  8619. {
  8620. container.removeDependencyWith(cloud);
  8621. }
  8622. }
  8623. container.removeAllChildren();
  8624. // retrieve or create the group to store the 'clipboard' clouds
  8625. ccHObject* clipboardGroup = nullptr;
  8626. {
  8627. static unsigned s_clipboardGroupID = 0;
  8628. if (s_clipboardGroupID != 0)
  8629. {
  8630. clipboardGroup = dbRootObject()->find(s_clipboardGroupID);
  8631. if (nullptr == clipboardGroup)
  8632. {
  8633. // can't find the previous group
  8634. s_clipboardGroupID = 0;
  8635. }
  8636. }
  8637. if (s_clipboardGroupID == 0)
  8638. {
  8639. clipboardGroup = new ccHObject(tr("Clipboard"));
  8640. s_clipboardGroupID = clipboardGroup->getUniqueID();
  8641. addToDB(clipboardGroup, false, false, false, false);
  8642. }
  8643. }
  8644. assert(clipboardGroup);
  8645. bool normalsDisplayedByDefault = ccOptions::Instance().normalsDisplayedByDefault;
  8646. for (ccHObject* cloud : clouds)
  8647. {
  8648. if (cloud)
  8649. {
  8650. clipboardGroup->addChild(cloud);
  8651. cloud->setName(tr("Cloud #%1").arg(clipboardGroup->getChildrenNumber()));
  8652. if (!normalsDisplayedByDefault)
  8653. {
  8654. // disable the normals on all loaded clouds!
  8655. static_cast<ccGenericPointCloud*>(cloud)->showNormals(false);
  8656. }
  8657. }
  8658. }
  8659. // eventually, we can add the clouds to the DB tree
  8660. for (size_t i = 0; i < clouds.size(); ++i)
  8661. {
  8662. ccHObject* cloud = clouds[i];
  8663. if (cloud)
  8664. {
  8665. bool lastCloud = (i + 1 == clouds.size());
  8666. addToDB(cloud, lastCloud, lastCloud, true, lastCloud);
  8667. }
  8668. }
  8669. QMainWindow::statusBar()->showMessage(tr("%1 cloud(s) loaded from the clipboard").arg(clouds.size()), 2000);
  8670. }
  8671. void MainWindow::toggleLockRotationAxis()
  8672. {
  8673. ccGLWindowInterface* win = getActiveGLWindow();
  8674. if (win)
  8675. {
  8676. bool wasLocked = win->isRotationAxisLocked();
  8677. bool isLocked = !wasLocked;
  8678. static CCVector3d s_lastAxis(0.0, 0.0, 1.0);
  8679. if (isLocked)
  8680. {
  8681. ccAskThreeDoubleValuesDlg axisDlg("x", "y", "z", -1.0e12, 1.0e12, s_lastAxis.x, s_lastAxis.y, s_lastAxis.z, 4, tr("Lock rotation axis"), this);
  8682. if (axisDlg.buttonBox->button(QDialogButtonBox::Ok))
  8683. axisDlg.buttonBox->button(QDialogButtonBox::Ok)->setFocus();
  8684. if (!axisDlg.exec())
  8685. return;
  8686. s_lastAxis.x = axisDlg.doubleSpinBox1->value();
  8687. s_lastAxis.y = axisDlg.doubleSpinBox2->value();
  8688. s_lastAxis.z = axisDlg.doubleSpinBox3->value();
  8689. }
  8690. win->lockRotationAxis(isLocked, s_lastAxis);
  8691. m_UI->actionLockRotationAxis->blockSignals(true);
  8692. m_UI->actionLockRotationAxis->setChecked(isLocked);
  8693. m_UI->actionLockRotationAxis->blockSignals(false);
  8694. if (isLocked)
  8695. {
  8696. win->displayNewMessage(tr("[ROTATION LOCKED]"), ccGLWindowInterface::UPPER_CENTER_MESSAGE, false, 24 * 3600, ccGLWindowInterface::ROTAION_LOCK_MESSAGE);
  8697. }
  8698. else
  8699. {
  8700. win->displayNewMessage(QString(), ccGLWindowInterface::UPPER_CENTER_MESSAGE, false, 0, ccGLWindowInterface::ROTAION_LOCK_MESSAGE);
  8701. }
  8702. win->redraw(true, false);
  8703. }
  8704. }
  8705. void MainWindow::doActionEnableBubbleViewMode()
  8706. {
  8707. //special case: the selected entity is a TLS sensor or a cloud with a TLS sensor
  8708. if (m_ccRoot)
  8709. {
  8710. ccHObject::Container selectedEntities;
  8711. m_ccRoot->getSelectedEntities(selectedEntities);
  8712. if (selectedEntities.size() == 1)
  8713. {
  8714. ccHObject* ent = selectedEntities.front();
  8715. ccGBLSensor* sensor = nullptr;
  8716. if (ent->isA(CC_TYPES::GBL_SENSOR))
  8717. {
  8718. sensor = static_cast<ccGBLSensor*>(ent);
  8719. }
  8720. else if (ent->isA(CC_TYPES::POINT_CLOUD))
  8721. {
  8722. ccHObject::Container sensors;
  8723. ent->filterChildren(sensors, false, CC_TYPES::GBL_SENSOR, true);
  8724. if (sensors.size() >= 1)
  8725. {
  8726. sensor = static_cast<ccGBLSensor*>(sensors.front());
  8727. }
  8728. }
  8729. if (sensor)
  8730. {
  8731. sensor->applyViewport();
  8732. return;
  8733. }
  8734. }
  8735. }
  8736. //otherwise we simply enable the bubble view mode in the active 3D view
  8737. ccGLWindowInterface* win = getActiveGLWindow();
  8738. if (win)
  8739. {
  8740. win->setBubbleViewMode(true);
  8741. win->redraw(false);
  8742. }
  8743. }
  8744. void MainWindow::doActionDeleteShader()
  8745. {
  8746. ccGLWindowInterface* win = getActiveGLWindow();
  8747. if (win)
  8748. {
  8749. win->setShader(nullptr);
  8750. }
  8751. }
  8752. void MainWindow::removeFromDB(ccHObject* obj, bool autoDelete/*=true*/)
  8753. {
  8754. if (!obj)
  8755. return;
  8756. //remove dependency to avoid deleting the object when removing it from DB tree
  8757. if (!autoDelete && obj->getParent())
  8758. obj->getParent()->removeDependencyWith(obj);
  8759. if (m_ccRoot)
  8760. m_ccRoot->removeElement(obj);
  8761. }
  8762. void MainWindow::setSelectedInDB(ccHObject* obj, bool selected)
  8763. {
  8764. if (obj && m_ccRoot)
  8765. {
  8766. if (selected)
  8767. m_ccRoot->selectEntity(obj);
  8768. else
  8769. m_ccRoot->unselectEntity(obj);
  8770. }
  8771. }
  8772. void MainWindow::addToDB( ccHObject* obj,
  8773. bool updateZoom/*=true*/,
  8774. bool autoExpandDBTree/*=true*/,
  8775. bool checkDimensions/*=true*/,
  8776. bool autoRedraw/*=true*/)
  8777. {
  8778. //let's check that the new entity is not too big nor too far from scene center!
  8779. if (checkDimensions)
  8780. {
  8781. //get entity bounding box
  8782. ccBBox bBox = obj->getBB_recursive();
  8783. CCVector3 center = bBox.getCenter();
  8784. PointCoordinateType diag = bBox.getDiagNorm();
  8785. CCVector3d P = center;
  8786. CCVector3d Pshift(0, 0, 0);
  8787. double scale = 1.0;
  8788. bool preserveCoordinateShift = true;
  8789. //here we must test that coordinates are not too big whatever the case because OpenGL
  8790. //really doesn't like big ones (even if we work with GLdoubles :( ).
  8791. if (ccGlobalShiftManager::Handle( P,
  8792. diag,
  8793. ccGlobalShiftManager::DIALOG_IF_NECESSARY,
  8794. false,
  8795. Pshift,
  8796. &preserveCoordinateShift,
  8797. &scale)
  8798. )
  8799. {
  8800. bool needRescale = (scale != 1.0);
  8801. bool needShift = (Pshift.norm2() > 0);
  8802. if (needRescale || needShift)
  8803. {
  8804. ccGLMatrix mat;
  8805. mat.toIdentity();
  8806. mat.data()[0] = mat.data()[5] = mat.data()[10] = static_cast<float>(scale);
  8807. mat.setTranslation(Pshift);
  8808. obj->applyGLTransformation_recursive(&mat);
  8809. ccConsole::Warning(tr("Entity '%1' has been translated: (%2,%3,%4) and rescaled of a factor %5 [original position will be restored when saving]").arg(obj->getName()).arg(Pshift.x,0,'f',2).arg(Pshift.y,0,'f',2).arg(Pshift.z,0,'f',2).arg(scale,0,'f',6));
  8810. }
  8811. //update 'global shift' and 'global scale' for ALL clouds recursively
  8812. if (preserveCoordinateShift)
  8813. {
  8814. //FIXME: why don't we do that all the time by the way?!
  8815. ccHObject::Container children;
  8816. children.push_back(obj);
  8817. while (!children.empty())
  8818. {
  8819. ccHObject* child = children.back();
  8820. children.pop_back();
  8821. if (child->isKindOf(CC_TYPES::POINT_CLOUD))
  8822. {
  8823. ccGenericPointCloud* pc = ccHObjectCaster::ToGenericPointCloud(child);
  8824. pc->setGlobalShift(pc->getGlobalShift() + Pshift);
  8825. pc->setGlobalScale(pc->getGlobalScale() * scale);
  8826. }
  8827. for (unsigned i = 0; i < child->getChildrenNumber(); ++i)
  8828. {
  8829. children.push_back(child->getChild(i));
  8830. }
  8831. }
  8832. }
  8833. }
  8834. }
  8835. //add object to DB root
  8836. if (m_ccRoot)
  8837. {
  8838. //force a 'global zoom' if the DB was emtpy!
  8839. if (!m_ccRoot->getRootEntity() || m_ccRoot->getRootEntity()->getChildrenNumber() == 0)
  8840. {
  8841. updateZoom = true;
  8842. }
  8843. m_ccRoot->addElement(obj, autoExpandDBTree);
  8844. }
  8845. else
  8846. {
  8847. ccLog::Warning(tr("[MainWindow::addToDB] Internal error: no associated DB?!"));
  8848. assert(false);
  8849. }
  8850. //we can now set destination display (if none already)
  8851. if (!obj->getDisplay())
  8852. {
  8853. ccGLWindowInterface* activeWin = getActiveGLWindow();
  8854. if (!activeWin)
  8855. {
  8856. //no active GL window?!
  8857. return;
  8858. }
  8859. obj->setDisplay_recursive(activeWin);
  8860. }
  8861. //eventually we update the corresponding display
  8862. assert(obj->getDisplay());
  8863. if (updateZoom)
  8864. {
  8865. static_cast<ccGLWindowInterface*>(obj->getDisplay())->zoomGlobal(); //automatically calls ccGLWindowInterface::redraw
  8866. }
  8867. else if (autoRedraw)
  8868. {
  8869. obj->redrawDisplay();
  8870. }
  8871. }
  8872. void MainWindow::onExclusiveFullScreenToggled(bool state)
  8873. {
  8874. //we simply update the fullscreen action method icon (whatever the window)
  8875. ccGLWindowInterface* win = getActiveGLWindow();
  8876. if (win == nullptr)
  8877. return;
  8878. m_UI->actionExclusiveFullScreen->blockSignals(true);
  8879. m_UI->actionExclusiveFullScreen->setChecked(win->exclusiveFullScreen());
  8880. m_UI->actionExclusiveFullScreen->blockSignals(false);
  8881. if ( !state
  8882. && win->stereoModeIsEnabled()
  8883. && ( win->getStereoParams().glassType == ccGLWindowInterface::StereoParams::NVIDIA_VISION
  8884. || win->getStereoParams().glassType == ccGLWindowInterface::StereoParams::GENERIC_STEREO_DISPLAY ))
  8885. {
  8886. //auto disable stereo mode as NVidia Vision only works in full screen mode!
  8887. m_UI->actionEnableStereo->setChecked(false);
  8888. }
  8889. }
  8890. ccHObject* MainWindow::loadFile(QString filename, bool silent)
  8891. {
  8892. FileIOFilter::LoadParameters parameters;
  8893. {
  8894. parameters.alwaysDisplayLoadDialog = silent ? false : true;
  8895. parameters.shiftHandlingMode = ccGlobalShiftManager::NO_DIALOG_AUTO_SHIFT;
  8896. parameters.parentWidget = silent ? nullptr : this;
  8897. }
  8898. CC_FILE_ERROR result = CC_FERR_NO_ERROR;
  8899. ccHObject* newGroup = FileIOFilter::LoadFromFile(filename, parameters, result);
  8900. return newGroup;
  8901. }
  8902. void MainWindow::addToDBAuto(const QStringList& filenames)
  8903. {
  8904. ccGLWindowInterface* win = ccGLWindowInterface::FromEmitter(sender());
  8905. if (win)
  8906. {
  8907. addToDB(filenames, QString(), win);
  8908. }
  8909. else
  8910. {
  8911. assert(false);
  8912. }
  8913. }
  8914. void MainWindow::addToDB( const QStringList& filenames,
  8915. QString fileFilter/*=QString()*/,
  8916. ccGLWindowInterface* destWin/*=nullptr*/)
  8917. {
  8918. //to use the same 'global shift' for multiple files
  8919. CCVector3d loadCoordinatesShift(0, 0, 0);
  8920. bool loadCoordinatesTransEnabled = false;
  8921. bool loadCoordinatesTransForced = false;
  8922. FileIOFilter::LoadParameters parameters;
  8923. {
  8924. parameters.alwaysDisplayLoadDialog = true;
  8925. parameters.shiftHandlingMode = ccGlobalShiftManager::DIALOG_IF_NECESSARY;
  8926. parameters._coordinatesShift = &loadCoordinatesShift;
  8927. parameters._coordinatesShiftEnabled = &loadCoordinatesTransEnabled;
  8928. parameters._coordinatesShiftForced = &loadCoordinatesTransForced;
  8929. parameters.parentWidget = this;
  8930. }
  8931. bool normalsDisplayedByDefault = ccOptions::Instance().normalsDisplayedByDefault;
  8932. FileIOFilter::ResetSesionCounter();
  8933. for ( const QString &filename : filenames )
  8934. {
  8935. CC_FILE_ERROR result = CC_FERR_NO_ERROR;
  8936. ccHObject* newGroup = FileIOFilter::LoadFromFile(filename, parameters, result, fileFilter);
  8937. if (newGroup)
  8938. {
  8939. if (!normalsDisplayedByDefault)
  8940. {
  8941. //disable the normals on all loaded clouds!
  8942. ccHObject::Container clouds;
  8943. newGroup->filterChildren(clouds, true, CC_TYPES::POINT_CLOUD);
  8944. for (ccHObject* cloud : clouds)
  8945. {
  8946. if (cloud)
  8947. {
  8948. static_cast<ccGenericPointCloud*>(cloud)->showNormals(false);
  8949. }
  8950. }
  8951. }
  8952. if (destWin)
  8953. {
  8954. newGroup->setDisplay_recursive(destWin);
  8955. }
  8956. addToDB(newGroup, true, true, false);
  8957. m_recentFiles->addFilePath( filename );
  8958. }
  8959. if (result == CC_FERR_CANCELED_BY_USER)
  8960. {
  8961. //stop importing the file if the user has cancelled the current process!
  8962. break;
  8963. }
  8964. }
  8965. QMainWindow::statusBar()->showMessage(tr("%1 file(s) loaded").arg(filenames.size()),2000);
  8966. }
  8967. void MainWindow::handleNewLabel(ccHObject* entity)
  8968. {
  8969. if (entity)
  8970. {
  8971. addToDB(entity, false, true, false, false);
  8972. }
  8973. else
  8974. {
  8975. assert(false);
  8976. }
  8977. }
  8978. void MainWindow::forceConsoleDisplay()
  8979. {
  8980. //if the console is hidden, we autoamtically display it!
  8981. if (m_UI->DockableConsole && m_UI->DockableConsole->isHidden())
  8982. {
  8983. m_UI->DockableConsole->show();
  8984. QApplication::processEvents();
  8985. }
  8986. }
  8987. ccColorScalesManager* MainWindow::getColorScalesManager()
  8988. {
  8989. return ccColorScalesManager::GetUniqueInstance();
  8990. }
  8991. void MainWindow::closeAll()
  8992. {
  8993. if (!m_ccRoot)
  8994. {
  8995. return;
  8996. }
  8997. QMessageBox message_box( QMessageBox::Question,
  8998. tr("Close all"),
  8999. tr("Are you sure you want to remove all loaded entities?"),
  9000. QMessageBox::Yes | QMessageBox::No,
  9001. this );
  9002. if (message_box.exec() == QMessageBox::No)
  9003. {
  9004. return;
  9005. }
  9006. m_ccRoot->unloadAll();
  9007. redrawAll(false);
  9008. }
  9009. void MainWindow::doActionLoadFile()
  9010. {
  9011. //persistent settings
  9012. QSettings settings;
  9013. settings.beginGroup(ccPS::LoadFile());
  9014. QString currentPath = settings.value(ccPS::CurrentPath(), ccFileUtils::defaultDocPath()).toString();
  9015. QString currentOpenDlgFilter = settings.value(ccPS::SelectedInputFilter(), BinFilter::GetFileFilter()).toString();
  9016. // Add all available file I/O filters (with import capabilities)
  9017. const QStringList filterStrings = FileIOFilter::ImportFilterList();
  9018. const QString &allFilter = filterStrings.at( 0 );
  9019. if ( !filterStrings.contains( currentOpenDlgFilter ) )
  9020. {
  9021. currentOpenDlgFilter = allFilter;
  9022. }
  9023. //file choosing dialog
  9024. QStringList selectedFiles = QFileDialog::getOpenFileNames( this,
  9025. tr("Open file(s)"),
  9026. currentPath,
  9027. filterStrings.join(s_fileFilterSeparator),
  9028. &currentOpenDlgFilter,
  9029. CCFileDialogOptions());
  9030. if (selectedFiles.isEmpty())
  9031. return;
  9032. //save last loading parameters
  9033. currentPath = QFileInfo(selectedFiles[0]).absolutePath();
  9034. settings.setValue(ccPS::CurrentPath(),currentPath);
  9035. settings.setValue(ccPS::SelectedInputFilter(),currentOpenDlgFilter);
  9036. settings.endGroup();
  9037. if (currentOpenDlgFilter == allFilter)
  9038. {
  9039. currentOpenDlgFilter.clear(); //this way FileIOFilter will try to guess the file type automatically!
  9040. }
  9041. //load files
  9042. addToDB(selectedFiles, currentOpenDlgFilter);
  9043. }
  9044. //Helper: check for a filename validity
  9045. static bool IsValidFileName(QString filename)
  9046. {
  9047. #ifdef CC_WINDOWS
  9048. QString sPattern("^(?!^(PRN|AUX|CLOCK\\$|NUL|CON|COM\\d|LPT\\d|\\..*)(\\..+)?$)[^\\x00-\\x1f\\\\?*:\\"";|/]+$");
  9049. #else
  9050. QString sPattern("^(([a-zA-Z]:|\\\\)\\\\)?(((\\.)|(\\.\\.)|([^\\\\/:\\*\\?""\\|<>\\. ](([^\\\\/:\\*\\?""\\|<>\\. ])|([^\\\\/:\\*\\?""\\|<>]*[^\\\\/:\\*\\?""\\|<>\\. ]))?))\\\\)*[^\\\\/:\\*\\?""\\|<>\\. ](([^\\\\/:\\*\\?""\\|<>\\. ])|([^\\\\/:\\*\\?""\\|<>]*[^\\\\/:\\*\\?""\\|<>\\. ]))?$");
  9051. #endif
  9052. return QRegExp(sPattern).exactMatch(filename);
  9053. }
  9054. void MainWindow::doActionSaveFile()
  9055. {
  9056. if (!haveSelection())
  9057. return;
  9058. ccHObject clouds("clouds");
  9059. ccHObject meshes("meshes");
  9060. ccHObject images("images");
  9061. ccHObject polylines("polylines");
  9062. ccHObject other("other");
  9063. ccHObject otherSerializable("serializable");
  9064. ccHObject::Container entitiesToDispatch;
  9065. entitiesToDispatch.insert(entitiesToDispatch.begin(), m_selectedEntities.begin(), m_selectedEntities.end());
  9066. ccHObject entitiesToSave;
  9067. while (!entitiesToDispatch.empty())
  9068. {
  9069. ccHObject* child = entitiesToDispatch.back();
  9070. entitiesToDispatch.pop_back();
  9071. if (child->isA(CC_TYPES::HIERARCHY_OBJECT))
  9072. {
  9073. for (unsigned j = 0; j < child->getChildrenNumber(); ++j)
  9074. entitiesToDispatch.push_back(child->getChild(j));
  9075. }
  9076. else
  9077. {
  9078. //we put the entity in the container corresponding to its type
  9079. ccHObject* dest = nullptr;
  9080. if (child->isA(CC_TYPES::POINT_CLOUD))
  9081. dest = &clouds;
  9082. else if (child->isKindOf(CC_TYPES::MESH))
  9083. dest = &meshes;
  9084. else if (child->isKindOf(CC_TYPES::IMAGE))
  9085. dest = &images;
  9086. else if (child->isKindOf(CC_TYPES::POLY_LINE))
  9087. dest = &polylines;
  9088. else if (child->isSerializable())
  9089. dest = &otherSerializable;
  9090. else
  9091. dest = &other;
  9092. assert(dest);
  9093. //we don't want double insertions if the user has highlighted both the father and the child
  9094. if (!dest->find(child->getUniqueID()))
  9095. {
  9096. dest->addChild(child, ccHObject::DP_NONE);
  9097. entitiesToSave.addChild(child, ccHObject::DP_NONE);
  9098. }
  9099. }
  9100. }
  9101. bool hasCloud = (clouds.getChildrenNumber() != 0);
  9102. bool hasMesh = (meshes.getChildrenNumber() != 0);
  9103. bool hasImages = (images.getChildrenNumber() != 0);
  9104. bool hasPolylines = (polylines.getChildrenNumber() != 0);
  9105. bool hasSerializable = (otherSerializable.getChildrenNumber() != 0);
  9106. bool hasOther = (other.getChildrenNumber() != 0);
  9107. int stdSaveTypes = static_cast<int>(hasCloud)
  9108. + static_cast<int>(hasMesh)
  9109. + static_cast<int>(hasImages)
  9110. + static_cast<int>(hasPolylines)
  9111. + static_cast<int>(hasSerializable);
  9112. if (stdSaveTypes == 0)
  9113. {
  9114. ccConsole::Error(tr("Can't save selected entity(ies) this way!"));
  9115. return;
  9116. }
  9117. //we set up the right file filters, depending on the selected
  9118. //entities type (cloud, mesh, etc.).
  9119. QStringList fileFilters;
  9120. {
  9121. for ( const FileIOFilter::Shared& filter : FileIOFilter::GetFilters() )
  9122. {
  9123. bool atLeastOneExclusive = false;
  9124. //can this filter export one or several clouds?
  9125. bool canExportClouds = true;
  9126. if (hasCloud)
  9127. {
  9128. bool isExclusive = true;
  9129. bool multiple = false;
  9130. canExportClouds = ( filter->canSave(CC_TYPES::POINT_CLOUD, multiple, isExclusive)
  9131. && (multiple || clouds.getChildrenNumber() == 1) );
  9132. atLeastOneExclusive |= isExclusive;
  9133. }
  9134. //can this filter export one or several meshes?
  9135. bool canExportMeshes = true;
  9136. if (hasMesh)
  9137. {
  9138. bool isExclusive = true;
  9139. bool multiple = false;
  9140. canExportMeshes = ( filter->canSave(CC_TYPES::MESH, multiple, isExclusive)
  9141. && (multiple || meshes.getChildrenNumber() == 1) );
  9142. atLeastOneExclusive |= isExclusive;
  9143. }
  9144. //can this filter export one or several polylines?
  9145. bool canExportPolylines = true;
  9146. if (hasPolylines)
  9147. {
  9148. bool isExclusive = true;
  9149. bool multiple = false;
  9150. canExportPolylines = ( filter->canSave(CC_TYPES::POLY_LINE, multiple, isExclusive)
  9151. && (multiple || polylines.getChildrenNumber() == 1) );
  9152. atLeastOneExclusive |= isExclusive;
  9153. }
  9154. //can this filter export one or several images?
  9155. bool canExportImages = true;
  9156. if (hasImages)
  9157. {
  9158. bool isExclusive = true;
  9159. bool multiple = false;
  9160. canExportImages = ( filter->canSave(CC_TYPES::IMAGE, multiple, isExclusive)
  9161. && (multiple || images.getChildrenNumber() == 1) );
  9162. atLeastOneExclusive |= isExclusive;
  9163. }
  9164. //can this filter export one or several other serializable entities?
  9165. bool canExportSerializables = true;
  9166. if (hasSerializable)
  9167. {
  9168. //check if all entities have the same type
  9169. {
  9170. CC_CLASS_ENUM firstClassID = otherSerializable.getChild(0)->getUniqueID();
  9171. for (unsigned j = 1; j < otherSerializable.getChildrenNumber(); ++j)
  9172. {
  9173. if (otherSerializable.getChild(j)->getUniqueID() != firstClassID)
  9174. {
  9175. //we add a virtual second 'stdSaveType' so as to properly handle exlusivity
  9176. ++stdSaveTypes;
  9177. break;
  9178. }
  9179. }
  9180. }
  9181. for (unsigned j = 0; j < otherSerializable.getChildrenNumber(); ++j)
  9182. {
  9183. ccHObject* child = otherSerializable.getChild(j);
  9184. bool isExclusive = true;
  9185. bool multiple = false;
  9186. canExportSerializables &= ( filter->canSave(child->getClassID(), multiple, isExclusive)
  9187. && (multiple || otherSerializable.getChildrenNumber() == 1) );
  9188. atLeastOneExclusive |= isExclusive;
  9189. }
  9190. }
  9191. bool useThisFilter = canExportClouds
  9192. && canExportMeshes
  9193. && canExportImages
  9194. && canExportPolylines
  9195. && canExportSerializables
  9196. && (!atLeastOneExclusive || stdSaveTypes == 1);
  9197. if (useThisFilter)
  9198. {
  9199. QStringList ff = filter->getFileFilters(false);
  9200. for (int j = 0; j < ff.size(); ++j)
  9201. fileFilters.append(ff[j]);
  9202. }
  9203. }
  9204. }
  9205. //persistent settings
  9206. QSettings settings;
  9207. settings.beginGroup(ccPS::SaveFile());
  9208. //default filter
  9209. QString selectedFilter = fileFilters.first();
  9210. if (hasCloud)
  9211. selectedFilter = settings.value(ccPS::SelectedOutputFilterCloud(), selectedFilter).toString();
  9212. else if (hasMesh)
  9213. selectedFilter = settings.value(ccPS::SelectedOutputFilterMesh(), selectedFilter).toString();
  9214. else if (hasImages)
  9215. selectedFilter = settings.value(ccPS::SelectedOutputFilterImage(), selectedFilter).toString();
  9216. else if (hasPolylines)
  9217. selectedFilter = settings.value(ccPS::SelectedOutputFilterPoly(), selectedFilter).toString();
  9218. //default output path (+ filename)
  9219. QString currentPath = settings.value(ccPS::CurrentPath(), ccFileUtils::defaultDocPath()).toString();
  9220. QString fullPathName = currentPath;
  9221. if (haveOneSelection())
  9222. {
  9223. //hierarchy objects have generally as name: 'filename.ext (fullpath)'
  9224. //so we must only take the first part! (otherwise this type of name
  9225. //with a path inside disturbs QFileDialog a lot ;))
  9226. QString defaultFileName(m_selectedEntities.front()->getName());
  9227. if (m_selectedEntities.front()->isA(CC_TYPES::HIERARCHY_OBJECT))
  9228. {
  9229. QStringList parts = defaultFileName.split(' ', QString::SkipEmptyParts);
  9230. if (!parts.empty())
  9231. {
  9232. defaultFileName = parts[0];
  9233. }
  9234. }
  9235. //we remove the extension
  9236. defaultFileName = QFileInfo(defaultFileName).completeBaseName();
  9237. if (!IsValidFileName(defaultFileName))
  9238. {
  9239. ccLog::Warning(tr("[I/O] First entity's name would make an invalid filename! Can't use it..."));
  9240. defaultFileName = "project";
  9241. }
  9242. fullPathName += QString("/") + defaultFileName;
  9243. }
  9244. //ask the user for the output filename
  9245. QString selectedFilename = QFileDialog::getSaveFileName(this,
  9246. tr("Save file"),
  9247. fullPathName,
  9248. fileFilters.join(s_fileFilterSeparator),
  9249. &selectedFilter,
  9250. CCFileDialogOptions());
  9251. if (selectedFilename.isEmpty())
  9252. {
  9253. //process cancelled by the user
  9254. return;
  9255. }
  9256. //ignored items
  9257. if (hasOther)
  9258. {
  9259. ccConsole::Warning(tr("[I/O] The following selected entities won't be saved:"));
  9260. for (unsigned i = 0; i < other.getChildrenNumber(); ++i)
  9261. {
  9262. ccConsole::Warning(QString("\t- %1s").arg(other.getChild(i)->getName()));
  9263. }
  9264. }
  9265. CC_FILE_ERROR result = CC_FERR_NO_ERROR;
  9266. FileIOFilter::SaveParameters parameters;
  9267. {
  9268. parameters.alwaysDisplaySaveDialog = true;
  9269. parameters.parentWidget = this;
  9270. }
  9271. //specific case: BIN format
  9272. if (selectedFilter == BinFilter::GetFileFilter())
  9273. {
  9274. if ( haveOneSelection() )
  9275. {
  9276. result = FileIOFilter::SaveToFile(m_selectedEntities.front(), selectedFilename, parameters, selectedFilter);
  9277. }
  9278. else
  9279. {
  9280. //we'll regroup all selected entities in a temporary group
  9281. ccHObject tempContainer;
  9282. ConvertToGroup(m_selectedEntities, tempContainer, ccHObject::DP_NONE);
  9283. if (tempContainer.getChildrenNumber())
  9284. {
  9285. result = FileIOFilter::SaveToFile(&tempContainer, selectedFilename, parameters, selectedFilter);
  9286. }
  9287. else
  9288. {
  9289. ccLog::Warning(tr("[I/O] None of the selected entities can be saved this way..."));
  9290. result = CC_FERR_NO_SAVE;
  9291. }
  9292. }
  9293. }
  9294. else if (entitiesToSave.getChildrenNumber() != 0)
  9295. {
  9296. //ignored items
  9297. //if (hasSerializable)
  9298. //{
  9299. // if (!hasOther)
  9300. // ccConsole::Warning(tr("[I/O] The following selected entites won't be saved:")); //display this warning only if not already done
  9301. // for (unsigned i = 0; i < otherSerializable.getChildrenNumber(); ++i)
  9302. // ccConsole::Warning(tr("\t- %1").arg(otherSerializable.getChild(i)->getName()));
  9303. //}
  9304. result = FileIOFilter::SaveToFile( entitiesToSave.getChildrenNumber() > 1 ? &entitiesToSave : entitiesToSave.getChild(0),
  9305. selectedFilename,
  9306. parameters,
  9307. selectedFilter);
  9308. if (result == CC_FERR_NO_ERROR && m_ccRoot)
  9309. {
  9310. m_ccRoot->unselectAllEntities();
  9311. }
  9312. }
  9313. if (result == CC_FERR_NO_ERROR && selectedFilter == BinFilter::GetFileFilter())
  9314. {
  9315. //only for BIN files: display the compatible CC version
  9316. short fileVersion = BinFilter::GetLastSavedFileVersion();
  9317. if (0 != fileVersion)
  9318. {
  9319. QString minCCVersion = ccApplication::GetMinCCVersionForFileVersion(fileVersion);
  9320. ccLog::Print(QString("This file can be loaded by CloudCompare version %1 and later").arg(minCCVersion));
  9321. }
  9322. }
  9323. //update default filters
  9324. if (hasCloud)
  9325. settings.setValue(ccPS::SelectedOutputFilterCloud(),selectedFilter);
  9326. if (hasMesh)
  9327. settings.setValue(ccPS::SelectedOutputFilterMesh(), selectedFilter);
  9328. if (hasImages)
  9329. settings.setValue(ccPS::SelectedOutputFilterImage(),selectedFilter);
  9330. if (hasPolylines)
  9331. settings.setValue(ccPS::SelectedOutputFilterPoly(), selectedFilter);
  9332. //we update current file path
  9333. currentPath = QFileInfo(selectedFilename).absolutePath();
  9334. settings.setValue(ccPS::CurrentPath(),currentPath);
  9335. settings.endGroup();
  9336. }
  9337. void MainWindow::doActionSaveProject()
  9338. {
  9339. if (!m_ccRoot || !m_ccRoot->getRootEntity())
  9340. {
  9341. assert(false);
  9342. return;
  9343. }
  9344. ccHObject* rootEntity = m_ccRoot->getRootEntity();
  9345. if (rootEntity->getChildrenNumber() == 0)
  9346. {
  9347. return;
  9348. }
  9349. //default output path (+ filename)
  9350. QSettings settings;
  9351. settings.beginGroup(ccPS::SaveFile());
  9352. QString currentPath = settings.value(ccPS::CurrentPath(), ccFileUtils::defaultDocPath()).toString();
  9353. ccLog::PrintDebug(currentPath);
  9354. QString fullPathName = currentPath;
  9355. static QString s_previousProjectName{ "project" };
  9356. QString defaultFileName = s_previousProjectName;
  9357. if (rootEntity->getChildrenNumber() == 1)
  9358. {
  9359. // If there's only on top entity, we can try to use its name as the project name.
  9360. ccHObject* topEntity = rootEntity->getChild(0);
  9361. defaultFileName = topEntity->getName();
  9362. if (topEntity->isA(CC_TYPES::HIERARCHY_OBJECT))
  9363. {
  9364. // Hierarchy objects have generally as name: 'filename.ext (fullpath)'
  9365. // so we must only take the first part! (otherwise this type of name
  9366. // with a path inside disturbs the QFileDialog a lot ;))
  9367. QStringList parts = defaultFileName.split(' ', QString::SkipEmptyParts);
  9368. if (!parts.empty())
  9369. {
  9370. defaultFileName = parts[0];
  9371. }
  9372. }
  9373. //we remove the extension
  9374. defaultFileName = QFileInfo(defaultFileName).completeBaseName();
  9375. if (!IsValidFileName(defaultFileName))
  9376. {
  9377. ccLog::Warning(tr("[I/O] Top entity's name would make an invalid filename! Can't use it..."));
  9378. defaultFileName = "project";
  9379. }
  9380. }
  9381. fullPathName += QString("/") + defaultFileName;
  9382. QString binFilter = BinFilter::GetFileFilter();
  9383. //ask the user for the output filename
  9384. QString selectedFilename = QFileDialog::getSaveFileName(this,
  9385. tr("Save file"),
  9386. fullPathName,
  9387. binFilter,
  9388. &binFilter,
  9389. CCFileDialogOptions());
  9390. if (selectedFilename.isEmpty())
  9391. {
  9392. //process cancelled by the user
  9393. return;
  9394. }
  9395. FileIOFilter::SaveParameters parameters;
  9396. {
  9397. parameters.alwaysDisplaySaveDialog = true;
  9398. parameters.parentWidget = this;
  9399. }
  9400. CC_FILE_ERROR result = FileIOFilter::SaveToFile(rootEntity->getChildrenNumber() == 1 ? rootEntity->getChild(0) : rootEntity, selectedFilename, parameters, binFilter);
  9401. if (result == CC_FERR_NO_ERROR)
  9402. {
  9403. //only for BIN files: display the compatible CC version
  9404. short fileVersion = BinFilter::GetLastSavedFileVersion();
  9405. if (0 != fileVersion)
  9406. {
  9407. QString minCCVersion = ccApplication::GetMinCCVersionForFileVersion(fileVersion);
  9408. ccLog::Print(QString("This file can be loaded by CloudCompare version %1 and later").arg(minCCVersion));
  9409. }
  9410. }
  9411. //we update the current 'save' path
  9412. QFileInfo fi(selectedFilename);
  9413. s_previousProjectName = fi.fileName();
  9414. currentPath = fi.absolutePath();
  9415. settings.setValue(ccPS::CurrentPath(), currentPath);
  9416. settings.endGroup();
  9417. }
  9418. void MainWindow::on3DViewActivated(QMdiSubWindow* mdiWin)
  9419. {
  9420. ccGLWindowInterface* win = mdiWin ? ccGLWindowInterface::FromWidget(mdiWin->widget()) : nullptr;
  9421. if (win)
  9422. {
  9423. updateViewModePopUpMenu(win);
  9424. updatePivotVisibilityPopUpMenu(win);
  9425. m_UI->actionLockRotationAxis->blockSignals(true);
  9426. m_UI->actionLockRotationAxis->setChecked(win->isRotationAxisLocked());
  9427. m_UI->actionLockRotationAxis->blockSignals(false);
  9428. m_UI->actionEnableStereo->blockSignals(true);
  9429. m_UI->actionEnableStereo->setChecked(win->stereoModeIsEnabled());
  9430. m_UI->actionEnableStereo->blockSignals(false);
  9431. m_UI->actionExclusiveFullScreen->blockSignals(true);
  9432. m_UI->actionExclusiveFullScreen->setChecked(win->exclusiveFullScreen());
  9433. m_UI->actionExclusiveFullScreen->blockSignals(false);
  9434. m_UI->actionShowCursor3DCoordinates->blockSignals(true);
  9435. m_UI->actionShowCursor3DCoordinates->setChecked(win->cursorCoordinatesShown());
  9436. m_UI->actionShowCursor3DCoordinates->blockSignals(false);
  9437. m_UI->actionAutoPickRotationCenter->blockSignals(true);
  9438. m_UI->actionAutoPickRotationCenter->setChecked(win->autoPickPivotAtCenter());
  9439. m_UI->actionAutoPickRotationCenter->blockSignals(false);
  9440. }
  9441. m_UI->actionLockRotationAxis->setEnabled(win != nullptr);
  9442. m_UI->actionEnableStereo->setEnabled(win != nullptr);
  9443. m_UI->actionExclusiveFullScreen->setEnabled(win != nullptr);
  9444. }
  9445. void MainWindow::updateViewModePopUpMenu(ccGLWindowInterface* win)
  9446. {
  9447. if (!m_viewModePopupButton)
  9448. return;
  9449. //update the view mode pop-up 'top' icon
  9450. if (win)
  9451. {
  9452. bool objectCentered = true;
  9453. bool perspectiveEnabled = win->getPerspectiveState(objectCentered);
  9454. QAction* currentModeAction = nullptr;
  9455. if (!perspectiveEnabled)
  9456. {
  9457. currentModeAction = m_UI->actionSetOrthoView;
  9458. }
  9459. else if (objectCentered)
  9460. {
  9461. currentModeAction = m_UI->actionSetCenteredPerspectiveView;
  9462. }
  9463. else
  9464. {
  9465. currentModeAction = m_UI->actionSetViewerPerspectiveView;
  9466. }
  9467. assert(currentModeAction);
  9468. m_viewModePopupButton->setIcon(currentModeAction->icon());
  9469. m_viewModePopupButton->setEnabled(true);
  9470. }
  9471. else
  9472. {
  9473. m_viewModePopupButton->setIcon(QIcon());
  9474. m_viewModePopupButton->setEnabled(false);
  9475. }
  9476. }
  9477. void MainWindow::updatePivotVisibilityPopUpMenu(ccGLWindowInterface* win)
  9478. {
  9479. if (!m_pivotVisibilityPopupButton)
  9480. return;
  9481. //update the pivot visibility pop-up 'top' icon
  9482. if (win)
  9483. {
  9484. QAction* visibilityAction = nullptr;
  9485. switch(win->getPivotVisibility())
  9486. {
  9487. case ccGLWindowInterface::PIVOT_HIDE:
  9488. visibilityAction = m_UI->actionSetPivotOff;
  9489. break;
  9490. case ccGLWindowInterface::PIVOT_SHOW_ON_MOVE:
  9491. visibilityAction = m_UI->actionSetPivotRotationOnly;
  9492. break;
  9493. case ccGLWindowInterface::PIVOT_ALWAYS_SHOW:
  9494. visibilityAction = m_UI->actionSetPivotAlwaysOn;
  9495. break;
  9496. default:
  9497. assert(false);
  9498. }
  9499. if (visibilityAction)
  9500. m_pivotVisibilityPopupButton->setIcon(visibilityAction->icon());
  9501. //pivot is not available in viewer-based perspective!
  9502. bool objectCentered = true;
  9503. win->getPerspectiveState(objectCentered);
  9504. m_pivotVisibilityPopupButton->setEnabled(objectCentered);
  9505. }
  9506. else
  9507. {
  9508. m_pivotVisibilityPopupButton->setIcon(QIcon());
  9509. m_pivotVisibilityPopupButton->setEnabled(false);
  9510. }
  9511. }
  9512. void MainWindow::updateMenus()
  9513. {
  9514. ccGLWindowInterface* active3DView = getActiveGLWindow();
  9515. bool hasMdiChild = (active3DView != nullptr);
  9516. int mdiChildCount = getGLWindowCount();
  9517. bool hasLoadedEntities = (m_ccRoot && m_ccRoot->getRootEntity() && m_ccRoot->getRootEntity()->getChildrenNumber() != 0);
  9518. bool hasSelectedEntities = (m_ccRoot && m_ccRoot->countSelectedEntities() > 0);
  9519. //General Menu
  9520. m_UI->menuEdit->setEnabled(true/*hasSelectedEntities*/);
  9521. m_UI->menuTools->setEnabled(true/*hasSelectedEntities*/);
  9522. //3D Views Menu
  9523. m_UI->actionClose3DView ->setEnabled(hasMdiChild);
  9524. m_UI->actionCloseAll3DViews->setEnabled(mdiChildCount != 0);
  9525. m_UI->actionTile3DViews ->setEnabled(mdiChildCount > 1);
  9526. m_UI->actionCascade3DViews ->setEnabled(mdiChildCount > 1);
  9527. m_UI->actionNext3DView ->setEnabled(mdiChildCount > 1);
  9528. m_UI->actionPrevious3DView ->setEnabled(mdiChildCount > 1);
  9529. //Shaders & Filters display Menu
  9530. bool shadersEnabled = (active3DView ? active3DView->areShadersEnabled() : false);
  9531. m_UI->actionLoadShader->setEnabled(shadersEnabled);
  9532. m_UI->actionDeleteShader->setEnabled(shadersEnabled);
  9533. //View Menu
  9534. m_UI->toolBarView->setEnabled(hasMdiChild);
  9535. //oher actions
  9536. m_UI->actionSegment->setEnabled(hasMdiChild && hasSelectedEntities);
  9537. m_UI->actionTranslateRotate->setEnabled(hasMdiChild && hasSelectedEntities);
  9538. m_UI->actionPointPicking->setEnabled(hasMdiChild && hasLoadedEntities);
  9539. m_UI->actionTestFrameRate->setEnabled(hasMdiChild);
  9540. m_UI->actionRenderToFile->setEnabled(hasMdiChild);
  9541. m_UI->actionToggleSunLight->setEnabled(hasMdiChild);
  9542. m_UI->actionToggleCustomLight->setEnabled(hasMdiChild);
  9543. m_UI->actionToggleCenteredPerspective->setEnabled(hasMdiChild);
  9544. m_UI->actionToggleViewerBasedPerspective->setEnabled(hasMdiChild);
  9545. //plugins
  9546. m_pluginUIManager->updateMenus();
  9547. }
  9548. void MainWindow::update3DViewsMenu()
  9549. {
  9550. m_UI->menu3DViews->clear();
  9551. m_UI->menu3DViews->addAction(m_UI->actionNew3DView);
  9552. m_UI->menu3DViews->addSeparator();
  9553. m_UI->menu3DViews->addAction(m_UI->actionZoomIn);
  9554. m_UI->menu3DViews->addAction(m_UI->actionZoomOut);
  9555. m_UI->menu3DViews->addSeparator();
  9556. m_UI->menu3DViews->addAction(m_UI->actionClose3DView);
  9557. m_UI->menu3DViews->addAction(m_UI->actionCloseAll3DViews);
  9558. m_UI->menu3DViews->addSeparator();
  9559. m_UI->menu3DViews->addAction(m_UI->actionTile3DViews);
  9560. m_UI->menu3DViews->addAction(m_UI->actionCascade3DViews);
  9561. m_UI->menu3DViews->addSeparator();
  9562. m_UI->menu3DViews->addAction(m_UI->actionNext3DView);
  9563. m_UI->menu3DViews->addAction(m_UI->actionPrevious3DView);
  9564. QList<QMdiSubWindow *> windows = m_mdiArea->subWindowList();
  9565. if (!windows.isEmpty())
  9566. {
  9567. //Dynamic Separator
  9568. QAction* separator = new QAction(this);
  9569. separator->setSeparator(true);
  9570. m_UI->menu3DViews->addAction(separator);
  9571. int i = 0;
  9572. for ( QMdiSubWindow* window : windows )
  9573. {
  9574. ccGLWindowInterface *child = ccGLWindowInterface::FromWidget(window->widget());
  9575. QString text = QString("&%1 %2").arg(++i).arg(child->getWindowTitle());
  9576. QAction *action = m_UI->menu3DViews->addAction(text);
  9577. action->setCheckable(true);
  9578. action->setChecked(child == getActiveGLWindow());
  9579. connect(action, &QAction::triggered, this, [=] () {
  9580. setActiveSubWindow( window );
  9581. } );
  9582. }
  9583. }
  9584. }
  9585. void MainWindow::setActiveSubWindow(QWidget *window)
  9586. {
  9587. if (!window || !m_mdiArea)
  9588. return;
  9589. m_mdiArea->setActiveSubWindow(qobject_cast<QMdiSubWindow*>(window));
  9590. }
  9591. void MainWindow::redrawAll(bool only2D/*=false*/)
  9592. {
  9593. for (QMdiSubWindow* window : m_mdiArea->subWindowList())
  9594. {
  9595. ccGLWindowInterface::FromWidget(window->widget())->redraw(only2D);
  9596. }
  9597. }
  9598. void MainWindow::refreshAll(bool only2D/*=false*/)
  9599. {
  9600. for (QMdiSubWindow* window : m_mdiArea->subWindowList())
  9601. {
  9602. ccGLWindowInterface::FromWidget(window->widget())->refresh(only2D);
  9603. }
  9604. }
  9605. void MainWindow::updateUI()
  9606. {
  9607. updateUIWithSelection();
  9608. updateMenus();
  9609. updatePropertiesView();
  9610. }
  9611. void MainWindow::updatePropertiesView()
  9612. {
  9613. if (m_ccRoot)
  9614. {
  9615. m_ccRoot->updatePropertiesView();
  9616. }
  9617. }
  9618. void MainWindow::updateUIWithSelection()
  9619. {
  9620. dbTreeSelectionInfo selInfo;
  9621. m_selectedEntities.clear();
  9622. if (m_ccRoot)
  9623. {
  9624. m_ccRoot->getSelectedEntities(m_selectedEntities, CC_TYPES::OBJECT, &selInfo);
  9625. }
  9626. enableUIItems(selInfo);
  9627. }
  9628. void MainWindow::enableAll()
  9629. {
  9630. for ( QMdiSubWindow* window : m_mdiArea->subWindowList() )
  9631. {
  9632. window->setEnabled( true );
  9633. }
  9634. }
  9635. void MainWindow::disableAll()
  9636. {
  9637. for ( QMdiSubWindow* window : m_mdiArea->subWindowList() )
  9638. {
  9639. window->setEnabled( false );
  9640. }
  9641. }
  9642. void MainWindow::disableAllBut(ccGLWindowInterface* win)
  9643. {
  9644. //we disable all other windows
  9645. for ( QMdiSubWindow* window : m_mdiArea->subWindowList() )
  9646. {
  9647. if (ccGLWindowInterface::FromWidget(window->widget()) != win)
  9648. {
  9649. window->setEnabled(false);
  9650. }
  9651. }
  9652. }
  9653. void MainWindow::enableUIItems(dbTreeSelectionInfo& selInfo)
  9654. {
  9655. bool dbIsEmpty = (!m_ccRoot || !m_ccRoot->getRootEntity() || m_ccRoot->getRootEntity()->getChildrenNumber() == 0);
  9656. bool atLeastOneEntity = (selInfo.selCount > 0);
  9657. bool atLeastOneCloud = (selInfo.cloudCount > 0);
  9658. bool atLeastOneMesh = (selInfo.meshCount > 0);
  9659. bool atLeastOnePrimitive = (selInfo.primitiveCount > 0);
  9660. //bool atLeastOneOctree = (selInfo.octreeCount > 0);
  9661. bool atLeastOneNormal = (selInfo.normalsCount > 0);
  9662. bool atLeastOneColor = (selInfo.colorCount > 0);
  9663. bool atLeastOneSF = (selInfo.sfCount > 0);
  9664. bool atLeastOneGrid = (selInfo.gridCound > 0);
  9665. //bool atLeastOneSensor = (selInfo.sensorCount > 0);
  9666. bool atLeastOneGBLSensor = (selInfo.gblSensorCount > 0);
  9667. bool atLeastOneCameraSensor = (selInfo.cameraSensorCount > 0);
  9668. bool atLeastOnePolyline = (selInfo.polylineCount > 0);
  9669. bool activeWindow = (getActiveGLWindow() != nullptr);
  9670. //menuEdit->setEnabled(atLeastOneEntity);
  9671. //menuTools->setEnabled(atLeastOneEntity);
  9672. m_UI->actionTracePolyline->setEnabled(!dbIsEmpty);
  9673. m_UI->actionZoomAndCenter->setEnabled(atLeastOneEntity && activeWindow);
  9674. m_UI->actionSave->setEnabled(atLeastOneEntity);
  9675. m_UI->actionSaveProject->setEnabled(!dbIsEmpty);
  9676. m_UI->actionClone->setEnabled(atLeastOneEntity);
  9677. m_UI->actionDelete->setEnabled(atLeastOneEntity);
  9678. m_UI->actionExportCoordToSF->setEnabled(atLeastOneEntity);
  9679. m_UI->actionExportNormalToSF->setEnabled(atLeastOneNormal);
  9680. m_UI->actionSegment->setEnabled(atLeastOneEntity && activeWindow);
  9681. m_UI->actionTranslateRotate->setEnabled(atLeastOneEntity && activeWindow);
  9682. m_UI->actionShowDepthBuffer->setEnabled(atLeastOneGBLSensor);
  9683. m_UI->actionExportDepthBuffer->setEnabled(atLeastOneGBLSensor);
  9684. m_UI->actionComputePointsVisibility->setEnabled(atLeastOneGBLSensor);
  9685. m_UI->actionResampleWithOctree->setEnabled(atLeastOneCloud);
  9686. m_UI->actionApplyScale->setEnabled(atLeastOneCloud || atLeastOneMesh || atLeastOnePolyline);
  9687. m_UI->actionApplyTransformation->setEnabled(atLeastOneEntity);
  9688. m_UI->actionComputeOctree->setEnabled(atLeastOneCloud || atLeastOneMesh);
  9689. m_UI->actionComputeNormals->setEnabled(atLeastOneCloud || atLeastOneMesh);
  9690. m_UI->actionChangeColorLevels->setEnabled(atLeastOneCloud || atLeastOneMesh);
  9691. m_UI->actionEditGlobalShiftAndScale->setEnabled(atLeastOneCloud || atLeastOneMesh || atLeastOnePolyline);
  9692. m_UI->actionCrop->setEnabled(atLeastOneCloud || atLeastOneMesh);
  9693. m_UI->actionSetUniqueColor->setEnabled(atLeastOneEntity/*atLeastOneCloud || atLeastOneMesh*/); //DGM: we can set color to a group now!
  9694. m_UI->actionSetColorGradient->setEnabled(atLeastOneCloud || atLeastOneMesh);
  9695. m_UI->actionColorize->setEnabled(atLeastOneEntity/*atLeastOneCloud || atLeastOneMesh*/); //DGM: we can set color to a group now!
  9696. m_UI->actionDeleteScanGrid->setEnabled(atLeastOneGrid);
  9697. m_UI->actionScalarFieldFromColor->setEnabled(atLeastOneEntity && atLeastOneColor);
  9698. m_UI->actionComputeMeshAA->setEnabled(atLeastOneCloud);
  9699. m_UI->actionComputeMeshLS->setEnabled(atLeastOneCloud);
  9700. m_UI->actionMeshScanGrids->setEnabled(atLeastOneGrid);
  9701. //actionComputeQuadric3D->setEnabled(atLeastOneCloud);
  9702. m_UI->actionComputeBestFitBB->setEnabled(atLeastOneEntity);
  9703. m_UI->actionComputeGeometricFeature->setEnabled(atLeastOneCloud);
  9704. m_UI->actionRemoveDuplicatePoints->setEnabled(atLeastOneCloud);
  9705. m_UI->actionFitPlane->setEnabled(atLeastOneEntity);
  9706. m_UI->actionFitPlaneProxy->setEnabled(atLeastOneEntity);
  9707. m_UI->actionFitSphere->setEnabled(atLeastOneCloud);
  9708. m_UI->actionFitCircle->setEnabled(atLeastOneCloud);
  9709. m_UI->actionLevel->setEnabled(atLeastOneEntity);
  9710. m_UI->actionFitFacet->setEnabled(atLeastOneEntity);
  9711. m_UI->actionFitQuadric->setEnabled(atLeastOneCloud);
  9712. m_UI->actionSubsample->setEnabled(atLeastOneCloud);
  9713. m_UI->actionSNETest->setEnabled(atLeastOneCloud);
  9714. m_UI->actionExportCloudInfo->setEnabled(atLeastOneEntity);
  9715. m_UI->actionExportPlaneInfo->setEnabled(atLeastOneEntity);
  9716. m_UI->actionFilterByValue->setEnabled(atLeastOneSF);
  9717. m_UI->actionConvertToRGB->setEnabled(atLeastOneSF);
  9718. m_UI->actionConvertToRandomRGB->setEnabled(atLeastOneSF);
  9719. m_UI->actionRenameSF->setEnabled(atLeastOneSF);
  9720. m_UI->actionAddIdField->setEnabled(atLeastOneCloud);
  9721. m_UI->actionSplitCloudUsingSF->setEnabled(atLeastOneSF);
  9722. m_UI->actionComputeStatParams->setEnabled(atLeastOneSF);
  9723. m_UI->actionComputeStatParams2->setEnabled(atLeastOneSF);
  9724. m_UI->actionShowHistogram->setEnabled(atLeastOneSF);
  9725. m_UI->actionGaussianFilter->setEnabled(atLeastOneSF);
  9726. m_UI->actionBilateralFilter->setEnabled(atLeastOneSF);
  9727. m_UI->actionDeleteScalarField->setEnabled(atLeastOneSF);
  9728. m_UI->actionDeleteAllSF->setEnabled(atLeastOneSF);
  9729. m_UI->actionMultiplySF->setEnabled(/*TODO: atLeastOneSF*/false);
  9730. m_UI->actionSFGradient->setEnabled(atLeastOneSF);
  9731. m_UI->actionSetSFAsCoord->setEnabled(atLeastOneSF && atLeastOneCloud);
  9732. m_UI->actionInterpolateSFs->setEnabled(atLeastOneCloud || atLeastOneMesh);
  9733. m_UI->actionSamplePointsOnMesh->setEnabled(atLeastOneMesh);
  9734. m_UI->actionMeasureMeshSurface->setEnabled(atLeastOneMesh);
  9735. m_UI->actionMeasureMeshVolume->setEnabled(atLeastOneMesh);
  9736. m_UI->actionFlagMeshVertices->setEnabled(atLeastOneMesh);
  9737. m_UI->actionSmoothMeshLaplacian->setEnabled(atLeastOneMesh);
  9738. m_UI->actionConvertTextureToColor->setEnabled(atLeastOneMesh);
  9739. m_UI->actionSubdivideMesh->setEnabled(atLeastOneMesh);
  9740. m_UI->actionFlipMeshTriangles->setEnabled(atLeastOneMesh);
  9741. m_UI->actionDistanceToBestFitQuadric3D->setEnabled(atLeastOneCloud);
  9742. m_UI->actionDistanceMap->setEnabled(atLeastOneMesh || atLeastOneCloud);
  9743. m_UI->menuMeshScalarField->setEnabled(atLeastOneSF && atLeastOneMesh);
  9744. //actionSmoothMeshSF->setEnabled(atLeastOneSF && atLeastOneMesh);
  9745. //actionEnhanceMeshSF->setEnabled(atLeastOneSF && atLeastOneMesh);
  9746. m_UI->actionOrientNormalsMST->setEnabled(atLeastOneCloud && atLeastOneNormal);
  9747. m_UI->actionOrientNormalsFM->setEnabled(atLeastOneCloud && atLeastOneNormal);
  9748. m_UI->actionShiftPointsAlongNormals->setEnabled(atLeastOneCloud && atLeastOneNormal);
  9749. m_UI->actionClearNormals->setEnabled(atLeastOneNormal);
  9750. m_UI->actionInvertNormals->setEnabled(atLeastOneNormal);
  9751. m_UI->actionConvertNormalToHSV->setEnabled(atLeastOneNormal);
  9752. m_UI->actionConvertNormalToDipDir->setEnabled(atLeastOneNormal);
  9753. m_UI->actionClearColor->setEnabled(atLeastOneColor);
  9754. m_UI->actionRGBToGreyScale->setEnabled(atLeastOneColor);
  9755. m_UI->actionEnhanceRGBWithIntensities->setEnabled(atLeastOneColor);
  9756. m_UI->actionRGBGaussianFilter->setEnabled(atLeastOneColor);
  9757. m_UI->actionRGBBilateralFilter->setEnabled(atLeastOneColor);
  9758. m_UI->actionRGBMeanFilter->setEnabled(atLeastOneColor);
  9759. m_UI->actionRGBMedianFilter->setEnabled(atLeastOneColor);
  9760. m_UI->actionColorFromScalarField->setEnabled(atLeastOneSF);
  9761. // == 1
  9762. bool exactlyOneEntity = (selInfo.selCount == 1);
  9763. bool exactlyOneGroup = (selInfo.groupCount == 1);
  9764. bool exactlyOneCloud = (selInfo.cloudCount == 1);
  9765. bool exactlyOneMesh = (selInfo.meshCount == 1);
  9766. bool exactlyOneSF = (selInfo.sfCount == 1);
  9767. bool exactlyOneSensor = (selInfo.sensorCount == 1);
  9768. bool exactlyOneCameraSensor = (selInfo.cameraSensorCount == 1);
  9769. m_UI->actionConvertPolylinesToMesh->setEnabled(atLeastOnePolyline || exactlyOneGroup);
  9770. m_UI->actionSamplePointsOnPolyline->setEnabled(atLeastOnePolyline);
  9771. m_UI->actionSmoothPolyline->setEnabled(atLeastOnePolyline);
  9772. m_UI->actionMeshTwoPolylines->setEnabled(selInfo.selCount == 2 && selInfo.polylineCount == 2);
  9773. m_UI->actionCreateSurfaceBetweenTwoPolylines->setEnabled(m_UI->actionMeshTwoPolylines->isEnabled()); //clone of actionMeshTwoPolylines
  9774. m_UI->actionModifySensor->setEnabled(exactlyOneSensor);
  9775. m_UI->actionComputeDistancesFromSensor->setEnabled(atLeastOneCameraSensor || atLeastOneGBLSensor);
  9776. m_UI->actionComputeScatteringAngles->setEnabled(exactlyOneSensor);
  9777. m_UI->actionViewFromSensor->setEnabled(exactlyOneSensor);
  9778. m_UI->actionCreateGBLSensor->setEnabled(atLeastOneCloud);
  9779. m_UI->actionCreateCameraSensor->setEnabled(selInfo.selCount <= 1); //free now
  9780. m_UI->actionProjectUncertainty->setEnabled(exactlyOneCameraSensor);
  9781. m_UI->actionCheckPointsInsideFrustum->setEnabled(exactlyOneCameraSensor);
  9782. m_UI->actionLabelConnectedComponents->setEnabled(atLeastOneCloud);
  9783. m_UI->actionSORFilter->setEnabled(atLeastOneCloud);
  9784. m_UI->actionNoiseFilter->setEnabled(atLeastOneCloud);
  9785. m_UI->actionUnroll->setEnabled(exactlyOneEntity);
  9786. m_UI->actionStatisticalTest->setEnabled(exactlyOneEntity && exactlyOneSF);
  9787. m_UI->actionAddConstantSF->setEnabled(exactlyOneCloud || exactlyOneMesh);
  9788. m_UI->actionAddClassificationSF->setEnabled(exactlyOneCloud || exactlyOneMesh);
  9789. m_UI->actionEditGlobalScale->setEnabled(exactlyOneCloud || exactlyOneMesh);
  9790. m_UI->actionComputeKdTree->setEnabled(exactlyOneCloud || exactlyOneMesh);
  9791. m_UI->actionSetSFsAsNormal->setEnabled(exactlyOneCloud || exactlyOneMesh);
  9792. m_UI->actionShowWaveDialog->setEnabled(exactlyOneCloud);
  9793. m_UI->actionCompressFWFData->setEnabled(atLeastOneCloud);
  9794. m_UI->actionKMeans->setEnabled(/*TODO: exactlyOneEntity && exactlyOneSF*/false);
  9795. m_UI->actionFrontPropagation->setEnabled(/*TODO: exactlyOneEntity && exactlyOneSF*/false);
  9796. //actionCreatePlane->setEnabled(true);
  9797. m_UI->actionEditPlane->setEnabled(selInfo.planeCount == 1);
  9798. m_UI->actionFlipPlane->setEnabled(selInfo.planeCount != 0);
  9799. m_UI->actionComparePlanes->setEnabled(selInfo.planeCount == 2);
  9800. m_UI->actionFindBiggestInnerRectangle->setEnabled(exactlyOneCloud);
  9801. m_UI->menuActiveScalarField->setEnabled((exactlyOneCloud || exactlyOneMesh) && selInfo.sfCount > 0);
  9802. m_UI->actionCrossSection->setEnabled(atLeastOneCloud || atLeastOneMesh || (selInfo.groupCount != 0));
  9803. m_UI->actionExtractSections->setEnabled(atLeastOneCloud);
  9804. m_UI->actionRasterize->setEnabled(exactlyOneCloud);
  9805. m_UI->actionCompute2HalfDimVolume->setEnabled(selInfo.cloudCount == selInfo.selCount && selInfo.cloudCount >= 1 && selInfo.cloudCount <= 2); //one or two clouds!
  9806. m_UI->actionPointListPicking->setEnabled(exactlyOneCloud || exactlyOneMesh);
  9807. // == 2
  9808. bool exactlyTwoEntities = (selInfo.selCount == 2);
  9809. bool exactlyTwoClouds = (selInfo.cloudCount == 2);
  9810. //bool exactlyTwoSF = (selInfo.sfCount == 2);
  9811. m_UI->actionRegister->setEnabled(exactlyTwoEntities);
  9812. m_UI->actionInterpolateColors->setEnabled(exactlyTwoEntities && atLeastOneColor);
  9813. m_UI->actionPointPairsAlign->setEnabled(atLeastOneEntity);
  9814. m_UI->actionBBCenterToOrigin->setEnabled(atLeastOneEntity);
  9815. m_UI->actionBBMinCornerToOrigin->setEnabled(atLeastOneEntity);
  9816. m_UI->actionBBMaxCornerToOrigin->setEnabled(atLeastOneEntity);
  9817. m_UI->actionAlign->setEnabled(exactlyTwoEntities); //Aurelien BEY le 13/11/2008
  9818. m_UI->actionCloudCloudDist->setEnabled(exactlyTwoClouds);
  9819. m_UI->actionCloudMeshDist->setEnabled(exactlyTwoEntities && atLeastOneMesh);
  9820. m_UI->actionCloudPrimitiveDist->setEnabled(atLeastOneCloud && (atLeastOnePrimitive || atLeastOnePolyline));
  9821. m_UI->actionCPS->setEnabled(exactlyTwoClouds);
  9822. m_UI->actionScalarFieldArithmetic->setEnabled(exactlyOneEntity && atLeastOneSF);
  9823. //>1
  9824. bool atLeastTwoEntities = (selInfo.selCount > 1);
  9825. m_UI->actionMerge->setEnabled(atLeastTwoEntities);
  9826. m_UI->actionMatchBBCenters->setEnabled(atLeastTwoEntities);
  9827. m_UI->actionMatchScales->setEnabled(atLeastTwoEntities);
  9828. //standard plugins
  9829. m_pluginUIManager->handleSelectionChanged();
  9830. }
  9831. void MainWindow::echoMouseWheelRotate(float wheelDelta_deg)
  9832. {
  9833. if (!m_UI->actionEnableCameraLink->isChecked())
  9834. return;
  9835. ccGLWindowInterface* sendingWindow = ccGLWindowInterface::FromEmitter(sender());
  9836. if (!sendingWindow)
  9837. return;
  9838. for ( QMdiSubWindow* window : m_mdiArea->subWindowList() )
  9839. {
  9840. ccGLWindowInterface* child = ccGLWindowInterface::FromWidget(window->widget());
  9841. if (child != sendingWindow)
  9842. {
  9843. child->signalEmitter()->blockSignals(true);
  9844. child->onWheelEvent(wheelDelta_deg);
  9845. child->signalEmitter()->blockSignals(false);
  9846. child->redraw();
  9847. }
  9848. }
  9849. }
  9850. void MainWindow::echoBaseViewMatRotation(const ccGLMatrixd& rotMat)
  9851. {
  9852. if (!m_UI->actionEnableCameraLink->isChecked())
  9853. return;
  9854. ccGLWindowInterface* sendingWindow = ccGLWindowInterface::FromEmitter(sender());
  9855. if (!sendingWindow)
  9856. return;
  9857. for ( QMdiSubWindow* window : m_mdiArea->subWindowList() )
  9858. {
  9859. ccGLWindowInterface* child = ccGLWindowInterface::FromWidget(window->widget());
  9860. if (child != sendingWindow)
  9861. {
  9862. child->signalEmitter()->blockSignals(true);
  9863. child->rotateBaseViewMat(rotMat);
  9864. child->signalEmitter()->blockSignals(false);
  9865. child->redraw();
  9866. }
  9867. }
  9868. }
  9869. void MainWindow::echoCameraPosChanged(const CCVector3d& P)
  9870. {
  9871. if (!m_UI->actionEnableCameraLink->isChecked())
  9872. return;
  9873. ccGLWindowInterface* sendingWindow = ccGLWindowInterface::FromEmitter(sender());
  9874. if (!sendingWindow)
  9875. return;
  9876. for ( QMdiSubWindow* window : m_mdiArea->subWindowList() )
  9877. {
  9878. ccGLWindowInterface* child = ccGLWindowInterface::FromWidget(window->widget());
  9879. if (child != sendingWindow)
  9880. {
  9881. child->signalEmitter()->blockSignals(true);
  9882. child->setCameraPos(P);
  9883. child->signalEmitter()->blockSignals(false);
  9884. child->redraw();
  9885. }
  9886. }
  9887. }
  9888. void MainWindow::echoPivotPointChanged(const CCVector3d& P)
  9889. {
  9890. if (!m_UI->actionEnableCameraLink->isChecked())
  9891. return;
  9892. ccGLWindowInterface* sendingWindow = ccGLWindowInterface::FromEmitter(sender());
  9893. if (!sendingWindow)
  9894. return;
  9895. for ( QMdiSubWindow* window : m_mdiArea->subWindowList() )
  9896. {
  9897. ccGLWindowInterface* child = ccGLWindowInterface::FromWidget(window->widget());
  9898. if (child != sendingWindow)
  9899. {
  9900. child->signalEmitter()->blockSignals(true);
  9901. child->setPivotPoint(P);
  9902. child->signalEmitter()->blockSignals(false);
  9903. child->redraw();
  9904. }
  9905. }
  9906. }
  9907. void MainWindow::dispToConsole(QString message, ConsoleMessageLevel level/*=STD_CONSOLE_MESSAGE*/)
  9908. {
  9909. switch(level)
  9910. {
  9911. case STD_CONSOLE_MESSAGE:
  9912. ccConsole::Print(message);
  9913. break;
  9914. case WRN_CONSOLE_MESSAGE:
  9915. ccConsole::Warning(message);
  9916. break;
  9917. case ERR_CONSOLE_MESSAGE:
  9918. ccConsole::Error(message);
  9919. break;
  9920. }
  9921. }
  9922. void MainWindow::doActionLoadShader() //TODO
  9923. {
  9924. ccConsole::Error(tr("Not yet implemented! Sorry ..."));
  9925. }
  9926. void MainWindow::doActionKMeans()//TODO
  9927. {
  9928. ccConsole::Error(tr("Not yet implemented! Sorry ..."));
  9929. }
  9930. void MainWindow::doActionFrontPropagation() //TODO
  9931. {
  9932. ccConsole::Error(tr("Not yet implemented! Sorry ..."));
  9933. }
  9934. /************** STATIC METHODS ******************/
  9935. MainWindow* MainWindow::TheInstance()
  9936. {
  9937. if (!s_instance)
  9938. s_instance = new MainWindow();
  9939. return s_instance;
  9940. }
  9941. void MainWindow::DestroyInstance()
  9942. {
  9943. delete s_instance;
  9944. s_instance=nullptr;
  9945. }
  9946. void MainWindow::GetGLWindows(std::vector<ccGLWindowInterface*>& glWindows)
  9947. {
  9948. const QList<QMdiSubWindow*> windows = TheInstance()->m_mdiArea->subWindowList();
  9949. if ( windows.empty() )
  9950. return;
  9951. glWindows.clear();
  9952. glWindows.reserve( windows.size() );
  9953. for ( QMdiSubWindow* window : windows )
  9954. {
  9955. glWindows.push_back(ccGLWindowInterface::FromWidget(window->widget()));
  9956. }
  9957. }
  9958. ccGLWindowInterface* MainWindow::GetActiveGLWindow()
  9959. {
  9960. return TheInstance()->getActiveGLWindow();
  9961. }
  9962. ccGLWindowInterface* MainWindow::GetGLWindow(const QString& title)
  9963. {
  9964. const QList<QMdiSubWindow *> windows = TheInstance()->m_mdiArea->subWindowList();
  9965. if ( windows.empty() )
  9966. return nullptr;
  9967. for ( QMdiSubWindow* window : windows )
  9968. {
  9969. ccGLWindowInterface* win = ccGLWindowInterface::FromWidget(window->widget());
  9970. if (win->getWindowTitle() == title)
  9971. return win;
  9972. }
  9973. return nullptr;
  9974. }
  9975. void MainWindow::RefreshAllGLWindow(bool only2D/*=false*/)
  9976. {
  9977. TheInstance()->refreshAll(only2D);
  9978. }
  9979. void MainWindow::UpdateUI()
  9980. {
  9981. TheInstance()->updateUI();
  9982. }
  9983. ccDBRoot* MainWindow::db()
  9984. {
  9985. return m_ccRoot;
  9986. }
  9987. void MainWindow::addEditPlaneAction( QMenu &menu ) const
  9988. {
  9989. menu.addAction( m_UI->actionEditPlane );
  9990. }
  9991. ccHObject* MainWindow::dbRootObject()
  9992. {
  9993. return (m_ccRoot ? m_ccRoot->getRootEntity() : nullptr);
  9994. }
  9995. ccUniqueIDGenerator::Shared MainWindow::getUniqueIDGenerator()
  9996. {
  9997. return ccObject::GetUniqueIDGenerator();
  9998. }
  9999. void MainWindow::createGLWindow(ccGLWindowInterface*& window, QWidget*& widget) const
  10000. {
  10001. bool stereoMode = ccGLWindowInterface::TestStereoSupport();
  10002. ccGLWindowInterface::Create(window, widget, stereoMode);
  10003. assert(window && widget);
  10004. }
  10005. void MainWindow::destroyGLWindow(ccGLWindowInterface* view3D) const
  10006. {
  10007. if (view3D)
  10008. {
  10009. view3D->asQObject()->setParent(nullptr);
  10010. delete view3D;
  10011. }
  10012. }
  10013. ccMainAppInterface::ccHObjectContext MainWindow::removeObjectTemporarilyFromDBTree(ccHObject* obj)
  10014. {
  10015. ccHObjectContext context;
  10016. assert(obj);
  10017. if (!m_ccRoot || !obj)
  10018. return context;
  10019. //mandatory (to call putObjectBackIntoDBTree)
  10020. context.parent = obj->getParent();
  10021. //remove the object's dependency to its father (in case it undergoes 'severe' modifications)
  10022. if (context.parent)
  10023. {
  10024. context.parentFlags = context.parent->getDependencyFlagsWith(obj);
  10025. context.childFlags = obj->getDependencyFlagsWith(context.parent);
  10026. context.parent->removeDependencyWith(obj);
  10027. obj->removeDependencyWith(context.parent);
  10028. }
  10029. m_ccRoot->removeElement(obj);
  10030. return context;
  10031. }
  10032. void MainWindow::putObjectBackIntoDBTree(ccHObject* obj, const ccHObjectContext& context)
  10033. {
  10034. assert(obj);
  10035. if (!obj || !m_ccRoot)
  10036. return;
  10037. if (context.parent)
  10038. {
  10039. context.parent->addChild(obj,context.parentFlags);
  10040. obj->addDependency(context.parent,context.childFlags);
  10041. }
  10042. //DGM: we must call 'notifyGeometryUpdate' as any call to this method
  10043. //while the object was temporarily 'cut' from the DB tree were
  10044. //ineffective!
  10045. obj->notifyGeometryUpdate();
  10046. m_ccRoot->addElement(obj,false);
  10047. }
  10048. void MainWindow::doActionGlobalShiftSeetings()
  10049. {
  10050. QDialog dialog(this);
  10051. Ui_GlobalShiftSettingsDialog ui;
  10052. ui.setupUi(&dialog);
  10053. ui.maxAbsCoordSpinBox->setValue(static_cast<int>(log10(ccGlobalShiftManager::MaxCoordinateAbsValue())));
  10054. ui.maxAbsDiagSpinBox->setValue(static_cast<int>(log10(ccGlobalShiftManager::MaxBoundgBoxDiagonal())));
  10055. if (!dialog.exec())
  10056. {
  10057. return;
  10058. }
  10059. double maxAbsCoord = pow(10.0, static_cast<double>(ui.maxAbsCoordSpinBox->value()));
  10060. double maxAbsDiag = pow(10.0, static_cast<double>(ui.maxAbsDiagSpinBox->value()));
  10061. ccGlobalShiftManager::SetMaxCoordinateAbsValue(maxAbsCoord);
  10062. ccGlobalShiftManager::SetMaxBoundgBoxDiagonal(maxAbsDiag);
  10063. ccLog::Print(tr("[Global Shift] Max abs. coord = %1 / max abs. diag = %2")
  10064. .arg(ccGlobalShiftManager::MaxCoordinateAbsValue(), 0, 'e', 0)
  10065. .arg(ccGlobalShiftManager::MaxBoundgBoxDiagonal(), 0, 'e', 0));
  10066. //save to persistent settings
  10067. {
  10068. QSettings settings;
  10069. settings.beginGroup(ccPS::GlobalShift());
  10070. settings.setValue(ccPS::MaxAbsCoord(), maxAbsCoord);
  10071. settings.setValue(ccPS::MaxAbsDiag(), maxAbsDiag);
  10072. settings.endGroup();
  10073. }
  10074. }
  10075. void MainWindow::doActionCompressFWFData()
  10076. {
  10077. for ( ccHObject *entity : getSelectedEntities() )
  10078. {
  10079. if (!entity || !entity->isKindOf(CC_TYPES::POINT_CLOUD))
  10080. {
  10081. continue;
  10082. }
  10083. ccPointCloud* cloud = static_cast<ccPointCloud*>(entity);
  10084. cloud->compressFWFData();
  10085. }
  10086. }
  10087. void MainWindow::doActionShowWaveDialog()
  10088. {
  10089. if (!haveSelection())
  10090. return;
  10091. ccHObject* entity = haveOneSelection() ? m_selectedEntities.front() : nullptr;
  10092. if (!entity || !entity->isKindOf(CC_TYPES::POINT_CLOUD))
  10093. {
  10094. ccConsole::Error(tr("Select one point cloud!"));
  10095. return;
  10096. }
  10097. ccPointCloud* cloud = static_cast<ccPointCloud*>(entity);
  10098. if (!cloud->hasFWF())
  10099. {
  10100. ccConsole::Error(tr("Cloud has no associated waveform information"));
  10101. return;
  10102. }
  10103. ccWaveDialog* wDlg = new ccWaveDialog(cloud, m_pickingHub, this);
  10104. wDlg->setAttribute(Qt::WA_DeleteOnClose);
  10105. wDlg->setModal(false);
  10106. wDlg->show();
  10107. }
  10108. void MainWindow::doActionCreatePlane()
  10109. {
  10110. ccPlaneEditDlg* peDlg = new ccPlaneEditDlg(m_pickingHub, this);
  10111. peDlg->show();
  10112. }
  10113. void MainWindow::doActionEditPlane()
  10114. {
  10115. if (!haveSelection())
  10116. {
  10117. assert(false);
  10118. return;
  10119. }
  10120. ccPlane* plane = ccHObjectCaster::ToPlane(m_selectedEntities.front());
  10121. if (!plane)
  10122. {
  10123. assert(false);
  10124. return;
  10125. }
  10126. ccPlaneEditDlg* peDlg = new ccPlaneEditDlg(m_pickingHub, this);
  10127. peDlg->initWithPlane(plane);
  10128. peDlg->show();
  10129. }
  10130. void MainWindow::doActionFlipPlane()
  10131. {
  10132. if (!haveSelection())
  10133. {
  10134. assert(false);
  10135. return;
  10136. }
  10137. for (ccHObject* entity : m_selectedEntities)
  10138. {
  10139. ccPlane* plane = ccHObjectCaster::ToPlane(entity);
  10140. if (plane)
  10141. {
  10142. plane->flip();
  10143. plane->prepareDisplayForRefresh();
  10144. }
  10145. }
  10146. refreshAll();
  10147. updatePropertiesView();
  10148. }
  10149. void MainWindow::doActionComparePlanes()
  10150. {
  10151. if (m_selectedEntities.size() != 2)
  10152. {
  10153. ccConsole::Error(tr("Select 2 planes!"));
  10154. return;
  10155. }
  10156. if (!m_selectedEntities.front()->isKindOf(CC_TYPES::PLANE) ||
  10157. !m_selectedEntities.back()->isKindOf(CC_TYPES::PLANE))
  10158. {
  10159. ccConsole::Error(tr("Select 2 planes!"));
  10160. return;
  10161. }
  10162. ccPlane* p1 = ccHObjectCaster::ToPlane(m_selectedEntities.front());
  10163. ccPlane* p2 = ccHObjectCaster::ToPlane(m_selectedEntities.back());
  10164. QStringList info;
  10165. info << tr("Plane 1: %1").arg(p1->getName());
  10166. ccLog::Print(tr("[Compare] ") + info.last());
  10167. info << tr("Plane 2: %1").arg(p2->getName());
  10168. ccLog::Print(tr("[Compare] ") + info.last());
  10169. CCVector3 N1;
  10170. CCVector3 N2;
  10171. PointCoordinateType d1;
  10172. PointCoordinateType d2;
  10173. p1->getEquation(N1, d1);
  10174. p2->getEquation(N2, d2);
  10175. double angle_rad = N1.angle_rad(N2);
  10176. info << tr("Angle P1/P2: %1 deg.").arg( CCCoreLib::RadiansToDegrees( angle_rad ) );
  10177. ccLog::Print(tr("[Compare] ") + info.last());
  10178. PointCoordinateType planeEq1[4] = { N1.x, N1.y, N1.z, d1 };
  10179. PointCoordinateType planeEq2[4] = { N2.x, N2.y, N2.z, d2 };
  10180. CCVector3 C1 = p1->getCenter();
  10181. ScalarType distCenter1ToPlane2 = CCCoreLib::DistanceComputationTools::computePoint2PlaneDistance(&C1, planeEq2);
  10182. info << tr("Distance Center(P1)/P2: %1").arg(distCenter1ToPlane2);
  10183. ccLog::Print(tr("[Compare] ") + info.last());
  10184. CCVector3 C2 = p2->getCenter();
  10185. ScalarType distCenter2ToPlane1 = CCCoreLib::DistanceComputationTools::computePoint2PlaneDistance(&C2, planeEq1);
  10186. info << tr("Distance Center(P2)/P1: %1").arg(distCenter2ToPlane1);
  10187. ccLog::Print(tr("[Compare] ") + info.last());
  10188. //pop-up summary
  10189. QMessageBox::information(this, tr("Plane comparison"), info.join("\n"));
  10190. forceConsoleDisplay();
  10191. }