node_3d_editor_plugin.cpp 371 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718
  1. /**************************************************************************/
  2. /* node_3d_editor_plugin.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "node_3d_editor_plugin.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/input/input.h"
  33. #include "core/input/input_map.h"
  34. #include "core/math/math_funcs.h"
  35. #include "core/math/projection.h"
  36. #include "core/os/keyboard.h"
  37. #include "editor/debugger/editor_debugger_node.h"
  38. #include "editor/editor_main_screen.h"
  39. #include "editor/editor_node.h"
  40. #include "editor/editor_settings.h"
  41. #include "editor/editor_string_names.h"
  42. #include "editor/editor_undo_redo_manager.h"
  43. #include "editor/gui/editor_run_bar.h"
  44. #include "editor/gui/editor_spin_slider.h"
  45. #include "editor/plugins/animation_player_editor_plugin.h"
  46. #include "editor/plugins/gizmos/audio_listener_3d_gizmo_plugin.h"
  47. #include "editor/plugins/gizmos/audio_stream_player_3d_gizmo_plugin.h"
  48. #include "editor/plugins/gizmos/camera_3d_gizmo_plugin.h"
  49. #include "editor/plugins/gizmos/collision_object_3d_gizmo_plugin.h"
  50. #include "editor/plugins/gizmos/collision_polygon_3d_gizmo_plugin.h"
  51. #include "editor/plugins/gizmos/collision_shape_3d_gizmo_plugin.h"
  52. #include "editor/plugins/gizmos/cpu_particles_3d_gizmo_plugin.h"
  53. #include "editor/plugins/gizmos/decal_gizmo_plugin.h"
  54. #include "editor/plugins/gizmos/fog_volume_gizmo_plugin.h"
  55. #include "editor/plugins/gizmos/geometry_instance_3d_gizmo_plugin.h"
  56. #include "editor/plugins/gizmos/gpu_particles_3d_gizmo_plugin.h"
  57. #include "editor/plugins/gizmos/gpu_particles_collision_3d_gizmo_plugin.h"
  58. #include "editor/plugins/gizmos/joint_3d_gizmo_plugin.h"
  59. #include "editor/plugins/gizmos/label_3d_gizmo_plugin.h"
  60. #include "editor/plugins/gizmos/light_3d_gizmo_plugin.h"
  61. #include "editor/plugins/gizmos/lightmap_gi_gizmo_plugin.h"
  62. #include "editor/plugins/gizmos/lightmap_probe_gizmo_plugin.h"
  63. #include "editor/plugins/gizmos/marker_3d_gizmo_plugin.h"
  64. #include "editor/plugins/gizmos/mesh_instance_3d_gizmo_plugin.h"
  65. #include "editor/plugins/gizmos/navigation_link_3d_gizmo_plugin.h"
  66. #include "editor/plugins/gizmos/navigation_region_3d_gizmo_plugin.h"
  67. #include "editor/plugins/gizmos/occluder_instance_3d_gizmo_plugin.h"
  68. #include "editor/plugins/gizmos/particles_3d_emission_shape_gizmo_plugin.h"
  69. #include "editor/plugins/gizmos/physics_bone_3d_gizmo_plugin.h"
  70. #include "editor/plugins/gizmos/ray_cast_3d_gizmo_plugin.h"
  71. #include "editor/plugins/gizmos/reflection_probe_gizmo_plugin.h"
  72. #include "editor/plugins/gizmos/shape_cast_3d_gizmo_plugin.h"
  73. #include "editor/plugins/gizmos/soft_body_3d_gizmo_plugin.h"
  74. #include "editor/plugins/gizmos/spring_arm_3d_gizmo_plugin.h"
  75. #include "editor/plugins/gizmos/spring_bone_3d_gizmo_plugin.h"
  76. #include "editor/plugins/gizmos/sprite_base_3d_gizmo_plugin.h"
  77. #include "editor/plugins/gizmos/vehicle_body_3d_gizmo_plugin.h"
  78. #include "editor/plugins/gizmos/visible_on_screen_notifier_3d_gizmo_plugin.h"
  79. #include "editor/plugins/gizmos/voxel_gi_gizmo_plugin.h"
  80. #include "editor/plugins/node_3d_editor_gizmos.h"
  81. #include "editor/scene_tree_dock.h"
  82. #include "scene/3d/audio_stream_player_3d.h"
  83. #include "scene/3d/camera_3d.h"
  84. #include "scene/3d/decal.h"
  85. #include "scene/3d/light_3d.h"
  86. #include "scene/3d/mesh_instance_3d.h"
  87. #include "scene/3d/physics/collision_shape_3d.h"
  88. #include "scene/3d/physics/physics_body_3d.h"
  89. #include "scene/3d/sprite_3d.h"
  90. #include "scene/3d/visual_instance_3d.h"
  91. #include "scene/3d/world_environment.h"
  92. #include "scene/gui/center_container.h"
  93. #include "scene/gui/color_picker.h"
  94. #include "scene/gui/flow_container.h"
  95. #include "scene/gui/separator.h"
  96. #include "scene/gui/split_container.h"
  97. #include "scene/gui/subviewport_container.h"
  98. #include "scene/resources/3d/sky_material.h"
  99. #include "scene/resources/packed_scene.h"
  100. #include "scene/resources/surface_tool.h"
  101. constexpr real_t DISTANCE_DEFAULT = 4;
  102. constexpr real_t GIZMO_ARROW_SIZE = 0.35;
  103. constexpr real_t GIZMO_RING_HALF_WIDTH = 0.1;
  104. constexpr real_t GIZMO_PLANE_SIZE = 0.2;
  105. constexpr real_t GIZMO_PLANE_DST = 0.3;
  106. constexpr real_t GIZMO_CIRCLE_SIZE = 1.1;
  107. constexpr real_t GIZMO_SCALE_OFFSET = GIZMO_CIRCLE_SIZE + 0.3;
  108. constexpr real_t GIZMO_ARROW_OFFSET = GIZMO_CIRCLE_SIZE + 0.3;
  109. constexpr real_t ZOOM_FREELOOK_MIN = 0.01;
  110. constexpr real_t ZOOM_FREELOOK_MULTIPLIER = 1.08;
  111. constexpr real_t ZOOM_FREELOOK_INDICATOR_DELAY_S = 1.5;
  112. #ifdef REAL_T_IS_DOUBLE
  113. constexpr double ZOOM_FREELOOK_MAX = 1'000'000'000'000;
  114. #else
  115. constexpr float ZOOM_FREELOOK_MAX = 10'000;
  116. #endif
  117. constexpr real_t MIN_Z = 0.01;
  118. constexpr real_t MAX_Z = 1000000.0;
  119. constexpr real_t MIN_FOV = 0.01;
  120. constexpr real_t MAX_FOV = 179;
  121. void ViewportNavigationControl::_notification(int p_what) {
  122. switch (p_what) {
  123. case NOTIFICATION_DRAW: {
  124. if (viewport != nullptr) {
  125. _draw();
  126. _update_navigation();
  127. }
  128. } break;
  129. case NOTIFICATION_MOUSE_ENTER: {
  130. hovered = true;
  131. queue_redraw();
  132. } break;
  133. case NOTIFICATION_MOUSE_EXIT: {
  134. hovered = false;
  135. queue_redraw();
  136. } break;
  137. }
  138. }
  139. void ViewportNavigationControl::_draw() {
  140. if (nav_mode == Node3DEditorViewport::NAVIGATION_NONE) {
  141. return;
  142. }
  143. Vector2 center = get_size() / 2.0;
  144. float radius = get_size().x / 2.0;
  145. const bool focused = focused_index != -1;
  146. draw_circle(center, radius, Color(0.5, 0.5, 0.5, focused || hovered ? 0.35 : 0.15));
  147. const Color c = focused ? Color(0.9, 0.9, 0.9, 0.9) : Color(0.5, 0.5, 0.5, 0.25);
  148. Vector2 circle_pos = focused ? center.move_toward(focused_pos, radius) : center;
  149. draw_circle(circle_pos, AXIS_CIRCLE_RADIUS, c);
  150. draw_circle(circle_pos, AXIS_CIRCLE_RADIUS * 0.8, c.darkened(0.4));
  151. }
  152. void ViewportNavigationControl::_process_click(int p_index, Vector2 p_position, bool p_pressed) {
  153. hovered = false;
  154. queue_redraw();
  155. if (focused_index != -1 && focused_index != p_index) {
  156. return;
  157. }
  158. if (p_pressed) {
  159. if (p_position.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
  160. focused_pos = p_position;
  161. focused_index = p_index;
  162. queue_redraw();
  163. }
  164. } else {
  165. focused_index = -1;
  166. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
  167. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  168. Input::get_singleton()->warp_mouse(focused_mouse_start);
  169. }
  170. }
  171. }
  172. void ViewportNavigationControl::_process_drag(int p_index, Vector2 p_position, Vector2 p_relative_position) {
  173. if (focused_index == p_index) {
  174. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_VISIBLE) {
  175. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
  176. focused_mouse_start = p_position;
  177. }
  178. focused_pos += p_relative_position;
  179. queue_redraw();
  180. }
  181. }
  182. void ViewportNavigationControl::gui_input(const Ref<InputEvent> &p_event) {
  183. // Mouse events
  184. const Ref<InputEventMouseButton> mouse_button = p_event;
  185. if (mouse_button.is_valid() && mouse_button->get_button_index() == MouseButton::LEFT) {
  186. _process_click(100, mouse_button->get_position(), mouse_button->is_pressed());
  187. }
  188. const Ref<InputEventMouseMotion> mouse_motion = p_event;
  189. if (mouse_motion.is_valid()) {
  190. _process_drag(100, mouse_motion->get_global_position(), viewport->_get_warped_mouse_motion(mouse_motion));
  191. }
  192. // Touch events
  193. const Ref<InputEventScreenTouch> screen_touch = p_event;
  194. if (screen_touch.is_valid()) {
  195. _process_click(screen_touch->get_index(), screen_touch->get_position(), screen_touch->is_pressed());
  196. }
  197. const Ref<InputEventScreenDrag> screen_drag = p_event;
  198. if (screen_drag.is_valid()) {
  199. _process_drag(screen_drag->get_index(), screen_drag->get_position(), screen_drag->get_relative());
  200. }
  201. }
  202. void ViewportNavigationControl::_update_navigation() {
  203. if (focused_index == -1) {
  204. return;
  205. }
  206. Vector2 delta = focused_pos - (get_size() / 2.0);
  207. Vector2 delta_normalized = delta.normalized();
  208. switch (nav_mode) {
  209. case Node3DEditorViewport::NavigationMode::NAVIGATION_MOVE: {
  210. real_t speed_multiplier = MIN(delta.length() / (get_size().x * 100.0), 3.0);
  211. real_t speed = viewport->freelook_speed * speed_multiplier;
  212. const Node3DEditorViewport::FreelookNavigationScheme navigation_scheme = (Node3DEditorViewport::FreelookNavigationScheme)EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_navigation_scheme").operator int();
  213. Vector3 forward;
  214. if (navigation_scheme == Node3DEditorViewport::FreelookNavigationScheme::FREELOOK_FULLY_AXIS_LOCKED) {
  215. // Forward/backward keys will always go straight forward/backward, never moving on the Y axis.
  216. forward = Vector3(0, 0, delta_normalized.y).rotated(Vector3(0, 1, 0), viewport->camera->get_rotation().y);
  217. } else {
  218. // Forward/backward keys will be relative to the camera pitch.
  219. forward = viewport->camera->get_transform().basis.xform(Vector3(0, 0, delta_normalized.y));
  220. }
  221. const Vector3 right = viewport->camera->get_transform().basis.xform(Vector3(delta_normalized.x, 0, 0));
  222. const Vector3 direction = forward + right;
  223. const Vector3 motion = direction * speed;
  224. viewport->cursor.pos += motion;
  225. viewport->cursor.eye_pos += motion;
  226. } break;
  227. case Node3DEditorViewport::NavigationMode::NAVIGATION_LOOK: {
  228. real_t speed_multiplier = MIN(delta.length() / (get_size().x * 2.5), 3.0);
  229. real_t speed = viewport->freelook_speed * speed_multiplier;
  230. viewport->_nav_look(nullptr, delta_normalized * speed);
  231. } break;
  232. case Node3DEditorViewport::NAVIGATION_PAN: {
  233. real_t speed_multiplier = MIN(delta.length() / (get_size().x), 3.0);
  234. real_t speed = viewport->freelook_speed * speed_multiplier;
  235. viewport->_nav_pan(nullptr, -delta_normalized * speed);
  236. } break;
  237. case Node3DEditorViewport::NAVIGATION_ZOOM: {
  238. real_t speed_multiplier = MIN(delta.length() / (get_size().x), 3.0);
  239. real_t speed = viewport->freelook_speed * speed_multiplier;
  240. viewport->_nav_zoom(nullptr, delta_normalized * speed);
  241. } break;
  242. case Node3DEditorViewport::NAVIGATION_ORBIT: {
  243. real_t speed_multiplier = MIN(delta.length() / (get_size().x), 3.0);
  244. real_t speed = viewport->freelook_speed * speed_multiplier;
  245. viewport->_nav_orbit(nullptr, delta_normalized * speed);
  246. } break;
  247. case Node3DEditorViewport::NAVIGATION_NONE: {
  248. } break;
  249. }
  250. }
  251. void ViewportNavigationControl::set_navigation_mode(Node3DEditorViewport::NavigationMode p_nav_mode) {
  252. nav_mode = p_nav_mode;
  253. }
  254. void ViewportNavigationControl::set_viewport(Node3DEditorViewport *p_viewport) {
  255. viewport = p_viewport;
  256. }
  257. void ViewportRotationControl::_notification(int p_what) {
  258. switch (p_what) {
  259. case NOTIFICATION_ENTER_TREE: {
  260. axis_menu_options.clear();
  261. axis_menu_options.push_back(Node3DEditorViewport::VIEW_RIGHT);
  262. axis_menu_options.push_back(Node3DEditorViewport::VIEW_TOP);
  263. axis_menu_options.push_back(Node3DEditorViewport::VIEW_FRONT);
  264. axis_menu_options.push_back(Node3DEditorViewport::VIEW_LEFT);
  265. axis_menu_options.push_back(Node3DEditorViewport::VIEW_BOTTOM);
  266. axis_menu_options.push_back(Node3DEditorViewport::VIEW_REAR);
  267. axis_colors.clear();
  268. axis_colors.push_back(get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor)));
  269. axis_colors.push_back(get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor)));
  270. axis_colors.push_back(get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor)));
  271. queue_redraw();
  272. } break;
  273. case NOTIFICATION_DRAW: {
  274. if (viewport != nullptr) {
  275. _draw();
  276. }
  277. } break;
  278. case NOTIFICATION_MOUSE_EXIT: {
  279. focused_axis = -2;
  280. queue_redraw();
  281. } break;
  282. }
  283. }
  284. void ViewportRotationControl::_draw() {
  285. const Vector2 center = get_size() / 2.0;
  286. const real_t radius = get_size().x / 2.0;
  287. if (focused_axis > -2 || orbiting_index != -1) {
  288. draw_circle(center, radius, Color(0.5, 0.5, 0.5, 0.25), true, -1.0, true);
  289. }
  290. Vector<Axis2D> axis_to_draw;
  291. _get_sorted_axis(axis_to_draw);
  292. for (int i = 0; i < axis_to_draw.size(); ++i) {
  293. _draw_axis(axis_to_draw[i]);
  294. }
  295. }
  296. void ViewportRotationControl::_draw_axis(const Axis2D &p_axis) {
  297. const bool focused = focused_axis == p_axis.axis;
  298. const bool positive = p_axis.axis < 3;
  299. const int direction = p_axis.axis % 3;
  300. const Color axis_color = axis_colors[direction];
  301. const double min_alpha = 0.35;
  302. const double alpha = focused ? 1.0 : Math::remap((p_axis.z_axis + 1.0) / 2.0, 0, 0.5, min_alpha, 1.0);
  303. const Color c = focused ? Color(axis_color.lightened(0.75), 1.0) : Color(axis_color, alpha);
  304. if (positive) {
  305. // Draw axis lines for the positive axes.
  306. const Vector2 center = get_size() / 2.0;
  307. const Vector2 diff = p_axis.screen_point - center;
  308. const float line_length = MAX(diff.length() - AXIS_CIRCLE_RADIUS - 0.5 * EDSCALE, 0);
  309. draw_line(center + diff.limit_length(0.5 * EDSCALE), center + diff.limit_length(line_length), c, 1.5 * EDSCALE, true);
  310. draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS, c, true, -1.0, true);
  311. // Draw the axis letter for the positive axes.
  312. const String axis_name = direction == 0 ? "X" : (direction == 1 ? "Y" : "Z");
  313. const Ref<Font> &font = get_theme_font(SNAME("rotation_control"), EditorStringName(EditorFonts));
  314. const int font_size = get_theme_font_size(SNAME("rotation_control_size"), EditorStringName(EditorFonts));
  315. const Size2 char_size = font->get_char_size(axis_name[0], font_size);
  316. const Vector2 char_offset = Vector2(-char_size.width / 2.0, char_size.height * 0.25);
  317. draw_char(font, p_axis.screen_point + char_offset, axis_name, font_size, Color(0.0, 0.0, 0.0, alpha * 0.6));
  318. } else {
  319. // Draw an outline around the negative axes.
  320. draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS, c, true, -1.0, true);
  321. draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS * 0.8, c.darkened(0.4), true, -1.0, true);
  322. }
  323. }
  324. void ViewportRotationControl::_get_sorted_axis(Vector<Axis2D> &r_axis) {
  325. const Vector2 center = get_size() / 2.0;
  326. const real_t radius = get_size().x / 2.0 - AXIS_CIRCLE_RADIUS - 2.0 * EDSCALE;
  327. const Basis camera_basis = viewport->to_camera_transform(viewport->cursor).get_basis().inverse();
  328. for (int i = 0; i < 3; ++i) {
  329. Vector3 axis_3d = camera_basis.get_column(i);
  330. Vector2 axis_vector = Vector2(axis_3d.x, -axis_3d.y) * radius;
  331. if (Math::abs(axis_3d.z) <= 1.0) {
  332. Axis2D pos_axis;
  333. pos_axis.axis = i;
  334. pos_axis.screen_point = center + axis_vector;
  335. pos_axis.z_axis = axis_3d.z;
  336. r_axis.push_back(pos_axis);
  337. Axis2D neg_axis;
  338. neg_axis.axis = i + 3;
  339. neg_axis.screen_point = center - axis_vector;
  340. neg_axis.z_axis = -axis_3d.z;
  341. r_axis.push_back(neg_axis);
  342. } else {
  343. // Special case when the camera is aligned with one axis
  344. Axis2D axis;
  345. axis.axis = i + (axis_3d.z <= 0 ? 0 : 3);
  346. axis.screen_point = center;
  347. axis.z_axis = 1.0;
  348. r_axis.push_back(axis);
  349. }
  350. }
  351. r_axis.sort_custom<Axis2DCompare>();
  352. }
  353. void ViewportRotationControl::_process_click(int p_index, Vector2 p_position, bool p_pressed) {
  354. if (orbiting_index != -1 && orbiting_index != p_index) {
  355. return;
  356. }
  357. if (p_pressed) {
  358. if (p_position.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
  359. orbiting_index = p_index;
  360. }
  361. } else {
  362. if (focused_axis > -1 && gizmo_activated) {
  363. viewport->_menu_option(axis_menu_options[focused_axis]);
  364. _update_focus();
  365. }
  366. orbiting_index = -1;
  367. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
  368. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  369. Input::get_singleton()->warp_mouse(orbiting_mouse_start);
  370. }
  371. }
  372. }
  373. void ViewportRotationControl::_process_drag(Ref<InputEventWithModifiers> p_event, int p_index, Vector2 p_position, Vector2 p_relative_position) {
  374. if (orbiting_index == p_index && gizmo_activated) {
  375. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_VISIBLE) {
  376. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
  377. orbiting_mouse_start = p_position;
  378. viewport->previous_cursor = viewport->cursor;
  379. }
  380. viewport->_nav_orbit(p_event, p_relative_position);
  381. focused_axis = -1;
  382. } else {
  383. _update_focus();
  384. }
  385. }
  386. void ViewportRotationControl::gui_input(const Ref<InputEvent> &p_event) {
  387. ERR_FAIL_COND(p_event.is_null());
  388. // Key events
  389. const Ref<InputEventKey> k = p_event;
  390. if (k.is_valid() && k->is_action_pressed(SNAME("ui_cancel"), false, true)) {
  391. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
  392. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  393. Input::get_singleton()->warp_mouse(orbiting_mouse_start);
  394. viewport->cursor = viewport->previous_cursor;
  395. gizmo_activated = false;
  396. }
  397. }
  398. // Mouse events
  399. const Ref<InputEventMouseButton> mb = p_event;
  400. if (mb.is_valid()) {
  401. if (mb->get_button_index() == MouseButton::LEFT) {
  402. _process_click(100, mb->get_position(), mb->is_pressed());
  403. if (mb->is_pressed()) {
  404. gizmo_activated = true;
  405. grab_focus();
  406. }
  407. } else if (mb->get_button_index() == MouseButton::RIGHT) {
  408. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
  409. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  410. Input::get_singleton()->warp_mouse(orbiting_mouse_start);
  411. viewport->cursor = viewport->previous_cursor;
  412. gizmo_activated = false;
  413. }
  414. }
  415. }
  416. const Ref<InputEventMouseMotion> mm = p_event;
  417. if (mm.is_valid()) {
  418. _process_drag(mm, 100, mm->get_global_position(), viewport->_get_warped_mouse_motion(mm));
  419. }
  420. // Touch events
  421. const Ref<InputEventScreenTouch> screen_touch = p_event;
  422. if (screen_touch.is_valid()) {
  423. _process_click(screen_touch->get_index(), screen_touch->get_position(), screen_touch->is_pressed());
  424. }
  425. const Ref<InputEventScreenDrag> screen_drag = p_event;
  426. if (screen_drag.is_valid()) {
  427. _process_drag(screen_drag, screen_drag->get_index(), screen_drag->get_position(), screen_drag->get_relative());
  428. }
  429. }
  430. void ViewportRotationControl::_update_focus() {
  431. int original_focus = focused_axis;
  432. focused_axis = -2;
  433. Vector2 mouse_pos = get_local_mouse_position();
  434. if (mouse_pos.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
  435. focused_axis = -1;
  436. }
  437. Vector<Axis2D> axes;
  438. _get_sorted_axis(axes);
  439. for (int i = 0; i < axes.size(); i++) {
  440. const Axis2D &axis = axes[i];
  441. if (mouse_pos.distance_to(axis.screen_point) < AXIS_CIRCLE_RADIUS) {
  442. focused_axis = axis.axis;
  443. }
  444. }
  445. if (focused_axis != original_focus) {
  446. queue_redraw();
  447. }
  448. }
  449. void ViewportRotationControl::set_viewport(Node3DEditorViewport *p_viewport) {
  450. viewport = p_viewport;
  451. }
  452. void Node3DEditorViewport::_view_settings_confirmed(real_t p_interp_delta) {
  453. // Set FOV override multiplier back to the default, so that the FOV
  454. // setting specified in the View menu is correctly applied.
  455. cursor.fov_scale = 1.0;
  456. _update_camera(p_interp_delta);
  457. }
  458. void Node3DEditorViewport::_update_navigation_controls_visibility() {
  459. bool show_viewport_rotation_gizmo = EDITOR_GET("editors/3d/navigation/show_viewport_rotation_gizmo") && (!previewing_cinema && !previewing_camera);
  460. rotation_control->set_visible(show_viewport_rotation_gizmo);
  461. bool show_viewport_navigation_gizmo = EDITOR_GET("editors/3d/navigation/show_viewport_navigation_gizmo") && (!previewing_cinema && !previewing_camera);
  462. position_control->set_visible(show_viewport_navigation_gizmo);
  463. look_control->set_visible(show_viewport_navigation_gizmo);
  464. }
  465. void Node3DEditorViewport::_update_camera(real_t p_interp_delta) {
  466. bool is_orthogonal = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
  467. Cursor old_camera_cursor = camera_cursor;
  468. camera_cursor = cursor;
  469. if (p_interp_delta > 0) {
  470. //-------
  471. // Perform smoothing
  472. if (is_freelook_active()) {
  473. // Higher inertia should increase "lag" (lerp with factor between 0 and 1)
  474. // 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.
  475. const real_t inertia = EDITOR_GET("editors/3d/freelook/freelook_inertia");
  476. real_t factor = (1.0 / inertia) * p_interp_delta;
  477. // We interpolate a different point here, because in freelook mode the focus point (cursor.pos) orbits around eye_pos
  478. camera_cursor.eye_pos = old_camera_cursor.eye_pos.lerp(cursor.eye_pos, CLAMP(factor, 0, 1));
  479. const real_t orbit_inertia = EDITOR_GET("editors/3d/navigation_feel/orbit_inertia");
  480. camera_cursor.x_rot = Math::lerp(old_camera_cursor.x_rot, cursor.x_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  481. camera_cursor.y_rot = Math::lerp(old_camera_cursor.y_rot, cursor.y_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  482. if (Math::abs(camera_cursor.x_rot - cursor.x_rot) < 0.1) {
  483. camera_cursor.x_rot = cursor.x_rot;
  484. }
  485. if (Math::abs(camera_cursor.y_rot - cursor.y_rot) < 0.1) {
  486. camera_cursor.y_rot = cursor.y_rot;
  487. }
  488. Vector3 forward = to_camera_transform(camera_cursor).basis.xform(Vector3(0, 0, -1));
  489. camera_cursor.pos = camera_cursor.eye_pos + forward * camera_cursor.distance;
  490. } else {
  491. const real_t orbit_inertia = EDITOR_GET("editors/3d/navigation_feel/orbit_inertia");
  492. const real_t translation_inertia = EDITOR_GET("editors/3d/navigation_feel/translation_inertia");
  493. const real_t zoom_inertia = EDITOR_GET("editors/3d/navigation_feel/zoom_inertia");
  494. camera_cursor.x_rot = Math::lerp(old_camera_cursor.x_rot, cursor.x_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  495. camera_cursor.y_rot = Math::lerp(old_camera_cursor.y_rot, cursor.y_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
  496. if (Math::abs(camera_cursor.x_rot - cursor.x_rot) < 0.1) {
  497. camera_cursor.x_rot = cursor.x_rot;
  498. }
  499. if (Math::abs(camera_cursor.y_rot - cursor.y_rot) < 0.1) {
  500. camera_cursor.y_rot = cursor.y_rot;
  501. }
  502. camera_cursor.pos = old_camera_cursor.pos.lerp(cursor.pos, MIN(1.f, p_interp_delta * (1 / translation_inertia)));
  503. camera_cursor.distance = Math::lerp(old_camera_cursor.distance, cursor.distance, MIN((real_t)1.0, p_interp_delta * (1 / zoom_inertia)));
  504. }
  505. }
  506. //-------
  507. // Apply camera transform
  508. real_t tolerance = 0.001;
  509. bool equal = true;
  510. 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)) {
  511. equal = false;
  512. } else if (!old_camera_cursor.pos.is_equal_approx(camera_cursor.pos)) {
  513. equal = false;
  514. } else if (!Math::is_equal_approx(old_camera_cursor.distance, camera_cursor.distance, tolerance)) {
  515. equal = false;
  516. } else if (!Math::is_equal_approx(old_camera_cursor.fov_scale, camera_cursor.fov_scale, tolerance)) {
  517. equal = false;
  518. }
  519. if (!equal || p_interp_delta == 0 || is_orthogonal != orthogonal) {
  520. last_camera_transform = to_camera_transform(camera_cursor);
  521. camera->set_global_transform(last_camera_transform);
  522. if (orthogonal) {
  523. float half_fov = Math::deg_to_rad(get_fov()) / 2.0;
  524. float height = 2.0 * cursor.distance * Math::tan(half_fov);
  525. camera->set_orthogonal(height, get_znear(), get_zfar());
  526. } else {
  527. camera->set_perspective(get_fov(), get_znear(), get_zfar());
  528. }
  529. update_transform_gizmo_view();
  530. rotation_control->queue_redraw();
  531. position_control->queue_redraw();
  532. look_control->queue_redraw();
  533. spatial_editor->update_grid();
  534. }
  535. }
  536. Transform3D Node3DEditorViewport::to_camera_transform(const Cursor &p_cursor) const {
  537. Transform3D camera_transform;
  538. camera_transform.translate_local(p_cursor.pos);
  539. camera_transform.basis.rotate(Vector3(1, 0, 0), -p_cursor.x_rot);
  540. camera_transform.basis.rotate(Vector3(0, 1, 0), -p_cursor.y_rot);
  541. if (orthogonal) {
  542. camera_transform.translate_local(0, 0, (get_zfar() - get_znear()) / 2.0);
  543. } else {
  544. camera_transform.translate_local(0, 0, p_cursor.distance);
  545. }
  546. return camera_transform;
  547. }
  548. int Node3DEditorViewport::get_selected_count() const {
  549. const HashMap<Node *, Object *> &selection = editor_selection->get_selection();
  550. int count = 0;
  551. for (const KeyValue<Node *, Object *> &E : selection) {
  552. Node3D *sp = Object::cast_to<Node3D>(E.key);
  553. if (!sp) {
  554. continue;
  555. }
  556. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  557. if (!se) {
  558. continue;
  559. }
  560. count++;
  561. }
  562. return count;
  563. }
  564. void Node3DEditorViewport::cancel_transform() {
  565. List<Node *> &selection = editor_selection->get_selected_node_list();
  566. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  567. Node3D *sp = Object::cast_to<Node3D>(E->get());
  568. if (!sp) {
  569. continue;
  570. }
  571. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  572. if (!se) {
  573. continue;
  574. }
  575. if (se && se->gizmo.is_valid()) {
  576. Vector<int> ids;
  577. Vector<Transform3D> restore;
  578. for (const KeyValue<int, Transform3D> &GE : se->subgizmos) {
  579. ids.push_back(GE.key);
  580. restore.push_back(GE.value);
  581. }
  582. se->gizmo->commit_subgizmos(ids, restore, true);
  583. }
  584. sp->set_global_transform(se->original);
  585. }
  586. collision_reposition = false;
  587. finish_transform();
  588. set_message(TTR("Transform Aborted."), 3);
  589. }
  590. void Node3DEditorViewport::_update_shrink() {
  591. bool shrink = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION));
  592. subviewport_container->set_stretch_shrink(shrink ? 2 : 1);
  593. subviewport_container->set_texture_filter(shrink ? TEXTURE_FILTER_NEAREST : TEXTURE_FILTER_PARENT_NODE);
  594. }
  595. float Node3DEditorViewport::get_znear() const {
  596. return CLAMP(spatial_editor->get_znear(), MIN_Z, MAX_Z);
  597. }
  598. float Node3DEditorViewport::get_zfar() const {
  599. return CLAMP(spatial_editor->get_zfar(), MIN_Z, MAX_Z);
  600. }
  601. float Node3DEditorViewport::get_fov() const {
  602. return CLAMP(spatial_editor->get_fov() * cursor.fov_scale, MIN_FOV, MAX_FOV);
  603. }
  604. Transform3D Node3DEditorViewport::_get_camera_transform() const {
  605. return camera->get_global_transform();
  606. }
  607. Vector3 Node3DEditorViewport::_get_camera_position() const {
  608. return _get_camera_transform().origin;
  609. }
  610. Point2 Node3DEditorViewport::point_to_screen(const Vector3 &p_point) {
  611. return camera->unproject_position(p_point) * subviewport_container->get_stretch_shrink();
  612. }
  613. Vector3 Node3DEditorViewport::get_ray_pos(const Vector2 &p_pos) const {
  614. return camera->project_ray_origin(p_pos / subviewport_container->get_stretch_shrink());
  615. }
  616. Vector3 Node3DEditorViewport::_get_camera_normal() const {
  617. return -_get_camera_transform().basis.get_column(2);
  618. }
  619. Vector3 Node3DEditorViewport::get_ray(const Vector2 &p_pos) const {
  620. return camera->project_ray_normal(p_pos / subviewport_container->get_stretch_shrink());
  621. }
  622. void Node3DEditorViewport::_clear_selected() {
  623. _edit.gizmo = Ref<EditorNode3DGizmo>();
  624. _edit.gizmo_handle = -1;
  625. _edit.gizmo_handle_secondary = false;
  626. _edit.gizmo_initial_value = Variant();
  627. Node3D *selected = spatial_editor->get_single_selected_node();
  628. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  629. if (se && se->gizmo.is_valid()) {
  630. se->subgizmos.clear();
  631. se->gizmo->redraw();
  632. se->gizmo.unref();
  633. spatial_editor->update_transform_gizmo();
  634. } else {
  635. editor_selection->clear();
  636. Node3DEditor::get_singleton()->edit(nullptr);
  637. }
  638. }
  639. void Node3DEditorViewport::_select_clicked(bool p_allow_locked) {
  640. Node *node = Object::cast_to<Node3D>(ObjectDB::get_instance(clicked));
  641. Node3D *selected = Object::cast_to<Node3D>(node);
  642. clicked = ObjectID();
  643. if (!selected) {
  644. return;
  645. }
  646. Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
  647. // Prevent selection of nodes not owned by the edited scene.
  648. while (node && node != edited_scene->get_parent()) {
  649. Node *node_owner = node->get_owner();
  650. if (node_owner == edited_scene || node == edited_scene || (node_owner != nullptr && edited_scene->is_editable_instance(node_owner))) {
  651. break;
  652. }
  653. node = node->get_parent();
  654. selected = Object::cast_to<Node3D>(node);
  655. }
  656. if (!p_allow_locked) {
  657. // Replace the node by the group if grouped
  658. while (node && node != edited_scene->get_parent()) {
  659. Node3D *selected_tmp = Object::cast_to<Node3D>(node);
  660. if (selected_tmp && node->has_meta("_edit_group_")) {
  661. selected = selected_tmp;
  662. }
  663. node = node->get_parent();
  664. }
  665. }
  666. if (p_allow_locked || (selected != nullptr && !_is_node_locked(selected))) {
  667. if (clicked_wants_append) {
  668. Node *active_node = editor_selection->get_selected_node_list().is_empty() ? nullptr : editor_selection->get_selected_node_list().back()->get();
  669. if (editor_selection->is_selected(selected)) {
  670. editor_selection->remove_node(selected);
  671. if (selected != active_node) {
  672. editor_selection->add_node(selected);
  673. }
  674. } else {
  675. editor_selection->add_node(selected);
  676. }
  677. } else {
  678. if (!editor_selection->is_selected(selected)) {
  679. editor_selection->clear();
  680. editor_selection->add_node(selected);
  681. EditorNode::get_singleton()->edit_node(selected);
  682. }
  683. }
  684. if (editor_selection->get_selected_node_list().size() == 1) {
  685. EditorNode::get_singleton()->edit_node(editor_selection->get_selected_node_list().front()->get());
  686. }
  687. }
  688. }
  689. ObjectID Node3DEditorViewport::_select_ray(const Point2 &p_pos) const {
  690. Vector3 ray = get_ray(p_pos);
  691. Vector3 pos = get_ray_pos(p_pos);
  692. Vector2 shrinked_pos = p_pos / subviewport_container->get_stretch_shrink();
  693. if (viewport->get_debug_draw() == Viewport::DEBUG_DRAW_SDFGI_PROBES) {
  694. RS::get_singleton()->sdfgi_set_debug_probe_select(pos, ray);
  695. }
  696. HashSet<Ref<EditorNode3DGizmo>> found_gizmos;
  697. Node *edited_scene = get_tree()->get_edited_scene_root();
  698. ObjectID closest;
  699. Node *item = nullptr;
  700. float closest_dist = 1e20;
  701. Vector<Node3D *> nodes_with_gizmos = Node3DEditor::get_singleton()->gizmo_bvh_ray_query(pos, pos + ray * camera->get_far());
  702. for (Node3D *spat : nodes_with_gizmos) {
  703. if (!spat || _is_node_locked(spat)) {
  704. continue;
  705. }
  706. Vector<Ref<Node3DGizmo>> gizmos = spat->get_gizmos();
  707. for (int j = 0; j < gizmos.size(); j++) {
  708. Ref<EditorNode3DGizmo> seg = gizmos[j];
  709. if (seg.is_null() || found_gizmos.has(seg)) {
  710. continue;
  711. }
  712. found_gizmos.insert(seg);
  713. Vector3 point;
  714. Vector3 normal;
  715. bool inters = seg->intersect_ray(camera, shrinked_pos, point, normal);
  716. if (!inters) {
  717. continue;
  718. }
  719. const real_t dist = pos.distance_to(point);
  720. if (dist < 0) {
  721. continue;
  722. }
  723. if (dist < closest_dist) {
  724. item = Object::cast_to<Node>(spat);
  725. if (item != edited_scene) {
  726. item = edited_scene->get_deepest_editable_node(item);
  727. }
  728. closest = item->get_instance_id();
  729. closest_dist = dist;
  730. }
  731. }
  732. }
  733. if (!item) {
  734. return ObjectID();
  735. }
  736. return closest;
  737. }
  738. void Node3DEditorViewport::_find_items_at_pos(const Point2 &p_pos, Vector<_RayResult> &r_results, bool p_include_locked_nodes) {
  739. Vector3 ray = get_ray(p_pos);
  740. Vector3 pos = get_ray_pos(p_pos);
  741. Vector<Node3D *> nodes_with_gizmos = Node3DEditor::get_singleton()->gizmo_bvh_ray_query(pos, pos + ray * camera->get_far());
  742. HashSet<Node3D *> found_nodes;
  743. for (Node3D *spat : nodes_with_gizmos) {
  744. if (!spat) {
  745. continue;
  746. }
  747. if (found_nodes.has(spat)) {
  748. continue;
  749. }
  750. if (!p_include_locked_nodes && _is_node_locked(spat)) {
  751. continue;
  752. }
  753. Vector<Ref<Node3DGizmo>> gizmos = spat->get_gizmos();
  754. for (int j = 0; j < gizmos.size(); j++) {
  755. Ref<EditorNode3DGizmo> seg = gizmos[j];
  756. if (seg.is_null()) {
  757. continue;
  758. }
  759. Vector3 point;
  760. Vector3 normal;
  761. bool inters = seg->intersect_ray(camera, p_pos, point, normal);
  762. if (!inters) {
  763. continue;
  764. }
  765. const real_t dist = pos.distance_to(point);
  766. if (dist < 0) {
  767. continue;
  768. }
  769. found_nodes.insert(spat);
  770. _RayResult res;
  771. res.item = spat;
  772. res.depth = dist;
  773. r_results.push_back(res);
  774. break;
  775. }
  776. }
  777. r_results.sort();
  778. }
  779. Vector3 Node3DEditorViewport::_get_screen_to_space(const Vector3 &p_vector3) {
  780. Projection cm;
  781. if (orthogonal) {
  782. cm.set_orthogonal(camera->get_size(), get_size().aspect(), get_znear() + p_vector3.z, get_zfar());
  783. } else {
  784. cm.set_perspective(get_fov(), get_size().aspect(), get_znear() + p_vector3.z, get_zfar());
  785. }
  786. Vector2 screen_he = cm.get_viewport_half_extents();
  787. Transform3D camera_transform;
  788. camera_transform.translate_local(cursor.pos);
  789. camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
  790. camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
  791. camera_transform.translate_local(0, 0, cursor.distance);
  792. 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)));
  793. }
  794. void Node3DEditorViewport::_select_region() {
  795. if (cursor.region_begin == cursor.region_end) {
  796. if (!clicked_wants_append) {
  797. _clear_selected();
  798. }
  799. return; //nothing really
  800. }
  801. const real_t z_offset = MAX(0.0, 5.0 - get_znear());
  802. Vector3 box[4] = {
  803. Vector3(
  804. MIN(cursor.region_begin.x, cursor.region_end.x),
  805. MIN(cursor.region_begin.y, cursor.region_end.y),
  806. z_offset),
  807. Vector3(
  808. MAX(cursor.region_begin.x, cursor.region_end.x),
  809. MIN(cursor.region_begin.y, cursor.region_end.y),
  810. z_offset),
  811. Vector3(
  812. MAX(cursor.region_begin.x, cursor.region_end.x),
  813. MAX(cursor.region_begin.y, cursor.region_end.y),
  814. z_offset),
  815. Vector3(
  816. MIN(cursor.region_begin.x, cursor.region_end.x),
  817. MAX(cursor.region_begin.y, cursor.region_end.y),
  818. z_offset)
  819. };
  820. Vector<Plane> frustum;
  821. Vector3 cam_pos = _get_camera_position();
  822. for (int i = 0; i < 4; i++) {
  823. Vector3 a = _get_screen_to_space(box[i]);
  824. Vector3 b = _get_screen_to_space(box[(i + 1) % 4]);
  825. if (orthogonal) {
  826. frustum.push_back(Plane((a - b).normalized(), a));
  827. } else {
  828. frustum.push_back(Plane(a, b, cam_pos));
  829. }
  830. }
  831. Plane near_plane = Plane(-_get_camera_normal(), cam_pos);
  832. near_plane.d -= get_znear();
  833. frustum.push_back(near_plane);
  834. Plane far_plane = -near_plane;
  835. far_plane.d += get_zfar();
  836. frustum.push_back(far_plane);
  837. if (spatial_editor->get_single_selected_node()) {
  838. Node3D *single_selected = spatial_editor->get_single_selected_node();
  839. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(single_selected);
  840. if (se) {
  841. Ref<EditorNode3DGizmo> old_gizmo;
  842. if (!clicked_wants_append) {
  843. se->subgizmos.clear();
  844. old_gizmo = se->gizmo;
  845. se->gizmo.unref();
  846. }
  847. bool found_subgizmos = false;
  848. Vector<Ref<Node3DGizmo>> gizmos = single_selected->get_gizmos();
  849. for (int j = 0; j < gizmos.size(); j++) {
  850. Ref<EditorNode3DGizmo> seg = gizmos[j];
  851. if (seg.is_null()) {
  852. continue;
  853. }
  854. if (se->gizmo.is_valid() && se->gizmo != seg) {
  855. continue;
  856. }
  857. Vector<int> subgizmos = seg->subgizmos_intersect_frustum(camera, frustum);
  858. if (!subgizmos.is_empty()) {
  859. se->gizmo = seg;
  860. for (int i = 0; i < subgizmos.size(); i++) {
  861. int subgizmo_id = subgizmos[i];
  862. if (!se->subgizmos.has(subgizmo_id)) {
  863. se->subgizmos.insert(subgizmo_id, se->gizmo->get_subgizmo_transform(subgizmo_id));
  864. }
  865. }
  866. found_subgizmos = true;
  867. break;
  868. }
  869. }
  870. if (!clicked_wants_append || found_subgizmos) {
  871. if (se->gizmo.is_valid()) {
  872. se->gizmo->redraw();
  873. }
  874. if (old_gizmo != se->gizmo && old_gizmo.is_valid()) {
  875. old_gizmo->redraw();
  876. }
  877. spatial_editor->update_transform_gizmo();
  878. }
  879. if (found_subgizmos) {
  880. return;
  881. }
  882. }
  883. }
  884. if (!clicked_wants_append) {
  885. _clear_selected();
  886. }
  887. Vector<Node3D *> nodes_with_gizmos = Node3DEditor::get_singleton()->gizmo_bvh_frustum_query(frustum);
  888. HashSet<Node3D *> found_nodes;
  889. Vector<Node *> selected;
  890. Node *edited_scene = get_tree()->get_edited_scene_root();
  891. if (edited_scene == nullptr) {
  892. return;
  893. }
  894. for (Node3D *sp : nodes_with_gizmos) {
  895. if (!sp || _is_node_locked(sp)) {
  896. continue;
  897. }
  898. if (found_nodes.has(sp)) {
  899. continue;
  900. }
  901. found_nodes.insert(sp);
  902. Node *node = Object::cast_to<Node>(sp);
  903. // Selection requires that the node is the edited scene or its descendant, and has an owner.
  904. if (node != edited_scene) {
  905. if (!node->get_owner() || !edited_scene->is_ancestor_of(node)) {
  906. continue;
  907. }
  908. node = edited_scene->get_deepest_editable_node(node);
  909. while (node != edited_scene) {
  910. Node *node_owner = node->get_owner();
  911. if (node_owner == edited_scene || (node_owner != nullptr && edited_scene->is_editable_instance(node_owner))) {
  912. break;
  913. }
  914. node = node->get_parent();
  915. }
  916. }
  917. // Replace the node by the group if grouped
  918. if (node->is_class("Node3D")) {
  919. Node3D *sel = Object::cast_to<Node3D>(node);
  920. while (node && node != EditorNode::get_singleton()->get_edited_scene()->get_parent()) {
  921. Node3D *selected_tmp = Object::cast_to<Node3D>(node);
  922. if (selected_tmp && node->has_meta("_edit_group_")) {
  923. sel = selected_tmp;
  924. }
  925. node = node->get_parent();
  926. }
  927. node = sel;
  928. }
  929. if (_is_node_locked(node)) {
  930. continue;
  931. }
  932. Vector<Ref<Node3DGizmo>> gizmos = sp->get_gizmos();
  933. for (int j = 0; j < gizmos.size(); j++) {
  934. Ref<EditorNode3DGizmo> seg = gizmos[j];
  935. if (seg.is_null()) {
  936. continue;
  937. }
  938. if (seg->intersect_frustum(camera, frustum)) {
  939. selected.push_back(node);
  940. }
  941. }
  942. }
  943. for (int i = 0; i < selected.size(); i++) {
  944. if (!editor_selection->is_selected(selected[i])) {
  945. editor_selection->add_node(selected[i]);
  946. }
  947. }
  948. if (editor_selection->get_selected_node_list().size() == 1) {
  949. EditorNode::get_singleton()->edit_node(editor_selection->get_selected_node_list().front()->get());
  950. }
  951. }
  952. void Node3DEditorViewport::_update_name() {
  953. String name;
  954. switch (view_type) {
  955. case VIEW_TYPE_USER: {
  956. if (orthogonal) {
  957. name = TTR("Orthogonal");
  958. } else {
  959. name = TTR("Perspective");
  960. }
  961. } break;
  962. case VIEW_TYPE_TOP: {
  963. if (orthogonal) {
  964. name = TTR("Top Orthogonal");
  965. } else {
  966. name = TTR("Top Perspective");
  967. }
  968. } break;
  969. case VIEW_TYPE_BOTTOM: {
  970. if (orthogonal) {
  971. name = TTR("Bottom Orthogonal");
  972. } else {
  973. name = TTR("Bottom Perspective");
  974. }
  975. } break;
  976. case VIEW_TYPE_LEFT: {
  977. if (orthogonal) {
  978. name = TTR("Left Orthogonal");
  979. } else {
  980. name = TTR("Left Perspective");
  981. }
  982. } break;
  983. case VIEW_TYPE_RIGHT: {
  984. if (orthogonal) {
  985. name = TTR("Right Orthogonal");
  986. } else {
  987. name = TTR("Right Perspective");
  988. }
  989. } break;
  990. case VIEW_TYPE_FRONT: {
  991. if (orthogonal) {
  992. name = TTR("Front Orthogonal");
  993. } else {
  994. name = TTR("Front Perspective");
  995. }
  996. } break;
  997. case VIEW_TYPE_REAR: {
  998. if (orthogonal) {
  999. name = TTR("Rear Orthogonal");
  1000. } else {
  1001. name = TTR("Rear Perspective");
  1002. }
  1003. } break;
  1004. }
  1005. if (auto_orthogonal) {
  1006. // TRANSLATORS: This will be appended to the view name when Auto Orthogonal is enabled.
  1007. name += " " + TTR("[auto]");
  1008. }
  1009. view_display_menu->set_text(name);
  1010. view_display_menu->reset_size();
  1011. }
  1012. void Node3DEditorViewport::_compute_edit(const Point2 &p_point) {
  1013. _edit.original_local = spatial_editor->are_local_coords_enabled();
  1014. _edit.click_ray = get_ray(p_point);
  1015. _edit.click_ray_pos = get_ray_pos(p_point);
  1016. _edit.plane = TRANSFORM_VIEW;
  1017. spatial_editor->update_transform_gizmo();
  1018. _edit.center = spatial_editor->get_gizmo_transform().origin;
  1019. Node3D *selected = spatial_editor->get_single_selected_node();
  1020. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  1021. if (se && se->gizmo.is_valid()) {
  1022. for (const KeyValue<int, Transform3D> &E : se->subgizmos) {
  1023. int subgizmo_id = E.key;
  1024. se->subgizmos[subgizmo_id] = se->gizmo->get_subgizmo_transform(subgizmo_id);
  1025. }
  1026. se->original_local = selected->get_transform();
  1027. se->original = selected->get_global_transform();
  1028. } else {
  1029. List<Node *> &selection = editor_selection->get_selected_node_list();
  1030. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  1031. Node3D *sp = Object::cast_to<Node3D>(E->get());
  1032. if (!sp) {
  1033. continue;
  1034. }
  1035. Node3DEditorSelectedItem *sel_item = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  1036. if (!sel_item) {
  1037. continue;
  1038. }
  1039. sel_item->original_local = sel_item->sp->get_local_gizmo_transform();
  1040. sel_item->original = sel_item->sp->get_global_gizmo_transform();
  1041. }
  1042. }
  1043. }
  1044. static Key _get_key_modifier_setting(const String &p_property) {
  1045. switch (EDITOR_GET(p_property).operator int()) {
  1046. case 0:
  1047. return Key::NONE;
  1048. case 1:
  1049. return Key::SHIFT;
  1050. case 2:
  1051. return Key::ALT;
  1052. case 3:
  1053. return Key::META;
  1054. case 4:
  1055. return Key::CTRL;
  1056. }
  1057. return Key::NONE;
  1058. }
  1059. static Key _get_key_modifier(Ref<InputEventWithModifiers> e) {
  1060. if (e->is_shift_pressed()) {
  1061. return Key::SHIFT;
  1062. }
  1063. if (e->is_alt_pressed()) {
  1064. return Key::ALT;
  1065. }
  1066. if (e->is_ctrl_pressed()) {
  1067. return Key::CTRL;
  1068. }
  1069. if (e->is_meta_pressed()) {
  1070. return Key::META;
  1071. }
  1072. return Key::NONE;
  1073. }
  1074. bool Node3DEditorViewport::_transform_gizmo_select(const Vector2 &p_screenpos, bool p_highlight_only) {
  1075. if (!spatial_editor->is_gizmo_visible()) {
  1076. return false;
  1077. }
  1078. if (get_selected_count() == 0) {
  1079. if (p_highlight_only) {
  1080. spatial_editor->select_gizmo_highlight_axis(-1);
  1081. }
  1082. return false;
  1083. }
  1084. Vector3 ray_pos = get_ray_pos(p_screenpos);
  1085. Vector3 ray = get_ray(p_screenpos);
  1086. Transform3D gt = spatial_editor->get_gizmo_transform();
  1087. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE) {
  1088. int col_axis = -1;
  1089. real_t col_d = 1e20;
  1090. for (int i = 0; i < 3; i++) {
  1091. const Vector3 grabber_pos = gt.origin + gt.basis.get_column(i).normalized() * gizmo_scale * (GIZMO_ARROW_OFFSET + (GIZMO_ARROW_SIZE * 0.5));
  1092. const real_t grabber_radius = gizmo_scale * GIZMO_ARROW_SIZE;
  1093. Vector3 r;
  1094. if (Geometry3D::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) {
  1095. const real_t d = r.distance_to(ray_pos);
  1096. if (d < col_d) {
  1097. col_d = d;
  1098. col_axis = i;
  1099. }
  1100. }
  1101. }
  1102. bool is_plane_translate = false;
  1103. // plane select
  1104. if (col_axis == -1) {
  1105. col_d = 1e20;
  1106. for (int i = 0; i < 3; i++) {
  1107. Vector3 ivec2 = gt.basis.get_column((i + 1) % 3).normalized();
  1108. Vector3 ivec3 = gt.basis.get_column((i + 2) % 3).normalized();
  1109. // Allow some tolerance to make the plane easier to click,
  1110. // even if the click is actually slightly outside the plane.
  1111. const Vector3 grabber_pos = gt.origin + (ivec2 + ivec3) * gizmo_scale * (GIZMO_PLANE_SIZE + GIZMO_PLANE_DST * 0.6667);
  1112. Vector3 r;
  1113. Plane plane(gt.basis.get_column(i).normalized(), gt.origin);
  1114. if (plane.intersects_ray(ray_pos, ray, &r)) {
  1115. const real_t dist = r.distance_to(grabber_pos);
  1116. // Allow some tolerance to make the plane easier to click,
  1117. // even if the click is actually slightly outside the plane.
  1118. if (dist < (gizmo_scale * GIZMO_PLANE_SIZE * 1.5)) {
  1119. const real_t d = ray_pos.distance_to(r);
  1120. if (d < col_d) {
  1121. col_d = d;
  1122. col_axis = i;
  1123. is_plane_translate = true;
  1124. }
  1125. }
  1126. }
  1127. }
  1128. }
  1129. if (col_axis != -1) {
  1130. if (p_highlight_only) {
  1131. spatial_editor->select_gizmo_highlight_axis(col_axis + (is_plane_translate ? 6 : 0));
  1132. } else {
  1133. //handle plane translate
  1134. _edit.mode = TRANSFORM_TRANSLATE;
  1135. _compute_edit(p_screenpos);
  1136. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis + (is_plane_translate ? 3 : 0));
  1137. }
  1138. return true;
  1139. }
  1140. }
  1141. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE) {
  1142. int col_axis = -1;
  1143. Vector3 hit_position;
  1144. Vector3 hit_normal;
  1145. real_t ray_length = gt.origin.distance_to(ray_pos) + (GIZMO_CIRCLE_SIZE * gizmo_scale) * 4.0f;
  1146. if (Geometry3D::segment_intersects_sphere(ray_pos, ray_pos + ray * ray_length, gt.origin, gizmo_scale * (GIZMO_CIRCLE_SIZE), &hit_position, &hit_normal)) {
  1147. if (hit_normal.dot(_get_camera_normal()) < 0.05) {
  1148. hit_position = gt.xform_inv(hit_position).abs();
  1149. int min_axis = hit_position.min_axis_index();
  1150. if (hit_position[min_axis] < gizmo_scale * GIZMO_RING_HALF_WIDTH) {
  1151. col_axis = min_axis;
  1152. }
  1153. }
  1154. }
  1155. if (col_axis == -1) {
  1156. float col_d = 1e20;
  1157. for (int i = 0; i < 3; i++) {
  1158. Plane plane(gt.basis.get_column(i).normalized(), gt.origin);
  1159. Vector3 r;
  1160. if (!plane.intersects_ray(ray_pos, ray, &r)) {
  1161. continue;
  1162. }
  1163. const real_t dist = r.distance_to(gt.origin);
  1164. const Vector3 r_dir = (r - gt.origin).normalized();
  1165. if (_get_camera_normal().dot(r_dir) <= 0.005) {
  1166. if (dist > gizmo_scale * (GIZMO_CIRCLE_SIZE - GIZMO_RING_HALF_WIDTH) && dist < gizmo_scale * (GIZMO_CIRCLE_SIZE + GIZMO_RING_HALF_WIDTH)) {
  1167. const real_t d = ray_pos.distance_to(r);
  1168. if (d < col_d) {
  1169. col_d = d;
  1170. col_axis = i;
  1171. }
  1172. }
  1173. }
  1174. }
  1175. }
  1176. if (col_axis != -1) {
  1177. if (p_highlight_only) {
  1178. spatial_editor->select_gizmo_highlight_axis(col_axis + 3);
  1179. } else {
  1180. //handle rotate
  1181. _edit.mode = TRANSFORM_ROTATE;
  1182. _compute_edit(p_screenpos);
  1183. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis);
  1184. }
  1185. return true;
  1186. }
  1187. }
  1188. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE) {
  1189. int col_axis = -1;
  1190. float col_d = 1e20;
  1191. for (int i = 0; i < 3; i++) {
  1192. const Vector3 grabber_pos = gt.origin + gt.basis.get_column(i).normalized() * gizmo_scale * GIZMO_SCALE_OFFSET;
  1193. const real_t grabber_radius = gizmo_scale * GIZMO_ARROW_SIZE;
  1194. Vector3 r;
  1195. if (Geometry3D::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) {
  1196. const real_t d = r.distance_to(ray_pos);
  1197. if (d < col_d) {
  1198. col_d = d;
  1199. col_axis = i;
  1200. }
  1201. }
  1202. }
  1203. bool is_plane_scale = false;
  1204. // plane select
  1205. if (col_axis == -1) {
  1206. col_d = 1e20;
  1207. for (int i = 0; i < 3; i++) {
  1208. const Vector3 ivec2 = gt.basis.get_column((i + 1) % 3).normalized();
  1209. const Vector3 ivec3 = gt.basis.get_column((i + 2) % 3).normalized();
  1210. // Allow some tolerance to make the plane easier to click,
  1211. // even if the click is actually slightly outside the plane.
  1212. const Vector3 grabber_pos = gt.origin + (ivec2 + ivec3) * gizmo_scale * (GIZMO_PLANE_SIZE + GIZMO_PLANE_DST * 0.6667);
  1213. Vector3 r;
  1214. Plane plane(gt.basis.get_column(i).normalized(), gt.origin);
  1215. if (plane.intersects_ray(ray_pos, ray, &r)) {
  1216. const real_t dist = r.distance_to(grabber_pos);
  1217. // Allow some tolerance to make the plane easier to click,
  1218. // even if the click is actually slightly outside the plane.
  1219. if (dist < (gizmo_scale * GIZMO_PLANE_SIZE * 1.5)) {
  1220. const real_t d = ray_pos.distance_to(r);
  1221. if (d < col_d) {
  1222. col_d = d;
  1223. col_axis = i;
  1224. is_plane_scale = true;
  1225. }
  1226. }
  1227. }
  1228. }
  1229. }
  1230. if (col_axis != -1) {
  1231. if (p_highlight_only) {
  1232. spatial_editor->select_gizmo_highlight_axis(col_axis + (is_plane_scale ? 12 : 9));
  1233. } else {
  1234. //handle scale
  1235. _edit.mode = TRANSFORM_SCALE;
  1236. _compute_edit(p_screenpos);
  1237. _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis + (is_plane_scale ? 3 : 0));
  1238. }
  1239. return true;
  1240. }
  1241. }
  1242. if (p_highlight_only) {
  1243. spatial_editor->select_gizmo_highlight_axis(-1);
  1244. }
  1245. return false;
  1246. }
  1247. void Node3DEditorViewport::_transform_gizmo_apply(Node3D *p_node, const Transform3D &p_transform, bool p_local) {
  1248. if (p_transform.basis.determinant() == 0) {
  1249. return;
  1250. }
  1251. if (p_local) {
  1252. p_node->set_transform(p_transform);
  1253. } else {
  1254. p_node->set_global_transform(p_transform);
  1255. }
  1256. }
  1257. Transform3D Node3DEditorViewport::_compute_transform(TransformMode p_mode, const Transform3D &p_original, const Transform3D &p_original_local, Vector3 p_motion, double p_extra, bool p_local, bool p_orthogonal) {
  1258. switch (p_mode) {
  1259. case TRANSFORM_SCALE: {
  1260. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1261. p_motion.snapf(p_extra);
  1262. }
  1263. Transform3D s;
  1264. if (p_local) {
  1265. s.basis = p_original_local.basis.scaled_local(p_motion + Vector3(1, 1, 1));
  1266. s.origin = p_original_local.origin;
  1267. } else {
  1268. s.basis.scale(p_motion + Vector3(1, 1, 1));
  1269. Transform3D base = Transform3D(Basis(), _edit.center);
  1270. s = base * (s * (base.inverse() * p_original));
  1271. // Recalculate orthogonalized scale without moving origin.
  1272. if (p_orthogonal) {
  1273. s.basis = p_original.basis.scaled_orthogonal(p_motion + Vector3(1, 1, 1));
  1274. }
  1275. }
  1276. return s;
  1277. }
  1278. case TRANSFORM_TRANSLATE: {
  1279. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  1280. p_motion.snapf(p_extra);
  1281. }
  1282. if (p_local) {
  1283. return p_original_local.translated_local(p_motion);
  1284. }
  1285. return p_original.translated(p_motion);
  1286. }
  1287. case TRANSFORM_ROTATE: {
  1288. Transform3D r;
  1289. if (p_local) {
  1290. Vector3 axis = p_original_local.basis.xform(p_motion);
  1291. r.basis = Basis(axis.normalized(), p_extra) * p_original_local.basis;
  1292. r.origin = p_original_local.origin;
  1293. } else {
  1294. Basis local = p_original.basis * p_original_local.basis.inverse();
  1295. Vector3 axis = local.xform_inv(p_motion);
  1296. r.basis = local * Basis(axis.normalized(), p_extra) * p_original_local.basis;
  1297. r.origin = Basis(p_motion, p_extra).xform(p_original.origin - _edit.center) + _edit.center;
  1298. }
  1299. return r;
  1300. }
  1301. default: {
  1302. ERR_FAIL_V_MSG(Transform3D(), "Invalid mode in '_compute_transform'");
  1303. }
  1304. }
  1305. }
  1306. void Node3DEditorViewport::_surface_mouse_enter() {
  1307. if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
  1308. return;
  1309. }
  1310. if (!surface->has_focus() && (!get_viewport()->gui_get_focus_owner() || !get_viewport()->gui_get_focus_owner()->is_text_field())) {
  1311. surface->grab_focus();
  1312. }
  1313. }
  1314. void Node3DEditorViewport::_surface_mouse_exit() {
  1315. _remove_preview_node();
  1316. _reset_preview_material();
  1317. _remove_preview_material();
  1318. }
  1319. void Node3DEditorViewport::_surface_focus_enter() {
  1320. view_display_menu->set_disable_shortcuts(false);
  1321. }
  1322. void Node3DEditorViewport::_surface_focus_exit() {
  1323. view_display_menu->set_disable_shortcuts(true);
  1324. }
  1325. bool Node3DEditorViewport::_is_node_locked(const Node *p_node) const {
  1326. return p_node->get_meta("_edit_lock_", false);
  1327. }
  1328. void Node3DEditorViewport::_list_select(Ref<InputEventMouseButton> b) {
  1329. Vector<_RayResult> potential_selection_results;
  1330. _find_items_at_pos(b->get_position(), potential_selection_results, b->is_alt_pressed());
  1331. Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
  1332. // Filter to a list of nodes which include either the edited scene or nodes directly owned by the edited scene.
  1333. // If a node has an invalid owner, recursively check their parents until a valid node is found.
  1334. for (int i = 0; i < potential_selection_results.size(); i++) {
  1335. Node3D *node = potential_selection_results[i].item;
  1336. while (true) {
  1337. if (node == nullptr || node == edited_scene->get_parent()) {
  1338. break;
  1339. } else {
  1340. Node *node_owner = node->get_owner();
  1341. if (node == edited_scene || node_owner == edited_scene || (node_owner != nullptr && edited_scene->is_editable_instance(node_owner))) {
  1342. if (!selection_results.has(node)) {
  1343. selection_results.append(node);
  1344. }
  1345. break;
  1346. }
  1347. }
  1348. node = Object::cast_to<Node3D>(node->get_parent());
  1349. }
  1350. }
  1351. clicked_wants_append = b->is_shift_pressed();
  1352. if (selection_results.size() == 1) {
  1353. clicked = selection_results[0]->get_instance_id();
  1354. selection_results.clear();
  1355. if (clicked.is_valid()) {
  1356. _select_clicked(b->is_alt_pressed());
  1357. }
  1358. } else if (!selection_results.is_empty()) {
  1359. NodePath root_path = get_tree()->get_edited_scene_root()->get_path();
  1360. StringName root_name = root_path.get_name(root_path.get_name_count() - 1);
  1361. for (int i = 0; i < selection_results.size(); i++) {
  1362. Node3D *spat = selection_results[i];
  1363. Ref<Texture2D> icon = EditorNode::get_singleton()->get_object_icon(spat, "Node");
  1364. String node_path = "/" + root_name + "/" + root_path.rel_path_to(spat->get_path());
  1365. int locked = 0;
  1366. if (_is_node_locked(spat)) {
  1367. locked = 1;
  1368. } else {
  1369. Node *ed_scene = EditorNode::get_singleton()->get_edited_scene();
  1370. Node *node = spat;
  1371. while (node && node != ed_scene->get_parent()) {
  1372. Node3D *selected_tmp = Object::cast_to<Node3D>(node);
  1373. if (selected_tmp && node->has_meta("_edit_group_")) {
  1374. locked = 2;
  1375. }
  1376. node = node->get_parent();
  1377. }
  1378. }
  1379. String suffix;
  1380. if (locked == 1) {
  1381. suffix = " (" + TTR("Locked") + ")";
  1382. } else if (locked == 2) {
  1383. suffix = " (" + TTR("Grouped") + ")";
  1384. }
  1385. selection_menu->add_item((String)spat->get_name() + suffix);
  1386. selection_menu->set_item_icon(i, icon);
  1387. selection_menu->set_item_metadata(i, node_path);
  1388. selection_menu->set_item_tooltip(i, String(spat->get_name()) + "\nType: " + spat->get_class() + "\nPath: " + node_path);
  1389. }
  1390. selection_results_menu = selection_results;
  1391. selection_menu->set_position(get_screen_position() + b->get_position());
  1392. selection_menu->reset_size();
  1393. selection_menu->popup();
  1394. }
  1395. }
  1396. // This is only active during instant transforms,
  1397. // to capture and wrap mouse events outside the control.
  1398. void Node3DEditorViewport::input(const Ref<InputEvent> &p_event) {
  1399. ERR_FAIL_COND(!_edit.instant);
  1400. Ref<InputEventMouseMotion> m = p_event;
  1401. if (m.is_valid()) {
  1402. _edit.mouse_pos += _get_warped_mouse_motion(p_event);
  1403. update_transform(_get_key_modifier(m) == Key::SHIFT);
  1404. }
  1405. }
  1406. void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
  1407. if (previewing || get_viewport()->gui_get_drag_data()) {
  1408. return; //do NONE
  1409. }
  1410. EditorPlugin::AfterGUIInput after = EditorPlugin::AFTER_GUI_INPUT_PASS;
  1411. {
  1412. EditorNode *en = EditorNode::get_singleton();
  1413. EditorPluginList *force_input_forwarding_list = en->get_editor_plugins_force_input_forwarding();
  1414. if (!force_input_forwarding_list->is_empty()) {
  1415. EditorPlugin::AfterGUIInput discard = force_input_forwarding_list->forward_3d_gui_input(camera, p_event, true);
  1416. if (discard == EditorPlugin::AFTER_GUI_INPUT_STOP) {
  1417. return;
  1418. }
  1419. if (discard == EditorPlugin::AFTER_GUI_INPUT_CUSTOM) {
  1420. after = EditorPlugin::AFTER_GUI_INPUT_CUSTOM;
  1421. }
  1422. }
  1423. }
  1424. {
  1425. EditorNode *en = EditorNode::get_singleton();
  1426. EditorPluginList *over_plugin_list = en->get_editor_plugins_over();
  1427. if (!over_plugin_list->is_empty()) {
  1428. EditorPlugin::AfterGUIInput discard = over_plugin_list->forward_3d_gui_input(camera, p_event, false);
  1429. if (discard == EditorPlugin::AFTER_GUI_INPUT_STOP) {
  1430. return;
  1431. }
  1432. if (discard == EditorPlugin::AFTER_GUI_INPUT_CUSTOM) {
  1433. after = EditorPlugin::AFTER_GUI_INPUT_CUSTOM;
  1434. }
  1435. }
  1436. }
  1437. Ref<InputEventMouseButton> b = p_event;
  1438. if (b.is_valid()) {
  1439. emit_signal(SNAME("clicked"));
  1440. ViewportNavMouseButton orbit_mouse_preference = (ViewportNavMouseButton)EDITOR_GET("editors/3d/navigation/orbit_mouse_button").operator int();
  1441. ViewportNavMouseButton pan_mouse_preference = (ViewportNavMouseButton)EDITOR_GET("editors/3d/navigation/pan_mouse_button").operator int();
  1442. ViewportNavMouseButton zoom_mouse_preference = (ViewportNavMouseButton)EDITOR_GET("editors/3d/navigation/zoom_mouse_button").operator int();
  1443. const real_t zoom_factor = 1 + (ZOOM_FREELOOK_MULTIPLIER - 1) * b->get_factor();
  1444. switch (b->get_button_index()) {
  1445. case MouseButton::WHEEL_UP: {
  1446. if (is_freelook_active()) {
  1447. scale_freelook_speed(zoom_factor);
  1448. } else {
  1449. scale_cursor_distance(1.0 / zoom_factor);
  1450. }
  1451. } break;
  1452. case MouseButton::WHEEL_DOWN: {
  1453. if (is_freelook_active()) {
  1454. scale_freelook_speed(1.0 / zoom_factor);
  1455. } else {
  1456. scale_cursor_distance(zoom_factor);
  1457. }
  1458. } break;
  1459. case MouseButton::RIGHT: {
  1460. if (b->is_pressed()) {
  1461. if (_edit.gizmo.is_valid()) {
  1462. // Restore.
  1463. _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, _edit.gizmo_initial_value, true);
  1464. _edit.gizmo = Ref<EditorNode3DGizmo>();
  1465. }
  1466. if (_edit.mode == TRANSFORM_NONE) {
  1467. if (orbit_mouse_preference == NAVIGATION_RIGHT_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_2")) {
  1468. break;
  1469. } else if (pan_mouse_preference == NAVIGATION_RIGHT_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_2")) {
  1470. break;
  1471. } else if (zoom_mouse_preference == NAVIGATION_RIGHT_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_2")) {
  1472. break;
  1473. }
  1474. }
  1475. if (b->is_alt_pressed()) {
  1476. _list_select(b);
  1477. return;
  1478. }
  1479. if (_edit.mode != TRANSFORM_NONE) {
  1480. cancel_transform();
  1481. break;
  1482. }
  1483. const Key mod = _get_key_modifier(b);
  1484. if (!orthogonal) {
  1485. if (mod == _get_key_modifier_setting("editors/3d/freelook/freelook_activation_modifier")) {
  1486. set_freelook_active(true);
  1487. }
  1488. }
  1489. } else {
  1490. set_freelook_active(false);
  1491. }
  1492. if (freelook_active && !surface->has_focus()) {
  1493. // Focus usually doesn't trigger on right-click, but in case of freelook it should,
  1494. // otherwise using keyboard navigation would misbehave
  1495. surface->grab_focus();
  1496. }
  1497. } break;
  1498. case MouseButton::MIDDLE: {
  1499. if (b->is_pressed() && _edit.mode != TRANSFORM_NONE) {
  1500. if (orbit_mouse_preference == NAVIGATION_MIDDLE_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_2")) {
  1501. break;
  1502. } else if (pan_mouse_preference == NAVIGATION_MIDDLE_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_2")) {
  1503. break;
  1504. } else if (zoom_mouse_preference == NAVIGATION_MIDDLE_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_2")) {
  1505. break;
  1506. }
  1507. switch (_edit.plane) {
  1508. case TRANSFORM_VIEW: {
  1509. _edit.plane = TRANSFORM_X_AXIS;
  1510. set_message(TTR("X-Axis Transform."), 2);
  1511. view_type = VIEW_TYPE_USER;
  1512. _update_name();
  1513. } break;
  1514. case TRANSFORM_X_AXIS: {
  1515. _edit.plane = TRANSFORM_Y_AXIS;
  1516. set_message(TTR("Y-Axis Transform."), 2);
  1517. } break;
  1518. case TRANSFORM_Y_AXIS: {
  1519. _edit.plane = TRANSFORM_Z_AXIS;
  1520. set_message(TTR("Z-Axis Transform."), 2);
  1521. } break;
  1522. case TRANSFORM_Z_AXIS: {
  1523. _edit.plane = TRANSFORM_VIEW;
  1524. // TRANSLATORS: This refers to the transform of the view plane.
  1525. set_message(TTR("View Plane Transform."), 2);
  1526. } break;
  1527. case TRANSFORM_YZ:
  1528. case TRANSFORM_XZ:
  1529. case TRANSFORM_XY: {
  1530. } break;
  1531. }
  1532. }
  1533. } break;
  1534. case MouseButton::LEFT: {
  1535. if (b->is_pressed()) {
  1536. clicked_wants_append = b->is_shift_pressed();
  1537. if (_edit.mode != TRANSFORM_NONE && (_edit.instant || collision_reposition)) {
  1538. commit_transform();
  1539. break; // just commit the edit, stop processing the event so we don't deselect the object
  1540. }
  1541. if (orbit_mouse_preference == NAVIGATION_LEFT_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_2")) {
  1542. break;
  1543. } else if (pan_mouse_preference == NAVIGATION_LEFT_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_2")) {
  1544. break;
  1545. } else if (zoom_mouse_preference == NAVIGATION_LEFT_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_2")) {
  1546. break;
  1547. }
  1548. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_RULER) {
  1549. EditorNode::get_singleton()->get_scene_root()->add_child(ruler);
  1550. collision_reposition = true;
  1551. break;
  1552. }
  1553. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_LIST_SELECT) {
  1554. _list_select(b);
  1555. break;
  1556. }
  1557. _edit.mouse_pos = b->get_position();
  1558. _edit.original_mouse_pos = b->get_position();
  1559. _edit.snap = spatial_editor->is_snap_enabled();
  1560. _edit.mode = TRANSFORM_NONE;
  1561. _edit.original = spatial_editor->get_gizmo_transform(); // To prevent to break when flipping with scale.
  1562. bool can_select_gizmos = spatial_editor->get_single_selected_node();
  1563. {
  1564. int idx = view_display_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  1565. int idx2 = view_display_menu->get_popup()->get_item_index(VIEW_TRANSFORM_GIZMO);
  1566. can_select_gizmos = can_select_gizmos && view_display_menu->get_popup()->is_item_checked(idx);
  1567. transform_gizmo_visible = view_display_menu->get_popup()->is_item_checked(idx2);
  1568. }
  1569. // Gizmo handles
  1570. if (can_select_gizmos) {
  1571. Vector<Ref<Node3DGizmo>> gizmos = spatial_editor->get_single_selected_node()->get_gizmos();
  1572. bool intersected_handle = false;
  1573. for (int i = 0; i < gizmos.size(); i++) {
  1574. Ref<EditorNode3DGizmo> seg = gizmos[i];
  1575. if (seg.is_null()) {
  1576. continue;
  1577. }
  1578. int gizmo_handle = -1;
  1579. bool gizmo_secondary = false;
  1580. seg->handles_intersect_ray(camera, _edit.mouse_pos, b->is_shift_pressed(), gizmo_handle, gizmo_secondary);
  1581. if (gizmo_handle != -1) {
  1582. _edit.gizmo = seg;
  1583. seg->begin_handle_action(gizmo_handle, gizmo_secondary);
  1584. _edit.gizmo_handle = gizmo_handle;
  1585. _edit.gizmo_handle_secondary = gizmo_secondary;
  1586. _edit.gizmo_initial_value = seg->get_handle_value(gizmo_handle, gizmo_secondary);
  1587. intersected_handle = true;
  1588. break;
  1589. }
  1590. }
  1591. if (intersected_handle) {
  1592. break;
  1593. }
  1594. }
  1595. // Transform gizmo
  1596. if (_transform_gizmo_select(_edit.mouse_pos)) {
  1597. break;
  1598. }
  1599. // Subgizmos
  1600. if (can_select_gizmos) {
  1601. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(spatial_editor->get_single_selected_node());
  1602. Vector<Ref<Node3DGizmo>> gizmos = spatial_editor->get_single_selected_node()->get_gizmos();
  1603. bool intersected_subgizmo = false;
  1604. for (int i = 0; i < gizmos.size(); i++) {
  1605. Ref<EditorNode3DGizmo> seg = gizmos[i];
  1606. if (seg.is_null()) {
  1607. continue;
  1608. }
  1609. int subgizmo_id = seg->subgizmos_intersect_ray(camera, _edit.mouse_pos);
  1610. if (subgizmo_id != -1) {
  1611. ERR_CONTINUE(!se);
  1612. if (b->is_shift_pressed()) {
  1613. if (se->subgizmos.has(subgizmo_id)) {
  1614. se->subgizmos.erase(subgizmo_id);
  1615. } else {
  1616. se->subgizmos.insert(subgizmo_id, seg->get_subgizmo_transform(subgizmo_id));
  1617. }
  1618. } else {
  1619. se->subgizmos.clear();
  1620. se->subgizmos.insert(subgizmo_id, seg->get_subgizmo_transform(subgizmo_id));
  1621. }
  1622. if (se->subgizmos.is_empty()) {
  1623. se->gizmo = Ref<EditorNode3DGizmo>();
  1624. } else {
  1625. se->gizmo = seg;
  1626. }
  1627. seg->redraw();
  1628. spatial_editor->update_transform_gizmo();
  1629. intersected_subgizmo = true;
  1630. break;
  1631. }
  1632. }
  1633. if (intersected_subgizmo) {
  1634. break;
  1635. }
  1636. }
  1637. clicked = ObjectID();
  1638. bool node_selected = get_selected_count() > 0;
  1639. if (node_selected && ((spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT && b->is_command_or_control_pressed()) || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE)) {
  1640. begin_transform(TRANSFORM_ROTATE, false);
  1641. break;
  1642. }
  1643. if (node_selected && spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE) {
  1644. begin_transform(TRANSFORM_TRANSLATE, false);
  1645. break;
  1646. }
  1647. if (node_selected && spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE) {
  1648. begin_transform(TRANSFORM_SCALE, false);
  1649. break;
  1650. }
  1651. if (after != EditorPlugin::AFTER_GUI_INPUT_CUSTOM) {
  1652. // Single item selection.
  1653. clicked = _select_ray(b->get_position());
  1654. selection_in_progress = true;
  1655. if (clicked.is_null()) {
  1656. // Default to region select.
  1657. cursor.region_select = true;
  1658. cursor.region_begin = b->get_position();
  1659. cursor.region_end = b->get_position();
  1660. }
  1661. }
  1662. surface->queue_redraw();
  1663. } else {
  1664. if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_RULER) {
  1665. EditorNode::get_singleton()->get_scene_root()->remove_child(ruler);
  1666. ruler_start_point->set_visible(false);
  1667. ruler_end_point->set_visible(false);
  1668. ruler_label->set_visible(false);
  1669. collision_reposition = false;
  1670. break;
  1671. }
  1672. if (_edit.gizmo.is_valid()) {
  1673. _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, _edit.gizmo_initial_value, false);
  1674. spatial_editor->get_single_selected_node()->update_gizmos();
  1675. _edit.gizmo = Ref<EditorNode3DGizmo>();
  1676. break;
  1677. }
  1678. if (after != EditorPlugin::AFTER_GUI_INPUT_CUSTOM) {
  1679. selection_in_progress = false;
  1680. if (clicked.is_valid()) {
  1681. _select_clicked(false);
  1682. }
  1683. if (cursor.region_select) {
  1684. _select_region();
  1685. cursor.region_select = false;
  1686. surface->queue_redraw();
  1687. }
  1688. }
  1689. if (!_edit.instant && _edit.mode != TRANSFORM_NONE) {
  1690. Node3D *selected = spatial_editor->get_single_selected_node();
  1691. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  1692. if (se && se->gizmo.is_valid()) {
  1693. Vector<int> ids;
  1694. Vector<Transform3D> restore;
  1695. for (const KeyValue<int, Transform3D> &GE : se->subgizmos) {
  1696. ids.push_back(GE.key);
  1697. restore.push_back(GE.value);
  1698. }
  1699. se->gizmo->commit_subgizmos(ids, restore, false);
  1700. } else {
  1701. if (_edit.original_mouse_pos != _edit.mouse_pos) {
  1702. commit_transform();
  1703. }
  1704. }
  1705. _edit.mode = TRANSFORM_NONE;
  1706. set_message("");
  1707. spatial_editor->update_transform_gizmo();
  1708. }
  1709. surface->queue_redraw();
  1710. }
  1711. } break;
  1712. default:
  1713. break;
  1714. }
  1715. }
  1716. ViewportNavMouseButton orbit_mouse_preference = (ViewportNavMouseButton)EDITOR_GET("editors/3d/navigation/orbit_mouse_button").operator int();
  1717. ViewportNavMouseButton pan_mouse_preference = (ViewportNavMouseButton)EDITOR_GET("editors/3d/navigation/pan_mouse_button").operator int();
  1718. ViewportNavMouseButton zoom_mouse_preference = (ViewportNavMouseButton)EDITOR_GET("editors/3d/navigation/zoom_mouse_button").operator int();
  1719. bool orbit_mod_pressed = _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_2");
  1720. bool pan_mod_pressed = _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_2");
  1721. bool zoom_mod_pressed = _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_2");
  1722. int orbit_mod_input_count = _get_shortcut_input_count("spatial_editor/viewport_orbit_modifier_1") + _get_shortcut_input_count("spatial_editor/viewport_orbit_modifier_2");
  1723. int pan_mod_input_count = _get_shortcut_input_count("spatial_editor/viewport_pan_modifier_1") + _get_shortcut_input_count("spatial_editor/viewport_pan_modifier_2");
  1724. int zoom_mod_input_count = _get_shortcut_input_count("spatial_editor/viewport_zoom_modifier_1") + _get_shortcut_input_count("spatial_editor/viewport_zoom_modifier_2");
  1725. bool orbit_not_empty = !_is_shortcut_empty("spatial_editor/viewport_orbit_modifier_1") || !_is_shortcut_empty("spatial_editor/viewport_orbit_modifier_2");
  1726. bool pan_not_empty = !_is_shortcut_empty("spatial_editor/viewport_pan_modifier_1") || !_is_shortcut_empty("spatial_editor/viewport_pan_modifier_2");
  1727. bool zoom_not_empty = !_is_shortcut_empty("spatial_editor/viewport_zoom_modifier_1") || !_is_shortcut_empty("spatial_editor/viewport_zoom_modifier_2");
  1728. Vector<ShortcutCheckSet> shortcut_check_sets;
  1729. shortcut_check_sets.push_back(ShortcutCheckSet(orbit_mod_pressed, orbit_not_empty, orbit_mod_input_count, orbit_mouse_preference, NAVIGATION_ORBIT));
  1730. shortcut_check_sets.push_back(ShortcutCheckSet(pan_mod_pressed, pan_not_empty, pan_mod_input_count, pan_mouse_preference, NAVIGATION_PAN));
  1731. shortcut_check_sets.push_back(ShortcutCheckSet(zoom_mod_pressed, zoom_not_empty, zoom_mod_input_count, zoom_mouse_preference, NAVIGATION_ZOOM));
  1732. shortcut_check_sets.sort_custom<ShortcutCheckSetComparator>();
  1733. Ref<InputEventMouseMotion> m = p_event;
  1734. // Instant transforms process mouse motion in input() to handle wrapping.
  1735. if (m.is_valid() && !_edit.instant) {
  1736. _edit.mouse_pos = m->get_position();
  1737. if (spatial_editor->get_single_selected_node()) {
  1738. Vector<Ref<Node3DGizmo>> gizmos = spatial_editor->get_single_selected_node()->get_gizmos();
  1739. Ref<EditorNode3DGizmo> found_gizmo;
  1740. int found_handle = -1;
  1741. bool found_handle_secondary = false;
  1742. for (int i = 0; i < gizmos.size(); i++) {
  1743. Ref<EditorNode3DGizmo> seg = gizmos[i];
  1744. if (seg.is_null()) {
  1745. continue;
  1746. }
  1747. seg->handles_intersect_ray(camera, _edit.mouse_pos, false, found_handle, found_handle_secondary);
  1748. if (found_handle != -1) {
  1749. found_gizmo = seg;
  1750. break;
  1751. }
  1752. }
  1753. if (found_gizmo.is_valid()) {
  1754. spatial_editor->select_gizmo_highlight_axis(-1);
  1755. }
  1756. bool current_hover_handle_secondary = false;
  1757. int current_hover_handle = spatial_editor->get_current_hover_gizmo_handle(current_hover_handle_secondary);
  1758. if (found_gizmo != spatial_editor->get_current_hover_gizmo() || found_handle != current_hover_handle || found_handle_secondary != current_hover_handle_secondary) {
  1759. spatial_editor->set_current_hover_gizmo(found_gizmo);
  1760. spatial_editor->set_current_hover_gizmo_handle(found_handle, found_handle_secondary);
  1761. spatial_editor->get_single_selected_node()->update_gizmos();
  1762. }
  1763. }
  1764. if (spatial_editor->get_current_hover_gizmo().is_null() && !m->get_button_mask().has_flag(MouseButtonMask::LEFT) && _edit.gizmo.is_null()) {
  1765. _transform_gizmo_select(_edit.mouse_pos, true);
  1766. }
  1767. NavigationMode nav_mode = NAVIGATION_NONE;
  1768. if (_edit.gizmo.is_valid()) {
  1769. _edit.gizmo->set_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, camera, m->get_position());
  1770. Variant v = _edit.gizmo->get_handle_value(_edit.gizmo_handle, _edit.gizmo_handle_secondary);
  1771. String n = _edit.gizmo->get_handle_name(_edit.gizmo_handle, _edit.gizmo_handle_secondary);
  1772. set_message(n + ": " + String(v));
  1773. } else if (m->get_button_mask().has_flag(MouseButtonMask::LEFT)) {
  1774. NavigationMode change_nav_from_shortcut = _get_nav_mode_from_shortcut_check(NAVIGATION_LEFT_MOUSE, shortcut_check_sets, false);
  1775. if (change_nav_from_shortcut != NAVIGATION_NONE) {
  1776. nav_mode = change_nav_from_shortcut;
  1777. } else {
  1778. const bool movement_threshold_passed = _edit.original_mouse_pos.distance_to(_edit.mouse_pos) > 8 * EDSCALE;
  1779. if (selection_in_progress && movement_threshold_passed && clicked.is_valid()) {
  1780. if (clicked_wants_append || !editor_selection->is_selected(Object::cast_to<Node>(ObjectDB::get_instance(clicked)))) {
  1781. cursor.region_select = true;
  1782. cursor.region_begin = _edit.original_mouse_pos;
  1783. clicked = ObjectID();
  1784. }
  1785. }
  1786. if (cursor.region_select) {
  1787. cursor.region_end = m->get_position();
  1788. surface->queue_redraw();
  1789. return;
  1790. }
  1791. if (clicked.is_valid() && movement_threshold_passed) {
  1792. _compute_edit(_edit.original_mouse_pos);
  1793. clicked = ObjectID();
  1794. _edit.mode = TRANSFORM_TRANSLATE;
  1795. }
  1796. if (_edit.mode == TRANSFORM_NONE || _edit.numeric_input != 0 || _edit.numeric_next_decimal != 0) {
  1797. return;
  1798. }
  1799. update_transform(_get_key_modifier(m) == Key::SHIFT);
  1800. }
  1801. } else if (m->get_button_mask().has_flag(MouseButtonMask::RIGHT) || freelook_active) {
  1802. NavigationMode change_nav_from_shortcut = _get_nav_mode_from_shortcut_check(NAVIGATION_RIGHT_MOUSE, shortcut_check_sets, false);
  1803. if (m->get_button_mask().has_flag(MouseButtonMask::RIGHT) && change_nav_from_shortcut != NAVIGATION_NONE) {
  1804. nav_mode = change_nav_from_shortcut;
  1805. } else if (freelook_active) {
  1806. nav_mode = NAVIGATION_LOOK;
  1807. } else if (orthogonal) {
  1808. nav_mode = NAVIGATION_PAN;
  1809. }
  1810. } else if (m->get_button_mask().has_flag(MouseButtonMask::MIDDLE)) {
  1811. NavigationMode change_nav_from_shortcut = _get_nav_mode_from_shortcut_check(NAVIGATION_MIDDLE_MOUSE, shortcut_check_sets, false);
  1812. if (change_nav_from_shortcut != NAVIGATION_NONE) {
  1813. nav_mode = change_nav_from_shortcut;
  1814. }
  1815. } else if (m->get_button_mask().has_flag(MouseButtonMask::MB_XBUTTON1)) {
  1816. NavigationMode change_nav_from_shortcut = _get_nav_mode_from_shortcut_check(NAVIGATION_MOUSE_4, shortcut_check_sets, false);
  1817. if (change_nav_from_shortcut != NAVIGATION_NONE) {
  1818. nav_mode = change_nav_from_shortcut;
  1819. }
  1820. } else if (m->get_button_mask().has_flag(MouseButtonMask::MB_XBUTTON2)) {
  1821. NavigationMode change_nav_from_shortcut = _get_nav_mode_from_shortcut_check(NAVIGATION_MOUSE_5, shortcut_check_sets, false);
  1822. if (change_nav_from_shortcut != NAVIGATION_NONE) {
  1823. nav_mode = change_nav_from_shortcut;
  1824. }
  1825. } else if (EDITOR_GET("editors/3d/navigation/emulate_3_button_mouse")) {
  1826. // Handle trackpad (no external mouse) use case
  1827. NavigationMode change_nav_from_shortcut = _get_nav_mode_from_shortcut_check(NAVIGATION_LEFT_MOUSE, shortcut_check_sets, true);
  1828. if (change_nav_from_shortcut != NAVIGATION_NONE) {
  1829. nav_mode = change_nav_from_shortcut;
  1830. }
  1831. }
  1832. switch (nav_mode) {
  1833. case NAVIGATION_PAN: {
  1834. _nav_pan(m, _get_warped_mouse_motion(m));
  1835. } break;
  1836. case NAVIGATION_ZOOM: {
  1837. _nav_zoom(m, m->get_relative());
  1838. } break;
  1839. case NAVIGATION_ORBIT: {
  1840. _nav_orbit(m, _get_warped_mouse_motion(m));
  1841. } break;
  1842. case NAVIGATION_LOOK: {
  1843. _nav_look(m, _get_warped_mouse_motion(m));
  1844. } break;
  1845. default: {
  1846. }
  1847. }
  1848. }
  1849. Ref<InputEventMagnifyGesture> magnify_gesture = p_event;
  1850. if (magnify_gesture.is_valid()) {
  1851. if (is_freelook_active()) {
  1852. scale_freelook_speed(magnify_gesture->get_factor());
  1853. } else {
  1854. scale_cursor_distance(1.0 / magnify_gesture->get_factor());
  1855. }
  1856. }
  1857. Ref<InputEventPanGesture> pan_gesture = p_event;
  1858. if (pan_gesture.is_valid()) {
  1859. NavigationMode nav_mode = NAVIGATION_NONE;
  1860. for (const ShortcutCheckSet &shortcut_check_set : shortcut_check_sets) {
  1861. if (shortcut_check_set.mod_pressed) {
  1862. nav_mode = shortcut_check_set.result_nav_mode;
  1863. break;
  1864. }
  1865. }
  1866. switch (nav_mode) {
  1867. case NAVIGATION_PAN: {
  1868. _nav_pan(pan_gesture, -pan_gesture->get_delta());
  1869. } break;
  1870. case NAVIGATION_ZOOM: {
  1871. _nav_zoom(pan_gesture, pan_gesture->get_delta());
  1872. } break;
  1873. case NAVIGATION_ORBIT: {
  1874. _nav_orbit(pan_gesture, -pan_gesture->get_delta());
  1875. } break;
  1876. case NAVIGATION_LOOK: {
  1877. _nav_look(pan_gesture, pan_gesture->get_delta());
  1878. } break;
  1879. default: {
  1880. }
  1881. }
  1882. }
  1883. Ref<InputEventKey> k = p_event;
  1884. if (k.is_valid()) {
  1885. if (!k->is_pressed()) {
  1886. return;
  1887. }
  1888. if (_edit.instant) {
  1889. // In a Blender-style transform, numbers set the magnitude of the transform.
  1890. // E.g. pressing g4.5x means "translate 4.5 units along the X axis".
  1891. // Use the Unicode value because we care about the text, not the actual keycode.
  1892. // This ensures numbers work consistently across different keyboard language layouts.
  1893. bool processed = true;
  1894. Key key = k->get_physical_keycode();
  1895. char32_t unicode = k->get_unicode();
  1896. if (unicode >= '0' && unicode <= '9') {
  1897. uint32_t value = uint32_t(unicode - Key::KEY_0);
  1898. if (_edit.numeric_next_decimal < 0) {
  1899. _edit.numeric_input = _edit.numeric_input + value * Math::pow(10.0, _edit.numeric_next_decimal--);
  1900. } else {
  1901. _edit.numeric_input = _edit.numeric_input * 10 + value;
  1902. }
  1903. update_transform_numeric();
  1904. } else if (unicode == '-') {
  1905. _edit.numeric_negate = !_edit.numeric_negate;
  1906. update_transform_numeric();
  1907. } else if (unicode == '.') {
  1908. if (_edit.numeric_next_decimal == 0) {
  1909. _edit.numeric_next_decimal = -1;
  1910. }
  1911. } else if (key == Key::ENTER || key == Key::KP_ENTER || key == Key::SPACE) {
  1912. commit_transform();
  1913. } else {
  1914. processed = false;
  1915. }
  1916. if (processed) {
  1917. // Ignore mouse inputs once we receive a numeric input.
  1918. set_process_input(false);
  1919. accept_event();
  1920. return;
  1921. }
  1922. }
  1923. if (EDITOR_GET("editors/3d/navigation/emulate_numpad")) {
  1924. const Key code = k->get_physical_keycode();
  1925. if (code >= Key::KEY_0 && code <= Key::KEY_9) {
  1926. k->set_keycode(code - Key::KEY_0 + Key::KP_0);
  1927. }
  1928. }
  1929. if (_edit.mode == TRANSFORM_NONE) {
  1930. if (_edit.gizmo.is_null() && is_freelook_active() && k->get_keycode() == Key::ESCAPE) {
  1931. set_freelook_active(false);
  1932. return;
  1933. }
  1934. if (_edit.gizmo.is_valid() && (k->get_keycode() == Key::ESCAPE || k->get_keycode() == Key::BACKSPACE)) {
  1935. // Restore.
  1936. _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, _edit.gizmo_initial_value, true);
  1937. _edit.gizmo = Ref<EditorNode3DGizmo>();
  1938. }
  1939. if (k->get_keycode() == Key::ESCAPE && !cursor.region_select) {
  1940. _clear_selected();
  1941. return;
  1942. }
  1943. } else {
  1944. // We're actively transforming, handle keys specially
  1945. TransformPlane new_plane = TRANSFORM_VIEW;
  1946. if (ED_IS_SHORTCUT("spatial_editor/lock_transform_x", p_event)) {
  1947. new_plane = TRANSFORM_X_AXIS;
  1948. } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_y", p_event)) {
  1949. new_plane = TRANSFORM_Y_AXIS;
  1950. } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_z", p_event)) {
  1951. new_plane = TRANSFORM_Z_AXIS;
  1952. } else if (_edit.mode != TRANSFORM_ROTATE) { // rotating on a plane doesn't make sense
  1953. if (ED_IS_SHORTCUT("spatial_editor/lock_transform_yz", p_event)) {
  1954. new_plane = TRANSFORM_YZ;
  1955. } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_xz", p_event)) {
  1956. new_plane = TRANSFORM_XZ;
  1957. } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_xy", p_event)) {
  1958. new_plane = TRANSFORM_XY;
  1959. }
  1960. }
  1961. if (new_plane != TRANSFORM_VIEW) {
  1962. if (new_plane != _edit.plane) {
  1963. // lock me once and get a global constraint
  1964. _edit.plane = new_plane;
  1965. spatial_editor->set_local_coords_enabled(false);
  1966. } else if (!spatial_editor->are_local_coords_enabled()) {
  1967. // lock me twice and get a local constraint
  1968. spatial_editor->set_local_coords_enabled(true);
  1969. } else {
  1970. // lock me thrice and we're back where we started
  1971. _edit.plane = TRANSFORM_VIEW;
  1972. spatial_editor->set_local_coords_enabled(false);
  1973. }
  1974. if (_edit.numeric_input != 0 || _edit.numeric_next_decimal != 0) {
  1975. update_transform_numeric();
  1976. } else {
  1977. update_transform(Input::get_singleton()->is_key_pressed(Key::SHIFT));
  1978. }
  1979. accept_event();
  1980. return;
  1981. }
  1982. }
  1983. if (ED_IS_SHORTCUT("spatial_editor/snap", p_event)) {
  1984. if (_edit.mode != TRANSFORM_NONE) {
  1985. _edit.snap = !_edit.snap;
  1986. }
  1987. }
  1988. if (ED_IS_SHORTCUT("spatial_editor/bottom_view", p_event)) {
  1989. _menu_option(VIEW_BOTTOM);
  1990. }
  1991. if (ED_IS_SHORTCUT("spatial_editor/top_view", p_event)) {
  1992. _menu_option(VIEW_TOP);
  1993. }
  1994. if (ED_IS_SHORTCUT("spatial_editor/rear_view", p_event)) {
  1995. _menu_option(VIEW_REAR);
  1996. }
  1997. if (ED_IS_SHORTCUT("spatial_editor/front_view", p_event)) {
  1998. _menu_option(VIEW_FRONT);
  1999. }
  2000. if (ED_IS_SHORTCUT("spatial_editor/left_view", p_event)) {
  2001. _menu_option(VIEW_LEFT);
  2002. }
  2003. if (ED_IS_SHORTCUT("spatial_editor/right_view", p_event)) {
  2004. _menu_option(VIEW_RIGHT);
  2005. }
  2006. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_down", p_event)) {
  2007. // Clamp rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  2008. cursor.x_rot = CLAMP(cursor.x_rot - Math_PI / 12.0, -1.57, 1.57);
  2009. view_type = VIEW_TYPE_USER;
  2010. _update_name();
  2011. }
  2012. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_up", p_event)) {
  2013. // Clamp rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  2014. cursor.x_rot = CLAMP(cursor.x_rot + Math_PI / 12.0, -1.57, 1.57);
  2015. view_type = VIEW_TYPE_USER;
  2016. _update_name();
  2017. }
  2018. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_right", p_event)) {
  2019. cursor.y_rot -= Math_PI / 12.0;
  2020. view_type = VIEW_TYPE_USER;
  2021. _update_name();
  2022. }
  2023. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_left", p_event)) {
  2024. cursor.y_rot += Math_PI / 12.0;
  2025. view_type = VIEW_TYPE_USER;
  2026. _update_name();
  2027. }
  2028. if (ED_IS_SHORTCUT("spatial_editor/orbit_view_180", p_event)) {
  2029. cursor.y_rot += Math_PI;
  2030. view_type = VIEW_TYPE_USER;
  2031. _update_name();
  2032. }
  2033. if (ED_IS_SHORTCUT("spatial_editor/focus_origin", p_event)) {
  2034. _menu_option(VIEW_CENTER_TO_ORIGIN);
  2035. }
  2036. if (ED_IS_SHORTCUT("spatial_editor/focus_selection", p_event)) {
  2037. _menu_option(VIEW_CENTER_TO_SELECTION);
  2038. }
  2039. if (ED_IS_SHORTCUT("spatial_editor/align_transform_with_view", p_event)) {
  2040. _menu_option(VIEW_ALIGN_TRANSFORM_WITH_VIEW);
  2041. }
  2042. if (ED_IS_SHORTCUT("spatial_editor/align_rotation_with_view", p_event)) {
  2043. _menu_option(VIEW_ALIGN_ROTATION_WITH_VIEW);
  2044. }
  2045. if (ED_IS_SHORTCUT("spatial_editor/insert_anim_key", p_event)) {
  2046. if (!get_selected_count() || _edit.mode != TRANSFORM_NONE) {
  2047. return;
  2048. }
  2049. if (!AnimationPlayerEditor::get_singleton()->get_track_editor()->has_keying()) {
  2050. set_message(TTR("Keying is disabled (no key inserted)."));
  2051. return;
  2052. }
  2053. List<Node *> &selection = editor_selection->get_selected_node_list();
  2054. for (Node *E : selection) {
  2055. Node3D *sp = Object::cast_to<Node3D>(E);
  2056. if (!sp) {
  2057. continue;
  2058. }
  2059. spatial_editor->emit_signal(SNAME("transform_key_request"), sp, "", sp->get_transform());
  2060. }
  2061. set_message(TTR("Animation Key Inserted."));
  2062. }
  2063. if (ED_IS_SHORTCUT("spatial_editor/cancel_transform", p_event) && _edit.mode != TRANSFORM_NONE) {
  2064. cancel_transform();
  2065. }
  2066. if (!is_freelook_active() && !k->is_echo()) {
  2067. if (ED_IS_SHORTCUT("spatial_editor/instant_translate", p_event) && (_edit.mode != TRANSFORM_TRANSLATE || collision_reposition)) {
  2068. if (_edit.mode == TRANSFORM_NONE) {
  2069. begin_transform(TRANSFORM_TRANSLATE, true);
  2070. } else if (_edit.instant || collision_reposition) {
  2071. commit_transform();
  2072. begin_transform(TRANSFORM_TRANSLATE, true);
  2073. }
  2074. }
  2075. if (ED_IS_SHORTCUT("spatial_editor/instant_rotate", p_event) && _edit.mode != TRANSFORM_ROTATE) {
  2076. if (_edit.mode == TRANSFORM_NONE) {
  2077. begin_transform(TRANSFORM_ROTATE, true);
  2078. } else if (_edit.instant || collision_reposition) {
  2079. commit_transform();
  2080. begin_transform(TRANSFORM_ROTATE, true);
  2081. }
  2082. }
  2083. if (ED_IS_SHORTCUT("spatial_editor/instant_scale", p_event) && _edit.mode != TRANSFORM_SCALE) {
  2084. if (_edit.mode == TRANSFORM_NONE) {
  2085. begin_transform(TRANSFORM_SCALE, true);
  2086. } else if (_edit.instant || collision_reposition) {
  2087. commit_transform();
  2088. begin_transform(TRANSFORM_SCALE, true);
  2089. }
  2090. }
  2091. if (ED_IS_SHORTCUT("spatial_editor/collision_reposition", p_event) && editor_selection->get_selected_node_list().size() == 1 && !collision_reposition) {
  2092. if (_edit.mode == TRANSFORM_NONE || _edit.instant) {
  2093. if (_edit.mode == TRANSFORM_NONE) {
  2094. _compute_edit(_edit.mouse_pos);
  2095. } else {
  2096. commit_transform();
  2097. _compute_edit(_edit.mouse_pos);
  2098. }
  2099. _edit.mode = TRANSFORM_TRANSLATE;
  2100. collision_reposition = true;
  2101. }
  2102. }
  2103. }
  2104. // Freelook doesn't work in orthogonal mode.
  2105. if (!orthogonal && ED_IS_SHORTCUT("spatial_editor/freelook_toggle", p_event)) {
  2106. set_freelook_active(!is_freelook_active());
  2107. } else if (k->get_keycode() == Key::ESCAPE) {
  2108. set_freelook_active(false);
  2109. }
  2110. if (k->get_keycode() == Key::SPACE) {
  2111. if (!k->is_pressed()) {
  2112. emit_signal(SNAME("toggle_maximize_view"), this);
  2113. }
  2114. }
  2115. if (ED_IS_SHORTCUT("spatial_editor/decrease_fov", p_event)) {
  2116. scale_fov(-0.05);
  2117. }
  2118. if (ED_IS_SHORTCUT("spatial_editor/increase_fov", p_event)) {
  2119. scale_fov(0.05);
  2120. }
  2121. if (ED_IS_SHORTCUT("spatial_editor/reset_fov", p_event)) {
  2122. reset_fov();
  2123. }
  2124. }
  2125. // freelook uses most of the useful shortcuts, like save, so its ok
  2126. // to consider freelook active as end of the line for future events.
  2127. if (freelook_active) {
  2128. accept_event();
  2129. }
  2130. }
  2131. int Node3DEditorViewport::_get_shortcut_input_count(const String &p_name) {
  2132. Ref<Shortcut> check_shortcut = ED_GET_SHORTCUT(p_name);
  2133. ERR_FAIL_COND_V_MSG(check_shortcut.is_null(), 0, "The Shortcut was null, possible name mismatch.");
  2134. return check_shortcut->get_events().size();
  2135. }
  2136. Node3DEditorViewport::NavigationMode Node3DEditorViewport::_get_nav_mode_from_shortcut_check(ViewportNavMouseButton p_mouse_button, Vector<ShortcutCheckSet> p_shortcut_check_sets, bool p_use_not_empty) {
  2137. if (p_use_not_empty) {
  2138. for (const ShortcutCheckSet &shortcut_check_set : p_shortcut_check_sets) {
  2139. if (shortcut_check_set.mod_pressed && shortcut_check_set.shortcut_not_empty) {
  2140. return shortcut_check_set.result_nav_mode;
  2141. }
  2142. }
  2143. } else {
  2144. for (const ShortcutCheckSet &shortcut_check_set : p_shortcut_check_sets) {
  2145. if (shortcut_check_set.mouse_preference == p_mouse_button && shortcut_check_set.mod_pressed) {
  2146. return shortcut_check_set.result_nav_mode;
  2147. }
  2148. }
  2149. }
  2150. return NAVIGATION_NONE;
  2151. }
  2152. void Node3DEditorViewport::_nav_pan(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  2153. const NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
  2154. const real_t translation_sensitivity = EDITOR_GET("editors/3d/navigation_feel/translation_sensitivity");
  2155. real_t pan_speed = translation_sensitivity / 150.0;
  2156. if (p_event.is_valid() && nav_scheme == NAVIGATION_MAYA && p_event->is_shift_pressed()) {
  2157. pan_speed *= 10;
  2158. }
  2159. Transform3D camera_transform;
  2160. camera_transform.translate_local(cursor.pos);
  2161. camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
  2162. camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
  2163. const bool invert_x_axis = EDITOR_GET("editors/3d/navigation/invert_x_axis");
  2164. const bool invert_y_axis = EDITOR_GET("editors/3d/navigation/invert_y_axis");
  2165. Vector3 translation(
  2166. (invert_x_axis ? -1 : 1) * -p_relative.x * pan_speed,
  2167. (invert_y_axis ? -1 : 1) * p_relative.y * pan_speed,
  2168. 0);
  2169. translation *= cursor.distance / DISTANCE_DEFAULT;
  2170. camera_transform.translate_local(translation);
  2171. cursor.pos = camera_transform.origin;
  2172. }
  2173. void Node3DEditorViewport::_nav_zoom(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  2174. const NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
  2175. real_t zoom_speed = 1 / 80.0;
  2176. if (p_event.is_valid() && nav_scheme == NAVIGATION_MAYA && p_event->is_shift_pressed()) {
  2177. zoom_speed *= 10;
  2178. }
  2179. NavigationZoomStyle zoom_style = (NavigationZoomStyle)EDITOR_GET("editors/3d/navigation/zoom_style").operator int();
  2180. if (zoom_style == NAVIGATION_ZOOM_HORIZONTAL) {
  2181. if (p_relative.x > 0) {
  2182. scale_cursor_distance(1 - p_relative.x * zoom_speed);
  2183. } else if (p_relative.x < 0) {
  2184. scale_cursor_distance(1.0 / (1 + p_relative.x * zoom_speed));
  2185. }
  2186. } else {
  2187. if (p_relative.y > 0) {
  2188. scale_cursor_distance(1 + p_relative.y * zoom_speed);
  2189. } else if (p_relative.y < 0) {
  2190. scale_cursor_distance(1.0 / (1 - p_relative.y * zoom_speed));
  2191. }
  2192. }
  2193. }
  2194. void Node3DEditorViewport::_nav_orbit(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  2195. if (lock_rotation) {
  2196. _nav_pan(p_event, p_relative);
  2197. return;
  2198. }
  2199. if (orthogonal && auto_orthogonal) {
  2200. _menu_option(VIEW_PERSPECTIVE);
  2201. }
  2202. const real_t degrees_per_pixel = EDITOR_GET("editors/3d/navigation_feel/orbit_sensitivity");
  2203. const real_t radians_per_pixel = Math::deg_to_rad(degrees_per_pixel);
  2204. const bool invert_y_axis = EDITOR_GET("editors/3d/navigation/invert_y_axis");
  2205. const bool invert_x_axis = EDITOR_GET("editors/3d/navigation/invert_x_axis");
  2206. if (invert_y_axis) {
  2207. cursor.x_rot -= p_relative.y * radians_per_pixel;
  2208. } else {
  2209. cursor.x_rot += p_relative.y * radians_per_pixel;
  2210. }
  2211. // Clamp the Y rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  2212. cursor.x_rot = CLAMP(cursor.x_rot, -1.57, 1.57);
  2213. if (invert_x_axis) {
  2214. cursor.y_rot -= p_relative.x * radians_per_pixel;
  2215. } else {
  2216. cursor.y_rot += p_relative.x * radians_per_pixel;
  2217. }
  2218. view_type = VIEW_TYPE_USER;
  2219. _update_name();
  2220. }
  2221. void Node3DEditorViewport::_nav_look(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
  2222. if (orthogonal) {
  2223. _nav_pan(p_event, p_relative);
  2224. return;
  2225. }
  2226. if (orthogonal && auto_orthogonal) {
  2227. _menu_option(VIEW_PERSPECTIVE);
  2228. }
  2229. // Scale mouse sensitivity with camera FOV scale when zoomed in to make it easier to point at things.
  2230. const real_t degrees_per_pixel = real_t(EDITOR_GET("editors/3d/freelook/freelook_sensitivity")) * MIN(1.0, cursor.fov_scale);
  2231. const real_t radians_per_pixel = Math::deg_to_rad(degrees_per_pixel);
  2232. const bool invert_y_axis = EDITOR_GET("editors/3d/navigation/invert_y_axis");
  2233. // Note: do NOT assume the camera has the "current" transform, because it is interpolated and may have "lag".
  2234. const Transform3D prev_camera_transform = to_camera_transform(cursor);
  2235. if (invert_y_axis) {
  2236. cursor.x_rot -= p_relative.y * radians_per_pixel;
  2237. } else {
  2238. cursor.x_rot += p_relative.y * radians_per_pixel;
  2239. }
  2240. // Clamp the Y rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
  2241. cursor.x_rot = CLAMP(cursor.x_rot, -1.57, 1.57);
  2242. cursor.y_rot += p_relative.x * radians_per_pixel;
  2243. // Look is like the opposite of Orbit: the focus point rotates around the camera
  2244. Transform3D camera_transform = to_camera_transform(cursor);
  2245. Vector3 pos = camera_transform.xform(Vector3(0, 0, 0));
  2246. Vector3 prev_pos = prev_camera_transform.xform(Vector3(0, 0, 0));
  2247. Vector3 diff = prev_pos - pos;
  2248. cursor.pos += diff;
  2249. view_type = VIEW_TYPE_USER;
  2250. _update_name();
  2251. }
  2252. void Node3DEditorViewport::set_freelook_active(bool active_now) {
  2253. if (!freelook_active && active_now) {
  2254. // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
  2255. cursor = camera_cursor;
  2256. // Make sure eye_pos is synced, because freelook referential is eye pos rather than orbit pos
  2257. Vector3 forward = to_camera_transform(cursor).basis.xform(Vector3(0, 0, -1));
  2258. cursor.eye_pos = cursor.pos - cursor.distance * forward;
  2259. // Also sync the camera cursor, otherwise switching to freelook will be trippy if inertia is active
  2260. camera_cursor.eye_pos = cursor.eye_pos;
  2261. if (EDITOR_GET("editors/3d/freelook/freelook_speed_zoom_link")) {
  2262. // Re-adjust freelook speed from the current zoom level
  2263. real_t base_speed = EDITOR_GET("editors/3d/freelook/freelook_base_speed");
  2264. freelook_speed = base_speed * cursor.distance;
  2265. }
  2266. previous_mouse_position = get_local_mouse_position();
  2267. // Hide mouse like in an FPS (warping doesn't work)
  2268. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
  2269. } else if (freelook_active && !active_now) {
  2270. // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
  2271. cursor = camera_cursor;
  2272. // Restore mouse
  2273. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  2274. // Restore the previous mouse position when leaving freelook mode.
  2275. // This is done because leaving `Input.MOUSE_MODE_CAPTURED` will center the cursor
  2276. // due to OS limitations.
  2277. warp_mouse(previous_mouse_position);
  2278. }
  2279. freelook_active = active_now;
  2280. }
  2281. void Node3DEditorViewport::scale_fov(real_t p_fov_offset) {
  2282. cursor.fov_scale = CLAMP(cursor.fov_scale + p_fov_offset, 0.1, 2.5);
  2283. surface->queue_redraw();
  2284. }
  2285. void Node3DEditorViewport::reset_fov() {
  2286. cursor.fov_scale = 1.0;
  2287. surface->queue_redraw();
  2288. }
  2289. void Node3DEditorViewport::scale_cursor_distance(real_t scale) {
  2290. real_t min_distance = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
  2291. real_t max_distance = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
  2292. if (unlikely(min_distance > max_distance)) {
  2293. cursor.distance = (min_distance + max_distance) / 2;
  2294. } else {
  2295. cursor.distance = CLAMP(cursor.distance * scale, min_distance, max_distance);
  2296. }
  2297. if (cursor.distance == max_distance || cursor.distance == min_distance) {
  2298. zoom_failed_attempts_count++;
  2299. } else {
  2300. zoom_failed_attempts_count = 0;
  2301. }
  2302. zoom_indicator_delay = ZOOM_FREELOOK_INDICATOR_DELAY_S;
  2303. surface->queue_redraw();
  2304. }
  2305. void Node3DEditorViewport::scale_freelook_speed(real_t scale) {
  2306. real_t min_speed = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
  2307. real_t max_speed = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
  2308. if (unlikely(min_speed > max_speed)) {
  2309. freelook_speed = (min_speed + max_speed) / 2;
  2310. } else {
  2311. freelook_speed = CLAMP(freelook_speed * scale, min_speed, max_speed);
  2312. }
  2313. zoom_indicator_delay = ZOOM_FREELOOK_INDICATOR_DELAY_S;
  2314. surface->queue_redraw();
  2315. }
  2316. bool Node3DEditorViewport::_is_nav_modifier_pressed(const String &p_name) {
  2317. return _is_shortcut_empty(p_name) || Input::get_singleton()->is_action_pressed(p_name);
  2318. }
  2319. bool Node3DEditorViewport::_is_shortcut_empty(const String &p_name) {
  2320. Ref<Shortcut> check_shortcut = ED_GET_SHORTCUT(p_name);
  2321. ERR_FAIL_COND_V_MSG(check_shortcut.is_null(), true, "The Shortcut was null, possible name mismatch.");
  2322. return check_shortcut->get_events().is_empty();
  2323. }
  2324. Point2 Node3DEditorViewport::_get_warped_mouse_motion(const Ref<InputEventMouseMotion> &p_ev_mouse_motion) const {
  2325. Point2 relative;
  2326. if (bool(EDITOR_GET("editors/3d/navigation/warped_mouse_panning"))) {
  2327. relative = Input::get_singleton()->warp_mouse_motion(p_ev_mouse_motion, surface->get_global_rect());
  2328. } else {
  2329. relative = p_ev_mouse_motion->get_relative();
  2330. }
  2331. return relative;
  2332. }
  2333. void Node3DEditorViewport::_update_freelook(real_t delta) {
  2334. if (!is_freelook_active()) {
  2335. return;
  2336. }
  2337. const FreelookNavigationScheme navigation_scheme = (FreelookNavigationScheme)EDITOR_GET("editors/3d/freelook/freelook_navigation_scheme").operator int();
  2338. Vector3 forward;
  2339. if (navigation_scheme == FREELOOK_FULLY_AXIS_LOCKED) {
  2340. // Forward/backward keys will always go straight forward/backward, never moving on the Y axis.
  2341. forward = Vector3(0, 0, -1).rotated(Vector3(0, 1, 0), camera->get_rotation().y);
  2342. } else {
  2343. // Forward/backward keys will be relative to the camera pitch.
  2344. forward = camera->get_transform().basis.xform(Vector3(0, 0, -1));
  2345. }
  2346. const Vector3 right = camera->get_transform().basis.xform(Vector3(1, 0, 0));
  2347. Vector3 up;
  2348. if (navigation_scheme == FREELOOK_PARTIALLY_AXIS_LOCKED || navigation_scheme == FREELOOK_FULLY_AXIS_LOCKED) {
  2349. // Up/down keys will always go up/down regardless of camera pitch.
  2350. up = Vector3(0, 1, 0);
  2351. } else {
  2352. // Up/down keys will be relative to the camera pitch.
  2353. up = camera->get_transform().basis.xform(Vector3(0, 1, 0));
  2354. }
  2355. Vector3 direction;
  2356. // Use actions from the inputmap, as this is the only way to reliably detect input in this method.
  2357. // See #54469 for more discussion and explanation.
  2358. Input *inp = Input::get_singleton();
  2359. if (inp->is_action_pressed("spatial_editor/freelook_left")) {
  2360. direction -= right;
  2361. }
  2362. if (inp->is_action_pressed("spatial_editor/freelook_right")) {
  2363. direction += right;
  2364. }
  2365. if (inp->is_action_pressed("spatial_editor/freelook_forward")) {
  2366. direction += forward;
  2367. }
  2368. if (inp->is_action_pressed("spatial_editor/freelook_backwards")) {
  2369. direction -= forward;
  2370. }
  2371. if (inp->is_action_pressed("spatial_editor/freelook_up")) {
  2372. direction += up;
  2373. }
  2374. if (inp->is_action_pressed("spatial_editor/freelook_down")) {
  2375. direction -= up;
  2376. }
  2377. real_t speed = freelook_speed;
  2378. if (inp->is_action_pressed("spatial_editor/freelook_speed_modifier")) {
  2379. speed *= 3.0;
  2380. }
  2381. if (inp->is_action_pressed("spatial_editor/freelook_slow_modifier")) {
  2382. speed *= 0.333333;
  2383. }
  2384. const Vector3 motion = direction * speed * delta;
  2385. cursor.pos += motion;
  2386. cursor.eye_pos += motion;
  2387. }
  2388. void Node3DEditorViewport::set_message(const String &p_message, float p_time) {
  2389. message = p_message;
  2390. message_time = p_time;
  2391. }
  2392. void Node3DEditorPlugin::edited_scene_changed() {
  2393. for (uint32_t i = 0; i < Node3DEditor::VIEWPORTS_COUNT; i++) {
  2394. Node3DEditorViewport *viewport = Node3DEditor::get_singleton()->get_editor_viewport(i);
  2395. if (viewport->is_visible()) {
  2396. viewport->notification(Control::NOTIFICATION_VISIBILITY_CHANGED);
  2397. }
  2398. }
  2399. }
  2400. void Node3DEditorViewport::_project_settings_changed() {
  2401. // Update shadow atlas if changed.
  2402. int shadowmap_size = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_size");
  2403. bool shadowmap_16_bits = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_16_bits");
  2404. int atlas_q0 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_0_subdiv");
  2405. int atlas_q1 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_1_subdiv");
  2406. int atlas_q2 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_2_subdiv");
  2407. int atlas_q3 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_3_subdiv");
  2408. viewport->set_positional_shadow_atlas_size(shadowmap_size);
  2409. viewport->set_positional_shadow_atlas_16_bits(shadowmap_16_bits);
  2410. viewport->set_positional_shadow_atlas_quadrant_subdiv(0, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q0));
  2411. viewport->set_positional_shadow_atlas_quadrant_subdiv(1, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q1));
  2412. viewport->set_positional_shadow_atlas_quadrant_subdiv(2, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q2));
  2413. viewport->set_positional_shadow_atlas_quadrant_subdiv(3, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q3));
  2414. _update_shrink();
  2415. // Update MSAA, screen-space AA and debanding if changed
  2416. const int msaa_mode = GLOBAL_GET("rendering/anti_aliasing/quality/msaa_3d");
  2417. viewport->set_msaa_3d(Viewport::MSAA(msaa_mode));
  2418. const int ssaa_mode = GLOBAL_GET("rendering/anti_aliasing/quality/screen_space_aa");
  2419. viewport->set_screen_space_aa(Viewport::ScreenSpaceAA(ssaa_mode));
  2420. const bool use_taa = GLOBAL_GET("rendering/anti_aliasing/quality/use_taa");
  2421. viewport->set_use_taa(use_taa);
  2422. const bool transparent_background = GLOBAL_GET("rendering/viewport/transparent_background");
  2423. viewport->set_transparent_background(transparent_background);
  2424. const bool use_hdr_2d = GLOBAL_GET("rendering/viewport/hdr_2d");
  2425. viewport->set_use_hdr_2d(use_hdr_2d);
  2426. const bool use_debanding = GLOBAL_GET("rendering/anti_aliasing/quality/use_debanding");
  2427. viewport->set_use_debanding(use_debanding);
  2428. const bool use_occlusion_culling = GLOBAL_GET("rendering/occlusion_culling/use_occlusion_culling");
  2429. viewport->set_use_occlusion_culling(use_occlusion_culling);
  2430. const float mesh_lod_threshold = GLOBAL_GET("rendering/mesh_lod/lod_change/threshold_pixels");
  2431. viewport->set_mesh_lod_threshold(mesh_lod_threshold);
  2432. const Viewport::Scaling3DMode scaling_3d_mode = Viewport::Scaling3DMode(int(GLOBAL_GET("rendering/scaling_3d/mode")));
  2433. viewport->set_scaling_3d_mode(scaling_3d_mode);
  2434. const float scaling_3d_scale = GLOBAL_GET("rendering/scaling_3d/scale");
  2435. viewport->set_scaling_3d_scale(scaling_3d_scale);
  2436. const float fsr_sharpness = GLOBAL_GET("rendering/scaling_3d/fsr_sharpness");
  2437. viewport->set_fsr_sharpness(fsr_sharpness);
  2438. const float texture_mipmap_bias = GLOBAL_GET("rendering/textures/default_filters/texture_mipmap_bias");
  2439. viewport->set_texture_mipmap_bias(texture_mipmap_bias);
  2440. const Viewport::AnisotropicFiltering anisotropic_filtering_level = Viewport::AnisotropicFiltering(int(GLOBAL_GET("rendering/textures/default_filters/anisotropic_filtering_level")));
  2441. viewport->set_anisotropic_filtering_level(anisotropic_filtering_level);
  2442. }
  2443. void Node3DEditorViewport::_notification(int p_what) {
  2444. switch (p_what) {
  2445. case NOTIFICATION_READY: {
  2446. ProjectSettings::get_singleton()->connect("settings_changed", callable_mp(this, &Node3DEditorViewport::_project_settings_changed));
  2447. } break;
  2448. case NOTIFICATION_VISIBILITY_CHANGED: {
  2449. bool vp_visible = is_visible_in_tree();
  2450. set_process(vp_visible);
  2451. set_physics_process(vp_visible);
  2452. if (vp_visible) {
  2453. orthogonal = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL));
  2454. _update_name();
  2455. _update_camera(0);
  2456. } else {
  2457. set_freelook_active(false);
  2458. }
  2459. callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view).call_deferred();
  2460. } break;
  2461. case NOTIFICATION_RESIZED: {
  2462. callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view).call_deferred();
  2463. } break;
  2464. case NOTIFICATION_PROCESS: {
  2465. if (ruler->is_inside_tree()) {
  2466. Vector3 start_pos = ruler_start_point->get_global_position();
  2467. Vector3 end_pos = ruler_end_point->get_global_position();
  2468. geometry->clear_surfaces();
  2469. geometry->surface_begin(Mesh::PRIMITIVE_LINES);
  2470. geometry->surface_add_vertex(start_pos);
  2471. geometry->surface_add_vertex(end_pos);
  2472. geometry->surface_end();
  2473. float distance = start_pos.distance_to(end_pos);
  2474. ruler_label->set_text(TS->format_number(vformat("%.3f m", distance)));
  2475. Vector3 center = (start_pos + end_pos) / 2;
  2476. Vector2 screen_position = camera->unproject_position(center) - (ruler_label->get_custom_minimum_size() / 2);
  2477. ruler_label->set_position(screen_position);
  2478. }
  2479. real_t delta = get_process_delta_time();
  2480. if (zoom_indicator_delay > 0) {
  2481. zoom_indicator_delay -= delta;
  2482. if (zoom_indicator_delay <= 0) {
  2483. surface->queue_redraw();
  2484. zoom_limit_label->hide();
  2485. }
  2486. }
  2487. _update_navigation_controls_visibility();
  2488. _update_freelook(delta);
  2489. Node *scene_root = SceneTreeDock::get_singleton()->get_editor_data()->get_edited_scene_root();
  2490. if (previewing_cinema && scene_root != nullptr) {
  2491. Camera3D *cam = scene_root->get_viewport()->get_camera_3d();
  2492. if (cam != nullptr && cam != previewing) {
  2493. //then switch the viewport's camera to the scene's viewport camera
  2494. if (previewing != nullptr) {
  2495. previewing->disconnect(SceneStringName(tree_exited), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  2496. }
  2497. previewing = cam;
  2498. previewing->connect(SceneStringName(tree_exited), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  2499. RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), cam->get_camera());
  2500. surface->queue_redraw();
  2501. }
  2502. }
  2503. if (_camera_moved_externally()) {
  2504. // If camera moved after this plugin last set it, presumably a tool script has moved it, accept the new camera transform as the cursor position.
  2505. _apply_camera_transform_to_cursor();
  2506. }
  2507. _update_camera(delta);
  2508. const HashMap<Node *, Object *> &selection = editor_selection->get_selection();
  2509. bool changed = false;
  2510. bool exist = false;
  2511. for (const KeyValue<Node *, Object *> &E : selection) {
  2512. Node3D *sp = Object::cast_to<Node3D>(E.key);
  2513. if (!sp) {
  2514. continue;
  2515. }
  2516. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  2517. if (!se) {
  2518. continue;
  2519. }
  2520. Transform3D t = sp->get_global_gizmo_transform();
  2521. AABB new_aabb = _calculate_spatial_bounds(sp);
  2522. exist = true;
  2523. if (se->last_xform == t && se->aabb == new_aabb && !se->last_xform_dirty) {
  2524. continue;
  2525. }
  2526. changed = true;
  2527. se->last_xform_dirty = false;
  2528. se->last_xform = t;
  2529. se->aabb = new_aabb;
  2530. Transform3D t_offset = t;
  2531. // apply AABB scaling before item's global transform
  2532. {
  2533. const Vector3 offset(0.005, 0.005, 0.005);
  2534. Basis aabb_s;
  2535. aabb_s.scale(se->aabb.size + offset);
  2536. t.translate_local(se->aabb.position - offset / 2);
  2537. t.basis = t.basis * aabb_s;
  2538. }
  2539. {
  2540. const Vector3 offset(0.01, 0.01, 0.01);
  2541. Basis aabb_s;
  2542. aabb_s.scale(se->aabb.size + offset);
  2543. t_offset.translate_local(se->aabb.position - offset / 2);
  2544. t_offset.basis = t_offset.basis * aabb_s;
  2545. }
  2546. RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance, t);
  2547. RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_offset, t_offset);
  2548. RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_xray, t);
  2549. RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_xray_offset, t_offset);
  2550. }
  2551. if (changed || (spatial_editor->is_gizmo_visible() && !exist)) {
  2552. spatial_editor->update_transform_gizmo();
  2553. }
  2554. if (message_time > 0) {
  2555. if (message != last_message) {
  2556. surface->queue_redraw();
  2557. last_message = message;
  2558. }
  2559. message_time -= get_process_delta_time();
  2560. if (message_time < 0) {
  2561. surface->queue_redraw();
  2562. }
  2563. }
  2564. bool show_info = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_INFORMATION));
  2565. if (show_info != info_panel->is_visible()) {
  2566. info_panel->set_visible(show_info);
  2567. }
  2568. Camera3D *current_camera;
  2569. if (previewing) {
  2570. current_camera = previewing;
  2571. } else {
  2572. current_camera = camera;
  2573. }
  2574. if (show_info) {
  2575. const String viewport_size = vformat(U"%d × %d", viewport->get_size().x, viewport->get_size().y);
  2576. String text;
  2577. text += vformat(TTR("X: %s\n"), rtos(current_camera->get_position().x).pad_decimals(1));
  2578. text += vformat(TTR("Y: %s\n"), rtos(current_camera->get_position().y).pad_decimals(1));
  2579. text += vformat(TTR("Z: %s\n"), rtos(current_camera->get_position().z).pad_decimals(1));
  2580. text += "\n";
  2581. text += vformat(
  2582. TTR("Size: %s (%.1fMP)\n"),
  2583. viewport_size,
  2584. viewport->get_size().x * viewport->get_size().y * 0.000001);
  2585. text += "\n";
  2586. text += vformat(TTR("Objects: %d\n"), viewport->get_render_info(Viewport::RENDER_INFO_TYPE_VISIBLE, Viewport::RENDER_INFO_OBJECTS_IN_FRAME));
  2587. text += vformat(TTR("Primitives: %d\n"), viewport->get_render_info(Viewport::RENDER_INFO_TYPE_VISIBLE, Viewport::RENDER_INFO_PRIMITIVES_IN_FRAME));
  2588. text += vformat(TTR("Draw Calls: %d"), viewport->get_render_info(Viewport::RENDER_INFO_TYPE_VISIBLE, Viewport::RENDER_INFO_DRAW_CALLS_IN_FRAME));
  2589. info_label->set_text(text);
  2590. }
  2591. // FPS Counter.
  2592. bool show_fps = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_FRAME_TIME));
  2593. if (show_fps != frame_time_panel->is_visible()) {
  2594. frame_time_panel->set_visible(show_fps);
  2595. RS::get_singleton()->viewport_set_measure_render_time(viewport->get_viewport_rid(), show_fps);
  2596. for (int i = 0; i < FRAME_TIME_HISTORY; i++) {
  2597. // Initialize to 120 FPS, so that the initial estimation until we get enough data is always reasonable.
  2598. cpu_time_history[i] = 8.333333;
  2599. gpu_time_history[i] = 8.333333;
  2600. }
  2601. cpu_time_history_index = 0;
  2602. gpu_time_history_index = 0;
  2603. }
  2604. if (show_fps) {
  2605. cpu_time_history[cpu_time_history_index] = RS::get_singleton()->viewport_get_measured_render_time_cpu(viewport->get_viewport_rid());
  2606. cpu_time_history_index = (cpu_time_history_index + 1) % FRAME_TIME_HISTORY;
  2607. double cpu_time = 0.0;
  2608. for (int i = 0; i < FRAME_TIME_HISTORY; i++) {
  2609. cpu_time += cpu_time_history[i];
  2610. }
  2611. cpu_time /= FRAME_TIME_HISTORY;
  2612. // Prevent unrealistically low values.
  2613. cpu_time = MAX(0.01, cpu_time);
  2614. gpu_time_history[gpu_time_history_index] = RS::get_singleton()->viewport_get_measured_render_time_gpu(viewport->get_viewport_rid());
  2615. gpu_time_history_index = (gpu_time_history_index + 1) % FRAME_TIME_HISTORY;
  2616. double gpu_time = 0.0;
  2617. for (int i = 0; i < FRAME_TIME_HISTORY; i++) {
  2618. gpu_time += gpu_time_history[i];
  2619. }
  2620. gpu_time /= FRAME_TIME_HISTORY;
  2621. // Prevent division by zero for the FPS counter (and unrealistically low values).
  2622. // This limits the reported FPS to 100000.
  2623. gpu_time = MAX(0.01, gpu_time);
  2624. // Color labels depending on performance level ("good" = green, "OK" = yellow, "bad" = red).
  2625. // Middle point is at 15 ms.
  2626. cpu_time_label->set_text(vformat(TTR("CPU Time: %s ms"), rtos(cpu_time).pad_decimals(2)));
  2627. cpu_time_label->add_theme_color_override(
  2628. SceneStringName(font_color),
  2629. frame_time_gradient->get_color_at_offset(
  2630. Math::remap(cpu_time, 0, 30, 0, 1)));
  2631. gpu_time_label->set_text(vformat(TTR("GPU Time: %s ms"), rtos(gpu_time).pad_decimals(2)));
  2632. // Middle point is at 15 ms.
  2633. gpu_time_label->add_theme_color_override(
  2634. SceneStringName(font_color),
  2635. frame_time_gradient->get_color_at_offset(
  2636. Math::remap(gpu_time, 0, 30, 0, 1)));
  2637. const double fps = 1000.0 / gpu_time;
  2638. fps_label->set_text(vformat(TTR("FPS: %d"), fps));
  2639. // Middle point is at 60 FPS.
  2640. fps_label->add_theme_color_override(
  2641. SceneStringName(font_color),
  2642. frame_time_gradient->get_color_at_offset(
  2643. Math::remap(fps, 110, 10, 0, 1)));
  2644. }
  2645. bool show_cinema = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW));
  2646. cinema_label->set_visible(show_cinema);
  2647. if (show_cinema) {
  2648. float cinema_half_width = cinema_label->get_size().width / 2.0f;
  2649. cinema_label->set_anchor_and_offset(SIDE_LEFT, 0.5f, -cinema_half_width);
  2650. }
  2651. if (lock_rotation) {
  2652. float locked_half_width = locked_label->get_size().width / 2.0f;
  2653. locked_label->set_anchor_and_offset(SIDE_LEFT, 0.5f, -locked_half_width);
  2654. }
  2655. } break;
  2656. case NOTIFICATION_PHYSICS_PROCESS: {
  2657. if (collision_reposition) {
  2658. Node3D *selected_node = nullptr;
  2659. if (ruler->is_inside_tree()) {
  2660. if (ruler_start_point->is_visible()) {
  2661. selected_node = ruler_end_point;
  2662. } else {
  2663. selected_node = ruler_start_point;
  2664. }
  2665. } else {
  2666. List<Node *> &selection = editor_selection->get_selected_node_list();
  2667. if (selection.size() == 1) {
  2668. selected_node = Object::cast_to<Node3D>(selection.front()->get());
  2669. }
  2670. }
  2671. if (selected_node) {
  2672. if (!ruler->is_inside_tree()) {
  2673. double snap = EDITOR_GET("interface/inspector/default_float_step");
  2674. int snap_step_decimals = Math::range_step_decimals(snap);
  2675. set_message(TTR("Translating:") + " (" + String::num(selected_node->get_global_position().x, snap_step_decimals) + ", " +
  2676. String::num(selected_node->get_global_position().y, snap_step_decimals) + ", " + String::num(selected_node->get_global_position().z, snap_step_decimals) + ")");
  2677. }
  2678. selected_node->set_global_position(spatial_editor->snap_point(_get_instance_position(_edit.mouse_pos, selected_node)));
  2679. if (ruler->is_inside_tree() && !ruler_start_point->is_visible()) {
  2680. ruler_end_point->set_global_position(ruler_start_point->get_global_position());
  2681. ruler_start_point->set_visible(true);
  2682. ruler_end_point->set_visible(true);
  2683. ruler_label->set_visible(true);
  2684. }
  2685. }
  2686. }
  2687. if (!update_preview_node) {
  2688. return;
  2689. }
  2690. if (preview_node->is_inside_tree()) {
  2691. preview_node_pos = spatial_editor->snap_point(_get_instance_position(preview_node_viewport_pos, preview_node));
  2692. double snap = EDITOR_GET("interface/inspector/default_float_step");
  2693. int snap_step_decimals = Math::range_step_decimals(snap);
  2694. set_message(TTR("Instantiating:") + " (" + String::num(preview_node_pos.x, snap_step_decimals) + ", " +
  2695. String::num(preview_node_pos.y, snap_step_decimals) + ", " + String::num(preview_node_pos.z, snap_step_decimals) + ")");
  2696. Transform3D preview_gl_transform = Transform3D(Basis(), preview_node_pos);
  2697. preview_node->set_global_transform(preview_gl_transform);
  2698. if (!preview_node->is_visible()) {
  2699. preview_node->show();
  2700. }
  2701. }
  2702. update_preview_node = false;
  2703. } break;
  2704. case NOTIFICATION_APPLICATION_FOCUS_OUT:
  2705. case NOTIFICATION_WM_WINDOW_FOCUS_OUT: {
  2706. set_freelook_active(false);
  2707. cursor.region_select = false;
  2708. surface->queue_redraw();
  2709. } break;
  2710. case NOTIFICATION_ENTER_TREE: {
  2711. surface->connect(SceneStringName(draw), callable_mp(this, &Node3DEditorViewport::_draw));
  2712. surface->connect(SceneStringName(gui_input), callable_mp(this, &Node3DEditorViewport::_sinput));
  2713. surface->connect(SceneStringName(mouse_entered), callable_mp(this, &Node3DEditorViewport::_surface_mouse_enter));
  2714. surface->connect(SceneStringName(mouse_exited), callable_mp(this, &Node3DEditorViewport::_surface_mouse_exit));
  2715. surface->connect(SceneStringName(focus_entered), callable_mp(this, &Node3DEditorViewport::_surface_focus_enter));
  2716. surface->connect(SceneStringName(focus_exited), callable_mp(this, &Node3DEditorViewport::_surface_focus_exit));
  2717. _init_gizmo_instance(index);
  2718. } break;
  2719. case NOTIFICATION_EXIT_TREE: {
  2720. _finish_gizmo_instances();
  2721. } break;
  2722. case NOTIFICATION_THEME_CHANGED: {
  2723. view_display_menu->set_button_icon(get_editor_theme_icon(SNAME("GuiTabMenuHl")));
  2724. preview_camera->set_button_icon(get_editor_theme_icon(SNAME("Camera3D")));
  2725. Control *gui_base = EditorNode::get_singleton()->get_gui_base();
  2726. const Ref<StyleBox> &information_3d_stylebox = gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles));
  2727. view_display_menu->begin_bulk_theme_override();
  2728. view_display_menu->add_theme_style_override(CoreStringName(normal), information_3d_stylebox);
  2729. view_display_menu->add_theme_style_override("normal_mirrored", information_3d_stylebox);
  2730. view_display_menu->add_theme_style_override(SceneStringName(hover), information_3d_stylebox);
  2731. view_display_menu->add_theme_style_override("hover_mirrored", information_3d_stylebox);
  2732. view_display_menu->add_theme_style_override("hover_pressed", information_3d_stylebox);
  2733. view_display_menu->add_theme_style_override("hover_pressed_mirrored", information_3d_stylebox);
  2734. view_display_menu->add_theme_style_override(SceneStringName(pressed), information_3d_stylebox);
  2735. view_display_menu->add_theme_style_override("pressed_mirrored", information_3d_stylebox);
  2736. view_display_menu->add_theme_style_override("focus", information_3d_stylebox);
  2737. view_display_menu->add_theme_style_override("focus_mirrored", information_3d_stylebox);
  2738. view_display_menu->add_theme_style_override("disabled", information_3d_stylebox);
  2739. view_display_menu->add_theme_style_override("disabled_mirrored", information_3d_stylebox);
  2740. view_display_menu->end_bulk_theme_override();
  2741. preview_camera->begin_bulk_theme_override();
  2742. preview_camera->add_theme_style_override(CoreStringName(normal), information_3d_stylebox);
  2743. preview_camera->add_theme_style_override("normal_mirrored", information_3d_stylebox);
  2744. preview_camera->add_theme_style_override(SceneStringName(hover), information_3d_stylebox);
  2745. preview_camera->add_theme_style_override("hover_mirrored", information_3d_stylebox);
  2746. preview_camera->add_theme_style_override("hover_pressed", information_3d_stylebox);
  2747. preview_camera->add_theme_style_override("hover_pressed_mirrored", information_3d_stylebox);
  2748. preview_camera->add_theme_style_override(SceneStringName(pressed), information_3d_stylebox);
  2749. preview_camera->add_theme_style_override("pressed_mirrored", information_3d_stylebox);
  2750. preview_camera->add_theme_style_override("focus", information_3d_stylebox);
  2751. preview_camera->add_theme_style_override("focus_mirrored", information_3d_stylebox);
  2752. preview_camera->add_theme_style_override("disabled", information_3d_stylebox);
  2753. preview_camera->add_theme_style_override("disabled_mirrored", information_3d_stylebox);
  2754. preview_camera->end_bulk_theme_override();
  2755. frame_time_gradient->set_color(0, get_theme_color(SNAME("success_color"), EditorStringName(Editor)));
  2756. frame_time_gradient->set_color(1, get_theme_color(SNAME("warning_color"), EditorStringName(Editor)));
  2757. frame_time_gradient->set_color(2, get_theme_color(SNAME("error_color"), EditorStringName(Editor)));
  2758. info_panel->add_theme_style_override(SceneStringName(panel), information_3d_stylebox);
  2759. frame_time_panel->add_theme_style_override(SceneStringName(panel), information_3d_stylebox);
  2760. // Set a minimum width to prevent the width from changing all the time
  2761. // when numbers vary rapidly. This minimum width is set based on a
  2762. // GPU time of 999.99 ms in the current editor language.
  2763. const float min_width = get_theme_font(SNAME("main"), EditorStringName(EditorFonts))->get_string_size(vformat(TTR("GPU Time: %s ms"), 999.99)).x;
  2764. frame_time_panel->set_custom_minimum_size(Size2(min_width, 0) * EDSCALE);
  2765. frame_time_vbox->add_theme_constant_override("separation", Math::round(-1 * EDSCALE));
  2766. cinema_label->add_theme_style_override(CoreStringName(normal), information_3d_stylebox);
  2767. locked_label->add_theme_style_override(CoreStringName(normal), information_3d_stylebox);
  2768. ruler_label->add_theme_color_override(SceneStringName(font_color), Color(1.0, 0.9, 0.0, 1.0));
  2769. ruler_label->add_theme_color_override("font_outline_color", Color(0.0, 0.0, 0.0, 1.0));
  2770. ruler_label->add_theme_constant_override("outline_size", 4 * EDSCALE);
  2771. ruler_label->add_theme_font_size_override(SceneStringName(font_size), 15 * EDSCALE);
  2772. ruler_label->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("bold"), EditorStringName(EditorFonts)));
  2773. } break;
  2774. case NOTIFICATION_DRAG_END: {
  2775. // Clear preview material when dropped outside applicable object.
  2776. if (spatial_editor->get_preview_material().is_valid() && !is_drag_successful()) {
  2777. _reset_preview_material();
  2778. _remove_preview_material();
  2779. } else {
  2780. _remove_preview_node();
  2781. }
  2782. } break;
  2783. }
  2784. }
  2785. static void draw_indicator_bar(Control &p_surface, real_t p_fill, const Ref<Texture2D> p_icon, const Ref<Font> p_font, int p_font_size, const String &p_text, const Color &p_color) {
  2786. // Adjust bar size from control height
  2787. const Vector2 surface_size = p_surface.get_size();
  2788. const real_t h = surface_size.y / 2.0;
  2789. const real_t y = (surface_size.y - h) / 2.0;
  2790. const Rect2 r(10 * EDSCALE, y, 6 * EDSCALE, h);
  2791. const real_t sy = r.size.y * p_fill;
  2792. // Note: because this bar appears over the viewport, it has to stay readable for any background color
  2793. // Draw both neutral dark and bright colors to account this
  2794. p_surface.draw_rect(r, p_color * Color(1, 1, 1, 0.2));
  2795. 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));
  2796. p_surface.draw_rect(r.grow(1), Color(0, 0, 0, 0.7), false, Math::round(EDSCALE));
  2797. const Vector2 icon_size = p_icon->get_size();
  2798. const Vector2 icon_pos = Vector2(r.position.x - (icon_size.x - r.size.x) / 2, r.position.y + r.size.y + 2 * EDSCALE);
  2799. p_surface.draw_texture(p_icon, icon_pos, p_color);
  2800. // Draw text below the bar (for speed/zoom information).
  2801. p_surface.draw_string_outline(p_font, Vector2(icon_pos.x, icon_pos.y + icon_size.y + 16 * EDSCALE), p_text, HORIZONTAL_ALIGNMENT_LEFT, -1.f, p_font_size, Math::round(2 * EDSCALE), Color(0, 0, 0));
  2802. p_surface.draw_string(p_font, Vector2(icon_pos.x, icon_pos.y + icon_size.y + 16 * EDSCALE), p_text, HORIZONTAL_ALIGNMENT_LEFT, -1.f, p_font_size, p_color);
  2803. }
  2804. void Node3DEditorViewport::_draw() {
  2805. EditorPluginList *over_plugin_list = EditorNode::get_singleton()->get_editor_plugins_over();
  2806. if (!over_plugin_list->is_empty()) {
  2807. over_plugin_list->forward_3d_draw_over_viewport(surface);
  2808. }
  2809. EditorPluginList *force_over_plugin_list = EditorNode::get_singleton()->get_editor_plugins_force_over();
  2810. if (!force_over_plugin_list->is_empty()) {
  2811. force_over_plugin_list->forward_3d_force_draw_over_viewport(surface);
  2812. }
  2813. if (surface->has_focus() || rotation_control->has_focus()) {
  2814. Size2 size = surface->get_size();
  2815. Rect2 r = Rect2(Point2(), size);
  2816. get_theme_stylebox(SNAME("FocusViewport"), EditorStringName(EditorStyles))->draw(surface->get_canvas_item(), r);
  2817. }
  2818. if (cursor.region_select) {
  2819. const Rect2 selection_rect = Rect2(cursor.region_begin, cursor.region_end - cursor.region_begin);
  2820. surface->draw_rect(
  2821. selection_rect,
  2822. get_theme_color(SNAME("box_selection_fill_color"), EditorStringName(Editor)));
  2823. surface->draw_rect(
  2824. selection_rect,
  2825. get_theme_color(SNAME("box_selection_stroke_color"), EditorStringName(Editor)),
  2826. false,
  2827. Math::round(EDSCALE));
  2828. }
  2829. RID ci = surface->get_canvas_item();
  2830. if (message_time > 0) {
  2831. Ref<Font> font = get_theme_font(SceneStringName(font), SNAME("Label"));
  2832. int font_size = get_theme_font_size(SceneStringName(font_size), SNAME("Label"));
  2833. Point2 msgpos = Point2(10 * EDSCALE, get_size().y - 14 * EDSCALE);
  2834. font->draw_string(ci, msgpos + Point2(1, 1), message, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, Color(0, 0, 0, 0.8));
  2835. font->draw_string(ci, msgpos + Point2(-1, -1), message, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, Color(0, 0, 0, 0.8));
  2836. font->draw_string(ci, msgpos, message, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, Color(1, 1, 1, 1));
  2837. }
  2838. if (_edit.mode == TRANSFORM_ROTATE && _edit.show_rotation_line) {
  2839. Point2 center = point_to_screen(_edit.center);
  2840. Color handle_color;
  2841. switch (_edit.plane) {
  2842. case TRANSFORM_X_AXIS:
  2843. handle_color = get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor));
  2844. break;
  2845. case TRANSFORM_Y_AXIS:
  2846. handle_color = get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor));
  2847. break;
  2848. case TRANSFORM_Z_AXIS:
  2849. handle_color = get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor));
  2850. break;
  2851. default:
  2852. handle_color = get_theme_color(SNAME("accent_color"), EditorStringName(Editor));
  2853. break;
  2854. }
  2855. handle_color = handle_color.from_hsv(handle_color.get_h(), 0.25, 1.0, 1);
  2856. RenderingServer::get_singleton()->canvas_item_add_line(
  2857. ci,
  2858. _edit.mouse_pos,
  2859. center,
  2860. handle_color,
  2861. Math::round(2 * EDSCALE));
  2862. }
  2863. if (previewing) {
  2864. Size2 ss = Size2(GLOBAL_GET("display/window/size/viewport_width"), GLOBAL_GET("display/window/size/viewport_height"));
  2865. float aspect = ss.aspect();
  2866. Size2 s = get_size();
  2867. Rect2 draw_rect;
  2868. switch (previewing->get_keep_aspect_mode()) {
  2869. case Camera3D::KEEP_WIDTH: {
  2870. draw_rect.size = Size2(s.width, s.width / aspect);
  2871. draw_rect.position.x = 0;
  2872. draw_rect.position.y = (s.height - draw_rect.size.y) * 0.5;
  2873. } break;
  2874. case Camera3D::KEEP_HEIGHT: {
  2875. draw_rect.size = Size2(s.height * aspect, s.height);
  2876. draw_rect.position.y = 0;
  2877. draw_rect.position.x = (s.width - draw_rect.size.x) * 0.5;
  2878. } break;
  2879. }
  2880. draw_rect = Rect2(Vector2(), s).intersection(draw_rect);
  2881. surface->draw_rect(draw_rect, Color(0.6, 0.6, 0.1, 0.5), false, Math::round(2 * EDSCALE));
  2882. } else {
  2883. if (zoom_indicator_delay > 0.0) {
  2884. if (is_freelook_active()) {
  2885. // Show speed
  2886. real_t min_speed = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
  2887. real_t max_speed = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
  2888. real_t scale_length = (max_speed - min_speed);
  2889. if (!Math::is_zero_approx(scale_length)) {
  2890. real_t logscale_t = 1.0 - Math::log1p(freelook_speed - min_speed) / Math::log1p(scale_length);
  2891. // Display the freelook speed to help the user get a better sense of scale.
  2892. const int precision = freelook_speed < 1.0 ? 2 : 1;
  2893. draw_indicator_bar(
  2894. *surface,
  2895. 1.0 - logscale_t,
  2896. get_editor_theme_icon(SNAME("ViewportSpeed")),
  2897. get_theme_font(SceneStringName(font), SNAME("Label")),
  2898. get_theme_font_size(SceneStringName(font_size), SNAME("Label")),
  2899. vformat("%s m/s", String::num(freelook_speed).pad_decimals(precision)),
  2900. Color(1.0, 0.95, 0.7));
  2901. }
  2902. } else {
  2903. // Show zoom
  2904. zoom_limit_label->set_visible(zoom_failed_attempts_count > 15);
  2905. real_t min_distance = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
  2906. real_t max_distance = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
  2907. real_t scale_length = (max_distance - min_distance);
  2908. if (!Math::is_zero_approx(scale_length)) {
  2909. real_t logscale_t = 1.0 - Math::log1p(cursor.distance - min_distance) / Math::log1p(scale_length);
  2910. // Display the zoom center distance to help the user get a better sense of scale.
  2911. const int precision = cursor.distance < 1.0 ? 2 : 1;
  2912. draw_indicator_bar(
  2913. *surface,
  2914. logscale_t,
  2915. get_editor_theme_icon(SNAME("ViewportZoom")),
  2916. get_theme_font(SceneStringName(font), SNAME("Label")),
  2917. get_theme_font_size(SceneStringName(font_size), SNAME("Label")),
  2918. vformat("%s m", String::num(cursor.distance).pad_decimals(precision)),
  2919. Color(0.7, 0.95, 1.0));
  2920. }
  2921. }
  2922. }
  2923. }
  2924. }
  2925. bool Node3DEditorViewport::_camera_moved_externally() {
  2926. Transform3D t = camera->get_global_transform();
  2927. return !t.is_equal_approx(last_camera_transform);
  2928. }
  2929. void Node3DEditorViewport::_apply_camera_transform_to_cursor() {
  2930. // Effectively the reverse of to_camera_transform, use camera transform to set cursor position and rotation.
  2931. Transform3D camera_transform = camera->get_camera_transform();
  2932. cursor.pos = camera_transform.origin;
  2933. cursor.x_rot = -camera_transform.basis.get_euler().x;
  2934. cursor.y_rot = -camera_transform.basis.get_euler().y;
  2935. }
  2936. void Node3DEditorViewport::_menu_option(int p_option) {
  2937. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  2938. switch (p_option) {
  2939. case VIEW_TOP: {
  2940. cursor.y_rot = 0;
  2941. cursor.x_rot = Math_PI / 2.0;
  2942. set_message(TTR("Top View."), 2);
  2943. view_type = VIEW_TYPE_TOP;
  2944. _set_auto_orthogonal();
  2945. _update_name();
  2946. } break;
  2947. case VIEW_BOTTOM: {
  2948. cursor.y_rot = 0;
  2949. cursor.x_rot = -Math_PI / 2.0;
  2950. set_message(TTR("Bottom View."), 2);
  2951. view_type = VIEW_TYPE_BOTTOM;
  2952. _set_auto_orthogonal();
  2953. _update_name();
  2954. } break;
  2955. case VIEW_LEFT: {
  2956. cursor.x_rot = 0;
  2957. cursor.y_rot = Math_PI / 2.0;
  2958. set_message(TTR("Left View."), 2);
  2959. view_type = VIEW_TYPE_LEFT;
  2960. _set_auto_orthogonal();
  2961. _update_name();
  2962. } break;
  2963. case VIEW_RIGHT: {
  2964. cursor.x_rot = 0;
  2965. cursor.y_rot = -Math_PI / 2.0;
  2966. set_message(TTR("Right View."), 2);
  2967. view_type = VIEW_TYPE_RIGHT;
  2968. _set_auto_orthogonal();
  2969. _update_name();
  2970. } break;
  2971. case VIEW_FRONT: {
  2972. cursor.x_rot = 0;
  2973. cursor.y_rot = 0;
  2974. set_message(TTR("Front View."), 2);
  2975. view_type = VIEW_TYPE_FRONT;
  2976. _set_auto_orthogonal();
  2977. _update_name();
  2978. } break;
  2979. case VIEW_REAR: {
  2980. cursor.x_rot = 0;
  2981. cursor.y_rot = Math_PI;
  2982. set_message(TTR("Rear View."), 2);
  2983. view_type = VIEW_TYPE_REAR;
  2984. _set_auto_orthogonal();
  2985. _update_name();
  2986. } break;
  2987. case VIEW_CENTER_TO_ORIGIN: {
  2988. cursor.pos = Vector3(0, 0, 0);
  2989. } break;
  2990. case VIEW_CENTER_TO_SELECTION: {
  2991. focus_selection();
  2992. } break;
  2993. case VIEW_ALIGN_TRANSFORM_WITH_VIEW: {
  2994. if (!get_selected_count()) {
  2995. break;
  2996. }
  2997. Transform3D camera_transform = camera->get_global_transform();
  2998. List<Node *> &selection = editor_selection->get_selected_node_list();
  2999. undo_redo->create_action(TTR("Align Transform with View"));
  3000. for (Node *E : selection) {
  3001. Node3D *sp = Object::cast_to<Node3D>(E);
  3002. if (!sp) {
  3003. continue;
  3004. }
  3005. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  3006. if (!se) {
  3007. continue;
  3008. }
  3009. Transform3D xform;
  3010. if (orthogonal) {
  3011. xform = sp->get_global_transform();
  3012. xform.basis = Basis::from_euler(camera_transform.basis.get_euler());
  3013. } else {
  3014. xform = camera_transform;
  3015. xform.scale_basis(sp->get_scale());
  3016. }
  3017. if (Object::cast_to<Decal>(E)) {
  3018. // Adjust rotation to match Decal's default orientation.
  3019. // This makes the decal "look" in the same direction as the camera,
  3020. // rather than pointing down relative to the camera orientation.
  3021. xform.basis.rotate_local(Vector3(1, 0, 0), Math_TAU * 0.25);
  3022. }
  3023. Node3D *parent = sp->get_parent_node_3d();
  3024. Transform3D local_xform = parent ? parent->get_global_transform().affine_inverse() * xform : xform;
  3025. undo_redo->add_do_method(sp, "set_transform", local_xform);
  3026. undo_redo->add_undo_method(sp, "set_transform", sp->get_local_gizmo_transform());
  3027. }
  3028. undo_redo->commit_action();
  3029. } break;
  3030. case VIEW_ALIGN_ROTATION_WITH_VIEW: {
  3031. if (!get_selected_count()) {
  3032. break;
  3033. }
  3034. Transform3D camera_transform = camera->get_global_transform();
  3035. List<Node *> &selection = editor_selection->get_selected_node_list();
  3036. undo_redo->create_action(TTR("Align Rotation with View"));
  3037. for (Node *E : selection) {
  3038. Node3D *sp = Object::cast_to<Node3D>(E);
  3039. if (!sp) {
  3040. continue;
  3041. }
  3042. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  3043. if (!se) {
  3044. continue;
  3045. }
  3046. Basis basis = camera_transform.basis;
  3047. if (Object::cast_to<Decal>(E)) {
  3048. // Adjust rotation to match Decal's default orientation.
  3049. // This makes the decal "look" in the same direction as the camera,
  3050. // rather than pointing down relative to the camera orientation.
  3051. basis.rotate_local(Vector3(1, 0, 0), Math_TAU * 0.25);
  3052. }
  3053. undo_redo->add_do_method(sp, "set_rotation", basis.get_euler_normalized());
  3054. undo_redo->add_undo_method(sp, "set_rotation", sp->get_rotation());
  3055. }
  3056. undo_redo->commit_action();
  3057. } break;
  3058. case VIEW_ENVIRONMENT: {
  3059. int idx = view_display_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT);
  3060. bool current = view_display_menu->get_popup()->is_item_checked(idx);
  3061. current = !current;
  3062. if (current) {
  3063. camera->set_environment(Ref<Resource>());
  3064. } else {
  3065. camera->set_environment(Node3DEditor::get_singleton()->get_viewport_environment());
  3066. }
  3067. view_display_menu->get_popup()->set_item_checked(idx, current);
  3068. } break;
  3069. case VIEW_PERSPECTIVE: {
  3070. view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
  3071. view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), false);
  3072. orthogonal = false;
  3073. auto_orthogonal = false;
  3074. callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view).call_deferred();
  3075. _update_camera(0);
  3076. _update_name();
  3077. } break;
  3078. case VIEW_ORTHOGONAL: {
  3079. view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), false);
  3080. view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), true);
  3081. orthogonal = true;
  3082. auto_orthogonal = false;
  3083. callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view).call_deferred();
  3084. _update_camera(0);
  3085. _update_name();
  3086. } break;
  3087. case VIEW_SWITCH_PERSPECTIVE_ORTHOGONAL: {
  3088. _menu_option(orthogonal ? VIEW_PERSPECTIVE : VIEW_ORTHOGONAL);
  3089. } break;
  3090. case VIEW_AUTO_ORTHOGONAL: {
  3091. int idx = view_display_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL);
  3092. bool current = view_display_menu->get_popup()->is_item_checked(idx);
  3093. current = !current;
  3094. view_display_menu->get_popup()->set_item_checked(idx, current);
  3095. if (auto_orthogonal) {
  3096. auto_orthogonal = false;
  3097. _update_name();
  3098. }
  3099. } break;
  3100. case VIEW_LOCK_ROTATION: {
  3101. int idx = view_display_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
  3102. bool current = view_display_menu->get_popup()->is_item_checked(idx);
  3103. _set_lock_view_rotation(!current);
  3104. } break;
  3105. case VIEW_AUDIO_LISTENER: {
  3106. int idx = view_display_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
  3107. bool current = view_display_menu->get_popup()->is_item_checked(idx);
  3108. current = !current;
  3109. viewport->set_as_audio_listener_3d(current);
  3110. view_display_menu->get_popup()->set_item_checked(idx, current);
  3111. } break;
  3112. case VIEW_AUDIO_DOPPLER: {
  3113. int idx = view_display_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
  3114. bool current = view_display_menu->get_popup()->is_item_checked(idx);
  3115. current = !current;
  3116. camera->set_doppler_tracking(current ? Camera3D::DOPPLER_TRACKING_IDLE_STEP : Camera3D::DOPPLER_TRACKING_DISABLED);
  3117. view_display_menu->get_popup()->set_item_checked(idx, current);
  3118. } break;
  3119. case VIEW_CINEMATIC_PREVIEW: {
  3120. int idx = view_display_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
  3121. bool current = view_display_menu->get_popup()->is_item_checked(idx);
  3122. current = !current;
  3123. view_display_menu->get_popup()->set_item_checked(idx, current);
  3124. previewing_cinema = true;
  3125. _toggle_cinema_preview(current);
  3126. if (current) {
  3127. preview_camera->hide();
  3128. } else {
  3129. if (previewing != nullptr) {
  3130. preview_camera->show();
  3131. }
  3132. }
  3133. } break;
  3134. case VIEW_GIZMOS: {
  3135. int idx = view_display_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  3136. bool current = view_display_menu->get_popup()->is_item_checked(idx);
  3137. current = !current;
  3138. uint32_t layers = camera->get_cull_mask();
  3139. layers &= ~(1 << GIZMO_EDIT_LAYER);
  3140. if (current) {
  3141. layers |= (1 << GIZMO_EDIT_LAYER);
  3142. }
  3143. camera->set_cull_mask(layers);
  3144. view_display_menu->get_popup()->set_item_checked(idx, current);
  3145. } break;
  3146. case VIEW_TRANSFORM_GIZMO: {
  3147. int idx = view_display_menu->get_popup()->get_item_index(VIEW_TRANSFORM_GIZMO);
  3148. bool current = view_display_menu->get_popup()->is_item_checked(idx);
  3149. current = !current;
  3150. transform_gizmo_visible = current;
  3151. spatial_editor->update_transform_gizmo();
  3152. view_display_menu->get_popup()->set_item_checked(idx, current);
  3153. } break;
  3154. case VIEW_HALF_RESOLUTION: {
  3155. int idx = view_display_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
  3156. bool current = view_display_menu->get_popup()->is_item_checked(idx);
  3157. view_display_menu->get_popup()->set_item_checked(idx, !current);
  3158. _update_shrink();
  3159. } break;
  3160. case VIEW_INFORMATION: {
  3161. int idx = view_display_menu->get_popup()->get_item_index(VIEW_INFORMATION);
  3162. bool current = view_display_menu->get_popup()->is_item_checked(idx);
  3163. view_display_menu->get_popup()->set_item_checked(idx, !current);
  3164. } break;
  3165. case VIEW_FRAME_TIME: {
  3166. int idx = view_display_menu->get_popup()->get_item_index(VIEW_FRAME_TIME);
  3167. bool current = view_display_menu->get_popup()->is_item_checked(idx);
  3168. view_display_menu->get_popup()->set_item_checked(idx, !current);
  3169. } break;
  3170. case VIEW_GRID: {
  3171. int idx = view_display_menu->get_popup()->get_item_index(VIEW_GRID);
  3172. bool current = view_display_menu->get_popup()->is_item_checked(idx);
  3173. current = !current;
  3174. uint32_t layers = camera->get_cull_mask();
  3175. layers &= ~(1 << GIZMO_GRID_LAYER);
  3176. if (current) {
  3177. layers |= (1 << GIZMO_GRID_LAYER);
  3178. }
  3179. camera->set_cull_mask(layers);
  3180. view_display_menu->get_popup()->set_item_checked(idx, current);
  3181. } break;
  3182. case VIEW_DISPLAY_NORMAL:
  3183. case VIEW_DISPLAY_WIREFRAME:
  3184. case VIEW_DISPLAY_OVERDRAW:
  3185. case VIEW_DISPLAY_UNSHADED:
  3186. case VIEW_DISPLAY_LIGHTING:
  3187. case VIEW_DISPLAY_NORMAL_BUFFER:
  3188. case VIEW_DISPLAY_DEBUG_SHADOW_ATLAS:
  3189. case VIEW_DISPLAY_DEBUG_DIRECTIONAL_SHADOW_ATLAS:
  3190. case VIEW_DISPLAY_DEBUG_VOXEL_GI_ALBEDO:
  3191. case VIEW_DISPLAY_DEBUG_VOXEL_GI_LIGHTING:
  3192. case VIEW_DISPLAY_DEBUG_VOXEL_GI_EMISSION:
  3193. case VIEW_DISPLAY_DEBUG_SCENE_LUMINANCE:
  3194. case VIEW_DISPLAY_DEBUG_SSAO:
  3195. case VIEW_DISPLAY_DEBUG_SSIL:
  3196. case VIEW_DISPLAY_DEBUG_PSSM_SPLITS:
  3197. case VIEW_DISPLAY_DEBUG_DECAL_ATLAS:
  3198. case VIEW_DISPLAY_DEBUG_SDFGI:
  3199. case VIEW_DISPLAY_DEBUG_SDFGI_PROBES:
  3200. case VIEW_DISPLAY_DEBUG_GI_BUFFER:
  3201. case VIEW_DISPLAY_DEBUG_DISABLE_LOD:
  3202. case VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS:
  3203. case VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS:
  3204. case VIEW_DISPLAY_DEBUG_CLUSTER_DECALS:
  3205. case VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES:
  3206. case VIEW_DISPLAY_DEBUG_OCCLUDERS:
  3207. case VIEW_DISPLAY_MOTION_VECTORS:
  3208. case VIEW_DISPLAY_INTERNAL_BUFFER: {
  3209. static const int display_options[] = {
  3210. VIEW_DISPLAY_NORMAL,
  3211. VIEW_DISPLAY_WIREFRAME,
  3212. VIEW_DISPLAY_OVERDRAW,
  3213. VIEW_DISPLAY_UNSHADED,
  3214. VIEW_DISPLAY_LIGHTING,
  3215. VIEW_DISPLAY_NORMAL_BUFFER,
  3216. VIEW_DISPLAY_DEBUG_SHADOW_ATLAS,
  3217. VIEW_DISPLAY_DEBUG_DIRECTIONAL_SHADOW_ATLAS,
  3218. VIEW_DISPLAY_DEBUG_VOXEL_GI_ALBEDO,
  3219. VIEW_DISPLAY_DEBUG_VOXEL_GI_LIGHTING,
  3220. VIEW_DISPLAY_DEBUG_VOXEL_GI_EMISSION,
  3221. VIEW_DISPLAY_DEBUG_SCENE_LUMINANCE,
  3222. VIEW_DISPLAY_DEBUG_SSAO,
  3223. VIEW_DISPLAY_DEBUG_SSIL,
  3224. VIEW_DISPLAY_DEBUG_GI_BUFFER,
  3225. VIEW_DISPLAY_DEBUG_DISABLE_LOD,
  3226. VIEW_DISPLAY_DEBUG_PSSM_SPLITS,
  3227. VIEW_DISPLAY_DEBUG_DECAL_ATLAS,
  3228. VIEW_DISPLAY_DEBUG_SDFGI,
  3229. VIEW_DISPLAY_DEBUG_SDFGI_PROBES,
  3230. VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS,
  3231. VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS,
  3232. VIEW_DISPLAY_DEBUG_CLUSTER_DECALS,
  3233. VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES,
  3234. VIEW_DISPLAY_DEBUG_OCCLUDERS,
  3235. VIEW_DISPLAY_MOTION_VECTORS,
  3236. VIEW_DISPLAY_INTERNAL_BUFFER,
  3237. VIEW_MAX
  3238. };
  3239. static const Viewport::DebugDraw debug_draw_modes[] = {
  3240. Viewport::DEBUG_DRAW_DISABLED,
  3241. Viewport::DEBUG_DRAW_WIREFRAME,
  3242. Viewport::DEBUG_DRAW_OVERDRAW,
  3243. Viewport::DEBUG_DRAW_UNSHADED,
  3244. Viewport::DEBUG_DRAW_LIGHTING,
  3245. Viewport::DEBUG_DRAW_NORMAL_BUFFER,
  3246. Viewport::DEBUG_DRAW_SHADOW_ATLAS,
  3247. Viewport::DEBUG_DRAW_DIRECTIONAL_SHADOW_ATLAS,
  3248. Viewport::DEBUG_DRAW_VOXEL_GI_ALBEDO,
  3249. Viewport::DEBUG_DRAW_VOXEL_GI_LIGHTING,
  3250. Viewport::DEBUG_DRAW_VOXEL_GI_EMISSION,
  3251. Viewport::DEBUG_DRAW_SCENE_LUMINANCE,
  3252. Viewport::DEBUG_DRAW_SSAO,
  3253. Viewport::DEBUG_DRAW_SSIL,
  3254. Viewport::DEBUG_DRAW_GI_BUFFER,
  3255. Viewport::DEBUG_DRAW_DISABLE_LOD,
  3256. Viewport::DEBUG_DRAW_PSSM_SPLITS,
  3257. Viewport::DEBUG_DRAW_DECAL_ATLAS,
  3258. Viewport::DEBUG_DRAW_SDFGI,
  3259. Viewport::DEBUG_DRAW_SDFGI_PROBES,
  3260. Viewport::DEBUG_DRAW_CLUSTER_OMNI_LIGHTS,
  3261. Viewport::DEBUG_DRAW_CLUSTER_SPOT_LIGHTS,
  3262. Viewport::DEBUG_DRAW_CLUSTER_DECALS,
  3263. Viewport::DEBUG_DRAW_CLUSTER_REFLECTION_PROBES,
  3264. Viewport::DEBUG_DRAW_OCCLUDERS,
  3265. Viewport::DEBUG_DRAW_MOTION_VECTORS,
  3266. Viewport::DEBUG_DRAW_INTERNAL_BUFFER,
  3267. };
  3268. for (int idx = 0; display_options[idx] != VIEW_MAX; idx++) {
  3269. int id = display_options[idx];
  3270. int item_idx = view_display_menu->get_popup()->get_item_index(id);
  3271. if (item_idx != -1) {
  3272. view_display_menu->get_popup()->set_item_checked(item_idx, id == p_option);
  3273. }
  3274. item_idx = display_submenu->get_item_index(id);
  3275. if (item_idx != -1) {
  3276. display_submenu->set_item_checked(item_idx, id == p_option);
  3277. }
  3278. if (id == p_option) {
  3279. viewport->set_debug_draw(debug_draw_modes[idx]);
  3280. }
  3281. }
  3282. } break;
  3283. }
  3284. }
  3285. void Node3DEditorViewport::_set_auto_orthogonal() {
  3286. if (!orthogonal && view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL))) {
  3287. _menu_option(VIEW_ORTHOGONAL);
  3288. auto_orthogonal = true;
  3289. }
  3290. }
  3291. void Node3DEditorViewport::_preview_exited_scene() {
  3292. preview_camera->disconnect(SceneStringName(toggled), callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
  3293. preview_camera->set_pressed(false);
  3294. _toggle_camera_preview(false);
  3295. preview_camera->connect(SceneStringName(toggled), callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
  3296. view_display_menu->show();
  3297. }
  3298. void Node3DEditorViewport::_init_gizmo_instance(int p_idx) {
  3299. uint32_t layer = 1 << (GIZMO_BASE_LAYER + p_idx);
  3300. for (int i = 0; i < 3; i++) {
  3301. move_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3302. RS::get_singleton()->instance_set_base(move_gizmo_instance[i], spatial_editor->get_move_gizmo(i)->get_rid());
  3303. RS::get_singleton()->instance_set_scenario(move_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3304. RS::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  3305. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3306. RS::get_singleton()->instance_set_layer_mask(move_gizmo_instance[i], layer);
  3307. RS::get_singleton()->instance_geometry_set_flag(move_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3308. RS::get_singleton()->instance_geometry_set_flag(move_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3309. move_plane_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3310. RS::get_singleton()->instance_set_base(move_plane_gizmo_instance[i], spatial_editor->get_move_plane_gizmo(i)->get_rid());
  3311. RS::get_singleton()->instance_set_scenario(move_plane_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3312. RS::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  3313. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_plane_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3314. RS::get_singleton()->instance_set_layer_mask(move_plane_gizmo_instance[i], layer);
  3315. RS::get_singleton()->instance_geometry_set_flag(move_plane_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3316. RS::get_singleton()->instance_geometry_set_flag(move_plane_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3317. rotate_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3318. RS::get_singleton()->instance_set_base(rotate_gizmo_instance[i], spatial_editor->get_rotate_gizmo(i)->get_rid());
  3319. RS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3320. RS::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  3321. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(rotate_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3322. RS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[i], layer);
  3323. RS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3324. RS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3325. scale_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3326. RS::get_singleton()->instance_set_base(scale_gizmo_instance[i], spatial_editor->get_scale_gizmo(i)->get_rid());
  3327. RS::get_singleton()->instance_set_scenario(scale_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3328. RS::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  3329. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3330. RS::get_singleton()->instance_set_layer_mask(scale_gizmo_instance[i], layer);
  3331. RS::get_singleton()->instance_geometry_set_flag(scale_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3332. RS::get_singleton()->instance_geometry_set_flag(scale_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3333. scale_plane_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3334. RS::get_singleton()->instance_set_base(scale_plane_gizmo_instance[i], spatial_editor->get_scale_plane_gizmo(i)->get_rid());
  3335. RS::get_singleton()->instance_set_scenario(scale_plane_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3336. RS::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  3337. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_plane_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3338. RS::get_singleton()->instance_set_layer_mask(scale_plane_gizmo_instance[i], layer);
  3339. RS::get_singleton()->instance_geometry_set_flag(scale_plane_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3340. RS::get_singleton()->instance_geometry_set_flag(scale_plane_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3341. axis_gizmo_instance[i] = RS::get_singleton()->instance_create();
  3342. RS::get_singleton()->instance_set_base(axis_gizmo_instance[i], spatial_editor->get_axis_gizmo(i)->get_rid());
  3343. RS::get_singleton()->instance_set_scenario(axis_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
  3344. RS::get_singleton()->instance_set_visible(axis_gizmo_instance[i], true);
  3345. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(axis_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
  3346. RS::get_singleton()->instance_set_layer_mask(axis_gizmo_instance[i], layer);
  3347. RS::get_singleton()->instance_geometry_set_flag(axis_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3348. RS::get_singleton()->instance_geometry_set_flag(axis_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3349. }
  3350. // Rotation white outline
  3351. rotate_gizmo_instance[3] = RS::get_singleton()->instance_create();
  3352. RS::get_singleton()->instance_set_base(rotate_gizmo_instance[3], spatial_editor->get_rotate_gizmo(3)->get_rid());
  3353. RS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[3], get_tree()->get_root()->get_world_3d()->get_scenario());
  3354. RS::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
  3355. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(rotate_gizmo_instance[3], RS::SHADOW_CASTING_SETTING_OFF);
  3356. RS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[3], layer);
  3357. RS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[3], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  3358. RS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[3], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  3359. }
  3360. void Node3DEditorViewport::_finish_gizmo_instances() {
  3361. ERR_FAIL_NULL(RenderingServer::get_singleton());
  3362. for (int i = 0; i < 3; i++) {
  3363. RS::get_singleton()->free(move_gizmo_instance[i]);
  3364. RS::get_singleton()->free(move_plane_gizmo_instance[i]);
  3365. RS::get_singleton()->free(rotate_gizmo_instance[i]);
  3366. RS::get_singleton()->free(scale_gizmo_instance[i]);
  3367. RS::get_singleton()->free(scale_plane_gizmo_instance[i]);
  3368. RS::get_singleton()->free(axis_gizmo_instance[i]);
  3369. }
  3370. // Rotation white outline
  3371. RS::get_singleton()->free(rotate_gizmo_instance[3]);
  3372. }
  3373. void Node3DEditorViewport::_toggle_camera_preview(bool p_activate) {
  3374. ERR_FAIL_COND(p_activate && !preview);
  3375. ERR_FAIL_COND(!p_activate && !previewing);
  3376. previewing_camera = p_activate;
  3377. _update_navigation_controls_visibility();
  3378. if (!p_activate) {
  3379. previewing->disconnect(SceneStringName(tree_exiting), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  3380. previewing = nullptr;
  3381. RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
  3382. if (!preview) {
  3383. preview_camera->hide();
  3384. }
  3385. surface->queue_redraw();
  3386. } else {
  3387. previewing = preview;
  3388. previewing->connect(SceneStringName(tree_exiting), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  3389. RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), preview->get_camera()); //replace
  3390. surface->queue_redraw();
  3391. }
  3392. }
  3393. void Node3DEditorViewport::_toggle_cinema_preview(bool p_activate) {
  3394. previewing_cinema = p_activate;
  3395. _update_navigation_controls_visibility();
  3396. if (!previewing_cinema) {
  3397. if (previewing != nullptr) {
  3398. previewing->disconnect(SceneStringName(tree_exited), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  3399. }
  3400. previewing = nullptr;
  3401. RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
  3402. preview_camera->set_pressed(false);
  3403. if (!preview) {
  3404. preview_camera->hide();
  3405. } else {
  3406. preview_camera->show();
  3407. }
  3408. view_display_menu->show();
  3409. surface->queue_redraw();
  3410. }
  3411. }
  3412. void Node3DEditorViewport::_selection_result_pressed(int p_result) {
  3413. if (selection_results_menu.size() <= p_result) {
  3414. return;
  3415. }
  3416. clicked = selection_results_menu[p_result]->get_instance_id();
  3417. if (clicked.is_valid()) {
  3418. _select_clicked(true);
  3419. }
  3420. selection_results_menu.clear();
  3421. }
  3422. void Node3DEditorViewport::_selection_menu_hide() {
  3423. selection_results.clear();
  3424. selection_menu->clear();
  3425. selection_menu->reset_size();
  3426. }
  3427. void Node3DEditorViewport::set_can_preview(Camera3D *p_preview) {
  3428. preview = p_preview;
  3429. if (!preview_camera->is_pressed() && !previewing_cinema) {
  3430. preview_camera->set_visible(p_preview);
  3431. }
  3432. }
  3433. void Node3DEditorViewport::update_transform_gizmo_view() {
  3434. if (!is_visible_in_tree()) {
  3435. return;
  3436. }
  3437. Transform3D xform = spatial_editor->get_gizmo_transform();
  3438. Transform3D camera_xform = camera->get_transform();
  3439. if (xform.origin.is_equal_approx(camera_xform.origin)) {
  3440. for (int i = 0; i < 3; i++) {
  3441. RenderingServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  3442. RenderingServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  3443. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  3444. RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  3445. RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  3446. RenderingServer::get_singleton()->instance_set_visible(axis_gizmo_instance[i], false);
  3447. }
  3448. // Rotation white outline
  3449. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
  3450. return;
  3451. }
  3452. const Vector3 camz = -camera_xform.get_basis().get_column(2).normalized();
  3453. const Vector3 camy = -camera_xform.get_basis().get_column(1).normalized();
  3454. const Plane p = Plane(camz, camera_xform.origin);
  3455. const real_t gizmo_d = MAX(Math::abs(p.distance_to(xform.origin)), CMP_EPSILON);
  3456. const real_t d0 = camera->unproject_position(camera_xform.origin + camz * gizmo_d).y;
  3457. const real_t d1 = camera->unproject_position(camera_xform.origin + camz * gizmo_d + camy).y;
  3458. const real_t dd = MAX(Math::abs(d0 - d1), CMP_EPSILON);
  3459. const real_t gizmo_size = EDITOR_GET("editors/3d/manipulator_gizmo_size");
  3460. // At low viewport heights, multiply the gizmo scale based on the viewport height.
  3461. // This prevents the gizmo from growing very large and going outside the viewport.
  3462. const int viewport_base_height = 400 * MAX(1, EDSCALE);
  3463. gizmo_scale =
  3464. (gizmo_size / Math::abs(dd)) * MAX(1, EDSCALE) *
  3465. MIN(viewport_base_height, subviewport_container->get_size().height) / viewport_base_height /
  3466. subviewport_container->get_stretch_shrink();
  3467. Vector3 scale = Vector3(1, 1, 1) * gizmo_scale;
  3468. // if the determinant is zero, we should disable the gizmo from being rendered
  3469. // this prevents supplying bad values to the renderer and then having to filter it out again
  3470. if (xform.basis.determinant() == 0) {
  3471. for (int i = 0; i < 3; i++) {
  3472. RenderingServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
  3473. RenderingServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
  3474. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
  3475. RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
  3476. RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
  3477. }
  3478. // Rotation white outline
  3479. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
  3480. return;
  3481. }
  3482. bool show_gizmo = spatial_editor->is_gizmo_visible() && !_edit.instant && transform_gizmo_visible && !collision_reposition;
  3483. for (int i = 0; i < 3; i++) {
  3484. Transform3D axis_angle;
  3485. if (xform.basis.get_column(i).normalized().dot(xform.basis.get_column((i + 1) % 3).normalized()) < 1.0) {
  3486. axis_angle = axis_angle.looking_at(xform.basis.get_column(i).normalized(), xform.basis.get_column((i + 1) % 3).normalized());
  3487. }
  3488. axis_angle.basis.scale(scale);
  3489. axis_angle.origin = xform.origin;
  3490. RenderingServer::get_singleton()->instance_set_transform(move_gizmo_instance[i], axis_angle);
  3491. RenderingServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE));
  3492. RenderingServer::get_singleton()->instance_set_transform(move_plane_gizmo_instance[i], axis_angle);
  3493. RenderingServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE));
  3494. RenderingServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[i], axis_angle);
  3495. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE));
  3496. RenderingServer::get_singleton()->instance_set_transform(scale_gizmo_instance[i], axis_angle);
  3497. RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE));
  3498. RenderingServer::get_singleton()->instance_set_transform(scale_plane_gizmo_instance[i], axis_angle);
  3499. RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE));
  3500. RenderingServer::get_singleton()->instance_set_transform(axis_gizmo_instance[i], xform);
  3501. }
  3502. bool show_axes = spatial_editor->is_gizmo_visible() && _edit.mode != TRANSFORM_NONE;
  3503. RenderingServer *rs = RenderingServer::get_singleton();
  3504. rs->instance_set_visible(axis_gizmo_instance[0], show_axes && (_edit.plane == TRANSFORM_X_AXIS || _edit.plane == TRANSFORM_XY || _edit.plane == TRANSFORM_XZ));
  3505. rs->instance_set_visible(axis_gizmo_instance[1], show_axes && (_edit.plane == TRANSFORM_Y_AXIS || _edit.plane == TRANSFORM_XY || _edit.plane == TRANSFORM_YZ));
  3506. rs->instance_set_visible(axis_gizmo_instance[2], show_axes && (_edit.plane == TRANSFORM_Z_AXIS || _edit.plane == TRANSFORM_XZ || _edit.plane == TRANSFORM_YZ));
  3507. // Rotation white outline
  3508. xform.orthonormalize();
  3509. xform.basis.scale(scale);
  3510. RenderingServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[3], xform);
  3511. RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], spatial_editor->is_gizmo_visible() && !_edit.instant && transform_gizmo_visible && !collision_reposition && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE));
  3512. }
  3513. void Node3DEditorViewport::set_state(const Dictionary &p_state) {
  3514. if (p_state.has("position")) {
  3515. cursor.pos = p_state["position"];
  3516. }
  3517. if (p_state.has("x_rotation")) {
  3518. cursor.x_rot = p_state["x_rotation"];
  3519. }
  3520. if (p_state.has("y_rotation")) {
  3521. cursor.y_rot = p_state["y_rotation"];
  3522. }
  3523. if (p_state.has("distance")) {
  3524. cursor.distance = p_state["distance"];
  3525. }
  3526. if (p_state.has("orthogonal")) {
  3527. bool orth = p_state["orthogonal"];
  3528. _menu_option(orth ? VIEW_ORTHOGONAL : VIEW_PERSPECTIVE);
  3529. }
  3530. if (p_state.has("view_type")) {
  3531. view_type = ViewType(p_state["view_type"].operator int());
  3532. _update_name();
  3533. }
  3534. if (p_state.has("auto_orthogonal")) {
  3535. auto_orthogonal = p_state["auto_orthogonal"];
  3536. _update_name();
  3537. }
  3538. if (p_state.has("auto_orthogonal_enabled")) {
  3539. bool enabled = p_state["auto_orthogonal_enabled"];
  3540. view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL), enabled);
  3541. }
  3542. if (p_state.has("display_mode")) {
  3543. int display = p_state["display_mode"];
  3544. int idx = view_display_menu->get_popup()->get_item_index(display);
  3545. if (idx != -1 && !view_display_menu->get_popup()->is_item_checked(idx)) {
  3546. _menu_option(display);
  3547. } else {
  3548. idx = display_submenu->get_item_index(display);
  3549. if (idx != -1 && !display_submenu->is_item_checked(idx)) {
  3550. _menu_option(display);
  3551. }
  3552. }
  3553. }
  3554. if (p_state.has("lock_rotation")) {
  3555. _set_lock_view_rotation(p_state["lock_rotation"]);
  3556. }
  3557. if (p_state.has("use_environment")) {
  3558. bool env = p_state["use_environment"];
  3559. if (env != camera->get_environment().is_valid()) {
  3560. _menu_option(VIEW_ENVIRONMENT);
  3561. }
  3562. }
  3563. if (p_state.has("listener")) {
  3564. bool listener = p_state["listener"];
  3565. int idx = view_display_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
  3566. viewport->set_as_audio_listener_3d(listener);
  3567. view_display_menu->get_popup()->set_item_checked(idx, listener);
  3568. }
  3569. if (p_state.has("doppler")) {
  3570. bool doppler = p_state["doppler"];
  3571. int idx = view_display_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
  3572. camera->set_doppler_tracking(doppler ? Camera3D::DOPPLER_TRACKING_IDLE_STEP : Camera3D::DOPPLER_TRACKING_DISABLED);
  3573. view_display_menu->get_popup()->set_item_checked(idx, doppler);
  3574. }
  3575. if (p_state.has("gizmos")) {
  3576. bool gizmos = p_state["gizmos"];
  3577. int idx = view_display_menu->get_popup()->get_item_index(VIEW_GIZMOS);
  3578. if (view_display_menu->get_popup()->is_item_checked(idx) != gizmos) {
  3579. _menu_option(VIEW_GIZMOS);
  3580. }
  3581. }
  3582. if (p_state.has("transform_gizmo")) {
  3583. bool transform_gizmo = p_state["transform_gizmo"];
  3584. int idx = view_display_menu->get_popup()->get_item_index(VIEW_TRANSFORM_GIZMO);
  3585. if (view_display_menu->get_popup()->is_item_checked(idx) != transform_gizmo) {
  3586. _menu_option(VIEW_TRANSFORM_GIZMO);
  3587. }
  3588. }
  3589. if (p_state.has("grid")) {
  3590. bool grid = p_state["grid"];
  3591. int idx = view_display_menu->get_popup()->get_item_index(VIEW_GRID);
  3592. if (view_display_menu->get_popup()->is_item_checked(idx) != grid) {
  3593. _menu_option(VIEW_GRID);
  3594. }
  3595. }
  3596. if (p_state.has("information")) {
  3597. bool information = p_state["information"];
  3598. int idx = view_display_menu->get_popup()->get_item_index(VIEW_INFORMATION);
  3599. if (view_display_menu->get_popup()->is_item_checked(idx) != information) {
  3600. _menu_option(VIEW_INFORMATION);
  3601. }
  3602. }
  3603. if (p_state.has("frame_time")) {
  3604. bool fps = p_state["frame_time"];
  3605. int idx = view_display_menu->get_popup()->get_item_index(VIEW_FRAME_TIME);
  3606. if (view_display_menu->get_popup()->is_item_checked(idx) != fps) {
  3607. _menu_option(VIEW_FRAME_TIME);
  3608. }
  3609. }
  3610. if (p_state.has("half_res")) {
  3611. bool half_res = p_state["half_res"];
  3612. int idx = view_display_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
  3613. view_display_menu->get_popup()->set_item_checked(idx, half_res);
  3614. _update_shrink();
  3615. }
  3616. if (p_state.has("cinematic_preview")) {
  3617. previewing_cinema = p_state["cinematic_preview"];
  3618. int idx = view_display_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
  3619. view_display_menu->get_popup()->set_item_checked(idx, previewing_cinema);
  3620. }
  3621. if (preview_camera->is_connected(SceneStringName(toggled), callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview))) {
  3622. preview_camera->disconnect(SceneStringName(toggled), callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
  3623. }
  3624. if (p_state.has("previewing")) {
  3625. Node *pv = EditorNode::get_singleton()->get_edited_scene()->get_node(p_state["previewing"]);
  3626. if (Object::cast_to<Camera3D>(pv)) {
  3627. previewing = Object::cast_to<Camera3D>(pv);
  3628. previewing->connect(SceneStringName(tree_exiting), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
  3629. RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), previewing->get_camera()); //replace
  3630. surface->queue_redraw();
  3631. previewing_camera = true;
  3632. preview_camera->set_pressed(true);
  3633. preview_camera->show();
  3634. }
  3635. }
  3636. preview_camera->connect(SceneStringName(toggled), callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
  3637. }
  3638. Dictionary Node3DEditorViewport::get_state() const {
  3639. Dictionary d;
  3640. d["position"] = cursor.pos;
  3641. d["x_rotation"] = cursor.x_rot;
  3642. d["y_rotation"] = cursor.y_rot;
  3643. d["distance"] = cursor.distance;
  3644. d["use_environment"] = camera->get_environment().is_valid();
  3645. d["orthogonal"] = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
  3646. d["view_type"] = view_type;
  3647. d["auto_orthogonal"] = auto_orthogonal;
  3648. d["auto_orthogonal_enabled"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL));
  3649. // Find selected display mode.
  3650. int display_mode = VIEW_DISPLAY_NORMAL;
  3651. for (int i = VIEW_DISPLAY_NORMAL; i < VIEW_DISPLAY_ADVANCED; i++) {
  3652. if (view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(i))) {
  3653. display_mode = i;
  3654. break;
  3655. }
  3656. }
  3657. for (int i = VIEW_DISPLAY_ADVANCED + 1; i < VIEW_DISPLAY_MAX; i++) {
  3658. if (display_submenu->is_item_checked(display_submenu->get_item_index(i))) {
  3659. display_mode = i;
  3660. break;
  3661. }
  3662. }
  3663. d["display_mode"] = display_mode;
  3664. d["listener"] = viewport->is_audio_listener_3d();
  3665. d["doppler"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER));
  3666. d["gizmos"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_GIZMOS));
  3667. d["transform_gizmo"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_TRANSFORM_GIZMO));
  3668. d["grid"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_GRID));
  3669. d["information"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_INFORMATION));
  3670. d["frame_time"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_FRAME_TIME));
  3671. d["half_res"] = subviewport_container->get_stretch_shrink() > 1;
  3672. d["cinematic_preview"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW));
  3673. if (previewing) {
  3674. d["previewing"] = EditorNode::get_singleton()->get_edited_scene()->get_path_to(previewing);
  3675. }
  3676. d["lock_rotation"] = lock_rotation;
  3677. return d;
  3678. }
  3679. void Node3DEditorViewport::_bind_methods() {
  3680. ADD_SIGNAL(MethodInfo("toggle_maximize_view", PropertyInfo(Variant::OBJECT, "viewport")));
  3681. ADD_SIGNAL(MethodInfo("clicked"));
  3682. }
  3683. void Node3DEditorViewport::reset() {
  3684. orthogonal = false;
  3685. auto_orthogonal = false;
  3686. lock_rotation = false;
  3687. message_time = 0;
  3688. message = "";
  3689. last_message = "";
  3690. view_type = VIEW_TYPE_USER;
  3691. cursor = Cursor();
  3692. _update_name();
  3693. }
  3694. void Node3DEditorViewport::focus_selection() {
  3695. Vector3 center;
  3696. int count = 0;
  3697. const List<Node *> &selection = editor_selection->get_selected_node_list();
  3698. for (Node *E : selection) {
  3699. Node3D *sp = Object::cast_to<Node3D>(E);
  3700. if (!sp) {
  3701. continue;
  3702. }
  3703. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  3704. if (!se) {
  3705. continue;
  3706. }
  3707. if (se->gizmo.is_valid()) {
  3708. for (const KeyValue<int, Transform3D> &GE : se->subgizmos) {
  3709. center += se->gizmo->get_subgizmo_transform(GE.key).origin;
  3710. count++;
  3711. }
  3712. }
  3713. center += sp->get_global_gizmo_transform().origin;
  3714. count++;
  3715. }
  3716. if (count != 0) {
  3717. center /= count;
  3718. }
  3719. cursor.pos = center;
  3720. }
  3721. void Node3DEditorViewport::assign_pending_data_pointers(Node3D *p_preview_node, AABB *p_preview_bounds, AcceptDialog *p_accept) {
  3722. preview_node = p_preview_node;
  3723. preview_bounds = p_preview_bounds;
  3724. accept = p_accept;
  3725. }
  3726. void _insert_rid_recursive(Node *node, HashSet<RID> &rids) {
  3727. CollisionObject3D *co = Object::cast_to<CollisionObject3D>(node);
  3728. if (co) {
  3729. rids.insert(co->get_rid());
  3730. } else if (node->is_class("CSGShape3D")) { // HACK: We should avoid referencing module logic.
  3731. rids.insert(node->call("_get_root_collision_instance"));
  3732. }
  3733. for (int i = 0; i < node->get_child_count(); i++) {
  3734. Node *child = node->get_child(i);
  3735. _insert_rid_recursive(child, rids);
  3736. }
  3737. }
  3738. Vector3 Node3DEditorViewport::_get_instance_position(const Point2 &p_pos, Node3D *p_node) const {
  3739. const float MAX_DISTANCE = 50.0;
  3740. const float FALLBACK_DISTANCE = 5.0;
  3741. Vector3 world_ray = get_ray(p_pos);
  3742. Vector3 world_pos = get_ray_pos(p_pos);
  3743. PhysicsDirectSpaceState3D *ss = get_tree()->get_root()->get_world_3d()->get_direct_space_state();
  3744. HashSet<RID> rids;
  3745. if (!preview_node->is_inside_tree() && !ruler->is_inside_tree()) {
  3746. List<Node *> &selection = editor_selection->get_selected_node_list();
  3747. Node3D *first_selected_node = Object::cast_to<Node3D>(selection.front()->get());
  3748. Array children = first_selected_node->get_children();
  3749. if (first_selected_node) {
  3750. _insert_rid_recursive(first_selected_node, rids);
  3751. }
  3752. }
  3753. PhysicsDirectSpaceState3D::RayParameters ray_params;
  3754. ray_params.exclude = rids;
  3755. ray_params.from = world_pos;
  3756. ray_params.to = world_pos + world_ray * camera->get_far();
  3757. PhysicsDirectSpaceState3D::RayResult result;
  3758. if (ss->intersect_ray(ray_params, result) && (preview_node->get_child_count() > 0 || !preview_node->is_inside_tree())) {
  3759. // Calculate an offset for the `p_node` such that the its bounding box is on top of and touching the contact surface's plane.
  3760. // Use the Gram-Schmidt process to get an orthonormal Basis aligned with the surface normal.
  3761. const Vector3 bb_basis_x = result.normal;
  3762. Vector3 bb_basis_y = Vector3(0, 1, 0);
  3763. bb_basis_y = bb_basis_y - bb_basis_y.project(bb_basis_x);
  3764. if (bb_basis_y.is_zero_approx()) {
  3765. bb_basis_y = Vector3(0, 0, 1);
  3766. bb_basis_y = bb_basis_y - bb_basis_y.project(bb_basis_x);
  3767. }
  3768. bb_basis_y = bb_basis_y.normalized();
  3769. const Vector3 bb_basis_z = bb_basis_x.cross(bb_basis_y);
  3770. const Basis bb_basis = Basis(bb_basis_x, bb_basis_y, bb_basis_z);
  3771. // This normal-aligned Basis allows us to create an AABB that can fit on the surface plane as snugly as possible.
  3772. const Transform3D bb_transform = Transform3D(bb_basis, p_node->get_transform().origin);
  3773. const AABB p_node_bb = _calculate_spatial_bounds(p_node, true, &bb_transform);
  3774. // The x-axis's alignment with the surface normal also makes it trivial to get the distance from `p_node`'s origin at (0, 0, 0) to the correct AABB face.
  3775. const float offset_distance = -p_node_bb.position.x;
  3776. // `result_offset` is in global space.
  3777. const Vector3 result_offset = result.position + result.normal * offset_distance;
  3778. return result_offset;
  3779. }
  3780. const bool is_orthogonal = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
  3781. // The XZ plane.
  3782. Vector3 intersection;
  3783. Plane plane(Vector3(0, 1, 0));
  3784. if (plane.intersects_ray(world_pos, world_ray, &intersection)) {
  3785. if (is_orthogonal || world_pos.distance_to(intersection) <= MAX_DISTANCE) {
  3786. return intersection;
  3787. }
  3788. }
  3789. // Plane facing the camera using fallback distance.
  3790. if (is_orthogonal) {
  3791. plane = Plane(world_ray, cursor.pos - world_ray * (cursor.distance - FALLBACK_DISTANCE));
  3792. } else {
  3793. plane = Plane(world_ray, world_pos + world_ray * FALLBACK_DISTANCE);
  3794. }
  3795. if (plane.intersects_ray(world_pos, world_ray, &intersection)) {
  3796. return intersection;
  3797. }
  3798. // Not likely, but just in case...
  3799. return world_pos + world_ray * FALLBACK_DISTANCE;
  3800. }
  3801. AABB Node3DEditorViewport::_calculate_spatial_bounds(const Node3D *p_parent, bool p_omit_top_level, const Transform3D *p_bounds_orientation) {
  3802. AABB bounds;
  3803. Transform3D bounds_orientation;
  3804. if (p_bounds_orientation) {
  3805. bounds_orientation = *p_bounds_orientation;
  3806. } else {
  3807. bounds_orientation = p_parent->get_global_transform();
  3808. }
  3809. if (!p_parent) {
  3810. return AABB(Vector3(-0.2, -0.2, -0.2), Vector3(0.4, 0.4, 0.4));
  3811. }
  3812. const Transform3D xform_to_top_level_parent_space = bounds_orientation.affine_inverse() * p_parent->get_global_transform();
  3813. const VisualInstance3D *visual_instance = Object::cast_to<VisualInstance3D>(p_parent);
  3814. if (visual_instance) {
  3815. bounds = visual_instance->get_aabb();
  3816. } else {
  3817. bounds = AABB();
  3818. }
  3819. bounds = xform_to_top_level_parent_space.xform(bounds);
  3820. for (int i = 0; i < p_parent->get_child_count(); i++) {
  3821. const Node3D *child = Object::cast_to<Node3D>(p_parent->get_child(i));
  3822. if (child && !(p_omit_top_level && child->is_set_as_top_level())) {
  3823. const AABB child_bounds = _calculate_spatial_bounds(child, p_omit_top_level, &bounds_orientation);
  3824. bounds.merge_with(child_bounds);
  3825. }
  3826. }
  3827. return bounds;
  3828. }
  3829. Node *Node3DEditorViewport::_sanitize_preview_node(Node *p_node) const {
  3830. Node3D *node_3d = Object::cast_to<Node3D>(p_node);
  3831. if (node_3d == nullptr) {
  3832. Node3D *replacement_node = memnew(Node3D);
  3833. replacement_node->set_name(p_node->get_name());
  3834. p_node->replace_by(replacement_node);
  3835. memdelete(p_node);
  3836. p_node = replacement_node;
  3837. } else {
  3838. VisualInstance3D *visual_instance = Object::cast_to<VisualInstance3D>(node_3d);
  3839. if (visual_instance == nullptr) {
  3840. Node3D *replacement_node = memnew(Node3D);
  3841. replacement_node->set_name(node_3d->get_name());
  3842. replacement_node->set_visible(node_3d->is_visible());
  3843. replacement_node->set_transform(node_3d->get_transform());
  3844. replacement_node->set_rotation_edit_mode(node_3d->get_rotation_edit_mode());
  3845. replacement_node->set_rotation_order(node_3d->get_rotation_order());
  3846. replacement_node->set_as_top_level(node_3d->is_set_as_top_level());
  3847. p_node->replace_by(replacement_node);
  3848. memdelete(p_node);
  3849. p_node = replacement_node;
  3850. }
  3851. }
  3852. for (int i = 0; i < p_node->get_child_count(); i++) {
  3853. _sanitize_preview_node(p_node->get_child(i));
  3854. }
  3855. return p_node;
  3856. }
  3857. void Node3DEditorViewport::_create_preview_node(const Vector<String> &files) const {
  3858. bool add_preview = false;
  3859. for (const String &path : files) {
  3860. Ref<Resource> res = ResourceLoader::load(path);
  3861. ERR_CONTINUE(res.is_null());
  3862. Ref<PackedScene> scene = res;
  3863. if (scene.is_valid()) {
  3864. Node *instance = scene->instantiate();
  3865. if (instance) {
  3866. instance = _sanitize_preview_node(instance);
  3867. preview_node->add_child(instance);
  3868. Node3D *node_3d = Object::cast_to<Node3D>(instance);
  3869. if (node_3d) {
  3870. node_3d->set_as_top_level(false);
  3871. }
  3872. }
  3873. add_preview = true;
  3874. }
  3875. Ref<Mesh> mesh = res;
  3876. if (mesh.is_valid()) {
  3877. MeshInstance3D *mesh_instance = memnew(MeshInstance3D);
  3878. mesh_instance->set_mesh(mesh);
  3879. preview_node->add_child(mesh_instance);
  3880. add_preview = true;
  3881. }
  3882. Ref<AudioStream> audio = res;
  3883. if (audio.is_valid()) {
  3884. Sprite3D *sprite = memnew(Sprite3D);
  3885. sprite->set_texture(get_editor_theme_icon(SNAME("Gizmo3DSamplePlayer")));
  3886. sprite->set_billboard_mode(StandardMaterial3D::BILLBOARD_ENABLED);
  3887. sprite->set_pixel_size(0.005);
  3888. preview_node->add_child(sprite);
  3889. add_preview = true;
  3890. }
  3891. }
  3892. if (add_preview) {
  3893. EditorNode::get_singleton()->get_scene_root()->add_child(preview_node);
  3894. }
  3895. *preview_bounds = _calculate_spatial_bounds(preview_node);
  3896. }
  3897. void Node3DEditorViewport::_remove_preview_node() {
  3898. set_message("");
  3899. if (preview_node->get_parent()) {
  3900. for (int i = preview_node->get_child_count() - 1; i >= 0; i--) {
  3901. Node *node = preview_node->get_child(i);
  3902. node->queue_free();
  3903. preview_node->remove_child(node);
  3904. }
  3905. EditorNode::get_singleton()->get_scene_root()->remove_child(preview_node);
  3906. }
  3907. }
  3908. bool Node3DEditorViewport::_apply_preview_material(ObjectID p_target, const Point2 &p_point) const {
  3909. _reset_preview_material();
  3910. if (p_target.is_null()) {
  3911. return false;
  3912. }
  3913. spatial_editor->set_preview_material_target(p_target);
  3914. Object *target_inst = ObjectDB::get_instance(p_target);
  3915. bool is_ctrl = Input::get_singleton()->is_key_pressed(Key::CTRL);
  3916. MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(target_inst);
  3917. if (is_ctrl && mesh_instance) {
  3918. Ref<Mesh> mesh = mesh_instance->get_mesh();
  3919. int surface_count = mesh->get_surface_count();
  3920. Vector3 world_ray = get_ray(p_point);
  3921. Vector3 world_pos = get_ray_pos(p_point);
  3922. int closest_surface = -1;
  3923. float closest_dist = 1e20;
  3924. Transform3D gt = mesh_instance->get_global_transform();
  3925. Transform3D ai = gt.affine_inverse();
  3926. Vector3 xform_ray = ai.basis.xform(world_ray).normalized();
  3927. Vector3 xform_pos = ai.xform(world_pos);
  3928. for (int surface_idx = 0; surface_idx < surface_count; surface_idx++) {
  3929. Ref<TriangleMesh> surface_mesh = mesh->generate_surface_triangle_mesh(surface_idx);
  3930. Vector3 rpos, rnorm;
  3931. if (surface_mesh->intersect_ray(xform_pos, xform_ray, rpos, rnorm)) {
  3932. Vector3 hitpos = gt.xform(rpos);
  3933. const real_t dist = world_pos.distance_to(hitpos);
  3934. if (dist < 0) {
  3935. continue;
  3936. }
  3937. if (dist < closest_dist) {
  3938. closest_surface = surface_idx;
  3939. closest_dist = dist;
  3940. }
  3941. }
  3942. }
  3943. if (closest_surface == -1) {
  3944. return false;
  3945. }
  3946. spatial_editor->set_preview_material_surface(closest_surface);
  3947. spatial_editor->set_preview_reset_material(mesh_instance->get_surface_override_material(closest_surface));
  3948. mesh_instance->set_surface_override_material(closest_surface, spatial_editor->get_preview_material());
  3949. return true;
  3950. }
  3951. GeometryInstance3D *geometry_instance = Object::cast_to<GeometryInstance3D>(target_inst);
  3952. if (geometry_instance) {
  3953. spatial_editor->set_preview_material_surface(-1);
  3954. spatial_editor->set_preview_reset_material(geometry_instance->get_material_override());
  3955. geometry_instance->set_material_override(spatial_editor->get_preview_material());
  3956. return true;
  3957. }
  3958. return false;
  3959. }
  3960. void Node3DEditorViewport::_reset_preview_material() const {
  3961. ObjectID last_target = spatial_editor->get_preview_material_target();
  3962. if (last_target.is_null()) {
  3963. return;
  3964. }
  3965. Object *last_target_inst = ObjectDB::get_instance(last_target);
  3966. MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(last_target_inst);
  3967. GeometryInstance3D *geometry_instance = Object::cast_to<GeometryInstance3D>(last_target_inst);
  3968. if (mesh_instance && spatial_editor->get_preview_material_surface() != -1) {
  3969. mesh_instance->set_surface_override_material(spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_reset_material());
  3970. } else if (geometry_instance) {
  3971. geometry_instance->set_material_override(spatial_editor->get_preview_reset_material());
  3972. }
  3973. }
  3974. void Node3DEditorViewport::_remove_preview_material() {
  3975. preview_material_label->hide();
  3976. preview_material_label_desc->hide();
  3977. spatial_editor->set_preview_material(Ref<Material>());
  3978. spatial_editor->set_preview_reset_material(Ref<Material>());
  3979. spatial_editor->set_preview_material_target(ObjectID());
  3980. spatial_editor->set_preview_material_surface(-1);
  3981. }
  3982. bool Node3DEditorViewport::_cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node) const {
  3983. if (p_desired_node->get_scene_file_path() == p_target_scene_path) {
  3984. return true;
  3985. }
  3986. int childCount = p_desired_node->get_child_count();
  3987. for (int i = 0; i < childCount; i++) {
  3988. Node *child = p_desired_node->get_child(i);
  3989. if (_cyclical_dependency_exists(p_target_scene_path, child)) {
  3990. return true;
  3991. }
  3992. }
  3993. return false;
  3994. }
  3995. bool Node3DEditorViewport::_create_instance(Node *p_parent, const String &p_path, const Point2 &p_point) {
  3996. Ref<Resource> res = ResourceLoader::load(p_path);
  3997. ERR_FAIL_COND_V(res.is_null(), false);
  3998. Ref<PackedScene> scene = res;
  3999. Ref<Mesh> mesh = res;
  4000. Node *instantiated_scene = nullptr;
  4001. if (mesh.is_valid() || scene.is_valid()) {
  4002. if (mesh.is_valid()) {
  4003. MeshInstance3D *mesh_instance = memnew(MeshInstance3D);
  4004. mesh_instance->set_mesh(mesh);
  4005. // Adjust casing according to project setting. The file name is expected to be in snake_case, but will work for others.
  4006. const String &node_name = Node::adjust_name_casing(p_path.get_file().get_basename());
  4007. if (!node_name.is_empty()) {
  4008. mesh_instance->set_name(node_name);
  4009. }
  4010. instantiated_scene = mesh_instance;
  4011. } else {
  4012. if (scene.is_null()) { // invalid scene
  4013. return false;
  4014. } else {
  4015. instantiated_scene = scene->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
  4016. }
  4017. }
  4018. }
  4019. if (instantiated_scene == nullptr) {
  4020. return false;
  4021. }
  4022. if (!EditorNode::get_singleton()->get_edited_scene()->get_scene_file_path().is_empty()) { // Cyclic instantiation.
  4023. if (_cyclical_dependency_exists(EditorNode::get_singleton()->get_edited_scene()->get_scene_file_path(), instantiated_scene)) {
  4024. memdelete(instantiated_scene);
  4025. return false;
  4026. }
  4027. }
  4028. if (scene.is_valid()) {
  4029. instantiated_scene->set_scene_file_path(ProjectSettings::get_singleton()->localize_path(p_path));
  4030. }
  4031. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  4032. undo_redo->add_do_method(p_parent, "add_child", instantiated_scene, true);
  4033. undo_redo->add_do_method(instantiated_scene, "set_owner", EditorNode::get_singleton()->get_edited_scene());
  4034. undo_redo->add_do_reference(instantiated_scene);
  4035. undo_redo->add_undo_method(p_parent, "remove_child", instantiated_scene);
  4036. undo_redo->add_do_method(editor_selection, "add_node", instantiated_scene);
  4037. String new_name = p_parent->validate_child_name(instantiated_scene);
  4038. EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
  4039. undo_redo->add_do_method(ed, "live_debug_instantiate_node", EditorNode::get_singleton()->get_edited_scene()->get_path_to(p_parent), p_path, new_name);
  4040. undo_redo->add_undo_method(ed, "live_debug_remove_node", NodePath(String(EditorNode::get_singleton()->get_edited_scene()->get_path_to(p_parent)) + "/" + new_name));
  4041. Node3D *node3d = Object::cast_to<Node3D>(instantiated_scene);
  4042. if (node3d) {
  4043. Transform3D parent_tf;
  4044. Node3D *parent_node3d = Object::cast_to<Node3D>(p_parent);
  4045. if (parent_node3d) {
  4046. parent_tf = parent_node3d->get_global_gizmo_transform();
  4047. }
  4048. Transform3D new_tf = node3d->get_transform();
  4049. if (node3d->is_set_as_top_level()) {
  4050. new_tf.origin += preview_node_pos;
  4051. } else {
  4052. new_tf.origin = parent_tf.affine_inverse().xform(preview_node_pos + node3d->get_position());
  4053. new_tf.basis = parent_tf.affine_inverse().basis * new_tf.basis;
  4054. }
  4055. undo_redo->add_do_method(instantiated_scene, "set_transform", new_tf);
  4056. }
  4057. return true;
  4058. }
  4059. bool Node3DEditorViewport::_create_audio_node(Node *p_parent, const String &p_path, const Point2 &p_point) {
  4060. Ref<AudioStream> audio = ResourceLoader::load(p_path);
  4061. ERR_FAIL_COND_V(audio.is_null(), false);
  4062. AudioStreamPlayer3D *audio_player = memnew(AudioStreamPlayer3D);
  4063. audio_player->set_stream(audio);
  4064. // Adjust casing according to project setting. The file name is expected to be in snake_case, but will work for others.
  4065. const String &node_name = Node::adjust_name_casing(p_path.get_file().get_basename());
  4066. if (!node_name.is_empty()) {
  4067. audio_player->set_name(node_name);
  4068. }
  4069. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  4070. undo_redo->add_do_method(p_parent, "add_child", audio_player, true);
  4071. undo_redo->add_do_method(audio_player, "set_owner", EditorNode::get_singleton()->get_edited_scene());
  4072. undo_redo->add_do_reference(audio_player);
  4073. undo_redo->add_undo_method(p_parent, "remove_child", audio_player);
  4074. undo_redo->add_do_method(editor_selection, "add_node", audio_player);
  4075. const String new_name = p_parent->validate_child_name(audio_player);
  4076. EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
  4077. undo_redo->add_do_method(ed, "live_debug_create_node", EditorNode::get_singleton()->get_edited_scene()->get_path_to(p_parent), audio_player->get_class(), new_name);
  4078. undo_redo->add_undo_method(ed, "live_debug_remove_node", NodePath(String(EditorNode::get_singleton()->get_edited_scene()->get_path_to(p_parent)) + "/" + new_name));
  4079. Transform3D parent_tf;
  4080. Node3D *parent_node3d = Object::cast_to<Node3D>(p_parent);
  4081. if (parent_node3d) {
  4082. parent_tf = parent_node3d->get_global_gizmo_transform();
  4083. }
  4084. Transform3D new_tf = audio_player->get_transform();
  4085. new_tf.origin = parent_tf.affine_inverse().xform(preview_node_pos + audio_player->get_position());
  4086. new_tf.basis = parent_tf.affine_inverse().basis * new_tf.basis;
  4087. undo_redo->add_do_method(audio_player, "set_transform", new_tf);
  4088. return true;
  4089. }
  4090. void Node3DEditorViewport::_perform_drop_data() {
  4091. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  4092. if (spatial_editor->get_preview_material_target().is_valid()) {
  4093. GeometryInstance3D *geometry_instance = Object::cast_to<GeometryInstance3D>(ObjectDB::get_instance(spatial_editor->get_preview_material_target()));
  4094. MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(ObjectDB::get_instance(spatial_editor->get_preview_material_target()));
  4095. if (mesh_instance && spatial_editor->get_preview_material_surface() != -1) {
  4096. undo_redo->create_action(vformat(TTR("Set Surface %d Override Material"), spatial_editor->get_preview_material_surface()));
  4097. undo_redo->add_do_method(geometry_instance, "set_surface_override_material", spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_material());
  4098. undo_redo->add_undo_method(geometry_instance, "set_surface_override_material", spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_reset_material());
  4099. undo_redo->commit_action();
  4100. } else if (geometry_instance) {
  4101. undo_redo->create_action(TTR("Set Material Override"));
  4102. undo_redo->add_do_method(geometry_instance, "set_material_override", spatial_editor->get_preview_material());
  4103. undo_redo->add_undo_method(geometry_instance, "set_material_override", spatial_editor->get_preview_reset_material());
  4104. undo_redo->commit_action();
  4105. }
  4106. _remove_preview_material();
  4107. return;
  4108. }
  4109. _remove_preview_node();
  4110. PackedStringArray error_files;
  4111. undo_redo->create_action(TTR("Create Node"), UndoRedo::MERGE_DISABLE, target_node);
  4112. undo_redo->add_do_method(editor_selection, "clear");
  4113. for (int i = 0; i < selected_files.size(); i++) {
  4114. String path = selected_files[i];
  4115. Ref<Resource> res = ResourceLoader::load(path);
  4116. if (res.is_null()) {
  4117. continue;
  4118. }
  4119. Ref<PackedScene> scene = res;
  4120. Ref<Mesh> mesh = res;
  4121. if (mesh.is_valid() || scene.is_valid()) {
  4122. if (!_create_instance(target_node, path, drop_pos)) {
  4123. error_files.push_back(path.get_file());
  4124. }
  4125. }
  4126. Ref<AudioStream> audio = res;
  4127. if (audio.is_valid()) {
  4128. if (!_create_audio_node(target_node, path, drop_pos)) {
  4129. error_files.push_back(path.get_file());
  4130. }
  4131. }
  4132. }
  4133. undo_redo->commit_action();
  4134. if (error_files.size() > 0) {
  4135. accept->set_text(vformat(TTR("Error instantiating scene from %s."), String(", ").join(error_files)));
  4136. accept->popup_centered();
  4137. }
  4138. }
  4139. bool Node3DEditorViewport::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
  4140. preview_node_viewport_pos = p_point;
  4141. bool can_instantiate = false;
  4142. bool is_cyclical_dep = false;
  4143. String error_file;
  4144. if (!preview_node->is_inside_tree() && spatial_editor->get_preview_material().is_null()) {
  4145. Dictionary d = p_data;
  4146. if (d.has("type") && (String(d["type"]) == "files")) {
  4147. Vector<String> files = d["files"];
  4148. // Track whether a type other than PackedScene is valid to stop checking them and only
  4149. // continue to check if the rest of the scenes are valid (don't have cyclic dependencies).
  4150. bool is_other_valid = false;
  4151. // Check if at least one of the dragged files is a mesh, material, texture or scene.
  4152. for (int i = 0; i < files.size(); i++) {
  4153. const String &res_type = ResourceLoader::get_resource_type(files[i]);
  4154. bool is_scene = ClassDB::is_parent_class(res_type, "PackedScene");
  4155. bool is_mesh = ClassDB::is_parent_class(res_type, "Mesh");
  4156. bool is_material = ClassDB::is_parent_class(res_type, "Material");
  4157. bool is_texture = ClassDB::is_parent_class(res_type, "Texture");
  4158. bool is_audio = ClassDB::is_parent_class(res_type, "AudioStream");
  4159. if (is_mesh || is_scene || is_material || is_texture || is_audio) {
  4160. Ref<Resource> res = ResourceLoader::load(files[i]);
  4161. if (res.is_null()) {
  4162. continue;
  4163. }
  4164. Ref<PackedScene> scn = res;
  4165. Ref<Mesh> mesh = res;
  4166. Ref<Material> mat = res;
  4167. Ref<Texture2D> tex = res;
  4168. Ref<AudioStream> audio = res;
  4169. if (scn.is_valid()) {
  4170. Node *instantiated_scene = scn->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
  4171. if (!instantiated_scene) {
  4172. continue;
  4173. }
  4174. Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
  4175. if (edited_scene && !edited_scene->get_scene_file_path().is_empty() && _cyclical_dependency_exists(edited_scene->get_scene_file_path(), instantiated_scene)) {
  4176. memdelete(instantiated_scene);
  4177. can_instantiate = false;
  4178. is_cyclical_dep = true;
  4179. error_file = files[i].get_file();
  4180. break;
  4181. }
  4182. memdelete(instantiated_scene);
  4183. } else if (!is_other_valid && mat.is_valid()) {
  4184. Ref<BaseMaterial3D> base_mat = res;
  4185. Ref<ShaderMaterial> shader_mat = res;
  4186. if (base_mat.is_null() && shader_mat.is_null()) {
  4187. continue;
  4188. }
  4189. spatial_editor->set_preview_material(mat);
  4190. is_other_valid = true;
  4191. continue;
  4192. } else if (!is_other_valid && mesh.is_valid()) {
  4193. // Let the mesh pass.
  4194. is_other_valid = true;
  4195. } else if (!is_other_valid && tex.is_valid()) {
  4196. Ref<StandardMaterial3D> new_mat = memnew(StandardMaterial3D);
  4197. new_mat->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, tex);
  4198. spatial_editor->set_preview_material(new_mat);
  4199. is_other_valid = true;
  4200. continue;
  4201. } else if (!is_other_valid && audio.is_valid()) {
  4202. is_other_valid = true;
  4203. } else {
  4204. continue;
  4205. }
  4206. can_instantiate = true;
  4207. }
  4208. }
  4209. if (can_instantiate) {
  4210. _create_preview_node(files);
  4211. preview_node->hide();
  4212. }
  4213. }
  4214. } else {
  4215. if (preview_node->is_inside_tree()) {
  4216. can_instantiate = true;
  4217. }
  4218. }
  4219. if (is_cyclical_dep) {
  4220. set_message(vformat(TTR("Can't instantiate: %s."), vformat(TTR("Circular dependency found at %s"), error_file)));
  4221. return false;
  4222. }
  4223. if (can_instantiate) {
  4224. update_preview_node = true;
  4225. return true;
  4226. }
  4227. if (spatial_editor->get_preview_material().is_valid()) {
  4228. preview_material_label->show();
  4229. preview_material_label_desc->show();
  4230. ObjectID new_preview_material_target = _select_ray(p_point);
  4231. return _apply_preview_material(new_preview_material_target, p_point);
  4232. }
  4233. return false;
  4234. }
  4235. void Node3DEditorViewport::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
  4236. if (!can_drop_data_fw(p_point, p_data, p_from)) {
  4237. return;
  4238. }
  4239. bool is_shift = Input::get_singleton()->is_key_pressed(Key::SHIFT);
  4240. bool is_alt = Input::get_singleton()->is_key_pressed(Key::ALT);
  4241. selected_files.clear();
  4242. Dictionary d = p_data;
  4243. if (d.has("type") && String(d["type"]) == "files") {
  4244. selected_files = d["files"];
  4245. }
  4246. List<Node *> selected_nodes = EditorNode::get_singleton()->get_editor_selection()->get_selected_node_list();
  4247. Node *root_node = EditorNode::get_singleton()->get_edited_scene();
  4248. if (selected_nodes.size() > 0) {
  4249. Node *selected_node = selected_nodes.front()->get();
  4250. if (is_alt) {
  4251. target_node = root_node;
  4252. } else if (is_shift) {
  4253. target_node = selected_node;
  4254. } else { // Default behavior.
  4255. target_node = (selected_node != root_node) ? selected_node->get_parent() : root_node;
  4256. }
  4257. } else {
  4258. if (root_node) {
  4259. target_node = root_node;
  4260. } else {
  4261. // Create a root node so we can add child nodes to it.
  4262. SceneTreeDock::get_singleton()->add_root_node(memnew(Node3D));
  4263. target_node = get_tree()->get_edited_scene_root();
  4264. }
  4265. }
  4266. drop_pos = p_point;
  4267. _perform_drop_data();
  4268. }
  4269. void Node3DEditorViewport::begin_transform(TransformMode p_mode, bool instant) {
  4270. if (get_selected_count() > 0) {
  4271. _edit.mode = p_mode;
  4272. _compute_edit(_edit.mouse_pos);
  4273. _edit.instant = instant;
  4274. _edit.snap = spatial_editor->is_snap_enabled();
  4275. update_transform_gizmo_view();
  4276. set_process_input(instant);
  4277. }
  4278. }
  4279. // Apply the current transform operation.
  4280. void Node3DEditorViewport::commit_transform() {
  4281. ERR_FAIL_COND(_edit.mode == TRANSFORM_NONE);
  4282. static const char *_transform_name[4] = {
  4283. TTRC("None"),
  4284. TTRC("Rotate"),
  4285. // TRANSLATORS: This refers to the movement that changes the position of an object.
  4286. TTRC("Translate"),
  4287. TTRC("Scale"),
  4288. };
  4289. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  4290. undo_redo->create_action(_transform_name[_edit.mode]);
  4291. List<Node *> &selection = editor_selection->get_selected_node_list();
  4292. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  4293. Node3D *sp = Object::cast_to<Node3D>(E->get());
  4294. if (!sp) {
  4295. continue;
  4296. }
  4297. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  4298. if (!se) {
  4299. continue;
  4300. }
  4301. undo_redo->add_do_method(sp, "set_transform", sp->get_local_gizmo_transform());
  4302. undo_redo->add_undo_method(sp, "set_transform", se->original_local);
  4303. }
  4304. undo_redo->commit_action();
  4305. collision_reposition = false;
  4306. finish_transform();
  4307. set_message("");
  4308. }
  4309. void Node3DEditorViewport::apply_transform(Vector3 p_motion, double p_snap) {
  4310. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
  4311. List<Node *> &selection = editor_selection->get_selected_node_list();
  4312. for (Node *E : selection) {
  4313. Node3D *sp = Object::cast_to<Node3D>(E);
  4314. if (!sp) {
  4315. continue;
  4316. }
  4317. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  4318. if (!se) {
  4319. continue;
  4320. }
  4321. if (sp->has_meta("_edit_lock_")) {
  4322. continue;
  4323. }
  4324. if (se->gizmo.is_valid()) {
  4325. for (KeyValue<int, Transform3D> &GE : se->subgizmos) {
  4326. Transform3D xform = GE.value;
  4327. Transform3D new_xform = _compute_transform(_edit.mode, se->original * xform, xform, p_motion, p_snap, local_coords, _edit.plane != TRANSFORM_VIEW); // Force orthogonal with subgizmo.
  4328. if (!local_coords) {
  4329. new_xform = se->original.affine_inverse() * new_xform;
  4330. }
  4331. se->gizmo->set_subgizmo_transform(GE.key, new_xform);
  4332. }
  4333. } else {
  4334. Transform3D new_xform = _compute_transform(_edit.mode, se->original, se->original_local, p_motion, p_snap, local_coords, sp->get_rotation_edit_mode() != Node3D::ROTATION_EDIT_MODE_BASIS && _edit.plane != TRANSFORM_VIEW);
  4335. _transform_gizmo_apply(se->sp, new_xform, local_coords);
  4336. }
  4337. }
  4338. spatial_editor->update_transform_gizmo();
  4339. surface->queue_redraw();
  4340. }
  4341. // Update the current transform operation in response to an input.
  4342. void Node3DEditorViewport::update_transform(bool p_shift) {
  4343. Vector3 ray_pos = get_ray_pos(_edit.mouse_pos);
  4344. Vector3 ray = get_ray(_edit.mouse_pos);
  4345. double snap = EDITOR_GET("interface/inspector/default_float_step");
  4346. int snap_step_decimals = Math::range_step_decimals(snap);
  4347. switch (_edit.mode) {
  4348. case TRANSFORM_SCALE: {
  4349. Vector3 motion_mask;
  4350. Plane plane;
  4351. bool plane_mv = false;
  4352. switch (_edit.plane) {
  4353. case TRANSFORM_VIEW:
  4354. motion_mask = Vector3(0, 0, 0);
  4355. plane = Plane(_get_camera_normal(), _edit.center);
  4356. break;
  4357. case TRANSFORM_X_AXIS:
  4358. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(0).normalized();
  4359. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  4360. break;
  4361. case TRANSFORM_Y_AXIS:
  4362. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
  4363. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  4364. break;
  4365. case TRANSFORM_Z_AXIS:
  4366. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized();
  4367. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  4368. break;
  4369. case TRANSFORM_YZ:
  4370. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized() + spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
  4371. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(0).normalized(), _edit.center);
  4372. plane_mv = true;
  4373. break;
  4374. case TRANSFORM_XZ:
  4375. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized() + spatial_editor->get_gizmo_transform().basis.get_column(0).normalized();
  4376. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(1).normalized(), _edit.center);
  4377. plane_mv = true;
  4378. break;
  4379. case TRANSFORM_XY:
  4380. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(0).normalized() + spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
  4381. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(2).normalized(), _edit.center);
  4382. plane_mv = true;
  4383. break;
  4384. }
  4385. Vector3 intersection;
  4386. if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
  4387. break;
  4388. }
  4389. Vector3 click;
  4390. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
  4391. break;
  4392. }
  4393. Vector3 motion = intersection - click;
  4394. if (_edit.plane != TRANSFORM_VIEW) {
  4395. if (!plane_mv) {
  4396. motion = motion_mask.dot(motion) * motion_mask;
  4397. } else {
  4398. // Alternative planar scaling mode
  4399. if (p_shift) {
  4400. motion = motion_mask.dot(motion) * motion_mask;
  4401. }
  4402. }
  4403. } else {
  4404. const real_t center_click_dist = click.distance_to(_edit.center);
  4405. const real_t center_inters_dist = intersection.distance_to(_edit.center);
  4406. if (center_click_dist == 0) {
  4407. break;
  4408. }
  4409. const real_t scale = center_inters_dist - center_click_dist;
  4410. motion = Vector3(scale, scale, scale);
  4411. }
  4412. motion /= click.distance_to(_edit.center);
  4413. // Disable local transformation for TRANSFORM_VIEW
  4414. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
  4415. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  4416. snap = spatial_editor->get_scale_snap() / 100;
  4417. }
  4418. Vector3 motion_snapped = motion;
  4419. motion_snapped.snapf(snap);
  4420. // This might not be necessary anymore after issue #288 is solved (in 4.0?).
  4421. // TRANSLATORS: Refers to changing the scale of a node in the 3D editor.
  4422. set_message(TTR("Scaling:") + " (" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
  4423. String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
  4424. if (local_coords) {
  4425. // TODO: needed?
  4426. motion = _edit.original.basis.inverse().xform(motion);
  4427. }
  4428. apply_transform(motion, snap);
  4429. } break;
  4430. case TRANSFORM_TRANSLATE: {
  4431. Vector3 motion_mask;
  4432. Plane plane;
  4433. bool plane_mv = false;
  4434. switch (_edit.plane) {
  4435. case TRANSFORM_VIEW:
  4436. plane = Plane(_get_camera_normal(), _edit.center);
  4437. break;
  4438. case TRANSFORM_X_AXIS:
  4439. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(0).normalized();
  4440. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  4441. break;
  4442. case TRANSFORM_Y_AXIS:
  4443. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
  4444. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  4445. break;
  4446. case TRANSFORM_Z_AXIS:
  4447. motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized();
  4448. plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
  4449. break;
  4450. case TRANSFORM_YZ:
  4451. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(0).normalized(), _edit.center);
  4452. plane_mv = true;
  4453. break;
  4454. case TRANSFORM_XZ:
  4455. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(1).normalized(), _edit.center);
  4456. plane_mv = true;
  4457. break;
  4458. case TRANSFORM_XY:
  4459. plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(2).normalized(), _edit.center);
  4460. plane_mv = true;
  4461. break;
  4462. }
  4463. Vector3 intersection;
  4464. if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
  4465. break;
  4466. }
  4467. Vector3 click;
  4468. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
  4469. break;
  4470. }
  4471. Vector3 motion = intersection - click;
  4472. if (_edit.plane != TRANSFORM_VIEW) {
  4473. if (!plane_mv) {
  4474. motion = motion_mask.dot(motion) * motion_mask;
  4475. }
  4476. }
  4477. // Disable local transformation for TRANSFORM_VIEW
  4478. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
  4479. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  4480. snap = spatial_editor->get_translate_snap();
  4481. }
  4482. Vector3 motion_snapped = motion;
  4483. motion_snapped.snapf(snap);
  4484. // TRANSLATORS: Refers to changing the position of a node in the 3D editor.
  4485. set_message(TTR("Translating:") + " (" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
  4486. String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
  4487. if (local_coords) {
  4488. motion = spatial_editor->get_gizmo_transform().basis.inverse().xform(motion);
  4489. }
  4490. apply_transform(motion, snap);
  4491. } break;
  4492. case TRANSFORM_ROTATE: {
  4493. Plane plane;
  4494. if (camera->get_projection() == Camera3D::PROJECTION_PERSPECTIVE) {
  4495. Vector3 cam_to_obj = _edit.center - _get_camera_position();
  4496. if (!cam_to_obj.is_zero_approx()) {
  4497. plane = Plane(cam_to_obj.normalized(), _edit.center);
  4498. } else {
  4499. plane = Plane(_get_camera_normal(), _edit.center);
  4500. }
  4501. } else {
  4502. plane = Plane(_get_camera_normal(), _edit.center);
  4503. }
  4504. Vector3 local_axis;
  4505. Vector3 global_axis;
  4506. switch (_edit.plane) {
  4507. case TRANSFORM_VIEW:
  4508. // local_axis unused
  4509. global_axis = plane.normal;
  4510. break;
  4511. case TRANSFORM_X_AXIS:
  4512. local_axis = Vector3(1, 0, 0);
  4513. break;
  4514. case TRANSFORM_Y_AXIS:
  4515. local_axis = Vector3(0, 1, 0);
  4516. break;
  4517. case TRANSFORM_Z_AXIS:
  4518. local_axis = Vector3(0, 0, 1);
  4519. break;
  4520. case TRANSFORM_YZ:
  4521. case TRANSFORM_XZ:
  4522. case TRANSFORM_XY:
  4523. break;
  4524. }
  4525. if (_edit.plane != TRANSFORM_VIEW) {
  4526. global_axis = spatial_editor->get_gizmo_transform().basis.xform(local_axis).normalized();
  4527. }
  4528. Vector3 intersection;
  4529. if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
  4530. break;
  4531. }
  4532. Vector3 click;
  4533. if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
  4534. break;
  4535. }
  4536. static const float orthogonal_threshold = Math::cos(Math::deg_to_rad(85.0f));
  4537. bool axis_is_orthogonal = ABS(plane.normal.dot(global_axis)) < orthogonal_threshold;
  4538. double angle = 0.0f;
  4539. if (axis_is_orthogonal) {
  4540. _edit.show_rotation_line = false;
  4541. Vector3 projection_axis = plane.normal.cross(global_axis);
  4542. Vector3 delta = intersection - click;
  4543. float projection = delta.dot(projection_axis);
  4544. angle = (projection * (Math_PI / 2.0f)) / (gizmo_scale * GIZMO_CIRCLE_SIZE);
  4545. } else {
  4546. _edit.show_rotation_line = true;
  4547. Vector3 click_axis = (click - _edit.center).normalized();
  4548. Vector3 current_axis = (intersection - _edit.center).normalized();
  4549. angle = click_axis.signed_angle_to(current_axis, global_axis);
  4550. }
  4551. if (_edit.snap || spatial_editor->is_snap_enabled()) {
  4552. snap = spatial_editor->get_rotate_snap();
  4553. }
  4554. angle = Math::snapped(Math::rad_to_deg(angle), snap);
  4555. set_message(vformat(TTR("Rotating %s degrees."), String::num(angle, snap_step_decimals)));
  4556. angle = Math::deg_to_rad(angle);
  4557. bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW); // Disable local transformation for TRANSFORM_VIEW
  4558. Vector3 compute_axis = local_coords ? local_axis : global_axis;
  4559. apply_transform(compute_axis, angle);
  4560. } break;
  4561. default: {
  4562. }
  4563. }
  4564. }
  4565. void Node3DEditorViewport::update_transform_numeric() {
  4566. Vector3 motion;
  4567. switch (_edit.plane) {
  4568. case TRANSFORM_VIEW: {
  4569. switch (_edit.mode) {
  4570. case TRANSFORM_TRANSLATE:
  4571. motion = Vector3(1, 0, 0);
  4572. break;
  4573. case TRANSFORM_ROTATE:
  4574. motion = spatial_editor->get_gizmo_transform().basis.xform_inv(_get_camera_normal()).normalized();
  4575. break;
  4576. case TRANSFORM_SCALE:
  4577. motion = Vector3(1, 1, 1);
  4578. break;
  4579. case TRANSFORM_NONE:
  4580. ERR_FAIL_MSG("_edit.mode cannot be TRANSFORM_NONE in update_transform_numeric.");
  4581. }
  4582. break;
  4583. }
  4584. case TRANSFORM_X_AXIS:
  4585. motion = Vector3(1, 0, 0);
  4586. break;
  4587. case TRANSFORM_Y_AXIS:
  4588. motion = Vector3(0, 1, 0);
  4589. break;
  4590. case TRANSFORM_Z_AXIS:
  4591. motion = Vector3(0, 0, 1);
  4592. break;
  4593. case TRANSFORM_XY:
  4594. motion = Vector3(1, 1, 0);
  4595. break;
  4596. case TRANSFORM_XZ:
  4597. motion = Vector3(1, 0, 1);
  4598. break;
  4599. case TRANSFORM_YZ:
  4600. motion = Vector3(0, 1, 1);
  4601. break;
  4602. }
  4603. double value = _edit.numeric_input * (_edit.numeric_negate ? -1 : 1);
  4604. double extra = 0.0;
  4605. switch (_edit.mode) {
  4606. case TRANSFORM_TRANSLATE:
  4607. motion *= value;
  4608. set_message(vformat(TTR("Translating %s."), motion));
  4609. break;
  4610. case TRANSFORM_ROTATE:
  4611. extra = Math::deg_to_rad(value);
  4612. set_message(vformat(TTR("Rotating %f degrees."), value));
  4613. break;
  4614. case TRANSFORM_SCALE:
  4615. // To halve the size of an object in Blender, you scale it by 0.5.
  4616. // Doing the same in Godot is considered scaling it by -0.5.
  4617. motion *= (value - 1.0);
  4618. set_message(vformat(TTR("Scaling %s."), motion));
  4619. break;
  4620. case TRANSFORM_NONE:
  4621. ERR_FAIL_MSG("_edit.mode cannot be TRANSFORM_NONE in update_transform_numeric.");
  4622. }
  4623. apply_transform(motion, extra);
  4624. }
  4625. // Perform cleanup after a transform operation is committed or canceled.
  4626. void Node3DEditorViewport::finish_transform() {
  4627. _edit.mode = TRANSFORM_NONE;
  4628. _edit.instant = false;
  4629. _edit.numeric_input = 0;
  4630. _edit.numeric_next_decimal = 0;
  4631. _edit.numeric_negate = false;
  4632. spatial_editor->set_local_coords_enabled(_edit.original_local);
  4633. spatial_editor->update_transform_gizmo();
  4634. surface->queue_redraw();
  4635. set_process_input(false);
  4636. }
  4637. // Register a shortcut and also add it as an input action with the same events.
  4638. void Node3DEditorViewport::register_shortcut_action(const String &p_path, const String &p_name, Key p_keycode, bool p_physical) {
  4639. Ref<Shortcut> sc = ED_SHORTCUT(p_path, p_name, p_keycode, p_physical);
  4640. shortcut_changed_callback(sc, p_path);
  4641. // Connect to the change event on the shortcut so the input binding can be updated.
  4642. sc->connect_changed(callable_mp(this, &Node3DEditorViewport::shortcut_changed_callback).bind(sc, p_path));
  4643. }
  4644. // Update the action in the InputMap to the provided shortcut events.
  4645. void Node3DEditorViewport::shortcut_changed_callback(const Ref<Shortcut> p_shortcut, const String &p_shortcut_path) {
  4646. InputMap *im = InputMap::get_singleton();
  4647. if (im->has_action(p_shortcut_path)) {
  4648. im->action_erase_events(p_shortcut_path);
  4649. } else {
  4650. im->add_action(p_shortcut_path);
  4651. }
  4652. for (int i = 0; i < p_shortcut->get_events().size(); i++) {
  4653. im->action_add_event(p_shortcut_path, p_shortcut->get_events()[i]);
  4654. }
  4655. }
  4656. void Node3DEditorViewport::_set_lock_view_rotation(bool p_lock_rotation) {
  4657. lock_rotation = p_lock_rotation;
  4658. int idx = view_display_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
  4659. view_display_menu->get_popup()->set_item_checked(idx, p_lock_rotation);
  4660. if (p_lock_rotation) {
  4661. locked_label->show();
  4662. } else {
  4663. locked_label->hide();
  4664. }
  4665. }
  4666. void Node3DEditorViewport::_add_advanced_debug_draw_mode_item(PopupMenu *p_popup, const String &p_name, int p_value, SupportedRenderingMethods p_rendering_methods, const String &p_tooltip) {
  4667. display_submenu->add_radio_check_item(p_name, p_value);
  4668. bool disabled = false;
  4669. String disabled_tooltip;
  4670. switch (p_rendering_methods) {
  4671. case SupportedRenderingMethods::ALL:
  4672. break;
  4673. case SupportedRenderingMethods::FORWARD_PLUS_MOBILE:
  4674. disabled = OS::get_singleton()->get_current_rendering_method() == "gl_compatibility";
  4675. disabled_tooltip = TTR("This debug draw mode is not supported when using the Compatibility rendering method.");
  4676. break;
  4677. case SupportedRenderingMethods::FORWARD_PLUS:
  4678. disabled = OS::get_singleton()->get_current_rendering_method() == "gl_compatibility" || OS::get_singleton()->get_current_rendering_method() == "mobile";
  4679. disabled_tooltip = TTR("This debug draw mode is not supported when using the Mobile or Compatibility rendering methods.");
  4680. break;
  4681. }
  4682. display_submenu->set_item_disabled(-1, disabled);
  4683. String tooltip = p_tooltip;
  4684. if (disabled) {
  4685. if (tooltip.is_empty()) {
  4686. tooltip = disabled_tooltip;
  4687. } else {
  4688. tooltip += "\n\n" + disabled_tooltip;
  4689. }
  4690. }
  4691. display_submenu->set_item_tooltip(-1, tooltip);
  4692. }
  4693. Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, int p_index) {
  4694. cpu_time_history_index = 0;
  4695. gpu_time_history_index = 0;
  4696. _edit.mode = TRANSFORM_NONE;
  4697. _edit.plane = TRANSFORM_VIEW;
  4698. _edit.snap = true;
  4699. _edit.show_rotation_line = true;
  4700. _edit.instant = false;
  4701. _edit.gizmo_handle = -1;
  4702. _edit.gizmo_handle_secondary = false;
  4703. index = p_index;
  4704. editor_selection = EditorNode::get_singleton()->get_editor_selection();
  4705. orthogonal = false;
  4706. auto_orthogonal = false;
  4707. lock_rotation = false;
  4708. message_time = 0;
  4709. zoom_indicator_delay = 0.0;
  4710. spatial_editor = p_spatial_editor;
  4711. SubViewportContainer *c = memnew(SubViewportContainer);
  4712. subviewport_container = c;
  4713. c->set_stretch(true);
  4714. add_child(c);
  4715. c->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
  4716. viewport = memnew(SubViewport);
  4717. viewport->set_disable_input(true);
  4718. c->add_child(viewport);
  4719. surface = memnew(Control);
  4720. SET_DRAG_FORWARDING_CD(surface, Node3DEditorViewport);
  4721. add_child(surface);
  4722. surface->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
  4723. surface->set_clip_contents(true);
  4724. camera = memnew(Camera3D);
  4725. camera->set_disable_gizmos(true);
  4726. 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));
  4727. viewport->add_child(camera);
  4728. camera->make_current();
  4729. surface->set_focus_mode(FOCUS_ALL);
  4730. VBoxContainer *vbox = memnew(VBoxContainer);
  4731. surface->add_child(vbox);
  4732. vbox->set_offset(SIDE_LEFT, 10 * EDSCALE);
  4733. vbox->set_offset(SIDE_TOP, 10 * EDSCALE);
  4734. view_display_menu = memnew(MenuButton);
  4735. view_display_menu->set_flat(false);
  4736. view_display_menu->set_h_size_flags(0);
  4737. view_display_menu->set_shortcut_context(this);
  4738. vbox->add_child(view_display_menu);
  4739. view_display_menu->get_popup()->set_hide_on_checkable_item_selection(false);
  4740. view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/top_view"), VIEW_TOP);
  4741. view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/bottom_view"), VIEW_BOTTOM);
  4742. view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/left_view"), VIEW_LEFT);
  4743. view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/right_view"), VIEW_RIGHT);
  4744. view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/front_view"), VIEW_FRONT);
  4745. view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/rear_view"), VIEW_REAR);
  4746. view_display_menu->get_popup()->add_separator();
  4747. view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/switch_perspective_orthogonal"), VIEW_SWITCH_PERSPECTIVE_ORTHOGONAL);
  4748. view_display_menu->get_popup()->add_radio_check_item(TTR("Perspective"), VIEW_PERSPECTIVE);
  4749. view_display_menu->get_popup()->add_radio_check_item(TTR("Orthogonal"), VIEW_ORTHOGONAL);
  4750. view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
  4751. view_display_menu->get_popup()->add_check_item(TTR("Auto Orthogonal Enabled"), VIEW_AUTO_ORTHOGONAL);
  4752. view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL), true);
  4753. view_display_menu->get_popup()->add_separator();
  4754. view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_lock_rotation", TTRC("Lock View Rotation")), VIEW_LOCK_ROTATION);
  4755. view_display_menu->get_popup()->add_separator();
  4756. // TRANSLATORS: "Normal" as in "normal life", not "normal vector".
  4757. view_display_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_normal", TTRC("Display Normal")), VIEW_DISPLAY_NORMAL);
  4758. view_display_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_wireframe", TTRC("Display Wireframe")), VIEW_DISPLAY_WIREFRAME);
  4759. view_display_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_overdraw", TTRC("Display Overdraw")), VIEW_DISPLAY_OVERDRAW);
  4760. view_display_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_lighting", TTRC("Display Lighting")), VIEW_DISPLAY_LIGHTING);
  4761. view_display_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_unshaded", TTRC("Display Unshaded")), VIEW_DISPLAY_UNSHADED);
  4762. view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), true);
  4763. display_submenu = memnew(PopupMenu);
  4764. display_submenu->set_hide_on_checkable_item_selection(false);
  4765. _add_advanced_debug_draw_mode_item(display_submenu, TTR("Directional Shadow Splits"), VIEW_DISPLAY_DEBUG_PSSM_SPLITS, SupportedRenderingMethods::FORWARD_PLUS_MOBILE,
  4766. TTR("Displays directional shadow splits in different colors to make adjusting split thresholds easier. \nRed: 1st split (closest to the camera), Green: 2nd split, Blue: 3rd split, Yellow: 4th split (furthest from the camera)"));
  4767. display_submenu->add_separator();
  4768. // TRANSLATORS: "Normal" as in "normal vector", not "normal life".
  4769. _add_advanced_debug_draw_mode_item(display_submenu, TTR("Normal Buffer"), VIEW_DISPLAY_NORMAL_BUFFER, SupportedRenderingMethods::FORWARD_PLUS);
  4770. display_submenu->add_separator();
  4771. _add_advanced_debug_draw_mode_item(display_submenu, TTR("Shadow Atlas"), VIEW_DISPLAY_DEBUG_SHADOW_ATLAS, SupportedRenderingMethods::ALL,
  4772. TTR("Displays the shadow atlas used for positional (omni/spot) shadow mapping.\nRequires a visible OmniLight3D or SpotLight3D node with shadows enabled to have a visible effect."));
  4773. _add_advanced_debug_draw_mode_item(display_submenu, TTR("Directional Shadow Map"), VIEW_DISPLAY_DEBUG_DIRECTIONAL_SHADOW_ATLAS, SupportedRenderingMethods::ALL,
  4774. TTR("Displays the shadow map used for directional shadow mapping.\nRequires a visible DirectionalLight3D node with shadows enabled to have a visible effect."));
  4775. display_submenu->add_separator();
  4776. _add_advanced_debug_draw_mode_item(display_submenu, TTR("Decal Atlas"), VIEW_DISPLAY_DEBUG_DECAL_ATLAS, SupportedRenderingMethods::FORWARD_PLUS_MOBILE);
  4777. display_submenu->add_separator();
  4778. _add_advanced_debug_draw_mode_item(display_submenu, TTR("VoxelGI Lighting"), VIEW_DISPLAY_DEBUG_VOXEL_GI_LIGHTING, SupportedRenderingMethods::FORWARD_PLUS,
  4779. TTR("Requires a visible VoxelGI node that has been baked to have a visible effect."));
  4780. _add_advanced_debug_draw_mode_item(display_submenu, TTR("VoxelGI Albedo"), VIEW_DISPLAY_DEBUG_VOXEL_GI_ALBEDO, SupportedRenderingMethods::FORWARD_PLUS,
  4781. TTR("Requires a visible VoxelGI node that has been baked to have a visible effect."));
  4782. _add_advanced_debug_draw_mode_item(display_submenu, TTR("VoxelGI Emission"), VIEW_DISPLAY_DEBUG_VOXEL_GI_EMISSION, SupportedRenderingMethods::FORWARD_PLUS,
  4783. TTR("Requires a visible VoxelGI node that has been baked to have a visible effect."));
  4784. display_submenu->add_separator();
  4785. _add_advanced_debug_draw_mode_item(display_submenu, TTR("SDFGI Cascades"), VIEW_DISPLAY_DEBUG_SDFGI, SupportedRenderingMethods::FORWARD_PLUS,
  4786. TTR("Requires SDFGI to be enabled in Environment to have a visible effect."));
  4787. _add_advanced_debug_draw_mode_item(display_submenu, TTR("SDFGI Probes"), VIEW_DISPLAY_DEBUG_SDFGI_PROBES, SupportedRenderingMethods::FORWARD_PLUS,
  4788. TTR("Requires SDFGI to be enabled in Environment to have a visible effect."));
  4789. display_submenu->add_separator();
  4790. _add_advanced_debug_draw_mode_item(display_submenu, TTR("Scene Luminance"), VIEW_DISPLAY_DEBUG_SCENE_LUMINANCE, SupportedRenderingMethods::FORWARD_PLUS_MOBILE,
  4791. TTR("Displays the scene luminance computed from the 3D buffer. This is used for Auto Exposure calculation.\nRequires Auto Exposure to be enabled in CameraAttributes to have a visible effect."));
  4792. display_submenu->add_separator();
  4793. _add_advanced_debug_draw_mode_item(display_submenu, TTR("SSAO"), VIEW_DISPLAY_DEBUG_SSAO, SupportedRenderingMethods::FORWARD_PLUS,
  4794. TTR("Displays the screen-space ambient occlusion buffer. Requires SSAO to be enabled in Environment to have a visible effect."));
  4795. _add_advanced_debug_draw_mode_item(display_submenu, TTR("SSIL"), VIEW_DISPLAY_DEBUG_SSIL, SupportedRenderingMethods::FORWARD_PLUS,
  4796. TTR("Displays the screen-space indirect lighting buffer. Requires SSIL to be enabled in Environment to have a visible effect."));
  4797. display_submenu->add_separator();
  4798. _add_advanced_debug_draw_mode_item(display_submenu, TTR("VoxelGI/SDFGI Buffer"), VIEW_DISPLAY_DEBUG_GI_BUFFER, SupportedRenderingMethods::FORWARD_PLUS,
  4799. TTR("Requires SDFGI or VoxelGI to be enabled to have a visible effect."));
  4800. display_submenu->add_separator();
  4801. _add_advanced_debug_draw_mode_item(display_submenu, TTR("Disable Mesh LOD"), VIEW_DISPLAY_DEBUG_DISABLE_LOD, SupportedRenderingMethods::ALL,
  4802. TTR("Renders all meshes with their highest level of detail regardless of their distance from the camera."));
  4803. display_submenu->add_separator();
  4804. _add_advanced_debug_draw_mode_item(display_submenu, TTR("OmniLight3D Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS, SupportedRenderingMethods::FORWARD_PLUS,
  4805. TTR("Highlights tiles of pixels that are affected by at least one OmniLight3D."));
  4806. _add_advanced_debug_draw_mode_item(display_submenu, TTR("SpotLight3D Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS, SupportedRenderingMethods::FORWARD_PLUS,
  4807. TTR("Highlights tiles of pixels that are affected by at least one SpotLight3D."));
  4808. _add_advanced_debug_draw_mode_item(display_submenu, TTR("Decal Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_DECALS, SupportedRenderingMethods::FORWARD_PLUS,
  4809. TTR("Highlights tiles of pixels that are affected by at least one Decal."));
  4810. _add_advanced_debug_draw_mode_item(display_submenu, TTR("ReflectionProbe Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES, SupportedRenderingMethods::FORWARD_PLUS,
  4811. TTR("Highlights tiles of pixels that are affected by at least one ReflectionProbe."));
  4812. _add_advanced_debug_draw_mode_item(display_submenu, TTR("Occlusion Culling Buffer"), VIEW_DISPLAY_DEBUG_OCCLUDERS, SupportedRenderingMethods::FORWARD_PLUS_MOBILE,
  4813. TTR("Represents occluders with black pixels. Requires occlusion culling to be enabled to have a visible effect."));
  4814. _add_advanced_debug_draw_mode_item(display_submenu, TTR("Motion Vectors"), VIEW_DISPLAY_MOTION_VECTORS, SupportedRenderingMethods::FORWARD_PLUS,
  4815. TTR("Represents motion vectors with colored lines in the direction of motion. Gray dots represent areas with no per-pixel motion."));
  4816. _add_advanced_debug_draw_mode_item(display_submenu, TTR("Internal Buffer"), VIEW_DISPLAY_INTERNAL_BUFFER, SupportedRenderingMethods::FORWARD_PLUS_MOBILE,
  4817. TTR("Shows the scene rendered in linear colorspace before any tonemapping or post-processing."));
  4818. view_display_menu->get_popup()->add_submenu_node_item(TTR("Display Advanced..."), display_submenu, VIEW_DISPLAY_ADVANCED);
  4819. view_display_menu->get_popup()->add_separator();
  4820. view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_environment", TTRC("View Environment")), VIEW_ENVIRONMENT);
  4821. view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_gizmos", TTRC("View Gizmos")), VIEW_GIZMOS);
  4822. view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_transform_gizmo", TTRC("View Transform Gizmo")), VIEW_TRANSFORM_GIZMO);
  4823. view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_grid_lines", TTRC("View Grid")), VIEW_GRID);
  4824. view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_information", TTRC("View Information")), VIEW_INFORMATION);
  4825. view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_fps", TTRC("View Frame Time")), VIEW_FRAME_TIME);
  4826. view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT), true);
  4827. view_display_menu->get_popup()->add_separator();
  4828. view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_half_resolution", TTRC("Half Resolution")), VIEW_HALF_RESOLUTION);
  4829. view_display_menu->get_popup()->add_separator();
  4830. view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_listener", TTRC("Audio Listener")), VIEW_AUDIO_LISTENER);
  4831. view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_doppler", TTRC("Enable Doppler")), VIEW_AUDIO_DOPPLER);
  4832. view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_GIZMOS), true);
  4833. view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_TRANSFORM_GIZMO), true);
  4834. view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_GRID), true);
  4835. view_display_menu->get_popup()->add_separator();
  4836. view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_cinematic_preview", TTRC("Cinematic Preview")), VIEW_CINEMATIC_PREVIEW);
  4837. view_display_menu->get_popup()->add_separator();
  4838. view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_origin"), VIEW_CENTER_TO_ORIGIN);
  4839. view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_selection"), VIEW_CENTER_TO_SELECTION);
  4840. view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_transform_with_view"), VIEW_ALIGN_TRANSFORM_WITH_VIEW);
  4841. view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_rotation_with_view"), VIEW_ALIGN_ROTATION_WITH_VIEW);
  4842. view_display_menu->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditorViewport::_menu_option));
  4843. display_submenu->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditorViewport::_menu_option));
  4844. view_display_menu->set_disable_shortcuts(true);
  4845. // Registering with Key::NONE intentionally creates an empty Array.
  4846. register_shortcut_action("spatial_editor/viewport_orbit_modifier_1", TTRC("Viewport Orbit Modifier 1"), Key::NONE);
  4847. register_shortcut_action("spatial_editor/viewport_orbit_modifier_2", TTRC("Viewport Orbit Modifier 2"), Key::NONE);
  4848. register_shortcut_action("spatial_editor/viewport_pan_modifier_1", TTRC("Viewport Pan Modifier 1"), Key::SHIFT);
  4849. register_shortcut_action("spatial_editor/viewport_pan_modifier_2", TTRC("Viewport Pan Modifier 2"), Key::NONE);
  4850. register_shortcut_action("spatial_editor/viewport_zoom_modifier_1", TTRC("Viewport Zoom Modifier 1"), Key::SHIFT);
  4851. register_shortcut_action("spatial_editor/viewport_zoom_modifier_2", TTRC("Viewport Zoom Modifier 2"), Key::CTRL);
  4852. register_shortcut_action("spatial_editor/freelook_left", TTRC("Freelook Left"), Key::A, true);
  4853. register_shortcut_action("spatial_editor/freelook_right", TTRC("Freelook Right"), Key::D, true);
  4854. register_shortcut_action("spatial_editor/freelook_forward", TTRC("Freelook Forward"), Key::W, true);
  4855. register_shortcut_action("spatial_editor/freelook_backwards", TTRC("Freelook Backwards"), Key::S, true);
  4856. register_shortcut_action("spatial_editor/freelook_up", TTRC("Freelook Up"), Key::E, true);
  4857. register_shortcut_action("spatial_editor/freelook_down", TTRC("Freelook Down"), Key::Q, true);
  4858. register_shortcut_action("spatial_editor/freelook_speed_modifier", TTRC("Freelook Speed Modifier"), Key::SHIFT);
  4859. register_shortcut_action("spatial_editor/freelook_slow_modifier", TTRC("Freelook Slow Modifier"), Key::ALT);
  4860. ED_SHORTCUT("spatial_editor/lock_transform_x", TTRC("Lock Transformation to X axis"), Key::X);
  4861. ED_SHORTCUT("spatial_editor/lock_transform_y", TTRC("Lock Transformation to Y axis"), Key::Y);
  4862. ED_SHORTCUT("spatial_editor/lock_transform_z", TTRC("Lock Transformation to Z axis"), Key::Z);
  4863. ED_SHORTCUT("spatial_editor/lock_transform_yz", TTRC("Lock Transformation to YZ plane"), KeyModifierMask::SHIFT | Key::X);
  4864. ED_SHORTCUT("spatial_editor/lock_transform_xz", TTRC("Lock Transformation to XZ plane"), KeyModifierMask::SHIFT | Key::Y);
  4865. ED_SHORTCUT("spatial_editor/lock_transform_xy", TTRC("Lock Transformation to XY plane"), KeyModifierMask::SHIFT | Key::Z);
  4866. ED_SHORTCUT("spatial_editor/cancel_transform", TTRC("Cancel Transformation"), Key::ESCAPE);
  4867. ED_SHORTCUT("spatial_editor/instant_translate", TTRC("Begin Translate Transformation"));
  4868. ED_SHORTCUT("spatial_editor/instant_rotate", TTRC("Begin Rotate Transformation"));
  4869. ED_SHORTCUT("spatial_editor/instant_scale", TTRC("Begin Scale Transformation"));
  4870. ED_SHORTCUT("spatial_editor/collision_reposition", TTRC("Reposition Using Collisions"), KeyModifierMask::SHIFT | Key::G);
  4871. preview_camera = memnew(CheckBox);
  4872. preview_camera->set_text(TTR("Preview"));
  4873. // Using Control even on macOS to avoid conflict with Quick Open shortcut.
  4874. preview_camera->set_shortcut(ED_SHORTCUT("spatial_editor/toggle_camera_preview", TTRC("Toggle Camera Preview"), KeyModifierMask::CTRL | Key::P));
  4875. vbox->add_child(preview_camera);
  4876. preview_camera->set_h_size_flags(0);
  4877. preview_camera->hide();
  4878. preview_camera->connect(SceneStringName(toggled), callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
  4879. previewing = nullptr;
  4880. gizmo_scale = 1.0;
  4881. preview_node = nullptr;
  4882. bottom_center_vbox = memnew(VBoxContainer);
  4883. bottom_center_vbox->set_anchors_preset(LayoutPreset::PRESET_CENTER);
  4884. bottom_center_vbox->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -20 * EDSCALE);
  4885. bottom_center_vbox->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, -10 * EDSCALE);
  4886. bottom_center_vbox->set_h_grow_direction(GROW_DIRECTION_BOTH);
  4887. bottom_center_vbox->set_v_grow_direction(GROW_DIRECTION_BEGIN);
  4888. surface->add_child(bottom_center_vbox);
  4889. info_panel = memnew(PanelContainer);
  4890. info_panel->set_anchor_and_offset(SIDE_LEFT, ANCHOR_END, -90 * EDSCALE);
  4891. info_panel->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -90 * EDSCALE);
  4892. info_panel->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, -10 * EDSCALE);
  4893. info_panel->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, -10 * EDSCALE);
  4894. info_panel->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  4895. info_panel->set_v_grow_direction(GROW_DIRECTION_BEGIN);
  4896. info_panel->set_mouse_filter(MOUSE_FILTER_IGNORE);
  4897. surface->add_child(info_panel);
  4898. info_panel->hide();
  4899. info_label = memnew(Label);
  4900. info_panel->add_child(info_label);
  4901. cinema_label = memnew(Label);
  4902. cinema_label->set_anchor_and_offset(SIDE_TOP, ANCHOR_BEGIN, 10 * EDSCALE);
  4903. cinema_label->set_h_grow_direction(GROW_DIRECTION_END);
  4904. cinema_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  4905. cinema_label->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
  4906. surface->add_child(cinema_label);
  4907. cinema_label->set_text(TTR("Cinematic Preview"));
  4908. cinema_label->hide();
  4909. previewing_cinema = false;
  4910. locked_label = memnew(Label);
  4911. locked_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  4912. locked_label->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
  4913. locked_label->set_h_size_flags(SIZE_SHRINK_CENTER);
  4914. bottom_center_vbox->add_child(locked_label);
  4915. locked_label->set_text(TTR("View Rotation Locked"));
  4916. locked_label->hide();
  4917. zoom_limit_label = memnew(Label);
  4918. zoom_limit_label->set_text(TTR("To zoom further, change the camera's clipping planes (View -> Settings...)"));
  4919. zoom_limit_label->set_name("ZoomLimitMessageLabel");
  4920. zoom_limit_label->add_theme_color_override(SceneStringName(font_color), Color(1, 1, 1, 1));
  4921. zoom_limit_label->hide();
  4922. bottom_center_vbox->add_child(zoom_limit_label);
  4923. preview_material_label = memnew(Label);
  4924. preview_material_label->set_anchors_and_offsets_preset(LayoutPreset::PRESET_BOTTOM_LEFT);
  4925. preview_material_label->set_offset(Side::SIDE_TOP, -70 * EDSCALE);
  4926. preview_material_label->set_text(TTR("Overriding material..."));
  4927. preview_material_label->add_theme_color_override(SceneStringName(font_color), Color(1, 1, 1, 1));
  4928. preview_material_label->hide();
  4929. surface->add_child(preview_material_label);
  4930. preview_material_label_desc = memnew(Label);
  4931. preview_material_label_desc->set_anchors_and_offsets_preset(LayoutPreset::PRESET_BOTTOM_LEFT);
  4932. preview_material_label_desc->set_offset(Side::SIDE_TOP, -50 * EDSCALE);
  4933. Key key = (OS::get_singleton()->has_feature("macos") || OS::get_singleton()->has_feature("web_macos") || OS::get_singleton()->has_feature("web_ios")) ? Key::META : Key::CTRL;
  4934. preview_material_label_desc->set_text(vformat(TTR("Drag and drop to override the material of any geometry node.\nHold %s when dropping to override a specific surface."), find_keycode_name(key)));
  4935. preview_material_label_desc->add_theme_color_override(SceneStringName(font_color), Color(0.8, 0.8, 0.8, 1));
  4936. preview_material_label_desc->add_theme_constant_override("line_spacing", 0);
  4937. preview_material_label_desc->hide();
  4938. surface->add_child(preview_material_label_desc);
  4939. frame_time_gradient = memnew(Gradient);
  4940. // The color is set when the theme changes.
  4941. frame_time_gradient->add_point(0.5, Color());
  4942. top_right_vbox = memnew(VBoxContainer);
  4943. top_right_vbox->add_theme_constant_override("separation", 10.0 * EDSCALE);
  4944. top_right_vbox->set_anchors_and_offsets_preset(PRESET_TOP_RIGHT, PRESET_MODE_MINSIZE, 10.0 * EDSCALE);
  4945. top_right_vbox->set_h_grow_direction(GROW_DIRECTION_BEGIN);
  4946. const int navigation_control_size = 150;
  4947. position_control = memnew(ViewportNavigationControl);
  4948. position_control->set_navigation_mode(Node3DEditorViewport::NAVIGATION_MOVE);
  4949. position_control->set_custom_minimum_size(Size2(navigation_control_size, navigation_control_size) * EDSCALE);
  4950. position_control->set_h_size_flags(SIZE_SHRINK_END);
  4951. position_control->set_anchor_and_offset(SIDE_LEFT, ANCHOR_BEGIN, 0);
  4952. position_control->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -navigation_control_size * EDSCALE);
  4953. position_control->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_BEGIN, navigation_control_size * EDSCALE);
  4954. position_control->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, 0);
  4955. position_control->set_viewport(this);
  4956. surface->add_child(position_control);
  4957. look_control = memnew(ViewportNavigationControl);
  4958. look_control->set_navigation_mode(Node3DEditorViewport::NAVIGATION_LOOK);
  4959. look_control->set_custom_minimum_size(Size2(navigation_control_size, navigation_control_size) * EDSCALE);
  4960. look_control->set_h_size_flags(SIZE_SHRINK_END);
  4961. look_control->set_anchor_and_offset(SIDE_LEFT, ANCHOR_END, -navigation_control_size * EDSCALE);
  4962. look_control->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -navigation_control_size * EDSCALE);
  4963. look_control->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, 0);
  4964. look_control->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, 0);
  4965. look_control->set_viewport(this);
  4966. surface->add_child(look_control);
  4967. rotation_control = memnew(ViewportRotationControl);
  4968. rotation_control->set_custom_minimum_size(Size2(80, 80) * EDSCALE);
  4969. rotation_control->set_h_size_flags(SIZE_SHRINK_END);
  4970. rotation_control->set_viewport(this);
  4971. rotation_control->set_focus_mode(FOCUS_CLICK);
  4972. top_right_vbox->add_child(rotation_control);
  4973. frame_time_panel = memnew(PanelContainer);
  4974. frame_time_panel->set_mouse_filter(MOUSE_FILTER_IGNORE);
  4975. top_right_vbox->add_child(frame_time_panel);
  4976. frame_time_panel->hide();
  4977. frame_time_vbox = memnew(VBoxContainer);
  4978. frame_time_panel->add_child(frame_time_vbox);
  4979. // Individual Labels are used to allow coloring each label with its own color.
  4980. cpu_time_label = memnew(Label);
  4981. frame_time_vbox->add_child(cpu_time_label);
  4982. gpu_time_label = memnew(Label);
  4983. frame_time_vbox->add_child(gpu_time_label);
  4984. fps_label = memnew(Label);
  4985. frame_time_vbox->add_child(fps_label);
  4986. surface->add_child(top_right_vbox);
  4987. accept = nullptr;
  4988. freelook_active = false;
  4989. freelook_speed = EDITOR_GET("editors/3d/freelook/freelook_base_speed");
  4990. selection_menu = memnew(PopupMenu);
  4991. add_child(selection_menu);
  4992. selection_menu->set_min_size(Size2(100, 0) * EDSCALE);
  4993. selection_menu->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditorViewport::_selection_result_pressed));
  4994. selection_menu->connect("popup_hide", callable_mp(this, &Node3DEditorViewport::_selection_menu_hide));
  4995. if (p_index == 0) {
  4996. view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER), true);
  4997. viewport->set_as_audio_listener_3d(true);
  4998. }
  4999. ruler = memnew(Node);
  5000. ruler_start_point = memnew(Node3D);
  5001. ruler_start_point->set_visible(false);
  5002. ruler_end_point = memnew(Node3D);
  5003. ruler_end_point->set_visible(false);
  5004. ruler_material.instantiate();
  5005. ruler_material->set_albedo(Color(1.0, 0.9, 0.0, 1.0));
  5006. ruler_material->set_flag(BaseMaterial3D::FLAG_DISABLE_FOG, true);
  5007. ruler_material->set_shading_mode(BaseMaterial3D::SHADING_MODE_UNSHADED);
  5008. ruler_material->set_depth_draw_mode(BaseMaterial3D::DEPTH_DRAW_DISABLED);
  5009. ruler_material_xray.instantiate();
  5010. ruler_material_xray->set_albedo(Color(1.0, 0.9, 0.0, 0.15));
  5011. ruler_material_xray->set_flag(BaseMaterial3D::FLAG_DISABLE_FOG, true);
  5012. ruler_material_xray->set_shading_mode(BaseMaterial3D::SHADING_MODE_UNSHADED);
  5013. ruler_material_xray->set_flag(BaseMaterial3D::FLAG_DISABLE_DEPTH_TEST, true);
  5014. ruler_material_xray->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA);
  5015. ruler_material_xray->set_render_priority(BaseMaterial3D::RENDER_PRIORITY_MAX);
  5016. geometry.instantiate();
  5017. ruler_line = memnew(MeshInstance3D);
  5018. ruler_line->set_mesh(geometry);
  5019. ruler_line->set_material_override(ruler_material);
  5020. ruler_line_xray = memnew(MeshInstance3D);
  5021. ruler_line_xray->set_mesh(geometry);
  5022. ruler_line_xray->set_material_override(ruler_material_xray);
  5023. ruler_label = memnew(Label);
  5024. ruler_label->set_visible(false);
  5025. ruler->add_child(ruler_start_point);
  5026. ruler->add_child(ruler_end_point);
  5027. ruler->add_child(ruler_line);
  5028. ruler->add_child(ruler_line_xray);
  5029. viewport->add_child(ruler_label);
  5030. view_type = VIEW_TYPE_USER;
  5031. _update_name();
  5032. EditorSettings::get_singleton()->connect("settings_changed", callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view));
  5033. }
  5034. Node3DEditorViewport::~Node3DEditorViewport() {
  5035. memdelete(ruler);
  5036. memdelete(frame_time_gradient);
  5037. }
  5038. //////////////////////////////////////////////////////////////
  5039. void Node3DEditorViewportContainer::gui_input(const Ref<InputEvent> &p_event) {
  5040. ERR_FAIL_COND(p_event.is_null());
  5041. Ref<InputEventMouseButton> mb = p_event;
  5042. if (mb.is_valid() && mb->get_button_index() == MouseButton::LEFT) {
  5043. if (mb->is_pressed()) {
  5044. Vector2 size = get_size();
  5045. int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
  5046. int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
  5047. int mid_w = size.width * ratio_h;
  5048. int mid_h = size.height * ratio_v;
  5049. dragging_h = mb->get_position().x > (mid_w - h_sep / 2) && mb->get_position().x < (mid_w + h_sep / 2);
  5050. dragging_v = mb->get_position().y > (mid_h - v_sep / 2) && mb->get_position().y < (mid_h + v_sep / 2);
  5051. drag_begin_pos = mb->get_position();
  5052. drag_begin_ratio.x = ratio_h;
  5053. drag_begin_ratio.y = ratio_v;
  5054. switch (view) {
  5055. case VIEW_USE_1_VIEWPORT: {
  5056. dragging_h = false;
  5057. dragging_v = false;
  5058. } break;
  5059. case VIEW_USE_2_VIEWPORTS: {
  5060. dragging_h = false;
  5061. } break;
  5062. case VIEW_USE_2_VIEWPORTS_ALT: {
  5063. dragging_v = false;
  5064. } break;
  5065. case VIEW_USE_3_VIEWPORTS:
  5066. case VIEW_USE_3_VIEWPORTS_ALT:
  5067. case VIEW_USE_4_VIEWPORTS: {
  5068. // Do nothing.
  5069. } break;
  5070. }
  5071. } else {
  5072. dragging_h = false;
  5073. dragging_v = false;
  5074. }
  5075. }
  5076. Ref<InputEventMouseMotion> mm = p_event;
  5077. if (mm.is_valid()) {
  5078. if (view == VIEW_USE_3_VIEWPORTS || view == VIEW_USE_3_VIEWPORTS_ALT || view == VIEW_USE_4_VIEWPORTS) {
  5079. Vector2 size = get_size();
  5080. int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
  5081. int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
  5082. int mid_w = size.width * ratio_h;
  5083. int mid_h = size.height * ratio_v;
  5084. bool was_hovering_h = hovering_h;
  5085. bool was_hovering_v = hovering_v;
  5086. hovering_h = mm->get_position().x > (mid_w - h_sep / 2) && mm->get_position().x < (mid_w + h_sep / 2);
  5087. hovering_v = mm->get_position().y > (mid_h - v_sep / 2) && mm->get_position().y < (mid_h + v_sep / 2);
  5088. if (was_hovering_h != hovering_h || was_hovering_v != hovering_v) {
  5089. queue_redraw();
  5090. }
  5091. }
  5092. if (dragging_h) {
  5093. real_t new_ratio = drag_begin_ratio.x + (mm->get_position().x - drag_begin_pos.x) / get_size().width;
  5094. new_ratio = CLAMP(new_ratio, 40 / get_size().width, (get_size().width - 40) / get_size().width);
  5095. ratio_h = new_ratio;
  5096. queue_sort();
  5097. queue_redraw();
  5098. }
  5099. if (dragging_v) {
  5100. real_t new_ratio = drag_begin_ratio.y + (mm->get_position().y - drag_begin_pos.y) / get_size().height;
  5101. new_ratio = CLAMP(new_ratio, 40 / get_size().height, (get_size().height - 40) / get_size().height);
  5102. ratio_v = new_ratio;
  5103. queue_sort();
  5104. queue_redraw();
  5105. }
  5106. }
  5107. }
  5108. void Node3DEditorViewportContainer::_notification(int p_what) {
  5109. switch (p_what) {
  5110. case NOTIFICATION_MOUSE_ENTER:
  5111. case NOTIFICATION_MOUSE_EXIT: {
  5112. mouseover = (p_what == NOTIFICATION_MOUSE_ENTER);
  5113. queue_redraw();
  5114. } break;
  5115. case NOTIFICATION_DRAW: {
  5116. if (mouseover) {
  5117. Ref<Texture2D> h_grabber = get_theme_icon(SNAME("grabber"), SNAME("HSplitContainer"));
  5118. Ref<Texture2D> v_grabber = get_theme_icon(SNAME("grabber"), SNAME("VSplitContainer"));
  5119. Ref<Texture2D> hdiag_grabber = get_editor_theme_icon(SNAME("GuiViewportHdiagsplitter"));
  5120. Ref<Texture2D> vdiag_grabber = get_editor_theme_icon(SNAME("GuiViewportVdiagsplitter"));
  5121. Ref<Texture2D> vh_grabber = get_editor_theme_icon(SNAME("GuiViewportVhsplitter"));
  5122. Vector2 size = get_size();
  5123. int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
  5124. int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
  5125. int mid_w = size.width * ratio_h;
  5126. int mid_h = size.height * ratio_v;
  5127. int size_left = mid_w - h_sep / 2;
  5128. int size_bottom = size.height - mid_h - v_sep / 2;
  5129. switch (view) {
  5130. case VIEW_USE_1_VIEWPORT: {
  5131. // Nothing to show.
  5132. } break;
  5133. case VIEW_USE_2_VIEWPORTS: {
  5134. draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  5135. set_default_cursor_shape(CURSOR_VSPLIT);
  5136. } break;
  5137. case VIEW_USE_2_VIEWPORTS_ALT: {
  5138. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
  5139. set_default_cursor_shape(CURSOR_HSPLIT);
  5140. } break;
  5141. case VIEW_USE_3_VIEWPORTS: {
  5142. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  5143. draw_texture(hdiag_grabber, Vector2(mid_w - hdiag_grabber->get_width() / 2, mid_h - v_grabber->get_height() / 4));
  5144. set_default_cursor_shape(CURSOR_DRAG);
  5145. } else if ((hovering_v && !dragging_h) || dragging_v) {
  5146. draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  5147. set_default_cursor_shape(CURSOR_VSPLIT);
  5148. } else if (hovering_h || dragging_h) {
  5149. 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));
  5150. set_default_cursor_shape(CURSOR_HSPLIT);
  5151. }
  5152. } break;
  5153. case VIEW_USE_3_VIEWPORTS_ALT: {
  5154. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  5155. draw_texture(vdiag_grabber, Vector2(mid_w - vdiag_grabber->get_width() + v_grabber->get_height() / 4, mid_h - vdiag_grabber->get_height() / 2));
  5156. set_default_cursor_shape(CURSOR_DRAG);
  5157. } else if ((hovering_v && !dragging_h) || dragging_v) {
  5158. draw_texture(v_grabber, Vector2((size_left - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
  5159. set_default_cursor_shape(CURSOR_VSPLIT);
  5160. } else if (hovering_h || dragging_h) {
  5161. draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
  5162. set_default_cursor_shape(CURSOR_HSPLIT);
  5163. }
  5164. } break;
  5165. case VIEW_USE_4_VIEWPORTS: {
  5166. Vector2 half(mid_w, mid_h);
  5167. if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
  5168. draw_texture(vh_grabber, half - vh_grabber->get_size() / 2.0);
  5169. set_default_cursor_shape(CURSOR_DRAG);
  5170. } else if ((hovering_v && !dragging_h) || dragging_v) {
  5171. draw_texture(v_grabber, half - v_grabber->get_size() / 2.0);
  5172. set_default_cursor_shape(CURSOR_VSPLIT);
  5173. } else if (hovering_h || dragging_h) {
  5174. draw_texture(h_grabber, half - h_grabber->get_size() / 2.0);
  5175. set_default_cursor_shape(CURSOR_HSPLIT);
  5176. }
  5177. } break;
  5178. }
  5179. }
  5180. } break;
  5181. case NOTIFICATION_SORT_CHILDREN: {
  5182. Node3DEditorViewport *viewports[4];
  5183. int vc = 0;
  5184. for (int i = 0; i < get_child_count(); i++) {
  5185. viewports[vc] = Object::cast_to<Node3DEditorViewport>(get_child(i));
  5186. if (viewports[vc]) {
  5187. vc++;
  5188. }
  5189. }
  5190. ERR_FAIL_COND(vc != 4);
  5191. Size2 size = get_size();
  5192. if (size.x < 10 || size.y < 10) {
  5193. for (int i = 0; i < 4; i++) {
  5194. viewports[i]->hide();
  5195. }
  5196. return;
  5197. }
  5198. int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
  5199. int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
  5200. int mid_w = size.width * ratio_h;
  5201. int mid_h = size.height * ratio_v;
  5202. int size_left = mid_w - h_sep / 2;
  5203. int size_right = size.width - mid_w - h_sep / 2;
  5204. int size_top = mid_h - v_sep / 2;
  5205. int size_bottom = size.height - mid_h - v_sep / 2;
  5206. switch (view) {
  5207. case VIEW_USE_1_VIEWPORT: {
  5208. viewports[0]->show();
  5209. for (int i = 1; i < 4; i++) {
  5210. viewports[i]->hide();
  5211. }
  5212. fit_child_in_rect(viewports[0], Rect2(Vector2(), size));
  5213. } break;
  5214. case VIEW_USE_2_VIEWPORTS: {
  5215. for (int i = 0; i < 4; i++) {
  5216. if (i == 1 || i == 3) {
  5217. viewports[i]->hide();
  5218. } else {
  5219. viewports[i]->show();
  5220. }
  5221. }
  5222. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
  5223. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size.width, size_bottom)));
  5224. } break;
  5225. case VIEW_USE_2_VIEWPORTS_ALT: {
  5226. for (int i = 0; i < 4; i++) {
  5227. if (i == 1 || i == 3) {
  5228. viewports[i]->hide();
  5229. } else {
  5230. viewports[i]->show();
  5231. }
  5232. }
  5233. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size.height)));
  5234. fit_child_in_rect(viewports[2], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
  5235. } break;
  5236. case VIEW_USE_3_VIEWPORTS: {
  5237. for (int i = 0; i < 4; i++) {
  5238. if (i == 1) {
  5239. viewports[i]->hide();
  5240. } else {
  5241. viewports[i]->show();
  5242. }
  5243. }
  5244. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
  5245. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  5246. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
  5247. } break;
  5248. case VIEW_USE_3_VIEWPORTS_ALT: {
  5249. for (int i = 0; i < 4; i++) {
  5250. if (i == 1) {
  5251. viewports[i]->hide();
  5252. } else {
  5253. viewports[i]->show();
  5254. }
  5255. }
  5256. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
  5257. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  5258. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
  5259. } break;
  5260. case VIEW_USE_4_VIEWPORTS: {
  5261. for (int i = 0; i < 4; i++) {
  5262. viewports[i]->show();
  5263. }
  5264. fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
  5265. fit_child_in_rect(viewports[1], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size_top)));
  5266. fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
  5267. fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
  5268. } break;
  5269. }
  5270. } break;
  5271. }
  5272. }
  5273. void Node3DEditorViewportContainer::set_view(View p_view) {
  5274. view = p_view;
  5275. queue_sort();
  5276. }
  5277. Node3DEditorViewportContainer::View Node3DEditorViewportContainer::get_view() {
  5278. return view;
  5279. }
  5280. Node3DEditorViewportContainer::Node3DEditorViewportContainer() {
  5281. set_clip_contents(true);
  5282. view = VIEW_USE_1_VIEWPORT;
  5283. mouseover = false;
  5284. ratio_h = 0.5;
  5285. ratio_v = 0.5;
  5286. hovering_v = false;
  5287. hovering_h = false;
  5288. dragging_v = false;
  5289. dragging_h = false;
  5290. }
  5291. ///////////////////////////////////////////////////////////////////
  5292. Node3DEditor *Node3DEditor::singleton = nullptr;
  5293. Node3DEditorSelectedItem::~Node3DEditorSelectedItem() {
  5294. ERR_FAIL_NULL(RenderingServer::get_singleton());
  5295. if (sbox_instance.is_valid()) {
  5296. RenderingServer::get_singleton()->free(sbox_instance);
  5297. }
  5298. if (sbox_instance_offset.is_valid()) {
  5299. RenderingServer::get_singleton()->free(sbox_instance_offset);
  5300. }
  5301. if (sbox_instance_xray.is_valid()) {
  5302. RenderingServer::get_singleton()->free(sbox_instance_xray);
  5303. }
  5304. if (sbox_instance_xray_offset.is_valid()) {
  5305. RenderingServer::get_singleton()->free(sbox_instance_xray_offset);
  5306. }
  5307. }
  5308. void Node3DEditor::select_gizmo_highlight_axis(int p_axis) {
  5309. for (int i = 0; i < 3; i++) {
  5310. move_gizmo[i]->surface_set_material(0, i == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  5311. move_plane_gizmo[i]->surface_set_material(0, (i + 6) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
  5312. rotate_gizmo[i]->surface_set_material(0, (i + 3) == p_axis ? rotate_gizmo_color_hl[i] : rotate_gizmo_color[i]);
  5313. scale_gizmo[i]->surface_set_material(0, (i + 9) == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
  5314. scale_plane_gizmo[i]->surface_set_material(0, (i + 12) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
  5315. }
  5316. }
  5317. void Node3DEditor::update_transform_gizmo() {
  5318. int count = 0;
  5319. bool local_gizmo_coords = are_local_coords_enabled();
  5320. Vector3 gizmo_center;
  5321. Basis gizmo_basis;
  5322. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  5323. if (se && se->gizmo.is_valid()) {
  5324. for (const KeyValue<int, Transform3D> &E : se->subgizmos) {
  5325. Transform3D xf = se->sp->get_global_transform() * se->gizmo->get_subgizmo_transform(E.key);
  5326. gizmo_center += xf.origin;
  5327. if ((unsigned int)count == se->subgizmos.size() - 1 && local_gizmo_coords) {
  5328. gizmo_basis = xf.basis;
  5329. }
  5330. count++;
  5331. }
  5332. } else {
  5333. List<Node *> &selection = editor_selection->get_selected_node_list();
  5334. for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
  5335. Node3D *sp = Object::cast_to<Node3D>(E->get());
  5336. if (!sp) {
  5337. continue;
  5338. }
  5339. if (sp->has_meta("_edit_lock_")) {
  5340. continue;
  5341. }
  5342. Node3DEditorSelectedItem *sel_item = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  5343. if (!sel_item) {
  5344. continue;
  5345. }
  5346. Transform3D xf = sel_item->sp->get_global_transform();
  5347. gizmo_center += xf.origin;
  5348. if (count == selection.size() - 1 && local_gizmo_coords) {
  5349. gizmo_basis = xf.basis;
  5350. }
  5351. count++;
  5352. }
  5353. }
  5354. gizmo.visible = count > 0;
  5355. gizmo.transform.origin = (count > 0) ? gizmo_center / count : Vector3();
  5356. gizmo.transform.basis = gizmo_basis;
  5357. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  5358. viewports[i]->update_transform_gizmo_view();
  5359. }
  5360. }
  5361. void _update_all_gizmos(Node *p_node) {
  5362. for (int i = p_node->get_child_count() - 1; 0 <= i; --i) {
  5363. Node3D *spatial_node = Object::cast_to<Node3D>(p_node->get_child(i));
  5364. if (spatial_node) {
  5365. spatial_node->update_gizmos();
  5366. }
  5367. _update_all_gizmos(p_node->get_child(i));
  5368. }
  5369. }
  5370. void Node3DEditor::update_all_gizmos(Node *p_node) {
  5371. if (!p_node && is_inside_tree()) {
  5372. p_node = get_tree()->get_edited_scene_root();
  5373. }
  5374. if (!p_node) {
  5375. // No edited scene, so nothing to update.
  5376. return;
  5377. }
  5378. _update_all_gizmos(p_node);
  5379. }
  5380. Object *Node3DEditor::_get_editor_data(Object *p_what) {
  5381. Node3D *sp = Object::cast_to<Node3D>(p_what);
  5382. if (!sp) {
  5383. return nullptr;
  5384. }
  5385. Node3DEditorSelectedItem *si = memnew(Node3DEditorSelectedItem);
  5386. si->sp = sp;
  5387. si->sbox_instance = RenderingServer::get_singleton()->instance_create2(
  5388. selection_box->get_rid(),
  5389. sp->get_world_3d()->get_scenario());
  5390. si->sbox_instance_offset = RenderingServer::get_singleton()->instance_create2(
  5391. selection_box->get_rid(),
  5392. sp->get_world_3d()->get_scenario());
  5393. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  5394. si->sbox_instance,
  5395. RS::SHADOW_CASTING_SETTING_OFF);
  5396. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  5397. si->sbox_instance_offset,
  5398. RS::SHADOW_CASTING_SETTING_OFF);
  5399. // Use the Edit layer to hide the selection box when View Gizmos is disabled, since it is a bit distracting.
  5400. // It's still possible to approximately guess what is selected by looking at the manipulation gizmo position.
  5401. RS::get_singleton()->instance_set_layer_mask(si->sbox_instance, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
  5402. RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_offset, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
  5403. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  5404. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  5405. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_offset, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  5406. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_offset, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  5407. si->sbox_instance_xray = RenderingServer::get_singleton()->instance_create2(
  5408. selection_box_xray->get_rid(),
  5409. sp->get_world_3d()->get_scenario());
  5410. si->sbox_instance_xray_offset = RenderingServer::get_singleton()->instance_create2(
  5411. selection_box_xray->get_rid(),
  5412. sp->get_world_3d()->get_scenario());
  5413. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  5414. si->sbox_instance_xray,
  5415. RS::SHADOW_CASTING_SETTING_OFF);
  5416. RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
  5417. si->sbox_instance_xray_offset,
  5418. RS::SHADOW_CASTING_SETTING_OFF);
  5419. // Use the Edit layer to hide the selection box when View Gizmos is disabled, since it is a bit distracting.
  5420. // It's still possible to approximately guess what is selected by looking at the manipulation gizmo position.
  5421. RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_xray, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
  5422. RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_xray_offset, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
  5423. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  5424. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  5425. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray_offset, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  5426. RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray_offset, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  5427. return si;
  5428. }
  5429. void Node3DEditor::_generate_selection_boxes() {
  5430. // Use two AABBs to create the illusion of a slightly thicker line.
  5431. AABB aabb(Vector3(), Vector3(1, 1, 1));
  5432. // Create a x-ray (visible through solid surfaces) and standard version of the selection box.
  5433. // Both will be drawn at the same position, but with different opacity.
  5434. // This lets the user see where the selection is while still having a sense of depth.
  5435. Ref<SurfaceTool> st = memnew(SurfaceTool);
  5436. Ref<SurfaceTool> st_xray = memnew(SurfaceTool);
  5437. Ref<SurfaceTool> active_st = memnew(SurfaceTool);
  5438. Ref<SurfaceTool> active_st_xray = memnew(SurfaceTool);
  5439. st->begin(Mesh::PRIMITIVE_LINES);
  5440. st_xray->begin(Mesh::PRIMITIVE_LINES);
  5441. active_st->begin(Mesh::PRIMITIVE_LINES);
  5442. active_st_xray->begin(Mesh::PRIMITIVE_LINES);
  5443. for (int i = 0; i < 12; i++) {
  5444. Vector3 a, b;
  5445. aabb.get_edge(i, a, b);
  5446. st->add_vertex(a);
  5447. st->add_vertex(b);
  5448. active_st->add_vertex(a);
  5449. active_st->add_vertex(b);
  5450. st_xray->add_vertex(a);
  5451. st_xray->add_vertex(b);
  5452. active_st_xray->add_vertex(a);
  5453. active_st_xray->add_vertex(b);
  5454. }
  5455. const Color selection_box_color = EDITOR_GET("editors/3d/selection_box_color");
  5456. const Color active_selection_box_color = EDITOR_GET("editors/3d/active_selection_box_color");
  5457. selection_box_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  5458. selection_box_mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  5459. selection_box_mat->set_albedo(selection_box_color);
  5460. selection_box_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  5461. st->set_material(selection_box_mat);
  5462. selection_box = st->commit();
  5463. selection_box_mat_xray->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  5464. selection_box_mat_xray->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  5465. selection_box_mat_xray->set_flag(StandardMaterial3D::FLAG_DISABLE_DEPTH_TEST, true);
  5466. selection_box_mat_xray->set_albedo(selection_box_color * Color(1, 1, 1, 0.15));
  5467. selection_box_mat_xray->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  5468. st_xray->set_material(selection_box_mat_xray);
  5469. selection_box_xray = st_xray->commit();
  5470. active_selection_box_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  5471. active_selection_box_mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  5472. active_selection_box_mat->set_albedo(active_selection_box_color);
  5473. active_selection_box_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  5474. active_st->set_material(active_selection_box_mat);
  5475. active_selection_box = active_st->commit();
  5476. active_selection_box_mat_xray->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  5477. active_selection_box_mat_xray->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  5478. active_selection_box_mat_xray->set_flag(StandardMaterial3D::FLAG_DISABLE_DEPTH_TEST, true);
  5479. active_selection_box_mat_xray->set_albedo(active_selection_box_color * Color(1, 1, 1, 0.15));
  5480. active_selection_box_mat_xray->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  5481. active_st_xray->set_material(active_selection_box_mat_xray);
  5482. active_selection_box_xray = active_st_xray->commit();
  5483. }
  5484. Dictionary Node3DEditor::get_state() const {
  5485. Dictionary d;
  5486. d["snap_enabled"] = snap_enabled;
  5487. d["translate_snap"] = snap_translate_value;
  5488. d["rotate_snap"] = snap_rotate_value;
  5489. d["scale_snap"] = snap_scale_value;
  5490. d["local_coords"] = tool_option_button[TOOL_OPT_LOCAL_COORDS]->is_pressed();
  5491. int vc = 0;
  5492. if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT))) {
  5493. vc = 1;
  5494. } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS))) {
  5495. vc = 2;
  5496. } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS))) {
  5497. vc = 3;
  5498. } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS))) {
  5499. vc = 4;
  5500. } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT))) {
  5501. vc = 5;
  5502. } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT))) {
  5503. vc = 6;
  5504. }
  5505. d["viewport_mode"] = vc;
  5506. Array vpdata;
  5507. for (int i = 0; i < 4; i++) {
  5508. vpdata.push_back(viewports[i]->get_state());
  5509. }
  5510. d["viewports"] = vpdata;
  5511. d["show_grid"] = view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_GRID));
  5512. d["show_origin"] = view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN));
  5513. d["fov"] = get_fov();
  5514. d["znear"] = get_znear();
  5515. d["zfar"] = get_zfar();
  5516. Dictionary gizmos_status;
  5517. for (int i = 0; i < gizmo_plugins_by_name.size(); i++) {
  5518. if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
  5519. continue;
  5520. }
  5521. int state = gizmos_menu->get_item_state(gizmos_menu->get_item_index(i));
  5522. String name = gizmo_plugins_by_name[i]->get_gizmo_name();
  5523. gizmos_status[name] = state;
  5524. }
  5525. d["gizmos_status"] = gizmos_status;
  5526. {
  5527. Dictionary pd;
  5528. pd["sun_rotation"] = sun_rotation;
  5529. pd["environ_sky_color"] = environ_sky_color->get_pick_color();
  5530. pd["environ_ground_color"] = environ_ground_color->get_pick_color();
  5531. pd["environ_energy"] = environ_energy->get_value();
  5532. pd["environ_glow_enabled"] = environ_glow_button->is_pressed();
  5533. pd["environ_tonemap_enabled"] = environ_tonemap_button->is_pressed();
  5534. pd["environ_ao_enabled"] = environ_ao_button->is_pressed();
  5535. pd["environ_gi_enabled"] = environ_gi_button->is_pressed();
  5536. pd["sun_max_distance"] = sun_max_distance->get_value();
  5537. pd["sun_color"] = sun_color->get_pick_color();
  5538. pd["sun_energy"] = sun_energy->get_value();
  5539. pd["sun_enabled"] = sun_button->is_pressed();
  5540. pd["environ_enabled"] = environ_button->is_pressed();
  5541. d["preview_sun_env"] = pd;
  5542. }
  5543. return d;
  5544. }
  5545. void Node3DEditor::set_state(const Dictionary &p_state) {
  5546. Dictionary d = p_state;
  5547. if (d.has("snap_enabled")) {
  5548. snap_enabled = d["snap_enabled"];
  5549. tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(d["snap_enabled"]);
  5550. }
  5551. if (d.has("translate_snap")) {
  5552. snap_translate_value = d["translate_snap"];
  5553. }
  5554. if (d.has("rotate_snap")) {
  5555. snap_rotate_value = d["rotate_snap"];
  5556. }
  5557. if (d.has("scale_snap")) {
  5558. snap_scale_value = d["scale_snap"];
  5559. }
  5560. _snap_update();
  5561. if (d.has("local_coords")) {
  5562. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(d["local_coords"]);
  5563. update_transform_gizmo();
  5564. }
  5565. if (d.has("viewport_mode")) {
  5566. int vc = d["viewport_mode"];
  5567. if (vc == 1) {
  5568. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  5569. } else if (vc == 2) {
  5570. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
  5571. } else if (vc == 3) {
  5572. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
  5573. } else if (vc == 4) {
  5574. _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
  5575. } else if (vc == 5) {
  5576. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
  5577. } else if (vc == 6) {
  5578. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
  5579. }
  5580. }
  5581. if (d.has("viewports")) {
  5582. Array vp = d["viewports"];
  5583. uint32_t vp_size = static_cast<uint32_t>(vp.size());
  5584. if (vp_size > VIEWPORTS_COUNT) {
  5585. WARN_PRINT("Ignoring superfluous viewport settings from spatial editor state.");
  5586. vp_size = VIEWPORTS_COUNT;
  5587. }
  5588. for (uint32_t i = 0; i < vp_size; i++) {
  5589. viewports[i]->set_state(vp[i]);
  5590. }
  5591. }
  5592. if (d.has("zfar")) {
  5593. settings_zfar->set_value(double(d["zfar"]));
  5594. }
  5595. if (d.has("znear")) {
  5596. settings_znear->set_value(double(d["znear"]));
  5597. }
  5598. if (d.has("fov")) {
  5599. settings_fov->set_value(double(d["fov"]));
  5600. }
  5601. if (d.has("show_grid")) {
  5602. bool use = d["show_grid"];
  5603. if (use != view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_GRID))) {
  5604. _menu_item_pressed(MENU_VIEW_GRID);
  5605. }
  5606. }
  5607. if (d.has("show_origin")) {
  5608. bool use = d["show_origin"];
  5609. if (use != view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN))) {
  5610. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), use);
  5611. RenderingServer::get_singleton()->instance_set_visible(origin_instance, use);
  5612. }
  5613. }
  5614. if (d.has("gizmos_status")) {
  5615. Dictionary gizmos_status = d["gizmos_status"];
  5616. for (int j = 0; j < gizmo_plugins_by_name.size(); ++j) {
  5617. if (!gizmo_plugins_by_name[j]->can_be_hidden()) {
  5618. continue;
  5619. }
  5620. int state = EditorNode3DGizmoPlugin::VISIBLE;
  5621. for (const KeyValue<Variant, Variant> &kv : gizmos_status) {
  5622. if (gizmo_plugins_by_name.write[j]->get_gizmo_name() == String(kv.key)) {
  5623. state = kv.value;
  5624. break;
  5625. }
  5626. }
  5627. gizmo_plugins_by_name.write[j]->set_state(state);
  5628. }
  5629. _update_gizmos_menu();
  5630. }
  5631. if (d.has("preview_sun_env")) {
  5632. sun_environ_updating = true;
  5633. Dictionary pd = d["preview_sun_env"];
  5634. sun_rotation = pd["sun_rotation"];
  5635. environ_sky_color->set_pick_color(pd["environ_sky_color"]);
  5636. environ_ground_color->set_pick_color(pd["environ_ground_color"]);
  5637. environ_energy->set_value(pd["environ_energy"]);
  5638. environ_glow_button->set_pressed(pd["environ_glow_enabled"]);
  5639. environ_tonemap_button->set_pressed(pd["environ_tonemap_enabled"]);
  5640. environ_ao_button->set_pressed(pd["environ_ao_enabled"]);
  5641. environ_gi_button->set_pressed(pd["environ_gi_enabled"]);
  5642. sun_max_distance->set_value(pd["sun_max_distance"]);
  5643. sun_color->set_pick_color(pd["sun_color"]);
  5644. sun_energy->set_value(pd["sun_energy"]);
  5645. sun_button->set_pressed(pd["sun_enabled"]);
  5646. environ_button->set_pressed(pd["environ_enabled"]);
  5647. sun_environ_updating = false;
  5648. _preview_settings_changed();
  5649. _update_preview_environment();
  5650. } else {
  5651. _load_default_preview_settings();
  5652. sun_button->set_pressed(true);
  5653. environ_button->set_pressed(true);
  5654. _preview_settings_changed();
  5655. _update_preview_environment();
  5656. }
  5657. }
  5658. void Node3DEditor::edit(Node3D *p_spatial) {
  5659. if (p_spatial != selected) {
  5660. if (selected) {
  5661. Vector<Ref<Node3DGizmo>> gizmos = selected->get_gizmos();
  5662. for (int i = 0; i < gizmos.size(); i++) {
  5663. Ref<EditorNode3DGizmo> seg = gizmos[i];
  5664. if (seg.is_null()) {
  5665. continue;
  5666. }
  5667. seg->set_selected(false);
  5668. }
  5669. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected);
  5670. if (se) {
  5671. se->gizmo.unref();
  5672. se->subgizmos.clear();
  5673. }
  5674. selected->update_gizmos();
  5675. }
  5676. selected = p_spatial;
  5677. current_hover_gizmo = Ref<EditorNode3DGizmo>();
  5678. current_hover_gizmo_handle = -1;
  5679. current_hover_gizmo_handle_secondary = false;
  5680. if (selected) {
  5681. Vector<Ref<Node3DGizmo>> gizmos = selected->get_gizmos();
  5682. for (int i = 0; i < gizmos.size(); i++) {
  5683. Ref<EditorNode3DGizmo> seg = gizmos[i];
  5684. if (seg.is_null()) {
  5685. continue;
  5686. }
  5687. seg->set_selected(true);
  5688. }
  5689. selected->update_gizmos();
  5690. }
  5691. }
  5692. }
  5693. void Node3DEditor::_snap_changed() {
  5694. snap_translate_value = snap_translate->get_text().to_float();
  5695. snap_rotate_value = snap_rotate->get_text().to_float();
  5696. snap_scale_value = snap_scale->get_text().to_float();
  5697. EditorSettings::get_singleton()->set_project_metadata("3d_editor", "snap_translate_value", snap_translate_value);
  5698. EditorSettings::get_singleton()->set_project_metadata("3d_editor", "snap_rotate_value", snap_rotate_value);
  5699. EditorSettings::get_singleton()->set_project_metadata("3d_editor", "snap_scale_value", snap_scale_value);
  5700. }
  5701. void Node3DEditor::_snap_update() {
  5702. double snap = EDITOR_GET("interface/inspector/default_float_step");
  5703. int snap_step_decimals = Math::range_step_decimals(snap);
  5704. snap_translate->set_text(String::num(snap_translate_value, snap_step_decimals));
  5705. snap_rotate->set_text(String::num(snap_rotate_value, snap_step_decimals));
  5706. snap_scale->set_text(String::num(snap_scale_value, snap_step_decimals));
  5707. }
  5708. void Node3DEditor::_xform_dialog_action() {
  5709. Transform3D t;
  5710. //translation
  5711. Vector3 scale;
  5712. Vector3 rotate;
  5713. Vector3 translate;
  5714. for (int i = 0; i < 3; i++) {
  5715. translate[i] = xform_translate[i]->get_text().to_float();
  5716. rotate[i] = Math::deg_to_rad(xform_rotate[i]->get_text().to_float());
  5717. scale[i] = xform_scale[i]->get_text().to_float();
  5718. }
  5719. t.basis.scale(scale);
  5720. t.basis.rotate(rotate);
  5721. t.origin = translate;
  5722. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  5723. undo_redo->create_action(TTR("XForm Dialog"));
  5724. const List<Node *> &selection = editor_selection->get_selected_node_list();
  5725. for (Node *E : selection) {
  5726. Node3D *sp = Object::cast_to<Node3D>(E);
  5727. if (!sp) {
  5728. continue;
  5729. }
  5730. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  5731. if (!se) {
  5732. continue;
  5733. }
  5734. bool post = xform_type->get_selected() > 0;
  5735. Transform3D tr = sp->get_global_gizmo_transform();
  5736. if (post) {
  5737. tr = tr * t;
  5738. } else {
  5739. tr.basis = t.basis * tr.basis;
  5740. tr.origin += t.origin;
  5741. }
  5742. Node3D *parent = sp->get_parent_node_3d();
  5743. Transform3D local_tr = parent ? parent->get_global_transform().affine_inverse() * tr : tr;
  5744. undo_redo->add_do_method(sp, "set_transform", local_tr);
  5745. undo_redo->add_undo_method(sp, "set_transform", sp->get_transform());
  5746. }
  5747. undo_redo->commit_action();
  5748. }
  5749. void Node3DEditor::_menu_item_toggled(bool pressed, int p_option) {
  5750. switch (p_option) {
  5751. case MENU_TOOL_LOCAL_COORDS: {
  5752. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(pressed);
  5753. update_transform_gizmo();
  5754. } break;
  5755. case MENU_TOOL_USE_SNAP: {
  5756. tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(pressed);
  5757. snap_enabled = pressed;
  5758. } break;
  5759. }
  5760. }
  5761. void Node3DEditor::_menu_gizmo_toggled(int p_option) {
  5762. const int idx = gizmos_menu->get_item_index(p_option);
  5763. gizmos_menu->toggle_item_multistate(idx);
  5764. // Change icon
  5765. const int state = gizmos_menu->get_item_state(idx);
  5766. switch (state) {
  5767. case EditorNode3DGizmoPlugin::VISIBLE:
  5768. gizmos_menu->set_item_icon(idx, view_layout_menu->get_popup()->get_theme_icon(SNAME("visibility_visible")));
  5769. break;
  5770. case EditorNode3DGizmoPlugin::ON_TOP:
  5771. gizmos_menu->set_item_icon(idx, view_layout_menu->get_popup()->get_theme_icon(SNAME("visibility_xray")));
  5772. break;
  5773. case EditorNode3DGizmoPlugin::HIDDEN:
  5774. gizmos_menu->set_item_icon(idx, view_layout_menu->get_popup()->get_theme_icon(SNAME("visibility_hidden")));
  5775. break;
  5776. }
  5777. gizmo_plugins_by_name.write[p_option]->set_state(state);
  5778. update_all_gizmos();
  5779. }
  5780. void Node3DEditor::_menu_item_pressed(int p_option) {
  5781. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  5782. switch (p_option) {
  5783. case MENU_TOOL_SELECT:
  5784. case MENU_TOOL_MOVE:
  5785. case MENU_TOOL_ROTATE:
  5786. case MENU_TOOL_SCALE:
  5787. case MENU_TOOL_LIST_SELECT: {
  5788. for (int i = 0; i < TOOL_MAX; i++) {
  5789. tool_button[i]->set_pressed(i == p_option);
  5790. }
  5791. tool_mode = (ToolMode)p_option;
  5792. update_transform_gizmo();
  5793. } break;
  5794. case MENU_TRANSFORM_CONFIGURE_SNAP: {
  5795. snap_dialog->popup_centered(Size2(200, 180));
  5796. } break;
  5797. case MENU_TRANSFORM_DIALOG: {
  5798. for (int i = 0; i < 3; i++) {
  5799. xform_translate[i]->set_text("0");
  5800. xform_rotate[i]->set_text("0");
  5801. xform_scale[i]->set_text("1");
  5802. }
  5803. xform_dialog->popup_centered(Size2(320, 240) * EDSCALE);
  5804. } break;
  5805. case MENU_VIEW_USE_1_VIEWPORT: {
  5806. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_1_VIEWPORT);
  5807. if (last_used_viewport > 0) {
  5808. last_used_viewport = 0;
  5809. }
  5810. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), true);
  5811. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  5812. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  5813. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  5814. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  5815. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  5816. } break;
  5817. case MENU_VIEW_USE_2_VIEWPORTS: {
  5818. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_2_VIEWPORTS);
  5819. if (last_used_viewport > 1) {
  5820. last_used_viewport = 0;
  5821. }
  5822. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  5823. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), true);
  5824. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  5825. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  5826. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  5827. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  5828. } break;
  5829. case MENU_VIEW_USE_2_VIEWPORTS_ALT: {
  5830. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_2_VIEWPORTS_ALT);
  5831. if (last_used_viewport > 1) {
  5832. last_used_viewport = 0;
  5833. }
  5834. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  5835. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  5836. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  5837. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  5838. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), true);
  5839. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  5840. } break;
  5841. case MENU_VIEW_USE_3_VIEWPORTS: {
  5842. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_3_VIEWPORTS);
  5843. if (last_used_viewport > 2) {
  5844. last_used_viewport = 0;
  5845. }
  5846. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  5847. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  5848. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), true);
  5849. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  5850. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  5851. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  5852. } break;
  5853. case MENU_VIEW_USE_3_VIEWPORTS_ALT: {
  5854. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_3_VIEWPORTS_ALT);
  5855. if (last_used_viewport > 2) {
  5856. last_used_viewport = 0;
  5857. }
  5858. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  5859. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  5860. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  5861. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
  5862. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  5863. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), true);
  5864. } break;
  5865. case MENU_VIEW_USE_4_VIEWPORTS: {
  5866. viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_4_VIEWPORTS);
  5867. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
  5868. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
  5869. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
  5870. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), true);
  5871. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
  5872. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
  5873. } break;
  5874. case MENU_VIEW_ORIGIN: {
  5875. bool is_checked = view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(p_option));
  5876. origin_enabled = !is_checked;
  5877. RenderingServer::get_singleton()->instance_set_visible(origin_instance, origin_enabled);
  5878. // Update the grid since its appearance depends on whether the origin is enabled
  5879. _finish_grid();
  5880. _init_grid();
  5881. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(p_option), origin_enabled);
  5882. } break;
  5883. case MENU_VIEW_GRID: {
  5884. bool is_checked = view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(p_option));
  5885. grid_enabled = !is_checked;
  5886. for (int i = 0; i < 3; ++i) {
  5887. if (grid_enable[i]) {
  5888. grid_visible[i] = grid_enabled;
  5889. }
  5890. }
  5891. _finish_grid();
  5892. _init_grid();
  5893. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(p_option), grid_enabled);
  5894. } break;
  5895. case MENU_VIEW_CAMERA_SETTINGS: {
  5896. settings_dialog->popup_centered(settings_vbc->get_combined_minimum_size() + Size2(50, 50));
  5897. } break;
  5898. case MENU_SNAP_TO_FLOOR: {
  5899. snap_selected_nodes_to_floor();
  5900. } break;
  5901. case MENU_LOCK_SELECTED: {
  5902. undo_redo->create_action(TTR("Lock Selected"));
  5903. List<Node *> &selection = editor_selection->get_selected_node_list();
  5904. for (Node *E : selection) {
  5905. Node3D *spatial = Object::cast_to<Node3D>(E);
  5906. if (!spatial || !spatial->is_inside_tree()) {
  5907. continue;
  5908. }
  5909. undo_redo->add_do_method(spatial, "set_meta", "_edit_lock_", true);
  5910. undo_redo->add_undo_method(spatial, "remove_meta", "_edit_lock_");
  5911. undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
  5912. undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
  5913. }
  5914. undo_redo->add_do_method(this, "_refresh_menu_icons");
  5915. undo_redo->add_undo_method(this, "_refresh_menu_icons");
  5916. undo_redo->commit_action();
  5917. } break;
  5918. case MENU_UNLOCK_SELECTED: {
  5919. undo_redo->create_action(TTR("Unlock Selected"));
  5920. List<Node *> &selection = editor_selection->get_selected_node_list();
  5921. for (Node *E : selection) {
  5922. Node3D *spatial = Object::cast_to<Node3D>(E);
  5923. if (!spatial || !spatial->is_inside_tree()) {
  5924. continue;
  5925. }
  5926. undo_redo->add_do_method(spatial, "remove_meta", "_edit_lock_");
  5927. undo_redo->add_undo_method(spatial, "set_meta", "_edit_lock_", true);
  5928. undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
  5929. undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
  5930. }
  5931. undo_redo->add_do_method(this, "_refresh_menu_icons");
  5932. undo_redo->add_undo_method(this, "_refresh_menu_icons");
  5933. undo_redo->commit_action();
  5934. } break;
  5935. case MENU_GROUP_SELECTED: {
  5936. undo_redo->create_action(TTR("Group Selected"));
  5937. List<Node *> &selection = editor_selection->get_selected_node_list();
  5938. for (Node *E : selection) {
  5939. Node3D *spatial = Object::cast_to<Node3D>(E);
  5940. if (!spatial || !spatial->is_inside_tree()) {
  5941. continue;
  5942. }
  5943. undo_redo->add_do_method(spatial, "set_meta", "_edit_group_", true);
  5944. undo_redo->add_undo_method(spatial, "remove_meta", "_edit_group_");
  5945. undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
  5946. undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
  5947. }
  5948. undo_redo->add_do_method(this, "_refresh_menu_icons");
  5949. undo_redo->add_undo_method(this, "_refresh_menu_icons");
  5950. undo_redo->commit_action();
  5951. } break;
  5952. case MENU_UNGROUP_SELECTED: {
  5953. undo_redo->create_action(TTR("Ungroup Selected"));
  5954. List<Node *> &selection = editor_selection->get_selected_node_list();
  5955. for (Node *E : selection) {
  5956. Node3D *spatial = Object::cast_to<Node3D>(E);
  5957. if (!spatial || !spatial->is_inside_tree()) {
  5958. continue;
  5959. }
  5960. undo_redo->add_do_method(spatial, "remove_meta", "_edit_group_");
  5961. undo_redo->add_undo_method(spatial, "set_meta", "_edit_group_", true);
  5962. undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
  5963. undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
  5964. }
  5965. undo_redo->add_do_method(this, "_refresh_menu_icons");
  5966. undo_redo->add_undo_method(this, "_refresh_menu_icons");
  5967. undo_redo->commit_action();
  5968. } break;
  5969. case MENU_RULER: {
  5970. for (int i = 0; i < TOOL_MAX; i++) {
  5971. tool_button[i]->set_pressed(i == p_option);
  5972. }
  5973. tool_button[TOOL_RULER]->set_pressed(true);
  5974. tool_mode = ToolMode::TOOL_RULER;
  5975. update_transform_gizmo();
  5976. } break;
  5977. }
  5978. }
  5979. void Node3DEditor::_init_indicators() {
  5980. {
  5981. origin_enabled = true;
  5982. grid_enabled = true;
  5983. Ref<Shader> origin_shader = memnew(Shader);
  5984. origin_shader->set_code(R"(
  5985. // 3D editor origin line shader.
  5986. shader_type spatial;
  5987. render_mode blend_mix, cull_disabled, unshaded, fog_disabled;
  5988. void vertex() {
  5989. vec3 point_a = MODEL_MATRIX[3].xyz;
  5990. // Encoded in scale.
  5991. vec3 point_b = vec3(MODEL_MATRIX[0].x, MODEL_MATRIX[1].y, MODEL_MATRIX[2].z);
  5992. // Points are already in world space, so no need for MODEL_MATRIX anymore.
  5993. vec4 clip_a = PROJECTION_MATRIX * (VIEW_MATRIX * vec4(point_a, 1.0));
  5994. vec4 clip_b = PROJECTION_MATRIX * (VIEW_MATRIX * vec4(point_b, 1.0));
  5995. vec2 screen_a = VIEWPORT_SIZE * (0.5 * clip_a.xy / clip_a.w + 0.5);
  5996. vec2 screen_b = VIEWPORT_SIZE * (0.5 * clip_b.xy / clip_b.w + 0.5);
  5997. vec2 x_basis = normalize(screen_b - screen_a);
  5998. vec2 y_basis = vec2(-x_basis.y, x_basis.x);
  5999. float width = 3.0;
  6000. vec2 screen_point_a = screen_a + width * (VERTEX.x * x_basis + VERTEX.y * y_basis);
  6001. vec2 screen_point_b = screen_b + width * (VERTEX.x * x_basis + VERTEX.y * y_basis);
  6002. vec2 screen_point_final = mix(screen_point_a, screen_point_b, VERTEX.z);
  6003. vec4 clip_final = mix(clip_a, clip_b, VERTEX.z);
  6004. POSITION = vec4(clip_final.w * ((2.0 * screen_point_final) / VIEWPORT_SIZE - 1.0), clip_final.z, clip_final.w);
  6005. UV = VERTEX.yz * clip_final.w;
  6006. if (!OUTPUT_IS_SRGB) {
  6007. 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)));
  6008. }
  6009. }
  6010. void fragment() {
  6011. // Multiply by 0.5 since UV is actually UV is [-1, 1].
  6012. float line_width = fwidth(UV.x * 0.5);
  6013. float line_uv = abs(UV.x * 0.5);
  6014. float line = smoothstep(line_width * 1.0, line_width * 0.25, line_uv);
  6015. ALBEDO = COLOR.rgb;
  6016. ALPHA *= COLOR.a * line;
  6017. }
  6018. )");
  6019. origin_mat.instantiate();
  6020. origin_mat->set_shader(origin_shader);
  6021. Vector<Vector3> origin_points;
  6022. origin_points.resize(6);
  6023. origin_points.set(0, Vector3(0.0, -0.5, 0.0));
  6024. origin_points.set(1, Vector3(0.0, -0.5, 1.0));
  6025. origin_points.set(2, Vector3(0.0, 0.5, 1.0));
  6026. origin_points.set(3, Vector3(0.0, -0.5, 0.0));
  6027. origin_points.set(4, Vector3(0.0, 0.5, 1.0));
  6028. origin_points.set(5, Vector3(0.0, 0.5, 0.0));
  6029. Array d;
  6030. d.resize(RS::ARRAY_MAX);
  6031. d[RenderingServer::ARRAY_VERTEX] = origin_points;
  6032. origin_mesh = RenderingServer::get_singleton()->mesh_create();
  6033. RenderingServer::get_singleton()->mesh_add_surface_from_arrays(origin_mesh, RenderingServer::PRIMITIVE_TRIANGLES, d);
  6034. RenderingServer::get_singleton()->mesh_surface_set_material(origin_mesh, 0, origin_mat->get_rid());
  6035. origin_multimesh = RenderingServer::get_singleton()->multimesh_create();
  6036. RenderingServer::get_singleton()->multimesh_set_mesh(origin_multimesh, origin_mesh);
  6037. RenderingServer::get_singleton()->multimesh_allocate_data(origin_multimesh, 12, RS::MultimeshTransformFormat::MULTIMESH_TRANSFORM_3D, true, false);
  6038. RenderingServer::get_singleton()->multimesh_set_visible_instances(origin_multimesh, -1);
  6039. LocalVector<float> distances;
  6040. distances.resize(5);
  6041. distances[0] = -1000000.0;
  6042. distances[1] = -1000.0;
  6043. distances[2] = 0.0;
  6044. distances[3] = 1000.0;
  6045. distances[4] = 1000000.0;
  6046. for (int i = 0; i < 3; i++) {
  6047. Color origin_color;
  6048. switch (i) {
  6049. case 0:
  6050. origin_color = get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor));
  6051. break;
  6052. case 1:
  6053. origin_color = get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor));
  6054. break;
  6055. case 2:
  6056. origin_color = get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor));
  6057. break;
  6058. default:
  6059. origin_color = Color();
  6060. break;
  6061. }
  6062. Vector3 axis;
  6063. axis[i] = 1;
  6064. for (int j = 0; j < 4; j++) {
  6065. Transform3D t = Transform3D();
  6066. if (distances[j] > 0.0) {
  6067. t = t.scaled(axis * distances[j + 1]);
  6068. t = t.translated(axis * distances[j]);
  6069. } else {
  6070. t = t.scaled(axis * distances[j]);
  6071. t = t.translated(axis * distances[j + 1]);
  6072. }
  6073. RenderingServer::get_singleton()->multimesh_instance_set_transform(origin_multimesh, i * 4 + j, t);
  6074. RenderingServer::get_singleton()->multimesh_instance_set_color(origin_multimesh, i * 4 + j, origin_color);
  6075. }
  6076. }
  6077. origin_instance = RenderingServer::get_singleton()->instance_create2(origin_multimesh, get_tree()->get_root()->get_world_3d()->get_scenario());
  6078. RS::get_singleton()->instance_set_layer_mask(origin_instance, 1 << Node3DEditorViewport::GIZMO_GRID_LAYER);
  6079. RS::get_singleton()->instance_geometry_set_flag(origin_instance, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  6080. RS::get_singleton()->instance_geometry_set_flag(origin_instance, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  6081. RenderingServer::get_singleton()->instance_geometry_set_cast_shadows_setting(origin_instance, RS::SHADOW_CASTING_SETTING_OFF);
  6082. Ref<Shader> grid_shader = memnew(Shader);
  6083. grid_shader->set_code(R"(
  6084. // 3D editor grid shader.
  6085. shader_type spatial;
  6086. render_mode unshaded, fog_disabled;
  6087. uniform bool orthogonal;
  6088. uniform float grid_size;
  6089. void vertex() {
  6090. // From FLAG_SRGB_VERTEX_COLOR.
  6091. if (!OUTPUT_IS_SRGB) {
  6092. 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)));
  6093. }
  6094. }
  6095. void fragment() {
  6096. ALBEDO = COLOR.rgb;
  6097. vec3 dir = orthogonal ? -vec3(0, 0, 1) : VIEW;
  6098. float angle_fade = abs(dot(dir, NORMAL));
  6099. angle_fade = smoothstep(0.05, 0.2, angle_fade);
  6100. vec3 world_pos = (INV_VIEW_MATRIX * vec4(VERTEX, 1.0)).xyz;
  6101. vec3 world_normal = (INV_VIEW_MATRIX * vec4(NORMAL, 0.0)).xyz;
  6102. vec3 camera_world_pos = INV_VIEW_MATRIX[3].xyz;
  6103. vec3 camera_world_pos_on_plane = camera_world_pos * (1.0 - world_normal);
  6104. float dist_fade = 1.0 - (distance(world_pos, camera_world_pos_on_plane) / grid_size);
  6105. dist_fade = smoothstep(0.02, 0.3, dist_fade);
  6106. ALPHA = COLOR.a * dist_fade * angle_fade;
  6107. }
  6108. )");
  6109. for (int i = 0; i < 3; i++) {
  6110. grid_mat[i].instantiate();
  6111. grid_mat[i]->set_shader(grid_shader);
  6112. }
  6113. grid_enable[0] = EDITOR_GET("editors/3d/grid_xy_plane");
  6114. grid_enable[1] = EDITOR_GET("editors/3d/grid_yz_plane");
  6115. grid_enable[2] = EDITOR_GET("editors/3d/grid_xz_plane");
  6116. grid_visible[0] = grid_enable[0];
  6117. grid_visible[1] = grid_enable[1];
  6118. grid_visible[2] = grid_enable[2];
  6119. _init_grid();
  6120. }
  6121. {
  6122. //move gizmo
  6123. // Inverted zxy.
  6124. Vector3 ivec = Vector3(0, 0, -1);
  6125. Vector3 nivec = Vector3(-1, -1, 0);
  6126. Vector3 ivec2 = Vector3(-1, 0, 0);
  6127. Vector3 ivec3 = Vector3(0, -1, 0);
  6128. for (int i = 0; i < 3; i++) {
  6129. Color col;
  6130. switch (i) {
  6131. case 0:
  6132. col = get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor));
  6133. break;
  6134. case 1:
  6135. col = get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor));
  6136. break;
  6137. case 2:
  6138. col = get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor));
  6139. break;
  6140. default:
  6141. col = Color();
  6142. break;
  6143. }
  6144. col.a = EDITOR_GET("editors/3d/manipulator_gizmo_opacity");
  6145. move_gizmo[i].instantiate();
  6146. move_plane_gizmo[i].instantiate();
  6147. rotate_gizmo[i].instantiate();
  6148. scale_gizmo[i].instantiate();
  6149. scale_plane_gizmo[i].instantiate();
  6150. axis_gizmo[i].instantiate();
  6151. Ref<StandardMaterial3D> mat = memnew(StandardMaterial3D);
  6152. mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  6153. mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  6154. mat->set_on_top_of_alpha();
  6155. mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  6156. mat->set_albedo(col);
  6157. gizmo_color[i] = mat;
  6158. Ref<StandardMaterial3D> mat_hl = mat->duplicate();
  6159. const Color albedo = col.from_hsv(col.get_h(), 0.25, 1.0, 1);
  6160. mat_hl->set_albedo(albedo);
  6161. gizmo_color_hl[i] = mat_hl;
  6162. //translate
  6163. {
  6164. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  6165. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  6166. // Arrow profile
  6167. const int arrow_points = 5;
  6168. Vector3 arrow[5] = {
  6169. nivec * 0.0 + ivec * 0.0,
  6170. nivec * 0.01 + ivec * 0.0,
  6171. nivec * 0.01 + ivec * GIZMO_ARROW_OFFSET,
  6172. nivec * 0.065 + ivec * GIZMO_ARROW_OFFSET,
  6173. nivec * 0.0 + ivec * (GIZMO_ARROW_OFFSET + GIZMO_ARROW_SIZE),
  6174. };
  6175. int arrow_sides = 16;
  6176. const real_t arrow_sides_step = Math_TAU / arrow_sides;
  6177. for (int k = 0; k < arrow_sides; k++) {
  6178. Basis ma(ivec, k * arrow_sides_step);
  6179. Basis mb(ivec, (k + 1) * arrow_sides_step);
  6180. for (int j = 0; j < arrow_points - 1; j++) {
  6181. Vector3 points[4] = {
  6182. ma.xform(arrow[j]),
  6183. mb.xform(arrow[j]),
  6184. mb.xform(arrow[j + 1]),
  6185. ma.xform(arrow[j + 1]),
  6186. };
  6187. surftool->add_vertex(points[0]);
  6188. surftool->add_vertex(points[1]);
  6189. surftool->add_vertex(points[2]);
  6190. surftool->add_vertex(points[0]);
  6191. surftool->add_vertex(points[2]);
  6192. surftool->add_vertex(points[3]);
  6193. }
  6194. }
  6195. surftool->set_material(mat);
  6196. surftool->commit(move_gizmo[i]);
  6197. }
  6198. // Plane Translation
  6199. {
  6200. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  6201. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  6202. Vector3 vec = ivec2 - ivec3;
  6203. Vector3 plane[4] = {
  6204. vec * GIZMO_PLANE_DST,
  6205. vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
  6206. vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
  6207. vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
  6208. };
  6209. Basis ma(ivec, Math_PI / 2);
  6210. Vector3 points[4] = {
  6211. ma.xform(plane[0]),
  6212. ma.xform(plane[1]),
  6213. ma.xform(plane[2]),
  6214. ma.xform(plane[3]),
  6215. };
  6216. surftool->add_vertex(points[0]);
  6217. surftool->add_vertex(points[1]);
  6218. surftool->add_vertex(points[2]);
  6219. surftool->add_vertex(points[0]);
  6220. surftool->add_vertex(points[2]);
  6221. surftool->add_vertex(points[3]);
  6222. Ref<StandardMaterial3D> plane_mat = memnew(StandardMaterial3D);
  6223. plane_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  6224. plane_mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  6225. plane_mat->set_on_top_of_alpha();
  6226. plane_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  6227. plane_mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED);
  6228. plane_mat->set_albedo(col);
  6229. plane_gizmo_color[i] = plane_mat; // needed, so we can draw planes from both sides
  6230. surftool->set_material(plane_mat);
  6231. surftool->commit(move_plane_gizmo[i]);
  6232. Ref<StandardMaterial3D> plane_mat_hl = plane_mat->duplicate();
  6233. plane_mat_hl->set_albedo(albedo);
  6234. plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides
  6235. }
  6236. // Rotate
  6237. {
  6238. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  6239. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  6240. int n = 128; // number of circle segments
  6241. int m = 3; // number of thickness segments
  6242. real_t step = Math_TAU / n;
  6243. for (int j = 0; j < n; ++j) {
  6244. Basis basis = Basis(ivec, j * step);
  6245. Vector3 vertex = basis.xform(ivec2 * GIZMO_CIRCLE_SIZE);
  6246. for (int k = 0; k < m; ++k) {
  6247. Vector2 ofs = Vector2(Math::cos((Math_TAU * k) / m), Math::sin((Math_TAU * k) / m));
  6248. Vector3 normal = ivec * ofs.x + ivec2 * ofs.y;
  6249. surftool->set_normal(basis.xform(normal));
  6250. surftool->add_vertex(vertex);
  6251. }
  6252. }
  6253. for (int j = 0; j < n; ++j) {
  6254. for (int k = 0; k < m; ++k) {
  6255. int current_ring = j * m;
  6256. int next_ring = ((j + 1) % n) * m;
  6257. int current_segment = k;
  6258. int next_segment = (k + 1) % m;
  6259. surftool->add_index(current_ring + next_segment);
  6260. surftool->add_index(current_ring + current_segment);
  6261. surftool->add_index(next_ring + current_segment);
  6262. surftool->add_index(next_ring + current_segment);
  6263. surftool->add_index(next_ring + next_segment);
  6264. surftool->add_index(current_ring + next_segment);
  6265. }
  6266. }
  6267. Ref<Shader> rotate_shader = memnew(Shader);
  6268. rotate_shader->set_code(R"(
  6269. // 3D editor rotation manipulator gizmo shader.
  6270. shader_type spatial;
  6271. render_mode unshaded, depth_test_disabled, fog_disabled;
  6272. uniform vec4 albedo;
  6273. mat3 orthonormalize(mat3 m) {
  6274. vec3 x = normalize(m[0]);
  6275. vec3 y = normalize(m[1] - x * dot(x, m[1]));
  6276. vec3 z = m[2] - x * dot(x, m[2]);
  6277. z = normalize(z - y * (dot(y, m[2])));
  6278. return mat3(x,y,z);
  6279. }
  6280. void vertex() {
  6281. mat3 mv = orthonormalize(mat3(MODELVIEW_MATRIX));
  6282. vec3 n = mv * VERTEX;
  6283. float orientation = dot(vec3(0.0, 0.0, -1.0), n);
  6284. if (orientation <= 0.005) {
  6285. VERTEX += NORMAL * 0.02;
  6286. }
  6287. }
  6288. void fragment() {
  6289. ALBEDO = albedo.rgb;
  6290. ALPHA = albedo.a;
  6291. }
  6292. )");
  6293. Ref<ShaderMaterial> rotate_mat = memnew(ShaderMaterial);
  6294. rotate_mat->set_render_priority(Material::RENDER_PRIORITY_MAX);
  6295. rotate_mat->set_shader(rotate_shader);
  6296. rotate_mat->set_shader_parameter("albedo", col);
  6297. rotate_gizmo_color[i] = rotate_mat;
  6298. Array arrays = surftool->commit_to_arrays();
  6299. rotate_gizmo[i]->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays);
  6300. rotate_gizmo[i]->surface_set_material(0, rotate_mat);
  6301. Ref<ShaderMaterial> rotate_mat_hl = rotate_mat->duplicate();
  6302. rotate_mat_hl->set_shader_parameter("albedo", albedo);
  6303. rotate_gizmo_color_hl[i] = rotate_mat_hl;
  6304. if (i == 2) { // Rotation white outline
  6305. Ref<ShaderMaterial> border_mat = rotate_mat->duplicate();
  6306. Ref<Shader> border_shader = memnew(Shader);
  6307. border_shader->set_code(R"(
  6308. // 3D editor rotation manipulator gizmo shader (white outline).
  6309. shader_type spatial;
  6310. render_mode unshaded, depth_test_disabled, fog_disabled;
  6311. uniform vec4 albedo;
  6312. mat3 orthonormalize(mat3 m) {
  6313. vec3 x = normalize(m[0]);
  6314. vec3 y = normalize(m[1] - x * dot(x, m[1]));
  6315. vec3 z = m[2] - x * dot(x, m[2]);
  6316. z = normalize(z - y * (dot(y, m[2])));
  6317. return mat3(x, y, z);
  6318. }
  6319. void vertex() {
  6320. mat3 mv = orthonormalize(mat3(MODELVIEW_MATRIX));
  6321. mv = inverse(mv);
  6322. VERTEX += NORMAL * 0.008;
  6323. vec3 camera_dir_local = mv * vec3(0.0, 0.0, 1.0);
  6324. vec3 camera_up_local = mv * vec3(0.0, 1.0, 0.0);
  6325. mat3 rotation_matrix = mat3(cross(camera_dir_local, camera_up_local), camera_up_local, camera_dir_local);
  6326. VERTEX = rotation_matrix * VERTEX;
  6327. }
  6328. void fragment() {
  6329. ALBEDO = albedo.rgb;
  6330. ALPHA = albedo.a;
  6331. }
  6332. )");
  6333. border_mat->set_shader(border_shader);
  6334. border_mat->set_shader_parameter("albedo", Color(0.75, 0.75, 0.75, col.a / 3.0));
  6335. rotate_gizmo[3].instantiate();
  6336. rotate_gizmo[3]->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays);
  6337. rotate_gizmo[3]->surface_set_material(0, border_mat);
  6338. }
  6339. }
  6340. // Scale
  6341. {
  6342. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  6343. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  6344. // Cube arrow profile
  6345. const int arrow_points = 6;
  6346. Vector3 arrow[6] = {
  6347. nivec * 0.0 + ivec * 0.0,
  6348. nivec * 0.01 + ivec * 0.0,
  6349. nivec * 0.01 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
  6350. nivec * 0.07 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
  6351. nivec * 0.07 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
  6352. nivec * 0.0 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
  6353. };
  6354. int arrow_sides = 4;
  6355. const real_t arrow_sides_step = Math_TAU / arrow_sides;
  6356. for (int k = 0; k < 4; k++) {
  6357. Basis ma(ivec, k * arrow_sides_step);
  6358. Basis mb(ivec, (k + 1) * arrow_sides_step);
  6359. for (int j = 0; j < arrow_points - 1; j++) {
  6360. Vector3 points[4] = {
  6361. ma.xform(arrow[j]),
  6362. mb.xform(arrow[j]),
  6363. mb.xform(arrow[j + 1]),
  6364. ma.xform(arrow[j + 1]),
  6365. };
  6366. surftool->add_vertex(points[0]);
  6367. surftool->add_vertex(points[1]);
  6368. surftool->add_vertex(points[2]);
  6369. surftool->add_vertex(points[0]);
  6370. surftool->add_vertex(points[2]);
  6371. surftool->add_vertex(points[3]);
  6372. }
  6373. }
  6374. surftool->set_material(mat);
  6375. surftool->commit(scale_gizmo[i]);
  6376. }
  6377. // Plane Scale
  6378. {
  6379. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  6380. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  6381. Vector3 vec = ivec2 - ivec3;
  6382. Vector3 plane[4] = {
  6383. vec * GIZMO_PLANE_DST,
  6384. vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
  6385. vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
  6386. vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
  6387. };
  6388. Basis ma(ivec, Math_PI / 2);
  6389. Vector3 points[4] = {
  6390. ma.xform(plane[0]),
  6391. ma.xform(plane[1]),
  6392. ma.xform(plane[2]),
  6393. ma.xform(plane[3]),
  6394. };
  6395. surftool->add_vertex(points[0]);
  6396. surftool->add_vertex(points[1]);
  6397. surftool->add_vertex(points[2]);
  6398. surftool->add_vertex(points[0]);
  6399. surftool->add_vertex(points[2]);
  6400. surftool->add_vertex(points[3]);
  6401. Ref<StandardMaterial3D> plane_mat = memnew(StandardMaterial3D);
  6402. plane_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  6403. plane_mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  6404. plane_mat->set_on_top_of_alpha();
  6405. plane_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  6406. plane_mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED);
  6407. plane_mat->set_albedo(col);
  6408. plane_gizmo_color[i] = plane_mat; // needed, so we can draw planes from both sides
  6409. surftool->set_material(plane_mat);
  6410. surftool->commit(scale_plane_gizmo[i]);
  6411. Ref<StandardMaterial3D> plane_mat_hl = plane_mat->duplicate();
  6412. plane_mat_hl->set_albedo(col.from_hsv(col.get_h(), 0.25, 1.0, 1));
  6413. plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides
  6414. }
  6415. // Lines to visualize transforms locked to an axis/plane
  6416. {
  6417. Ref<SurfaceTool> surftool = memnew(SurfaceTool);
  6418. surftool->begin(Mesh::PRIMITIVE_LINE_STRIP);
  6419. Vector3 vec;
  6420. vec[i] = 1;
  6421. // line extending through infinity(ish)
  6422. surftool->add_vertex(vec * -1048576);
  6423. surftool->add_vertex(Vector3());
  6424. surftool->add_vertex(vec * 1048576);
  6425. surftool->set_material(mat_hl);
  6426. surftool->commit(axis_gizmo[i]);
  6427. }
  6428. }
  6429. }
  6430. _generate_selection_boxes();
  6431. }
  6432. void Node3DEditor::_update_gizmos_menu() {
  6433. gizmos_menu->clear();
  6434. for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
  6435. if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
  6436. continue;
  6437. }
  6438. String plugin_name = gizmo_plugins_by_name[i]->get_gizmo_name();
  6439. const int plugin_state = gizmo_plugins_by_name[i]->get_state();
  6440. gizmos_menu->add_multistate_item(plugin_name, 3, plugin_state, i);
  6441. const int idx = gizmos_menu->get_item_index(i);
  6442. gizmos_menu->set_item_tooltip(
  6443. idx,
  6444. 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\")."));
  6445. switch (plugin_state) {
  6446. case EditorNode3DGizmoPlugin::VISIBLE:
  6447. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_visible")));
  6448. break;
  6449. case EditorNode3DGizmoPlugin::ON_TOP:
  6450. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_xray")));
  6451. break;
  6452. case EditorNode3DGizmoPlugin::HIDDEN:
  6453. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_hidden")));
  6454. break;
  6455. }
  6456. }
  6457. }
  6458. void Node3DEditor::_update_gizmos_menu_theme() {
  6459. for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
  6460. if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
  6461. continue;
  6462. }
  6463. const int plugin_state = gizmo_plugins_by_name[i]->get_state();
  6464. const int idx = gizmos_menu->get_item_index(i);
  6465. switch (plugin_state) {
  6466. case EditorNode3DGizmoPlugin::VISIBLE:
  6467. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_visible")));
  6468. break;
  6469. case EditorNode3DGizmoPlugin::ON_TOP:
  6470. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_xray")));
  6471. break;
  6472. case EditorNode3DGizmoPlugin::HIDDEN:
  6473. gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon(SNAME("visibility_hidden")));
  6474. break;
  6475. }
  6476. }
  6477. }
  6478. void Node3DEditor::_init_grid() {
  6479. if (!grid_enabled) {
  6480. return;
  6481. }
  6482. Camera3D *camera = get_editor_viewport(0)->camera;
  6483. Vector3 camera_position = camera->get_position();
  6484. if (camera_position == Vector3()) {
  6485. return; // Camera3D is invalid, don't draw the grid.
  6486. }
  6487. bool orthogonal = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
  6488. static LocalVector<Color> grid_colors[3];
  6489. static LocalVector<Vector3> grid_points[3];
  6490. static LocalVector<Vector3> grid_normals[3];
  6491. for (uint32_t n = 0; n < 3; n++) {
  6492. grid_colors[n].clear();
  6493. grid_points[n].clear();
  6494. grid_normals[n].clear();
  6495. }
  6496. Color primary_grid_color = EDITOR_GET("editors/3d/primary_grid_color");
  6497. Color secondary_grid_color = EDITOR_GET("editors/3d/secondary_grid_color");
  6498. int grid_size = EDITOR_GET("editors/3d/grid_size");
  6499. int primary_grid_steps = EDITOR_GET("editors/3d/primary_grid_steps");
  6500. // Which grid planes are enabled? Which should we generate?
  6501. grid_enable[0] = grid_visible[0] = orthogonal || EDITOR_GET("editors/3d/grid_xy_plane");
  6502. grid_enable[1] = grid_visible[1] = orthogonal || EDITOR_GET("editors/3d/grid_yz_plane");
  6503. grid_enable[2] = grid_visible[2] = orthogonal || EDITOR_GET("editors/3d/grid_xz_plane");
  6504. // Offsets division_level for bigger or smaller grids.
  6505. // Default value is -0.2. -1.0 gives Blender-like behavior, 0.5 gives huge grids.
  6506. real_t division_level_bias = EDITOR_GET("editors/3d/grid_division_level_bias");
  6507. // Default largest grid size is 8^2 (default value is 2) when primary_grid_steps is 8 (64m apart, so primary grid lines are 512m apart).
  6508. int division_level_max = EDITOR_GET("editors/3d/grid_division_level_max");
  6509. // Default smallest grid size is 8^0 (default value is 0) when primary_grid_steps is 8.
  6510. int division_level_min = EDITOR_GET("editors/3d/grid_division_level_min");
  6511. 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.");
  6512. if (primary_grid_steps != 10) { // Log10 of 10 is 1.
  6513. // Change of base rule, divide by ln(10).
  6514. real_t div = Math::log((real_t)primary_grid_steps) / (real_t)2.302585092994045901094;
  6515. // Truncation (towards zero) is intentional.
  6516. division_level_max = (int)(division_level_max / div);
  6517. division_level_min = (int)(division_level_min / div);
  6518. }
  6519. for (int a = 0; a < 3; a++) {
  6520. if (!grid_enable[a]) {
  6521. continue; // If this grid plane is disabled, skip generation.
  6522. }
  6523. int b = (a + 1) % 3;
  6524. int c = (a + 2) % 3;
  6525. Vector3 normal;
  6526. normal[c] = 1.0;
  6527. real_t camera_distance = Math::abs(camera_position[c]);
  6528. if (orthogonal) {
  6529. camera_distance = camera->get_size() / 2.0;
  6530. Vector3 camera_direction = -camera->get_global_transform().get_basis().get_column(2);
  6531. Plane grid_plane = Plane(normal);
  6532. Vector3 intersection;
  6533. if (grid_plane.intersects_ray(camera_position, camera_direction, &intersection)) {
  6534. camera_position = intersection;
  6535. }
  6536. }
  6537. real_t division_level = Math::log(Math::abs(camera_distance)) / Math::log((double)primary_grid_steps) + division_level_bias;
  6538. real_t clamped_division_level = CLAMP(division_level, division_level_min, division_level_max);
  6539. real_t division_level_floored = Math::floor(clamped_division_level);
  6540. real_t division_level_decimals = clamped_division_level - division_level_floored;
  6541. real_t small_step_size = Math::pow(primary_grid_steps, division_level_floored);
  6542. real_t large_step_size = small_step_size * primary_grid_steps;
  6543. real_t center_a = large_step_size * (int)(camera_position[a] / large_step_size);
  6544. real_t center_b = large_step_size * (int)(camera_position[b] / large_step_size);
  6545. real_t bgn_a = center_a - grid_size * small_step_size;
  6546. real_t end_a = center_a + grid_size * small_step_size;
  6547. real_t bgn_b = center_b - grid_size * small_step_size;
  6548. real_t end_b = center_b + grid_size * small_step_size;
  6549. real_t fade_size = Math::pow(primary_grid_steps, division_level - 1.0);
  6550. real_t min_fade_size = Math::pow(primary_grid_steps, float(division_level_min));
  6551. real_t max_fade_size = Math::pow(primary_grid_steps, float(division_level_max));
  6552. fade_size = CLAMP(fade_size, min_fade_size, max_fade_size);
  6553. real_t grid_fade_size = (grid_size - primary_grid_steps) * fade_size;
  6554. grid_mat[c]->set_shader_parameter("grid_size", grid_fade_size);
  6555. grid_mat[c]->set_shader_parameter("orthogonal", orthogonal);
  6556. LocalVector<Vector3> &ref_grid = grid_points[c];
  6557. LocalVector<Vector3> &ref_grid_normals = grid_normals[c];
  6558. LocalVector<Color> &ref_grid_colors = grid_colors[c];
  6559. // Count our elements same as code below it.
  6560. int expected_size = 0;
  6561. for (int i = -grid_size; i <= grid_size; i++) {
  6562. const real_t position_a = center_a + i * small_step_size;
  6563. const real_t position_b = center_b + i * small_step_size;
  6564. // Don't draw lines over the origin if it's enabled.
  6565. if (!(origin_enabled && Math::is_zero_approx(position_a))) {
  6566. expected_size += 2;
  6567. }
  6568. if (!(origin_enabled && Math::is_zero_approx(position_b))) {
  6569. expected_size += 2;
  6570. }
  6571. }
  6572. int idx = 0;
  6573. ref_grid.resize(expected_size);
  6574. ref_grid_normals.resize(expected_size);
  6575. ref_grid_colors.resize(expected_size);
  6576. // In each iteration of this loop, draw one line in each direction (so two lines per loop, in each if statement).
  6577. for (int i = -grid_size; i <= grid_size; i++) {
  6578. Color line_color;
  6579. // Is this a primary line? Set the appropriate color.
  6580. if (i % primary_grid_steps == 0) {
  6581. line_color = primary_grid_color.lerp(secondary_grid_color, division_level_decimals);
  6582. } else {
  6583. line_color = secondary_grid_color;
  6584. line_color.a = line_color.a * (1 - division_level_decimals);
  6585. }
  6586. real_t position_a = center_a + i * small_step_size;
  6587. real_t position_b = center_b + i * small_step_size;
  6588. // Don't draw lines over the origin if it's enabled.
  6589. if (!(origin_enabled && Math::is_zero_approx(position_a))) {
  6590. Vector3 line_bgn;
  6591. Vector3 line_end;
  6592. line_bgn[a] = position_a;
  6593. line_end[a] = position_a;
  6594. line_bgn[b] = bgn_b;
  6595. line_end[b] = end_b;
  6596. ref_grid[idx] = line_bgn;
  6597. ref_grid[idx + 1] = line_end;
  6598. ref_grid_colors[idx] = line_color;
  6599. ref_grid_colors[idx + 1] = line_color;
  6600. ref_grid_normals[idx] = normal;
  6601. ref_grid_normals[idx + 1] = normal;
  6602. idx += 2;
  6603. }
  6604. if (!(origin_enabled && Math::is_zero_approx(position_b))) {
  6605. Vector3 line_bgn;
  6606. Vector3 line_end;
  6607. line_bgn[b] = position_b;
  6608. line_end[b] = position_b;
  6609. line_bgn[a] = bgn_a;
  6610. line_end[a] = end_a;
  6611. ref_grid[idx] = line_bgn;
  6612. ref_grid[idx + 1] = line_end;
  6613. ref_grid_colors[idx] = line_color;
  6614. ref_grid_colors[idx + 1] = line_color;
  6615. ref_grid_normals[idx] = normal;
  6616. ref_grid_normals[idx + 1] = normal;
  6617. idx += 2;
  6618. }
  6619. }
  6620. // Create a mesh from the pushed vector points and colors.
  6621. grid[c] = RenderingServer::get_singleton()->mesh_create();
  6622. Array d;
  6623. d.resize(RS::ARRAY_MAX);
  6624. d[RenderingServer::ARRAY_VERTEX] = (Vector<Vector3>)grid_points[c];
  6625. d[RenderingServer::ARRAY_COLOR] = (Vector<Color>)grid_colors[c];
  6626. d[RenderingServer::ARRAY_NORMAL] = (Vector<Vector3>)grid_normals[c];
  6627. RenderingServer::get_singleton()->mesh_add_surface_from_arrays(grid[c], RenderingServer::PRIMITIVE_LINES, d);
  6628. RenderingServer::get_singleton()->mesh_surface_set_material(grid[c], 0, grid_mat[c]->get_rid());
  6629. grid_instance[c] = RenderingServer::get_singleton()->instance_create2(grid[c], get_tree()->get_root()->get_world_3d()->get_scenario());
  6630. // Yes, the end of this line is supposed to be a.
  6631. RenderingServer::get_singleton()->instance_set_visible(grid_instance[c], grid_visible[a]);
  6632. RenderingServer::get_singleton()->instance_geometry_set_cast_shadows_setting(grid_instance[c], RS::SHADOW_CASTING_SETTING_OFF);
  6633. RS::get_singleton()->instance_set_layer_mask(grid_instance[c], 1 << Node3DEditorViewport::GIZMO_GRID_LAYER);
  6634. RS::get_singleton()->instance_geometry_set_flag(grid_instance[c], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
  6635. RS::get_singleton()->instance_geometry_set_flag(grid_instance[c], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
  6636. }
  6637. }
  6638. void Node3DEditor::_finish_indicators() {
  6639. RenderingServer::get_singleton()->free(origin_instance);
  6640. RenderingServer::get_singleton()->free(origin_multimesh);
  6641. RenderingServer::get_singleton()->free(origin_mesh);
  6642. _finish_grid();
  6643. }
  6644. void Node3DEditor::_finish_grid() {
  6645. for (int i = 0; i < 3; i++) {
  6646. RenderingServer::get_singleton()->free(grid_instance[i]);
  6647. RenderingServer::get_singleton()->free(grid[i]);
  6648. }
  6649. }
  6650. void Node3DEditor::update_grid() {
  6651. const Camera3D::ProjectionType current_projection = viewports[0]->camera->get_projection();
  6652. if (current_projection != grid_camera_last_update_perspective) {
  6653. grid_init_draw = false; // redraw
  6654. grid_camera_last_update_perspective = current_projection;
  6655. }
  6656. // Gets a orthogonal or perspective position correctly (for the grid comparison)
  6657. const Vector3 camera_position = get_editor_viewport(0)->camera->get_position();
  6658. if (!grid_init_draw || grid_camera_last_update_position.distance_squared_to(camera_position) >= 100.0f) {
  6659. _finish_grid();
  6660. _init_grid();
  6661. grid_init_draw = true;
  6662. grid_camera_last_update_position = camera_position;
  6663. }
  6664. }
  6665. void Node3DEditor::_selection_changed() {
  6666. _refresh_menu_icons();
  6667. const HashMap<Node *, Object *> &selection = editor_selection->get_selection();
  6668. for (const KeyValue<Node *, Object *> &E : selection) {
  6669. Node3D *sp = Object::cast_to<Node3D>(E.key);
  6670. if (!sp) {
  6671. continue;
  6672. }
  6673. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  6674. if (!se) {
  6675. continue;
  6676. }
  6677. if (sp == editor_selection->get_selected_node_list().back()->get()) {
  6678. RenderingServer::get_singleton()->instance_set_base(se->sbox_instance, active_selection_box->get_rid());
  6679. RenderingServer::get_singleton()->instance_set_base(se->sbox_instance_xray, active_selection_box_xray->get_rid());
  6680. RenderingServer::get_singleton()->instance_set_base(se->sbox_instance_offset, active_selection_box->get_rid());
  6681. RenderingServer::get_singleton()->instance_set_base(se->sbox_instance_xray_offset, active_selection_box_xray->get_rid());
  6682. } else {
  6683. RenderingServer::get_singleton()->instance_set_base(se->sbox_instance, selection_box->get_rid());
  6684. RenderingServer::get_singleton()->instance_set_base(se->sbox_instance_xray, selection_box_xray->get_rid());
  6685. RenderingServer::get_singleton()->instance_set_base(se->sbox_instance_offset, selection_box->get_rid());
  6686. RenderingServer::get_singleton()->instance_set_base(se->sbox_instance_xray_offset, selection_box_xray->get_rid());
  6687. }
  6688. }
  6689. if (selected && editor_selection->get_selected_node_list().size() != 1) {
  6690. Vector<Ref<Node3DGizmo>> gizmos = selected->get_gizmos();
  6691. for (int i = 0; i < gizmos.size(); i++) {
  6692. Ref<EditorNode3DGizmo> seg = gizmos[i];
  6693. if (seg.is_null()) {
  6694. continue;
  6695. }
  6696. seg->set_selected(false);
  6697. }
  6698. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected);
  6699. if (se) {
  6700. se->gizmo.unref();
  6701. se->subgizmos.clear();
  6702. }
  6703. selected->update_gizmos();
  6704. selected = nullptr;
  6705. }
  6706. update_transform_gizmo();
  6707. }
  6708. void Node3DEditor::_refresh_menu_icons() {
  6709. bool all_locked = true;
  6710. bool all_grouped = true;
  6711. bool has_node3d_item = false;
  6712. List<Node *> &selection = editor_selection->get_selected_node_list();
  6713. if (selection.is_empty()) {
  6714. all_locked = false;
  6715. all_grouped = false;
  6716. } else {
  6717. for (Node *E : selection) {
  6718. Node3D *node = Object::cast_to<Node3D>(E);
  6719. if (node) {
  6720. if (all_locked && !node->has_meta("_edit_lock_")) {
  6721. all_locked = false;
  6722. }
  6723. if (all_grouped && !node->has_meta("_edit_group_")) {
  6724. all_grouped = false;
  6725. }
  6726. has_node3d_item = true;
  6727. }
  6728. if (!all_locked && !all_grouped) {
  6729. break;
  6730. }
  6731. }
  6732. }
  6733. all_locked = all_locked && has_node3d_item;
  6734. all_grouped = all_grouped && has_node3d_item;
  6735. tool_button[TOOL_LOCK_SELECTED]->set_visible(!all_locked);
  6736. tool_button[TOOL_LOCK_SELECTED]->set_disabled(!has_node3d_item);
  6737. tool_button[TOOL_UNLOCK_SELECTED]->set_visible(all_locked);
  6738. tool_button[TOOL_UNLOCK_SELECTED]->set_disabled(!has_node3d_item);
  6739. tool_button[TOOL_GROUP_SELECTED]->set_visible(!all_grouped);
  6740. tool_button[TOOL_GROUP_SELECTED]->set_disabled(!has_node3d_item);
  6741. tool_button[TOOL_UNGROUP_SELECTED]->set_visible(all_grouped);
  6742. tool_button[TOOL_UNGROUP_SELECTED]->set_disabled(!has_node3d_item);
  6743. }
  6744. template <typename T>
  6745. HashSet<T *> _get_child_nodes(Node *parent_node) {
  6746. HashSet<T *> nodes = HashSet<T *>();
  6747. T *node = Node::cast_to<T>(parent_node);
  6748. if (node) {
  6749. nodes.insert(node);
  6750. }
  6751. for (int i = 0; i < parent_node->get_child_count(); i++) {
  6752. Node *child_node = parent_node->get_child(i);
  6753. HashSet<T *> child_nodes = _get_child_nodes<T>(child_node);
  6754. for (T *I : child_nodes) {
  6755. nodes.insert(I);
  6756. }
  6757. }
  6758. return nodes;
  6759. }
  6760. HashSet<RID> _get_physics_bodies_rid(Node *node) {
  6761. HashSet<RID> rids = HashSet<RID>();
  6762. PhysicsBody3D *pb = Node::cast_to<PhysicsBody3D>(node);
  6763. if (pb) {
  6764. rids.insert(pb->get_rid());
  6765. }
  6766. HashSet<PhysicsBody3D *> child_nodes = _get_child_nodes<PhysicsBody3D>(node);
  6767. for (const PhysicsBody3D *I : child_nodes) {
  6768. rids.insert(I->get_rid());
  6769. }
  6770. return rids;
  6771. }
  6772. void Node3DEditor::snap_selected_nodes_to_floor() {
  6773. do_snap_selected_nodes_to_floor = true;
  6774. }
  6775. void Node3DEditor::_snap_selected_nodes_to_floor() {
  6776. const List<Node *> &selection = editor_selection->get_selected_node_list();
  6777. Dictionary snap_data;
  6778. for (Node *E : selection) {
  6779. Node3D *sp = Object::cast_to<Node3D>(E);
  6780. if (sp) {
  6781. Vector3 from;
  6782. Vector3 position_offset;
  6783. // Priorities for snapping to floor are CollisionShapes, VisualInstances and then origin
  6784. HashSet<VisualInstance3D *> vi = _get_child_nodes<VisualInstance3D>(sp);
  6785. HashSet<CollisionShape3D *> cs = _get_child_nodes<CollisionShape3D>(sp);
  6786. bool found_valid_shape = false;
  6787. if (cs.size()) {
  6788. AABB aabb;
  6789. HashSet<CollisionShape3D *>::Iterator I = cs.begin();
  6790. if ((*I)->get_shape().is_valid()) {
  6791. CollisionShape3D *collision_shape = *cs.begin();
  6792. aabb = collision_shape->get_global_transform().xform(collision_shape->get_shape()->get_debug_mesh()->get_aabb());
  6793. found_valid_shape = true;
  6794. }
  6795. for (++I; I; ++I) {
  6796. CollisionShape3D *col_shape = *I;
  6797. if (col_shape->get_shape().is_valid()) {
  6798. aabb.merge_with(col_shape->get_global_transform().xform(col_shape->get_shape()->get_debug_mesh()->get_aabb()));
  6799. found_valid_shape = true;
  6800. }
  6801. }
  6802. if (found_valid_shape) {
  6803. Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
  6804. from = aabb.position + size;
  6805. position_offset.y = from.y - sp->get_global_transform().origin.y;
  6806. }
  6807. }
  6808. if (!found_valid_shape && vi.size()) {
  6809. VisualInstance3D *begin = *vi.begin();
  6810. AABB aabb = begin->get_global_transform().xform(begin->get_aabb());
  6811. for (const VisualInstance3D *I : vi) {
  6812. aabb.merge_with(I->get_global_transform().xform(I->get_aabb()));
  6813. }
  6814. Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
  6815. from = aabb.position + size;
  6816. position_offset.y = from.y - sp->get_global_transform().origin.y;
  6817. } else if (!found_valid_shape) {
  6818. from = sp->get_global_transform().origin;
  6819. }
  6820. // We add a bit of margin to the from position to avoid it from snapping
  6821. // when the spatial is already on a floor and there's another floor under
  6822. // it
  6823. from = from + Vector3(0.0, 1, 0.0);
  6824. Dictionary d;
  6825. d["from"] = from;
  6826. d["position_offset"] = position_offset;
  6827. snap_data[sp] = d;
  6828. }
  6829. }
  6830. PhysicsDirectSpaceState3D *ss = get_tree()->get_root()->get_world_3d()->get_direct_space_state();
  6831. PhysicsDirectSpaceState3D::RayResult result;
  6832. Array keys = snap_data.keys();
  6833. // The maximum height an object can travel to be snapped
  6834. const float max_snap_height = 500.0;
  6835. // Will be set to `true` if at least one node from the selection was successfully snapped
  6836. bool snapped_to_floor = false;
  6837. if (keys.size()) {
  6838. // For snapping to be performed, there must be solid geometry under at least one of the selected nodes.
  6839. // We need to check this before snapping to register the undo/redo action only if needed.
  6840. for (int i = 0; i < keys.size(); i++) {
  6841. Node *node = Object::cast_to<Node>(keys[i]);
  6842. Node3D *sp = Object::cast_to<Node3D>(node);
  6843. Dictionary d = snap_data[node];
  6844. Vector3 from = d["from"];
  6845. Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
  6846. HashSet<RID> excluded = _get_physics_bodies_rid(sp);
  6847. PhysicsDirectSpaceState3D::RayParameters ray_params;
  6848. ray_params.from = from;
  6849. ray_params.to = to;
  6850. ray_params.exclude = excluded;
  6851. if (ss->intersect_ray(ray_params, result)) {
  6852. snapped_to_floor = true;
  6853. }
  6854. }
  6855. if (snapped_to_floor) {
  6856. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  6857. undo_redo->create_action(TTR("Snap Nodes to Floor"));
  6858. // Perform snapping if at least one node can be snapped
  6859. for (int i = 0; i < keys.size(); i++) {
  6860. Node *node = Object::cast_to<Node>(keys[i]);
  6861. Node3D *sp = Object::cast_to<Node3D>(node);
  6862. Dictionary d = snap_data[node];
  6863. Vector3 from = d["from"];
  6864. Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
  6865. HashSet<RID> excluded = _get_physics_bodies_rid(sp);
  6866. PhysicsDirectSpaceState3D::RayParameters ray_params;
  6867. ray_params.from = from;
  6868. ray_params.to = to;
  6869. ray_params.exclude = excluded;
  6870. if (ss->intersect_ray(ray_params, result)) {
  6871. Vector3 position_offset = d["position_offset"];
  6872. Transform3D new_transform = sp->get_global_transform();
  6873. new_transform.origin.y = result.position.y;
  6874. new_transform.origin = new_transform.origin - position_offset;
  6875. Node3D *parent = sp->get_parent_node_3d();
  6876. Transform3D new_local_xform = parent ? parent->get_global_transform().affine_inverse() * new_transform : new_transform;
  6877. undo_redo->add_do_method(sp, "set_transform", new_local_xform);
  6878. undo_redo->add_undo_method(sp, "set_transform", sp->get_transform());
  6879. }
  6880. }
  6881. undo_redo->commit_action();
  6882. } else {
  6883. EditorNode::get_singleton()->show_warning(TTR("Couldn't find a solid floor to snap the selection to."));
  6884. }
  6885. }
  6886. }
  6887. void Node3DEditor::shortcut_input(const Ref<InputEvent> &p_event) {
  6888. ERR_FAIL_COND(p_event.is_null());
  6889. if (!is_visible_in_tree()) {
  6890. return;
  6891. }
  6892. snap_key_enabled = Input::get_singleton()->is_key_pressed(Key::CTRL);
  6893. }
  6894. void Node3DEditor::_sun_environ_settings_pressed() {
  6895. Vector2 pos = sun_environ_settings->get_screen_position() + sun_environ_settings->get_size();
  6896. sun_environ_popup->set_position(pos - Vector2(sun_environ_popup->get_contents_minimum_size().width / 2, 0));
  6897. sun_environ_popup->reset_size();
  6898. sun_environ_popup->popup();
  6899. // Grabbing the focus is required for Shift modifier checking to be functional
  6900. // (when the Add sun/environment buttons are pressed).
  6901. sun_environ_popup->grab_focus();
  6902. }
  6903. void Node3DEditor::_add_sun_to_scene(bool p_already_added_environment) {
  6904. sun_environ_popup->hide();
  6905. if (!p_already_added_environment && world_env_count == 0 && Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
  6906. // Prevent infinite feedback loop between the sun and environment methods.
  6907. _add_environment_to_scene(true);
  6908. }
  6909. Node *base = get_tree()->get_edited_scene_root();
  6910. if (!base) {
  6911. // Create a root node so we can add child nodes to it.
  6912. SceneTreeDock::get_singleton()->add_root_node(memnew(Node3D));
  6913. base = get_tree()->get_edited_scene_root();
  6914. }
  6915. ERR_FAIL_NULL(base);
  6916. Node *new_sun = preview_sun->duplicate();
  6917. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  6918. undo_redo->create_action(TTR("Add Preview Sun to Scene"));
  6919. undo_redo->add_do_method(base, "add_child", new_sun, true);
  6920. // Move to the beginning of the scene tree since more "global" nodes
  6921. // generally look better when placed at the top.
  6922. undo_redo->add_do_method(base, "move_child", new_sun, 0);
  6923. undo_redo->add_do_method(new_sun, "set_owner", base);
  6924. undo_redo->add_undo_method(base, "remove_child", new_sun);
  6925. undo_redo->add_do_reference(new_sun);
  6926. undo_redo->commit_action();
  6927. }
  6928. void Node3DEditor::_add_environment_to_scene(bool p_already_added_sun) {
  6929. sun_environ_popup->hide();
  6930. if (!p_already_added_sun && directional_light_count == 0 && Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
  6931. // Prevent infinite feedback loop between the sun and environment methods.
  6932. _add_sun_to_scene(true);
  6933. }
  6934. Node *base = get_tree()->get_edited_scene_root();
  6935. if (!base) {
  6936. // Create a root node so we can add child nodes to it.
  6937. SceneTreeDock::get_singleton()->add_root_node(memnew(Node3D));
  6938. base = get_tree()->get_edited_scene_root();
  6939. }
  6940. ERR_FAIL_NULL(base);
  6941. WorldEnvironment *new_env = memnew(WorldEnvironment);
  6942. new_env->set_environment(preview_environment->get_environment()->duplicate(true));
  6943. if (GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units")) {
  6944. new_env->set_camera_attributes(preview_environment->get_camera_attributes()->duplicate(true));
  6945. }
  6946. EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
  6947. undo_redo->create_action(TTR("Add Preview Environment to Scene"));
  6948. undo_redo->add_do_method(base, "add_child", new_env, true);
  6949. // Move to the beginning of the scene tree since more "global" nodes
  6950. // generally look better when placed at the top.
  6951. undo_redo->add_do_method(base, "move_child", new_env, 0);
  6952. undo_redo->add_do_method(new_env, "set_owner", base);
  6953. undo_redo->add_undo_method(base, "remove_child", new_env);
  6954. undo_redo->add_do_reference(new_env);
  6955. undo_redo->commit_action();
  6956. }
  6957. void Node3DEditor::_update_theme() {
  6958. tool_button[TOOL_MODE_SELECT]->set_button_icon(get_editor_theme_icon(SNAME("ToolSelect")));
  6959. tool_button[TOOL_MODE_MOVE]->set_button_icon(get_editor_theme_icon(SNAME("ToolMove")));
  6960. tool_button[TOOL_MODE_ROTATE]->set_button_icon(get_editor_theme_icon(SNAME("ToolRotate")));
  6961. tool_button[TOOL_MODE_SCALE]->set_button_icon(get_editor_theme_icon(SNAME("ToolScale")));
  6962. tool_button[TOOL_MODE_LIST_SELECT]->set_button_icon(get_editor_theme_icon(SNAME("ListSelect")));
  6963. tool_button[TOOL_LOCK_SELECTED]->set_button_icon(get_editor_theme_icon(SNAME("Lock")));
  6964. tool_button[TOOL_UNLOCK_SELECTED]->set_button_icon(get_editor_theme_icon(SNAME("Unlock")));
  6965. tool_button[TOOL_GROUP_SELECTED]->set_button_icon(get_editor_theme_icon(SNAME("Group")));
  6966. tool_button[TOOL_UNGROUP_SELECTED]->set_button_icon(get_editor_theme_icon(SNAME("Ungroup")));
  6967. tool_button[TOOL_RULER]->set_button_icon(get_editor_theme_icon(SNAME("Ruler")));
  6968. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_button_icon(get_editor_theme_icon(SNAME("Object")));
  6969. tool_option_button[TOOL_OPT_USE_SNAP]->set_button_icon(get_editor_theme_icon(SNAME("Snap")));
  6970. view_layout_menu->get_popup()->set_item_icon(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), get_editor_theme_icon(SNAME("Panels1")));
  6971. view_layout_menu->get_popup()->set_item_icon(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), get_editor_theme_icon(SNAME("Panels2")));
  6972. view_layout_menu->get_popup()->set_item_icon(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), get_editor_theme_icon(SNAME("Panels2Alt")));
  6973. view_layout_menu->get_popup()->set_item_icon(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), get_editor_theme_icon(SNAME("Panels3")));
  6974. view_layout_menu->get_popup()->set_item_icon(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), get_editor_theme_icon(SNAME("Panels3Alt")));
  6975. view_layout_menu->get_popup()->set_item_icon(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), get_editor_theme_icon(SNAME("Panels4")));
  6976. sun_button->set_button_icon(get_editor_theme_icon(SNAME("PreviewSun")));
  6977. environ_button->set_button_icon(get_editor_theme_icon(SNAME("PreviewEnvironment")));
  6978. sun_environ_settings->set_button_icon(get_editor_theme_icon(SNAME("GuiTabMenuHl")));
  6979. sun_title->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("title_font"), SNAME("Window")));
  6980. environ_title->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("title_font"), SNAME("Window")));
  6981. sun_color->set_custom_minimum_size(Size2(0, get_theme_constant(SNAME("color_picker_button_height"), EditorStringName(Editor))));
  6982. environ_sky_color->set_custom_minimum_size(Size2(0, get_theme_constant(SNAME("color_picker_button_height"), EditorStringName(Editor))));
  6983. environ_ground_color->set_custom_minimum_size(Size2(0, get_theme_constant(SNAME("color_picker_button_height"), EditorStringName(Editor))));
  6984. context_toolbar_panel->add_theme_style_override(SceneStringName(panel), get_theme_stylebox(SNAME("ContextualToolbar"), EditorStringName(EditorStyles)));
  6985. }
  6986. void Node3DEditor::_notification(int p_what) {
  6987. switch (p_what) {
  6988. case NOTIFICATION_READY: {
  6989. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  6990. _refresh_menu_icons();
  6991. get_tree()->connect("node_removed", callable_mp(this, &Node3DEditor::_node_removed));
  6992. get_tree()->connect("node_added", callable_mp(this, &Node3DEditor::_node_added));
  6993. SceneTreeDock::get_singleton()->get_tree_editor()->connect("node_changed", callable_mp(this, &Node3DEditor::_refresh_menu_icons));
  6994. editor_selection->connect("selection_changed", callable_mp(this, &Node3DEditor::_selection_changed));
  6995. _update_preview_environment();
  6996. sun_state->set_custom_minimum_size(sun_vb->get_combined_minimum_size());
  6997. environ_state->set_custom_minimum_size(environ_vb->get_combined_minimum_size());
  6998. ProjectSettings::get_singleton()->connect("settings_changed", callable_mp(this, &Node3DEditor::update_all_gizmos).bind(Variant()));
  6999. } break;
  7000. case NOTIFICATION_ENTER_TREE: {
  7001. _update_theme();
  7002. _register_all_gizmos();
  7003. _update_gizmos_menu();
  7004. _init_indicators();
  7005. update_all_gizmos();
  7006. } break;
  7007. case NOTIFICATION_EXIT_TREE: {
  7008. _finish_indicators();
  7009. } break;
  7010. case NOTIFICATION_THEME_CHANGED: {
  7011. _update_theme();
  7012. _update_gizmos_menu_theme();
  7013. sun_title->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("title_font"), SNAME("Window")));
  7014. environ_title->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("title_font"), SNAME("Window")));
  7015. } break;
  7016. case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
  7017. if (EditorSettings::get_singleton()->check_changed_settings_in_group("editors/3d")) {
  7018. const Color selection_box_color = EDITOR_GET("editors/3d/selection_box_color");
  7019. const Color active_selection_box_color = EDITOR_GET("editors/3d/active_selection_box_color");
  7020. if (selection_box_color != selection_box_mat->get_albedo()) {
  7021. selection_box_mat->set_albedo(selection_box_color);
  7022. selection_box_mat_xray->set_albedo(selection_box_color * Color(1, 1, 1, 0.15));
  7023. }
  7024. if (active_selection_box_color != active_selection_box_mat->get_albedo()) {
  7025. active_selection_box_mat->set_albedo(active_selection_box_color);
  7026. active_selection_box_mat_xray->set_albedo(active_selection_box_color * Color(1, 1, 1, 0.15));
  7027. }
  7028. // Update grid color by rebuilding grid.
  7029. _finish_grid();
  7030. _init_grid();
  7031. }
  7032. } break;
  7033. case NOTIFICATION_PHYSICS_PROCESS: {
  7034. if (do_snap_selected_nodes_to_floor) {
  7035. _snap_selected_nodes_to_floor();
  7036. do_snap_selected_nodes_to_floor = false;
  7037. }
  7038. }
  7039. }
  7040. }
  7041. bool Node3DEditor::is_subgizmo_selected(int p_id) {
  7042. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  7043. if (se) {
  7044. return se->subgizmos.has(p_id);
  7045. }
  7046. return false;
  7047. }
  7048. bool Node3DEditor::is_current_selected_gizmo(const EditorNode3DGizmo *p_gizmo) {
  7049. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  7050. if (se) {
  7051. return se->gizmo == p_gizmo;
  7052. }
  7053. return false;
  7054. }
  7055. Vector<int> Node3DEditor::get_subgizmo_selection() {
  7056. Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
  7057. Vector<int> ret;
  7058. if (se) {
  7059. for (const KeyValue<int, Transform3D> &E : se->subgizmos) {
  7060. ret.push_back(E.key);
  7061. }
  7062. }
  7063. return ret;
  7064. }
  7065. void Node3DEditor::clear_subgizmo_selection(Object *p_obj) {
  7066. _clear_subgizmo_selection(p_obj);
  7067. }
  7068. void Node3DEditor::add_control_to_menu_panel(Control *p_control) {
  7069. ERR_FAIL_NULL(p_control);
  7070. ERR_FAIL_COND(p_control->get_parent());
  7071. VSeparator *sep = memnew(VSeparator);
  7072. context_toolbar_hbox->add_child(sep);
  7073. context_toolbar_hbox->add_child(p_control);
  7074. context_toolbar_separators[p_control] = sep;
  7075. p_control->connect(SceneStringName(visibility_changed), callable_mp(this, &Node3DEditor::_update_context_toolbar));
  7076. _update_context_toolbar();
  7077. }
  7078. void Node3DEditor::remove_control_from_menu_panel(Control *p_control) {
  7079. ERR_FAIL_NULL(p_control);
  7080. ERR_FAIL_COND(p_control->get_parent() != context_toolbar_hbox);
  7081. p_control->disconnect(SceneStringName(visibility_changed), callable_mp(this, &Node3DEditor::_update_context_toolbar));
  7082. VSeparator *sep = context_toolbar_separators[p_control];
  7083. context_toolbar_hbox->remove_child(sep);
  7084. context_toolbar_hbox->remove_child(p_control);
  7085. context_toolbar_separators.erase(p_control);
  7086. memdelete(sep);
  7087. _update_context_toolbar();
  7088. }
  7089. void Node3DEditor::_update_context_toolbar() {
  7090. bool has_visible = false;
  7091. bool first_visible = false;
  7092. for (int i = 0; i < context_toolbar_hbox->get_child_count(); i++) {
  7093. Control *child = Object::cast_to<Control>(context_toolbar_hbox->get_child(i));
  7094. if (!child || !context_toolbar_separators.has(child)) {
  7095. continue;
  7096. }
  7097. if (child->is_visible()) {
  7098. first_visible = !has_visible;
  7099. has_visible = true;
  7100. }
  7101. VSeparator *sep = context_toolbar_separators[child];
  7102. sep->set_visible(!first_visible && child->is_visible());
  7103. }
  7104. context_toolbar_panel->set_visible(has_visible);
  7105. }
  7106. void Node3DEditor::set_can_preview(Camera3D *p_preview) {
  7107. for (int i = 0; i < 4; i++) {
  7108. viewports[i]->set_can_preview(p_preview);
  7109. }
  7110. }
  7111. VSplitContainer *Node3DEditor::get_shader_split() {
  7112. return shader_split;
  7113. }
  7114. Node3DEditorViewport *Node3DEditor::get_last_used_viewport() {
  7115. return viewports[last_used_viewport];
  7116. }
  7117. void Node3DEditor::add_control_to_left_panel(Control *p_control) {
  7118. left_panel_split->add_child(p_control);
  7119. left_panel_split->move_child(p_control, 0);
  7120. }
  7121. void Node3DEditor::add_control_to_right_panel(Control *p_control) {
  7122. right_panel_split->add_child(p_control);
  7123. right_panel_split->move_child(p_control, 1);
  7124. }
  7125. void Node3DEditor::remove_control_from_left_panel(Control *p_control) {
  7126. left_panel_split->remove_child(p_control);
  7127. }
  7128. void Node3DEditor::remove_control_from_right_panel(Control *p_control) {
  7129. right_panel_split->remove_child(p_control);
  7130. }
  7131. void Node3DEditor::move_control_to_left_panel(Control *p_control) {
  7132. ERR_FAIL_NULL(p_control);
  7133. if (p_control->get_parent() == left_panel_split) {
  7134. return;
  7135. }
  7136. ERR_FAIL_COND(p_control->get_parent() != right_panel_split);
  7137. right_panel_split->remove_child(p_control);
  7138. add_control_to_left_panel(p_control);
  7139. }
  7140. void Node3DEditor::move_control_to_right_panel(Control *p_control) {
  7141. ERR_FAIL_NULL(p_control);
  7142. if (p_control->get_parent() == right_panel_split) {
  7143. return;
  7144. }
  7145. ERR_FAIL_COND(p_control->get_parent() != left_panel_split);
  7146. left_panel_split->remove_child(p_control);
  7147. add_control_to_right_panel(p_control);
  7148. }
  7149. void Node3DEditor::_request_gizmo(Object *p_obj) {
  7150. Node3D *sp = Object::cast_to<Node3D>(p_obj);
  7151. if (!sp) {
  7152. return;
  7153. }
  7154. bool is_selected = (sp == selected);
  7155. Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
  7156. if (edited_scene && (sp == edited_scene || (sp->get_owner() && edited_scene->is_ancestor_of(sp)))) {
  7157. for (int i = 0; i < gizmo_plugins_by_priority.size(); ++i) {
  7158. Ref<EditorNode3DGizmo> seg = gizmo_plugins_by_priority.write[i]->get_gizmo(sp);
  7159. if (seg.is_valid()) {
  7160. sp->add_gizmo(seg);
  7161. if (is_selected != seg->is_selected()) {
  7162. seg->set_selected(is_selected);
  7163. }
  7164. }
  7165. }
  7166. if (!sp->get_gizmos().is_empty()) {
  7167. sp->update_gizmos();
  7168. }
  7169. }
  7170. }
  7171. void Node3DEditor::_request_gizmo_for_id(ObjectID p_id) {
  7172. Node3D *node = Object::cast_to<Node3D>(ObjectDB::get_instance(p_id));
  7173. if (node) {
  7174. _request_gizmo(node);
  7175. }
  7176. }
  7177. void Node3DEditor::_set_subgizmo_selection(Object *p_obj, Ref<Node3DGizmo> p_gizmo, int p_id, Transform3D p_transform) {
  7178. if (p_id == -1) {
  7179. _clear_subgizmo_selection(p_obj);
  7180. return;
  7181. }
  7182. Node3D *sp = nullptr;
  7183. if (p_obj) {
  7184. sp = Object::cast_to<Node3D>(p_obj);
  7185. } else {
  7186. sp = selected;
  7187. }
  7188. if (!sp) {
  7189. return;
  7190. }
  7191. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  7192. if (se) {
  7193. se->subgizmos.clear();
  7194. se->subgizmos.insert(p_id, p_transform);
  7195. se->gizmo = p_gizmo;
  7196. sp->update_gizmos();
  7197. update_transform_gizmo();
  7198. }
  7199. }
  7200. void Node3DEditor::_clear_subgizmo_selection(Object *p_obj) {
  7201. Node3D *sp = nullptr;
  7202. if (p_obj) {
  7203. sp = Object::cast_to<Node3D>(p_obj);
  7204. } else {
  7205. sp = selected;
  7206. }
  7207. if (!sp) {
  7208. return;
  7209. }
  7210. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
  7211. if (se) {
  7212. se->subgizmos.clear();
  7213. se->gizmo.unref();
  7214. sp->update_gizmos();
  7215. update_transform_gizmo();
  7216. }
  7217. }
  7218. void Node3DEditor::_toggle_maximize_view(Object *p_viewport) {
  7219. if (!p_viewport) {
  7220. return;
  7221. }
  7222. Node3DEditorViewport *current_viewport = Object::cast_to<Node3DEditorViewport>(p_viewport);
  7223. if (!current_viewport) {
  7224. return;
  7225. }
  7226. int index = -1;
  7227. bool maximized = false;
  7228. for (int i = 0; i < 4; i++) {
  7229. if (viewports[i] == current_viewport) {
  7230. index = i;
  7231. if (current_viewport->get_global_rect() == viewport_base->get_global_rect()) {
  7232. maximized = true;
  7233. }
  7234. break;
  7235. }
  7236. }
  7237. if (index == -1) {
  7238. return;
  7239. }
  7240. if (!maximized) {
  7241. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  7242. if (i == (uint32_t)index) {
  7243. viewports[i]->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
  7244. } else {
  7245. viewports[i]->hide();
  7246. }
  7247. }
  7248. } else {
  7249. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  7250. viewports[i]->show();
  7251. }
  7252. if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT))) {
  7253. _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
  7254. } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS))) {
  7255. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
  7256. } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT))) {
  7257. _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
  7258. } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS))) {
  7259. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
  7260. } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT))) {
  7261. _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
  7262. } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS))) {
  7263. _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
  7264. }
  7265. }
  7266. }
  7267. void Node3DEditor::_viewport_clicked(int p_viewport_idx) {
  7268. last_used_viewport = p_viewport_idx;
  7269. }
  7270. void Node3DEditor::_node_added(Node *p_node) {
  7271. if (EditorNode::get_singleton()->get_scene_root()->is_ancestor_of(p_node)) {
  7272. if (Object::cast_to<WorldEnvironment>(p_node)) {
  7273. world_env_count++;
  7274. if (world_env_count == 1) {
  7275. _update_preview_environment();
  7276. }
  7277. } else if (Object::cast_to<DirectionalLight3D>(p_node)) {
  7278. directional_light_count++;
  7279. if (directional_light_count == 1) {
  7280. _update_preview_environment();
  7281. }
  7282. }
  7283. }
  7284. }
  7285. void Node3DEditor::_node_removed(Node *p_node) {
  7286. if (EditorNode::get_singleton()->get_scene_root()->is_ancestor_of(p_node)) {
  7287. if (Object::cast_to<WorldEnvironment>(p_node)) {
  7288. world_env_count--;
  7289. if (world_env_count == 0) {
  7290. _update_preview_environment();
  7291. }
  7292. } else if (Object::cast_to<DirectionalLight3D>(p_node)) {
  7293. directional_light_count--;
  7294. if (directional_light_count == 0) {
  7295. _update_preview_environment();
  7296. }
  7297. }
  7298. }
  7299. if (p_node == selected) {
  7300. Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected);
  7301. if (se) {
  7302. se->gizmo.unref();
  7303. se->subgizmos.clear();
  7304. }
  7305. selected = nullptr;
  7306. update_transform_gizmo();
  7307. }
  7308. }
  7309. void Node3DEditor::_register_all_gizmos() {
  7310. add_gizmo_plugin(Ref<Camera3DGizmoPlugin>(memnew(Camera3DGizmoPlugin)));
  7311. add_gizmo_plugin(Ref<Light3DGizmoPlugin>(memnew(Light3DGizmoPlugin)));
  7312. add_gizmo_plugin(Ref<AudioStreamPlayer3DGizmoPlugin>(memnew(AudioStreamPlayer3DGizmoPlugin)));
  7313. add_gizmo_plugin(Ref<AudioListener3DGizmoPlugin>(memnew(AudioListener3DGizmoPlugin)));
  7314. add_gizmo_plugin(Ref<MeshInstance3DGizmoPlugin>(memnew(MeshInstance3DGizmoPlugin)));
  7315. add_gizmo_plugin(Ref<OccluderInstance3DGizmoPlugin>(memnew(OccluderInstance3DGizmoPlugin)));
  7316. add_gizmo_plugin(Ref<SoftBody3DGizmoPlugin>(memnew(SoftBody3DGizmoPlugin)));
  7317. add_gizmo_plugin(Ref<SpriteBase3DGizmoPlugin>(memnew(SpriteBase3DGizmoPlugin)));
  7318. add_gizmo_plugin(Ref<Label3DGizmoPlugin>(memnew(Label3DGizmoPlugin)));
  7319. add_gizmo_plugin(Ref<GeometryInstance3DGizmoPlugin>(memnew(GeometryInstance3DGizmoPlugin)));
  7320. add_gizmo_plugin(Ref<Marker3DGizmoPlugin>(memnew(Marker3DGizmoPlugin)));
  7321. add_gizmo_plugin(Ref<RayCast3DGizmoPlugin>(memnew(RayCast3DGizmoPlugin)));
  7322. add_gizmo_plugin(Ref<ShapeCast3DGizmoPlugin>(memnew(ShapeCast3DGizmoPlugin)));
  7323. add_gizmo_plugin(Ref<SpringArm3DGizmoPlugin>(memnew(SpringArm3DGizmoPlugin)));
  7324. add_gizmo_plugin(Ref<SpringBoneCollision3DGizmoPlugin>(memnew(SpringBoneCollision3DGizmoPlugin)));
  7325. add_gizmo_plugin(Ref<SpringBoneSimulator3DGizmoPlugin>(memnew(SpringBoneSimulator3DGizmoPlugin)));
  7326. add_gizmo_plugin(Ref<VehicleWheel3DGizmoPlugin>(memnew(VehicleWheel3DGizmoPlugin)));
  7327. add_gizmo_plugin(Ref<VisibleOnScreenNotifier3DGizmoPlugin>(memnew(VisibleOnScreenNotifier3DGizmoPlugin)));
  7328. add_gizmo_plugin(Ref<GPUParticles3DGizmoPlugin>(memnew(GPUParticles3DGizmoPlugin)));
  7329. add_gizmo_plugin(Ref<GPUParticlesCollision3DGizmoPlugin>(memnew(GPUParticlesCollision3DGizmoPlugin)));
  7330. add_gizmo_plugin(Ref<Particles3DEmissionShapeGizmoPlugin>(memnew(Particles3DEmissionShapeGizmoPlugin)));
  7331. add_gizmo_plugin(Ref<CPUParticles3DGizmoPlugin>(memnew(CPUParticles3DGizmoPlugin)));
  7332. add_gizmo_plugin(Ref<ReflectionProbeGizmoPlugin>(memnew(ReflectionProbeGizmoPlugin)));
  7333. add_gizmo_plugin(Ref<DecalGizmoPlugin>(memnew(DecalGizmoPlugin)));
  7334. add_gizmo_plugin(Ref<VoxelGIGizmoPlugin>(memnew(VoxelGIGizmoPlugin)));
  7335. add_gizmo_plugin(Ref<LightmapGIGizmoPlugin>(memnew(LightmapGIGizmoPlugin)));
  7336. add_gizmo_plugin(Ref<LightmapProbeGizmoPlugin>(memnew(LightmapProbeGizmoPlugin)));
  7337. add_gizmo_plugin(Ref<CollisionObject3DGizmoPlugin>(memnew(CollisionObject3DGizmoPlugin)));
  7338. add_gizmo_plugin(Ref<CollisionShape3DGizmoPlugin>(memnew(CollisionShape3DGizmoPlugin)));
  7339. add_gizmo_plugin(Ref<CollisionPolygon3DGizmoPlugin>(memnew(CollisionPolygon3DGizmoPlugin)));
  7340. add_gizmo_plugin(Ref<NavigationLink3DGizmoPlugin>(memnew(NavigationLink3DGizmoPlugin)));
  7341. add_gizmo_plugin(Ref<NavigationRegion3DGizmoPlugin>(memnew(NavigationRegion3DGizmoPlugin)));
  7342. add_gizmo_plugin(Ref<Joint3DGizmoPlugin>(memnew(Joint3DGizmoPlugin)));
  7343. add_gizmo_plugin(Ref<PhysicalBone3DGizmoPlugin>(memnew(PhysicalBone3DGizmoPlugin)));
  7344. add_gizmo_plugin(Ref<FogVolumeGizmoPlugin>(memnew(FogVolumeGizmoPlugin)));
  7345. }
  7346. void Node3DEditor::_bind_methods() {
  7347. ClassDB::bind_method("_get_editor_data", &Node3DEditor::_get_editor_data);
  7348. ClassDB::bind_method("_request_gizmo", &Node3DEditor::_request_gizmo);
  7349. ClassDB::bind_method("_request_gizmo_for_id", &Node3DEditor::_request_gizmo_for_id);
  7350. ClassDB::bind_method("_set_subgizmo_selection", &Node3DEditor::_set_subgizmo_selection);
  7351. ClassDB::bind_method("_clear_subgizmo_selection", &Node3DEditor::_clear_subgizmo_selection);
  7352. ClassDB::bind_method("_refresh_menu_icons", &Node3DEditor::_refresh_menu_icons);
  7353. ClassDB::bind_method("update_all_gizmos", &Node3DEditor::update_all_gizmos);
  7354. ClassDB::bind_method("update_transform_gizmo", &Node3DEditor::update_transform_gizmo);
  7355. ADD_SIGNAL(MethodInfo("transform_key_request"));
  7356. ADD_SIGNAL(MethodInfo("item_lock_status_changed"));
  7357. ADD_SIGNAL(MethodInfo("item_group_status_changed"));
  7358. }
  7359. void Node3DEditor::clear() {
  7360. settings_fov->set_value(EDITOR_GET("editors/3d/default_fov"));
  7361. settings_znear->set_value(EDITOR_GET("editors/3d/default_z_near"));
  7362. settings_zfar->set_value(EDITOR_GET("editors/3d/default_z_far"));
  7363. snap_translate_value = EditorSettings::get_singleton()->get_project_metadata("3d_editor", "snap_translate_value", 1);
  7364. snap_rotate_value = EditorSettings::get_singleton()->get_project_metadata("3d_editor", "snap_rotate_value", 15);
  7365. snap_scale_value = EditorSettings::get_singleton()->get_project_metadata("3d_editor", "snap_scale_value", 10);
  7366. _snap_update();
  7367. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  7368. viewports[i]->reset();
  7369. }
  7370. if (origin_instance.is_valid()) {
  7371. RenderingServer::get_singleton()->instance_set_visible(origin_instance, true);
  7372. }
  7373. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), true);
  7374. for (int i = 0; i < 3; ++i) {
  7375. if (grid_enable[i]) {
  7376. grid_visible[i] = true;
  7377. }
  7378. }
  7379. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  7380. viewports[i]->view_display_menu->get_popup()->set_item_checked(viewports[i]->view_display_menu->get_popup()->get_item_index(Node3DEditorViewport::VIEW_AUDIO_LISTENER), i == 0);
  7381. viewports[i]->viewport->set_as_audio_listener_3d(i == 0);
  7382. }
  7383. view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_GRID), true);
  7384. grid_enabled = true;
  7385. grid_init_draw = false;
  7386. }
  7387. void Node3DEditor::_sun_direction_draw() {
  7388. sun_direction->draw_rect(Rect2(Vector2(), sun_direction->get_size()), Color(1, 1, 1, 1));
  7389. Vector3 z_axis = preview_sun->get_transform().basis.get_column(Vector3::AXIS_Z);
  7390. z_axis = get_editor_viewport(0)->camera->get_camera_transform().basis.xform_inv(z_axis);
  7391. sun_direction_material->set_shader_parameter("sun_direction", Vector3(z_axis.x, -z_axis.y, z_axis.z));
  7392. Color color = sun_color->get_pick_color() * sun_energy->get_value();
  7393. sun_direction_material->set_shader_parameter("sun_color", Vector3(color.r, color.g, color.b));
  7394. }
  7395. void Node3DEditor::_preview_settings_changed() {
  7396. if (sun_environ_updating) {
  7397. return;
  7398. }
  7399. { // preview sun
  7400. Transform3D t;
  7401. t.basis = Basis::from_euler(Vector3(sun_rotation.x, sun_rotation.y, 0));
  7402. preview_sun->set_transform(t);
  7403. sun_direction->queue_redraw();
  7404. preview_sun->set_param(Light3D::PARAM_ENERGY, sun_energy->get_value());
  7405. preview_sun->set_param(Light3D::PARAM_SHADOW_MAX_DISTANCE, sun_max_distance->get_value());
  7406. preview_sun->set_color(sun_color->get_pick_color());
  7407. }
  7408. { //preview env
  7409. sky_material->set_energy_multiplier(environ_energy->get_value());
  7410. Color hz_color = environ_sky_color->get_pick_color().lerp(environ_ground_color->get_pick_color(), 0.5);
  7411. float hz_lum = hz_color.get_luminance() * 3.333;
  7412. hz_color = hz_color.lerp(Color(hz_lum, hz_lum, hz_lum), 0.5);
  7413. sky_material->set_sky_top_color(environ_sky_color->get_pick_color());
  7414. sky_material->set_sky_horizon_color(hz_color);
  7415. sky_material->set_ground_bottom_color(environ_ground_color->get_pick_color());
  7416. sky_material->set_ground_horizon_color(hz_color);
  7417. environment->set_ssao_enabled(environ_ao_button->is_pressed());
  7418. environment->set_glow_enabled(environ_glow_button->is_pressed());
  7419. environment->set_sdfgi_enabled(environ_gi_button->is_pressed());
  7420. environment->set_tonemapper(environ_tonemap_button->is_pressed() ? Environment::TONE_MAPPER_FILMIC : Environment::TONE_MAPPER_LINEAR);
  7421. }
  7422. }
  7423. void Node3DEditor::_load_default_preview_settings() {
  7424. sun_environ_updating = true;
  7425. // These default rotations place the preview sun at an angular altitude
  7426. // of 60 degrees (must be negative) and an azimuth of 30 degrees clockwise
  7427. // from north (or 150 CCW from south), from north east, facing south west.
  7428. // On any not-tidally-locked planet, a sun would have an angular altitude
  7429. // of 60 degrees as the average of all points on the sphere at noon.
  7430. // The azimuth choice is arbitrary, but ideally shouldn't be on an axis.
  7431. sun_rotation = Vector2(-Math::deg_to_rad(60.0), Math::deg_to_rad(150.0));
  7432. sun_angle_altitude->set_value(-Math::rad_to_deg(sun_rotation.x));
  7433. sun_angle_azimuth->set_value(180.0 - Math::rad_to_deg(sun_rotation.y));
  7434. sun_direction->queue_redraw();
  7435. environ_sky_color->set_pick_color(Color(0.385, 0.454, 0.55));
  7436. environ_ground_color->set_pick_color(Color(0.2, 0.169, 0.133));
  7437. environ_energy->set_value(1.0);
  7438. if (OS::get_singleton()->get_current_rendering_method() != "gl_compatibility") {
  7439. environ_glow_button->set_pressed(true);
  7440. }
  7441. environ_tonemap_button->set_pressed(true);
  7442. environ_ao_button->set_pressed(false);
  7443. environ_gi_button->set_pressed(false);
  7444. sun_max_distance->set_value(100);
  7445. sun_color->set_pick_color(Color(1, 1, 1));
  7446. sun_energy->set_value(1.0);
  7447. sun_environ_updating = false;
  7448. }
  7449. void Node3DEditor::_update_preview_environment() {
  7450. bool disable_light = directional_light_count > 0 || !sun_button->is_pressed();
  7451. sun_button->set_disabled(directional_light_count > 0);
  7452. if (disable_light) {
  7453. if (preview_sun->get_parent()) {
  7454. preview_sun->get_parent()->remove_child(preview_sun);
  7455. sun_state->show();
  7456. sun_vb->hide();
  7457. preview_sun_dangling = true;
  7458. }
  7459. if (directional_light_count > 0) {
  7460. sun_state->set_text(TTR("Scene contains\nDirectionalLight3D.\nPreview disabled."));
  7461. } else {
  7462. sun_state->set_text(TTR("Preview disabled."));
  7463. }
  7464. } else {
  7465. if (!preview_sun->get_parent()) {
  7466. add_child(preview_sun, true);
  7467. sun_state->hide();
  7468. sun_vb->show();
  7469. preview_sun_dangling = false;
  7470. }
  7471. }
  7472. sun_angle_altitude->set_value(-Math::rad_to_deg(sun_rotation.x));
  7473. sun_angle_azimuth->set_value(180.0 - Math::rad_to_deg(sun_rotation.y));
  7474. bool disable_env = world_env_count > 0 || !environ_button->is_pressed();
  7475. environ_button->set_disabled(world_env_count > 0);
  7476. if (disable_env) {
  7477. if (preview_environment->get_parent()) {
  7478. preview_environment->get_parent()->remove_child(preview_environment);
  7479. environ_state->show();
  7480. environ_vb->hide();
  7481. preview_env_dangling = true;
  7482. }
  7483. if (world_env_count > 0) {
  7484. environ_state->set_text(TTR("Scene contains\nWorldEnvironment.\nPreview disabled."));
  7485. } else {
  7486. environ_state->set_text(TTR("Preview disabled."));
  7487. }
  7488. } else {
  7489. if (!preview_environment->get_parent()) {
  7490. add_child(preview_environment);
  7491. environ_state->hide();
  7492. environ_vb->show();
  7493. preview_env_dangling = false;
  7494. }
  7495. }
  7496. }
  7497. void Node3DEditor::_sun_direction_input(const Ref<InputEvent> &p_event) {
  7498. Ref<InputEventMouseMotion> mm = p_event;
  7499. if (mm.is_valid() && (mm->get_button_mask().has_flag(MouseButtonMask::LEFT))) {
  7500. sun_rotation.x += mm->get_relative().y * (0.02 * EDSCALE);
  7501. sun_rotation.y -= mm->get_relative().x * (0.02 * EDSCALE);
  7502. sun_rotation.x = CLAMP(sun_rotation.x, -Math_TAU / 4, Math_TAU / 4);
  7503. sun_angle_altitude->set_value(-Math::rad_to_deg(sun_rotation.x));
  7504. sun_angle_azimuth->set_value(180.0 - Math::rad_to_deg(sun_rotation.y));
  7505. _preview_settings_changed();
  7506. }
  7507. }
  7508. void Node3DEditor::_sun_direction_angle_set() {
  7509. sun_rotation.x = Math::deg_to_rad(-sun_angle_altitude->get_value());
  7510. sun_rotation.y = Math::deg_to_rad(180.0 - sun_angle_azimuth->get_value());
  7511. _preview_settings_changed();
  7512. }
  7513. Node3DEditor::Node3DEditor() {
  7514. gizmo.visible = true;
  7515. gizmo.scale = 1.0;
  7516. viewport_environment.instantiate();
  7517. VBoxContainer *vbc = this;
  7518. custom_camera = nullptr;
  7519. ERR_FAIL_COND_MSG(singleton != nullptr, "A Node3DEditor singleton already exists.");
  7520. singleton = this;
  7521. editor_selection = EditorNode::get_singleton()->get_editor_selection();
  7522. editor_selection->add_editor_plugin(this);
  7523. snap_enabled = false;
  7524. snap_key_enabled = false;
  7525. tool_mode = TOOL_MODE_SELECT;
  7526. // Add some margin to the sides for better aesthetics.
  7527. // This prevents the first button's hover/pressed effect from "touching" the panel's border,
  7528. // which looks ugly.
  7529. MarginContainer *toolbar_margin = memnew(MarginContainer);
  7530. toolbar_margin->add_theme_constant_override("margin_left", 4 * EDSCALE);
  7531. toolbar_margin->add_theme_constant_override("margin_right", 4 * EDSCALE);
  7532. vbc->add_child(toolbar_margin);
  7533. // A fluid container for all toolbars.
  7534. HFlowContainer *main_flow = memnew(HFlowContainer);
  7535. toolbar_margin->add_child(main_flow);
  7536. // Main toolbars.
  7537. HBoxContainer *main_menu_hbox = memnew(HBoxContainer);
  7538. main_flow->add_child(main_menu_hbox);
  7539. String sct;
  7540. tool_button[TOOL_MODE_SELECT] = memnew(Button);
  7541. main_menu_hbox->add_child(tool_button[TOOL_MODE_SELECT]);
  7542. tool_button[TOOL_MODE_SELECT]->set_toggle_mode(true);
  7543. tool_button[TOOL_MODE_SELECT]->set_theme_type_variation(SceneStringName(FlatButton));
  7544. tool_button[TOOL_MODE_SELECT]->set_pressed(true);
  7545. tool_button[TOOL_MODE_SELECT]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_SELECT));
  7546. tool_button[TOOL_MODE_SELECT]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_select", TTRC("Select Mode"), Key::Q, true));
  7547. tool_button[TOOL_MODE_SELECT]->set_shortcut_context(this);
  7548. tool_button[TOOL_MODE_SELECT]->set_tooltip_text(keycode_get_string((Key)KeyModifierMask::CMD_OR_CTRL) + TTR("Drag: Rotate selected node around pivot.") + "\n" + TTR("Alt+RMB: Show list of all nodes at position clicked, including locked.") + "\n" + TTR("(Available in all modes.)"));
  7549. main_menu_hbox->add_child(memnew(VSeparator));
  7550. tool_button[TOOL_MODE_MOVE] = memnew(Button);
  7551. main_menu_hbox->add_child(tool_button[TOOL_MODE_MOVE]);
  7552. tool_button[TOOL_MODE_MOVE]->set_toggle_mode(true);
  7553. tool_button[TOOL_MODE_MOVE]->set_theme_type_variation(SceneStringName(FlatButton));
  7554. tool_button[TOOL_MODE_MOVE]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_MOVE));
  7555. tool_button[TOOL_MODE_MOVE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_move", TTRC("Move Mode"), Key::W, true));
  7556. tool_button[TOOL_MODE_MOVE]->set_shortcut_context(this);
  7557. tool_button[TOOL_MODE_MOVE]->set_tooltip_text(keycode_get_string((Key)KeyModifierMask::CMD_OR_CTRL) + TTR("Drag: Use snap.") + "\n" + TTR("Alt+RMB: Show list of all nodes at position clicked, including locked."));
  7558. tool_button[TOOL_MODE_ROTATE] = memnew(Button);
  7559. main_menu_hbox->add_child(tool_button[TOOL_MODE_ROTATE]);
  7560. tool_button[TOOL_MODE_ROTATE]->set_toggle_mode(true);
  7561. tool_button[TOOL_MODE_ROTATE]->set_theme_type_variation(SceneStringName(FlatButton));
  7562. tool_button[TOOL_MODE_ROTATE]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_ROTATE));
  7563. tool_button[TOOL_MODE_ROTATE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_rotate", TTRC("Rotate Mode"), Key::E, true));
  7564. tool_button[TOOL_MODE_ROTATE]->set_shortcut_context(this);
  7565. tool_button[TOOL_MODE_ROTATE]->set_tooltip_text(keycode_get_string((Key)KeyModifierMask::CMD_OR_CTRL) + TTR("Drag: Use snap.") + "\n" + TTR("Alt+RMB: Show list of all nodes at position clicked, including locked."));
  7566. tool_button[TOOL_MODE_SCALE] = memnew(Button);
  7567. main_menu_hbox->add_child(tool_button[TOOL_MODE_SCALE]);
  7568. tool_button[TOOL_MODE_SCALE]->set_toggle_mode(true);
  7569. tool_button[TOOL_MODE_SCALE]->set_theme_type_variation(SceneStringName(FlatButton));
  7570. tool_button[TOOL_MODE_SCALE]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_SCALE));
  7571. tool_button[TOOL_MODE_SCALE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_scale", TTRC("Scale Mode"), Key::R, true));
  7572. tool_button[TOOL_MODE_SCALE]->set_shortcut_context(this);
  7573. tool_button[TOOL_MODE_SCALE]->set_tooltip_text(keycode_get_string((Key)KeyModifierMask::CMD_OR_CTRL) + TTR("Drag: Use snap.") + "\n" + TTR("Alt+RMB: Show list of all nodes at position clicked, including locked."));
  7574. main_menu_hbox->add_child(memnew(VSeparator));
  7575. tool_button[TOOL_MODE_LIST_SELECT] = memnew(Button);
  7576. main_menu_hbox->add_child(tool_button[TOOL_MODE_LIST_SELECT]);
  7577. tool_button[TOOL_MODE_LIST_SELECT]->set_toggle_mode(true);
  7578. tool_button[TOOL_MODE_LIST_SELECT]->set_theme_type_variation(SceneStringName(FlatButton));
  7579. tool_button[TOOL_MODE_LIST_SELECT]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_LIST_SELECT));
  7580. tool_button[TOOL_MODE_LIST_SELECT]->set_tooltip_text(TTR("Show list of selectable nodes at position clicked."));
  7581. tool_button[TOOL_LOCK_SELECTED] = memnew(Button);
  7582. main_menu_hbox->add_child(tool_button[TOOL_LOCK_SELECTED]);
  7583. tool_button[TOOL_LOCK_SELECTED]->set_theme_type_variation(SceneStringName(FlatButton));
  7584. tool_button[TOOL_LOCK_SELECTED]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_LOCK_SELECTED));
  7585. tool_button[TOOL_LOCK_SELECTED]->set_tooltip_text(TTRC("Lock selected node, preventing selection and movement."));
  7586. // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
  7587. tool_button[TOOL_LOCK_SELECTED]->set_shortcut(ED_GET_SHORTCUT("editor/lock_selected_nodes"));
  7588. tool_button[TOOL_UNLOCK_SELECTED] = memnew(Button);
  7589. main_menu_hbox->add_child(tool_button[TOOL_UNLOCK_SELECTED]);
  7590. tool_button[TOOL_UNLOCK_SELECTED]->set_theme_type_variation(SceneStringName(FlatButton));
  7591. tool_button[TOOL_UNLOCK_SELECTED]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_UNLOCK_SELECTED));
  7592. tool_button[TOOL_UNLOCK_SELECTED]->set_tooltip_text(TTRC("Unlock selected node, allowing selection and movement."));
  7593. // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
  7594. tool_button[TOOL_UNLOCK_SELECTED]->set_shortcut(ED_GET_SHORTCUT("editor/unlock_selected_nodes"));
  7595. tool_button[TOOL_GROUP_SELECTED] = memnew(Button);
  7596. main_menu_hbox->add_child(tool_button[TOOL_GROUP_SELECTED]);
  7597. tool_button[TOOL_GROUP_SELECTED]->set_theme_type_variation(SceneStringName(FlatButton));
  7598. tool_button[TOOL_GROUP_SELECTED]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_GROUP_SELECTED));
  7599. tool_button[TOOL_GROUP_SELECTED]->set_tooltip_text(TTRC("Groups the selected node with its children. This selects the parent when any child node is clicked in 2D and 3D view."));
  7600. // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
  7601. tool_button[TOOL_GROUP_SELECTED]->set_shortcut(ED_GET_SHORTCUT("editor/group_selected_nodes"));
  7602. tool_button[TOOL_UNGROUP_SELECTED] = memnew(Button);
  7603. main_menu_hbox->add_child(tool_button[TOOL_UNGROUP_SELECTED]);
  7604. tool_button[TOOL_UNGROUP_SELECTED]->set_theme_type_variation(SceneStringName(FlatButton));
  7605. tool_button[TOOL_UNGROUP_SELECTED]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_UNGROUP_SELECTED));
  7606. tool_button[TOOL_UNGROUP_SELECTED]->set_tooltip_text(TTRC("Ungroups the selected node from its children. Child nodes will be individual items in 2D and 3D view."));
  7607. // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
  7608. tool_button[TOOL_UNGROUP_SELECTED]->set_shortcut(ED_GET_SHORTCUT("editor/ungroup_selected_nodes"));
  7609. tool_button[TOOL_RULER] = memnew(Button);
  7610. main_menu_hbox->add_child(tool_button[TOOL_RULER]);
  7611. tool_button[TOOL_RULER]->set_toggle_mode(true);
  7612. tool_button[TOOL_RULER]->set_theme_type_variation("FlatButton");
  7613. tool_button[TOOL_RULER]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_RULER));
  7614. tool_button[TOOL_RULER]->set_tooltip_text(TTRC("LMB+Drag: Measure the distance between two points in 3D space."));
  7615. // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
  7616. tool_button[TOOL_RULER]->set_shortcut(ED_SHORTCUT("spatial_editor/measure", TTRC("Ruler Mode"), Key::M));
  7617. main_menu_hbox->add_child(memnew(VSeparator));
  7618. tool_option_button[TOOL_OPT_LOCAL_COORDS] = memnew(Button);
  7619. main_menu_hbox->add_child(tool_option_button[TOOL_OPT_LOCAL_COORDS]);
  7620. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_toggle_mode(true);
  7621. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_theme_type_variation(SceneStringName(FlatButton));
  7622. tool_option_button[TOOL_OPT_LOCAL_COORDS]->connect(SceneStringName(toggled), callable_mp(this, &Node3DEditor::_menu_item_toggled).bind(MENU_TOOL_LOCAL_COORDS));
  7623. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_shortcut(ED_SHORTCUT("spatial_editor/local_coords", TTRC("Use Local Space"), Key::T));
  7624. tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_shortcut_context(this);
  7625. tool_option_button[TOOL_OPT_USE_SNAP] = memnew(Button);
  7626. main_menu_hbox->add_child(tool_option_button[TOOL_OPT_USE_SNAP]);
  7627. tool_option_button[TOOL_OPT_USE_SNAP]->set_toggle_mode(true);
  7628. tool_option_button[TOOL_OPT_USE_SNAP]->set_theme_type_variation(SceneStringName(FlatButton));
  7629. tool_option_button[TOOL_OPT_USE_SNAP]->connect(SceneStringName(toggled), callable_mp(this, &Node3DEditor::_menu_item_toggled).bind(MENU_TOOL_USE_SNAP));
  7630. tool_option_button[TOOL_OPT_USE_SNAP]->set_shortcut(ED_SHORTCUT("spatial_editor/snap", TTRC("Use Snap"), Key::Y));
  7631. tool_option_button[TOOL_OPT_USE_SNAP]->set_shortcut_context(this);
  7632. main_menu_hbox->add_child(memnew(VSeparator));
  7633. sun_button = memnew(Button);
  7634. sun_button->set_tooltip_text(TTR("Toggle preview sunlight.\nIf a DirectionalLight3D node is added to the scene, preview sunlight is disabled."));
  7635. sun_button->set_toggle_mode(true);
  7636. sun_button->set_theme_type_variation(SceneStringName(FlatButton));
  7637. sun_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_update_preview_environment), CONNECT_DEFERRED);
  7638. // Preview is enabled by default - ensure this applies on editor startup when there is no state yet.
  7639. sun_button->set_pressed(true);
  7640. main_menu_hbox->add_child(sun_button);
  7641. environ_button = memnew(Button);
  7642. environ_button->set_tooltip_text(TTR("Toggle preview environment.\nIf a WorldEnvironment node is added to the scene, preview environment is disabled."));
  7643. environ_button->set_toggle_mode(true);
  7644. environ_button->set_theme_type_variation(SceneStringName(FlatButton));
  7645. environ_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_update_preview_environment), CONNECT_DEFERRED);
  7646. // Preview is enabled by default - ensure this applies on editor startup when there is no state yet.
  7647. environ_button->set_pressed(true);
  7648. main_menu_hbox->add_child(environ_button);
  7649. sun_environ_settings = memnew(Button);
  7650. sun_environ_settings->set_tooltip_text(TTR("Edit Sun and Environment settings."));
  7651. sun_environ_settings->set_theme_type_variation(SceneStringName(FlatButton));
  7652. sun_environ_settings->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_sun_environ_settings_pressed));
  7653. main_menu_hbox->add_child(sun_environ_settings);
  7654. main_menu_hbox->add_child(memnew(VSeparator));
  7655. // Drag and drop support;
  7656. preview_node = memnew(Node3D);
  7657. preview_bounds = AABB();
  7658. ED_SHORTCUT("spatial_editor/bottom_view", TTRC("Bottom View"), KeyModifierMask::ALT + Key::KP_7);
  7659. ED_SHORTCUT("spatial_editor/top_view", TTRC("Top View"), Key::KP_7);
  7660. ED_SHORTCUT("spatial_editor/rear_view", TTRC("Rear View"), KeyModifierMask::ALT + Key::KP_1);
  7661. ED_SHORTCUT("spatial_editor/front_view", TTRC("Front View"), Key::KP_1);
  7662. ED_SHORTCUT("spatial_editor/left_view", TTRC("Left View"), KeyModifierMask::ALT + Key::KP_3);
  7663. ED_SHORTCUT("spatial_editor/right_view", TTRC("Right View"), Key::KP_3);
  7664. ED_SHORTCUT("spatial_editor/orbit_view_down", TTRC("Orbit View Down"), Key::KP_2);
  7665. ED_SHORTCUT("spatial_editor/orbit_view_left", TTRC("Orbit View Left"), Key::KP_4);
  7666. ED_SHORTCUT("spatial_editor/orbit_view_right", TTRC("Orbit View Right"), Key::KP_6);
  7667. ED_SHORTCUT("spatial_editor/orbit_view_up", TTRC("Orbit View Up"), Key::KP_8);
  7668. ED_SHORTCUT("spatial_editor/orbit_view_180", TTRC("Orbit View 180"), Key::KP_9);
  7669. ED_SHORTCUT("spatial_editor/switch_perspective_orthogonal", TTRC("Switch Perspective/Orthogonal View"), Key::KP_5);
  7670. ED_SHORTCUT("spatial_editor/insert_anim_key", TTRC("Insert Animation Key"), Key::K);
  7671. ED_SHORTCUT("spatial_editor/focus_origin", TTRC("Focus Origin"), Key::O);
  7672. ED_SHORTCUT("spatial_editor/focus_selection", TTRC("Focus Selection"), Key::F);
  7673. ED_SHORTCUT_ARRAY("spatial_editor/align_transform_with_view", TTRC("Align Transform with View"),
  7674. { int32_t(KeyModifierMask::ALT | KeyModifierMask::CTRL | Key::KP_0),
  7675. int32_t(KeyModifierMask::ALT | KeyModifierMask::CTRL | Key::M),
  7676. int32_t(KeyModifierMask::ALT | KeyModifierMask::CTRL | Key::G) });
  7677. ED_SHORTCUT_OVERRIDE_ARRAY("spatial_editor/align_transform_with_view", "macos",
  7678. { int32_t(KeyModifierMask::ALT | KeyModifierMask::META | Key::KP_0),
  7679. int32_t(KeyModifierMask::ALT | KeyModifierMask::META | Key::G) });
  7680. ED_SHORTCUT("spatial_editor/align_rotation_with_view", TTRC("Align Rotation with View"), KeyModifierMask::ALT + KeyModifierMask::CMD_OR_CTRL + Key::F);
  7681. ED_SHORTCUT("spatial_editor/freelook_toggle", TTRC("Toggle Freelook"), KeyModifierMask::SHIFT + Key::F);
  7682. ED_SHORTCUT("spatial_editor/decrease_fov", TTRC("Decrease Field of View"), KeyModifierMask::CMD_OR_CTRL + Key::EQUAL); // Usually direct access key for `KEY_PLUS`.
  7683. ED_SHORTCUT("spatial_editor/increase_fov", TTRC("Increase Field of View"), KeyModifierMask::CMD_OR_CTRL + Key::MINUS);
  7684. ED_SHORTCUT("spatial_editor/reset_fov", TTRC("Reset Field of View to Default"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_0);
  7685. PopupMenu *p;
  7686. transform_menu = memnew(MenuButton);
  7687. transform_menu->set_flat(false);
  7688. transform_menu->set_theme_type_variation("FlatMenuButton");
  7689. transform_menu->set_text(TTR("Transform"));
  7690. transform_menu->set_switch_on_hover(true);
  7691. transform_menu->set_shortcut_context(this);
  7692. main_menu_hbox->add_child(transform_menu);
  7693. p = transform_menu->get_popup();
  7694. p->add_shortcut(ED_SHORTCUT("spatial_editor/snap_to_floor", TTRC("Snap Object to Floor"), Key::PAGEDOWN), MENU_SNAP_TO_FLOOR);
  7695. p->add_shortcut(ED_SHORTCUT("spatial_editor/transform_dialog", TTRC("Transform Dialog...")), MENU_TRANSFORM_DIALOG);
  7696. p->add_separator();
  7697. p->add_shortcut(ED_SHORTCUT("spatial_editor/configure_snap", TTRC("Configure Snap...")), MENU_TRANSFORM_CONFIGURE_SNAP);
  7698. p->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed));
  7699. view_layout_menu = memnew(MenuButton);
  7700. view_layout_menu->set_flat(false);
  7701. view_layout_menu->set_theme_type_variation("FlatMenuButton");
  7702. // TRANSLATORS: Noun, name of the 2D/3D View menus.
  7703. view_layout_menu->set_text(TTR("View"));
  7704. view_layout_menu->set_switch_on_hover(true);
  7705. view_layout_menu->set_shortcut_context(this);
  7706. main_menu_hbox->add_child(view_layout_menu);
  7707. main_menu_hbox->add_child(memnew(VSeparator));
  7708. context_toolbar_panel = memnew(PanelContainer);
  7709. context_toolbar_hbox = memnew(HBoxContainer);
  7710. context_toolbar_panel->add_child(context_toolbar_hbox);
  7711. main_flow->add_child(context_toolbar_panel);
  7712. // Get the view menu popup and have it stay open when a checkable item is selected
  7713. p = view_layout_menu->get_popup();
  7714. p->set_hide_on_checkable_item_selection(false);
  7715. accept = memnew(AcceptDialog);
  7716. EditorNode::get_singleton()->get_gui_base()->add_child(accept);
  7717. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/1_viewport", TTRC("1 Viewport"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_1), MENU_VIEW_USE_1_VIEWPORT);
  7718. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports", TTRC("2 Viewports"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_2), MENU_VIEW_USE_2_VIEWPORTS);
  7719. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports_alt", TTRC("2 Viewports (Alt)"), KeyModifierMask::ALT + KeyModifierMask::CMD_OR_CTRL + Key::KEY_2), MENU_VIEW_USE_2_VIEWPORTS_ALT);
  7720. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports", TTRC("3 Viewports"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_3), MENU_VIEW_USE_3_VIEWPORTS);
  7721. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports_alt", TTRC("3 Viewports (Alt)"), KeyModifierMask::ALT + KeyModifierMask::CMD_OR_CTRL + Key::KEY_3), MENU_VIEW_USE_3_VIEWPORTS_ALT);
  7722. p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/4_viewports", TTRC("4 Viewports"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_4), MENU_VIEW_USE_4_VIEWPORTS);
  7723. p->add_separator();
  7724. gizmos_menu = memnew(PopupMenu);
  7725. gizmos_menu->set_hide_on_checkable_item_selection(false);
  7726. p->add_submenu_node_item(TTR("Gizmos"), gizmos_menu);
  7727. gizmos_menu->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditor::_menu_gizmo_toggled));
  7728. p->add_separator();
  7729. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_origin", TTRC("View Origin")), MENU_VIEW_ORIGIN);
  7730. p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_grid", TTRC("View Grid"), Key::NUMBERSIGN), MENU_VIEW_GRID);
  7731. p->add_separator();
  7732. p->add_shortcut(ED_SHORTCUT("spatial_editor/settings", TTRC("Settings...")), MENU_VIEW_CAMERA_SETTINGS);
  7733. p->set_item_checked(p->get_item_index(MENU_VIEW_ORIGIN), true);
  7734. p->set_item_checked(p->get_item_index(MENU_VIEW_GRID), true);
  7735. p->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed));
  7736. /* REST OF MENU */
  7737. left_panel_split = memnew(HSplitContainer);
  7738. left_panel_split->set_v_size_flags(SIZE_EXPAND_FILL);
  7739. vbc->add_child(left_panel_split);
  7740. right_panel_split = memnew(HSplitContainer);
  7741. right_panel_split->set_v_size_flags(SIZE_EXPAND_FILL);
  7742. left_panel_split->add_child(right_panel_split);
  7743. shader_split = memnew(VSplitContainer);
  7744. shader_split->set_h_size_flags(SIZE_EXPAND_FILL);
  7745. right_panel_split->add_child(shader_split);
  7746. viewport_base = memnew(Node3DEditorViewportContainer);
  7747. shader_split->add_child(viewport_base);
  7748. viewport_base->set_v_size_flags(SIZE_EXPAND_FILL);
  7749. for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
  7750. viewports[i] = memnew(Node3DEditorViewport(this, i));
  7751. viewports[i]->connect("toggle_maximize_view", callable_mp(this, &Node3DEditor::_toggle_maximize_view));
  7752. viewports[i]->connect("clicked", callable_mp(this, &Node3DEditor::_viewport_clicked).bind(i));
  7753. viewports[i]->assign_pending_data_pointers(preview_node, &preview_bounds, accept);
  7754. viewport_base->add_child(viewports[i]);
  7755. }
  7756. /* SNAP DIALOG */
  7757. snap_dialog = memnew(ConfirmationDialog);
  7758. snap_dialog->set_title(TTR("Snap Settings"));
  7759. add_child(snap_dialog);
  7760. snap_dialog->connect(SceneStringName(confirmed), callable_mp(this, &Node3DEditor::_snap_changed));
  7761. snap_dialog->get_cancel_button()->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_snap_update));
  7762. VBoxContainer *snap_dialog_vbc = memnew(VBoxContainer);
  7763. snap_dialog->add_child(snap_dialog_vbc);
  7764. snap_translate = memnew(LineEdit);
  7765. snap_translate->set_select_all_on_focus(true);
  7766. snap_dialog_vbc->add_margin_child(TTR("Translate Snap:"), snap_translate);
  7767. snap_rotate = memnew(LineEdit);
  7768. snap_rotate->set_select_all_on_focus(true);
  7769. snap_dialog_vbc->add_margin_child(TTR("Rotate Snap (deg.):"), snap_rotate);
  7770. snap_scale = memnew(LineEdit);
  7771. snap_scale->set_select_all_on_focus(true);
  7772. snap_dialog_vbc->add_margin_child(TTR("Scale Snap (%):"), snap_scale);
  7773. /* SETTINGS DIALOG */
  7774. settings_dialog = memnew(ConfirmationDialog);
  7775. settings_dialog->set_title(TTR("Viewport Settings"));
  7776. add_child(settings_dialog);
  7777. settings_vbc = memnew(VBoxContainer);
  7778. settings_vbc->set_custom_minimum_size(Size2(200, 0) * EDSCALE);
  7779. settings_dialog->add_child(settings_vbc);
  7780. settings_fov = memnew(SpinBox);
  7781. settings_fov->set_max(MAX_FOV);
  7782. settings_fov->set_min(MIN_FOV);
  7783. settings_fov->set_step(0.1);
  7784. settings_fov->set_value(EDITOR_GET("editors/3d/default_fov"));
  7785. settings_fov->set_select_all_on_focus(true);
  7786. settings_fov->set_tooltip_text(TTR("FOV is defined as a vertical value, as the editor camera always uses the Keep Height aspect mode."));
  7787. settings_vbc->add_margin_child(TTR("Perspective VFOV (deg.):"), settings_fov);
  7788. settings_znear = memnew(SpinBox);
  7789. settings_znear->set_max(MAX_Z);
  7790. settings_znear->set_min(MIN_Z);
  7791. settings_znear->set_step(0.01);
  7792. settings_znear->set_value(EDITOR_GET("editors/3d/default_z_near"));
  7793. settings_znear->set_select_all_on_focus(true);
  7794. settings_vbc->add_margin_child(TTR("View Z-Near:"), settings_znear);
  7795. settings_zfar = memnew(SpinBox);
  7796. settings_zfar->set_max(MAX_Z);
  7797. settings_zfar->set_min(MIN_Z);
  7798. settings_zfar->set_step(0.1);
  7799. settings_zfar->set_value(EDITOR_GET("editors/3d/default_z_far"));
  7800. settings_zfar->set_select_all_on_focus(true);
  7801. settings_vbc->add_margin_child(TTR("View Z-Far:"), settings_zfar);
  7802. for (uint32_t i = 0; i < VIEWPORTS_COUNT; ++i) {
  7803. settings_dialog->connect(SceneStringName(confirmed), callable_mp(viewports[i], &Node3DEditorViewport::_view_settings_confirmed).bind(0.0));
  7804. }
  7805. /* XFORM DIALOG */
  7806. xform_dialog = memnew(ConfirmationDialog);
  7807. xform_dialog->set_title(TTR("Transform Change"));
  7808. add_child(xform_dialog);
  7809. VBoxContainer *xform_vbc = memnew(VBoxContainer);
  7810. xform_dialog->add_child(xform_vbc);
  7811. Label *l = memnew(Label);
  7812. l->set_text(TTR("Translate:"));
  7813. xform_vbc->add_child(l);
  7814. HBoxContainer *xform_hbc = memnew(HBoxContainer);
  7815. xform_vbc->add_child(xform_hbc);
  7816. for (int i = 0; i < 3; i++) {
  7817. xform_translate[i] = memnew(LineEdit);
  7818. xform_translate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  7819. xform_translate[i]->set_select_all_on_focus(true);
  7820. xform_hbc->add_child(xform_translate[i]);
  7821. }
  7822. l = memnew(Label);
  7823. l->set_text(TTR("Rotate (deg.):"));
  7824. xform_vbc->add_child(l);
  7825. xform_hbc = memnew(HBoxContainer);
  7826. xform_vbc->add_child(xform_hbc);
  7827. for (int i = 0; i < 3; i++) {
  7828. xform_rotate[i] = memnew(LineEdit);
  7829. xform_rotate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  7830. xform_rotate[i]->set_select_all_on_focus(true);
  7831. xform_hbc->add_child(xform_rotate[i]);
  7832. }
  7833. l = memnew(Label);
  7834. l->set_text(TTR("Scale (ratio):"));
  7835. xform_vbc->add_child(l);
  7836. xform_hbc = memnew(HBoxContainer);
  7837. xform_vbc->add_child(xform_hbc);
  7838. for (int i = 0; i < 3; i++) {
  7839. xform_scale[i] = memnew(LineEdit);
  7840. xform_scale[i]->set_h_size_flags(SIZE_EXPAND_FILL);
  7841. xform_scale[i]->set_select_all_on_focus(true);
  7842. xform_hbc->add_child(xform_scale[i]);
  7843. }
  7844. l = memnew(Label);
  7845. l->set_text(TTR("Transform Type"));
  7846. xform_vbc->add_child(l);
  7847. xform_type = memnew(OptionButton);
  7848. xform_type->set_h_size_flags(SIZE_EXPAND_FILL);
  7849. xform_type->add_item(TTR("Pre"));
  7850. xform_type->add_item(TTR("Post"));
  7851. xform_vbc->add_child(xform_type);
  7852. xform_dialog->connect(SceneStringName(confirmed), callable_mp(this, &Node3DEditor::_xform_dialog_action));
  7853. selected = nullptr;
  7854. set_process_shortcut_input(true);
  7855. add_to_group(SceneStringName(_spatial_editor_group));
  7856. current_hover_gizmo_handle = -1;
  7857. current_hover_gizmo_handle_secondary = false;
  7858. {
  7859. // Sun/preview environment popup.
  7860. sun_environ_popup = memnew(PopupPanel);
  7861. add_child(sun_environ_popup);
  7862. HBoxContainer *sun_environ_hb = memnew(HBoxContainer);
  7863. sun_environ_popup->add_child(sun_environ_hb);
  7864. sun_vb = memnew(VBoxContainer);
  7865. sun_environ_hb->add_child(sun_vb);
  7866. sun_vb->set_custom_minimum_size(Size2(200 * EDSCALE, 0));
  7867. sun_vb->hide();
  7868. sun_title = memnew(Label);
  7869. sun_title->set_theme_type_variation("HeaderMedium");
  7870. sun_vb->add_child(sun_title);
  7871. sun_title->set_text(TTR("Preview Sun"));
  7872. sun_title->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  7873. CenterContainer *sun_direction_center = memnew(CenterContainer);
  7874. sun_direction = memnew(Control);
  7875. sun_direction->set_custom_minimum_size(Size2(128, 128) * EDSCALE);
  7876. sun_direction_center->add_child(sun_direction);
  7877. sun_vb->add_margin_child(TTR("Sun Direction"), sun_direction_center);
  7878. sun_direction->connect(SceneStringName(gui_input), callable_mp(this, &Node3DEditor::_sun_direction_input));
  7879. sun_direction->connect(SceneStringName(draw), callable_mp(this, &Node3DEditor::_sun_direction_draw));
  7880. sun_direction->set_default_cursor_shape(CURSOR_MOVE);
  7881. sun_direction_shader.instantiate();
  7882. sun_direction_shader->set_code(R"(
  7883. // 3D editor Preview Sun direction shader.
  7884. shader_type canvas_item;
  7885. uniform vec3 sun_direction;
  7886. uniform vec3 sun_color;
  7887. void fragment() {
  7888. vec3 n;
  7889. n.xy = UV * 2.0 - 1.0;
  7890. n.z = sqrt(max(0.0, 1.0 - dot(n.xy, n.xy)));
  7891. COLOR.rgb = dot(n, sun_direction) * sun_color;
  7892. COLOR.a = 1.0 - smoothstep(0.99, 1.0, length(n.xy));
  7893. }
  7894. )");
  7895. sun_direction_material.instantiate();
  7896. sun_direction_material->set_shader(sun_direction_shader);
  7897. sun_direction_material->set_shader_parameter("sun_direction", Vector3(0, 0, 1));
  7898. sun_direction_material->set_shader_parameter("sun_color", Vector3(1, 1, 1));
  7899. sun_direction->set_material(sun_direction_material);
  7900. HBoxContainer *sun_angle_hbox = memnew(HBoxContainer);
  7901. sun_angle_hbox->set_h_size_flags(SIZE_EXPAND_FILL);
  7902. VBoxContainer *sun_angle_altitude_vbox = memnew(VBoxContainer);
  7903. sun_angle_altitude_vbox->set_h_size_flags(SIZE_EXPAND_FILL);
  7904. Label *sun_angle_altitude_label = memnew(Label);
  7905. sun_angle_altitude_label->set_text(TTR("Angular Altitude"));
  7906. sun_angle_altitude_vbox->add_child(sun_angle_altitude_label);
  7907. sun_angle_altitude = memnew(EditorSpinSlider);
  7908. sun_angle_altitude->set_suffix(U"\u00B0");
  7909. sun_angle_altitude->set_max(90);
  7910. sun_angle_altitude->set_min(-90);
  7911. sun_angle_altitude->set_step(0.1);
  7912. sun_angle_altitude->connect(SceneStringName(value_changed), callable_mp(this, &Node3DEditor::_sun_direction_angle_set).unbind(1));
  7913. sun_angle_altitude_vbox->add_child(sun_angle_altitude);
  7914. sun_angle_hbox->add_child(sun_angle_altitude_vbox);
  7915. VBoxContainer *sun_angle_azimuth_vbox = memnew(VBoxContainer);
  7916. sun_angle_azimuth_vbox->set_h_size_flags(SIZE_EXPAND_FILL);
  7917. sun_angle_azimuth_vbox->set_custom_minimum_size(Vector2(100, 0));
  7918. Label *sun_angle_azimuth_label = memnew(Label);
  7919. sun_angle_azimuth_label->set_text(TTR("Azimuth"));
  7920. sun_angle_azimuth_vbox->add_child(sun_angle_azimuth_label);
  7921. sun_angle_azimuth = memnew(EditorSpinSlider);
  7922. sun_angle_azimuth->set_suffix(U"\u00B0");
  7923. sun_angle_azimuth->set_max(180);
  7924. sun_angle_azimuth->set_min(-180);
  7925. sun_angle_azimuth->set_step(0.1);
  7926. sun_angle_azimuth->set_allow_greater(true);
  7927. sun_angle_azimuth->set_allow_lesser(true);
  7928. sun_angle_azimuth->connect(SceneStringName(value_changed), callable_mp(this, &Node3DEditor::_sun_direction_angle_set).unbind(1));
  7929. sun_angle_azimuth_vbox->add_child(sun_angle_azimuth);
  7930. sun_angle_hbox->add_child(sun_angle_azimuth_vbox);
  7931. sun_angle_hbox->add_theme_constant_override("separation", 10);
  7932. sun_vb->add_child(sun_angle_hbox);
  7933. sun_color = memnew(ColorPickerButton);
  7934. sun_color->set_edit_alpha(false);
  7935. sun_vb->add_margin_child(TTR("Sun Color"), sun_color);
  7936. sun_color->connect("color_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7937. sun_color->get_popup()->connect("about_to_popup", callable_mp(EditorNode::get_singleton(), &EditorNode::setup_color_picker).bind(sun_color->get_picker()));
  7938. sun_energy = memnew(EditorSpinSlider);
  7939. sun_energy->set_max(64.0);
  7940. sun_energy->set_min(0);
  7941. sun_energy->set_step(0.05);
  7942. sun_vb->add_margin_child(TTR("Sun Energy"), sun_energy);
  7943. sun_energy->connect(SceneStringName(value_changed), callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7944. sun_max_distance = memnew(EditorSpinSlider);
  7945. sun_vb->add_margin_child(TTR("Shadow Max Distance"), sun_max_distance);
  7946. sun_max_distance->connect(SceneStringName(value_changed), callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7947. sun_max_distance->set_min(1);
  7948. sun_max_distance->set_max(4096);
  7949. sun_add_to_scene = memnew(Button);
  7950. sun_add_to_scene->set_text(TTR("Add Sun to Scene"));
  7951. sun_add_to_scene->set_tooltip_text(TTR("Adds a DirectionalLight3D node matching the preview sun settings to the current scene.\nHold Shift while clicking to also add the preview environment to the current scene."));
  7952. sun_add_to_scene->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_add_sun_to_scene).bind(false));
  7953. sun_vb->add_spacer();
  7954. sun_vb->add_child(sun_add_to_scene);
  7955. sun_state = memnew(Label);
  7956. sun_environ_hb->add_child(sun_state);
  7957. sun_state->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  7958. sun_state->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
  7959. sun_state->set_h_size_flags(SIZE_EXPAND_FILL);
  7960. VSeparator *sc = memnew(VSeparator);
  7961. sc->set_custom_minimum_size(Size2(10 * EDSCALE, 0));
  7962. sc->set_v_size_flags(SIZE_EXPAND_FILL);
  7963. sun_environ_hb->add_child(sc);
  7964. environ_vb = memnew(VBoxContainer);
  7965. sun_environ_hb->add_child(environ_vb);
  7966. environ_vb->set_custom_minimum_size(Size2(200 * EDSCALE, 0));
  7967. environ_vb->hide();
  7968. environ_title = memnew(Label);
  7969. environ_title->set_theme_type_variation("HeaderMedium");
  7970. environ_vb->add_child(environ_title);
  7971. environ_title->set_text(TTR("Preview Environment"));
  7972. environ_title->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  7973. environ_sky_color = memnew(ColorPickerButton);
  7974. environ_sky_color->set_edit_alpha(false);
  7975. environ_sky_color->connect("color_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7976. environ_sky_color->get_popup()->connect("about_to_popup", callable_mp(EditorNode::get_singleton(), &EditorNode::setup_color_picker).bind(environ_sky_color->get_picker()));
  7977. environ_vb->add_margin_child(TTR("Sky Color"), environ_sky_color);
  7978. environ_ground_color = memnew(ColorPickerButton);
  7979. environ_ground_color->connect("color_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7980. environ_ground_color->set_edit_alpha(false);
  7981. environ_ground_color->get_popup()->connect("about_to_popup", callable_mp(EditorNode::get_singleton(), &EditorNode::setup_color_picker).bind(environ_ground_color->get_picker()));
  7982. environ_vb->add_margin_child(TTR("Ground Color"), environ_ground_color);
  7983. environ_energy = memnew(EditorSpinSlider);
  7984. environ_energy->set_max(8.0);
  7985. environ_energy->set_min(0);
  7986. environ_energy->set_step(0.05);
  7987. environ_energy->connect(SceneStringName(value_changed), callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1));
  7988. environ_vb->add_margin_child(TTR("Sky Energy"), environ_energy);
  7989. HBoxContainer *fx_vb = memnew(HBoxContainer);
  7990. fx_vb->set_h_size_flags(SIZE_EXPAND_FILL);
  7991. environ_ao_button = memnew(Button);
  7992. environ_ao_button->set_text(TTR("AO"));
  7993. environ_ao_button->set_h_size_flags(SIZE_EXPAND_FILL);
  7994. environ_ao_button->set_toggle_mode(true);
  7995. environ_ao_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_preview_settings_changed), CONNECT_DEFERRED);
  7996. fx_vb->add_child(environ_ao_button);
  7997. environ_glow_button = memnew(Button);
  7998. environ_glow_button->set_text(TTR("Glow"));
  7999. environ_glow_button->set_h_size_flags(SIZE_EXPAND_FILL);
  8000. environ_glow_button->set_toggle_mode(true);
  8001. environ_glow_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_preview_settings_changed), CONNECT_DEFERRED);
  8002. fx_vb->add_child(environ_glow_button);
  8003. environ_tonemap_button = memnew(Button);
  8004. environ_tonemap_button->set_text(TTR("Tonemap"));
  8005. environ_tonemap_button->set_h_size_flags(SIZE_EXPAND_FILL);
  8006. environ_tonemap_button->set_toggle_mode(true);
  8007. environ_tonemap_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_preview_settings_changed), CONNECT_DEFERRED);
  8008. fx_vb->add_child(environ_tonemap_button);
  8009. environ_gi_button = memnew(Button);
  8010. environ_gi_button->set_text(TTR("GI"));
  8011. environ_gi_button->set_h_size_flags(SIZE_EXPAND_FILL);
  8012. environ_gi_button->set_toggle_mode(true);
  8013. environ_gi_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_preview_settings_changed), CONNECT_DEFERRED);
  8014. fx_vb->add_child(environ_gi_button);
  8015. environ_vb->add_margin_child(TTR("Post Process"), fx_vb);
  8016. environ_add_to_scene = memnew(Button);
  8017. environ_add_to_scene->set_text(TTR("Add Environment to Scene"));
  8018. environ_add_to_scene->set_tooltip_text(TTR("Adds a WorldEnvironment node matching the preview environment settings to the current scene.\nHold Shift while clicking to also add the preview sun to the current scene."));
  8019. environ_add_to_scene->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_add_environment_to_scene).bind(false));
  8020. environ_vb->add_spacer();
  8021. environ_vb->add_child(environ_add_to_scene);
  8022. environ_state = memnew(Label);
  8023. sun_environ_hb->add_child(environ_state);
  8024. environ_state->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  8025. environ_state->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
  8026. environ_state->set_h_size_flags(SIZE_EXPAND_FILL);
  8027. preview_sun = memnew(DirectionalLight3D);
  8028. preview_sun->set_shadow(true);
  8029. preview_sun->set_shadow_mode(DirectionalLight3D::SHADOW_PARALLEL_4_SPLITS);
  8030. preview_environment = memnew(WorldEnvironment);
  8031. environment.instantiate();
  8032. preview_environment->set_environment(environment);
  8033. if (GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units")) {
  8034. camera_attributes.instantiate();
  8035. preview_environment->set_camera_attributes(camera_attributes);
  8036. }
  8037. Ref<Sky> sky;
  8038. sky.instantiate();
  8039. sky_material.instantiate();
  8040. sky->set_material(sky_material);
  8041. environment->set_sky(sky);
  8042. environment->set_background(Environment::BG_SKY);
  8043. _load_default_preview_settings();
  8044. _preview_settings_changed();
  8045. }
  8046. clear(); // Make sure values are initialized. Will call _snap_update() for us.
  8047. }
  8048. Node3DEditor::~Node3DEditor() {
  8049. singleton = nullptr;
  8050. memdelete(preview_node);
  8051. if (preview_sun_dangling && preview_sun) {
  8052. memdelete(preview_sun);
  8053. }
  8054. if (preview_env_dangling && preview_environment) {
  8055. memdelete(preview_environment);
  8056. }
  8057. }
  8058. void Node3DEditorPlugin::make_visible(bool p_visible) {
  8059. if (p_visible) {
  8060. spatial_editor->show();
  8061. spatial_editor->set_process(true);
  8062. spatial_editor->set_physics_process(true);
  8063. } else {
  8064. spatial_editor->hide();
  8065. spatial_editor->set_process(false);
  8066. spatial_editor->set_physics_process(false);
  8067. }
  8068. }
  8069. void Node3DEditorPlugin::edit(Object *p_object) {
  8070. spatial_editor->edit(Object::cast_to<Node3D>(p_object));
  8071. }
  8072. bool Node3DEditorPlugin::handles(Object *p_object) const {
  8073. return p_object->is_class("Node3D");
  8074. }
  8075. Dictionary Node3DEditorPlugin::get_state() const {
  8076. return spatial_editor->get_state();
  8077. }
  8078. void Node3DEditorPlugin::set_state(const Dictionary &p_state) {
  8079. spatial_editor->set_state(p_state);
  8080. }
  8081. Size2i Node3DEditor::get_camera_viewport_size(Camera3D *p_camera) {
  8082. Viewport *viewport = p_camera->get_viewport();
  8083. Window *window = Object::cast_to<Window>(viewport);
  8084. if (window) {
  8085. return window->get_size();
  8086. }
  8087. SubViewport *sub_viewport = Object::cast_to<SubViewport>(viewport);
  8088. ERR_FAIL_NULL_V(sub_viewport, Size2i());
  8089. if (sub_viewport == EditorNode::get_singleton()->get_scene_root()) {
  8090. return Size2(GLOBAL_GET("display/window/size/viewport_width"), GLOBAL_GET("display/window/size/viewport_height"));
  8091. }
  8092. return sub_viewport->get_size();
  8093. }
  8094. Vector3 Node3DEditor::snap_point(Vector3 p_target, Vector3 p_start) const {
  8095. if (is_snap_enabled()) {
  8096. real_t snap = get_translate_snap();
  8097. p_target.snapf(snap);
  8098. }
  8099. return p_target;
  8100. }
  8101. bool Node3DEditor::is_gizmo_visible() const {
  8102. if (selected) {
  8103. return gizmo.visible && selected->is_transform_gizmo_visible();
  8104. }
  8105. return gizmo.visible;
  8106. }
  8107. real_t Node3DEditor::get_translate_snap() const {
  8108. real_t snap_value = snap_translate_value;
  8109. if (Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
  8110. snap_value /= 10.0f;
  8111. }
  8112. return snap_value;
  8113. }
  8114. real_t Node3DEditor::get_rotate_snap() const {
  8115. real_t snap_value = snap_rotate_value;
  8116. if (Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
  8117. snap_value /= 3.0f;
  8118. }
  8119. return snap_value;
  8120. }
  8121. real_t Node3DEditor::get_scale_snap() const {
  8122. real_t snap_value = snap_scale_value;
  8123. if (Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
  8124. snap_value /= 2.0f;
  8125. }
  8126. return snap_value;
  8127. }
  8128. struct _GizmoPluginPriorityComparator {
  8129. bool operator()(const Ref<EditorNode3DGizmoPlugin> &p_a, const Ref<EditorNode3DGizmoPlugin> &p_b) const {
  8130. if (p_a->get_priority() == p_b->get_priority()) {
  8131. return p_a->get_gizmo_name() < p_b->get_gizmo_name();
  8132. }
  8133. return p_a->get_priority() > p_b->get_priority();
  8134. }
  8135. };
  8136. struct _GizmoPluginNameComparator {
  8137. bool operator()(const Ref<EditorNode3DGizmoPlugin> &p_a, const Ref<EditorNode3DGizmoPlugin> &p_b) const {
  8138. return p_a->get_gizmo_name() < p_b->get_gizmo_name();
  8139. }
  8140. };
  8141. void Node3DEditor::add_gizmo_plugin(Ref<EditorNode3DGizmoPlugin> p_plugin) {
  8142. ERR_FAIL_COND(p_plugin.is_null());
  8143. gizmo_plugins_by_priority.push_back(p_plugin);
  8144. gizmo_plugins_by_priority.sort_custom<_GizmoPluginPriorityComparator>();
  8145. gizmo_plugins_by_name.push_back(p_plugin);
  8146. gizmo_plugins_by_name.sort_custom<_GizmoPluginNameComparator>();
  8147. _update_gizmos_menu();
  8148. }
  8149. void Node3DEditor::remove_gizmo_plugin(Ref<EditorNode3DGizmoPlugin> p_plugin) {
  8150. gizmo_plugins_by_priority.erase(p_plugin);
  8151. gizmo_plugins_by_name.erase(p_plugin);
  8152. _update_gizmos_menu();
  8153. }
  8154. DynamicBVH::ID Node3DEditor::insert_gizmo_bvh_node(Node3D *p_node, const AABB &p_aabb) {
  8155. return gizmo_bvh.insert(p_aabb, p_node);
  8156. }
  8157. void Node3DEditor::update_gizmo_bvh_node(DynamicBVH::ID p_id, const AABB &p_aabb) {
  8158. gizmo_bvh.update(p_id, p_aabb);
  8159. gizmo_bvh.optimize_incremental(1);
  8160. }
  8161. void Node3DEditor::remove_gizmo_bvh_node(DynamicBVH::ID p_id) {
  8162. gizmo_bvh.remove(p_id);
  8163. }
  8164. Vector<Node3D *> Node3DEditor::gizmo_bvh_ray_query(const Vector3 &p_ray_start, const Vector3 &p_ray_end) {
  8165. struct Result {
  8166. Vector<Node3D *> nodes;
  8167. bool operator()(void *p_data) {
  8168. nodes.append((Node3D *)p_data);
  8169. return false;
  8170. }
  8171. } result;
  8172. gizmo_bvh.ray_query(p_ray_start, p_ray_end, result);
  8173. return result.nodes;
  8174. }
  8175. Vector<Node3D *> Node3DEditor::gizmo_bvh_frustum_query(const Vector<Plane> &p_frustum) {
  8176. Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&p_frustum[0], p_frustum.size());
  8177. struct Result {
  8178. Vector<Node3D *> nodes;
  8179. bool operator()(void *p_data) {
  8180. nodes.append((Node3D *)p_data);
  8181. return false;
  8182. }
  8183. } result;
  8184. gizmo_bvh.convex_query(p_frustum.ptr(), p_frustum.size(), points.ptr(), points.size(), result);
  8185. return result.nodes;
  8186. }
  8187. Node3DEditorPlugin::Node3DEditorPlugin() {
  8188. spatial_editor = memnew(Node3DEditor);
  8189. spatial_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  8190. EditorNode::get_singleton()->get_editor_main_screen()->get_control()->add_child(spatial_editor);
  8191. spatial_editor->hide();
  8192. }
  8193. Node3DEditorPlugin::~Node3DEditorPlugin() {
  8194. }