spatial_editor_plugin.cpp 265 KB

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