node_3d_editor_plugin.cpp 332 KB

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