spatial_editor_plugin.cpp 246 KB

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