spatial_editor_plugin.cpp 244 KB

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