node_3d_editor_plugin.cpp 334 KB

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