node_3d_editor_plugin.cpp 361 KB

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