spatial_editor_plugin.cpp 264 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386
  1. /*************************************************************************/
  2. /* spatial_editor_plugin.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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 "spatial_editor_plugin.h"
  31. #include "core/math/camera_matrix.h"
  32. #include "core/os/input.h"
  33. #include "core/os/keyboard.h"
  34. #include "core/print_string.h"
  35. #include "core/project_settings.h"
  36. #include "core/sort_array.h"
  37. #include "editor/editor_node.h"
  38. #include "editor/editor_scale.h"
  39. #include "editor/editor_settings.h"
  40. #include "editor/plugins/animation_player_editor_plugin.h"
  41. #include "editor/plugins/script_editor_plugin.h"
  42. #include "editor/script_editor_debugger.h"
  43. #include "editor/spatial_editor_gizmos.h"
  44. #include "scene/3d/camera.h"
  45. #include "scene/3d/collision_shape.h"
  46. #include "scene/3d/mesh_instance.h"
  47. #include "scene/3d/physics_body.h"
  48. #include "scene/3d/room_manager.h"
  49. #include "scene/3d/visual_instance.h"
  50. #include "scene/gui/viewport_container.h"
  51. #include "scene/resources/packed_scene.h"
  52. #include "scene/resources/surface_tool.h"
  53. #define DISTANCE_DEFAULT 4
  54. #define GIZMO_ARROW_SIZE 0.35
  55. #define GIZMO_RING_HALF_WIDTH 0.1
  56. #define GIZMO_SCALE_DEFAULT 0.15
  57. #define GIZMO_PLANE_SIZE 0.2
  58. #define GIZMO_PLANE_DST 0.3
  59. #define GIZMO_CIRCLE_SIZE 1.1
  60. #define GIZMO_SCALE_OFFSET (GIZMO_CIRCLE_SIZE + 0.3)
  61. #define GIZMO_ARROW_OFFSET (GIZMO_CIRCLE_SIZE + 0.3)
  62. #define ZOOM_FREELOOK_MIN 0.01
  63. #define ZOOM_FREELOOK_MULTIPLIER 1.08
  64. #define ZOOM_FREELOOK_INDICATOR_DELAY_S 1.5
  65. #define ZOOM_FREELOOK_MAX 10'000
  66. #define MIN_Z 0.01
  67. #define MAX_Z 1000000.0
  68. #define MIN_FOV 0.01
  69. #define MAX_FOV 179
  70. void ViewportRotationControl::_notification(int p_what) {
  71. if (p_what == NOTIFICATION_ENTER_TREE) {
  72. axis_menu_options.clear();
  73. axis_menu_options.push_back(SpatialEditorViewport::VIEW_RIGHT);
  74. axis_menu_options.push_back(SpatialEditorViewport::VIEW_TOP);
  75. axis_menu_options.push_back(SpatialEditorViewport::VIEW_REAR);
  76. axis_menu_options.push_back(SpatialEditorViewport::VIEW_LEFT);
  77. axis_menu_options.push_back(SpatialEditorViewport::VIEW_BOTTOM);
  78. axis_menu_options.push_back(SpatialEditorViewport::VIEW_FRONT);
  79. axis_colors.clear();
  80. axis_colors.push_back(get_color("axis_x_color", "Editor"));
  81. axis_colors.push_back(get_color("axis_y_color", "Editor"));
  82. axis_colors.push_back(get_color("axis_z_color", "Editor"));
  83. update();
  84. if (!is_connected("mouse_exited", this, "_on_mouse_exited")) {
  85. connect("mouse_exited", this, "_on_mouse_exited");
  86. }
  87. }
  88. if (p_what == NOTIFICATION_DRAW && viewport != nullptr) {
  89. _draw();
  90. }
  91. }
  92. void ViewportRotationControl::_draw() {
  93. Vector2i center = get_size() / 2.0;
  94. float radius = get_size().x / 2.0;
  95. if (focused_axis > -2 || orbiting) {
  96. draw_circle(center, radius, Color(0.5, 0.5, 0.5, 0.25));
  97. }
  98. Vector<Axis2D> axis_to_draw;
  99. _get_sorted_axis(axis_to_draw);
  100. for (int i = 0; i < axis_to_draw.size(); ++i) {
  101. _draw_axis(axis_to_draw[i]);
  102. }
  103. }
  104. void ViewportRotationControl::_draw_axis(const Axis2D &p_axis) {
  105. const bool focused = focused_axis == p_axis.axis;
  106. const bool positive = p_axis.axis < 3;
  107. const int direction = p_axis.axis % 3;
  108. const Color axis_color = axis_colors[direction];
  109. const double alpha = focused ? 1.0 : ((p_axis.z_axis + 1.0) / 2.0) * 0.5 + 0.5;
  110. const Color c = focused ? Color(0.9, 0.9, 0.9) : Color(axis_color.r, axis_color.g, axis_color.b, alpha);
  111. if (positive) {
  112. // Draw axis lines for the positive axes.
  113. const Vector2i center = get_size() / 2.0;
  114. draw_line(center, p_axis.screen_point, c, 1.5 * EDSCALE, true);
  115. draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS, c);
  116. // Draw the axis letter for the positive axes.
  117. const String axis_name = direction == 0 ? "X" : (direction == 1 ? "Y" : "Z");
  118. draw_char(get_font("rotation_control", "EditorFonts"), p_axis.screen_point + Vector2(-4.0, 5.0) * EDSCALE, axis_name, "", Color(0.0, 0.0, 0.0, alpha));
  119. } else {
  120. // Draw an outline around the negative axes.
  121. draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS, c);
  122. draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS * 0.8, c.darkened(0.4));
  123. }
  124. }
  125. void ViewportRotationControl::_get_sorted_axis(Vector<Axis2D> &r_axis) {
  126. Vector2i center = get_size() / 2.0;
  127. float radius = get_size().x / 2.0;
  128. float axis_radius = radius - AXIS_CIRCLE_RADIUS - 2.0 * EDSCALE;
  129. Basis camera_basis = viewport->to_camera_transform(viewport->cursor).get_basis().inverse();
  130. for (int i = 0; i < 3; ++i) {
  131. Vector3 axis_3d = camera_basis.get_axis(i);
  132. Vector2i axis_vector = Vector2(axis_3d.x, -axis_3d.y) * axis_radius;
  133. if (Math::abs(axis_3d.z) < 1.0) {
  134. Axis2D pos_axis;
  135. pos_axis.axis = i;
  136. pos_axis.screen_point = center + axis_vector;
  137. pos_axis.z_axis = axis_3d.z;
  138. r_axis.push_back(pos_axis);
  139. Axis2D neg_axis;
  140. neg_axis.axis = i + 3;
  141. neg_axis.screen_point = center - axis_vector;
  142. neg_axis.z_axis = -axis_3d.z;
  143. r_axis.push_back(neg_axis);
  144. } else {
  145. // Special case when the camera is aligned with one axis
  146. Axis2D axis;
  147. axis.axis = i + (axis_3d.z < 0 ? 0 : 3);
  148. axis.screen_point = center;
  149. axis.z_axis = 1.0;
  150. r_axis.push_back(axis);
  151. }
  152. }
  153. r_axis.sort_custom<Axis2DCompare>();
  154. }
  155. void ViewportRotationControl::_gui_input(Ref<InputEvent> p_event) {
  156. const Ref<InputEventMouseButton> mb = p_event;
  157. if (mb.is_valid() && mb->get_button_index() == BUTTON_LEFT) {
  158. Vector2 pos = mb->get_position();
  159. if (mb->is_pressed()) {
  160. if (pos.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
  161. orbiting = true;
  162. }
  163. } else {
  164. if (focused_axis > -1) {
  165. viewport->_menu_option(axis_menu_options[focused_axis]);
  166. _update_focus();
  167. }
  168. orbiting = false;
  169. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
  170. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  171. Input::get_singleton()->warp_mouse_position(orbiting_mouse_start);
  172. }
  173. }
  174. }
  175. const Ref<InputEventMouseMotion> mm = p_event;
  176. if (mm.is_valid()) {
  177. if (orbiting) {
  178. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_VISIBLE) {
  179. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
  180. orbiting_mouse_start = mm->get_global_position();
  181. }
  182. viewport->_nav_orbit(mm, viewport->_get_warped_mouse_motion(mm));
  183. focused_axis = -1;
  184. } else {
  185. _update_focus();
  186. }
  187. }
  188. }
  189. void ViewportRotationControl::_update_focus() {
  190. int original_focus = focused_axis;
  191. focused_axis = -2;
  192. Vector2 mouse_pos = get_local_mouse_position();
  193. if (mouse_pos.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
  194. focused_axis = -1;
  195. }
  196. Vector<Axis2D> axes;
  197. _get_sorted_axis(axes);
  198. for (int i = 0; i < axes.size(); i++) {
  199. const Axis2D &axis = axes[i];
  200. if (mouse_pos.distance_to(axis.screen_point) < AXIS_CIRCLE_RADIUS) {
  201. focused_axis = axis.axis;
  202. }
  203. }
  204. if (focused_axis != original_focus) {
  205. update();
  206. }
  207. }
  208. void ViewportRotationControl::_on_mouse_exited() {
  209. focused_axis = -2;
  210. update();
  211. }
  212. void ViewportRotationControl::set_viewport(SpatialEditorViewport *p_viewport) {
  213. viewport = p_viewport;
  214. }
  215. void ViewportRotationControl::_bind_methods() {
  216. ClassDB::bind_method(D_METHOD("_gui_input"), &ViewportRotationControl::_gui_input);
  217. ClassDB::bind_method(D_METHOD("_on_mouse_exited"), &ViewportRotationControl::_on_mouse_exited);
  218. }
  219. void SpatialEditorViewport::_view_settings_confirmed(real_t p_interp_delta) {
  220. // Set FOV override multiplier back to the default, so that the FOV
  221. // setting specified in the View menu is correctly applied.
  222. cursor.fov_scale = 1.0;
  223. _update_camera(p_interp_delta);
  224. }
  225. void SpatialEditorViewport::_update_camera(float p_interp_delta) {
  226. bool is_orthogonal = camera->get_projection() == Camera::PROJECTION_ORTHOGONAL;
  227. Cursor old_camera_cursor = camera_cursor;
  228. camera_cursor = cursor;
  229. if (p_interp_delta > 0) {
  230. //-------
  231. // Perform smoothing
  232. if (is_freelook_active()) {
  233. // Higher inertia should increase "lag" (lerp with factor between 0 and 1)
  234. // 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.
  235. const real_t inertia = EDITOR_GET("editors/3d/freelook/freelook_inertia");
  236. real_t factor = (1.0 / inertia) * p_interp_delta;
  237. // We interpolate a different point here, because in freelook mode the focus point (cursor.pos) orbits around eye_pos
  238. camera_cursor.eye_pos = old_camera_cursor.eye_pos.linear_interpolate(cursor.eye_pos, CLAMP(factor, 0, 1));
  239. const float orbit_inertia = EDITOR_GET("editors/3d/navigation_feel/orbit_inertia");
  240. camera_cursor.x_rot = Math::lerp(old_camera_cursor.x_rot, cursor.x_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  241. camera_cursor.y_rot = Math::lerp(old_camera_cursor.y_rot, cursor.y_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  242. if (Math::abs(camera_cursor.x_rot - cursor.x_rot) < 0.1) {
  243. camera_cursor.x_rot = cursor.x_rot;
  244. }
  245. if (Math::abs(camera_cursor.y_rot - cursor.y_rot) < 0.1) {
  246. camera_cursor.y_rot = cursor.y_rot;
  247. }
  248. Vector3 forward = to_camera_transform(camera_cursor).basis.xform(Vector3(0, 0, -1));
  249. camera_cursor.pos = camera_cursor.eye_pos + forward * camera_cursor.distance;
  250. } else {
  251. const float orbit_inertia = EDITOR_GET("editors/3d/navigation_feel/orbit_inertia");
  252. const float translation_inertia = EDITOR_GET("editors/3d/navigation_feel/translation_inertia");
  253. const float zoom_inertia = EDITOR_GET("editors/3d/navigation_feel/zoom_inertia");
  254. camera_cursor.x_rot = Math::lerp(old_camera_cursor.x_rot, cursor.x_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  255. camera_cursor.y_rot = Math::lerp(old_camera_cursor.y_rot, cursor.y_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  256. if (Math::abs(camera_cursor.x_rot - cursor.x_rot) < 0.1) {
  257. camera_cursor.x_rot = cursor.x_rot;
  258. }
  259. if (Math::abs(camera_cursor.y_rot - cursor.y_rot) < 0.1) {
  260. camera_cursor.y_rot = cursor.y_rot;
  261. }
  262. camera_cursor.pos = old_camera_cursor.pos.linear_interpolate(cursor.pos, MIN(1.f, p_interp_delta * (1 / translation_inertia)));
  263. camera_cursor.distance = Math::lerp(old_camera_cursor.distance, cursor.distance, MIN(1.f, p_interp_delta * (1 / zoom_inertia)));
  264. }
  265. }
  266. //-------
  267. // Apply camera transform
  268. real_t tolerance = 0.001;
  269. bool equal = true;
  270. 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)) {
  271. equal = false;
  272. } else if (!old_camera_cursor.pos.is_equal_approx(camera_cursor.pos)) {
  273. equal = false;
  274. } else if (!Math::is_equal_approx(old_camera_cursor.distance, camera_cursor.distance, tolerance)) {
  275. equal = false;
  276. } else if (!Math::is_equal_approx(old_camera_cursor.fov_scale, camera_cursor.fov_scale, tolerance)) {
  277. equal = false;
  278. }
  279. if (!equal || p_interp_delta == 0 || is_orthogonal != orthogonal) {
  280. camera->set_global_transform(to_camera_transform(camera_cursor));
  281. if (orthogonal) {
  282. float half_fov = Math::deg2rad(get_fov()) / 2.0;
  283. float height = 2.0 * cursor.distance * Math::tan(half_fov);
  284. camera->set_orthogonal(height, get_znear(), get_zfar());
  285. } else {
  286. camera->set_perspective(get_fov(), get_znear(), get_zfar());
  287. }
  288. update_transform_gizmo_view();
  289. rotation_control->update();
  290. spatial_editor->update_grid();
  291. }
  292. }
  293. Transform SpatialEditorViewport::to_camera_transform(const Cursor &p_cursor) const {
  294. Transform camera_transform;
  295. camera_transform.translate(p_cursor.pos);
  296. camera_transform.basis.rotate(Vector3(1, 0, 0), -p_cursor.x_rot);
  297. camera_transform.basis.rotate(Vector3(0, 1, 0), -p_cursor.y_rot);
  298. if (orthogonal) {
  299. camera_transform.translate(0, 0, (get_zfar() - get_znear()) / 2.0);
  300. } else {
  301. camera_transform.translate(0, 0, p_cursor.distance);
  302. }
  303. return camera_transform;
  304. }
  305. int SpatialEditorViewport::get_selected_count() const {
  306. Map<Node *, Object *> &selection = editor_selection->get_selection();
  307. int count = 0;
  308. for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
  309. Spatial *sp = Object::cast_to<Spatial>(E->key());
  310. if (!sp) {
  311. continue;
  312. }
  313. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  314. if (!se) {
  315. continue;
  316. }
  317. count++;
  318. }
  319. return count;
  320. }
  321. float SpatialEditorViewport::get_znear() const {
  322. return CLAMP(spatial_editor->get_znear(), MIN_Z, MAX_Z);
  323. }
  324. float SpatialEditorViewport::get_zfar() const {
  325. return CLAMP(spatial_editor->get_zfar(), MIN_Z, MAX_Z);
  326. }
  327. float SpatialEditorViewport::get_fov() const {
  328. return CLAMP(spatial_editor->get_fov() * cursor.fov_scale, MIN_FOV, MAX_FOV);
  329. }
  330. Transform SpatialEditorViewport::_get_camera_transform() const {
  331. return camera->get_global_transform();
  332. }
  333. Vector3 SpatialEditorViewport::_get_camera_position() const {
  334. return _get_camera_transform().origin;
  335. }
  336. Point2 SpatialEditorViewport::_point_to_screen(const Vector3 &p_point) {
  337. return camera->unproject_position(p_point) * viewport_container->get_stretch_shrink();
  338. }
  339. Vector3 SpatialEditorViewport::_get_ray_pos(const Vector2 &p_pos) const {
  340. return camera->project_ray_origin(p_pos / viewport_container->get_stretch_shrink());
  341. }
  342. Vector3 SpatialEditorViewport::_get_camera_normal() const {
  343. return -_get_camera_transform().basis.get_axis(2);
  344. }
  345. Vector3 SpatialEditorViewport::_get_ray(const Vector2 &p_pos) const {
  346. return camera->project_ray_normal(p_pos / viewport_container->get_stretch_shrink());
  347. }
  348. void SpatialEditorViewport::_clear_selected() {
  349. editor_selection->clear();
  350. }
  351. void SpatialEditorViewport::_select_clicked(bool p_append, bool p_single, bool p_allow_locked) {
  352. if (!clicked) {
  353. return;
  354. }
  355. Node *node = Object::cast_to<Node>(ObjectDB::get_instance(clicked));
  356. Spatial *selected = Object::cast_to<Spatial>(node);
  357. if (!selected) {
  358. return;
  359. }
  360. if (!p_allow_locked) {
  361. // Replace the node by the group if grouped.
  362. while (node && node != editor->get_edited_scene()->get_parent()) {
  363. Spatial *selected_tmp = Object::cast_to<Spatial>(node);
  364. if (selected_tmp && node->has_meta("_edit_group_")) {
  365. selected = selected_tmp;
  366. }
  367. node = node->get_parent();
  368. }
  369. }
  370. if (p_allow_locked || !_is_node_locked(selected)) {
  371. _select(selected, clicked_wants_append, true);
  372. }
  373. }
  374. void SpatialEditorViewport::_select(Node *p_node, bool p_append, bool p_single) {
  375. if (!p_append) {
  376. editor_selection->clear();
  377. }
  378. if (editor_selection->is_selected(p_node)) {
  379. //erase
  380. editor_selection->remove_node(p_node);
  381. } else {
  382. editor_selection->add_node(p_node);
  383. }
  384. if (p_single) {
  385. if (Engine::get_singleton()->is_editor_hint()) {
  386. editor->call("edit_node", p_node);
  387. }
  388. }
  389. }
  390. ObjectID SpatialEditorViewport::_select_ray(const Point2 &p_pos, bool p_append, bool &r_includes_current, int *r_gizmo_handle, bool p_alt_select) {
  391. if (r_gizmo_handle) {
  392. *r_gizmo_handle = -1;
  393. }
  394. Vector3 ray = _get_ray(p_pos);
  395. Vector3 pos = _get_ray_pos(p_pos);
  396. Vector2 shrinked_pos = p_pos / viewport_container->get_stretch_shrink();
  397. Vector<ObjectID> instances = VisualServer::get_singleton()->instances_cull_ray(pos, ray, get_tree()->get_root()->get_world()->get_scenario());
  398. Set<Ref<EditorSpatialGizmo>> found_gizmos;
  399. Node *edited_scene = get_tree()->get_edited_scene_root();
  400. ObjectID closest = 0;
  401. Node *item = nullptr;
  402. float closest_dist = 1e20;
  403. int selected_handle = -1;
  404. for (int i = 0; i < instances.size(); i++) {
  405. Spatial *spat = Object::cast_to<Spatial>(ObjectDB::get_instance(instances[i]));
  406. if (!spat) {
  407. continue;
  408. }
  409. Ref<EditorSpatialGizmo> seg = spat->get_gizmo();
  410. if ((!seg.is_valid()) || found_gizmos.has(seg)) {
  411. continue;
  412. }
  413. found_gizmos.insert(seg);
  414. Vector3 point;
  415. Vector3 normal;
  416. int handle = -1;
  417. bool inters = seg->intersect_ray(camera, shrinked_pos, point, normal, &handle, p_alt_select);
  418. if (!inters) {
  419. continue;
  420. }
  421. float dist = pos.distance_to(point);
  422. if (dist < 0) {
  423. continue;
  424. }
  425. if (dist < closest_dist) {
  426. item = Object::cast_to<Node>(spat);
  427. if (item != edited_scene) {
  428. item = edited_scene->get_deepest_editable_node(item);
  429. }
  430. closest = item->get_instance_id();
  431. closest_dist = dist;
  432. selected_handle = handle;
  433. }
  434. }
  435. if (!item) {
  436. return 0;
  437. }
  438. if (!editor_selection->is_selected(item) || (r_gizmo_handle && selected_handle >= 0)) {
  439. if (r_gizmo_handle) {
  440. *r_gizmo_handle = selected_handle;
  441. }
  442. }
  443. return closest;
  444. }
  445. void SpatialEditorViewport::_find_items_at_pos(const Point2 &p_pos, bool &r_includes_current, Vector<_RayResult> &results, bool p_alt_select) {
  446. Vector3 ray = _get_ray(p_pos);
  447. Vector3 pos = _get_ray_pos(p_pos);
  448. Vector<ObjectID> instances = VisualServer::get_singleton()->instances_cull_ray(pos, ray, get_tree()->get_root()->get_world()->get_scenario());
  449. Set<Ref<EditorSpatialGizmo>> found_gizmos;
  450. r_includes_current = false;
  451. for (int i = 0; i < instances.size(); i++) {
  452. Spatial *spat = Object::cast_to<Spatial>(ObjectDB::get_instance(instances[i]));
  453. if (!spat) {
  454. continue;
  455. }
  456. Ref<EditorSpatialGizmo> seg = spat->get_gizmo();
  457. if (!seg.is_valid()) {
  458. continue;
  459. }
  460. if (found_gizmos.has(seg)) {
  461. continue;
  462. }
  463. found_gizmos.insert(seg);
  464. Vector3 point;
  465. Vector3 normal;
  466. int handle = -1;
  467. bool inters = seg->intersect_ray(camera, p_pos, point, normal, nullptr, p_alt_select);
  468. if (!inters) {
  469. continue;
  470. }
  471. float dist = pos.distance_to(point);
  472. if (dist < 0) {
  473. continue;
  474. }
  475. if (editor_selection->is_selected(spat)) {
  476. r_includes_current = true;
  477. }
  478. _RayResult res;
  479. res.item = spat;
  480. res.depth = dist;
  481. res.handle = handle;
  482. results.push_back(res);
  483. }
  484. if (results.empty()) {
  485. return;
  486. }
  487. results.sort();
  488. }
  489. Vector3 SpatialEditorViewport::_get_screen_to_space(const Vector3 &p_vector3) {
  490. CameraMatrix cm;
  491. if (orthogonal) {
  492. cm.set_orthogonal(camera->get_size(), get_size().aspect(), get_znear() + p_vector3.z, get_zfar());
  493. } else {
  494. cm.set_perspective(get_fov(), get_size().aspect(), get_znear() + p_vector3.z, get_zfar());
  495. }
  496. Vector2 screen_he = cm.get_viewport_half_extents();
  497. Transform camera_transform;
  498. camera_transform.translate(cursor.pos);
  499. camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
  500. camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
  501. camera_transform.translate(0, 0, cursor.distance);
  502. 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)));
  503. }
  504. void SpatialEditorViewport::_select_region() {
  505. if (cursor.region_begin == cursor.region_end) {
  506. return; //nothing really
  507. }
  508. float z_offset = MAX(0.0, 5.0 - get_znear());
  509. Vector3 box[4] = {
  510. Vector3(
  511. MIN(cursor.region_begin.x, cursor.region_end.x),
  512. MIN(cursor.region_begin.y, cursor.region_end.y),
  513. z_offset),
  514. Vector3(
  515. MAX(cursor.region_begin.x, cursor.region_end.x),
  516. MIN(cursor.region_begin.y, cursor.region_end.y),
  517. z_offset),
  518. Vector3(
  519. MAX(cursor.region_begin.x, cursor.region_end.x),
  520. MAX(cursor.region_begin.y, cursor.region_end.y),
  521. z_offset),
  522. Vector3(
  523. MIN(cursor.region_begin.x, cursor.region_end.x),
  524. MAX(cursor.region_begin.y, cursor.region_end.y),
  525. z_offset)
  526. };
  527. Vector<Plane> frustum;
  528. Vector3 cam_pos = _get_camera_position();
  529. for (int i = 0; i < 4; i++) {
  530. Vector3 a = _get_screen_to_space(box[i]);
  531. Vector3 b = _get_screen_to_space(box[(i + 1) % 4]);
  532. if (orthogonal) {
  533. frustum.push_back(Plane(a, (a - b).normalized()));
  534. } else {
  535. frustum.push_back(Plane(a, b, cam_pos));
  536. }
  537. }
  538. Plane near(cam_pos, -_get_camera_normal());
  539. near.d -= get_znear();
  540. frustum.push_back(near);
  541. Plane far = -near;
  542. far.d += get_zfar();
  543. frustum.push_back(far);
  544. Vector<ObjectID> instances = VisualServer::get_singleton()->instances_cull_convex(frustum, get_tree()->get_root()->get_world()->get_scenario());
  545. Vector<Node *> selected;
  546. Node *edited_scene = get_tree()->get_edited_scene_root();
  547. for (int i = 0; i < instances.size(); i++) {
  548. Spatial *sp = Object::cast_to<Spatial>(ObjectDB::get_instance(instances[i]));
  549. if (!sp || _is_node_locked(sp)) {
  550. continue;
  551. }
  552. Node *item = Object::cast_to<Node>(sp);
  553. if (item != edited_scene) {
  554. item = edited_scene->get_deepest_editable_node(item);
  555. }
  556. // Replace the node by the group if grouped
  557. if (item->is_class("Spatial")) {
  558. Spatial *sel = Object::cast_to<Spatial>(item);
  559. while (item && item != editor->get_edited_scene()->get_parent()) {
  560. Spatial *selected_tmp = Object::cast_to<Spatial>(item);
  561. if (selected_tmp && item->has_meta("_edit_group_")) {
  562. sel = selected_tmp;
  563. }
  564. item = item->get_parent();
  565. }
  566. item = sel;
  567. }
  568. if (selected.find(item) != -1) {
  569. continue;
  570. }
  571. if (_is_node_locked(item)) {
  572. continue;
  573. }
  574. Ref<EditorSpatialGizmo> seg = sp->get_gizmo();
  575. if (!seg.is_valid()) {
  576. continue;
  577. }
  578. if (seg->intersect_frustum(camera, frustum)) {
  579. selected.push_back(item);
  580. }
  581. }
  582. bool single = selected.size() == 1;
  583. for (int i = 0; i < selected.size(); i++) {
  584. _select(selected[i], true, single);
  585. }
  586. }
  587. void SpatialEditorViewport::_update_name() {
  588. String name;
  589. switch (view_type) {
  590. case VIEW_TYPE_USER: {
  591. if (orthogonal) {
  592. name = TTR("Orthogonal");
  593. } else {
  594. name = TTR("Perspective");
  595. }
  596. } break;
  597. case VIEW_TYPE_TOP: {
  598. if (orthogonal) {
  599. name = TTR("Top Orthogonal");
  600. } else {
  601. name = TTR("Top Perspective");
  602. }
  603. } break;
  604. case VIEW_TYPE_BOTTOM: {
  605. if (orthogonal) {
  606. name = TTR("Bottom Orthogonal");
  607. } else {
  608. name = TTR("Bottom Perspective");
  609. }
  610. } break;
  611. case VIEW_TYPE_LEFT: {
  612. if (orthogonal) {
  613. name = TTR("Left Orthogonal");
  614. } else {
  615. name = TTR("Left Perspective");
  616. }
  617. } break;
  618. case VIEW_TYPE_RIGHT: {
  619. if (orthogonal) {
  620. name = TTR("Right Orthogonal");
  621. } else {
  622. name = TTR("Right Perspective");
  623. }
  624. } break;
  625. case VIEW_TYPE_FRONT: {
  626. if (orthogonal) {
  627. name = TTR("Front Orthogonal");
  628. } else {
  629. name = TTR("Front Perspective");
  630. }
  631. } break;
  632. case VIEW_TYPE_REAR: {
  633. if (orthogonal) {
  634. name = TTR("Rear Orthogonal");
  635. } else {
  636. name = TTR("Rear Perspective");
  637. }
  638. } break;
  639. }
  640. if (auto_orthogonal) {
  641. // TRANSLATORS: This will be appended to the view name when Auto Orthogonal is enabled.
  642. name += TTR(" [auto]");
  643. }
  644. if (RoomManager::static_rooms_get_active_and_loaded()) {
  645. // TRANSLATORS: This will be appended to the view name when Portal Occulusion is enabled.
  646. name += TTR(" [portals active]");
  647. }
  648. view_menu->set_text(name);
  649. view_menu->set_size(Vector2(0, 0)); // resets the button size
  650. }
  651. void SpatialEditorViewport::_compute_edit(const Point2 &p_point) {
  652. _edit.click_ray = _get_ray(Vector2(p_point.x, p_point.y));
  653. _edit.click_ray_pos = _get_ray_pos(Vector2(p_point.x, p_point.y));
  654. _edit.plane = TRANSFORM_VIEW;
  655. spatial_editor->update_transform_gizmo();
  656. _edit.center = spatial_editor->get_gizmo_transform().origin;
  657. List<Node *> &selection = editor_selection->get_selected_node_list();
  658. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  659. Spatial *sp = Object::cast_to<Spatial>(E->get());
  660. if (!sp) {
  661. continue;
  662. }
  663. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  664. if (!se) {
  665. continue;
  666. }
  667. se->original = se->sp->get_global_gizmo_transform();
  668. se->original_local = se->sp->get_local_gizmo_transform();
  669. }
  670. }
  671. static int _get_key_modifier_setting(const String &p_property) {
  672. switch (EditorSettings::get_singleton()->get(p_property).operator int()) {
  673. case 0:
  674. return 0;
  675. case 1:
  676. return KEY_SHIFT;
  677. case 2:
  678. return KEY_ALT;
  679. case 3:
  680. return KEY_META;
  681. case 4:
  682. return KEY_CONTROL;
  683. }
  684. return 0;
  685. }
  686. static int _get_key_modifier(Ref<InputEventWithModifiers> e) {
  687. if (e->get_shift()) {
  688. return KEY_SHIFT;
  689. }
  690. if (e->get_alt()) {
  691. return KEY_ALT;
  692. }
  693. if (e->get_control()) {
  694. return KEY_CONTROL;
  695. }
  696. if (e->get_metakey()) {
  697. return KEY_META;
  698. }
  699. return 0;
  700. }
  701. bool SpatialEditorViewport::_gizmo_select(const Vector2 &p_screenpos, bool p_highlight_only) {
  702. if (!spatial_editor->is_gizmo_visible()) {
  703. return false;
  704. }
  705. if (get_selected_count() == 0) {
  706. if (p_highlight_only) {
  707. spatial_editor->select_gizmo_highlight_axis(-1);
  708. }
  709. return false;
  710. }
  711. Vector3 ray_pos = _get_ray_pos(Vector2(p_screenpos.x, p_screenpos.y));
  712. Vector3 ray = _get_ray(Vector2(p_screenpos.x, p_screenpos.y));
  713. Transform gt = spatial_editor->get_gizmo_transform();
  714. float gs = gizmo_scale;
  715. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_MOVE) {
  716. int col_axis = -1;
  717. float col_d = 1e20;
  718. for (int i = 0; i < 3; i++) {
  719. Vector3 grabber_pos = gt.origin + gt.basis.get_axis(i) * gs * (GIZMO_ARROW_OFFSET + (GIZMO_ARROW_SIZE * 0.5));
  720. float grabber_radius = gs * GIZMO_ARROW_SIZE;
  721. Vector3 r;
  722. if (Geometry::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) {
  723. float d = r.distance_to(ray_pos);
  724. if (d < col_d) {
  725. col_d = d;
  726. col_axis = i;
  727. }
  728. }
  729. }
  730. bool is_plane_translate = false;
  731. // plane select
  732. if (col_axis == -1) {
  733. col_d = 1e20;
  734. for (int i = 0; i < 3; i++) {
  735. Vector3 ivec2 = gt.basis.get_axis((i + 1) % 3).normalized();
  736. Vector3 ivec3 = gt.basis.get_axis((i + 2) % 3).normalized();
  737. // Allow some tolerance to make the plane easier to click,
  738. // even if the click is actually slightly outside the plane.
  739. const Vector3 grabber_pos = gt.origin + (ivec2 + ivec3) * gs * (GIZMO_PLANE_SIZE + GIZMO_PLANE_DST * 0.6667);
  740. Vector3 r;
  741. Plane plane(gt.origin, gt.basis.get_axis(i).normalized());
  742. if (plane.intersects_ray(ray_pos, ray, &r)) {
  743. float dist = r.distance_to(grabber_pos);
  744. // Allow some tolerance to make the plane easier to click,
  745. // even if the click is actually slightly outside the plane.
  746. if (dist < (gs * GIZMO_PLANE_SIZE * 1.5)) {
  747. float d = ray_pos.distance_to(r);
  748. if (d < col_d) {
  749. col_d = d;
  750. col_axis = i;
  751. is_plane_translate = true;
  752. }
  753. }
  754. }
  755. }
  756. }
  757. if (col_axis != -1) {
  758. if (p_highlight_only) {
  759. spatial_editor->select_gizmo_highlight_axis(col_axis + (is_plane_translate ? 6 : 0));
  760. } else {
  761. //handle plane translate
  762. _edit.mode = TRANSFORM_TRANSLATE;
  763. _compute_edit(Point2(p_screenpos.x, p_screenpos.y));
  764. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis + (is_plane_translate ? 3 : 0));
  765. }
  766. return true;
  767. }
  768. }
  769. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_ROTATE) {
  770. int col_axis = -1;
  771. float col_d = 1e20;
  772. for (int i = 0; i < 3; i++) {
  773. Plane plane(gt.origin, gt.basis.get_axis(i).normalized());
  774. Vector3 r;
  775. if (!plane.intersects_ray(ray_pos, ray, &r)) {
  776. continue;
  777. }
  778. float dist = r.distance_to(gt.origin);
  779. Vector3 r_dir = (r - gt.origin).normalized();
  780. if (_get_camera_normal().dot(r_dir) <= 0.005) {
  781. if (dist > gs * (GIZMO_CIRCLE_SIZE - GIZMO_RING_HALF_WIDTH) && dist < gs * (GIZMO_CIRCLE_SIZE + GIZMO_RING_HALF_WIDTH)) {
  782. float d = ray_pos.distance_to(r);
  783. if (d < col_d) {
  784. col_d = d;
  785. col_axis = i;
  786. }
  787. }
  788. }
  789. }
  790. if (col_axis != -1) {
  791. if (p_highlight_only) {
  792. spatial_editor->select_gizmo_highlight_axis(col_axis + 3);
  793. } else {
  794. //handle rotate
  795. _edit.mode = TRANSFORM_ROTATE;
  796. _compute_edit(Point2(p_screenpos.x, p_screenpos.y));
  797. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis);
  798. }
  799. return true;
  800. }
  801. }
  802. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SCALE) {
  803. int col_axis = -1;
  804. float col_d = 1e20;
  805. for (int i = 0; i < 3; i++) {
  806. Vector3 grabber_pos = gt.origin + gt.basis.get_axis(i) * gs * GIZMO_SCALE_OFFSET;
  807. float grabber_radius = gs * GIZMO_ARROW_SIZE;
  808. Vector3 r;
  809. if (Geometry::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) {
  810. float d = r.distance_to(ray_pos);
  811. if (d < col_d) {
  812. col_d = d;
  813. col_axis = i;
  814. }
  815. }
  816. }
  817. bool is_plane_scale = false;
  818. // plane select
  819. if (col_axis == -1) {
  820. col_d = 1e20;
  821. for (int i = 0; i < 3; i++) {
  822. Vector3 ivec2 = gt.basis.get_axis((i + 1) % 3).normalized();
  823. Vector3 ivec3 = gt.basis.get_axis((i + 2) % 3).normalized();
  824. // Allow some tolerance to make the plane easier to click,
  825. // even if the click is actually slightly outside the plane.
  826. Vector3 grabber_pos = gt.origin + (ivec2 + ivec3) * gs * (GIZMO_PLANE_SIZE + GIZMO_PLANE_DST * 0.6667);
  827. Vector3 r;
  828. Plane plane(gt.origin, gt.basis.get_axis(i).normalized());
  829. if (plane.intersects_ray(ray_pos, ray, &r)) {
  830. float dist = r.distance_to(grabber_pos);
  831. // Allow some tolerance to make the plane easier to click,
  832. // even if the click is actually slightly outside the plane.
  833. if (dist < (gs * GIZMO_PLANE_SIZE * 1.5)) {
  834. float d = ray_pos.distance_to(r);
  835. if (d < col_d) {
  836. col_d = d;
  837. col_axis = i;
  838. is_plane_scale = true;
  839. }
  840. }
  841. }
  842. }
  843. }
  844. if (col_axis != -1) {
  845. if (p_highlight_only) {
  846. spatial_editor->select_gizmo_highlight_axis(col_axis + (is_plane_scale ? 12 : 9));
  847. } else {
  848. //handle scale
  849. _edit.mode = TRANSFORM_SCALE;
  850. _compute_edit(Point2(p_screenpos.x, p_screenpos.y));
  851. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis + (is_plane_scale ? 3 : 0));
  852. }
  853. return true;
  854. }
  855. }
  856. if (p_highlight_only) {
  857. spatial_editor->select_gizmo_highlight_axis(-1);
  858. }
  859. return false;
  860. }
  861. void SpatialEditorViewport::_surface_mouse_enter() {
  862. if (!surface->has_focus() && (!get_focus_owner() || !get_focus_owner()->is_text_field())) {
  863. surface->grab_focus();
  864. }
  865. }
  866. void SpatialEditorViewport::_surface_mouse_exit() {
  867. _remove_preview();
  868. }
  869. void SpatialEditorViewport::_surface_focus_enter() {
  870. view_menu->set_disable_shortcuts(false);
  871. }
  872. void SpatialEditorViewport::_surface_focus_exit() {
  873. view_menu->set_disable_shortcuts(true);
  874. }
  875. bool SpatialEditorViewport ::_is_node_locked(const Node *p_node) {
  876. return p_node->has_meta("_edit_lock_") && p_node->get_meta("_edit_lock_");
  877. }
  878. void SpatialEditorViewport::_list_select(Ref<InputEventMouseButton> b) {
  879. _find_items_at_pos(b->get_position(), clicked_includes_current, selection_results, b->get_shift());
  880. Node *scene = editor->get_edited_scene();
  881. for (int i = 0; i < selection_results.size(); i++) {
  882. Spatial *item = selection_results[i].item;
  883. if (item != scene && item->get_owner() != scene && item != scene->get_deepest_editable_node(item)) {
  884. //invalid result
  885. selection_results.remove(i);
  886. i--;
  887. }
  888. }
  889. clicked_wants_append = b->get_shift();
  890. bool allow_locked = b->get_alt() && spatial_editor->get_tool_mode() != SpatialEditor::TOOL_MODE_LIST_SELECT;
  891. if (selection_results.size() == 1) {
  892. clicked = selection_results[0].item->get_instance_id();
  893. selection_results.clear();
  894. if (clicked) {
  895. _select_clicked(clicked_wants_append, true, allow_locked);
  896. clicked = 0;
  897. }
  898. } else if (!selection_results.empty()) {
  899. NodePath root_path = get_tree()->get_edited_scene_root()->get_path();
  900. StringName root_name = root_path.get_name(root_path.get_name_count() - 1);
  901. for (int i = 0; i < selection_results.size(); i++) {
  902. Spatial *spat = selection_results[i].item;
  903. Ref<Texture> icon = EditorNode::get_singleton()->get_object_icon(spat, "Node");
  904. String node_path = "/" + root_name + "/" + root_path.rel_path_to(spat->get_path());
  905. int locked = 0;
  906. if (_is_node_locked(spat)) {
  907. locked = 1;
  908. } else {
  909. Node *ed_scene = editor->get_edited_scene();
  910. Node *node = spat;
  911. while (node && node != ed_scene->get_parent()) {
  912. Spatial *selected_tmp = Object::cast_to<Spatial>(node);
  913. if (selected_tmp && node->has_meta("_edit_group_")) {
  914. locked = 2;
  915. }
  916. node = node->get_parent();
  917. }
  918. }
  919. if (!allow_locked && locked > 0) {
  920. continue;
  921. }
  922. String suffix = String();
  923. if (locked == 1) {
  924. suffix = " (" + TTR("Locked") + ")";
  925. } else if (locked == 2) {
  926. suffix = " (" + TTR("Grouped") + ")";
  927. }
  928. selection_menu->add_item((String)spat->get_name() + suffix);
  929. selection_menu->set_item_icon(i, icon);
  930. selection_menu->set_item_metadata(i, node_path);
  931. selection_menu->set_item_tooltip(i, String(spat->get_name()) + "\nType: " + spat->get_class() + "\nPath: " + node_path);
  932. }
  933. if (selection_menu->get_item_count() > 0) {
  934. selection_menu->set_global_position(b->get_global_position());
  935. selection_menu->popup();
  936. }
  937. }
  938. }
  939. void SpatialEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
  940. if (previewing) {
  941. return; //do NONE
  942. }
  943. {
  944. EditorNode *en = editor;
  945. EditorPluginList *force_input_forwarding_list = en->get_editor_plugins_force_input_forwarding();
  946. if (!force_input_forwarding_list->empty()) {
  947. bool discard = force_input_forwarding_list->forward_spatial_gui_input(camera, p_event, true);
  948. if (discard) {
  949. return;
  950. }
  951. }
  952. }
  953. {
  954. EditorNode *en = editor;
  955. EditorPluginList *over_plugin_list = en->get_editor_plugins_over();
  956. if (!over_plugin_list->empty()) {
  957. bool discard = over_plugin_list->forward_spatial_gui_input(camera, p_event, false);
  958. if (discard) {
  959. return;
  960. }
  961. }
  962. }
  963. Ref<InputEventMouseButton> b = p_event;
  964. if (b.is_valid()) {
  965. emit_signal("clicked", this);
  966. float zoom_factor = 1 + (ZOOM_FREELOOK_MULTIPLIER - 1) * b->get_factor();
  967. switch (b->get_button_index()) {
  968. case BUTTON_WHEEL_UP: {
  969. if (b->get_alt()) {
  970. scale_fov(-0.05);
  971. } else {
  972. if (is_freelook_active()) {
  973. scale_freelook_speed(zoom_factor);
  974. } else {
  975. scale_cursor_distance(1.0 / zoom_factor);
  976. }
  977. }
  978. } break;
  979. case BUTTON_WHEEL_DOWN: {
  980. if (b->get_alt()) {
  981. scale_fov(0.05);
  982. } else {
  983. if (is_freelook_active()) {
  984. scale_freelook_speed(1.0 / zoom_factor);
  985. } else {
  986. scale_cursor_distance(zoom_factor);
  987. }
  988. }
  989. } break;
  990. case BUTTON_RIGHT: {
  991. NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  992. if (b->is_pressed() && _edit.gizmo.is_valid()) {
  993. //restore
  994. _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_initial_value, true);
  995. _edit.gizmo = Ref<EditorSpatialGizmo>();
  996. }
  997. if (_edit.mode == TRANSFORM_NONE && b->is_pressed()) {
  998. if (b->get_alt()) {
  999. if (nav_scheme == NAVIGATION_MAYA) {
  1000. break;
  1001. }
  1002. _list_select(b);
  1003. return;
  1004. }
  1005. }
  1006. if (_edit.mode != TRANSFORM_NONE && b->is_pressed()) {
  1007. //cancel motion
  1008. _edit.mode = TRANSFORM_NONE;
  1009. List<Node *> &selection = editor_selection->get_selected_node_list();
  1010. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1011. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1012. if (!sp) {
  1013. continue;
  1014. }
  1015. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1016. if (!se) {
  1017. continue;
  1018. }
  1019. sp->set_global_transform(se->original);
  1020. }
  1021. surface->update();
  1022. set_message(TTR("Transform Aborted."), 3);
  1023. }
  1024. if (b->is_pressed()) {
  1025. const int mod = _get_key_modifier(b);
  1026. if (!orthogonal) {
  1027. if (mod == _get_key_modifier_setting("editors/3d/freelook/freelook_activation_modifier")) {
  1028. set_freelook_active(true);
  1029. }
  1030. }
  1031. } else {
  1032. set_freelook_active(false);
  1033. }
  1034. if (freelook_active && !surface->has_focus()) {
  1035. // Focus usually doesn't trigger on right-click, but in case of freelook it should,
  1036. // otherwise using keyboard navigation would misbehave
  1037. surface->grab_focus();
  1038. }
  1039. } break;
  1040. case BUTTON_MIDDLE: {
  1041. if (b->is_pressed() && _edit.mode != TRANSFORM_NONE) {
  1042. switch (_edit.plane) {
  1043. case TRANSFORM_VIEW: {
  1044. _edit.plane = TRANSFORM_X_AXIS;
  1045. set_message(TTR("X-Axis Transform."), 2);
  1046. view_type = VIEW_TYPE_USER;
  1047. _update_name();
  1048. } break;
  1049. case TRANSFORM_X_AXIS: {
  1050. _edit.plane = TRANSFORM_Y_AXIS;
  1051. set_message(TTR("Y-Axis Transform."), 2);
  1052. } break;
  1053. case TRANSFORM_Y_AXIS: {
  1054. _edit.plane = TRANSFORM_Z_AXIS;
  1055. set_message(TTR("Z-Axis Transform."), 2);
  1056. } break;
  1057. case TRANSFORM_Z_AXIS: {
  1058. _edit.plane = TRANSFORM_VIEW;
  1059. set_message(TTR("View Plane Transform."), 2);
  1060. } break;
  1061. case TRANSFORM_YZ:
  1062. case TRANSFORM_XZ:
  1063. case TRANSFORM_XY: {
  1064. } break;
  1065. }
  1066. }
  1067. } break;
  1068. case BUTTON_LEFT: {
  1069. if (b->is_pressed()) {
  1070. NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  1071. if ((nav_scheme == NAVIGATION_MAYA || nav_scheme == NAVIGATION_MODO) && b->get_alt()) {
  1072. break;
  1073. }
  1074. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_LIST_SELECT) {
  1075. _list_select(b);
  1076. break;
  1077. }
  1078. _edit.mouse_pos = b->get_position();
  1079. _edit.original_mouse_pos = b->get_position();
  1080. _edit.snap = spatial_editor->is_snap_enabled();
  1081. _edit.mode = TRANSFORM_NONE;
  1082. //gizmo has priority over everything
  1083. bool can_select_gizmos = true;
  1084. {
  1085. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  1086. can_select_gizmos = view_menu->get_popup()->is_item_checked(idx);
  1087. }
  1088. if (can_select_gizmos && spatial_editor->get_selected()) {
  1089. Ref<EditorSpatialGizmo> seg = spatial_editor->get_selected()->get_gizmo();
  1090. if (seg.is_valid()) {
  1091. int handle = -1;
  1092. Vector3 point;
  1093. Vector3 normal;
  1094. bool inters = seg->intersect_ray(camera, _edit.mouse_pos, point, normal, &handle, b->get_shift());
  1095. if (inters && handle != -1) {
  1096. _edit.gizmo = seg;
  1097. _edit.gizmo_handle = handle;
  1098. _edit.gizmo_initial_value = seg->get_handle_value(handle);
  1099. break;
  1100. }
  1101. }
  1102. }
  1103. if (_gizmo_select(_edit.mouse_pos)) {
  1104. break;
  1105. }
  1106. clicked = 0;
  1107. clicked_includes_current = false;
  1108. if ((spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT && b->get_command()) || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_ROTATE) {
  1109. /* HANDLE ROTATION */
  1110. if (get_selected_count() == 0) {
  1111. break; //bye
  1112. }
  1113. //handle rotate
  1114. _edit.mode = TRANSFORM_ROTATE;
  1115. _compute_edit(b->get_position());
  1116. break;
  1117. }
  1118. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_MOVE) {
  1119. if (get_selected_count() == 0) {
  1120. break; //bye
  1121. }
  1122. //handle translate
  1123. _edit.mode = TRANSFORM_TRANSLATE;
  1124. _compute_edit(b->get_position());
  1125. break;
  1126. }
  1127. if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SCALE) {
  1128. if (get_selected_count() == 0) {
  1129. break; //bye
  1130. }
  1131. //handle scale
  1132. _edit.mode = TRANSFORM_SCALE;
  1133. _compute_edit(b->get_position());
  1134. break;
  1135. }
  1136. // todo scale
  1137. int gizmo_handle = -1;
  1138. clicked = _select_ray(b->get_position(), b->get_shift(), clicked_includes_current, &gizmo_handle, b->get_shift());
  1139. selection_in_progress = true;
  1140. //clicking is always deferred to either move or release
  1141. clicked_wants_append = b->get_shift();
  1142. if (!clicked) {
  1143. if (!clicked_wants_append) {
  1144. _clear_selected();
  1145. }
  1146. //default to regionselect
  1147. cursor.region_select = true;
  1148. cursor.region_begin = b->get_position();
  1149. cursor.region_end = b->get_position();
  1150. }
  1151. if (clicked && gizmo_handle >= 0) {
  1152. Spatial *spa = Object::cast_to<Spatial>(ObjectDB::get_instance(clicked));
  1153. if (spa) {
  1154. Ref<EditorSpatialGizmo> seg = spa->get_gizmo();
  1155. if (seg.is_valid()) {
  1156. _edit.gizmo = seg;
  1157. _edit.gizmo_handle = gizmo_handle;
  1158. _edit.gizmo_initial_value = seg->get_handle_value(gizmo_handle);
  1159. break;
  1160. }
  1161. }
  1162. }
  1163. surface->update();
  1164. } else {
  1165. if (_edit.gizmo.is_valid()) {
  1166. _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_initial_value, false);
  1167. _edit.gizmo = Ref<EditorSpatialGizmo>();
  1168. break;
  1169. }
  1170. if (clicked) {
  1171. _select_clicked(clicked_wants_append, true);
  1172. // Processing was deferred.
  1173. clicked = 0;
  1174. }
  1175. if (cursor.region_select) {
  1176. if (!clicked_wants_append) {
  1177. _clear_selected();
  1178. }
  1179. _select_region();
  1180. cursor.region_select = false;
  1181. surface->update();
  1182. }
  1183. selection_in_progress = false;
  1184. if (_edit.mode != TRANSFORM_NONE) {
  1185. static const char *_transform_name[4] = {
  1186. TTRC("None"),
  1187. TTRC("Rotate"),
  1188. // TRANSLATORS: This refers to the movement that changes the position of an object.
  1189. TTRC("Translate"),
  1190. TTRC("Scale"),
  1191. };
  1192. undo_redo->create_action(TTRGET(_transform_name[_edit.mode]));
  1193. List<Node *> &selection = editor_selection->get_selected_node_list();
  1194. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1195. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1196. if (!sp) {
  1197. continue;
  1198. }
  1199. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1200. if (!se) {
  1201. continue;
  1202. }
  1203. undo_redo->add_do_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
  1204. undo_redo->add_undo_method(sp, "set_global_transform", se->original);
  1205. }
  1206. undo_redo->commit_action();
  1207. _edit.mode = TRANSFORM_NONE;
  1208. set_message("");
  1209. }
  1210. surface->update();
  1211. }
  1212. } break;
  1213. }
  1214. }
  1215. Ref<InputEventMouseMotion> m = p_event;
  1216. if (m.is_valid()) {
  1217. _edit.mouse_pos = m->get_position();
  1218. if (spatial_editor->get_selected()) {
  1219. Ref<EditorSpatialGizmo> seg = spatial_editor->get_selected()->get_gizmo();
  1220. if (seg.is_valid()) {
  1221. int selected_handle = -1;
  1222. int handle = -1;
  1223. Vector3 point;
  1224. Vector3 normal;
  1225. bool inters = seg->intersect_ray(camera, _edit.mouse_pos, point, normal, &handle, false);
  1226. if (inters && handle != -1) {
  1227. selected_handle = handle;
  1228. }
  1229. if (selected_handle != spatial_editor->get_over_gizmo_handle()) {
  1230. spatial_editor->set_over_gizmo_handle(selected_handle);
  1231. spatial_editor->get_selected()->update_gizmo();
  1232. if (selected_handle != -1) {
  1233. spatial_editor->select_gizmo_highlight_axis(-1);
  1234. }
  1235. }
  1236. }
  1237. }
  1238. if (spatial_editor->get_over_gizmo_handle() == -1 && !(m->get_button_mask() & 1) && !_edit.gizmo.is_valid()) {
  1239. _gizmo_select(_edit.mouse_pos, true);
  1240. }
  1241. NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  1242. NavigationMode nav_mode = NAVIGATION_NONE;
  1243. if (_edit.gizmo.is_valid()) {
  1244. _edit.gizmo->set_handle(_edit.gizmo_handle, camera, m->get_position());
  1245. Variant v = _edit.gizmo->get_handle_value(_edit.gizmo_handle);
  1246. String n = _edit.gizmo->get_handle_name(_edit.gizmo_handle);
  1247. set_message(n + ": " + String(v));
  1248. } else if (m->get_button_mask() & BUTTON_MASK_LEFT) {
  1249. if (nav_scheme == NAVIGATION_MAYA && m->get_alt()) {
  1250. nav_mode = NAVIGATION_ORBIT;
  1251. } else if (nav_scheme == NAVIGATION_MODO && m->get_alt() && m->get_shift()) {
  1252. nav_mode = NAVIGATION_PAN;
  1253. } else if (nav_scheme == NAVIGATION_MODO && m->get_alt() && m->get_control()) {
  1254. nav_mode = NAVIGATION_ZOOM;
  1255. } else if (nav_scheme == NAVIGATION_MODO && m->get_alt()) {
  1256. nav_mode = NAVIGATION_ORBIT;
  1257. } else {
  1258. const bool movement_threshold_passed = _edit.original_mouse_pos.distance_to(_edit.mouse_pos) > 8 * EDSCALE;
  1259. if (selection_in_progress && movement_threshold_passed) {
  1260. if (get_selected_count() == 0 || clicked_wants_append) {
  1261. cursor.region_select = true;
  1262. cursor.region_begin = _edit.original_mouse_pos;
  1263. clicked = 0;
  1264. }
  1265. }
  1266. if (cursor.region_select) {
  1267. cursor.region_end = m->get_position();
  1268. surface->update();
  1269. return;
  1270. }
  1271. if (clicked && movement_threshold_passed) {
  1272. _compute_edit(_edit.mouse_pos);
  1273. clicked = 0;
  1274. _edit.mode = TRANSFORM_TRANSLATE;
  1275. }
  1276. if (_edit.mode == TRANSFORM_NONE) {
  1277. return;
  1278. }
  1279. Vector3 ray_pos = _get_ray_pos(m->get_position());
  1280. Vector3 ray = _get_ray(m->get_position());
  1281. double snap = EDITOR_GET("interface/inspector/default_float_step");
  1282. int snap_step_decimals = Math::range_step_decimals(snap);
  1283. switch (_edit.mode) {
  1284. case TRANSFORM_SCALE: {
  1285. Vector3 motion_mask;
  1286. Plane plane;
  1287. bool plane_mv = false;
  1288. switch (_edit.plane) {
  1289. case TRANSFORM_VIEW:
  1290. motion_mask = Vector3(0, 0, 0);
  1291. plane = Plane(_edit.center, _get_camera_normal());
  1292. break;
  1293. case TRANSFORM_X_AXIS:
  1294. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0);
  1295. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  1296. break;
  1297. case TRANSFORM_Y_AXIS:
  1298. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(1);
  1299. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  1300. break;
  1301. case TRANSFORM_Z_AXIS:
  1302. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2);
  1303. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  1304. break;
  1305. case TRANSFORM_YZ:
  1306. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2) + spatial_editor->get_gizmo_transform().basis.get_axis(1);
  1307. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(0));
  1308. plane_mv = true;
  1309. break;
  1310. case TRANSFORM_XZ:
  1311. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2) + spatial_editor->get_gizmo_transform().basis.get_axis(0);
  1312. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(1));
  1313. plane_mv = true;
  1314. break;
  1315. case TRANSFORM_XY:
  1316. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0) + spatial_editor->get_gizmo_transform().basis.get_axis(1);
  1317. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(2));
  1318. plane_mv = true;
  1319. break;
  1320. }
  1321. Vector3 intersection;
  1322. if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
  1323. break;
  1324. }
  1325. Vector3 click;
  1326. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
  1327. break;
  1328. }
  1329. Vector3 motion = intersection - click;
  1330. if (_edit.plane != TRANSFORM_VIEW) {
  1331. if (!plane_mv) {
  1332. motion = motion_mask.dot(motion) * motion_mask;
  1333. } else {
  1334. // Alternative planar scaling mode
  1335. if (_get_key_modifier(m) != KEY_SHIFT) {
  1336. motion = motion_mask.dot(motion) * motion_mask;
  1337. }
  1338. }
  1339. } else {
  1340. float center_click_dist = click.distance_to(_edit.center);
  1341. float center_inters_dist = intersection.distance_to(_edit.center);
  1342. if (center_click_dist == 0) {
  1343. break;
  1344. }
  1345. float scale = center_inters_dist - center_click_dist;
  1346. motion = Vector3(scale, scale, scale);
  1347. }
  1348. motion /= click.distance_to(_edit.center);
  1349. List<Node *> &selection = editor_selection->get_selected_node_list();
  1350. // Disable local transformation for TRANSFORM_VIEW
  1351. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
  1352. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1353. snap = spatial_editor->get_scale_snap() / 100;
  1354. }
  1355. Vector3 motion_snapped = motion;
  1356. motion_snapped.snap(Vector3(snap, snap, snap));
  1357. // This might not be necessary anymore after issue #288 is solved (in 4.0?).
  1358. set_message(TTR("Scaling: ") + "(" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
  1359. String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
  1360. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1361. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1362. if (!sp) {
  1363. continue;
  1364. }
  1365. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1366. if (!se) {
  1367. continue;
  1368. }
  1369. if (sp->has_meta("_edit_lock_")) {
  1370. continue;
  1371. }
  1372. Transform original = se->original;
  1373. Transform original_local = se->original_local;
  1374. Transform base = Transform(Basis(), _edit.center);
  1375. Transform t;
  1376. Vector3 local_scale;
  1377. if (local_coords) {
  1378. Basis g = original.basis.orthonormalized();
  1379. Vector3 local_motion = g.inverse().xform(motion);
  1380. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1381. local_motion.snap(Vector3(snap, snap, snap));
  1382. }
  1383. local_scale = original_local.basis.get_scale() * (local_motion + Vector3(1, 1, 1));
  1384. // Prevent scaling to 0 it would break the gizmo
  1385. Basis check = original_local.basis;
  1386. check.scale(local_scale);
  1387. if (check.determinant() != 0) {
  1388. // Apply scale
  1389. sp->set_scale(local_scale);
  1390. }
  1391. } else {
  1392. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1393. motion.snap(Vector3(snap, snap, snap));
  1394. }
  1395. Transform r;
  1396. r.basis.scale(motion + Vector3(1, 1, 1));
  1397. t = base * (r * (base.inverse() * original));
  1398. // Apply scale
  1399. sp->set_global_transform(t);
  1400. }
  1401. }
  1402. surface->update();
  1403. } break;
  1404. case TRANSFORM_TRANSLATE: {
  1405. Vector3 motion_mask;
  1406. Plane plane;
  1407. bool plane_mv = false;
  1408. switch (_edit.plane) {
  1409. case TRANSFORM_VIEW:
  1410. plane = Plane(_edit.center, _get_camera_normal());
  1411. break;
  1412. case TRANSFORM_X_AXIS:
  1413. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0);
  1414. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  1415. break;
  1416. case TRANSFORM_Y_AXIS:
  1417. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(1);
  1418. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  1419. break;
  1420. case TRANSFORM_Z_AXIS:
  1421. motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2);
  1422. plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
  1423. break;
  1424. case TRANSFORM_YZ:
  1425. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(0));
  1426. plane_mv = true;
  1427. break;
  1428. case TRANSFORM_XZ:
  1429. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(1));
  1430. plane_mv = true;
  1431. break;
  1432. case TRANSFORM_XY:
  1433. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(2));
  1434. plane_mv = true;
  1435. break;
  1436. }
  1437. Vector3 intersection;
  1438. if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
  1439. break;
  1440. }
  1441. Vector3 click;
  1442. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
  1443. break;
  1444. }
  1445. Vector3 motion = intersection - click;
  1446. if (_edit.plane != TRANSFORM_VIEW) {
  1447. if (!plane_mv) {
  1448. motion = motion_mask.dot(motion) * motion_mask;
  1449. }
  1450. }
  1451. List<Node *> &selection = editor_selection->get_selected_node_list();
  1452. // Disable local transformation for TRANSFORM_VIEW
  1453. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
  1454. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1455. snap = spatial_editor->get_translate_snap();
  1456. }
  1457. Vector3 motion_snapped = motion;
  1458. motion_snapped.snap(Vector3(snap, snap, snap));
  1459. set_message(TTR("Translating: ") + "(" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
  1460. String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
  1461. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1462. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1463. if (!sp) {
  1464. continue;
  1465. }
  1466. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1467. if (!se) {
  1468. continue;
  1469. }
  1470. if (sp->has_meta("_edit_lock_")) {
  1471. continue;
  1472. }
  1473. Transform original = se->original;
  1474. Transform t;
  1475. if (local_coords) {
  1476. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1477. Basis g = original.basis.orthonormalized();
  1478. Vector3 local_motion = g.inverse().xform(motion);
  1479. local_motion.snap(Vector3(snap, snap, snap));
  1480. motion = g.xform(local_motion);
  1481. }
  1482. } else {
  1483. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1484. motion.snap(Vector3(snap, snap, snap));
  1485. }
  1486. }
  1487. // Apply translation
  1488. t = original;
  1489. t.origin += motion;
  1490. sp->set_global_transform(t);
  1491. }
  1492. surface->update();
  1493. } break;
  1494. case TRANSFORM_ROTATE: {
  1495. Plane plane;
  1496. Vector3 axis;
  1497. switch (_edit.plane) {
  1498. case TRANSFORM_VIEW:
  1499. plane = Plane(_edit.center, _get_camera_normal());
  1500. break;
  1501. case TRANSFORM_X_AXIS:
  1502. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(0));
  1503. axis = Vector3(1, 0, 0);
  1504. break;
  1505. case TRANSFORM_Y_AXIS:
  1506. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(1));
  1507. axis = Vector3(0, 1, 0);
  1508. break;
  1509. case TRANSFORM_Z_AXIS:
  1510. plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(2));
  1511. axis = Vector3(0, 0, 1);
  1512. break;
  1513. case TRANSFORM_YZ:
  1514. case TRANSFORM_XZ:
  1515. case TRANSFORM_XY:
  1516. break;
  1517. }
  1518. Vector3 intersection;
  1519. if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
  1520. break;
  1521. }
  1522. Vector3 click;
  1523. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
  1524. break;
  1525. }
  1526. Vector3 y_axis = (click - _edit.center).normalized();
  1527. Vector3 x_axis = plane.normal.cross(y_axis).normalized();
  1528. double angle = Math::atan2(x_axis.dot(intersection - _edit.center), y_axis.dot(intersection - _edit.center));
  1529. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1530. snap = spatial_editor->get_rotate_snap();
  1531. }
  1532. angle = Math::rad2deg(angle) + snap * 0.5; //else it won't reach +180
  1533. angle -= Math::fmod(angle, snap);
  1534. set_message(vformat(TTR("Rotating %s degrees."), String::num(angle, snap_step_decimals)));
  1535. angle = Math::deg2rad(angle);
  1536. List<Node *> &selection = editor_selection->get_selected_node_list();
  1537. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW); // Disable local transformation for TRANSFORM_VIEW
  1538. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1539. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1540. if (!sp) {
  1541. continue;
  1542. }
  1543. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  1544. if (!se) {
  1545. continue;
  1546. }
  1547. if (sp->has_meta("_edit_lock_")) {
  1548. continue;
  1549. }
  1550. Transform t;
  1551. if (local_coords) {
  1552. Transform original_local = se->original_local;
  1553. Basis rot = Basis(axis, angle);
  1554. t.basis = original_local.get_basis().orthonormalized() * rot;
  1555. t.origin = original_local.origin;
  1556. // Apply rotation
  1557. sp->set_transform(t);
  1558. sp->set_scale(original_local.basis.get_scale()); // re-apply original scale
  1559. } else {
  1560. Transform original = se->original;
  1561. Transform r;
  1562. Transform base = Transform(Basis(), _edit.center);
  1563. r.basis.rotate(plane.normal, angle);
  1564. t = base * r * base.inverse() * original;
  1565. // Apply rotation
  1566. sp->set_global_transform(t);
  1567. }
  1568. }
  1569. surface->update();
  1570. } break;
  1571. default: {
  1572. }
  1573. }
  1574. }
  1575. } else if ((m->get_button_mask() & BUTTON_MASK_RIGHT) || freelook_active) {
  1576. if (nav_scheme == NAVIGATION_MAYA && m->get_alt()) {
  1577. nav_mode = NAVIGATION_ZOOM;
  1578. } else if (freelook_active) {
  1579. nav_mode = NAVIGATION_LOOK;
  1580. } else if (orthogonal) {
  1581. nav_mode = NAVIGATION_PAN;
  1582. }
  1583. } else if (m->get_button_mask() & BUTTON_MASK_MIDDLE) {
  1584. const int mod = _get_key_modifier(m);
  1585. if (nav_scheme == NAVIGATION_GODOT) {
  1586. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1587. nav_mode = NAVIGATION_PAN;
  1588. } else if (mod == _get_key_modifier_setting("editors/3d/navigation/zoom_modifier")) {
  1589. nav_mode = NAVIGATION_ZOOM;
  1590. } else if (mod == KEY_ALT || mod == _get_key_modifier_setting("editors/3d/navigation/orbit_modifier")) {
  1591. // Always allow Alt as a modifier to better support graphic tablets.
  1592. nav_mode = NAVIGATION_ORBIT;
  1593. }
  1594. } else if (nav_scheme == NAVIGATION_MAYA) {
  1595. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1596. nav_mode = NAVIGATION_PAN;
  1597. }
  1598. }
  1599. } else if (EditorSettings::get_singleton()->get("editors/3d/navigation/emulate_3_button_mouse")) {
  1600. // Handle trackpad (no external mouse) use case
  1601. const int mod = _get_key_modifier(m);
  1602. if (mod) {
  1603. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1604. nav_mode = NAVIGATION_PAN;
  1605. } else if (mod == _get_key_modifier_setting("editors/3d/navigation/zoom_modifier")) {
  1606. nav_mode = NAVIGATION_ZOOM;
  1607. } else if (mod == KEY_ALT || mod == _get_key_modifier_setting("editors/3d/navigation/orbit_modifier")) {
  1608. // Always allow Alt as a modifier to better support graphic tablets.
  1609. nav_mode = NAVIGATION_ORBIT;
  1610. }
  1611. }
  1612. }
  1613. switch (nav_mode) {
  1614. case NAVIGATION_PAN: {
  1615. _nav_pan(m, _get_warped_mouse_motion(m));
  1616. } break;
  1617. case NAVIGATION_ZOOM: {
  1618. _nav_zoom(m, m->get_relative());
  1619. } break;
  1620. case NAVIGATION_ORBIT: {
  1621. _nav_orbit(m, _get_warped_mouse_motion(m));
  1622. } break;
  1623. case NAVIGATION_LOOK: {
  1624. _nav_look(m, _get_warped_mouse_motion(m));
  1625. } break;
  1626. default: {
  1627. }
  1628. }
  1629. }
  1630. Ref<InputEventMagnifyGesture> magnify_gesture = p_event;
  1631. if (magnify_gesture.is_valid()) {
  1632. if (is_freelook_active()) {
  1633. scale_freelook_speed(magnify_gesture->get_factor());
  1634. } else {
  1635. scale_cursor_distance(1.0 / magnify_gesture->get_factor());
  1636. }
  1637. }
  1638. Ref<InputEventPanGesture> pan_gesture = p_event;
  1639. if (pan_gesture.is_valid()) {
  1640. NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  1641. NavigationMode nav_mode = NAVIGATION_NONE;
  1642. if (nav_scheme == NAVIGATION_GODOT) {
  1643. const int mod = _get_key_modifier(pan_gesture);
  1644. if (mod == _get_key_modifier_setting("editors/3d/navigation/pan_modifier")) {
  1645. nav_mode = NAVIGATION_PAN;
  1646. } else if (mod == _get_key_modifier_setting("editors/3d/navigation/zoom_modifier")) {
  1647. nav_mode = NAVIGATION_ZOOM;
  1648. } else if (mod == KEY_ALT || mod == _get_key_modifier_setting("editors/3d/navigation/orbit_modifier")) {
  1649. // Always allow Alt as a modifier to better support graphic tablets.
  1650. nav_mode = NAVIGATION_ORBIT;
  1651. }
  1652. } else if (nav_scheme == NAVIGATION_MAYA) {
  1653. if (pan_gesture->get_alt()) {
  1654. nav_mode = NAVIGATION_PAN;
  1655. }
  1656. }
  1657. switch (nav_mode) {
  1658. case NAVIGATION_PAN: {
  1659. _nav_pan(pan_gesture, pan_gesture->get_delta());
  1660. } break;
  1661. case NAVIGATION_ZOOM: {
  1662. _nav_zoom(pan_gesture, pan_gesture->get_delta());
  1663. } break;
  1664. case NAVIGATION_ORBIT: {
  1665. _nav_orbit(pan_gesture, pan_gesture->get_delta());
  1666. } break;
  1667. case NAVIGATION_LOOK: {
  1668. _nav_look(pan_gesture, pan_gesture->get_delta());
  1669. } break;
  1670. default: {
  1671. }
  1672. }
  1673. }
  1674. Ref<InputEventKey> k = p_event;
  1675. if (k.is_valid()) {
  1676. if (!k->is_pressed()) {
  1677. return;
  1678. }
  1679. if (_edit.mode == TRANSFORM_NONE && !cursor.region_select) {
  1680. if (k->get_scancode() == KEY_ESCAPE) {
  1681. _clear_selected();
  1682. return;
  1683. }
  1684. }
  1685. if (EditorSettings::get_singleton()->get("editors/3d/navigation/emulate_numpad")) {
  1686. const uint32_t code = k->get_scancode();
  1687. if (code >= KEY_0 && code <= KEY_9) {
  1688. k->set_scancode(code - KEY_0 + KEY_KP_0);
  1689. }
  1690. }
  1691. if (ED_IS_SHORTCUT("spatial_editor/snap", p_event)) {
  1692. if (_edit.mode != TRANSFORM_NONE) {
  1693. _edit.snap = !_edit.snap;
  1694. }
  1695. }
  1696. if (ED_IS_SHORTCUT("spatial_editor/bottom_view", p_event)) {
  1697. _menu_option(VIEW_BOTTOM);
  1698. }
  1699. if (ED_IS_SHORTCUT("spatial_editor/top_view", p_event)) {
  1700. _menu_option(VIEW_TOP);
  1701. }
  1702. if (ED_IS_SHORTCUT("spatial_editor/rear_view", p_event)) {
  1703. _menu_option(VIEW_REAR);
  1704. }
  1705. if (ED_IS_SHORTCUT("spatial_editor/front_view", p_event)) {
  1706. _menu_option(VIEW_FRONT);
  1707. }
  1708. if (ED_IS_SHORTCUT("spatial_editor/left_view", p_event)) {
  1709. _menu_option(VIEW_LEFT);
  1710. }
  1711. if (ED_IS_SHORTCUT("spatial_editor/right_view", p_event)) {
  1712. _menu_option(VIEW_RIGHT);
  1713. }
  1714. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_down", p_event)) {
  1715. // Clamp rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  1716. cursor.x_rot = CLAMP(cursor.x_rot - Math_PI / 12.0, -1.57, 1.57);
  1717. view_type = VIEW_TYPE_USER;
  1718. _update_name();
  1719. }
  1720. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_up", p_event)) {
  1721. // Clamp rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  1722. cursor.x_rot = CLAMP(cursor.x_rot + Math_PI / 12.0, -1.57, 1.57);
  1723. view_type = VIEW_TYPE_USER;
  1724. _update_name();
  1725. }
  1726. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_right", p_event)) {
  1727. cursor.y_rot -= Math_PI / 12.0;
  1728. view_type = VIEW_TYPE_USER;
  1729. _update_name();
  1730. }
  1731. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_left", p_event)) {
  1732. cursor.y_rot += Math_PI / 12.0;
  1733. view_type = VIEW_TYPE_USER;
  1734. _update_name();
  1735. }
  1736. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_180", p_event)) {
  1737. cursor.y_rot += Math_PI;
  1738. view_type = VIEW_TYPE_USER;
  1739. _update_name();
  1740. }
  1741. if (ED_IS_SHORTCUT("spatial_editor/focus_origin", p_event)) {
  1742. _menu_option(VIEW_CENTER_TO_ORIGIN);
  1743. }
  1744. if (ED_IS_SHORTCUT("spatial_editor/focus_selection", p_event)) {
  1745. _menu_option(VIEW_CENTER_TO_SELECTION);
  1746. }
  1747. // Orthgonal mode doesn't work in freelook.
  1748. if (!freelook_active && ED_IS_SHORTCUT("spatial_editor/switch_perspective_orthogonal", p_event)) {
  1749. _menu_option(orthogonal ? VIEW_PERSPECTIVE : VIEW_ORTHOGONAL);
  1750. }
  1751. if (ED_IS_SHORTCUT("spatial_editor/align_transform_with_view", p_event)) {
  1752. _menu_option(VIEW_ALIGN_TRANSFORM_WITH_VIEW);
  1753. }
  1754. if (ED_IS_SHORTCUT("spatial_editor/align_rotation_with_view", p_event)) {
  1755. _menu_option(VIEW_ALIGN_ROTATION_WITH_VIEW);
  1756. }
  1757. if (ED_IS_SHORTCUT("spatial_editor/insert_anim_key", p_event)) {
  1758. if (!get_selected_count() || _edit.mode != TRANSFORM_NONE) {
  1759. return;
  1760. }
  1761. if (!AnimationPlayerEditor::singleton->get_track_editor()->has_keying()) {
  1762. set_message(TTR("Keying is disabled (no key inserted)."));
  1763. return;
  1764. }
  1765. List<Node *> &selection = editor_selection->get_selected_node_list();
  1766. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1767. Spatial *sp = Object::cast_to<Spatial>(E->get());
  1768. if (!sp) {
  1769. continue;
  1770. }
  1771. spatial_editor->emit_signal("transform_key_request", sp, "", sp->get_transform());
  1772. }
  1773. set_message(TTR("Animation Key Inserted."));
  1774. }
  1775. // Freelook doesn't work in orthogonal mode.
  1776. if (!orthogonal && ED_IS_SHORTCUT("spatial_editor/freelook_toggle", p_event)) {
  1777. set_freelook_active(!is_freelook_active());
  1778. } else if (k->get_scancode() == KEY_ESCAPE) {
  1779. set_freelook_active(false);
  1780. }
  1781. if (k->get_scancode() == KEY_SPACE) {
  1782. if (!k->is_pressed()) {
  1783. emit_signal("toggle_maximize_view", this);
  1784. }
  1785. }
  1786. if (ED_IS_SHORTCUT("spatial_editor/decrease_fov", p_event)) {
  1787. scale_fov(-0.05);
  1788. }
  1789. if (ED_IS_SHORTCUT("spatial_editor/increase_fov", p_event)) {
  1790. scale_fov(0.05);
  1791. }
  1792. if (ED_IS_SHORTCUT("spatial_editor/reset_fov", p_event)) {
  1793. reset_fov();
  1794. }
  1795. }
  1796. // freelook uses most of the useful shortcuts, like save, so its ok
  1797. // to consider freelook active as end of the line for future events.
  1798. if (freelook_active) {
  1799. accept_event();
  1800. }
  1801. }
  1802. void SpatialEditorViewport::_nav_pan(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  1803. const NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  1804. real_t pan_speed = 1 / 150.0;
  1805. int pan_speed_modifier = 10;
  1806. if (nav_scheme == NAVIGATION_MAYA && p_event->get_shift()) {
  1807. pan_speed *= pan_speed_modifier;
  1808. }
  1809. Transform camera_transform;
  1810. camera_transform.translate(cursor.pos);
  1811. camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
  1812. camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
  1813. const bool invert_x_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_x_axis");
  1814. const bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y_axis");
  1815. Vector3 translation(
  1816. (invert_x_axis ? -1 : 1) * -p_relative.x * pan_speed,
  1817. (invert_y_axis ? -1 : 1) * p_relative.y * pan_speed,
  1818. 0);
  1819. translation *= cursor.distance / DISTANCE_DEFAULT;
  1820. camera_transform.translate(translation);
  1821. cursor.pos = camera_transform.origin;
  1822. }
  1823. void SpatialEditorViewport::_nav_zoom(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  1824. const NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
  1825. real_t zoom_speed = 1 / 80.0;
  1826. int zoom_speed_modifier = 10;
  1827. if (nav_scheme == NAVIGATION_MAYA && p_event->get_shift()) {
  1828. zoom_speed *= zoom_speed_modifier;
  1829. }
  1830. NavigationZoomStyle zoom_style = (NavigationZoomStyle)EditorSettings::get_singleton()->get("editors/3d/navigation/zoom_style").operator int();
  1831. if (zoom_style == NAVIGATION_ZOOM_HORIZONTAL) {
  1832. if (p_relative.x > 0) {
  1833. scale_cursor_distance(1 - p_relative.x * zoom_speed);
  1834. } else if (p_relative.x < 0) {
  1835. scale_cursor_distance(1.0 / (1 + p_relative.x * zoom_speed));
  1836. }
  1837. } else {
  1838. if (p_relative.y > 0) {
  1839. scale_cursor_distance(1 + p_relative.y * zoom_speed);
  1840. } else if (p_relative.y < 0) {
  1841. scale_cursor_distance(1.0 / (1 - p_relative.y * zoom_speed));
  1842. }
  1843. }
  1844. }
  1845. void SpatialEditorViewport::_nav_orbit(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  1846. if (lock_rotation) {
  1847. _nav_pan(p_event, p_relative);
  1848. return;
  1849. }
  1850. if (orthogonal && auto_orthogonal) {
  1851. _menu_option(VIEW_PERSPECTIVE);
  1852. }
  1853. const real_t degrees_per_pixel = EditorSettings::get_singleton()->get("editors/3d/navigation_feel/orbit_sensitivity");
  1854. const real_t radians_per_pixel = Math::deg2rad(degrees_per_pixel);
  1855. const bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y_axis");
  1856. const bool invert_x_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_x_axis");
  1857. if (invert_y_axis) {
  1858. cursor.x_rot -= p_relative.y * radians_per_pixel;
  1859. } else {
  1860. cursor.x_rot += p_relative.y * radians_per_pixel;
  1861. }
  1862. // Clamp the Y rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  1863. cursor.x_rot = CLAMP(cursor.x_rot, -1.57, 1.57);
  1864. if (invert_x_axis) {
  1865. cursor.y_rot -= p_relative.x * radians_per_pixel;
  1866. } else {
  1867. cursor.y_rot += p_relative.x * radians_per_pixel;
  1868. }
  1869. view_type = VIEW_TYPE_USER;
  1870. _update_name();
  1871. }
  1872. void SpatialEditorViewport::_nav_look(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  1873. if (orthogonal) {
  1874. _nav_pan(p_event, p_relative);
  1875. return;
  1876. }
  1877. if (orthogonal && auto_orthogonal) {
  1878. _menu_option(VIEW_PERSPECTIVE);
  1879. }
  1880. // Scale mouse sensitivity with camera FOV scale when zoomed in to make it easier to point at things.
  1881. const real_t degrees_per_pixel = real_t(EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_sensitivity")) * MIN(1.0, cursor.fov_scale);
  1882. const real_t radians_per_pixel = Math::deg2rad(degrees_per_pixel);
  1883. const bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y_axis");
  1884. // Note: do NOT assume the camera has the "current" transform, because it is interpolated and may have "lag".
  1885. const Transform prev_camera_transform = to_camera_transform(cursor);
  1886. if (invert_y_axis) {
  1887. cursor.x_rot -= p_relative.y * radians_per_pixel;
  1888. } else {
  1889. cursor.x_rot += p_relative.y * radians_per_pixel;
  1890. }
  1891. // Clamp the Y rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  1892. cursor.x_rot = CLAMP(cursor.x_rot, -1.57, 1.57);
  1893. cursor.y_rot += p_relative.x * radians_per_pixel;
  1894. // Look is like the opposite of Orbit: the focus point rotates around the camera
  1895. Transform camera_transform = to_camera_transform(cursor);
  1896. Vector3 pos = camera_transform.xform(Vector3(0, 0, 0));
  1897. Vector3 prev_pos = prev_camera_transform.xform(Vector3(0, 0, 0));
  1898. Vector3 diff = prev_pos - pos;
  1899. cursor.pos += diff;
  1900. view_type = VIEW_TYPE_USER;
  1901. _update_name();
  1902. }
  1903. void SpatialEditorViewport::set_freelook_active(bool active_now) {
  1904. if (!freelook_active && active_now) {
  1905. // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
  1906. cursor = camera_cursor;
  1907. // Make sure eye_pos is synced, because freelook referential is eye pos rather than orbit pos
  1908. Vector3 forward = to_camera_transform(cursor).basis.xform(Vector3(0, 0, -1));
  1909. cursor.eye_pos = cursor.pos - cursor.distance * forward;
  1910. // Also sync the camera cursor, otherwise switching to freelook will be trippy if inertia is active
  1911. camera_cursor.eye_pos = cursor.eye_pos;
  1912. if (EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_speed_zoom_link")) {
  1913. // Re-adjust freelook speed from the current zoom level
  1914. real_t base_speed = EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_base_speed");
  1915. freelook_speed = base_speed * cursor.distance;
  1916. }
  1917. previous_mouse_position = get_local_mouse_position();
  1918. // Hide mouse like in an FPS (warping doesn't work)
  1919. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
  1920. } else if (freelook_active && !active_now) {
  1921. // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
  1922. cursor = camera_cursor;
  1923. // Restore mouse
  1924. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  1925. // Restore the previous mouse position when leaving freelook mode.
  1926. // This is done because leaving `Input.MOUSE_MODE_CAPTURED` will center the cursor
  1927. // due to OS limitations.
  1928. warp_mouse(previous_mouse_position);
  1929. }
  1930. freelook_active = active_now;
  1931. }
  1932. void SpatialEditorViewport::scale_fov(real_t p_fov_offset) {
  1933. cursor.fov_scale = CLAMP(cursor.fov_scale + p_fov_offset, 0.1, 2.5);
  1934. surface->update();
  1935. }
  1936. void SpatialEditorViewport::reset_fov() {
  1937. cursor.fov_scale = 1.0;
  1938. surface->update();
  1939. }
  1940. void SpatialEditorViewport::scale_cursor_distance(real_t scale) {
  1941. real_t min_distance = MAX(camera->get_znear() * 4, ZOOM_FREELOOK_MIN);
  1942. real_t max_distance = MIN(camera->get_zfar() / 2, ZOOM_FREELOOK_MAX);
  1943. if (unlikely(min_distance > max_distance)) {
  1944. cursor.distance = (min_distance + max_distance) / 2;
  1945. } else {
  1946. cursor.distance = CLAMP(cursor.distance * scale, min_distance, max_distance);
  1947. }
  1948. if (cursor.distance == max_distance || cursor.distance == min_distance) {
  1949. zoom_failed_attempts_count++;
  1950. } else {
  1951. zoom_failed_attempts_count = 0;
  1952. }
  1953. zoom_indicator_delay = ZOOM_FREELOOK_INDICATOR_DELAY_S;
  1954. surface->update();
  1955. }
  1956. void SpatialEditorViewport::scale_freelook_speed(real_t scale) {
  1957. real_t min_speed = MAX(camera->get_znear() * 4, ZOOM_FREELOOK_MIN);
  1958. real_t max_speed = MIN(camera->get_zfar() / 2, ZOOM_FREELOOK_MAX);
  1959. if (unlikely(min_speed > max_speed)) {
  1960. freelook_speed = (min_speed + max_speed) / 2;
  1961. } else {
  1962. freelook_speed = CLAMP(freelook_speed * scale, min_speed, max_speed);
  1963. }
  1964. zoom_indicator_delay = ZOOM_FREELOOK_INDICATOR_DELAY_S;
  1965. surface->update();
  1966. }
  1967. Point2i SpatialEditorViewport::_get_warped_mouse_motion(const Ref<InputEventMouseMotion> &p_ev_mouse_motion) const {
  1968. Point2i relative;
  1969. if (bool(EDITOR_DEF("editors/3d/navigation/warped_mouse_panning", false))) {
  1970. relative = Input::get_singleton()->warp_mouse_motion(p_ev_mouse_motion, surface->get_global_rect());
  1971. } else {
  1972. relative = p_ev_mouse_motion->get_relative();
  1973. }
  1974. return relative;
  1975. }
  1976. static bool is_shortcut_pressed(const String &p_path) {
  1977. Ref<ShortCut> shortcut = ED_GET_SHORTCUT(p_path);
  1978. if (shortcut.is_null()) {
  1979. return false;
  1980. }
  1981. InputEventKey *k = Object::cast_to<InputEventKey>(shortcut->get_shortcut().ptr());
  1982. if (k == nullptr) {
  1983. return false;
  1984. }
  1985. const Input &input = *Input::get_singleton();
  1986. int scancode = k->get_scancode();
  1987. return input.is_key_pressed(scancode);
  1988. }
  1989. void SpatialEditorViewport::_update_freelook(real_t delta) {
  1990. if (!is_freelook_active()) {
  1991. return;
  1992. }
  1993. const FreelookNavigationScheme navigation_scheme = (FreelookNavigationScheme)EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_navigation_scheme").operator int();
  1994. Vector3 forward;
  1995. if (navigation_scheme == FREELOOK_FULLY_AXIS_LOCKED) {
  1996. // Forward/backward keys will always go straight forward/backward, never moving on the Y axis.
  1997. forward = Vector3(0, 0, -1).rotated(Vector3(0, 1, 0), camera->get_rotation().y);
  1998. } else {
  1999. // Forward/backward keys will be relative to the camera pitch.
  2000. forward = camera->get_transform().basis.xform(Vector3(0, 0, -1));
  2001. }
  2002. const Vector3 right = camera->get_transform().basis.xform(Vector3(1, 0, 0));
  2003. Vector3 up;
  2004. if (navigation_scheme == FREELOOK_PARTIALLY_AXIS_LOCKED || navigation_scheme == FREELOOK_FULLY_AXIS_LOCKED) {
  2005. // Up/down keys will always go up/down regardless of camera pitch.
  2006. up = Vector3(0, 1, 0);
  2007. } else {
  2008. // Up/down keys will be relative to the camera pitch.
  2009. up = camera->get_transform().basis.xform(Vector3(0, 1, 0));
  2010. }
  2011. Vector3 direction;
  2012. if (is_shortcut_pressed("spatial_editor/freelook_left")) {
  2013. direction -= right;
  2014. }
  2015. if (is_shortcut_pressed("spatial_editor/freelook_right")) {
  2016. direction += right;
  2017. }
  2018. if (is_shortcut_pressed("spatial_editor/freelook_forward")) {
  2019. direction += forward;
  2020. }
  2021. if (is_shortcut_pressed("spatial_editor/freelook_backwards")) {
  2022. direction -= forward;
  2023. }
  2024. if (is_shortcut_pressed("spatial_editor/freelook_up")) {
  2025. direction += up;
  2026. }
  2027. if (is_shortcut_pressed("spatial_editor/freelook_down")) {
  2028. direction -= up;
  2029. }
  2030. real_t speed = freelook_speed;
  2031. if (is_shortcut_pressed("spatial_editor/freelook_speed_modifier")) {
  2032. speed *= 3.0;
  2033. }
  2034. if (is_shortcut_pressed("spatial_editor/freelook_slow_modifier")) {
  2035. speed *= 0.333333;
  2036. }
  2037. const Vector3 motion = direction * speed * delta;
  2038. cursor.pos += motion;
  2039. cursor.eye_pos += motion;
  2040. }
  2041. void SpatialEditorViewport::set_message(String p_message, float p_time) {
  2042. message = p_message;
  2043. message_time = p_time;
  2044. }
  2045. void SpatialEditorPlugin::edited_scene_changed() {
  2046. for (uint32_t i = 0; i < SpatialEditor::VIEWPORTS_COUNT; i++) {
  2047. SpatialEditorViewport *viewport = SpatialEditor::get_singleton()->get_editor_viewport(i);
  2048. if (viewport->is_visible()) {
  2049. viewport->notification(Control::NOTIFICATION_VISIBILITY_CHANGED);
  2050. }
  2051. }
  2052. }
  2053. void SpatialEditorViewport::_project_settings_changed() {
  2054. if (viewport) {
  2055. _project_settings_change_pending = false;
  2056. //update shadow atlas if changed
  2057. int shadowmap_size = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/size");
  2058. int atlas_q0 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_0_subdiv");
  2059. int atlas_q1 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_1_subdiv");
  2060. int atlas_q2 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_2_subdiv");
  2061. int atlas_q3 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_3_subdiv");
  2062. viewport->set_shadow_atlas_size(shadowmap_size);
  2063. viewport->set_shadow_atlas_quadrant_subdiv(0, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q0));
  2064. viewport->set_shadow_atlas_quadrant_subdiv(1, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q1));
  2065. viewport->set_shadow_atlas_quadrant_subdiv(2, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q2));
  2066. viewport->set_shadow_atlas_quadrant_subdiv(3, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q3));
  2067. // Update MSAA, FXAA, debanding and HDR if changed.
  2068. int msaa_mode = ProjectSettings::get_singleton()->get("rendering/quality/filters/msaa");
  2069. viewport->set_msaa(Viewport::MSAA(msaa_mode));
  2070. bool use_fxaa = ProjectSettings::get_singleton()->get("rendering/quality/filters/use_fxaa");
  2071. viewport->set_use_fxaa(use_fxaa);
  2072. bool use_debanding = ProjectSettings::get_singleton()->get("rendering/quality/filters/use_debanding");
  2073. viewport->set_use_debanding(use_debanding);
  2074. float sharpen_intensity = ProjectSettings::get_singleton()->get("rendering/quality/filters/sharpen_intensity");
  2075. viewport->set_sharpen_intensity(sharpen_intensity);
  2076. bool hdr = ProjectSettings::get_singleton()->get("rendering/quality/depth/hdr");
  2077. viewport->set_hdr(hdr);
  2078. const bool use_32_bpc_depth = ProjectSettings::get_singleton()->get("rendering/quality/depth/use_32_bpc_depth");
  2079. viewport->set_use_32_bpc_depth(use_32_bpc_depth);
  2080. } else {
  2081. // Could not update immediately, set a pending update.
  2082. // This may never happen, but is included for safety
  2083. _project_settings_change_pending = true;
  2084. }
  2085. }
  2086. void SpatialEditorViewport::_notification(int p_what) {
  2087. if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
  2088. bool visible = is_visible_in_tree();
  2089. set_process(visible);
  2090. if (visible) {
  2091. orthogonal = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL));
  2092. _update_name();
  2093. _update_camera(0);
  2094. } else {
  2095. set_freelook_active(false);
  2096. }
  2097. call_deferred("update_transform_gizmo_view");
  2098. rotation_control->set_visible(EditorSettings::get_singleton()->get("editors/3d/navigation/show_viewport_rotation_gizmo"));
  2099. }
  2100. if (p_what == NOTIFICATION_RESIZED) {
  2101. call_deferred("update_transform_gizmo_view");
  2102. }
  2103. if (p_what == NOTIFICATION_PROCESS) {
  2104. real_t delta = get_process_delta_time();
  2105. if (zoom_indicator_delay > 0) {
  2106. zoom_indicator_delay -= delta;
  2107. if (zoom_indicator_delay <= 0) {
  2108. surface->update();
  2109. zoom_limit_label->hide();
  2110. }
  2111. }
  2112. _update_freelook(delta);
  2113. Node *scene_root = editor->get_scene_tree_dock()->get_editor_data()->get_edited_scene_root();
  2114. if (previewing_cinema && scene_root != nullptr) {
  2115. Camera *cam = scene_root->get_viewport()->get_camera();
  2116. if (cam != nullptr && cam != previewing) {
  2117. //then switch the viewport's camera to the scene's viewport camera
  2118. if (previewing != nullptr) {
  2119. previewing->disconnect("tree_exited", this, "_preview_exited_scene");
  2120. }
  2121. previewing = cam;
  2122. previewing->connect("tree_exited", this, "_preview_exited_scene");
  2123. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), cam->get_camera());
  2124. surface->update();
  2125. }
  2126. }
  2127. _update_camera(delta);
  2128. Map<Node *, Object *> &selection = editor_selection->get_selection();
  2129. bool changed = false;
  2130. bool exist = false;
  2131. for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
  2132. Spatial *sp = Object::cast_to<Spatial>(E->key());
  2133. if (!sp) {
  2134. continue;
  2135. }
  2136. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  2137. if (!se) {
  2138. continue;
  2139. }
  2140. Transform t = sp->get_global_gizmo_transform();
  2141. VisualInstance *vi = Object::cast_to<VisualInstance>(sp);
  2142. AABB new_aabb = vi ? vi->get_aabb() : _calculate_spatial_bounds(sp);
  2143. exist = true;
  2144. if (se->last_xform == t && se->aabb == new_aabb && !se->last_xform_dirty) {
  2145. continue;
  2146. }
  2147. changed = true;
  2148. se->last_xform_dirty = false;
  2149. se->last_xform = t;
  2150. se->aabb = new_aabb;
  2151. Transform t_offset = t;
  2152. // apply AABB scaling before item's global transform
  2153. {
  2154. const Vector3 offset(0.005, 0.005, 0.005);
  2155. Basis aabb_s;
  2156. aabb_s.scale(se->aabb.size + offset);
  2157. t.translate(se->aabb.position - offset / 2);
  2158. t.basis = t.basis * aabb_s;
  2159. }
  2160. {
  2161. const Vector3 offset(0.01, 0.01, 0.01);
  2162. Basis aabb_s;
  2163. aabb_s.scale(se->aabb.size + offset);
  2164. t_offset.translate(se->aabb.position - offset / 2);
  2165. t_offset.basis = t_offset.basis * aabb_s;
  2166. }
  2167. VisualServer::get_singleton()->instance_set_transform(se->sbox_instance, t);
  2168. VisualServer::get_singleton()->instance_set_transform(se->sbox_instance_offset, t_offset);
  2169. VisualServer::get_singleton()->instance_set_transform(se->sbox_instance_xray, t);
  2170. VisualServer::get_singleton()->instance_set_transform(se->sbox_instance_xray_offset, t_offset);
  2171. }
  2172. if (changed || (spatial_editor->is_gizmo_visible() && !exist)) {
  2173. spatial_editor->update_transform_gizmo();
  2174. }
  2175. if (message_time > 0) {
  2176. if (message != last_message) {
  2177. surface->update();
  2178. last_message = message;
  2179. }
  2180. message_time -= get_physics_process_delta_time();
  2181. if (message_time < 0) {
  2182. surface->update();
  2183. }
  2184. }
  2185. if (_project_settings_change_pending) {
  2186. _project_settings_changed();
  2187. }
  2188. bool shrink = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION));
  2189. if (shrink != (viewport_container->get_stretch_shrink() > 1)) {
  2190. viewport_container->set_stretch_shrink(shrink ? 2 : 1);
  2191. }
  2192. bool show_info = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_INFORMATION));
  2193. info_label->set_visible(show_info);
  2194. Camera *current_camera;
  2195. if (previewing) {
  2196. current_camera = previewing;
  2197. } else {
  2198. current_camera = camera;
  2199. }
  2200. if (show_info) {
  2201. const String viewport_size = vformat(String::utf8("%d × %d"), viewport->get_size().x, viewport->get_size().y);
  2202. String text;
  2203. text += "X: " + rtos(current_camera->get_translation().x).pad_decimals(1) + "\n";
  2204. text += "Y: " + rtos(current_camera->get_translation().y).pad_decimals(1) + "\n";
  2205. text += "Z: " + rtos(current_camera->get_translation().z).pad_decimals(1) + "\n";
  2206. text += TTR("Pitch:") + " " + itos(Math::round(current_camera->get_rotation_degrees().x)) + "\n";
  2207. text += TTR("Yaw:") + " " + itos(Math::round(current_camera->get_rotation_degrees().y)) + "\n\n";
  2208. text += TTR("Size:") +
  2209. vformat(
  2210. " %s (%.1fMP)\n",
  2211. viewport_size,
  2212. viewport->get_size().x * viewport->get_size().y * 0.000'001);
  2213. text += TTR("Objects Drawn:") + " " + itos(viewport->get_render_info(Viewport::RENDER_INFO_OBJECTS_IN_FRAME)) + "\n";
  2214. text += TTR("Material Changes:") + " " + itos(viewport->get_render_info(Viewport::RENDER_INFO_MATERIAL_CHANGES_IN_FRAME)) + "\n";
  2215. text += TTR("Shader Changes:") + " " + itos(viewport->get_render_info(Viewport::RENDER_INFO_SHADER_CHANGES_IN_FRAME)) + "\n";
  2216. text += TTR("Surface Changes:") + " " + itos(viewport->get_render_info(Viewport::RENDER_INFO_SURFACE_CHANGES_IN_FRAME)) + "\n";
  2217. text += TTR("Draw Calls:") + " " + itos(viewport->get_render_info(Viewport::RENDER_INFO_DRAW_CALLS_IN_FRAME)) + "\n";
  2218. text += TTR("Vertices:") + " " + itos(viewport->get_render_info(Viewport::RENDER_INFO_VERTICES_IN_FRAME));
  2219. info_label->set_text(text);
  2220. }
  2221. // FPS Counter.
  2222. bool show_fps = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_FPS));
  2223. fps_label->set_visible(show_fps);
  2224. if (show_fps) {
  2225. const float fps = Engine::get_singleton()->get_frames_per_second();
  2226. fps_label->set_text(vformat(TTR("FPS: %d (%s ms)"), fps, rtos(1000.0f / fps).pad_decimals(2)));
  2227. // Middle point is at 60 FPS.
  2228. fps_label->add_color_override(
  2229. "font_color",
  2230. frame_time_gradient->get_color_at_offset(
  2231. Math::range_lerp(fps, 110, 10, 0, 1)));
  2232. }
  2233. bool show_cinema = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW));
  2234. cinema_label->set_visible(show_cinema);
  2235. if (show_cinema) {
  2236. float cinema_half_width = cinema_label->get_size().width / 2.0f;
  2237. cinema_label->set_anchor_and_margin(MARGIN_LEFT, 0.5f, -cinema_half_width);
  2238. }
  2239. if (lock_rotation) {
  2240. float locked_half_width = locked_label->get_size().width / 2.0f;
  2241. locked_label->set_anchor_and_margin(MARGIN_LEFT, 0.5f, -locked_half_width);
  2242. }
  2243. }
  2244. if (p_what == NOTIFICATION_ENTER_TREE) {
  2245. surface->connect("draw", this, "_draw");
  2246. surface->connect("gui_input", this, "_sinput");
  2247. surface->connect("mouse_entered", this, "_surface_mouse_enter");
  2248. surface->connect("mouse_exited", this, "_surface_mouse_exit");
  2249. surface->connect("focus_entered", this, "_surface_focus_enter");
  2250. surface->connect("focus_exited", this, "_surface_focus_exit");
  2251. // Ensure we are up to date with project settings
  2252. _project_settings_changed();
  2253. // Any further changes to project settings get a signal
  2254. ProjectSettings::get_singleton()->connect("project_settings_changed", this, "_project_settings_changed");
  2255. _init_gizmo_instance(index);
  2256. }
  2257. if (p_what == NOTIFICATION_EXIT_TREE) {
  2258. ProjectSettings::get_singleton()->disconnect("project_settings_changed", this, "_project_settings_changed");
  2259. _finish_gizmo_instances();
  2260. }
  2261. if (p_what == NOTIFICATION_THEME_CHANGED) {
  2262. view_menu->set_icon(get_icon("GuiTabMenuHl", "EditorIcons"));
  2263. preview_camera->set_icon(get_icon("Camera", "EditorIcons"));
  2264. view_menu->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2265. view_menu->add_style_override("hover", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2266. view_menu->add_style_override("pressed", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2267. view_menu->add_style_override("focus", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2268. view_menu->add_style_override("disabled", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2269. preview_camera->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2270. preview_camera->add_style_override("hover", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2271. preview_camera->add_style_override("pressed", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2272. preview_camera->add_style_override("focus", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2273. preview_camera->add_style_override("disabled", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2274. info_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2275. fps_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2276. cinema_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2277. locked_label->add_style_override("normal", editor->get_gui_base()->get_stylebox("Information3dViewport", "EditorStyles"));
  2278. frame_time_gradient->set_color(0, get_color("success_color", "Editor"));
  2279. frame_time_gradient->set_color(1, get_color("warning_color", "Editor"));
  2280. frame_time_gradient->set_color(2, get_color("error_color", "Editor"));
  2281. }
  2282. }
  2283. static void draw_indicator_bar(Control &p_surface, real_t p_fill, const Ref<Texture> p_icon, const Ref<Font> p_font, const String &p_text, const Color &p_color) {
  2284. // Adjust bar size from control height
  2285. const Vector2 surface_size = p_surface.get_size();
  2286. const real_t h = surface_size.y / 2.0;
  2287. const real_t y = (surface_size.y - h) / 2.0;
  2288. const Rect2 r(10 * EDSCALE, y, 6 * EDSCALE, h);
  2289. const real_t sy = r.size.y * p_fill;
  2290. // Note: because this bar appears over the viewport, it has to stay readable for any background color
  2291. // Draw both neutral dark and bright colors to account this
  2292. p_surface.draw_rect(r, p_color * Color(1, 1, 1, 0.2));
  2293. 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));
  2294. p_surface.draw_rect(r.grow(1), Color(0, 0, 0, 0.7), false, Math::round(EDSCALE));
  2295. const Vector2 icon_size = p_icon->get_size();
  2296. const Vector2 icon_pos = Vector2(r.position.x - (icon_size.x - r.size.x) / 2, r.position.y + r.size.y + 2 * EDSCALE);
  2297. p_surface.draw_texture(p_icon, icon_pos, p_color);
  2298. // Draw a shadow for the text to make it easier to read.
  2299. p_surface.draw_string(p_font, Vector2(icon_pos.x + EDSCALE, icon_pos.y + icon_size.y + 17 * EDSCALE), p_text, Color(0, 0, 0));
  2300. // Draw text below the bar (for speed/zoom information).
  2301. p_surface.draw_string(p_font, Vector2(icon_pos.x, icon_pos.y + icon_size.y + 16 * EDSCALE), p_text, p_color);
  2302. }
  2303. void SpatialEditorViewport::_draw() {
  2304. EditorPluginList *over_plugin_list = EditorNode::get_singleton()->get_editor_plugins_over();
  2305. if (!over_plugin_list->empty()) {
  2306. over_plugin_list->forward_spatial_draw_over_viewport(surface);
  2307. }
  2308. EditorPluginList *force_over_plugin_list = editor->get_editor_plugins_force_over();
  2309. if (!force_over_plugin_list->empty()) {
  2310. force_over_plugin_list->forward_spatial_force_draw_over_viewport(surface);
  2311. }
  2312. if (surface->has_focus()) {
  2313. Size2 size = surface->get_size();
  2314. Rect2 r = Rect2(Point2(), size);
  2315. get_stylebox("Focus", "EditorStyles")->draw(surface->get_canvas_item(), r);
  2316. }
  2317. if (cursor.region_select) {
  2318. const Rect2 selection_rect = Rect2(cursor.region_begin, cursor.region_end - cursor.region_begin);
  2319. surface->draw_rect(
  2320. selection_rect,
  2321. get_color("box_selection_fill_color", "Editor"));
  2322. surface->draw_rect(
  2323. selection_rect,
  2324. get_color("box_selection_stroke_color", "Editor"),
  2325. false,
  2326. Math::round(EDSCALE));
  2327. }
  2328. RID ci = surface->get_canvas_item();
  2329. if (message_time > 0) {
  2330. Ref<Font> font = get_font("font", "Label");
  2331. Point2 msgpos = Point2(5, get_size().y - 20);
  2332. font->draw(ci, msgpos + Point2(1, 1), message, Color(0, 0, 0, 0.8));
  2333. font->draw(ci, msgpos + Point2(-1, -1), message, Color(0, 0, 0, 0.8));
  2334. font->draw(ci, msgpos, message, Color(1, 1, 1, 1));
  2335. }
  2336. if (_edit.mode == TRANSFORM_ROTATE) {
  2337. Point2 center = _point_to_screen(_edit.center);
  2338. Color handle_color;
  2339. switch (_edit.plane) {
  2340. case TRANSFORM_X_AXIS:
  2341. handle_color = get_color("axis_x_color", "Editor");
  2342. break;
  2343. case TRANSFORM_Y_AXIS:
  2344. handle_color = get_color("axis_y_color", "Editor");
  2345. break;
  2346. case TRANSFORM_Z_AXIS:
  2347. handle_color = get_color("axis_z_color", "Editor");
  2348. break;
  2349. default:
  2350. handle_color = get_color("accent_color", "Editor");
  2351. break;
  2352. }
  2353. handle_color = handle_color.from_hsv(handle_color.get_h(), 0.25, 1.0, 1);
  2354. VisualServer::get_singleton()->canvas_item_add_line(
  2355. ci,
  2356. _edit.mouse_pos,
  2357. center,
  2358. handle_color,
  2359. Math::round(2 * EDSCALE),
  2360. true);
  2361. }
  2362. if (previewing) {
  2363. Size2 ss = Size2(ProjectSettings::get_singleton()->get("display/window/size/width"), ProjectSettings::get_singleton()->get("display/window/size/height"));
  2364. float aspect = ss.aspect();
  2365. Size2 s = get_size();
  2366. Rect2 draw_rect;
  2367. switch (previewing->get_keep_aspect_mode()) {
  2368. case Camera::KEEP_WIDTH: {
  2369. draw_rect.size = Size2(s.width, s.width / aspect);
  2370. draw_rect.position.x = 0;
  2371. draw_rect.position.y = (s.height - draw_rect.size.y) * 0.5;
  2372. } break;
  2373. case Camera::KEEP_HEIGHT: {
  2374. draw_rect.size = Size2(s.height * aspect, s.height);
  2375. draw_rect.position.y = 0;
  2376. draw_rect.position.x = (s.width - draw_rect.size.x) * 0.5;
  2377. } break;
  2378. }
  2379. draw_rect = Rect2(Vector2(), s).clip(draw_rect);
  2380. surface->draw_rect(draw_rect, Color(0.6, 0.6, 0.1, 0.5), false, Math::round(2 * EDSCALE));
  2381. } else {
  2382. if (zoom_indicator_delay > 0.0) {
  2383. if (is_freelook_active()) {
  2384. // Show speed
  2385. real_t min_speed = MAX(camera->get_znear() * 4, ZOOM_FREELOOK_MIN);
  2386. real_t max_speed = MIN(camera->get_zfar() / 2, ZOOM_FREELOOK_MAX);
  2387. real_t scale_length = (max_speed - min_speed);
  2388. if (!Math::is_zero_approx(scale_length)) {
  2389. real_t logscale_t = 1.0 - Math::log(1 + freelook_speed - min_speed) / Math::log(1 + scale_length);
  2390. // Display the freelook speed to help the user get a better sense of scale.
  2391. const int precision = freelook_speed < 1.0 ? 2 : 1;
  2392. draw_indicator_bar(
  2393. *surface,
  2394. 1.0 - logscale_t,
  2395. get_icon("ViewportSpeed", "EditorIcons"),
  2396. get_font("font", "Label"),
  2397. vformat("%s u/s", String::num(freelook_speed).pad_decimals(precision)),
  2398. Color(1.0, 0.95, 0.7));
  2399. }
  2400. } else {
  2401. // Show zoom
  2402. zoom_limit_label->set_visible(zoom_failed_attempts_count > 15);
  2403. real_t min_distance = MAX(camera->get_znear() * 4, ZOOM_FREELOOK_MIN);
  2404. real_t max_distance = MIN(camera->get_zfar() / 2, ZOOM_FREELOOK_MAX);
  2405. real_t scale_length = (max_distance - min_distance);
  2406. if (!Math::is_zero_approx(scale_length)) {
  2407. real_t logscale_t = 1.0 - Math::log(1 + cursor.distance - min_distance) / Math::log(1 + scale_length);
  2408. // Display the zoom center distance to help the user get a better sense of scale.
  2409. const int precision = cursor.distance < 1.0 ? 2 : 1;
  2410. draw_indicator_bar(
  2411. *surface,
  2412. logscale_t,
  2413. get_icon("ViewportZoom", "EditorIcons"),
  2414. get_font("font", "Label"),
  2415. vformat("%s u", String::num(cursor.distance).pad_decimals(precision)),
  2416. Color(0.7, 0.95, 1.0));
  2417. }
  2418. }
  2419. }
  2420. }
  2421. }
  2422. void SpatialEditorViewport::_menu_option(int p_option) {
  2423. switch (p_option) {
  2424. case VIEW_TOP: {
  2425. cursor.y_rot = 0;
  2426. cursor.x_rot = Math_PI / 2.0;
  2427. set_message(TTR("Top View."), 2);
  2428. view_type = VIEW_TYPE_TOP;
  2429. _set_auto_orthogonal();
  2430. _update_name();
  2431. } break;
  2432. case VIEW_BOTTOM: {
  2433. cursor.y_rot = 0;
  2434. cursor.x_rot = -Math_PI / 2.0;
  2435. set_message(TTR("Bottom View."), 2);
  2436. view_type = VIEW_TYPE_BOTTOM;
  2437. _set_auto_orthogonal();
  2438. _update_name();
  2439. } break;
  2440. case VIEW_LEFT: {
  2441. cursor.x_rot = 0;
  2442. cursor.y_rot = Math_PI / 2.0;
  2443. set_message(TTR("Left View."), 2);
  2444. view_type = VIEW_TYPE_LEFT;
  2445. _set_auto_orthogonal();
  2446. _update_name();
  2447. } break;
  2448. case VIEW_RIGHT: {
  2449. cursor.x_rot = 0;
  2450. cursor.y_rot = -Math_PI / 2.0;
  2451. set_message(TTR("Right View."), 2);
  2452. view_type = VIEW_TYPE_RIGHT;
  2453. _set_auto_orthogonal();
  2454. _update_name();
  2455. } break;
  2456. case VIEW_FRONT: {
  2457. cursor.x_rot = 0;
  2458. cursor.y_rot = Math_PI;
  2459. set_message(TTR("Front View."), 2);
  2460. view_type = VIEW_TYPE_FRONT;
  2461. _set_auto_orthogonal();
  2462. _update_name();
  2463. } break;
  2464. case VIEW_REAR: {
  2465. cursor.x_rot = 0;
  2466. cursor.y_rot = 0;
  2467. set_message(TTR("Rear View."), 2);
  2468. view_type = VIEW_TYPE_REAR;
  2469. _set_auto_orthogonal();
  2470. _update_name();
  2471. } break;
  2472. case VIEW_CENTER_TO_ORIGIN: {
  2473. cursor.pos = Vector3(0, 0, 0);
  2474. } break;
  2475. case VIEW_CENTER_TO_SELECTION: {
  2476. focus_selection();
  2477. } break;
  2478. case VIEW_ALIGN_TRANSFORM_WITH_VIEW: {
  2479. if (!get_selected_count()) {
  2480. break;
  2481. }
  2482. Transform camera_transform = camera->get_global_transform();
  2483. List<Node *> &selection = editor_selection->get_selected_node_list();
  2484. undo_redo->create_action(TTR("Align Transform with View"));
  2485. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  2486. Spatial *sp = Object::cast_to<Spatial>(E->get());
  2487. if (!sp) {
  2488. continue;
  2489. }
  2490. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  2491. if (!se) {
  2492. continue;
  2493. }
  2494. Transform xform;
  2495. if (orthogonal) {
  2496. xform = sp->get_global_transform();
  2497. xform.basis.set_euler(camera_transform.basis.get_euler());
  2498. } else {
  2499. xform = camera_transform;
  2500. xform.scale_basis(sp->get_scale());
  2501. }
  2502. undo_redo->add_do_method(sp, "set_global_transform", xform);
  2503. undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
  2504. }
  2505. undo_redo->commit_action();
  2506. } break;
  2507. case VIEW_ALIGN_ROTATION_WITH_VIEW: {
  2508. if (!get_selected_count()) {
  2509. break;
  2510. }
  2511. Transform camera_transform = camera->get_global_transform();
  2512. List<Node *> &selection = editor_selection->get_selected_node_list();
  2513. undo_redo->create_action(TTR("Align Rotation with View"));
  2514. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  2515. Spatial *sp = Object::cast_to<Spatial>(E->get());
  2516. if (!sp) {
  2517. continue;
  2518. }
  2519. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  2520. if (!se) {
  2521. continue;
  2522. }
  2523. undo_redo->add_do_method(sp, "set_rotation", camera_transform.basis.get_rotation());
  2524. undo_redo->add_undo_method(sp, "set_rotation", sp->get_rotation());
  2525. }
  2526. undo_redo->commit_action();
  2527. } break;
  2528. case VIEW_ENVIRONMENT: {
  2529. int idx = view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT);
  2530. bool current = view_menu->get_popup()->is_item_checked(idx);
  2531. current = !current;
  2532. if (current) {
  2533. camera->set_environment(RES());
  2534. } else {
  2535. camera->set_environment(SpatialEditor::get_singleton()->get_viewport_environment());
  2536. }
  2537. view_menu->get_popup()->set_item_checked(idx, current);
  2538. } break;
  2539. case VIEW_PERSPECTIVE: {
  2540. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
  2541. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), false);
  2542. orthogonal = false;
  2543. auto_orthogonal = false;
  2544. call_deferred("update_transform_gizmo_view");
  2545. _update_name();
  2546. } break;
  2547. case VIEW_ORTHOGONAL: {
  2548. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), false);
  2549. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), true);
  2550. orthogonal = true;
  2551. auto_orthogonal = false;
  2552. call_deferred("update_transform_gizmo_view");
  2553. _update_name();
  2554. } break;
  2555. case VIEW_AUTO_ORTHOGONAL: {
  2556. int idx = view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL);
  2557. bool current = view_menu->get_popup()->is_item_checked(idx);
  2558. current = !current;
  2559. view_menu->get_popup()->set_item_checked(idx, current);
  2560. if (auto_orthogonal) {
  2561. auto_orthogonal = false;
  2562. _update_name();
  2563. }
  2564. } break;
  2565. case VIEW_LOCK_ROTATION: {
  2566. int idx = view_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
  2567. bool current = view_menu->get_popup()->is_item_checked(idx);
  2568. lock_rotation = !current;
  2569. view_menu->get_popup()->set_item_checked(idx, !current);
  2570. if (lock_rotation) {
  2571. locked_label->show();
  2572. } else {
  2573. locked_label->hide();
  2574. }
  2575. } break;
  2576. case VIEW_AUDIO_LISTENER: {
  2577. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
  2578. bool current = view_menu->get_popup()->is_item_checked(idx);
  2579. current = !current;
  2580. viewport->set_as_audio_listener(current);
  2581. view_menu->get_popup()->set_item_checked(idx, current);
  2582. } break;
  2583. case VIEW_AUDIO_DOPPLER: {
  2584. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
  2585. bool current = view_menu->get_popup()->is_item_checked(idx);
  2586. current = !current;
  2587. camera->set_doppler_tracking(current ? Camera::DOPPLER_TRACKING_IDLE_STEP : Camera::DOPPLER_TRACKING_DISABLED);
  2588. view_menu->get_popup()->set_item_checked(idx, current);
  2589. } break;
  2590. case VIEW_CINEMATIC_PREVIEW: {
  2591. int idx = view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
  2592. bool current = view_menu->get_popup()->is_item_checked(idx);
  2593. current = !current;
  2594. view_menu->get_popup()->set_item_checked(idx, current);
  2595. previewing_cinema = true;
  2596. _toggle_cinema_preview(current);
  2597. if (current) {
  2598. preview_camera->hide();
  2599. } else {
  2600. if (previewing != nullptr) {
  2601. preview_camera->show();
  2602. }
  2603. }
  2604. } break;
  2605. case VIEW_GIZMOS: {
  2606. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  2607. bool current = view_menu->get_popup()->is_item_checked(idx);
  2608. current = !current;
  2609. uint32_t layers = ((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + index)) | (1 << GIZMO_GRID_LAYER) | (1 << MISC_TOOL_LAYER);
  2610. if (current) {
  2611. layers |= (1 << GIZMO_EDIT_LAYER);
  2612. }
  2613. camera->set_cull_mask(layers);
  2614. view_menu->get_popup()->set_item_checked(idx, current);
  2615. } break;
  2616. case VIEW_HALF_RESOLUTION: {
  2617. int idx = view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
  2618. bool current = view_menu->get_popup()->is_item_checked(idx);
  2619. current = !current;
  2620. view_menu->get_popup()->set_item_checked(idx, current);
  2621. } break;
  2622. case VIEW_INFORMATION: {
  2623. int idx = view_menu->get_popup()->get_item_index(VIEW_INFORMATION);
  2624. bool current = view_menu->get_popup()->is_item_checked(idx);
  2625. view_menu->get_popup()->set_item_checked(idx, !current);
  2626. } break;
  2627. case VIEW_FPS: {
  2628. int idx = view_menu->get_popup()->get_item_index(VIEW_FPS);
  2629. bool current = view_menu->get_popup()->is_item_checked(idx);
  2630. view_menu->get_popup()->set_item_checked(idx, !current);
  2631. } break;
  2632. case VIEW_DISPLAY_NORMAL: {
  2633. viewport->set_debug_draw(Viewport::DEBUG_DRAW_DISABLED);
  2634. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), true);
  2635. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), false);
  2636. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), false);
  2637. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), false);
  2638. } break;
  2639. case VIEW_DISPLAY_WIREFRAME: {
  2640. viewport->set_debug_draw(Viewport::DEBUG_DRAW_WIREFRAME);
  2641. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), false);
  2642. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), true);
  2643. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), false);
  2644. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), false);
  2645. } break;
  2646. case VIEW_DISPLAY_OVERDRAW: {
  2647. viewport->set_debug_draw(Viewport::DEBUG_DRAW_OVERDRAW);
  2648. VisualServer::get_singleton()->scenario_set_debug(get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_OVERDRAW);
  2649. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), false);
  2650. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), false);
  2651. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), true);
  2652. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), false);
  2653. } break;
  2654. case VIEW_DISPLAY_SHADELESS: {
  2655. viewport->set_debug_draw(Viewport::DEBUG_DRAW_UNSHADED);
  2656. VisualServer::get_singleton()->scenario_set_debug(get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_SHADELESS);
  2657. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), false);
  2658. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME), false);
  2659. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW), false);
  2660. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS), true);
  2661. } break;
  2662. }
  2663. }
  2664. void SpatialEditorViewport::_set_auto_orthogonal() {
  2665. if (!orthogonal && view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL))) {
  2666. _menu_option(VIEW_ORTHOGONAL);
  2667. auto_orthogonal = true;
  2668. }
  2669. }
  2670. void SpatialEditorViewport::_preview_exited_scene() {
  2671. preview_camera->disconnect("toggled", this, "_toggle_camera_preview");
  2672. preview_camera->set_pressed(false);
  2673. _toggle_camera_preview(false);
  2674. preview_camera->connect("toggled", this, "_toggle_camera_preview");
  2675. view_menu->show();
  2676. }
  2677. void SpatialEditorViewport::_init_gizmo_instance(int p_idx) {
  2678. uint32_t layer = 1 << (GIZMO_BASE_LAYER + p_idx);
  2679. for (int i = 0; i < 3; i++) {
  2680. move_gizmo_instance[i] = RID_PRIME(VS::get_singleton()->instance_create());
  2681. VS::get_singleton()->instance_set_base(move_gizmo_instance[i], spatial_editor->get_move_gizmo(i)->get_rid());
  2682. VS::get_singleton()->instance_set_scenario(move_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2683. VS::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  2684. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2685. VS::get_singleton()->instance_set_layer_mask(move_gizmo_instance[i], layer);
  2686. VS::get_singleton()->instance_set_portal_mode(move_gizmo_instance[i], VisualServer::INSTANCE_PORTAL_MODE_GLOBAL);
  2687. move_plane_gizmo_instance[i] = RID_PRIME(VS::get_singleton()->instance_create());
  2688. VS::get_singleton()->instance_set_base(move_plane_gizmo_instance[i], spatial_editor->get_move_plane_gizmo(i)->get_rid());
  2689. VS::get_singleton()->instance_set_scenario(move_plane_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2690. VS::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  2691. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_plane_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2692. VS::get_singleton()->instance_set_layer_mask(move_plane_gizmo_instance[i], layer);
  2693. VS::get_singleton()->instance_set_portal_mode(move_plane_gizmo_instance[i], VisualServer::INSTANCE_PORTAL_MODE_GLOBAL);
  2694. rotate_gizmo_instance[i] = RID_PRIME(VS::get_singleton()->instance_create());
  2695. VS::get_singleton()->instance_set_base(rotate_gizmo_instance[i], spatial_editor->get_rotate_gizmo(i)->get_rid());
  2696. VS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2697. VS::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  2698. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(rotate_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2699. VS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[i], layer);
  2700. VS::get_singleton()->instance_set_portal_mode(rotate_gizmo_instance[i], VisualServer::INSTANCE_PORTAL_MODE_GLOBAL);
  2701. scale_gizmo_instance[i] = RID_PRIME(VS::get_singleton()->instance_create());
  2702. VS::get_singleton()->instance_set_base(scale_gizmo_instance[i], spatial_editor->get_scale_gizmo(i)->get_rid());
  2703. VS::get_singleton()->instance_set_scenario(scale_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2704. VS::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  2705. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2706. VS::get_singleton()->instance_set_layer_mask(scale_gizmo_instance[i], layer);
  2707. VS::get_singleton()->instance_set_portal_mode(scale_gizmo_instance[i], VisualServer::INSTANCE_PORTAL_MODE_GLOBAL);
  2708. scale_plane_gizmo_instance[i] = RID_PRIME(VS::get_singleton()->instance_create());
  2709. VS::get_singleton()->instance_set_base(scale_plane_gizmo_instance[i], spatial_editor->get_scale_plane_gizmo(i)->get_rid());
  2710. VS::get_singleton()->instance_set_scenario(scale_plane_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
  2711. VS::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  2712. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_plane_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
  2713. VS::get_singleton()->instance_set_layer_mask(scale_plane_gizmo_instance[i], layer);
  2714. VS::get_singleton()->instance_set_portal_mode(scale_plane_gizmo_instance[i], VisualServer::INSTANCE_PORTAL_MODE_GLOBAL);
  2715. }
  2716. // Rotation white outline
  2717. rotate_gizmo_instance[3] = RID_PRIME(VS::get_singleton()->instance_create());
  2718. VS::get_singleton()->instance_set_base(rotate_gizmo_instance[3], spatial_editor->get_rotate_gizmo(3)->get_rid());
  2719. VS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[3], get_tree()->get_root()->get_world()->get_scenario());
  2720. VS::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
  2721. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(rotate_gizmo_instance[3], VS::SHADOW_CASTING_SETTING_OFF);
  2722. VS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[3], layer);
  2723. }
  2724. void SpatialEditorViewport::_finish_gizmo_instances() {
  2725. for (int i = 0; i < 3; i++) {
  2726. if (move_gizmo_instance[i].is_valid()) {
  2727. VS::get_singleton()->free(move_gizmo_instance[i]);
  2728. move_gizmo_instance[i] = RID();
  2729. }
  2730. if (move_plane_gizmo_instance[i].is_valid()) {
  2731. VS::get_singleton()->free(move_plane_gizmo_instance[i]);
  2732. move_plane_gizmo_instance[i] = RID();
  2733. }
  2734. if (rotate_gizmo_instance[i].is_valid()) {
  2735. VS::get_singleton()->free(rotate_gizmo_instance[i]);
  2736. rotate_gizmo_instance[i] = RID();
  2737. }
  2738. if (scale_gizmo_instance[i].is_valid()) {
  2739. VS::get_singleton()->free(scale_gizmo_instance[i]);
  2740. scale_gizmo_instance[i] = RID();
  2741. }
  2742. if (scale_plane_gizmo_instance[i].is_valid()) {
  2743. VS::get_singleton()->free(scale_plane_gizmo_instance[i]);
  2744. scale_plane_gizmo_instance[i] = RID();
  2745. }
  2746. }
  2747. // Rotation white outline. All of the arrays above have 3 elements, this has 4.
  2748. if (rotate_gizmo_instance[3].is_valid()) {
  2749. VS::get_singleton()->free(rotate_gizmo_instance[3]);
  2750. rotate_gizmo_instance[3] = RID();
  2751. }
  2752. }
  2753. void SpatialEditorViewport::_toggle_camera_preview(bool p_activate) {
  2754. ERR_FAIL_COND(p_activate && !preview);
  2755. ERR_FAIL_COND(!p_activate && !previewing);
  2756. rotation_control->set_visible(!p_activate);
  2757. if (!p_activate) {
  2758. previewing->disconnect("tree_exiting", this, "_preview_exited_scene");
  2759. previewing = nullptr;
  2760. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
  2761. if (!preview) {
  2762. preview_camera->hide();
  2763. }
  2764. surface->update();
  2765. } else {
  2766. previewing = preview;
  2767. previewing->connect("tree_exiting", this, "_preview_exited_scene");
  2768. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), preview->get_camera()); //replace
  2769. surface->update();
  2770. }
  2771. }
  2772. void SpatialEditorViewport::_toggle_cinema_preview(bool p_activate) {
  2773. previewing_cinema = p_activate;
  2774. rotation_control->set_visible(!p_activate);
  2775. if (!previewing_cinema) {
  2776. if (previewing != nullptr) {
  2777. previewing->disconnect("tree_exited", this, "_preview_exited_scene");
  2778. }
  2779. previewing = nullptr;
  2780. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
  2781. preview_camera->set_pressed(false);
  2782. if (!preview) {
  2783. preview_camera->hide();
  2784. } else {
  2785. preview_camera->show();
  2786. }
  2787. view_menu->show();
  2788. surface->update();
  2789. }
  2790. }
  2791. void SpatialEditorViewport::_selection_result_pressed(int p_result) {
  2792. if (selection_results.size() <= p_result) {
  2793. return;
  2794. }
  2795. clicked = selection_results[p_result].item->get_instance_id();
  2796. if (clicked) {
  2797. _select_clicked(clicked_wants_append, true, spatial_editor->get_tool_mode() != SpatialEditor::TOOL_MODE_LIST_SELECT);
  2798. clicked = 0;
  2799. }
  2800. }
  2801. void SpatialEditorViewport::_selection_menu_hide() {
  2802. selection_results.clear();
  2803. selection_menu->clear();
  2804. selection_menu->set_size(Vector2(0, 0));
  2805. }
  2806. void SpatialEditorViewport::set_can_preview(Camera *p_preview) {
  2807. preview = p_preview;
  2808. if (!preview_camera->is_pressed() && !previewing_cinema) {
  2809. preview_camera->set_visible(p_preview);
  2810. }
  2811. }
  2812. void SpatialEditorViewport::update_transform_gizmo_view() {
  2813. if (!is_visible_in_tree()) {
  2814. return;
  2815. }
  2816. Transform xform = spatial_editor->get_gizmo_transform();
  2817. Transform camera_xform = camera->get_transform();
  2818. if (xform.origin.distance_squared_to(camera_xform.origin) < 0.01) {
  2819. for (int i = 0; i < 3; i++) {
  2820. VisualServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  2821. VisualServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  2822. VisualServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  2823. VisualServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  2824. VisualServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  2825. }
  2826. // Rotation white outline
  2827. VisualServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
  2828. return;
  2829. }
  2830. Vector3 camz = -camera_xform.get_basis().get_axis(2).normalized();
  2831. Vector3 camy = -camera_xform.get_basis().get_axis(1).normalized();
  2832. Plane p(camera_xform.origin, camz);
  2833. float gizmo_d = MAX(Math::abs(p.distance_to(xform.origin)), CMP_EPSILON);
  2834. float d0 = camera->unproject_position(camera_xform.origin + camz * gizmo_d).y;
  2835. float d1 = camera->unproject_position(camera_xform.origin + camz * gizmo_d + camy).y;
  2836. float dd = Math::abs(d0 - d1);
  2837. if (dd == 0) {
  2838. dd = 0.0001;
  2839. }
  2840. float gizmo_size = EditorSettings::get_singleton()->get("editors/3d/manipulator_gizmo_size");
  2841. // At low viewport heights, multiply the gizmo scale based on the viewport height.
  2842. // This prevents the gizmo from growing very large and going outside the viewport.
  2843. const int viewport_base_height = 400 * MAX(1, EDSCALE);
  2844. gizmo_scale =
  2845. (gizmo_size / Math::abs(dd)) * MAX(1, EDSCALE) *
  2846. MIN(viewport_base_height, viewport_container->get_size().height) / viewport_base_height /
  2847. viewport_container->get_stretch_shrink();
  2848. Vector3 scale = Vector3(1, 1, 1) * gizmo_scale;
  2849. xform.basis.scale(scale);
  2850. for (int i = 0; i < 3; i++) {
  2851. VisualServer::get_singleton()->instance_set_transform(move_gizmo_instance[i], xform);
  2852. VisualServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_MOVE));
  2853. VisualServer::get_singleton()->instance_set_transform(move_plane_gizmo_instance[i], xform);
  2854. VisualServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_MOVE));
  2855. VisualServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[i], xform);
  2856. VisualServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_ROTATE));
  2857. VisualServer::get_singleton()->instance_set_transform(scale_gizmo_instance[i], xform);
  2858. VisualServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SCALE));
  2859. VisualServer::get_singleton()->instance_set_transform(scale_plane_gizmo_instance[i], xform);
  2860. VisualServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SCALE));
  2861. }
  2862. // Rotation white outline
  2863. VisualServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[3], xform);
  2864. VisualServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_ROTATE));
  2865. }
  2866. void SpatialEditorViewport::set_state(const Dictionary &p_state) {
  2867. if (p_state.has("position")) {
  2868. cursor.pos = p_state["position"];
  2869. }
  2870. if (p_state.has("x_rotation")) {
  2871. cursor.x_rot = p_state["x_rotation"];
  2872. }
  2873. if (p_state.has("y_rotation")) {
  2874. cursor.y_rot = p_state["y_rotation"];
  2875. }
  2876. if (p_state.has("distance")) {
  2877. cursor.distance = p_state["distance"];
  2878. }
  2879. if (p_state.has("use_orthogonal")) {
  2880. bool orth = p_state["use_orthogonal"];
  2881. if (orth) {
  2882. _menu_option(VIEW_ORTHOGONAL);
  2883. } else {
  2884. _menu_option(VIEW_PERSPECTIVE);
  2885. }
  2886. }
  2887. if (p_state.has("view_type")) {
  2888. view_type = ViewType(p_state["view_type"].operator int());
  2889. _update_name();
  2890. }
  2891. if (p_state.has("auto_orthogonal")) {
  2892. auto_orthogonal = p_state["auto_orthogonal"];
  2893. _update_name();
  2894. }
  2895. if (p_state.has("auto_orthogonal_enabled")) {
  2896. bool enabled = p_state["auto_orthogonal_enabled"];
  2897. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL), enabled);
  2898. }
  2899. if (p_state.has("display_mode")) {
  2900. int display = p_state["display_mode"];
  2901. int idx = view_menu->get_popup()->get_item_index(display);
  2902. if (!view_menu->get_popup()->is_item_checked(idx)) {
  2903. _menu_option(display);
  2904. }
  2905. }
  2906. if (p_state.has("lock_rotation")) {
  2907. lock_rotation = p_state["lock_rotation"];
  2908. int idx = view_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
  2909. view_menu->get_popup()->set_item_checked(idx, lock_rotation);
  2910. }
  2911. if (p_state.has("use_environment")) {
  2912. bool env = p_state["use_environment"];
  2913. if (env != camera->get_environment().is_valid()) {
  2914. _menu_option(VIEW_ENVIRONMENT);
  2915. }
  2916. }
  2917. if (p_state.has("listener")) {
  2918. bool listener = p_state["listener"];
  2919. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
  2920. viewport->set_as_audio_listener(listener);
  2921. view_menu->get_popup()->set_item_checked(idx, listener);
  2922. }
  2923. if (p_state.has("doppler")) {
  2924. bool doppler = p_state["doppler"];
  2925. int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
  2926. camera->set_doppler_tracking(doppler ? Camera::DOPPLER_TRACKING_IDLE_STEP : Camera::DOPPLER_TRACKING_DISABLED);
  2927. view_menu->get_popup()->set_item_checked(idx, doppler);
  2928. }
  2929. if (p_state.has("gizmos")) {
  2930. bool gizmos = p_state["gizmos"];
  2931. int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  2932. if (view_menu->get_popup()->is_item_checked(idx) != gizmos) {
  2933. _menu_option(VIEW_GIZMOS);
  2934. }
  2935. }
  2936. if (p_state.has("information")) {
  2937. bool information = p_state["information"];
  2938. int idx = view_menu->get_popup()->get_item_index(VIEW_INFORMATION);
  2939. if (view_menu->get_popup()->is_item_checked(idx) != information) {
  2940. _menu_option(VIEW_INFORMATION);
  2941. }
  2942. }
  2943. if (p_state.has("fps")) {
  2944. bool fps = p_state["fps"];
  2945. int idx = view_menu->get_popup()->get_item_index(VIEW_FPS);
  2946. if (view_menu->get_popup()->is_item_checked(idx) != fps) {
  2947. _menu_option(VIEW_FPS);
  2948. }
  2949. }
  2950. if (p_state.has("half_res")) {
  2951. bool half_res = p_state["half_res"];
  2952. int idx = view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
  2953. view_menu->get_popup()->set_item_checked(idx, half_res);
  2954. }
  2955. if (p_state.has("cinematic_preview")) {
  2956. previewing_cinema = p_state["cinematic_preview"];
  2957. int idx = view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
  2958. view_menu->get_popup()->set_item_checked(idx, previewing_cinema);
  2959. }
  2960. if (preview_camera->is_connected("toggled", this, "_toggle_camera_preview")) {
  2961. preview_camera->disconnect("toggled", this, "_toggle_camera_preview");
  2962. }
  2963. if (p_state.has("previewing")) {
  2964. Node *pv = EditorNode::get_singleton()->get_edited_scene()->get_node(p_state["previewing"]);
  2965. if (Object::cast_to<Camera>(pv)) {
  2966. previewing = Object::cast_to<Camera>(pv);
  2967. previewing->connect("tree_exiting", this, "_preview_exited_scene");
  2968. VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), previewing->get_camera()); //replace
  2969. surface->update();
  2970. preview_camera->set_pressed(true);
  2971. preview_camera->show();
  2972. }
  2973. }
  2974. preview_camera->connect("toggled", this, "_toggle_camera_preview");
  2975. }
  2976. Dictionary SpatialEditorViewport::get_state() const {
  2977. Dictionary d;
  2978. d["position"] = cursor.pos;
  2979. d["x_rotation"] = cursor.x_rot;
  2980. d["y_rotation"] = cursor.y_rot;
  2981. d["distance"] = cursor.distance;
  2982. d["use_environment"] = camera->get_environment().is_valid();
  2983. d["use_orthogonal"] = camera->get_projection() == Camera::PROJECTION_ORTHOGONAL;
  2984. d["view_type"] = view_type;
  2985. d["auto_orthogonal"] = auto_orthogonal;
  2986. d["auto_orthogonal_enabled"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL));
  2987. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL))) {
  2988. d["display_mode"] = VIEW_DISPLAY_NORMAL;
  2989. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME))) {
  2990. d["display_mode"] = VIEW_DISPLAY_WIREFRAME;
  2991. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW))) {
  2992. d["display_mode"] = VIEW_DISPLAY_OVERDRAW;
  2993. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS))) {
  2994. d["display_mode"] = VIEW_DISPLAY_SHADELESS;
  2995. }
  2996. d["listener"] = viewport->is_audio_listener();
  2997. d["doppler"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER));
  2998. d["gizmos"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_GIZMOS));
  2999. d["information"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_INFORMATION));
  3000. d["fps"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_FPS));
  3001. d["half_res"] = viewport_container->get_stretch_shrink() > 1;
  3002. d["cinematic_preview"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW));
  3003. if (previewing) {
  3004. d["previewing"] = EditorNode::get_singleton()->get_edited_scene()->get_path_to(previewing);
  3005. }
  3006. if (lock_rotation) {
  3007. d["lock_rotation"] = lock_rotation;
  3008. }
  3009. return d;
  3010. }
  3011. void SpatialEditorViewport::_bind_methods() {
  3012. ClassDB::bind_method(D_METHOD("_draw"), &SpatialEditorViewport::_draw);
  3013. ClassDB::bind_method(D_METHOD("_surface_mouse_enter"), &SpatialEditorViewport::_surface_mouse_enter);
  3014. ClassDB::bind_method(D_METHOD("_surface_mouse_exit"), &SpatialEditorViewport::_surface_mouse_exit);
  3015. ClassDB::bind_method(D_METHOD("_surface_focus_enter"), &SpatialEditorViewport::_surface_focus_enter);
  3016. ClassDB::bind_method(D_METHOD("_surface_focus_exit"), &SpatialEditorViewport::_surface_focus_exit);
  3017. ClassDB::bind_method(D_METHOD("_sinput"), &SpatialEditorViewport::_sinput);
  3018. ClassDB::bind_method(D_METHOD("_menu_option"), &SpatialEditorViewport::_menu_option);
  3019. ClassDB::bind_method(D_METHOD("_toggle_camera_preview"), &SpatialEditorViewport::_toggle_camera_preview);
  3020. ClassDB::bind_method(D_METHOD("_preview_exited_scene"), &SpatialEditorViewport::_preview_exited_scene);
  3021. ClassDB::bind_method(D_METHOD("_view_settings_confirmed"), &SpatialEditorViewport::_view_settings_confirmed);
  3022. ClassDB::bind_method(D_METHOD("_update_camera"), &SpatialEditorViewport::_update_camera);
  3023. ClassDB::bind_method(D_METHOD("update_transform_gizmo_view"), &SpatialEditorViewport::update_transform_gizmo_view);
  3024. ClassDB::bind_method(D_METHOD("_selection_result_pressed"), &SpatialEditorViewport::_selection_result_pressed);
  3025. ClassDB::bind_method(D_METHOD("_selection_menu_hide"), &SpatialEditorViewport::_selection_menu_hide);
  3026. ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &SpatialEditorViewport::can_drop_data_fw);
  3027. ClassDB::bind_method(D_METHOD("drop_data_fw"), &SpatialEditorViewport::drop_data_fw);
  3028. ClassDB::bind_method(D_METHOD("_project_settings_changed"), &SpatialEditorViewport::_project_settings_changed);
  3029. ADD_SIGNAL(MethodInfo("toggle_maximize_view", PropertyInfo(Variant::OBJECT, "viewport")));
  3030. ADD_SIGNAL(MethodInfo("clicked", PropertyInfo(Variant::OBJECT, "viewport")));
  3031. }
  3032. void SpatialEditorViewport::reset() {
  3033. orthogonal = false;
  3034. auto_orthogonal = false;
  3035. lock_rotation = false;
  3036. message_time = 0;
  3037. message = "";
  3038. last_message = "";
  3039. view_type = VIEW_TYPE_USER;
  3040. cursor = Cursor();
  3041. _update_name();
  3042. }
  3043. void SpatialEditorViewport::focus_selection() {
  3044. Vector3 center;
  3045. int count = 0;
  3046. List<Node *> &selection = editor_selection->get_selected_node_list();
  3047. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3048. Spatial *sp = Object::cast_to<Spatial>(E->get());
  3049. if (!sp) {
  3050. continue;
  3051. }
  3052. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  3053. if (!se) {
  3054. continue;
  3055. }
  3056. center += sp->get_global_gizmo_transform().origin;
  3057. count++;
  3058. }
  3059. if (count != 0) {
  3060. center /= float(count);
  3061. }
  3062. cursor.pos = center;
  3063. }
  3064. void SpatialEditorViewport::assign_pending_data_pointers(Spatial *p_preview_node, AABB *p_preview_bounds, AcceptDialog *p_accept) {
  3065. preview_node = p_preview_node;
  3066. preview_bounds = p_preview_bounds;
  3067. accept = p_accept;
  3068. }
  3069. Vector3 SpatialEditorViewport::_get_instance_position(const Point2 &p_pos) const {
  3070. const float MAX_DISTANCE = 50.0;
  3071. Vector3 world_ray = _get_ray(p_pos);
  3072. Vector3 world_pos = _get_ray_pos(p_pos);
  3073. Vector3 point = world_pos + world_ray * MAX_DISTANCE;
  3074. PhysicsDirectSpaceState *ss = get_tree()->get_root()->get_world()->get_direct_space_state();
  3075. PhysicsDirectSpaceState::RayResult result;
  3076. if (ss->intersect_ray(world_pos, world_pos + world_ray * MAX_DISTANCE, result)) {
  3077. point = result.position;
  3078. }
  3079. return point;
  3080. }
  3081. AABB SpatialEditorViewport::_calculate_spatial_bounds(const Spatial *p_parent, bool p_exclude_toplevel_transform) {
  3082. AABB bounds;
  3083. const VisualInstance *visual_instance = Object::cast_to<VisualInstance>(p_parent);
  3084. if (visual_instance) {
  3085. bounds = visual_instance->get_aabb();
  3086. }
  3087. for (int i = 0; i < p_parent->get_child_count(); i++) {
  3088. Spatial *child = Object::cast_to<Spatial>(p_parent->get_child(i));
  3089. if (child) {
  3090. AABB child_bounds = _calculate_spatial_bounds(child, false);
  3091. if (bounds.size == Vector3() && p_parent->get_class_name() == StringName("Spatial")) {
  3092. bounds = child_bounds;
  3093. } else {
  3094. bounds.merge_with(child_bounds);
  3095. }
  3096. }
  3097. }
  3098. if (bounds.size == Vector3() && p_parent->get_class_name() != StringName("Spatial")) {
  3099. #ifdef TOOLS_ENABLED
  3100. bounds = p_parent->get_fallback_gizmo_aabb();
  3101. #else
  3102. bounds = AABB(Vector3(-0.2, -0.2, -0.2), Vector3(0.4, 0.4, 0.4));
  3103. #endif
  3104. }
  3105. if (!p_exclude_toplevel_transform) {
  3106. bounds = p_parent->get_transform().xform(bounds);
  3107. }
  3108. return bounds;
  3109. }
  3110. Node *SpatialEditorViewport::_sanitize_preview_node(Node *p_node) const {
  3111. Spatial *spatial = Object::cast_to<Spatial>(p_node);
  3112. if (spatial == nullptr) {
  3113. Spatial *replacement_node = memnew(Spatial);
  3114. replacement_node->set_name(p_node->get_name());
  3115. p_node->replace_by(replacement_node);
  3116. memdelete(p_node);
  3117. p_node = replacement_node;
  3118. } else {
  3119. VisualInstance *visual_instance = Object::cast_to<VisualInstance>(spatial);
  3120. if (visual_instance == nullptr) {
  3121. Spatial *replacement_node = memnew(Spatial);
  3122. replacement_node->set_name(spatial->get_name());
  3123. replacement_node->set_visible(spatial->is_visible());
  3124. replacement_node->set_transform(spatial->get_transform());
  3125. replacement_node->set_as_toplevel(spatial->is_set_as_toplevel());
  3126. p_node->replace_by(replacement_node);
  3127. memdelete(p_node);
  3128. p_node = replacement_node;
  3129. }
  3130. }
  3131. for (int i = 0; i < p_node->get_child_count(); i++) {
  3132. _sanitize_preview_node(p_node->get_child(i));
  3133. }
  3134. return p_node;
  3135. }
  3136. void SpatialEditorViewport::_create_preview(const Vector<String> &files) const {
  3137. for (int i = 0; i < files.size(); i++) {
  3138. String path = files[i];
  3139. RES res = ResourceLoader::load(path);
  3140. ERR_CONTINUE(res.is_null());
  3141. Ref<PackedScene> scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
  3142. Ref<Mesh> mesh = Ref<Mesh>(Object::cast_to<Mesh>(*res));
  3143. if (mesh != nullptr || scene != nullptr) {
  3144. if (mesh != nullptr) {
  3145. MeshInstance *mesh_instance = memnew(MeshInstance);
  3146. mesh_instance->set_mesh(mesh);
  3147. preview_node->add_child(mesh_instance);
  3148. } else {
  3149. if (scene.is_valid()) {
  3150. Node *instance = scene->instance();
  3151. if (instance) {
  3152. instance = _sanitize_preview_node(instance);
  3153. preview_node->add_child(instance);
  3154. }
  3155. }
  3156. }
  3157. editor->get_scene_root()->add_child(preview_node);
  3158. }
  3159. }
  3160. *preview_bounds = _calculate_spatial_bounds(preview_node);
  3161. }
  3162. void SpatialEditorViewport::_remove_preview() {
  3163. if (preview_node->get_parent()) {
  3164. for (int i = preview_node->get_child_count() - 1; i >= 0; i--) {
  3165. Node *node = preview_node->get_child(i);
  3166. node->queue_delete();
  3167. preview_node->remove_child(node);
  3168. }
  3169. editor->get_scene_root()->remove_child(preview_node);
  3170. }
  3171. }
  3172. bool SpatialEditorViewport::_cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node) {
  3173. if (p_desired_node->get_filename() == p_target_scene_path) {
  3174. return true;
  3175. }
  3176. int childCount = p_desired_node->get_child_count();
  3177. for (int i = 0; i < childCount; i++) {
  3178. Node *child = p_desired_node->get_child(i);
  3179. if (_cyclical_dependency_exists(p_target_scene_path, child)) {
  3180. return true;
  3181. }
  3182. }
  3183. return false;
  3184. }
  3185. bool SpatialEditorViewport::_create_instance(Node *parent, String &path, const Point2 &p_point) {
  3186. RES res = ResourceLoader::load(path);
  3187. ERR_FAIL_COND_V(res.is_null(), false);
  3188. Ref<PackedScene> scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
  3189. Ref<Mesh> mesh = Ref<Mesh>(Object::cast_to<Mesh>(*res));
  3190. Node *instanced_scene = nullptr;
  3191. if (mesh != nullptr || scene != nullptr) {
  3192. if (mesh != nullptr) {
  3193. MeshInstance *mesh_instance = memnew(MeshInstance);
  3194. mesh_instance->set_mesh(mesh);
  3195. mesh_instance->set_name(path.get_file().get_basename());
  3196. instanced_scene = mesh_instance;
  3197. } else {
  3198. if (!scene.is_valid()) { // invalid scene
  3199. return false;
  3200. } else {
  3201. instanced_scene = scene->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
  3202. }
  3203. }
  3204. }
  3205. if (instanced_scene == nullptr) {
  3206. return false;
  3207. }
  3208. if (editor->get_edited_scene()->get_filename() != "") { // cyclical instancing
  3209. if (_cyclical_dependency_exists(editor->get_edited_scene()->get_filename(), instanced_scene)) {
  3210. memdelete(instanced_scene);
  3211. return false;
  3212. }
  3213. }
  3214. if (scene != nullptr) {
  3215. instanced_scene->set_filename(ProjectSettings::get_singleton()->localize_path(path));
  3216. }
  3217. editor_data->get_undo_redo().add_do_method(parent, "add_child", instanced_scene);
  3218. editor_data->get_undo_redo().add_do_method(instanced_scene, "set_owner", editor->get_edited_scene());
  3219. editor_data->get_undo_redo().add_do_reference(instanced_scene);
  3220. editor_data->get_undo_redo().add_undo_method(parent, "remove_child", instanced_scene);
  3221. String new_name = parent->validate_child_name(instanced_scene);
  3222. ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger();
  3223. editor_data->get_undo_redo().add_do_method(sed, "live_debug_instance_node", editor->get_edited_scene()->get_path_to(parent), path, new_name);
  3224. editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(editor->get_edited_scene()->get_path_to(parent)) + "/" + new_name));
  3225. Spatial *spatial = Object::cast_to<Spatial>(instanced_scene);
  3226. if (spatial) {
  3227. Transform global_transform;
  3228. Spatial *parent_spatial = Object::cast_to<Spatial>(parent);
  3229. if (parent_spatial) {
  3230. global_transform = parent_spatial->get_global_gizmo_transform();
  3231. }
  3232. global_transform.origin = spatial_editor->snap_point(_get_instance_position(p_point));
  3233. global_transform.basis *= spatial->get_transform().basis;
  3234. editor_data->get_undo_redo().add_do_method(instanced_scene, "set_global_transform", global_transform);
  3235. }
  3236. return true;
  3237. }
  3238. void SpatialEditorViewport::_perform_drop_data() {
  3239. _remove_preview();
  3240. Vector<String> error_files;
  3241. editor_data->get_undo_redo().create_action(TTR("Create Node"));
  3242. for (int i = 0; i < selected_files.size(); i++) {
  3243. String path = selected_files[i];
  3244. RES res = ResourceLoader::load(path);
  3245. if (res.is_null()) {
  3246. continue;
  3247. }
  3248. Ref<PackedScene> scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
  3249. Ref<Mesh> mesh = Ref<Mesh>(Object::cast_to<Mesh>(*res));
  3250. if (mesh != nullptr || scene != nullptr) {
  3251. bool success = _create_instance(target_node, path, drop_pos);
  3252. if (!success) {
  3253. error_files.push_back(path);
  3254. }
  3255. }
  3256. }
  3257. editor_data->get_undo_redo().commit_action();
  3258. if (error_files.size() > 0) {
  3259. String files_str;
  3260. for (int i = 0; i < error_files.size(); i++) {
  3261. files_str += error_files[i].get_file().get_basename() + ",";
  3262. }
  3263. files_str = files_str.substr(0, files_str.length() - 1);
  3264. accept->set_text(vformat(TTR("Error instancing scene from %s"), files_str.c_str()));
  3265. accept->popup_centered_minsize();
  3266. }
  3267. }
  3268. bool SpatialEditorViewport::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
  3269. bool can_instance = false;
  3270. if (!preview_node->is_inside_tree()) {
  3271. Dictionary d = p_data;
  3272. if (d.has("type") && (String(d["type"]) == "files")) {
  3273. Vector<String> files = d["files"];
  3274. List<String> scene_extensions;
  3275. ResourceLoader::get_recognized_extensions_for_type("PackedScene", &scene_extensions);
  3276. List<String> mesh_extensions;
  3277. ResourceLoader::get_recognized_extensions_for_type("Mesh", &mesh_extensions);
  3278. for (int i = 0; i < files.size(); i++) {
  3279. if (mesh_extensions.find(files[i].get_extension()) || scene_extensions.find(files[i].get_extension())) {
  3280. RES res = ResourceLoader::load(files[i]);
  3281. if (res.is_null()) {
  3282. continue;
  3283. }
  3284. String type = res->get_class();
  3285. if (type == "PackedScene") {
  3286. Ref<PackedScene> sdata = ResourceLoader::load(files[i]);
  3287. Node *instanced_scene = sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
  3288. if (!instanced_scene) {
  3289. continue;
  3290. }
  3291. memdelete(instanced_scene);
  3292. } else if (type == "Mesh" || type == "ArrayMesh" || type == "PrimitiveMesh") {
  3293. Ref<Mesh> mesh = ResourceLoader::load(files[i]);
  3294. if (!mesh.is_valid()) {
  3295. continue;
  3296. }
  3297. } else {
  3298. continue;
  3299. }
  3300. can_instance = true;
  3301. break;
  3302. }
  3303. }
  3304. if (can_instance) {
  3305. _create_preview(files);
  3306. }
  3307. }
  3308. } else {
  3309. can_instance = true;
  3310. }
  3311. if (can_instance) {
  3312. Transform global_transform = Transform(Basis(), _get_instance_position(p_point));
  3313. preview_node->set_global_transform(global_transform);
  3314. }
  3315. return can_instance;
  3316. }
  3317. void SpatialEditorViewport::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
  3318. if (!can_drop_data_fw(p_point, p_data, p_from)) {
  3319. return;
  3320. }
  3321. bool is_shift = Input::get_singleton()->is_key_pressed(KEY_SHIFT);
  3322. selected_files.clear();
  3323. Dictionary d = p_data;
  3324. if (d.has("type") && String(d["type"]) == "files") {
  3325. selected_files = d["files"];
  3326. }
  3327. List<Node *> list = editor->get_editor_selection()->get_selected_node_list();
  3328. if (list.size() == 0) {
  3329. Node *root_node = editor->get_edited_scene();
  3330. if (root_node) {
  3331. list.push_back(root_node);
  3332. } else {
  3333. accept->set_text(TTR("No parent to instance a child at."));
  3334. accept->popup_centered_minsize();
  3335. _remove_preview();
  3336. return;
  3337. }
  3338. }
  3339. if (list.size() != 1) {
  3340. accept->set_text(TTR("This operation requires a single selected node."));
  3341. accept->popup_centered_minsize();
  3342. _remove_preview();
  3343. return;
  3344. }
  3345. target_node = list[0];
  3346. if (is_shift && target_node != editor->get_edited_scene()) {
  3347. target_node = target_node->get_parent();
  3348. }
  3349. drop_pos = p_point;
  3350. _perform_drop_data();
  3351. }
  3352. SpatialEditorViewport::SpatialEditorViewport(SpatialEditor *p_spatial_editor, EditorNode *p_editor, int p_index) {
  3353. _edit.mode = TRANSFORM_NONE;
  3354. _edit.plane = TRANSFORM_VIEW;
  3355. _edit.edited_gizmo = 0;
  3356. _edit.snap = true;
  3357. _edit.gizmo_handle = 0;
  3358. index = p_index;
  3359. editor = p_editor;
  3360. editor_data = editor->get_scene_tree_dock()->get_editor_data();
  3361. editor_selection = editor->get_editor_selection();
  3362. undo_redo = editor->get_undo_redo();
  3363. clicked = 0;
  3364. clicked_includes_current = false;
  3365. orthogonal = false;
  3366. auto_orthogonal = false;
  3367. lock_rotation = false;
  3368. message_time = 0;
  3369. zoom_indicator_delay = 0.0;
  3370. spatial_editor = p_spatial_editor;
  3371. ViewportContainer *c = memnew(ViewportContainer);
  3372. viewport_container = c;
  3373. c->set_stretch(true);
  3374. add_child(c);
  3375. c->set_anchors_and_margins_preset(Control::PRESET_WIDE);
  3376. viewport = memnew(Viewport);
  3377. viewport->set_disable_input(true);
  3378. c->add_child(viewport);
  3379. surface = memnew(Control);
  3380. surface->set_drag_forwarding(this);
  3381. add_child(surface);
  3382. surface->set_anchors_and_margins_preset(Control::PRESET_WIDE);
  3383. surface->set_clip_contents(true);
  3384. camera = memnew(Camera);
  3385. camera->set_disable_gizmo(true);
  3386. 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));
  3387. viewport->add_child(camera);
  3388. camera->make_current();
  3389. surface->set_focus_mode(FOCUS_ALL);
  3390. VBoxContainer *vbox = memnew(VBoxContainer);
  3391. surface->add_child(vbox);
  3392. vbox->set_position(Point2(10, 10) * EDSCALE);
  3393. view_menu = memnew(MenuButton);
  3394. view_menu->set_flat(false);
  3395. vbox->add_child(view_menu);
  3396. view_menu->set_h_size_flags(0);
  3397. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/top_view"), VIEW_TOP);
  3398. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/bottom_view"), VIEW_BOTTOM);
  3399. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/left_view"), VIEW_LEFT);
  3400. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/right_view"), VIEW_RIGHT);
  3401. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/front_view"), VIEW_FRONT);
  3402. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/rear_view"), VIEW_REAR);
  3403. view_menu->get_popup()->add_separator();
  3404. view_menu->get_popup()->add_radio_check_item(TTR("Perspective") + " (" + ED_GET_SHORTCUT("spatial_editor/switch_perspective_orthogonal")->get_as_text() + ")", VIEW_PERSPECTIVE);
  3405. view_menu->get_popup()->add_radio_check_item(TTR("Orthogonal") + " (" + ED_GET_SHORTCUT("spatial_editor/switch_perspective_orthogonal")->get_as_text() + ")", VIEW_ORTHOGONAL);
  3406. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
  3407. view_menu->get_popup()->add_check_item(TTR("Auto Orthogonal Enabled"), VIEW_AUTO_ORTHOGONAL);
  3408. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL), true);
  3409. view_menu->get_popup()->add_separator();
  3410. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_lock_rotation", TTR("Lock View Rotation")), VIEW_LOCK_ROTATION);
  3411. view_menu->get_popup()->add_separator();
  3412. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_normal", TTR("Display Normal")), VIEW_DISPLAY_NORMAL);
  3413. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_wireframe", TTR("Display Wireframe")), VIEW_DISPLAY_WIREFRAME);
  3414. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_overdraw", TTR("Display Overdraw")), VIEW_DISPLAY_OVERDRAW);
  3415. view_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_unshaded", TTR("Display Unshaded")), VIEW_DISPLAY_SHADELESS);
  3416. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), true);
  3417. view_menu->get_popup()->add_separator();
  3418. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_environment", TTR("View Environment")), VIEW_ENVIRONMENT);
  3419. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT), true);
  3420. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_gizmos", TTR("View Gizmos")), VIEW_GIZMOS);
  3421. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_GIZMOS), true);
  3422. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_information", TTR("View Information")), VIEW_INFORMATION);
  3423. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_fps", TTR("View FPS")), VIEW_FPS);
  3424. view_menu->get_popup()->add_separator();
  3425. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_half_resolution", TTR("Half Resolution")), VIEW_HALF_RESOLUTION);
  3426. view_menu->get_popup()->add_separator();
  3427. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_listener", TTR("Audio Listener")), VIEW_AUDIO_LISTENER);
  3428. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_doppler", TTR("Enable Doppler")), VIEW_AUDIO_DOPPLER);
  3429. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER), true);
  3430. view_menu->get_popup()->add_separator();
  3431. view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_cinematic_preview", TTR("Cinematic Preview")), VIEW_CINEMATIC_PREVIEW);
  3432. view_menu->get_popup()->add_separator();
  3433. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_origin"), VIEW_CENTER_TO_ORIGIN);
  3434. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_selection"), VIEW_CENTER_TO_SELECTION);
  3435. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_transform_with_view"), VIEW_ALIGN_TRANSFORM_WITH_VIEW);
  3436. view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_rotation_with_view"), VIEW_ALIGN_ROTATION_WITH_VIEW);
  3437. view_menu->get_popup()->connect("id_pressed", this, "_menu_option");
  3438. view_menu->set_disable_shortcuts(true);
  3439. if (OS::get_singleton()->get_current_video_driver() == OS::VIDEO_DRIVER_GLES2) {
  3440. // Alternate display modes only work when using the GLES3 renderer; make this explicit.
  3441. const int normal_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL);
  3442. const int wireframe_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_WIREFRAME);
  3443. const int overdraw_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_OVERDRAW);
  3444. const int shadeless_idx = view_menu->get_popup()->get_item_index(VIEW_DISPLAY_SHADELESS);
  3445. const String unsupported_suffix = " " + TTR("(Not in GLES2)");
  3446. const String unsupported_tooltip = TTR("Debug draw modes are only available when using the GLES3 renderer, not GLES2.");
  3447. view_menu->get_popup()->set_item_tooltip(normal_idx, unsupported_tooltip);
  3448. view_menu->get_popup()->set_item_disabled(wireframe_idx, true);
  3449. view_menu->get_popup()->set_item_text(wireframe_idx, TTR("Display Wireframe") + unsupported_suffix);
  3450. view_menu->get_popup()->set_item_tooltip(wireframe_idx, unsupported_tooltip);
  3451. view_menu->get_popup()->set_item_disabled(overdraw_idx, true);
  3452. view_menu->get_popup()->set_item_text(overdraw_idx, TTR("Display Overdraw") + unsupported_suffix);
  3453. view_menu->get_popup()->set_item_tooltip(overdraw_idx, unsupported_tooltip);
  3454. view_menu->get_popup()->set_item_disabled(shadeless_idx, true);
  3455. view_menu->get_popup()->set_item_text(shadeless_idx, TTR("Display Unshaded") + unsupported_suffix);
  3456. view_menu->get_popup()->set_item_tooltip(shadeless_idx, unsupported_tooltip);
  3457. }
  3458. ED_SHORTCUT("spatial_editor/freelook_left", TTR("Freelook Left"), KEY_A);
  3459. ED_SHORTCUT("spatial_editor/freelook_right", TTR("Freelook Right"), KEY_D);
  3460. ED_SHORTCUT("spatial_editor/freelook_forward", TTR("Freelook Forward"), KEY_W);
  3461. ED_SHORTCUT("spatial_editor/freelook_backwards", TTR("Freelook Backwards"), KEY_S);
  3462. ED_SHORTCUT("spatial_editor/freelook_up", TTR("Freelook Up"), KEY_E);
  3463. ED_SHORTCUT("spatial_editor/freelook_down", TTR("Freelook Down"), KEY_Q);
  3464. ED_SHORTCUT("spatial_editor/freelook_speed_modifier", TTR("Freelook Speed Modifier"), KEY_SHIFT);
  3465. ED_SHORTCUT("spatial_editor/freelook_slow_modifier", TTR("Freelook Slow Modifier"), KEY_ALT);
  3466. preview_camera = memnew(CheckBox);
  3467. preview_camera->set_text(TTR("Preview"));
  3468. preview_camera->set_shortcut(ED_SHORTCUT("spatial_editor/toggle_camera_preview", TTR("Toggle Camera Preview"), KEY_MASK_CMD | KEY_P));
  3469. vbox->add_child(preview_camera);
  3470. preview_camera->set_h_size_flags(0);
  3471. preview_camera->hide();
  3472. preview_camera->connect("toggled", this, "_toggle_camera_preview");
  3473. previewing = nullptr;
  3474. gizmo_scale = 1.0;
  3475. preview_node = nullptr;
  3476. _project_settings_change_pending = false;
  3477. info_label = memnew(Label);
  3478. info_label->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, -90 * EDSCALE);
  3479. info_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_END, -90 * EDSCALE);
  3480. info_label->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, -10 * EDSCALE);
  3481. info_label->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, -10 * EDSCALE);
  3482. info_label->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  3483. info_label->set_v_grow_direction(GROW_DIRECTION_BEGIN);
  3484. surface->add_child(info_label);
  3485. info_label->hide();
  3486. cinema_label = memnew(Label);
  3487. cinema_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 10 * EDSCALE);
  3488. cinema_label->set_h_grow_direction(GROW_DIRECTION_END);
  3489. cinema_label->set_align(Label::ALIGN_CENTER);
  3490. surface->add_child(cinema_label);
  3491. cinema_label->set_text(TTR("Cinematic Preview"));
  3492. cinema_label->hide();
  3493. previewing_cinema = false;
  3494. locked_label = memnew(Label);
  3495. locked_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_END, -20 * EDSCALE);
  3496. locked_label->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, -10 * EDSCALE);
  3497. locked_label->set_h_grow_direction(GROW_DIRECTION_END);
  3498. locked_label->set_v_grow_direction(GROW_DIRECTION_BEGIN);
  3499. locked_label->set_align(Label::ALIGN_CENTER);
  3500. surface->add_child(locked_label);
  3501. locked_label->set_text(TTR("View Rotation Locked"));
  3502. locked_label->hide();
  3503. zoom_limit_label = memnew(Label);
  3504. zoom_limit_label->set_anchors_and_margins_preset(LayoutPreset::PRESET_BOTTOM_LEFT);
  3505. zoom_limit_label->set_margin(Margin::MARGIN_TOP, -28 * EDSCALE);
  3506. zoom_limit_label->set_text(TTR("To zoom further, change the camera's clipping planes (View -> Settings...)"));
  3507. zoom_limit_label->set_name("ZoomLimitMessageLabel");
  3508. zoom_limit_label->add_color_override("font_color", Color(1, 1, 1, 1));
  3509. zoom_limit_label->hide();
  3510. surface->add_child(zoom_limit_label);
  3511. top_right_vbox = memnew(VBoxContainer);
  3512. top_right_vbox->set_anchors_and_margins_preset(PRESET_TOP_RIGHT, PRESET_MODE_MINSIZE, 2.0 * EDSCALE);
  3513. top_right_vbox->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  3514. rotation_control = memnew(ViewportRotationControl);
  3515. rotation_control->set_custom_minimum_size(Size2(80, 80) * EDSCALE);
  3516. rotation_control->set_h_size_flags(SIZE_SHRINK_END);
  3517. rotation_control->set_viewport(this);
  3518. top_right_vbox->add_child(rotation_control);
  3519. frame_time_gradient = memnew(Gradient);
  3520. // The color is set when the theme changes.
  3521. frame_time_gradient->add_point(0.5, Color());
  3522. fps_label = memnew(Label);
  3523. fps_label->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, -90 * EDSCALE);
  3524. fps_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 10 * EDSCALE);
  3525. fps_label->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, -10 * EDSCALE);
  3526. fps_label->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  3527. fps_label->set_tooltip(TTR("Note: The FPS value displayed is the editor's framerate.\nIt cannot be used as a reliable indication of in-game performance."));
  3528. fps_label->set_mouse_filter(MOUSE_FILTER_PASS); // Otherwise tooltip doesn't show.
  3529. top_right_vbox->add_child(fps_label);
  3530. fps_label->hide();
  3531. surface->add_child(top_right_vbox);
  3532. accept = nullptr;
  3533. freelook_active = false;
  3534. freelook_speed = EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_base_speed");
  3535. selection_menu = memnew(PopupMenu);
  3536. add_child(selection_menu);
  3537. selection_menu->set_custom_minimum_size(Size2(100, 0) * EDSCALE);
  3538. selection_menu->connect("id_pressed", this, "_selection_result_pressed");
  3539. selection_menu->connect("popup_hide", this, "_selection_menu_hide");
  3540. if (p_index == 0) {
  3541. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER), true);
  3542. viewport->set_as_audio_listener(true);
  3543. }
  3544. view_type = VIEW_TYPE_USER;
  3545. _update_name();
  3546. EditorSettings::get_singleton()->connect("settings_changed", this, "update_transform_gizmo_view");
  3547. }
  3548. SpatialEditorViewport::~SpatialEditorViewport() {
  3549. memdelete(frame_time_gradient);
  3550. }
  3551. //////////////////////////////////////////////////////////////
  3552. void SpatialEditorViewportContainer::_gui_input(const Ref<InputEvent> &p_event) {
  3553. Ref<InputEventMouseButton> mb = p_event;
  3554. if (mb.is_valid() && mb->get_button_index() == BUTTON_LEFT) {
  3555. if (mb->is_pressed()) {
  3556. Vector2 size = get_size();
  3557. int h_sep = get_constant("separation", "HSplitContainer");
  3558. int v_sep = get_constant("separation", "VSplitContainer");
  3559. int mid_w = size.width * ratio_h;
  3560. int mid_h = size.height * ratio_v;
  3561. dragging_h = mb->get_position().x > (mid_w - h_sep / 2) && mb->get_position().x < (mid_w + h_sep / 2);
  3562. dragging_v = mb->get_position().y > (mid_h - v_sep / 2) && mb->get_position().y < (mid_h + v_sep / 2);
  3563. drag_begin_pos = mb->get_position();
  3564. drag_begin_ratio.x = ratio_h;
  3565. drag_begin_ratio.y = ratio_v;
  3566. switch (view) {
  3567. case VIEW_USE_1_VIEWPORT: {
  3568. dragging_h = false;
  3569. dragging_v = false;
  3570. } break;
  3571. case VIEW_USE_2_VIEWPORTS: {
  3572. dragging_h = false;
  3573. } break;
  3574. case VIEW_USE_2_VIEWPORTS_ALT: {
  3575. dragging_v = false;
  3576. } break;
  3577. case VIEW_USE_3_VIEWPORTS:
  3578. case VIEW_USE_3_VIEWPORTS_ALT:
  3579. case VIEW_USE_4_VIEWPORTS: {
  3580. // Do nothing.
  3581. } break;
  3582. }
  3583. } else {
  3584. dragging_h = false;
  3585. dragging_v = false;
  3586. }
  3587. }
  3588. Ref<InputEventMouseMotion> mm = p_event;
  3589. if (mm.is_valid()) {
  3590. if (view == VIEW_USE_3_VIEWPORTS || view == VIEW_USE_3_VIEWPORTS_ALT || view == VIEW_USE_4_VIEWPORTS) {
  3591. Vector2 size = get_size();
  3592. int h_sep = get_constant("separation", "HSplitContainer");
  3593. int v_sep = get_constant("separation", "VSplitContainer");
  3594. int mid_w = size.width * ratio_h;
  3595. int mid_h = size.height * ratio_v;
  3596. bool was_hovering_h = hovering_h;
  3597. bool was_hovering_v = hovering_v;
  3598. hovering_h = mm->get_position().x > (mid_w - h_sep / 2) && mm->get_position().x < (mid_w + h_sep / 2);
  3599. hovering_v = mm->get_position().y > (mid_h - v_sep / 2) && mm->get_position().y < (mid_h + v_sep / 2);
  3600. if (was_hovering_h != hovering_h || was_hovering_v != hovering_v) {
  3601. update();
  3602. }
  3603. }
  3604. if (dragging_h) {
  3605. float new_ratio = drag_begin_ratio.x + (mm->get_position().x - drag_begin_pos.x) / get_size().width;
  3606. new_ratio = CLAMP(new_ratio, 40 / get_size().width, (get_size().width - 40) / get_size().width);
  3607. ratio_h = new_ratio;
  3608. queue_sort();
  3609. update();
  3610. }
  3611. if (dragging_v) {
  3612. float new_ratio = drag_begin_ratio.y + (mm->get_position().y - drag_begin_pos.y) / get_size().height;
  3613. new_ratio = CLAMP(new_ratio, 40 / get_size().height, (get_size().height - 40) / get_size().height);
  3614. ratio_v = new_ratio;
  3615. queue_sort();
  3616. update();
  3617. }
  3618. }
  3619. }
  3620. void SpatialEditorViewportContainer::_notification(int p_what) {
  3621. if (p_what == NOTIFICATION_MOUSE_ENTER || p_what == NOTIFICATION_MOUSE_EXIT) {
  3622. mouseover = (p_what == NOTIFICATION_MOUSE_ENTER);
  3623. update();
  3624. }
  3625. if (p_what == NOTIFICATION_DRAW && mouseover) {
  3626. Ref<Texture> h_grabber = get_icon("grabber", "HSplitContainer");
  3627. Ref<Texture> v_grabber = get_icon("grabber", "VSplitContainer");
  3628. Ref<Texture> hdiag_grabber = get_icon("GuiViewportHdiagsplitter", "EditorIcons");
  3629. Ref<Texture> vdiag_grabber = get_icon("GuiViewportVdiagsplitter", "EditorIcons");
  3630. Ref<Texture> vh_grabber = get_icon("GuiViewportVhsplitter", "EditorIcons");
  3631. Vector2 size = get_size();
  3632. int h_sep = get_constant("separation", "HSplitContainer");
  3633. int v_sep = get_constant("separation", "VSplitContainer");
  3634. int mid_w = size.width * ratio_h;
  3635. int mid_h = size.height * ratio_v;
  3636. int size_left = mid_w - h_sep / 2;
  3637. int size_bottom = size.height - mid_h - v_sep / 2;
  3638. switch (view) {
  3639. case VIEW_USE_1_VIEWPORT: {
  3640. // Nothing to show.
  3641. } break;
  3642. case VIEW_USE_2_VIEWPORTS: {
  3643. draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  3644. set_default_cursor_shape(CURSOR_VSPLIT);
  3645. } break;
  3646. case VIEW_USE_2_VIEWPORTS_ALT: {
  3647. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
  3648. set_default_cursor_shape(CURSOR_HSPLIT);
  3649. } break;
  3650. case VIEW_USE_3_VIEWPORTS: {
  3651. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  3652. draw_texture(hdiag_grabber, Vector2(mid_w - hdiag_grabber->get_width() / 2, mid_h - v_grabber->get_height() / 4));
  3653. set_default_cursor_shape(CURSOR_DRAG);
  3654. } else if ((hovering_v && !dragging_h) || dragging_v) {
  3655. draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  3656. set_default_cursor_shape(CURSOR_VSPLIT);
  3657. } else if (hovering_h || dragging_h) {
  3658. 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));
  3659. set_default_cursor_shape(CURSOR_HSPLIT);
  3660. }
  3661. } break;
  3662. case VIEW_USE_3_VIEWPORTS_ALT: {
  3663. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  3664. draw_texture(vdiag_grabber, Vector2(mid_w - vdiag_grabber->get_width() + v_grabber->get_height() / 4, mid_h - vdiag_grabber->get_height() / 2));
  3665. set_default_cursor_shape(CURSOR_DRAG);
  3666. } else if ((hovering_v && !dragging_h) || dragging_v) {
  3667. draw_texture(v_grabber, Vector2((size_left - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  3668. set_default_cursor_shape(CURSOR_VSPLIT);
  3669. } else if (hovering_h || dragging_h) {
  3670. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
  3671. set_default_cursor_shape(CURSOR_HSPLIT);
  3672. }
  3673. } break;
  3674. case VIEW_USE_4_VIEWPORTS: {
  3675. Vector2 half(mid_w, mid_h);
  3676. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  3677. draw_texture(vh_grabber, half - vh_grabber->get_size() / 2.0);
  3678. set_default_cursor_shape(CURSOR_DRAG);
  3679. } else if ((hovering_v && !dragging_h) || dragging_v) {
  3680. draw_texture(v_grabber, half - v_grabber->get_size() / 2.0);
  3681. set_default_cursor_shape(CURSOR_VSPLIT);
  3682. } else if (hovering_h || dragging_h) {
  3683. draw_texture(h_grabber, half - h_grabber->get_size() / 2.0);
  3684. set_default_cursor_shape(CURSOR_HSPLIT);
  3685. }
  3686. } break;
  3687. }
  3688. }
  3689. if (p_what == NOTIFICATION_SORT_CHILDREN) {
  3690. SpatialEditorViewport *viewports[4];
  3691. int vc = 0;
  3692. for (int i = 0; i < get_child_count(); i++) {
  3693. viewports[vc] = Object::cast_to<SpatialEditorViewport>(get_child(i));
  3694. if (viewports[vc]) {
  3695. vc++;
  3696. }
  3697. }
  3698. ERR_FAIL_COND(vc != 4);
  3699. Size2 size = get_size();
  3700. if (size.x < 10 || size.y < 10) {
  3701. for (int i = 0; i < 4; i++) {
  3702. viewports[i]->hide();
  3703. }
  3704. return;
  3705. }
  3706. int h_sep = get_constant("separation", "HSplitContainer");
  3707. int v_sep = get_constant("separation", "VSplitContainer");
  3708. int mid_w = size.width * ratio_h;
  3709. int mid_h = size.height * ratio_v;
  3710. int size_left = mid_w - h_sep / 2;
  3711. int size_right = size.width - mid_w - h_sep / 2;
  3712. int size_top = mid_h - v_sep / 2;
  3713. int size_bottom = size.height - mid_h - v_sep / 2;
  3714. switch (view) {
  3715. case VIEW_USE_1_VIEWPORT: {
  3716. viewports[0]->show();
  3717. for (int i = 1; i < 4; i++) {
  3718. viewports[i]->hide();
  3719. }
  3720. fit_child_in_rect(viewports[0], Rect2(Vector2(), size));
  3721. } break;
  3722. case VIEW_USE_2_VIEWPORTS: {
  3723. for (int i = 0; i < 4; i++) {
  3724. if (i == 1 || i == 3) {
  3725. viewports[i]->hide();
  3726. } else {
  3727. viewports[i]->show();
  3728. }
  3729. }
  3730. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
  3731. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size.width, size_bottom)));
  3732. } break;
  3733. case VIEW_USE_2_VIEWPORTS_ALT: {
  3734. for (int i = 0; i < 4; i++) {
  3735. if (i == 1 || i == 3) {
  3736. viewports[i]->hide();
  3737. } else {
  3738. viewports[i]->show();
  3739. }
  3740. }
  3741. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size.height)));
  3742. fit_child_in_rect(viewports[2], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
  3743. } break;
  3744. case VIEW_USE_3_VIEWPORTS: {
  3745. for (int i = 0; i < 4; i++) {
  3746. if (i == 1) {
  3747. viewports[i]->hide();
  3748. } else {
  3749. viewports[i]->show();
  3750. }
  3751. }
  3752. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
  3753. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  3754. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
  3755. } break;
  3756. case VIEW_USE_3_VIEWPORTS_ALT: {
  3757. for (int i = 0; i < 4; i++) {
  3758. if (i == 1) {
  3759. viewports[i]->hide();
  3760. } else {
  3761. viewports[i]->show();
  3762. }
  3763. }
  3764. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
  3765. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  3766. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
  3767. } break;
  3768. case VIEW_USE_4_VIEWPORTS: {
  3769. for (int i = 0; i < 4; i++) {
  3770. viewports[i]->show();
  3771. }
  3772. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
  3773. fit_child_in_rect(viewports[1], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size_top)));
  3774. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  3775. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
  3776. } break;
  3777. }
  3778. }
  3779. }
  3780. void SpatialEditorViewportContainer::set_view(View p_view) {
  3781. view = p_view;
  3782. queue_sort();
  3783. }
  3784. SpatialEditorViewportContainer::View SpatialEditorViewportContainer::get_view() {
  3785. return view;
  3786. }
  3787. void SpatialEditorViewportContainer::_bind_methods() {
  3788. ClassDB::bind_method("_gui_input", &SpatialEditorViewportContainer::_gui_input);
  3789. }
  3790. SpatialEditorViewportContainer::SpatialEditorViewportContainer() {
  3791. set_clip_contents(true);
  3792. view = VIEW_USE_1_VIEWPORT;
  3793. mouseover = false;
  3794. ratio_h = 0.5;
  3795. ratio_v = 0.5;
  3796. hovering_v = false;
  3797. hovering_h = false;
  3798. dragging_v = false;
  3799. dragging_h = false;
  3800. }
  3801. ///////////////////////////////////////////////////////////////////
  3802. SpatialEditor *SpatialEditor::singleton = nullptr;
  3803. SpatialEditorSelectedItem::~SpatialEditorSelectedItem() {
  3804. if (sbox_instance.is_valid()) {
  3805. VisualServer::get_singleton()->free(sbox_instance);
  3806. }
  3807. if (sbox_instance_offset.is_valid()) {
  3808. VisualServer::get_singleton()->free(sbox_instance_offset);
  3809. }
  3810. if (sbox_instance_xray.is_valid()) {
  3811. VisualServer::get_singleton()->free(sbox_instance_xray);
  3812. }
  3813. if (sbox_instance_xray_offset.is_valid()) {
  3814. VisualServer::get_singleton()->free(sbox_instance_xray_offset);
  3815. }
  3816. }
  3817. void SpatialEditor::select_gizmo_highlight_axis(int p_axis) {
  3818. for (int i = 0; i < 3; i++) {
  3819. move_gizmo[i]->surface_set_material(0, i == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  3820. move_plane_gizmo[i]->surface_set_material(0, (i + 6) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
  3821. rotate_gizmo[i]->surface_set_material(0, (i + 3) == p_axis ? rotate_gizmo_color_hl[i] : rotate_gizmo_color[i]);
  3822. scale_gizmo[i]->surface_set_material(0, (i + 9) == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  3823. scale_plane_gizmo[i]->surface_set_material(0, (i + 12) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
  3824. }
  3825. }
  3826. void SpatialEditor::show_advanced_portal_tools(bool p_show) {
  3827. // toolbar button
  3828. Button *const button = tool_button[TOOL_CONVERT_ROOMS];
  3829. if (p_show) {
  3830. button->set_text(TTR("Convert Rooms"));
  3831. } else {
  3832. button->set_text("");
  3833. }
  3834. }
  3835. void SpatialEditor::update_portal_tools() {
  3836. // just some protection against calling null pointers, hopefully not needed
  3837. if (view_menu && view_menu->get_popup()) {
  3838. // the view portal culling toggle
  3839. int view_portal_item_index = view_menu->get_popup()->get_item_index(MENU_VIEW_PORTAL_CULLING);
  3840. if (RoomManager::active_room_manager) {
  3841. view_menu->get_popup()->set_item_disabled(view_portal_item_index, false);
  3842. bool active = RoomManager::static_rooms_get_active();
  3843. view_menu->get_popup()->set_item_checked(view_portal_item_index, active);
  3844. } else {
  3845. view_menu->get_popup()->set_item_disabled(view_portal_item_index, true);
  3846. }
  3847. // toolbar button
  3848. Button *const button = tool_button[TOOL_CONVERT_ROOMS];
  3849. if (RoomManager::active_room_manager) {
  3850. button->show();
  3851. } else {
  3852. button->hide();
  3853. }
  3854. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  3855. viewports[i]->_update_name();
  3856. }
  3857. }
  3858. }
  3859. void SpatialEditor::update_transform_gizmo() {
  3860. List<Node *> &selection = editor_selection->get_selected_node_list();
  3861. AABB center;
  3862. bool first = true;
  3863. Basis gizmo_basis;
  3864. bool local_gizmo_coords = are_local_coords_enabled();
  3865. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  3866. Spatial *sp = Object::cast_to<Spatial>(E->get());
  3867. if (!sp) {
  3868. continue;
  3869. }
  3870. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  3871. if (!se) {
  3872. continue;
  3873. }
  3874. Transform xf = se->sp->get_global_gizmo_transform();
  3875. if (first) {
  3876. center.position = xf.origin;
  3877. first = false;
  3878. if (local_gizmo_coords) {
  3879. gizmo_basis = xf.basis;
  3880. gizmo_basis.orthonormalize();
  3881. }
  3882. } else {
  3883. center.expand_to(xf.origin);
  3884. gizmo_basis = Basis();
  3885. }
  3886. }
  3887. Vector3 pcenter = center.position + center.size * 0.5;
  3888. gizmo.visible = !first;
  3889. gizmo.transform.origin = pcenter;
  3890. gizmo.transform.basis = gizmo_basis;
  3891. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  3892. viewports[i]->update_transform_gizmo_view();
  3893. }
  3894. }
  3895. void _update_all_gizmos(Node *p_node) {
  3896. for (int i = p_node->get_child_count() - 1; 0 <= i; --i) {
  3897. Spatial *spatial_node = Object::cast_to<Spatial>(p_node->get_child(i));
  3898. if (spatial_node) {
  3899. spatial_node->update_gizmo();
  3900. }
  3901. _update_all_gizmos(p_node->get_child(i));
  3902. }
  3903. }
  3904. void SpatialEditor::update_all_gizmos(Node *p_node) {
  3905. if (!p_node) {
  3906. if (SceneTree::get_singleton()) {
  3907. p_node = SceneTree::get_singleton()->get_root();
  3908. } else {
  3909. // No scene tree, so nothing to update.
  3910. return;
  3911. }
  3912. }
  3913. _update_all_gizmos(p_node);
  3914. }
  3915. Object *SpatialEditor::_get_editor_data(Object *p_what) {
  3916. Spatial *sp = Object::cast_to<Spatial>(p_what);
  3917. if (!sp) {
  3918. return nullptr;
  3919. }
  3920. SpatialEditorSelectedItem *si = memnew(SpatialEditorSelectedItem);
  3921. si->sp = sp;
  3922. si->sbox_instance = VisualServer::get_singleton()->instance_create2(
  3923. selection_box->get_rid(),
  3924. sp->get_world()->get_scenario());
  3925. si->sbox_instance_offset = VisualServer::get_singleton()->instance_create2(
  3926. selection_box->get_rid(),
  3927. sp->get_world()->get_scenario());
  3928. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  3929. si->sbox_instance,
  3930. VS::SHADOW_CASTING_SETTING_OFF);
  3931. // Use the Edit layer to hide the selection box when View Gizmos is disabled, since it is a bit distracting.
  3932. // It's still possible to approximately guess what is selected by looking at the manipulation gizmo position.
  3933. VS::get_singleton()->instance_set_layer_mask(si->sbox_instance, 1 << SpatialEditorViewport::GIZMO_EDIT_LAYER);
  3934. VS::get_singleton()->instance_set_layer_mask(si->sbox_instance_offset, 1 << SpatialEditorViewport::GIZMO_EDIT_LAYER);
  3935. si->sbox_instance_xray = VisualServer::get_singleton()->instance_create2(
  3936. selection_box_xray->get_rid(),
  3937. sp->get_world()->get_scenario());
  3938. si->sbox_instance_xray_offset = VisualServer::get_singleton()->instance_create2(
  3939. selection_box_xray->get_rid(),
  3940. sp->get_world()->get_scenario());
  3941. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  3942. si->sbox_instance_xray,
  3943. VS::SHADOW_CASTING_SETTING_OFF);
  3944. VS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  3945. si->sbox_instance_xray_offset,
  3946. VS::SHADOW_CASTING_SETTING_OFF);
  3947. // Use the Edit layer to hide the selection box when View Gizmos is disabled, since it is a bit distracting.
  3948. // It's still possible to approximately guess what is selected by looking at the manipulation gizmo position.
  3949. VS::get_singleton()->instance_set_layer_mask(si->sbox_instance_xray, 1 << SpatialEditorViewport::GIZMO_EDIT_LAYER);
  3950. VS::get_singleton()->instance_set_layer_mask(si->sbox_instance_xray_offset, 1 << SpatialEditorViewport::GIZMO_EDIT_LAYER);
  3951. return si;
  3952. }
  3953. void SpatialEditor::_generate_selection_boxes() {
  3954. // Use two AABBs to create the illusion of a slightly thicker line.
  3955. AABB aabb(Vector3(), Vector3(1, 1, 1));
  3956. // Create a x-ray (visible through solid surfaces) and standard version of the selection box.
  3957. // Both will be drawn at the same position, but with different opacity.
  3958. // This lets the user see where the selection is while still having a sense of depth.
  3959. Ref<SurfaceTool> st = memnew(SurfaceTool);
  3960. Ref<SurfaceTool> st_xray = memnew(SurfaceTool);
  3961. st->begin(Mesh::PRIMITIVE_LINES);
  3962. st_xray->begin(Mesh::PRIMITIVE_LINES);
  3963. for (int i = 0; i < 12; i++) {
  3964. Vector3 a, b;
  3965. aabb.get_edge(i, a, b);
  3966. st->add_vertex(a);
  3967. st->add_vertex(b);
  3968. st_xray->add_vertex(a);
  3969. st_xray->add_vertex(b);
  3970. }
  3971. Ref<SpatialMaterial> mat = memnew(SpatialMaterial);
  3972. mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  3973. const Color selection_box_color = EDITOR_GET("editors/3d/selection_box_color");
  3974. mat->set_albedo(selection_box_color);
  3975. mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  3976. st->set_material(mat);
  3977. selection_box = st->commit();
  3978. Ref<SpatialMaterial> mat_xray = memnew(SpatialMaterial);
  3979. mat_xray->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  3980. mat_xray->set_flag(SpatialMaterial::FLAG_DISABLE_DEPTH_TEST, true);
  3981. mat_xray->set_albedo(selection_box_color * Color(1, 1, 1, 0.15));
  3982. mat_xray->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  3983. st_xray->set_material(mat_xray);
  3984. selection_box_xray = st_xray->commit();
  3985. }
  3986. Dictionary SpatialEditor::get_state() const {
  3987. Dictionary d;
  3988. d["snap_enabled"] = snap_enabled;
  3989. d["translate_snap"] = get_translate_snap();
  3990. d["rotate_snap"] = get_rotate_snap();
  3991. d["scale_snap"] = get_scale_snap();
  3992. d["local_coords"] = tool_option_button[TOOL_OPT_LOCAL_COORDS]->is_pressed();
  3993. int vc = 0;
  3994. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT))) {
  3995. vc = 1;
  3996. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS))) {
  3997. vc = 2;
  3998. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS))) {
  3999. vc = 3;
  4000. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS))) {
  4001. vc = 4;
  4002. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT))) {
  4003. vc = 5;
  4004. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT))) {
  4005. vc = 6;
  4006. }
  4007. d["viewport_mode"] = vc;
  4008. Array vpdata;
  4009. for (int i = 0; i < 4; i++) {
  4010. vpdata.push_back(viewports[i]->get_state());
  4011. }
  4012. d["viewports"] = vpdata;
  4013. d["show_grid"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID));
  4014. d["show_origin"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN));
  4015. d["fov"] = get_fov();
  4016. d["znear"] = get_znear();
  4017. d["zfar"] = get_zfar();
  4018. Dictionary gizmos_status;
  4019. for (int i = 0; i < gizmo_plugins_by_name.size(); i++) {
  4020. if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
  4021. continue;
  4022. }
  4023. int state = gizmos_menu->get_item_state(gizmos_menu->get_item_index(i));
  4024. String name = gizmo_plugins_by_name[i]->get_name();
  4025. gizmos_status[name] = state;
  4026. }
  4027. d["gizmos_status"] = gizmos_status;
  4028. return d;
  4029. }
  4030. void SpatialEditor::set_state(const Dictionary &p_state) {
  4031. Dictionary d = p_state;
  4032. if (d.has("snap_enabled")) {
  4033. snap_enabled = d["snap_enabled"];
  4034. tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(d["snap_enabled"]);
  4035. }
  4036. if (d.has("translate_snap")) {
  4037. snap_translate_value = d["translate_snap"];
  4038. }
  4039. if (d.has("rotate_snap")) {
  4040. snap_rotate_value = d["rotate_snap"];
  4041. }
  4042. if (d.has("scale_snap")) {
  4043. snap_scale_value = d["scale_snap"];
  4044. }
  4045. _snap_update();
  4046. if (d.has("local_coords")) {
  4047. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(d["local_coords"]);
  4048. update_transform_gizmo();
  4049. }
  4050. if (d.has("viewport_mode")) {
  4051. int vc = d["viewport_mode"];
  4052. if (vc == 1) {
  4053. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  4054. } else if (vc == 2) {
  4055. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
  4056. } else if (vc == 3) {
  4057. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
  4058. } else if (vc == 4) {
  4059. _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
  4060. } else if (vc == 5) {
  4061. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
  4062. } else if (vc == 6) {
  4063. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
  4064. }
  4065. }
  4066. if (d.has("viewports")) {
  4067. Array vp = d["viewports"];
  4068. uint32_t vp_size = static_cast<uint32_t>(vp.size());
  4069. if (vp_size > VIEWPORTS_COUNT) {
  4070. WARN_PRINT("Ignoring superfluous viewport settings from spatial editor state.");
  4071. vp_size = VIEWPORTS_COUNT;
  4072. }
  4073. for (uint32_t i = 0; i < vp_size; i++) {
  4074. viewports[i]->set_state(vp[i]);
  4075. }
  4076. }
  4077. if (d.has("zfar")) {
  4078. settings_zfar->set_value(float(d["zfar"]));
  4079. }
  4080. if (d.has("znear")) {
  4081. settings_znear->set_value(float(d["znear"]));
  4082. }
  4083. if (d.has("fov")) {
  4084. settings_fov->set_value(float(d["fov"]));
  4085. }
  4086. if (d.has("show_grid")) {
  4087. bool use = d["show_grid"];
  4088. if (use != view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID))) {
  4089. _menu_item_pressed(MENU_VIEW_GRID);
  4090. }
  4091. }
  4092. if (d.has("show_origin")) {
  4093. bool use = d["show_origin"];
  4094. if (use != view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN))) {
  4095. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), use);
  4096. VisualServer::get_singleton()->instance_set_visible(origin_instance, use);
  4097. }
  4098. }
  4099. if (d.has("gizmos_status")) {
  4100. Dictionary gizmos_status = d["gizmos_status"];
  4101. List<Variant> keys;
  4102. gizmos_status.get_key_list(&keys);
  4103. for (int j = 0; j < gizmo_plugins_by_name.size(); ++j) {
  4104. if (!gizmo_plugins_by_name[j]->can_be_hidden()) {
  4105. continue;
  4106. }
  4107. int state = EditorSpatialGizmoPlugin::VISIBLE;
  4108. for (int i = 0; i < keys.size(); i++) {
  4109. if (gizmo_plugins_by_name.write[j]->get_name() == keys[i]) {
  4110. state = gizmos_status[keys[i]];
  4111. break;
  4112. }
  4113. }
  4114. gizmo_plugins_by_name.write[j]->set_state(state);
  4115. }
  4116. _update_gizmos_menu();
  4117. }
  4118. }
  4119. void SpatialEditor::edit(Spatial *p_spatial) {
  4120. if (p_spatial != selected) {
  4121. if (selected) {
  4122. Ref<EditorSpatialGizmo> seg = selected->get_gizmo();
  4123. if (seg.is_valid()) {
  4124. seg->set_selected(false);
  4125. selected->update_gizmo();
  4126. }
  4127. }
  4128. selected = p_spatial;
  4129. over_gizmo_handle = -1;
  4130. if (selected) {
  4131. Ref<EditorSpatialGizmo> seg = selected->get_gizmo();
  4132. if (seg.is_valid()) {
  4133. seg->set_selected(true);
  4134. selected->update_gizmo();
  4135. }
  4136. }
  4137. }
  4138. }
  4139. void SpatialEditor::_snap_changed() {
  4140. snap_translate_value = snap_translate->get_text().to_double();
  4141. snap_rotate_value = snap_rotate->get_text().to_double();
  4142. snap_scale_value = snap_scale->get_text().to_double();
  4143. }
  4144. void SpatialEditor::_snap_update() {
  4145. snap_translate->set_text(String::num(snap_translate_value));
  4146. snap_rotate->set_text(String::num(snap_rotate_value));
  4147. snap_scale->set_text(String::num(snap_scale_value));
  4148. }
  4149. void SpatialEditor::_xform_dialog_action() {
  4150. Transform t;
  4151. //translation
  4152. Vector3 scale;
  4153. Vector3 rotate;
  4154. Vector3 translate;
  4155. for (int i = 0; i < 3; i++) {
  4156. translate[i] = xform_translate[i]->get_text().to_double();
  4157. rotate[i] = Math::deg2rad(xform_rotate[i]->get_text().to_double());
  4158. scale[i] = xform_scale[i]->get_text().to_double();
  4159. }
  4160. t.basis.scale(scale);
  4161. t.basis.rotate(rotate);
  4162. t.origin = translate;
  4163. undo_redo->create_action(TTR("XForm Dialog"));
  4164. List<Node *> &selection = editor_selection->get_selected_node_list();
  4165. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4166. Spatial *sp = Object::cast_to<Spatial>(E->get());
  4167. if (!sp) {
  4168. continue;
  4169. }
  4170. SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
  4171. if (!se) {
  4172. continue;
  4173. }
  4174. bool post = xform_type->get_selected() > 0;
  4175. Transform tr = sp->get_global_gizmo_transform();
  4176. if (post) {
  4177. tr = tr * t;
  4178. } else {
  4179. tr.basis = t.basis * tr.basis;
  4180. tr.origin += t.origin;
  4181. }
  4182. undo_redo->add_do_method(sp, "set_global_transform", tr);
  4183. undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
  4184. }
  4185. undo_redo->commit_action();
  4186. }
  4187. void SpatialEditor::_menu_item_toggled(bool pressed, int p_option) {
  4188. switch (p_option) {
  4189. case MENU_TOOL_LOCAL_COORDS: {
  4190. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(pressed);
  4191. update_transform_gizmo();
  4192. } break;
  4193. case MENU_TOOL_USE_SNAP: {
  4194. tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(pressed);
  4195. snap_enabled = pressed;
  4196. } break;
  4197. case MENU_TOOL_OVERRIDE_CAMERA: {
  4198. ScriptEditorDebugger *const debugger = ScriptEditor::get_singleton()->get_debugger();
  4199. if (pressed) {
  4200. using Override = ScriptEditorDebugger::CameraOverride;
  4201. debugger->set_camera_override((Override)(Override::OVERRIDE_3D_1 + camera_override_viewport_id));
  4202. } else {
  4203. debugger->set_camera_override(ScriptEditorDebugger::OVERRIDE_NONE);
  4204. }
  4205. } break;
  4206. }
  4207. }
  4208. void SpatialEditor::_menu_gizmo_toggled(int p_option) {
  4209. const int idx = gizmos_menu->get_item_index(p_option);
  4210. gizmos_menu->toggle_item_multistate(idx);
  4211. // Change icon
  4212. const int state = gizmos_menu->get_item_state(idx);
  4213. switch (state) {
  4214. case EditorSpatialGizmoPlugin::VISIBLE:
  4215. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_icon("visibility_visible"));
  4216. break;
  4217. case EditorSpatialGizmoPlugin::ON_TOP:
  4218. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_icon("visibility_xray"));
  4219. break;
  4220. case EditorSpatialGizmoPlugin::HIDDEN:
  4221. gizmos_menu->set_item_icon(idx, view_menu->get_popup()->get_icon("visibility_hidden"));
  4222. break;
  4223. }
  4224. gizmo_plugins_by_name.write[p_option]->set_state(state);
  4225. update_all_gizmos();
  4226. }
  4227. void SpatialEditor::_update_camera_override_button(bool p_game_running) {
  4228. Button *const button = tool_option_button[TOOL_OPT_OVERRIDE_CAMERA];
  4229. if (p_game_running) {
  4230. button->set_disabled(false);
  4231. button->set_tooltip(TTR("Project Camera Override\nOverrides the running project's camera with the editor viewport camera."));
  4232. } else {
  4233. button->set_disabled(true);
  4234. button->set_pressed(false);
  4235. button->set_tooltip(TTR("Project Camera Override\nNo project instance running. Run the project from the editor to use this feature."));
  4236. }
  4237. }
  4238. void SpatialEditor::_update_camera_override_viewport(Object *p_viewport) {
  4239. SpatialEditorViewport *current_viewport = Object::cast_to<SpatialEditorViewport>(p_viewport);
  4240. if (!current_viewport) {
  4241. return;
  4242. }
  4243. ScriptEditorDebugger *const debugger = ScriptEditor::get_singleton()->get_debugger();
  4244. camera_override_viewport_id = current_viewport->index;
  4245. if (debugger->get_camera_override() >= ScriptEditorDebugger::OVERRIDE_3D_1) {
  4246. using Override = ScriptEditorDebugger::CameraOverride;
  4247. debugger->set_camera_override((Override)(Override::OVERRIDE_3D_1 + camera_override_viewport_id));
  4248. }
  4249. }
  4250. void SpatialEditor::_menu_item_pressed(int p_option) {
  4251. switch (p_option) {
  4252. case MENU_TOOL_SELECT:
  4253. case MENU_TOOL_MOVE:
  4254. case MENU_TOOL_ROTATE:
  4255. case MENU_TOOL_SCALE:
  4256. case MENU_TOOL_LIST_SELECT: {
  4257. for (int i = 0; i < TOOL_MAX; i++) {
  4258. tool_button[i]->set_pressed(i == p_option);
  4259. }
  4260. tool_mode = (ToolMode)p_option;
  4261. update_transform_gizmo();
  4262. } break;
  4263. case MENU_TOOL_CONVERT_ROOMS: {
  4264. RoomManager::static_rooms_convert();
  4265. update_portal_tools();
  4266. } break;
  4267. case MENU_TRANSFORM_CONFIGURE_SNAP: {
  4268. snap_dialog->popup_centered(Size2(200, 180));
  4269. } break;
  4270. case MENU_TRANSFORM_DIALOG: {
  4271. for (int i = 0; i < 3; i++) {
  4272. xform_translate[i]->set_text("0");
  4273. xform_rotate[i]->set_text("0");
  4274. xform_scale[i]->set_text("1");
  4275. }
  4276. xform_dialog->popup_centered(Size2(320, 240) * EDSCALE);
  4277. } break;
  4278. case MENU_VIEW_USE_1_VIEWPORT: {
  4279. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_1_VIEWPORT);
  4280. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), true);
  4281. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  4282. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  4283. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  4284. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  4285. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  4286. } break;
  4287. case MENU_VIEW_USE_2_VIEWPORTS: {
  4288. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_2_VIEWPORTS);
  4289. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  4290. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), true);
  4291. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  4292. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  4293. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  4294. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  4295. } break;
  4296. case MENU_VIEW_USE_2_VIEWPORTS_ALT: {
  4297. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_2_VIEWPORTS_ALT);
  4298. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  4299. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  4300. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  4301. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  4302. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), true);
  4303. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  4304. } break;
  4305. case MENU_VIEW_USE_3_VIEWPORTS: {
  4306. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_3_VIEWPORTS);
  4307. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  4308. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  4309. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), true);
  4310. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  4311. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  4312. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  4313. } break;
  4314. case MENU_VIEW_USE_3_VIEWPORTS_ALT: {
  4315. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_3_VIEWPORTS_ALT);
  4316. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  4317. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  4318. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  4319. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  4320. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  4321. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), true);
  4322. } break;
  4323. case MENU_VIEW_USE_4_VIEWPORTS: {
  4324. viewport_base->set_view(SpatialEditorViewportContainer::VIEW_USE_4_VIEWPORTS);
  4325. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  4326. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  4327. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  4328. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), true);
  4329. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  4330. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  4331. } break;
  4332. case MENU_VIEW_ORIGIN: {
  4333. bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
  4334. origin_enabled = !is_checked;
  4335. VisualServer::get_singleton()->instance_set_visible(origin_instance, origin_enabled);
  4336. // Update the grid since its appearance depends on whether the origin is enabled
  4337. _finish_grid();
  4338. _init_grid();
  4339. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), origin_enabled);
  4340. } break;
  4341. case MENU_VIEW_GRID: {
  4342. bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
  4343. grid_enabled = !is_checked;
  4344. for (int i = 0; i < 3; ++i) {
  4345. if (grid_enable[i]) {
  4346. grid_visible[i] = grid_enabled;
  4347. }
  4348. }
  4349. _finish_grid();
  4350. _init_grid();
  4351. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), grid_enabled);
  4352. } break;
  4353. case MENU_VIEW_PORTAL_CULLING: {
  4354. bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
  4355. RoomManager::static_rooms_set_active(!is_checked);
  4356. update_portal_tools();
  4357. } break;
  4358. case MENU_VIEW_OCCLUSION_CULLING: {
  4359. int checkbox_id = view_menu->get_popup()->get_item_index(p_option);
  4360. bool is_checked = view_menu->get_popup()->is_item_checked(checkbox_id);
  4361. VisualServer::get_singleton()->set_use_occlusion_culling(!is_checked);
  4362. view_menu->get_popup()->set_item_checked(checkbox_id, !is_checked);
  4363. } break;
  4364. case MENU_VIEW_CAMERA_SETTINGS: {
  4365. settings_dialog->popup_centered(settings_vbc->get_combined_minimum_size() + Size2(50, 50));
  4366. } break;
  4367. case MENU_SNAP_TO_FLOOR: {
  4368. snap_selected_nodes_to_floor();
  4369. } break;
  4370. case MENU_LOCK_SELECTED: {
  4371. undo_redo->create_action(TTR("Lock Selected"));
  4372. List<Node *> &selection = editor_selection->get_selected_node_list();
  4373. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4374. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  4375. if (!spatial || !spatial->is_visible_in_tree()) {
  4376. continue;
  4377. }
  4378. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  4379. continue;
  4380. }
  4381. undo_redo->add_do_method(spatial, "set_meta", "_edit_lock_", true);
  4382. undo_redo->add_undo_method(spatial, "remove_meta", "_edit_lock_");
  4383. undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
  4384. undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
  4385. }
  4386. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  4387. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  4388. undo_redo->commit_action();
  4389. } break;
  4390. case MENU_UNLOCK_SELECTED: {
  4391. undo_redo->create_action(TTR("Unlock Selected"));
  4392. List<Node *> &selection = editor_selection->get_selected_node_list();
  4393. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4394. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  4395. if (!spatial || !spatial->is_visible_in_tree()) {
  4396. continue;
  4397. }
  4398. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  4399. continue;
  4400. }
  4401. undo_redo->add_do_method(spatial, "remove_meta", "_edit_lock_");
  4402. undo_redo->add_undo_method(spatial, "set_meta", "_edit_lock_", true);
  4403. undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
  4404. undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
  4405. }
  4406. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  4407. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  4408. undo_redo->commit_action();
  4409. } break;
  4410. case MENU_GROUP_SELECTED: {
  4411. undo_redo->create_action(TTR("Group Selected"));
  4412. List<Node *> &selection = editor_selection->get_selected_node_list();
  4413. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4414. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  4415. if (!spatial || !spatial->is_visible_in_tree()) {
  4416. continue;
  4417. }
  4418. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  4419. continue;
  4420. }
  4421. undo_redo->add_do_method(spatial, "set_meta", "_edit_group_", true);
  4422. undo_redo->add_undo_method(spatial, "remove_meta", "_edit_group_");
  4423. undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
  4424. undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
  4425. }
  4426. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  4427. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  4428. undo_redo->commit_action();
  4429. } break;
  4430. case MENU_UNGROUP_SELECTED: {
  4431. undo_redo->create_action(TTR("Ungroup Selected"));
  4432. List<Node *> &selection = editor_selection->get_selected_node_list();
  4433. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4434. Spatial *spatial = Object::cast_to<Spatial>(E->get());
  4435. if (!spatial || !spatial->is_visible_in_tree()) {
  4436. continue;
  4437. }
  4438. if (spatial->get_viewport() != EditorNode::get_singleton()->get_scene_root()) {
  4439. continue;
  4440. }
  4441. undo_redo->add_do_method(spatial, "remove_meta", "_edit_group_");
  4442. undo_redo->add_undo_method(spatial, "set_meta", "_edit_group_", true);
  4443. undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
  4444. undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
  4445. }
  4446. undo_redo->add_do_method(this, "_refresh_menu_icons", Variant());
  4447. undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant());
  4448. undo_redo->commit_action();
  4449. } break;
  4450. }
  4451. }
  4452. void SpatialEditor::_init_indicators() {
  4453. {
  4454. origin_enabled = true;
  4455. grid_enabled = true;
  4456. indicator_mat.instance();
  4457. indicator_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  4458. indicator_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  4459. indicator_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  4460. indicator_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  4461. Vector<Color> origin_colors;
  4462. Vector<Vector3> origin_points;
  4463. for (int i = 0; i < 3; i++) {
  4464. Vector3 axis;
  4465. axis[i] = 1;
  4466. Color origin_color;
  4467. switch (i) {
  4468. case 0:
  4469. origin_color = get_color("axis_x_color", "Editor");
  4470. break;
  4471. case 1:
  4472. origin_color = get_color("axis_y_color", "Editor");
  4473. break;
  4474. case 2:
  4475. origin_color = get_color("axis_z_color", "Editor");
  4476. break;
  4477. default:
  4478. origin_color = Color();
  4479. break;
  4480. }
  4481. grid_enable[i] = false;
  4482. grid_visible[i] = false;
  4483. origin_colors.push_back(origin_color);
  4484. origin_colors.push_back(origin_color);
  4485. origin_colors.push_back(origin_color);
  4486. origin_colors.push_back(origin_color);
  4487. origin_colors.push_back(origin_color);
  4488. origin_colors.push_back(origin_color);
  4489. // To both allow having a large origin size and avoid jitter
  4490. // at small scales, we should segment the line into pieces.
  4491. // 3 pieces seems to do the trick, and let's use powers of 2.
  4492. origin_points.push_back(axis * 1048576);
  4493. origin_points.push_back(axis * 1024);
  4494. origin_points.push_back(axis * 1024);
  4495. origin_points.push_back(axis * -1024);
  4496. origin_points.push_back(axis * -1024);
  4497. origin_points.push_back(axis * -1048576);
  4498. }
  4499. Ref<Shader> grid_shader = memnew(Shader);
  4500. grid_shader->set_code(
  4501. "\n"
  4502. "shader_type spatial; \n"
  4503. "render_mode unshaded; \n"
  4504. "uniform bool orthogonal; \n"
  4505. "uniform float grid_size; \n"
  4506. "\n"
  4507. "void vertex() { \n"
  4508. " // From FLAG_SRGB_VERTEX_COLOR \n"
  4509. " if (!OUTPUT_IS_SRGB) { \n"
  4510. " 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))); \n"
  4511. " } \n"
  4512. "} \n"
  4513. "\n"
  4514. "void fragment() { \n"
  4515. " ALBEDO = COLOR.rgb; \n"
  4516. " vec3 dir = orthogonal ? -vec3(0, 0, 1) : VIEW; \n"
  4517. " float angle_fade = abs(dot(dir, NORMAL)); \n"
  4518. " angle_fade = smoothstep(0.05, 0.2, angle_fade); \n"
  4519. " \n"
  4520. " vec3 world_pos = (CAMERA_MATRIX * vec4(VERTEX, 1.0)).xyz; \n"
  4521. " vec3 world_normal = (CAMERA_MATRIX * vec4(NORMAL, 0.0)).xyz; \n"
  4522. " vec3 camera_world_pos = CAMERA_MATRIX[3].xyz; \n"
  4523. " vec3 camera_world_pos_on_plane = camera_world_pos * (1.0 - world_normal); \n"
  4524. " float dist_fade = 1.0 - (distance(world_pos, camera_world_pos_on_plane) / grid_size); \n"
  4525. " dist_fade = smoothstep(0.02, 0.3, dist_fade); \n"
  4526. " \n"
  4527. " ALPHA = COLOR.a * dist_fade * angle_fade; \n"
  4528. "}");
  4529. for (int i = 0; i < 3; i++) {
  4530. grid_mat[i].instance();
  4531. grid_mat[i]->set_shader(grid_shader);
  4532. }
  4533. grid_enable[0] = EditorSettings::get_singleton()->get("editors/3d/grid_xy_plane");
  4534. grid_enable[1] = EditorSettings::get_singleton()->get("editors/3d/grid_yz_plane");
  4535. grid_enable[2] = EditorSettings::get_singleton()->get("editors/3d/grid_xz_plane");
  4536. grid_visible[0] = grid_enable[0];
  4537. grid_visible[1] = grid_enable[1];
  4538. grid_visible[2] = grid_enable[2];
  4539. _init_grid();
  4540. origin = RID_PRIME(VisualServer::get_singleton()->mesh_create());
  4541. Array d;
  4542. d.resize(VS::ARRAY_MAX);
  4543. d[VisualServer::ARRAY_VERTEX] = origin_points;
  4544. d[VisualServer::ARRAY_COLOR] = origin_colors;
  4545. VisualServer::get_singleton()->mesh_add_surface_from_arrays(origin, VisualServer::PRIMITIVE_LINES, d);
  4546. VisualServer::get_singleton()->mesh_surface_set_material(origin, 0, indicator_mat->get_rid());
  4547. origin_instance = VisualServer::get_singleton()->instance_create2(origin, get_tree()->get_root()->get_world()->get_scenario());
  4548. VS::get_singleton()->instance_set_layer_mask(origin_instance, 1 << SpatialEditorViewport::GIZMO_GRID_LAYER);
  4549. VisualServer::get_singleton()->instance_geometry_set_cast_shadows_setting(origin_instance, VS::SHADOW_CASTING_SETTING_OFF);
  4550. }
  4551. {
  4552. //move gizmo
  4553. for (int i = 0; i < 3; i++) {
  4554. Color col;
  4555. switch (i) {
  4556. case 0:
  4557. col = get_color("axis_x_color", "Editor");
  4558. break;
  4559. case 1:
  4560. col = get_color("axis_y_color", "Editor");
  4561. break;
  4562. case 2:
  4563. col = get_color("axis_z_color", "Editor");
  4564. break;
  4565. default:
  4566. col = Color();
  4567. break;
  4568. }
  4569. col.a = EditorSettings::get_singleton()->get("editors/3d/manipulator_gizmo_opacity");
  4570. move_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  4571. move_plane_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  4572. rotate_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  4573. scale_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  4574. scale_plane_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
  4575. Ref<SpatialMaterial> mat = memnew(SpatialMaterial);
  4576. mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  4577. mat->set_on_top_of_alpha();
  4578. mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  4579. mat->set_albedo(col);
  4580. gizmo_color[i] = mat;
  4581. Ref<SpatialMaterial> mat_hl = mat->duplicate();
  4582. const Color albedo = col.from_hsv(col.get_h(), 0.25, 1.0, 1);
  4583. mat_hl->set_albedo(albedo);
  4584. gizmo_color_hl[i] = mat_hl;
  4585. Vector3 ivec;
  4586. ivec[i] = 1;
  4587. Vector3 nivec;
  4588. nivec[(i + 1) % 3] = 1;
  4589. nivec[(i + 2) % 3] = 1;
  4590. Vector3 ivec2;
  4591. ivec2[(i + 1) % 3] = 1;
  4592. Vector3 ivec3;
  4593. ivec3[(i + 2) % 3] = 1;
  4594. //translate
  4595. {
  4596. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  4597. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  4598. // Arrow profile
  4599. const int arrow_points = 5;
  4600. Vector3 arrow[5] = {
  4601. nivec * 0.0 + ivec * 0.0,
  4602. nivec * 0.01 + ivec * 0.0,
  4603. nivec * 0.01 + ivec * GIZMO_ARROW_OFFSET,
  4604. nivec * 0.065 + ivec * GIZMO_ARROW_OFFSET,
  4605. nivec * 0.0 + ivec * (GIZMO_ARROW_OFFSET + GIZMO_ARROW_SIZE),
  4606. };
  4607. int arrow_sides = 16;
  4608. for (int k = 0; k < arrow_sides; k++) {
  4609. Basis ma(ivec, Math_PI * 2 * float(k) / arrow_sides);
  4610. Basis mb(ivec, Math_PI * 2 * float(k + 1) / arrow_sides);
  4611. for (int j = 0; j < arrow_points - 1; j++) {
  4612. Vector3 points[4] = {
  4613. ma.xform(arrow[j]),
  4614. mb.xform(arrow[j]),
  4615. mb.xform(arrow[j + 1]),
  4616. ma.xform(arrow[j + 1]),
  4617. };
  4618. surftool->add_vertex(points[0]);
  4619. surftool->add_vertex(points[1]);
  4620. surftool->add_vertex(points[2]);
  4621. surftool->add_vertex(points[0]);
  4622. surftool->add_vertex(points[2]);
  4623. surftool->add_vertex(points[3]);
  4624. }
  4625. }
  4626. surftool->set_material(mat);
  4627. surftool->commit(move_gizmo[i]);
  4628. }
  4629. // Plane Translation
  4630. {
  4631. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  4632. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  4633. Vector3 vec = ivec2 - ivec3;
  4634. Vector3 plane[4] = {
  4635. vec * GIZMO_PLANE_DST,
  4636. vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
  4637. vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
  4638. vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
  4639. };
  4640. Basis ma(ivec, Math_PI / 2);
  4641. Vector3 points[4] = {
  4642. ma.xform(plane[0]),
  4643. ma.xform(plane[1]),
  4644. ma.xform(plane[2]),
  4645. ma.xform(plane[3]),
  4646. };
  4647. surftool->add_vertex(points[0]);
  4648. surftool->add_vertex(points[1]);
  4649. surftool->add_vertex(points[2]);
  4650. surftool->add_vertex(points[0]);
  4651. surftool->add_vertex(points[2]);
  4652. surftool->add_vertex(points[3]);
  4653. Ref<SpatialMaterial> plane_mat = memnew(SpatialMaterial);
  4654. plane_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  4655. plane_mat->set_on_top_of_alpha();
  4656. plane_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  4657. plane_mat->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  4658. plane_mat->set_albedo(col);
  4659. plane_gizmo_color[i] = plane_mat; // needed, so we can draw planes from both sides
  4660. surftool->set_material(plane_mat);
  4661. surftool->commit(move_plane_gizmo[i]);
  4662. Ref<SpatialMaterial> plane_mat_hl = plane_mat->duplicate();
  4663. plane_mat_hl->set_albedo(albedo);
  4664. plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides
  4665. }
  4666. // Rotate
  4667. {
  4668. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  4669. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  4670. int n = 128; // number of circle segments
  4671. int m = 3; // number of thickness segments
  4672. for (int j = 0; j < n; ++j) {
  4673. Basis basis = Basis(ivec, (Math_PI * 2.0f * j) / n);
  4674. Vector3 vertex = basis.xform(ivec2 * GIZMO_CIRCLE_SIZE);
  4675. for (int k = 0; k < m; ++k) {
  4676. Vector2 ofs = Vector2(Math::cos((Math_PI * 2.0 * k) / m), Math::sin((Math_PI * 2.0 * k) / m));
  4677. Vector3 normal = ivec * ofs.x + ivec2 * ofs.y;
  4678. surftool->add_normal(basis.xform(normal));
  4679. surftool->add_vertex(vertex);
  4680. }
  4681. }
  4682. for (int j = 0; j < n; ++j) {
  4683. for (int k = 0; k < m; ++k) {
  4684. int current_ring = j * m;
  4685. int next_ring = ((j + 1) % n) * m;
  4686. int current_segment = k;
  4687. int next_segment = (k + 1) % m;
  4688. surftool->add_index(current_ring + next_segment);
  4689. surftool->add_index(current_ring + current_segment);
  4690. surftool->add_index(next_ring + current_segment);
  4691. surftool->add_index(next_ring + current_segment);
  4692. surftool->add_index(next_ring + next_segment);
  4693. surftool->add_index(current_ring + next_segment);
  4694. }
  4695. }
  4696. Ref<Shader> rotate_shader = memnew(Shader);
  4697. rotate_shader->set_code(
  4698. "\n"
  4699. "shader_type spatial; \n"
  4700. "render_mode unshaded, depth_test_disable; \n"
  4701. "uniform vec4 albedo; \n"
  4702. "\n"
  4703. "mat3 orthonormalize(mat3 m) { \n"
  4704. " vec3 x = normalize(m[0]); \n"
  4705. " vec3 y = normalize(m[1] - x * dot(x, m[1])); \n"
  4706. " vec3 z = m[2] - x * dot(x, m[2]); \n"
  4707. " z = normalize(z - y * (dot(y,m[2]))); \n"
  4708. " return mat3(x,y,z); \n"
  4709. "} \n"
  4710. "\n"
  4711. "void vertex() { \n"
  4712. " mat3 mv = orthonormalize(mat3(MODELVIEW_MATRIX)); \n"
  4713. " vec3 n = mv * VERTEX; \n"
  4714. " float orientation = dot(vec3(0,0,-1),n); \n"
  4715. " if (orientation <= 0.005) { \n"
  4716. " VERTEX += NORMAL*0.02; \n"
  4717. " } \n"
  4718. "} \n"
  4719. "\n"
  4720. "void fragment() { \n"
  4721. " ALBEDO = albedo.rgb; \n"
  4722. " ALPHA = albedo.a; \n"
  4723. "}");
  4724. Ref<ShaderMaterial> rotate_mat = memnew(ShaderMaterial);
  4725. rotate_mat->set_render_priority(Material::RENDER_PRIORITY_MAX);
  4726. rotate_mat->set_shader(rotate_shader);
  4727. rotate_mat->set_shader_param("albedo", col);
  4728. rotate_gizmo_color[i] = rotate_mat;
  4729. Array arrays = surftool->commit_to_arrays();
  4730. rotate_gizmo[i]->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays);
  4731. rotate_gizmo[i]->surface_set_material(0, rotate_mat);
  4732. Ref<ShaderMaterial> rotate_mat_hl = rotate_mat->duplicate();
  4733. rotate_mat_hl->set_shader_param("albedo", albedo);
  4734. rotate_gizmo_color_hl[i] = rotate_mat_hl;
  4735. if (i == 2) { // Rotation white outline
  4736. Ref<ShaderMaterial> border_mat = rotate_mat->duplicate();
  4737. Ref<Shader> border_shader = memnew(Shader);
  4738. border_shader->set_code(
  4739. "\n"
  4740. "shader_type spatial; \n"
  4741. "render_mode unshaded, depth_test_disable; \n"
  4742. "uniform vec4 albedo; \n"
  4743. "\n"
  4744. "mat3 orthonormalize(mat3 m) { \n"
  4745. " vec3 x = normalize(m[0]); \n"
  4746. " vec3 y = normalize(m[1] - x * dot(x, m[1])); \n"
  4747. " vec3 z = m[2] - x * dot(x, m[2]); \n"
  4748. " z = normalize(z - y * (dot(y,m[2]))); \n"
  4749. " return mat3(x,y,z); \n"
  4750. "} \n"
  4751. "\n"
  4752. "void vertex() { \n"
  4753. " mat3 mv = orthonormalize(mat3(MODELVIEW_MATRIX)); \n"
  4754. " mv = inverse(mv); \n"
  4755. " VERTEX += NORMAL*0.008; \n"
  4756. " vec3 camera_dir_local = mv * vec3(0,0,1); \n"
  4757. " vec3 camera_up_local = mv * vec3(0,1,0); \n"
  4758. " mat3 rotation_matrix = mat3(cross(camera_dir_local, camera_up_local), camera_up_local, camera_dir_local); \n"
  4759. " VERTEX = rotation_matrix * VERTEX; \n"
  4760. "} \n"
  4761. "\n"
  4762. "void fragment() { \n"
  4763. " ALBEDO = albedo.rgb; \n"
  4764. " ALPHA = albedo.a; \n"
  4765. "}");
  4766. border_mat->set_shader(border_shader);
  4767. border_mat->set_shader_param("albedo", Color(0.75, 0.75, 0.75, col.a / 3.0));
  4768. rotate_gizmo[3] = Ref<ArrayMesh>(memnew(ArrayMesh));
  4769. rotate_gizmo[3]->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays);
  4770. rotate_gizmo[3]->surface_set_material(0, border_mat);
  4771. }
  4772. }
  4773. // Scale
  4774. {
  4775. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  4776. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  4777. // Cube arrow profile
  4778. const int arrow_points = 6;
  4779. Vector3 arrow[6] = {
  4780. nivec * 0.0 + ivec * 0.0,
  4781. nivec * 0.01 + ivec * 0.0,
  4782. nivec * 0.01 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
  4783. nivec * 0.07 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
  4784. nivec * 0.07 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
  4785. nivec * 0.0 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
  4786. };
  4787. int arrow_sides = 4;
  4788. for (int k = 0; k < 4; k++) {
  4789. Basis ma(ivec, Math_PI * 2 * float(k) / arrow_sides);
  4790. Basis mb(ivec, Math_PI * 2 * float(k + 1) / arrow_sides);
  4791. for (int j = 0; j < arrow_points - 1; j++) {
  4792. Vector3 points[4] = {
  4793. ma.xform(arrow[j]),
  4794. mb.xform(arrow[j]),
  4795. mb.xform(arrow[j + 1]),
  4796. ma.xform(arrow[j + 1]),
  4797. };
  4798. surftool->add_vertex(points[0]);
  4799. surftool->add_vertex(points[1]);
  4800. surftool->add_vertex(points[2]);
  4801. surftool->add_vertex(points[0]);
  4802. surftool->add_vertex(points[2]);
  4803. surftool->add_vertex(points[3]);
  4804. }
  4805. }
  4806. surftool->set_material(mat);
  4807. surftool->commit(scale_gizmo[i]);
  4808. }
  4809. // Plane Scale
  4810. {
  4811. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  4812. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  4813. Vector3 vec = ivec2 - ivec3;
  4814. Vector3 plane[4] = {
  4815. vec * GIZMO_PLANE_DST,
  4816. vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
  4817. vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
  4818. vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
  4819. };
  4820. Basis ma(ivec, Math_PI / 2);
  4821. Vector3 points[4] = {
  4822. ma.xform(plane[0]),
  4823. ma.xform(plane[1]),
  4824. ma.xform(plane[2]),
  4825. ma.xform(plane[3]),
  4826. };
  4827. surftool->add_vertex(points[0]);
  4828. surftool->add_vertex(points[1]);
  4829. surftool->add_vertex(points[2]);
  4830. surftool->add_vertex(points[0]);
  4831. surftool->add_vertex(points[2]);
  4832. surftool->add_vertex(points[3]);
  4833. Ref<SpatialMaterial> plane_mat = memnew(SpatialMaterial);
  4834. plane_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  4835. plane_mat->set_on_top_of_alpha();
  4836. plane_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  4837. plane_mat->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  4838. plane_mat->set_albedo(col);
  4839. plane_gizmo_color[i] = plane_mat; // needed, so we can draw planes from both sides
  4840. surftool->set_material(plane_mat);
  4841. surftool->commit(scale_plane_gizmo[i]);
  4842. Ref<SpatialMaterial> plane_mat_hl = plane_mat->duplicate();
  4843. plane_mat_hl->set_albedo(col.from_hsv(col.get_h(), 0.25, 1.0, 1));
  4844. plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides
  4845. }
  4846. }
  4847. }
  4848. _generate_selection_boxes();
  4849. }
  4850. void SpatialEditor::_update_context_menu_stylebox() {
  4851. // This must be called when the theme changes to follow the new accent color.
  4852. Ref<StyleBoxFlat> context_menu_stylebox = memnew(StyleBoxFlat);
  4853. const Color accent_color = EditorNode::get_singleton()->get_gui_base()->get_color("accent_color", "Editor");
  4854. context_menu_stylebox->set_bg_color(accent_color * Color(1, 1, 1, 0.1));
  4855. // Add an underline to the StyleBox, but prevent its minimum vertical size from changing.
  4856. context_menu_stylebox->set_border_color(accent_color);
  4857. context_menu_stylebox->set_border_width(MARGIN_BOTTOM, Math::round(2 * EDSCALE));
  4858. context_menu_stylebox->set_default_margin(MARGIN_BOTTOM, 0);
  4859. context_menu_container->add_style_override("panel", context_menu_stylebox);
  4860. }
  4861. void SpatialEditor::_update_gizmos_menu() {
  4862. gizmos_menu->clear();
  4863. for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
  4864. if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
  4865. continue;
  4866. }
  4867. String plugin_name = gizmo_plugins_by_name[i]->get_name();
  4868. const int plugin_state = gizmo_plugins_by_name[i]->get_state();
  4869. gizmos_menu->add_multistate_item(TTR(plugin_name), 3, plugin_state, i);
  4870. const int idx = gizmos_menu->get_item_index(i);
  4871. gizmos_menu->set_item_tooltip(
  4872. idx,
  4873. 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\")."));
  4874. switch (plugin_state) {
  4875. case EditorSpatialGizmoPlugin::VISIBLE:
  4876. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_visible"));
  4877. break;
  4878. case EditorSpatialGizmoPlugin::ON_TOP:
  4879. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_xray"));
  4880. break;
  4881. case EditorSpatialGizmoPlugin::HIDDEN:
  4882. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_hidden"));
  4883. break;
  4884. }
  4885. }
  4886. }
  4887. void SpatialEditor::_update_gizmos_menu_theme() {
  4888. for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
  4889. if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
  4890. continue;
  4891. }
  4892. const int plugin_state = gizmo_plugins_by_name[i]->get_state();
  4893. const int idx = gizmos_menu->get_item_index(i);
  4894. switch (plugin_state) {
  4895. case EditorSpatialGizmoPlugin::VISIBLE:
  4896. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_visible"));
  4897. break;
  4898. case EditorSpatialGizmoPlugin::ON_TOP:
  4899. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_xray"));
  4900. break;
  4901. case EditorSpatialGizmoPlugin::HIDDEN:
  4902. gizmos_menu->set_item_icon(idx, gizmos_menu->get_icon("visibility_hidden"));
  4903. break;
  4904. }
  4905. }
  4906. }
  4907. void SpatialEditor::_init_grid() {
  4908. if (!grid_enabled) {
  4909. return;
  4910. }
  4911. Camera *camera = get_editor_viewport(0)->camera;
  4912. Vector3 camera_position = camera->get_translation();
  4913. if (camera_position == Vector3()) {
  4914. return; // Camera is invalid, don't draw the grid.
  4915. }
  4916. bool orthogonal = camera->get_projection() == Camera::PROJECTION_ORTHOGONAL;
  4917. PoolVector<Color> grid_colors[3];
  4918. PoolVector<Vector3> grid_points[3];
  4919. PoolVector<Vector3> grid_normals[3];
  4920. Color primary_grid_color = EditorSettings::get_singleton()->get("editors/3d/primary_grid_color");
  4921. Color secondary_grid_color = EditorSettings::get_singleton()->get("editors/3d/secondary_grid_color");
  4922. int grid_size = EditorSettings::get_singleton()->get("editors/3d/grid_size");
  4923. int primary_grid_steps = EditorSettings::get_singleton()->get("editors/3d/primary_grid_steps");
  4924. // Which grid planes are enabled? Which should we generate?
  4925. grid_enable[0] = grid_visible[0] = EditorSettings::get_singleton()->get("editors/3d/grid_xy_plane");
  4926. grid_enable[1] = grid_visible[1] = EditorSettings::get_singleton()->get("editors/3d/grid_yz_plane");
  4927. grid_enable[2] = grid_visible[2] = EditorSettings::get_singleton()->get("editors/3d/grid_xz_plane");
  4928. // Offsets division_level for bigger or smaller grids.
  4929. // Default value is -0.2. -1.0 gives Blender-like behavior, 0.5 gives huge grids.
  4930. real_t division_level_bias = EditorSettings::get_singleton()->get("editors/3d/grid_division_level_bias");
  4931. // Default largest grid size is 8^2 when primary_grid_steps is 8 (64m apart, so primary grid lines are 512m apart).
  4932. int division_level_max = EditorSettings::get_singleton()->get("editors/3d/grid_division_level_max");
  4933. // Default smallest grid size is 1cm, 10^-2 (default value is -2).
  4934. int division_level_min = EditorSettings::get_singleton()->get("editors/3d/grid_division_level_min");
  4935. 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.");
  4936. if (primary_grid_steps != 10) { // Log10 of 10 is 1.
  4937. // Change of base rule, divide by ln(10).
  4938. real_t div = Math::log((real_t)primary_grid_steps) / (real_t)2.302585092994045901094;
  4939. // Trucation (towards zero) is intentional.
  4940. division_level_max = (int)(division_level_max / div);
  4941. division_level_min = (int)(division_level_min / div);
  4942. }
  4943. for (int a = 0; a < 3; a++) {
  4944. if (!grid_enable[a]) {
  4945. continue; // If this grid plane is disabled, skip generation.
  4946. }
  4947. int b = (a + 1) % 3;
  4948. int c = (a + 2) % 3;
  4949. Vector3 normal;
  4950. normal[c] = 1.0;
  4951. real_t camera_distance = Math::abs(camera_position[c]);
  4952. if (orthogonal) {
  4953. camera_distance = camera->get_size() / 2.0;
  4954. Vector3 camera_direction = -camera->get_global_transform().get_basis().get_axis(2);
  4955. Plane grid_plane = Plane(Vector3(), normal);
  4956. Vector3 intersection;
  4957. if (grid_plane.intersects_ray(camera_position, camera_direction, &intersection)) {
  4958. camera_position = intersection;
  4959. }
  4960. }
  4961. real_t division_level = Math::log(Math::abs(camera_distance)) / Math::log((double)primary_grid_steps) + division_level_bias;
  4962. real_t clamped_division_level = CLAMP(division_level, division_level_min, division_level_max);
  4963. real_t division_level_floored = Math::floor(clamped_division_level);
  4964. real_t division_level_decimals = clamped_division_level - division_level_floored;
  4965. real_t small_step_size = Math::pow(primary_grid_steps, division_level_floored);
  4966. real_t large_step_size = small_step_size * primary_grid_steps;
  4967. real_t center_a = large_step_size * (int)(camera_position[a] / large_step_size);
  4968. real_t center_b = large_step_size * (int)(camera_position[b] / large_step_size);
  4969. real_t bgn_a = center_a - grid_size * small_step_size;
  4970. real_t end_a = center_a + grid_size * small_step_size;
  4971. real_t bgn_b = center_b - grid_size * small_step_size;
  4972. real_t end_b = center_b + grid_size * small_step_size;
  4973. real_t fade_size = Math::pow(primary_grid_steps, division_level - 1.0);
  4974. real_t min_fade_size = Math::pow(primary_grid_steps, float(division_level_min));
  4975. real_t max_fade_size = Math::pow(primary_grid_steps, float(division_level_max));
  4976. fade_size = CLAMP(fade_size, min_fade_size, max_fade_size);
  4977. real_t grid_fade_size = (grid_size - primary_grid_steps) * fade_size;
  4978. grid_mat[c]->set_shader_param("grid_size", grid_fade_size);
  4979. grid_mat[c]->set_shader_param("orthogonal", orthogonal);
  4980. // In each iteration of this loop, draw one line in each direction (so two lines per loop, in each if statement).
  4981. for (int i = -grid_size; i <= grid_size; i++) {
  4982. Color line_color;
  4983. // Is this a primary line? Set the appropriate color.
  4984. if (i % primary_grid_steps == 0) {
  4985. line_color = primary_grid_color.linear_interpolate(secondary_grid_color, division_level_decimals);
  4986. } else {
  4987. line_color = secondary_grid_color;
  4988. line_color.a = line_color.a * (1 - division_level_decimals);
  4989. }
  4990. real_t position_a = center_a + i * small_step_size;
  4991. real_t position_b = center_b + i * small_step_size;
  4992. // Don't draw lines over the origin if it's enabled.
  4993. if (!(origin_enabled && Math::is_zero_approx(position_a))) {
  4994. Vector3 line_bgn = Vector3();
  4995. Vector3 line_end = Vector3();
  4996. line_bgn[a] = position_a;
  4997. line_end[a] = position_a;
  4998. line_bgn[b] = bgn_b;
  4999. line_end[b] = end_b;
  5000. grid_points[c].push_back(line_bgn);
  5001. grid_points[c].push_back(line_end);
  5002. grid_colors[c].push_back(line_color);
  5003. grid_colors[c].push_back(line_color);
  5004. grid_normals[c].push_back(normal);
  5005. grid_normals[c].push_back(normal);
  5006. }
  5007. if (!(origin_enabled && Math::is_zero_approx(position_b))) {
  5008. Vector3 line_bgn = Vector3();
  5009. Vector3 line_end = Vector3();
  5010. line_bgn[b] = position_b;
  5011. line_end[b] = position_b;
  5012. line_bgn[a] = bgn_a;
  5013. line_end[a] = end_a;
  5014. grid_points[c].push_back(line_bgn);
  5015. grid_points[c].push_back(line_end);
  5016. grid_colors[c].push_back(line_color);
  5017. grid_colors[c].push_back(line_color);
  5018. grid_normals[c].push_back(normal);
  5019. grid_normals[c].push_back(normal);
  5020. }
  5021. }
  5022. // Create a mesh from the pushed vector points and colors.
  5023. grid[c] = RID_PRIME(VisualServer::get_singleton()->mesh_create());
  5024. Array d;
  5025. d.resize(VS::ARRAY_MAX);
  5026. d[VisualServer::ARRAY_VERTEX] = grid_points[c];
  5027. d[VisualServer::ARRAY_COLOR] = grid_colors[c];
  5028. d[VisualServer::ARRAY_NORMAL] = grid_normals[c];
  5029. VisualServer::get_singleton()->mesh_add_surface_from_arrays(grid[c], VisualServer::PRIMITIVE_LINES, d);
  5030. VisualServer::get_singleton()->mesh_surface_set_material(grid[c], 0, grid_mat[c]->get_rid());
  5031. grid_instance[c] = VisualServer::get_singleton()->instance_create2(grid[c], get_tree()->get_root()->get_world()->get_scenario());
  5032. // Yes, the end of this line is supposed to be a.
  5033. VisualServer::get_singleton()->instance_set_visible(grid_instance[c], grid_visible[a]);
  5034. VisualServer::get_singleton()->instance_geometry_set_cast_shadows_setting(grid_instance[c], VS::SHADOW_CASTING_SETTING_OFF);
  5035. VS::get_singleton()->instance_set_layer_mask(grid_instance[c], 1 << SpatialEditorViewport::GIZMO_GRID_LAYER);
  5036. }
  5037. }
  5038. void SpatialEditor::_finish_indicators() {
  5039. if (origin_instance.is_valid()) {
  5040. VisualServer::get_singleton()->free(origin_instance);
  5041. origin_instance = RID();
  5042. }
  5043. if (origin.is_valid()) {
  5044. VisualServer::get_singleton()->free(origin);
  5045. origin = RID();
  5046. }
  5047. _finish_grid();
  5048. }
  5049. void SpatialEditor::_finish_grid() {
  5050. for (int i = 0; i < 3; i++) {
  5051. if (grid_instance[i].is_valid()) {
  5052. VisualServer::get_singleton()->free(grid_instance[i]);
  5053. grid_instance[i] = RID();
  5054. }
  5055. if (grid[i].is_valid()) {
  5056. VisualServer::get_singleton()->free(grid[i]);
  5057. grid[i] = RID();
  5058. }
  5059. }
  5060. }
  5061. void SpatialEditor::update_grid() {
  5062. _finish_grid();
  5063. _init_grid();
  5064. }
  5065. bool SpatialEditor::is_any_freelook_active() const {
  5066. for (unsigned int i = 0; i < VIEWPORTS_COUNT; ++i) {
  5067. if (viewports[i]->is_freelook_active()) {
  5068. return true;
  5069. }
  5070. }
  5071. return false;
  5072. }
  5073. void SpatialEditor::_refresh_menu_icons() {
  5074. bool all_locked = true;
  5075. bool all_grouped = true;
  5076. List<Node *> &selection = editor_selection->get_selected_node_list();
  5077. if (selection.empty()) {
  5078. all_locked = false;
  5079. all_grouped = false;
  5080. } else {
  5081. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  5082. if (Object::cast_to<Spatial>(E->get()) && !Object::cast_to<Spatial>(E->get())->has_meta("_edit_lock_")) {
  5083. all_locked = false;
  5084. break;
  5085. }
  5086. }
  5087. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  5088. if (Object::cast_to<Spatial>(E->get()) && !Object::cast_to<Spatial>(E->get())->has_meta("_edit_group_")) {
  5089. all_grouped = false;
  5090. break;
  5091. }
  5092. }
  5093. }
  5094. tool_button[TOOL_LOCK_SELECTED]->set_visible(!all_locked);
  5095. tool_button[TOOL_LOCK_SELECTED]->set_disabled(selection.empty());
  5096. tool_button[TOOL_UNLOCK_SELECTED]->set_visible(all_locked);
  5097. tool_button[TOOL_GROUP_SELECTED]->set_visible(!all_grouped);
  5098. tool_button[TOOL_GROUP_SELECTED]->set_disabled(selection.empty());
  5099. tool_button[TOOL_UNGROUP_SELECTED]->set_visible(all_grouped);
  5100. }
  5101. template <typename T>
  5102. Set<T *> _get_child_nodes(Node *parent_node) {
  5103. Set<T *> nodes = Set<T *>();
  5104. T *node = Node::cast_to<T>(parent_node);
  5105. if (node) {
  5106. nodes.insert(node);
  5107. }
  5108. for (int i = 0; i < parent_node->get_child_count(); i++) {
  5109. Node *child_node = parent_node->get_child(i);
  5110. Set<T *> child_nodes = _get_child_nodes<T>(child_node);
  5111. for (typename Set<T *>::Element *I = child_nodes.front(); I; I = I->next()) {
  5112. nodes.insert(I->get());
  5113. }
  5114. }
  5115. return nodes;
  5116. }
  5117. Set<RID> _get_physics_bodies_rid(Node *node) {
  5118. Set<RID> rids = Set<RID>();
  5119. PhysicsBody *pb = Node::cast_to<PhysicsBody>(node);
  5120. if (pb) {
  5121. rids.insert(pb->get_rid());
  5122. }
  5123. Set<PhysicsBody *> child_nodes = _get_child_nodes<PhysicsBody>(node);
  5124. for (Set<PhysicsBody *>::Element *I = child_nodes.front(); I; I = I->next()) {
  5125. rids.insert(I->get()->get_rid());
  5126. }
  5127. return rids;
  5128. }
  5129. void SpatialEditor::snap_selected_nodes_to_floor() {
  5130. List<Node *> &selection = editor_selection->get_selected_node_list();
  5131. Dictionary snap_data;
  5132. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  5133. Spatial *sp = Object::cast_to<Spatial>(E->get());
  5134. if (sp) {
  5135. Vector3 from = Vector3();
  5136. Vector3 position_offset = Vector3();
  5137. // Priorities for snapping to floor are CollisionShapes, VisualInstances and then origin
  5138. Set<VisualInstance *> vi = _get_child_nodes<VisualInstance>(sp);
  5139. Set<CollisionShape *> cs = _get_child_nodes<CollisionShape>(sp);
  5140. bool found_valid_shape = false;
  5141. if (cs.size()) {
  5142. AABB aabb;
  5143. Set<CollisionShape *>::Element *I = cs.front();
  5144. if (I->get()->get_shape().is_valid()) {
  5145. CollisionShape *collision_shape = cs.front()->get();
  5146. aabb = collision_shape->get_global_transform().xform(collision_shape->get_shape()->get_debug_mesh()->get_aabb());
  5147. found_valid_shape = true;
  5148. }
  5149. for (I = I->next(); I; I = I->next()) {
  5150. CollisionShape *col_shape = I->get();
  5151. if (col_shape->get_shape().is_valid()) {
  5152. aabb.merge_with(col_shape->get_global_transform().xform(col_shape->get_shape()->get_debug_mesh()->get_aabb()));
  5153. found_valid_shape = true;
  5154. }
  5155. }
  5156. if (found_valid_shape) {
  5157. Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
  5158. from = aabb.position + size;
  5159. position_offset.y = from.y - sp->get_global_transform().origin.y;
  5160. }
  5161. }
  5162. if (!found_valid_shape && vi.size()) {
  5163. AABB aabb = vi.front()->get()->get_transformed_aabb();
  5164. for (Set<VisualInstance *>::Element *I = vi.front(); I; I = I->next()) {
  5165. aabb.merge_with(I->get()->get_transformed_aabb());
  5166. }
  5167. Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
  5168. from = aabb.position + size;
  5169. position_offset.y = from.y - sp->get_global_transform().origin.y;
  5170. } else if (!found_valid_shape) {
  5171. from = sp->get_global_transform().origin;
  5172. }
  5173. // We add a bit of margin to the from position to avoid it from snapping
  5174. // when the spatial is already on a floor and there's another floor under
  5175. // it
  5176. from = from + Vector3(0.0, 1, 0.0);
  5177. Dictionary d;
  5178. d["from"] = from;
  5179. d["position_offset"] = position_offset;
  5180. snap_data[sp] = d;
  5181. }
  5182. }
  5183. PhysicsDirectSpaceState *ss = get_tree()->get_root()->get_world()->get_direct_space_state();
  5184. PhysicsDirectSpaceState::RayResult result;
  5185. Array keys = snap_data.keys();
  5186. // The maximum height an object can travel to be snapped
  5187. const float max_snap_height = 500.0;
  5188. // Will be set to `true` if at least one node from the selection was successfully snapped
  5189. bool snapped_to_floor = false;
  5190. if (keys.size()) {
  5191. // For snapping to be performed, there must be solid geometry under at least one of the selected nodes.
  5192. // We need to check this before snapping to register the undo/redo action only if needed.
  5193. for (int i = 0; i < keys.size(); i++) {
  5194. Node *node = keys[i];
  5195. Spatial *sp = Object::cast_to<Spatial>(node);
  5196. Dictionary d = snap_data[node];
  5197. Vector3 from = d["from"];
  5198. Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
  5199. Set<RID> excluded = _get_physics_bodies_rid(sp);
  5200. if (ss->intersect_ray(from, to, result, excluded)) {
  5201. snapped_to_floor = true;
  5202. }
  5203. }
  5204. if (snapped_to_floor) {
  5205. undo_redo->create_action(TTR("Snap Nodes to Floor"));
  5206. // Perform snapping if at least one node can be snapped
  5207. for (int i = 0; i < keys.size(); i++) {
  5208. Node *node = keys[i];
  5209. Spatial *sp = Object::cast_to<Spatial>(node);
  5210. Dictionary d = snap_data[node];
  5211. Vector3 from = d["from"];
  5212. Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
  5213. Set<RID> excluded = _get_physics_bodies_rid(sp);
  5214. if (ss->intersect_ray(from, to, result, excluded)) {
  5215. Vector3 position_offset = d["position_offset"];
  5216. Transform new_transform = sp->get_global_transform();
  5217. new_transform.origin.y = result.position.y;
  5218. new_transform.origin = new_transform.origin - position_offset;
  5219. undo_redo->add_do_method(sp, "set_global_transform", new_transform);
  5220. undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_transform());
  5221. }
  5222. }
  5223. undo_redo->commit_action();
  5224. } else {
  5225. EditorNode::get_singleton()->show_warning(TTR("Couldn't find a solid floor to snap the selection to."));
  5226. }
  5227. }
  5228. }
  5229. void SpatialEditor::_unhandled_key_input(Ref<InputEvent> p_event) {
  5230. ERR_FAIL_COND(p_event.is_null());
  5231. if (!is_visible_in_tree() || get_viewport()->gui_has_modal_stack()) {
  5232. return;
  5233. }
  5234. snap_key_enabled = Input::get_singleton()->is_key_pressed(KEY_CONTROL);
  5235. }
  5236. void SpatialEditor::_notification(int p_what) {
  5237. if (p_what == NOTIFICATION_READY) {
  5238. tool_button[SpatialEditor::TOOL_MODE_SELECT]->set_icon(get_icon("ToolSelect", "EditorIcons"));
  5239. tool_button[SpatialEditor::TOOL_MODE_MOVE]->set_icon(get_icon("ToolMove", "EditorIcons"));
  5240. tool_button[SpatialEditor::TOOL_MODE_ROTATE]->set_icon(get_icon("ToolRotate", "EditorIcons"));
  5241. tool_button[SpatialEditor::TOOL_MODE_SCALE]->set_icon(get_icon("ToolScale", "EditorIcons"));
  5242. tool_button[SpatialEditor::TOOL_MODE_LIST_SELECT]->set_icon(get_icon("ListSelect", "EditorIcons"));
  5243. tool_button[SpatialEditor::TOOL_LOCK_SELECTED]->set_icon(get_icon("Lock", "EditorIcons"));
  5244. tool_button[SpatialEditor::TOOL_UNLOCK_SELECTED]->set_icon(get_icon("Unlock", "EditorIcons"));
  5245. tool_button[SpatialEditor::TOOL_GROUP_SELECTED]->set_icon(get_icon("Group", "EditorIcons"));
  5246. tool_button[SpatialEditor::TOOL_UNGROUP_SELECTED]->set_icon(get_icon("Ungroup", "EditorIcons"));
  5247. tool_button[SpatialEditor::TOOL_CONVERT_ROOMS]->set_icon(get_icon("RoomGroup", "EditorIcons"));
  5248. tool_option_button[SpatialEditor::TOOL_OPT_LOCAL_COORDS]->set_icon(get_icon("Object", "EditorIcons"));
  5249. tool_option_button[SpatialEditor::TOOL_OPT_USE_SNAP]->set_icon(get_icon("Snap", "EditorIcons"));
  5250. tool_option_button[SpatialEditor::TOOL_OPT_OVERRIDE_CAMERA]->set_icon(get_icon("Camera", "EditorIcons"));
  5251. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), get_icon("Panels1", "EditorIcons"));
  5252. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), get_icon("Panels2", "EditorIcons"));
  5253. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), get_icon("Panels2Alt", "EditorIcons"));
  5254. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), get_icon("Panels3", "EditorIcons"));
  5255. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), get_icon("Panels3Alt", "EditorIcons"));
  5256. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), get_icon("Panels4", "EditorIcons"));
  5257. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  5258. _refresh_menu_icons();
  5259. get_tree()->connect("node_removed", this, "_node_removed");
  5260. EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor()->connect("node_changed", this, "_refresh_menu_icons");
  5261. editor_selection->connect("selection_changed", this, "_refresh_menu_icons");
  5262. editor->connect("stop_pressed", this, "_update_camera_override_button", make_binds(false));
  5263. editor->connect("play_pressed", this, "_update_camera_override_button", make_binds(true));
  5264. } else if (p_what == NOTIFICATION_ENTER_TREE) {
  5265. _register_all_gizmos();
  5266. _update_gizmos_menu();
  5267. _init_indicators();
  5268. } else if (p_what == NOTIFICATION_THEME_CHANGED) {
  5269. _update_gizmos_menu_theme();
  5270. _update_context_menu_stylebox();
  5271. } else if (p_what == NOTIFICATION_EXIT_TREE) {
  5272. _finish_indicators();
  5273. } else if (p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) {
  5274. tool_button[SpatialEditor::TOOL_MODE_SELECT]->set_icon(get_icon("ToolSelect", "EditorIcons"));
  5275. tool_button[SpatialEditor::TOOL_MODE_MOVE]->set_icon(get_icon("ToolMove", "EditorIcons"));
  5276. tool_button[SpatialEditor::TOOL_MODE_ROTATE]->set_icon(get_icon("ToolRotate", "EditorIcons"));
  5277. tool_button[SpatialEditor::TOOL_MODE_SCALE]->set_icon(get_icon("ToolScale", "EditorIcons"));
  5278. tool_button[SpatialEditor::TOOL_MODE_LIST_SELECT]->set_icon(get_icon("ListSelect", "EditorIcons"));
  5279. tool_button[SpatialEditor::TOOL_LOCK_SELECTED]->set_icon(get_icon("Lock", "EditorIcons"));
  5280. tool_button[SpatialEditor::TOOL_UNLOCK_SELECTED]->set_icon(get_icon("Unlock", "EditorIcons"));
  5281. tool_button[SpatialEditor::TOOL_GROUP_SELECTED]->set_icon(get_icon("Group", "EditorIcons"));
  5282. tool_button[SpatialEditor::TOOL_UNGROUP_SELECTED]->set_icon(get_icon("Ungroup", "EditorIcons"));
  5283. tool_option_button[SpatialEditor::TOOL_OPT_LOCAL_COORDS]->set_icon(get_icon("Object", "EditorIcons"));
  5284. tool_option_button[SpatialEditor::TOOL_OPT_USE_SNAP]->set_icon(get_icon("Snap", "EditorIcons"));
  5285. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), get_icon("Panels1", "EditorIcons"));
  5286. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), get_icon("Panels2", "EditorIcons"));
  5287. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), get_icon("Panels2Alt", "EditorIcons"));
  5288. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), get_icon("Panels3", "EditorIcons"));
  5289. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), get_icon("Panels3Alt", "EditorIcons"));
  5290. view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), get_icon("Panels4", "EditorIcons"));
  5291. // Update grid color by rebuilding grid.
  5292. _finish_grid();
  5293. _init_grid();
  5294. } else if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
  5295. if (!is_visible() && tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->is_pressed()) {
  5296. ScriptEditorDebugger *debugger = ScriptEditor::get_singleton()->get_debugger();
  5297. debugger->set_camera_override(ScriptEditorDebugger::OVERRIDE_NONE);
  5298. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_pressed(false);
  5299. }
  5300. }
  5301. }
  5302. void SpatialEditor::add_control_to_menu_panel(Control *p_control) {
  5303. hbc_context_menu->add_child(p_control);
  5304. }
  5305. void SpatialEditor::remove_control_from_menu_panel(Control *p_control) {
  5306. hbc_context_menu->remove_child(p_control);
  5307. }
  5308. void SpatialEditor::set_can_preview(Camera *p_preview) {
  5309. for (int i = 0; i < 4; i++) {
  5310. viewports[i]->set_can_preview(p_preview);
  5311. }
  5312. }
  5313. void SpatialEditor::set_message(String p_message, float p_time) {
  5314. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  5315. SpatialEditorViewport *viewport = get_editor_viewport(i);
  5316. if (viewport->is_visible()) {
  5317. viewport->set_message(p_message, p_time);
  5318. }
  5319. }
  5320. }
  5321. VSplitContainer *SpatialEditor::get_shader_split() {
  5322. return shader_split;
  5323. }
  5324. void SpatialEditor::add_control_to_left_panel(Control *p_control) {
  5325. left_panel_split->add_child(p_control);
  5326. left_panel_split->move_child(p_control, 0);
  5327. }
  5328. void SpatialEditor::add_control_to_right_panel(Control *p_control) {
  5329. right_panel_split->add_child(p_control);
  5330. right_panel_split->move_child(p_control, 1);
  5331. }
  5332. void SpatialEditor::remove_control_from_left_panel(Control *p_control) {
  5333. left_panel_split->remove_child(p_control);
  5334. }
  5335. void SpatialEditor::remove_control_from_right_panel(Control *p_control) {
  5336. right_panel_split->remove_child(p_control);
  5337. }
  5338. void SpatialEditor::move_control_to_left_panel(Control *p_control) {
  5339. ERR_FAIL_NULL(p_control);
  5340. if (p_control->get_parent() == left_panel_split) {
  5341. return;
  5342. }
  5343. ERR_FAIL_COND(p_control->get_parent() != right_panel_split);
  5344. right_panel_split->remove_child(p_control);
  5345. add_control_to_left_panel(p_control);
  5346. }
  5347. void SpatialEditor::move_control_to_right_panel(Control *p_control) {
  5348. ERR_FAIL_NULL(p_control);
  5349. if (p_control->get_parent() == right_panel_split) {
  5350. return;
  5351. }
  5352. ERR_FAIL_COND(p_control->get_parent() != left_panel_split);
  5353. left_panel_split->remove_child(p_control);
  5354. add_control_to_right_panel(p_control);
  5355. }
  5356. void SpatialEditor::_request_gizmo(Object *p_obj) {
  5357. Spatial *sp = Object::cast_to<Spatial>(p_obj);
  5358. if (!sp) {
  5359. return;
  5360. }
  5361. if (editor->get_edited_scene() && (sp == editor->get_edited_scene() || (sp->get_owner() && editor->get_edited_scene()->is_a_parent_of(sp)))) {
  5362. Ref<EditorSpatialGizmo> seg;
  5363. for (int i = 0; i < gizmo_plugins_by_priority.size(); ++i) {
  5364. seg = gizmo_plugins_by_priority.write[i]->get_gizmo(sp);
  5365. if (seg.is_valid()) {
  5366. sp->set_gizmo(seg);
  5367. if (sp == selected) {
  5368. seg->set_selected(true);
  5369. selected->update_gizmo();
  5370. }
  5371. break;
  5372. }
  5373. }
  5374. }
  5375. }
  5376. void SpatialEditor::_toggle_maximize_view(Object *p_viewport) {
  5377. if (!p_viewport) {
  5378. return;
  5379. }
  5380. SpatialEditorViewport *current_viewport = Object::cast_to<SpatialEditorViewport>(p_viewport);
  5381. if (!current_viewport) {
  5382. return;
  5383. }
  5384. int index = -1;
  5385. bool maximized = false;
  5386. for (int i = 0; i < 4; i++) {
  5387. if (viewports[i] == current_viewport) {
  5388. index = i;
  5389. if (current_viewport->get_global_rect() == viewport_base->get_global_rect()) {
  5390. maximized = true;
  5391. }
  5392. break;
  5393. }
  5394. }
  5395. if (index == -1) {
  5396. return;
  5397. }
  5398. if (!maximized) {
  5399. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  5400. if (i == (uint32_t)index) {
  5401. viewports[i]->set_anchors_and_margins_preset(Control::PRESET_WIDE);
  5402. } else {
  5403. viewports[i]->hide();
  5404. }
  5405. }
  5406. } else {
  5407. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  5408. viewports[i]->show();
  5409. }
  5410. if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT))) {
  5411. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  5412. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS))) {
  5413. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
  5414. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT))) {
  5415. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
  5416. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS))) {
  5417. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
  5418. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT))) {
  5419. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
  5420. } else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS))) {
  5421. _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
  5422. }
  5423. }
  5424. }
  5425. void SpatialEditor::_node_removed(Node *p_node) {
  5426. if (p_node == selected) {
  5427. selected = nullptr;
  5428. }
  5429. }
  5430. void SpatialEditor::_register_all_gizmos() {
  5431. add_gizmo_plugin(Ref<CameraSpatialGizmoPlugin>(memnew(CameraSpatialGizmoPlugin)));
  5432. add_gizmo_plugin(Ref<LightSpatialGizmoPlugin>(memnew(LightSpatialGizmoPlugin)));
  5433. add_gizmo_plugin(Ref<AudioStreamPlayer3DSpatialGizmoPlugin>(memnew(AudioStreamPlayer3DSpatialGizmoPlugin)));
  5434. add_gizmo_plugin(Ref<ListenerSpatialGizmoPlugin>(memnew(ListenerSpatialGizmoPlugin)));
  5435. add_gizmo_plugin(Ref<MeshInstanceSpatialGizmoPlugin>(memnew(MeshInstanceSpatialGizmoPlugin)));
  5436. add_gizmo_plugin(Ref<SoftBodySpatialGizmoPlugin>(memnew(SoftBodySpatialGizmoPlugin)));
  5437. add_gizmo_plugin(Ref<Sprite3DSpatialGizmoPlugin>(memnew(Sprite3DSpatialGizmoPlugin)));
  5438. add_gizmo_plugin(Ref<SkeletonSpatialGizmoPlugin>(memnew(SkeletonSpatialGizmoPlugin)));
  5439. add_gizmo_plugin(Ref<Position3DSpatialGizmoPlugin>(memnew(Position3DSpatialGizmoPlugin)));
  5440. add_gizmo_plugin(Ref<RayCastSpatialGizmoPlugin>(memnew(RayCastSpatialGizmoPlugin)));
  5441. add_gizmo_plugin(Ref<SpringArmSpatialGizmoPlugin>(memnew(SpringArmSpatialGizmoPlugin)));
  5442. add_gizmo_plugin(Ref<VehicleWheelSpatialGizmoPlugin>(memnew(VehicleWheelSpatialGizmoPlugin)));
  5443. add_gizmo_plugin(Ref<VisibilityNotifierGizmoPlugin>(memnew(VisibilityNotifierGizmoPlugin)));
  5444. add_gizmo_plugin(Ref<ParticlesGizmoPlugin>(memnew(ParticlesGizmoPlugin)));
  5445. add_gizmo_plugin(Ref<CPUParticlesGizmoPlugin>(memnew(CPUParticlesGizmoPlugin)));
  5446. add_gizmo_plugin(Ref<ReflectionProbeGizmoPlugin>(memnew(ReflectionProbeGizmoPlugin)));
  5447. add_gizmo_plugin(Ref<GIProbeGizmoPlugin>(memnew(GIProbeGizmoPlugin)));
  5448. add_gizmo_plugin(Ref<BakedIndirectLightGizmoPlugin>(memnew(BakedIndirectLightGizmoPlugin)));
  5449. add_gizmo_plugin(Ref<CollisionObjectGizmoPlugin>(memnew(CollisionObjectGizmoPlugin)));
  5450. add_gizmo_plugin(Ref<CollisionShapeSpatialGizmoPlugin>(memnew(CollisionShapeSpatialGizmoPlugin)));
  5451. add_gizmo_plugin(Ref<CollisionPolygonSpatialGizmoPlugin>(memnew(CollisionPolygonSpatialGizmoPlugin)));
  5452. add_gizmo_plugin(Ref<NavigationMeshSpatialGizmoPlugin>(memnew(NavigationMeshSpatialGizmoPlugin)));
  5453. add_gizmo_plugin(Ref<JointSpatialGizmoPlugin>(memnew(JointSpatialGizmoPlugin)));
  5454. add_gizmo_plugin(Ref<PhysicalBoneSpatialGizmoPlugin>(memnew(PhysicalBoneSpatialGizmoPlugin)));
  5455. }
  5456. void SpatialEditor::_bind_methods() {
  5457. ClassDB::bind_method("_unhandled_key_input", &SpatialEditor::_unhandled_key_input);
  5458. ClassDB::bind_method("_node_removed", &SpatialEditor::_node_removed);
  5459. ClassDB::bind_method("_menu_item_pressed", &SpatialEditor::_menu_item_pressed);
  5460. ClassDB::bind_method("_menu_gizmo_toggled", &SpatialEditor::_menu_gizmo_toggled);
  5461. ClassDB::bind_method("_menu_item_toggled", &SpatialEditor::_menu_item_toggled);
  5462. ClassDB::bind_method("_xform_dialog_action", &SpatialEditor::_xform_dialog_action);
  5463. ClassDB::bind_method("_get_editor_data", &SpatialEditor::_get_editor_data);
  5464. ClassDB::bind_method("_request_gizmo", &SpatialEditor::_request_gizmo);
  5465. ClassDB::bind_method("_toggle_maximize_view", &SpatialEditor::_toggle_maximize_view);
  5466. ClassDB::bind_method("_refresh_menu_icons", &SpatialEditor::_refresh_menu_icons);
  5467. ClassDB::bind_method("_update_camera_override_button", &SpatialEditor::_update_camera_override_button);
  5468. ClassDB::bind_method("_update_camera_override_viewport", &SpatialEditor::_update_camera_override_viewport);
  5469. ClassDB::bind_method("_snap_changed", &SpatialEditor::_snap_changed);
  5470. ClassDB::bind_method("_snap_update", &SpatialEditor::_snap_update);
  5471. ADD_SIGNAL(MethodInfo("transform_key_request"));
  5472. ADD_SIGNAL(MethodInfo("item_lock_status_changed"));
  5473. ADD_SIGNAL(MethodInfo("item_group_status_changed"));
  5474. }
  5475. void SpatialEditor::clear() {
  5476. settings_fov->set_value(EDITOR_DEF("editors/3d/default_fov", 70.0));
  5477. settings_znear->set_value(EDITOR_DEF("editors/3d/default_z_near", 0.05));
  5478. settings_zfar->set_value(EDITOR_DEF("editors/3d/default_z_far", 1500.0));
  5479. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  5480. viewports[i]->reset();
  5481. }
  5482. VisualServer::get_singleton()->instance_set_visible(origin_instance, true);
  5483. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), true);
  5484. for (int i = 0; i < 3; ++i) {
  5485. if (grid_enable[i]) {
  5486. grid_visible[i] = true;
  5487. }
  5488. }
  5489. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  5490. viewports[i]->view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(SpatialEditorViewport::VIEW_AUDIO_LISTENER), i == 0);
  5491. viewports[i]->viewport->set_as_audio_listener(i == 0);
  5492. }
  5493. view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID), true);
  5494. }
  5495. SpatialEditor::SpatialEditor(EditorNode *p_editor) {
  5496. gizmo.visible = true;
  5497. gizmo.scale = 1.0;
  5498. viewport_environment = Ref<Environment>(memnew(Environment));
  5499. undo_redo = p_editor->get_undo_redo();
  5500. VBoxContainer *vbc = this;
  5501. custom_camera = nullptr;
  5502. singleton = this;
  5503. editor = p_editor;
  5504. editor_selection = editor->get_editor_selection();
  5505. editor_selection->add_editor_plugin(this);
  5506. snap_enabled = false;
  5507. snap_key_enabled = false;
  5508. tool_mode = TOOL_MODE_SELECT;
  5509. camera_override_viewport_id = 0;
  5510. hbc_menu = memnew(HBoxContainer);
  5511. vbc->add_child(hbc_menu);
  5512. Vector<Variant> button_binds;
  5513. button_binds.resize(1);
  5514. String sct;
  5515. tool_button[TOOL_MODE_SELECT] = memnew(ToolButton);
  5516. hbc_menu->add_child(tool_button[TOOL_MODE_SELECT]);
  5517. tool_button[TOOL_MODE_SELECT]->set_toggle_mode(true);
  5518. tool_button[TOOL_MODE_SELECT]->set_flat(true);
  5519. tool_button[TOOL_MODE_SELECT]->set_pressed(true);
  5520. button_binds.write[0] = MENU_TOOL_SELECT;
  5521. tool_button[TOOL_MODE_SELECT]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5522. tool_button[TOOL_MODE_SELECT]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_select", TTR("Select Mode"), KEY_Q));
  5523. tool_button[TOOL_MODE_SELECT]->set_tooltip(keycode_get_string(KEY_MASK_CMD) + TTR("Drag: Rotate selected node around pivot.") + "\n" + TTR("Alt+RMB: Show list of all nodes at position clicked, including locked."));
  5524. hbc_menu->add_child(memnew(VSeparator));
  5525. tool_button[TOOL_MODE_MOVE] = memnew(ToolButton);
  5526. hbc_menu->add_child(tool_button[TOOL_MODE_MOVE]);
  5527. tool_button[TOOL_MODE_MOVE]->set_toggle_mode(true);
  5528. tool_button[TOOL_MODE_MOVE]->set_flat(true);
  5529. button_binds.write[0] = MENU_TOOL_MOVE;
  5530. tool_button[TOOL_MODE_MOVE]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5531. tool_button[TOOL_MODE_MOVE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_move", TTR("Move Mode"), KEY_W));
  5532. tool_button[TOOL_MODE_ROTATE] = memnew(ToolButton);
  5533. hbc_menu->add_child(tool_button[TOOL_MODE_ROTATE]);
  5534. tool_button[TOOL_MODE_ROTATE]->set_toggle_mode(true);
  5535. tool_button[TOOL_MODE_ROTATE]->set_flat(true);
  5536. button_binds.write[0] = MENU_TOOL_ROTATE;
  5537. tool_button[TOOL_MODE_ROTATE]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5538. tool_button[TOOL_MODE_ROTATE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_rotate", TTR("Rotate Mode"), KEY_E));
  5539. tool_button[TOOL_MODE_SCALE] = memnew(ToolButton);
  5540. hbc_menu->add_child(tool_button[TOOL_MODE_SCALE]);
  5541. tool_button[TOOL_MODE_SCALE]->set_toggle_mode(true);
  5542. tool_button[TOOL_MODE_SCALE]->set_flat(true);
  5543. button_binds.write[0] = MENU_TOOL_SCALE;
  5544. tool_button[TOOL_MODE_SCALE]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5545. tool_button[TOOL_MODE_SCALE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_scale", TTR("Scale Mode"), KEY_R));
  5546. hbc_menu->add_child(memnew(VSeparator));
  5547. tool_button[TOOL_MODE_LIST_SELECT] = memnew(ToolButton);
  5548. hbc_menu->add_child(tool_button[TOOL_MODE_LIST_SELECT]);
  5549. tool_button[TOOL_MODE_LIST_SELECT]->set_toggle_mode(true);
  5550. tool_button[TOOL_MODE_LIST_SELECT]->set_flat(true);
  5551. button_binds.write[0] = MENU_TOOL_LIST_SELECT;
  5552. tool_button[TOOL_MODE_LIST_SELECT]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5553. tool_button[TOOL_MODE_LIST_SELECT]->set_tooltip(TTR("Show a list of all objects at the position clicked\n(same as Alt+RMB in select mode)."));
  5554. tool_button[TOOL_LOCK_SELECTED] = memnew(ToolButton);
  5555. hbc_menu->add_child(tool_button[TOOL_LOCK_SELECTED]);
  5556. button_binds.write[0] = MENU_LOCK_SELECTED;
  5557. tool_button[TOOL_LOCK_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5558. tool_button[TOOL_LOCK_SELECTED]->set_tooltip(TTR("Lock the selected object in place (can't be moved)."));
  5559. tool_button[TOOL_LOCK_SELECTED]->set_shortcut(ED_SHORTCUT("editor/lock_selected_nodes", TTR("Lock Selected Node(s)"), KEY_MASK_CMD | KEY_L));
  5560. tool_button[TOOL_UNLOCK_SELECTED] = memnew(ToolButton);
  5561. hbc_menu->add_child(tool_button[TOOL_UNLOCK_SELECTED]);
  5562. button_binds.write[0] = MENU_UNLOCK_SELECTED;
  5563. tool_button[TOOL_UNLOCK_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5564. tool_button[TOOL_UNLOCK_SELECTED]->set_tooltip(TTR("Unlock the selected object (can be moved)."));
  5565. tool_button[TOOL_UNLOCK_SELECTED]->set_shortcut(ED_SHORTCUT("editor/unlock_selected_nodes", TTR("Unlock Selected Node(s)"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_L));
  5566. tool_button[TOOL_GROUP_SELECTED] = memnew(ToolButton);
  5567. hbc_menu->add_child(tool_button[TOOL_GROUP_SELECTED]);
  5568. button_binds.write[0] = MENU_GROUP_SELECTED;
  5569. tool_button[TOOL_GROUP_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5570. tool_button[TOOL_GROUP_SELECTED]->set_tooltip(TTR("Makes sure the object's children are not selectable."));
  5571. tool_button[TOOL_GROUP_SELECTED]->set_shortcut(ED_SHORTCUT("editor/group_selected_nodes", TTR("Group Selected Node(s)"), KEY_MASK_CMD | KEY_G));
  5572. tool_button[TOOL_UNGROUP_SELECTED] = memnew(ToolButton);
  5573. hbc_menu->add_child(tool_button[TOOL_UNGROUP_SELECTED]);
  5574. button_binds.write[0] = MENU_UNGROUP_SELECTED;
  5575. tool_button[TOOL_UNGROUP_SELECTED]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5576. tool_button[TOOL_UNGROUP_SELECTED]->set_tooltip(TTR("Restores the object's children's ability to be selected."));
  5577. tool_button[TOOL_UNGROUP_SELECTED]->set_shortcut(ED_SHORTCUT("editor/ungroup_selected_nodes", TTR("Ungroup Selected Node(s)"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_G));
  5578. hbc_menu->add_child(memnew(VSeparator));
  5579. tool_option_button[TOOL_OPT_LOCAL_COORDS] = memnew(ToolButton);
  5580. hbc_menu->add_child(tool_option_button[TOOL_OPT_LOCAL_COORDS]);
  5581. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_toggle_mode(true);
  5582. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_flat(true);
  5583. button_binds.write[0] = MENU_TOOL_LOCAL_COORDS;
  5584. tool_option_button[TOOL_OPT_LOCAL_COORDS]->connect("toggled", this, "_menu_item_toggled", button_binds);
  5585. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_shortcut(ED_SHORTCUT("spatial_editor/local_coords", TTR("Use Local Space"), KEY_T));
  5586. tool_option_button[TOOL_OPT_USE_SNAP] = memnew(ToolButton);
  5587. hbc_menu->add_child(tool_option_button[TOOL_OPT_USE_SNAP]);
  5588. tool_option_button[TOOL_OPT_USE_SNAP]->set_toggle_mode(true);
  5589. tool_option_button[TOOL_OPT_USE_SNAP]->set_flat(true);
  5590. button_binds.write[0] = MENU_TOOL_USE_SNAP;
  5591. tool_option_button[TOOL_OPT_USE_SNAP]->connect("toggled", this, "_menu_item_toggled", button_binds);
  5592. tool_option_button[TOOL_OPT_USE_SNAP]->set_shortcut(ED_SHORTCUT("spatial_editor/snap", TTR("Use Snap"), KEY_Y));
  5593. hbc_menu->add_child(memnew(VSeparator));
  5594. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA] = memnew(ToolButton);
  5595. hbc_menu->add_child(tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]);
  5596. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_toggle_mode(true);
  5597. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_flat(true);
  5598. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_disabled(true);
  5599. button_binds.write[0] = MENU_TOOL_OVERRIDE_CAMERA;
  5600. tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->connect("toggled", this, "_menu_item_toggled", button_binds);
  5601. _update_camera_override_button(false);
  5602. tool_button[TOOL_CONVERT_ROOMS] = memnew(ToolButton);
  5603. hbc_menu->add_child(tool_button[TOOL_CONVERT_ROOMS]);
  5604. tool_button[TOOL_CONVERT_ROOMS]->set_toggle_mode(false);
  5605. tool_button[TOOL_CONVERT_ROOMS]->set_flat(true);
  5606. button_binds.write[0] = MENU_TOOL_CONVERT_ROOMS;
  5607. tool_button[TOOL_CONVERT_ROOMS]->connect("pressed", this, "_menu_item_pressed", button_binds);
  5608. tool_button[TOOL_CONVERT_ROOMS]->set_shortcut(ED_SHORTCUT("spatial_editor/convert_rooms", TTR("Convert Rooms"), KEY_MASK_ALT | KEY_C));
  5609. tool_button[TOOL_CONVERT_ROOMS]->set_tooltip(TTR("Converts rooms for portal culling."));
  5610. hbc_menu->add_child(memnew(VSeparator));
  5611. // Drag and drop support;
  5612. preview_node = memnew(Spatial);
  5613. preview_bounds = AABB();
  5614. ED_SHORTCUT("spatial_editor/bottom_view", TTR("Bottom View"), KEY_MASK_ALT + KEY_KP_7);
  5615. ED_SHORTCUT("spatial_editor/top_view", TTR("Top View"), KEY_KP_7);
  5616. ED_SHORTCUT("spatial_editor/rear_view", TTR("Rear View"), KEY_MASK_ALT + KEY_KP_1);
  5617. ED_SHORTCUT("spatial_editor/front_view", TTR("Front View"), KEY_KP_1);
  5618. ED_SHORTCUT("spatial_editor/left_view", TTR("Left View"), KEY_MASK_ALT + KEY_KP_3);
  5619. ED_SHORTCUT("spatial_editor/right_view", TTR("Right View"), KEY_KP_3);
  5620. ED_SHORTCUT("spatial_editor/orbit_view_down", TTR("Orbit View Down"), KEY_KP_2);
  5621. ED_SHORTCUT("spatial_editor/orbit_view_left", TTR("Orbit View Left"), KEY_KP_4);
  5622. ED_SHORTCUT("spatial_editor/orbit_view_right", TTR("Orbit View Right"), KEY_KP_6);
  5623. ED_SHORTCUT("spatial_editor/orbit_view_up", TTR("Orbit View Up"), KEY_KP_8);
  5624. ED_SHORTCUT("spatial_editor/orbit_view_180", TTR("Orbit View 180"), KEY_KP_9);
  5625. ED_SHORTCUT("spatial_editor/switch_perspective_orthogonal", TTR("Switch Perspective/Orthogonal View"), KEY_KP_5);
  5626. ED_SHORTCUT("spatial_editor/insert_anim_key", TTR("Insert Animation Key"), KEY_K);
  5627. ED_SHORTCUT("spatial_editor/focus_origin", TTR("Focus Origin"), KEY_O);
  5628. ED_SHORTCUT("spatial_editor/focus_selection", TTR("Focus Selection"), KEY_F);
  5629. ED_SHORTCUT("spatial_editor/align_transform_with_view", TTR("Align Transform with View"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_M);
  5630. ED_SHORTCUT("spatial_editor/align_rotation_with_view", TTR("Align Rotation with View"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_F);
  5631. ED_SHORTCUT("spatial_editor/freelook_toggle", TTR("Toggle Freelook"), KEY_MASK_SHIFT + KEY_F);
  5632. ED_SHORTCUT("spatial_editor/decrease_fov", TTR("Decrease Field of View"), KEY_MASK_CMD + KEY_EQUAL); // Usually direct access key for `KEY_PLUS`.
  5633. ED_SHORTCUT("spatial_editor/increase_fov", TTR("Increase Field of View"), KEY_MASK_CMD + KEY_MINUS);
  5634. ED_SHORTCUT("spatial_editor/reset_fov", TTR("Reset Field of View to Default"), KEY_MASK_CMD + KEY_0);
  5635. PopupMenu *p;
  5636. transform_menu = memnew(MenuButton);
  5637. transform_menu->set_text(TTR("Transform"));
  5638. transform_menu->set_switch_on_hover(true);
  5639. hbc_menu->add_child(transform_menu);
  5640. p = transform_menu->get_popup();
  5641. p->add_shortcut(ED_SHORTCUT("spatial_editor/snap_to_floor", TTR("Snap Object to Floor"), KEY_PAGEDOWN), MENU_SNAP_TO_FLOOR);
  5642. p->add_shortcut(ED_SHORTCUT("spatial_editor/transform_dialog", TTR("Transform Dialog...")), MENU_TRANSFORM_DIALOG);
  5643. p->add_separator();
  5644. p->add_shortcut(ED_SHORTCUT("spatial_editor/configure_snap", TTR("Configure Snap...")), MENU_TRANSFORM_CONFIGURE_SNAP);
  5645. p->connect("id_pressed", this, "_menu_item_pressed");
  5646. view_menu = memnew(MenuButton);
  5647. view_menu->set_text(TTR("View"));
  5648. view_menu->set_switch_on_hover(true);
  5649. hbc_menu->add_child(view_menu);
  5650. hbc_menu->add_child(memnew(VSeparator));
  5651. context_menu_container = memnew(PanelContainer);
  5652. hbc_context_menu = memnew(HBoxContainer);
  5653. context_menu_container->add_child(hbc_context_menu);
  5654. // Use a custom stylebox to make contextual menu items stand out from the rest.
  5655. // This helps with editor usability as contextual menu items change when selecting nodes,
  5656. // even though it may not be immediately obvious at first.
  5657. hbc_menu->add_child(context_menu_container);
  5658. _update_context_menu_stylebox();
  5659. // Get the view menu popup and have it stay open when a checkable item is selected
  5660. p = view_menu->get_popup();
  5661. p->set_hide_on_checkable_item_selection(false);
  5662. accept = memnew(AcceptDialog);
  5663. editor->get_gui_base()->add_child(accept);
  5664. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/1_viewport", TTR("1 Viewport"), KEY_MASK_CMD + KEY_1), MENU_VIEW_USE_1_VIEWPORT);
  5665. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports", TTR("2 Viewports"), KEY_MASK_CMD + KEY_2), MENU_VIEW_USE_2_VIEWPORTS);
  5666. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports_alt", TTR("2 Viewports (Alt)"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_2), MENU_VIEW_USE_2_VIEWPORTS_ALT);
  5667. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports", TTR("3 Viewports"), KEY_MASK_CMD + KEY_3), MENU_VIEW_USE_3_VIEWPORTS);
  5668. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports_alt", TTR("3 Viewports (Alt)"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_3), MENU_VIEW_USE_3_VIEWPORTS_ALT);
  5669. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/4_viewports", TTR("4 Viewports"), KEY_MASK_CMD + KEY_4), MENU_VIEW_USE_4_VIEWPORTS);
  5670. p->add_separator();
  5671. p->add_submenu_item(TTR("Gizmos"), "GizmosMenu");
  5672. p->add_separator();
  5673. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_origin", TTR("View Origin")), MENU_VIEW_ORIGIN);
  5674. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_grid", TTR("View Grid"), KEY_NUMBERSIGN), MENU_VIEW_GRID);
  5675. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_portal_culling", TTR("View Portal Culling"), KEY_MASK_ALT | KEY_P), MENU_VIEW_PORTAL_CULLING);
  5676. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_occlusion_culling", TTR("View Occlusion Culling")), MENU_VIEW_OCCLUSION_CULLING);
  5677. p->add_separator();
  5678. p->add_shortcut(ED_SHORTCUT("spatial_editor/settings", TTR("Settings...")), MENU_VIEW_CAMERA_SETTINGS);
  5679. p->set_item_checked(p->get_item_index(MENU_VIEW_ORIGIN), true);
  5680. p->set_item_checked(p->get_item_index(MENU_VIEW_GRID), true);
  5681. p->set_item_checked(p->get_item_index(MENU_VIEW_OCCLUSION_CULLING), true);
  5682. p->connect("id_pressed", this, "_menu_item_pressed");
  5683. gizmos_menu = memnew(PopupMenu);
  5684. p->add_child(gizmos_menu);
  5685. gizmos_menu->set_name("GizmosMenu");
  5686. gizmos_menu->set_hide_on_checkable_item_selection(false);
  5687. gizmos_menu->connect("id_pressed", this, "_menu_gizmo_toggled");
  5688. /* REST OF MENU */
  5689. left_panel_split = memnew(HSplitContainer);
  5690. left_panel_split->set_v_size_flags(SIZE_EXPAND_FILL);
  5691. vbc->add_child(left_panel_split);
  5692. right_panel_split = memnew(HSplitContainer);
  5693. right_panel_split->set_v_size_flags(SIZE_EXPAND_FILL);
  5694. left_panel_split->add_child(right_panel_split);
  5695. shader_split = memnew(VSplitContainer);
  5696. shader_split->set_h_size_flags(SIZE_EXPAND_FILL);
  5697. right_panel_split->add_child(shader_split);
  5698. viewport_base = memnew(SpatialEditorViewportContainer);
  5699. shader_split->add_child(viewport_base);
  5700. viewport_base->set_v_size_flags(SIZE_EXPAND_FILL);
  5701. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  5702. viewports[i] = memnew(SpatialEditorViewport(this, editor, i));
  5703. viewports[i]->connect("toggle_maximize_view", this, "_toggle_maximize_view");
  5704. viewports[i]->connect("clicked", this, "_update_camera_override_viewport");
  5705. viewports[i]->assign_pending_data_pointers(preview_node, &preview_bounds, accept);
  5706. viewport_base->add_child(viewports[i]);
  5707. }
  5708. /* SNAP DIALOG */
  5709. snap_translate_value = 1;
  5710. snap_rotate_value = 15;
  5711. snap_scale_value = 10;
  5712. snap_dialog = memnew(ConfirmationDialog);
  5713. snap_dialog->set_title(TTR("Snap Settings"));
  5714. add_child(snap_dialog);
  5715. snap_dialog->connect("confirmed", this, "_snap_changed");
  5716. snap_dialog->get_cancel()->connect("pressed", this, "_snap_update");
  5717. VBoxContainer *snap_dialog_vbc = memnew(VBoxContainer);
  5718. snap_dialog->add_child(snap_dialog_vbc);
  5719. snap_translate = memnew(LineEdit);
  5720. snap_dialog_vbc->add_margin_child(TTR("Translate Snap:"), snap_translate);
  5721. snap_rotate = memnew(LineEdit);
  5722. snap_dialog_vbc->add_margin_child(TTR("Rotate Snap (deg.):"), snap_rotate);
  5723. snap_scale = memnew(LineEdit);
  5724. snap_dialog_vbc->add_margin_child(TTR("Scale Snap (%):"), snap_scale);
  5725. _snap_update();
  5726. /* SETTINGS DIALOG */
  5727. settings_dialog = memnew(ConfirmationDialog);
  5728. settings_dialog->set_title(TTR("Viewport Settings"));
  5729. add_child(settings_dialog);
  5730. settings_vbc = memnew(VBoxContainer);
  5731. settings_vbc->set_custom_minimum_size(Size2(200, 0) * EDSCALE);
  5732. settings_dialog->add_child(settings_vbc);
  5733. settings_fov = memnew(SpinBox);
  5734. settings_fov->set_max(MAX_FOV);
  5735. settings_fov->set_min(MIN_FOV);
  5736. settings_fov->set_step(0.01);
  5737. settings_fov->set_value(EDITOR_DEF("editors/3d/default_fov", 70.0));
  5738. settings_vbc->add_margin_child(TTR("Perspective FOV (deg.):"), settings_fov);
  5739. settings_znear = memnew(SpinBox);
  5740. settings_znear->set_max(MAX_Z);
  5741. settings_znear->set_min(MIN_Z);
  5742. settings_znear->set_step(0.01);
  5743. settings_znear->set_value(EDITOR_DEF("editors/3d/default_z_near", 0.05));
  5744. settings_vbc->add_margin_child(TTR("View Z-Near:"), settings_znear);
  5745. settings_zfar = memnew(SpinBox);
  5746. settings_zfar->set_max(MAX_Z);
  5747. settings_zfar->set_min(MIN_Z);
  5748. settings_zfar->set_step(0.01);
  5749. settings_zfar->set_value(EDITOR_DEF("editors/3d/default_z_far", 1500));
  5750. settings_vbc->add_margin_child(TTR("View Z-Far:"), settings_zfar);
  5751. for (uint32_t i = 0; i < VIEWPORTS_COUNT; ++i) {
  5752. settings_dialog->connect("confirmed", viewports[i], "_view_settings_confirmed", varray(0.0));
  5753. }
  5754. /* XFORM DIALOG */
  5755. xform_dialog = memnew(ConfirmationDialog);
  5756. xform_dialog->set_title(TTR("Transform Change"));
  5757. add_child(xform_dialog);
  5758. VBoxContainer *xform_vbc = memnew(VBoxContainer);
  5759. xform_dialog->add_child(xform_vbc);
  5760. Label *l = memnew(Label);
  5761. l->set_text(TTR("Translate:"));
  5762. xform_vbc->add_child(l);
  5763. HBoxContainer *xform_hbc = memnew(HBoxContainer);
  5764. xform_vbc->add_child(xform_hbc);
  5765. for (int i = 0; i < 3; i++) {
  5766. xform_translate[i] = memnew(LineEdit);
  5767. xform_translate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  5768. xform_hbc->add_child(xform_translate[i]);
  5769. }
  5770. l = memnew(Label);
  5771. l->set_text(TTR("Rotate (deg.):"));
  5772. xform_vbc->add_child(l);
  5773. xform_hbc = memnew(HBoxContainer);
  5774. xform_vbc->add_child(xform_hbc);
  5775. for (int i = 0; i < 3; i++) {
  5776. xform_rotate[i] = memnew(LineEdit);
  5777. xform_rotate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  5778. xform_hbc->add_child(xform_rotate[i]);
  5779. }
  5780. l = memnew(Label);
  5781. l->set_text(TTR("Scale (ratio):"));
  5782. xform_vbc->add_child(l);
  5783. xform_hbc = memnew(HBoxContainer);
  5784. xform_vbc->add_child(xform_hbc);
  5785. for (int i = 0; i < 3; i++) {
  5786. xform_scale[i] = memnew(LineEdit);
  5787. xform_scale[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  5788. xform_hbc->add_child(xform_scale[i]);
  5789. }
  5790. l = memnew(Label);
  5791. l->set_text(TTR("Transform Type"));
  5792. xform_vbc->add_child(l);
  5793. xform_type = memnew(OptionButton);
  5794. xform_type->set_h_size_flags(SIZE_EXPAND_FILL);
  5795. xform_type->add_item(TTR("Pre"));
  5796. xform_type->add_item(TTR("Post"));
  5797. xform_vbc->add_child(xform_type);
  5798. xform_dialog->connect("confirmed", this, "_xform_dialog_action");
  5799. scenario_debug = VisualServer::SCENARIO_DEBUG_DISABLED;
  5800. selected = nullptr;
  5801. set_process_unhandled_key_input(true);
  5802. add_to_group("_spatial_editor_group");
  5803. EDITOR_DEF("editors/3d/manipulator_gizmo_size", 80);
  5804. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "editors/3d/manipulator_gizmo_size", PROPERTY_HINT_RANGE, "16,160,1"));
  5805. EDITOR_DEF("editors/3d/manipulator_gizmo_opacity", 0.9);
  5806. EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::REAL, "editors/3d/manipulator_gizmo_opacity", PROPERTY_HINT_RANGE, "0,1,0.01"));
  5807. EDITOR_DEF("editors/3d/navigation/show_viewport_rotation_gizmo", true);
  5808. over_gizmo_handle = -1;
  5809. // make sure the portal tools are off by default
  5810. // (when no RoomManager is present)
  5811. update_portal_tools();
  5812. }
  5813. SpatialEditor::~SpatialEditor() {
  5814. memdelete(preview_node);
  5815. }
  5816. void SpatialEditorPlugin::make_visible(bool p_visible) {
  5817. if (p_visible) {
  5818. spatial_editor->show();
  5819. spatial_editor->set_process(true);
  5820. } else {
  5821. spatial_editor->hide();
  5822. spatial_editor->set_process(false);
  5823. }
  5824. }
  5825. void SpatialEditorPlugin::edit(Object *p_object) {
  5826. spatial_editor->edit(Object::cast_to<Spatial>(p_object));
  5827. }
  5828. bool SpatialEditorPlugin::handles(Object *p_object) const {
  5829. return p_object->is_class("Spatial");
  5830. }
  5831. Dictionary SpatialEditorPlugin::get_state() const {
  5832. return spatial_editor->get_state();
  5833. }
  5834. void SpatialEditorPlugin::set_state(const Dictionary &p_state) {
  5835. spatial_editor->set_state(p_state);
  5836. }
  5837. void SpatialEditor::snap_cursor_to_plane(const Plane &p_plane) {
  5838. //cursor.pos=p_plane.project(cursor.pos);
  5839. }
  5840. Vector3 SpatialEditor::snap_point(Vector3 p_target, Vector3 p_start) const {
  5841. if (is_snap_enabled()) {
  5842. p_target.x = Math::snap_scalar(0.0, get_translate_snap(), p_target.x);
  5843. p_target.y = Math::snap_scalar(0.0, get_translate_snap(), p_target.y);
  5844. p_target.z = Math::snap_scalar(0.0, get_translate_snap(), p_target.z);
  5845. }
  5846. return p_target;
  5847. }
  5848. float SpatialEditor::get_translate_snap() const {
  5849. float snap_value;
  5850. if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
  5851. snap_value = snap_translate->get_text().to_double() / 10.0;
  5852. } else {
  5853. snap_value = snap_translate->get_text().to_double();
  5854. }
  5855. return snap_value;
  5856. }
  5857. float SpatialEditor::get_rotate_snap() const {
  5858. float snap_value;
  5859. if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
  5860. snap_value = snap_rotate->get_text().to_double() / 3.0;
  5861. } else {
  5862. snap_value = snap_rotate->get_text().to_double();
  5863. }
  5864. return snap_value;
  5865. }
  5866. float SpatialEditor::get_scale_snap() const {
  5867. float snap_value;
  5868. if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
  5869. snap_value = snap_scale->get_text().to_double() / 2.0;
  5870. } else {
  5871. snap_value = snap_scale->get_text().to_double();
  5872. }
  5873. return snap_value;
  5874. }
  5875. void SpatialEditorPlugin::_bind_methods() {
  5876. ClassDB::bind_method("snap_cursor_to_plane", &SpatialEditorPlugin::snap_cursor_to_plane);
  5877. }
  5878. void SpatialEditorPlugin::snap_cursor_to_plane(const Plane &p_plane) {
  5879. spatial_editor->snap_cursor_to_plane(p_plane);
  5880. }
  5881. struct _GizmoPluginPriorityComparator {
  5882. bool operator()(const Ref<EditorSpatialGizmoPlugin> &p_a, const Ref<EditorSpatialGizmoPlugin> &p_b) const {
  5883. if (p_a->get_priority() == p_b->get_priority()) {
  5884. return p_a->get_name() < p_b->get_name();
  5885. }
  5886. return p_a->get_priority() > p_b->get_priority();
  5887. }
  5888. };
  5889. struct _GizmoPluginNameComparator {
  5890. bool operator()(const Ref<EditorSpatialGizmoPlugin> &p_a, const Ref<EditorSpatialGizmoPlugin> &p_b) const {
  5891. return p_a->get_name() < p_b->get_name();
  5892. }
  5893. };
  5894. void SpatialEditor::add_gizmo_plugin(Ref<EditorSpatialGizmoPlugin> p_plugin) {
  5895. ERR_FAIL_NULL(p_plugin.ptr());
  5896. gizmo_plugins_by_priority.push_back(p_plugin);
  5897. gizmo_plugins_by_priority.sort_custom<_GizmoPluginPriorityComparator>();
  5898. gizmo_plugins_by_name.push_back(p_plugin);
  5899. gizmo_plugins_by_name.sort_custom<_GizmoPluginNameComparator>();
  5900. _update_gizmos_menu();
  5901. SpatialEditor::get_singleton()->update_all_gizmos();
  5902. }
  5903. void SpatialEditor::remove_gizmo_plugin(Ref<EditorSpatialGizmoPlugin> p_plugin) {
  5904. gizmo_plugins_by_priority.erase(p_plugin);
  5905. gizmo_plugins_by_name.erase(p_plugin);
  5906. _update_gizmos_menu();
  5907. }
  5908. SpatialEditorPlugin::SpatialEditorPlugin(EditorNode *p_node) {
  5909. editor = p_node;
  5910. spatial_editor = memnew(SpatialEditor(p_node));
  5911. spatial_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  5912. editor->get_viewport()->add_child(spatial_editor);
  5913. spatial_editor->hide();
  5914. spatial_editor->connect("transform_key_request", editor->get_inspector_dock(), "_transform_keyed");
  5915. }
  5916. SpatialEditorPlugin::~SpatialEditorPlugin() {
  5917. }
  5918. void EditorSpatialGizmoPlugin::create_material(const String &p_name, const Color &p_color, bool p_billboard, bool p_on_top, bool p_use_vertex_color) {
  5919. Color instanced_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/instanced", Color(0.7, 0.7, 0.7, 0.6));
  5920. Vector<Ref<SpatialMaterial>> mats;
  5921. for (int i = 0; i < 4; i++) {
  5922. bool selected = i % 2 == 1;
  5923. bool instanced = i < 2;
  5924. Ref<SpatialMaterial> material = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  5925. Color color = instanced ? instanced_color : p_color;
  5926. if (!selected) {
  5927. color.a *= 0.3;
  5928. }
  5929. material->set_albedo(color);
  5930. material->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  5931. material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  5932. material->set_render_priority(SpatialMaterial::RENDER_PRIORITY_MIN + 1);
  5933. if (p_use_vertex_color) {
  5934. material->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  5935. material->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  5936. }
  5937. if (p_billboard) {
  5938. material->set_billboard_mode(SpatialMaterial::BILLBOARD_ENABLED);
  5939. }
  5940. if (p_on_top && selected) {
  5941. material->set_on_top_of_alpha();
  5942. }
  5943. mats.push_back(material);
  5944. }
  5945. materials[p_name] = mats;
  5946. }
  5947. void EditorSpatialGizmoPlugin::create_icon_material(const String &p_name, const Ref<Texture> &p_texture, bool p_on_top, const Color &p_albedo) {
  5948. Color instanced_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/instanced", Color(0.7, 0.7, 0.7, 0.6));
  5949. Vector<Ref<SpatialMaterial>> icons;
  5950. for (int i = 0; i < 4; i++) {
  5951. bool selected = i % 2 == 1;
  5952. bool instanced = i < 2;
  5953. Ref<SpatialMaterial> icon = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  5954. Color color = instanced ? instanced_color : p_albedo;
  5955. if (!selected) {
  5956. color.a *= 0.85;
  5957. }
  5958. icon->set_albedo(color);
  5959. icon->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  5960. icon->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  5961. icon->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  5962. icon->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  5963. icon->set_depth_draw_mode(SpatialMaterial::DEPTH_DRAW_DISABLED);
  5964. icon->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  5965. icon->set_texture(SpatialMaterial::TEXTURE_ALBEDO, p_texture);
  5966. icon->set_flag(SpatialMaterial::FLAG_FIXED_SIZE, true);
  5967. icon->set_billboard_mode(SpatialMaterial::BILLBOARD_ENABLED);
  5968. icon->set_render_priority(SpatialMaterial::RENDER_PRIORITY_MIN);
  5969. if (p_on_top && selected) {
  5970. icon->set_on_top_of_alpha();
  5971. }
  5972. icons.push_back(icon);
  5973. }
  5974. materials[p_name] = icons;
  5975. }
  5976. void EditorSpatialGizmoPlugin::create_handle_material(const String &p_name, bool p_billboard, const Ref<Texture> &p_icon) {
  5977. Ref<SpatialMaterial> handle_material = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  5978. handle_material->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  5979. handle_material->set_flag(SpatialMaterial::FLAG_USE_POINT_SIZE, true);
  5980. Ref<Texture> handle_t = p_icon != nullptr ? p_icon : SpatialEditor::get_singleton()->get_icon("Editor3DHandle", "EditorIcons");
  5981. handle_material->set_point_size(handle_t->get_width());
  5982. handle_material->set_texture(SpatialMaterial::TEXTURE_ALBEDO, handle_t);
  5983. handle_material->set_albedo(Color(1, 1, 1));
  5984. handle_material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  5985. handle_material->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  5986. handle_material->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  5987. handle_material->set_on_top_of_alpha();
  5988. if (p_billboard) {
  5989. handle_material->set_billboard_mode(SpatialMaterial::BILLBOARD_ENABLED);
  5990. handle_material->set_on_top_of_alpha();
  5991. }
  5992. materials[p_name] = Vector<Ref<SpatialMaterial>>();
  5993. materials[p_name].push_back(handle_material);
  5994. }
  5995. void EditorSpatialGizmoPlugin::add_material(const String &p_name, Ref<SpatialMaterial> p_material) {
  5996. materials[p_name] = Vector<Ref<SpatialMaterial>>();
  5997. materials[p_name].push_back(p_material);
  5998. }
  5999. Ref<SpatialMaterial> EditorSpatialGizmoPlugin::get_material(const String &p_name, const Ref<EditorSpatialGizmo> &p_gizmo) {
  6000. ERR_FAIL_COND_V(!materials.has(p_name), Ref<SpatialMaterial>());
  6001. ERR_FAIL_COND_V(materials[p_name].size() == 0, Ref<SpatialMaterial>());
  6002. if (p_gizmo.is_null() || materials[p_name].size() == 1) {
  6003. return materials[p_name][0];
  6004. }
  6005. int index = (p_gizmo->is_selected() ? 1 : 0) + (p_gizmo->is_editable() ? 2 : 0);
  6006. Ref<SpatialMaterial> mat = materials[p_name][index];
  6007. if (current_state == ON_TOP && p_gizmo->is_selected()) {
  6008. mat->set_flag(SpatialMaterial::FLAG_DISABLE_DEPTH_TEST, true);
  6009. } else {
  6010. mat->set_flag(SpatialMaterial::FLAG_DISABLE_DEPTH_TEST, false);
  6011. }
  6012. return mat;
  6013. }
  6014. String EditorSpatialGizmoPlugin::get_name() const {
  6015. if (get_script_instance() && get_script_instance()->has_method("get_name")) {
  6016. return get_script_instance()->call("get_name");
  6017. }
  6018. WARN_PRINT_ONCE("A 3D editor gizmo has no name defined (it will appear as \"Unnamed Gizmo\" in the \"View > Gizmos\" menu). To resolve this, override the `get_name()` function to return a String in the script that extends EditorSpatialGizmoPlugin.");
  6019. return TTR("Unnamed Gizmo");
  6020. }
  6021. int EditorSpatialGizmoPlugin::get_priority() const {
  6022. if (get_script_instance() && get_script_instance()->has_method("get_priority")) {
  6023. return get_script_instance()->call("get_priority");
  6024. }
  6025. return 0;
  6026. }
  6027. Ref<EditorSpatialGizmo> EditorSpatialGizmoPlugin::get_gizmo(Spatial *p_spatial) {
  6028. if (get_script_instance() && get_script_instance()->has_method("get_gizmo")) {
  6029. return get_script_instance()->call("get_gizmo", p_spatial);
  6030. }
  6031. Ref<EditorSpatialGizmo> ref = create_gizmo(p_spatial);
  6032. if (ref.is_null()) {
  6033. return ref;
  6034. }
  6035. ref->set_plugin(this);
  6036. ref->set_spatial_node(p_spatial);
  6037. ref->set_hidden(current_state == HIDDEN);
  6038. current_gizmos.push_back(ref.ptr());
  6039. return ref;
  6040. }
  6041. void EditorSpatialGizmoPlugin::_bind_methods() {
  6042. #define GIZMO_REF PropertyInfo(Variant::OBJECT, "gizmo", PROPERTY_HINT_RESOURCE_TYPE, "EditorSpatialGizmo")
  6043. BIND_VMETHOD(MethodInfo(Variant::BOOL, "has_gizmo", PropertyInfo(Variant::OBJECT, "spatial", PROPERTY_HINT_RESOURCE_TYPE, "Spatial")));
  6044. BIND_VMETHOD(MethodInfo(GIZMO_REF, "create_gizmo", PropertyInfo(Variant::OBJECT, "spatial", PROPERTY_HINT_RESOURCE_TYPE, "Spatial")));
  6045. ClassDB::bind_method(D_METHOD("create_material", "name", "color", "billboard", "on_top", "use_vertex_color"), &EditorSpatialGizmoPlugin::create_material, DEFVAL(false), DEFVAL(false), DEFVAL(false));
  6046. ClassDB::bind_method(D_METHOD("create_icon_material", "name", "texture", "on_top", "color"), &EditorSpatialGizmoPlugin::create_icon_material, DEFVAL(false), DEFVAL(Color(1, 1, 1, 1)));
  6047. ClassDB::bind_method(D_METHOD("create_handle_material", "name", "billboard", "texture"), &EditorSpatialGizmoPlugin::create_handle_material, DEFVAL(false), DEFVAL(Variant()));
  6048. ClassDB::bind_method(D_METHOD("add_material", "name", "material"), &EditorSpatialGizmoPlugin::add_material);
  6049. ClassDB::bind_method(D_METHOD("get_material", "name", "gizmo"), &EditorSpatialGizmoPlugin::get_material, DEFVAL(Ref<EditorSpatialGizmo>()));
  6050. BIND_VMETHOD(MethodInfo(Variant::STRING, "get_name"));
  6051. BIND_VMETHOD(MethodInfo(Variant::INT, "get_priority"));
  6052. BIND_VMETHOD(MethodInfo(Variant::BOOL, "can_be_hidden"));
  6053. BIND_VMETHOD(MethodInfo(Variant::BOOL, "is_selectable_when_hidden"));
  6054. BIND_VMETHOD(MethodInfo("redraw", GIZMO_REF));
  6055. BIND_VMETHOD(MethodInfo(Variant::STRING, "get_handle_name", GIZMO_REF, PropertyInfo(Variant::INT, "index")));
  6056. MethodInfo hvget(Variant::NIL, "get_handle_value", GIZMO_REF, PropertyInfo(Variant::INT, "index"));
  6057. hvget.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  6058. BIND_VMETHOD(hvget);
  6059. BIND_VMETHOD(MethodInfo("set_handle", GIZMO_REF, PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::OBJECT, "camera", PROPERTY_HINT_RESOURCE_TYPE, "Camera"), PropertyInfo(Variant::VECTOR2, "point")));
  6060. MethodInfo cm = MethodInfo("commit_handle", GIZMO_REF, PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::NIL, "restore"), PropertyInfo(Variant::BOOL, "cancel"));
  6061. cm.default_arguments.push_back(false);
  6062. BIND_VMETHOD(cm);
  6063. BIND_VMETHOD(MethodInfo(Variant::BOOL, "is_handle_highlighted", GIZMO_REF, PropertyInfo(Variant::INT, "index")));
  6064. #undef GIZMO_REF
  6065. }
  6066. bool EditorSpatialGizmoPlugin::has_gizmo(Spatial *p_spatial) {
  6067. if (get_script_instance() && get_script_instance()->has_method("has_gizmo")) {
  6068. return get_script_instance()->call("has_gizmo", p_spatial);
  6069. }
  6070. return false;
  6071. }
  6072. Ref<EditorSpatialGizmo> EditorSpatialGizmoPlugin::create_gizmo(Spatial *p_spatial) {
  6073. if (get_script_instance() && get_script_instance()->has_method("create_gizmo")) {
  6074. return get_script_instance()->call("create_gizmo", p_spatial);
  6075. }
  6076. Ref<EditorSpatialGizmo> ref;
  6077. if (has_gizmo(p_spatial)) {
  6078. ref.instance();
  6079. }
  6080. return ref;
  6081. }
  6082. bool EditorSpatialGizmoPlugin::can_be_hidden() const {
  6083. if (get_script_instance() && get_script_instance()->has_method("can_be_hidden")) {
  6084. return get_script_instance()->call("can_be_hidden");
  6085. }
  6086. return true;
  6087. }
  6088. bool EditorSpatialGizmoPlugin::is_selectable_when_hidden() const {
  6089. if (get_script_instance() && get_script_instance()->has_method("is_selectable_when_hidden")) {
  6090. return get_script_instance()->call("is_selectable_when_hidden");
  6091. }
  6092. return false;
  6093. }
  6094. void EditorSpatialGizmoPlugin::redraw(EditorSpatialGizmo *p_gizmo) {
  6095. if (get_script_instance() && get_script_instance()->has_method("redraw")) {
  6096. Ref<EditorSpatialGizmo> ref(p_gizmo);
  6097. get_script_instance()->call("redraw", ref);
  6098. }
  6099. }
  6100. String EditorSpatialGizmoPlugin::get_handle_name(const EditorSpatialGizmo *p_gizmo, int p_idx) const {
  6101. if (get_script_instance() && get_script_instance()->has_method("get_handle_name")) {
  6102. return get_script_instance()->call("get_handle_name", p_gizmo, p_idx);
  6103. }
  6104. return "";
  6105. }
  6106. Variant EditorSpatialGizmoPlugin::get_handle_value(EditorSpatialGizmo *p_gizmo, int p_idx) const {
  6107. if (get_script_instance() && get_script_instance()->has_method("get_handle_value")) {
  6108. return get_script_instance()->call("get_handle_value", p_gizmo, p_idx);
  6109. }
  6110. return Variant();
  6111. }
  6112. void EditorSpatialGizmoPlugin::set_handle(EditorSpatialGizmo *p_gizmo, int p_idx, Camera *p_camera, const Point2 &p_point) {
  6113. if (get_script_instance() && get_script_instance()->has_method("set_handle")) {
  6114. get_script_instance()->call("set_handle", p_gizmo, p_idx, p_camera, p_point);
  6115. }
  6116. }
  6117. void EditorSpatialGizmoPlugin::commit_handle(EditorSpatialGizmo *p_gizmo, int p_idx, const Variant &p_restore, bool p_cancel) {
  6118. if (get_script_instance() && get_script_instance()->has_method("commit_handle")) {
  6119. get_script_instance()->call("commit_handle", p_gizmo, p_idx, p_restore, p_cancel);
  6120. }
  6121. }
  6122. bool EditorSpatialGizmoPlugin::is_handle_highlighted(const EditorSpatialGizmo *p_gizmo, int p_idx) const {
  6123. if (get_script_instance() && get_script_instance()->has_method("is_handle_highlighted")) {
  6124. return get_script_instance()->call("is_handle_highlighted", p_gizmo, p_idx);
  6125. }
  6126. return false;
  6127. }
  6128. void EditorSpatialGizmoPlugin::set_state(int p_state) {
  6129. current_state = p_state;
  6130. for (int i = 0; i < current_gizmos.size(); ++i) {
  6131. current_gizmos[i]->set_hidden(current_state == HIDDEN);
  6132. }
  6133. }
  6134. int EditorSpatialGizmoPlugin::get_state() const {
  6135. return current_state;
  6136. }
  6137. void EditorSpatialGizmoPlugin::unregister_gizmo(EditorSpatialGizmo *p_gizmo) {
  6138. current_gizmos.erase(p_gizmo);
  6139. }
  6140. EditorSpatialGizmoPlugin::EditorSpatialGizmoPlugin() {
  6141. current_state = VISIBLE;
  6142. }
  6143. EditorSpatialGizmoPlugin::~EditorSpatialGizmoPlugin() {
  6144. for (int i = 0; i < current_gizmos.size(); ++i) {
  6145. current_gizmos[i]->set_plugin(nullptr);
  6146. current_gizmos[i]->get_spatial_node()->set_gizmo(nullptr);
  6147. }
  6148. if (SpatialEditor::get_singleton()) {
  6149. SpatialEditor::get_singleton()->update_all_gizmos();
  6150. }
  6151. }