node_3d_editor_plugin.cpp 330 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954
  1. /**************************************************************************/
  2. /* node_3d_editor_plugin.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "node_3d_editor_plugin.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/input/input.h"
  33. #include "core/input/input_map.h"
  34. #include "core/math/math_funcs.h"
  35. #include "core/math/projection.h"
  36. #include "core/os/keyboard.h"
  37. #include "editor/debugger/editor_debugger_node.h"
  38. #include "editor/editor_node.h"
  39. #include "editor/editor_settings.h"
  40. #include "editor/editor_string_names.h"
  41. #include "editor/editor_undo_redo_manager.h"
  42. #include "editor/gui/editor_run_bar.h"
  43. #include "editor/gui/editor_spin_slider.h"
  44. #include "editor/plugins/animation_player_editor_plugin.h"
  45. #include "editor/plugins/gizmos/audio_listener_3d_gizmo_plugin.h"
  46. #include "editor/plugins/gizmos/audio_stream_player_3d_gizmo_plugin.h"
  47. #include "editor/plugins/gizmos/camera_3d_gizmo_plugin.h"
  48. #include "editor/plugins/gizmos/collision_object_3d_gizmo_plugin.h"
  49. #include "editor/plugins/gizmos/collision_polygon_3d_gizmo_plugin.h"
  50. #include "editor/plugins/gizmos/collision_shape_3d_gizmo_plugin.h"
  51. #include "editor/plugins/gizmos/cpu_particles_3d_gizmo_plugin.h"
  52. #include "editor/plugins/gizmos/decal_gizmo_plugin.h"
  53. #include "editor/plugins/gizmos/fog_volume_gizmo_plugin.h"
  54. #include "editor/plugins/gizmos/gpu_particles_3d_gizmo_plugin.h"
  55. #include "editor/plugins/gizmos/gpu_particles_collision_3d_gizmo_plugin.h"
  56. #include "editor/plugins/gizmos/joint_3d_gizmo_plugin.h"
  57. #include "editor/plugins/gizmos/label_3d_gizmo_plugin.h"
  58. #include "editor/plugins/gizmos/light_3d_gizmo_plugin.h"
  59. #include "editor/plugins/gizmos/lightmap_gi_gizmo_plugin.h"
  60. #include "editor/plugins/gizmos/lightmap_probe_gizmo_plugin.h"
  61. #include "editor/plugins/gizmos/marker_3d_gizmo_plugin.h"
  62. #include "editor/plugins/gizmos/mesh_instance_3d_gizmo_plugin.h"
  63. #include "editor/plugins/gizmos/navigation_link_3d_gizmo_plugin.h"
  64. #include "editor/plugins/gizmos/navigation_region_3d_gizmo_plugin.h"
  65. #include "editor/plugins/gizmos/occluder_instance_3d_gizmo_plugin.h"
  66. #include "editor/plugins/gizmos/physics_bone_3d_gizmo_plugin.h"
  67. #include "editor/plugins/gizmos/ray_cast_3d_gizmo_plugin.h"
  68. #include "editor/plugins/gizmos/reflection_probe_gizmo_plugin.h"
  69. #include "editor/plugins/gizmos/shape_cast_3d_gizmo_plugin.h"
  70. #include "editor/plugins/gizmos/soft_body_3d_gizmo_plugin.h"
  71. #include "editor/plugins/gizmos/spring_arm_3d_gizmo_plugin.h"
  72. #include "editor/plugins/gizmos/sprite_3d_gizmo_plugin.h"
  73. #include "editor/plugins/gizmos/vehicle_body_3d_gizmo_plugin.h"
  74. #include "editor/plugins/gizmos/visible_on_screen_notifier_3d_gizmo_plugin.h"
  75. #include "editor/plugins/gizmos/voxel_gi_gizmo_plugin.h"
  76. #include "editor/plugins/node_3d_editor_gizmos.h"
  77. #include "editor/scene_tree_dock.h"
  78. #include "scene/3d/camera_3d.h"
  79. #include "scene/3d/collision_shape_3d.h"
  80. #include "scene/3d/decal.h"
  81. #include "scene/3d/light_3d.h"
  82. #include "scene/3d/mesh_instance_3d.h"
  83. #include "scene/3d/physics_body_3d.h"
  84. #include "scene/3d/visual_instance_3d.h"
  85. #include "scene/3d/world_environment.h"
  86. #include "scene/gui/center_container.h"
  87. #include "scene/gui/color_picker.h"
  88. #include "scene/gui/flow_container.h"
  89. #include "scene/gui/split_container.h"
  90. #include "scene/gui/subviewport_container.h"
  91. #include "scene/resources/packed_scene.h"
  92. #include "scene/resources/sky_material.h"
  93. #include "scene/resources/surface_tool.h"
  94. constexpr real_t DISTANCE_DEFAULT = 4;
  95. constexpr real_t GIZMO_ARROW_SIZE = 0.35;
  96. constexpr real_t GIZMO_RING_HALF_WIDTH = 0.1;
  97. constexpr real_t GIZMO_PLANE_SIZE = 0.2;
  98. constexpr real_t GIZMO_PLANE_DST = 0.3;
  99. constexpr real_t GIZMO_CIRCLE_SIZE = 1.1;
  100. constexpr real_t GIZMO_SCALE_OFFSET = GIZMO_CIRCLE_SIZE + 0.3;
  101. constexpr real_t GIZMO_ARROW_OFFSET = GIZMO_CIRCLE_SIZE + 0.3;
  102. constexpr real_t ZOOM_FREELOOK_MIN = 0.01;
  103. constexpr real_t ZOOM_FREELOOK_MULTIPLIER = 1.08;
  104. constexpr real_t ZOOM_FREELOOK_INDICATOR_DELAY_S = 1.5;
  105. #ifdef REAL_T_IS_DOUBLE
  106. constexpr double ZOOM_FREELOOK_MAX = 1'000'000'000'000;
  107. #else
  108. constexpr float ZOOM_FREELOOK_MAX = 10'000;
  109. #endif
  110. constexpr real_t MIN_Z = 0.01;
  111. constexpr real_t MAX_Z = 1000000.0;
  112. constexpr real_t MIN_FOV = 0.01;
  113. constexpr real_t MAX_FOV = 179;
  114. void ViewportNavigationControl::_notification(int p_what) {
  115. switch (p_what) {
  116. case NOTIFICATION_ENTER_TREE: {
  117. if (!is_connected("mouse_exited", callable_mp(this, &ViewportNavigationControl::_on_mouse_exited))) {
  118. connect("mouse_exited", callable_mp(this, &ViewportNavigationControl::_on_mouse_exited));
  119. }
  120. if (!is_connected("mouse_entered", callable_mp(this, &ViewportNavigationControl::_on_mouse_entered))) {
  121. connect("mouse_entered", callable_mp(this, &ViewportNavigationControl::_on_mouse_entered));
  122. }
  123. } break;
  124. case NOTIFICATION_DRAW: {
  125. if (viewport != nullptr) {
  126. _draw();
  127. _update_navigation();
  128. }
  129. } break;
  130. }
  131. }
  132. void ViewportNavigationControl::_draw() {
  133. if (nav_mode == Node3DEditorViewport::NAVIGATION_NONE) {
  134. return;
  135. }
  136. Vector2 center = get_size() / 2.0;
  137. float radius = get_size().x / 2.0;
  138. const bool focused = focused_index != -1;
  139. draw_circle(center, radius, Color(0.5, 0.5, 0.5, focused || hovered ? 0.35 : 0.15));
  140. const Color c = focused ? Color(0.9, 0.9, 0.9, 0.9) : Color(0.5, 0.5, 0.5, 0.25);
  141. Vector2 circle_pos = focused ? center.move_toward(focused_pos, radius) : center;
  142. draw_circle(circle_pos, AXIS_CIRCLE_RADIUS, c);
  143. draw_circle(circle_pos, AXIS_CIRCLE_RADIUS * 0.8, c.darkened(0.4));
  144. }
  145. void ViewportNavigationControl::_process_click(int p_index, Vector2 p_position, bool p_pressed) {
  146. hovered = false;
  147. queue_redraw();
  148. if (focused_index != -1 && focused_index != p_index) {
  149. return;
  150. }
  151. if (p_pressed) {
  152. if (p_position.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
  153. focused_pos = p_position;
  154. focused_index = p_index;
  155. queue_redraw();
  156. }
  157. } else {
  158. focused_index = -1;
  159. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
  160. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  161. Input::get_singleton()->warp_mouse(focused_mouse_start);
  162. }
  163. }
  164. }
  165. void ViewportNavigationControl::_process_drag(int p_index, Vector2 p_position, Vector2 p_relative_position) {
  166. if (focused_index == p_index) {
  167. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_VISIBLE) {
  168. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
  169. focused_mouse_start = p_position;
  170. }
  171. focused_pos += p_relative_position;
  172. queue_redraw();
  173. }
  174. }
  175. void ViewportNavigationControl::gui_input(const Ref<InputEvent> &p_event) {
  176. // Mouse events
  177. const Ref<InputEventMouseButton> mouse_button = p_event;
  178. if (mouse_button.is_valid() && mouse_button->get_button_index() == MouseButton::LEFT) {
  179. _process_click(100, mouse_button->get_position(), mouse_button->is_pressed());
  180. }
  181. const Ref<InputEventMouseMotion> mouse_motion = p_event;
  182. if (mouse_motion.is_valid()) {
  183. _process_drag(100, mouse_motion->get_global_position(), viewport->_get_warped_mouse_motion(mouse_motion));
  184. }
  185. // Touch events
  186. const Ref<InputEventScreenTouch> screen_touch = p_event;
  187. if (screen_touch.is_valid()) {
  188. _process_click(screen_touch->get_index(), screen_touch->get_position(), screen_touch->is_pressed());
  189. }
  190. const Ref<InputEventScreenDrag> screen_drag = p_event;
  191. if (screen_drag.is_valid()) {
  192. _process_drag(screen_drag->get_index(), screen_drag->get_position(), screen_drag->get_relative());
  193. }
  194. }
  195. void ViewportNavigationControl::_update_navigation() {
  196. if (focused_index == -1) {
  197. return;
  198. }
  199. Vector2 delta = focused_pos - (get_size() / 2.0);
  200. Vector2 delta_normalized = delta.normalized();
  201. switch (nav_mode) {
  202. case Node3DEditorViewport::NavigationMode::NAVIGATION_MOVE: {
  203. real_t speed_multiplier = MIN(delta.length() / (get_size().x * 100.0), 3.0);
  204. real_t speed = viewport->freelook_speed * speed_multiplier;
  205. const Node3DEditorViewport::FreelookNavigationScheme navigation_scheme = (Node3DEditorViewport::FreelookNavigationScheme)EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_navigation_scheme").operator int();
  206. Vector3 forward;
  207. if (navigation_scheme == Node3DEditorViewport::FreelookNavigationScheme::FREELOOK_FULLY_AXIS_LOCKED) {
  208. // Forward/backward keys will always go straight forward/backward, never moving on the Y axis.
  209. forward = Vector3(0, 0, delta_normalized.y).rotated(Vector3(0, 1, 0), viewport->camera->get_rotation().y);
  210. } else {
  211. // Forward/backward keys will be relative to the camera pitch.
  212. forward = viewport->camera->get_transform().basis.xform(Vector3(0, 0, delta_normalized.y));
  213. }
  214. const Vector3 right = viewport->camera->get_transform().basis.xform(Vector3(delta_normalized.x, 0, 0));
  215. const Vector3 direction = forward + right;
  216. const Vector3 motion = direction * speed;
  217. viewport->cursor.pos += motion;
  218. viewport->cursor.eye_pos += motion;
  219. } break;
  220. case Node3DEditorViewport::NavigationMode::NAVIGATION_LOOK: {
  221. real_t speed_multiplier = MIN(delta.length() / (get_size().x * 2.5), 3.0);
  222. real_t speed = viewport->freelook_speed * speed_multiplier;
  223. viewport->_nav_look(nullptr, delta_normalized * speed);
  224. } break;
  225. case Node3DEditorViewport::NAVIGATION_PAN: {
  226. real_t speed_multiplier = MIN(delta.length() / (get_size().x), 3.0);
  227. real_t speed = viewport->freelook_speed * speed_multiplier;
  228. viewport->_nav_pan(nullptr, -delta_normalized * speed);
  229. } break;
  230. case Node3DEditorViewport::NAVIGATION_ZOOM: {
  231. real_t speed_multiplier = MIN(delta.length() / (get_size().x), 3.0);
  232. real_t speed = viewport->freelook_speed * speed_multiplier;
  233. viewport->_nav_zoom(nullptr, delta_normalized * speed);
  234. } break;
  235. case Node3DEditorViewport::NAVIGATION_ORBIT: {
  236. real_t speed_multiplier = MIN(delta.length() / (get_size().x), 3.0);
  237. real_t speed = viewport->freelook_speed * speed_multiplier;
  238. viewport->_nav_orbit(nullptr, delta_normalized * speed);
  239. } break;
  240. case Node3DEditorViewport::NAVIGATION_NONE: {
  241. } break;
  242. }
  243. }
  244. void ViewportNavigationControl::_on_mouse_entered() {
  245. hovered = true;
  246. queue_redraw();
  247. }
  248. void ViewportNavigationControl::_on_mouse_exited() {
  249. hovered = false;
  250. queue_redraw();
  251. }
  252. void ViewportNavigationControl::set_navigation_mode(Node3DEditorViewport::NavigationMode p_nav_mode) {
  253. nav_mode = p_nav_mode;
  254. }
  255. void ViewportNavigationControl::set_viewport(Node3DEditorViewport *p_viewport) {
  256. viewport = p_viewport;
  257. }
  258. void ViewportRotationControl::_notification(int p_what) {
  259. switch (p_what) {
  260. case NOTIFICATION_ENTER_TREE: {
  261. axis_menu_options.clear();
  262. axis_menu_options.push_back(Node3DEditorViewport::VIEW_RIGHT);
  263. axis_menu_options.push_back(Node3DEditorViewport::VIEW_TOP);
  264. axis_menu_options.push_back(Node3DEditorViewport::VIEW_FRONT);
  265. axis_menu_options.push_back(Node3DEditorViewport::VIEW_LEFT);
  266. axis_menu_options.push_back(Node3DEditorViewport::VIEW_BOTTOM);
  267. axis_menu_options.push_back(Node3DEditorViewport::VIEW_REAR);
  268. axis_colors.clear();
  269. axis_colors.push_back(get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor)));
  270. axis_colors.push_back(get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor)));
  271. axis_colors.push_back(get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor)));
  272. queue_redraw();
  273. if (!is_connected("mouse_exited", callable_mp(this, &ViewportRotationControl::_on_mouse_exited))) {
  274. connect("mouse_exited", callable_mp(this, &ViewportRotationControl::_on_mouse_exited));
  275. }
  276. } break;
  277. case NOTIFICATION_DRAW: {
  278. if (viewport != nullptr) {
  279. _draw();
  280. }
  281. } break;
  282. }
  283. }
  284. void ViewportRotationControl::_draw() {
  285. const Vector2i center = get_size() / 2.0;
  286. const real_t radius = get_size().x / 2.0;
  287. if (focused_axis > -2 || orbiting_index != -1) {
  288. draw_circle(center, radius, Color(0.5, 0.5, 0.5, 0.25));
  289. }
  290. Vector<Axis2D> axis_to_draw;
  291. _get_sorted_axis(axis_to_draw);
  292. for (int i = 0; i < axis_to_draw.size(); ++i) {
  293. _draw_axis(axis_to_draw[i]);
  294. }
  295. }
  296. void ViewportRotationControl::_draw_axis(const Axis2D &p_axis) {
  297. const bool focused = focused_axis == p_axis.axis;
  298. const bool positive = p_axis.axis < 3;
  299. const int direction = p_axis.axis % 3;
  300. const Color axis_color = axis_colors[direction];
  301. const double alpha = focused ? 1.0 : ((p_axis.z_axis + 1.0) / 2.0) * 0.5 + 0.5;
  302. const Color c = focused ? Color(0.9, 0.9, 0.9) : Color(axis_color, alpha);
  303. if (positive) {
  304. // Draw axis lines for the positive axes.
  305. const Vector2i center = get_size() / 2.0;
  306. draw_line(center, p_axis.screen_point, c, 1.5 * EDSCALE);
  307. draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS, c);
  308. // Draw the axis letter for the positive axes.
  309. const String axis_name = direction == 0 ? "X" : (direction == 1 ? "Y" : "Z");
  310. draw_char(get_theme_font(SNAME("rotation_control"), EditorStringName(EditorFonts)), p_axis.screen_point + Vector2i(Math::round(-4.0 * EDSCALE), Math::round(5.0 * EDSCALE)), axis_name, get_theme_font_size(SNAME("rotation_control_size"), EditorStringName(EditorFonts)), Color(0.0, 0.0, 0.0, alpha));
  311. } else {
  312. // Draw an outline around the negative axes.
  313. draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS, c);
  314. draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS * 0.8, c.darkened(0.4));
  315. }
  316. }
  317. void ViewportRotationControl::_get_sorted_axis(Vector<Axis2D> &r_axis) {
  318. const Vector2i center = get_size() / 2.0;
  319. const real_t radius = get_size().x / 2.0 - AXIS_CIRCLE_RADIUS - 2.0 * EDSCALE;
  320. const Basis camera_basis = viewport->to_camera_transform(viewport->cursor).get_basis().inverse();
  321. for (int i = 0; i < 3; ++i) {
  322. Vector3 axis_3d = camera_basis.get_column(i);
  323. Vector2i axis_vector = Vector2(axis_3d.x, -axis_3d.y) * radius;
  324. if (Math::abs(axis_3d.z) <= 1.0) {
  325. Axis2D pos_axis;
  326. pos_axis.axis = i;
  327. pos_axis.screen_point = center + axis_vector;
  328. pos_axis.z_axis = axis_3d.z;
  329. r_axis.push_back(pos_axis);
  330. Axis2D neg_axis;
  331. neg_axis.axis = i + 3;
  332. neg_axis.screen_point = center - axis_vector;
  333. neg_axis.z_axis = -axis_3d.z;
  334. r_axis.push_back(neg_axis);
  335. } else {
  336. // Special case when the camera is aligned with one axis
  337. Axis2D axis;
  338. axis.axis = i + (axis_3d.z <= 0 ? 0 : 3);
  339. axis.screen_point = center;
  340. axis.z_axis = 1.0;
  341. r_axis.push_back(axis);
  342. }
  343. }
  344. r_axis.sort_custom<Axis2DCompare>();
  345. }
  346. void ViewportRotationControl::_process_click(int p_index, Vector2 p_position, bool p_pressed) {
  347. if (orbiting_index != -1 && orbiting_index != p_index) {
  348. return;
  349. }
  350. if (p_pressed) {
  351. if (p_position.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
  352. orbiting_index = p_index;
  353. }
  354. } else {
  355. if (focused_axis > -1) {
  356. viewport->_menu_option(axis_menu_options[focused_axis]);
  357. _update_focus();
  358. }
  359. orbiting_index = -1;
  360. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
  361. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  362. Input::get_singleton()->warp_mouse(orbiting_mouse_start);
  363. }
  364. }
  365. }
  366. void ViewportRotationControl::_process_drag(Ref<InputEventWithModifiers> p_event, int p_index, Vector2 p_position, Vector2 p_relative_position) {
  367. if (orbiting_index == p_index) {
  368. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_VISIBLE) {
  369. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
  370. orbiting_mouse_start = p_position;
  371. }
  372. viewport->_nav_orbit(p_event, p_relative_position);
  373. focused_axis = -1;
  374. } else {
  375. _update_focus();
  376. }
  377. }
  378. void ViewportRotationControl::gui_input(const Ref<InputEvent> &p_event) {
  379. ERR_FAIL_COND(p_event.is_null());
  380. // Mouse events
  381. const Ref<InputEventMouseButton> mb = p_event;
  382. if (mb.is_valid() && mb->get_button_index() == MouseButton::LEFT) {
  383. _process_click(100, mb->get_position(), mb->is_pressed());
  384. }
  385. const Ref<InputEventMouseMotion> mm = p_event;
  386. if (mm.is_valid()) {
  387. _process_drag(mm, 100, mm->get_global_position(), viewport->_get_warped_mouse_motion(mm));
  388. }
  389. // Touch events
  390. const Ref<InputEventScreenTouch> screen_touch = p_event;
  391. if (screen_touch.is_valid()) {
  392. _process_click(screen_touch->get_index(), screen_touch->get_position(), screen_touch->is_pressed());
  393. }
  394. const Ref<InputEventScreenDrag> screen_drag = p_event;
  395. if (screen_drag.is_valid()) {
  396. _process_drag(screen_drag, screen_drag->get_index(), screen_drag->get_position(), screen_drag->get_relative());
  397. }
  398. }
  399. void ViewportRotationControl::_update_focus() {
  400. int original_focus = focused_axis;
  401. focused_axis = -2;
  402. Vector2 mouse_pos = get_local_mouse_position();
  403. if (mouse_pos.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
  404. focused_axis = -1;
  405. }
  406. Vector<Axis2D> axes;
  407. _get_sorted_axis(axes);
  408. for (int i = 0; i < axes.size(); i++) {
  409. const Axis2D &axis = axes[i];
  410. if (mouse_pos.distance_to(axis.screen_point) < AXIS_CIRCLE_RADIUS) {
  411. focused_axis = axis.axis;
  412. }
  413. }
  414. if (focused_axis != original_focus) {
  415. queue_redraw();
  416. }
  417. }
  418. void ViewportRotationControl::_on_mouse_exited() {
  419. focused_axis = -2;
  420. queue_redraw();
  421. }
  422. void ViewportRotationControl::set_viewport(Node3DEditorViewport *p_viewport) {
  423. viewport = p_viewport;
  424. }
  425. void Node3DEditorViewport::_view_settings_confirmed(real_t p_interp_delta) {
  426. // Set FOV override multiplier back to the default, so that the FOV
  427. // setting specified in the View menu is correctly applied.
  428. cursor.fov_scale = 1.0;
  429. _update_camera(p_interp_delta);
  430. }
  431. void Node3DEditorViewport::_update_navigation_controls_visibility() {
  432. bool show_viewport_rotation_gizmo = EDITOR_GET("editors/3d/navigation/show_viewport_rotation_gizmo") && (!previewing_cinema && !previewing_camera);
  433. rotation_control->set_visible(show_viewport_rotation_gizmo);
  434. bool show_viewport_navigation_gizmo = EDITOR_GET("editors/3d/navigation/show_viewport_navigation_gizmo") && (!previewing_cinema && !previewing_camera);
  435. position_control->set_visible(show_viewport_navigation_gizmo);
  436. look_control->set_visible(show_viewport_navigation_gizmo);
  437. }
  438. void Node3DEditorViewport::_update_camera(real_t p_interp_delta) {
  439. bool is_orthogonal = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
  440. Cursor old_camera_cursor = camera_cursor;
  441. camera_cursor = cursor;
  442. if (p_interp_delta > 0) {
  443. //-------
  444. // Perform smoothing
  445. if (is_freelook_active()) {
  446. // Higher inertia should increase "lag" (lerp with factor between 0 and 1)
  447. // Inertia of zero should produce instant movement (lerp with factor of 1) in this case it returns a really high value and gets clamped to 1.
  448. const real_t inertia = EDITOR_GET("editors/3d/freelook/freelook_inertia");
  449. real_t factor = (1.0 / inertia) * p_interp_delta;
  450. // We interpolate a different point here, because in freelook mode the focus point (cursor.pos) orbits around eye_pos
  451. camera_cursor.eye_pos = old_camera_cursor.eye_pos.lerp(cursor.eye_pos, CLAMP(factor, 0, 1));
  452. const real_t orbit_inertia = EDITOR_GET("editors/3d/navigation_feel/orbit_inertia");
  453. camera_cursor.x_rot = Math::lerp(old_camera_cursor.x_rot, cursor.x_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  454. camera_cursor.y_rot = Math::lerp(old_camera_cursor.y_rot, cursor.y_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  455. if (Math::abs(camera_cursor.x_rot - cursor.x_rot) < 0.1) {
  456. camera_cursor.x_rot = cursor.x_rot;
  457. }
  458. if (Math::abs(camera_cursor.y_rot - cursor.y_rot) < 0.1) {
  459. camera_cursor.y_rot = cursor.y_rot;
  460. }
  461. Vector3 forward = to_camera_transform(camera_cursor).basis.xform(Vector3(0, 0, -1));
  462. camera_cursor.pos = camera_cursor.eye_pos + forward * camera_cursor.distance;
  463. } else {
  464. const real_t orbit_inertia = EDITOR_GET("editors/3d/navigation_feel/orbit_inertia");
  465. const real_t translation_inertia = EDITOR_GET("editors/3d/navigation_feel/translation_inertia");
  466. const real_t zoom_inertia = EDITOR_GET("editors/3d/navigation_feel/zoom_inertia");
  467. camera_cursor.x_rot = Math::lerp(old_camera_cursor.x_rot, cursor.x_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  468. camera_cursor.y_rot = Math::lerp(old_camera_cursor.y_rot, cursor.y_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  469. if (Math::abs(camera_cursor.x_rot - cursor.x_rot) < 0.1) {
  470. camera_cursor.x_rot = cursor.x_rot;
  471. }
  472. if (Math::abs(camera_cursor.y_rot - cursor.y_rot) < 0.1) {
  473. camera_cursor.y_rot = cursor.y_rot;
  474. }
  475. camera_cursor.pos = old_camera_cursor.pos.lerp(cursor.pos, MIN(1.f, p_interp_delta * (1 / translation_inertia)));
  476. camera_cursor.distance = Math::lerp(old_camera_cursor.distance, cursor.distance, MIN((real_t)1.0, p_interp_delta * (1 / zoom_inertia)));
  477. }
  478. }
  479. //-------
  480. // Apply camera transform
  481. real_t tolerance = 0.001;
  482. bool equal = true;
  483. if (!Math::is_equal_approx(old_camera_cursor.x_rot, camera_cursor.x_rot, tolerance) || !Math::is_equal_approx(old_camera_cursor.y_rot, camera_cursor.y_rot, tolerance)) {
  484. equal = false;
  485. } else if (!old_camera_cursor.pos.is_equal_approx(camera_cursor.pos)) {
  486. equal = false;
  487. } else if (!Math::is_equal_approx(old_camera_cursor.distance, camera_cursor.distance, tolerance)) {
  488. equal = false;
  489. } else if (!Math::is_equal_approx(old_camera_cursor.fov_scale, camera_cursor.fov_scale, tolerance)) {
  490. equal = false;
  491. }
  492. if (!equal || p_interp_delta == 0 || is_orthogonal != orthogonal) {
  493. camera->set_global_transform(to_camera_transform(camera_cursor));
  494. if (orthogonal) {
  495. float half_fov = Math::deg_to_rad(get_fov()) / 2.0;
  496. float height = 2.0 * cursor.distance * Math::tan(half_fov);
  497. camera->set_orthogonal(height, get_znear(), get_zfar());
  498. } else {
  499. camera->set_perspective(get_fov(), get_znear(), get_zfar());
  500. }
  501. update_transform_gizmo_view();
  502. rotation_control->queue_redraw();
  503. position_control->queue_redraw();
  504. look_control->queue_redraw();
  505. spatial_editor->update_grid();
  506. }
  507. }
  508. Transform3D Node3DEditorViewport::to_camera_transform(const Cursor &p_cursor) const {
  509. Transform3D camera_transform;
  510. camera_transform.translate_local(p_cursor.pos);
  511. camera_transform.basis.rotate(Vector3(1, 0, 0), -p_cursor.x_rot);
  512. camera_transform.basis.rotate(Vector3(0, 1, 0), -p_cursor.y_rot);
  513. if (orthogonal) {
  514. camera_transform.translate_local(0, 0, (get_zfar() - get_znear()) / 2.0);
  515. } else {
  516. camera_transform.translate_local(0, 0, p_cursor.distance);
  517. }
  518. return camera_transform;
  519. }
  520. int Node3DEditorViewport::get_selected_count() const {
  521. const HashMap<Node *, Object *> &selection = editor_selection->get_selection();
  522. int count = 0;
  523. for (const KeyValue<Node *, Object *> &E : selection) {
  524. Node3D *sp = Object::cast_to<Node3D>(E.key);
  525. if (!sp) {
  526. continue;
  527. }
  528. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  529. if (!se) {
  530. continue;
  531. }
  532. count++;
  533. }
  534. return count;
  535. }
  536. void Node3DEditorViewport::cancel_transform() {
  537. List<Node *> &selection = editor_selection->get_selected_node_list();
  538. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  539. Node3D *sp = Object::cast_to<Node3D>(E->get());
  540. if (!sp) {
  541. continue;
  542. }
  543. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  544. if (!se) {
  545. continue;
  546. }
  547. sp->set_global_transform(se->original);
  548. }
  549. finish_transform();
  550. set_message(TTR("Transform Aborted."), 3);
  551. }
  552. void Node3DEditorViewport::_update_shrink() {
  553. bool shrink = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION));
  554. subviewport_container->set_stretch_shrink(shrink ? 2 : 1);
  555. subviewport_container->set_texture_filter(shrink ? TEXTURE_FILTER_NEAREST : TEXTURE_FILTER_PARENT_NODE);
  556. }
  557. float Node3DEditorViewport::get_znear() const {
  558. return CLAMP(spatial_editor->get_znear(), MIN_Z, MAX_Z);
  559. }
  560. float Node3DEditorViewport::get_zfar() const {
  561. return CLAMP(spatial_editor->get_zfar(), MIN_Z, MAX_Z);
  562. }
  563. float Node3DEditorViewport::get_fov() const {
  564. return CLAMP(spatial_editor->get_fov() * cursor.fov_scale, MIN_FOV, MAX_FOV);
  565. }
  566. Transform3D Node3DEditorViewport::_get_camera_transform() const {
  567. return camera->get_global_transform();
  568. }
  569. Vector3 Node3DEditorViewport::_get_camera_position() const {
  570. return _get_camera_transform().origin;
  571. }
  572. Point2 Node3DEditorViewport::_point_to_screen(const Vector3 &p_point) {
  573. return camera->unproject_position(p_point) * subviewport_container->get_stretch_shrink();
  574. }
  575. Vector3 Node3DEditorViewport::_get_ray_pos(const Vector2 &p_pos) const {
  576. return camera->project_ray_origin(p_pos / subviewport_container->get_stretch_shrink());
  577. }
  578. Vector3 Node3DEditorViewport::_get_camera_normal() const {
  579. return -_get_camera_transform().basis.get_column(2);
  580. }
  581. Vector3 Node3DEditorViewport::_get_ray(const Vector2 &p_pos) const {
  582. return camera->project_ray_normal(p_pos / subviewport_container->get_stretch_shrink());
  583. }
  584. void Node3DEditorViewport::_clear_selected() {
  585. _edit.gizmo = Ref<EditorNode3DGizmo>();
  586. _edit.gizmo_handle = -1;
  587. _edit.gizmo_handle_secondary = false;
  588. _edit.gizmo_initial_value = Variant();
  589. Node3D *selected = spatial_editor->get_single_selected_node();
  590. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  591. if (se && se->gizmo.is_valid()) {
  592. se->subgizmos.clear();
  593. se->gizmo->redraw();
  594. se->gizmo.unref();
  595. spatial_editor->update_transform_gizmo();
  596. } else {
  597. editor_selection->clear();
  598. Node3DEditor::get_singleton()->edit(nullptr);
  599. }
  600. }
  601. void Node3DEditorViewport::_select_clicked(bool p_allow_locked) {
  602. Node *node = Object::cast_to<Node3D>(ObjectDB::get_instance(clicked));
  603. Node3D *selected = Object::cast_to<Node3D>(node);
  604. clicked = ObjectID();
  605. if (!selected) {
  606. return;
  607. }
  608. if (!p_allow_locked) {
  609. // Replace the node by the group if grouped
  610. while (node && node != EditorNode::get_singleton()->get_edited_scene()->get_parent()) {
  611. Node3D *selected_tmp = Object::cast_to<Node3D>(node);
  612. if (selected_tmp && node->has_meta("_edit_group_")) {
  613. selected = selected_tmp;
  614. }
  615. node = node->get_parent();
  616. }
  617. }
  618. if (p_allow_locked || !_is_node_locked(selected)) {
  619. if (clicked_wants_append) {
  620. if (editor_selection->is_selected(selected)) {
  621. editor_selection->remove_node(selected);
  622. } else {
  623. editor_selection->add_node(selected);
  624. }
  625. } else {
  626. if (!editor_selection->is_selected(selected)) {
  627. editor_selection->clear();
  628. editor_selection->add_node(selected);
  629. EditorNode::get_singleton()->edit_node(selected);
  630. }
  631. }
  632. if (editor_selection->get_selected_node_list().size() == 1) {
  633. EditorNode::get_singleton()->edit_node(editor_selection->get_selected_node_list()[0]);
  634. }
  635. }
  636. }
  637. ObjectID Node3DEditorViewport::_select_ray(const Point2 &p_pos) const {
  638. Vector3 ray = _get_ray(p_pos);
  639. Vector3 pos = _get_ray_pos(p_pos);
  640. Vector2 shrinked_pos = p_pos / subviewport_container->get_stretch_shrink();
  641. if (viewport->get_debug_draw() == Viewport::DEBUG_DRAW_SDFGI_PROBES) {
  642. RS::get_singleton()->sdfgi_set_debug_probe_select(pos, ray);
  643. }
  644. Vector<ObjectID> instances = RenderingServer::get_singleton()->instances_cull_ray(pos, pos + ray * camera->get_far(), get_tree()->get_root()->get_world_3d()->get_scenario());
  645. HashSet<Ref<EditorNode3DGizmo>> found_gizmos;
  646. Node *edited_scene = get_tree()->get_edited_scene_root();
  647. ObjectID closest;
  648. Node *item = nullptr;
  649. float closest_dist = 1e20;
  650. for (int i = 0; i < instances.size(); i++) {
  651. Node3D *spat = Object::cast_to<Node3D>(ObjectDB::get_instance(instances[i]));
  652. if (!spat) {
  653. continue;
  654. }
  655. Vector<Ref<Node3DGizmo>> gizmos = spat->get_gizmos();
  656. for (int j = 0; j < gizmos.size(); j++) {
  657. Ref<EditorNode3DGizmo> seg = gizmos[j];
  658. if ((!seg.is_valid()) || found_gizmos.has(seg)) {
  659. continue;
  660. }
  661. found_gizmos.insert(seg);
  662. Vector3 point;
  663. Vector3 normal;
  664. bool inters = seg->intersect_ray(camera, shrinked_pos, point, normal);
  665. if (!inters) {
  666. continue;
  667. }
  668. const real_t dist = pos.distance_to(point);
  669. if (dist < 0) {
  670. continue;
  671. }
  672. if (dist < closest_dist) {
  673. item = Object::cast_to<Node>(spat);
  674. if (item != edited_scene) {
  675. item = edited_scene->get_deepest_editable_node(item);
  676. }
  677. closest = item->get_instance_id();
  678. closest_dist = dist;
  679. }
  680. }
  681. }
  682. if (!item) {
  683. return ObjectID();
  684. }
  685. return closest;
  686. }
  687. void Node3DEditorViewport::_find_items_at_pos(const Point2 &p_pos, Vector<_RayResult> &r_results, bool p_include_locked_nodes) {
  688. Vector3 ray = _get_ray(p_pos);
  689. Vector3 pos = _get_ray_pos(p_pos);
  690. Vector<ObjectID> instances = RenderingServer::get_singleton()->instances_cull_ray(pos, pos + ray * camera->get_far(), get_tree()->get_root()->get_world_3d()->get_scenario());
  691. HashSet<Node3D *> found_nodes;
  692. for (int i = 0; i < instances.size(); i++) {
  693. Node3D *spat = Object::cast_to<Node3D>(ObjectDB::get_instance(instances[i]));
  694. if (!spat) {
  695. continue;
  696. }
  697. if (found_nodes.has(spat)) {
  698. continue;
  699. }
  700. if (!p_include_locked_nodes && _is_node_locked(spat)) {
  701. continue;
  702. }
  703. Vector<Ref<Node3DGizmo>> gizmos = spat->get_gizmos();
  704. for (int j = 0; j < gizmos.size(); j++) {
  705. Ref<EditorNode3DGizmo> seg = gizmos[j];
  706. if (!seg.is_valid()) {
  707. continue;
  708. }
  709. Vector3 point;
  710. Vector3 normal;
  711. bool inters = seg->intersect_ray(camera, p_pos, point, normal);
  712. if (!inters) {
  713. continue;
  714. }
  715. const real_t dist = pos.distance_to(point);
  716. if (dist < 0) {
  717. continue;
  718. }
  719. found_nodes.insert(spat);
  720. _RayResult res;
  721. res.item = spat;
  722. res.depth = dist;
  723. r_results.push_back(res);
  724. break;
  725. }
  726. }
  727. r_results.sort();
  728. }
  729. Vector3 Node3DEditorViewport::_get_screen_to_space(const Vector3 &p_vector3) {
  730. Projection cm;
  731. if (orthogonal) {
  732. cm.set_orthogonal(camera->get_size(), get_size().aspect(), get_znear() + p_vector3.z, get_zfar());
  733. } else {
  734. cm.set_perspective(get_fov(), get_size().aspect(), get_znear() + p_vector3.z, get_zfar());
  735. }
  736. Vector2 screen_he = cm.get_viewport_half_extents();
  737. Transform3D camera_transform;
  738. camera_transform.translate_local(cursor.pos);
  739. camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
  740. camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
  741. camera_transform.translate_local(0, 0, cursor.distance);
  742. return camera_transform.xform(Vector3(((p_vector3.x / get_size().width) * 2.0 - 1.0) * screen_he.x, ((1.0 - (p_vector3.y / get_size().height)) * 2.0 - 1.0) * screen_he.y, -(get_znear() + p_vector3.z)));
  743. }
  744. void Node3DEditorViewport::_select_region() {
  745. if (cursor.region_begin == cursor.region_end) {
  746. if (!clicked_wants_append) {
  747. _clear_selected();
  748. }
  749. return; //nothing really
  750. }
  751. const real_t z_offset = MAX(0.0, 5.0 - get_znear());
  752. Vector3 box[4] = {
  753. Vector3(
  754. MIN(cursor.region_begin.x, cursor.region_end.x),
  755. MIN(cursor.region_begin.y, cursor.region_end.y),
  756. z_offset),
  757. Vector3(
  758. MAX(cursor.region_begin.x, cursor.region_end.x),
  759. MIN(cursor.region_begin.y, cursor.region_end.y),
  760. z_offset),
  761. Vector3(
  762. MAX(cursor.region_begin.x, cursor.region_end.x),
  763. MAX(cursor.region_begin.y, cursor.region_end.y),
  764. z_offset),
  765. Vector3(
  766. MIN(cursor.region_begin.x, cursor.region_end.x),
  767. MAX(cursor.region_begin.y, cursor.region_end.y),
  768. z_offset)
  769. };
  770. Vector<Plane> frustum;
  771. Vector3 cam_pos = _get_camera_position();
  772. for (int i = 0; i < 4; i++) {
  773. Vector3 a = _get_screen_to_space(box[i]);
  774. Vector3 b = _get_screen_to_space(box[(i + 1) % 4]);
  775. if (orthogonal) {
  776. frustum.push_back(Plane((a - b).normalized(), a));
  777. } else {
  778. frustum.push_back(Plane(a, b, cam_pos));
  779. }
  780. }
  781. Plane near(-_get_camera_normal(), cam_pos);
  782. near.d -= get_znear();
  783. frustum.push_back(near);
  784. Plane far = -near;
  785. far.d += get_zfar();
  786. frustum.push_back(far);
  787. if (spatial_editor->get_single_selected_node()) {
  788. Node3D *single_selected = spatial_editor->get_single_selected_node();
  789. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(single_selected);
  790. if (se) {
  791. Ref<EditorNode3DGizmo> old_gizmo;
  792. if (!clicked_wants_append) {
  793. se->subgizmos.clear();
  794. old_gizmo = se->gizmo;
  795. se->gizmo.unref();
  796. }
  797. bool found_subgizmos = false;
  798. Vector<Ref<Node3DGizmo>> gizmos = single_selected->get_gizmos();
  799. for (int j = 0; j < gizmos.size(); j++) {
  800. Ref<EditorNode3DGizmo> seg = gizmos[j];
  801. if (!seg.is_valid()) {
  802. continue;
  803. }
  804. if (se->gizmo.is_valid() && se->gizmo != seg) {
  805. continue;
  806. }
  807. Vector<int> subgizmos = seg->subgizmos_intersect_frustum(camera, frustum);
  808. if (!subgizmos.is_empty()) {
  809. se->gizmo = seg;
  810. for (int i = 0; i < subgizmos.size(); i++) {
  811. int subgizmo_id = subgizmos[i];
  812. if (!se->subgizmos.has(subgizmo_id)) {
  813. se->subgizmos.insert(subgizmo_id, se->gizmo->get_subgizmo_transform(subgizmo_id));
  814. }
  815. }
  816. found_subgizmos = true;
  817. break;
  818. }
  819. }
  820. if (!clicked_wants_append || found_subgizmos) {
  821. if (se->gizmo.is_valid()) {
  822. se->gizmo->redraw();
  823. }
  824. if (old_gizmo != se->gizmo && old_gizmo.is_valid()) {
  825. old_gizmo->redraw();
  826. }
  827. spatial_editor->update_transform_gizmo();
  828. }
  829. if (found_subgizmos) {
  830. return;
  831. }
  832. }
  833. }
  834. if (!clicked_wants_append) {
  835. _clear_selected();
  836. }
  837. Vector<ObjectID> instances = RenderingServer::get_singleton()->instances_cull_convex(frustum, get_tree()->get_root()->get_world_3d()->get_scenario());
  838. HashSet<Node3D *> found_nodes;
  839. Vector<Node *> selected;
  840. Node *edited_scene = get_tree()->get_edited_scene_root();
  841. for (int i = 0; i < instances.size(); i++) {
  842. Node3D *sp = Object::cast_to<Node3D>(ObjectDB::get_instance(instances[i]));
  843. if (!sp || _is_node_locked(sp)) {
  844. continue;
  845. }
  846. if (found_nodes.has(sp)) {
  847. continue;
  848. }
  849. found_nodes.insert(sp);
  850. Node *item = Object::cast_to<Node>(sp);
  851. if (item != edited_scene) {
  852. item = edited_scene->get_deepest_editable_node(item);
  853. }
  854. // Replace the node by the group if grouped
  855. if (item->is_class("Node3D")) {
  856. Node3D *sel = Object::cast_to<Node3D>(item);
  857. while (item && item != EditorNode::get_singleton()->get_edited_scene()->get_parent()) {
  858. Node3D *selected_tmp = Object::cast_to<Node3D>(item);
  859. if (selected_tmp && item->has_meta("_edit_group_")) {
  860. sel = selected_tmp;
  861. }
  862. item = item->get_parent();
  863. }
  864. item = sel;
  865. }
  866. if (_is_node_locked(item)) {
  867. continue;
  868. }
  869. Vector<Ref<Node3DGizmo>> gizmos = sp->get_gizmos();
  870. for (int j = 0; j < gizmos.size(); j++) {
  871. Ref<EditorNode3DGizmo> seg = gizmos[j];
  872. if (!seg.is_valid()) {
  873. continue;
  874. }
  875. if (seg->intersect_frustum(camera, frustum)) {
  876. selected.push_back(item);
  877. }
  878. }
  879. }
  880. for (int i = 0; i < selected.size(); i++) {
  881. if (!editor_selection->is_selected(selected[i])) {
  882. editor_selection->add_node(selected[i]);
  883. }
  884. }
  885. if (editor_selection->get_selected_node_list().size() == 1) {
  886. EditorNode::get_singleton()->edit_node(editor_selection->get_selected_node_list()[0]);
  887. }
  888. }
  889. void Node3DEditorViewport::_update_name() {
  890. String name;
  891. switch (view_type) {
  892. case VIEW_TYPE_USER: {
  893. if (orthogonal) {
  894. name = TTR("Orthogonal");
  895. } else {
  896. name = TTR("Perspective");
  897. }
  898. } break;
  899. case VIEW_TYPE_TOP: {
  900. if (orthogonal) {
  901. name = TTR("Top Orthogonal");
  902. } else {
  903. name = TTR("Top Perspective");
  904. }
  905. } break;
  906. case VIEW_TYPE_BOTTOM: {
  907. if (orthogonal) {
  908. name = TTR("Bottom Orthogonal");
  909. } else {
  910. name = TTR("Bottom Perspective");
  911. }
  912. } break;
  913. case VIEW_TYPE_LEFT: {
  914. if (orthogonal) {
  915. name = TTR("Left Orthogonal");
  916. } else {
  917. name = TTR("Left Perspective");
  918. }
  919. } break;
  920. case VIEW_TYPE_RIGHT: {
  921. if (orthogonal) {
  922. name = TTR("Right Orthogonal");
  923. } else {
  924. name = TTR("Right Perspective");
  925. }
  926. } break;
  927. case VIEW_TYPE_FRONT: {
  928. if (orthogonal) {
  929. name = TTR("Front Orthogonal");
  930. } else {
  931. name = TTR("Front Perspective");
  932. }
  933. } break;
  934. case VIEW_TYPE_REAR: {
  935. if (orthogonal) {
  936. name = TTR("Rear Orthogonal");
  937. } else {
  938. name = TTR("Rear Perspective");
  939. }
  940. } break;
  941. }
  942. if (auto_orthogonal) {
  943. // TRANSLATORS: This will be appended to the view name when Auto Orthogonal is enabled.
  944. name += TTR(" [auto]");
  945. }
  946. view_menu->set_text(name);
  947. view_menu->reset_size();
  948. }
  949. void Node3DEditorViewport::_compute_edit(const Point2 &p_point) {
  950. _edit.original_local = spatial_editor->are_local_coords_enabled();
  951. _edit.click_ray = _get_ray(p_point);
  952. _edit.click_ray_pos = _get_ray_pos(p_point);
  953. _edit.plane = TRANSFORM_VIEW;
  954. spatial_editor->update_transform_gizmo();
  955. _edit.center = spatial_editor->get_gizmo_transform().origin;
  956. Node3D *selected = spatial_editor->get_single_selected_node();
  957. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  958. if (se && se->gizmo.is_valid()) {
  959. for (const KeyValue<int, Transform3D> &E : se->subgizmos) {
  960. int subgizmo_id = E.key;
  961. se->subgizmos[subgizmo_id] = se->gizmo->get_subgizmo_transform(subgizmo_id);
  962. }
  963. se->original_local = selected->get_transform();
  964. se->original = selected->get_global_transform();
  965. } else {
  966. List<Node *> &selection = editor_selection->get_selected_node_list();
  967. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  968. Node3D *sp = Object::cast_to<Node3D>(E->get());
  969. if (!sp) {
  970. continue;
  971. }
  972. Node3DEditorSelectedItem *sel_item = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  973. if (!sel_item) {
  974. continue;
  975. }
  976. sel_item->original_local = sel_item->sp->get_local_gizmo_transform();
  977. sel_item->original = sel_item->sp->get_global_gizmo_transform();
  978. }
  979. }
  980. }
  981. static Key _get_key_modifier_setting(const String &p_property) {
  982. switch (EDITOR_GET(p_property).operator int()) {
  983. case 0:
  984. return Key::NONE;
  985. case 1:
  986. return Key::SHIFT;
  987. case 2:
  988. return Key::ALT;
  989. case 3:
  990. return Key::META;
  991. case 4:
  992. return Key::CTRL;
  993. }
  994. return Key::NONE;
  995. }
  996. static Key _get_key_modifier(Ref<InputEventWithModifiers> e) {
  997. if (e->is_shift_pressed()) {
  998. return Key::SHIFT;
  999. }
  1000. if (e->is_alt_pressed()) {
  1001. return Key::ALT;
  1002. }
  1003. if (e->is_ctrl_pressed()) {
  1004. return Key::CTRL;
  1005. }
  1006. if (e->is_meta_pressed()) {
  1007. return Key::META;
  1008. }
  1009. return Key::NONE;
  1010. }
  1011. bool Node3DEditorViewport::_transform_gizmo_select(const Vector2 &p_screenpos, bool p_highlight_only) {
  1012. if (!spatial_editor->is_gizmo_visible()) {
  1013. return false;
  1014. }
  1015. if (get_selected_count() == 0) {
  1016. if (p_highlight_only) {
  1017. spatial_editor->select_gizmo_highlight_axis(-1);
  1018. }
  1019. return false;
  1020. }
  1021. Vector3 ray_pos = _get_ray_pos(p_screenpos);
  1022. Vector3 ray = _get_ray(p_screenpos);
  1023. Transform3D gt = spatial_editor->get_gizmo_transform();
  1024. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE) {
  1025. int col_axis = -1;
  1026. real_t col_d = 1e20;
  1027. for (int i = 0; i < 3; i++) {
  1028. const Vector3 grabber_pos = gt.origin + gt.basis.get_column(i).normalized() * gizmo_scale * (GIZMO_ARROW_OFFSET + (GIZMO_ARROW_SIZE * 0.5));
  1029. const real_t grabber_radius = gizmo_scale * GIZMO_ARROW_SIZE;
  1030. Vector3 r;
  1031. if (Geometry3D::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) {
  1032. const real_t d = r.distance_to(ray_pos);
  1033. if (d < col_d) {
  1034. col_d = d;
  1035. col_axis = i;
  1036. }
  1037. }
  1038. }
  1039. bool is_plane_translate = false;
  1040. // plane select
  1041. if (col_axis == -1) {
  1042. col_d = 1e20;
  1043. for (int i = 0; i < 3; i++) {
  1044. Vector3 ivec2 = gt.basis.get_column((i + 1) % 3).normalized();
  1045. Vector3 ivec3 = gt.basis.get_column((i + 2) % 3).normalized();
  1046. // Allow some tolerance to make the plane easier to click,
  1047. // even if the click is actually slightly outside the plane.
  1048. const Vector3 grabber_pos = gt.origin + (ivec2 + ivec3) * gizmo_scale * (GIZMO_PLANE_SIZE + GIZMO_PLANE_DST * 0.6667);
  1049. Vector3 r;
  1050. Plane plane(gt.basis.get_column(i).normalized(), gt.origin);
  1051. if (plane.intersects_ray(ray_pos, ray, &r)) {
  1052. const real_t dist = r.distance_to(grabber_pos);
  1053. // Allow some tolerance to make the plane easier to click,
  1054. // even if the click is actually slightly outside the plane.
  1055. if (dist < (gizmo_scale * GIZMO_PLANE_SIZE * 1.5)) {
  1056. const real_t d = ray_pos.distance_to(r);
  1057. if (d < col_d) {
  1058. col_d = d;
  1059. col_axis = i;
  1060. is_plane_translate = true;
  1061. }
  1062. }
  1063. }
  1064. }
  1065. }
  1066. if (col_axis != -1) {
  1067. if (p_highlight_only) {
  1068. spatial_editor->select_gizmo_highlight_axis(col_axis + (is_plane_translate ? 6 : 0));
  1069. } else {
  1070. //handle plane translate
  1071. _edit.mode = TRANSFORM_TRANSLATE;
  1072. _compute_edit(p_screenpos);
  1073. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis + (is_plane_translate ? 3 : 0));
  1074. }
  1075. return true;
  1076. }
  1077. }
  1078. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE) {
  1079. int col_axis = -1;
  1080. Vector3 hit_position;
  1081. Vector3 hit_normal;
  1082. real_t ray_length = gt.origin.distance_to(ray_pos) + (GIZMO_CIRCLE_SIZE * gizmo_scale) * 4.0f;
  1083. if (Geometry3D::segment_intersects_sphere(ray_pos, ray_pos + ray * ray_length, gt.origin, gizmo_scale * (GIZMO_CIRCLE_SIZE), &hit_position, &hit_normal)) {
  1084. if (hit_normal.dot(_get_camera_normal()) < 0.05) {
  1085. hit_position = gt.xform_inv(hit_position).abs();
  1086. int min_axis = hit_position.min_axis_index();
  1087. if (hit_position[min_axis] < gizmo_scale * GIZMO_RING_HALF_WIDTH) {
  1088. col_axis = min_axis;
  1089. }
  1090. }
  1091. }
  1092. if (col_axis == -1) {
  1093. float col_d = 1e20;
  1094. for (int i = 0; i < 3; i++) {
  1095. Plane plane(gt.basis.get_column(i).normalized(), gt.origin);
  1096. Vector3 r;
  1097. if (!plane.intersects_ray(ray_pos, ray, &r)) {
  1098. continue;
  1099. }
  1100. const real_t dist = r.distance_to(gt.origin);
  1101. const Vector3 r_dir = (r - gt.origin).normalized();
  1102. if (_get_camera_normal().dot(r_dir) <= 0.005) {
  1103. if (dist > gizmo_scale * (GIZMO_CIRCLE_SIZE - GIZMO_RING_HALF_WIDTH) && dist < gizmo_scale * (GIZMO_CIRCLE_SIZE + GIZMO_RING_HALF_WIDTH)) {
  1104. const real_t d = ray_pos.distance_to(r);
  1105. if (d < col_d) {
  1106. col_d = d;
  1107. col_axis = i;
  1108. }
  1109. }
  1110. }
  1111. }
  1112. }
  1113. if (col_axis != -1) {
  1114. if (p_highlight_only) {
  1115. spatial_editor->select_gizmo_highlight_axis(col_axis + 3);
  1116. } else {
  1117. //handle rotate
  1118. _edit.mode = TRANSFORM_ROTATE;
  1119. _compute_edit(p_screenpos);
  1120. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis);
  1121. }
  1122. return true;
  1123. }
  1124. }
  1125. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE) {
  1126. int col_axis = -1;
  1127. float col_d = 1e20;
  1128. for (int i = 0; i < 3; i++) {
  1129. const Vector3 grabber_pos = gt.origin + gt.basis.get_column(i).normalized() * gizmo_scale * GIZMO_SCALE_OFFSET;
  1130. const real_t grabber_radius = gizmo_scale * GIZMO_ARROW_SIZE;
  1131. Vector3 r;
  1132. if (Geometry3D::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) {
  1133. const real_t d = r.distance_to(ray_pos);
  1134. if (d < col_d) {
  1135. col_d = d;
  1136. col_axis = i;
  1137. }
  1138. }
  1139. }
  1140. bool is_plane_scale = false;
  1141. // plane select
  1142. if (col_axis == -1) {
  1143. col_d = 1e20;
  1144. for (int i = 0; i < 3; i++) {
  1145. const Vector3 ivec2 = gt.basis.get_column((i + 1) % 3).normalized();
  1146. const Vector3 ivec3 = gt.basis.get_column((i + 2) % 3).normalized();
  1147. // Allow some tolerance to make the plane easier to click,
  1148. // even if the click is actually slightly outside the plane.
  1149. const Vector3 grabber_pos = gt.origin + (ivec2 + ivec3) * gizmo_scale * (GIZMO_PLANE_SIZE + GIZMO_PLANE_DST * 0.6667);
  1150. Vector3 r;
  1151. Plane plane(gt.basis.get_column(i).normalized(), gt.origin);
  1152. if (plane.intersects_ray(ray_pos, ray, &r)) {
  1153. const real_t dist = r.distance_to(grabber_pos);
  1154. // Allow some tolerance to make the plane easier to click,
  1155. // even if the click is actually slightly outside the plane.
  1156. if (dist < (gizmo_scale * GIZMO_PLANE_SIZE * 1.5)) {
  1157. const real_t d = ray_pos.distance_to(r);
  1158. if (d < col_d) {
  1159. col_d = d;
  1160. col_axis = i;
  1161. is_plane_scale = true;
  1162. }
  1163. }
  1164. }
  1165. }
  1166. }
  1167. if (col_axis != -1) {
  1168. if (p_highlight_only) {
  1169. spatial_editor->select_gizmo_highlight_axis(col_axis + (is_plane_scale ? 12 : 9));
  1170. } else {
  1171. //handle scale
  1172. _edit.mode = TRANSFORM_SCALE;
  1173. _compute_edit(p_screenpos);
  1174. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis + (is_plane_scale ? 3 : 0));
  1175. }
  1176. return true;
  1177. }
  1178. }
  1179. if (p_highlight_only) {
  1180. spatial_editor->select_gizmo_highlight_axis(-1);
  1181. }
  1182. return false;
  1183. }
  1184. void Node3DEditorViewport::_transform_gizmo_apply(Node3D *p_node, const Transform3D &p_transform, bool p_local) {
  1185. if (p_transform.basis.determinant() == 0) {
  1186. return;
  1187. }
  1188. if (p_local) {
  1189. p_node->set_transform(p_transform);
  1190. } else {
  1191. p_node->set_global_transform(p_transform);
  1192. }
  1193. }
  1194. Transform3D Node3DEditorViewport::_compute_transform(TransformMode p_mode, const Transform3D &p_original, const Transform3D &p_original_local, Vector3 p_motion, double p_extra, bool p_local, bool p_orthogonal) {
  1195. switch (p_mode) {
  1196. case TRANSFORM_SCALE: {
  1197. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1198. p_motion.snap(Vector3(p_extra, p_extra, p_extra));
  1199. }
  1200. Transform3D s;
  1201. if (p_local) {
  1202. s.basis = p_original_local.basis.scaled_local(p_motion + Vector3(1, 1, 1));
  1203. s.origin = p_original_local.origin;
  1204. } else {
  1205. s.basis.scale(p_motion + Vector3(1, 1, 1));
  1206. Transform3D base = Transform3D(Basis(), _edit.center);
  1207. s = base * (s * (base.inverse() * p_original));
  1208. // Recalculate orthogonalized scale without moving origin.
  1209. if (p_orthogonal) {
  1210. s.basis = p_original.basis.scaled_orthogonal(p_motion + Vector3(1, 1, 1));
  1211. }
  1212. }
  1213. return s;
  1214. }
  1215. case TRANSFORM_TRANSLATE: {
  1216. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1217. p_motion.snap(Vector3(p_extra, p_extra, p_extra));
  1218. }
  1219. if (p_local) {
  1220. return p_original_local.translated_local(p_motion);
  1221. }
  1222. return p_original.translated(p_motion);
  1223. }
  1224. case TRANSFORM_ROTATE: {
  1225. Transform3D r;
  1226. if (p_local) {
  1227. Vector3 axis = p_original_local.basis.xform(p_motion);
  1228. r.basis = Basis(axis.normalized(), p_extra) * p_original_local.basis;
  1229. r.origin = p_original_local.origin;
  1230. } else {
  1231. Basis local = p_original.basis * p_original_local.basis.inverse();
  1232. Vector3 axis = local.xform_inv(p_motion);
  1233. r.basis = local * Basis(axis.normalized(), p_extra) * p_original_local.basis;
  1234. r.origin = Basis(p_motion, p_extra).xform(p_original.origin - _edit.center) + _edit.center;
  1235. }
  1236. return r;
  1237. }
  1238. default: {
  1239. ERR_FAIL_V_MSG(Transform3D(), "Invalid mode in '_compute_transform'");
  1240. }
  1241. }
  1242. }
  1243. void Node3DEditorViewport::_surface_mouse_enter() {
  1244. if (!surface->has_focus() && (!get_viewport()->gui_get_focus_owner() || !get_viewport()->gui_get_focus_owner()->is_text_field())) {
  1245. surface->grab_focus();
  1246. }
  1247. }
  1248. void Node3DEditorViewport::_surface_mouse_exit() {
  1249. _remove_preview_node();
  1250. _reset_preview_material();
  1251. _remove_preview_material();
  1252. }
  1253. void Node3DEditorViewport::_surface_focus_enter() {
  1254. view_menu->set_disable_shortcuts(false);
  1255. }
  1256. void Node3DEditorViewport::_surface_focus_exit() {
  1257. view_menu->set_disable_shortcuts(true);
  1258. }
  1259. bool Node3DEditorViewport ::_is_node_locked(const Node *p_node) {
  1260. return p_node->get_meta("_edit_lock_", false);
  1261. }
  1262. void Node3DEditorViewport::_list_select(Ref<InputEventMouseButton> b) {
  1263. _find_items_at_pos(b->get_position(), selection_results, spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT);
  1264. Node *scene = EditorNode::get_singleton()->get_edited_scene();
  1265. for (int i = 0; i < selection_results.size(); i++) {
  1266. Node3D *item = selection_results[i].item;
  1267. if (item != scene && item->get_owner() != scene && item != scene->get_deepest_editable_node(item)) {
  1268. //invalid result
  1269. selection_results.remove_at(i);
  1270. i--;
  1271. }
  1272. }
  1273. clicked_wants_append = b->is_shift_pressed();
  1274. if (selection_results.size() == 1) {
  1275. clicked = selection_results[0].item->get_instance_id();
  1276. selection_results.clear();
  1277. if (clicked.is_valid()) {
  1278. _select_clicked(spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT);
  1279. }
  1280. } else if (!selection_results.is_empty()) {
  1281. NodePath root_path = get_tree()->get_edited_scene_root()->get_path();
  1282. StringName root_name = root_path.get_name(root_path.get_name_count() - 1);
  1283. for (int i = 0; i < selection_results.size(); i++) {
  1284. Node3D *spat = selection_results[i].item;
  1285. Ref<Texture2D> icon = EditorNode::get_singleton()->get_object_icon(spat, "Node");
  1286. String node_path = "/" + root_name + "/" + root_path.rel_path_to(spat->get_path());
  1287. int locked = 0;
  1288. if (_is_node_locked(spat)) {
  1289. locked = 1;
  1290. } else {
  1291. Node *ed_scene = EditorNode::get_singleton()->get_edited_scene();
  1292. Node *node = spat;
  1293. while (node && node != ed_scene->get_parent()) {
  1294. Node3D *selected_tmp = Object::cast_to<Node3D>(node);
  1295. if (selected_tmp && node->has_meta("_edit_group_")) {
  1296. locked = 2;
  1297. }
  1298. node = node->get_parent();
  1299. }
  1300. }
  1301. String suffix;
  1302. if (locked == 1) {
  1303. suffix = " (" + TTR("Locked") + ")";
  1304. } else if (locked == 2) {
  1305. suffix = " (" + TTR("Grouped") + ")";
  1306. }
  1307. selection_menu->add_item((String)spat->get_name() + suffix);
  1308. selection_menu->set_item_icon(i, icon);
  1309. selection_menu->set_item_metadata(i, node_path);
  1310. selection_menu->set_item_tooltip(i, String(spat->get_name()) + "\nType: " + spat->get_class() + "\nPath: " + node_path);
  1311. }
  1312. selection_results_menu = selection_results;
  1313. selection_menu->set_position(get_screen_position() + b->get_position());
  1314. selection_menu->reset_size();
  1315. selection_menu->popup();
  1316. }
  1317. }
  1318. // This is only active during instant transforms,
  1319. // to capture and wrap mouse events outside the control.
  1320. void Node3DEditorViewport::input(const Ref<InputEvent> &p_event) {
  1321. ERR_FAIL_COND(!_edit.instant);
  1322. Ref<InputEventMouseMotion> m = p_event;
  1323. if (m.is_valid()) {
  1324. if (_edit.mode == TRANSFORM_ROTATE) {
  1325. _edit.mouse_pos = m->get_position(); // rotate should not wrap
  1326. } else {
  1327. _edit.mouse_pos += _get_warped_mouse_motion(p_event);
  1328. }
  1329. update_transform(_get_key_modifier(m) == Key::SHIFT);
  1330. }
  1331. }
  1332. void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
  1333. if (previewing) {
  1334. return; //do NONE
  1335. }
  1336. EditorPlugin::AfterGUIInput after = EditorPlugin::AFTER_GUI_INPUT_PASS;
  1337. {
  1338. EditorNode *en = EditorNode::get_singleton();
  1339. EditorPluginList *force_input_forwarding_list = en->get_editor_plugins_force_input_forwarding();
  1340. if (!force_input_forwarding_list->is_empty()) {
  1341. EditorPlugin::AfterGUIInput discard = force_input_forwarding_list->forward_3d_gui_input(camera, p_event, true);
  1342. if (discard == EditorPlugin::AFTER_GUI_INPUT_STOP) {
  1343. return;
  1344. }
  1345. if (discard == EditorPlugin::AFTER_GUI_INPUT_CUSTOM) {
  1346. after = EditorPlugin::AFTER_GUI_INPUT_CUSTOM;
  1347. }
  1348. }
  1349. }
  1350. {
  1351. EditorNode *en = EditorNode::get_singleton();
  1352. EditorPluginList *over_plugin_list = en->get_editor_plugins_over();
  1353. if (!over_plugin_list->is_empty()) {
  1354. EditorPlugin::AfterGUIInput discard = over_plugin_list->forward_3d_gui_input(camera, p_event, false);
  1355. if (discard == EditorPlugin::AFTER_GUI_INPUT_STOP) {
  1356. return;
  1357. }
  1358. if (discard == EditorPlugin::AFTER_GUI_INPUT_CUSTOM) {
  1359. after = EditorPlugin::AFTER_GUI_INPUT_CUSTOM;
  1360. }
  1361. }
  1362. }
  1363. Ref<InputEventMouseButton> b = p_event;
  1364. if (b.is_valid()) {
  1365. emit_signal(SNAME("clicked"), this);
  1366. const real_t zoom_factor = 1 + (ZOOM_FREELOOK_MULTIPLIER - 1) * b->get_factor();
  1367. switch (b->get_button_index()) {
  1368. case MouseButton::WHEEL_UP: {
  1369. if (is_freelook_active()) {
  1370. scale_freelook_speed(zoom_factor);
  1371. } else {
  1372. scale_cursor_distance(1.0 / zoom_factor);
  1373. }
  1374. } break;
  1375. case MouseButton::WHEEL_DOWN: {
  1376. if (is_freelook_active()) {
  1377. scale_freelook_speed(1.0 / zoom_factor);
  1378. } else {
  1379. scale_cursor_distance(zoom_factor);
  1380. }
  1381. } break;
  1382. case MouseButton::RIGHT: {
  1383. NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
  1384. if (b->is_pressed() && _edit.gizmo.is_valid()) {
  1385. //restore
  1386. _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, _edit.gizmo_initial_value, true);
  1387. _edit.gizmo = Ref<EditorNode3DGizmo>();
  1388. }
  1389. if (_edit.mode == TRANSFORM_NONE && b->is_pressed()) {
  1390. if (b->is_alt_pressed()) {
  1391. if (nav_scheme == NAVIGATION_MAYA) {
  1392. break;
  1393. }
  1394. _list_select(b);
  1395. return;
  1396. }
  1397. }
  1398. if (_edit.mode != TRANSFORM_NONE && b->is_pressed()) {
  1399. cancel_transform();
  1400. break;
  1401. }
  1402. if (b->is_pressed()) {
  1403. const Key mod = _get_key_modifier(b);
  1404. if (!orthogonal) {
  1405. if (mod == _get_key_modifier_setting("editors/3d/freelook/freelook_activation_modifier")) {
  1406. set_freelook_active(true);
  1407. }
  1408. }
  1409. } else {
  1410. set_freelook_active(false);
  1411. }
  1412. if (freelook_active && !surface->has_focus()) {
  1413. // Focus usually doesn't trigger on right-click, but in case of freelook it should,
  1414. // otherwise using keyboard navigation would misbehave
  1415. surface->grab_focus();
  1416. }
  1417. } break;
  1418. case MouseButton::MIDDLE: {
  1419. if (b->is_pressed() && _edit.mode != TRANSFORM_NONE) {
  1420. switch (_edit.plane) {
  1421. case TRANSFORM_VIEW: {
  1422. _edit.plane = TRANSFORM_X_AXIS;
  1423. set_message(TTR("X-Axis Transform."), 2);
  1424. view_type = VIEW_TYPE_USER;
  1425. _update_name();
  1426. } break;
  1427. case TRANSFORM_X_AXIS: {
  1428. _edit.plane = TRANSFORM_Y_AXIS;
  1429. set_message(TTR("Y-Axis Transform."), 2);
  1430. } break;
  1431. case TRANSFORM_Y_AXIS: {
  1432. _edit.plane = TRANSFORM_Z_AXIS;
  1433. set_message(TTR("Z-Axis Transform."), 2);
  1434. } break;
  1435. case TRANSFORM_Z_AXIS: {
  1436. _edit.plane = TRANSFORM_VIEW;
  1437. // TRANSLATORS: This refers to the transform of the view plane.
  1438. set_message(TTR("View Plane Transform."), 2);
  1439. } break;
  1440. case TRANSFORM_YZ:
  1441. case TRANSFORM_XZ:
  1442. case TRANSFORM_XY: {
  1443. } break;
  1444. }
  1445. }
  1446. } break;
  1447. case MouseButton::LEFT: {
  1448. if (b->is_pressed()) {
  1449. clicked_wants_append = b->is_shift_pressed();
  1450. if (_edit.mode != TRANSFORM_NONE && _edit.instant) {
  1451. commit_transform();
  1452. break; // just commit the edit, stop processing the event so we don't deselect the object
  1453. }
  1454. NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
  1455. if ((nav_scheme == NAVIGATION_MAYA || nav_scheme == NAVIGATION_MODO) && b->is_alt_pressed()) {
  1456. break;
  1457. }
  1458. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_LIST_SELECT) {
  1459. _list_select(b);
  1460. break;
  1461. }
  1462. _edit.mouse_pos = b->get_position();
  1463. _edit.original_mouse_pos = b->get_position();
  1464. _edit.snap = spatial_editor->is_snap_enabled();
  1465. _edit.mode = TRANSFORM_NONE;
  1466. _edit.original = spatial_editor->get_gizmo_transform(); // To prevent to break when flipping with scale.
  1467. bool can_select_gizmos = spatial_editor->get_single_selected_node();
  1468. {
  1469. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  1470. can_select_gizmos = can_select_gizmos && view_menu->get_popup()->is_item_checked(idx);
  1471. }
  1472. // Gizmo handles
  1473. if (can_select_gizmos) {
  1474. Vector<Ref<Node3DGizmo>> gizmos = spatial_editor->get_single_selected_node()->get_gizmos();
  1475. bool intersected_handle = false;
  1476. for (int i = 0; i < gizmos.size(); i++) {
  1477. Ref<EditorNode3DGizmo> seg = gizmos[i];
  1478. if ((!seg.is_valid())) {
  1479. continue;
  1480. }
  1481. int gizmo_handle = -1;
  1482. bool gizmo_secondary = false;
  1483. seg->handles_intersect_ray(camera, _edit.mouse_pos, b->is_shift_pressed(), gizmo_handle, gizmo_secondary);
  1484. if (gizmo_handle != -1) {
  1485. _edit.gizmo = seg;
  1486. seg->begin_handle_action(gizmo_handle, gizmo_secondary);
  1487. _edit.gizmo_handle = gizmo_handle;
  1488. _edit.gizmo_handle_secondary = gizmo_secondary;
  1489. _edit.gizmo_initial_value = seg->get_handle_value(gizmo_handle, gizmo_secondary);
  1490. intersected_handle = true;
  1491. break;
  1492. }
  1493. }
  1494. if (intersected_handle) {
  1495. break;
  1496. }
  1497. }
  1498. // Transform gizmo
  1499. if (_transform_gizmo_select(_edit.mouse_pos)) {
  1500. break;
  1501. }
  1502. // Subgizmos
  1503. if (can_select_gizmos) {
  1504. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(spatial_editor->get_single_selected_node());
  1505. Vector<Ref<Node3DGizmo>> gizmos = spatial_editor->get_single_selected_node()->get_gizmos();
  1506. bool intersected_subgizmo = false;
  1507. for (int i = 0; i < gizmos.size(); i++) {
  1508. Ref<EditorNode3DGizmo> seg = gizmos[i];
  1509. if ((!seg.is_valid())) {
  1510. continue;
  1511. }
  1512. int subgizmo_id = seg->subgizmos_intersect_ray(camera, _edit.mouse_pos);
  1513. if (subgizmo_id != -1) {
  1514. ERR_CONTINUE(!se);
  1515. if (b->is_shift_pressed()) {
  1516. if (se->subgizmos.has(subgizmo_id)) {
  1517. se->subgizmos.erase(subgizmo_id);
  1518. } else {
  1519. se->subgizmos.insert(subgizmo_id, seg->get_subgizmo_transform(subgizmo_id));
  1520. }
  1521. } else {
  1522. se->subgizmos.clear();
  1523. se->subgizmos.insert(subgizmo_id, seg->get_subgizmo_transform(subgizmo_id));
  1524. }
  1525. if (se->subgizmos.is_empty()) {
  1526. se->gizmo = Ref<EditorNode3DGizmo>();
  1527. } else {
  1528. se->gizmo = seg;
  1529. }
  1530. seg->redraw();
  1531. spatial_editor->update_transform_gizmo();
  1532. intersected_subgizmo = true;
  1533. break;
  1534. }
  1535. }
  1536. if (intersected_subgizmo) {
  1537. break;
  1538. }
  1539. }
  1540. clicked = ObjectID();
  1541. if ((spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT && b->is_command_or_control_pressed()) || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE) {
  1542. begin_transform(TRANSFORM_ROTATE, false);
  1543. break;
  1544. }
  1545. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE) {
  1546. begin_transform(TRANSFORM_TRANSLATE, false);
  1547. break;
  1548. }
  1549. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE) {
  1550. begin_transform(TRANSFORM_SCALE, false);
  1551. break;
  1552. }
  1553. if (after != EditorPlugin::AFTER_GUI_INPUT_CUSTOM) {
  1554. //clicking is always deferred to either move or release
  1555. clicked = _select_ray(b->get_position());
  1556. selection_in_progress = true;
  1557. if (clicked.is_null()) {
  1558. //default to regionselect
  1559. cursor.region_select = true;
  1560. cursor.region_begin = b->get_position();
  1561. cursor.region_end = b->get_position();
  1562. }
  1563. }
  1564. surface->queue_redraw();
  1565. } else {
  1566. if (_edit.gizmo.is_valid()) {
  1567. _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, _edit.gizmo_initial_value, false);
  1568. _edit.gizmo = Ref<EditorNode3DGizmo>();
  1569. break;
  1570. }
  1571. if (after != EditorPlugin::AFTER_GUI_INPUT_CUSTOM) {
  1572. selection_in_progress = false;
  1573. if (clicked.is_valid()) {
  1574. _select_clicked(false);
  1575. }
  1576. if (cursor.region_select) {
  1577. _select_region();
  1578. cursor.region_select = false;
  1579. surface->queue_redraw();
  1580. }
  1581. }
  1582. if (_edit.mode != TRANSFORM_NONE) {
  1583. Node3D *selected = spatial_editor->get_single_selected_node();
  1584. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  1585. if (se && se->gizmo.is_valid()) {
  1586. Vector<int> ids;
  1587. Vector<Transform3D> restore;
  1588. for (const KeyValue<int, Transform3D> &GE : se->subgizmos) {
  1589. ids.push_back(GE.key);
  1590. restore.push_back(GE.value);
  1591. }
  1592. se->gizmo->commit_subgizmos(ids, restore, false);
  1593. } else {
  1594. commit_transform();
  1595. }
  1596. _edit.mode = TRANSFORM_NONE;
  1597. set_message("");
  1598. spatial_editor->update_transform_gizmo();
  1599. }
  1600. surface->queue_redraw();
  1601. }
  1602. } break;
  1603. default:
  1604. break;
  1605. }
  1606. }
  1607. Ref<InputEventMouseMotion> m = p_event;
  1608. // Instant transforms process mouse motion in input() to handle wrapping.
  1609. if (m.is_valid() && !_edit.instant) {
  1610. _edit.mouse_pos = m->get_position();
  1611. if (spatial_editor->get_single_selected_node()) {
  1612. Vector<Ref<Node3DGizmo>> gizmos = spatial_editor->get_single_selected_node()->get_gizmos();
  1613. Ref<EditorNode3DGizmo> found_gizmo;
  1614. int found_handle = -1;
  1615. bool found_handle_secondary = false;
  1616. for (int i = 0; i < gizmos.size(); i++) {
  1617. Ref<EditorNode3DGizmo> seg = gizmos[i];
  1618. if (!seg.is_valid()) {
  1619. continue;
  1620. }
  1621. seg->handles_intersect_ray(camera, _edit.mouse_pos, false, found_handle, found_handle_secondary);
  1622. if (found_handle != -1) {
  1623. found_gizmo = seg;
  1624. break;
  1625. }
  1626. }
  1627. if (found_gizmo.is_valid()) {
  1628. spatial_editor->select_gizmo_highlight_axis(-1);
  1629. }
  1630. bool current_hover_handle_secondary = false;
  1631. int curreny_hover_handle = spatial_editor->get_current_hover_gizmo_handle(current_hover_handle_secondary);
  1632. if (found_gizmo != spatial_editor->get_current_hover_gizmo() || found_handle != curreny_hover_handle || found_handle_secondary != current_hover_handle_secondary) {
  1633. spatial_editor->set_current_hover_gizmo(found_gizmo);
  1634. spatial_editor->set_current_hover_gizmo_handle(found_handle, found_handle_secondary);
  1635. spatial_editor->get_single_selected_node()->update_gizmos();
  1636. }
  1637. }
  1638. if (spatial_editor->get_current_hover_gizmo().is_null() && !m->get_button_mask().has_flag(MouseButtonMask::LEFT) && !_edit.gizmo.is_valid()) {
  1639. _transform_gizmo_select(_edit.mouse_pos, true);
  1640. }
  1641. NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
  1642. NavigationMode nav_mode = NAVIGATION_NONE;
  1643. if (_edit.gizmo.is_valid()) {
  1644. _edit.gizmo->set_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, camera, m->get_position());
  1645. Variant v = _edit.gizmo->get_handle_value(_edit.gizmo_handle, _edit.gizmo_handle_secondary);
  1646. String n = _edit.gizmo->get_handle_name(_edit.gizmo_handle, _edit.gizmo_handle_secondary);
  1647. set_message(n + ": " + String(v));
  1648. } else if (m->get_button_mask().has_flag(MouseButtonMask::LEFT)) {
  1649. if (nav_scheme == NAVIGATION_MAYA && m->is_alt_pressed()) {
  1650. nav_mode = NAVIGATION_ORBIT;
  1651. } else if (nav_scheme == NAVIGATION_MODO && m->is_alt_pressed() && m->is_shift_pressed()) {
  1652. nav_mode = NAVIGATION_PAN;
  1653. } else if (nav_scheme == NAVIGATION_MODO && m->is_alt_pressed() && m->is_command_or_control_pressed()) {
  1654. nav_mode = NAVIGATION_ZOOM;
  1655. } else if (nav_scheme == NAVIGATION_MODO && m->is_alt_pressed()) {
  1656. nav_mode = NAVIGATION_ORBIT;
  1657. } else {
  1658. const bool movement_threshold_passed = _edit.original_mouse_pos.distance_to(_edit.mouse_pos) > 8 * EDSCALE;
  1659. // enable region-select if nothing has been selected yet or multi-select (shift key) is active
  1660. if (selection_in_progress && movement_threshold_passed) {
  1661. if (get_selected_count() == 0 || clicked_wants_append) {
  1662. cursor.region_select = true;
  1663. cursor.region_begin = _edit.original_mouse_pos;
  1664. clicked = ObjectID();
  1665. }
  1666. }
  1667. if (cursor.region_select) {
  1668. cursor.region_end = m->get_position();
  1669. surface->queue_redraw();
  1670. return;
  1671. }
  1672. if (clicked.is_valid() && movement_threshold_passed) {
  1673. _compute_edit(_edit.original_mouse_pos);
  1674. clicked = ObjectID();
  1675. _edit.mode = TRANSFORM_TRANSLATE;
  1676. }
  1677. if (_edit.mode == TRANSFORM_NONE || _edit.numeric_input != 0 || _edit.numeric_next_decimal != 0) {
  1678. return;
  1679. }
  1680. update_transform(_get_key_modifier(m) == Key::SHIFT);
  1681. }
  1682. } else if (m->get_button_mask().has_flag(MouseButtonMask::RIGHT) || freelook_active) {
  1683. if (nav_scheme == NAVIGATION_MAYA && m->is_alt_pressed()) {
  1684. nav_mode = NAVIGATION_ZOOM;
  1685. } else if (freelook_active) {
  1686. nav_mode = NAVIGATION_LOOK;
  1687. } else if (orthogonal) {
  1688. nav_mode = NAVIGATION_PAN;
  1689. }
  1690. } else if (m->get_button_mask().has_flag(MouseButtonMask::MIDDLE)) {
  1691. const Key mod = _get_key_modifier(m);
  1692. if (nav_scheme == NAVIGATION_GODOT) {
  1693. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1694. nav_mode = NAVIGATION_PAN;
  1695. } else if (mod == _get_key_modifier_setting("editors/3d/navigation/zoom_modifier")) {
  1696. nav_mode = NAVIGATION_ZOOM;
  1697. } else if (mod == Key::ALT || mod == _get_key_modifier_setting("editors/3d/navigation/orbit_modifier")) {
  1698. // Always allow Alt as a modifier to better support graphic tablets.
  1699. nav_mode = NAVIGATION_ORBIT;
  1700. }
  1701. } else if (nav_scheme == NAVIGATION_MAYA) {
  1702. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1703. nav_mode = NAVIGATION_PAN;
  1704. }
  1705. }
  1706. } else if (EDITOR_GET("editors/3d/navigation/emulate_3_button_mouse")) {
  1707. // Handle trackpad (no external mouse) use case
  1708. const Key mod = _get_key_modifier(m);
  1709. if (mod != Key::NONE) {
  1710. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1711. nav_mode = NAVIGATION_PAN;
  1712. } else if (mod == _get_key_modifier_setting("editors/3d/navigation/zoom_modifier")) {
  1713. nav_mode = NAVIGATION_ZOOM;
  1714. } else if (mod == Key::ALT || mod == _get_key_modifier_setting("editors/3d/navigation/orbit_modifier")) {
  1715. // Always allow Alt as a modifier to better support graphic tablets.
  1716. nav_mode = NAVIGATION_ORBIT;
  1717. }
  1718. }
  1719. }
  1720. switch (nav_mode) {
  1721. case NAVIGATION_PAN: {
  1722. _nav_pan(m, _get_warped_mouse_motion(m));
  1723. } break;
  1724. case NAVIGATION_ZOOM: {
  1725. _nav_zoom(m, m->get_relative());
  1726. } break;
  1727. case NAVIGATION_ORBIT: {
  1728. _nav_orbit(m, _get_warped_mouse_motion(m));
  1729. } break;
  1730. case NAVIGATION_LOOK: {
  1731. _nav_look(m, _get_warped_mouse_motion(m));
  1732. } break;
  1733. default: {
  1734. }
  1735. }
  1736. }
  1737. Ref<InputEventMagnifyGesture> magnify_gesture = p_event;
  1738. if (magnify_gesture.is_valid()) {
  1739. if (is_freelook_active()) {
  1740. scale_freelook_speed(magnify_gesture->get_factor());
  1741. } else {
  1742. scale_cursor_distance(1.0 / magnify_gesture->get_factor());
  1743. }
  1744. }
  1745. Ref<InputEventPanGesture> pan_gesture = p_event;
  1746. if (pan_gesture.is_valid()) {
  1747. NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
  1748. NavigationMode nav_mode = NAVIGATION_NONE;
  1749. if (nav_scheme == NAVIGATION_GODOT) {
  1750. const Key mod = _get_key_modifier(pan_gesture);
  1751. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1752. nav_mode = NAVIGATION_PAN;
  1753. } else if (mod == _get_key_modifier_setting("editors/3d/navigation/zoom_modifier")) {
  1754. nav_mode = NAVIGATION_ZOOM;
  1755. } else if (mod == Key::ALT || mod == _get_key_modifier_setting("editors/3d/navigation/orbit_modifier")) {
  1756. // Always allow Alt as a modifier to better support graphic tablets.
  1757. nav_mode = NAVIGATION_ORBIT;
  1758. }
  1759. } else if (nav_scheme == NAVIGATION_MAYA) {
  1760. if (pan_gesture->is_alt_pressed()) {
  1761. nav_mode = NAVIGATION_PAN;
  1762. }
  1763. }
  1764. switch (nav_mode) {
  1765. case NAVIGATION_PAN: {
  1766. _nav_pan(pan_gesture, -pan_gesture->get_delta());
  1767. } break;
  1768. case NAVIGATION_ZOOM: {
  1769. _nav_zoom(pan_gesture, pan_gesture->get_delta());
  1770. } break;
  1771. case NAVIGATION_ORBIT: {
  1772. _nav_orbit(pan_gesture, -pan_gesture->get_delta());
  1773. } break;
  1774. case NAVIGATION_LOOK: {
  1775. _nav_look(pan_gesture, pan_gesture->get_delta());
  1776. } break;
  1777. default: {
  1778. }
  1779. }
  1780. }
  1781. Ref<InputEventKey> k = p_event;
  1782. if (k.is_valid()) {
  1783. if (!k->is_pressed()) {
  1784. return;
  1785. }
  1786. if (_edit.instant) {
  1787. // In a Blender-style transform, numbers set the magnitude of the transform.
  1788. // E.g. pressing g4.5x means "translate 4.5 units along the X axis".
  1789. // Use the Unicode value because we care about the text, not the actual keycode.
  1790. // This ensures numbers work consistently across different keyboard language layouts.
  1791. bool processed = true;
  1792. Key key = k->get_physical_keycode();
  1793. char32_t unicode = k->get_unicode();
  1794. if (unicode >= '0' && unicode <= '9') {
  1795. uint32_t value = uint32_t(unicode - Key::KEY_0);
  1796. if (_edit.numeric_next_decimal < 0) {
  1797. _edit.numeric_input = _edit.numeric_input + value * Math::pow(10.0, _edit.numeric_next_decimal--);
  1798. } else {
  1799. _edit.numeric_input = _edit.numeric_input * 10 + value;
  1800. }
  1801. update_transform_numeric();
  1802. } else if (unicode == '-') {
  1803. _edit.numeric_negate = !_edit.numeric_negate;
  1804. update_transform_numeric();
  1805. } else if (unicode == '.') {
  1806. if (_edit.numeric_next_decimal == 0) {
  1807. _edit.numeric_next_decimal = -1;
  1808. }
  1809. } else if (key == Key::ENTER || key == Key::KP_ENTER || key == Key::SPACE) {
  1810. commit_transform();
  1811. } else {
  1812. processed = false;
  1813. }
  1814. if (processed) {
  1815. // Ignore mouse inputs once we receive a numeric input.
  1816. set_process_input(false);
  1817. accept_event();
  1818. return;
  1819. }
  1820. }
  1821. if (EDITOR_GET("editors/3d/navigation/emulate_numpad")) {
  1822. const Key code = k->get_physical_keycode();
  1823. if (code >= Key::KEY_0 && code <= Key::KEY_9) {
  1824. k->set_keycode(code - Key::KEY_0 + Key::KP_0);
  1825. }
  1826. }
  1827. if (_edit.mode == TRANSFORM_NONE) {
  1828. if (_edit.gizmo.is_valid() && (k->get_keycode() == Key::ESCAPE || k->get_keycode() == Key::BACKSPACE)) {
  1829. // Restore.
  1830. _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, _edit.gizmo_initial_value, true);
  1831. _edit.gizmo = Ref<EditorNode3DGizmo>();
  1832. }
  1833. if (k->get_keycode() == Key::ESCAPE && !cursor.region_select) {
  1834. _clear_selected();
  1835. return;
  1836. }
  1837. } else {
  1838. // We're actively transforming, handle keys specially
  1839. TransformPlane new_plane = TRANSFORM_VIEW;
  1840. if (ED_IS_SHORTCUT("spatial_editor/lock_transform_x", p_event)) {
  1841. new_plane = TRANSFORM_X_AXIS;
  1842. } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_y", p_event)) {
  1843. new_plane = TRANSFORM_Y_AXIS;
  1844. } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_z", p_event)) {
  1845. new_plane = TRANSFORM_Z_AXIS;
  1846. } else if (_edit.mode != TRANSFORM_ROTATE) { // rotating on a plane doesn't make sense
  1847. if (ED_IS_SHORTCUT("spatial_editor/lock_transform_yz", p_event)) {
  1848. new_plane = TRANSFORM_YZ;
  1849. } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_xz", p_event)) {
  1850. new_plane = TRANSFORM_XZ;
  1851. } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_xy", p_event)) {
  1852. new_plane = TRANSFORM_XY;
  1853. }
  1854. }
  1855. if (new_plane != TRANSFORM_VIEW) {
  1856. if (new_plane != _edit.plane) {
  1857. // lock me once and get a global constraint
  1858. _edit.plane = new_plane;
  1859. spatial_editor->set_local_coords_enabled(false);
  1860. } else if (!spatial_editor->are_local_coords_enabled()) {
  1861. // lock me twice and get a local constraint
  1862. spatial_editor->set_local_coords_enabled(true);
  1863. } else {
  1864. // lock me thrice and we're back where we started
  1865. _edit.plane = TRANSFORM_VIEW;
  1866. spatial_editor->set_local_coords_enabled(false);
  1867. }
  1868. if (_edit.numeric_input != 0 || _edit.numeric_next_decimal != 0) {
  1869. update_transform_numeric();
  1870. } else {
  1871. update_transform(Input::get_singleton()->is_key_pressed(Key::SHIFT));
  1872. }
  1873. accept_event();
  1874. return;
  1875. }
  1876. }
  1877. if (ED_IS_SHORTCUT("spatial_editor/snap", p_event)) {
  1878. if (_edit.mode != TRANSFORM_NONE) {
  1879. _edit.snap = !_edit.snap;
  1880. }
  1881. }
  1882. if (ED_IS_SHORTCUT("spatial_editor/bottom_view", p_event)) {
  1883. _menu_option(VIEW_BOTTOM);
  1884. }
  1885. if (ED_IS_SHORTCUT("spatial_editor/top_view", p_event)) {
  1886. _menu_option(VIEW_TOP);
  1887. }
  1888. if (ED_IS_SHORTCUT("spatial_editor/rear_view", p_event)) {
  1889. _menu_option(VIEW_REAR);
  1890. }
  1891. if (ED_IS_SHORTCUT("spatial_editor/front_view", p_event)) {
  1892. _menu_option(VIEW_FRONT);
  1893. }
  1894. if (ED_IS_SHORTCUT("spatial_editor/left_view", p_event)) {
  1895. _menu_option(VIEW_LEFT);
  1896. }
  1897. if (ED_IS_SHORTCUT("spatial_editor/right_view", p_event)) {
  1898. _menu_option(VIEW_RIGHT);
  1899. }
  1900. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_down", p_event)) {
  1901. // Clamp rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  1902. cursor.x_rot = CLAMP(cursor.x_rot - Math_PI / 12.0, -1.57, 1.57);
  1903. view_type = VIEW_TYPE_USER;
  1904. _update_name();
  1905. }
  1906. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_up", p_event)) {
  1907. // Clamp rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  1908. cursor.x_rot = CLAMP(cursor.x_rot + Math_PI / 12.0, -1.57, 1.57);
  1909. view_type = VIEW_TYPE_USER;
  1910. _update_name();
  1911. }
  1912. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_right", p_event)) {
  1913. cursor.y_rot -= Math_PI / 12.0;
  1914. view_type = VIEW_TYPE_USER;
  1915. _update_name();
  1916. }
  1917. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_left", p_event)) {
  1918. cursor.y_rot += Math_PI / 12.0;
  1919. view_type = VIEW_TYPE_USER;
  1920. _update_name();
  1921. }
  1922. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_180", p_event)) {
  1923. cursor.y_rot += Math_PI;
  1924. view_type = VIEW_TYPE_USER;
  1925. _update_name();
  1926. }
  1927. if (ED_IS_SHORTCUT("spatial_editor/focus_origin", p_event)) {
  1928. _menu_option(VIEW_CENTER_TO_ORIGIN);
  1929. }
  1930. if (ED_IS_SHORTCUT("spatial_editor/focus_selection", p_event)) {
  1931. _menu_option(VIEW_CENTER_TO_SELECTION);
  1932. }
  1933. if (ED_IS_SHORTCUT("spatial_editor/align_transform_with_view", p_event)) {
  1934. _menu_option(VIEW_ALIGN_TRANSFORM_WITH_VIEW);
  1935. }
  1936. if (ED_IS_SHORTCUT("spatial_editor/align_rotation_with_view", p_event)) {
  1937. _menu_option(VIEW_ALIGN_ROTATION_WITH_VIEW);
  1938. }
  1939. if (ED_IS_SHORTCUT("spatial_editor/insert_anim_key", p_event)) {
  1940. if (!get_selected_count() || _edit.mode != TRANSFORM_NONE) {
  1941. return;
  1942. }
  1943. if (!AnimationPlayerEditor::get_singleton()->get_track_editor()->has_keying()) {
  1944. set_message(TTR("Keying is disabled (no key inserted)."));
  1945. return;
  1946. }
  1947. List<Node *> &selection = editor_selection->get_selected_node_list();
  1948. for (Node *E : selection) {
  1949. Node3D *sp = Object::cast_to<Node3D>(E);
  1950. if (!sp) {
  1951. continue;
  1952. }
  1953. spatial_editor->emit_signal(SNAME("transform_key_request"), sp, "", sp->get_transform());
  1954. }
  1955. set_message(TTR("Animation Key Inserted."));
  1956. }
  1957. if (ED_IS_SHORTCUT("spatial_editor/cancel_transform", p_event) && _edit.mode != TRANSFORM_NONE) {
  1958. cancel_transform();
  1959. }
  1960. if (!is_freelook_active()) {
  1961. if (ED_IS_SHORTCUT("spatial_editor/instant_translate", p_event)) {
  1962. begin_transform(TRANSFORM_TRANSLATE, true);
  1963. }
  1964. if (ED_IS_SHORTCUT("spatial_editor/instant_rotate", p_event)) {
  1965. begin_transform(TRANSFORM_ROTATE, true);
  1966. }
  1967. if (ED_IS_SHORTCUT("spatial_editor/instant_scale", p_event)) {
  1968. begin_transform(TRANSFORM_SCALE, true);
  1969. }
  1970. }
  1971. // Freelook doesn't work in orthogonal mode.
  1972. if (!orthogonal && ED_IS_SHORTCUT("spatial_editor/freelook_toggle", p_event)) {
  1973. set_freelook_active(!is_freelook_active());
  1974. } else if (k->get_keycode() == Key::ESCAPE) {
  1975. set_freelook_active(false);
  1976. }
  1977. if (k->get_keycode() == Key::SPACE) {
  1978. if (!k->is_pressed()) {
  1979. emit_signal(SNAME("toggle_maximize_view"), this);
  1980. }
  1981. }
  1982. if (ED_IS_SHORTCUT("spatial_editor/decrease_fov", p_event)) {
  1983. scale_fov(-0.05);
  1984. }
  1985. if (ED_IS_SHORTCUT("spatial_editor/increase_fov", p_event)) {
  1986. scale_fov(0.05);
  1987. }
  1988. if (ED_IS_SHORTCUT("spatial_editor/reset_fov", p_event)) {
  1989. reset_fov();
  1990. }
  1991. }
  1992. // freelook uses most of the useful shortcuts, like save, so its ok
  1993. // to consider freelook active as end of the line for future events.
  1994. if (freelook_active) {
  1995. accept_event();
  1996. }
  1997. }
  1998. void Node3DEditorViewport::_nav_pan(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  1999. const NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
  2000. real_t pan_speed = 1 / 150.0;
  2001. if (p_event.is_valid() && nav_scheme == NAVIGATION_MAYA && p_event->is_shift_pressed()) {
  2002. pan_speed *= 10;
  2003. }
  2004. Transform3D camera_transform;
  2005. camera_transform.translate_local(cursor.pos);
  2006. camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
  2007. camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
  2008. const bool invert_x_axis = EDITOR_GET("editors/3d/navigation/invert_x_axis");
  2009. const bool invert_y_axis = EDITOR_GET("editors/3d/navigation/invert_y_axis");
  2010. Vector3 translation(
  2011. (invert_x_axis ? -1 : 1) * -p_relative.x * pan_speed,
  2012. (invert_y_axis ? -1 : 1) * p_relative.y * pan_speed,
  2013. 0);
  2014. translation *= cursor.distance / DISTANCE_DEFAULT;
  2015. camera_transform.translate_local(translation);
  2016. cursor.pos = camera_transform.origin;
  2017. }
  2018. void Node3DEditorViewport::_nav_zoom(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  2019. const NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
  2020. real_t zoom_speed = 1 / 80.0;
  2021. if (p_event.is_valid() && nav_scheme == NAVIGATION_MAYA && p_event->is_shift_pressed()) {
  2022. zoom_speed *= 10;
  2023. }
  2024. NavigationZoomStyle zoom_style = (NavigationZoomStyle)EDITOR_GET("editors/3d/navigation/zoom_style").operator int();
  2025. if (zoom_style == NAVIGATION_ZOOM_HORIZONTAL) {
  2026. if (p_relative.x > 0) {
  2027. scale_cursor_distance(1 - p_relative.x * zoom_speed);
  2028. } else if (p_relative.x < 0) {
  2029. scale_cursor_distance(1.0 / (1 + p_relative.x * zoom_speed));
  2030. }
  2031. } else {
  2032. if (p_relative.y > 0) {
  2033. scale_cursor_distance(1 + p_relative.y * zoom_speed);
  2034. } else if (p_relative.y < 0) {
  2035. scale_cursor_distance(1.0 / (1 - p_relative.y * zoom_speed));
  2036. }
  2037. }
  2038. }
  2039. void Node3DEditorViewport::_nav_orbit(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  2040. if (lock_rotation) {
  2041. _nav_pan(p_event, p_relative);
  2042. return;
  2043. }
  2044. if (orthogonal && auto_orthogonal) {
  2045. _menu_option(VIEW_PERSPECTIVE);
  2046. }
  2047. const real_t degrees_per_pixel = EDITOR_GET("editors/3d/navigation_feel/orbit_sensitivity");
  2048. const real_t radians_per_pixel = Math::deg_to_rad(degrees_per_pixel);
  2049. const bool invert_y_axis = EDITOR_GET("editors/3d/navigation/invert_y_axis");
  2050. const bool invert_x_axis = EDITOR_GET("editors/3d/navigation/invert_x_axis");
  2051. if (invert_y_axis) {
  2052. cursor.x_rot -= p_relative.y * radians_per_pixel;
  2053. } else {
  2054. cursor.x_rot += p_relative.y * radians_per_pixel;
  2055. }
  2056. // Clamp the Y rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  2057. cursor.x_rot = CLAMP(cursor.x_rot, -1.57, 1.57);
  2058. if (invert_x_axis) {
  2059. cursor.y_rot -= p_relative.x * radians_per_pixel;
  2060. } else {
  2061. cursor.y_rot += p_relative.x * radians_per_pixel;
  2062. }
  2063. view_type = VIEW_TYPE_USER;
  2064. _update_name();
  2065. }
  2066. void Node3DEditorViewport::_nav_look(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  2067. if (orthogonal) {
  2068. _nav_pan(p_event, p_relative);
  2069. return;
  2070. }
  2071. if (orthogonal && auto_orthogonal) {
  2072. _menu_option(VIEW_PERSPECTIVE);
  2073. }
  2074. // Scale mouse sensitivity with camera FOV scale when zoomed in to make it easier to point at things.
  2075. const real_t degrees_per_pixel = real_t(EDITOR_GET("editors/3d/freelook/freelook_sensitivity")) * MIN(1.0, cursor.fov_scale);
  2076. const real_t radians_per_pixel = Math::deg_to_rad(degrees_per_pixel);
  2077. const bool invert_y_axis = EDITOR_GET("editors/3d/navigation/invert_y_axis");
  2078. // Note: do NOT assume the camera has the "current" transform, because it is interpolated and may have "lag".
  2079. const Transform3D prev_camera_transform = to_camera_transform(cursor);
  2080. if (invert_y_axis) {
  2081. cursor.x_rot -= p_relative.y * radians_per_pixel;
  2082. } else {
  2083. cursor.x_rot += p_relative.y * radians_per_pixel;
  2084. }
  2085. // Clamp the Y rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  2086. cursor.x_rot = CLAMP(cursor.x_rot, -1.57, 1.57);
  2087. cursor.y_rot += p_relative.x * radians_per_pixel;
  2088. // Look is like the opposite of Orbit: the focus point rotates around the camera
  2089. Transform3D camera_transform = to_camera_transform(cursor);
  2090. Vector3 pos = camera_transform.xform(Vector3(0, 0, 0));
  2091. Vector3 prev_pos = prev_camera_transform.xform(Vector3(0, 0, 0));
  2092. Vector3 diff = prev_pos - pos;
  2093. cursor.pos += diff;
  2094. view_type = VIEW_TYPE_USER;
  2095. _update_name();
  2096. }
  2097. void Node3DEditorViewport::set_freelook_active(bool active_now) {
  2098. if (!freelook_active && active_now) {
  2099. // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
  2100. cursor = camera_cursor;
  2101. // Make sure eye_pos is synced, because freelook referential is eye pos rather than orbit pos
  2102. Vector3 forward = to_camera_transform(cursor).basis.xform(Vector3(0, 0, -1));
  2103. cursor.eye_pos = cursor.pos - cursor.distance * forward;
  2104. // Also sync the camera cursor, otherwise switching to freelook will be trippy if inertia is active
  2105. camera_cursor.eye_pos = cursor.eye_pos;
  2106. if (EDITOR_GET("editors/3d/freelook/freelook_speed_zoom_link")) {
  2107. // Re-adjust freelook speed from the current zoom level
  2108. real_t base_speed = EDITOR_GET("editors/3d/freelook/freelook_base_speed");
  2109. freelook_speed = base_speed * cursor.distance;
  2110. }
  2111. previous_mouse_position = get_local_mouse_position();
  2112. // Hide mouse like in an FPS (warping doesn't work)
  2113. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
  2114. } else if (freelook_active && !active_now) {
  2115. // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
  2116. cursor = camera_cursor;
  2117. // Restore mouse
  2118. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  2119. // Restore the previous mouse position when leaving freelook mode.
  2120. // This is done because leaving `Input.MOUSE_MODE_CAPTURED` will center the cursor
  2121. // due to OS limitations.
  2122. warp_mouse(previous_mouse_position);
  2123. }
  2124. freelook_active = active_now;
  2125. }
  2126. void Node3DEditorViewport::scale_fov(real_t p_fov_offset) {
  2127. cursor.fov_scale = CLAMP(cursor.fov_scale + p_fov_offset, 0.1, 2.5);
  2128. surface->queue_redraw();
  2129. }
  2130. void Node3DEditorViewport::reset_fov() {
  2131. cursor.fov_scale = 1.0;
  2132. surface->queue_redraw();
  2133. }
  2134. void Node3DEditorViewport::scale_cursor_distance(real_t scale) {
  2135. real_t min_distance = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
  2136. real_t max_distance = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
  2137. if (unlikely(min_distance > max_distance)) {
  2138. cursor.distance = (min_distance + max_distance) / 2;
  2139. } else {
  2140. cursor.distance = CLAMP(cursor.distance * scale, min_distance, max_distance);
  2141. }
  2142. if (cursor.distance == max_distance || cursor.distance == min_distance) {
  2143. zoom_failed_attempts_count++;
  2144. } else {
  2145. zoom_failed_attempts_count = 0;
  2146. }
  2147. zoom_indicator_delay = ZOOM_FREELOOK_INDICATOR_DELAY_S;
  2148. surface->queue_redraw();
  2149. }
  2150. void Node3DEditorViewport::scale_freelook_speed(real_t scale) {
  2151. real_t min_speed = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
  2152. real_t max_speed = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
  2153. if (unlikely(min_speed > max_speed)) {
  2154. freelook_speed = (min_speed + max_speed) / 2;
  2155. } else {
  2156. freelook_speed = CLAMP(freelook_speed * scale, min_speed, max_speed);
  2157. }
  2158. zoom_indicator_delay = ZOOM_FREELOOK_INDICATOR_DELAY_S;
  2159. surface->queue_redraw();
  2160. }
  2161. Point2i Node3DEditorViewport::_get_warped_mouse_motion(const Ref<InputEventMouseMotion> &p_ev_mouse_motion) const {
  2162. Point2i relative;
  2163. if (bool(EDITOR_GET("editors/3d/navigation/warped_mouse_panning"))) {
  2164. relative = Input::get_singleton()->warp_mouse_motion(p_ev_mouse_motion, surface->get_global_rect());
  2165. } else {
  2166. relative = p_ev_mouse_motion->get_relative();
  2167. }
  2168. return relative;
  2169. }
  2170. void Node3DEditorViewport::_update_freelook(real_t delta) {
  2171. if (!is_freelook_active()) {
  2172. return;
  2173. }
  2174. const FreelookNavigationScheme navigation_scheme = (FreelookNavigationScheme)EDITOR_GET("editors/3d/freelook/freelook_navigation_scheme").operator int();
  2175. Vector3 forward;
  2176. if (navigation_scheme == FREELOOK_FULLY_AXIS_LOCKED) {
  2177. // Forward/backward keys will always go straight forward/backward, never moving on the Y axis.
  2178. forward = Vector3(0, 0, -1).rotated(Vector3(0, 1, 0), camera->get_rotation().y);
  2179. } else {
  2180. // Forward/backward keys will be relative to the camera pitch.
  2181. forward = camera->get_transform().basis.xform(Vector3(0, 0, -1));
  2182. }
  2183. const Vector3 right = camera->get_transform().basis.xform(Vector3(1, 0, 0));
  2184. Vector3 up;
  2185. if (navigation_scheme == FREELOOK_PARTIALLY_AXIS_LOCKED || navigation_scheme == FREELOOK_FULLY_AXIS_LOCKED) {
  2186. // Up/down keys will always go up/down regardless of camera pitch.
  2187. up = Vector3(0, 1, 0);
  2188. } else {
  2189. // Up/down keys will be relative to the camera pitch.
  2190. up = camera->get_transform().basis.xform(Vector3(0, 1, 0));
  2191. }
  2192. Vector3 direction;
  2193. // Use actions from the inputmap, as this is the only way to reliably detect input in this method.
  2194. // See #54469 for more discussion and explanation.
  2195. Input *inp = Input::get_singleton();
  2196. if (inp->is_action_pressed("spatial_editor/freelook_left")) {
  2197. direction -= right;
  2198. }
  2199. if (inp->is_action_pressed("spatial_editor/freelook_right")) {
  2200. direction += right;
  2201. }
  2202. if (inp->is_action_pressed("spatial_editor/freelook_forward")) {
  2203. direction += forward;
  2204. }
  2205. if (inp->is_action_pressed("spatial_editor/freelook_backwards")) {
  2206. direction -= forward;
  2207. }
  2208. if (inp->is_action_pressed("spatial_editor/freelook_up")) {
  2209. direction += up;
  2210. }
  2211. if (inp->is_action_pressed("spatial_editor/freelook_down")) {
  2212. direction -= up;
  2213. }
  2214. real_t speed = freelook_speed;
  2215. if (inp->is_action_pressed("spatial_editor/freelook_speed_modifier")) {
  2216. speed *= 3.0;
  2217. }
  2218. if (inp->is_action_pressed("spatial_editor/freelook_slow_modifier")) {
  2219. speed *= 0.333333;
  2220. }
  2221. const Vector3 motion = direction * speed * delta;
  2222. cursor.pos += motion;
  2223. cursor.eye_pos += motion;
  2224. }
  2225. void Node3DEditorViewport::set_message(String p_message, float p_time) {
  2226. message = p_message;
  2227. message_time = p_time;
  2228. }
  2229. void Node3DEditorPlugin::edited_scene_changed() {
  2230. for (uint32_t i = 0; i < Node3DEditor::VIEWPORTS_COUNT; i++) {
  2231. Node3DEditorViewport *viewport = Node3DEditor::get_singleton()->get_editor_viewport(i);
  2232. if (viewport->is_visible()) {
  2233. viewport->notification(Control::NOTIFICATION_VISIBILITY_CHANGED);
  2234. }
  2235. }
  2236. }
  2237. void Node3DEditorViewport::_project_settings_changed() {
  2238. //update shadow atlas if changed
  2239. int shadowmap_size = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_size");
  2240. bool shadowmap_16_bits = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_16_bits");
  2241. int atlas_q0 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_0_subdiv");
  2242. int atlas_q1 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_1_subdiv");
  2243. int atlas_q2 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_2_subdiv");
  2244. int atlas_q3 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_3_subdiv");
  2245. viewport->set_positional_shadow_atlas_size(shadowmap_size);
  2246. viewport->set_positional_shadow_atlas_16_bits(shadowmap_16_bits);
  2247. viewport->set_positional_shadow_atlas_quadrant_subdiv(0, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q0));
  2248. viewport->set_positional_shadow_atlas_quadrant_subdiv(1, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q1));
  2249. viewport->set_positional_shadow_atlas_quadrant_subdiv(2, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q2));
  2250. viewport->set_positional_shadow_atlas_quadrant_subdiv(3, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q3));
  2251. _update_shrink();
  2252. // Update MSAA, screen-space AA and debanding if changed
  2253. const int msaa_mode = GLOBAL_GET("rendering/anti_aliasing/quality/msaa_3d");
  2254. viewport->set_msaa_3d(Viewport::MSAA(msaa_mode));
  2255. const int ssaa_mode = GLOBAL_GET("rendering/anti_aliasing/quality/screen_space_aa");
  2256. viewport->set_screen_space_aa(Viewport::ScreenSpaceAA(ssaa_mode));
  2257. const bool use_taa = GLOBAL_GET("rendering/anti_aliasing/quality/use_taa");
  2258. viewport->set_use_taa(use_taa);
  2259. const bool transparent_background = GLOBAL_GET("rendering/viewport/transparent_background");
  2260. viewport->set_transparent_background(transparent_background);
  2261. const bool use_hdr_2d = GLOBAL_GET("rendering/viewport/hdr_2d");
  2262. viewport->set_use_hdr_2d(use_hdr_2d);
  2263. const bool use_debanding = GLOBAL_GET("rendering/anti_aliasing/quality/use_debanding");
  2264. viewport->set_use_debanding(use_debanding);
  2265. const bool use_occlusion_culling = GLOBAL_GET("rendering/occlusion_culling/use_occlusion_culling");
  2266. viewport->set_use_occlusion_culling(use_occlusion_culling);
  2267. const float mesh_lod_threshold = GLOBAL_GET("rendering/mesh_lod/lod_change/threshold_pixels");
  2268. viewport->set_mesh_lod_threshold(mesh_lod_threshold);
  2269. const Viewport::Scaling3DMode scaling_3d_mode = Viewport::Scaling3DMode(int(GLOBAL_GET("rendering/scaling_3d/mode")));
  2270. viewport->set_scaling_3d_mode(scaling_3d_mode);
  2271. const float scaling_3d_scale = GLOBAL_GET("rendering/scaling_3d/scale");
  2272. viewport->set_scaling_3d_scale(scaling_3d_scale);
  2273. const float fsr_sharpness = GLOBAL_GET("rendering/scaling_3d/fsr_sharpness");
  2274. viewport->set_fsr_sharpness(fsr_sharpness);
  2275. const float texture_mipmap_bias = GLOBAL_GET("rendering/textures/default_filters/texture_mipmap_bias");
  2276. viewport->set_texture_mipmap_bias(texture_mipmap_bias);
  2277. }
  2278. void Node3DEditorViewport::_notification(int p_what) {
  2279. switch (p_what) {
  2280. case NOTIFICATION_READY: {
  2281. ProjectSettings::get_singleton()->connect("settings_changed", callable_mp(this, &Node3DEditorViewport::_project_settings_changed));
  2282. } break;
  2283. case NOTIFICATION_VISIBILITY_CHANGED: {
  2284. bool vp_visible = is_visible_in_tree();
  2285. set_process(vp_visible);
  2286. set_physics_process(vp_visible);
  2287. if (vp_visible) {
  2288. orthogonal = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL));
  2289. _update_name();
  2290. _update_camera(0);
  2291. } else {
  2292. set_freelook_active(false);
  2293. }
  2294. call_deferred(SNAME("update_transform_gizmo_view"));
  2295. } break;
  2296. case NOTIFICATION_RESIZED: {
  2297. call_deferred(SNAME("update_transform_gizmo_view"));
  2298. } break;
  2299. case NOTIFICATION_PROCESS: {
  2300. real_t delta = get_process_delta_time();
  2301. if (zoom_indicator_delay > 0) {
  2302. zoom_indicator_delay -= delta;
  2303. if (zoom_indicator_delay <= 0) {
  2304. surface->queue_redraw();
  2305. zoom_limit_label->hide();
  2306. }
  2307. }
  2308. _update_navigation_controls_visibility();
  2309. _update_freelook(delta);
  2310. Node *scene_root = SceneTreeDock::get_singleton()->get_editor_data()->get_edited_scene_root();
  2311. if (previewing_cinema && scene_root != nullptr) {
  2312. Camera3D *cam = scene_root->get_viewport()->get_camera_3d();
  2313. if (cam != nullptr && cam != previewing) {
  2314. //then switch the viewport's camera to the scene's viewport camera
  2315. if (previewing != nullptr) {
  2316. previewing->disconnect("tree_exited", callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  2317. }
  2318. previewing = cam;
  2319. previewing->connect("tree_exited", callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  2320. RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), cam->get_camera());
  2321. surface->queue_redraw();
  2322. }
  2323. }
  2324. _update_camera(delta);
  2325. const HashMap<Node *, Object *> &selection = editor_selection->get_selection();
  2326. bool changed = false;
  2327. bool exist = false;
  2328. for (const KeyValue<Node *, Object *> &E : selection) {
  2329. Node3D *sp = Object::cast_to<Node3D>(E.key);
  2330. if (!sp) {
  2331. continue;
  2332. }
  2333. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  2334. if (!se) {
  2335. continue;
  2336. }
  2337. Transform3D t = sp->get_global_gizmo_transform();
  2338. VisualInstance3D *vi = Object::cast_to<VisualInstance3D>(sp);
  2339. AABB new_aabb = vi ? vi->get_aabb() : _calculate_spatial_bounds(sp);
  2340. exist = true;
  2341. if (se->last_xform == t && se->aabb == new_aabb && !se->last_xform_dirty) {
  2342. continue;
  2343. }
  2344. changed = true;
  2345. se->last_xform_dirty = false;
  2346. se->last_xform = t;
  2347. se->aabb = new_aabb;
  2348. Transform3D t_offset = t;
  2349. // apply AABB scaling before item's global transform
  2350. {
  2351. const Vector3 offset(0.005, 0.005, 0.005);
  2352. Basis aabb_s;
  2353. aabb_s.scale(se->aabb.size + offset);
  2354. t.translate_local(se->aabb.position - offset / 2);
  2355. t.basis = t.basis * aabb_s;
  2356. }
  2357. {
  2358. const Vector3 offset(0.01, 0.01, 0.01);
  2359. Basis aabb_s;
  2360. aabb_s.scale(se->aabb.size + offset);
  2361. t_offset.translate_local(se->aabb.position - offset / 2);
  2362. t_offset.basis = t_offset.basis * aabb_s;
  2363. }
  2364. RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance, t);
  2365. RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_offset, t_offset);
  2366. RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_xray, t);
  2367. RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_xray_offset, t_offset);
  2368. }
  2369. if (changed || (spatial_editor->is_gizmo_visible() && !exist)) {
  2370. spatial_editor->update_transform_gizmo();
  2371. }
  2372. if (message_time > 0) {
  2373. if (message != last_message) {
  2374. surface->queue_redraw();
  2375. last_message = message;
  2376. }
  2377. message_time -= get_physics_process_delta_time();
  2378. if (message_time < 0) {
  2379. surface->queue_redraw();
  2380. }
  2381. }
  2382. bool show_info = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_INFORMATION));
  2383. if (show_info != info_label->is_visible()) {
  2384. info_label->set_visible(show_info);
  2385. }
  2386. Camera3D *current_camera;
  2387. if (previewing) {
  2388. current_camera = previewing;
  2389. } else {
  2390. current_camera = camera;
  2391. }
  2392. if (show_info) {
  2393. const String viewport_size = vformat(U"%d × %d", viewport->get_size().x, viewport->get_size().y);
  2394. String text;
  2395. text += vformat(TTR("X: %s\n"), rtos(current_camera->get_position().x).pad_decimals(1));
  2396. text += vformat(TTR("Y: %s\n"), rtos(current_camera->get_position().y).pad_decimals(1));
  2397. text += vformat(TTR("Z: %s\n"), rtos(current_camera->get_position().z).pad_decimals(1));
  2398. text += "\n";
  2399. text += vformat(
  2400. TTR("Size: %s (%.1fMP)\n"),
  2401. viewport_size,
  2402. viewport->get_size().x * viewport->get_size().y * 0.000001);
  2403. text += "\n";
  2404. text += vformat(TTR("Objects: %d\n"), viewport->get_render_info(Viewport::RENDER_INFO_TYPE_VISIBLE, Viewport::RENDER_INFO_OBJECTS_IN_FRAME));
  2405. text += vformat(TTR("Primitives: %d\n"), viewport->get_render_info(Viewport::RENDER_INFO_TYPE_VISIBLE, Viewport::RENDER_INFO_PRIMITIVES_IN_FRAME));
  2406. text += vformat(TTR("Draw Calls: %d"), viewport->get_render_info(Viewport::RENDER_INFO_TYPE_VISIBLE, Viewport::RENDER_INFO_DRAW_CALLS_IN_FRAME));
  2407. info_label->set_text(text);
  2408. }
  2409. // FPS Counter.
  2410. bool show_fps = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_FRAME_TIME));
  2411. if (show_fps != fps_label->is_visible()) {
  2412. cpu_time_label->set_visible(show_fps);
  2413. gpu_time_label->set_visible(show_fps);
  2414. fps_label->set_visible(show_fps);
  2415. RS::get_singleton()->viewport_set_measure_render_time(viewport->get_viewport_rid(), show_fps);
  2416. for (int i = 0; i < FRAME_TIME_HISTORY; i++) {
  2417. // Initialize to 120 FPS, so that the initial estimation until we get enough data is always reasonable.
  2418. cpu_time_history[i] = 8.333333;
  2419. gpu_time_history[i] = 8.333333;
  2420. }
  2421. cpu_time_history_index = 0;
  2422. gpu_time_history_index = 0;
  2423. }
  2424. if (show_fps) {
  2425. cpu_time_history[cpu_time_history_index] = RS::get_singleton()->viewport_get_measured_render_time_cpu(viewport->get_viewport_rid());
  2426. cpu_time_history_index = (cpu_time_history_index + 1) % FRAME_TIME_HISTORY;
  2427. double cpu_time = 0.0;
  2428. for (int i = 0; i < FRAME_TIME_HISTORY; i++) {
  2429. cpu_time += cpu_time_history[i];
  2430. }
  2431. cpu_time /= FRAME_TIME_HISTORY;
  2432. // Prevent unrealistically low values.
  2433. cpu_time = MAX(0.01, cpu_time);
  2434. gpu_time_history[gpu_time_history_index] = RS::get_singleton()->viewport_get_measured_render_time_gpu(viewport->get_viewport_rid());
  2435. gpu_time_history_index = (gpu_time_history_index + 1) % FRAME_TIME_HISTORY;
  2436. double gpu_time = 0.0;
  2437. for (int i = 0; i < FRAME_TIME_HISTORY; i++) {
  2438. gpu_time += gpu_time_history[i];
  2439. }
  2440. gpu_time /= FRAME_TIME_HISTORY;
  2441. // Prevent division by zero for the FPS counter (and unrealistically low values).
  2442. // This limits the reported FPS to 100000.
  2443. gpu_time = MAX(0.01, gpu_time);
  2444. // Color labels depending on performance level ("good" = green, "OK" = yellow, "bad" = red).
  2445. // Middle point is at 15 ms.
  2446. cpu_time_label->set_text(vformat(TTR("CPU Time: %s ms"), rtos(cpu_time).pad_decimals(2)));
  2447. cpu_time_label->add_theme_color_override(
  2448. "font_color",
  2449. frame_time_gradient->get_color_at_offset(
  2450. Math::remap(cpu_time, 0, 30, 0, 1)));
  2451. gpu_time_label->set_text(vformat(TTR("GPU Time: %s ms"), rtos(gpu_time).pad_decimals(2)));
  2452. // Middle point is at 15 ms.
  2453. gpu_time_label->add_theme_color_override(
  2454. "font_color",
  2455. frame_time_gradient->get_color_at_offset(
  2456. Math::remap(gpu_time, 0, 30, 0, 1)));
  2457. const double fps = 1000.0 / gpu_time;
  2458. fps_label->set_text(vformat(TTR("FPS: %d"), fps));
  2459. // Middle point is at 60 FPS.
  2460. fps_label->add_theme_color_override(
  2461. "font_color",
  2462. frame_time_gradient->get_color_at_offset(
  2463. Math::remap(fps, 110, 10, 0, 1)));
  2464. }
  2465. bool show_cinema = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW));
  2466. cinema_label->set_visible(show_cinema);
  2467. if (show_cinema) {
  2468. float cinema_half_width = cinema_label->get_size().width / 2.0f;
  2469. cinema_label->set_anchor_and_offset(SIDE_LEFT, 0.5f, -cinema_half_width);
  2470. }
  2471. if (lock_rotation) {
  2472. float locked_half_width = locked_label->get_size().width / 2.0f;
  2473. locked_label->set_anchor_and_offset(SIDE_LEFT, 0.5f, -locked_half_width);
  2474. }
  2475. } break;
  2476. case NOTIFICATION_PHYSICS_PROCESS: {
  2477. if (!update_preview_node) {
  2478. return;
  2479. }
  2480. if (preview_node->is_inside_tree()) {
  2481. preview_node_pos = spatial_editor->snap_point(_get_instance_position(preview_node_viewport_pos));
  2482. Transform3D preview_gl_transform = Transform3D(Basis(), preview_node_pos);
  2483. preview_node->set_global_transform(preview_gl_transform);
  2484. if (!preview_node->is_visible()) {
  2485. preview_node->show();
  2486. }
  2487. }
  2488. update_preview_node = false;
  2489. } break;
  2490. case NOTIFICATION_ENTER_TREE: {
  2491. surface->connect("draw", callable_mp(this, &Node3DEditorViewport::_draw));
  2492. surface->connect("gui_input", callable_mp(this, &Node3DEditorViewport::_sinput));
  2493. surface->connect("mouse_entered", callable_mp(this, &Node3DEditorViewport::_surface_mouse_enter));
  2494. surface->connect("mouse_exited", callable_mp(this, &Node3DEditorViewport::_surface_mouse_exit));
  2495. surface->connect("focus_entered", callable_mp(this, &Node3DEditorViewport::_surface_focus_enter));
  2496. surface->connect("focus_exited", callable_mp(this, &Node3DEditorViewport::_surface_focus_exit));
  2497. _init_gizmo_instance(index);
  2498. } break;
  2499. case NOTIFICATION_EXIT_TREE: {
  2500. _finish_gizmo_instances();
  2501. } break;
  2502. case NOTIFICATION_THEME_CHANGED: {
  2503. view_menu->set_icon(get_editor_theme_icon(SNAME("GuiTabMenuHl")));
  2504. preview_camera->set_icon(get_editor_theme_icon(SNAME("Camera3D")));
  2505. Control *gui_base = EditorNode::get_singleton()->get_gui_base();
  2506. view_menu->add_theme_style_override("normal", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2507. view_menu->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2508. view_menu->add_theme_style_override("pressed", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2509. view_menu->add_theme_style_override("focus", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2510. view_menu->add_theme_style_override("disabled", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2511. preview_camera->add_theme_style_override("normal", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2512. preview_camera->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2513. preview_camera->add_theme_style_override("pressed", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2514. preview_camera->add_theme_style_override("focus", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2515. preview_camera->add_theme_style_override("disabled", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2516. frame_time_gradient->set_color(0, get_theme_color(SNAME("success_color"), EditorStringName(Editor)));
  2517. frame_time_gradient->set_color(1, get_theme_color(SNAME("warning_color"), EditorStringName(Editor)));
  2518. frame_time_gradient->set_color(2, get_theme_color(SNAME("error_color"), EditorStringName(Editor)));
  2519. info_label->add_theme_style_override("normal", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2520. cpu_time_label->add_theme_style_override("normal", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2521. gpu_time_label->add_theme_style_override("normal", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2522. fps_label->add_theme_style_override("normal", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2523. cinema_label->add_theme_style_override("normal", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2524. locked_label->add_theme_style_override("normal", gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles)));
  2525. } break;
  2526. case NOTIFICATION_DRAG_END: {
  2527. // Clear preview material when dropped outside applicable object.
  2528. if (spatial_editor->get_preview_material().is_valid() && !is_drag_successful()) {
  2529. _remove_preview_material();
  2530. }
  2531. } break;
  2532. }
  2533. }
  2534. static void draw_indicator_bar(Control &p_surface, real_t p_fill, const Ref<Texture2D> p_icon, const Ref<Font> p_font, int p_font_size, const String &p_text, const Color &p_color) {
  2535. // Adjust bar size from control height
  2536. const Vector2 surface_size = p_surface.get_size();
  2537. const real_t h = surface_size.y / 2.0;
  2538. const real_t y = (surface_size.y - h) / 2.0;
  2539. const Rect2 r(10 * EDSCALE, y, 6 * EDSCALE, h);
  2540. const real_t sy = r.size.y * p_fill;
  2541. // Note: because this bar appears over the viewport, it has to stay readable for any background color
  2542. // Draw both neutral dark and bright colors to account this
  2543. p_surface.draw_rect(r, p_color * Color(1, 1, 1, 0.2));
  2544. p_surface.draw_rect(Rect2(r.position.x, r.position.y + r.size.y - sy, r.size.x, sy), p_color * Color(1, 1, 1, 0.6));
  2545. p_surface.draw_rect(r.grow(1), Color(0, 0, 0, 0.7), false, Math::round(EDSCALE));
  2546. const Vector2 icon_size = p_icon->get_size();
  2547. const Vector2 icon_pos = Vector2(r.position.x - (icon_size.x - r.size.x) / 2, r.position.y + r.size.y + 2 * EDSCALE);
  2548. p_surface.draw_texture(p_icon, icon_pos, p_color);
  2549. // Draw text below the bar (for speed/zoom information).
  2550. p_surface.draw_string_outline(p_font, Vector2(icon_pos.x, icon_pos.y + icon_size.y + 16 * EDSCALE), p_text, HORIZONTAL_ALIGNMENT_LEFT, -1.f, p_font_size, Math::round(2 * EDSCALE), Color(0, 0, 0));
  2551. p_surface.draw_string(p_font, Vector2(icon_pos.x, icon_pos.y + icon_size.y + 16 * EDSCALE), p_text, HORIZONTAL_ALIGNMENT_LEFT, -1.f, p_font_size, p_color);
  2552. }
  2553. void Node3DEditorViewport::_draw() {
  2554. EditorPluginList *over_plugin_list = EditorNode::get_singleton()->get_editor_plugins_over();
  2555. if (!over_plugin_list->is_empty()) {
  2556. over_plugin_list->forward_3d_draw_over_viewport(surface);
  2557. }
  2558. EditorPluginList *force_over_plugin_list = EditorNode::get_singleton()->get_editor_plugins_force_over();
  2559. if (!force_over_plugin_list->is_empty()) {
  2560. force_over_plugin_list->forward_3d_force_draw_over_viewport(surface);
  2561. }
  2562. if (surface->has_focus()) {
  2563. Size2 size = surface->get_size();
  2564. Rect2 r = Rect2(Point2(), size);
  2565. get_theme_stylebox(SNAME("FocusViewport"), EditorStringName(EditorStyles))->draw(surface->get_canvas_item(), r);
  2566. }
  2567. if (cursor.region_select) {
  2568. const Rect2 selection_rect = Rect2(cursor.region_begin, cursor.region_end - cursor.region_begin);
  2569. surface->draw_rect(
  2570. selection_rect,
  2571. get_theme_color(SNAME("box_selection_fill_color"), EditorStringName(Editor)));
  2572. surface->draw_rect(
  2573. selection_rect,
  2574. get_theme_color(SNAME("box_selection_stroke_color"), EditorStringName(Editor)),
  2575. false,
  2576. Math::round(EDSCALE));
  2577. }
  2578. RID ci = surface->get_canvas_item();
  2579. if (message_time > 0) {
  2580. Ref<Font> font = get_theme_font(SNAME("font"), SNAME("Label"));
  2581. int font_size = get_theme_font_size(SNAME("font_size"), SNAME("Label"));
  2582. Point2 msgpos = Point2(5, get_size().y - 20);
  2583. font->draw_string(ci, msgpos + Point2(1, 1), message, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, Color(0, 0, 0, 0.8));
  2584. font->draw_string(ci, msgpos + Point2(-1, -1), message, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, Color(0, 0, 0, 0.8));
  2585. font->draw_string(ci, msgpos, message, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, Color(1, 1, 1, 1));
  2586. }
  2587. if (_edit.mode == TRANSFORM_ROTATE && _edit.show_rotation_line) {
  2588. Point2 center = _point_to_screen(_edit.center);
  2589. Color handle_color;
  2590. switch (_edit.plane) {
  2591. case TRANSFORM_X_AXIS:
  2592. handle_color = get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor));
  2593. break;
  2594. case TRANSFORM_Y_AXIS:
  2595. handle_color = get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor));
  2596. break;
  2597. case TRANSFORM_Z_AXIS:
  2598. handle_color = get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor));
  2599. break;
  2600. default:
  2601. handle_color = get_theme_color(SNAME("accent_color"), EditorStringName(Editor));
  2602. break;
  2603. }
  2604. handle_color = handle_color.from_hsv(handle_color.get_h(), 0.25, 1.0, 1);
  2605. RenderingServer::get_singleton()->canvas_item_add_line(
  2606. ci,
  2607. _edit.mouse_pos,
  2608. center,
  2609. handle_color,
  2610. Math::round(2 * EDSCALE));
  2611. }
  2612. if (previewing) {
  2613. Size2 ss = Size2(GLOBAL_GET("display/window/size/viewport_width"), GLOBAL_GET("display/window/size/viewport_height"));
  2614. float aspect = ss.aspect();
  2615. Size2 s = get_size();
  2616. Rect2 draw_rect;
  2617. switch (previewing->get_keep_aspect_mode()) {
  2618. case Camera3D::KEEP_WIDTH: {
  2619. draw_rect.size = Size2(s.width, s.width / aspect);
  2620. draw_rect.position.x = 0;
  2621. draw_rect.position.y = (s.height - draw_rect.size.y) * 0.5;
  2622. } break;
  2623. case Camera3D::KEEP_HEIGHT: {
  2624. draw_rect.size = Size2(s.height * aspect, s.height);
  2625. draw_rect.position.y = 0;
  2626. draw_rect.position.x = (s.width - draw_rect.size.x) * 0.5;
  2627. } break;
  2628. }
  2629. draw_rect = Rect2(Vector2(), s).intersection(draw_rect);
  2630. surface->draw_rect(draw_rect, Color(0.6, 0.6, 0.1, 0.5), false, Math::round(2 * EDSCALE));
  2631. } else {
  2632. if (zoom_indicator_delay > 0.0) {
  2633. if (is_freelook_active()) {
  2634. // Show speed
  2635. real_t min_speed = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
  2636. real_t max_speed = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
  2637. real_t scale_length = (max_speed - min_speed);
  2638. if (!Math::is_zero_approx(scale_length)) {
  2639. real_t logscale_t = 1.0 - Math::log1p(freelook_speed - min_speed) / Math::log1p(scale_length);
  2640. // Display the freelook speed to help the user get a better sense of scale.
  2641. const int precision = freelook_speed < 1.0 ? 2 : 1;
  2642. draw_indicator_bar(
  2643. *surface,
  2644. 1.0 - logscale_t,
  2645. get_editor_theme_icon(SNAME("ViewportSpeed")),
  2646. get_theme_font(SNAME("font"), SNAME("Label")),
  2647. get_theme_font_size(SNAME("font_size"), SNAME("Label")),
  2648. vformat("%s m/s", String::num(freelook_speed).pad_decimals(precision)),
  2649. Color(1.0, 0.95, 0.7));
  2650. }
  2651. } else {
  2652. // Show zoom
  2653. zoom_limit_label->set_visible(zoom_failed_attempts_count > 15);
  2654. real_t min_distance = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
  2655. real_t max_distance = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
  2656. real_t scale_length = (max_distance - min_distance);
  2657. if (!Math::is_zero_approx(scale_length)) {
  2658. real_t logscale_t = 1.0 - Math::log1p(cursor.distance - min_distance) / Math::log1p(scale_length);
  2659. // Display the zoom center distance to help the user get a better sense of scale.
  2660. const int precision = cursor.distance < 1.0 ? 2 : 1;
  2661. draw_indicator_bar(
  2662. *surface,
  2663. logscale_t,
  2664. get_editor_theme_icon(SNAME("ViewportZoom")),
  2665. get_theme_font(SNAME("font"), SNAME("Label")),
  2666. get_theme_font_size(SNAME("font_size"), SNAME("Label")),
  2667. vformat("%s m", String::num(cursor.distance).pad_decimals(precision)),
  2668. Color(0.7, 0.95, 1.0));
  2669. }
  2670. }
  2671. }
  2672. }
  2673. }
  2674. void Node3DEditorViewport::_menu_option(int p_option) {
  2675. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  2676. switch (p_option) {
  2677. case VIEW_TOP: {
  2678. cursor.y_rot = 0;
  2679. cursor.x_rot = Math_PI / 2.0;
  2680. set_message(TTR("Top View."), 2);
  2681. view_type = VIEW_TYPE_TOP;
  2682. _set_auto_orthogonal();
  2683. _update_name();
  2684. } break;
  2685. case VIEW_BOTTOM: {
  2686. cursor.y_rot = 0;
  2687. cursor.x_rot = -Math_PI / 2.0;
  2688. set_message(TTR("Bottom View."), 2);
  2689. view_type = VIEW_TYPE_BOTTOM;
  2690. _set_auto_orthogonal();
  2691. _update_name();
  2692. } break;
  2693. case VIEW_LEFT: {
  2694. cursor.x_rot = 0;
  2695. cursor.y_rot = Math_PI / 2.0;
  2696. set_message(TTR("Left View."), 2);
  2697. view_type = VIEW_TYPE_LEFT;
  2698. _set_auto_orthogonal();
  2699. _update_name();
  2700. } break;
  2701. case VIEW_RIGHT: {
  2702. cursor.x_rot = 0;
  2703. cursor.y_rot = -Math_PI / 2.0;
  2704. set_message(TTR("Right View."), 2);
  2705. view_type = VIEW_TYPE_RIGHT;
  2706. _set_auto_orthogonal();
  2707. _update_name();
  2708. } break;
  2709. case VIEW_FRONT: {
  2710. cursor.x_rot = 0;
  2711. cursor.y_rot = 0;
  2712. set_message(TTR("Front View."), 2);
  2713. view_type = VIEW_TYPE_FRONT;
  2714. _set_auto_orthogonal();
  2715. _update_name();
  2716. } break;
  2717. case VIEW_REAR: {
  2718. cursor.x_rot = 0;
  2719. cursor.y_rot = Math_PI;
  2720. set_message(TTR("Rear View."), 2);
  2721. view_type = VIEW_TYPE_REAR;
  2722. _set_auto_orthogonal();
  2723. _update_name();
  2724. } break;
  2725. case VIEW_CENTER_TO_ORIGIN: {
  2726. cursor.pos = Vector3(0, 0, 0);
  2727. } break;
  2728. case VIEW_CENTER_TO_SELECTION: {
  2729. focus_selection();
  2730. } break;
  2731. case VIEW_ALIGN_TRANSFORM_WITH_VIEW: {
  2732. if (!get_selected_count()) {
  2733. break;
  2734. }
  2735. Transform3D camera_transform = camera->get_global_transform();
  2736. List<Node *> &selection = editor_selection->get_selected_node_list();
  2737. undo_redo->create_action(TTR("Align Transform with View"));
  2738. for (Node *E : selection) {
  2739. Node3D *sp = Object::cast_to<Node3D>(E);
  2740. if (!sp) {
  2741. continue;
  2742. }
  2743. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  2744. if (!se) {
  2745. continue;
  2746. }
  2747. Transform3D xform;
  2748. if (orthogonal) {
  2749. xform = sp->get_global_transform();
  2750. xform.basis = Basis::from_euler(camera_transform.basis.get_euler());
  2751. } else {
  2752. xform = camera_transform;
  2753. xform.scale_basis(sp->get_scale());
  2754. }
  2755. if (Object::cast_to<Decal>(E)) {
  2756. // Adjust rotation to match Decal's default orientation.
  2757. // This makes the decal "look" in the same direction as the camera,
  2758. // rather than pointing down relative to the camera orientation.
  2759. xform.basis.rotate_local(Vector3(1, 0, 0), Math_TAU * 0.25);
  2760. }
  2761. undo_redo->add_do_method(sp, "set_global_transform", xform);
  2762. undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
  2763. }
  2764. undo_redo->commit_action();
  2765. } break;
  2766. case VIEW_ALIGN_ROTATION_WITH_VIEW: {
  2767. if (!get_selected_count()) {
  2768. break;
  2769. }
  2770. Transform3D camera_transform = camera->get_global_transform();
  2771. List<Node *> &selection = editor_selection->get_selected_node_list();
  2772. undo_redo->create_action(TTR("Align Rotation with View"));
  2773. for (Node *E : selection) {
  2774. Node3D *sp = Object::cast_to<Node3D>(E);
  2775. if (!sp) {
  2776. continue;
  2777. }
  2778. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  2779. if (!se) {
  2780. continue;
  2781. }
  2782. Basis basis = camera_transform.basis;
  2783. if (Object::cast_to<Decal>(E)) {
  2784. // Adjust rotation to match Decal's default orientation.
  2785. // This makes the decal "look" in the same direction as the camera,
  2786. // rather than pointing down relative to the camera orientation.
  2787. basis.rotate_local(Vector3(1, 0, 0), Math_TAU * 0.25);
  2788. }
  2789. undo_redo->add_do_method(sp, "set_rotation", basis.get_euler_normalized());
  2790. undo_redo->add_undo_method(sp, "set_rotation", sp->get_rotation());
  2791. }
  2792. undo_redo->commit_action();
  2793. } break;
  2794. case VIEW_ENVIRONMENT: {
  2795. int idx = view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT);
  2796. bool current = view_menu->get_popup()->is_item_checked(idx);
  2797. current = !current;
  2798. if (current) {
  2799. camera->set_environment(Ref<Resource>());
  2800. } else {
  2801. camera->set_environment(Node3DEditor::get_singleton()->get_viewport_environment());
  2802. }
  2803. view_menu->get_popup()->set_item_checked(idx, current);
  2804. } break;
  2805. case VIEW_PERSPECTIVE: {
  2806. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
  2807. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), false);
  2808. orthogonal = false;
  2809. auto_orthogonal = false;
  2810. call_deferred(SNAME("update_transform_gizmo_view"));
  2811. _update_camera(0);
  2812. _update_name();
  2813. } break;
  2814. case VIEW_ORTHOGONAL: {
  2815. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), false);
  2816. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), true);
  2817. orthogonal = true;
  2818. auto_orthogonal = false;
  2819. call_deferred(SNAME("update_transform_gizmo_view"));
  2820. _update_camera(0);
  2821. _update_name();
  2822. } break;
  2823. case VIEW_SWITCH_PERSPECTIVE_ORTHOGONAL: {
  2824. _menu_option(orthogonal ? VIEW_PERSPECTIVE : VIEW_ORTHOGONAL);
  2825. } break;
  2826. case VIEW_AUTO_ORTHOGONAL: {
  2827. int idx = view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL);
  2828. bool current = view_menu->get_popup()->is_item_checked(idx);
  2829. current = !current;
  2830. view_menu->get_popup()->set_item_checked(idx, current);
  2831. if (auto_orthogonal) {
  2832. auto_orthogonal = false;
  2833. _update_name();
  2834. }
  2835. } break;
  2836. case VIEW_LOCK_ROTATION: {
  2837. int idx = view_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
  2838. bool current = view_menu->get_popup()->is_item_checked(idx);
  2839. _set_lock_view_rotation(!current);
  2840. } break;
  2841. case VIEW_AUDIO_LISTENER: {
  2842. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
  2843. bool current = view_menu->get_popup()->is_item_checked(idx);
  2844. current = !current;
  2845. viewport->set_as_audio_listener_3d(current);
  2846. view_menu->get_popup()->set_item_checked(idx, current);
  2847. } break;
  2848. case VIEW_AUDIO_DOPPLER: {
  2849. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
  2850. bool current = view_menu->get_popup()->is_item_checked(idx);
  2851. current = !current;
  2852. camera->set_doppler_tracking(current ? Camera3D::DOPPLER_TRACKING_IDLE_STEP : Camera3D::DOPPLER_TRACKING_DISABLED);
  2853. view_menu->get_popup()->set_item_checked(idx, current);
  2854. } break;
  2855. case VIEW_CINEMATIC_PREVIEW: {
  2856. int idx = view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
  2857. bool current = view_menu->get_popup()->is_item_checked(idx);
  2858. current = !current;
  2859. view_menu->get_popup()->set_item_checked(idx, current);
  2860. previewing_cinema = true;
  2861. _toggle_cinema_preview(current);
  2862. if (current) {
  2863. preview_camera->hide();
  2864. } else {
  2865. if (previewing != nullptr) {
  2866. preview_camera->show();
  2867. }
  2868. }
  2869. } break;
  2870. case VIEW_GIZMOS: {
  2871. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  2872. bool current = view_menu->get_popup()->is_item_checked(idx);
  2873. current = !current;
  2874. uint32_t layers = ((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + index)) | (1 << GIZMO_GRID_LAYER) | (1 << MISC_TOOL_LAYER);
  2875. if (current) {
  2876. layers |= (1 << GIZMO_EDIT_LAYER);
  2877. }
  2878. camera->set_cull_mask(layers);
  2879. view_menu->get_popup()->set_item_checked(idx, current);
  2880. } break;
  2881. case VIEW_HALF_RESOLUTION: {
  2882. int idx = view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
  2883. bool current = view_menu->get_popup()->is_item_checked(idx);
  2884. view_menu->get_popup()->set_item_checked(idx, !current);
  2885. _update_shrink();
  2886. } break;
  2887. case VIEW_INFORMATION: {
  2888. int idx = view_menu->get_popup()->get_item_index(VIEW_INFORMATION);
  2889. bool current = view_menu->get_popup()->is_item_checked(idx);
  2890. view_menu->get_popup()->set_item_checked(idx, !current);
  2891. } break;
  2892. case VIEW_FRAME_TIME: {
  2893. int idx = view_menu->get_popup()->get_item_index(VIEW_FRAME_TIME);
  2894. bool current = view_menu->get_popup()->is_item_checked(idx);
  2895. view_menu->get_popup()->set_item_checked(idx, !current);
  2896. } break;
  2897. case VIEW_DISPLAY_NORMAL:
  2898. case VIEW_DISPLAY_WIREFRAME:
  2899. case VIEW_DISPLAY_OVERDRAW:
  2900. case VIEW_DISPLAY_UNSHADED:
  2901. case VIEW_DISPLAY_LIGHTING:
  2902. case VIEW_DISPLAY_NORMAL_BUFFER:
  2903. case VIEW_DISPLAY_DEBUG_SHADOW_ATLAS:
  2904. case VIEW_DISPLAY_DEBUG_DIRECTIONAL_SHADOW_ATLAS:
  2905. case VIEW_DISPLAY_DEBUG_VOXEL_GI_ALBEDO:
  2906. case VIEW_DISPLAY_DEBUG_VOXEL_GI_LIGHTING:
  2907. case VIEW_DISPLAY_DEBUG_VOXEL_GI_EMISSION:
  2908. case VIEW_DISPLAY_DEBUG_SCENE_LUMINANCE:
  2909. case VIEW_DISPLAY_DEBUG_SSAO:
  2910. case VIEW_DISPLAY_DEBUG_SSIL:
  2911. case VIEW_DISPLAY_DEBUG_PSSM_SPLITS:
  2912. case VIEW_DISPLAY_DEBUG_DECAL_ATLAS:
  2913. case VIEW_DISPLAY_DEBUG_SDFGI:
  2914. case VIEW_DISPLAY_DEBUG_SDFGI_PROBES:
  2915. case VIEW_DISPLAY_DEBUG_GI_BUFFER:
  2916. case VIEW_DISPLAY_DEBUG_DISABLE_LOD:
  2917. case VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS:
  2918. case VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS:
  2919. case VIEW_DISPLAY_DEBUG_CLUSTER_DECALS:
  2920. case VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES:
  2921. case VIEW_DISPLAY_DEBUG_OCCLUDERS:
  2922. case VIEW_DISPLAY_MOTION_VECTORS:
  2923. case VIEW_DISPLAY_INTERNAL_BUFFER: {
  2924. static const int display_options[] = {
  2925. VIEW_DISPLAY_NORMAL,
  2926. VIEW_DISPLAY_WIREFRAME,
  2927. VIEW_DISPLAY_OVERDRAW,
  2928. VIEW_DISPLAY_UNSHADED,
  2929. VIEW_DISPLAY_LIGHTING,
  2930. VIEW_DISPLAY_NORMAL_BUFFER,
  2931. VIEW_DISPLAY_DEBUG_SHADOW_ATLAS,
  2932. VIEW_DISPLAY_DEBUG_DIRECTIONAL_SHADOW_ATLAS,
  2933. VIEW_DISPLAY_DEBUG_VOXEL_GI_ALBEDO,
  2934. VIEW_DISPLAY_DEBUG_VOXEL_GI_LIGHTING,
  2935. VIEW_DISPLAY_DEBUG_VOXEL_GI_EMISSION,
  2936. VIEW_DISPLAY_DEBUG_SCENE_LUMINANCE,
  2937. VIEW_DISPLAY_DEBUG_SSAO,
  2938. VIEW_DISPLAY_DEBUG_SSIL,
  2939. VIEW_DISPLAY_DEBUG_GI_BUFFER,
  2940. VIEW_DISPLAY_DEBUG_DISABLE_LOD,
  2941. VIEW_DISPLAY_DEBUG_PSSM_SPLITS,
  2942. VIEW_DISPLAY_DEBUG_DECAL_ATLAS,
  2943. VIEW_DISPLAY_DEBUG_SDFGI,
  2944. VIEW_DISPLAY_DEBUG_SDFGI_PROBES,
  2945. VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS,
  2946. VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS,
  2947. VIEW_DISPLAY_DEBUG_CLUSTER_DECALS,
  2948. VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES,
  2949. VIEW_DISPLAY_DEBUG_OCCLUDERS,
  2950. VIEW_DISPLAY_MOTION_VECTORS,
  2951. VIEW_DISPLAY_INTERNAL_BUFFER,
  2952. VIEW_MAX
  2953. };
  2954. static const Viewport::DebugDraw debug_draw_modes[] = {
  2955. Viewport::DEBUG_DRAW_DISABLED,
  2956. Viewport::DEBUG_DRAW_WIREFRAME,
  2957. Viewport::DEBUG_DRAW_OVERDRAW,
  2958. Viewport::DEBUG_DRAW_UNSHADED,
  2959. Viewport::DEBUG_DRAW_LIGHTING,
  2960. Viewport::DEBUG_DRAW_NORMAL_BUFFER,
  2961. Viewport::DEBUG_DRAW_SHADOW_ATLAS,
  2962. Viewport::DEBUG_DRAW_DIRECTIONAL_SHADOW_ATLAS,
  2963. Viewport::DEBUG_DRAW_VOXEL_GI_ALBEDO,
  2964. Viewport::DEBUG_DRAW_VOXEL_GI_LIGHTING,
  2965. Viewport::DEBUG_DRAW_VOXEL_GI_EMISSION,
  2966. Viewport::DEBUG_DRAW_SCENE_LUMINANCE,
  2967. Viewport::DEBUG_DRAW_SSAO,
  2968. Viewport::DEBUG_DRAW_SSIL,
  2969. Viewport::DEBUG_DRAW_GI_BUFFER,
  2970. Viewport::DEBUG_DRAW_DISABLE_LOD,
  2971. Viewport::DEBUG_DRAW_PSSM_SPLITS,
  2972. Viewport::DEBUG_DRAW_DECAL_ATLAS,
  2973. Viewport::DEBUG_DRAW_SDFGI,
  2974. Viewport::DEBUG_DRAW_SDFGI_PROBES,
  2975. Viewport::DEBUG_DRAW_CLUSTER_OMNI_LIGHTS,
  2976. Viewport::DEBUG_DRAW_CLUSTER_SPOT_LIGHTS,
  2977. Viewport::DEBUG_DRAW_CLUSTER_DECALS,
  2978. Viewport::DEBUG_DRAW_CLUSTER_REFLECTION_PROBES,
  2979. Viewport::DEBUG_DRAW_OCCLUDERS,
  2980. Viewport::DEBUG_DRAW_MOTION_VECTORS,
  2981. Viewport::DEBUG_DRAW_INTERNAL_BUFFER,
  2982. };
  2983. for (int idx = 0; display_options[idx] != VIEW_MAX; idx++) {
  2984. int id = display_options[idx];
  2985. int item_idx = view_menu->get_popup()->get_item_index(id);
  2986. if (item_idx != -1) {
  2987. view_menu->get_popup()->set_item_checked(item_idx, id == p_option);
  2988. }
  2989. item_idx = display_submenu->get_item_index(id);
  2990. if (item_idx != -1) {
  2991. display_submenu->set_item_checked(item_idx, id == p_option);
  2992. }
  2993. if (id == p_option) {
  2994. viewport->set_debug_draw(debug_draw_modes[idx]);
  2995. }
  2996. }
  2997. } break;
  2998. }
  2999. }
  3000. void Node3DEditorViewport::_set_auto_orthogonal() {
  3001. if (!orthogonal && view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL))) {
  3002. _menu_option(VIEW_ORTHOGONAL);
  3003. auto_orthogonal = true;
  3004. }
  3005. }
  3006. void Node3DEditorViewport::_preview_exited_scene() {
  3007. preview_camera->disconnect("toggled", callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
  3008. preview_camera->set_pressed(false);
  3009. _toggle_camera_preview(false);
  3010. preview_camera->connect("toggled", callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
  3011. view_menu->show();
  3012. }
  3013. void Node3DEditorViewport::_init_gizmo_instance(int p_idx) {
  3014. uint32_t layer = 1 << (GIZMO_BASE_LAYER + p_idx);
  3015. for (int i = 0; i < 3; i++) {
  3016. move_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3017. RS::get_singleton()->instance_set_base(move_gizmo_instance[i], spatial_editor->get_move_gizmo(i)->get_rid());
  3018. RS::get_singleton()->instance_set_scenario(move_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3019. RS::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  3020. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3021. RS::get_singleton()->instance_set_layer_mask(move_gizmo_instance[i], layer);
  3022. RS::get_singleton()->instance_geometry_set_flag(move_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3023. RS::get_singleton()->instance_geometry_set_flag(move_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3024. move_plane_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3025. RS::get_singleton()->instance_set_base(move_plane_gizmo_instance[i], spatial_editor->get_move_plane_gizmo(i)->get_rid());
  3026. RS::get_singleton()->instance_set_scenario(move_plane_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3027. RS::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  3028. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_plane_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3029. RS::get_singleton()->instance_set_layer_mask(move_plane_gizmo_instance[i], layer);
  3030. RS::get_singleton()->instance_geometry_set_flag(move_plane_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3031. RS::get_singleton()->instance_geometry_set_flag(move_plane_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3032. rotate_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3033. RS::get_singleton()->instance_set_base(rotate_gizmo_instance[i], spatial_editor->get_rotate_gizmo(i)->get_rid());
  3034. RS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3035. RS::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  3036. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(rotate_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3037. RS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[i], layer);
  3038. RS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3039. RS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3040. scale_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3041. RS::get_singleton()->instance_set_base(scale_gizmo_instance[i], spatial_editor->get_scale_gizmo(i)->get_rid());
  3042. RS::get_singleton()->instance_set_scenario(scale_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3043. RS::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  3044. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3045. RS::get_singleton()->instance_set_layer_mask(scale_gizmo_instance[i], layer);
  3046. RS::get_singleton()->instance_geometry_set_flag(scale_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3047. RS::get_singleton()->instance_geometry_set_flag(scale_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3048. scale_plane_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3049. RS::get_singleton()->instance_set_base(scale_plane_gizmo_instance[i], spatial_editor->get_scale_plane_gizmo(i)->get_rid());
  3050. RS::get_singleton()->instance_set_scenario(scale_plane_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3051. RS::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  3052. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_plane_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3053. RS::get_singleton()->instance_set_layer_mask(scale_plane_gizmo_instance[i], layer);
  3054. RS::get_singleton()->instance_geometry_set_flag(scale_plane_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3055. RS::get_singleton()->instance_geometry_set_flag(scale_plane_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3056. axis_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3057. RS::get_singleton()->instance_set_base(axis_gizmo_instance[i], spatial_editor->get_axis_gizmo(i)->get_rid());
  3058. RS::get_singleton()->instance_set_scenario(axis_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3059. RS::get_singleton()->instance_set_visible(axis_gizmo_instance[i], true);
  3060. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(axis_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3061. RS::get_singleton()->instance_set_layer_mask(axis_gizmo_instance[i], layer);
  3062. RS::get_singleton()->instance_geometry_set_flag(axis_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3063. RS::get_singleton()->instance_geometry_set_flag(axis_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3064. }
  3065. // Rotation white outline
  3066. rotate_gizmo_instance[3] = RS::get_singleton()->instance_create();
  3067. RS::get_singleton()->instance_set_base(rotate_gizmo_instance[3], spatial_editor->get_rotate_gizmo(3)->get_rid());
  3068. RS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[3], get_tree()->get_root()->get_world_3d()->get_scenario());
  3069. RS::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
  3070. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(rotate_gizmo_instance[3], RS::SHADOW_CASTING_SETTING_OFF);
  3071. RS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[3], layer);
  3072. RS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[3], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3073. RS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[3], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3074. }
  3075. void Node3DEditorViewport::_finish_gizmo_instances() {
  3076. ERR_FAIL_NULL(RenderingServer::get_singleton());
  3077. for (int i = 0; i < 3; i++) {
  3078. RS::get_singleton()->free(move_gizmo_instance[i]);
  3079. RS::get_singleton()->free(move_plane_gizmo_instance[i]);
  3080. RS::get_singleton()->free(rotate_gizmo_instance[i]);
  3081. RS::get_singleton()->free(scale_gizmo_instance[i]);
  3082. RS::get_singleton()->free(scale_plane_gizmo_instance[i]);
  3083. RS::get_singleton()->free(axis_gizmo_instance[i]);
  3084. }
  3085. // Rotation white outline
  3086. RS::get_singleton()->free(rotate_gizmo_instance[3]);
  3087. }
  3088. void Node3DEditorViewport::_toggle_camera_preview(bool p_activate) {
  3089. ERR_FAIL_COND(p_activate && !preview);
  3090. ERR_FAIL_COND(!p_activate && !previewing);
  3091. previewing_camera = p_activate;
  3092. _update_navigation_controls_visibility();
  3093. if (!p_activate) {
  3094. previewing->disconnect("tree_exiting", callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  3095. previewing = nullptr;
  3096. RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
  3097. if (!preview) {
  3098. preview_camera->hide();
  3099. }
  3100. surface->queue_redraw();
  3101. } else {
  3102. previewing = preview;
  3103. previewing->connect("tree_exiting", callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  3104. RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), preview->get_camera()); //replace
  3105. surface->queue_redraw();
  3106. }
  3107. }
  3108. void Node3DEditorViewport::_toggle_cinema_preview(bool p_activate) {
  3109. previewing_cinema = p_activate;
  3110. _update_navigation_controls_visibility();
  3111. if (!previewing_cinema) {
  3112. if (previewing != nullptr) {
  3113. previewing->disconnect("tree_exited", callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  3114. }
  3115. previewing = nullptr;
  3116. RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
  3117. preview_camera->set_pressed(false);
  3118. if (!preview) {
  3119. preview_camera->hide();
  3120. } else {
  3121. preview_camera->show();
  3122. }
  3123. view_menu->show();
  3124. surface->queue_redraw();
  3125. }
  3126. }
  3127. void Node3DEditorViewport::_selection_result_pressed(int p_result) {
  3128. if (selection_results_menu.size() <= p_result) {
  3129. return;
  3130. }
  3131. clicked = selection_results_menu[p_result].item->get_instance_id();
  3132. if (clicked.is_valid()) {
  3133. _select_clicked(spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT);
  3134. }
  3135. selection_results_menu.clear();
  3136. }
  3137. void Node3DEditorViewport::_selection_menu_hide() {
  3138. selection_results.clear();
  3139. selection_menu->clear();
  3140. selection_menu->reset_size();
  3141. }
  3142. void Node3DEditorViewport::set_can_preview(Camera3D *p_preview) {
  3143. preview = p_preview;
  3144. if (!preview_camera->is_pressed() && !previewing_cinema) {
  3145. preview_camera->set_visible(p_preview);
  3146. }
  3147. }
  3148. void Node3DEditorViewport::update_transform_gizmo_view() {
  3149. if (!is_visible_in_tree()) {
  3150. return;
  3151. }
  3152. Transform3D xform = spatial_editor->get_gizmo_transform();
  3153. Transform3D camera_xform = camera->get_transform();
  3154. if (xform.origin.is_equal_approx(camera_xform.origin)) {
  3155. for (int i = 0; i < 3; i++) {
  3156. RenderingServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  3157. RenderingServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  3158. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  3159. RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  3160. RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  3161. RenderingServer::get_singleton()->instance_set_visible(axis_gizmo_instance[i], false);
  3162. }
  3163. // Rotation white outline
  3164. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
  3165. return;
  3166. }
  3167. const Vector3 camz = -camera_xform.get_basis().get_column(2).normalized();
  3168. const Vector3 camy = -camera_xform.get_basis().get_column(1).normalized();
  3169. const Plane p = Plane(camz, camera_xform.origin);
  3170. const real_t gizmo_d = MAX(Math::abs(p.distance_to(xform.origin)), CMP_EPSILON);
  3171. const real_t d0 = camera->unproject_position(camera_xform.origin + camz * gizmo_d).y;
  3172. const real_t d1 = camera->unproject_position(camera_xform.origin + camz * gizmo_d + camy).y;
  3173. const real_t dd = MAX(Math::abs(d0 - d1), CMP_EPSILON);
  3174. const real_t gizmo_size = EDITOR_GET("editors/3d/manipulator_gizmo_size");
  3175. // At low viewport heights, multiply the gizmo scale based on the viewport height.
  3176. // This prevents the gizmo from growing very large and going outside the viewport.
  3177. const int viewport_base_height = 400 * MAX(1, EDSCALE);
  3178. gizmo_scale =
  3179. (gizmo_size / Math::abs(dd)) * MAX(1, EDSCALE) *
  3180. MIN(viewport_base_height, subviewport_container->get_size().height) / viewport_base_height /
  3181. subviewport_container->get_stretch_shrink();
  3182. Vector3 scale = Vector3(1, 1, 1) * gizmo_scale;
  3183. // if the determinant is zero, we should disable the gizmo from being rendered
  3184. // this prevents supplying bad values to the renderer and then having to filter it out again
  3185. if (xform.basis.determinant() == 0) {
  3186. for (int i = 0; i < 3; i++) {
  3187. RenderingServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  3188. RenderingServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  3189. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  3190. RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  3191. RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  3192. }
  3193. // Rotation white outline
  3194. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
  3195. return;
  3196. }
  3197. bool show_gizmo = spatial_editor->is_gizmo_visible() && !_edit.instant;
  3198. for (int i = 0; i < 3; i++) {
  3199. Transform3D axis_angle;
  3200. if (xform.basis.get_column(i).normalized().dot(xform.basis.get_column((i + 1) % 3).normalized()) < 1.0) {
  3201. axis_angle = axis_angle.looking_at(xform.basis.get_column(i).normalized(), xform.basis.get_column((i + 1) % 3).normalized());
  3202. }
  3203. axis_angle.basis.scale(scale);
  3204. axis_angle.origin = xform.origin;
  3205. RenderingServer::get_singleton()->instance_set_transform(move_gizmo_instance[i], axis_angle);
  3206. RenderingServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE));
  3207. RenderingServer::get_singleton()->instance_set_transform(move_plane_gizmo_instance[i], axis_angle);
  3208. RenderingServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE));
  3209. RenderingServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[i], axis_angle);
  3210. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE));
  3211. RenderingServer::get_singleton()->instance_set_transform(scale_gizmo_instance[i], axis_angle);
  3212. RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE));
  3213. RenderingServer::get_singleton()->instance_set_transform(scale_plane_gizmo_instance[i], axis_angle);
  3214. RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE));
  3215. RenderingServer::get_singleton()->instance_set_transform(axis_gizmo_instance[i], xform);
  3216. }
  3217. bool show_axes = spatial_editor->is_gizmo_visible() && _edit.mode != TRANSFORM_NONE;
  3218. RenderingServer *rs = RenderingServer::get_singleton();
  3219. rs->instance_set_visible(axis_gizmo_instance[0], show_axes && (_edit.plane == TRANSFORM_X_AXIS || _edit.plane == TRANSFORM_XY || _edit.plane == TRANSFORM_XZ));
  3220. rs->instance_set_visible(axis_gizmo_instance[1], show_axes && (_edit.plane == TRANSFORM_Y_AXIS || _edit.plane == TRANSFORM_XY || _edit.plane == TRANSFORM_YZ));
  3221. rs->instance_set_visible(axis_gizmo_instance[2], show_axes && (_edit.plane == TRANSFORM_Z_AXIS || _edit.plane == TRANSFORM_XZ || _edit.plane == TRANSFORM_YZ));
  3222. // Rotation white outline
  3223. xform.orthonormalize();
  3224. xform.basis.scale(scale);
  3225. RenderingServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[3], xform);
  3226. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE));
  3227. }
  3228. void Node3DEditorViewport::set_state(const Dictionary &p_state) {
  3229. if (p_state.has("position")) {
  3230. cursor.pos = p_state["position"];
  3231. }
  3232. if (p_state.has("x_rotation")) {
  3233. cursor.x_rot = p_state["x_rotation"];
  3234. }
  3235. if (p_state.has("y_rotation")) {
  3236. cursor.y_rot = p_state["y_rotation"];
  3237. }
  3238. if (p_state.has("distance")) {
  3239. cursor.distance = p_state["distance"];
  3240. }
  3241. if (p_state.has("orthogonal")) {
  3242. bool orth = p_state["orthogonal"];
  3243. _menu_option(orth ? VIEW_ORTHOGONAL : VIEW_PERSPECTIVE);
  3244. }
  3245. if (p_state.has("view_type")) {
  3246. view_type = ViewType(p_state["view_type"].operator int());
  3247. _update_name();
  3248. }
  3249. if (p_state.has("auto_orthogonal")) {
  3250. auto_orthogonal = p_state["auto_orthogonal"];
  3251. _update_name();
  3252. }
  3253. if (p_state.has("auto_orthogonal_enabled")) {
  3254. bool enabled = p_state["auto_orthogonal_enabled"];
  3255. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL), enabled);
  3256. }
  3257. if (p_state.has("display_mode")) {
  3258. int display = p_state["display_mode"];
  3259. int idx = view_menu->get_popup()->get_item_index(display);
  3260. if (idx != -1 && !view_menu->get_popup()->is_item_checked(idx)) {
  3261. _menu_option(display);
  3262. } else {
  3263. idx = display_submenu->get_item_index(display);
  3264. if (idx != -1 && !display_submenu->is_item_checked(idx)) {
  3265. _menu_option(display);
  3266. }
  3267. }
  3268. }
  3269. if (p_state.has("lock_rotation")) {
  3270. _set_lock_view_rotation(p_state["lock_rotation"]);
  3271. }
  3272. if (p_state.has("use_environment")) {
  3273. bool env = p_state["use_environment"];
  3274. if (env != camera->get_environment().is_valid()) {
  3275. _menu_option(VIEW_ENVIRONMENT);
  3276. }
  3277. }
  3278. if (p_state.has("listener")) {
  3279. bool listener = p_state["listener"];
  3280. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
  3281. viewport->set_as_audio_listener_3d(listener);
  3282. view_menu->get_popup()->set_item_checked(idx, listener);
  3283. }
  3284. if (p_state.has("doppler")) {
  3285. bool doppler = p_state["doppler"];
  3286. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
  3287. camera->set_doppler_tracking(doppler ? Camera3D::DOPPLER_TRACKING_IDLE_STEP : Camera3D::DOPPLER_TRACKING_DISABLED);
  3288. view_menu->get_popup()->set_item_checked(idx, doppler);
  3289. }
  3290. if (p_state.has("gizmos")) {
  3291. bool gizmos = p_state["gizmos"];
  3292. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  3293. if (view_menu->get_popup()->is_item_checked(idx) != gizmos) {
  3294. _menu_option(VIEW_GIZMOS);
  3295. }
  3296. }
  3297. if (p_state.has("information")) {
  3298. bool information = p_state["information"];
  3299. int idx = view_menu->get_popup()->get_item_index(VIEW_INFORMATION);
  3300. if (view_menu->get_popup()->is_item_checked(idx) != information) {
  3301. _menu_option(VIEW_INFORMATION);
  3302. }
  3303. }
  3304. if (p_state.has("frame_time")) {
  3305. bool fps = p_state["frame_time"];
  3306. int idx = view_menu->get_popup()->get_item_index(VIEW_FRAME_TIME);
  3307. if (view_menu->get_popup()->is_item_checked(idx) != fps) {
  3308. _menu_option(VIEW_FRAME_TIME);
  3309. }
  3310. }
  3311. if (p_state.has("half_res")) {
  3312. bool half_res = p_state["half_res"];
  3313. int idx = view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
  3314. view_menu->get_popup()->set_item_checked(idx, half_res);
  3315. _update_shrink();
  3316. }
  3317. if (p_state.has("cinematic_preview")) {
  3318. previewing_cinema = p_state["cinematic_preview"];
  3319. int idx = view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
  3320. view_menu->get_popup()->set_item_checked(idx, previewing_cinema);
  3321. }
  3322. if (preview_camera->is_connected("toggled", callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview))) {
  3323. preview_camera->disconnect("toggled", callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
  3324. }
  3325. if (p_state.has("previewing")) {
  3326. Node *pv = EditorNode::get_singleton()->get_edited_scene()->get_node(p_state["previewing"]);
  3327. if (Object::cast_to<Camera3D>(pv)) {
  3328. previewing = Object::cast_to<Camera3D>(pv);
  3329. previewing->connect("tree_exiting", callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  3330. RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), previewing->get_camera()); //replace
  3331. surface->queue_redraw();
  3332. preview_camera->set_pressed(true);
  3333. preview_camera->show();
  3334. }
  3335. }
  3336. preview_camera->connect("toggled", callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
  3337. }
  3338. Dictionary Node3DEditorViewport::get_state() const {
  3339. Dictionary d;
  3340. d["position"] = cursor.pos;
  3341. d["x_rotation"] = cursor.x_rot;
  3342. d["y_rotation"] = cursor.y_rot;
  3343. d["distance"] = cursor.distance;
  3344. d["use_environment"] = camera->get_environment().is_valid();
  3345. d["orthogonal"] = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
  3346. d["view_type"] = view_type;
  3347. d["auto_orthogonal"] = auto_orthogonal;
  3348. d["auto_orthogonal_enabled"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL));
  3349. // Find selected display mode.
  3350. int display_mode = VIEW_DISPLAY_NORMAL;
  3351. for (int i = VIEW_DISPLAY_NORMAL; i < VIEW_DISPLAY_ADVANCED; i++) {
  3352. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(i))) {
  3353. display_mode = i;
  3354. break;
  3355. }
  3356. }
  3357. for (int i = VIEW_DISPLAY_ADVANCED + 1; i < VIEW_DISPLAY_MAX; i++) {
  3358. if (display_submenu->is_item_checked(display_submenu->get_item_index(i))) {
  3359. display_mode = i;
  3360. break;
  3361. }
  3362. }
  3363. d["display_mode"] = display_mode;
  3364. d["listener"] = viewport->is_audio_listener_3d();
  3365. d["doppler"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER));
  3366. d["gizmos"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_GIZMOS));
  3367. d["information"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_INFORMATION));
  3368. d["frame_time"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_FRAME_TIME));
  3369. d["half_res"] = subviewport_container->get_stretch_shrink() > 1;
  3370. d["cinematic_preview"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW));
  3371. if (previewing) {
  3372. d["previewing"] = EditorNode::get_singleton()->get_edited_scene()->get_path_to(previewing);
  3373. }
  3374. d["lock_rotation"] = lock_rotation;
  3375. return d;
  3376. }
  3377. void Node3DEditorViewport::_bind_methods() {
  3378. ClassDB::bind_method(D_METHOD("update_transform_gizmo_view"), &Node3DEditorViewport::update_transform_gizmo_view); // Used by call_deferred.
  3379. ADD_SIGNAL(MethodInfo("toggle_maximize_view", PropertyInfo(Variant::OBJECT, "viewport")));
  3380. ADD_SIGNAL(MethodInfo("clicked", PropertyInfo(Variant::OBJECT, "viewport")));
  3381. }
  3382. void Node3DEditorViewport::reset() {
  3383. orthogonal = false;
  3384. auto_orthogonal = false;
  3385. lock_rotation = false;
  3386. message_time = 0;
  3387. message = "";
  3388. last_message = "";
  3389. view_type = VIEW_TYPE_USER;
  3390. cursor = Cursor();
  3391. _update_name();
  3392. }
  3393. void Node3DEditorViewport::focus_selection() {
  3394. Vector3 center;
  3395. int count = 0;
  3396. const List<Node *> &selection = editor_selection->get_selected_node_list();
  3397. for (Node *E : selection) {
  3398. Node3D *sp = Object::cast_to<Node3D>(E);
  3399. if (!sp) {
  3400. continue;
  3401. }
  3402. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  3403. if (!se) {
  3404. continue;
  3405. }
  3406. if (se->gizmo.is_valid()) {
  3407. for (const KeyValue<int, Transform3D> &GE : se->subgizmos) {
  3408. center += se->gizmo->get_subgizmo_transform(GE.key).origin;
  3409. count++;
  3410. }
  3411. }
  3412. center += sp->get_global_gizmo_transform().origin;
  3413. count++;
  3414. }
  3415. if (count != 0) {
  3416. center /= count;
  3417. }
  3418. cursor.pos = center;
  3419. }
  3420. void Node3DEditorViewport::assign_pending_data_pointers(Node3D *p_preview_node, AABB *p_preview_bounds, AcceptDialog *p_accept) {
  3421. preview_node = p_preview_node;
  3422. preview_bounds = p_preview_bounds;
  3423. accept = p_accept;
  3424. }
  3425. Vector3 Node3DEditorViewport::_get_instance_position(const Point2 &p_pos) const {
  3426. const float MAX_DISTANCE = 50.0;
  3427. const float FALLBACK_DISTANCE = 5.0;
  3428. Vector3 world_ray = _get_ray(p_pos);
  3429. Vector3 world_pos = _get_ray_pos(p_pos);
  3430. PhysicsDirectSpaceState3D *ss = get_tree()->get_root()->get_world_3d()->get_direct_space_state();
  3431. PhysicsDirectSpaceState3D::RayParameters ray_params;
  3432. ray_params.from = world_pos;
  3433. ray_params.to = world_pos + world_ray * camera->get_far();
  3434. PhysicsDirectSpaceState3D::RayResult result;
  3435. if (ss->intersect_ray(ray_params, result)) {
  3436. return result.position;
  3437. }
  3438. const bool is_orthogonal = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
  3439. // The XZ plane.
  3440. Vector3 intersection;
  3441. Plane plane(Vector3(0, 1, 0));
  3442. if (plane.intersects_ray(world_pos, world_ray, &intersection)) {
  3443. if (is_orthogonal || world_pos.distance_to(intersection) <= MAX_DISTANCE) {
  3444. return intersection;
  3445. }
  3446. }
  3447. // Plane facing the camera using fallback distance.
  3448. if (is_orthogonal) {
  3449. plane = Plane(world_ray, cursor.pos - world_ray * (cursor.distance - FALLBACK_DISTANCE));
  3450. } else {
  3451. plane = Plane(world_ray, world_pos + world_ray * FALLBACK_DISTANCE);
  3452. }
  3453. if (plane.intersects_ray(world_pos, world_ray, &intersection)) {
  3454. return intersection;
  3455. }
  3456. // Not likely, but just in case...
  3457. return world_pos + world_ray * FALLBACK_DISTANCE;
  3458. }
  3459. AABB Node3DEditorViewport::_calculate_spatial_bounds(const Node3D *p_parent, bool p_exclude_top_level_transform) {
  3460. AABB bounds;
  3461. const VisualInstance3D *visual_instance = Object::cast_to<VisualInstance3D>(p_parent);
  3462. if (visual_instance) {
  3463. bounds = visual_instance->get_aabb();
  3464. }
  3465. for (int i = 0; i < p_parent->get_child_count(); i++) {
  3466. Node3D *child = Object::cast_to<Node3D>(p_parent->get_child(i));
  3467. if (child) {
  3468. AABB child_bounds = _calculate_spatial_bounds(child, false);
  3469. if (bounds.size == Vector3() && p_parent) {
  3470. bounds = child_bounds;
  3471. } else {
  3472. bounds.merge_with(child_bounds);
  3473. }
  3474. }
  3475. }
  3476. if (bounds.size == Vector3() && !p_parent) {
  3477. bounds = AABB(Vector3(-0.2, -0.2, -0.2), Vector3(0.4, 0.4, 0.4));
  3478. }
  3479. if (!p_exclude_top_level_transform) {
  3480. bounds = p_parent->get_transform().xform(bounds);
  3481. }
  3482. return bounds;
  3483. }
  3484. Node *Node3DEditorViewport::_sanitize_preview_node(Node *p_node) const {
  3485. Node3D *node_3d = Object::cast_to<Node3D>(p_node);
  3486. if (node_3d == nullptr) {
  3487. Node3D *replacement_node = memnew(Node3D);
  3488. replacement_node->set_name(p_node->get_name());
  3489. p_node->replace_by(replacement_node);
  3490. memdelete(p_node);
  3491. p_node = replacement_node;
  3492. } else {
  3493. VisualInstance3D *visual_instance = Object::cast_to<VisualInstance3D>(node_3d);
  3494. if (visual_instance == nullptr) {
  3495. Node3D *replacement_node = memnew(Node3D);
  3496. replacement_node->set_name(node_3d->get_name());
  3497. replacement_node->set_visible(node_3d->is_visible());
  3498. replacement_node->set_transform(node_3d->get_transform());
  3499. replacement_node->set_rotation_edit_mode(node_3d->get_rotation_edit_mode());
  3500. replacement_node->set_rotation_order(node_3d->get_rotation_order());
  3501. replacement_node->set_as_top_level(node_3d->is_set_as_top_level());
  3502. p_node->replace_by(replacement_node);
  3503. memdelete(p_node);
  3504. p_node = replacement_node;
  3505. }
  3506. }
  3507. for (int i = 0; i < p_node->get_child_count(); i++) {
  3508. _sanitize_preview_node(p_node->get_child(i));
  3509. }
  3510. return p_node;
  3511. }
  3512. void Node3DEditorViewport::_create_preview_node(const Vector<String> &files) const {
  3513. for (int i = 0; i < files.size(); i++) {
  3514. String path = files[i];
  3515. Ref<Resource> res = ResourceLoader::load(path);
  3516. ERR_CONTINUE(res.is_null());
  3517. Ref<PackedScene> scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
  3518. Ref<Mesh> mesh = Ref<Mesh>(Object::cast_to<Mesh>(*res));
  3519. if (mesh != nullptr || scene != nullptr) {
  3520. if (mesh != nullptr) {
  3521. MeshInstance3D *mesh_instance = memnew(MeshInstance3D);
  3522. mesh_instance->set_mesh(mesh);
  3523. preview_node->add_child(mesh_instance);
  3524. } else {
  3525. if (scene.is_valid()) {
  3526. Node *instance = scene->instantiate();
  3527. if (instance) {
  3528. instance = _sanitize_preview_node(instance);
  3529. preview_node->add_child(instance);
  3530. }
  3531. }
  3532. }
  3533. EditorNode::get_singleton()->get_scene_root()->add_child(preview_node);
  3534. }
  3535. }
  3536. *preview_bounds = _calculate_spatial_bounds(preview_node);
  3537. }
  3538. void Node3DEditorViewport::_remove_preview_node() {
  3539. if (preview_node->get_parent()) {
  3540. for (int i = preview_node->get_child_count() - 1; i >= 0; i--) {
  3541. Node *node = preview_node->get_child(i);
  3542. node->queue_free();
  3543. preview_node->remove_child(node);
  3544. }
  3545. EditorNode::get_singleton()->get_scene_root()->remove_child(preview_node);
  3546. }
  3547. }
  3548. bool Node3DEditorViewport::_apply_preview_material(ObjectID p_target, const Point2 &p_point) const {
  3549. _reset_preview_material();
  3550. if (p_target.is_null()) {
  3551. return false;
  3552. }
  3553. spatial_editor->set_preview_material_target(p_target);
  3554. Object *target_inst = ObjectDB::get_instance(p_target);
  3555. bool is_ctrl = Input::get_singleton()->is_key_pressed(Key::CTRL);
  3556. MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(target_inst);
  3557. if (is_ctrl && mesh_instance) {
  3558. Ref<Mesh> mesh = mesh_instance->get_mesh();
  3559. int surface_count = mesh->get_surface_count();
  3560. Vector3 world_ray = _get_ray(p_point);
  3561. Vector3 world_pos = _get_ray_pos(p_point);
  3562. int closest_surface = -1;
  3563. float closest_dist = 1e20;
  3564. Transform3D gt = mesh_instance->get_global_transform();
  3565. Transform3D ai = gt.affine_inverse();
  3566. Vector3 xform_ray = ai.basis.xform(world_ray).normalized();
  3567. Vector3 xform_pos = ai.xform(world_pos);
  3568. for (int surface_idx = 0; surface_idx < surface_count; surface_idx++) {
  3569. Ref<TriangleMesh> surface_mesh = mesh->generate_surface_triangle_mesh(surface_idx);
  3570. Vector3 rpos, rnorm;
  3571. if (surface_mesh->intersect_ray(xform_pos, xform_ray, rpos, rnorm)) {
  3572. Vector3 hitpos = gt.xform(rpos);
  3573. const real_t dist = world_pos.distance_to(hitpos);
  3574. if (dist < 0) {
  3575. continue;
  3576. }
  3577. if (dist < closest_dist) {
  3578. closest_surface = surface_idx;
  3579. closest_dist = dist;
  3580. }
  3581. }
  3582. }
  3583. if (closest_surface == -1) {
  3584. return false;
  3585. }
  3586. if (spatial_editor->get_preview_material() != mesh_instance->get_surface_override_material(closest_surface)) {
  3587. spatial_editor->set_preview_material_surface(closest_surface);
  3588. spatial_editor->set_preview_reset_material(mesh_instance->get_surface_override_material(closest_surface));
  3589. mesh_instance->set_surface_override_material(closest_surface, spatial_editor->get_preview_material());
  3590. }
  3591. return true;
  3592. }
  3593. GeometryInstance3D *geometry_instance = Object::cast_to<GeometryInstance3D>(target_inst);
  3594. if (geometry_instance && spatial_editor->get_preview_material() != geometry_instance->get_material_override()) {
  3595. spatial_editor->set_preview_reset_material(geometry_instance->get_material_override());
  3596. geometry_instance->set_material_override(spatial_editor->get_preview_material());
  3597. return true;
  3598. }
  3599. return false;
  3600. }
  3601. void Node3DEditorViewport::_reset_preview_material() const {
  3602. ObjectID last_target = spatial_editor->get_preview_material_target();
  3603. if (last_target.is_null()) {
  3604. return;
  3605. }
  3606. Object *last_target_inst = ObjectDB::get_instance(last_target);
  3607. MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(last_target_inst);
  3608. GeometryInstance3D *geometry_instance = Object::cast_to<GeometryInstance3D>(last_target_inst);
  3609. if (mesh_instance && spatial_editor->get_preview_material_surface() != -1) {
  3610. mesh_instance->set_surface_override_material(spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_reset_material());
  3611. spatial_editor->set_preview_material_surface(-1);
  3612. } else if (geometry_instance) {
  3613. geometry_instance->set_material_override(spatial_editor->get_preview_reset_material());
  3614. }
  3615. }
  3616. void Node3DEditorViewport::_remove_preview_material() {
  3617. preview_material_label->hide();
  3618. preview_material_label_desc->hide();
  3619. spatial_editor->set_preview_material(Ref<Material>());
  3620. spatial_editor->set_preview_reset_material(Ref<Material>());
  3621. spatial_editor->set_preview_material_target(ObjectID());
  3622. spatial_editor->set_preview_material_surface(-1);
  3623. }
  3624. bool Node3DEditorViewport::_cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node) {
  3625. if (p_desired_node->get_scene_file_path() == p_target_scene_path) {
  3626. return true;
  3627. }
  3628. int childCount = p_desired_node->get_child_count();
  3629. for (int i = 0; i < childCount; i++) {
  3630. Node *child = p_desired_node->get_child(i);
  3631. if (_cyclical_dependency_exists(p_target_scene_path, child)) {
  3632. return true;
  3633. }
  3634. }
  3635. return false;
  3636. }
  3637. bool Node3DEditorViewport::_create_instance(Node *parent, String &path, const Point2 &p_point) {
  3638. Ref<Resource> res = ResourceLoader::load(path);
  3639. ERR_FAIL_COND_V(res.is_null(), false);
  3640. Ref<PackedScene> scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
  3641. Ref<Mesh> mesh = Ref<Mesh>(Object::cast_to<Mesh>(*res));
  3642. Node *instantiated_scene = nullptr;
  3643. if (mesh != nullptr || scene != nullptr) {
  3644. if (mesh != nullptr) {
  3645. MeshInstance3D *mesh_instance = memnew(MeshInstance3D);
  3646. mesh_instance->set_mesh(mesh);
  3647. // Adjust casing according to project setting. The file name is expected to be in snake_case, but will work for others.
  3648. String name = path.get_file().get_basename();
  3649. mesh_instance->set_name(Node::adjust_name_casing(name));
  3650. instantiated_scene = mesh_instance;
  3651. } else {
  3652. if (!scene.is_valid()) { // invalid scene
  3653. return false;
  3654. } else {
  3655. instantiated_scene = scene->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
  3656. }
  3657. }
  3658. }
  3659. if (instantiated_scene == nullptr) {
  3660. return false;
  3661. }
  3662. if (!EditorNode::get_singleton()->get_edited_scene()->get_scene_file_path().is_empty()) { // Cyclic instantiation.
  3663. if (_cyclical_dependency_exists(EditorNode::get_singleton()->get_edited_scene()->get_scene_file_path(), instantiated_scene)) {
  3664. memdelete(instantiated_scene);
  3665. return false;
  3666. }
  3667. }
  3668. if (scene != nullptr) {
  3669. instantiated_scene->set_scene_file_path(ProjectSettings::get_singleton()->localize_path(path));
  3670. }
  3671. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  3672. undo_redo->add_do_method(parent, "add_child", instantiated_scene, true);
  3673. undo_redo->add_do_method(instantiated_scene, "set_owner", EditorNode::get_singleton()->get_edited_scene());
  3674. undo_redo->add_do_reference(instantiated_scene);
  3675. undo_redo->add_undo_method(parent, "remove_child", instantiated_scene);
  3676. String new_name = parent->validate_child_name(instantiated_scene);
  3677. EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
  3678. undo_redo->add_do_method(ed, "live_debug_instantiate_node", EditorNode::get_singleton()->get_edited_scene()->get_path_to(parent), path, new_name);
  3679. undo_redo->add_undo_method(ed, "live_debug_remove_node", NodePath(String(EditorNode::get_singleton()->get_edited_scene()->get_path_to(parent)) + "/" + new_name));
  3680. Node3D *node3d = Object::cast_to<Node3D>(instantiated_scene);
  3681. if (node3d) {
  3682. Transform3D gl_transform;
  3683. Node3D *parent_node3d = Object::cast_to<Node3D>(parent);
  3684. if (parent_node3d) {
  3685. gl_transform = parent_node3d->get_global_gizmo_transform();
  3686. }
  3687. gl_transform.origin = preview_node_pos;
  3688. gl_transform.basis *= node3d->get_transform().basis;
  3689. undo_redo->add_do_method(instantiated_scene, "set_global_transform", gl_transform);
  3690. }
  3691. return true;
  3692. }
  3693. void Node3DEditorViewport::_perform_drop_data() {
  3694. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  3695. if (spatial_editor->get_preview_material_target().is_valid()) {
  3696. GeometryInstance3D *geometry_instance = Object::cast_to<GeometryInstance3D>(ObjectDB::get_instance(spatial_editor->get_preview_material_target()));
  3697. MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(ObjectDB::get_instance(spatial_editor->get_preview_material_target()));
  3698. if (mesh_instance && spatial_editor->get_preview_material_surface() != -1) {
  3699. undo_redo->create_action(vformat(TTR("Set Surface %d Override Material"), spatial_editor->get_preview_material_surface()));
  3700. undo_redo->add_do_method(geometry_instance, "set_surface_override_material", spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_material());
  3701. undo_redo->add_undo_method(geometry_instance, "set_surface_override_material", spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_reset_material());
  3702. undo_redo->commit_action();
  3703. } else if (geometry_instance) {
  3704. undo_redo->create_action(TTR("Set Material Override"));
  3705. undo_redo->add_do_method(geometry_instance, "set_material_override", spatial_editor->get_preview_material());
  3706. undo_redo->add_undo_method(geometry_instance, "set_material_override", spatial_editor->get_preview_reset_material());
  3707. undo_redo->commit_action();
  3708. }
  3709. _remove_preview_material();
  3710. return;
  3711. }
  3712. _remove_preview_node();
  3713. Vector<String> error_files;
  3714. undo_redo->create_action(TTR("Create Node"));
  3715. for (int i = 0; i < selected_files.size(); i++) {
  3716. String path = selected_files[i];
  3717. Ref<Resource> res = ResourceLoader::load(path);
  3718. if (res.is_null()) {
  3719. continue;
  3720. }
  3721. Ref<PackedScene> scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
  3722. Ref<Mesh> mesh = Ref<Mesh>(Object::cast_to<Mesh>(*res));
  3723. if (mesh != nullptr || scene != nullptr) {
  3724. bool success = _create_instance(target_node, path, drop_pos);
  3725. if (!success) {
  3726. error_files.push_back(path);
  3727. }
  3728. }
  3729. }
  3730. undo_redo->commit_action();
  3731. if (error_files.size() > 0) {
  3732. String files_str;
  3733. for (int i = 0; i < error_files.size(); i++) {
  3734. files_str += error_files[i].get_file().get_basename() + ",";
  3735. }
  3736. files_str = files_str.substr(0, files_str.length() - 1);
  3737. accept->set_text(vformat(TTR("Error instantiating scene from %s"), files_str.get_data()));
  3738. accept->popup_centered();
  3739. }
  3740. }
  3741. bool Node3DEditorViewport::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
  3742. preview_node_viewport_pos = p_point;
  3743. bool can_instantiate = false;
  3744. if (!preview_node->is_inside_tree() && spatial_editor->get_preview_material().is_null()) {
  3745. Dictionary d = p_data;
  3746. if (d.has("type") && (String(d["type"]) == "files")) {
  3747. Vector<String> files = d["files"];
  3748. List<String> scene_extensions;
  3749. ResourceLoader::get_recognized_extensions_for_type("PackedScene", &scene_extensions);
  3750. List<String> mesh_extensions;
  3751. ResourceLoader::get_recognized_extensions_for_type("Mesh", &mesh_extensions);
  3752. List<String> material_extensions;
  3753. ResourceLoader::get_recognized_extensions_for_type("Material", &material_extensions);
  3754. List<String> texture_extensions;
  3755. ResourceLoader::get_recognized_extensions_for_type("Texture", &texture_extensions);
  3756. for (int i = 0; i < files.size(); i++) {
  3757. String extension = files[i].get_extension().to_lower();
  3758. // Check if dragged files with mesh or scene extension can be created at least once.
  3759. if (mesh_extensions.find(extension) ||
  3760. scene_extensions.find(extension) ||
  3761. material_extensions.find(extension) ||
  3762. texture_extensions.find(extension)) {
  3763. Ref<Resource> res = ResourceLoader::load(files[i]);
  3764. if (res.is_null()) {
  3765. continue;
  3766. }
  3767. Ref<PackedScene> scn = res;
  3768. Ref<Mesh> mesh = res;
  3769. Ref<Material> mat = res;
  3770. Ref<Texture2D> tex = res;
  3771. if (scn.is_valid()) {
  3772. Node *instantiated_scene = scn->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
  3773. if (!instantiated_scene) {
  3774. continue;
  3775. }
  3776. memdelete(instantiated_scene);
  3777. } else if (mat.is_valid()) {
  3778. Ref<BaseMaterial3D> base_mat = res;
  3779. Ref<ShaderMaterial> shader_mat = res;
  3780. if (base_mat.is_null() && !shader_mat.is_null()) {
  3781. break;
  3782. }
  3783. spatial_editor->set_preview_material(mat);
  3784. break;
  3785. } else if (mesh.is_valid()) {
  3786. // Let the mesh pass.
  3787. } else if (tex.is_valid()) {
  3788. Ref<StandardMaterial3D> new_mat = memnew(StandardMaterial3D);
  3789. new_mat->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, tex);
  3790. spatial_editor->set_preview_material(new_mat);
  3791. break;
  3792. } else {
  3793. continue;
  3794. }
  3795. can_instantiate = true;
  3796. break;
  3797. }
  3798. }
  3799. if (can_instantiate) {
  3800. _create_preview_node(files);
  3801. preview_node->hide();
  3802. }
  3803. }
  3804. } else {
  3805. if (preview_node->is_inside_tree()) {
  3806. can_instantiate = true;
  3807. }
  3808. }
  3809. if (can_instantiate) {
  3810. update_preview_node = true;
  3811. return true;
  3812. }
  3813. if (spatial_editor->get_preview_material().is_valid()) {
  3814. preview_material_label->show();
  3815. preview_material_label_desc->show();
  3816. ObjectID new_preview_material_target = _select_ray(p_point);
  3817. return _apply_preview_material(new_preview_material_target, p_point);
  3818. }
  3819. return false;
  3820. }
  3821. void Node3DEditorViewport::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
  3822. if (!can_drop_data_fw(p_point, p_data, p_from)) {
  3823. return;
  3824. }
  3825. bool is_shift = Input::get_singleton()->is_key_pressed(Key::SHIFT);
  3826. bool is_ctrl = Input::get_singleton()->is_key_pressed(Key::CTRL);
  3827. selected_files.clear();
  3828. Dictionary d = p_data;
  3829. if (d.has("type") && String(d["type"]) == "files") {
  3830. selected_files = d["files"];
  3831. }
  3832. List<Node *> selected_nodes = EditorNode::get_singleton()->get_editor_selection()->get_selected_node_list();
  3833. Node *root_node = EditorNode::get_singleton()->get_edited_scene();
  3834. if (selected_nodes.size() == 1) {
  3835. Node *selected_node = selected_nodes[0];
  3836. target_node = root_node;
  3837. if (is_ctrl) {
  3838. target_node = selected_node;
  3839. } else if (is_shift && selected_node != root_node) {
  3840. target_node = selected_node->get_parent();
  3841. }
  3842. } else if (selected_nodes.size() == 0) {
  3843. if (root_node) {
  3844. target_node = root_node;
  3845. } else {
  3846. // Create a root node so we can add child nodes to it.
  3847. SceneTreeDock::get_singleton()->add_root_node(memnew(Node3D));
  3848. target_node = get_tree()->get_edited_scene_root();
  3849. }
  3850. } else {
  3851. accept->set_text(TTR("Cannot drag and drop into multiple selected nodes."));
  3852. accept->popup_centered();
  3853. _remove_preview_node();
  3854. return;
  3855. }
  3856. drop_pos = p_point;
  3857. _perform_drop_data();
  3858. }
  3859. void Node3DEditorViewport::begin_transform(TransformMode p_mode, bool instant) {
  3860. if (get_selected_count() > 0) {
  3861. _edit.mode = p_mode;
  3862. _compute_edit(_edit.mouse_pos);
  3863. _edit.instant = instant;
  3864. _edit.snap = spatial_editor->is_snap_enabled();
  3865. update_transform_gizmo_view();
  3866. set_process_input(instant);
  3867. }
  3868. }
  3869. // Apply the current transform operation.
  3870. void Node3DEditorViewport::commit_transform() {
  3871. ERR_FAIL_COND(_edit.mode == TRANSFORM_NONE);
  3872. static const char *_transform_name[4] = {
  3873. TTRC("None"),
  3874. TTRC("Rotate"),
  3875. // TRANSLATORS: This refers to the movement that changes the position of an object.
  3876. TTRC("Translate"),
  3877. TTRC("Scale"),
  3878. };
  3879. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  3880. undo_redo->create_action(_transform_name[_edit.mode]);
  3881. List<Node *> &selection = editor_selection->get_selected_node_list();
  3882. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3883. Node3D *sp = Object::cast_to<Node3D>(E->get());
  3884. if (!sp) {
  3885. continue;
  3886. }
  3887. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  3888. if (!se) {
  3889. continue;
  3890. }
  3891. undo_redo->add_do_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
  3892. undo_redo->add_undo_method(sp, "set_global_transform", se->original);
  3893. }
  3894. undo_redo->commit_action();
  3895. finish_transform();
  3896. set_message("");
  3897. }
  3898. void Node3DEditorViewport::apply_transform(Vector3 p_motion, double p_snap) {
  3899. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
  3900. List<Node *> &selection = editor_selection->get_selected_node_list();
  3901. for (Node *E : selection) {
  3902. Node3D *sp = Object::cast_to<Node3D>(E);
  3903. if (!sp) {
  3904. continue;
  3905. }
  3906. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  3907. if (!se) {
  3908. continue;
  3909. }
  3910. if (sp->has_meta("_edit_lock_")) {
  3911. continue;
  3912. }
  3913. if (se->gizmo.is_valid()) {
  3914. for (KeyValue<int, Transform3D> &GE : se->subgizmos) {
  3915. Transform3D xform = GE.value;
  3916. Transform3D new_xform = _compute_transform(_edit.mode, se->original * xform, xform, p_motion, p_snap, local_coords, _edit.plane != TRANSFORM_VIEW); // Force orthogonal with subgizmo.
  3917. if (!local_coords) {
  3918. new_xform = se->original.affine_inverse() * new_xform;
  3919. }
  3920. se->gizmo->set_subgizmo_transform(GE.key, new_xform);
  3921. }
  3922. } else {
  3923. Transform3D new_xform = _compute_transform(_edit.mode, se->original, se->original_local, p_motion, p_snap, local_coords, sp->get_rotation_edit_mode() != Node3D::ROTATION_EDIT_MODE_BASIS && _edit.plane != TRANSFORM_VIEW);
  3924. _transform_gizmo_apply(se->sp, new_xform, local_coords);
  3925. }
  3926. }
  3927. spatial_editor->update_transform_gizmo();
  3928. surface->queue_redraw();
  3929. }
  3930. // Update the current transform operation in response to an input.
  3931. void Node3DEditorViewport::update_transform(bool p_shift) {
  3932. Vector3 ray_pos = _get_ray_pos(_edit.mouse_pos);
  3933. Vector3 ray = _get_ray(_edit.mouse_pos);
  3934. double snap = EDITOR_GET("interface/inspector/default_float_step");
  3935. int snap_step_decimals = Math::range_step_decimals(snap);
  3936. switch (_edit.mode) {
  3937. case TRANSFORM_SCALE: {
  3938. Vector3 motion_mask;
  3939. Plane plane;
  3940. bool plane_mv = false;
  3941. switch (_edit.plane) {
  3942. case TRANSFORM_VIEW:
  3943. motion_mask = Vector3(0, 0, 0);
  3944. plane = Plane(_get_camera_normal(), _edit.center);
  3945. break;
  3946. case TRANSFORM_X_AXIS:
  3947. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(0).normalized();
  3948. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  3949. break;
  3950. case TRANSFORM_Y_AXIS:
  3951. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
  3952. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  3953. break;
  3954. case TRANSFORM_Z_AXIS:
  3955. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized();
  3956. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  3957. break;
  3958. case TRANSFORM_YZ:
  3959. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized() + spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
  3960. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(0).normalized(), _edit.center);
  3961. plane_mv = true;
  3962. break;
  3963. case TRANSFORM_XZ:
  3964. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized() + spatial_editor->get_gizmo_transform().basis.get_column(0).normalized();
  3965. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(1).normalized(), _edit.center);
  3966. plane_mv = true;
  3967. break;
  3968. case TRANSFORM_XY:
  3969. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(0).normalized() + spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
  3970. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(2).normalized(), _edit.center);
  3971. plane_mv = true;
  3972. break;
  3973. }
  3974. Vector3 intersection;
  3975. if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
  3976. break;
  3977. }
  3978. Vector3 click;
  3979. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
  3980. break;
  3981. }
  3982. Vector3 motion = intersection - click;
  3983. if (_edit.plane != TRANSFORM_VIEW) {
  3984. if (!plane_mv) {
  3985. motion = motion_mask.dot(motion) * motion_mask;
  3986. } else {
  3987. // Alternative planar scaling mode
  3988. if (p_shift) {
  3989. motion = motion_mask.dot(motion) * motion_mask;
  3990. }
  3991. }
  3992. } else {
  3993. const real_t center_click_dist = click.distance_to(_edit.center);
  3994. const real_t center_inters_dist = intersection.distance_to(_edit.center);
  3995. if (center_click_dist == 0) {
  3996. break;
  3997. }
  3998. const real_t scale = center_inters_dist - center_click_dist;
  3999. motion = Vector3(scale, scale, scale);
  4000. }
  4001. motion /= click.distance_to(_edit.center);
  4002. // Disable local transformation for TRANSFORM_VIEW
  4003. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
  4004. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  4005. snap = spatial_editor->get_scale_snap() / 100;
  4006. }
  4007. Vector3 motion_snapped = motion;
  4008. motion_snapped.snap(Vector3(snap, snap, snap));
  4009. // This might not be necessary anymore after issue #288 is solved (in 4.0?).
  4010. // TRANSLATORS: Refers to changing the scale of a node in the 3D editor.
  4011. set_message(TTR("Scaling:") + " (" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
  4012. String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
  4013. if (local_coords) {
  4014. // TODO: needed?
  4015. motion = _edit.original.basis.inverse().xform(motion);
  4016. }
  4017. apply_transform(motion, snap);
  4018. } break;
  4019. case TRANSFORM_TRANSLATE: {
  4020. Vector3 motion_mask;
  4021. Plane plane;
  4022. bool plane_mv = false;
  4023. switch (_edit.plane) {
  4024. case TRANSFORM_VIEW:
  4025. plane = Plane(_get_camera_normal(), _edit.center);
  4026. break;
  4027. case TRANSFORM_X_AXIS:
  4028. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(0).normalized();
  4029. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  4030. break;
  4031. case TRANSFORM_Y_AXIS:
  4032. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
  4033. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  4034. break;
  4035. case TRANSFORM_Z_AXIS:
  4036. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized();
  4037. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  4038. break;
  4039. case TRANSFORM_YZ:
  4040. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(0).normalized(), _edit.center);
  4041. plane_mv = true;
  4042. break;
  4043. case TRANSFORM_XZ:
  4044. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(1).normalized(), _edit.center);
  4045. plane_mv = true;
  4046. break;
  4047. case TRANSFORM_XY:
  4048. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(2).normalized(), _edit.center);
  4049. plane_mv = true;
  4050. break;
  4051. }
  4052. Vector3 intersection;
  4053. if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
  4054. break;
  4055. }
  4056. Vector3 click;
  4057. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
  4058. break;
  4059. }
  4060. Vector3 motion = intersection - click;
  4061. if (_edit.plane != TRANSFORM_VIEW) {
  4062. if (!plane_mv) {
  4063. motion = motion_mask.dot(motion) * motion_mask;
  4064. }
  4065. }
  4066. // Disable local transformation for TRANSFORM_VIEW
  4067. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
  4068. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  4069. snap = spatial_editor->get_translate_snap();
  4070. }
  4071. Vector3 motion_snapped = motion;
  4072. motion_snapped.snap(Vector3(snap, snap, snap));
  4073. // TRANSLATORS: Refers to changing the position of a node in the 3D editor.
  4074. set_message(TTR("Translating:") + " (" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
  4075. String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
  4076. if (local_coords) {
  4077. motion = spatial_editor->get_gizmo_transform().basis.inverse().xform(motion);
  4078. }
  4079. apply_transform(motion, snap);
  4080. } break;
  4081. case TRANSFORM_ROTATE: {
  4082. Plane plane = Plane(_get_camera_normal(), _edit.center);
  4083. Vector3 local_axis;
  4084. Vector3 global_axis;
  4085. switch (_edit.plane) {
  4086. case TRANSFORM_VIEW:
  4087. // local_axis unused
  4088. global_axis = _get_camera_normal();
  4089. break;
  4090. case TRANSFORM_X_AXIS:
  4091. local_axis = Vector3(1, 0, 0);
  4092. break;
  4093. case TRANSFORM_Y_AXIS:
  4094. local_axis = Vector3(0, 1, 0);
  4095. break;
  4096. case TRANSFORM_Z_AXIS:
  4097. local_axis = Vector3(0, 0, 1);
  4098. break;
  4099. case TRANSFORM_YZ:
  4100. case TRANSFORM_XZ:
  4101. case TRANSFORM_XY:
  4102. break;
  4103. }
  4104. if (_edit.plane != TRANSFORM_VIEW) {
  4105. global_axis = spatial_editor->get_gizmo_transform().basis.xform(local_axis).normalized();
  4106. }
  4107. Vector3 intersection;
  4108. if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
  4109. break;
  4110. }
  4111. Vector3 click;
  4112. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
  4113. break;
  4114. }
  4115. static const float orthogonal_threshold = Math::cos(Math::deg_to_rad(87.0f));
  4116. bool axis_is_orthogonal = ABS(plane.normal.dot(global_axis)) < orthogonal_threshold;
  4117. double angle = 0.0f;
  4118. if (axis_is_orthogonal) {
  4119. _edit.show_rotation_line = false;
  4120. Vector3 projection_axis = plane.normal.cross(global_axis);
  4121. Vector3 delta = intersection - click;
  4122. float projection = delta.dot(projection_axis);
  4123. angle = (projection * (Math_PI / 2.0f)) / (gizmo_scale * GIZMO_CIRCLE_SIZE);
  4124. } else {
  4125. _edit.show_rotation_line = true;
  4126. Vector3 click_axis = (click - _edit.center).normalized();
  4127. Vector3 current_axis = (intersection - _edit.center).normalized();
  4128. angle = click_axis.signed_angle_to(current_axis, global_axis);
  4129. }
  4130. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  4131. snap = spatial_editor->get_rotate_snap();
  4132. }
  4133. angle = Math::rad_to_deg(angle) + snap * 0.5; //else it won't reach +180
  4134. angle -= Math::fmod(angle, snap);
  4135. set_message(vformat(TTR("Rotating %s degrees."), String::num(angle, snap_step_decimals)));
  4136. angle = Math::deg_to_rad(angle);
  4137. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW); // Disable local transformation for TRANSFORM_VIEW
  4138. Vector3 compute_axis = local_coords ? local_axis : global_axis;
  4139. apply_transform(compute_axis, angle);
  4140. } break;
  4141. default: {
  4142. }
  4143. }
  4144. }
  4145. void Node3DEditorViewport::update_transform_numeric() {
  4146. Vector3 motion;
  4147. switch (_edit.plane) {
  4148. case TRANSFORM_VIEW: {
  4149. switch (_edit.mode) {
  4150. case TRANSFORM_TRANSLATE:
  4151. motion = Vector3(1, 0, 0);
  4152. break;
  4153. case TRANSFORM_ROTATE:
  4154. motion = spatial_editor->get_gizmo_transform().basis.xform_inv(_get_camera_normal()).normalized();
  4155. break;
  4156. case TRANSFORM_SCALE:
  4157. motion = Vector3(1, 1, 1);
  4158. break;
  4159. case TRANSFORM_NONE:
  4160. ERR_FAIL_MSG("_edit.mode cannot be TRANSFORM_NONE in update_transform_numeric.");
  4161. }
  4162. break;
  4163. }
  4164. case TRANSFORM_X_AXIS:
  4165. motion = Vector3(1, 0, 0);
  4166. break;
  4167. case TRANSFORM_Y_AXIS:
  4168. motion = Vector3(0, 1, 0);
  4169. break;
  4170. case TRANSFORM_Z_AXIS:
  4171. motion = Vector3(0, 0, 1);
  4172. break;
  4173. case TRANSFORM_XY:
  4174. motion = Vector3(1, 1, 0);
  4175. break;
  4176. case TRANSFORM_XZ:
  4177. motion = Vector3(1, 0, 1);
  4178. break;
  4179. case TRANSFORM_YZ:
  4180. motion = Vector3(0, 1, 1);
  4181. break;
  4182. }
  4183. double value = _edit.numeric_input * (_edit.numeric_negate ? -1 : 1);
  4184. double extra = 0.0;
  4185. switch (_edit.mode) {
  4186. case TRANSFORM_TRANSLATE:
  4187. motion *= value;
  4188. set_message(vformat(TTR("Translating %s."), motion));
  4189. break;
  4190. case TRANSFORM_ROTATE:
  4191. extra = Math::deg_to_rad(value);
  4192. set_message(vformat(TTR("Rotating %f degrees."), value));
  4193. break;
  4194. case TRANSFORM_SCALE:
  4195. // To halve the size of an object in Blender, you scale it by 0.5.
  4196. // Doing the same in Godot is considered scaling it by -0.5.
  4197. motion *= (value - 1.0);
  4198. set_message(vformat(TTR("Scaling %s."), motion));
  4199. break;
  4200. case TRANSFORM_NONE:
  4201. ERR_FAIL_MSG("_edit.mode cannot be TRANSFORM_NONE in update_transform_numeric.");
  4202. }
  4203. apply_transform(motion, extra);
  4204. }
  4205. // Perform cleanup after a transform operation is committed or canceled.
  4206. void Node3DEditorViewport::finish_transform() {
  4207. _edit.mode = TRANSFORM_NONE;
  4208. _edit.instant = false;
  4209. _edit.numeric_input = 0;
  4210. _edit.numeric_next_decimal = 0;
  4211. _edit.numeric_negate = false;
  4212. spatial_editor->set_local_coords_enabled(_edit.original_local);
  4213. spatial_editor->update_transform_gizmo();
  4214. surface->queue_redraw();
  4215. set_process_input(false);
  4216. }
  4217. // Register a shortcut and also add it as an input action with the same events.
  4218. void Node3DEditorViewport::register_shortcut_action(const String &p_path, const String &p_name, Key p_keycode, bool p_physical) {
  4219. Ref<Shortcut> sc = ED_SHORTCUT(p_path, p_name, p_keycode, p_physical);
  4220. shortcut_changed_callback(sc, p_path);
  4221. // Connect to the change event on the shortcut so the input binding can be updated.
  4222. sc->connect_changed(callable_mp(this, &Node3DEditorViewport::shortcut_changed_callback).bind(sc, p_path));
  4223. }
  4224. // Update the action in the InputMap to the provided shortcut events.
  4225. void Node3DEditorViewport::shortcut_changed_callback(const Ref<Shortcut> p_shortcut, const String &p_shortcut_path) {
  4226. InputMap *im = InputMap::get_singleton();
  4227. if (im->has_action(p_shortcut_path)) {
  4228. im->action_erase_events(p_shortcut_path);
  4229. } else {
  4230. im->add_action(p_shortcut_path);
  4231. }
  4232. for (int i = 0; i < p_shortcut->get_events().size(); i++) {
  4233. im->action_add_event(p_shortcut_path, p_shortcut->get_events()[i]);
  4234. }
  4235. }
  4236. void Node3DEditorViewport::_set_lock_view_rotation(bool p_lock_rotation) {
  4237. lock_rotation = p_lock_rotation;
  4238. int idx = view_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
  4239. view_menu->get_popup()->set_item_checked(idx, p_lock_rotation);
  4240. if (p_lock_rotation) {
  4241. locked_label->show();
  4242. } else {
  4243. locked_label->hide();
  4244. }
  4245. }
  4246. Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, int p_index) {
  4247. cpu_time_history_index = 0;
  4248. gpu_time_history_index = 0;
  4249. _edit.mode = TRANSFORM_NONE;
  4250. _edit.plane = TRANSFORM_VIEW;
  4251. _edit.snap = true;
  4252. _edit.show_rotation_line = true;
  4253. _edit.instant = false;
  4254. _edit.gizmo_handle = -1;
  4255. _edit.gizmo_handle_secondary = false;
  4256. index = p_index;
  4257. editor_selection = EditorNode::get_singleton()->get_editor_selection();
  4258. orthogonal = false;
  4259. auto_orthogonal = false;
  4260. lock_rotation = false;
  4261. message_time = 0;
  4262. zoom_indicator_delay = 0.0;
  4263. spatial_editor = p_spatial_editor;
  4264. SubViewportContainer *c = memnew(SubViewportContainer);
  4265. subviewport_container = c;
  4266. c->set_stretch(true);
  4267. add_child(c);
  4268. c->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
  4269. viewport = memnew(SubViewport);
  4270. viewport->set_disable_input(true);
  4271. c->add_child(viewport);
  4272. surface = memnew(Control);
  4273. SET_DRAG_FORWARDING_CD(surface, Node3DEditorViewport);
  4274. add_child(surface);
  4275. surface->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
  4276. surface->set_clip_contents(true);
  4277. camera = memnew(Camera3D);
  4278. camera->set_disable_gizmos(true);
  4279. camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + p_index)) | (1 << GIZMO_EDIT_LAYER) | (1 << GIZMO_GRID_LAYER) | (1 << MISC_TOOL_LAYER));
  4280. viewport->add_child(camera);
  4281. camera->make_current();
  4282. surface->set_focus_mode(FOCUS_ALL);
  4283. VBoxContainer *vbox = memnew(VBoxContainer);
  4284. surface->add_child(vbox);
  4285. vbox->set_offset(SIDE_LEFT, 10 * EDSCALE);
  4286. vbox->set_offset(SIDE_TOP, 10 * EDSCALE);
  4287. view_menu = memnew(MenuButton);
  4288. view_menu->set_flat(false);
  4289. view_menu->set_h_size_flags(0);
  4290. view_menu->set_shortcut_context(this);
  4291. vbox->add_child(view_menu);
  4292. display_submenu = memnew(PopupMenu);
  4293. view_menu->get_popup()->set_hide_on_checkable_item_selection(false);
  4294. view_menu->get_popup()->add_child(display_submenu);
  4295. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/top_view"), VIEW_TOP);
  4296. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/bottom_view"), VIEW_BOTTOM);
  4297. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/left_view"), VIEW_LEFT);
  4298. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/right_view"), VIEW_RIGHT);
  4299. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/front_view"), VIEW_FRONT);
  4300. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/rear_view"), VIEW_REAR);
  4301. view_menu->get_popup()->add_separator();
  4302. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/switch_perspective_orthogonal"), VIEW_SWITCH_PERSPECTIVE_ORTHOGONAL);
  4303. view_menu->get_popup()->add_radio_check_item(TTR("Perspective"), VIEW_PERSPECTIVE);
  4304. view_menu->get_popup()->add_radio_check_item(TTR("Orthogonal"), VIEW_ORTHOGONAL);
  4305. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
  4306. view_menu->get_popup()->add_check_item(TTR("Auto Orthogonal Enabled"), VIEW_AUTO_ORTHOGONAL);
  4307. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL), true);
  4308. view_menu->get_popup()->add_separator();
  4309. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_lock_rotation", TTR("Lock View Rotation")), VIEW_LOCK_ROTATION);
  4310. view_menu->get_popup()->add_separator();
  4311. // TRANSLATORS: "Normal" as in "normal life", not "normal vector".
  4312. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_normal", TTR("Display Normal")), VIEW_DISPLAY_NORMAL);
  4313. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_wireframe", TTR("Display Wireframe")), VIEW_DISPLAY_WIREFRAME);
  4314. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_overdraw", TTR("Display Overdraw")), VIEW_DISPLAY_OVERDRAW);
  4315. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_lighting", TTR("Display Lighting")), VIEW_DISPLAY_LIGHTING);
  4316. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_unshaded", TTR("Display Unshaded")), VIEW_DISPLAY_UNSHADED);
  4317. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), true);
  4318. display_submenu->set_hide_on_checkable_item_selection(false);
  4319. display_submenu->add_radio_check_item(TTR("Directional Shadow Splits"), VIEW_DISPLAY_DEBUG_PSSM_SPLITS);
  4320. display_submenu->add_separator();
  4321. display_submenu->add_radio_check_item(TTR("Normal Buffer"), VIEW_DISPLAY_NORMAL_BUFFER);
  4322. display_submenu->add_separator();
  4323. display_submenu->add_radio_check_item(TTR("Shadow Atlas"), VIEW_DISPLAY_DEBUG_SHADOW_ATLAS);
  4324. display_submenu->add_radio_check_item(TTR("Directional Shadow Map"), VIEW_DISPLAY_DEBUG_DIRECTIONAL_SHADOW_ATLAS);
  4325. display_submenu->add_separator();
  4326. display_submenu->add_radio_check_item(TTR("Decal Atlas"), VIEW_DISPLAY_DEBUG_DECAL_ATLAS);
  4327. display_submenu->add_separator();
  4328. display_submenu->add_radio_check_item(TTR("VoxelGI Lighting"), VIEW_DISPLAY_DEBUG_VOXEL_GI_LIGHTING);
  4329. display_submenu->add_radio_check_item(TTR("VoxelGI Albedo"), VIEW_DISPLAY_DEBUG_VOXEL_GI_ALBEDO);
  4330. display_submenu->add_radio_check_item(TTR("VoxelGI Emission"), VIEW_DISPLAY_DEBUG_VOXEL_GI_EMISSION);
  4331. display_submenu->add_separator();
  4332. display_submenu->add_radio_check_item(TTR("SDFGI Cascades"), VIEW_DISPLAY_DEBUG_SDFGI);
  4333. display_submenu->add_radio_check_item(TTR("SDFGI Probes"), VIEW_DISPLAY_DEBUG_SDFGI_PROBES);
  4334. display_submenu->add_separator();
  4335. display_submenu->add_radio_check_item(TTR("Scene Luminance"), VIEW_DISPLAY_DEBUG_SCENE_LUMINANCE);
  4336. display_submenu->add_separator();
  4337. display_submenu->add_radio_check_item(TTR("SSAO"), VIEW_DISPLAY_DEBUG_SSAO);
  4338. display_submenu->add_radio_check_item(TTR("SSIL"), VIEW_DISPLAY_DEBUG_SSIL);
  4339. display_submenu->add_separator();
  4340. display_submenu->add_radio_check_item(TTR("VoxelGI/SDFGI Buffer"), VIEW_DISPLAY_DEBUG_GI_BUFFER);
  4341. display_submenu->add_separator();
  4342. display_submenu->add_radio_check_item(TTR("Disable Mesh LOD"), VIEW_DISPLAY_DEBUG_DISABLE_LOD);
  4343. display_submenu->add_separator();
  4344. display_submenu->add_radio_check_item(TTR("OmniLight3D Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS);
  4345. display_submenu->add_radio_check_item(TTR("SpotLight3D Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS);
  4346. display_submenu->add_radio_check_item(TTR("Decal Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_DECALS);
  4347. display_submenu->add_radio_check_item(TTR("ReflectionProbe Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES);
  4348. display_submenu->add_radio_check_item(TTR("Occlusion Culling Buffer"), VIEW_DISPLAY_DEBUG_OCCLUDERS);
  4349. display_submenu->add_radio_check_item(TTR("Motion Vectors"), VIEW_DISPLAY_MOTION_VECTORS);
  4350. display_submenu->add_radio_check_item(TTR("Internal Buffer"), VIEW_DISPLAY_INTERNAL_BUFFER);
  4351. display_submenu->set_name("display_advanced");
  4352. view_menu->get_popup()->add_submenu_item(TTR("Display Advanced..."), "display_advanced", VIEW_DISPLAY_ADVANCED);
  4353. view_menu->get_popup()->add_separator();
  4354. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_environment", TTR("View Environment")), VIEW_ENVIRONMENT);
  4355. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_gizmos", TTR("View Gizmos")), VIEW_GIZMOS);
  4356. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_information", TTR("View Information")), VIEW_INFORMATION);
  4357. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_fps", TTR("View Frame Time")), VIEW_FRAME_TIME);
  4358. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT), true);
  4359. view_menu->get_popup()->add_separator();
  4360. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_half_resolution", TTR("Half Resolution")), VIEW_HALF_RESOLUTION);
  4361. view_menu->get_popup()->add_separator();
  4362. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_listener", TTR("Audio Listener")), VIEW_AUDIO_LISTENER);
  4363. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_doppler", TTR("Enable Doppler")), VIEW_AUDIO_DOPPLER);
  4364. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_GIZMOS), true);
  4365. view_menu->get_popup()->add_separator();
  4366. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_cinematic_preview", TTR("Cinematic Preview")), VIEW_CINEMATIC_PREVIEW);
  4367. view_menu->get_popup()->add_separator();
  4368. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_origin"), VIEW_CENTER_TO_ORIGIN);
  4369. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_selection"), VIEW_CENTER_TO_SELECTION);
  4370. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_transform_with_view"), VIEW_ALIGN_TRANSFORM_WITH_VIEW);
  4371. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_rotation_with_view"), VIEW_ALIGN_ROTATION_WITH_VIEW);
  4372. view_menu->get_popup()->connect("id_pressed", callable_mp(this, &Node3DEditorViewport::_menu_option));
  4373. display_submenu->connect("id_pressed", callable_mp(this, &Node3DEditorViewport::_menu_option));
  4374. view_menu->set_disable_shortcuts(true);
  4375. // TODO: Re-evaluate with new OpenGL3 renderer, and implement.
  4376. //if (OS::get_singleton()->get_current_video_driver() == OS::RENDERING_DRIVER_OPENGL3) {
  4377. if (false) {
  4378. // Alternate display modes only work when using the Vulkan renderer; make this explicit.
  4379. const int normal_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL);
  4380. const int wireframe_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME);
  4381. const int overdraw_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW);
  4382. const int shadeless_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_UNSHADED);
  4383. const String unsupported_tooltip = TTR("Not available when using the OpenGL renderer.");
  4384. view_menu->get_popup()->set_item_disabled(normal_idx, true);
  4385. view_menu->get_popup()->set_item_tooltip(normal_idx, unsupported_tooltip);
  4386. view_menu->get_popup()->set_item_disabled(wireframe_idx, true);
  4387. view_menu->get_popup()->set_item_tooltip(wireframe_idx, unsupported_tooltip);
  4388. view_menu->get_popup()->set_item_disabled(overdraw_idx, true);
  4389. view_menu->get_popup()->set_item_tooltip(overdraw_idx, unsupported_tooltip);
  4390. view_menu->get_popup()->set_item_disabled(shadeless_idx, true);
  4391. view_menu->get_popup()->set_item_tooltip(shadeless_idx, unsupported_tooltip);
  4392. }
  4393. register_shortcut_action("spatial_editor/freelook_left", TTR("Freelook Left"), Key::A, true);
  4394. register_shortcut_action("spatial_editor/freelook_right", TTR("Freelook Right"), Key::D, true);
  4395. register_shortcut_action("spatial_editor/freelook_forward", TTR("Freelook Forward"), Key::W, true);
  4396. register_shortcut_action("spatial_editor/freelook_backwards", TTR("Freelook Backwards"), Key::S, true);
  4397. register_shortcut_action("spatial_editor/freelook_up", TTR("Freelook Up"), Key::E, true);
  4398. register_shortcut_action("spatial_editor/freelook_down", TTR("Freelook Down"), Key::Q, true);
  4399. register_shortcut_action("spatial_editor/freelook_speed_modifier", TTR("Freelook Speed Modifier"), Key::SHIFT);
  4400. register_shortcut_action("spatial_editor/freelook_slow_modifier", TTR("Freelook Slow Modifier"), Key::ALT);
  4401. ED_SHORTCUT("spatial_editor/lock_transform_x", TTR("Lock Transformation to X axis"), Key::X);
  4402. ED_SHORTCUT("spatial_editor/lock_transform_y", TTR("Lock Transformation to Y axis"), Key::Y);
  4403. ED_SHORTCUT("spatial_editor/lock_transform_z", TTR("Lock Transformation to Z axis"), Key::Z);
  4404. ED_SHORTCUT("spatial_editor/lock_transform_yz", TTR("Lock Transformation to YZ plane"), KeyModifierMask::SHIFT | Key::X);
  4405. ED_SHORTCUT("spatial_editor/lock_transform_xz", TTR("Lock Transformation to XZ plane"), KeyModifierMask::SHIFT | Key::Y);
  4406. ED_SHORTCUT("spatial_editor/lock_transform_xy", TTR("Lock Transformation to XY plane"), KeyModifierMask::SHIFT | Key::Z);
  4407. ED_SHORTCUT("spatial_editor/cancel_transform", TTR("Cancel Transformation"), Key::ESCAPE);
  4408. ED_SHORTCUT("spatial_editor/instant_translate", TTR("Begin Translate Transformation"));
  4409. ED_SHORTCUT("spatial_editor/instant_rotate", TTR("Begin Rotate Transformation"));
  4410. ED_SHORTCUT("spatial_editor/instant_scale", TTR("Begin Scale Transformation"));
  4411. preview_camera = memnew(CheckBox);
  4412. preview_camera->set_text(TTR("Preview"));
  4413. preview_camera->set_shortcut(ED_SHORTCUT("spatial_editor/toggle_camera_preview", TTR("Toggle Camera Preview"), KeyModifierMask::CMD_OR_CTRL | Key::P));
  4414. vbox->add_child(preview_camera);
  4415. preview_camera->set_h_size_flags(0);
  4416. preview_camera->hide();
  4417. preview_camera->connect("toggled", callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
  4418. previewing = nullptr;
  4419. gizmo_scale = 1.0;
  4420. preview_node = nullptr;
  4421. bottom_center_vbox = memnew(VBoxContainer);
  4422. bottom_center_vbox->set_anchors_preset(LayoutPreset::PRESET_CENTER);
  4423. bottom_center_vbox->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -20 * EDSCALE);
  4424. bottom_center_vbox->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, -10 * EDSCALE);
  4425. bottom_center_vbox->set_h_grow_direction(GROW_DIRECTION_BOTH);
  4426. bottom_center_vbox->set_v_grow_direction(GROW_DIRECTION_BEGIN);
  4427. surface->add_child(bottom_center_vbox);
  4428. info_label = memnew(Label);
  4429. info_label->set_anchor_and_offset(SIDE_LEFT, ANCHOR_END, -90 * EDSCALE);
  4430. info_label->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -90 * EDSCALE);
  4431. info_label->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, -10 * EDSCALE);
  4432. info_label->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, -10 * EDSCALE);
  4433. info_label->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  4434. info_label->set_v_grow_direction(GROW_DIRECTION_BEGIN);
  4435. surface->add_child(info_label);
  4436. info_label->hide();
  4437. cinema_label = memnew(Label);
  4438. cinema_label->set_anchor_and_offset(SIDE_TOP, ANCHOR_BEGIN, 10 * EDSCALE);
  4439. cinema_label->set_h_grow_direction(GROW_DIRECTION_END);
  4440. cinema_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  4441. surface->add_child(cinema_label);
  4442. cinema_label->set_text(TTR("Cinematic Preview"));
  4443. cinema_label->hide();
  4444. previewing_cinema = false;
  4445. locked_label = memnew(Label);
  4446. locked_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  4447. locked_label->set_h_size_flags(SIZE_SHRINK_CENTER);
  4448. bottom_center_vbox->add_child(locked_label);
  4449. locked_label->set_text(TTR("View Rotation Locked"));
  4450. locked_label->hide();
  4451. zoom_limit_label = memnew(Label);
  4452. zoom_limit_label->set_text(TTR("To zoom further, change the camera's clipping planes (View -> Settings...)"));
  4453. zoom_limit_label->set_name("ZoomLimitMessageLabel");
  4454. zoom_limit_label->add_theme_color_override("font_color", Color(1, 1, 1, 1));
  4455. zoom_limit_label->hide();
  4456. bottom_center_vbox->add_child(zoom_limit_label);
  4457. preview_material_label = memnew(Label);
  4458. preview_material_label->set_anchors_and_offsets_preset(LayoutPreset::PRESET_BOTTOM_LEFT);
  4459. preview_material_label->set_offset(Side::SIDE_TOP, -70 * EDSCALE);
  4460. preview_material_label->set_text(TTR("Overriding material..."));
  4461. preview_material_label->add_theme_color_override("font_color", Color(1, 1, 1, 1));
  4462. preview_material_label->hide();
  4463. surface->add_child(preview_material_label);
  4464. preview_material_label_desc = memnew(Label);
  4465. preview_material_label_desc->set_anchors_and_offsets_preset(LayoutPreset::PRESET_BOTTOM_LEFT);
  4466. preview_material_label_desc->set_offset(Side::SIDE_TOP, -50 * EDSCALE);
  4467. Key key = (OS::get_singleton()->has_feature("macos") || OS::get_singleton()->has_feature("web_macos") || OS::get_singleton()->has_feature("web_ios")) ? Key::META : Key::CTRL;
  4468. preview_material_label_desc->set_text(vformat(TTR("Drag and drop to override the material of any geometry node.\nHold %s when dropping to override a specific surface."), find_keycode_name(key)));
  4469. preview_material_label_desc->add_theme_color_override("font_color", Color(0.8, 0.8, 0.8, 1));
  4470. preview_material_label_desc->add_theme_constant_override("line_spacing", 0);
  4471. preview_material_label_desc->hide();
  4472. surface->add_child(preview_material_label_desc);
  4473. frame_time_gradient = memnew(Gradient);
  4474. // The color is set when the theme changes.
  4475. frame_time_gradient->add_point(0.5, Color());
  4476. top_right_vbox = memnew(VBoxContainer);
  4477. top_right_vbox->set_anchors_and_offsets_preset(PRESET_TOP_RIGHT, PRESET_MODE_MINSIZE, 10.0 * EDSCALE);
  4478. top_right_vbox->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  4479. // Make sure frame time labels don't touch the viewport's edge.
  4480. top_right_vbox->set_custom_minimum_size(Size2(100, 0) * EDSCALE);
  4481. // Prevent visible spacing between frame time labels.
  4482. top_right_vbox->add_theme_constant_override("separation", 0);
  4483. const int navigation_control_size = 150;
  4484. position_control = memnew(ViewportNavigationControl);
  4485. position_control->set_navigation_mode(Node3DEditorViewport::NAVIGATION_MOVE);
  4486. position_control->set_custom_minimum_size(Size2(navigation_control_size, navigation_control_size) * EDSCALE);
  4487. position_control->set_h_size_flags(SIZE_SHRINK_END);
  4488. position_control->set_anchor_and_offset(SIDE_LEFT, ANCHOR_BEGIN, 0);
  4489. position_control->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -navigation_control_size * EDSCALE);
  4490. position_control->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_BEGIN, navigation_control_size * EDSCALE);
  4491. position_control->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, 0);
  4492. position_control->set_viewport(this);
  4493. surface->add_child(position_control);
  4494. look_control = memnew(ViewportNavigationControl);
  4495. look_control->set_navigation_mode(Node3DEditorViewport::NAVIGATION_LOOK);
  4496. look_control->set_custom_minimum_size(Size2(navigation_control_size, navigation_control_size) * EDSCALE);
  4497. look_control->set_h_size_flags(SIZE_SHRINK_END);
  4498. look_control->set_anchor_and_offset(SIDE_LEFT, ANCHOR_END, -navigation_control_size * EDSCALE);
  4499. look_control->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -navigation_control_size * EDSCALE);
  4500. look_control->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, 0);
  4501. look_control->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, 0);
  4502. look_control->set_viewport(this);
  4503. surface->add_child(look_control);
  4504. rotation_control = memnew(ViewportRotationControl);
  4505. rotation_control->set_custom_minimum_size(Size2(80, 80) * EDSCALE);
  4506. rotation_control->set_h_size_flags(SIZE_SHRINK_END);
  4507. rotation_control->set_viewport(this);
  4508. top_right_vbox->add_child(rotation_control);
  4509. // Individual Labels are used to allow coloring each label with its own color.
  4510. cpu_time_label = memnew(Label);
  4511. top_right_vbox->add_child(cpu_time_label);
  4512. cpu_time_label->hide();
  4513. gpu_time_label = memnew(Label);
  4514. top_right_vbox->add_child(gpu_time_label);
  4515. gpu_time_label->hide();
  4516. fps_label = memnew(Label);
  4517. top_right_vbox->add_child(fps_label);
  4518. fps_label->hide();
  4519. surface->add_child(top_right_vbox);
  4520. accept = nullptr;
  4521. freelook_active = false;
  4522. freelook_speed = EDITOR_GET("editors/3d/freelook/freelook_base_speed");
  4523. selection_menu = memnew(PopupMenu);
  4524. add_child(selection_menu);
  4525. selection_menu->set_min_size(Size2(100, 0) * EDSCALE);
  4526. selection_menu->connect("id_pressed", callable_mp(this, &Node3DEditorViewport::_selection_result_pressed));
  4527. selection_menu->connect("popup_hide", callable_mp(this, &Node3DEditorViewport::_selection_menu_hide));
  4528. if (p_index == 0) {
  4529. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER), true);
  4530. viewport->set_as_audio_listener_3d(true);
  4531. }
  4532. view_type = VIEW_TYPE_USER;
  4533. _update_name();
  4534. EditorSettings::get_singleton()->connect("settings_changed", callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view));
  4535. }
  4536. Node3DEditorViewport::~Node3DEditorViewport() {
  4537. memdelete(frame_time_gradient);
  4538. }
  4539. //////////////////////////////////////////////////////////////
  4540. void Node3DEditorViewportContainer::gui_input(const Ref<InputEvent> &p_event) {
  4541. ERR_FAIL_COND(p_event.is_null());
  4542. Ref<InputEventMouseButton> mb = p_event;
  4543. if (mb.is_valid() && mb->get_button_index() == MouseButton::LEFT) {
  4544. if (mb->is_pressed()) {
  4545. Vector2 size = get_size();
  4546. int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
  4547. int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
  4548. int mid_w = size.width * ratio_h;
  4549. int mid_h = size.height * ratio_v;
  4550. dragging_h = mb->get_position().x > (mid_w - h_sep / 2) && mb->get_position().x < (mid_w + h_sep / 2);
  4551. dragging_v = mb->get_position().y > (mid_h - v_sep / 2) && mb->get_position().y < (mid_h + v_sep / 2);
  4552. drag_begin_pos = mb->get_position();
  4553. drag_begin_ratio.x = ratio_h;
  4554. drag_begin_ratio.y = ratio_v;
  4555. switch (view) {
  4556. case VIEW_USE_1_VIEWPORT: {
  4557. dragging_h = false;
  4558. dragging_v = false;
  4559. } break;
  4560. case VIEW_USE_2_VIEWPORTS: {
  4561. dragging_h = false;
  4562. } break;
  4563. case VIEW_USE_2_VIEWPORTS_ALT: {
  4564. dragging_v = false;
  4565. } break;
  4566. case VIEW_USE_3_VIEWPORTS:
  4567. case VIEW_USE_3_VIEWPORTS_ALT:
  4568. case VIEW_USE_4_VIEWPORTS: {
  4569. // Do nothing.
  4570. } break;
  4571. }
  4572. } else {
  4573. dragging_h = false;
  4574. dragging_v = false;
  4575. }
  4576. }
  4577. Ref<InputEventMouseMotion> mm = p_event;
  4578. if (mm.is_valid()) {
  4579. if (view == VIEW_USE_3_VIEWPORTS || view == VIEW_USE_3_VIEWPORTS_ALT || view == VIEW_USE_4_VIEWPORTS) {
  4580. Vector2 size = get_size();
  4581. int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
  4582. int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
  4583. int mid_w = size.width * ratio_h;
  4584. int mid_h = size.height * ratio_v;
  4585. bool was_hovering_h = hovering_h;
  4586. bool was_hovering_v = hovering_v;
  4587. hovering_h = mm->get_position().x > (mid_w - h_sep / 2) && mm->get_position().x < (mid_w + h_sep / 2);
  4588. hovering_v = mm->get_position().y > (mid_h - v_sep / 2) && mm->get_position().y < (mid_h + v_sep / 2);
  4589. if (was_hovering_h != hovering_h || was_hovering_v != hovering_v) {
  4590. queue_redraw();
  4591. }
  4592. }
  4593. if (dragging_h) {
  4594. real_t new_ratio = drag_begin_ratio.x + (mm->get_position().x - drag_begin_pos.x) / get_size().width;
  4595. new_ratio = CLAMP(new_ratio, 40 / get_size().width, (get_size().width - 40) / get_size().width);
  4596. ratio_h = new_ratio;
  4597. queue_sort();
  4598. queue_redraw();
  4599. }
  4600. if (dragging_v) {
  4601. real_t new_ratio = drag_begin_ratio.y + (mm->get_position().y - drag_begin_pos.y) / get_size().height;
  4602. new_ratio = CLAMP(new_ratio, 40 / get_size().height, (get_size().height - 40) / get_size().height);
  4603. ratio_v = new_ratio;
  4604. queue_sort();
  4605. queue_redraw();
  4606. }
  4607. }
  4608. }
  4609. void Node3DEditorViewportContainer::_notification(int p_what) {
  4610. switch (p_what) {
  4611. case NOTIFICATION_MOUSE_ENTER:
  4612. case NOTIFICATION_MOUSE_EXIT: {
  4613. mouseover = (p_what == NOTIFICATION_MOUSE_ENTER);
  4614. queue_redraw();
  4615. } break;
  4616. case NOTIFICATION_DRAW: {
  4617. if (mouseover) {
  4618. Ref<Texture2D> h_grabber = get_theme_icon(SNAME("grabber"), SNAME("HSplitContainer"));
  4619. Ref<Texture2D> v_grabber = get_theme_icon(SNAME("grabber"), SNAME("VSplitContainer"));
  4620. Ref<Texture2D> hdiag_grabber = get_editor_theme_icon(SNAME("GuiViewportHdiagsplitter"));
  4621. Ref<Texture2D> vdiag_grabber = get_editor_theme_icon(SNAME("GuiViewportVdiagsplitter"));
  4622. Ref<Texture2D> vh_grabber = get_editor_theme_icon(SNAME("GuiViewportVhsplitter"));
  4623. Vector2 size = get_size();
  4624. int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
  4625. int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
  4626. int mid_w = size.width * ratio_h;
  4627. int mid_h = size.height * ratio_v;
  4628. int size_left = mid_w - h_sep / 2;
  4629. int size_bottom = size.height - mid_h - v_sep / 2;
  4630. switch (view) {
  4631. case VIEW_USE_1_VIEWPORT: {
  4632. // Nothing to show.
  4633. } break;
  4634. case VIEW_USE_2_VIEWPORTS: {
  4635. draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  4636. set_default_cursor_shape(CURSOR_VSPLIT);
  4637. } break;
  4638. case VIEW_USE_2_VIEWPORTS_ALT: {
  4639. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
  4640. set_default_cursor_shape(CURSOR_HSPLIT);
  4641. } break;
  4642. case VIEW_USE_3_VIEWPORTS: {
  4643. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  4644. draw_texture(hdiag_grabber, Vector2(mid_w - hdiag_grabber->get_width() / 2, mid_h - v_grabber->get_height() / 4));
  4645. set_default_cursor_shape(CURSOR_DRAG);
  4646. } else if ((hovering_v && !dragging_h) || dragging_v) {
  4647. draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  4648. set_default_cursor_shape(CURSOR_VSPLIT);
  4649. } else if (hovering_h || dragging_h) {
  4650. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, mid_h + v_grabber->get_height() / 2 + (size_bottom - h_grabber->get_height()) / 2));
  4651. set_default_cursor_shape(CURSOR_HSPLIT);
  4652. }
  4653. } break;
  4654. case VIEW_USE_3_VIEWPORTS_ALT: {
  4655. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  4656. draw_texture(vdiag_grabber, Vector2(mid_w - vdiag_grabber->get_width() + v_grabber->get_height() / 4, mid_h - vdiag_grabber->get_height() / 2));
  4657. set_default_cursor_shape(CURSOR_DRAG);
  4658. } else if ((hovering_v && !dragging_h) || dragging_v) {
  4659. draw_texture(v_grabber, Vector2((size_left - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  4660. set_default_cursor_shape(CURSOR_VSPLIT);
  4661. } else if (hovering_h || dragging_h) {
  4662. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
  4663. set_default_cursor_shape(CURSOR_HSPLIT);
  4664. }
  4665. } break;
  4666. case VIEW_USE_4_VIEWPORTS: {
  4667. Vector2 half(mid_w, mid_h);
  4668. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  4669. draw_texture(vh_grabber, half - vh_grabber->get_size() / 2.0);
  4670. set_default_cursor_shape(CURSOR_DRAG);
  4671. } else if ((hovering_v && !dragging_h) || dragging_v) {
  4672. draw_texture(v_grabber, half - v_grabber->get_size() / 2.0);
  4673. set_default_cursor_shape(CURSOR_VSPLIT);
  4674. } else if (hovering_h || dragging_h) {
  4675. draw_texture(h_grabber, half - h_grabber->get_size() / 2.0);
  4676. set_default_cursor_shape(CURSOR_HSPLIT);
  4677. }
  4678. } break;
  4679. }
  4680. }
  4681. } break;
  4682. case NOTIFICATION_SORT_CHILDREN: {
  4683. Node3DEditorViewport *viewports[4];
  4684. int vc = 0;
  4685. for (int i = 0; i < get_child_count(); i++) {
  4686. viewports[vc] = Object::cast_to<Node3DEditorViewport>(get_child(i));
  4687. if (viewports[vc]) {
  4688. vc++;
  4689. }
  4690. }
  4691. ERR_FAIL_COND(vc != 4);
  4692. Size2 size = get_size();
  4693. if (size.x < 10 || size.y < 10) {
  4694. for (int i = 0; i < 4; i++) {
  4695. viewports[i]->hide();
  4696. }
  4697. return;
  4698. }
  4699. int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
  4700. int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
  4701. int mid_w = size.width * ratio_h;
  4702. int mid_h = size.height * ratio_v;
  4703. int size_left = mid_w - h_sep / 2;
  4704. int size_right = size.width - mid_w - h_sep / 2;
  4705. int size_top = mid_h - v_sep / 2;
  4706. int size_bottom = size.height - mid_h - v_sep / 2;
  4707. switch (view) {
  4708. case VIEW_USE_1_VIEWPORT: {
  4709. viewports[0]->show();
  4710. for (int i = 1; i < 4; i++) {
  4711. viewports[i]->hide();
  4712. }
  4713. fit_child_in_rect(viewports[0], Rect2(Vector2(), size));
  4714. } break;
  4715. case VIEW_USE_2_VIEWPORTS: {
  4716. for (int i = 0; i < 4; i++) {
  4717. if (i == 1 || i == 3) {
  4718. viewports[i]->hide();
  4719. } else {
  4720. viewports[i]->show();
  4721. }
  4722. }
  4723. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
  4724. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size.width, size_bottom)));
  4725. } break;
  4726. case VIEW_USE_2_VIEWPORTS_ALT: {
  4727. for (int i = 0; i < 4; i++) {
  4728. if (i == 1 || i == 3) {
  4729. viewports[i]->hide();
  4730. } else {
  4731. viewports[i]->show();
  4732. }
  4733. }
  4734. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size.height)));
  4735. fit_child_in_rect(viewports[2], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
  4736. } break;
  4737. case VIEW_USE_3_VIEWPORTS: {
  4738. for (int i = 0; i < 4; i++) {
  4739. if (i == 1) {
  4740. viewports[i]->hide();
  4741. } else {
  4742. viewports[i]->show();
  4743. }
  4744. }
  4745. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
  4746. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  4747. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
  4748. } break;
  4749. case VIEW_USE_3_VIEWPORTS_ALT: {
  4750. for (int i = 0; i < 4; i++) {
  4751. if (i == 1) {
  4752. viewports[i]->hide();
  4753. } else {
  4754. viewports[i]->show();
  4755. }
  4756. }
  4757. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
  4758. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  4759. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
  4760. } break;
  4761. case VIEW_USE_4_VIEWPORTS: {
  4762. for (int i = 0; i < 4; i++) {
  4763. viewports[i]->show();
  4764. }
  4765. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
  4766. fit_child_in_rect(viewports[1], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size_top)));
  4767. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  4768. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
  4769. } break;
  4770. }
  4771. } break;
  4772. }
  4773. }
  4774. void Node3DEditorViewportContainer::set_view(View p_view) {
  4775. view = p_view;
  4776. queue_sort();
  4777. }
  4778. Node3DEditorViewportContainer::View Node3DEditorViewportContainer::get_view() {
  4779. return view;
  4780. }
  4781. Node3DEditorViewportContainer::Node3DEditorViewportContainer() {
  4782. set_clip_contents(true);
  4783. view = VIEW_USE_1_VIEWPORT;
  4784. mouseover = false;
  4785. ratio_h = 0.5;
  4786. ratio_v = 0.5;
  4787. hovering_v = false;
  4788. hovering_h = false;
  4789. dragging_v = false;
  4790. dragging_h = false;
  4791. }
  4792. ///////////////////////////////////////////////////////////////////
  4793. Node3DEditor *Node3DEditor::singleton = nullptr;
  4794. Node3DEditorSelectedItem::~Node3DEditorSelectedItem() {
  4795. ERR_FAIL_NULL(RenderingServer::get_singleton());
  4796. if (sbox_instance.is_valid()) {
  4797. RenderingServer::get_singleton()->free(sbox_instance);
  4798. }
  4799. if (sbox_instance_offset.is_valid()) {
  4800. RenderingServer::get_singleton()->free(sbox_instance_offset);
  4801. }
  4802. if (sbox_instance_xray.is_valid()) {
  4803. RenderingServer::get_singleton()->free(sbox_instance_xray);
  4804. }
  4805. if (sbox_instance_xray_offset.is_valid()) {
  4806. RenderingServer::get_singleton()->free(sbox_instance_xray_offset);
  4807. }
  4808. }
  4809. void Node3DEditor::select_gizmo_highlight_axis(int p_axis) {
  4810. for (int i = 0; i < 3; i++) {
  4811. move_gizmo[i]->surface_set_material(0, i == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  4812. move_plane_gizmo[i]->surface_set_material(0, (i + 6) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
  4813. rotate_gizmo[i]->surface_set_material(0, (i + 3) == p_axis ? rotate_gizmo_color_hl[i] : rotate_gizmo_color[i]);
  4814. scale_gizmo[i]->surface_set_material(0, (i + 9) == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  4815. scale_plane_gizmo[i]->surface_set_material(0, (i + 12) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
  4816. }
  4817. }
  4818. void Node3DEditor::update_transform_gizmo() {
  4819. int count = 0;
  4820. bool local_gizmo_coords = are_local_coords_enabled();
  4821. Vector3 gizmo_center;
  4822. Basis gizmo_basis;
  4823. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  4824. if (se && se->gizmo.is_valid()) {
  4825. for (const KeyValue<int, Transform3D> &E : se->subgizmos) {
  4826. Transform3D xf = se->sp->get_global_transform() * se->gizmo->get_subgizmo_transform(E.key);
  4827. gizmo_center += xf.origin;
  4828. if (count == 0 && local_gizmo_coords) {
  4829. gizmo_basis = xf.basis;
  4830. }
  4831. count++;
  4832. }
  4833. } else {
  4834. List<Node *> &selection = editor_selection->get_selected_node_list();
  4835. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4836. Node3D *sp = Object::cast_to<Node3D>(E->get());
  4837. if (!sp) {
  4838. continue;
  4839. }
  4840. if (sp->has_meta("_edit_lock_")) {
  4841. continue;
  4842. }
  4843. Node3DEditorSelectedItem *sel_item = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  4844. if (!sel_item) {
  4845. continue;
  4846. }
  4847. Transform3D xf = sel_item->sp->get_global_transform();
  4848. gizmo_center += xf.origin;
  4849. if (count == 0 && local_gizmo_coords) {
  4850. gizmo_basis = xf.basis;
  4851. }
  4852. count++;
  4853. }
  4854. }
  4855. gizmo.visible = count > 0;
  4856. gizmo.transform.origin = (count > 0) ? gizmo_center / count : Vector3();
  4857. gizmo.transform.basis = (count == 1) ? gizmo_basis : Basis();
  4858. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  4859. viewports[i]->update_transform_gizmo_view();
  4860. }
  4861. }
  4862. void _update_all_gizmos(Node *p_node) {
  4863. for (int i = p_node->get_child_count() - 1; 0 <= i; --i) {
  4864. Node3D *spatial_node = Object::cast_to<Node3D>(p_node->get_child(i));
  4865. if (spatial_node) {
  4866. spatial_node->update_gizmos();
  4867. }
  4868. _update_all_gizmos(p_node->get_child(i));
  4869. }
  4870. }
  4871. void Node3DEditor::update_all_gizmos(Node *p_node) {
  4872. if (!p_node && is_inside_tree()) {
  4873. p_node = get_tree()->get_edited_scene_root();
  4874. }
  4875. if (!p_node) {
  4876. // No edited scene, so nothing to update.
  4877. return;
  4878. }
  4879. _update_all_gizmos(p_node);
  4880. }
  4881. Object *Node3DEditor::_get_editor_data(Object *p_what) {
  4882. Node3D *sp = Object::cast_to<Node3D>(p_what);
  4883. if (!sp) {
  4884. return nullptr;
  4885. }
  4886. Node3DEditorSelectedItem *si = memnew(Node3DEditorSelectedItem);
  4887. si->sp = sp;
  4888. si->sbox_instance = RenderingServer::get_singleton()->instance_create2(
  4889. selection_box->get_rid(),
  4890. sp->get_world_3d()->get_scenario());
  4891. si->sbox_instance_offset = RenderingServer::get_singleton()->instance_create2(
  4892. selection_box->get_rid(),
  4893. sp->get_world_3d()->get_scenario());
  4894. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  4895. si->sbox_instance,
  4896. RS::SHADOW_CASTING_SETTING_OFF);
  4897. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  4898. si->sbox_instance_offset,
  4899. RS::SHADOW_CASTING_SETTING_OFF);
  4900. // Use the Edit layer to hide the selection box when View Gizmos is disabled, since it is a bit distracting.
  4901. // It's still possible to approximately guess what is selected by looking at the manipulation gizmo position.
  4902. RS::get_singleton()->instance_set_layer_mask(si->sbox_instance, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
  4903. RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_offset, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
  4904. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  4905. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  4906. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_offset, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  4907. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_offset, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  4908. si->sbox_instance_xray = RenderingServer::get_singleton()->instance_create2(
  4909. selection_box_xray->get_rid(),
  4910. sp->get_world_3d()->get_scenario());
  4911. si->sbox_instance_xray_offset = RenderingServer::get_singleton()->instance_create2(
  4912. selection_box_xray->get_rid(),
  4913. sp->get_world_3d()->get_scenario());
  4914. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  4915. si->sbox_instance_xray,
  4916. RS::SHADOW_CASTING_SETTING_OFF);
  4917. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  4918. si->sbox_instance_xray_offset,
  4919. RS::SHADOW_CASTING_SETTING_OFF);
  4920. // Use the Edit layer to hide the selection box when View Gizmos is disabled, since it is a bit distracting.
  4921. // It's still possible to approximately guess what is selected by looking at the manipulation gizmo position.
  4922. RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_xray, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
  4923. RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_xray_offset, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
  4924. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  4925. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  4926. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray_offset, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  4927. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray_offset, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  4928. return si;
  4929. }
  4930. void Node3DEditor::_generate_selection_boxes() {
  4931. // Use two AABBs to create the illusion of a slightly thicker line.
  4932. AABB aabb(Vector3(), Vector3(1, 1, 1));
  4933. // Create a x-ray (visible through solid surfaces) and standard version of the selection box.
  4934. // Both will be drawn at the same position, but with different opacity.
  4935. // This lets the user see where the selection is while still having a sense of depth.
  4936. Ref<SurfaceTool> st = memnew(SurfaceTool);
  4937. Ref<SurfaceTool> st_xray = memnew(SurfaceTool);
  4938. st->begin(Mesh::PRIMITIVE_LINES);
  4939. st_xray->begin(Mesh::PRIMITIVE_LINES);
  4940. for (int i = 0; i < 12; i++) {
  4941. Vector3 a, b;
  4942. aabb.get_edge(i, a, b);
  4943. st->add_vertex(a);
  4944. st->add_vertex(b);
  4945. st_xray->add_vertex(a);
  4946. st_xray->add_vertex(b);
  4947. }
  4948. Ref<StandardMaterial3D> mat = memnew(StandardMaterial3D);
  4949. mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  4950. const Color selection_box_color = EDITOR_GET("editors/3d/selection_box_color");
  4951. mat->set_albedo(selection_box_color);
  4952. mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  4953. st->set_material(mat);
  4954. selection_box = st->commit();
  4955. Ref<StandardMaterial3D> mat_xray = memnew(StandardMaterial3D);
  4956. mat_xray->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  4957. mat_xray->set_flag(StandardMaterial3D::FLAG_DISABLE_DEPTH_TEST, true);
  4958. mat_xray->set_albedo(selection_box_color * Color(1, 1, 1, 0.15));
  4959. mat_xray->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  4960. st_xray->set_material(mat_xray);
  4961. selection_box_xray = st_xray->commit();
  4962. }
  4963. Dictionary Node3DEditor::get_state() const {
  4964. Dictionary d;
  4965. d["snap_enabled"] = snap_enabled;
  4966. d["translate_snap"] = get_translate_snap();
  4967. d["rotate_snap"] = get_rotate_snap();
  4968. d["scale_snap"] = get_scale_snap();
  4969. d["local_coords"] = tool_option_button[TOOL_OPT_LOCAL_COORDS]->is_pressed();
  4970. int vc = 0;
  4971. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT))) {
  4972. vc = 1;
  4973. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS))) {
  4974. vc = 2;
  4975. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS))) {
  4976. vc = 3;
  4977. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS))) {
  4978. vc = 4;
  4979. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT))) {
  4980. vc = 5;
  4981. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT))) {
  4982. vc = 6;
  4983. }
  4984. d["viewport_mode"] = vc;
  4985. Array vpdata;
  4986. for (int i = 0; i < 4; i++) {
  4987. vpdata.push_back(viewports[i]->get_state());
  4988. }
  4989. d["viewports"] = vpdata;
  4990. d["show_grid"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID));
  4991. d["show_origin"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN));
  4992. d["fov"] = get_fov();
  4993. d["znear"] = get_znear();
  4994. d["zfar"] = get_zfar();
  4995. Dictionary gizmos_status;
  4996. for (int i = 0; i < gizmo_plugins_by_name.size(); i++) {
  4997. if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
  4998. continue;
  4999. }
  5000. int state = gizmos_menu->get_item_state(gizmos_menu->get_item_index(i));
  5001. String name = gizmo_plugins_by_name[i]->get_gizmo_name();
  5002. gizmos_status[name] = state;
  5003. }
  5004. d["gizmos_status"] = gizmos_status;
  5005. {
  5006. Dictionary pd;
  5007. pd["sun_rotation"] = sun_rotation;
  5008. pd["environ_sky_color"] = environ_sky_color->get_pick_color();
  5009. pd["environ_ground_color"] = environ_ground_color->get_pick_color();
  5010. pd["environ_energy"] = environ_energy->get_value();
  5011. pd["environ_glow_enabled"] = environ_glow_button->is_pressed();
  5012. pd["environ_tonemap_enabled"] = environ_tonemap_button->is_pressed();
  5013. pd["environ_ao_enabled"] = environ_ao_button->is_pressed();
  5014. pd["environ_gi_enabled"] = environ_gi_button->is_pressed();
  5015. pd["sun_max_distance"] = sun_max_distance->get_value();
  5016. pd["sun_color"] = sun_color->get_pick_color();
  5017. pd["sun_energy"] = sun_energy->get_value();
  5018. pd["sun_enabled"] = sun_button->is_pressed();
  5019. pd["environ_enabled"] = environ_button->is_pressed();
  5020. d["preview_sun_env"] = pd;
  5021. }
  5022. return d;
  5023. }
  5024. void Node3DEditor::set_state(const Dictionary &p_state) {
  5025. Dictionary d = p_state;
  5026. if (d.has("snap_enabled")) {
  5027. snap_enabled = d["snap_enabled"];
  5028. tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(d["snap_enabled"]);
  5029. }
  5030. if (d.has("translate_snap")) {
  5031. snap_translate_value = d["translate_snap"];
  5032. }
  5033. if (d.has("rotate_snap")) {
  5034. snap_rotate_value = d["rotate_snap"];
  5035. }
  5036. if (d.has("scale_snap")) {
  5037. snap_scale_value = d["scale_snap"];
  5038. }
  5039. _snap_update();
  5040. if (d.has("local_coords")) {
  5041. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(d["local_coords"]);
  5042. update_transform_gizmo();
  5043. }
  5044. if (d.has("viewport_mode")) {
  5045. int vc = d["viewport_mode"];
  5046. if (vc == 1) {
  5047. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  5048. } else if (vc == 2) {
  5049. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
  5050. } else if (vc == 3) {
  5051. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
  5052. } else if (vc == 4) {
  5053. _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
  5054. } else if (vc == 5) {
  5055. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
  5056. } else if (vc == 6) {
  5057. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
  5058. }
  5059. }
  5060. if (d.has("viewports")) {
  5061. Array vp = d["viewports"];
  5062. uint32_t vp_size = static_cast<uint32_t>(vp.size());
  5063. if (vp_size > VIEWPORTS_COUNT) {
  5064. WARN_PRINT("Ignoring superfluous viewport settings from spatial editor state.");
  5065. vp_size = VIEWPORTS_COUNT;
  5066. }
  5067. for (uint32_t i = 0; i < vp_size; i++) {
  5068. viewports[i]->set_state(vp[i]);
  5069. }
  5070. }
  5071. if (d.has("zfar")) {
  5072. settings_zfar->set_value(double(d["zfar"]));
  5073. }
  5074. if (d.has("znear")) {
  5075. settings_znear->set_value(double(d["znear"]));
  5076. }
  5077. if (d.has("fov")) {
  5078. settings_fov->set_value(double(d["fov"]));
  5079. }
  5080. if (d.has("show_grid")) {
  5081. bool use = d["show_grid"];
  5082. if (use != view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID))) {
  5083. _menu_item_pressed(MENU_VIEW_GRID);
  5084. }
  5085. }
  5086. if (d.has("show_origin")) {
  5087. bool use = d["show_origin"];
  5088. if (use != view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN))) {
  5089. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), use);
  5090. RenderingServer::get_singleton()->instance_set_visible(origin_instance, use);
  5091. }
  5092. }
  5093. if (d.has("gizmos_status")) {
  5094. Dictionary gizmos_status = d["gizmos_status"];
  5095. List<Variant> keys;
  5096. gizmos_status.get_key_list(&keys);
  5097. for (int j = 0; j < gizmo_plugins_by_name.size(); ++j) {
  5098. if (!gizmo_plugins_by_name[j]->can_be_hidden()) {
  5099. continue;
  5100. }
  5101. int state = EditorNode3DGizmoPlugin::VISIBLE;
  5102. for (int i = 0; i < keys.size(); i++) {
  5103. if (gizmo_plugins_by_name.write[j]->get_gizmo_name() == String(keys[i])) {
  5104. state = gizmos_status[keys[i]];
  5105. break;
  5106. }
  5107. }
  5108. gizmo_plugins_by_name.write[j]->set_state(state);
  5109. }
  5110. _update_gizmos_menu();
  5111. }
  5112. if (d.has("preview_sun_env")) {
  5113. sun_environ_updating = true;
  5114. Dictionary pd = d["preview_sun_env"];
  5115. sun_rotation = pd["sun_rotation"];
  5116. environ_sky_color->set_pick_color(pd["environ_sky_color"]);
  5117. environ_ground_color->set_pick_color(pd["environ_ground_color"]);
  5118. environ_energy->set_value(pd["environ_energy"]);
  5119. environ_glow_button->set_pressed(pd["environ_glow_enabled"]);
  5120. environ_tonemap_button->set_pressed(pd["environ_tonemap_enabled"]);
  5121. environ_ao_button->set_pressed(pd["environ_ao_enabled"]);
  5122. environ_gi_button->set_pressed(pd["environ_gi_enabled"]);
  5123. sun_max_distance->set_value(pd["sun_max_distance"]);
  5124. sun_color->set_pick_color(pd["sun_color"]);
  5125. sun_energy->set_value(pd["sun_energy"]);
  5126. sun_button->set_pressed(pd["sun_enabled"]);
  5127. environ_button->set_pressed(pd["environ_enabled"]);
  5128. sun_environ_updating = false;
  5129. _preview_settings_changed();
  5130. _update_preview_environment();
  5131. } else {
  5132. _load_default_preview_settings();
  5133. sun_button->set_pressed(true);
  5134. environ_button->set_pressed(true);
  5135. _preview_settings_changed();
  5136. _update_preview_environment();
  5137. }
  5138. }
  5139. void Node3DEditor::edit(Node3D *p_spatial) {
  5140. if (p_spatial != selected) {
  5141. if (selected) {
  5142. Vector<Ref<Node3DGizmo>> gizmos = selected->get_gizmos();
  5143. for (int i = 0; i < gizmos.size(); i++) {
  5144. Ref<EditorNode3DGizmo> seg = gizmos[i];
  5145. if (!seg.is_valid()) {
  5146. continue;
  5147. }
  5148. seg->set_selected(false);
  5149. }
  5150. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected);
  5151. if (se) {
  5152. se->gizmo.unref();
  5153. se->subgizmos.clear();
  5154. }
  5155. selected->update_gizmos();
  5156. }
  5157. selected = p_spatial;
  5158. current_hover_gizmo = Ref<EditorNode3DGizmo>();
  5159. current_hover_gizmo_handle = -1;
  5160. current_hover_gizmo_handle_secondary = false;
  5161. if (selected) {
  5162. Vector<Ref<Node3DGizmo>> gizmos = selected->get_gizmos();
  5163. for (int i = 0; i < gizmos.size(); i++) {
  5164. Ref<EditorNode3DGizmo> seg = gizmos[i];
  5165. if (!seg.is_valid()) {
  5166. continue;
  5167. }
  5168. seg->set_selected(true);
  5169. }
  5170. selected->update_gizmos();
  5171. }
  5172. }
  5173. }
  5174. void Node3DEditor::_snap_changed() {
  5175. snap_translate_value = snap_translate->get_text().to_float();
  5176. snap_rotate_value = snap_rotate->get_text().to_float();
  5177. snap_scale_value = snap_scale->get_text().to_float();
  5178. EditorSettings::get_singleton()->set_project_metadata("3d_editor", "snap_translate_value", snap_translate_value);
  5179. EditorSettings::get_singleton()->set_project_metadata("3d_editor", "snap_rotate_value", snap_rotate_value);
  5180. EditorSettings::get_singleton()->set_project_metadata("3d_editor", "snap_scale_value", snap_scale_value);
  5181. }
  5182. void Node3DEditor::_snap_update() {
  5183. snap_translate->set_text(String::num(snap_translate_value));
  5184. snap_rotate->set_text(String::num(snap_rotate_value));
  5185. snap_scale->set_text(String::num(snap_scale_value));
  5186. }
  5187. void Node3DEditor::_xform_dialog_action() {
  5188. Transform3D t;
  5189. //translation
  5190. Vector3 scale;
  5191. Vector3 rotate;
  5192. Vector3 translate;
  5193. for (int i = 0; i < 3; i++) {
  5194. translate[i] = xform_translate[i]->get_text().to_float();
  5195. rotate[i] = Math::deg_to_rad(xform_rotate[i]->get_text().to_float());
  5196. scale[i] = xform_scale[i]->get_text().to_float();
  5197. }
  5198. t.basis.scale(scale);
  5199. t.basis.rotate(rotate);
  5200. t.origin = translate;
  5201. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  5202. undo_redo->create_action(TTR("XForm Dialog"));
  5203. const List<Node *> &selection = editor_selection->get_selected_node_list();
  5204. for (Node *E : selection) {
  5205. Node3D *sp = Object::cast_to<Node3D>(E);
  5206. if (!sp) {
  5207. continue;
  5208. }
  5209. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  5210. if (!se) {
  5211. continue;
  5212. }
  5213. bool post = xform_type->get_selected() > 0;
  5214. Transform3D tr = sp->get_global_gizmo_transform();
  5215. if (post) {
  5216. tr = tr * t;
  5217. } else {
  5218. tr.basis = t.basis * tr.basis;
  5219. tr.origin += t.origin;
  5220. }
  5221. undo_redo->add_do_method(sp, "set_global_transform", tr);
  5222. undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
  5223. }
  5224. undo_redo->commit_action();
  5225. }
  5226. void Node3DEditor::_menu_item_toggled(bool pressed, int p_option) {
  5227. switch (p_option) {
  5228. case MENU_TOOL_LOCAL_COORDS: {
  5229. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(pressed);
  5230. update_transform_gizmo();
  5231. } break;
  5232. case MENU_TOOL_USE_SNAP: {
  5233. tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(pressed);
  5234. snap_enabled = pressed;
  5235. } break;
  5236. case MENU_TOOL_OVERRIDE_CAMERA: {
  5237. EditorDebuggerNode *const debugger = EditorDebuggerNode::get_singleton();
  5238. using Override = EditorDebuggerNode::CameraOverride;
  5239. if (pressed) {
  5240. debugger->set_camera_override((Override)(Override::OVERRIDE_3D_1 + camera_override_viewport_id));
  5241. } else {
  5242. debugger->set_camera_override(Override::OVERRIDE_NONE);
  5243. }
  5244. } break;
  5245. }
  5246. }
  5247. void Node3DEditor::_menu_gizmo_toggled(int p_option) {
  5248. const int idx = gizmos_menu->get_item_index(p_option);
  5249. gizmos_menu->toggle_item_multistate(idx);
  5250. // Change icon
  5251. const int state = gizmos_menu->get_item_state(idx);
  5252. switch (state) {
  5253. case EditorNode3DGizmoPlugin::VISIBLE:
  5254. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_theme_icon(SNAME("visibility_visible")));
  5255. break;
  5256. case EditorNode3DGizmoPlugin::ON_TOP:
  5257. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_theme_icon(SNAME("visibility_xray")));
  5258. break;
  5259. case EditorNode3DGizmoPlugin::HIDDEN:
  5260. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_theme_icon(SNAME("visibility_hidden")));
  5261. break;
  5262. }
  5263. gizmo_plugins_by_name.write[p_option]->set_state(state);
  5264. update_all_gizmos();
  5265. }
  5266. void Node3DEditor::_update_camera_override_button(bool p_game_running) {
  5267. Button *const button = tool_option_button[TOOL_OPT_OVERRIDE_CAMERA];
  5268. if (p_game_running) {
  5269. button->set_disabled(false);
  5270. button->set_tooltip_text(TTR("Project Camera Override\nOverrides the running project's camera with the editor viewport camera."));
  5271. } else {
  5272. button->set_disabled(true);
  5273. button->set_pressed(false);
  5274. button->set_tooltip_text(TTR("Project Camera Override\nNo project instance running. Run the project from the editor to use this feature."));
  5275. }
  5276. }
  5277. void Node3DEditor::_update_camera_override_viewport(Object *p_viewport) {
  5278. Node3DEditorViewport *current_viewport = Object::cast_to<Node3DEditorViewport>(p_viewport);
  5279. if (!current_viewport) {
  5280. return;
  5281. }
  5282. EditorDebuggerNode *const debugger = EditorDebuggerNode::get_singleton();
  5283. camera_override_viewport_id = current_viewport->index;
  5284. if (debugger->get_camera_override() >= EditorDebuggerNode::OVERRIDE_3D_1) {
  5285. using Override = EditorDebuggerNode::CameraOverride;
  5286. debugger->set_camera_override((Override)(Override::OVERRIDE_3D_1 + camera_override_viewport_id));
  5287. }
  5288. }
  5289. void Node3DEditor::_menu_item_pressed(int p_option) {
  5290. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  5291. switch (p_option) {
  5292. case MENU_TOOL_SELECT:
  5293. case MENU_TOOL_MOVE:
  5294. case MENU_TOOL_ROTATE:
  5295. case MENU_TOOL_SCALE:
  5296. case MENU_TOOL_LIST_SELECT: {
  5297. for (int i = 0; i < TOOL_MAX; i++) {
  5298. tool_button[i]->set_pressed(i == p_option);
  5299. }
  5300. tool_mode = (ToolMode)p_option;
  5301. update_transform_gizmo();
  5302. } break;
  5303. case MENU_TRANSFORM_CONFIGURE_SNAP: {
  5304. snap_dialog->popup_centered(Size2(200, 180));
  5305. } break;
  5306. case MENU_TRANSFORM_DIALOG: {
  5307. for (int i = 0; i < 3; i++) {
  5308. xform_translate[i]->set_text("0");
  5309. xform_rotate[i]->set_text("0");
  5310. xform_scale[i]->set_text("1");
  5311. }
  5312. xform_dialog->popup_centered(Size2(320, 240) * EDSCALE);
  5313. } break;
  5314. case MENU_VIEW_USE_1_VIEWPORT: {
  5315. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_1_VIEWPORT);
  5316. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), true);
  5317. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  5318. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  5319. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  5320. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  5321. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  5322. } break;
  5323. case MENU_VIEW_USE_2_VIEWPORTS: {
  5324. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_2_VIEWPORTS);
  5325. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  5326. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), true);
  5327. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  5328. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  5329. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  5330. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  5331. } break;
  5332. case MENU_VIEW_USE_2_VIEWPORTS_ALT: {
  5333. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_2_VIEWPORTS_ALT);
  5334. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  5335. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  5336. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  5337. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  5338. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), true);
  5339. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  5340. } break;
  5341. case MENU_VIEW_USE_3_VIEWPORTS: {
  5342. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_3_VIEWPORTS);
  5343. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  5344. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  5345. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), true);
  5346. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  5347. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  5348. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  5349. } break;
  5350. case MENU_VIEW_USE_3_VIEWPORTS_ALT: {
  5351. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_3_VIEWPORTS_ALT);
  5352. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  5353. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  5354. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  5355. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  5356. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  5357. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), true);
  5358. } break;
  5359. case MENU_VIEW_USE_4_VIEWPORTS: {
  5360. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_4_VIEWPORTS);
  5361. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  5362. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  5363. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  5364. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), true);
  5365. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  5366. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  5367. } break;
  5368. case MENU_VIEW_ORIGIN: {
  5369. bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
  5370. origin_enabled = !is_checked;
  5371. RenderingServer::get_singleton()->instance_set_visible(origin_instance, origin_enabled);
  5372. // Update the grid since its appearance depends on whether the origin is enabled
  5373. _finish_grid();
  5374. _init_grid();
  5375. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), origin_enabled);
  5376. } break;
  5377. case MENU_VIEW_GRID: {
  5378. bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
  5379. grid_enabled = !is_checked;
  5380. for (int i = 0; i < 3; ++i) {
  5381. if (grid_enable[i]) {
  5382. grid_visible[i] = grid_enabled;
  5383. }
  5384. }
  5385. _finish_grid();
  5386. _init_grid();
  5387. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), grid_enabled);
  5388. } break;
  5389. case MENU_VIEW_CAMERA_SETTINGS: {
  5390. settings_dialog->popup_centered(settings_vbc->get_combined_minimum_size() + Size2(50, 50));
  5391. } break;
  5392. case MENU_SNAP_TO_FLOOR: {
  5393. snap_selected_nodes_to_floor();
  5394. } break;
  5395. case MENU_LOCK_SELECTED: {
  5396. undo_redo->create_action(TTR("Lock Selected"));
  5397. List<Node *> &selection = editor_selection->get_selected_node_list();
  5398. for (Node *E : selection) {
  5399. Node3D *spatial = Object::cast_to<Node3D>(E);
  5400. if (!spatial || !spatial->is_inside_tree()) {
  5401. continue;
  5402. }
  5403. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  5404. continue;
  5405. }
  5406. undo_redo->add_do_method(spatial, "set_meta", "_edit_lock_", true);
  5407. undo_redo->add_undo_method(spatial, "remove_meta", "_edit_lock_");
  5408. undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
  5409. undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
  5410. }
  5411. undo_redo->add_do_method(this, "_refresh_menu_icons");
  5412. undo_redo->add_undo_method(this, "_refresh_menu_icons");
  5413. undo_redo->commit_action();
  5414. } break;
  5415. case MENU_UNLOCK_SELECTED: {
  5416. undo_redo->create_action(TTR("Unlock Selected"));
  5417. List<Node *> &selection = editor_selection->get_selected_node_list();
  5418. for (Node *E : selection) {
  5419. Node3D *spatial = Object::cast_to<Node3D>(E);
  5420. if (!spatial || !spatial->is_inside_tree()) {
  5421. continue;
  5422. }
  5423. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  5424. continue;
  5425. }
  5426. undo_redo->add_do_method(spatial, "remove_meta", "_edit_lock_");
  5427. undo_redo->add_undo_method(spatial, "set_meta", "_edit_lock_", true);
  5428. undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
  5429. undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
  5430. }
  5431. undo_redo->add_do_method(this, "_refresh_menu_icons");
  5432. undo_redo->add_undo_method(this, "_refresh_menu_icons");
  5433. undo_redo->commit_action();
  5434. } break;
  5435. case MENU_GROUP_SELECTED: {
  5436. undo_redo->create_action(TTR("Group Selected"));
  5437. List<Node *> &selection = editor_selection->get_selected_node_list();
  5438. for (Node *E : selection) {
  5439. Node3D *spatial = Object::cast_to<Node3D>(E);
  5440. if (!spatial || !spatial->is_inside_tree()) {
  5441. continue;
  5442. }
  5443. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  5444. continue;
  5445. }
  5446. undo_redo->add_do_method(spatial, "set_meta", "_edit_group_", true);
  5447. undo_redo->add_undo_method(spatial, "remove_meta", "_edit_group_");
  5448. undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
  5449. undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
  5450. }
  5451. undo_redo->add_do_method(this, "_refresh_menu_icons");
  5452. undo_redo->add_undo_method(this, "_refresh_menu_icons");
  5453. undo_redo->commit_action();
  5454. } break;
  5455. case MENU_UNGROUP_SELECTED: {
  5456. undo_redo->create_action(TTR("Ungroup Selected"));
  5457. List<Node *> &selection = editor_selection->get_selected_node_list();
  5458. for (Node *E : selection) {
  5459. Node3D *spatial = Object::cast_to<Node3D>(E);
  5460. if (!spatial || !spatial->is_inside_tree()) {
  5461. continue;
  5462. }
  5463. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  5464. continue;
  5465. }
  5466. undo_redo->add_do_method(spatial, "remove_meta", "_edit_group_");
  5467. undo_redo->add_undo_method(spatial, "set_meta", "_edit_group_", true);
  5468. undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
  5469. undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
  5470. }
  5471. undo_redo->add_do_method(this, "_refresh_menu_icons");
  5472. undo_redo->add_undo_method(this, "_refresh_menu_icons");
  5473. undo_redo->commit_action();
  5474. } break;
  5475. }
  5476. }
  5477. void Node3DEditor::_init_indicators() {
  5478. {
  5479. origin_enabled = true;
  5480. grid_enabled = true;
  5481. indicator_mat.instantiate();
  5482. indicator_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  5483. indicator_mat->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  5484. indicator_mat->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
  5485. indicator_mat->set_transparency(StandardMaterial3D::Transparency::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS);
  5486. Vector<Color> origin_colors;
  5487. Vector<Vector3> origin_points;
  5488. const int count_of_elements = 3 * 6;
  5489. origin_colors.resize(count_of_elements);
  5490. origin_points.resize(count_of_elements);
  5491. int x = 0;
  5492. for (int i = 0; i < 3; i++) {
  5493. Vector3 axis;
  5494. axis[i] = 1;
  5495. Color origin_color;
  5496. switch (i) {
  5497. case 0:
  5498. origin_color = get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor));
  5499. break;
  5500. case 1:
  5501. origin_color = get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor));
  5502. break;
  5503. case 2:
  5504. origin_color = get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor));
  5505. break;
  5506. default:
  5507. origin_color = Color();
  5508. break;
  5509. }
  5510. grid_enable[i] = false;
  5511. grid_visible[i] = false;
  5512. origin_colors.set(x, origin_color);
  5513. origin_colors.set(x + 1, origin_color);
  5514. origin_colors.set(x + 2, origin_color);
  5515. origin_colors.set(x + 3, origin_color);
  5516. origin_colors.set(x + 4, origin_color);
  5517. origin_colors.set(x + 5, origin_color);
  5518. // To both allow having a large origin size and avoid jitter
  5519. // at small scales, we should segment the line into pieces.
  5520. // 3 pieces seems to do the trick, and let's use powers of 2.
  5521. origin_points.set(x, axis * 1048576);
  5522. origin_points.set(x + 1, axis * 1024);
  5523. origin_points.set(x + 2, axis * 1024);
  5524. origin_points.set(x + 3, axis * -1024);
  5525. origin_points.set(x + 4, axis * -1024);
  5526. origin_points.set(x + 5, axis * -1048576);
  5527. x += 6;
  5528. }
  5529. Ref<Shader> grid_shader = memnew(Shader);
  5530. grid_shader->set_code(R"(
  5531. // 3D editor grid shader.
  5532. shader_type spatial;
  5533. render_mode unshaded;
  5534. uniform bool orthogonal;
  5535. uniform float grid_size;
  5536. void vertex() {
  5537. // From FLAG_SRGB_VERTEX_COLOR.
  5538. if (!OUTPUT_IS_SRGB) {
  5539. COLOR.rgb = mix(pow((COLOR.rgb + vec3(0.055)) * (1.0 / (1.0 + 0.055)), vec3(2.4)), COLOR.rgb * (1.0 / 12.92), lessThan(COLOR.rgb, vec3(0.04045)));
  5540. }
  5541. }
  5542. void fragment() {
  5543. ALBEDO = COLOR.rgb;
  5544. vec3 dir = orthogonal ? -vec3(0, 0, 1) : VIEW;
  5545. float angle_fade = abs(dot(dir, NORMAL));
  5546. angle_fade = smoothstep(0.05, 0.2, angle_fade);
  5547. vec3 world_pos = (INV_VIEW_MATRIX * vec4(VERTEX, 1.0)).xyz;
  5548. vec3 world_normal = (INV_VIEW_MATRIX * vec4(NORMAL, 0.0)).xyz;
  5549. vec3 camera_world_pos = INV_VIEW_MATRIX[3].xyz;
  5550. vec3 camera_world_pos_on_plane = camera_world_pos * (1.0 - world_normal);
  5551. float dist_fade = 1.0 - (distance(world_pos, camera_world_pos_on_plane) / grid_size);
  5552. dist_fade = smoothstep(0.02, 0.3, dist_fade);
  5553. ALPHA = COLOR.a * dist_fade * angle_fade;
  5554. }
  5555. )");
  5556. for (int i = 0; i < 3; i++) {
  5557. grid_mat[i].instantiate();
  5558. grid_mat[i]->set_shader(grid_shader);
  5559. }
  5560. grid_enable[0] = EDITOR_GET("editors/3d/grid_xy_plane");
  5561. grid_enable[1] = EDITOR_GET("editors/3d/grid_yz_plane");
  5562. grid_enable[2] = EDITOR_GET("editors/3d/grid_xz_plane");
  5563. grid_visible[0] = grid_enable[0];
  5564. grid_visible[1] = grid_enable[1];
  5565. grid_visible[2] = grid_enable[2];
  5566. _init_grid();
  5567. origin = RenderingServer::get_singleton()->mesh_create();
  5568. Array d;
  5569. d.resize(RS::ARRAY_MAX);
  5570. d[RenderingServer::ARRAY_VERTEX] = origin_points;
  5571. d[RenderingServer::ARRAY_COLOR] = origin_colors;
  5572. RenderingServer::get_singleton()->mesh_add_surface_from_arrays(origin, RenderingServer::PRIMITIVE_LINES, d);
  5573. RenderingServer::get_singleton()->mesh_surface_set_material(origin, 0, indicator_mat->get_rid());
  5574. origin_instance = RenderingServer::get_singleton()->instance_create2(origin, get_tree()->get_root()->get_world_3d()->get_scenario());
  5575. RS::get_singleton()->instance_set_layer_mask(origin_instance, 1 << Node3DEditorViewport::GIZMO_GRID_LAYER);
  5576. RS::get_singleton()->instance_geometry_set_flag(origin_instance, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  5577. RS::get_singleton()->instance_geometry_set_flag(origin_instance, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  5578. RenderingServer::get_singleton()->instance_geometry_set_cast_shadows_setting(origin_instance, RS::SHADOW_CASTING_SETTING_OFF);
  5579. }
  5580. {
  5581. //move gizmo
  5582. // Inverted zxy.
  5583. Vector3 ivec = Vector3(0, 0, -1);
  5584. Vector3 nivec = Vector3(-1, -1, 0);
  5585. Vector3 ivec2 = Vector3(-1, 0, 0);
  5586. Vector3 ivec3 = Vector3(0, -1, 0);
  5587. for (int i = 0; i < 3; i++) {
  5588. Color col;
  5589. switch (i) {
  5590. case 0:
  5591. col = get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor));
  5592. break;
  5593. case 1:
  5594. col = get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor));
  5595. break;
  5596. case 2:
  5597. col = get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor));
  5598. break;
  5599. default:
  5600. col = Color();
  5601. break;
  5602. }
  5603. col.a = EDITOR_GET("editors/3d/manipulator_gizmo_opacity");
  5604. move_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  5605. move_plane_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  5606. rotate_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  5607. scale_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  5608. scale_plane_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  5609. axis_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  5610. Ref<StandardMaterial3D> mat = memnew(StandardMaterial3D);
  5611. mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  5612. mat->set_on_top_of_alpha();
  5613. mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  5614. mat->set_albedo(col);
  5615. gizmo_color[i] = mat;
  5616. Ref<StandardMaterial3D> mat_hl = mat->duplicate();
  5617. const Color albedo = col.from_hsv(col.get_h(), 0.25, 1.0, 1);
  5618. mat_hl->set_albedo(albedo);
  5619. gizmo_color_hl[i] = mat_hl;
  5620. //translate
  5621. {
  5622. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  5623. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  5624. // Arrow profile
  5625. const int arrow_points = 5;
  5626. Vector3 arrow[5] = {
  5627. nivec * 0.0 + ivec * 0.0,
  5628. nivec * 0.01 + ivec * 0.0,
  5629. nivec * 0.01 + ivec * GIZMO_ARROW_OFFSET,
  5630. nivec * 0.065 + ivec * GIZMO_ARROW_OFFSET,
  5631. nivec * 0.0 + ivec * (GIZMO_ARROW_OFFSET + GIZMO_ARROW_SIZE),
  5632. };
  5633. int arrow_sides = 16;
  5634. const real_t arrow_sides_step = Math_TAU / arrow_sides;
  5635. for (int k = 0; k < arrow_sides; k++) {
  5636. Basis ma(ivec, k * arrow_sides_step);
  5637. Basis mb(ivec, (k + 1) * arrow_sides_step);
  5638. for (int j = 0; j < arrow_points - 1; j++) {
  5639. Vector3 points[4] = {
  5640. ma.xform(arrow[j]),
  5641. mb.xform(arrow[j]),
  5642. mb.xform(arrow[j + 1]),
  5643. ma.xform(arrow[j + 1]),
  5644. };
  5645. surftool->add_vertex(points[0]);
  5646. surftool->add_vertex(points[1]);
  5647. surftool->add_vertex(points[2]);
  5648. surftool->add_vertex(points[0]);
  5649. surftool->add_vertex(points[2]);
  5650. surftool->add_vertex(points[3]);
  5651. }
  5652. }
  5653. surftool->set_material(mat);
  5654. surftool->commit(move_gizmo[i]);
  5655. }
  5656. // Plane Translation
  5657. {
  5658. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  5659. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  5660. Vector3 vec = ivec2 - ivec3;
  5661. Vector3 plane[4] = {
  5662. vec * GIZMO_PLANE_DST,
  5663. vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
  5664. vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
  5665. vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
  5666. };
  5667. Basis ma(ivec, Math_PI / 2);
  5668. Vector3 points[4] = {
  5669. ma.xform(plane[0]),
  5670. ma.xform(plane[1]),
  5671. ma.xform(plane[2]),
  5672. ma.xform(plane[3]),
  5673. };
  5674. surftool->add_vertex(points[0]);
  5675. surftool->add_vertex(points[1]);
  5676. surftool->add_vertex(points[2]);
  5677. surftool->add_vertex(points[0]);
  5678. surftool->add_vertex(points[2]);
  5679. surftool->add_vertex(points[3]);
  5680. Ref<StandardMaterial3D> plane_mat = memnew(StandardMaterial3D);
  5681. plane_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  5682. plane_mat->set_on_top_of_alpha();
  5683. plane_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  5684. plane_mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED);
  5685. plane_mat->set_albedo(col);
  5686. plane_gizmo_color[i] = plane_mat; // needed, so we can draw planes from both sides
  5687. surftool->set_material(plane_mat);
  5688. surftool->commit(move_plane_gizmo[i]);
  5689. Ref<StandardMaterial3D> plane_mat_hl = plane_mat->duplicate();
  5690. plane_mat_hl->set_albedo(albedo);
  5691. plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides
  5692. }
  5693. // Rotate
  5694. {
  5695. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  5696. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  5697. int n = 128; // number of circle segments
  5698. int m = 3; // number of thickness segments
  5699. real_t step = Math_TAU / n;
  5700. for (int j = 0; j < n; ++j) {
  5701. Basis basis = Basis(ivec, j * step);
  5702. Vector3 vertex = basis.xform(ivec2 * GIZMO_CIRCLE_SIZE);
  5703. for (int k = 0; k < m; ++k) {
  5704. Vector2 ofs = Vector2(Math::cos((Math_TAU * k) / m), Math::sin((Math_TAU * k) / m));
  5705. Vector3 normal = ivec * ofs.x + ivec2 * ofs.y;
  5706. surftool->set_normal(basis.xform(normal));
  5707. surftool->add_vertex(vertex);
  5708. }
  5709. }
  5710. for (int j = 0; j < n; ++j) {
  5711. for (int k = 0; k < m; ++k) {
  5712. int current_ring = j * m;
  5713. int next_ring = ((j + 1) % n) * m;
  5714. int current_segment = k;
  5715. int next_segment = (k + 1) % m;
  5716. surftool->add_index(current_ring + next_segment);
  5717. surftool->add_index(current_ring + current_segment);
  5718. surftool->add_index(next_ring + current_segment);
  5719. surftool->add_index(next_ring + current_segment);
  5720. surftool->add_index(next_ring + next_segment);
  5721. surftool->add_index(current_ring + next_segment);
  5722. }
  5723. }
  5724. Ref<Shader> rotate_shader = memnew(Shader);
  5725. rotate_shader->set_code(R"(
  5726. // 3D editor rotation manipulator gizmo shader.
  5727. shader_type spatial;
  5728. render_mode unshaded, depth_test_disabled;
  5729. uniform vec4 albedo;
  5730. mat3 orthonormalize(mat3 m) {
  5731. vec3 x = normalize(m[0]);
  5732. vec3 y = normalize(m[1] - x * dot(x, m[1]));
  5733. vec3 z = m[2] - x * dot(x, m[2]);
  5734. z = normalize(z - y * (dot(y,m[2])));
  5735. return mat3(x,y,z);
  5736. }
  5737. void vertex() {
  5738. mat3 mv = orthonormalize(mat3(MODELVIEW_MATRIX));
  5739. vec3 n = mv * VERTEX;
  5740. float orientation = dot(vec3(0, 0, -1), n);
  5741. if (orientation <= 0.005) {
  5742. VERTEX += NORMAL * 0.02;
  5743. }
  5744. }
  5745. void fragment() {
  5746. ALBEDO = albedo.rgb;
  5747. ALPHA = albedo.a;
  5748. }
  5749. )");
  5750. Ref<ShaderMaterial> rotate_mat = memnew(ShaderMaterial);
  5751. rotate_mat->set_render_priority(Material::RENDER_PRIORITY_MAX);
  5752. rotate_mat->set_shader(rotate_shader);
  5753. rotate_mat->set_shader_parameter("albedo", col);
  5754. rotate_gizmo_color[i] = rotate_mat;
  5755. Array arrays = surftool->commit_to_arrays();
  5756. rotate_gizmo[i]->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays);
  5757. rotate_gizmo[i]->surface_set_material(0, rotate_mat);
  5758. Ref<ShaderMaterial> rotate_mat_hl = rotate_mat->duplicate();
  5759. rotate_mat_hl->set_shader_parameter("albedo", albedo);
  5760. rotate_gizmo_color_hl[i] = rotate_mat_hl;
  5761. if (i == 2) { // Rotation white outline
  5762. Ref<ShaderMaterial> border_mat = rotate_mat->duplicate();
  5763. Ref<Shader> border_shader = memnew(Shader);
  5764. border_shader->set_code(R"(
  5765. // 3D editor rotation manipulator gizmo shader (white outline).
  5766. shader_type spatial;
  5767. render_mode unshaded, depth_test_disabled;
  5768. uniform vec4 albedo;
  5769. mat3 orthonormalize(mat3 m) {
  5770. vec3 x = normalize(m[0]);
  5771. vec3 y = normalize(m[1] - x * dot(x, m[1]));
  5772. vec3 z = m[2] - x * dot(x, m[2]);
  5773. z = normalize(z - y * (dot(y,m[2])));
  5774. return mat3(x,y,z);
  5775. }
  5776. void vertex() {
  5777. mat3 mv = orthonormalize(mat3(MODELVIEW_MATRIX));
  5778. mv = inverse(mv);
  5779. VERTEX += NORMAL*0.008;
  5780. vec3 camera_dir_local = mv * vec3(0,0,1);
  5781. vec3 camera_up_local = mv * vec3(0,1,0);
  5782. mat3 rotation_matrix = mat3(cross(camera_dir_local, camera_up_local), camera_up_local, camera_dir_local);
  5783. VERTEX = rotation_matrix * VERTEX;
  5784. }
  5785. void fragment() {
  5786. ALBEDO = albedo.rgb;
  5787. ALPHA = albedo.a;
  5788. }
  5789. )");
  5790. border_mat->set_shader(border_shader);
  5791. border_mat->set_shader_parameter("albedo", Color(0.75, 0.75, 0.75, col.a / 3.0));
  5792. rotate_gizmo[3] = Ref<ArrayMesh>(memnew(ArrayMesh));
  5793. rotate_gizmo[3]->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays);
  5794. rotate_gizmo[3]->surface_set_material(0, border_mat);
  5795. }
  5796. }
  5797. // Scale
  5798. {
  5799. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  5800. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  5801. // Cube arrow profile
  5802. const int arrow_points = 6;
  5803. Vector3 arrow[6] = {
  5804. nivec * 0.0 + ivec * 0.0,
  5805. nivec * 0.01 + ivec * 0.0,
  5806. nivec * 0.01 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
  5807. nivec * 0.07 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
  5808. nivec * 0.07 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
  5809. nivec * 0.0 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
  5810. };
  5811. int arrow_sides = 4;
  5812. const real_t arrow_sides_step = Math_TAU / arrow_sides;
  5813. for (int k = 0; k < 4; k++) {
  5814. Basis ma(ivec, k * arrow_sides_step);
  5815. Basis mb(ivec, (k + 1) * arrow_sides_step);
  5816. for (int j = 0; j < arrow_points - 1; j++) {
  5817. Vector3 points[4] = {
  5818. ma.xform(arrow[j]),
  5819. mb.xform(arrow[j]),
  5820. mb.xform(arrow[j + 1]),
  5821. ma.xform(arrow[j + 1]),
  5822. };
  5823. surftool->add_vertex(points[0]);
  5824. surftool->add_vertex(points[1]);
  5825. surftool->add_vertex(points[2]);
  5826. surftool->add_vertex(points[0]);
  5827. surftool->add_vertex(points[2]);
  5828. surftool->add_vertex(points[3]);
  5829. }
  5830. }
  5831. surftool->set_material(mat);
  5832. surftool->commit(scale_gizmo[i]);
  5833. }
  5834. // Plane Scale
  5835. {
  5836. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  5837. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  5838. Vector3 vec = ivec2 - ivec3;
  5839. Vector3 plane[4] = {
  5840. vec * GIZMO_PLANE_DST,
  5841. vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
  5842. vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
  5843. vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
  5844. };
  5845. Basis ma(ivec, Math_PI / 2);
  5846. Vector3 points[4] = {
  5847. ma.xform(plane[0]),
  5848. ma.xform(plane[1]),
  5849. ma.xform(plane[2]),
  5850. ma.xform(plane[3]),
  5851. };
  5852. surftool->add_vertex(points[0]);
  5853. surftool->add_vertex(points[1]);
  5854. surftool->add_vertex(points[2]);
  5855. surftool->add_vertex(points[0]);
  5856. surftool->add_vertex(points[2]);
  5857. surftool->add_vertex(points[3]);
  5858. Ref<StandardMaterial3D> plane_mat = memnew(StandardMaterial3D);
  5859. plane_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  5860. plane_mat->set_on_top_of_alpha();
  5861. plane_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  5862. plane_mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED);
  5863. plane_mat->set_albedo(col);
  5864. plane_gizmo_color[i] = plane_mat; // needed, so we can draw planes from both sides
  5865. surftool->set_material(plane_mat);
  5866. surftool->commit(scale_plane_gizmo[i]);
  5867. Ref<StandardMaterial3D> plane_mat_hl = plane_mat->duplicate();
  5868. plane_mat_hl->set_albedo(col.from_hsv(col.get_h(), 0.25, 1.0, 1));
  5869. plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides
  5870. }
  5871. // Lines to visualize transforms locked to an axis/plane
  5872. {
  5873. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  5874. surftool->begin(Mesh::PRIMITIVE_LINE_STRIP);
  5875. Vector3 vec;
  5876. vec[i] = 1;
  5877. // line extending through infinity(ish)
  5878. surftool->add_vertex(vec * -1048576);
  5879. surftool->add_vertex(Vector3());
  5880. surftool->add_vertex(vec * 1048576);
  5881. surftool->set_material(mat_hl);
  5882. surftool->commit(axis_gizmo[i]);
  5883. }
  5884. }
  5885. }
  5886. _generate_selection_boxes();
  5887. }
  5888. void Node3DEditor::_update_gizmos_menu() {
  5889. gizmos_menu->clear();
  5890. for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
  5891. if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
  5892. continue;
  5893. }
  5894. String plugin_name = gizmo_plugins_by_name[i]->get_gizmo_name();
  5895. const int plugin_state = gizmo_plugins_by_name[i]->get_state();
  5896. gizmos_menu->add_multistate_item(plugin_name, 3, plugin_state, i);
  5897. const int idx = gizmos_menu->get_item_index(i);
  5898. gizmos_menu->set_item_tooltip(
  5899. idx,
  5900. TTR("Click to toggle between visibility states.\n\nOpen eye: Gizmo is visible.\nClosed eye: Gizmo is hidden.\nHalf-open eye: Gizmo is also visible through opaque surfaces (\"x-ray\")."));
  5901. switch (plugin_state) {
  5902. case EditorNode3DGizmoPlugin::VISIBLE:
  5903. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_visible")));
  5904. break;
  5905. case EditorNode3DGizmoPlugin::ON_TOP:
  5906. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_xray")));
  5907. break;
  5908. case EditorNode3DGizmoPlugin::HIDDEN:
  5909. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_hidden")));
  5910. break;
  5911. }
  5912. }
  5913. }
  5914. void Node3DEditor::_update_gizmos_menu_theme() {
  5915. for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
  5916. if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
  5917. continue;
  5918. }
  5919. const int plugin_state = gizmo_plugins_by_name[i]->get_state();
  5920. const int idx = gizmos_menu->get_item_index(i);
  5921. switch (plugin_state) {
  5922. case EditorNode3DGizmoPlugin::VISIBLE:
  5923. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_visible")));
  5924. break;
  5925. case EditorNode3DGizmoPlugin::ON_TOP:
  5926. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_xray")));
  5927. break;
  5928. case EditorNode3DGizmoPlugin::HIDDEN:
  5929. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_hidden")));
  5930. break;
  5931. }
  5932. }
  5933. }
  5934. void Node3DEditor::_init_grid() {
  5935. if (!grid_enabled) {
  5936. return;
  5937. }
  5938. Camera3D *camera = get_editor_viewport(0)->camera;
  5939. Vector3 camera_position = camera->get_position();
  5940. if (camera_position == Vector3()) {
  5941. return; // Camera3D is invalid, don't draw the grid.
  5942. }
  5943. bool orthogonal = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
  5944. Vector<Color> grid_colors[3];
  5945. Vector<Vector3> grid_points[3];
  5946. Vector<Vector3> grid_normals[3];
  5947. Color primary_grid_color = EDITOR_GET("editors/3d/primary_grid_color");
  5948. Color secondary_grid_color = EDITOR_GET("editors/3d/secondary_grid_color");
  5949. int grid_size = EDITOR_GET("editors/3d/grid_size");
  5950. int primary_grid_steps = EDITOR_GET("editors/3d/primary_grid_steps");
  5951. // Which grid planes are enabled? Which should we generate?
  5952. grid_enable[0] = grid_visible[0] = EDITOR_GET("editors/3d/grid_xy_plane");
  5953. grid_enable[1] = grid_visible[1] = EDITOR_GET("editors/3d/grid_yz_plane");
  5954. grid_enable[2] = grid_visible[2] = EDITOR_GET("editors/3d/grid_xz_plane");
  5955. // Offsets division_level for bigger or smaller grids.
  5956. // Default value is -0.2. -1.0 gives Blender-like behavior, 0.5 gives huge grids.
  5957. real_t division_level_bias = EDITOR_GET("editors/3d/grid_division_level_bias");
  5958. // Default largest grid size is 8^2 (default value is 2) when primary_grid_steps is 8 (64m apart, so primary grid lines are 512m apart).
  5959. int division_level_max = EDITOR_GET("editors/3d/grid_division_level_max");
  5960. // Default smallest grid size is 8^0 (default value is 0) when primary_grid_steps is 8.
  5961. int division_level_min = EDITOR_GET("editors/3d/grid_division_level_min");
  5962. ERR_FAIL_COND_MSG(division_level_max < division_level_min, "The 3D grid's maximum division level cannot be lower than its minimum division level.");
  5963. if (primary_grid_steps != 10) { // Log10 of 10 is 1.
  5964. // Change of base rule, divide by ln(10).
  5965. real_t div = Math::log((real_t)primary_grid_steps) / (real_t)2.302585092994045901094;
  5966. // Trucation (towards zero) is intentional.
  5967. division_level_max = (int)(division_level_max / div);
  5968. division_level_min = (int)(division_level_min / div);
  5969. }
  5970. for (int a = 0; a < 3; a++) {
  5971. if (!grid_enable[a]) {
  5972. continue; // If this grid plane is disabled, skip generation.
  5973. }
  5974. int b = (a + 1) % 3;
  5975. int c = (a + 2) % 3;
  5976. Vector3 normal;
  5977. normal[c] = 1.0;
  5978. real_t camera_distance = Math::abs(camera_position[c]);
  5979. if (orthogonal) {
  5980. camera_distance = camera->get_size() / 2.0;
  5981. Vector3 camera_direction = -camera->get_global_transform().get_basis().get_column(2);
  5982. Plane grid_plane = Plane(normal);
  5983. Vector3 intersection;
  5984. if (grid_plane.intersects_ray(camera_position, camera_direction, &intersection)) {
  5985. camera_position = intersection;
  5986. }
  5987. }
  5988. real_t division_level = Math::log(Math::abs(camera_distance)) / Math::log((double)primary_grid_steps) + division_level_bias;
  5989. real_t clamped_division_level = CLAMP(division_level, division_level_min, division_level_max);
  5990. real_t division_level_floored = Math::floor(clamped_division_level);
  5991. real_t division_level_decimals = clamped_division_level - division_level_floored;
  5992. real_t small_step_size = Math::pow(primary_grid_steps, division_level_floored);
  5993. real_t large_step_size = small_step_size * primary_grid_steps;
  5994. real_t center_a = large_step_size * (int)(camera_position[a] / large_step_size);
  5995. real_t center_b = large_step_size * (int)(camera_position[b] / large_step_size);
  5996. real_t bgn_a = center_a - grid_size * small_step_size;
  5997. real_t end_a = center_a + grid_size * small_step_size;
  5998. real_t bgn_b = center_b - grid_size * small_step_size;
  5999. real_t end_b = center_b + grid_size * small_step_size;
  6000. real_t fade_size = Math::pow(primary_grid_steps, division_level - 1.0);
  6001. real_t min_fade_size = Math::pow(primary_grid_steps, float(division_level_min));
  6002. real_t max_fade_size = Math::pow(primary_grid_steps, float(division_level_max));
  6003. fade_size = CLAMP(fade_size, min_fade_size, max_fade_size);
  6004. real_t grid_fade_size = (grid_size - primary_grid_steps) * fade_size;
  6005. grid_mat[c]->set_shader_parameter("grid_size", grid_fade_size);
  6006. grid_mat[c]->set_shader_parameter("orthogonal", orthogonal);
  6007. // Cache these so we don't have to re-access memory.
  6008. Vector<Vector3> &ref_grid = grid_points[c];
  6009. Vector<Vector3> &ref_grid_normals = grid_normals[c];
  6010. Vector<Color> &ref_grid_colors = grid_colors[c];
  6011. // Count our elements same as code below it.
  6012. int expected_size = 0;
  6013. for (int i = -grid_size; i <= grid_size; i++) {
  6014. const real_t position_a = center_a + i * small_step_size;
  6015. const real_t position_b = center_b + i * small_step_size;
  6016. // Don't draw lines over the origin if it's enabled.
  6017. if (!(origin_enabled && Math::is_zero_approx(position_a))) {
  6018. expected_size += 2;
  6019. }
  6020. if (!(origin_enabled && Math::is_zero_approx(position_b))) {
  6021. expected_size += 2;
  6022. }
  6023. }
  6024. int idx = 0;
  6025. ref_grid.resize(expected_size);
  6026. ref_grid_normals.resize(expected_size);
  6027. ref_grid_colors.resize(expected_size);
  6028. // In each iteration of this loop, draw one line in each direction (so two lines per loop, in each if statement).
  6029. for (int i = -grid_size; i <= grid_size; i++) {
  6030. Color line_color;
  6031. // Is this a primary line? Set the appropriate color.
  6032. if (i % primary_grid_steps == 0) {
  6033. line_color = primary_grid_color.lerp(secondary_grid_color, division_level_decimals);
  6034. } else {
  6035. line_color = secondary_grid_color;
  6036. line_color.a = line_color.a * (1 - division_level_decimals);
  6037. }
  6038. real_t position_a = center_a + i * small_step_size;
  6039. real_t position_b = center_b + i * small_step_size;
  6040. // Don't draw lines over the origin if it's enabled.
  6041. if (!(origin_enabled && Math::is_zero_approx(position_a))) {
  6042. Vector3 line_bgn;
  6043. Vector3 line_end;
  6044. line_bgn[a] = position_a;
  6045. line_end[a] = position_a;
  6046. line_bgn[b] = bgn_b;
  6047. line_end[b] = end_b;
  6048. ref_grid.set(idx, line_bgn);
  6049. ref_grid.set(idx + 1, line_end);
  6050. ref_grid_colors.set(idx, line_color);
  6051. ref_grid_colors.set(idx + 1, line_color);
  6052. ref_grid_normals.set(idx, normal);
  6053. ref_grid_normals.set(idx + 1, normal);
  6054. idx += 2;
  6055. }
  6056. if (!(origin_enabled && Math::is_zero_approx(position_b))) {
  6057. Vector3 line_bgn;
  6058. Vector3 line_end;
  6059. line_bgn[b] = position_b;
  6060. line_end[b] = position_b;
  6061. line_bgn[a] = bgn_a;
  6062. line_end[a] = end_a;
  6063. ref_grid.set(idx, line_bgn);
  6064. ref_grid.set(idx + 1, line_end);
  6065. ref_grid_colors.set(idx, line_color);
  6066. ref_grid_colors.set(idx + 1, line_color);
  6067. ref_grid_normals.set(idx, normal);
  6068. ref_grid_normals.set(idx + 1, normal);
  6069. idx += 2;
  6070. }
  6071. }
  6072. // Create a mesh from the pushed vector points and colors.
  6073. grid[c] = RenderingServer::get_singleton()->mesh_create();
  6074. Array d;
  6075. d.resize(RS::ARRAY_MAX);
  6076. d[RenderingServer::ARRAY_VERTEX] = grid_points[c];
  6077. d[RenderingServer::ARRAY_COLOR] = grid_colors[c];
  6078. d[RenderingServer::ARRAY_NORMAL] = grid_normals[c];
  6079. RenderingServer::get_singleton()->mesh_add_surface_from_arrays(grid[c], RenderingServer::PRIMITIVE_LINES, d);
  6080. RenderingServer::get_singleton()->mesh_surface_set_material(grid[c], 0, grid_mat[c]->get_rid());
  6081. grid_instance[c] = RenderingServer::get_singleton()->instance_create2(grid[c], get_tree()->get_root()->get_world_3d()->get_scenario());
  6082. // Yes, the end of this line is supposed to be a.
  6083. RenderingServer::get_singleton()->instance_set_visible(grid_instance[c], grid_visible[a]);
  6084. RenderingServer::get_singleton()->instance_geometry_set_cast_shadows_setting(grid_instance[c], RS::SHADOW_CASTING_SETTING_OFF);
  6085. RS::get_singleton()->instance_set_layer_mask(grid_instance[c], 1 << Node3DEditorViewport::GIZMO_GRID_LAYER);
  6086. RS::get_singleton()->instance_geometry_set_flag(grid_instance[c], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  6087. RS::get_singleton()->instance_geometry_set_flag(grid_instance[c], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  6088. }
  6089. }
  6090. void Node3DEditor::_finish_indicators() {
  6091. RenderingServer::get_singleton()->free(origin_instance);
  6092. RenderingServer::get_singleton()->free(origin);
  6093. _finish_grid();
  6094. }
  6095. void Node3DEditor::_finish_grid() {
  6096. for (int i = 0; i < 3; i++) {
  6097. RenderingServer::get_singleton()->free(grid_instance[i]);
  6098. RenderingServer::get_singleton()->free(grid[i]);
  6099. }
  6100. }
  6101. void Node3DEditor::update_grid() {
  6102. const Camera3D::ProjectionType current_projection = viewports[0]->camera->get_projection();
  6103. if (current_projection != grid_camera_last_update_perspective) {
  6104. grid_init_draw = false; // redraw
  6105. grid_camera_last_update_perspective = current_projection;
  6106. }
  6107. // Gets a orthogonal or perspective position correctly (for the grid comparison)
  6108. const Vector3 camera_position = get_editor_viewport(0)->camera->get_position();
  6109. if (!grid_init_draw || grid_camera_last_update_position.distance_squared_to(camera_position) >= 100.0f) {
  6110. _finish_grid();
  6111. _init_grid();
  6112. grid_init_draw = true;
  6113. grid_camera_last_update_position = camera_position;
  6114. }
  6115. }
  6116. void Node3DEditor::_selection_changed() {
  6117. _refresh_menu_icons();
  6118. if (selected && editor_selection->get_selected_node_list().size() != 1) {
  6119. Vector<Ref<Node3DGizmo>> gizmos = selected->get_gizmos();
  6120. for (int i = 0; i < gizmos.size(); i++) {
  6121. Ref<EditorNode3DGizmo> seg = gizmos[i];
  6122. if (!seg.is_valid()) {
  6123. continue;
  6124. }
  6125. seg->set_selected(false);
  6126. }
  6127. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected);
  6128. if (se) {
  6129. se->gizmo.unref();
  6130. se->subgizmos.clear();
  6131. }
  6132. selected->update_gizmos();
  6133. selected = nullptr;
  6134. }
  6135. update_transform_gizmo();
  6136. }
  6137. void Node3DEditor::_refresh_menu_icons() {
  6138. bool all_locked = true;
  6139. bool all_grouped = true;
  6140. List<Node *> &selection = editor_selection->get_selected_node_list();
  6141. if (selection.is_empty()) {
  6142. all_locked = false;
  6143. all_grouped = false;
  6144. } else {
  6145. for (Node *E : selection) {
  6146. if (Object::cast_to<Node3D>(E) && !Object::cast_to<Node3D>(E)->has_meta("_edit_lock_")) {
  6147. all_locked = false;
  6148. break;
  6149. }
  6150. }
  6151. for (Node *E : selection) {
  6152. if (Object::cast_to<Node3D>(E) && !Object::cast_to<Node3D>(E)->has_meta("_edit_group_")) {
  6153. all_grouped = false;
  6154. break;
  6155. }
  6156. }
  6157. }
  6158. tool_button[TOOL_LOCK_SELECTED]->set_visible(!all_locked);
  6159. tool_button[TOOL_LOCK_SELECTED]->set_disabled(selection.is_empty());
  6160. tool_button[TOOL_UNLOCK_SELECTED]->set_visible(all_locked);
  6161. tool_button[TOOL_GROUP_SELECTED]->set_visible(!all_grouped);
  6162. tool_button[TOOL_GROUP_SELECTED]->set_disabled(selection.is_empty());
  6163. tool_button[TOOL_UNGROUP_SELECTED]->set_visible(all_grouped);
  6164. }
  6165. template <typename T>
  6166. HashSet<T *> _get_child_nodes(Node *parent_node) {
  6167. HashSet<T *> nodes = HashSet<T *>();
  6168. T *node = Node::cast_to<T>(parent_node);
  6169. if (node) {
  6170. nodes.insert(node);
  6171. }
  6172. for (int i = 0; i < parent_node->get_child_count(); i++) {
  6173. Node *child_node = parent_node->get_child(i);
  6174. HashSet<T *> child_nodes = _get_child_nodes<T>(child_node);
  6175. for (T *I : child_nodes) {
  6176. nodes.insert(I);
  6177. }
  6178. }
  6179. return nodes;
  6180. }
  6181. HashSet<RID> _get_physics_bodies_rid(Node *node) {
  6182. HashSet<RID> rids = HashSet<RID>();
  6183. PhysicsBody3D *pb = Node::cast_to<PhysicsBody3D>(node);
  6184. if (pb) {
  6185. rids.insert(pb->get_rid());
  6186. }
  6187. HashSet<PhysicsBody3D *> child_nodes = _get_child_nodes<PhysicsBody3D>(node);
  6188. for (const PhysicsBody3D *I : child_nodes) {
  6189. rids.insert(I->get_rid());
  6190. }
  6191. return rids;
  6192. }
  6193. void Node3DEditor::snap_selected_nodes_to_floor() {
  6194. do_snap_selected_nodes_to_floor = true;
  6195. }
  6196. void Node3DEditor::_snap_selected_nodes_to_floor() {
  6197. const List<Node *> &selection = editor_selection->get_selected_node_list();
  6198. Dictionary snap_data;
  6199. for (Node *E : selection) {
  6200. Node3D *sp = Object::cast_to<Node3D>(E);
  6201. if (sp) {
  6202. Vector3 from;
  6203. Vector3 position_offset;
  6204. // Priorities for snapping to floor are CollisionShapes, VisualInstances and then origin
  6205. HashSet<VisualInstance3D *> vi = _get_child_nodes<VisualInstance3D>(sp);
  6206. HashSet<CollisionShape3D *> cs = _get_child_nodes<CollisionShape3D>(sp);
  6207. bool found_valid_shape = false;
  6208. if (cs.size()) {
  6209. AABB aabb;
  6210. HashSet<CollisionShape3D *>::Iterator I = cs.begin();
  6211. if ((*I)->get_shape().is_valid()) {
  6212. CollisionShape3D *collision_shape = *cs.begin();
  6213. aabb = collision_shape->get_global_transform().xform(collision_shape->get_shape()->get_debug_mesh()->get_aabb());
  6214. found_valid_shape = true;
  6215. }
  6216. for (++I; I; ++I) {
  6217. CollisionShape3D *col_shape = *I;
  6218. if (col_shape->get_shape().is_valid()) {
  6219. aabb.merge_with(col_shape->get_global_transform().xform(col_shape->get_shape()->get_debug_mesh()->get_aabb()));
  6220. found_valid_shape = true;
  6221. }
  6222. }
  6223. if (found_valid_shape) {
  6224. Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
  6225. from = aabb.position + size;
  6226. position_offset.y = from.y - sp->get_global_transform().origin.y;
  6227. }
  6228. }
  6229. if (!found_valid_shape && vi.size()) {
  6230. VisualInstance3D *begin = *vi.begin();
  6231. AABB aabb = begin->get_global_transform().xform(begin->get_aabb());
  6232. for (const VisualInstance3D *I : vi) {
  6233. aabb.merge_with(I->get_global_transform().xform(I->get_aabb()));
  6234. }
  6235. Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
  6236. from = aabb.position + size;
  6237. position_offset.y = from.y - sp->get_global_transform().origin.y;
  6238. } else if (!found_valid_shape) {
  6239. from = sp->get_global_transform().origin;
  6240. }
  6241. // We add a bit of margin to the from position to avoid it from snapping
  6242. // when the spatial is already on a floor and there's another floor under
  6243. // it
  6244. from = from + Vector3(0.0, 1, 0.0);
  6245. Dictionary d;
  6246. d["from"] = from;
  6247. d["position_offset"] = position_offset;
  6248. snap_data[sp] = d;
  6249. }
  6250. }
  6251. PhysicsDirectSpaceState3D *ss = get_tree()->get_root()->get_world_3d()->get_direct_space_state();
  6252. PhysicsDirectSpaceState3D::RayResult result;
  6253. Array keys = snap_data.keys();
  6254. // The maximum height an object can travel to be snapped
  6255. const float max_snap_height = 500.0;
  6256. // Will be set to `true` if at least one node from the selection was successfully snapped
  6257. bool snapped_to_floor = false;
  6258. if (keys.size()) {
  6259. // For snapping to be performed, there must be solid geometry under at least one of the selected nodes.
  6260. // We need to check this before snapping to register the undo/redo action only if needed.
  6261. for (int i = 0; i < keys.size(); i++) {
  6262. Node *node = Object::cast_to<Node>(keys[i]);
  6263. Node3D *sp = Object::cast_to<Node3D>(node);
  6264. Dictionary d = snap_data[node];
  6265. Vector3 from = d["from"];
  6266. Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
  6267. HashSet<RID> excluded = _get_physics_bodies_rid(sp);
  6268. PhysicsDirectSpaceState3D::RayParameters ray_params;
  6269. ray_params.from = from;
  6270. ray_params.to = to;
  6271. ray_params.exclude = excluded;
  6272. if (ss->intersect_ray(ray_params, result)) {
  6273. snapped_to_floor = true;
  6274. }
  6275. }
  6276. if (snapped_to_floor) {
  6277. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  6278. undo_redo->create_action(TTR("Snap Nodes to Floor"));
  6279. // Perform snapping if at least one node can be snapped
  6280. for (int i = 0; i < keys.size(); i++) {
  6281. Node *node = Object::cast_to<Node>(keys[i]);
  6282. Node3D *sp = Object::cast_to<Node3D>(node);
  6283. Dictionary d = snap_data[node];
  6284. Vector3 from = d["from"];
  6285. Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
  6286. HashSet<RID> excluded = _get_physics_bodies_rid(sp);
  6287. PhysicsDirectSpaceState3D::RayParameters ray_params;
  6288. ray_params.from = from;
  6289. ray_params.to = to;
  6290. ray_params.exclude = excluded;
  6291. if (ss->intersect_ray(ray_params, result)) {
  6292. Vector3 position_offset = d["position_offset"];
  6293. Transform3D new_transform = sp->get_global_transform();
  6294. new_transform.origin.y = result.position.y;
  6295. new_transform.origin = new_transform.origin - position_offset;
  6296. undo_redo->add_do_method(sp, "set_global_transform", new_transform);
  6297. undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_transform());
  6298. }
  6299. }
  6300. undo_redo->commit_action();
  6301. } else {
  6302. EditorNode::get_singleton()->show_warning(TTR("Couldn't find a solid floor to snap the selection to."));
  6303. }
  6304. }
  6305. }
  6306. void Node3DEditor::shortcut_input(const Ref<InputEvent> &p_event) {
  6307. ERR_FAIL_COND(p_event.is_null());
  6308. if (!is_visible_in_tree()) {
  6309. return;
  6310. }
  6311. snap_key_enabled = Input::get_singleton()->is_key_pressed(Key::CTRL);
  6312. }
  6313. void Node3DEditor::_sun_environ_settings_pressed() {
  6314. Vector2 pos = sun_environ_settings->get_screen_position() + sun_environ_settings->get_size();
  6315. sun_environ_popup->set_position(pos - Vector2(sun_environ_popup->get_contents_minimum_size().width / 2, 0));
  6316. sun_environ_popup->reset_size();
  6317. sun_environ_popup->popup();
  6318. }
  6319. void Node3DEditor::_add_sun_to_scene(bool p_already_added_environment) {
  6320. sun_environ_popup->hide();
  6321. if (!p_already_added_environment && world_env_count == 0 && Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
  6322. // Prevent infinite feedback loop between the sun and environment methods.
  6323. _add_environment_to_scene(true);
  6324. }
  6325. Node *base = get_tree()->get_edited_scene_root();
  6326. if (!base) {
  6327. // Create a root node so we can add child nodes to it.
  6328. SceneTreeDock::get_singleton()->add_root_node(memnew(Node3D));
  6329. base = get_tree()->get_edited_scene_root();
  6330. }
  6331. ERR_FAIL_NULL(base);
  6332. Node *new_sun = preview_sun->duplicate();
  6333. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  6334. undo_redo->create_action(TTR("Add Preview Sun to Scene"));
  6335. undo_redo->add_do_method(base, "add_child", new_sun, true);
  6336. // Move to the beginning of the scene tree since more "global" nodes
  6337. // generally look better when placed at the top.
  6338. undo_redo->add_do_method(base, "move_child", new_sun, 0);
  6339. undo_redo->add_do_method(new_sun, "set_owner", base);
  6340. undo_redo->add_undo_method(base, "remove_child", new_sun);
  6341. undo_redo->add_do_reference(new_sun);
  6342. undo_redo->commit_action();
  6343. }
  6344. void Node3DEditor::_add_environment_to_scene(bool p_already_added_sun) {
  6345. sun_environ_popup->hide();
  6346. if (!p_already_added_sun && directional_light_count == 0 && Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
  6347. // Prevent infinite feedback loop between the sun and environment methods.
  6348. _add_sun_to_scene(true);
  6349. }
  6350. Node *base = get_tree()->get_edited_scene_root();
  6351. if (!base) {
  6352. // Create a root node so we can add child nodes to it.
  6353. SceneTreeDock::get_singleton()->add_root_node(memnew(Node3D));
  6354. base = get_tree()->get_edited_scene_root();
  6355. }
  6356. ERR_FAIL_NULL(base);
  6357. WorldEnvironment *new_env = memnew(WorldEnvironment);
  6358. new_env->set_environment(preview_environment->get_environment()->duplicate(true));
  6359. if (GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units")) {
  6360. new_env->set_camera_attributes(preview_environment->get_camera_attributes()->duplicate(true));
  6361. }
  6362. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  6363. undo_redo->create_action(TTR("Add Preview Environment to Scene"));
  6364. undo_redo->add_do_method(base, "add_child", new_env, true);
  6365. // Move to the beginning of the scene tree since more "global" nodes
  6366. // generally look better when placed at the top.
  6367. undo_redo->add_do_method(base, "move_child", new_env, 0);
  6368. undo_redo->add_do_method(new_env, "set_owner", base);
  6369. undo_redo->add_undo_method(base, "remove_child", new_env);
  6370. undo_redo->add_do_reference(new_env);
  6371. undo_redo->commit_action();
  6372. }
  6373. void Node3DEditor::_update_theme() {
  6374. tool_button[TOOL_MODE_SELECT]->set_icon(get_editor_theme_icon(SNAME("ToolSelect")));
  6375. tool_button[TOOL_MODE_MOVE]->set_icon(get_editor_theme_icon(SNAME("ToolMove")));
  6376. tool_button[TOOL_MODE_ROTATE]->set_icon(get_editor_theme_icon(SNAME("ToolRotate")));
  6377. tool_button[TOOL_MODE_SCALE]->set_icon(get_editor_theme_icon(SNAME("ToolScale")));
  6378. tool_button[TOOL_MODE_LIST_SELECT]->set_icon(get_editor_theme_icon(SNAME("ListSelect")));
  6379. tool_button[TOOL_LOCK_SELECTED]->set_icon(get_editor_theme_icon(SNAME("Lock")));
  6380. tool_button[TOOL_UNLOCK_SELECTED]->set_icon(get_editor_theme_icon(SNAME("Unlock")));
  6381. tool_button[TOOL_GROUP_SELECTED]->set_icon(get_editor_theme_icon(SNAME("Group")));
  6382. tool_button[TOOL_UNGROUP_SELECTED]->set_icon(get_editor_theme_icon(SNAME("Ungroup")));
  6383. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_icon(get_editor_theme_icon(SNAME("Object")));
  6384. tool_option_button[TOOL_OPT_USE_SNAP]->set_icon(get_editor_theme_icon(SNAME("Snap")));
  6385. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_icon(get_editor_theme_icon(SNAME("Camera3D")));
  6386. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), get_editor_theme_icon(SNAME("Panels1")));
  6387. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), get_editor_theme_icon(SNAME("Panels2")));
  6388. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), get_editor_theme_icon(SNAME("Panels2Alt")));
  6389. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), get_editor_theme_icon(SNAME("Panels3")));
  6390. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), get_editor_theme_icon(SNAME("Panels3Alt")));
  6391. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), get_editor_theme_icon(SNAME("Panels4")));
  6392. sun_button->set_icon(get_editor_theme_icon(SNAME("PreviewSun")));
  6393. environ_button->set_icon(get_editor_theme_icon(SNAME("PreviewEnvironment")));
  6394. sun_environ_settings->set_icon(get_editor_theme_icon(SNAME("GuiTabMenuHl")));
  6395. sun_title->add_theme_font_override("font", get_theme_font(SNAME("title_font"), SNAME("Window")));
  6396. environ_title->add_theme_font_override("font", get_theme_font(SNAME("title_font"), SNAME("Window")));
  6397. sun_color->set_custom_minimum_size(Size2(0, get_theme_constant(SNAME("color_picker_button_height"), EditorStringName(Editor))));
  6398. environ_sky_color->set_custom_minimum_size(Size2(0, get_theme_constant(SNAME("color_picker_button_height"), EditorStringName(Editor))));
  6399. environ_ground_color->set_custom_minimum_size(Size2(0, get_theme_constant(SNAME("color_picker_button_height"), EditorStringName(Editor))));
  6400. context_toolbar_panel->add_theme_style_override("panel", get_theme_stylebox(SNAME("ContextualToolbar"), EditorStringName(EditorStyles)));
  6401. }
  6402. void Node3DEditor::_notification(int p_what) {
  6403. switch (p_what) {
  6404. case NOTIFICATION_READY: {
  6405. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  6406. _refresh_menu_icons();
  6407. get_tree()->connect("node_removed", callable_mp(this, &Node3DEditor::_node_removed));
  6408. get_tree()->connect("node_added", callable_mp(this, &Node3DEditor::_node_added));
  6409. SceneTreeDock::get_singleton()->get_tree_editor()->connect("node_changed", callable_mp(this, &Node3DEditor::_refresh_menu_icons));
  6410. editor_selection->connect("selection_changed", callable_mp(this, &Node3DEditor::_selection_changed));
  6411. EditorRunBar::get_singleton()->connect("stop_pressed", callable_mp(this, &Node3DEditor::_update_camera_override_button).bind(false));
  6412. EditorRunBar::get_singleton()->connect("play_pressed", callable_mp(this, &Node3DEditor::_update_camera_override_button).bind(true));
  6413. _update_preview_environment();
  6414. sun_state->set_custom_minimum_size(sun_vb->get_combined_minimum_size());
  6415. environ_state->set_custom_minimum_size(environ_vb->get_combined_minimum_size());
  6416. ProjectSettings::get_singleton()->connect("settings_changed", callable_mp(this, &Node3DEditor::update_all_gizmos).bind(Variant()));
  6417. } break;
  6418. case NOTIFICATION_ENTER_TREE: {
  6419. _update_theme();
  6420. _register_all_gizmos();
  6421. _update_gizmos_menu();
  6422. _init_indicators();
  6423. update_all_gizmos();
  6424. } break;
  6425. case NOTIFICATION_EXIT_TREE: {
  6426. _finish_indicators();
  6427. } break;
  6428. case NOTIFICATION_THEME_CHANGED: {
  6429. _update_theme();
  6430. _update_gizmos_menu_theme();
  6431. sun_title->add_theme_font_override("font", get_theme_font(SNAME("title_font"), SNAME("Window")));
  6432. environ_title->add_theme_font_override("font", get_theme_font(SNAME("title_font"), SNAME("Window")));
  6433. } break;
  6434. case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
  6435. // Update grid color by rebuilding grid.
  6436. _finish_grid();
  6437. _init_grid();
  6438. } break;
  6439. case NOTIFICATION_VISIBILITY_CHANGED: {
  6440. if (!is_visible() && tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->is_pressed()) {
  6441. EditorDebuggerNode *debugger = EditorDebuggerNode::get_singleton();
  6442. debugger->set_camera_override(EditorDebuggerNode::OVERRIDE_NONE);
  6443. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_pressed(false);
  6444. }
  6445. } break;
  6446. case NOTIFICATION_PHYSICS_PROCESS: {
  6447. if (do_snap_selected_nodes_to_floor) {
  6448. _snap_selected_nodes_to_floor();
  6449. do_snap_selected_nodes_to_floor = false;
  6450. }
  6451. }
  6452. }
  6453. }
  6454. bool Node3DEditor::is_subgizmo_selected(int p_id) {
  6455. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  6456. if (se) {
  6457. return se->subgizmos.has(p_id);
  6458. }
  6459. return false;
  6460. }
  6461. bool Node3DEditor::is_current_selected_gizmo(const EditorNode3DGizmo *p_gizmo) {
  6462. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  6463. if (se) {
  6464. return se->gizmo == p_gizmo;
  6465. }
  6466. return false;
  6467. }
  6468. Vector<int> Node3DEditor::get_subgizmo_selection() {
  6469. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  6470. Vector<int> ret;
  6471. if (se) {
  6472. for (const KeyValue<int, Transform3D> &E : se->subgizmos) {
  6473. ret.push_back(E.key);
  6474. }
  6475. }
  6476. return ret;
  6477. }
  6478. void Node3DEditor::add_control_to_menu_panel(Control *p_control) {
  6479. ERR_FAIL_NULL(p_control);
  6480. ERR_FAIL_COND(p_control->get_parent());
  6481. VSeparator *sep = memnew(VSeparator);
  6482. context_toolbar_hbox->add_child(sep);
  6483. context_toolbar_hbox->add_child(p_control);
  6484. context_toolbar_separators[p_control] = sep;
  6485. p_control->connect("visibility_changed", callable_mp(this, &Node3DEditor::_update_context_toolbar));
  6486. _update_context_toolbar();
  6487. }
  6488. void Node3DEditor::remove_control_from_menu_panel(Control *p_control) {
  6489. ERR_FAIL_NULL(p_control);
  6490. ERR_FAIL_COND(p_control->get_parent() != context_toolbar_hbox);
  6491. p_control->disconnect("visibility_changed", callable_mp(this, &Node3DEditor::_update_context_toolbar));
  6492. VSeparator *sep = context_toolbar_separators[p_control];
  6493. context_toolbar_hbox->remove_child(sep);
  6494. context_toolbar_hbox->remove_child(p_control);
  6495. context_toolbar_separators.erase(p_control);
  6496. memdelete(sep);
  6497. _update_context_toolbar();
  6498. }
  6499. void Node3DEditor::_update_context_toolbar() {
  6500. bool has_visible = false;
  6501. bool first_visible = false;
  6502. for (int i = 0; i < context_toolbar_hbox->get_child_count(); i++) {
  6503. Control *child = Object::cast_to<Control>(context_toolbar_hbox->get_child(i));
  6504. if (!child || !context_toolbar_separators.has(child)) {
  6505. continue;
  6506. }
  6507. if (child->is_visible()) {
  6508. first_visible = !has_visible;
  6509. has_visible = true;
  6510. }
  6511. VSeparator *sep = context_toolbar_separators[child];
  6512. sep->set_visible(!first_visible && child->is_visible());
  6513. }
  6514. context_toolbar_panel->set_visible(has_visible);
  6515. }
  6516. void Node3DEditor::set_can_preview(Camera3D *p_preview) {
  6517. for (int i = 0; i < 4; i++) {
  6518. viewports[i]->set_can_preview(p_preview);
  6519. }
  6520. }
  6521. VSplitContainer *Node3DEditor::get_shader_split() {
  6522. return shader_split;
  6523. }
  6524. void Node3DEditor::add_control_to_left_panel(Control *p_control) {
  6525. left_panel_split->add_child(p_control);
  6526. left_panel_split->move_child(p_control, 0);
  6527. }
  6528. void Node3DEditor::add_control_to_right_panel(Control *p_control) {
  6529. right_panel_split->add_child(p_control);
  6530. right_panel_split->move_child(p_control, 1);
  6531. }
  6532. void Node3DEditor::remove_control_from_left_panel(Control *p_control) {
  6533. left_panel_split->remove_child(p_control);
  6534. }
  6535. void Node3DEditor::remove_control_from_right_panel(Control *p_control) {
  6536. right_panel_split->remove_child(p_control);
  6537. }
  6538. void Node3DEditor::move_control_to_left_panel(Control *p_control) {
  6539. ERR_FAIL_NULL(p_control);
  6540. if (p_control->get_parent() == left_panel_split) {
  6541. return;
  6542. }
  6543. ERR_FAIL_COND(p_control->get_parent() != right_panel_split);
  6544. right_panel_split->remove_child(p_control);
  6545. add_control_to_left_panel(p_control);
  6546. }
  6547. void Node3DEditor::move_control_to_right_panel(Control *p_control) {
  6548. ERR_FAIL_NULL(p_control);
  6549. if (p_control->get_parent() == right_panel_split) {
  6550. return;
  6551. }
  6552. ERR_FAIL_COND(p_control->get_parent() != left_panel_split);
  6553. left_panel_split->remove_child(p_control);
  6554. add_control_to_right_panel(p_control);
  6555. }
  6556. void Node3DEditor::_request_gizmo(Object *p_obj) {
  6557. Node3D *sp = Object::cast_to<Node3D>(p_obj);
  6558. if (!sp) {
  6559. return;
  6560. }
  6561. bool is_selected = (sp == selected);
  6562. Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
  6563. if (edited_scene && (sp == edited_scene || (sp->get_owner() && edited_scene->is_ancestor_of(sp)))) {
  6564. for (int i = 0; i < gizmo_plugins_by_priority.size(); ++i) {
  6565. Ref<EditorNode3DGizmo> seg = gizmo_plugins_by_priority.write[i]->get_gizmo(sp);
  6566. if (seg.is_valid()) {
  6567. sp->add_gizmo(seg);
  6568. if (is_selected != seg->is_selected()) {
  6569. seg->set_selected(is_selected);
  6570. }
  6571. }
  6572. }
  6573. if (!sp->get_gizmos().is_empty()) {
  6574. sp->update_gizmos();
  6575. }
  6576. }
  6577. }
  6578. void Node3DEditor::_request_gizmo_for_id(ObjectID p_id) {
  6579. Node3D *node = Object::cast_to<Node3D>(ObjectDB::get_instance(p_id));
  6580. if (node) {
  6581. _request_gizmo(node);
  6582. }
  6583. }
  6584. void Node3DEditor::_set_subgizmo_selection(Object *p_obj, Ref<Node3DGizmo> p_gizmo, int p_id, Transform3D p_transform) {
  6585. if (p_id == -1) {
  6586. _clear_subgizmo_selection(p_obj);
  6587. return;
  6588. }
  6589. Node3D *sp = nullptr;
  6590. if (p_obj) {
  6591. sp = Object::cast_to<Node3D>(p_obj);
  6592. } else {
  6593. sp = selected;
  6594. }
  6595. if (!sp) {
  6596. return;
  6597. }
  6598. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  6599. if (se) {
  6600. se->subgizmos.clear();
  6601. se->subgizmos.insert(p_id, p_transform);
  6602. se->gizmo = p_gizmo;
  6603. sp->update_gizmos();
  6604. update_transform_gizmo();
  6605. }
  6606. }
  6607. void Node3DEditor::_clear_subgizmo_selection(Object *p_obj) {
  6608. Node3D *sp = nullptr;
  6609. if (p_obj) {
  6610. sp = Object::cast_to<Node3D>(p_obj);
  6611. } else {
  6612. sp = selected;
  6613. }
  6614. if (!sp) {
  6615. return;
  6616. }
  6617. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  6618. if (se) {
  6619. se->subgizmos.clear();
  6620. se->gizmo.unref();
  6621. sp->update_gizmos();
  6622. update_transform_gizmo();
  6623. }
  6624. }
  6625. void Node3DEditor::_toggle_maximize_view(Object *p_viewport) {
  6626. if (!p_viewport) {
  6627. return;
  6628. }
  6629. Node3DEditorViewport *current_viewport = Object::cast_to<Node3DEditorViewport>(p_viewport);
  6630. if (!current_viewport) {
  6631. return;
  6632. }
  6633. int index = -1;
  6634. bool maximized = false;
  6635. for (int i = 0; i < 4; i++) {
  6636. if (viewports[i] == current_viewport) {
  6637. index = i;
  6638. if (current_viewport->get_global_rect() == viewport_base->get_global_rect()) {
  6639. maximized = true;
  6640. }
  6641. break;
  6642. }
  6643. }
  6644. if (index == -1) {
  6645. return;
  6646. }
  6647. if (!maximized) {
  6648. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  6649. if (i == (uint32_t)index) {
  6650. viewports[i]->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
  6651. } else {
  6652. viewports[i]->hide();
  6653. }
  6654. }
  6655. } else {
  6656. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  6657. viewports[i]->show();
  6658. }
  6659. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT))) {
  6660. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  6661. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS))) {
  6662. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
  6663. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT))) {
  6664. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
  6665. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS))) {
  6666. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
  6667. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT))) {
  6668. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
  6669. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS))) {
  6670. _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
  6671. }
  6672. }
  6673. }
  6674. void Node3DEditor::_node_added(Node *p_node) {
  6675. if (EditorNode::get_singleton()->get_scene_root()->is_ancestor_of(p_node)) {
  6676. if (Object::cast_to<WorldEnvironment>(p_node)) {
  6677. world_env_count++;
  6678. if (world_env_count == 1) {
  6679. _update_preview_environment();
  6680. }
  6681. } else if (Object::cast_to<DirectionalLight3D>(p_node)) {
  6682. directional_light_count++;
  6683. if (directional_light_count == 1) {
  6684. _update_preview_environment();
  6685. }
  6686. }
  6687. }
  6688. }
  6689. void Node3DEditor::_node_removed(Node *p_node) {
  6690. if (EditorNode::get_singleton()->get_scene_root()->is_ancestor_of(p_node)) {
  6691. if (Object::cast_to<WorldEnvironment>(p_node)) {
  6692. world_env_count--;
  6693. if (world_env_count == 0) {
  6694. _update_preview_environment();
  6695. }
  6696. } else if (Object::cast_to<DirectionalLight3D>(p_node)) {
  6697. directional_light_count--;
  6698. if (directional_light_count == 0) {
  6699. _update_preview_environment();
  6700. }
  6701. }
  6702. }
  6703. if (p_node == selected) {
  6704. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected);
  6705. if (se) {
  6706. se->gizmo.unref();
  6707. se->subgizmos.clear();
  6708. }
  6709. selected = nullptr;
  6710. update_transform_gizmo();
  6711. }
  6712. }
  6713. void Node3DEditor::_register_all_gizmos() {
  6714. add_gizmo_plugin(Ref<Camera3DGizmoPlugin>(memnew(Camera3DGizmoPlugin)));
  6715. add_gizmo_plugin(Ref<Light3DGizmoPlugin>(memnew(Light3DGizmoPlugin)));
  6716. add_gizmo_plugin(Ref<AudioStreamPlayer3DGizmoPlugin>(memnew(AudioStreamPlayer3DGizmoPlugin)));
  6717. add_gizmo_plugin(Ref<AudioListener3DGizmoPlugin>(memnew(AudioListener3DGizmoPlugin)));
  6718. add_gizmo_plugin(Ref<MeshInstance3DGizmoPlugin>(memnew(MeshInstance3DGizmoPlugin)));
  6719. add_gizmo_plugin(Ref<OccluderInstance3DGizmoPlugin>(memnew(OccluderInstance3DGizmoPlugin)));
  6720. add_gizmo_plugin(Ref<SoftBody3DGizmoPlugin>(memnew(SoftBody3DGizmoPlugin)));
  6721. add_gizmo_plugin(Ref<Sprite3DGizmoPlugin>(memnew(Sprite3DGizmoPlugin)));
  6722. add_gizmo_plugin(Ref<Label3DGizmoPlugin>(memnew(Label3DGizmoPlugin)));
  6723. add_gizmo_plugin(Ref<Marker3DGizmoPlugin>(memnew(Marker3DGizmoPlugin)));
  6724. add_gizmo_plugin(Ref<RayCast3DGizmoPlugin>(memnew(RayCast3DGizmoPlugin)));
  6725. add_gizmo_plugin(Ref<ShapeCast3DGizmoPlugin>(memnew(ShapeCast3DGizmoPlugin)));
  6726. add_gizmo_plugin(Ref<SpringArm3DGizmoPlugin>(memnew(SpringArm3DGizmoPlugin)));
  6727. add_gizmo_plugin(Ref<VehicleWheel3DGizmoPlugin>(memnew(VehicleWheel3DGizmoPlugin)));
  6728. add_gizmo_plugin(Ref<VisibleOnScreenNotifier3DGizmoPlugin>(memnew(VisibleOnScreenNotifier3DGizmoPlugin)));
  6729. add_gizmo_plugin(Ref<GPUParticles3DGizmoPlugin>(memnew(GPUParticles3DGizmoPlugin)));
  6730. add_gizmo_plugin(Ref<GPUParticlesCollision3DGizmoPlugin>(memnew(GPUParticlesCollision3DGizmoPlugin)));
  6731. add_gizmo_plugin(Ref<CPUParticles3DGizmoPlugin>(memnew(CPUParticles3DGizmoPlugin)));
  6732. add_gizmo_plugin(Ref<ReflectionProbeGizmoPlugin>(memnew(ReflectionProbeGizmoPlugin)));
  6733. add_gizmo_plugin(Ref<DecalGizmoPlugin>(memnew(DecalGizmoPlugin)));
  6734. add_gizmo_plugin(Ref<VoxelGIGizmoPlugin>(memnew(VoxelGIGizmoPlugin)));
  6735. add_gizmo_plugin(Ref<LightmapGIGizmoPlugin>(memnew(LightmapGIGizmoPlugin)));
  6736. add_gizmo_plugin(Ref<LightmapProbeGizmoPlugin>(memnew(LightmapProbeGizmoPlugin)));
  6737. add_gizmo_plugin(Ref<CollisionObject3DGizmoPlugin>(memnew(CollisionObject3DGizmoPlugin)));
  6738. add_gizmo_plugin(Ref<CollisionShape3DGizmoPlugin>(memnew(CollisionShape3DGizmoPlugin)));
  6739. add_gizmo_plugin(Ref<CollisionPolygon3DGizmoPlugin>(memnew(CollisionPolygon3DGizmoPlugin)));
  6740. add_gizmo_plugin(Ref<NavigationLink3DGizmoPlugin>(memnew(NavigationLink3DGizmoPlugin)));
  6741. add_gizmo_plugin(Ref<NavigationRegion3DGizmoPlugin>(memnew(NavigationRegion3DGizmoPlugin)));
  6742. add_gizmo_plugin(Ref<Joint3DGizmoPlugin>(memnew(Joint3DGizmoPlugin)));
  6743. add_gizmo_plugin(Ref<PhysicalBone3DGizmoPlugin>(memnew(PhysicalBone3DGizmoPlugin)));
  6744. add_gizmo_plugin(Ref<FogVolumeGizmoPlugin>(memnew(FogVolumeGizmoPlugin)));
  6745. }
  6746. void Node3DEditor::_bind_methods() {
  6747. ClassDB::bind_method("_get_editor_data", &Node3DEditor::_get_editor_data);
  6748. ClassDB::bind_method("_request_gizmo", &Node3DEditor::_request_gizmo);
  6749. ClassDB::bind_method("_request_gizmo_for_id", &Node3DEditor::_request_gizmo_for_id);
  6750. ClassDB::bind_method("_set_subgizmo_selection", &Node3DEditor::_set_subgizmo_selection);
  6751. ClassDB::bind_method("_clear_subgizmo_selection", &Node3DEditor::_clear_subgizmo_selection);
  6752. ClassDB::bind_method("_refresh_menu_icons", &Node3DEditor::_refresh_menu_icons);
  6753. ADD_SIGNAL(MethodInfo("transform_key_request"));
  6754. ADD_SIGNAL(MethodInfo("item_lock_status_changed"));
  6755. ADD_SIGNAL(MethodInfo("item_group_status_changed"));
  6756. }
  6757. void Node3DEditor::clear() {
  6758. settings_fov->set_value(EDITOR_GET("editors/3d/default_fov"));
  6759. settings_znear->set_value(EDITOR_GET("editors/3d/default_z_near"));
  6760. settings_zfar->set_value(EDITOR_GET("editors/3d/default_z_far"));
  6761. snap_translate_value = EditorSettings::get_singleton()->get_project_metadata("3d_editor", "snap_translate_value", 1);
  6762. snap_rotate_value = EditorSettings::get_singleton()->get_project_metadata("3d_editor", "snap_rotate_value", 15);
  6763. snap_scale_value = EditorSettings::get_singleton()->get_project_metadata("3d_editor", "snap_scale_value", 10);
  6764. _snap_update();
  6765. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  6766. viewports[i]->reset();
  6767. }
  6768. if (origin_instance.is_valid()) {
  6769. RenderingServer::get_singleton()->instance_set_visible(origin_instance, true);
  6770. }
  6771. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), true);
  6772. for (int i = 0; i < 3; ++i) {
  6773. if (grid_enable[i]) {
  6774. grid_visible[i] = true;
  6775. }
  6776. }
  6777. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  6778. viewports[i]->view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(Node3DEditorViewport::VIEW_AUDIO_LISTENER), i == 0);
  6779. viewports[i]->viewport->set_as_audio_listener_3d(i == 0);
  6780. }
  6781. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID), true);
  6782. grid_enabled = true;
  6783. grid_init_draw = false;
  6784. }
  6785. void Node3DEditor::_sun_direction_draw() {
  6786. sun_direction->draw_rect(Rect2(Vector2(), sun_direction->get_size()), Color(1, 1, 1, 1));
  6787. Vector3 z_axis = preview_sun->get_transform().basis.get_column(Vector3::AXIS_Z);
  6788. z_axis = get_editor_viewport(0)->camera->get_camera_transform().basis.xform_inv(z_axis);
  6789. sun_direction_material->set_shader_parameter("sun_direction", Vector3(z_axis.x, -z_axis.y, z_axis.z));
  6790. Color color = sun_color->get_pick_color() * sun_energy->get_value();
  6791. sun_direction_material->set_shader_parameter("sun_color", Vector3(color.r, color.g, color.b));
  6792. }
  6793. void Node3DEditor::_preview_settings_changed() {
  6794. if (sun_environ_updating) {
  6795. return;
  6796. }
  6797. { // preview sun
  6798. Transform3D t;
  6799. t.basis = Basis::from_euler(Vector3(sun_rotation.x, sun_rotation.y, 0));
  6800. preview_sun->set_transform(t);
  6801. sun_direction->queue_redraw();
  6802. preview_sun->set_param(Light3D::PARAM_ENERGY, sun_energy->get_value());
  6803. preview_sun->set_param(Light3D::PARAM_SHADOW_MAX_DISTANCE, sun_max_distance->get_value());
  6804. preview_sun->set_color(sun_color->get_pick_color());
  6805. }
  6806. { //preview env
  6807. sky_material->set_sky_energy_multiplier(environ_energy->get_value());
  6808. Color hz_color = environ_sky_color->get_pick_color().lerp(environ_ground_color->get_pick_color(), 0.5).lerp(Color(1, 1, 1), 0.5);
  6809. sky_material->set_sky_top_color(environ_sky_color->get_pick_color());
  6810. sky_material->set_sky_horizon_color(hz_color);
  6811. sky_material->set_ground_bottom_color(environ_ground_color->get_pick_color());
  6812. sky_material->set_ground_horizon_color(hz_color);
  6813. environment->set_ssao_enabled(environ_ao_button->is_pressed());
  6814. environment->set_glow_enabled(environ_glow_button->is_pressed());
  6815. environment->set_sdfgi_enabled(environ_gi_button->is_pressed());
  6816. environment->set_tonemapper(environ_tonemap_button->is_pressed() ? Environment::TONE_MAPPER_FILMIC : Environment::TONE_MAPPER_LINEAR);
  6817. }
  6818. }
  6819. void Node3DEditor::_load_default_preview_settings() {
  6820. sun_environ_updating = true;
  6821. // These default rotations place the preview sun at an angular altitude
  6822. // of 60 degrees (must be negative) and an azimuth of 30 degrees clockwise
  6823. // from north (or 150 CCW from south), from north east, facing south west.
  6824. // On any not-tidally-locked planet, a sun would have an angular altitude
  6825. // of 60 degrees as the average of all points on the sphere at noon.
  6826. // The azimuth choice is arbitrary, but ideally shouldn't be on an axis.
  6827. sun_rotation = Vector2(-Math::deg_to_rad(60.0), Math::deg_to_rad(150.0));
  6828. sun_angle_altitude->set_value(-Math::rad_to_deg(sun_rotation.x));
  6829. sun_angle_azimuth->set_value(180.0 - Math::rad_to_deg(sun_rotation.y));
  6830. sun_direction->queue_redraw();
  6831. environ_sky_color->set_pick_color(Color(0.385, 0.454, 0.55));
  6832. environ_ground_color->set_pick_color(Color(0.2, 0.169, 0.133));
  6833. environ_energy->set_value(1.0);
  6834. if (OS::get_singleton()->get_current_rendering_method() != "gl_compatibility") {
  6835. environ_glow_button->set_pressed(true);
  6836. }
  6837. environ_tonemap_button->set_pressed(true);
  6838. environ_ao_button->set_pressed(false);
  6839. environ_gi_button->set_pressed(false);
  6840. sun_max_distance->set_value(100);
  6841. sun_color->set_pick_color(Color(1, 1, 1));
  6842. sun_energy->set_value(1.0);
  6843. sun_environ_updating = false;
  6844. }
  6845. void Node3DEditor::_update_preview_environment() {
  6846. bool disable_light = directional_light_count > 0 || !sun_button->is_pressed();
  6847. sun_button->set_disabled(directional_light_count > 0);
  6848. if (disable_light) {
  6849. if (preview_sun->get_parent()) {
  6850. preview_sun->get_parent()->remove_child(preview_sun);
  6851. sun_state->show();
  6852. sun_vb->hide();
  6853. preview_sun_dangling = true;
  6854. }
  6855. if (directional_light_count > 0) {
  6856. sun_state->set_text(TTR("Scene contains\nDirectionalLight3D.\nPreview disabled."));
  6857. } else {
  6858. sun_state->set_text(TTR("Preview disabled."));
  6859. }
  6860. } else {
  6861. if (!preview_sun->get_parent()) {
  6862. add_child(preview_sun, true);
  6863. sun_state->hide();
  6864. sun_vb->show();
  6865. preview_sun_dangling = false;
  6866. }
  6867. }
  6868. sun_angle_altitude->set_value(-Math::rad_to_deg(sun_rotation.x));
  6869. sun_angle_azimuth->set_value(180.0 - Math::rad_to_deg(sun_rotation.y));
  6870. bool disable_env = world_env_count > 0 || !environ_button->is_pressed();
  6871. environ_button->set_disabled(world_env_count > 0);
  6872. if (disable_env) {
  6873. if (preview_environment->get_parent()) {
  6874. preview_environment->get_parent()->remove_child(preview_environment);
  6875. environ_state->show();
  6876. environ_vb->hide();
  6877. preview_env_dangling = true;
  6878. }
  6879. if (world_env_count > 0) {
  6880. environ_state->set_text(TTR("Scene contains\nWorldEnvironment.\nPreview disabled."));
  6881. } else {
  6882. environ_state->set_text(TTR("Preview disabled."));
  6883. }
  6884. } else {
  6885. if (!preview_environment->get_parent()) {
  6886. add_child(preview_environment);
  6887. environ_state->hide();
  6888. environ_vb->show();
  6889. preview_env_dangling = false;
  6890. }
  6891. }
  6892. }
  6893. void Node3DEditor::_sun_direction_input(const Ref<InputEvent> &p_event) {
  6894. Ref<InputEventMouseMotion> mm = p_event;
  6895. if (mm.is_valid() && (mm->get_button_mask().has_flag(MouseButtonMask::LEFT))) {
  6896. sun_rotation.x += mm->get_relative().y * (0.02 * EDSCALE);
  6897. sun_rotation.y -= mm->get_relative().x * (0.02 * EDSCALE);
  6898. sun_rotation.x = CLAMP(sun_rotation.x, -Math_TAU / 4, Math_TAU / 4);
  6899. sun_angle_altitude->set_value(-Math::rad_to_deg(sun_rotation.x));
  6900. sun_angle_azimuth->set_value(180.0 - Math::rad_to_deg(sun_rotation.y));
  6901. _preview_settings_changed();
  6902. }
  6903. }
  6904. void Node3DEditor::_sun_direction_angle_set() {
  6905. sun_rotation.x = Math::deg_to_rad(-sun_angle_altitude->get_value());
  6906. sun_rotation.y = Math::deg_to_rad(180.0 - sun_angle_azimuth->get_value());
  6907. _preview_settings_changed();
  6908. }
  6909. Node3DEditor::Node3DEditor() {
  6910. gizmo.visible = true;
  6911. gizmo.scale = 1.0;
  6912. viewport_environment = Ref<Environment>(memnew(Environment));
  6913. VBoxContainer *vbc = this;
  6914. custom_camera = nullptr;
  6915. singleton = this;
  6916. editor_selection = EditorNode::get_singleton()->get_editor_selection();
  6917. editor_selection->add_editor_plugin(this);
  6918. snap_enabled = false;
  6919. snap_key_enabled = false;
  6920. tool_mode = TOOL_MODE_SELECT;
  6921. camera_override_viewport_id = 0;
  6922. // Add some margin to the sides for better esthetics.
  6923. // This prevents the first button's hover/pressed effect from "touching" the panel's border,
  6924. // which looks ugly.
  6925. MarginContainer *toolbar_margin = memnew(MarginContainer);
  6926. toolbar_margin->add_theme_constant_override("margin_left", 4 * EDSCALE);
  6927. toolbar_margin->add_theme_constant_override("margin_right", 4 * EDSCALE);
  6928. vbc->add_child(toolbar_margin);
  6929. // A fluid container for all toolbars.
  6930. HFlowContainer *main_flow = memnew(HFlowContainer);
  6931. toolbar_margin->add_child(main_flow);
  6932. // Main toolbars.
  6933. HBoxContainer *main_menu_hbox = memnew(HBoxContainer);
  6934. main_flow->add_child(main_menu_hbox);
  6935. String sct;
  6936. tool_button[TOOL_MODE_SELECT] = memnew(Button);
  6937. main_menu_hbox->add_child(tool_button[TOOL_MODE_SELECT]);
  6938. tool_button[TOOL_MODE_SELECT]->set_toggle_mode(true);
  6939. tool_button[TOOL_MODE_SELECT]->set_theme_type_variation("FlatButton");
  6940. tool_button[TOOL_MODE_SELECT]->set_pressed(true);
  6941. tool_button[TOOL_MODE_SELECT]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_SELECT));
  6942. tool_button[TOOL_MODE_SELECT]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_select", TTR("Select Mode"), Key::Q));
  6943. tool_button[TOOL_MODE_SELECT]->set_shortcut_context(this);
  6944. tool_button[TOOL_MODE_SELECT]->set_tooltip_text(keycode_get_string((Key)KeyModifierMask::CMD_OR_CTRL) + TTR("Drag: Rotate selected node around pivot.") + "\n" + TTR("Alt+RMB: Show list of all nodes at position clicked, including locked."));
  6945. main_menu_hbox->add_child(memnew(VSeparator));
  6946. tool_button[TOOL_MODE_MOVE] = memnew(Button);
  6947. main_menu_hbox->add_child(tool_button[TOOL_MODE_MOVE]);
  6948. tool_button[TOOL_MODE_MOVE]->set_toggle_mode(true);
  6949. tool_button[TOOL_MODE_MOVE]->set_theme_type_variation("FlatButton");
  6950. tool_button[TOOL_MODE_MOVE]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_MOVE));
  6951. tool_button[TOOL_MODE_MOVE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_move", TTR("Move Mode"), Key::W));
  6952. tool_button[TOOL_MODE_MOVE]->set_shortcut_context(this);
  6953. tool_button[TOOL_MODE_ROTATE] = memnew(Button);
  6954. main_menu_hbox->add_child(tool_button[TOOL_MODE_ROTATE]);
  6955. tool_button[TOOL_MODE_ROTATE]->set_toggle_mode(true);
  6956. tool_button[TOOL_MODE_ROTATE]->set_theme_type_variation("FlatButton");
  6957. tool_button[TOOL_MODE_ROTATE]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_ROTATE));
  6958. tool_button[TOOL_MODE_ROTATE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_rotate", TTR("Rotate Mode"), Key::E));
  6959. tool_button[TOOL_MODE_ROTATE]->set_shortcut_context(this);
  6960. tool_button[TOOL_MODE_SCALE] = memnew(Button);
  6961. main_menu_hbox->add_child(tool_button[TOOL_MODE_SCALE]);
  6962. tool_button[TOOL_MODE_SCALE]->set_toggle_mode(true);
  6963. tool_button[TOOL_MODE_SCALE]->set_theme_type_variation("FlatButton");
  6964. tool_button[TOOL_MODE_SCALE]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_SCALE));
  6965. tool_button[TOOL_MODE_SCALE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_scale", TTR("Scale Mode"), Key::R));
  6966. tool_button[TOOL_MODE_SCALE]->set_shortcut_context(this);
  6967. main_menu_hbox->add_child(memnew(VSeparator));
  6968. tool_button[TOOL_MODE_LIST_SELECT] = memnew(Button);
  6969. main_menu_hbox->add_child(tool_button[TOOL_MODE_LIST_SELECT]);
  6970. tool_button[TOOL_MODE_LIST_SELECT]->set_toggle_mode(true);
  6971. tool_button[TOOL_MODE_LIST_SELECT]->set_theme_type_variation("FlatButton");
  6972. tool_button[TOOL_MODE_LIST_SELECT]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_LIST_SELECT));
  6973. tool_button[TOOL_MODE_LIST_SELECT]->set_tooltip_text(TTR("Show list of selectable nodes at position clicked."));
  6974. tool_button[TOOL_LOCK_SELECTED] = memnew(Button);
  6975. main_menu_hbox->add_child(tool_button[TOOL_LOCK_SELECTED]);
  6976. tool_button[TOOL_LOCK_SELECTED]->set_theme_type_variation("FlatButton");
  6977. tool_button[TOOL_LOCK_SELECTED]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_LOCK_SELECTED));
  6978. tool_button[TOOL_LOCK_SELECTED]->set_tooltip_text(TTR("Lock selected node, preventing selection and movement."));
  6979. // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
  6980. tool_button[TOOL_LOCK_SELECTED]->set_shortcut(ED_SHORTCUT("editor/lock_selected_nodes", TTR("Lock Selected Node(s)"), KeyModifierMask::CMD_OR_CTRL | Key::L));
  6981. tool_button[TOOL_UNLOCK_SELECTED] = memnew(Button);
  6982. main_menu_hbox->add_child(tool_button[TOOL_UNLOCK_SELECTED]);
  6983. tool_button[TOOL_UNLOCK_SELECTED]->set_theme_type_variation("FlatButton");
  6984. tool_button[TOOL_UNLOCK_SELECTED]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_UNLOCK_SELECTED));
  6985. tool_button[TOOL_UNLOCK_SELECTED]->set_tooltip_text(TTR("Unlock selected node, allowing selection and movement."));
  6986. // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
  6987. tool_button[TOOL_UNLOCK_SELECTED]->set_shortcut(ED_SHORTCUT("editor/unlock_selected_nodes", TTR("Unlock Selected Node(s)"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::L));
  6988. tool_button[TOOL_GROUP_SELECTED] = memnew(Button);
  6989. main_menu_hbox->add_child(tool_button[TOOL_GROUP_SELECTED]);
  6990. tool_button[TOOL_GROUP_SELECTED]->set_theme_type_variation("FlatButton");
  6991. tool_button[TOOL_GROUP_SELECTED]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_GROUP_SELECTED));
  6992. tool_button[TOOL_GROUP_SELECTED]->set_tooltip_text(TTR("Make selected node's children not selectable."));
  6993. // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
  6994. tool_button[TOOL_GROUP_SELECTED]->set_shortcut(ED_SHORTCUT("editor/group_selected_nodes", TTR("Group Selected Node(s)"), KeyModifierMask::CMD_OR_CTRL | Key::G));
  6995. tool_button[TOOL_UNGROUP_SELECTED] = memnew(Button);
  6996. main_menu_hbox->add_child(tool_button[TOOL_UNGROUP_SELECTED]);
  6997. tool_button[TOOL_UNGROUP_SELECTED]->set_theme_type_variation("FlatButton");
  6998. tool_button[TOOL_UNGROUP_SELECTED]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_UNGROUP_SELECTED));
  6999. tool_button[TOOL_UNGROUP_SELECTED]->set_tooltip_text(TTR("Make selected node's children selectable."));
  7000. // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
  7001. tool_button[TOOL_UNGROUP_SELECTED]->set_shortcut(ED_SHORTCUT("editor/ungroup_selected_nodes", TTR("Ungroup Selected Node(s)"), KeyModifierMask::CMD_OR_CTRL | KeyModifierMask::SHIFT | Key::G));
  7002. main_menu_hbox->add_child(memnew(VSeparator));
  7003. tool_option_button[TOOL_OPT_LOCAL_COORDS] = memnew(Button);
  7004. main_menu_hbox->add_child(tool_option_button[TOOL_OPT_LOCAL_COORDS]);
  7005. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_toggle_mode(true);
  7006. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_theme_type_variation("FlatButton");
  7007. tool_option_button[TOOL_OPT_LOCAL_COORDS]->connect("toggled", callable_mp(this, &Node3DEditor::_menu_item_toggled).bind(MENU_TOOL_LOCAL_COORDS));
  7008. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_shortcut(ED_SHORTCUT("spatial_editor/local_coords", TTR("Use Local Space"), Key::T));
  7009. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_shortcut_context(this);
  7010. tool_option_button[TOOL_OPT_USE_SNAP] = memnew(Button);
  7011. main_menu_hbox->add_child(tool_option_button[TOOL_OPT_USE_SNAP]);
  7012. tool_option_button[TOOL_OPT_USE_SNAP]->set_toggle_mode(true);
  7013. tool_option_button[TOOL_OPT_USE_SNAP]->set_theme_type_variation("FlatButton");
  7014. tool_option_button[TOOL_OPT_USE_SNAP]->connect("toggled", callable_mp(this, &Node3DEditor::_menu_item_toggled).bind(MENU_TOOL_USE_SNAP));
  7015. tool_option_button[TOOL_OPT_USE_SNAP]->set_shortcut(ED_SHORTCUT("spatial_editor/snap", TTR("Use Snap"), Key::Y));
  7016. tool_option_button[TOOL_OPT_USE_SNAP]->set_shortcut_context(this);
  7017. main_menu_hbox->add_child(memnew(VSeparator));
  7018. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA] = memnew(Button);
  7019. main_menu_hbox->add_child(tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]);
  7020. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_toggle_mode(true);
  7021. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_theme_type_variation("FlatButton");
  7022. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_disabled(true);
  7023. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->connect("toggled", callable_mp(this, &Node3DEditor::_menu_item_toggled).bind(MENU_TOOL_OVERRIDE_CAMERA));
  7024. _update_camera_override_button(false);
  7025. main_menu_hbox->add_child(memnew(VSeparator));
  7026. sun_button = memnew(Button);
  7027. sun_button->set_tooltip_text(TTR("Toggle preview sunlight.\nIf a DirectionalLight3D node is added to the scene, preview sunlight is disabled."));
  7028. sun_button->set_toggle_mode(true);
  7029. sun_button->set_theme_type_variation("FlatButton");
  7030. sun_button->connect("pressed", callable_mp(this, &Node3DEditor::_update_preview_environment), CONNECT_DEFERRED);
  7031. // Preview is enabled by default - ensure this applies on editor startup when there is no state yet.
  7032. sun_button->set_pressed(true);
  7033. main_menu_hbox->add_child(sun_button);
  7034. environ_button = memnew(Button);
  7035. environ_button->set_tooltip_text(TTR("Toggle preview environment.\nIf a WorldEnvironment node is added to the scene, preview environment is disabled."));
  7036. environ_button->set_toggle_mode(true);
  7037. environ_button->set_theme_type_variation("FlatButton");
  7038. environ_button->connect("pressed", callable_mp(this, &Node3DEditor::_update_preview_environment), CONNECT_DEFERRED);
  7039. // Preview is enabled by default - ensure this applies on editor startup when there is no state yet.
  7040. environ_button->set_pressed(true);
  7041. main_menu_hbox->add_child(environ_button);
  7042. sun_environ_settings = memnew(Button);
  7043. sun_environ_settings->set_tooltip_text(TTR("Edit Sun and Environment settings."));
  7044. sun_environ_settings->set_theme_type_variation("FlatButton");
  7045. sun_environ_settings->connect("pressed", callable_mp(this, &Node3DEditor::_sun_environ_settings_pressed));
  7046. main_menu_hbox->add_child(sun_environ_settings);
  7047. main_menu_hbox->add_child(memnew(VSeparator));
  7048. // Drag and drop support;
  7049. preview_node = memnew(Node3D);
  7050. preview_bounds = AABB();
  7051. ED_SHORTCUT("spatial_editor/bottom_view", TTR("Bottom View"), KeyModifierMask::ALT + Key::KP_7);
  7052. ED_SHORTCUT("spatial_editor/top_view", TTR("Top View"), Key::KP_7);
  7053. ED_SHORTCUT("spatial_editor/rear_view", TTR("Rear View"), KeyModifierMask::ALT + Key::KP_1);
  7054. ED_SHORTCUT("spatial_editor/front_view", TTR("Front View"), Key::KP_1);
  7055. ED_SHORTCUT("spatial_editor/left_view", TTR("Left View"), KeyModifierMask::ALT + Key::KP_3);
  7056. ED_SHORTCUT("spatial_editor/right_view", TTR("Right View"), Key::KP_3);
  7057. ED_SHORTCUT("spatial_editor/orbit_view_down", TTR("Orbit View Down"), Key::KP_2);
  7058. ED_SHORTCUT("spatial_editor/orbit_view_left", TTR("Orbit View Left"), Key::KP_4);
  7059. ED_SHORTCUT("spatial_editor/orbit_view_right", TTR("Orbit View Right"), Key::KP_6);
  7060. ED_SHORTCUT("spatial_editor/orbit_view_up", TTR("Orbit View Up"), Key::KP_8);
  7061. ED_SHORTCUT("spatial_editor/orbit_view_180", TTR("Orbit View 180"), Key::KP_9);
  7062. ED_SHORTCUT("spatial_editor/switch_perspective_orthogonal", TTR("Switch Perspective/Orthogonal View"), Key::KP_5);
  7063. ED_SHORTCUT("spatial_editor/insert_anim_key", TTR("Insert Animation Key"), Key::K);
  7064. ED_SHORTCUT("spatial_editor/focus_origin", TTR("Focus Origin"), Key::O);
  7065. ED_SHORTCUT("spatial_editor/focus_selection", TTR("Focus Selection"), Key::F);
  7066. ED_SHORTCUT("spatial_editor/align_transform_with_view", TTR("Align Transform with View"), KeyModifierMask::ALT + KeyModifierMask::CMD_OR_CTRL + Key::M);
  7067. ED_SHORTCUT("spatial_editor/align_rotation_with_view", TTR("Align Rotation with View"), KeyModifierMask::ALT + KeyModifierMask::CMD_OR_CTRL + Key::F);
  7068. ED_SHORTCUT("spatial_editor/freelook_toggle", TTR("Toggle Freelook"), KeyModifierMask::SHIFT + Key::F);
  7069. ED_SHORTCUT("spatial_editor/decrease_fov", TTR("Decrease Field of View"), KeyModifierMask::CMD_OR_CTRL + Key::EQUAL); // Usually direct access key for `KEY_PLUS`.
  7070. ED_SHORTCUT("spatial_editor/increase_fov", TTR("Increase Field of View"), KeyModifierMask::CMD_OR_CTRL + Key::MINUS);
  7071. ED_SHORTCUT("spatial_editor/reset_fov", TTR("Reset Field of View to Default"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_0);
  7072. PopupMenu *p;
  7073. transform_menu = memnew(MenuButton);
  7074. transform_menu->set_flat(false);
  7075. transform_menu->set_theme_type_variation("FlatMenuButton");
  7076. transform_menu->set_text(TTR("Transform"));
  7077. transform_menu->set_switch_on_hover(true);
  7078. transform_menu->set_shortcut_context(this);
  7079. main_menu_hbox->add_child(transform_menu);
  7080. p = transform_menu->get_popup();
  7081. p->add_shortcut(ED_SHORTCUT("spatial_editor/snap_to_floor", TTR("Snap Object to Floor"), Key::PAGEDOWN), MENU_SNAP_TO_FLOOR);
  7082. p->add_shortcut(ED_SHORTCUT("spatial_editor/transform_dialog", TTR("Transform Dialog...")), MENU_TRANSFORM_DIALOG);
  7083. p->add_separator();
  7084. p->add_shortcut(ED_SHORTCUT("spatial_editor/configure_snap", TTR("Configure Snap...")), MENU_TRANSFORM_CONFIGURE_SNAP);
  7085. p->connect("id_pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed));
  7086. view_menu = memnew(MenuButton);
  7087. view_menu->set_flat(false);
  7088. view_menu->set_theme_type_variation("FlatMenuButton");
  7089. // TRANSLATORS: Noun, name of the 2D/3D View menus.
  7090. view_menu->set_text(TTR("View"));
  7091. view_menu->set_switch_on_hover(true);
  7092. view_menu->set_shortcut_context(this);
  7093. main_menu_hbox->add_child(view_menu);
  7094. main_menu_hbox->add_child(memnew(VSeparator));
  7095. context_toolbar_panel = memnew(PanelContainer);
  7096. context_toolbar_hbox = memnew(HBoxContainer);
  7097. context_toolbar_panel->add_child(context_toolbar_hbox);
  7098. main_flow->add_child(context_toolbar_panel);
  7099. // Get the view menu popup and have it stay open when a checkable item is selected
  7100. p = view_menu->get_popup();
  7101. p->set_hide_on_checkable_item_selection(false);
  7102. accept = memnew(AcceptDialog);
  7103. EditorNode::get_singleton()->get_gui_base()->add_child(accept);
  7104. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/1_viewport", TTR("1 Viewport"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_1), MENU_VIEW_USE_1_VIEWPORT);
  7105. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports", TTR("2 Viewports"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_2), MENU_VIEW_USE_2_VIEWPORTS);
  7106. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports_alt", TTR("2 Viewports (Alt)"), KeyModifierMask::ALT + KeyModifierMask::CMD_OR_CTRL + Key::KEY_2), MENU_VIEW_USE_2_VIEWPORTS_ALT);
  7107. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports", TTR("3 Viewports"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_3), MENU_VIEW_USE_3_VIEWPORTS);
  7108. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports_alt", TTR("3 Viewports (Alt)"), KeyModifierMask::ALT + KeyModifierMask::CMD_OR_CTRL + Key::KEY_3), MENU_VIEW_USE_3_VIEWPORTS_ALT);
  7109. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/4_viewports", TTR("4 Viewports"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_4), MENU_VIEW_USE_4_VIEWPORTS);
  7110. p->add_separator();
  7111. p->add_submenu_item(TTR("Gizmos"), "GizmosMenu");
  7112. p->add_separator();
  7113. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_origin", TTR("View Origin")), MENU_VIEW_ORIGIN);
  7114. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_grid", TTR("View Grid"), Key::NUMBERSIGN), MENU_VIEW_GRID);
  7115. p->add_separator();
  7116. p->add_shortcut(ED_SHORTCUT("spatial_editor/settings", TTR("Settings...")), MENU_VIEW_CAMERA_SETTINGS);
  7117. p->set_item_checked(p->get_item_index(MENU_VIEW_ORIGIN), true);
  7118. p->set_item_checked(p->get_item_index(MENU_VIEW_GRID), true);
  7119. p->connect("id_pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed));
  7120. gizmos_menu = memnew(PopupMenu);
  7121. p->add_child(gizmos_menu);
  7122. gizmos_menu->set_name("GizmosMenu");
  7123. gizmos_menu->set_hide_on_checkable_item_selection(false);
  7124. gizmos_menu->connect("id_pressed", callable_mp(this, &Node3DEditor::_menu_gizmo_toggled));
  7125. /* REST OF MENU */
  7126. left_panel_split = memnew(HSplitContainer);
  7127. left_panel_split->set_v_size_flags(SIZE_EXPAND_FILL);
  7128. vbc->add_child(left_panel_split);
  7129. right_panel_split = memnew(HSplitContainer);
  7130. right_panel_split->set_v_size_flags(SIZE_EXPAND_FILL);
  7131. left_panel_split->add_child(right_panel_split);
  7132. shader_split = memnew(VSplitContainer);
  7133. shader_split->set_h_size_flags(SIZE_EXPAND_FILL);
  7134. right_panel_split->add_child(shader_split);
  7135. viewport_base = memnew(Node3DEditorViewportContainer);
  7136. shader_split->add_child(viewport_base);
  7137. viewport_base->set_v_size_flags(SIZE_EXPAND_FILL);
  7138. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  7139. viewports[i] = memnew(Node3DEditorViewport(this, i));
  7140. viewports[i]->connect("toggle_maximize_view", callable_mp(this, &Node3DEditor::_toggle_maximize_view));
  7141. viewports[i]->connect("clicked", callable_mp(this, &Node3DEditor::_update_camera_override_viewport));
  7142. viewports[i]->assign_pending_data_pointers(preview_node, &preview_bounds, accept);
  7143. viewport_base->add_child(viewports[i]);
  7144. }
  7145. /* SNAP DIALOG */
  7146. snap_dialog = memnew(ConfirmationDialog);
  7147. snap_dialog->set_title(TTR("Snap Settings"));
  7148. add_child(snap_dialog);
  7149. snap_dialog->connect("confirmed", callable_mp(this, &Node3DEditor::_snap_changed));
  7150. snap_dialog->get_cancel_button()->connect("pressed", callable_mp(this, &Node3DEditor::_snap_update));
  7151. VBoxContainer *snap_dialog_vbc = memnew(VBoxContainer);
  7152. snap_dialog->add_child(snap_dialog_vbc);
  7153. snap_translate = memnew(LineEdit);
  7154. snap_translate->set_select_all_on_focus(true);
  7155. snap_dialog_vbc->add_margin_child(TTR("Translate Snap:"), snap_translate);
  7156. snap_rotate = memnew(LineEdit);
  7157. snap_rotate->set_select_all_on_focus(true);
  7158. snap_dialog_vbc->add_margin_child(TTR("Rotate Snap (deg.):"), snap_rotate);
  7159. snap_scale = memnew(LineEdit);
  7160. snap_scale->set_select_all_on_focus(true);
  7161. snap_dialog_vbc->add_margin_child(TTR("Scale Snap (%):"), snap_scale);
  7162. /* SETTINGS DIALOG */
  7163. settings_dialog = memnew(ConfirmationDialog);
  7164. settings_dialog->set_title(TTR("Viewport Settings"));
  7165. add_child(settings_dialog);
  7166. settings_vbc = memnew(VBoxContainer);
  7167. settings_vbc->set_custom_minimum_size(Size2(200, 0) * EDSCALE);
  7168. settings_dialog->add_child(settings_vbc);
  7169. settings_fov = memnew(SpinBox);
  7170. settings_fov->set_max(MAX_FOV);
  7171. settings_fov->set_min(MIN_FOV);
  7172. settings_fov->set_step(0.1);
  7173. settings_fov->set_value(EDITOR_GET("editors/3d/default_fov"));
  7174. settings_fov->set_select_all_on_focus(true);
  7175. settings_vbc->add_margin_child(TTR("Perspective FOV (deg.):"), settings_fov);
  7176. settings_znear = memnew(SpinBox);
  7177. settings_znear->set_max(MAX_Z);
  7178. settings_znear->set_min(MIN_Z);
  7179. settings_znear->set_step(0.01);
  7180. settings_znear->set_value(EDITOR_GET("editors/3d/default_z_near"));
  7181. settings_znear->set_select_all_on_focus(true);
  7182. settings_vbc->add_margin_child(TTR("View Z-Near:"), settings_znear);
  7183. settings_zfar = memnew(SpinBox);
  7184. settings_zfar->set_max(MAX_Z);
  7185. settings_zfar->set_min(MIN_Z);
  7186. settings_zfar->set_step(0.1);
  7187. settings_zfar->set_value(EDITOR_GET("editors/3d/default_z_far"));
  7188. settings_zfar->set_select_all_on_focus(true);
  7189. settings_vbc->add_margin_child(TTR("View Z-Far:"), settings_zfar);
  7190. for (uint32_t i = 0; i < VIEWPORTS_COUNT; ++i) {
  7191. settings_dialog->connect("confirmed", callable_mp(viewports[i], &Node3DEditorViewport::_view_settings_confirmed).bind(0.0));
  7192. }
  7193. /* XFORM DIALOG */
  7194. xform_dialog = memnew(ConfirmationDialog);
  7195. xform_dialog->set_title(TTR("Transform Change"));
  7196. add_child(xform_dialog);
  7197. VBoxContainer *xform_vbc = memnew(VBoxContainer);
  7198. xform_dialog->add_child(xform_vbc);
  7199. Label *l = memnew(Label);
  7200. l->set_text(TTR("Translate:"));
  7201. xform_vbc->add_child(l);
  7202. HBoxContainer *xform_hbc = memnew(HBoxContainer);
  7203. xform_vbc->add_child(xform_hbc);
  7204. for (int i = 0; i < 3; i++) {
  7205. xform_translate[i] = memnew(LineEdit);
  7206. xform_translate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  7207. xform_translate[i]->set_select_all_on_focus(true);
  7208. xform_hbc->add_child(xform_translate[i]);
  7209. }
  7210. l = memnew(Label);
  7211. l->set_text(TTR("Rotate (deg.):"));
  7212. xform_vbc->add_child(l);
  7213. xform_hbc = memnew(HBoxContainer);
  7214. xform_vbc->add_child(xform_hbc);
  7215. for (int i = 0; i < 3; i++) {
  7216. xform_rotate[i] = memnew(LineEdit);
  7217. xform_rotate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  7218. xform_rotate[i]->set_select_all_on_focus(true);
  7219. xform_hbc->add_child(xform_rotate[i]);
  7220. }
  7221. l = memnew(Label);
  7222. l->set_text(TTR("Scale (ratio):"));
  7223. xform_vbc->add_child(l);
  7224. xform_hbc = memnew(HBoxContainer);
  7225. xform_vbc->add_child(xform_hbc);
  7226. for (int i = 0; i < 3; i++) {
  7227. xform_scale[i] = memnew(LineEdit);
  7228. xform_scale[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  7229. xform_scale[i]->set_select_all_on_focus(true);
  7230. xform_hbc->add_child(xform_scale[i]);
  7231. }
  7232. l = memnew(Label);
  7233. l->set_text(TTR("Transform Type"));
  7234. xform_vbc->add_child(l);
  7235. xform_type = memnew(OptionButton);
  7236. xform_type->set_h_size_flags(SIZE_EXPAND_FILL);
  7237. xform_type->add_item(TTR("Pre"));
  7238. xform_type->add_item(TTR("Post"));
  7239. xform_vbc->add_child(xform_type);
  7240. xform_dialog->connect("confirmed", callable_mp(this, &Node3DEditor::_xform_dialog_action));
  7241. selected = nullptr;
  7242. set_process_shortcut_input(true);
  7243. add_to_group("_spatial_editor_group");
  7244. EDITOR_DEF("editors/3d/manipulator_gizmo_size", 80);
  7245. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "editors/3d/manipulator_gizmo_size", PROPERTY_HINT_RANGE, "16,160,1"));
  7246. EDITOR_DEF("editors/3d/manipulator_gizmo_opacity", 0.9);
  7247. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::FLOAT, "editors/3d/manipulator_gizmo_opacity", PROPERTY_HINT_RANGE, "0,1,0.01"));
  7248. EDITOR_DEF("editors/3d/navigation/show_viewport_rotation_gizmo", true);
  7249. EDITOR_DEF("editors/3d/navigation/show_viewport_navigation_gizmo", DisplayServer::get_singleton()->is_touchscreen_available());
  7250. current_hover_gizmo_handle = -1;
  7251. current_hover_gizmo_handle_secondary = false;
  7252. {
  7253. //sun popup
  7254. sun_environ_popup = memnew(PopupPanel);
  7255. add_child(sun_environ_popup);
  7256. HBoxContainer *sun_environ_hb = memnew(HBoxContainer);
  7257. sun_environ_popup->add_child(sun_environ_hb);
  7258. sun_vb = memnew(VBoxContainer);
  7259. sun_environ_hb->add_child(sun_vb);
  7260. sun_vb->set_custom_minimum_size(Size2(200 * EDSCALE, 0));
  7261. sun_vb->hide();
  7262. sun_title = memnew(Label);
  7263. sun_title->set_theme_type_variation("HeaderSmall");
  7264. sun_vb->add_child(sun_title);
  7265. sun_title->set_text(TTR("Preview Sun"));
  7266. sun_title->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  7267. CenterContainer *sun_direction_center = memnew(CenterContainer);
  7268. sun_direction = memnew(Control);
  7269. sun_direction->set_custom_minimum_size(Size2(128, 128) * EDSCALE);
  7270. sun_direction_center->add_child(sun_direction);
  7271. sun_vb->add_margin_child(TTR("Sun Direction"), sun_direction_center);
  7272. sun_direction->connect("gui_input", callable_mp(this, &Node3DEditor::_sun_direction_input));
  7273. sun_direction->connect("draw", callable_mp(this, &Node3DEditor::_sun_direction_draw));
  7274. sun_direction->set_default_cursor_shape(CURSOR_MOVE);
  7275. sun_direction_shader.instantiate();
  7276. sun_direction_shader->set_code(R"(
  7277. // 3D editor Preview Sun direction shader.
  7278. shader_type canvas_item;
  7279. uniform vec3 sun_direction;
  7280. uniform vec3 sun_color;
  7281. void fragment() {
  7282. vec3 n;
  7283. n.xy = UV * 2.0 - 1.0;
  7284. n.z = sqrt(max(0.0, 1.0 - dot(n.xy, n.xy)));
  7285. COLOR.rgb = dot(n, sun_direction) * sun_color;
  7286. COLOR.a = 1.0 - smoothstep(0.99, 1.0, length(n.xy));
  7287. }
  7288. )");
  7289. sun_direction_material.instantiate();
  7290. sun_direction_material->set_shader(sun_direction_shader);
  7291. sun_direction_material->set_shader_parameter("sun_direction", Vector3(0, 0, 1));
  7292. sun_direction_material->set_shader_parameter("sun_color", Vector3(1, 1, 1));
  7293. sun_direction->set_material(sun_direction_material);
  7294. HBoxContainer *sun_angle_hbox = memnew(HBoxContainer);
  7295. VBoxContainer *sun_angle_altitude_vbox = memnew(VBoxContainer);
  7296. Label *sun_angle_altitude_label = memnew(Label);
  7297. sun_angle_altitude_label->set_text(TTR("Angular Altitude"));
  7298. sun_angle_altitude_vbox->add_child(sun_angle_altitude_label);
  7299. sun_angle_altitude = memnew(EditorSpinSlider);
  7300. sun_angle_altitude->set_max(90);
  7301. sun_angle_altitude->set_min(-90);
  7302. sun_angle_altitude->set_step(0.1);
  7303. sun_angle_altitude->connect("value_changed", callable_mp(this, &Node3DEditor::_sun_direction_angle_set).unbind(1));
  7304. sun_angle_altitude_vbox->add_child(sun_angle_altitude);
  7305. sun_angle_hbox->add_child(sun_angle_altitude_vbox);
  7306. VBoxContainer *sun_angle_azimuth_vbox = memnew(VBoxContainer);
  7307. sun_angle_azimuth_vbox->set_custom_minimum_size(Vector2(100, 0));
  7308. Label *sun_angle_azimuth_label = memnew(Label);
  7309. sun_angle_azimuth_label->set_text(TTR("Azimuth"));
  7310. sun_angle_azimuth_vbox->add_child(sun_angle_azimuth_label);
  7311. sun_angle_azimuth = memnew(EditorSpinSlider);
  7312. sun_angle_azimuth->set_max(180);
  7313. sun_angle_azimuth->set_min(-180);
  7314. sun_angle_azimuth->set_step(0.1);
  7315. sun_angle_azimuth->set_allow_greater(true);
  7316. sun_angle_azimuth->set_allow_lesser(true);
  7317. sun_angle_azimuth->connect("value_changed", callable_mp(this, &Node3DEditor::_sun_direction_angle_set).unbind(1));
  7318. sun_angle_azimuth_vbox->add_child(sun_angle_azimuth);
  7319. sun_angle_hbox->add_child(sun_angle_azimuth_vbox);
  7320. sun_angle_hbox->add_theme_constant_override("separation", 10);
  7321. sun_vb->add_child(sun_angle_hbox);
  7322. sun_color = memnew(ColorPickerButton);
  7323. sun_color->set_edit_alpha(false);
  7324. sun_vb->add_margin_child(TTR("Sun Color"), sun_color);
  7325. sun_color->connect("color_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7326. sun_color->get_popup()->connect("about_to_popup", callable_mp(EditorNode::get_singleton(), &EditorNode::setup_color_picker).bind(sun_color->get_picker()));
  7327. sun_energy = memnew(EditorSpinSlider);
  7328. sun_energy->set_max(64.0);
  7329. sun_energy->set_min(0);
  7330. sun_energy->set_step(0.05);
  7331. sun_vb->add_margin_child(TTR("Sun Energy"), sun_energy);
  7332. sun_energy->connect("value_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7333. sun_max_distance = memnew(EditorSpinSlider);
  7334. sun_vb->add_margin_child(TTR("Shadow Max Distance"), sun_max_distance);
  7335. sun_max_distance->connect("value_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7336. sun_max_distance->set_min(1);
  7337. sun_max_distance->set_max(4096);
  7338. sun_add_to_scene = memnew(Button);
  7339. sun_add_to_scene->set_text(TTR("Add Sun to Scene"));
  7340. sun_add_to_scene->set_tooltip_text(TTR("Adds a DirectionalLight3D node matching the preview sun settings to the current scene.\nHold Shift while clicking to also add the preview environment to the current scene."));
  7341. sun_add_to_scene->connect("pressed", callable_mp(this, &Node3DEditor::_add_sun_to_scene).bind(false));
  7342. sun_vb->add_spacer();
  7343. sun_vb->add_child(sun_add_to_scene);
  7344. sun_state = memnew(Label);
  7345. sun_environ_hb->add_child(sun_state);
  7346. sun_state->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  7347. sun_state->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
  7348. sun_state->set_h_size_flags(SIZE_EXPAND_FILL);
  7349. VSeparator *sc = memnew(VSeparator);
  7350. sc->set_custom_minimum_size(Size2(50 * EDSCALE, 0));
  7351. sc->set_v_size_flags(SIZE_EXPAND_FILL);
  7352. sun_environ_hb->add_child(sc);
  7353. environ_vb = memnew(VBoxContainer);
  7354. sun_environ_hb->add_child(environ_vb);
  7355. environ_vb->set_custom_minimum_size(Size2(200 * EDSCALE, 0));
  7356. environ_vb->hide();
  7357. environ_title = memnew(Label);
  7358. environ_title->set_theme_type_variation("HeaderSmall");
  7359. environ_vb->add_child(environ_title);
  7360. environ_title->set_text(TTR("Preview Environment"));
  7361. environ_title->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  7362. environ_sky_color = memnew(ColorPickerButton);
  7363. environ_sky_color->set_edit_alpha(false);
  7364. environ_sky_color->connect("color_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7365. environ_sky_color->get_popup()->connect("about_to_popup", callable_mp(EditorNode::get_singleton(), &EditorNode::setup_color_picker).bind(environ_sky_color->get_picker()));
  7366. environ_vb->add_margin_child(TTR("Sky Color"), environ_sky_color);
  7367. environ_ground_color = memnew(ColorPickerButton);
  7368. environ_ground_color->connect("color_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7369. environ_ground_color->set_edit_alpha(false);
  7370. environ_ground_color->get_popup()->connect("about_to_popup", callable_mp(EditorNode::get_singleton(), &EditorNode::setup_color_picker).bind(environ_ground_color->get_picker()));
  7371. environ_vb->add_margin_child(TTR("Ground Color"), environ_ground_color);
  7372. environ_energy = memnew(EditorSpinSlider);
  7373. environ_energy->set_max(8.0);
  7374. environ_energy->set_min(0);
  7375. environ_energy->set_step(0.05);
  7376. environ_energy->connect("value_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7377. environ_vb->add_margin_child(TTR("Sky Energy"), environ_energy);
  7378. HBoxContainer *fx_vb = memnew(HBoxContainer);
  7379. fx_vb->set_h_size_flags(SIZE_EXPAND_FILL);
  7380. environ_ao_button = memnew(Button);
  7381. environ_ao_button->set_text(TTR("AO"));
  7382. environ_ao_button->set_toggle_mode(true);
  7383. environ_ao_button->connect("pressed", callable_mp(this, &Node3DEditor::_preview_settings_changed), CONNECT_DEFERRED);
  7384. fx_vb->add_child(environ_ao_button);
  7385. environ_glow_button = memnew(Button);
  7386. environ_glow_button->set_text(TTR("Glow"));
  7387. environ_glow_button->set_toggle_mode(true);
  7388. environ_glow_button->connect("pressed", callable_mp(this, &Node3DEditor::_preview_settings_changed), CONNECT_DEFERRED);
  7389. fx_vb->add_child(environ_glow_button);
  7390. environ_tonemap_button = memnew(Button);
  7391. environ_tonemap_button->set_text(TTR("Tonemap"));
  7392. environ_tonemap_button->set_toggle_mode(true);
  7393. environ_tonemap_button->connect("pressed", callable_mp(this, &Node3DEditor::_preview_settings_changed), CONNECT_DEFERRED);
  7394. fx_vb->add_child(environ_tonemap_button);
  7395. environ_gi_button = memnew(Button);
  7396. environ_gi_button->set_text(TTR("GI"));
  7397. environ_gi_button->set_toggle_mode(true);
  7398. environ_gi_button->connect("pressed", callable_mp(this, &Node3DEditor::_preview_settings_changed), CONNECT_DEFERRED);
  7399. fx_vb->add_child(environ_gi_button);
  7400. environ_vb->add_margin_child(TTR("Post Process"), fx_vb);
  7401. environ_add_to_scene = memnew(Button);
  7402. environ_add_to_scene->set_text(TTR("Add Environment to Scene"));
  7403. environ_add_to_scene->set_tooltip_text(TTR("Adds a WorldEnvironment node matching the preview environment settings to the current scene.\nHold Shift while clicking to also add the preview sun to the current scene."));
  7404. environ_add_to_scene->connect("pressed", callable_mp(this, &Node3DEditor::_add_environment_to_scene).bind(false));
  7405. environ_vb->add_spacer();
  7406. environ_vb->add_child(environ_add_to_scene);
  7407. environ_state = memnew(Label);
  7408. sun_environ_hb->add_child(environ_state);
  7409. environ_state->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  7410. environ_state->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
  7411. environ_state->set_h_size_flags(SIZE_EXPAND_FILL);
  7412. preview_sun = memnew(DirectionalLight3D);
  7413. preview_sun->set_shadow(true);
  7414. preview_sun->set_shadow_mode(DirectionalLight3D::SHADOW_PARALLEL_4_SPLITS);
  7415. preview_environment = memnew(WorldEnvironment);
  7416. environment.instantiate();
  7417. preview_environment->set_environment(environment);
  7418. if (GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units")) {
  7419. camera_attributes.instantiate();
  7420. preview_environment->set_camera_attributes(camera_attributes);
  7421. }
  7422. Ref<Sky> sky;
  7423. sky.instantiate();
  7424. sky_material.instantiate();
  7425. sky->set_material(sky_material);
  7426. environment->set_sky(sky);
  7427. environment->set_background(Environment::BG_SKY);
  7428. _load_default_preview_settings();
  7429. _preview_settings_changed();
  7430. }
  7431. clear(); // Make sure values are initialized. Will call _snap_update() for us.
  7432. }
  7433. Node3DEditor::~Node3DEditor() {
  7434. memdelete(preview_node);
  7435. if (preview_sun_dangling && preview_sun) {
  7436. memdelete(preview_sun);
  7437. }
  7438. if (preview_env_dangling && preview_environment) {
  7439. memdelete(preview_environment);
  7440. }
  7441. }
  7442. void Node3DEditorPlugin::make_visible(bool p_visible) {
  7443. if (p_visible) {
  7444. spatial_editor->show();
  7445. spatial_editor->set_process(true);
  7446. spatial_editor->set_physics_process(true);
  7447. } else {
  7448. spatial_editor->hide();
  7449. spatial_editor->set_process(false);
  7450. spatial_editor->set_physics_process(false);
  7451. }
  7452. }
  7453. void Node3DEditorPlugin::edit(Object *p_object) {
  7454. spatial_editor->edit(Object::cast_to<Node3D>(p_object));
  7455. }
  7456. bool Node3DEditorPlugin::handles(Object *p_object) const {
  7457. return p_object->is_class("Node3D");
  7458. }
  7459. Dictionary Node3DEditorPlugin::get_state() const {
  7460. return spatial_editor->get_state();
  7461. }
  7462. void Node3DEditorPlugin::set_state(const Dictionary &p_state) {
  7463. spatial_editor->set_state(p_state);
  7464. }
  7465. Vector3 Node3DEditor::snap_point(Vector3 p_target, Vector3 p_start) const {
  7466. if (is_snap_enabled()) {
  7467. p_target.x = Math::snap_scalar(0.0, get_translate_snap(), p_target.x);
  7468. p_target.y = Math::snap_scalar(0.0, get_translate_snap(), p_target.y);
  7469. p_target.z = Math::snap_scalar(0.0, get_translate_snap(), p_target.z);
  7470. }
  7471. return p_target;
  7472. }
  7473. bool Node3DEditor::is_gizmo_visible() const {
  7474. if (selected) {
  7475. return gizmo.visible && selected->is_transform_gizmo_visible();
  7476. }
  7477. return gizmo.visible;
  7478. }
  7479. double Node3DEditor::get_translate_snap() const {
  7480. double snap_value;
  7481. if (Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
  7482. snap_value = snap_translate->get_text().to_float() / 10.0;
  7483. } else {
  7484. snap_value = snap_translate->get_text().to_float();
  7485. }
  7486. return snap_value;
  7487. }
  7488. double Node3DEditor::get_rotate_snap() const {
  7489. double snap_value;
  7490. if (Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
  7491. snap_value = snap_rotate->get_text().to_float() / 3.0;
  7492. } else {
  7493. snap_value = snap_rotate->get_text().to_float();
  7494. }
  7495. return snap_value;
  7496. }
  7497. double Node3DEditor::get_scale_snap() const {
  7498. double snap_value;
  7499. if (Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
  7500. snap_value = snap_scale->get_text().to_float() / 2.0;
  7501. } else {
  7502. snap_value = snap_scale->get_text().to_float();
  7503. }
  7504. return snap_value;
  7505. }
  7506. struct _GizmoPluginPriorityComparator {
  7507. bool operator()(const Ref<EditorNode3DGizmoPlugin> &p_a, const Ref<EditorNode3DGizmoPlugin> &p_b) const {
  7508. if (p_a->get_priority() == p_b->get_priority()) {
  7509. return p_a->get_gizmo_name() < p_b->get_gizmo_name();
  7510. }
  7511. return p_a->get_priority() > p_b->get_priority();
  7512. }
  7513. };
  7514. struct _GizmoPluginNameComparator {
  7515. bool operator()(const Ref<EditorNode3DGizmoPlugin> &p_a, const Ref<EditorNode3DGizmoPlugin> &p_b) const {
  7516. return p_a->get_gizmo_name() < p_b->get_gizmo_name();
  7517. }
  7518. };
  7519. void Node3DEditor::add_gizmo_plugin(Ref<EditorNode3DGizmoPlugin> p_plugin) {
  7520. ERR_FAIL_NULL(p_plugin.ptr());
  7521. gizmo_plugins_by_priority.push_back(p_plugin);
  7522. gizmo_plugins_by_priority.sort_custom<_GizmoPluginPriorityComparator>();
  7523. gizmo_plugins_by_name.push_back(p_plugin);
  7524. gizmo_plugins_by_name.sort_custom<_GizmoPluginNameComparator>();
  7525. _update_gizmos_menu();
  7526. }
  7527. void Node3DEditor::remove_gizmo_plugin(Ref<EditorNode3DGizmoPlugin> p_plugin) {
  7528. gizmo_plugins_by_priority.erase(p_plugin);
  7529. gizmo_plugins_by_name.erase(p_plugin);
  7530. _update_gizmos_menu();
  7531. }
  7532. Node3DEditorPlugin::Node3DEditorPlugin() {
  7533. spatial_editor = memnew(Node3DEditor);
  7534. spatial_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  7535. EditorNode::get_singleton()->get_main_screen_control()->add_child(spatial_editor);
  7536. spatial_editor->hide();
  7537. }
  7538. Node3DEditorPlugin::~Node3DEditorPlugin() {
  7539. }