spatial_editor_plugin.cpp 245 KB

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