node_3d_editor_plugin.cpp 343 KB

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