rendering_device.cpp 276 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519
  1. /**************************************************************************/
  2. /* rendering_device.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 "rendering_device.h"
  31. #include "rendering_device.compat.inc"
  32. #include "rendering_device_binds.h"
  33. #include "core/config/project_settings.h"
  34. #include "core/io/dir_access.h"
  35. #define FORCE_SEPARATE_PRESENT_QUEUE 0
  36. /**************************/
  37. /**** HELPER FUNCTIONS ****/
  38. /**************************/
  39. static String _get_device_vendor_name(const RenderingContextDriver::Device &p_device) {
  40. switch (p_device.vendor) {
  41. case RenderingContextDriver::VENDOR_AMD:
  42. return "AMD";
  43. case RenderingContextDriver::VENDOR_IMGTEC:
  44. return "ImgTec";
  45. case RenderingContextDriver::VENDOR_APPLE:
  46. return "Apple";
  47. case RenderingContextDriver::VENDOR_NVIDIA:
  48. return "NVIDIA";
  49. case RenderingContextDriver::VENDOR_ARM:
  50. return "ARM";
  51. case RenderingContextDriver::VENDOR_MICROSOFT:
  52. return "Microsoft";
  53. case RenderingContextDriver::VENDOR_QUALCOMM:
  54. return "Qualcomm";
  55. case RenderingContextDriver::VENDOR_INTEL:
  56. return "Intel";
  57. default:
  58. return "Unknown";
  59. }
  60. }
  61. static String _get_device_type_name(const RenderingContextDriver::Device &p_device) {
  62. switch (p_device.type) {
  63. case RenderingContextDriver::DEVICE_TYPE_INTEGRATED_GPU:
  64. return "Integrated";
  65. case RenderingContextDriver::DEVICE_TYPE_DISCRETE_GPU:
  66. return "Discrete";
  67. case RenderingContextDriver::DEVICE_TYPE_VIRTUAL_GPU:
  68. return "Virtual";
  69. case RenderingContextDriver::DEVICE_TYPE_CPU:
  70. return "CPU";
  71. case RenderingContextDriver::DEVICE_TYPE_OTHER:
  72. default:
  73. return "Other";
  74. }
  75. }
  76. static uint32_t _get_device_type_score(const RenderingContextDriver::Device &p_device) {
  77. switch (p_device.type) {
  78. case RenderingContextDriver::DEVICE_TYPE_INTEGRATED_GPU:
  79. return 4;
  80. case RenderingContextDriver::DEVICE_TYPE_DISCRETE_GPU:
  81. return 5;
  82. case RenderingContextDriver::DEVICE_TYPE_VIRTUAL_GPU:
  83. return 3;
  84. case RenderingContextDriver::DEVICE_TYPE_CPU:
  85. return 2;
  86. case RenderingContextDriver::DEVICE_TYPE_OTHER:
  87. default:
  88. return 1;
  89. }
  90. }
  91. /**************************/
  92. /**** RENDERING DEVICE ****/
  93. /**************************/
  94. // When true, the command graph will attempt to reorder the rendering commands submitted by the user based on the dependencies detected from
  95. // the commands automatically. This should improve rendering performance in most scenarios at the cost of some extra CPU overhead.
  96. //
  97. // This behavior can be disabled if it's suspected that the graph is not detecting dependencies correctly and more control over the order of
  98. // the commands is desired (e.g. debugging).
  99. #define RENDER_GRAPH_REORDER 1
  100. // Synchronization barriers are issued between the graph's levels only with the necessary amount of detail to achieve the correct result. If
  101. // it's suspected that the graph is not doing this correctly, full barriers can be issued instead that will block all types of operations
  102. // between the synchronization levels. This setting will have a very negative impact on performance when enabled, so it's only intended for
  103. // debugging purposes.
  104. #define RENDER_GRAPH_FULL_BARRIERS 0
  105. // The command graph can automatically issue secondary command buffers and record them on background threads when they reach an arbitrary
  106. // size threshold. This can be very beneficial towards reducing the time the main thread takes to record all the rendering commands. However,
  107. // this setting is not enabled by default as it's been shown to cause some strange issues with certain IHVs that have yet to be understood.
  108. #define SECONDARY_COMMAND_BUFFERS_PER_FRAME 0
  109. RenderingDevice *RenderingDevice::singleton = nullptr;
  110. RenderingDevice *RenderingDevice::get_singleton() {
  111. return singleton;
  112. }
  113. RenderingDevice::ShaderCompileToSPIRVFunction RenderingDevice::compile_to_spirv_function = nullptr;
  114. RenderingDevice::ShaderCacheFunction RenderingDevice::cache_function = nullptr;
  115. RenderingDevice::ShaderSPIRVGetCacheKeyFunction RenderingDevice::get_spirv_cache_key_function = nullptr;
  116. /***************************/
  117. /**** ID INFRASTRUCTURE ****/
  118. /***************************/
  119. void RenderingDevice::_add_dependency(RID p_id, RID p_depends_on) {
  120. if (!dependency_map.has(p_depends_on)) {
  121. dependency_map[p_depends_on] = HashSet<RID>();
  122. }
  123. dependency_map[p_depends_on].insert(p_id);
  124. if (!reverse_dependency_map.has(p_id)) {
  125. reverse_dependency_map[p_id] = HashSet<RID>();
  126. }
  127. reverse_dependency_map[p_id].insert(p_depends_on);
  128. }
  129. void RenderingDevice::_free_dependencies(RID p_id) {
  130. // Direct dependencies must be freed.
  131. HashMap<RID, HashSet<RID>>::Iterator E = dependency_map.find(p_id);
  132. if (E) {
  133. while (E->value.size()) {
  134. free(*E->value.begin());
  135. }
  136. dependency_map.remove(E);
  137. }
  138. // Reverse dependencies must be unreferenced.
  139. E = reverse_dependency_map.find(p_id);
  140. if (E) {
  141. for (const RID &F : E->value) {
  142. HashMap<RID, HashSet<RID>>::Iterator G = dependency_map.find(F);
  143. ERR_CONTINUE(!G);
  144. ERR_CONTINUE(!G->value.has(p_id));
  145. G->value.erase(p_id);
  146. }
  147. reverse_dependency_map.remove(E);
  148. }
  149. }
  150. void RenderingDevice::shader_set_compile_to_spirv_function(ShaderCompileToSPIRVFunction p_function) {
  151. compile_to_spirv_function = p_function;
  152. }
  153. void RenderingDevice::shader_set_spirv_cache_function(ShaderCacheFunction p_function) {
  154. cache_function = p_function;
  155. }
  156. void RenderingDevice::shader_set_get_cache_key_function(ShaderSPIRVGetCacheKeyFunction p_function) {
  157. get_spirv_cache_key_function = p_function;
  158. }
  159. Vector<uint8_t> RenderingDevice::shader_compile_spirv_from_source(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language, String *r_error, bool p_allow_cache) {
  160. if (p_allow_cache && cache_function) {
  161. Vector<uint8_t> cache = cache_function(p_stage, p_source_code, p_language);
  162. if (cache.size()) {
  163. return cache;
  164. }
  165. }
  166. ERR_FAIL_NULL_V(compile_to_spirv_function, Vector<uint8_t>());
  167. return compile_to_spirv_function(p_stage, p_source_code, p_language, r_error, this);
  168. }
  169. String RenderingDevice::shader_get_spirv_cache_key() const {
  170. if (get_spirv_cache_key_function) {
  171. return get_spirv_cache_key_function(this);
  172. }
  173. return String();
  174. }
  175. RID RenderingDevice::shader_create_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv, const String &p_shader_name) {
  176. Vector<uint8_t> bytecode = shader_compile_binary_from_spirv(p_spirv, p_shader_name);
  177. ERR_FAIL_COND_V(bytecode.is_empty(), RID());
  178. return shader_create_from_bytecode(bytecode);
  179. }
  180. /***************************/
  181. /**** BUFFER MANAGEMENT ****/
  182. /***************************/
  183. RenderingDevice::Buffer *RenderingDevice::_get_buffer_from_owner(RID p_buffer) {
  184. Buffer *buffer = nullptr;
  185. if (vertex_buffer_owner.owns(p_buffer)) {
  186. buffer = vertex_buffer_owner.get_or_null(p_buffer);
  187. } else if (index_buffer_owner.owns(p_buffer)) {
  188. buffer = index_buffer_owner.get_or_null(p_buffer);
  189. } else if (uniform_buffer_owner.owns(p_buffer)) {
  190. buffer = uniform_buffer_owner.get_or_null(p_buffer);
  191. } else if (texture_buffer_owner.owns(p_buffer)) {
  192. DEV_ASSERT(false && "FIXME: Broken.");
  193. //buffer = texture_buffer_owner.get_or_null(p_buffer)->buffer;
  194. } else if (storage_buffer_owner.owns(p_buffer)) {
  195. buffer = storage_buffer_owner.get_or_null(p_buffer);
  196. }
  197. return buffer;
  198. }
  199. Error RenderingDevice::_insert_staging_block() {
  200. StagingBufferBlock block;
  201. block.driver_id = driver->buffer_create(staging_buffer_block_size, RDD::BUFFER_USAGE_TRANSFER_FROM_BIT, RDD::MEMORY_ALLOCATION_TYPE_CPU);
  202. ERR_FAIL_COND_V(!block.driver_id, ERR_CANT_CREATE);
  203. block.frame_used = 0;
  204. block.fill_amount = 0;
  205. staging_buffer_blocks.insert(staging_buffer_current, block);
  206. return OK;
  207. }
  208. Error RenderingDevice::_staging_buffer_allocate(uint32_t p_amount, uint32_t p_required_align, uint32_t &r_alloc_offset, uint32_t &r_alloc_size, StagingRequiredAction &r_required_action, bool p_can_segment) {
  209. // Determine a block to use.
  210. r_alloc_size = p_amount;
  211. r_required_action = STAGING_REQUIRED_ACTION_NONE;
  212. while (true) {
  213. r_alloc_offset = 0;
  214. // See if we can use current block.
  215. if (staging_buffer_blocks[staging_buffer_current].frame_used == frames_drawn) {
  216. // We used this block this frame, let's see if there is still room.
  217. uint32_t write_from = staging_buffer_blocks[staging_buffer_current].fill_amount;
  218. {
  219. uint32_t align_remainder = write_from % p_required_align;
  220. if (align_remainder != 0) {
  221. write_from += p_required_align - align_remainder;
  222. }
  223. }
  224. int32_t available_bytes = int32_t(staging_buffer_block_size) - int32_t(write_from);
  225. if ((int32_t)p_amount < available_bytes) {
  226. // All is good, we should be ok, all will fit.
  227. r_alloc_offset = write_from;
  228. } else if (p_can_segment && available_bytes >= (int32_t)p_required_align) {
  229. // Ok all won't fit but at least we can fit a chunkie.
  230. // All is good, update what needs to be written to.
  231. r_alloc_offset = write_from;
  232. r_alloc_size = available_bytes - (available_bytes % p_required_align);
  233. } else {
  234. // Can't fit it into this buffer.
  235. // Will need to try next buffer.
  236. staging_buffer_current = (staging_buffer_current + 1) % staging_buffer_blocks.size();
  237. // Before doing anything, though, let's check that we didn't manage to fill all blocks.
  238. // Possible in a single frame.
  239. if (staging_buffer_blocks[staging_buffer_current].frame_used == frames_drawn) {
  240. // Guess we did.. ok, let's see if we can insert a new block.
  241. if ((uint64_t)staging_buffer_blocks.size() * staging_buffer_block_size < staging_buffer_max_size) {
  242. // We can, so we are safe.
  243. Error err = _insert_staging_block();
  244. if (err) {
  245. return err;
  246. }
  247. // Claim for this frame.
  248. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  249. } else {
  250. // Ok, worst case scenario, all the staging buffers belong to this frame
  251. // and this frame is not even done.
  252. // If this is the main thread, it means the user is likely loading a lot of resources at once,.
  253. // Otherwise, the thread should just be blocked until the next frame (currently unimplemented).
  254. r_required_action = STAGING_REQUIRED_ACTION_FLUSH_AND_STALL_ALL;
  255. }
  256. } else {
  257. // Not from current frame, so continue and try again.
  258. continue;
  259. }
  260. }
  261. } else if (staging_buffer_blocks[staging_buffer_current].frame_used <= frames_drawn - frames.size()) {
  262. // This is an old block, which was already processed, let's reuse.
  263. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  264. staging_buffer_blocks.write[staging_buffer_current].fill_amount = 0;
  265. } else {
  266. // This block may still be in use, let's not touch it unless we have to, so.. can we create a new one?
  267. if ((uint64_t)staging_buffer_blocks.size() * staging_buffer_block_size < staging_buffer_max_size) {
  268. // We are still allowed to create a new block, so let's do that and insert it for current pos.
  269. Error err = _insert_staging_block();
  270. if (err) {
  271. return err;
  272. }
  273. // Claim for this frame.
  274. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  275. } else {
  276. // Oops, we are out of room and we can't create more.
  277. // Let's flush older frames.
  278. // The logic here is that if a game is loading a lot of data from the main thread, it will need to be stalled anyway.
  279. // If loading from a separate thread, we can block that thread until next frame when more room is made (not currently implemented, though).
  280. r_required_action = STAGING_REQUIRED_ACTION_STALL_PREVIOUS;
  281. }
  282. }
  283. // All was good, break.
  284. break;
  285. }
  286. staging_buffer_used = true;
  287. return OK;
  288. }
  289. void RenderingDevice::_staging_buffer_execute_required_action(StagingRequiredAction p_required_action) {
  290. switch (p_required_action) {
  291. case STAGING_REQUIRED_ACTION_NONE: {
  292. // Do nothing.
  293. } break;
  294. case STAGING_REQUIRED_ACTION_FLUSH_AND_STALL_ALL: {
  295. _flush_and_stall_for_all_frames();
  296. // Clear the whole staging buffer.
  297. for (int i = 0; i < staging_buffer_blocks.size(); i++) {
  298. staging_buffer_blocks.write[i].frame_used = 0;
  299. staging_buffer_blocks.write[i].fill_amount = 0;
  300. }
  301. // Claim for current frame.
  302. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  303. } break;
  304. case STAGING_REQUIRED_ACTION_STALL_PREVIOUS: {
  305. _stall_for_previous_frames();
  306. for (int i = 0; i < staging_buffer_blocks.size(); i++) {
  307. // Clear all blocks but the ones from this frame.
  308. int block_idx = (i + staging_buffer_current) % staging_buffer_blocks.size();
  309. if (staging_buffer_blocks[block_idx].frame_used == frames_drawn) {
  310. break; // Ok, we reached something from this frame, abort.
  311. }
  312. staging_buffer_blocks.write[block_idx].frame_used = 0;
  313. staging_buffer_blocks.write[block_idx].fill_amount = 0;
  314. }
  315. // Claim for current frame.
  316. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  317. } break;
  318. default: {
  319. DEV_ASSERT(false && "Unknown required action.");
  320. } break;
  321. }
  322. }
  323. Error RenderingDevice::_buffer_update(Buffer *p_buffer, RID p_buffer_id, size_t p_offset, const uint8_t *p_data, size_t p_data_size, bool p_use_draw_queue, uint32_t p_required_align) {
  324. // Submitting may get chunked for various reasons, so convert this to a task.
  325. size_t to_submit = p_data_size;
  326. size_t submit_from = 0;
  327. thread_local LocalVector<RDG::RecordedBufferCopy> command_buffer_copies_vector;
  328. command_buffer_copies_vector.clear();
  329. while (to_submit > 0) {
  330. uint32_t block_write_offset;
  331. uint32_t block_write_amount;
  332. StagingRequiredAction required_action;
  333. Error err = _staging_buffer_allocate(MIN(to_submit, staging_buffer_block_size), p_required_align, block_write_offset, block_write_amount, required_action);
  334. if (err) {
  335. return err;
  336. }
  337. if (p_use_draw_queue && !command_buffer_copies_vector.is_empty() && required_action == STAGING_REQUIRED_ACTION_FLUSH_AND_STALL_ALL) {
  338. if (_buffer_make_mutable(p_buffer, p_buffer_id)) {
  339. // The buffer must be mutable to be used as a copy destination.
  340. draw_graph.add_synchronization();
  341. }
  342. // If we're using the draw queue and the staging buffer requires flushing everything, we submit the command early and clear the current vector.
  343. draw_graph.add_buffer_update(p_buffer->driver_id, p_buffer->draw_tracker, command_buffer_copies_vector);
  344. command_buffer_copies_vector.clear();
  345. }
  346. _staging_buffer_execute_required_action(required_action);
  347. // Map staging buffer (It's CPU and coherent).
  348. uint8_t *data_ptr = driver->buffer_map(staging_buffer_blocks[staging_buffer_current].driver_id);
  349. ERR_FAIL_NULL_V(data_ptr, ERR_CANT_CREATE);
  350. // Copy to staging buffer.
  351. memcpy(data_ptr + block_write_offset, p_data + submit_from, block_write_amount);
  352. // Unmap.
  353. driver->buffer_unmap(staging_buffer_blocks[staging_buffer_current].driver_id);
  354. // Insert a command to copy this.
  355. RDD::BufferCopyRegion region;
  356. region.src_offset = block_write_offset;
  357. region.dst_offset = submit_from + p_offset;
  358. region.size = block_write_amount;
  359. if (p_use_draw_queue) {
  360. RDG::RecordedBufferCopy buffer_copy;
  361. buffer_copy.source = staging_buffer_blocks[staging_buffer_current].driver_id;
  362. buffer_copy.region = region;
  363. command_buffer_copies_vector.push_back(buffer_copy);
  364. } else {
  365. driver->command_copy_buffer(frames[frame].setup_command_buffer, staging_buffer_blocks[staging_buffer_current].driver_id, p_buffer->driver_id, region);
  366. }
  367. staging_buffer_blocks.write[staging_buffer_current].fill_amount = block_write_offset + block_write_amount;
  368. to_submit -= block_write_amount;
  369. submit_from += block_write_amount;
  370. }
  371. if (p_use_draw_queue && !command_buffer_copies_vector.is_empty()) {
  372. if (_buffer_make_mutable(p_buffer, p_buffer_id)) {
  373. // The buffer must be mutable to be used as a copy destination.
  374. draw_graph.add_synchronization();
  375. }
  376. draw_graph.add_buffer_update(p_buffer->driver_id, p_buffer->draw_tracker, command_buffer_copies_vector);
  377. }
  378. return OK;
  379. }
  380. Error RenderingDevice::buffer_copy(RID p_src_buffer, RID p_dst_buffer, uint32_t p_src_offset, uint32_t p_dst_offset, uint32_t p_size) {
  381. _THREAD_SAFE_METHOD_
  382. ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER,
  383. "Copying buffers is forbidden during creation of a draw list");
  384. ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER,
  385. "Copying buffers is forbidden during creation of a compute list");
  386. Buffer *src_buffer = _get_buffer_from_owner(p_src_buffer);
  387. if (!src_buffer) {
  388. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Source buffer argument is not a valid buffer of any type.");
  389. }
  390. Buffer *dst_buffer = _get_buffer_from_owner(p_dst_buffer);
  391. if (!dst_buffer) {
  392. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Destination buffer argument is not a valid buffer of any type.");
  393. }
  394. // Validate the copy's dimensions for both buffers.
  395. ERR_FAIL_COND_V_MSG((p_size + p_src_offset) > src_buffer->size, ERR_INVALID_PARAMETER, "Size is larger than the source buffer.");
  396. ERR_FAIL_COND_V_MSG((p_size + p_dst_offset) > dst_buffer->size, ERR_INVALID_PARAMETER, "Size is larger than the destination buffer.");
  397. // Perform the copy.
  398. RDD::BufferCopyRegion region;
  399. region.src_offset = p_src_offset;
  400. region.dst_offset = p_dst_offset;
  401. region.size = p_size;
  402. if (_buffer_make_mutable(dst_buffer, p_dst_buffer)) {
  403. // The destination buffer must be mutable to be used as a copy destination.
  404. draw_graph.add_synchronization();
  405. }
  406. draw_graph.add_buffer_copy(src_buffer->driver_id, src_buffer->draw_tracker, dst_buffer->driver_id, dst_buffer->draw_tracker, region);
  407. return OK;
  408. }
  409. Error RenderingDevice::buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data) {
  410. _THREAD_SAFE_METHOD_
  411. ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER,
  412. "Updating buffers is forbidden during creation of a draw list");
  413. ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER,
  414. "Updating buffers is forbidden during creation of a compute list");
  415. Buffer *buffer = _get_buffer_from_owner(p_buffer);
  416. if (!buffer) {
  417. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type.");
  418. }
  419. ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER,
  420. "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end.");
  421. return _buffer_update(buffer, p_buffer, p_offset, (uint8_t *)p_data, p_size, true);
  422. }
  423. Error RenderingDevice::buffer_clear(RID p_buffer, uint32_t p_offset, uint32_t p_size) {
  424. _THREAD_SAFE_METHOD_
  425. ERR_FAIL_COND_V_MSG((p_size % 4) != 0, ERR_INVALID_PARAMETER,
  426. "Size must be a multiple of four");
  427. ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER,
  428. "Updating buffers in is forbidden during creation of a draw list");
  429. ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER,
  430. "Updating buffers is forbidden during creation of a compute list");
  431. Buffer *buffer = _get_buffer_from_owner(p_buffer);
  432. if (!buffer) {
  433. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type.");
  434. }
  435. ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER,
  436. "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end.");
  437. if (_buffer_make_mutable(buffer, p_buffer)) {
  438. // The destination buffer must be mutable to be used as a clear destination.
  439. draw_graph.add_synchronization();
  440. }
  441. draw_graph.add_buffer_clear(buffer->driver_id, buffer->draw_tracker, p_offset, p_size);
  442. return OK;
  443. }
  444. Vector<uint8_t> RenderingDevice::buffer_get_data(RID p_buffer, uint32_t p_offset, uint32_t p_size) {
  445. _THREAD_SAFE_METHOD_
  446. Buffer *buffer = _get_buffer_from_owner(p_buffer);
  447. if (!buffer) {
  448. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Buffer is either invalid or this type of buffer can't be retrieved. Only Index and Vertex buffers allow retrieving.");
  449. }
  450. // Size of buffer to retrieve.
  451. if (!p_size) {
  452. p_size = buffer->size;
  453. } else {
  454. ERR_FAIL_COND_V_MSG(p_size + p_offset > buffer->size, Vector<uint8_t>(),
  455. "Size is larger than the buffer.");
  456. }
  457. RDD::BufferID tmp_buffer = driver->buffer_create(buffer->size, RDD::BUFFER_USAGE_TRANSFER_TO_BIT, RDD::MEMORY_ALLOCATION_TYPE_CPU);
  458. ERR_FAIL_COND_V(!tmp_buffer, Vector<uint8_t>());
  459. RDD::BufferCopyRegion region;
  460. region.src_offset = p_offset;
  461. region.size = p_size;
  462. draw_graph.add_buffer_get_data(buffer->driver_id, buffer->draw_tracker, tmp_buffer, region);
  463. // Flush everything so memory can be safely mapped.
  464. _flush_and_stall_for_all_frames();
  465. uint8_t *buffer_mem = driver->buffer_map(tmp_buffer);
  466. ERR_FAIL_NULL_V(buffer_mem, Vector<uint8_t>());
  467. Vector<uint8_t> buffer_data;
  468. {
  469. buffer_data.resize(p_size);
  470. uint8_t *w = buffer_data.ptrw();
  471. memcpy(w, buffer_mem, p_size);
  472. }
  473. driver->buffer_unmap(tmp_buffer);
  474. driver->buffer_free(tmp_buffer);
  475. return buffer_data;
  476. }
  477. RID RenderingDevice::storage_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data, BitField<StorageBufferUsage> p_usage) {
  478. _THREAD_SAFE_METHOD_
  479. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  480. Buffer buffer;
  481. buffer.size = p_size_bytes;
  482. buffer.usage = (RDD::BUFFER_USAGE_TRANSFER_FROM_BIT | RDD::BUFFER_USAGE_TRANSFER_TO_BIT | RDD::BUFFER_USAGE_STORAGE_BIT);
  483. if (p_usage.has_flag(STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT)) {
  484. buffer.usage.set_flag(RDD::BUFFER_USAGE_INDIRECT_BIT);
  485. }
  486. buffer.driver_id = driver->buffer_create(buffer.size, buffer.usage, RDD::MEMORY_ALLOCATION_TYPE_GPU);
  487. ERR_FAIL_COND_V(!buffer.driver_id, RID());
  488. // Storage buffers are assumed to be mutable.
  489. buffer.draw_tracker = RDG::resource_tracker_create();
  490. buffer.draw_tracker->buffer_driver_id = buffer.driver_id;
  491. if (p_data.size()) {
  492. _buffer_update(&buffer, RID(), 0, p_data.ptr(), p_data.size());
  493. }
  494. buffer_memory += buffer.size;
  495. RID id = storage_buffer_owner.make_rid(buffer);
  496. #ifdef DEV_ENABLED
  497. set_resource_name(id, "RID:" + itos(id.get_id()));
  498. #endif
  499. return id;
  500. }
  501. RID RenderingDevice::texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector<uint8_t> &p_data) {
  502. _THREAD_SAFE_METHOD_
  503. uint32_t element_size = get_format_vertex_size(p_format);
  504. ERR_FAIL_COND_V_MSG(element_size == 0, RID(), "Format requested is not supported for texture buffers");
  505. uint64_t size_bytes = uint64_t(element_size) * p_size_elements;
  506. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != size_bytes, RID());
  507. Buffer texture_buffer;
  508. texture_buffer.size = size_bytes;
  509. BitField<RDD::BufferUsageBits> usage = (RDD::BUFFER_USAGE_TRANSFER_FROM_BIT | RDD::BUFFER_USAGE_TRANSFER_TO_BIT | RDD::BUFFER_USAGE_TEXEL_BIT);
  510. texture_buffer.driver_id = driver->buffer_create(size_bytes, usage, RDD::MEMORY_ALLOCATION_TYPE_GPU);
  511. ERR_FAIL_COND_V(!texture_buffer.driver_id, RID());
  512. // Texture buffers are assumed to be immutable unless they don't have initial data.
  513. if (p_data.is_empty()) {
  514. texture_buffer.draw_tracker = RDG::resource_tracker_create();
  515. texture_buffer.draw_tracker->buffer_driver_id = texture_buffer.driver_id;
  516. }
  517. bool ok = driver->buffer_set_texel_format(texture_buffer.driver_id, p_format);
  518. if (!ok) {
  519. driver->buffer_free(texture_buffer.driver_id);
  520. ERR_FAIL_V(RID());
  521. }
  522. if (p_data.size()) {
  523. _buffer_update(&texture_buffer, RID(), 0, p_data.ptr(), p_data.size());
  524. }
  525. buffer_memory += size_bytes;
  526. RID id = texture_buffer_owner.make_rid(texture_buffer);
  527. #ifdef DEV_ENABLED
  528. set_resource_name(id, "RID:" + itos(id.get_id()));
  529. #endif
  530. return id;
  531. }
  532. /*****************/
  533. /**** TEXTURE ****/
  534. /*****************/
  535. RID RenderingDevice::texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector<Vector<uint8_t>> &p_data) {
  536. _THREAD_SAFE_METHOD_
  537. // Some adjustments will happen.
  538. TextureFormat format = p_format;
  539. if (format.shareable_formats.size()) {
  540. ERR_FAIL_COND_V_MSG(!format.shareable_formats.has(format.format), RID(),
  541. "If supplied a list of shareable formats, the current format must be present in the list");
  542. ERR_FAIL_COND_V_MSG(p_view.format_override != DATA_FORMAT_MAX && !format.shareable_formats.has(p_view.format_override), RID(),
  543. "If supplied a list of shareable formats, the current view format override must be present in the list");
  544. }
  545. ERR_FAIL_INDEX_V(format.texture_type, RDD::TEXTURE_TYPE_MAX, RID());
  546. ERR_FAIL_COND_V_MSG(format.width < 1, RID(), "Width must be equal or greater than 1 for all textures");
  547. if (format.texture_type != TEXTURE_TYPE_1D && format.texture_type != TEXTURE_TYPE_1D_ARRAY) {
  548. ERR_FAIL_COND_V_MSG(format.height < 1, RID(), "Height must be equal or greater than 1 for 2D and 3D textures");
  549. }
  550. if (format.texture_type == TEXTURE_TYPE_3D) {
  551. ERR_FAIL_COND_V_MSG(format.depth < 1, RID(), "Depth must be equal or greater than 1 for 3D textures");
  552. }
  553. ERR_FAIL_COND_V(format.mipmaps < 1, RID());
  554. if (format.texture_type == TEXTURE_TYPE_1D_ARRAY || format.texture_type == TEXTURE_TYPE_2D_ARRAY || format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || format.texture_type == TEXTURE_TYPE_CUBE) {
  555. ERR_FAIL_COND_V_MSG(format.array_layers < 1, RID(),
  556. "Amount of layers must be equal or greater than 1 for arrays and cubemaps.");
  557. ERR_FAIL_COND_V_MSG((format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || format.texture_type == TEXTURE_TYPE_CUBE) && (format.array_layers % 6) != 0, RID(),
  558. "Cubemap and cubemap array textures must provide a layer number that is multiple of 6");
  559. } else {
  560. format.array_layers = 1;
  561. }
  562. ERR_FAIL_INDEX_V(format.samples, TEXTURE_SAMPLES_MAX, RID());
  563. format.height = format.texture_type != TEXTURE_TYPE_1D && format.texture_type != TEXTURE_TYPE_1D_ARRAY ? format.height : 1;
  564. format.depth = format.texture_type == TEXTURE_TYPE_3D ? format.depth : 1;
  565. uint32_t required_mipmaps = get_image_required_mipmaps(format.width, format.height, format.depth);
  566. ERR_FAIL_COND_V_MSG(required_mipmaps < format.mipmaps, RID(),
  567. "Too many mipmaps requested for texture format and dimensions (" + itos(format.mipmaps) + "), maximum allowed: (" + itos(required_mipmaps) + ").");
  568. uint32_t forced_usage_bits = 0;
  569. if (p_data.size()) {
  570. ERR_FAIL_COND_V_MSG(p_data.size() != (int)format.array_layers, RID(),
  571. "Default supplied data for image format is of invalid length (" + itos(p_data.size()) + "), should be (" + itos(format.array_layers) + ").");
  572. for (uint32_t i = 0; i < format.array_layers; i++) {
  573. uint32_t required_size = get_image_format_required_size(format.format, format.width, format.height, format.depth, format.mipmaps);
  574. ERR_FAIL_COND_V_MSG((uint32_t)p_data[i].size() != required_size, RID(),
  575. "Data for slice index " + itos(i) + " (mapped to layer " + itos(i) + ") differs in size (supplied: " + itos(p_data[i].size()) + ") than what is required by the format (" + itos(required_size) + ").");
  576. }
  577. if (!(format.usage_bits & TEXTURE_USAGE_CAN_UPDATE_BIT)) {
  578. forced_usage_bits = TEXTURE_USAGE_CAN_UPDATE_BIT;
  579. }
  580. }
  581. {
  582. // Validate that this image is supported for the intended use.
  583. bool cpu_readable = (format.usage_bits & RDD::TEXTURE_USAGE_CPU_READ_BIT);
  584. BitField<RDD::TextureUsageBits> supported_usage = driver->texture_get_usages_supported_by_format(format.format, cpu_readable);
  585. String format_text = "'" + String(FORMAT_NAMES[format.format]) + "'";
  586. if ((format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_SAMPLING_BIT)) {
  587. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as sampling texture.");
  588. }
  589. if ((format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) {
  590. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as color attachment.");
  591. }
  592. if ((format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  593. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as depth-stencil attachment.");
  594. }
  595. if ((format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_STORAGE_BIT)) {
  596. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as storage image.");
  597. }
  598. if ((format.usage_bits & TEXTURE_USAGE_STORAGE_ATOMIC_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_STORAGE_ATOMIC_BIT)) {
  599. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as atomic storage image.");
  600. }
  601. if ((format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_VRS_ATTACHMENT_BIT)) {
  602. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as VRS attachment.");
  603. }
  604. }
  605. // Transfer and validate view info.
  606. RDD::TextureView tv;
  607. if (p_view.format_override == DATA_FORMAT_MAX) {
  608. tv.format = format.format;
  609. } else {
  610. ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());
  611. tv.format = p_view.format_override;
  612. }
  613. ERR_FAIL_INDEX_V(p_view.swizzle_r, TEXTURE_SWIZZLE_MAX, RID());
  614. ERR_FAIL_INDEX_V(p_view.swizzle_g, TEXTURE_SWIZZLE_MAX, RID());
  615. ERR_FAIL_INDEX_V(p_view.swizzle_b, TEXTURE_SWIZZLE_MAX, RID());
  616. ERR_FAIL_INDEX_V(p_view.swizzle_a, TEXTURE_SWIZZLE_MAX, RID());
  617. tv.swizzle_r = p_view.swizzle_r;
  618. tv.swizzle_g = p_view.swizzle_g;
  619. tv.swizzle_b = p_view.swizzle_b;
  620. tv.swizzle_a = p_view.swizzle_a;
  621. // Create.
  622. Texture texture;
  623. format.usage_bits |= forced_usage_bits;
  624. texture.driver_id = driver->texture_create(format, tv);
  625. ERR_FAIL_COND_V(!texture.driver_id, RID());
  626. texture.type = format.texture_type;
  627. texture.format = format.format;
  628. texture.width = format.width;
  629. texture.height = format.height;
  630. texture.depth = format.depth;
  631. texture.layers = format.array_layers;
  632. texture.mipmaps = format.mipmaps;
  633. texture.base_mipmap = 0;
  634. texture.base_layer = 0;
  635. texture.is_resolve_buffer = format.is_resolve_buffer;
  636. texture.usage_flags = format.usage_bits & ~forced_usage_bits;
  637. texture.samples = format.samples;
  638. texture.allowed_shared_formats = format.shareable_formats;
  639. texture.has_initial_data = !p_data.is_empty();
  640. if ((format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  641. texture.read_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT);
  642. texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT);
  643. if (format_has_stencil(format.format)) {
  644. texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_STENCIL_BIT);
  645. }
  646. } else {
  647. texture.read_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT);
  648. texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT);
  649. }
  650. texture.bound = false;
  651. // Textures are only assumed to be immutable if they have initial data and none of the other bits that indicate write usage are enabled.
  652. bool texture_mutable_by_default = texture.usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_STORAGE_BIT | TEXTURE_USAGE_STORAGE_ATOMIC_BIT | TEXTURE_USAGE_VRS_ATTACHMENT_BIT);
  653. if (p_data.is_empty() || texture_mutable_by_default) {
  654. _texture_make_mutable(&texture, RID());
  655. }
  656. texture_memory += driver->texture_get_allocation_size(texture.driver_id);
  657. RID id = texture_owner.make_rid(texture);
  658. #ifdef DEV_ENABLED
  659. set_resource_name(id, "RID:" + itos(id.get_id()));
  660. #endif
  661. if (p_data.size()) {
  662. for (uint32_t i = 0; i < p_format.array_layers; i++) {
  663. _texture_update(id, i, p_data[i], true, false);
  664. }
  665. if (texture.draw_tracker != nullptr) {
  666. // Draw tracker can assume the texture will be in transfer destination.
  667. texture.draw_tracker->usage = RDG::RESOURCE_USAGE_TRANSFER_TO;
  668. }
  669. }
  670. return id;
  671. }
  672. RID RenderingDevice::texture_create_shared(const TextureView &p_view, RID p_with_texture) {
  673. _THREAD_SAFE_METHOD_
  674. Texture *src_texture = texture_owner.get_or_null(p_with_texture);
  675. ERR_FAIL_NULL_V(src_texture, RID());
  676. if (src_texture->owner.is_valid()) { // Ahh this is a share. The RenderingDeviceDriver needs the actual owner.
  677. p_with_texture = src_texture->owner;
  678. src_texture = texture_owner.get_or_null(src_texture->owner);
  679. ERR_FAIL_NULL_V(src_texture, RID()); // This is a bug.
  680. }
  681. // Create view.
  682. Texture texture = *src_texture;
  683. RDD::TextureView tv;
  684. if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) {
  685. tv.format = texture.format;
  686. } else {
  687. ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());
  688. ERR_FAIL_COND_V_MSG(!texture.allowed_shared_formats.has(p_view.format_override), RID(),
  689. "Format override is not in the list of allowed shareable formats for original texture.");
  690. tv.format = p_view.format_override;
  691. }
  692. tv.swizzle_r = p_view.swizzle_r;
  693. tv.swizzle_g = p_view.swizzle_g;
  694. tv.swizzle_b = p_view.swizzle_b;
  695. tv.swizzle_a = p_view.swizzle_a;
  696. texture.driver_id = driver->texture_create_shared(texture.driver_id, tv);
  697. ERR_FAIL_COND_V(!texture.driver_id, RID());
  698. texture.slice_trackers.clear();
  699. if (texture.draw_tracker != nullptr) {
  700. texture.draw_tracker->reference_count++;
  701. }
  702. texture.owner = p_with_texture;
  703. RID id = texture_owner.make_rid(texture);
  704. #ifdef DEV_ENABLED
  705. set_resource_name(id, "RID:" + itos(id.get_id()));
  706. #endif
  707. _add_dependency(id, p_with_texture);
  708. return id;
  709. }
  710. RID RenderingDevice::texture_create_from_extension(TextureType p_type, DataFormat p_format, TextureSamples p_samples, BitField<RenderingDevice::TextureUsageBits> p_usage, uint64_t p_image, uint64_t p_width, uint64_t p_height, uint64_t p_depth, uint64_t p_layers) {
  711. _THREAD_SAFE_METHOD_
  712. // This method creates a texture object using a VkImage created by an extension, module or other external source (OpenXR uses this).
  713. Texture texture;
  714. texture.type = p_type;
  715. texture.format = p_format;
  716. texture.samples = p_samples;
  717. texture.width = p_width;
  718. texture.height = p_height;
  719. texture.depth = p_depth;
  720. texture.layers = p_layers;
  721. texture.mipmaps = 1;
  722. texture.usage_flags = p_usage;
  723. texture.base_mipmap = 0;
  724. texture.base_layer = 0;
  725. texture.allowed_shared_formats.push_back(RD::DATA_FORMAT_R8G8B8A8_UNORM);
  726. texture.allowed_shared_formats.push_back(RD::DATA_FORMAT_R8G8B8A8_SRGB);
  727. if (p_usage.has_flag(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  728. texture.read_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT);
  729. texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT);
  730. /*if (format_has_stencil(p_format.format)) {
  731. texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_STENCIL_BIT);
  732. }*/
  733. } else {
  734. texture.read_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT);
  735. texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT);
  736. }
  737. texture.driver_id = driver->texture_create_from_extension(p_image, p_type, p_format, p_layers, (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT));
  738. ERR_FAIL_COND_V(!texture.driver_id, RID());
  739. _texture_make_mutable(&texture, RID());
  740. RID id = texture_owner.make_rid(texture);
  741. #ifdef DEV_ENABLED
  742. set_resource_name(id, "RID:" + itos(id.get_id()));
  743. #endif
  744. return id;
  745. }
  746. RID RenderingDevice::texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps, TextureSliceType p_slice_type, uint32_t p_layers) {
  747. _THREAD_SAFE_METHOD_
  748. Texture *src_texture = texture_owner.get_or_null(p_with_texture);
  749. ERR_FAIL_NULL_V(src_texture, RID());
  750. if (src_texture->owner.is_valid()) { // // Ahh this is a share. The RenderingDeviceDriver needs the actual owner.
  751. p_with_texture = src_texture->owner;
  752. src_texture = texture_owner.get_or_null(src_texture->owner);
  753. ERR_FAIL_NULL_V(src_texture, RID()); // This is a bug.
  754. }
  755. ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_CUBEMAP && (src_texture->type != TEXTURE_TYPE_CUBE && src_texture->type != TEXTURE_TYPE_CUBE_ARRAY), RID(),
  756. "Can only create a cubemap slice from a cubemap or cubemap array mipmap");
  757. ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_3D && src_texture->type != TEXTURE_TYPE_3D, RID(),
  758. "Can only create a 3D slice from a 3D texture");
  759. ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_2D_ARRAY && (src_texture->type != TEXTURE_TYPE_2D_ARRAY), RID(),
  760. "Can only create an array slice from a 2D array mipmap");
  761. // Create view.
  762. ERR_FAIL_UNSIGNED_INDEX_V(p_mipmap, src_texture->mipmaps, RID());
  763. ERR_FAIL_COND_V(p_mipmap + p_mipmaps > src_texture->mipmaps, RID());
  764. ERR_FAIL_UNSIGNED_INDEX_V(p_layer, src_texture->layers, RID());
  765. int slice_layers = 1;
  766. if (p_layers != 0) {
  767. ERR_FAIL_COND_V_MSG(p_layers > 1 && p_slice_type != TEXTURE_SLICE_2D_ARRAY, RID(), "layer slicing only supported for 2D arrays");
  768. ERR_FAIL_COND_V_MSG(p_layer + p_layers > src_texture->layers, RID(), "layer slice is out of bounds");
  769. slice_layers = p_layers;
  770. } else if (p_slice_type == TEXTURE_SLICE_2D_ARRAY) {
  771. ERR_FAIL_COND_V_MSG(p_layer != 0, RID(), "layer must be 0 when obtaining a 2D array mipmap slice");
  772. slice_layers = src_texture->layers;
  773. } else if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {
  774. slice_layers = 6;
  775. }
  776. Texture texture = *src_texture;
  777. get_image_format_required_size(texture.format, texture.width, texture.height, texture.depth, p_mipmap + 1, &texture.width, &texture.height);
  778. texture.mipmaps = p_mipmaps;
  779. texture.layers = slice_layers;
  780. texture.base_mipmap = p_mipmap;
  781. texture.base_layer = p_layer;
  782. if (p_slice_type == TEXTURE_SLICE_2D) {
  783. texture.type = TEXTURE_TYPE_2D;
  784. } else if (p_slice_type == TEXTURE_SLICE_3D) {
  785. texture.type = TEXTURE_TYPE_3D;
  786. }
  787. RDD::TextureView tv;
  788. if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) {
  789. tv.format = texture.format;
  790. } else {
  791. ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());
  792. ERR_FAIL_COND_V_MSG(!texture.allowed_shared_formats.has(p_view.format_override), RID(),
  793. "Format override is not in the list of allowed shareable formats for original texture.");
  794. tv.format = p_view.format_override;
  795. }
  796. tv.swizzle_r = p_view.swizzle_r;
  797. tv.swizzle_g = p_view.swizzle_g;
  798. tv.swizzle_b = p_view.swizzle_b;
  799. tv.swizzle_a = p_view.swizzle_a;
  800. if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {
  801. ERR_FAIL_COND_V_MSG(p_layer >= src_texture->layers, RID(),
  802. "Specified layer is invalid for cubemap");
  803. ERR_FAIL_COND_V_MSG((p_layer % 6) != 0, RID(),
  804. "Specified layer must be a multiple of 6.");
  805. }
  806. texture.driver_id = driver->texture_create_shared_from_slice(src_texture->driver_id, tv, p_slice_type, p_layer, slice_layers, p_mipmap, p_mipmaps);
  807. ERR_FAIL_COND_V(!texture.driver_id, RID());
  808. const Rect2i slice_rect(p_mipmap, p_layer, p_mipmaps, slice_layers);
  809. texture.owner = p_with_texture;
  810. texture.slice_type = p_slice_type;
  811. texture.slice_rect = slice_rect;
  812. // If parent is mutable, make slice mutable by default.
  813. if (src_texture->draw_tracker != nullptr) {
  814. texture.draw_tracker = nullptr;
  815. _texture_make_mutable(&texture, RID());
  816. }
  817. RID id = texture_owner.make_rid(texture);
  818. #ifdef DEV_ENABLED
  819. set_resource_name(id, "RID:" + itos(id.get_id()));
  820. #endif
  821. _add_dependency(id, p_with_texture);
  822. return id;
  823. }
  824. Error RenderingDevice::texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data) {
  825. return _texture_update(p_texture, p_layer, p_data, false, true);
  826. }
  827. static _ALWAYS_INLINE_ void _copy_region(uint8_t const *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_x, uint32_t p_src_y, uint32_t p_src_w, uint32_t p_src_h, uint32_t p_src_full_w, uint32_t p_dst_pitch, uint32_t p_unit_size) {
  828. uint32_t src_offset = (p_src_y * p_src_full_w + p_src_x) * p_unit_size;
  829. uint32_t dst_offset = 0;
  830. for (uint32_t y = p_src_h; y > 0; y--) {
  831. uint8_t const *__restrict src = p_src + src_offset;
  832. uint8_t *__restrict dst = p_dst + dst_offset;
  833. for (uint32_t x = p_src_w * p_unit_size; x > 0; x--) {
  834. *dst = *src;
  835. src++;
  836. dst++;
  837. }
  838. src_offset += p_src_full_w * p_unit_size;
  839. dst_offset += p_dst_pitch;
  840. }
  841. }
  842. Error RenderingDevice::_texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, bool p_use_setup_queue, bool p_validate_can_update) {
  843. _THREAD_SAFE_METHOD_
  844. ERR_FAIL_COND_V_MSG((draw_list || compute_list) && !p_use_setup_queue, ERR_INVALID_PARAMETER,
  845. "Updating textures is forbidden during creation of a draw or compute list");
  846. Texture *texture = texture_owner.get_or_null(p_texture);
  847. ERR_FAIL_NULL_V(texture, ERR_INVALID_PARAMETER);
  848. if (texture->owner != RID()) {
  849. p_texture = texture->owner;
  850. texture = texture_owner.get_or_null(texture->owner);
  851. ERR_FAIL_NULL_V(texture, ERR_BUG); // This is a bug.
  852. }
  853. ERR_FAIL_COND_V_MSG(texture->bound, ERR_CANT_ACQUIRE_RESOURCE,
  854. "Texture can't be updated while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to update this texture.");
  855. ERR_FAIL_COND_V_MSG(p_validate_can_update && !(texture->usage_flags & TEXTURE_USAGE_CAN_UPDATE_BIT), ERR_INVALID_PARAMETER,
  856. "Texture requires the `RenderingDevice.TEXTURE_USAGE_CAN_UPDATE_BIT` to be set to be updatable.");
  857. uint32_t layer_count = texture->layers;
  858. if (texture->type == TEXTURE_TYPE_CUBE || texture->type == TEXTURE_TYPE_CUBE_ARRAY) {
  859. layer_count *= 6;
  860. }
  861. ERR_FAIL_COND_V(p_layer >= layer_count, ERR_INVALID_PARAMETER);
  862. uint32_t width, height;
  863. uint32_t tight_mip_size = get_image_format_required_size(texture->format, texture->width, texture->height, texture->depth, texture->mipmaps, &width, &height);
  864. uint32_t required_size = tight_mip_size;
  865. uint32_t required_align = get_compressed_image_format_block_byte_size(texture->format);
  866. if (required_align == 1) {
  867. required_align = get_image_format_pixel_size(texture->format);
  868. }
  869. required_align = STEPIFY(required_align, driver->api_trait_get(RDD::API_TRAIT_TEXTURE_TRANSFER_ALIGNMENT));
  870. ERR_FAIL_COND_V_MSG(required_size != (uint32_t)p_data.size(), ERR_INVALID_PARAMETER,
  871. "Required size for texture update (" + itos(required_size) + ") does not match data supplied size (" + itos(p_data.size()) + ").");
  872. uint32_t region_size = texture_upload_region_size_px;
  873. const uint8_t *r = p_data.ptr();
  874. thread_local LocalVector<RDG::RecordedBufferToTextureCopy> command_buffer_to_texture_copies_vector;
  875. command_buffer_to_texture_copies_vector.clear();
  876. if (p_use_setup_queue && driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS)) {
  877. // When using the setup queue directly, we transition the texture to the optimal layout.
  878. RDD::TextureBarrier tb;
  879. tb.texture = texture->driver_id;
  880. tb.dst_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT;
  881. tb.prev_layout = RDD::TEXTURE_LAYOUT_UNDEFINED;
  882. tb.next_layout = RDD::TEXTURE_LAYOUT_TRANSFER_DST_OPTIMAL;
  883. tb.subresources.aspect = texture->barrier_aspect_flags;
  884. tb.subresources.mipmap_count = texture->mipmaps;
  885. tb.subresources.base_layer = p_layer;
  886. tb.subresources.layer_count = 1;
  887. driver->command_pipeline_barrier(frames[frame].setup_command_buffer, RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, RDD::PIPELINE_STAGE_TRANSFER_BIT, {}, {}, tb);
  888. }
  889. uint32_t mipmap_offset = 0;
  890. uint32_t logic_width = texture->width;
  891. uint32_t logic_height = texture->height;
  892. for (uint32_t mm_i = 0; mm_i < texture->mipmaps; mm_i++) {
  893. uint32_t depth = 0;
  894. uint32_t image_total = get_image_format_required_size(texture->format, texture->width, texture->height, texture->depth, mm_i + 1, &width, &height, &depth);
  895. const uint8_t *read_ptr_mipmap = r + mipmap_offset;
  896. tight_mip_size = image_total - mipmap_offset;
  897. for (uint32_t z = 0; z < depth; z++) { // For 3D textures, depth may be > 0.
  898. const uint8_t *read_ptr = read_ptr_mipmap + (tight_mip_size / depth) * z;
  899. for (uint32_t y = 0; y < height; y += region_size) {
  900. for (uint32_t x = 0; x < width; x += region_size) {
  901. uint32_t region_w = MIN(region_size, width - x);
  902. uint32_t region_h = MIN(region_size, height - y);
  903. uint32_t region_logic_w = MIN(region_size, logic_width - x);
  904. uint32_t region_logic_h = MIN(region_size, logic_height - y);
  905. uint32_t pixel_size = get_image_format_pixel_size(texture->format);
  906. uint32_t block_w = 0, block_h = 0;
  907. get_compressed_image_format_block_dimensions(texture->format, block_w, block_h);
  908. uint32_t region_pitch = (region_w * pixel_size * block_w) >> get_compressed_image_format_pixel_rshift(texture->format);
  909. uint32_t pitch_step = driver->api_trait_get(RDD::API_TRAIT_TEXTURE_DATA_ROW_PITCH_STEP);
  910. region_pitch = STEPIFY(region_pitch, pitch_step);
  911. uint32_t to_allocate = region_pitch * region_h;
  912. uint32_t alloc_offset = 0, alloc_size = 0;
  913. StagingRequiredAction required_action;
  914. Error err = _staging_buffer_allocate(to_allocate, required_align, alloc_offset, alloc_size, required_action, false);
  915. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  916. if (!p_use_setup_queue && !command_buffer_to_texture_copies_vector.is_empty() && required_action == STAGING_REQUIRED_ACTION_FLUSH_AND_STALL_ALL) {
  917. if (_texture_make_mutable(texture, p_texture)) {
  918. // The texture must be mutable to be used as a copy destination.
  919. draw_graph.add_synchronization();
  920. }
  921. // If we're using the draw queue and the staging buffer requires flushing everything, we submit the command early and clear the current vector.
  922. draw_graph.add_texture_update(texture->driver_id, texture->draw_tracker, command_buffer_to_texture_copies_vector);
  923. command_buffer_to_texture_copies_vector.clear();
  924. }
  925. _staging_buffer_execute_required_action(required_action);
  926. uint8_t *write_ptr;
  927. { // Map.
  928. uint8_t *data_ptr = driver->buffer_map(staging_buffer_blocks[staging_buffer_current].driver_id);
  929. ERR_FAIL_NULL_V(data_ptr, ERR_CANT_CREATE);
  930. write_ptr = data_ptr;
  931. write_ptr += alloc_offset;
  932. }
  933. ERR_FAIL_COND_V(region_w % block_w, ERR_BUG);
  934. ERR_FAIL_COND_V(region_h % block_h, ERR_BUG);
  935. if (block_w != 1 || block_h != 1) {
  936. // Compressed image (blocks).
  937. // Must copy a block region.
  938. uint32_t block_size = get_compressed_image_format_block_byte_size(texture->format);
  939. // Re-create current variables in blocky format.
  940. uint32_t xb = x / block_w;
  941. uint32_t yb = y / block_h;
  942. uint32_t wb = width / block_w;
  943. //uint32_t hb = height / block_h;
  944. uint32_t region_wb = region_w / block_w;
  945. uint32_t region_hb = region_h / block_h;
  946. _copy_region(read_ptr, write_ptr, xb, yb, region_wb, region_hb, wb, region_pitch, block_size);
  947. } else {
  948. // Regular image (pixels).
  949. // Must copy a pixel region.
  950. _copy_region(read_ptr, write_ptr, x, y, region_w, region_h, width, region_pitch, pixel_size);
  951. }
  952. { // Unmap.
  953. driver->buffer_unmap(staging_buffer_blocks[staging_buffer_current].driver_id);
  954. }
  955. RDD::BufferTextureCopyRegion copy_region;
  956. copy_region.buffer_offset = alloc_offset;
  957. copy_region.texture_subresources.aspect = texture->read_aspect_flags;
  958. copy_region.texture_subresources.mipmap = mm_i;
  959. copy_region.texture_subresources.base_layer = p_layer;
  960. copy_region.texture_subresources.layer_count = 1;
  961. copy_region.texture_offset = Vector3i(x, y, z);
  962. copy_region.texture_region_size = Vector3i(region_logic_w, region_logic_h, 1);
  963. if (p_use_setup_queue) {
  964. driver->command_copy_buffer_to_texture(frames[frame].setup_command_buffer, staging_buffer_blocks[staging_buffer_current].driver_id, texture->driver_id, RDD::TEXTURE_LAYOUT_TRANSFER_DST_OPTIMAL, copy_region);
  965. } else {
  966. RDG::RecordedBufferToTextureCopy buffer_to_texture_copy;
  967. buffer_to_texture_copy.from_buffer = staging_buffer_blocks[staging_buffer_current].driver_id;
  968. buffer_to_texture_copy.region = copy_region;
  969. command_buffer_to_texture_copies_vector.push_back(buffer_to_texture_copy);
  970. }
  971. staging_buffer_blocks.write[staging_buffer_current].fill_amount = alloc_offset + alloc_size;
  972. }
  973. }
  974. }
  975. mipmap_offset = image_total;
  976. logic_width = MAX(1u, logic_width >> 1);
  977. logic_height = MAX(1u, logic_height >> 1);
  978. }
  979. if (p_use_setup_queue && (texture->draw_tracker == nullptr) && driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS)) {
  980. // If the texture does not have a tracker, it means it must be transitioned to the sampling state.
  981. RDD::TextureBarrier tb;
  982. tb.texture = texture->driver_id;
  983. tb.src_access = RDD::BARRIER_ACCESS_TRANSFER_WRITE_BIT;
  984. tb.prev_layout = RDD::TEXTURE_LAYOUT_TRANSFER_DST_OPTIMAL;
  985. tb.next_layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  986. tb.subresources.aspect = texture->barrier_aspect_flags;
  987. tb.subresources.mipmap_count = texture->mipmaps;
  988. tb.subresources.base_layer = p_layer;
  989. tb.subresources.layer_count = 1;
  990. driver->command_pipeline_barrier(frames[frame].setup_command_buffer, RDD::PIPELINE_STAGE_TRANSFER_BIT, RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, {}, {}, tb);
  991. } else if (!p_use_setup_queue && !command_buffer_to_texture_copies_vector.is_empty()) {
  992. if (_texture_make_mutable(texture, p_texture)) {
  993. // The texture must be mutable to be used as a copy destination.
  994. draw_graph.add_synchronization();
  995. }
  996. draw_graph.add_texture_update(texture->driver_id, texture->draw_tracker, command_buffer_to_texture_copies_vector);
  997. }
  998. return OK;
  999. }
  1000. Vector<uint8_t> RenderingDevice::_texture_get_data(Texture *tex, uint32_t p_layer, bool p_2d) {
  1001. uint32_t width, height, depth;
  1002. uint32_t tight_mip_size = get_image_format_required_size(tex->format, tex->width, tex->height, p_2d ? 1 : tex->depth, tex->mipmaps, &width, &height, &depth);
  1003. Vector<uint8_t> image_data;
  1004. image_data.resize(tight_mip_size);
  1005. uint32_t blockw, blockh;
  1006. get_compressed_image_format_block_dimensions(tex->format, blockw, blockh);
  1007. uint32_t block_size = get_compressed_image_format_block_byte_size(tex->format);
  1008. uint32_t pixel_size = get_image_format_pixel_size(tex->format);
  1009. {
  1010. uint8_t *w = image_data.ptrw();
  1011. uint32_t mipmap_offset = 0;
  1012. for (uint32_t mm_i = 0; mm_i < tex->mipmaps; mm_i++) {
  1013. uint32_t image_total = get_image_format_required_size(tex->format, tex->width, tex->height, p_2d ? 1 : tex->depth, mm_i + 1, &width, &height, &depth);
  1014. uint8_t *write_ptr_mipmap = w + mipmap_offset;
  1015. tight_mip_size = image_total - mipmap_offset;
  1016. RDD::TextureSubresource subres;
  1017. subres.aspect = RDD::TEXTURE_ASPECT_COLOR;
  1018. subres.layer = p_layer;
  1019. subres.mipmap = mm_i;
  1020. RDD::TextureCopyableLayout layout;
  1021. driver->texture_get_copyable_layout(tex->driver_id, subres, &layout);
  1022. uint8_t *img_mem = driver->texture_map(tex->driver_id, subres);
  1023. ERR_FAIL_NULL_V(img_mem, Vector<uint8_t>());
  1024. for (uint32_t z = 0; z < depth; z++) {
  1025. uint8_t *write_ptr = write_ptr_mipmap + z * tight_mip_size / depth;
  1026. const uint8_t *slice_read_ptr = img_mem + z * layout.depth_pitch;
  1027. if (block_size > 1) {
  1028. // Compressed.
  1029. uint32_t line_width = (block_size * (width / blockw));
  1030. for (uint32_t y = 0; y < height / blockh; y++) {
  1031. const uint8_t *rptr = slice_read_ptr + y * layout.row_pitch;
  1032. uint8_t *wptr = write_ptr + y * line_width;
  1033. memcpy(wptr, rptr, line_width);
  1034. }
  1035. } else {
  1036. // Uncompressed.
  1037. for (uint32_t y = 0; y < height; y++) {
  1038. const uint8_t *rptr = slice_read_ptr + y * layout.row_pitch;
  1039. uint8_t *wptr = write_ptr + y * pixel_size * width;
  1040. memcpy(wptr, rptr, (uint64_t)pixel_size * width);
  1041. }
  1042. }
  1043. }
  1044. driver->texture_unmap(tex->driver_id);
  1045. mipmap_offset = image_total;
  1046. }
  1047. }
  1048. return image_data;
  1049. }
  1050. Vector<uint8_t> RenderingDevice::texture_get_data(RID p_texture, uint32_t p_layer) {
  1051. _THREAD_SAFE_METHOD_
  1052. Texture *tex = texture_owner.get_or_null(p_texture);
  1053. ERR_FAIL_NULL_V(tex, Vector<uint8_t>());
  1054. ERR_FAIL_COND_V_MSG(tex->bound, Vector<uint8_t>(),
  1055. "Texture can't be retrieved while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to retrieve this texture.");
  1056. ERR_FAIL_COND_V_MSG(!(tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), Vector<uint8_t>(),
  1057. "Texture requires the `RenderingDevice.TEXTURE_USAGE_CAN_COPY_FROM_BIT` to be set to be retrieved.");
  1058. uint32_t layer_count = tex->layers;
  1059. if (tex->type == TEXTURE_TYPE_CUBE || tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  1060. layer_count *= 6;
  1061. }
  1062. ERR_FAIL_COND_V(p_layer >= layer_count, Vector<uint8_t>());
  1063. if ((tex->usage_flags & TEXTURE_USAGE_CPU_READ_BIT)) {
  1064. // Does not need anything fancy, map and read.
  1065. return _texture_get_data(tex, p_layer);
  1066. } else {
  1067. LocalVector<RDD::TextureCopyableLayout> mip_layouts;
  1068. uint32_t work_mip_alignment = driver->api_trait_get(RDD::API_TRAIT_TEXTURE_TRANSFER_ALIGNMENT);
  1069. uint32_t work_buffer_size = 0;
  1070. mip_layouts.resize(tex->mipmaps);
  1071. for (uint32_t i = 0; i < tex->mipmaps; i++) {
  1072. RDD::TextureSubresource subres;
  1073. subres.aspect = RDD::TEXTURE_ASPECT_COLOR;
  1074. subres.layer = p_layer;
  1075. subres.mipmap = i;
  1076. driver->texture_get_copyable_layout(tex->driver_id, subres, &mip_layouts[i]);
  1077. // Assuming layers are tightly packed. If this is not true on some driver, we must modify the copy algorithm.
  1078. DEV_ASSERT(mip_layouts[i].layer_pitch == mip_layouts[i].size / layer_count);
  1079. work_buffer_size = STEPIFY(work_buffer_size, work_mip_alignment) + mip_layouts[i].size;
  1080. }
  1081. RDD::BufferID tmp_buffer = driver->buffer_create(work_buffer_size, RDD::BUFFER_USAGE_TRANSFER_TO_BIT, RDD::MEMORY_ALLOCATION_TYPE_CPU);
  1082. ERR_FAIL_COND_V(!tmp_buffer, Vector<uint8_t>());
  1083. thread_local LocalVector<RDD::BufferTextureCopyRegion> command_buffer_texture_copy_regions_vector;
  1084. command_buffer_texture_copy_regions_vector.clear();
  1085. uint32_t block_w = 0, block_h = 0;
  1086. get_compressed_image_format_block_dimensions(tex->format, block_w, block_h);
  1087. uint32_t w = tex->width;
  1088. uint32_t h = tex->height;
  1089. uint32_t d = tex->depth;
  1090. for (uint32_t i = 0; i < tex->mipmaps; i++) {
  1091. RDD::BufferTextureCopyRegion copy_region;
  1092. copy_region.buffer_offset = mip_layouts[i].offset;
  1093. copy_region.texture_subresources.aspect = tex->read_aspect_flags;
  1094. copy_region.texture_subresources.mipmap = i;
  1095. copy_region.texture_subresources.base_layer = p_layer;
  1096. copy_region.texture_subresources.layer_count = 1;
  1097. copy_region.texture_region_size.x = w;
  1098. copy_region.texture_region_size.y = h;
  1099. copy_region.texture_region_size.z = d;
  1100. command_buffer_texture_copy_regions_vector.push_back(copy_region);
  1101. w = MAX(block_w, w >> 1);
  1102. h = MAX(block_h, h >> 1);
  1103. d = MAX(1u, d >> 1);
  1104. }
  1105. if (_texture_make_mutable(tex, p_texture)) {
  1106. // The texture must be mutable to be used as a copy source due to layout transitions.
  1107. draw_graph.add_synchronization();
  1108. }
  1109. draw_graph.add_texture_get_data(tex->driver_id, tex->draw_tracker, tmp_buffer, command_buffer_texture_copy_regions_vector);
  1110. // Flush everything so memory can be safely mapped.
  1111. _flush_and_stall_for_all_frames();
  1112. const uint8_t *read_ptr = driver->buffer_map(tmp_buffer);
  1113. ERR_FAIL_NULL_V(read_ptr, Vector<uint8_t>());
  1114. Vector<uint8_t> buffer_data;
  1115. uint32_t tight_buffer_size = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, tex->mipmaps);
  1116. buffer_data.resize(tight_buffer_size);
  1117. uint8_t *write_ptr = buffer_data.ptrw();
  1118. w = tex->width;
  1119. h = tex->height;
  1120. d = tex->depth;
  1121. for (uint32_t i = 0; i < tex->mipmaps; i++) {
  1122. uint32_t width = 0, height = 0, depth = 0;
  1123. uint32_t tight_mip_size = get_image_format_required_size(tex->format, w, h, d, 1, &width, &height, &depth);
  1124. uint32_t tight_row_pitch = tight_mip_size / ((height / block_h) * depth);
  1125. // Copy row-by-row to erase padding due to alignments.
  1126. const uint8_t *rp = read_ptr;
  1127. uint8_t *wp = write_ptr;
  1128. for (uint32_t row = h * d / block_h; row != 0; row--) {
  1129. memcpy(wp, rp, tight_row_pitch);
  1130. rp += mip_layouts[i].row_pitch;
  1131. wp += tight_row_pitch;
  1132. }
  1133. w = MAX(block_w, w >> 1);
  1134. h = MAX(block_h, h >> 1);
  1135. d = MAX(1u, d >> 1);
  1136. read_ptr += mip_layouts[i].size;
  1137. write_ptr += tight_mip_size;
  1138. }
  1139. driver->buffer_unmap(tmp_buffer);
  1140. driver->buffer_free(tmp_buffer);
  1141. return buffer_data;
  1142. }
  1143. }
  1144. bool RenderingDevice::texture_is_shared(RID p_texture) {
  1145. _THREAD_SAFE_METHOD_
  1146. Texture *tex = texture_owner.get_or_null(p_texture);
  1147. ERR_FAIL_NULL_V(tex, false);
  1148. return tex->owner.is_valid();
  1149. }
  1150. bool RenderingDevice::texture_is_valid(RID p_texture) {
  1151. return texture_owner.owns(p_texture);
  1152. }
  1153. RD::TextureFormat RenderingDevice::texture_get_format(RID p_texture) {
  1154. _THREAD_SAFE_METHOD_
  1155. Texture *tex = texture_owner.get_or_null(p_texture);
  1156. ERR_FAIL_NULL_V(tex, TextureFormat());
  1157. TextureFormat tf;
  1158. tf.format = tex->format;
  1159. tf.width = tex->width;
  1160. tf.height = tex->height;
  1161. tf.depth = tex->depth;
  1162. tf.array_layers = tex->layers;
  1163. tf.mipmaps = tex->mipmaps;
  1164. tf.texture_type = tex->type;
  1165. tf.samples = tex->samples;
  1166. tf.usage_bits = tex->usage_flags;
  1167. tf.shareable_formats = tex->allowed_shared_formats;
  1168. tf.is_resolve_buffer = tex->is_resolve_buffer;
  1169. return tf;
  1170. }
  1171. Size2i RenderingDevice::texture_size(RID p_texture) {
  1172. _THREAD_SAFE_METHOD_
  1173. Texture *tex = texture_owner.get_or_null(p_texture);
  1174. ERR_FAIL_NULL_V(tex, Size2i());
  1175. return Size2i(tex->width, tex->height);
  1176. }
  1177. #ifndef DISABLE_DEPRECATED
  1178. uint64_t RenderingDevice::texture_get_native_handle(RID p_texture) {
  1179. return get_driver_resource(DRIVER_RESOURCE_TEXTURE, p_texture);
  1180. }
  1181. #endif
  1182. Error RenderingDevice::texture_copy(RID p_from_texture, RID p_to_texture, const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_size, uint32_t p_src_mipmap, uint32_t p_dst_mipmap, uint32_t p_src_layer, uint32_t p_dst_layer) {
  1183. _THREAD_SAFE_METHOD_
  1184. Texture *src_tex = texture_owner.get_or_null(p_from_texture);
  1185. ERR_FAIL_NULL_V(src_tex, ERR_INVALID_PARAMETER);
  1186. ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,
  1187. "Source texture can't be copied while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to copy this texture.");
  1188. ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), ERR_INVALID_PARAMETER,
  1189. "Source texture requires the `RenderingDevice.TEXTURE_USAGE_CAN_COPY_FROM_BIT` to be set to be retrieved.");
  1190. uint32_t src_layer_count = src_tex->layers;
  1191. uint32_t src_width, src_height, src_depth;
  1192. get_image_format_required_size(src_tex->format, src_tex->width, src_tex->height, src_tex->depth, p_src_mipmap + 1, &src_width, &src_height, &src_depth);
  1193. if (src_tex->type == TEXTURE_TYPE_CUBE || src_tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  1194. src_layer_count *= 6;
  1195. }
  1196. ERR_FAIL_COND_V(p_from.x < 0 || p_from.x + p_size.x > src_width, ERR_INVALID_PARAMETER);
  1197. ERR_FAIL_COND_V(p_from.y < 0 || p_from.y + p_size.y > src_height, ERR_INVALID_PARAMETER);
  1198. ERR_FAIL_COND_V(p_from.z < 0 || p_from.z + p_size.z > src_depth, ERR_INVALID_PARAMETER);
  1199. ERR_FAIL_COND_V(p_src_mipmap >= src_tex->mipmaps, ERR_INVALID_PARAMETER);
  1200. ERR_FAIL_COND_V(p_src_layer >= src_layer_count, ERR_INVALID_PARAMETER);
  1201. Texture *dst_tex = texture_owner.get_or_null(p_to_texture);
  1202. ERR_FAIL_NULL_V(dst_tex, ERR_INVALID_PARAMETER);
  1203. ERR_FAIL_COND_V_MSG(dst_tex->bound, ERR_INVALID_PARAMETER,
  1204. "Destination texture can't be copied while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to copy this texture.");
  1205. ERR_FAIL_COND_V_MSG(!(dst_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,
  1206. "Destination texture requires the `RenderingDevice.TEXTURE_USAGE_CAN_COPY_TO_BIT` to be set to be retrieved.");
  1207. uint32_t dst_layer_count = dst_tex->layers;
  1208. uint32_t dst_width, dst_height, dst_depth;
  1209. get_image_format_required_size(dst_tex->format, dst_tex->width, dst_tex->height, dst_tex->depth, p_dst_mipmap + 1, &dst_width, &dst_height, &dst_depth);
  1210. if (dst_tex->type == TEXTURE_TYPE_CUBE || dst_tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  1211. dst_layer_count *= 6;
  1212. }
  1213. ERR_FAIL_COND_V(p_to.x < 0 || p_to.x + p_size.x > dst_width, ERR_INVALID_PARAMETER);
  1214. ERR_FAIL_COND_V(p_to.y < 0 || p_to.y + p_size.y > dst_height, ERR_INVALID_PARAMETER);
  1215. ERR_FAIL_COND_V(p_to.z < 0 || p_to.z + p_size.z > dst_depth, ERR_INVALID_PARAMETER);
  1216. ERR_FAIL_COND_V(p_dst_mipmap >= dst_tex->mipmaps, ERR_INVALID_PARAMETER);
  1217. ERR_FAIL_COND_V(p_dst_layer >= dst_layer_count, ERR_INVALID_PARAMETER);
  1218. ERR_FAIL_COND_V_MSG(src_tex->read_aspect_flags != dst_tex->read_aspect_flags, ERR_INVALID_PARAMETER,
  1219. "Source and destination texture must be of the same type (color or depth).");
  1220. RDD::TextureCopyRegion copy_region;
  1221. copy_region.src_subresources.aspect = src_tex->read_aspect_flags;
  1222. copy_region.src_subresources.mipmap = p_src_mipmap;
  1223. copy_region.src_subresources.base_layer = p_src_layer;
  1224. copy_region.src_subresources.layer_count = 1;
  1225. copy_region.src_offset = p_from;
  1226. copy_region.dst_subresources.aspect = dst_tex->read_aspect_flags;
  1227. copy_region.dst_subresources.mipmap = p_dst_mipmap;
  1228. copy_region.dst_subresources.base_layer = p_dst_layer;
  1229. copy_region.dst_subresources.layer_count = 1;
  1230. copy_region.dst_offset = p_to;
  1231. copy_region.size = p_size;
  1232. // The textures must be mutable to be used in the copy operation.
  1233. bool src_made_mutable = _texture_make_mutable(src_tex, p_from_texture);
  1234. bool dst_made_mutable = _texture_make_mutable(dst_tex, p_to_texture);
  1235. if (src_made_mutable || dst_made_mutable) {
  1236. draw_graph.add_synchronization();
  1237. }
  1238. draw_graph.add_texture_copy(src_tex->driver_id, src_tex->draw_tracker, dst_tex->driver_id, dst_tex->draw_tracker, copy_region);
  1239. return OK;
  1240. }
  1241. Error RenderingDevice::texture_resolve_multisample(RID p_from_texture, RID p_to_texture) {
  1242. _THREAD_SAFE_METHOD_
  1243. Texture *src_tex = texture_owner.get_or_null(p_from_texture);
  1244. ERR_FAIL_NULL_V(src_tex, ERR_INVALID_PARAMETER);
  1245. ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,
  1246. "Source texture can't be copied while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to copy this texture.");
  1247. ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), ERR_INVALID_PARAMETER,
  1248. "Source texture requires the `RenderingDevice.TEXTURE_USAGE_CAN_COPY_FROM_BIT` to be set to be retrieved.");
  1249. ERR_FAIL_COND_V_MSG(src_tex->type != TEXTURE_TYPE_2D, ERR_INVALID_PARAMETER, "Source texture must be 2D (or a slice of a 3D/Cube texture)");
  1250. ERR_FAIL_COND_V_MSG(src_tex->samples == TEXTURE_SAMPLES_1, ERR_INVALID_PARAMETER, "Source texture must be multisampled.");
  1251. Texture *dst_tex = texture_owner.get_or_null(p_to_texture);
  1252. ERR_FAIL_NULL_V(dst_tex, ERR_INVALID_PARAMETER);
  1253. ERR_FAIL_COND_V_MSG(dst_tex->bound, ERR_INVALID_PARAMETER,
  1254. "Destination texture can't be copied while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to copy this texture.");
  1255. ERR_FAIL_COND_V_MSG(!(dst_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,
  1256. "Destination texture requires the `RenderingDevice.TEXTURE_USAGE_CAN_COPY_TO_BIT` to be set to be retrieved.");
  1257. ERR_FAIL_COND_V_MSG(dst_tex->type != TEXTURE_TYPE_2D, ERR_INVALID_PARAMETER, "Destination texture must be 2D (or a slice of a 3D/Cube texture).");
  1258. ERR_FAIL_COND_V_MSG(dst_tex->samples != TEXTURE_SAMPLES_1, ERR_INVALID_PARAMETER, "Destination texture must not be multisampled.");
  1259. ERR_FAIL_COND_V_MSG(src_tex->format != dst_tex->format, ERR_INVALID_PARAMETER, "Source and Destination textures must be the same format.");
  1260. ERR_FAIL_COND_V_MSG(src_tex->width != dst_tex->width && src_tex->height != dst_tex->height && src_tex->depth != dst_tex->depth, ERR_INVALID_PARAMETER, "Source and Destination textures must have the same dimensions.");
  1261. ERR_FAIL_COND_V_MSG(src_tex->read_aspect_flags != dst_tex->read_aspect_flags, ERR_INVALID_PARAMETER,
  1262. "Source and destination texture must be of the same type (color or depth).");
  1263. // The textures must be mutable to be used in the resolve operation.
  1264. bool src_made_mutable = _texture_make_mutable(src_tex, p_from_texture);
  1265. bool dst_made_mutable = _texture_make_mutable(dst_tex, p_to_texture);
  1266. if (src_made_mutable || dst_made_mutable) {
  1267. draw_graph.add_synchronization();
  1268. }
  1269. draw_graph.add_texture_resolve(src_tex->driver_id, src_tex->draw_tracker, dst_tex->driver_id, dst_tex->draw_tracker, src_tex->base_layer, src_tex->base_mipmap, dst_tex->base_layer, dst_tex->base_mipmap);
  1270. return OK;
  1271. }
  1272. Error RenderingDevice::texture_clear(RID p_texture, const Color &p_color, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers) {
  1273. _THREAD_SAFE_METHOD_
  1274. Texture *src_tex = texture_owner.get_or_null(p_texture);
  1275. ERR_FAIL_NULL_V(src_tex, ERR_INVALID_PARAMETER);
  1276. ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,
  1277. "Source texture can't be cleared while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to clear this texture.");
  1278. ERR_FAIL_COND_V(p_layers == 0, ERR_INVALID_PARAMETER);
  1279. ERR_FAIL_COND_V(p_mipmaps == 0, ERR_INVALID_PARAMETER);
  1280. ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,
  1281. "Source texture requires the `RenderingDevice.TEXTURE_USAGE_CAN_COPY_TO_BIT` to be set to be cleared.");
  1282. uint32_t src_layer_count = src_tex->layers;
  1283. if (src_tex->type == TEXTURE_TYPE_CUBE || src_tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  1284. src_layer_count *= 6;
  1285. }
  1286. ERR_FAIL_COND_V(p_base_mipmap + p_mipmaps > src_tex->mipmaps, ERR_INVALID_PARAMETER);
  1287. ERR_FAIL_COND_V(p_base_layer + p_layers > src_layer_count, ERR_INVALID_PARAMETER);
  1288. RDD::TextureSubresourceRange range;
  1289. range.aspect = src_tex->read_aspect_flags;
  1290. range.base_mipmap = src_tex->base_mipmap + p_base_mipmap;
  1291. range.mipmap_count = p_mipmaps;
  1292. range.base_layer = src_tex->base_layer + p_base_layer;
  1293. range.layer_count = p_layers;
  1294. if (_texture_make_mutable(src_tex, p_texture)) {
  1295. // The texture must be mutable to be used as a clear destination.
  1296. draw_graph.add_synchronization();
  1297. }
  1298. draw_graph.add_texture_clear(src_tex->driver_id, src_tex->draw_tracker, p_color, range);
  1299. return OK;
  1300. }
  1301. bool RenderingDevice::texture_is_format_supported_for_usage(DataFormat p_format, BitField<RenderingDevice::TextureUsageBits> p_usage) const {
  1302. ERR_FAIL_INDEX_V(p_format, DATA_FORMAT_MAX, false);
  1303. _THREAD_SAFE_METHOD_
  1304. bool cpu_readable = (p_usage & RDD::TEXTURE_USAGE_CPU_READ_BIT);
  1305. BitField<TextureUsageBits> supported = driver->texture_get_usages_supported_by_format(p_format, cpu_readable);
  1306. bool any_unsupported = (((int64_t)supported) | ((int64_t)p_usage)) != ((int64_t)supported);
  1307. return !any_unsupported;
  1308. }
  1309. /*********************/
  1310. /**** FRAMEBUFFER ****/
  1311. /*********************/
  1312. static RDD::AttachmentLoadOp initial_action_to_load_op(RenderingDevice::InitialAction p_action) {
  1313. switch (p_action) {
  1314. case RenderingDevice::INITIAL_ACTION_LOAD:
  1315. return RDD::ATTACHMENT_LOAD_OP_LOAD;
  1316. case RenderingDevice::INITIAL_ACTION_CLEAR:
  1317. return RDD::ATTACHMENT_LOAD_OP_CLEAR;
  1318. case RenderingDevice::INITIAL_ACTION_DISCARD:
  1319. return RDD::ATTACHMENT_LOAD_OP_DONT_CARE;
  1320. default:
  1321. ERR_FAIL_V_MSG(RDD::ATTACHMENT_LOAD_OP_DONT_CARE, "Invalid initial action value (" + itos(p_action) + ")");
  1322. }
  1323. }
  1324. static RDD::AttachmentStoreOp final_action_to_store_op(RenderingDevice::FinalAction p_action) {
  1325. switch (p_action) {
  1326. case RenderingDevice::FINAL_ACTION_STORE:
  1327. return RDD::ATTACHMENT_STORE_OP_STORE;
  1328. case RenderingDevice::FINAL_ACTION_DISCARD:
  1329. return RDD::ATTACHMENT_STORE_OP_DONT_CARE;
  1330. default:
  1331. ERR_FAIL_V_MSG(RDD::ATTACHMENT_STORE_OP_DONT_CARE, "Invalid final action value (" + itos(p_action) + ")");
  1332. }
  1333. }
  1334. RDD::RenderPassID RenderingDevice::_render_pass_create(const Vector<AttachmentFormat> &p_attachments, const Vector<FramebufferPass> &p_passes, InitialAction p_initial_action, FinalAction p_final_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, uint32_t p_view_count, Vector<TextureSamples> *r_samples) {
  1335. // NOTE:
  1336. // Before the refactor to RenderingDevice-RenderingDeviceDriver, there was commented out code to
  1337. // specify dependencies to external subpasses. Since it had been unused for a long timel it wasn't ported
  1338. // to the new architecture.
  1339. LocalVector<int32_t> attachment_last_pass;
  1340. attachment_last_pass.resize(p_attachments.size());
  1341. if (p_view_count > 1) {
  1342. const RDD::MultiviewCapabilities &capabilities = driver->get_multiview_capabilities();
  1343. // This only works with multiview!
  1344. ERR_FAIL_COND_V_MSG(!capabilities.is_supported, RDD::RenderPassID(), "Multiview not supported");
  1345. // Make sure we limit this to the number of views we support.
  1346. ERR_FAIL_COND_V_MSG(p_view_count > capabilities.max_view_count, RDD::RenderPassID(), "Hardware does not support requested number of views for Multiview render pass");
  1347. }
  1348. LocalVector<RDD::Attachment> attachments;
  1349. LocalVector<int> attachment_remap;
  1350. for (int i = 0; i < p_attachments.size(); i++) {
  1351. if (p_attachments[i].usage_flags == AttachmentFormat::UNUSED_ATTACHMENT) {
  1352. attachment_remap.push_back(RDD::AttachmentReference::UNUSED);
  1353. continue;
  1354. }
  1355. ERR_FAIL_INDEX_V(p_attachments[i].format, DATA_FORMAT_MAX, RDD::RenderPassID());
  1356. ERR_FAIL_INDEX_V(p_attachments[i].samples, TEXTURE_SAMPLES_MAX, RDD::RenderPassID());
  1357. ERR_FAIL_COND_V_MSG(!(p_attachments[i].usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT | TEXTURE_USAGE_VRS_ATTACHMENT_BIT)),
  1358. RDD::RenderPassID(), "Texture format for index (" + itos(i) + ") requires an attachment (color, depth-stencil, input or VRS) bit set.");
  1359. RDD::Attachment description;
  1360. description.format = p_attachments[i].format;
  1361. description.samples = p_attachments[i].samples;
  1362. // We can setup a framebuffer where we write to our VRS texture to set it up.
  1363. // We make the assumption here that if our texture is actually used as our VRS attachment.
  1364. // It is used as such for each subpass. This is fairly certain seeing the restrictions on subpasses.
  1365. bool is_vrs = (p_attachments[i].usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) && i == p_passes[0].vrs_attachment;
  1366. if (is_vrs) {
  1367. description.load_op = RDD::ATTACHMENT_LOAD_OP_LOAD;
  1368. description.store_op = RDD::ATTACHMENT_STORE_OP_DONT_CARE;
  1369. description.stencil_load_op = RDD::ATTACHMENT_LOAD_OP_LOAD;
  1370. description.stencil_store_op = RDD::ATTACHMENT_STORE_OP_DONT_CARE;
  1371. description.initial_layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  1372. description.final_layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  1373. } else {
  1374. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  1375. description.load_op = initial_action_to_load_op(p_initial_action);
  1376. description.store_op = final_action_to_store_op(p_final_action);
  1377. description.stencil_load_op = RDD::ATTACHMENT_LOAD_OP_DONT_CARE;
  1378. description.stencil_store_op = RDD::ATTACHMENT_STORE_OP_DONT_CARE;
  1379. description.initial_layout = RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1380. description.final_layout = RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1381. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1382. description.load_op = initial_action_to_load_op(p_initial_depth_action);
  1383. description.store_op = final_action_to_store_op(p_final_depth_action);
  1384. description.stencil_load_op = initial_action_to_load_op(p_initial_depth_action);
  1385. description.stencil_store_op = final_action_to_store_op(p_final_depth_action);
  1386. description.initial_layout = RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  1387. description.final_layout = RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  1388. } else {
  1389. description.load_op = RDD::ATTACHMENT_LOAD_OP_DONT_CARE;
  1390. description.store_op = RDD::ATTACHMENT_STORE_OP_DONT_CARE;
  1391. description.stencil_load_op = RDD::ATTACHMENT_LOAD_OP_DONT_CARE;
  1392. description.stencil_store_op = RDD::ATTACHMENT_STORE_OP_DONT_CARE;
  1393. description.initial_layout = RDD::TEXTURE_LAYOUT_UNDEFINED;
  1394. description.final_layout = RDD::TEXTURE_LAYOUT_UNDEFINED;
  1395. }
  1396. }
  1397. attachment_last_pass[i] = -1;
  1398. attachment_remap.push_back(attachments.size());
  1399. attachments.push_back(description);
  1400. }
  1401. LocalVector<RDD::Subpass> subpasses;
  1402. subpasses.resize(p_passes.size());
  1403. LocalVector<RDD::SubpassDependency> subpass_dependencies;
  1404. for (int i = 0; i < p_passes.size(); i++) {
  1405. const FramebufferPass *pass = &p_passes[i];
  1406. RDD::Subpass &subpass = subpasses[i];
  1407. TextureSamples texture_samples = TEXTURE_SAMPLES_1;
  1408. bool is_multisample_first = true;
  1409. for (int j = 0; j < pass->color_attachments.size(); j++) {
  1410. int32_t attachment = pass->color_attachments[j];
  1411. RDD::AttachmentReference reference;
  1412. if (attachment == ATTACHMENT_UNUSED) {
  1413. reference.attachment = RDD::AttachmentReference::UNUSED;
  1414. reference.layout = RDD::TEXTURE_LAYOUT_UNDEFINED;
  1415. } else {
  1416. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), color attachment (" + itos(j) + ").");
  1417. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not usable as color attachment.");
  1418. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  1419. if (is_multisample_first) {
  1420. texture_samples = p_attachments[attachment].samples;
  1421. is_multisample_first = false;
  1422. } else {
  1423. ERR_FAIL_COND_V_MSG(texture_samples != p_attachments[attachment].samples, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), if an attachment is marked as multisample, all of them should be multisample and use the same number of samples.");
  1424. }
  1425. reference.attachment = attachment_remap[attachment];
  1426. reference.layout = RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1427. attachment_last_pass[attachment] = i;
  1428. }
  1429. reference.aspect = RDD::TEXTURE_ASPECT_COLOR_BIT;
  1430. subpass.color_references.push_back(reference);
  1431. }
  1432. for (int j = 0; j < pass->input_attachments.size(); j++) {
  1433. int32_t attachment = pass->input_attachments[j];
  1434. RDD::AttachmentReference reference;
  1435. if (attachment == ATTACHMENT_UNUSED) {
  1436. reference.attachment = RDD::AttachmentReference::UNUSED;
  1437. reference.layout = RDD::TEXTURE_LAYOUT_UNDEFINED;
  1438. } else {
  1439. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), input attachment (" + itos(j) + ").");
  1440. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it isn't marked as an input texture.");
  1441. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  1442. reference.attachment = attachment_remap[attachment];
  1443. reference.layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  1444. attachment_last_pass[attachment] = i;
  1445. }
  1446. reference.aspect = RDD::TEXTURE_ASPECT_COLOR_BIT;
  1447. subpass.input_references.push_back(reference);
  1448. }
  1449. if (pass->resolve_attachments.size() > 0) {
  1450. ERR_FAIL_COND_V_MSG(pass->resolve_attachments.size() != pass->color_attachments.size(), RDD::RenderPassID(), "The amount of resolve attachments (" + itos(pass->resolve_attachments.size()) + ") must match the number of color attachments (" + itos(pass->color_attachments.size()) + ").");
  1451. ERR_FAIL_COND_V_MSG(texture_samples == TEXTURE_SAMPLES_1, RDD::RenderPassID(), "Resolve attachments specified, but color attachments are not multisample.");
  1452. }
  1453. for (int j = 0; j < pass->resolve_attachments.size(); j++) {
  1454. int32_t attachment = pass->resolve_attachments[j];
  1455. RDD::AttachmentReference reference;
  1456. if (attachment == ATTACHMENT_UNUSED) {
  1457. reference.attachment = RDD::AttachmentReference::UNUSED;
  1458. reference.layout = RDD::TEXTURE_LAYOUT_UNDEFINED;
  1459. } else {
  1460. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + ").");
  1461. ERR_FAIL_COND_V_MSG(pass->color_attachments[j] == ATTACHMENT_UNUSED, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + "), the respective color attachment is marked as unused.");
  1462. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment, it isn't marked as a color texture.");
  1463. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  1464. bool multisample = p_attachments[attachment].samples > TEXTURE_SAMPLES_1;
  1465. ERR_FAIL_COND_V_MSG(multisample, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachments can't be multisample.");
  1466. reference.attachment = attachment_remap[attachment];
  1467. reference.layout = RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
  1468. attachment_last_pass[attachment] = i;
  1469. }
  1470. reference.aspect = RDD::TEXTURE_ASPECT_COLOR_BIT;
  1471. subpass.resolve_references.push_back(reference);
  1472. }
  1473. if (pass->depth_attachment != ATTACHMENT_UNUSED) {
  1474. int32_t attachment = pass->depth_attachment;
  1475. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), depth attachment.");
  1476. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not a depth attachment.");
  1477. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  1478. subpass.depth_stencil_reference.attachment = attachment_remap[attachment];
  1479. subpass.depth_stencil_reference.layout = RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  1480. attachment_last_pass[attachment] = i;
  1481. if (is_multisample_first) {
  1482. texture_samples = p_attachments[attachment].samples;
  1483. is_multisample_first = false;
  1484. } else {
  1485. ERR_FAIL_COND_V_MSG(texture_samples != p_attachments[attachment].samples, RDD::RenderPassID(), "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), if an attachment is marked as multisample, all of them should be multisample and use the same number of samples including the depth.");
  1486. }
  1487. } else {
  1488. subpass.depth_stencil_reference.attachment = RDD::AttachmentReference::UNUSED;
  1489. subpass.depth_stencil_reference.layout = RDD::TEXTURE_LAYOUT_UNDEFINED;
  1490. }
  1491. if (pass->vrs_attachment != ATTACHMENT_UNUSED) {
  1492. int32_t attachment = pass->vrs_attachment;
  1493. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer VRS format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), VRS attachment.");
  1494. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer VRS format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as VRS, but it's not a VRS attachment.");
  1495. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer VRS attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  1496. subpass.vrs_reference.attachment = attachment_remap[attachment];
  1497. subpass.vrs_reference.layout = RDD::TEXTURE_LAYOUT_VRS_ATTACHMENT_OPTIMAL;
  1498. attachment_last_pass[attachment] = i;
  1499. }
  1500. for (int j = 0; j < pass->preserve_attachments.size(); j++) {
  1501. int32_t attachment = pass->preserve_attachments[j];
  1502. ERR_FAIL_COND_V_MSG(attachment == ATTACHMENT_UNUSED, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + "). Preserve attachments can't be unused.");
  1503. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + ").");
  1504. if (attachment_last_pass[attachment] != i) {
  1505. // Preserve can still be used to keep depth or color from being discarded after use.
  1506. attachment_last_pass[attachment] = i;
  1507. subpasses[i].preserve_attachments.push_back(attachment);
  1508. }
  1509. }
  1510. if (r_samples) {
  1511. r_samples->push_back(texture_samples);
  1512. }
  1513. if (i > 0) {
  1514. RDD::SubpassDependency dependency;
  1515. dependency.src_subpass = i - 1;
  1516. dependency.dst_subpass = i;
  1517. dependency.src_stages = (RDD::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | RDD::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | RDD::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT);
  1518. dependency.dst_stages = (RDD::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | RDD::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | RDD::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
  1519. dependency.src_access = (RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT);
  1520. dependency.dst_access = (RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_READ_BIT | RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | RDD::BARRIER_ACCESS_INPUT_ATTACHMENT_READ_BIT);
  1521. subpass_dependencies.push_back(dependency);
  1522. }
  1523. }
  1524. RDD::RenderPassID render_pass = driver->render_pass_create(attachments, subpasses, subpass_dependencies, p_view_count);
  1525. ERR_FAIL_COND_V(!render_pass, RDD::RenderPassID());
  1526. return render_pass;
  1527. }
  1528. RenderingDevice::FramebufferFormatID RenderingDevice::framebuffer_format_create(const Vector<AttachmentFormat> &p_format, uint32_t p_view_count) {
  1529. FramebufferPass pass;
  1530. for (int i = 0; i < p_format.size(); i++) {
  1531. if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1532. pass.depth_attachment = i;
  1533. } else {
  1534. pass.color_attachments.push_back(i);
  1535. }
  1536. }
  1537. Vector<FramebufferPass> passes;
  1538. passes.push_back(pass);
  1539. return framebuffer_format_create_multipass(p_format, passes, p_view_count);
  1540. }
  1541. RenderingDevice::FramebufferFormatID RenderingDevice::framebuffer_format_create_multipass(const Vector<AttachmentFormat> &p_attachments, const Vector<FramebufferPass> &p_passes, uint32_t p_view_count) {
  1542. _THREAD_SAFE_METHOD_
  1543. FramebufferFormatKey key;
  1544. key.attachments = p_attachments;
  1545. key.passes = p_passes;
  1546. key.view_count = p_view_count;
  1547. const RBMap<FramebufferFormatKey, FramebufferFormatID>::Element *E = framebuffer_format_cache.find(key);
  1548. if (E) {
  1549. // Exists, return.
  1550. return E->get();
  1551. }
  1552. Vector<TextureSamples> samples;
  1553. RDD::RenderPassID render_pass = _render_pass_create(p_attachments, p_passes, INITIAL_ACTION_CLEAR, FINAL_ACTION_STORE, INITIAL_ACTION_CLEAR, FINAL_ACTION_STORE, p_view_count, &samples); // Actions don't matter for this use case.
  1554. if (!render_pass) { // Was likely invalid.
  1555. return INVALID_ID;
  1556. }
  1557. FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT));
  1558. E = framebuffer_format_cache.insert(key, id);
  1559. FramebufferFormat fb_format;
  1560. fb_format.E = E;
  1561. fb_format.render_pass = render_pass;
  1562. fb_format.pass_samples = samples;
  1563. fb_format.view_count = p_view_count;
  1564. framebuffer_formats[id] = fb_format;
  1565. return id;
  1566. }
  1567. RenderingDevice::FramebufferFormatID RenderingDevice::framebuffer_format_create_empty(TextureSamples p_samples) {
  1568. FramebufferFormatKey key;
  1569. key.passes.push_back(FramebufferPass());
  1570. const RBMap<FramebufferFormatKey, FramebufferFormatID>::Element *E = framebuffer_format_cache.find(key);
  1571. if (E) {
  1572. // Exists, return.
  1573. return E->get();
  1574. }
  1575. LocalVector<RDD::Subpass> subpass;
  1576. subpass.resize(1);
  1577. RDD::RenderPassID render_pass = driver->render_pass_create({}, subpass, {}, 1);
  1578. ERR_FAIL_COND_V(!render_pass, FramebufferFormatID());
  1579. FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT));
  1580. E = framebuffer_format_cache.insert(key, id);
  1581. FramebufferFormat fb_format;
  1582. fb_format.E = E;
  1583. fb_format.render_pass = render_pass;
  1584. fb_format.pass_samples.push_back(p_samples);
  1585. framebuffer_formats[id] = fb_format;
  1586. return id;
  1587. }
  1588. RenderingDevice::TextureSamples RenderingDevice::framebuffer_format_get_texture_samples(FramebufferFormatID p_format, uint32_t p_pass) {
  1589. HashMap<FramebufferFormatID, FramebufferFormat>::Iterator E = framebuffer_formats.find(p_format);
  1590. ERR_FAIL_COND_V(!E, TEXTURE_SAMPLES_1);
  1591. ERR_FAIL_COND_V(p_pass >= uint32_t(E->value.pass_samples.size()), TEXTURE_SAMPLES_1);
  1592. return E->value.pass_samples[p_pass];
  1593. }
  1594. RID RenderingDevice::framebuffer_create_empty(const Size2i &p_size, TextureSamples p_samples, FramebufferFormatID p_format_check) {
  1595. _THREAD_SAFE_METHOD_
  1596. Framebuffer framebuffer;
  1597. framebuffer.format_id = framebuffer_format_create_empty(p_samples);
  1598. ERR_FAIL_COND_V(p_format_check != INVALID_FORMAT_ID && framebuffer.format_id != p_format_check, RID());
  1599. framebuffer.size = p_size;
  1600. framebuffer.view_count = 1;
  1601. RID id = framebuffer_owner.make_rid(framebuffer);
  1602. #ifdef DEV_ENABLED
  1603. set_resource_name(id, "RID:" + itos(id.get_id()));
  1604. #endif
  1605. return id;
  1606. }
  1607. RID RenderingDevice::framebuffer_create(const Vector<RID> &p_texture_attachments, FramebufferFormatID p_format_check, uint32_t p_view_count) {
  1608. _THREAD_SAFE_METHOD_
  1609. FramebufferPass pass;
  1610. for (int i = 0; i < p_texture_attachments.size(); i++) {
  1611. Texture *texture = texture_owner.get_or_null(p_texture_attachments[i]);
  1612. ERR_FAIL_COND_V_MSG(texture && texture->layers != p_view_count, RID(), "Layers of our texture doesn't match view count for this framebuffer");
  1613. if (texture && texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1614. pass.depth_attachment = i;
  1615. } else if (texture && texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) {
  1616. pass.vrs_attachment = i;
  1617. } else {
  1618. if (texture && texture->is_resolve_buffer) {
  1619. pass.resolve_attachments.push_back(i);
  1620. } else {
  1621. pass.color_attachments.push_back(texture ? i : ATTACHMENT_UNUSED);
  1622. }
  1623. }
  1624. }
  1625. Vector<FramebufferPass> passes;
  1626. passes.push_back(pass);
  1627. return framebuffer_create_multipass(p_texture_attachments, passes, p_format_check, p_view_count);
  1628. }
  1629. RID RenderingDevice::framebuffer_create_multipass(const Vector<RID> &p_texture_attachments, const Vector<FramebufferPass> &p_passes, FramebufferFormatID p_format_check, uint32_t p_view_count) {
  1630. _THREAD_SAFE_METHOD_
  1631. Vector<AttachmentFormat> attachments;
  1632. attachments.resize(p_texture_attachments.size());
  1633. Size2i size;
  1634. bool size_set = false;
  1635. for (int i = 0; i < p_texture_attachments.size(); i++) {
  1636. AttachmentFormat af;
  1637. Texture *texture = texture_owner.get_or_null(p_texture_attachments[i]);
  1638. if (!texture) {
  1639. af.usage_flags = AttachmentFormat::UNUSED_ATTACHMENT;
  1640. } else {
  1641. ERR_FAIL_COND_V_MSG(texture->layers != p_view_count, RID(), "Layers of our texture doesn't match view count for this framebuffer");
  1642. if (!size_set) {
  1643. size.width = texture->width;
  1644. size.height = texture->height;
  1645. size_set = true;
  1646. } else if (texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) {
  1647. // If this is not the first attachment we assume this is used as the VRS attachment.
  1648. // In this case this texture will be 1/16th the size of the color attachment.
  1649. // So we skip the size check.
  1650. } else {
  1651. ERR_FAIL_COND_V_MSG((uint32_t)size.width != texture->width || (uint32_t)size.height != texture->height, RID(),
  1652. "All textures in a framebuffer should be the same size.");
  1653. }
  1654. af.format = texture->format;
  1655. af.samples = texture->samples;
  1656. af.usage_flags = texture->usage_flags;
  1657. }
  1658. attachments.write[i] = af;
  1659. }
  1660. ERR_FAIL_COND_V_MSG(!size_set, RID(), "All attachments unused.");
  1661. FramebufferFormatID format_id = framebuffer_format_create_multipass(attachments, p_passes, p_view_count);
  1662. if (format_id == INVALID_ID) {
  1663. return RID();
  1664. }
  1665. ERR_FAIL_COND_V_MSG(p_format_check != INVALID_ID && format_id != p_format_check, RID(),
  1666. "The format used to check this framebuffer differs from the intended framebuffer format.");
  1667. Framebuffer framebuffer;
  1668. framebuffer.format_id = format_id;
  1669. framebuffer.texture_ids = p_texture_attachments;
  1670. framebuffer.size = size;
  1671. framebuffer.view_count = p_view_count;
  1672. RID id = framebuffer_owner.make_rid(framebuffer);
  1673. #ifdef DEV_ENABLED
  1674. set_resource_name(id, "RID:" + itos(id.get_id()));
  1675. #endif
  1676. for (int i = 0; i < p_texture_attachments.size(); i++) {
  1677. if (p_texture_attachments[i].is_valid()) {
  1678. _add_dependency(id, p_texture_attachments[i]);
  1679. }
  1680. }
  1681. return id;
  1682. }
  1683. RenderingDevice::FramebufferFormatID RenderingDevice::framebuffer_get_format(RID p_framebuffer) {
  1684. _THREAD_SAFE_METHOD_
  1685. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  1686. ERR_FAIL_NULL_V(framebuffer, INVALID_ID);
  1687. return framebuffer->format_id;
  1688. }
  1689. bool RenderingDevice::framebuffer_is_valid(RID p_framebuffer) const {
  1690. _THREAD_SAFE_METHOD_
  1691. return framebuffer_owner.owns(p_framebuffer);
  1692. }
  1693. void RenderingDevice::framebuffer_set_invalidation_callback(RID p_framebuffer, InvalidationCallback p_callback, void *p_userdata) {
  1694. _THREAD_SAFE_METHOD_
  1695. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  1696. ERR_FAIL_NULL(framebuffer);
  1697. framebuffer->invalidated_callback = p_callback;
  1698. framebuffer->invalidated_callback_userdata = p_userdata;
  1699. }
  1700. /*****************/
  1701. /**** SAMPLER ****/
  1702. /*****************/
  1703. RID RenderingDevice::sampler_create(const SamplerState &p_state) {
  1704. _THREAD_SAFE_METHOD_
  1705. ERR_FAIL_INDEX_V(p_state.repeat_u, SAMPLER_REPEAT_MODE_MAX, RID());
  1706. ERR_FAIL_INDEX_V(p_state.repeat_v, SAMPLER_REPEAT_MODE_MAX, RID());
  1707. ERR_FAIL_INDEX_V(p_state.repeat_w, SAMPLER_REPEAT_MODE_MAX, RID());
  1708. ERR_FAIL_INDEX_V(p_state.compare_op, COMPARE_OP_MAX, RID());
  1709. ERR_FAIL_INDEX_V(p_state.border_color, SAMPLER_BORDER_COLOR_MAX, RID());
  1710. RDD::SamplerID sampler = driver->sampler_create(p_state);
  1711. ERR_FAIL_COND_V(!sampler, RID());
  1712. RID id = sampler_owner.make_rid(sampler);
  1713. #ifdef DEV_ENABLED
  1714. set_resource_name(id, "RID:" + itos(id.get_id()));
  1715. #endif
  1716. return id;
  1717. }
  1718. bool RenderingDevice::sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_sampler_filter) const {
  1719. ERR_FAIL_INDEX_V(p_format, DATA_FORMAT_MAX, false);
  1720. _THREAD_SAFE_METHOD_
  1721. return driver->sampler_is_format_supported_for_filter(p_format, p_sampler_filter);
  1722. }
  1723. /***********************/
  1724. /**** VERTEX BUFFER ****/
  1725. /***********************/
  1726. RID RenderingDevice::vertex_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data, bool p_use_as_storage) {
  1727. _THREAD_SAFE_METHOD_
  1728. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  1729. Buffer buffer;
  1730. buffer.size = p_size_bytes;
  1731. buffer.usage = RDD::BUFFER_USAGE_TRANSFER_FROM_BIT | RDD::BUFFER_USAGE_TRANSFER_TO_BIT | RDD::BUFFER_USAGE_VERTEX_BIT;
  1732. if (p_use_as_storage) {
  1733. buffer.usage.set_flag(RDD::BUFFER_USAGE_STORAGE_BIT);
  1734. }
  1735. buffer.driver_id = driver->buffer_create(buffer.size, buffer.usage, RDD::MEMORY_ALLOCATION_TYPE_GPU);
  1736. ERR_FAIL_COND_V(!buffer.driver_id, RID());
  1737. // Vertex buffers are assumed to be immutable unless they don't have initial data or they've been marked for storage explicitly.
  1738. if (p_data.is_empty() || p_use_as_storage) {
  1739. buffer.draw_tracker = RDG::resource_tracker_create();
  1740. buffer.draw_tracker->buffer_driver_id = buffer.driver_id;
  1741. }
  1742. if (p_data.size()) {
  1743. _buffer_update(&buffer, RID(), 0, p_data.ptr(), p_data.size());
  1744. }
  1745. buffer_memory += buffer.size;
  1746. RID id = vertex_buffer_owner.make_rid(buffer);
  1747. #ifdef DEV_ENABLED
  1748. set_resource_name(id, "RID:" + itos(id.get_id()));
  1749. #endif
  1750. return id;
  1751. }
  1752. // Internally reference counted, this ID is warranted to be unique for the same description, but needs to be freed as many times as it was allocated.
  1753. RenderingDevice::VertexFormatID RenderingDevice::vertex_format_create(const Vector<VertexAttribute> &p_vertex_descriptions) {
  1754. _THREAD_SAFE_METHOD_
  1755. VertexDescriptionKey key;
  1756. key.vertex_formats = p_vertex_descriptions;
  1757. VertexFormatID *idptr = vertex_format_cache.getptr(key);
  1758. if (idptr) {
  1759. return *idptr;
  1760. }
  1761. HashSet<int> used_locations;
  1762. for (int i = 0; i < p_vertex_descriptions.size(); i++) {
  1763. ERR_CONTINUE(p_vertex_descriptions[i].format >= DATA_FORMAT_MAX);
  1764. ERR_FAIL_COND_V(used_locations.has(p_vertex_descriptions[i].location), INVALID_ID);
  1765. ERR_FAIL_COND_V_MSG(get_format_vertex_size(p_vertex_descriptions[i].format) == 0, INVALID_ID,
  1766. "Data format for attachment (" + itos(i) + "), '" + FORMAT_NAMES[p_vertex_descriptions[i].format] + "', is not valid for a vertex array.");
  1767. used_locations.insert(p_vertex_descriptions[i].location);
  1768. }
  1769. RDD::VertexFormatID driver_id = driver->vertex_format_create(p_vertex_descriptions);
  1770. ERR_FAIL_COND_V(!driver_id, 0);
  1771. VertexFormatID id = (vertex_format_cache.size() | ((int64_t)ID_TYPE_VERTEX_FORMAT << ID_BASE_SHIFT));
  1772. vertex_format_cache[key] = id;
  1773. vertex_formats[id].vertex_formats = p_vertex_descriptions;
  1774. vertex_formats[id].driver_id = driver_id;
  1775. return id;
  1776. }
  1777. RID RenderingDevice::vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector<RID> &p_src_buffers, const Vector<uint64_t> &p_offsets) {
  1778. _THREAD_SAFE_METHOD_
  1779. ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID());
  1780. const VertexDescriptionCache &vd = vertex_formats[p_vertex_format];
  1781. ERR_FAIL_COND_V(vd.vertex_formats.size() != p_src_buffers.size(), RID());
  1782. for (int i = 0; i < p_src_buffers.size(); i++) {
  1783. ERR_FAIL_COND_V(!vertex_buffer_owner.owns(p_src_buffers[i]), RID());
  1784. }
  1785. VertexArray vertex_array;
  1786. if (p_offsets.is_empty()) {
  1787. vertex_array.offsets.resize_zeroed(p_src_buffers.size());
  1788. } else {
  1789. ERR_FAIL_COND_V(p_offsets.size() != p_src_buffers.size(), RID());
  1790. vertex_array.offsets = p_offsets;
  1791. }
  1792. vertex_array.vertex_count = p_vertex_count;
  1793. vertex_array.description = p_vertex_format;
  1794. vertex_array.max_instances_allowed = 0xFFFFFFFF; // By default as many as you want.
  1795. for (int i = 0; i < p_src_buffers.size(); i++) {
  1796. Buffer *buffer = vertex_buffer_owner.get_or_null(p_src_buffers[i]);
  1797. // Validate with buffer.
  1798. {
  1799. const VertexAttribute &atf = vd.vertex_formats[i];
  1800. uint32_t element_size = get_format_vertex_size(atf.format);
  1801. ERR_FAIL_COND_V(element_size == 0, RID()); // Should never happens since this was prevalidated.
  1802. if (atf.frequency == VERTEX_FREQUENCY_VERTEX) {
  1803. // Validate size for regular drawing.
  1804. uint64_t total_size = uint64_t(atf.stride) * (p_vertex_count - 1) + atf.offset + element_size;
  1805. ERR_FAIL_COND_V_MSG(total_size > buffer->size, RID(),
  1806. "Attachment (" + itos(i) + ") will read past the end of the buffer.");
  1807. } else {
  1808. // Validate size for instances drawing.
  1809. uint64_t available = buffer->size - atf.offset;
  1810. ERR_FAIL_COND_V_MSG(available < element_size, RID(),
  1811. "Attachment (" + itos(i) + ") uses instancing, but it's just too small.");
  1812. uint32_t instances_allowed = available / atf.stride;
  1813. vertex_array.max_instances_allowed = MIN(instances_allowed, vertex_array.max_instances_allowed);
  1814. }
  1815. }
  1816. vertex_array.buffers.push_back(buffer->driver_id);
  1817. if (buffer->draw_tracker != nullptr) {
  1818. vertex_array.draw_trackers.push_back(buffer->draw_tracker);
  1819. } else {
  1820. vertex_array.untracked_buffers.insert(p_src_buffers[i]);
  1821. }
  1822. }
  1823. RID id = vertex_array_owner.make_rid(vertex_array);
  1824. for (int i = 0; i < p_src_buffers.size(); i++) {
  1825. _add_dependency(id, p_src_buffers[i]);
  1826. }
  1827. return id;
  1828. }
  1829. RID RenderingDevice::index_buffer_create(uint32_t p_index_count, IndexBufferFormat p_format, const Vector<uint8_t> &p_data, bool p_use_restart_indices) {
  1830. _THREAD_SAFE_METHOD_
  1831. ERR_FAIL_COND_V(p_index_count == 0, RID());
  1832. IndexBuffer index_buffer;
  1833. index_buffer.format = p_format;
  1834. index_buffer.supports_restart_indices = p_use_restart_indices;
  1835. index_buffer.index_count = p_index_count;
  1836. uint32_t size_bytes = p_index_count * ((p_format == INDEX_BUFFER_FORMAT_UINT16) ? 2 : 4);
  1837. #ifdef DEBUG_ENABLED
  1838. if (p_data.size()) {
  1839. index_buffer.max_index = 0;
  1840. ERR_FAIL_COND_V_MSG((uint32_t)p_data.size() != size_bytes, RID(),
  1841. "Default index buffer initializer array size (" + itos(p_data.size()) + ") does not match format required size (" + itos(size_bytes) + ").");
  1842. const uint8_t *r = p_data.ptr();
  1843. if (p_format == INDEX_BUFFER_FORMAT_UINT16) {
  1844. const uint16_t *index16 = (const uint16_t *)r;
  1845. for (uint32_t i = 0; i < p_index_count; i++) {
  1846. if (p_use_restart_indices && index16[i] == 0xFFFF) {
  1847. continue; // Restart index, ignore.
  1848. }
  1849. index_buffer.max_index = MAX(index16[i], index_buffer.max_index);
  1850. }
  1851. } else {
  1852. const uint32_t *index32 = (const uint32_t *)r;
  1853. for (uint32_t i = 0; i < p_index_count; i++) {
  1854. if (p_use_restart_indices && index32[i] == 0xFFFFFFFF) {
  1855. continue; // Restart index, ignore.
  1856. }
  1857. index_buffer.max_index = MAX(index32[i], index_buffer.max_index);
  1858. }
  1859. }
  1860. } else {
  1861. index_buffer.max_index = 0xFFFFFFFF;
  1862. }
  1863. #else
  1864. index_buffer.max_index = 0xFFFFFFFF;
  1865. #endif
  1866. index_buffer.size = size_bytes;
  1867. index_buffer.usage = (RDD::BUFFER_USAGE_TRANSFER_FROM_BIT | RDD::BUFFER_USAGE_TRANSFER_TO_BIT | RDD::BUFFER_USAGE_INDEX_BIT);
  1868. index_buffer.driver_id = driver->buffer_create(index_buffer.size, index_buffer.usage, RDD::MEMORY_ALLOCATION_TYPE_GPU);
  1869. ERR_FAIL_COND_V(!index_buffer.driver_id, RID());
  1870. // Index buffers are assumed to be immutable unless they don't have initial data.
  1871. if (p_data.is_empty()) {
  1872. index_buffer.draw_tracker = RDG::resource_tracker_create();
  1873. index_buffer.draw_tracker->buffer_driver_id = index_buffer.driver_id;
  1874. }
  1875. if (p_data.size()) {
  1876. _buffer_update(&index_buffer, RID(), 0, p_data.ptr(), p_data.size());
  1877. }
  1878. buffer_memory += index_buffer.size;
  1879. RID id = index_buffer_owner.make_rid(index_buffer);
  1880. #ifdef DEV_ENABLED
  1881. set_resource_name(id, "RID:" + itos(id.get_id()));
  1882. #endif
  1883. return id;
  1884. }
  1885. RID RenderingDevice::index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count) {
  1886. _THREAD_SAFE_METHOD_
  1887. ERR_FAIL_COND_V(!index_buffer_owner.owns(p_index_buffer), RID());
  1888. IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_index_buffer);
  1889. ERR_FAIL_COND_V(p_index_count == 0, RID());
  1890. ERR_FAIL_COND_V(p_index_offset + p_index_count > index_buffer->index_count, RID());
  1891. IndexArray index_array;
  1892. index_array.max_index = index_buffer->max_index;
  1893. index_array.driver_id = index_buffer->driver_id;
  1894. index_array.draw_tracker = index_buffer->draw_tracker;
  1895. index_array.offset = p_index_offset;
  1896. index_array.indices = p_index_count;
  1897. index_array.format = index_buffer->format;
  1898. index_array.supports_restart_indices = index_buffer->supports_restart_indices;
  1899. RID id = index_array_owner.make_rid(index_array);
  1900. _add_dependency(id, p_index_buffer);
  1901. return id;
  1902. }
  1903. /****************/
  1904. /**** SHADER ****/
  1905. /****************/
  1906. static const char *SHADER_UNIFORM_NAMES[RenderingDevice::UNIFORM_TYPE_MAX] = {
  1907. "Sampler", "CombinedSampler", "Texture", "Image", "TextureBuffer", "SamplerTextureBuffer", "ImageBuffer", "UniformBuffer", "StorageBuffer", "InputAttachment"
  1908. };
  1909. String RenderingDevice::_shader_uniform_debug(RID p_shader, int p_set) {
  1910. String ret;
  1911. const Shader *shader = shader_owner.get_or_null(p_shader);
  1912. ERR_FAIL_NULL_V(shader, String());
  1913. for (int i = 0; i < shader->uniform_sets.size(); i++) {
  1914. if (p_set >= 0 && i != p_set) {
  1915. continue;
  1916. }
  1917. for (int j = 0; j < shader->uniform_sets[i].size(); j++) {
  1918. const ShaderUniform &ui = shader->uniform_sets[i][j];
  1919. if (!ret.is_empty()) {
  1920. ret += "\n";
  1921. }
  1922. ret += "Set: " + itos(i) + " Binding: " + itos(ui.binding) + " Type: " + SHADER_UNIFORM_NAMES[ui.type] + " Writable: " + (ui.writable ? "Y" : "N") + " Length: " + itos(ui.length);
  1923. }
  1924. }
  1925. return ret;
  1926. }
  1927. String RenderingDevice::shader_get_binary_cache_key() const {
  1928. return driver->shader_get_binary_cache_key();
  1929. }
  1930. Vector<uint8_t> RenderingDevice::shader_compile_binary_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv, const String &p_shader_name) {
  1931. return driver->shader_compile_binary_from_spirv(p_spirv, p_shader_name);
  1932. }
  1933. RID RenderingDevice::shader_create_from_bytecode(const Vector<uint8_t> &p_shader_binary, RID p_placeholder) {
  1934. _THREAD_SAFE_METHOD_
  1935. ShaderDescription shader_desc;
  1936. String name;
  1937. RDD::ShaderID shader_id = driver->shader_create_from_bytecode(p_shader_binary, shader_desc, name);
  1938. ERR_FAIL_COND_V(!shader_id, RID());
  1939. // All good, let's create modules.
  1940. RID id;
  1941. if (p_placeholder.is_null()) {
  1942. id = shader_owner.make_rid();
  1943. } else {
  1944. id = p_placeholder;
  1945. }
  1946. Shader *shader = shader_owner.get_or_null(id);
  1947. ERR_FAIL_NULL_V(shader, RID());
  1948. *((ShaderDescription *)shader) = shader_desc; // ShaderDescription bundle.
  1949. shader->name = name;
  1950. shader->driver_id = shader_id;
  1951. shader->layout_hash = driver->shader_get_layout_hash(shader_id);
  1952. for (int i = 0; i < shader->uniform_sets.size(); i++) {
  1953. uint32_t format = 0; // No format, default.
  1954. if (shader->uniform_sets[i].size()) {
  1955. // Sort and hash.
  1956. shader->uniform_sets.write[i].sort();
  1957. UniformSetFormat usformat;
  1958. usformat.uniforms = shader->uniform_sets[i];
  1959. RBMap<UniformSetFormat, uint32_t>::Element *E = uniform_set_format_cache.find(usformat);
  1960. if (E) {
  1961. format = E->get();
  1962. } else {
  1963. format = uniform_set_format_cache.size() + 1;
  1964. uniform_set_format_cache.insert(usformat, format);
  1965. }
  1966. }
  1967. shader->set_formats.push_back(format);
  1968. }
  1969. for (ShaderStage stage : shader_desc.stages) {
  1970. switch (stage) {
  1971. case SHADER_STAGE_VERTEX:
  1972. shader->stage_bits.set_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT);
  1973. break;
  1974. case SHADER_STAGE_FRAGMENT:
  1975. shader->stage_bits.set_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
  1976. break;
  1977. case SHADER_STAGE_TESSELATION_CONTROL:
  1978. shader->stage_bits.set_flag(RDD::PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT);
  1979. break;
  1980. case SHADER_STAGE_TESSELATION_EVALUATION:
  1981. shader->stage_bits.set_flag(RDD::PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT);
  1982. break;
  1983. case SHADER_STAGE_COMPUTE:
  1984. shader->stage_bits.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT);
  1985. break;
  1986. default:
  1987. DEV_ASSERT(false && "Unknown shader stage.");
  1988. break;
  1989. }
  1990. }
  1991. #ifdef DEV_ENABLED
  1992. set_resource_name(id, "RID:" + itos(id.get_id()));
  1993. #endif
  1994. return id;
  1995. }
  1996. RID RenderingDevice::shader_create_placeholder() {
  1997. Shader shader;
  1998. return shader_owner.make_rid(shader);
  1999. }
  2000. uint64_t RenderingDevice::shader_get_vertex_input_attribute_mask(RID p_shader) {
  2001. _THREAD_SAFE_METHOD_
  2002. const Shader *shader = shader_owner.get_or_null(p_shader);
  2003. ERR_FAIL_NULL_V(shader, 0);
  2004. return shader->vertex_input_mask;
  2005. }
  2006. /******************/
  2007. /**** UNIFORMS ****/
  2008. /******************/
  2009. RID RenderingDevice::uniform_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data) {
  2010. _THREAD_SAFE_METHOD_
  2011. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  2012. Buffer buffer;
  2013. buffer.size = p_size_bytes;
  2014. buffer.usage = (RDD::BUFFER_USAGE_TRANSFER_TO_BIT | RDD::BUFFER_USAGE_UNIFORM_BIT);
  2015. buffer.driver_id = driver->buffer_create(buffer.size, buffer.usage, RDD::MEMORY_ALLOCATION_TYPE_GPU);
  2016. ERR_FAIL_COND_V(!buffer.driver_id, RID());
  2017. // Uniform buffers are assumed to be immutable unless they don't have initial data.
  2018. if (p_data.is_empty()) {
  2019. buffer.draw_tracker = RDG::resource_tracker_create();
  2020. buffer.draw_tracker->buffer_driver_id = buffer.driver_id;
  2021. }
  2022. if (p_data.size()) {
  2023. _buffer_update(&buffer, RID(), 0, p_data.ptr(), p_data.size());
  2024. }
  2025. buffer_memory += buffer.size;
  2026. RID id = uniform_buffer_owner.make_rid(buffer);
  2027. #ifdef DEV_ENABLED
  2028. set_resource_name(id, "RID:" + itos(id.get_id()));
  2029. #endif
  2030. return id;
  2031. }
  2032. RID RenderingDevice::uniform_set_create(const Vector<Uniform> &p_uniforms, RID p_shader, uint32_t p_shader_set) {
  2033. _THREAD_SAFE_METHOD_
  2034. ERR_FAIL_COND_V(p_uniforms.is_empty(), RID());
  2035. Shader *shader = shader_owner.get_or_null(p_shader);
  2036. ERR_FAIL_NULL_V(shader, RID());
  2037. ERR_FAIL_COND_V_MSG(p_shader_set >= (uint32_t)shader->uniform_sets.size() || shader->uniform_sets[p_shader_set].is_empty(), RID(),
  2038. "Desired set (" + itos(p_shader_set) + ") not used by shader.");
  2039. // See that all sets in shader are satisfied.
  2040. const Vector<ShaderUniform> &set = shader->uniform_sets[p_shader_set];
  2041. uint32_t uniform_count = p_uniforms.size();
  2042. const Uniform *uniforms = p_uniforms.ptr();
  2043. uint32_t set_uniform_count = set.size();
  2044. const ShaderUniform *set_uniforms = set.ptr();
  2045. LocalVector<RDD::BoundUniform> driver_uniforms;
  2046. driver_uniforms.resize(set_uniform_count);
  2047. // Used for verification to make sure a uniform set does not use a framebuffer bound texture.
  2048. LocalVector<UniformSet::AttachableTexture> attachable_textures;
  2049. Vector<RDG::ResourceTracker *> draw_trackers;
  2050. Vector<RDG::ResourceUsage> draw_trackers_usage;
  2051. HashMap<RID, RDG::ResourceUsage> untracked_usage;
  2052. for (uint32_t i = 0; i < set_uniform_count; i++) {
  2053. const ShaderUniform &set_uniform = set_uniforms[i];
  2054. int uniform_idx = -1;
  2055. for (int j = 0; j < (int)uniform_count; j++) {
  2056. if (uniforms[j].binding == set_uniform.binding) {
  2057. uniform_idx = j;
  2058. }
  2059. }
  2060. ERR_FAIL_COND_V_MSG(uniform_idx == -1, RID(),
  2061. "All the shader bindings for the given set must be covered by the uniforms provided. Binding (" + itos(set_uniform.binding) + "), set (" + itos(p_shader_set) + ") was not provided.");
  2062. const Uniform &uniform = uniforms[uniform_idx];
  2063. ERR_FAIL_COND_V_MSG(uniform.uniform_type != set_uniform.type, RID(),
  2064. "Mismatch uniform type for binding (" + itos(set_uniform.binding) + "), set (" + itos(p_shader_set) + "). Expected '" + SHADER_UNIFORM_NAMES[set_uniform.type] + "', supplied: '" + SHADER_UNIFORM_NAMES[uniform.uniform_type] + "'.");
  2065. RDD::BoundUniform &driver_uniform = driver_uniforms[i];
  2066. driver_uniform.type = uniform.uniform_type;
  2067. driver_uniform.binding = uniform.binding;
  2068. switch (uniform.uniform_type) {
  2069. case UNIFORM_TYPE_SAMPLER: {
  2070. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  2071. if (set_uniform.length > 1) {
  2072. ERR_FAIL_V_MSG(RID(), "Sampler (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") sampler elements, so it should be provided equal number of sampler IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");
  2073. } else {
  2074. ERR_FAIL_V_MSG(RID(), "Sampler (binding: " + itos(uniform.binding) + ") should provide one ID referencing a sampler (IDs provided: " + itos(uniform.get_id_count()) + ").");
  2075. }
  2076. }
  2077. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  2078. RDD::SamplerID *sampler_driver_id = sampler_owner.get_or_null(uniform.get_id(j));
  2079. ERR_FAIL_NULL_V_MSG(sampler_driver_id, RID(), "Sampler (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid sampler.");
  2080. driver_uniform.ids.push_back(*sampler_driver_id);
  2081. }
  2082. } break;
  2083. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {
  2084. if (uniform.get_id_count() != (uint32_t)set_uniform.length * 2) {
  2085. if (set_uniform.length > 1) {
  2086. ERR_FAIL_V_MSG(RID(), "SamplerTexture (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") sampler&texture elements, so it should provided twice the amount of IDs (sampler,texture pairs) to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");
  2087. } else {
  2088. ERR_FAIL_V_MSG(RID(), "SamplerTexture (binding: " + itos(uniform.binding) + ") should provide two IDs referencing a sampler and then a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");
  2089. }
  2090. }
  2091. for (uint32_t j = 0; j < uniform.get_id_count(); j += 2) {
  2092. RDD::SamplerID *sampler_driver_id = sampler_owner.get_or_null(uniform.get_id(j + 0));
  2093. ERR_FAIL_NULL_V_MSG(sampler_driver_id, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler.");
  2094. RID texture_id = uniform.get_id(j + 1);
  2095. Texture *texture = texture_owner.get_or_null(texture_id);
  2096. ERR_FAIL_NULL_V_MSG(texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  2097. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  2098. "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  2099. if ((texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT))) {
  2100. UniformSet::AttachableTexture attachable_texture;
  2101. attachable_texture.bind = set_uniform.binding;
  2102. attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.get_id(j + 1);
  2103. attachable_textures.push_back(attachable_texture);
  2104. }
  2105. if (texture->draw_tracker != nullptr) {
  2106. draw_trackers.push_back(texture->draw_tracker);
  2107. draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_TEXTURE_SAMPLE);
  2108. } else {
  2109. untracked_usage[texture_id] = RDG::RESOURCE_USAGE_TEXTURE_SAMPLE;
  2110. }
  2111. DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner));
  2112. driver_uniform.ids.push_back(*sampler_driver_id);
  2113. driver_uniform.ids.push_back(texture->driver_id);
  2114. }
  2115. } break;
  2116. case UNIFORM_TYPE_TEXTURE: {
  2117. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  2118. if (set_uniform.length > 1) {
  2119. ERR_FAIL_V_MSG(RID(), "Texture (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");
  2120. } else {
  2121. ERR_FAIL_V_MSG(RID(), "Texture (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");
  2122. }
  2123. }
  2124. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  2125. RID texture_id = uniform.get_id(j);
  2126. Texture *texture = texture_owner.get_or_null(texture_id);
  2127. ERR_FAIL_NULL_V_MSG(texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  2128. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  2129. "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  2130. if ((texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT))) {
  2131. UniformSet::AttachableTexture attachable_texture;
  2132. attachable_texture.bind = set_uniform.binding;
  2133. attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.get_id(j);
  2134. attachable_textures.push_back(attachable_texture);
  2135. }
  2136. if (texture->draw_tracker != nullptr) {
  2137. draw_trackers.push_back(texture->draw_tracker);
  2138. draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_TEXTURE_SAMPLE);
  2139. } else {
  2140. untracked_usage[texture_id] = RDG::RESOURCE_USAGE_TEXTURE_SAMPLE;
  2141. }
  2142. DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner));
  2143. driver_uniform.ids.push_back(texture->driver_id);
  2144. }
  2145. } break;
  2146. case UNIFORM_TYPE_IMAGE: {
  2147. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  2148. if (set_uniform.length > 1) {
  2149. ERR_FAIL_V_MSG(RID(), "Image (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");
  2150. } else {
  2151. ERR_FAIL_V_MSG(RID(), "Image (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");
  2152. }
  2153. }
  2154. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  2155. RID texture_id = uniform.get_id(j);
  2156. Texture *texture = texture_owner.get_or_null(texture_id);
  2157. ERR_FAIL_NULL_V_MSG(texture, RID(),
  2158. "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  2159. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT), RID(),
  2160. "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_STORAGE_BIT usage flag set in order to be used as uniform.");
  2161. if (_texture_make_mutable(texture, texture_id)) {
  2162. // The texture must be mutable as a layout transition will be required.
  2163. draw_graph.add_synchronization();
  2164. }
  2165. if (texture->draw_tracker != nullptr) {
  2166. draw_trackers.push_back(texture->draw_tracker);
  2167. if (set_uniform.writable) {
  2168. draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_STORAGE_IMAGE_READ_WRITE);
  2169. } else {
  2170. draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_STORAGE_IMAGE_READ);
  2171. }
  2172. }
  2173. DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner));
  2174. driver_uniform.ids.push_back(texture->driver_id);
  2175. }
  2176. } break;
  2177. case UNIFORM_TYPE_TEXTURE_BUFFER: {
  2178. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  2179. if (set_uniform.length > 1) {
  2180. ERR_FAIL_V_MSG(RID(), "Buffer (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") texture buffer elements, so it should be provided equal number of texture buffer IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");
  2181. } else {
  2182. ERR_FAIL_V_MSG(RID(), "Buffer (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture buffer (IDs provided: " + itos(uniform.get_id_count()) + ").");
  2183. }
  2184. }
  2185. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  2186. RID buffer_id = uniform.get_id(j);
  2187. Buffer *buffer = texture_buffer_owner.get_or_null(buffer_id);
  2188. ERR_FAIL_NULL_V_MSG(buffer, RID(), "Texture Buffer (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture buffer.");
  2189. if (set_uniform.writable && _buffer_make_mutable(buffer, buffer_id)) {
  2190. // The buffer must be mutable if it's used for writing.
  2191. draw_graph.add_synchronization();
  2192. }
  2193. if (buffer->draw_tracker != nullptr) {
  2194. draw_trackers.push_back(buffer->draw_tracker);
  2195. if (set_uniform.writable) {
  2196. draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_TEXTURE_BUFFER_READ_WRITE);
  2197. } else {
  2198. draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_TEXTURE_BUFFER_READ);
  2199. }
  2200. } else {
  2201. untracked_usage[buffer_id] = RDG::RESOURCE_USAGE_TEXTURE_BUFFER_READ;
  2202. }
  2203. driver_uniform.ids.push_back(buffer->driver_id);
  2204. }
  2205. } break;
  2206. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: {
  2207. if (uniform.get_id_count() != (uint32_t)set_uniform.length * 2) {
  2208. if (set_uniform.length > 1) {
  2209. ERR_FAIL_V_MSG(RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") sampler buffer elements, so it should provided twice the amount of IDs (sampler,buffer pairs) to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");
  2210. } else {
  2211. ERR_FAIL_V_MSG(RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ") should provide two IDs referencing a sampler and then a texture buffer (IDs provided: " + itos(uniform.get_id_count()) + ").");
  2212. }
  2213. }
  2214. for (uint32_t j = 0; j < uniform.get_id_count(); j += 2) {
  2215. RDD::SamplerID *sampler_driver_id = sampler_owner.get_or_null(uniform.get_id(j + 0));
  2216. ERR_FAIL_NULL_V_MSG(sampler_driver_id, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler.");
  2217. RID buffer_id = uniform.get_id(j + 1);
  2218. Buffer *buffer = texture_buffer_owner.get_or_null(buffer_id);
  2219. ERR_FAIL_NULL_V_MSG(buffer, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid texture buffer.");
  2220. if (buffer->draw_tracker != nullptr) {
  2221. draw_trackers.push_back(buffer->draw_tracker);
  2222. draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_TEXTURE_BUFFER_READ);
  2223. } else {
  2224. untracked_usage[buffer_id] = RDG::RESOURCE_USAGE_TEXTURE_BUFFER_READ;
  2225. }
  2226. driver_uniform.ids.push_back(*sampler_driver_id);
  2227. driver_uniform.ids.push_back(buffer->driver_id);
  2228. }
  2229. } break;
  2230. case UNIFORM_TYPE_IMAGE_BUFFER: {
  2231. // Todo.
  2232. } break;
  2233. case UNIFORM_TYPE_UNIFORM_BUFFER: {
  2234. ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(),
  2235. "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.get_id_count()) + " provided).");
  2236. RID buffer_id = uniform.get_id(0);
  2237. Buffer *buffer = uniform_buffer_owner.get_or_null(buffer_id);
  2238. ERR_FAIL_NULL_V_MSG(buffer, RID(), "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") is invalid.");
  2239. ERR_FAIL_COND_V_MSG(buffer->size < (uint32_t)set_uniform.length, RID(),
  2240. "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " is smaller than size of shader uniform: (" + itos(set_uniform.length) + ").");
  2241. if (buffer->draw_tracker != nullptr) {
  2242. draw_trackers.push_back(buffer->draw_tracker);
  2243. draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_UNIFORM_BUFFER_READ);
  2244. } else {
  2245. untracked_usage[buffer_id] = RDG::RESOURCE_USAGE_UNIFORM_BUFFER_READ;
  2246. }
  2247. driver_uniform.ids.push_back(buffer->driver_id);
  2248. } break;
  2249. case UNIFORM_TYPE_STORAGE_BUFFER: {
  2250. ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(),
  2251. "Storage buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.get_id_count()) + " provided).");
  2252. Buffer *buffer = nullptr;
  2253. RID buffer_id = uniform.get_id(0);
  2254. if (storage_buffer_owner.owns(buffer_id)) {
  2255. buffer = storage_buffer_owner.get_or_null(buffer_id);
  2256. } else if (vertex_buffer_owner.owns(buffer_id)) {
  2257. buffer = vertex_buffer_owner.get_or_null(buffer_id);
  2258. ERR_FAIL_COND_V_MSG(!(buffer->usage.has_flag(RDD::BUFFER_USAGE_STORAGE_BIT)), RID(), "Vertex buffer supplied (binding: " + itos(uniform.binding) + ") was not created with storage flag.");
  2259. }
  2260. ERR_FAIL_NULL_V_MSG(buffer, RID(), "Storage buffer supplied (binding: " + itos(uniform.binding) + ") is invalid.");
  2261. // If 0, then it's sized on link time.
  2262. ERR_FAIL_COND_V_MSG(set_uniform.length > 0 && buffer->size != (uint32_t)set_uniform.length, RID(),
  2263. "Storage buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " does not match size of shader uniform: (" + itos(set_uniform.length) + ").");
  2264. if (set_uniform.writable && _buffer_make_mutable(buffer, buffer_id)) {
  2265. // The buffer must be mutable if it's used for writing.
  2266. draw_graph.add_synchronization();
  2267. }
  2268. if (buffer->draw_tracker != nullptr) {
  2269. draw_trackers.push_back(buffer->draw_tracker);
  2270. if (set_uniform.writable) {
  2271. draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_STORAGE_BUFFER_READ_WRITE);
  2272. } else {
  2273. draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_STORAGE_BUFFER_READ);
  2274. }
  2275. } else {
  2276. untracked_usage[buffer_id] = RDG::RESOURCE_USAGE_STORAGE_BUFFER_READ;
  2277. }
  2278. driver_uniform.ids.push_back(buffer->driver_id);
  2279. } break;
  2280. case UNIFORM_TYPE_INPUT_ATTACHMENT: {
  2281. ERR_FAIL_COND_V_MSG(shader->is_compute, RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") supplied for compute shader (this is not allowed).");
  2282. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  2283. if (set_uniform.length > 1) {
  2284. ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");
  2285. } else {
  2286. ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");
  2287. }
  2288. }
  2289. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  2290. RID texture_id = uniform.get_id(j);
  2291. Texture *texture = texture_owner.get_or_null(texture_id);
  2292. ERR_FAIL_NULL_V_MSG(texture, RID(),
  2293. "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  2294. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  2295. "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  2296. DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner));
  2297. driver_uniform.ids.push_back(texture->driver_id);
  2298. }
  2299. } break;
  2300. default: {
  2301. }
  2302. }
  2303. }
  2304. RDD::UniformSetID driver_uniform_set = driver->uniform_set_create(driver_uniforms, shader->driver_id, p_shader_set);
  2305. ERR_FAIL_COND_V(!driver_uniform_set, RID());
  2306. UniformSet uniform_set;
  2307. uniform_set.driver_id = driver_uniform_set;
  2308. uniform_set.format = shader->set_formats[p_shader_set];
  2309. uniform_set.attachable_textures = attachable_textures;
  2310. uniform_set.draw_trackers = draw_trackers;
  2311. uniform_set.draw_trackers_usage = draw_trackers_usage;
  2312. uniform_set.untracked_usage = untracked_usage;
  2313. uniform_set.shader_set = p_shader_set;
  2314. uniform_set.shader_id = p_shader;
  2315. RID id = uniform_set_owner.make_rid(uniform_set);
  2316. #ifdef DEV_ENABLED
  2317. set_resource_name(id, "RID:" + itos(id.get_id()));
  2318. #endif
  2319. // Add dependencies.
  2320. _add_dependency(id, p_shader);
  2321. for (uint32_t i = 0; i < uniform_count; i++) {
  2322. const Uniform &uniform = uniforms[i];
  2323. int id_count = uniform.get_id_count();
  2324. for (int j = 0; j < id_count; j++) {
  2325. _add_dependency(id, uniform.get_id(j));
  2326. }
  2327. }
  2328. return id;
  2329. }
  2330. bool RenderingDevice::uniform_set_is_valid(RID p_uniform_set) {
  2331. return uniform_set_owner.owns(p_uniform_set);
  2332. }
  2333. void RenderingDevice::uniform_set_set_invalidation_callback(RID p_uniform_set, InvalidationCallback p_callback, void *p_userdata) {
  2334. UniformSet *us = uniform_set_owner.get_or_null(p_uniform_set);
  2335. ERR_FAIL_NULL(us);
  2336. us->invalidated_callback = p_callback;
  2337. us->invalidated_callback_userdata = p_userdata;
  2338. }
  2339. /*******************/
  2340. /**** PIPELINES ****/
  2341. /*******************/
  2342. RID RenderingDevice::render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const PipelineRasterizationState &p_rasterization_state, const PipelineMultisampleState &p_multisample_state, const PipelineDepthStencilState &p_depth_stencil_state, const PipelineColorBlendState &p_blend_state, BitField<PipelineDynamicStateFlags> p_dynamic_state_flags, uint32_t p_for_render_pass, const Vector<PipelineSpecializationConstant> &p_specialization_constants) {
  2343. _THREAD_SAFE_METHOD_
  2344. // Needs a shader.
  2345. Shader *shader = shader_owner.get_or_null(p_shader);
  2346. ERR_FAIL_NULL_V(shader, RID());
  2347. ERR_FAIL_COND_V_MSG(shader->is_compute, RID(),
  2348. "Compute shaders can't be used in render pipelines");
  2349. if (p_framebuffer_format == INVALID_ID) {
  2350. // If nothing provided, use an empty one (no attachments).
  2351. p_framebuffer_format = framebuffer_format_create(Vector<AttachmentFormat>());
  2352. }
  2353. ERR_FAIL_COND_V(!framebuffer_formats.has(p_framebuffer_format), RID());
  2354. const FramebufferFormat &fb_format = framebuffer_formats[p_framebuffer_format];
  2355. // Validate shader vs. framebuffer.
  2356. {
  2357. ERR_FAIL_COND_V_MSG(p_for_render_pass >= uint32_t(fb_format.E->key().passes.size()), RID(), "Render pass requested for pipeline creation (" + itos(p_for_render_pass) + ") is out of bounds");
  2358. const FramebufferPass &pass = fb_format.E->key().passes[p_for_render_pass];
  2359. uint32_t output_mask = 0;
  2360. for (int i = 0; i < pass.color_attachments.size(); i++) {
  2361. if (pass.color_attachments[i] != ATTACHMENT_UNUSED) {
  2362. output_mask |= 1 << i;
  2363. }
  2364. }
  2365. ERR_FAIL_COND_V_MSG(shader->fragment_output_mask != output_mask, RID(),
  2366. "Mismatch fragment shader output mask (" + itos(shader->fragment_output_mask) + ") and framebuffer color output mask (" + itos(output_mask) + ") when binding both in render pipeline.");
  2367. }
  2368. RDD::VertexFormatID driver_vertex_format;
  2369. if (p_vertex_format != INVALID_ID) {
  2370. // Uses vertices, else it does not.
  2371. ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID());
  2372. const VertexDescriptionCache &vd = vertex_formats[p_vertex_format];
  2373. driver_vertex_format = vertex_formats[p_vertex_format].driver_id;
  2374. // Validate with inputs.
  2375. for (uint32_t i = 0; i < 64; i++) {
  2376. if (!(shader->vertex_input_mask & ((uint64_t)1) << i)) {
  2377. continue;
  2378. }
  2379. bool found = false;
  2380. for (int j = 0; j < vd.vertex_formats.size(); j++) {
  2381. if (vd.vertex_formats[j].location == i) {
  2382. found = true;
  2383. }
  2384. }
  2385. ERR_FAIL_COND_V_MSG(!found, RID(),
  2386. "Shader vertex input location (" + itos(i) + ") not provided in vertex input description for pipeline creation.");
  2387. }
  2388. } else {
  2389. ERR_FAIL_COND_V_MSG(shader->vertex_input_mask != 0, RID(),
  2390. "Shader contains vertex inputs, but no vertex input description was provided for pipeline creation.");
  2391. }
  2392. ERR_FAIL_INDEX_V(p_render_primitive, RENDER_PRIMITIVE_MAX, RID());
  2393. ERR_FAIL_INDEX_V(p_rasterization_state.cull_mode, 3, RID());
  2394. if (p_multisample_state.sample_mask.size()) {
  2395. // Use sample mask.
  2396. ERR_FAIL_COND_V((int)TEXTURE_SAMPLES_COUNT[p_multisample_state.sample_count] != p_multisample_state.sample_mask.size(), RID());
  2397. }
  2398. ERR_FAIL_INDEX_V(p_depth_stencil_state.depth_compare_operator, COMPARE_OP_MAX, RID());
  2399. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.fail, STENCIL_OP_MAX, RID());
  2400. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.pass, STENCIL_OP_MAX, RID());
  2401. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.depth_fail, STENCIL_OP_MAX, RID());
  2402. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.compare, COMPARE_OP_MAX, RID());
  2403. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.fail, STENCIL_OP_MAX, RID());
  2404. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.pass, STENCIL_OP_MAX, RID());
  2405. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.depth_fail, STENCIL_OP_MAX, RID());
  2406. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.compare, COMPARE_OP_MAX, RID());
  2407. ERR_FAIL_INDEX_V(p_blend_state.logic_op, LOGIC_OP_MAX, RID());
  2408. const FramebufferPass &pass = fb_format.E->key().passes[p_for_render_pass];
  2409. ERR_FAIL_COND_V(p_blend_state.attachments.size() < pass.color_attachments.size(), RID());
  2410. for (int i = 0; i < pass.color_attachments.size(); i++) {
  2411. if (pass.color_attachments[i] != ATTACHMENT_UNUSED) {
  2412. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_color_blend_factor, BLEND_FACTOR_MAX, RID());
  2413. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_color_blend_factor, BLEND_FACTOR_MAX, RID());
  2414. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].color_blend_op, BLEND_OP_MAX, RID());
  2415. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_alpha_blend_factor, BLEND_FACTOR_MAX, RID());
  2416. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_alpha_blend_factor, BLEND_FACTOR_MAX, RID());
  2417. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].alpha_blend_op, BLEND_OP_MAX, RID());
  2418. }
  2419. }
  2420. for (int i = 0; i < shader->specialization_constants.size(); i++) {
  2421. const ShaderSpecializationConstant &sc = shader->specialization_constants[i];
  2422. for (int j = 0; j < p_specialization_constants.size(); j++) {
  2423. const PipelineSpecializationConstant &psc = p_specialization_constants[j];
  2424. if (psc.constant_id == sc.constant_id) {
  2425. ERR_FAIL_COND_V_MSG(psc.type != sc.type, RID(), "Specialization constant provided for id (" + itos(sc.constant_id) + ") is of the wrong type.");
  2426. break;
  2427. }
  2428. }
  2429. }
  2430. RenderPipeline pipeline;
  2431. pipeline.driver_id = driver->render_pipeline_create(
  2432. shader->driver_id,
  2433. driver_vertex_format,
  2434. p_render_primitive,
  2435. p_rasterization_state,
  2436. p_multisample_state,
  2437. p_depth_stencil_state,
  2438. p_blend_state,
  2439. pass.color_attachments,
  2440. p_dynamic_state_flags,
  2441. fb_format.render_pass,
  2442. p_for_render_pass,
  2443. p_specialization_constants);
  2444. ERR_FAIL_COND_V(!pipeline.driver_id, RID());
  2445. if (pipeline_cache_enabled) {
  2446. _update_pipeline_cache();
  2447. }
  2448. pipeline.shader = p_shader;
  2449. pipeline.shader_driver_id = shader->driver_id;
  2450. pipeline.shader_layout_hash = shader->layout_hash;
  2451. pipeline.set_formats = shader->set_formats;
  2452. pipeline.push_constant_size = shader->push_constant_size;
  2453. pipeline.stage_bits = shader->stage_bits;
  2454. #ifdef DEBUG_ENABLED
  2455. pipeline.validation.dynamic_state = p_dynamic_state_flags;
  2456. pipeline.validation.framebuffer_format = p_framebuffer_format;
  2457. pipeline.validation.render_pass = p_for_render_pass;
  2458. pipeline.validation.vertex_format = p_vertex_format;
  2459. pipeline.validation.uses_restart_indices = p_render_primitive == RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX;
  2460. static const uint32_t primitive_divisor[RENDER_PRIMITIVE_MAX] = {
  2461. 1, 2, 1, 1, 1, 3, 1, 1, 1, 1, 1
  2462. };
  2463. pipeline.validation.primitive_divisor = primitive_divisor[p_render_primitive];
  2464. static const uint32_t primitive_minimum[RENDER_PRIMITIVE_MAX] = {
  2465. 1,
  2466. 2,
  2467. 2,
  2468. 2,
  2469. 2,
  2470. 3,
  2471. 3,
  2472. 3,
  2473. 3,
  2474. 3,
  2475. 1,
  2476. };
  2477. pipeline.validation.primitive_minimum = primitive_minimum[p_render_primitive];
  2478. #endif
  2479. // Create ID to associate with this pipeline.
  2480. RID id = render_pipeline_owner.make_rid(pipeline);
  2481. #ifdef DEV_ENABLED
  2482. set_resource_name(id, "RID:" + itos(id.get_id()));
  2483. #endif
  2484. // Now add all the dependencies.
  2485. _add_dependency(id, p_shader);
  2486. return id;
  2487. }
  2488. bool RenderingDevice::render_pipeline_is_valid(RID p_pipeline) {
  2489. _THREAD_SAFE_METHOD_
  2490. return render_pipeline_owner.owns(p_pipeline);
  2491. }
  2492. RID RenderingDevice::compute_pipeline_create(RID p_shader, const Vector<PipelineSpecializationConstant> &p_specialization_constants) {
  2493. _THREAD_SAFE_METHOD_
  2494. // Needs a shader.
  2495. Shader *shader = shader_owner.get_or_null(p_shader);
  2496. ERR_FAIL_NULL_V(shader, RID());
  2497. ERR_FAIL_COND_V_MSG(!shader->is_compute, RID(),
  2498. "Non-compute shaders can't be used in compute pipelines");
  2499. for (int i = 0; i < shader->specialization_constants.size(); i++) {
  2500. const ShaderSpecializationConstant &sc = shader->specialization_constants[i];
  2501. for (int j = 0; j < p_specialization_constants.size(); j++) {
  2502. const PipelineSpecializationConstant &psc = p_specialization_constants[j];
  2503. if (psc.constant_id == sc.constant_id) {
  2504. ERR_FAIL_COND_V_MSG(psc.type != sc.type, RID(), "Specialization constant provided for id (" + itos(sc.constant_id) + ") is of the wrong type.");
  2505. break;
  2506. }
  2507. }
  2508. }
  2509. ComputePipeline pipeline;
  2510. pipeline.driver_id = driver->compute_pipeline_create(shader->driver_id, p_specialization_constants);
  2511. ERR_FAIL_COND_V(!pipeline.driver_id, RID());
  2512. if (pipeline_cache_enabled) {
  2513. _update_pipeline_cache();
  2514. }
  2515. pipeline.shader = p_shader;
  2516. pipeline.shader_driver_id = shader->driver_id;
  2517. pipeline.shader_layout_hash = shader->layout_hash;
  2518. pipeline.set_formats = shader->set_formats;
  2519. pipeline.push_constant_size = shader->push_constant_size;
  2520. pipeline.local_group_size[0] = shader->compute_local_size[0];
  2521. pipeline.local_group_size[1] = shader->compute_local_size[1];
  2522. pipeline.local_group_size[2] = shader->compute_local_size[2];
  2523. // Create ID to associate with this pipeline.
  2524. RID id = compute_pipeline_owner.make_rid(pipeline);
  2525. #ifdef DEV_ENABLED
  2526. set_resource_name(id, "RID:" + itos(id.get_id()));
  2527. #endif
  2528. // Now add all the dependencies.
  2529. _add_dependency(id, p_shader);
  2530. return id;
  2531. }
  2532. bool RenderingDevice::compute_pipeline_is_valid(RID p_pipeline) {
  2533. return compute_pipeline_owner.owns(p_pipeline);
  2534. }
  2535. /****************/
  2536. /**** SCREEN ****/
  2537. /****************/
  2538. uint32_t RenderingDevice::_get_swap_chain_desired_count() const {
  2539. return MAX(2U, uint32_t(GLOBAL_GET("rendering/rendering_device/vsync/swapchain_image_count")));
  2540. }
  2541. Error RenderingDevice::screen_create(DisplayServer::WindowID p_screen) {
  2542. _THREAD_SAFE_METHOD_
  2543. RenderingContextDriver::SurfaceID surface = context->surface_get_from_window(p_screen);
  2544. ERR_FAIL_COND_V_MSG(surface == 0, ERR_CANT_CREATE, "A surface was not created for the screen.");
  2545. HashMap<DisplayServer::WindowID, RDD::SwapChainID>::ConstIterator it = screen_swap_chains.find(p_screen);
  2546. ERR_FAIL_COND_V_MSG(it != screen_swap_chains.end(), ERR_CANT_CREATE, "A swap chain was already created for the screen.");
  2547. RDD::SwapChainID swap_chain = driver->swap_chain_create(surface);
  2548. ERR_FAIL_COND_V_MSG(swap_chain.id == 0, ERR_CANT_CREATE, "Unable to create swap chain.");
  2549. screen_swap_chains[p_screen] = swap_chain;
  2550. return OK;
  2551. }
  2552. Error RenderingDevice::screen_prepare_for_drawing(DisplayServer::WindowID p_screen) {
  2553. _THREAD_SAFE_METHOD_
  2554. HashMap<DisplayServer::WindowID, RDD::SwapChainID>::ConstIterator it = screen_swap_chains.find(p_screen);
  2555. ERR_FAIL_COND_V_MSG(it == screen_swap_chains.end(), ERR_CANT_CREATE, "A swap chain was not created for the screen.");
  2556. // Erase the framebuffer corresponding to this screen from the map in case any of the operations fail.
  2557. screen_framebuffers.erase(p_screen);
  2558. // If this frame has already queued this swap chain for presentation, we present it and remove it from the pending list.
  2559. uint32_t to_present_index = 0;
  2560. while (to_present_index < frames[frame].swap_chains_to_present.size()) {
  2561. if (frames[frame].swap_chains_to_present[to_present_index] == it->value) {
  2562. driver->command_queue_execute_and_present(present_queue, {}, {}, {}, {}, it->value);
  2563. frames[frame].swap_chains_to_present.remove_at(to_present_index);
  2564. } else {
  2565. to_present_index++;
  2566. }
  2567. }
  2568. bool resize_required = false;
  2569. RDD::FramebufferID framebuffer = driver->swap_chain_acquire_framebuffer(main_queue, it->value, resize_required);
  2570. if (resize_required) {
  2571. // Flush everything so nothing can be using the swap chain before resizing it.
  2572. _flush_and_stall_for_all_frames();
  2573. Error err = driver->swap_chain_resize(main_queue, it->value, _get_swap_chain_desired_count());
  2574. if (err != OK) {
  2575. // Resize is allowed to fail silently because the window can be minimized.
  2576. return err;
  2577. }
  2578. framebuffer = driver->swap_chain_acquire_framebuffer(main_queue, it->value, resize_required);
  2579. }
  2580. ERR_FAIL_COND_V_MSG(framebuffer.id == 0, FAILED, "Unable to acquire framebuffer.");
  2581. // Store the framebuffer that will be used next to draw to this screen.
  2582. screen_framebuffers[p_screen] = framebuffer;
  2583. frames[frame].swap_chains_to_present.push_back(it->value);
  2584. return OK;
  2585. }
  2586. int RenderingDevice::screen_get_width(DisplayServer::WindowID p_screen) const {
  2587. _THREAD_SAFE_METHOD_
  2588. RenderingContextDriver::SurfaceID surface = context->surface_get_from_window(p_screen);
  2589. ERR_FAIL_COND_V_MSG(surface == 0, 0, "A surface was not created for the screen.");
  2590. return context->surface_get_width(surface);
  2591. }
  2592. int RenderingDevice::screen_get_height(DisplayServer::WindowID p_screen) const {
  2593. _THREAD_SAFE_METHOD_
  2594. RenderingContextDriver::SurfaceID surface = context->surface_get_from_window(p_screen);
  2595. ERR_FAIL_COND_V_MSG(surface == 0, 0, "A surface was not created for the screen.");
  2596. return context->surface_get_height(surface);
  2597. }
  2598. RenderingDevice::FramebufferFormatID RenderingDevice::screen_get_framebuffer_format(DisplayServer::WindowID p_screen) const {
  2599. _THREAD_SAFE_METHOD_
  2600. HashMap<DisplayServer::WindowID, RDD::SwapChainID>::ConstIterator it = screen_swap_chains.find(p_screen);
  2601. ERR_FAIL_COND_V_MSG(it == screen_swap_chains.end(), FAILED, "Screen was never prepared.");
  2602. DataFormat format = driver->swap_chain_get_format(it->value);
  2603. ERR_FAIL_COND_V(format == DATA_FORMAT_MAX, INVALID_ID);
  2604. AttachmentFormat attachment;
  2605. attachment.format = format;
  2606. attachment.samples = TEXTURE_SAMPLES_1;
  2607. attachment.usage_flags = TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  2608. Vector<AttachmentFormat> screen_attachment;
  2609. screen_attachment.push_back(attachment);
  2610. return const_cast<RenderingDevice *>(this)->framebuffer_format_create(screen_attachment);
  2611. }
  2612. Error RenderingDevice::screen_free(DisplayServer::WindowID p_screen) {
  2613. _THREAD_SAFE_METHOD_
  2614. HashMap<DisplayServer::WindowID, RDD::SwapChainID>::ConstIterator it = screen_swap_chains.find(p_screen);
  2615. ERR_FAIL_COND_V_MSG(it == screen_swap_chains.end(), FAILED, "Screen was never created.");
  2616. // Flush everything so nothing can be using the swap chain before erasing it.
  2617. _flush_and_stall_for_all_frames();
  2618. const DisplayServer::WindowID screen = it->key;
  2619. const RDD::SwapChainID swap_chain = it->value;
  2620. driver->swap_chain_free(swap_chain);
  2621. screen_framebuffers.erase(screen);
  2622. screen_swap_chains.erase(screen);
  2623. return OK;
  2624. }
  2625. /*******************/
  2626. /**** DRAW LIST ****/
  2627. /*******************/
  2628. RenderingDevice::DrawListID RenderingDevice::draw_list_begin_for_screen(DisplayServer::WindowID p_screen, const Color &p_clear_color) {
  2629. _THREAD_SAFE_METHOD_
  2630. ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  2631. ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  2632. RenderingContextDriver::SurfaceID surface = context->surface_get_from_window(p_screen);
  2633. HashMap<DisplayServer::WindowID, RDD::SwapChainID>::ConstIterator sc_it = screen_swap_chains.find(p_screen);
  2634. HashMap<DisplayServer::WindowID, RDD::FramebufferID>::ConstIterator fb_it = screen_framebuffers.find(p_screen);
  2635. ERR_FAIL_COND_V_MSG(surface == 0, 0, "A surface was not created for the screen.");
  2636. ERR_FAIL_COND_V_MSG(sc_it == screen_swap_chains.end(), INVALID_ID, "Screen was never prepared.");
  2637. ERR_FAIL_COND_V_MSG(fb_it == screen_framebuffers.end(), INVALID_ID, "Framebuffer was never prepared.");
  2638. Rect2i viewport = Rect2i(0, 0, context->surface_get_width(surface), context->surface_get_height(surface));
  2639. _draw_list_allocate(viewport, 0);
  2640. #ifdef DEBUG_ENABLED
  2641. draw_list_framebuffer_format = screen_get_framebuffer_format(p_screen);
  2642. #endif
  2643. draw_list_subpass_count = 1;
  2644. RDD::RenderPassClearValue clear_value;
  2645. clear_value.color = p_clear_color;
  2646. RDD::RenderPassID render_pass = driver->swap_chain_get_render_pass(sc_it->value);
  2647. draw_graph.add_draw_list_begin(render_pass, fb_it->value, viewport, clear_value, true, false);
  2648. _draw_list_set_viewport(viewport);
  2649. _draw_list_set_scissor(viewport);
  2650. return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;
  2651. }
  2652. Error RenderingDevice::_draw_list_setup_framebuffer(Framebuffer *p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, RDD::FramebufferID *r_framebuffer, RDD::RenderPassID *r_render_pass, uint32_t *r_subpass_count) {
  2653. Framebuffer::VersionKey vk;
  2654. vk.initial_color_action = p_initial_color_action;
  2655. vk.final_color_action = p_final_color_action;
  2656. vk.initial_depth_action = p_initial_depth_action;
  2657. vk.final_depth_action = p_final_depth_action;
  2658. vk.view_count = p_framebuffer->view_count;
  2659. if (!p_framebuffer->framebuffers.has(vk)) {
  2660. // Need to create this version.
  2661. Framebuffer::Version version;
  2662. version.render_pass = _render_pass_create(framebuffer_formats[p_framebuffer->format_id].E->key().attachments, framebuffer_formats[p_framebuffer->format_id].E->key().passes, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_framebuffer->view_count);
  2663. LocalVector<RDD::TextureID> attachments;
  2664. for (int i = 0; i < p_framebuffer->texture_ids.size(); i++) {
  2665. Texture *texture = texture_owner.get_or_null(p_framebuffer->texture_ids[i]);
  2666. if (texture) {
  2667. attachments.push_back(texture->driver_id);
  2668. if (!(texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT)) { // VRS attachment will be a different size.
  2669. ERR_FAIL_COND_V(texture->width != p_framebuffer->size.width, ERR_BUG);
  2670. ERR_FAIL_COND_V(texture->height != p_framebuffer->size.height, ERR_BUG);
  2671. }
  2672. }
  2673. }
  2674. version.framebuffer = driver->framebuffer_create(version.render_pass, attachments, p_framebuffer->size.width, p_framebuffer->size.height);
  2675. ERR_FAIL_COND_V(!version.framebuffer, ERR_CANT_CREATE);
  2676. version.subpass_count = framebuffer_formats[p_framebuffer->format_id].E->key().passes.size();
  2677. p_framebuffer->framebuffers.insert(vk, version);
  2678. }
  2679. const Framebuffer::Version &version = p_framebuffer->framebuffers[vk];
  2680. *r_framebuffer = version.framebuffer;
  2681. *r_render_pass = version.render_pass;
  2682. *r_subpass_count = version.subpass_count;
  2683. return OK;
  2684. }
  2685. Error RenderingDevice::_draw_list_render_pass_begin(Framebuffer *p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_colors, float p_clear_depth, uint32_t p_clear_stencil, Point2i p_viewport_offset, Point2i p_viewport_size, RDD::FramebufferID p_framebuffer_driver_id, RDD::RenderPassID p_render_pass) {
  2686. thread_local LocalVector<RDD::RenderPassClearValue> clear_values;
  2687. thread_local LocalVector<RDG::ResourceTracker *> resource_trackers;
  2688. thread_local LocalVector<RDG::ResourceUsage> resource_usages;
  2689. bool uses_color = false;
  2690. bool uses_depth = false;
  2691. clear_values.clear();
  2692. clear_values.resize(p_framebuffer->texture_ids.size());
  2693. resource_trackers.clear();
  2694. resource_usages.clear();
  2695. int clear_values_count = 0;
  2696. {
  2697. int color_index = 0;
  2698. for (int i = 0; i < p_framebuffer->texture_ids.size(); i++) {
  2699. RDD::RenderPassClearValue clear_value;
  2700. Texture *texture = texture_owner.get_or_null(p_framebuffer->texture_ids[i]);
  2701. if (!texture) {
  2702. color_index++;
  2703. continue;
  2704. }
  2705. if (texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2706. if (color_index < p_clear_colors.size()) {
  2707. ERR_FAIL_INDEX_V(color_index, p_clear_colors.size(), ERR_BUG); // A bug.
  2708. clear_value.color = p_clear_colors[color_index];
  2709. color_index++;
  2710. }
  2711. resource_trackers.push_back(texture->draw_tracker);
  2712. resource_usages.push_back(RDG::RESOURCE_USAGE_ATTACHMENT_COLOR_READ_WRITE);
  2713. uses_color = true;
  2714. } else if (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2715. clear_value.depth = p_clear_depth;
  2716. clear_value.stencil = p_clear_stencil;
  2717. resource_trackers.push_back(texture->draw_tracker);
  2718. resource_usages.push_back(RDG::RESOURCE_USAGE_ATTACHMENT_DEPTH_STENCIL_READ_WRITE);
  2719. uses_depth = true;
  2720. }
  2721. clear_values[clear_values_count++] = clear_value;
  2722. }
  2723. }
  2724. draw_graph.add_draw_list_begin(p_render_pass, p_framebuffer_driver_id, Rect2i(p_viewport_offset, p_viewport_size), clear_values, uses_color, uses_depth);
  2725. draw_graph.add_draw_list_usages(resource_trackers, resource_usages);
  2726. // Mark textures as bound.
  2727. draw_list_bound_textures.clear();
  2728. for (int i = 0; i < p_framebuffer->texture_ids.size(); i++) {
  2729. Texture *texture = texture_owner.get_or_null(p_framebuffer->texture_ids[i]);
  2730. if (!texture) {
  2731. continue;
  2732. }
  2733. texture->bound = true;
  2734. draw_list_bound_textures.push_back(p_framebuffer->texture_ids[i]);
  2735. }
  2736. return OK;
  2737. }
  2738. void RenderingDevice::_draw_list_set_viewport(Rect2i p_rect) {
  2739. draw_graph.add_draw_list_set_viewport(p_rect);
  2740. }
  2741. void RenderingDevice::_draw_list_set_scissor(Rect2i p_rect) {
  2742. draw_graph.add_draw_list_set_scissor(p_rect);
  2743. }
  2744. void RenderingDevice::_draw_list_insert_clear_region(DrawList *p_draw_list, Framebuffer *p_framebuffer, Point2i p_viewport_offset, Point2i p_viewport_size, bool p_clear_color, const Vector<Color> &p_clear_colors, bool p_clear_depth, float p_depth, uint32_t p_stencil) {
  2745. LocalVector<RDD::AttachmentClear> clear_attachments;
  2746. int color_index = 0;
  2747. int texture_index = 0;
  2748. for (int i = 0; i < p_framebuffer->texture_ids.size(); i++) {
  2749. Texture *texture = texture_owner.get_or_null(p_framebuffer->texture_ids[i]);
  2750. if (!texture) {
  2751. texture_index++;
  2752. continue;
  2753. }
  2754. RDD::AttachmentClear clear_at;
  2755. if (p_clear_color && (texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) {
  2756. Color clear_color = p_clear_colors[texture_index++];
  2757. clear_at.value.color = clear_color;
  2758. clear_at.color_attachment = color_index++;
  2759. clear_at.aspect = RDD::TEXTURE_ASPECT_COLOR_BIT;
  2760. } else if (p_clear_depth && (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  2761. clear_at.value.depth = p_depth;
  2762. clear_at.value.stencil = p_stencil;
  2763. clear_at.color_attachment = 0;
  2764. clear_at.aspect = RDD::TEXTURE_ASPECT_DEPTH_BIT;
  2765. if (format_has_stencil(texture->format)) {
  2766. clear_at.aspect.set_flag(RDD::TEXTURE_ASPECT_STENCIL_BIT);
  2767. }
  2768. } else {
  2769. ERR_CONTINUE(true);
  2770. }
  2771. clear_attachments.push_back(clear_at);
  2772. }
  2773. Rect2i rect = Rect2i(p_viewport_offset, p_viewport_size);
  2774. draw_graph.add_draw_list_clear_attachments(clear_attachments, rect);
  2775. }
  2776. RenderingDevice::DrawListID RenderingDevice::draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region) {
  2777. _THREAD_SAFE_METHOD_
  2778. ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  2779. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  2780. ERR_FAIL_NULL_V(framebuffer, INVALID_ID);
  2781. Point2i viewport_offset;
  2782. Point2i viewport_size = framebuffer->size;
  2783. if (p_region != Rect2() && p_region != Rect2(Vector2(), viewport_size)) { // Check custom region.
  2784. Rect2i viewport(viewport_offset, viewport_size);
  2785. Rect2i regioni = p_region;
  2786. if (!((regioni.position.x >= viewport.position.x) && (regioni.position.y >= viewport.position.y) &&
  2787. ((regioni.position.x + regioni.size.x) <= (viewport.position.x + viewport.size.x)) &&
  2788. ((regioni.position.y + regioni.size.y) <= (viewport.position.y + viewport.size.y)))) {
  2789. ERR_FAIL_V_MSG(INVALID_ID, "When supplying a custom region, it must be contained within the framebuffer rectangle");
  2790. }
  2791. viewport_offset = regioni.position;
  2792. viewport_size = regioni.size;
  2793. }
  2794. if (p_initial_color_action == INITIAL_ACTION_CLEAR) { // Check clear values.
  2795. int color_count = 0;
  2796. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  2797. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  2798. // We only check for our VRS usage bit if this is not the first texture id.
  2799. // If it is the first we're likely populating our VRS texture.
  2800. // Bit dirty but...
  2801. if (!texture || (!(texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) && !(i != 0 && texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT))) {
  2802. if (!texture || !texture->is_resolve_buffer) {
  2803. color_count++;
  2804. }
  2805. }
  2806. }
  2807. ERR_FAIL_COND_V_MSG(p_clear_color_values.size() != color_count, INVALID_ID, "Clear color values supplied (" + itos(p_clear_color_values.size()) + ") differ from the amount required for framebuffer color attachments (" + itos(color_count) + ").");
  2808. }
  2809. RDD::FramebufferID fb_driver_id;
  2810. RDD::RenderPassID render_pass;
  2811. Error err = _draw_list_setup_framebuffer(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, &fb_driver_id, &render_pass, &draw_list_subpass_count);
  2812. ERR_FAIL_COND_V(err != OK, INVALID_ID);
  2813. err = _draw_list_render_pass_begin(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, viewport_offset, viewport_size, fb_driver_id, render_pass);
  2814. if (err != OK) {
  2815. return INVALID_ID;
  2816. }
  2817. draw_list_render_pass = render_pass;
  2818. draw_list_vkframebuffer = fb_driver_id;
  2819. _draw_list_allocate(Rect2i(viewport_offset, viewport_size), 0);
  2820. #ifdef DEBUG_ENABLED
  2821. draw_list_framebuffer_format = framebuffer->format_id;
  2822. #endif
  2823. draw_list_current_subpass = 0;
  2824. _draw_list_set_viewport(Rect2i(viewport_offset, viewport_size));
  2825. _draw_list_set_scissor(Rect2i(viewport_offset, viewport_size));
  2826. return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;
  2827. }
  2828. #ifndef DISABLE_DEPRECATED
  2829. Error RenderingDevice::draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, DrawListID *r_split_ids, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const Vector<RID> &p_storage_textures) {
  2830. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "Deprecated. Split draw lists are used automatically by RenderingDevice.");
  2831. }
  2832. #endif
  2833. RenderingDevice::DrawList *RenderingDevice::_get_draw_list_ptr(DrawListID p_id) {
  2834. if (p_id < 0) {
  2835. return nullptr;
  2836. }
  2837. if (!draw_list) {
  2838. return nullptr;
  2839. } else if (p_id == (int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT)) {
  2840. return draw_list;
  2841. } else {
  2842. return nullptr;
  2843. }
  2844. }
  2845. void RenderingDevice::draw_list_set_blend_constants(DrawListID p_list, const Color &p_color) {
  2846. DrawList *dl = _get_draw_list_ptr(p_list);
  2847. ERR_FAIL_NULL(dl);
  2848. #ifdef DEBUG_ENABLED
  2849. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  2850. #endif
  2851. draw_graph.add_draw_list_set_blend_constants(p_color);
  2852. }
  2853. void RenderingDevice::draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline) {
  2854. DrawList *dl = _get_draw_list_ptr(p_list);
  2855. ERR_FAIL_NULL(dl);
  2856. #ifdef DEBUG_ENABLED
  2857. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  2858. #endif
  2859. const RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_render_pipeline);
  2860. ERR_FAIL_NULL(pipeline);
  2861. #ifdef DEBUG_ENABLED
  2862. ERR_FAIL_COND(pipeline->validation.framebuffer_format != draw_list_framebuffer_format && pipeline->validation.render_pass != draw_list_current_subpass);
  2863. #endif
  2864. if (p_render_pipeline == dl->state.pipeline) {
  2865. return; // Redundant state, return.
  2866. }
  2867. dl->state.pipeline = p_render_pipeline;
  2868. draw_graph.add_draw_list_bind_pipeline(pipeline->driver_id, pipeline->stage_bits);
  2869. if (dl->state.pipeline_shader != pipeline->shader) {
  2870. // Shader changed, so descriptor sets may become incompatible.
  2871. uint32_t pcount = pipeline->set_formats.size(); // Formats count in this pipeline.
  2872. dl->state.set_count = MAX(dl->state.set_count, pcount);
  2873. const uint32_t *pformats = pipeline->set_formats.ptr(); // Pipeline set formats.
  2874. uint32_t first_invalid_set = UINT32_MAX; // All valid by default.
  2875. switch (driver->api_trait_get(RDD::API_TRAIT_SHADER_CHANGE_INVALIDATION)) {
  2876. case RDD::SHADER_CHANGE_INVALIDATION_ALL_BOUND_UNIFORM_SETS: {
  2877. first_invalid_set = 0;
  2878. } break;
  2879. case RDD::SHADER_CHANGE_INVALIDATION_INCOMPATIBLE_SETS_PLUS_CASCADE: {
  2880. for (uint32_t i = 0; i < pcount; i++) {
  2881. if (dl->state.sets[i].pipeline_expected_format != pformats[i]) {
  2882. first_invalid_set = i;
  2883. break;
  2884. }
  2885. }
  2886. } break;
  2887. case RDD::SHADER_CHANGE_INVALIDATION_ALL_OR_NONE_ACCORDING_TO_LAYOUT_HASH: {
  2888. if (dl->state.pipeline_shader_layout_hash != pipeline->shader_layout_hash) {
  2889. first_invalid_set = 0;
  2890. }
  2891. } break;
  2892. }
  2893. for (uint32_t i = 0; i < pcount; i++) {
  2894. dl->state.sets[i].bound = dl->state.sets[i].bound && i < first_invalid_set;
  2895. dl->state.sets[i].pipeline_expected_format = pformats[i];
  2896. }
  2897. for (uint32_t i = pcount; i < dl->state.set_count; i++) {
  2898. // Unbind the ones above (not used) if exist.
  2899. dl->state.sets[i].bound = false;
  2900. }
  2901. dl->state.set_count = pcount; // Update set count.
  2902. if (pipeline->push_constant_size) {
  2903. #ifdef DEBUG_ENABLED
  2904. dl->validation.pipeline_push_constant_supplied = false;
  2905. #endif
  2906. }
  2907. dl->state.pipeline_shader = pipeline->shader;
  2908. dl->state.pipeline_shader_driver_id = pipeline->shader_driver_id;
  2909. dl->state.pipeline_shader_layout_hash = pipeline->shader_layout_hash;
  2910. }
  2911. #ifdef DEBUG_ENABLED
  2912. // Update render pass pipeline info.
  2913. dl->validation.pipeline_active = true;
  2914. dl->validation.pipeline_dynamic_state = pipeline->validation.dynamic_state;
  2915. dl->validation.pipeline_vertex_format = pipeline->validation.vertex_format;
  2916. dl->validation.pipeline_uses_restart_indices = pipeline->validation.uses_restart_indices;
  2917. dl->validation.pipeline_primitive_divisor = pipeline->validation.primitive_divisor;
  2918. dl->validation.pipeline_primitive_minimum = pipeline->validation.primitive_minimum;
  2919. dl->validation.pipeline_push_constant_size = pipeline->push_constant_size;
  2920. #endif
  2921. }
  2922. void RenderingDevice::draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index) {
  2923. #ifdef DEBUG_ENABLED
  2924. ERR_FAIL_COND_MSG(p_index >= driver->limit_get(LIMIT_MAX_BOUND_UNIFORM_SETS) || p_index >= MAX_UNIFORM_SETS,
  2925. "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(driver->limit_get(LIMIT_MAX_BOUND_UNIFORM_SETS)) + ").");
  2926. #endif
  2927. DrawList *dl = _get_draw_list_ptr(p_list);
  2928. ERR_FAIL_NULL(dl);
  2929. #ifdef DEBUG_ENABLED
  2930. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  2931. #endif
  2932. const UniformSet *uniform_set = uniform_set_owner.get_or_null(p_uniform_set);
  2933. ERR_FAIL_NULL(uniform_set);
  2934. if (p_index > dl->state.set_count) {
  2935. dl->state.set_count = p_index;
  2936. }
  2937. dl->state.sets[p_index].uniform_set_driver_id = uniform_set->driver_id; // Update set pointer.
  2938. dl->state.sets[p_index].bound = false; // Needs rebind.
  2939. dl->state.sets[p_index].uniform_set_format = uniform_set->format;
  2940. dl->state.sets[p_index].uniform_set = p_uniform_set;
  2941. #ifdef DEBUG_ENABLED
  2942. { // Validate that textures bound are not attached as framebuffer bindings.
  2943. uint32_t attachable_count = uniform_set->attachable_textures.size();
  2944. const UniformSet::AttachableTexture *attachable_ptr = uniform_set->attachable_textures.ptr();
  2945. uint32_t bound_count = draw_list_bound_textures.size();
  2946. const RID *bound_ptr = draw_list_bound_textures.ptr();
  2947. for (uint32_t i = 0; i < attachable_count; i++) {
  2948. for (uint32_t j = 0; j < bound_count; j++) {
  2949. ERR_FAIL_COND_MSG(attachable_ptr[i].texture == bound_ptr[j],
  2950. "Attempted to use the same texture in framebuffer attachment and a uniform (set: " + itos(p_index) + ", binding: " + itos(attachable_ptr[i].bind) + "), this is not allowed.");
  2951. }
  2952. }
  2953. }
  2954. #endif
  2955. }
  2956. void RenderingDevice::draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array) {
  2957. DrawList *dl = _get_draw_list_ptr(p_list);
  2958. ERR_FAIL_NULL(dl);
  2959. #ifdef DEBUG_ENABLED
  2960. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  2961. #endif
  2962. const VertexArray *vertex_array = vertex_array_owner.get_or_null(p_vertex_array);
  2963. ERR_FAIL_NULL(vertex_array);
  2964. if (dl->state.vertex_array == p_vertex_array) {
  2965. return; // Already set.
  2966. }
  2967. dl->state.vertex_array = p_vertex_array;
  2968. #ifdef DEBUG_ENABLED
  2969. dl->validation.vertex_format = vertex_array->description;
  2970. dl->validation.vertex_max_instances_allowed = vertex_array->max_instances_allowed;
  2971. #endif
  2972. dl->validation.vertex_array_size = vertex_array->vertex_count;
  2973. draw_graph.add_draw_list_bind_vertex_buffers(vertex_array->buffers, vertex_array->offsets);
  2974. for (int i = 0; i < vertex_array->draw_trackers.size(); i++) {
  2975. draw_graph.add_draw_list_usage(vertex_array->draw_trackers[i], RDG::RESOURCE_USAGE_VERTEX_BUFFER_READ);
  2976. }
  2977. }
  2978. void RenderingDevice::draw_list_bind_index_array(DrawListID p_list, RID p_index_array) {
  2979. DrawList *dl = _get_draw_list_ptr(p_list);
  2980. ERR_FAIL_NULL(dl);
  2981. #ifdef DEBUG_ENABLED
  2982. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  2983. #endif
  2984. const IndexArray *index_array = index_array_owner.get_or_null(p_index_array);
  2985. ERR_FAIL_NULL(index_array);
  2986. if (dl->state.index_array == p_index_array) {
  2987. return; // Already set.
  2988. }
  2989. dl->state.index_array = p_index_array;
  2990. #ifdef DEBUG_ENABLED
  2991. dl->validation.index_array_max_index = index_array->max_index;
  2992. #endif
  2993. dl->validation.index_array_count = index_array->indices;
  2994. const uint64_t offset_bytes = index_array->offset * (index_array->format == INDEX_BUFFER_FORMAT_UINT16 ? sizeof(uint16_t) : sizeof(uint32_t));
  2995. draw_graph.add_draw_list_bind_index_buffer(index_array->driver_id, index_array->format, offset_bytes);
  2996. if (index_array->draw_tracker != nullptr) {
  2997. draw_graph.add_draw_list_usage(index_array->draw_tracker, RDG::RESOURCE_USAGE_INDEX_BUFFER_READ);
  2998. }
  2999. }
  3000. void RenderingDevice::draw_list_set_line_width(DrawListID p_list, float p_width) {
  3001. DrawList *dl = _get_draw_list_ptr(p_list);
  3002. ERR_FAIL_NULL(dl);
  3003. #ifdef DEBUG_ENABLED
  3004. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  3005. #endif
  3006. draw_graph.add_draw_list_set_line_width(p_width);
  3007. }
  3008. void RenderingDevice::draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size) {
  3009. DrawList *dl = _get_draw_list_ptr(p_list);
  3010. ERR_FAIL_NULL(dl);
  3011. #ifdef DEBUG_ENABLED
  3012. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  3013. #endif
  3014. #ifdef DEBUG_ENABLED
  3015. ERR_FAIL_COND_MSG(p_data_size != dl->validation.pipeline_push_constant_size,
  3016. "This render pipeline requires (" + itos(dl->validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")");
  3017. #endif
  3018. draw_graph.add_draw_list_set_push_constant(dl->state.pipeline_shader_driver_id, p_data, p_data_size);
  3019. #ifdef DEBUG_ENABLED
  3020. dl->validation.pipeline_push_constant_supplied = true;
  3021. #endif
  3022. }
  3023. void RenderingDevice::draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances, uint32_t p_procedural_vertices) {
  3024. DrawList *dl = _get_draw_list_ptr(p_list);
  3025. ERR_FAIL_NULL(dl);
  3026. #ifdef DEBUG_ENABLED
  3027. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  3028. #endif
  3029. #ifdef DEBUG_ENABLED
  3030. ERR_FAIL_COND_MSG(!dl->validation.pipeline_active,
  3031. "No render pipeline was set before attempting to draw.");
  3032. if (dl->validation.pipeline_vertex_format != INVALID_ID) {
  3033. // Pipeline uses vertices, validate format.
  3034. ERR_FAIL_COND_MSG(dl->validation.vertex_format == INVALID_ID,
  3035. "No vertex array was bound, and render pipeline expects vertices.");
  3036. // Make sure format is right.
  3037. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format != dl->validation.vertex_format,
  3038. "The vertex format used to create the pipeline does not match the vertex format bound.");
  3039. // Make sure number of instances is valid.
  3040. ERR_FAIL_COND_MSG(p_instances > dl->validation.vertex_max_instances_allowed,
  3041. "Number of instances requested (" + itos(p_instances) + " is larger than the maximum number supported by the bound vertex array (" + itos(dl->validation.vertex_max_instances_allowed) + ").");
  3042. }
  3043. if (dl->validation.pipeline_push_constant_size > 0) {
  3044. // Using push constants, check that they were supplied.
  3045. ERR_FAIL_COND_MSG(!dl->validation.pipeline_push_constant_supplied,
  3046. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  3047. }
  3048. #endif
  3049. #ifdef DEBUG_ENABLED
  3050. for (uint32_t i = 0; i < dl->state.set_count; i++) {
  3051. if (dl->state.sets[i].pipeline_expected_format == 0) {
  3052. // Nothing expected by this pipeline.
  3053. continue;
  3054. }
  3055. if (dl->state.sets[i].pipeline_expected_format != dl->state.sets[i].uniform_set_format) {
  3056. if (dl->state.sets[i].uniform_set_format == 0) {
  3057. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline.");
  3058. } else if (uniform_set_owner.owns(dl->state.sets[i].uniform_set)) {
  3059. UniformSet *us = uniform_set_owner.get_or_null(dl->state.sets[i].uniform_set);
  3060. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + "):\n" + _shader_uniform_debug(us->shader_id, us->shader_set) + "\nare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(dl->state.pipeline_shader));
  3061. } else {
  3062. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(dl->state.pipeline_shader));
  3063. }
  3064. }
  3065. }
  3066. #endif
  3067. // Prepare descriptor sets if the API doesn't use pipeline barriers.
  3068. if (!driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS)) {
  3069. for (uint32_t i = 0; i < dl->state.set_count; i++) {
  3070. if (dl->state.sets[i].pipeline_expected_format == 0) {
  3071. // Nothing expected by this pipeline.
  3072. continue;
  3073. }
  3074. draw_graph.add_draw_list_uniform_set_prepare_for_use(dl->state.pipeline_shader_driver_id, dl->state.sets[i].uniform_set_driver_id, i);
  3075. }
  3076. }
  3077. // Bind descriptor sets.
  3078. for (uint32_t i = 0; i < dl->state.set_count; i++) {
  3079. if (dl->state.sets[i].pipeline_expected_format == 0) {
  3080. continue; // Nothing expected by this pipeline.
  3081. }
  3082. if (!dl->state.sets[i].bound) {
  3083. // All good, see if this requires re-binding.
  3084. draw_graph.add_draw_list_bind_uniform_set(dl->state.pipeline_shader_driver_id, dl->state.sets[i].uniform_set_driver_id, i);
  3085. UniformSet *uniform_set = uniform_set_owner.get_or_null(dl->state.sets[i].uniform_set);
  3086. draw_graph.add_draw_list_usages(uniform_set->draw_trackers, uniform_set->draw_trackers_usage);
  3087. dl->state.sets[i].bound = true;
  3088. }
  3089. }
  3090. if (p_use_indices) {
  3091. #ifdef DEBUG_ENABLED
  3092. ERR_FAIL_COND_MSG(p_procedural_vertices > 0,
  3093. "Procedural vertices can't be used together with indices.");
  3094. ERR_FAIL_COND_MSG(!dl->validation.index_array_count,
  3095. "Draw command requested indices, but no index buffer was set.");
  3096. ERR_FAIL_COND_MSG(dl->validation.pipeline_uses_restart_indices != dl->validation.index_buffer_uses_restart_indices,
  3097. "The usage of restart indices in index buffer does not match the render primitive in the pipeline.");
  3098. #endif
  3099. uint32_t to_draw = dl->validation.index_array_count;
  3100. #ifdef DEBUG_ENABLED
  3101. ERR_FAIL_COND_MSG(to_draw < dl->validation.pipeline_primitive_minimum,
  3102. "Too few indices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(dl->validation.pipeline_primitive_minimum) + ").");
  3103. ERR_FAIL_COND_MSG((to_draw % dl->validation.pipeline_primitive_divisor) != 0,
  3104. "Index amount (" + itos(to_draw) + ") must be a multiple of the amount of indices required by the render primitive (" + itos(dl->validation.pipeline_primitive_divisor) + ").");
  3105. #endif
  3106. draw_graph.add_draw_list_draw_indexed(to_draw, p_instances, 0);
  3107. } else {
  3108. uint32_t to_draw;
  3109. if (p_procedural_vertices > 0) {
  3110. #ifdef DEBUG_ENABLED
  3111. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format != INVALID_ID,
  3112. "Procedural vertices requested, but pipeline expects a vertex array.");
  3113. #endif
  3114. to_draw = p_procedural_vertices;
  3115. } else {
  3116. #ifdef DEBUG_ENABLED
  3117. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format == INVALID_ID,
  3118. "Draw command lacks indices, but pipeline format does not use vertices.");
  3119. #endif
  3120. to_draw = dl->validation.vertex_array_size;
  3121. }
  3122. #ifdef DEBUG_ENABLED
  3123. ERR_FAIL_COND_MSG(to_draw < dl->validation.pipeline_primitive_minimum,
  3124. "Too few vertices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(dl->validation.pipeline_primitive_minimum) + ").");
  3125. ERR_FAIL_COND_MSG((to_draw % dl->validation.pipeline_primitive_divisor) != 0,
  3126. "Vertex amount (" + itos(to_draw) + ") must be a multiple of the amount of vertices required by the render primitive (" + itos(dl->validation.pipeline_primitive_divisor) + ").");
  3127. #endif
  3128. draw_graph.add_draw_list_draw(to_draw, p_instances);
  3129. }
  3130. dl->state.draw_count++;
  3131. }
  3132. void RenderingDevice::draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect) {
  3133. DrawList *dl = _get_draw_list_ptr(p_list);
  3134. ERR_FAIL_NULL(dl);
  3135. #ifdef DEBUG_ENABLED
  3136. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  3137. #endif
  3138. Rect2i rect = p_rect;
  3139. rect.position += dl->viewport.position;
  3140. rect = dl->viewport.intersection(rect);
  3141. if (rect.get_area() == 0) {
  3142. return;
  3143. }
  3144. _draw_list_set_scissor(rect);
  3145. }
  3146. void RenderingDevice::draw_list_disable_scissor(DrawListID p_list) {
  3147. DrawList *dl = _get_draw_list_ptr(p_list);
  3148. ERR_FAIL_NULL(dl);
  3149. #ifdef DEBUG_ENABLED
  3150. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  3151. #endif
  3152. _draw_list_set_scissor(dl->viewport);
  3153. }
  3154. uint32_t RenderingDevice::draw_list_get_current_pass() {
  3155. return draw_list_current_subpass;
  3156. }
  3157. RenderingDevice::DrawListID RenderingDevice::draw_list_switch_to_next_pass() {
  3158. _THREAD_SAFE_METHOD_
  3159. ERR_FAIL_NULL_V(draw_list, INVALID_ID);
  3160. ERR_FAIL_COND_V(draw_list_current_subpass >= draw_list_subpass_count - 1, INVALID_FORMAT_ID);
  3161. draw_list_current_subpass++;
  3162. Rect2i viewport;
  3163. _draw_list_free(&viewport);
  3164. draw_graph.add_draw_list_next_subpass(RDD::COMMAND_BUFFER_TYPE_PRIMARY);
  3165. _draw_list_allocate(viewport, draw_list_current_subpass);
  3166. return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;
  3167. }
  3168. #ifndef DISABLE_DEPRECATED
  3169. Error RenderingDevice::draw_list_switch_to_next_pass_split(uint32_t p_splits, DrawListID *r_split_ids) {
  3170. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "Deprecated. Split draw lists are used automatically by RenderingDevice.");
  3171. }
  3172. #endif
  3173. Error RenderingDevice::_draw_list_allocate(const Rect2i &p_viewport, uint32_t p_subpass) {
  3174. // Lock while draw_list is active.
  3175. _THREAD_SAFE_LOCK_
  3176. draw_list = memnew(DrawList);
  3177. draw_list->viewport = p_viewport;
  3178. return OK;
  3179. }
  3180. void RenderingDevice::_draw_list_free(Rect2i *r_last_viewport) {
  3181. if (r_last_viewport) {
  3182. *r_last_viewport = draw_list->viewport;
  3183. }
  3184. // Just end the list.
  3185. memdelete(draw_list);
  3186. draw_list = nullptr;
  3187. // Draw_list is no longer active.
  3188. _THREAD_SAFE_UNLOCK_
  3189. }
  3190. void RenderingDevice::draw_list_end() {
  3191. _THREAD_SAFE_METHOD_
  3192. ERR_FAIL_NULL_MSG(draw_list, "Immediate draw list is already inactive.");
  3193. draw_graph.add_draw_list_end();
  3194. _draw_list_free();
  3195. for (int i = 0; i < draw_list_bound_textures.size(); i++) {
  3196. Texture *texture = texture_owner.get_or_null(draw_list_bound_textures[i]);
  3197. ERR_CONTINUE(!texture); // Wtf.
  3198. if (texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3199. texture->bound = false;
  3200. }
  3201. if (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3202. texture->bound = false;
  3203. }
  3204. }
  3205. draw_list_bound_textures.clear();
  3206. }
  3207. /***********************/
  3208. /**** COMPUTE LISTS ****/
  3209. /***********************/
  3210. RenderingDevice::ComputeListID RenderingDevice::compute_list_begin() {
  3211. _THREAD_SAFE_METHOD_
  3212. ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  3213. // Lock while compute_list is active.
  3214. _THREAD_SAFE_LOCK_
  3215. compute_list = memnew(ComputeList);
  3216. draw_graph.add_compute_list_begin();
  3217. return ID_TYPE_COMPUTE_LIST;
  3218. }
  3219. void RenderingDevice::compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline) {
  3220. // Must be called within a compute list, the class mutex is locked during that time
  3221. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  3222. ERR_FAIL_NULL(compute_list);
  3223. ComputeList *cl = compute_list;
  3224. const ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_compute_pipeline);
  3225. ERR_FAIL_NULL(pipeline);
  3226. if (p_compute_pipeline == cl->state.pipeline) {
  3227. return; // Redundant state, return.
  3228. }
  3229. cl->state.pipeline = p_compute_pipeline;
  3230. draw_graph.add_compute_list_bind_pipeline(pipeline->driver_id);
  3231. if (cl->state.pipeline_shader != pipeline->shader) {
  3232. // Shader changed, so descriptor sets may become incompatible.
  3233. uint32_t pcount = pipeline->set_formats.size(); // Formats count in this pipeline.
  3234. cl->state.set_count = MAX(cl->state.set_count, pcount);
  3235. const uint32_t *pformats = pipeline->set_formats.ptr(); // Pipeline set formats.
  3236. uint32_t first_invalid_set = UINT32_MAX; // All valid by default.
  3237. switch (driver->api_trait_get(RDD::API_TRAIT_SHADER_CHANGE_INVALIDATION)) {
  3238. case RDD::SHADER_CHANGE_INVALIDATION_ALL_BOUND_UNIFORM_SETS: {
  3239. first_invalid_set = 0;
  3240. } break;
  3241. case RDD::SHADER_CHANGE_INVALIDATION_INCOMPATIBLE_SETS_PLUS_CASCADE: {
  3242. for (uint32_t i = 0; i < pcount; i++) {
  3243. if (cl->state.sets[i].pipeline_expected_format != pformats[i]) {
  3244. first_invalid_set = i;
  3245. break;
  3246. }
  3247. }
  3248. } break;
  3249. case RDD::SHADER_CHANGE_INVALIDATION_ALL_OR_NONE_ACCORDING_TO_LAYOUT_HASH: {
  3250. if (cl->state.pipeline_shader_layout_hash != pipeline->shader_layout_hash) {
  3251. first_invalid_set = 0;
  3252. }
  3253. } break;
  3254. }
  3255. for (uint32_t i = 0; i < pcount; i++) {
  3256. cl->state.sets[i].bound = cl->state.sets[i].bound && i < first_invalid_set;
  3257. cl->state.sets[i].pipeline_expected_format = pformats[i];
  3258. }
  3259. for (uint32_t i = pcount; i < cl->state.set_count; i++) {
  3260. // Unbind the ones above (not used) if exist.
  3261. cl->state.sets[i].bound = false;
  3262. }
  3263. cl->state.set_count = pcount; // Update set count.
  3264. if (pipeline->push_constant_size) {
  3265. #ifdef DEBUG_ENABLED
  3266. cl->validation.pipeline_push_constant_supplied = false;
  3267. #endif
  3268. }
  3269. cl->state.pipeline_shader = pipeline->shader;
  3270. cl->state.pipeline_shader_driver_id = pipeline->shader_driver_id;
  3271. cl->state.pipeline_shader_layout_hash = pipeline->shader_layout_hash;
  3272. cl->state.local_group_size[0] = pipeline->local_group_size[0];
  3273. cl->state.local_group_size[1] = pipeline->local_group_size[1];
  3274. cl->state.local_group_size[2] = pipeline->local_group_size[2];
  3275. }
  3276. #ifdef DEBUG_ENABLED
  3277. // Update compute pass pipeline info.
  3278. cl->validation.pipeline_active = true;
  3279. cl->validation.pipeline_push_constant_size = pipeline->push_constant_size;
  3280. #endif
  3281. }
  3282. void RenderingDevice::compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index) {
  3283. // Must be called within a compute list, the class mutex is locked during that time
  3284. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  3285. ERR_FAIL_NULL(compute_list);
  3286. ComputeList *cl = compute_list;
  3287. #ifdef DEBUG_ENABLED
  3288. ERR_FAIL_COND_MSG(p_index >= driver->limit_get(LIMIT_MAX_BOUND_UNIFORM_SETS) || p_index >= MAX_UNIFORM_SETS,
  3289. "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(driver->limit_get(LIMIT_MAX_BOUND_UNIFORM_SETS)) + ").");
  3290. #endif
  3291. #ifdef DEBUG_ENABLED
  3292. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  3293. #endif
  3294. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_uniform_set);
  3295. ERR_FAIL_NULL(uniform_set);
  3296. if (p_index > cl->state.set_count) {
  3297. cl->state.set_count = p_index;
  3298. }
  3299. cl->state.sets[p_index].uniform_set_driver_id = uniform_set->driver_id; // Update set pointer.
  3300. cl->state.sets[p_index].bound = false; // Needs rebind.
  3301. cl->state.sets[p_index].uniform_set_format = uniform_set->format;
  3302. cl->state.sets[p_index].uniform_set = p_uniform_set;
  3303. #if 0
  3304. { // Validate that textures bound are not attached as framebuffer bindings.
  3305. uint32_t attachable_count = uniform_set->attachable_textures.size();
  3306. const RID *attachable_ptr = uniform_set->attachable_textures.ptr();
  3307. uint32_t bound_count = draw_list_bound_textures.size();
  3308. const RID *bound_ptr = draw_list_bound_textures.ptr();
  3309. for (uint32_t i = 0; i < attachable_count; i++) {
  3310. for (uint32_t j = 0; j < bound_count; j++) {
  3311. ERR_FAIL_COND_MSG(attachable_ptr[i] == bound_ptr[j],
  3312. "Attempted to use the same texture in framebuffer attachment and a uniform set, this is not allowed.");
  3313. }
  3314. }
  3315. }
  3316. #endif
  3317. }
  3318. void RenderingDevice::compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size) {
  3319. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  3320. ERR_FAIL_NULL(compute_list);
  3321. ERR_FAIL_COND_MSG(p_data_size > MAX_PUSH_CONSTANT_SIZE, "Push constants can't be bigger than 128 bytes to maintain compatibility.");
  3322. ComputeList *cl = compute_list;
  3323. #ifdef DEBUG_ENABLED
  3324. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  3325. #endif
  3326. #ifdef DEBUG_ENABLED
  3327. ERR_FAIL_COND_MSG(p_data_size != cl->validation.pipeline_push_constant_size,
  3328. "This compute pipeline requires (" + itos(cl->validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")");
  3329. #endif
  3330. draw_graph.add_compute_list_set_push_constant(cl->state.pipeline_shader_driver_id, p_data, p_data_size);
  3331. // Store it in the state in case we need to restart the compute list.
  3332. memcpy(cl->state.push_constant_data, p_data, p_data_size);
  3333. cl->state.push_constant_size = p_data_size;
  3334. #ifdef DEBUG_ENABLED
  3335. cl->validation.pipeline_push_constant_supplied = true;
  3336. #endif
  3337. }
  3338. void RenderingDevice::compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) {
  3339. // Must be called within a compute list, the class mutex is locked during that time
  3340. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  3341. ERR_FAIL_NULL(compute_list);
  3342. ComputeList *cl = compute_list;
  3343. #ifdef DEBUG_ENABLED
  3344. ERR_FAIL_COND_MSG(p_x_groups == 0, "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is zero.");
  3345. ERR_FAIL_COND_MSG(p_z_groups == 0, "Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is zero.");
  3346. ERR_FAIL_COND_MSG(p_y_groups == 0, "Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is zero.");
  3347. ERR_FAIL_COND_MSG(p_x_groups > driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X),
  3348. "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is larger than device limit (" + itos(driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X)) + ")");
  3349. ERR_FAIL_COND_MSG(p_y_groups > driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y),
  3350. "Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is larger than device limit (" + itos(driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y)) + ")");
  3351. ERR_FAIL_COND_MSG(p_z_groups > driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z),
  3352. "Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is larger than device limit (" + itos(driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z)) + ")");
  3353. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  3354. #endif
  3355. #ifdef DEBUG_ENABLED
  3356. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  3357. if (cl->validation.pipeline_push_constant_size > 0) {
  3358. // Using push constants, check that they were supplied.
  3359. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  3360. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  3361. }
  3362. #endif
  3363. #ifdef DEBUG_ENABLED
  3364. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  3365. if (cl->state.sets[i].pipeline_expected_format == 0) {
  3366. // Nothing expected by this pipeline.
  3367. continue;
  3368. }
  3369. if (cl->state.sets[i].pipeline_expected_format != cl->state.sets[i].uniform_set_format) {
  3370. if (cl->state.sets[i].uniform_set_format == 0) {
  3371. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline.");
  3372. } else if (uniform_set_owner.owns(cl->state.sets[i].uniform_set)) {
  3373. UniformSet *us = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set);
  3374. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + "):\n" + _shader_uniform_debug(us->shader_id, us->shader_set) + "\nare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader));
  3375. } else {
  3376. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader));
  3377. }
  3378. }
  3379. }
  3380. #endif
  3381. // Prepare descriptor sets if the API doesn't use pipeline barriers.
  3382. if (!driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS)) {
  3383. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  3384. if (cl->state.sets[i].pipeline_expected_format == 0) {
  3385. // Nothing expected by this pipeline.
  3386. continue;
  3387. }
  3388. draw_graph.add_compute_list_uniform_set_prepare_for_use(cl->state.pipeline_shader_driver_id, cl->state.sets[i].uniform_set_driver_id, i);
  3389. }
  3390. }
  3391. // Bind descriptor sets.
  3392. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  3393. if (cl->state.sets[i].pipeline_expected_format == 0) {
  3394. continue; // Nothing expected by this pipeline.
  3395. }
  3396. if (!cl->state.sets[i].bound) {
  3397. // All good, see if this requires re-binding.
  3398. draw_graph.add_compute_list_bind_uniform_set(cl->state.pipeline_shader_driver_id, cl->state.sets[i].uniform_set_driver_id, i);
  3399. UniformSet *uniform_set = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set);
  3400. draw_graph.add_compute_list_usages(uniform_set->draw_trackers, uniform_set->draw_trackers_usage);
  3401. cl->state.sets[i].bound = true;
  3402. }
  3403. }
  3404. draw_graph.add_compute_list_dispatch(p_x_groups, p_y_groups, p_z_groups);
  3405. cl->state.dispatch_count++;
  3406. }
  3407. void RenderingDevice::compute_list_dispatch_threads(ComputeListID p_list, uint32_t p_x_threads, uint32_t p_y_threads, uint32_t p_z_threads) {
  3408. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  3409. ERR_FAIL_NULL(compute_list);
  3410. #ifdef DEBUG_ENABLED
  3411. ERR_FAIL_COND_MSG(p_x_threads == 0, "Dispatch amount of X compute threads (" + itos(p_x_threads) + ") is zero.");
  3412. ERR_FAIL_COND_MSG(p_y_threads == 0, "Dispatch amount of Y compute threads (" + itos(p_y_threads) + ") is zero.");
  3413. ERR_FAIL_COND_MSG(p_z_threads == 0, "Dispatch amount of Z compute threads (" + itos(p_z_threads) + ") is zero.");
  3414. #endif
  3415. ComputeList *cl = compute_list;
  3416. #ifdef DEBUG_ENABLED
  3417. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  3418. if (cl->validation.pipeline_push_constant_size > 0) {
  3419. // Using push constants, check that they were supplied.
  3420. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  3421. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  3422. }
  3423. #endif
  3424. compute_list_dispatch(p_list, Math::division_round_up(p_x_threads, cl->state.local_group_size[0]), Math::division_round_up(p_y_threads, cl->state.local_group_size[1]), Math::division_round_up(p_z_threads, cl->state.local_group_size[2]));
  3425. }
  3426. void RenderingDevice::compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset) {
  3427. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  3428. ERR_FAIL_NULL(compute_list);
  3429. ComputeList *cl = compute_list;
  3430. Buffer *buffer = storage_buffer_owner.get_or_null(p_buffer);
  3431. ERR_FAIL_NULL(buffer);
  3432. ERR_FAIL_COND_MSG(!buffer->usage.has_flag(RDD::BUFFER_USAGE_INDIRECT_BIT), "Buffer provided was not created to do indirect dispatch.");
  3433. ERR_FAIL_COND_MSG(p_offset + 12 > buffer->size, "Offset provided (+12) is past the end of buffer.");
  3434. #ifdef DEBUG_ENABLED
  3435. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  3436. #endif
  3437. #ifdef DEBUG_ENABLED
  3438. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  3439. if (cl->validation.pipeline_push_constant_size > 0) {
  3440. // Using push constants, check that they were supplied.
  3441. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  3442. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  3443. }
  3444. #endif
  3445. #ifdef DEBUG_ENABLED
  3446. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  3447. if (cl->state.sets[i].pipeline_expected_format == 0) {
  3448. // Nothing expected by this pipeline.
  3449. continue;
  3450. }
  3451. if (cl->state.sets[i].pipeline_expected_format != cl->state.sets[i].uniform_set_format) {
  3452. if (cl->state.sets[i].uniform_set_format == 0) {
  3453. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline.");
  3454. } else if (uniform_set_owner.owns(cl->state.sets[i].uniform_set)) {
  3455. UniformSet *us = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set);
  3456. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + "):\n" + _shader_uniform_debug(us->shader_id, us->shader_set) + "\nare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader));
  3457. } else {
  3458. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader));
  3459. }
  3460. }
  3461. }
  3462. #endif
  3463. // Prepare descriptor sets if the API doesn't use pipeline barriers.
  3464. if (!driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS)) {
  3465. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  3466. if (cl->state.sets[i].pipeline_expected_format == 0) {
  3467. // Nothing expected by this pipeline.
  3468. continue;
  3469. }
  3470. draw_graph.add_compute_list_uniform_set_prepare_for_use(cl->state.pipeline_shader_driver_id, cl->state.sets[i].uniform_set_driver_id, i);
  3471. }
  3472. }
  3473. // Bind descriptor sets.
  3474. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  3475. if (cl->state.sets[i].pipeline_expected_format == 0) {
  3476. continue; // Nothing expected by this pipeline.
  3477. }
  3478. if (!cl->state.sets[i].bound) {
  3479. // All good, see if this requires re-binding.
  3480. draw_graph.add_compute_list_bind_uniform_set(cl->state.pipeline_shader_driver_id, cl->state.sets[i].uniform_set_driver_id, i);
  3481. UniformSet *uniform_set = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set);
  3482. draw_graph.add_compute_list_usages(uniform_set->draw_trackers, uniform_set->draw_trackers_usage);
  3483. cl->state.sets[i].bound = true;
  3484. }
  3485. }
  3486. draw_graph.add_compute_list_dispatch_indirect(buffer->driver_id, p_offset);
  3487. cl->state.dispatch_count++;
  3488. if (buffer->draw_tracker != nullptr) {
  3489. draw_graph.add_compute_list_usage(buffer->draw_tracker, RDG::RESOURCE_USAGE_INDIRECT_BUFFER_READ);
  3490. }
  3491. }
  3492. void RenderingDevice::compute_list_add_barrier(ComputeListID p_list) {
  3493. // Must be called within a compute list, the class mutex is locked during that time
  3494. compute_list_barrier_state = compute_list->state;
  3495. compute_list_end();
  3496. compute_list_begin();
  3497. if (compute_list_barrier_state.pipeline.is_valid()) {
  3498. compute_list_bind_compute_pipeline(p_list, compute_list_barrier_state.pipeline);
  3499. }
  3500. for (uint32_t i = 0; i < compute_list_barrier_state.set_count; i++) {
  3501. if (compute_list_barrier_state.sets[i].uniform_set.is_valid()) {
  3502. compute_list_bind_uniform_set(p_list, compute_list_barrier_state.sets[i].uniform_set, i);
  3503. }
  3504. }
  3505. if (compute_list_barrier_state.push_constant_size > 0) {
  3506. compute_list_set_push_constant(p_list, compute_list_barrier_state.push_constant_data, compute_list_barrier_state.push_constant_size);
  3507. }
  3508. }
  3509. void RenderingDevice::compute_list_end() {
  3510. ERR_FAIL_NULL(compute_list);
  3511. draw_graph.add_compute_list_end();
  3512. memdelete(compute_list);
  3513. compute_list = nullptr;
  3514. // Compute_list is no longer active.
  3515. _THREAD_SAFE_UNLOCK_
  3516. }
  3517. #ifndef DISABLE_DEPRECATED
  3518. void RenderingDevice::barrier(BitField<BarrierMask> p_from, BitField<BarrierMask> p_to) {
  3519. WARN_PRINT("Deprecated. Barriers are automatically inserted by RenderingDevice.");
  3520. }
  3521. void RenderingDevice::full_barrier() {
  3522. WARN_PRINT("Deprecated. Barriers are automatically inserted by RenderingDevice.");
  3523. }
  3524. #endif
  3525. /***********************/
  3526. /**** COMMAND GRAPH ****/
  3527. /***********************/
  3528. bool RenderingDevice::_texture_make_mutable(Texture *p_texture, RID p_texture_id) {
  3529. if (p_texture->draw_tracker != nullptr) {
  3530. // Texture already has a tracker.
  3531. return false;
  3532. } else {
  3533. if (p_texture->owner.is_valid()) {
  3534. // Texture has an owner.
  3535. Texture *owner_texture = texture_owner.get_or_null(p_texture->owner);
  3536. ERR_FAIL_NULL_V(owner_texture, false);
  3537. if (owner_texture->draw_tracker != nullptr) {
  3538. // Create a tracker for this dependency in particular.
  3539. if (p_texture->slice_type == TEXTURE_SLICE_MAX) {
  3540. // Shared texture.
  3541. p_texture->draw_tracker = owner_texture->draw_tracker;
  3542. p_texture->draw_tracker->reference_count++;
  3543. } else {
  3544. // Slice texture.
  3545. HashMap<Rect2i, RDG::ResourceTracker *>::ConstIterator draw_tracker_iterator = owner_texture->slice_trackers.find(p_texture->slice_rect);
  3546. RDG::ResourceTracker *draw_tracker = nullptr;
  3547. if (draw_tracker_iterator != owner_texture->slice_trackers.end()) {
  3548. // Reuse the tracker at the matching rectangle.
  3549. draw_tracker = draw_tracker_iterator->value;
  3550. } else {
  3551. // Create a new tracker and store it on the map.
  3552. draw_tracker = RDG::resource_tracker_create();
  3553. draw_tracker->parent = owner_texture->draw_tracker;
  3554. draw_tracker->texture_driver_id = p_texture->driver_id;
  3555. draw_tracker->texture_subresources = p_texture->barrier_range();
  3556. draw_tracker->texture_slice_or_dirty_rect = p_texture->slice_rect;
  3557. owner_texture->slice_trackers[p_texture->slice_rect] = draw_tracker;
  3558. }
  3559. p_texture->slice_trackers.clear();
  3560. p_texture->draw_tracker = draw_tracker;
  3561. p_texture->draw_tracker->reference_count++;
  3562. }
  3563. if (p_texture_id.is_valid()) {
  3564. _dependencies_make_mutable(p_texture_id, p_texture->draw_tracker);
  3565. }
  3566. } else {
  3567. // Delegate this to the owner instead, as it'll make all its dependencies mutable.
  3568. _texture_make_mutable(owner_texture, p_texture->owner);
  3569. }
  3570. } else {
  3571. // Regular texture.
  3572. p_texture->draw_tracker = RDG::resource_tracker_create();
  3573. p_texture->draw_tracker->texture_driver_id = p_texture->driver_id;
  3574. p_texture->draw_tracker->texture_subresources = p_texture->barrier_range();
  3575. p_texture->draw_tracker->reference_count = 1;
  3576. if (p_texture_id.is_valid()) {
  3577. if (p_texture->has_initial_data) {
  3578. // If the texture was initialized with initial data but wasn't made mutable from the start, assume the texture sampling usage.
  3579. p_texture->draw_tracker->usage = RDG::RESOURCE_USAGE_TEXTURE_SAMPLE;
  3580. }
  3581. _dependencies_make_mutable(p_texture_id, p_texture->draw_tracker);
  3582. }
  3583. }
  3584. return true;
  3585. }
  3586. }
  3587. bool RenderingDevice::_buffer_make_mutable(Buffer *p_buffer, RID p_buffer_id) {
  3588. if (p_buffer->draw_tracker != nullptr) {
  3589. // Buffer already has a tracker.
  3590. return false;
  3591. } else {
  3592. // Create a tracker for the buffer and make all its dependencies mutable.
  3593. p_buffer->draw_tracker = RDG::resource_tracker_create();
  3594. p_buffer->draw_tracker->buffer_driver_id = p_buffer->driver_id;
  3595. if (p_buffer_id.is_valid()) {
  3596. _dependencies_make_mutable(p_buffer_id, p_buffer->draw_tracker);
  3597. }
  3598. return true;
  3599. }
  3600. }
  3601. bool RenderingDevice::_vertex_array_make_mutable(VertexArray *p_vertex_array, RID p_resource_id, RDG::ResourceTracker *p_resource_tracker) {
  3602. if (!p_vertex_array->untracked_buffers.has(p_resource_id)) {
  3603. // Vertex array thinks the buffer is already tracked or does not use it.
  3604. return false;
  3605. } else {
  3606. // Vertex array is aware of the buffer but it isn't being tracked.
  3607. p_vertex_array->draw_trackers.push_back(p_resource_tracker);
  3608. p_vertex_array->untracked_buffers.erase(p_resource_id);
  3609. return true;
  3610. }
  3611. }
  3612. bool RenderingDevice::_index_array_make_mutable(IndexArray *p_index_array, RDG::ResourceTracker *p_resource_tracker) {
  3613. if (p_index_array->draw_tracker != nullptr) {
  3614. // Index array already has a tracker.
  3615. return false;
  3616. } else {
  3617. // Index array should assign the tracker from the buffer.
  3618. p_index_array->draw_tracker = p_resource_tracker;
  3619. return true;
  3620. }
  3621. }
  3622. bool RenderingDevice::_uniform_set_make_mutable(UniformSet *p_uniform_set, RID p_resource_id, RDG::ResourceTracker *p_resource_tracker) {
  3623. HashMap<RID, RDG::ResourceUsage>::Iterator E = p_uniform_set->untracked_usage.find(p_resource_id);
  3624. if (!E) {
  3625. // Uniform set thinks the resource is already tracked or does not use it.
  3626. return false;
  3627. } else {
  3628. // Uniform set has seen the resource but hasn't added its tracker yet.
  3629. p_uniform_set->draw_trackers.push_back(p_resource_tracker);
  3630. p_uniform_set->draw_trackers_usage.push_back(E->value);
  3631. p_uniform_set->untracked_usage.remove(E);
  3632. return true;
  3633. }
  3634. }
  3635. bool RenderingDevice::_dependency_make_mutable(RID p_id, RID p_resource_id, RDG::ResourceTracker *p_resource_tracker) {
  3636. if (texture_owner.owns(p_id)) {
  3637. Texture *texture = texture_owner.get_or_null(p_id);
  3638. return _texture_make_mutable(texture, p_id);
  3639. } else if (vertex_array_owner.owns(p_id)) {
  3640. VertexArray *vertex_array = vertex_array_owner.get_or_null(p_id);
  3641. return _vertex_array_make_mutable(vertex_array, p_resource_id, p_resource_tracker);
  3642. } else if (index_array_owner.owns(p_id)) {
  3643. IndexArray *index_array = index_array_owner.get_or_null(p_id);
  3644. return _index_array_make_mutable(index_array, p_resource_tracker);
  3645. } else if (uniform_set_owner.owns(p_id)) {
  3646. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id);
  3647. return _uniform_set_make_mutable(uniform_set, p_resource_id, p_resource_tracker);
  3648. } else {
  3649. DEV_ASSERT(false && "Unknown resource type to make mutable.");
  3650. return false;
  3651. }
  3652. }
  3653. bool RenderingDevice::_dependencies_make_mutable(RID p_id, RDG::ResourceTracker *p_resource_tracker) {
  3654. bool made_mutable = false;
  3655. HashMap<RID, HashSet<RID>>::Iterator E = dependency_map.find(p_id);
  3656. if (E) {
  3657. for (RID rid : E->value) {
  3658. made_mutable = _dependency_make_mutable(rid, p_id, p_resource_tracker) || made_mutable;
  3659. }
  3660. }
  3661. return made_mutable;
  3662. }
  3663. /**************************/
  3664. /**** FRAME MANAGEMENT ****/
  3665. /**************************/
  3666. void RenderingDevice::free(RID p_id) {
  3667. _THREAD_SAFE_METHOD_
  3668. _free_dependencies(p_id); // Recursively erase dependencies first, to avoid potential API problems.
  3669. _free_internal(p_id);
  3670. }
  3671. void RenderingDevice::_free_internal(RID p_id) {
  3672. #ifdef DEV_ENABLED
  3673. String resource_name;
  3674. if (resource_names.has(p_id)) {
  3675. resource_name = resource_names[p_id];
  3676. resource_names.erase(p_id);
  3677. }
  3678. #endif
  3679. // Push everything so it's disposed of next time this frame index is processed (means, it's safe to do it).
  3680. if (texture_owner.owns(p_id)) {
  3681. Texture *texture = texture_owner.get_or_null(p_id);
  3682. RDG::ResourceTracker *draw_tracker = texture->draw_tracker;
  3683. if (draw_tracker != nullptr) {
  3684. draw_tracker->reference_count--;
  3685. if (draw_tracker->reference_count == 0) {
  3686. RDG::resource_tracker_free(draw_tracker);
  3687. if (texture->owner.is_valid() && (texture->slice_type != TEXTURE_SLICE_MAX)) {
  3688. // If this was a texture slice, erase the tracker from the map.
  3689. Texture *owner_texture = texture_owner.get_or_null(texture->owner);
  3690. if (owner_texture != nullptr) {
  3691. owner_texture->slice_trackers.erase(texture->slice_rect);
  3692. }
  3693. }
  3694. }
  3695. }
  3696. frames[frame].textures_to_dispose_of.push_back(*texture);
  3697. texture_owner.free(p_id);
  3698. } else if (framebuffer_owner.owns(p_id)) {
  3699. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_id);
  3700. frames[frame].framebuffers_to_dispose_of.push_back(*framebuffer);
  3701. if (framebuffer->invalidated_callback != nullptr) {
  3702. framebuffer->invalidated_callback(framebuffer->invalidated_callback_userdata);
  3703. }
  3704. framebuffer_owner.free(p_id);
  3705. } else if (sampler_owner.owns(p_id)) {
  3706. RDD::SamplerID sampler_driver_id = *sampler_owner.get_or_null(p_id);
  3707. frames[frame].samplers_to_dispose_of.push_back(sampler_driver_id);
  3708. sampler_owner.free(p_id);
  3709. } else if (vertex_buffer_owner.owns(p_id)) {
  3710. Buffer *vertex_buffer = vertex_buffer_owner.get_or_null(p_id);
  3711. RDG::resource_tracker_free(vertex_buffer->draw_tracker);
  3712. frames[frame].buffers_to_dispose_of.push_back(*vertex_buffer);
  3713. vertex_buffer_owner.free(p_id);
  3714. } else if (vertex_array_owner.owns(p_id)) {
  3715. vertex_array_owner.free(p_id);
  3716. } else if (index_buffer_owner.owns(p_id)) {
  3717. IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_id);
  3718. RDG::resource_tracker_free(index_buffer->draw_tracker);
  3719. frames[frame].buffers_to_dispose_of.push_back(*index_buffer);
  3720. index_buffer_owner.free(p_id);
  3721. } else if (index_array_owner.owns(p_id)) {
  3722. index_array_owner.free(p_id);
  3723. } else if (shader_owner.owns(p_id)) {
  3724. Shader *shader = shader_owner.get_or_null(p_id);
  3725. if (shader->driver_id) { // Not placeholder?
  3726. frames[frame].shaders_to_dispose_of.push_back(*shader);
  3727. }
  3728. shader_owner.free(p_id);
  3729. } else if (uniform_buffer_owner.owns(p_id)) {
  3730. Buffer *uniform_buffer = uniform_buffer_owner.get_or_null(p_id);
  3731. RDG::resource_tracker_free(uniform_buffer->draw_tracker);
  3732. frames[frame].buffers_to_dispose_of.push_back(*uniform_buffer);
  3733. uniform_buffer_owner.free(p_id);
  3734. } else if (texture_buffer_owner.owns(p_id)) {
  3735. Buffer *texture_buffer = texture_buffer_owner.get_or_null(p_id);
  3736. RDG::resource_tracker_free(texture_buffer->draw_tracker);
  3737. frames[frame].buffers_to_dispose_of.push_back(*texture_buffer);
  3738. texture_buffer_owner.free(p_id);
  3739. } else if (storage_buffer_owner.owns(p_id)) {
  3740. Buffer *storage_buffer = storage_buffer_owner.get_or_null(p_id);
  3741. RDG::resource_tracker_free(storage_buffer->draw_tracker);
  3742. frames[frame].buffers_to_dispose_of.push_back(*storage_buffer);
  3743. storage_buffer_owner.free(p_id);
  3744. } else if (uniform_set_owner.owns(p_id)) {
  3745. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id);
  3746. frames[frame].uniform_sets_to_dispose_of.push_back(*uniform_set);
  3747. uniform_set_owner.free(p_id);
  3748. if (uniform_set->invalidated_callback != nullptr) {
  3749. uniform_set->invalidated_callback(uniform_set->invalidated_callback_userdata);
  3750. }
  3751. } else if (render_pipeline_owner.owns(p_id)) {
  3752. RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_id);
  3753. frames[frame].render_pipelines_to_dispose_of.push_back(*pipeline);
  3754. render_pipeline_owner.free(p_id);
  3755. } else if (compute_pipeline_owner.owns(p_id)) {
  3756. ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_id);
  3757. frames[frame].compute_pipelines_to_dispose_of.push_back(*pipeline);
  3758. compute_pipeline_owner.free(p_id);
  3759. } else {
  3760. #ifdef DEV_ENABLED
  3761. ERR_PRINT("Attempted to free invalid ID: " + itos(p_id.get_id()) + " " + resource_name);
  3762. #else
  3763. ERR_PRINT("Attempted to free invalid ID: " + itos(p_id.get_id()));
  3764. #endif
  3765. }
  3766. }
  3767. // The full list of resources that can be named is in the VkObjectType enum.
  3768. // We just expose the resources that are owned and can be accessed easily.
  3769. void RenderingDevice::set_resource_name(RID p_id, const String &p_name) {
  3770. if (texture_owner.owns(p_id)) {
  3771. Texture *texture = texture_owner.get_or_null(p_id);
  3772. driver->set_object_name(RDD::OBJECT_TYPE_TEXTURE, texture->driver_id, p_name);
  3773. } else if (framebuffer_owner.owns(p_id)) {
  3774. //Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_id);
  3775. // Not implemented for now as the relationship between Framebuffer and RenderPass is very complex.
  3776. } else if (sampler_owner.owns(p_id)) {
  3777. RDD::SamplerID sampler_driver_id = *sampler_owner.get_or_null(p_id);
  3778. driver->set_object_name(RDD::OBJECT_TYPE_SAMPLER, sampler_driver_id, p_name);
  3779. } else if (vertex_buffer_owner.owns(p_id)) {
  3780. Buffer *vertex_buffer = vertex_buffer_owner.get_or_null(p_id);
  3781. driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, vertex_buffer->driver_id, p_name);
  3782. } else if (index_buffer_owner.owns(p_id)) {
  3783. IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_id);
  3784. driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, index_buffer->driver_id, p_name);
  3785. } else if (shader_owner.owns(p_id)) {
  3786. Shader *shader = shader_owner.get_or_null(p_id);
  3787. driver->set_object_name(RDD::OBJECT_TYPE_SHADER, shader->driver_id, p_name);
  3788. } else if (uniform_buffer_owner.owns(p_id)) {
  3789. Buffer *uniform_buffer = uniform_buffer_owner.get_or_null(p_id);
  3790. driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, uniform_buffer->driver_id, p_name);
  3791. } else if (texture_buffer_owner.owns(p_id)) {
  3792. Buffer *texture_buffer = texture_buffer_owner.get_or_null(p_id);
  3793. driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, texture_buffer->driver_id, p_name);
  3794. } else if (storage_buffer_owner.owns(p_id)) {
  3795. Buffer *storage_buffer = storage_buffer_owner.get_or_null(p_id);
  3796. driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, storage_buffer->driver_id, p_name);
  3797. } else if (uniform_set_owner.owns(p_id)) {
  3798. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id);
  3799. driver->set_object_name(RDD::OBJECT_TYPE_UNIFORM_SET, uniform_set->driver_id, p_name);
  3800. } else if (render_pipeline_owner.owns(p_id)) {
  3801. RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_id);
  3802. driver->set_object_name(RDD::OBJECT_TYPE_PIPELINE, pipeline->driver_id, p_name);
  3803. } else if (compute_pipeline_owner.owns(p_id)) {
  3804. ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_id);
  3805. driver->set_object_name(RDD::OBJECT_TYPE_PIPELINE, pipeline->driver_id, p_name);
  3806. } else {
  3807. ERR_PRINT("Attempted to name invalid ID: " + itos(p_id.get_id()));
  3808. return;
  3809. }
  3810. #ifdef DEV_ENABLED
  3811. resource_names[p_id] = p_name;
  3812. #endif
  3813. }
  3814. void RenderingDevice::draw_command_begin_label(String p_label_name, const Color &p_color) {
  3815. if (!context->is_debug_utils_enabled()) {
  3816. return;
  3817. }
  3818. draw_graph.begin_label(p_label_name, p_color);
  3819. }
  3820. #ifndef DISABLE_DEPRECATED
  3821. void RenderingDevice::draw_command_insert_label(String p_label_name, const Color &p_color) {
  3822. WARN_PRINT("Deprecated. Inserting labels no longer applies due to command reordering.");
  3823. }
  3824. #endif
  3825. void RenderingDevice::draw_command_end_label() {
  3826. draw_graph.end_label();
  3827. }
  3828. String RenderingDevice::get_device_vendor_name() const {
  3829. return _get_device_vendor_name(device);
  3830. }
  3831. String RenderingDevice::get_device_name() const {
  3832. return device.name;
  3833. }
  3834. RenderingDevice::DeviceType RenderingDevice::get_device_type() const {
  3835. return DeviceType(device.type);
  3836. }
  3837. String RenderingDevice::get_device_api_name() const {
  3838. return driver->get_api_name();
  3839. }
  3840. bool RenderingDevice::is_composite_alpha_supported() const {
  3841. return driver->is_composite_alpha_supported(main_queue);
  3842. }
  3843. String RenderingDevice::get_device_api_version() const {
  3844. return driver->get_api_version();
  3845. }
  3846. String RenderingDevice::get_device_pipeline_cache_uuid() const {
  3847. return driver->get_pipeline_cache_uuid();
  3848. }
  3849. void RenderingDevice::swap_buffers() {
  3850. _THREAD_SAFE_METHOD_
  3851. _end_frame();
  3852. _execute_frame(true);
  3853. // Advance to the next frame and begin recording again.
  3854. frame = (frame + 1) % frames.size();
  3855. _begin_frame();
  3856. }
  3857. void RenderingDevice::submit() {
  3858. _THREAD_SAFE_METHOD_
  3859. _end_frame();
  3860. _execute_frame(false);
  3861. }
  3862. void RenderingDevice::sync() {
  3863. _THREAD_SAFE_METHOD_
  3864. _begin_frame();
  3865. }
  3866. void RenderingDevice::_free_pending_resources(int p_frame) {
  3867. // Free in dependency usage order, so nothing weird happens.
  3868. // Pipelines.
  3869. while (frames[p_frame].render_pipelines_to_dispose_of.front()) {
  3870. RenderPipeline *pipeline = &frames[p_frame].render_pipelines_to_dispose_of.front()->get();
  3871. driver->pipeline_free(pipeline->driver_id);
  3872. frames[p_frame].render_pipelines_to_dispose_of.pop_front();
  3873. }
  3874. while (frames[p_frame].compute_pipelines_to_dispose_of.front()) {
  3875. ComputePipeline *pipeline = &frames[p_frame].compute_pipelines_to_dispose_of.front()->get();
  3876. driver->pipeline_free(pipeline->driver_id);
  3877. frames[p_frame].compute_pipelines_to_dispose_of.pop_front();
  3878. }
  3879. // Uniform sets.
  3880. while (frames[p_frame].uniform_sets_to_dispose_of.front()) {
  3881. UniformSet *uniform_set = &frames[p_frame].uniform_sets_to_dispose_of.front()->get();
  3882. driver->uniform_set_free(uniform_set->driver_id);
  3883. frames[p_frame].uniform_sets_to_dispose_of.pop_front();
  3884. }
  3885. // Shaders.
  3886. while (frames[p_frame].shaders_to_dispose_of.front()) {
  3887. Shader *shader = &frames[p_frame].shaders_to_dispose_of.front()->get();
  3888. driver->shader_free(shader->driver_id);
  3889. frames[p_frame].shaders_to_dispose_of.pop_front();
  3890. }
  3891. // Samplers.
  3892. while (frames[p_frame].samplers_to_dispose_of.front()) {
  3893. RDD::SamplerID sampler = frames[p_frame].samplers_to_dispose_of.front()->get();
  3894. driver->sampler_free(sampler);
  3895. frames[p_frame].samplers_to_dispose_of.pop_front();
  3896. }
  3897. // Framebuffers.
  3898. while (frames[p_frame].framebuffers_to_dispose_of.front()) {
  3899. Framebuffer *framebuffer = &frames[p_frame].framebuffers_to_dispose_of.front()->get();
  3900. for (const KeyValue<Framebuffer::VersionKey, Framebuffer::Version> &E : framebuffer->framebuffers) {
  3901. // First framebuffer, then render pass because it depends on it.
  3902. driver->framebuffer_free(E.value.framebuffer);
  3903. driver->render_pass_free(E.value.render_pass);
  3904. }
  3905. frames[p_frame].framebuffers_to_dispose_of.pop_front();
  3906. }
  3907. // Textures.
  3908. while (frames[p_frame].textures_to_dispose_of.front()) {
  3909. Texture *texture = &frames[p_frame].textures_to_dispose_of.front()->get();
  3910. if (texture->bound) {
  3911. WARN_PRINT("Deleted a texture while it was bound.");
  3912. }
  3913. texture_memory -= driver->texture_get_allocation_size(texture->driver_id);
  3914. driver->texture_free(texture->driver_id);
  3915. frames[p_frame].textures_to_dispose_of.pop_front();
  3916. }
  3917. // Buffers.
  3918. while (frames[p_frame].buffers_to_dispose_of.front()) {
  3919. Buffer &buffer = frames[p_frame].buffers_to_dispose_of.front()->get();
  3920. driver->buffer_free(buffer.driver_id);
  3921. buffer_memory -= buffer.size;
  3922. frames[p_frame].buffers_to_dispose_of.pop_front();
  3923. }
  3924. }
  3925. uint32_t RenderingDevice::get_frame_delay() const {
  3926. return frames.size();
  3927. }
  3928. uint64_t RenderingDevice::get_memory_usage(MemoryType p_type) const {
  3929. switch (p_type) {
  3930. case MEMORY_BUFFERS: {
  3931. return buffer_memory;
  3932. }
  3933. case MEMORY_TEXTURES: {
  3934. return texture_memory;
  3935. }
  3936. case MEMORY_TOTAL: {
  3937. return driver->get_total_memory_used();
  3938. }
  3939. default: {
  3940. DEV_ASSERT(false);
  3941. return 0;
  3942. }
  3943. }
  3944. }
  3945. void RenderingDevice::_begin_frame() {
  3946. // Before beginning this frame, wait on the fence if it was signaled to make sure its work is finished.
  3947. if (frames[frame].draw_fence_signaled) {
  3948. driver->fence_wait(frames[frame].draw_fence);
  3949. frames[frame].draw_fence_signaled = false;
  3950. }
  3951. // Begin recording on the frame's command buffers.
  3952. driver->begin_segment(frame, frames_drawn++);
  3953. driver->command_buffer_begin(frames[frame].setup_command_buffer);
  3954. driver->command_buffer_begin(frames[frame].draw_command_buffer);
  3955. // Reset the graph.
  3956. draw_graph.begin();
  3957. // Erase pending resources.
  3958. _free_pending_resources(frame);
  3959. // Advance staging buffer if used.
  3960. if (staging_buffer_used) {
  3961. staging_buffer_current = (staging_buffer_current + 1) % staging_buffer_blocks.size();
  3962. staging_buffer_used = false;
  3963. }
  3964. if (frames[frame].timestamp_count) {
  3965. driver->timestamp_query_pool_get_results(frames[frame].timestamp_pool, frames[frame].timestamp_count, frames[frame].timestamp_result_values.ptr());
  3966. driver->command_timestamp_query_pool_reset(frames[frame].setup_command_buffer, frames[frame].timestamp_pool, frames[frame].timestamp_count);
  3967. SWAP(frames[frame].timestamp_names, frames[frame].timestamp_result_names);
  3968. SWAP(frames[frame].timestamp_cpu_values, frames[frame].timestamp_cpu_result_values);
  3969. }
  3970. frames[frame].timestamp_result_count = frames[frame].timestamp_count;
  3971. frames[frame].timestamp_count = 0;
  3972. frames[frame].index = Engine::get_singleton()->get_frames_drawn();
  3973. }
  3974. void RenderingDevice::_end_frame() {
  3975. if (draw_list) {
  3976. ERR_PRINT("Found open draw list at the end of the frame, this should never happen (further drawing will likely not work).");
  3977. }
  3978. if (compute_list) {
  3979. ERR_PRINT("Found open compute list at the end of the frame, this should never happen (further compute will likely not work).");
  3980. }
  3981. driver->command_buffer_end(frames[frame].setup_command_buffer);
  3982. // The command buffer must be copied into a stack variable as the driver workarounds can change the command buffer in use.
  3983. RDD::CommandBufferID command_buffer = frames[frame].draw_command_buffer;
  3984. draw_graph.end(RENDER_GRAPH_REORDER, RENDER_GRAPH_FULL_BARRIERS, command_buffer, frames[frame].command_buffer_pool);
  3985. driver->command_buffer_end(command_buffer);
  3986. driver->end_segment();
  3987. }
  3988. void RenderingDevice::_execute_frame(bool p_present) {
  3989. // Check whether this frame should present the swap chains and in which queue.
  3990. const bool frame_can_present = p_present && !frames[frame].swap_chains_to_present.is_empty();
  3991. const bool separate_present_queue = main_queue != present_queue;
  3992. thread_local LocalVector<RDD::SwapChainID> swap_chains;
  3993. swap_chains.clear();
  3994. // Execute the setup command buffer.
  3995. driver->command_queue_execute_and_present(main_queue, {}, frames[frame].setup_command_buffer, frames[frame].setup_semaphore, {}, {});
  3996. // Execute command buffers and use semaphores to wait on the execution of the previous one. Normally there's only one command buffer,
  3997. // but driver workarounds can force situations where there'll be more.
  3998. uint32_t command_buffer_count = 1;
  3999. RDG::CommandBufferPool &buffer_pool = frames[frame].command_buffer_pool;
  4000. if (buffer_pool.buffers_used > 0) {
  4001. command_buffer_count += buffer_pool.buffers_used;
  4002. buffer_pool.buffers_used = 0;
  4003. }
  4004. RDD::SemaphoreID wait_semaphore = frames[frame].setup_semaphore;
  4005. for (uint32_t i = 0; i < command_buffer_count; i++) {
  4006. RDD::CommandBufferID command_buffer;
  4007. RDD::SemaphoreID signal_semaphore;
  4008. RDD::FenceID signal_fence;
  4009. if (i > 0) {
  4010. command_buffer = buffer_pool.buffers[i - 1];
  4011. signal_semaphore = buffer_pool.semaphores[i - 1];
  4012. } else {
  4013. command_buffer = frames[frame].draw_command_buffer;
  4014. signal_semaphore = frames[frame].draw_semaphore;
  4015. }
  4016. bool signal_semaphore_valid;
  4017. if (i == (command_buffer_count - 1)) {
  4018. // This is the last command buffer, it should signal the fence.
  4019. signal_fence = frames[frame].draw_fence;
  4020. signal_semaphore_valid = false;
  4021. if (frame_can_present && separate_present_queue) {
  4022. // The semaphore is required if the frame can be presented and a separate present queue is used.
  4023. signal_semaphore_valid = true;
  4024. } else if (frame_can_present) {
  4025. // Just present the swap chains as part of the last command execution.
  4026. swap_chains = frames[frame].swap_chains_to_present;
  4027. }
  4028. } else {
  4029. // Semaphores always need to be signaled if it's not the last command buffer.
  4030. signal_semaphore_valid = true;
  4031. }
  4032. driver->command_queue_execute_and_present(main_queue, wait_semaphore, command_buffer, signal_semaphore_valid ? signal_semaphore : VectorView<RDD::SemaphoreID>(), signal_fence, swap_chains);
  4033. // Make the next command buffer wait on the semaphore signaled by this one.
  4034. wait_semaphore = signal_semaphore;
  4035. }
  4036. // Indicate the fence has been signaled so the next time the frame's contents need to be used, the CPU needs to wait on the work to be completed.
  4037. frames[frame].draw_fence_signaled = true;
  4038. if (frame_can_present) {
  4039. if (separate_present_queue) {
  4040. // Issue the presentation separately if the presentation queue is different from the main queue.
  4041. driver->command_queue_execute_and_present(present_queue, wait_semaphore, {}, {}, {}, frames[frame].swap_chains_to_present);
  4042. }
  4043. frames[frame].swap_chains_to_present.clear();
  4044. }
  4045. }
  4046. void RenderingDevice::_stall_for_previous_frames() {
  4047. for (uint32_t i = 0; i < frames.size(); i++) {
  4048. if (frames[i].draw_fence_signaled) {
  4049. driver->fence_wait(frames[i].draw_fence);
  4050. frames[i].draw_fence_signaled = false;
  4051. }
  4052. }
  4053. }
  4054. void RenderingDevice::_flush_and_stall_for_all_frames() {
  4055. _stall_for_previous_frames();
  4056. _end_frame();
  4057. _execute_frame(false);
  4058. _begin_frame();
  4059. }
  4060. Error RenderingDevice::initialize(RenderingContextDriver *p_context, DisplayServer::WindowID p_main_window) {
  4061. Error err;
  4062. RenderingContextDriver::SurfaceID main_surface = 0;
  4063. const bool main_instance = (singleton == this) && (p_main_window != DisplayServer::INVALID_WINDOW_ID);
  4064. if (p_main_window != DisplayServer::INVALID_WINDOW_ID) {
  4065. // Retrieve the surface from the main window if it was specified.
  4066. main_surface = p_context->surface_get_from_window(p_main_window);
  4067. ERR_FAIL_COND_V(main_surface == 0, FAILED);
  4068. }
  4069. context = p_context;
  4070. driver = context->driver_create();
  4071. print_verbose("Devices:");
  4072. int32_t device_index = Engine::get_singleton()->get_gpu_index();
  4073. const uint32_t device_count = context->device_get_count();
  4074. const bool detect_device = (device_index < 0) || (device_index >= int32_t(device_count));
  4075. uint32_t device_type_score = 0;
  4076. for (uint32_t i = 0; i < device_count; i++) {
  4077. RenderingContextDriver::Device device_option = context->device_get(i);
  4078. String name = device_option.name;
  4079. String vendor = _get_device_vendor_name(device_option);
  4080. String type = _get_device_type_name(device_option);
  4081. bool present_supported = main_surface != 0 ? context->device_supports_present(i, main_surface) : false;
  4082. print_verbose(" #" + itos(i) + ": " + vendor + " " + name + " - " + (present_supported ? "Supported" : "Unsupported") + ", " + type);
  4083. if (detect_device && (present_supported || main_surface == 0)) {
  4084. // If a window was specified, present must be supported by the device to be available as an option.
  4085. // Assign a score for each type of device and prefer the device with the higher score.
  4086. uint32_t option_score = _get_device_type_score(device_option);
  4087. if (option_score > device_type_score) {
  4088. device_index = i;
  4089. device_type_score = option_score;
  4090. }
  4091. }
  4092. }
  4093. ERR_FAIL_COND_V_MSG((device_index < 0) || (device_index >= int32_t(device_count)), ERR_CANT_CREATE, "None of the devices supports both graphics and present queues.");
  4094. uint32_t frame_count = 1;
  4095. if (main_surface != 0) {
  4096. frame_count = MAX(2U, uint32_t(GLOBAL_GET("rendering/rendering_device/vsync/frame_queue_size")));
  4097. }
  4098. frame = 0;
  4099. frames.resize(frame_count);
  4100. max_timestamp_query_elements = 256;
  4101. device = context->device_get(device_index);
  4102. err = driver->initialize(device_index, frame_count);
  4103. ERR_FAIL_COND_V_MSG(err != OK, FAILED, "Failed to initialize driver for device.");
  4104. if (main_instance) {
  4105. // Only the singleton instance with a display should print this information.
  4106. String rendering_method;
  4107. if (OS::get_singleton()->get_current_rendering_method() == "mobile") {
  4108. rendering_method = "Forward Mobile";
  4109. } else {
  4110. rendering_method = "Forward+";
  4111. }
  4112. // Output our device version.
  4113. Engine::get_singleton()->print_header(vformat("%s %s - %s - Using Device #%d: %s - %s", get_device_api_name(), get_device_api_version(), rendering_method, device_index, _get_device_vendor_name(device), device.name));
  4114. }
  4115. // Pick the main queue family. It is worth noting we explicitly do not request the transfer bit, as apparently the specification defines
  4116. // that the existence of either the graphics or compute bit implies that the queue can also do transfer operations, but it is optional
  4117. // to indicate whether it supports them or not with the dedicated transfer bit if either is set.
  4118. BitField<RDD::CommandQueueFamilyBits> main_queue_bits;
  4119. main_queue_bits.set_flag(RDD::COMMAND_QUEUE_FAMILY_GRAPHICS_BIT);
  4120. main_queue_bits.set_flag(RDD::COMMAND_QUEUE_FAMILY_COMPUTE_BIT);
  4121. #if !FORCE_SEPARATE_PRESENT_QUEUE
  4122. // Needing to use a separate queue for presentation is an edge case that remains to be seen what hardware triggers it at all.
  4123. main_queue_family = driver->command_queue_family_get(main_queue_bits, main_surface);
  4124. if (!main_queue_family && (main_surface != 0))
  4125. #endif
  4126. {
  4127. // If it was not possible to find a main queue that supports the surface, we attempt to get two different queues instead.
  4128. main_queue_family = driver->command_queue_family_get(main_queue_bits);
  4129. present_queue_family = driver->command_queue_family_get(BitField<RDD::CommandQueueFamilyBits>(), main_surface);
  4130. ERR_FAIL_COND_V(!present_queue_family, FAILED);
  4131. }
  4132. ERR_FAIL_COND_V(!main_queue_family, FAILED);
  4133. // Create the main queue.
  4134. main_queue = driver->command_queue_create(main_queue_family, true);
  4135. ERR_FAIL_COND_V(!main_queue, FAILED);
  4136. if (present_queue_family) {
  4137. // Create the presentation queue.
  4138. present_queue = driver->command_queue_create(present_queue_family);
  4139. ERR_FAIL_COND_V(!present_queue, FAILED);
  4140. } else {
  4141. present_queue = main_queue;
  4142. }
  4143. // Create data for all the frames.
  4144. for (uint32_t i = 0; i < frames.size(); i++) {
  4145. frames[i].index = 0;
  4146. // Create command pool, command buffers, semaphores and fences.
  4147. frames[i].command_pool = driver->command_pool_create(main_queue_family, RDD::COMMAND_BUFFER_TYPE_PRIMARY);
  4148. ERR_FAIL_COND_V(!frames[i].command_pool, FAILED);
  4149. frames[i].setup_command_buffer = driver->command_buffer_create(frames[i].command_pool);
  4150. ERR_FAIL_COND_V(!frames[i].setup_command_buffer, FAILED);
  4151. frames[i].draw_command_buffer = driver->command_buffer_create(frames[i].command_pool);
  4152. ERR_FAIL_COND_V(!frames[i].draw_command_buffer, FAILED);
  4153. frames[i].setup_semaphore = driver->semaphore_create();
  4154. ERR_FAIL_COND_V(!frames[i].setup_semaphore, FAILED);
  4155. frames[i].draw_semaphore = driver->semaphore_create();
  4156. ERR_FAIL_COND_V(!frames[i].draw_semaphore, FAILED);
  4157. frames[i].draw_fence = driver->fence_create();
  4158. ERR_FAIL_COND_V(!frames[i].draw_fence, FAILED);
  4159. frames[i].draw_fence_signaled = false;
  4160. // Create query pool.
  4161. frames[i].timestamp_pool = driver->timestamp_query_pool_create(max_timestamp_query_elements);
  4162. frames[i].timestamp_names.resize(max_timestamp_query_elements);
  4163. frames[i].timestamp_cpu_values.resize(max_timestamp_query_elements);
  4164. frames[i].timestamp_count = 0;
  4165. frames[i].timestamp_result_names.resize(max_timestamp_query_elements);
  4166. frames[i].timestamp_cpu_result_values.resize(max_timestamp_query_elements);
  4167. frames[i].timestamp_result_values.resize(max_timestamp_query_elements);
  4168. frames[i].timestamp_result_count = 0;
  4169. // Assign the main queue family and command pool to the command buffer pool.
  4170. frames[i].command_buffer_pool.pool = frames[i].command_pool;
  4171. }
  4172. // Start from frame count, so everything else is immediately old.
  4173. frames_drawn = frames.size();
  4174. // Initialize recording on the first frame.
  4175. driver->begin_segment(frame, frames_drawn++);
  4176. driver->command_buffer_begin(frames[0].setup_command_buffer);
  4177. driver->command_buffer_begin(frames[0].draw_command_buffer);
  4178. // Create draw graph and start it initialized as well.
  4179. draw_graph.initialize(driver, device, frames.size(), main_queue_family, SECONDARY_COMMAND_BUFFERS_PER_FRAME);
  4180. draw_graph.begin();
  4181. for (uint32_t i = 0; i < frames.size(); i++) {
  4182. // Reset all queries in a query pool before doing any operations with them..
  4183. driver->command_timestamp_query_pool_reset(frames[0].setup_command_buffer, frames[i].timestamp_pool, max_timestamp_query_elements);
  4184. }
  4185. // Convert block size from KB.
  4186. staging_buffer_block_size = GLOBAL_GET("rendering/rendering_device/staging_buffer/block_size_kb");
  4187. staging_buffer_block_size = MAX(4u, staging_buffer_block_size);
  4188. staging_buffer_block_size *= 1024;
  4189. // Convert staging buffer size from MB.
  4190. staging_buffer_max_size = GLOBAL_GET("rendering/rendering_device/staging_buffer/max_size_mb");
  4191. staging_buffer_max_size = MAX(1u, staging_buffer_max_size);
  4192. staging_buffer_max_size *= 1024 * 1024;
  4193. if (staging_buffer_max_size < staging_buffer_block_size * 4) {
  4194. // Validate enough blocks.
  4195. staging_buffer_max_size = staging_buffer_block_size * 4;
  4196. }
  4197. texture_upload_region_size_px = GLOBAL_GET("rendering/rendering_device/staging_buffer/texture_upload_region_size_px");
  4198. texture_upload_region_size_px = nearest_power_of_2_templated(texture_upload_region_size_px);
  4199. // Ensure current staging block is valid and at least one per frame exists.
  4200. staging_buffer_current = 0;
  4201. staging_buffer_used = false;
  4202. for (uint32_t i = 0; i < frames.size(); i++) {
  4203. // Staging was never used, create a block.
  4204. err = _insert_staging_block();
  4205. ERR_CONTINUE(err != OK);
  4206. }
  4207. draw_list = nullptr;
  4208. compute_list = nullptr;
  4209. bool project_pipeline_cache_enable = GLOBAL_GET("rendering/rendering_device/pipeline_cache/enable");
  4210. if (main_instance && project_pipeline_cache_enable) {
  4211. // Only the instance that is not a local device and is also the singleton is allowed to manage a pipeline cache.
  4212. pipeline_cache_file_path = vformat("user://vulkan/pipelines.%s.%s",
  4213. OS::get_singleton()->get_current_rendering_method(),
  4214. device.name.validate_filename().replace(" ", "_").to_lower());
  4215. if (Engine::get_singleton()->is_editor_hint()) {
  4216. pipeline_cache_file_path += ".editor";
  4217. }
  4218. pipeline_cache_file_path += ".cache";
  4219. Vector<uint8_t> cache_data = _load_pipeline_cache();
  4220. pipeline_cache_enabled = driver->pipeline_cache_create(cache_data);
  4221. if (pipeline_cache_enabled) {
  4222. pipeline_cache_size = driver->pipeline_cache_query_size();
  4223. print_verbose(vformat("Startup PSO cache (%.1f MiB)", pipeline_cache_size / (1024.0f * 1024.0f)));
  4224. }
  4225. }
  4226. return OK;
  4227. }
  4228. Vector<uint8_t> RenderingDevice::_load_pipeline_cache() {
  4229. DirAccess::make_dir_recursive_absolute(pipeline_cache_file_path.get_base_dir());
  4230. if (FileAccess::exists(pipeline_cache_file_path)) {
  4231. Error file_error;
  4232. Vector<uint8_t> file_data = FileAccess::get_file_as_bytes(pipeline_cache_file_path, &file_error);
  4233. return file_data;
  4234. } else {
  4235. return Vector<uint8_t>();
  4236. }
  4237. }
  4238. void RenderingDevice::_update_pipeline_cache(bool p_closing) {
  4239. {
  4240. bool still_saving = pipeline_cache_save_task != WorkerThreadPool::INVALID_TASK_ID && !WorkerThreadPool::get_singleton()->is_task_completed(pipeline_cache_save_task);
  4241. if (still_saving) {
  4242. if (p_closing) {
  4243. WorkerThreadPool::get_singleton()->wait_for_task_completion(pipeline_cache_save_task);
  4244. pipeline_cache_save_task = WorkerThreadPool::INVALID_TASK_ID;
  4245. } else {
  4246. // We can't save until the currently running save is done. We'll retry next time; worst case, we'll save when exiting.
  4247. return;
  4248. }
  4249. }
  4250. }
  4251. {
  4252. size_t new_pipelines_cache_size = driver->pipeline_cache_query_size();
  4253. ERR_FAIL_COND(!new_pipelines_cache_size);
  4254. size_t difference = new_pipelines_cache_size - pipeline_cache_size;
  4255. bool must_save = false;
  4256. if (p_closing) {
  4257. must_save = difference > 0;
  4258. } else {
  4259. float save_interval = GLOBAL_GET("rendering/rendering_device/pipeline_cache/save_chunk_size_mb");
  4260. must_save = difference > 0 && difference / (1024.0f * 1024.0f) >= save_interval;
  4261. }
  4262. if (must_save) {
  4263. pipeline_cache_size = new_pipelines_cache_size;
  4264. } else {
  4265. return;
  4266. }
  4267. }
  4268. if (p_closing) {
  4269. _save_pipeline_cache(this);
  4270. } else {
  4271. pipeline_cache_save_task = WorkerThreadPool::get_singleton()->add_native_task(&_save_pipeline_cache, this, false, "PipelineCacheSave");
  4272. }
  4273. }
  4274. void RenderingDevice::_save_pipeline_cache(void *p_data) {
  4275. RenderingDevice *self = static_cast<RenderingDevice *>(p_data);
  4276. self->_thread_safe_.lock();
  4277. Vector<uint8_t> cache_blob = self->driver->pipeline_cache_serialize();
  4278. self->_thread_safe_.unlock();
  4279. if (cache_blob.size() == 0) {
  4280. return;
  4281. }
  4282. print_verbose(vformat("Updated PSO cache (%.1f MiB)", cache_blob.size() / (1024.0f * 1024.0f)));
  4283. Ref<FileAccess> f = FileAccess::open(self->pipeline_cache_file_path, FileAccess::WRITE, nullptr);
  4284. if (f.is_valid()) {
  4285. f->store_buffer(cache_blob);
  4286. }
  4287. }
  4288. template <typename T>
  4289. void RenderingDevice::_free_rids(T &p_owner, const char *p_type) {
  4290. List<RID> owned;
  4291. p_owner.get_owned_list(&owned);
  4292. if (owned.size()) {
  4293. if (owned.size() == 1) {
  4294. WARN_PRINT(vformat("1 RID of type \"%s\" was leaked.", p_type));
  4295. } else {
  4296. WARN_PRINT(vformat("%d RIDs of type \"%s\" were leaked.", owned.size(), p_type));
  4297. }
  4298. for (const RID &E : owned) {
  4299. #ifdef DEV_ENABLED
  4300. if (resource_names.has(E)) {
  4301. print_line(String(" - ") + resource_names[E]);
  4302. }
  4303. #endif
  4304. free(E);
  4305. }
  4306. }
  4307. }
  4308. void RenderingDevice::capture_timestamp(const String &p_name) {
  4309. ERR_FAIL_COND_MSG(draw_list != nullptr && draw_list->state.draw_count > 0, "Capturing timestamps during draw list creation is not allowed. Offending timestamp was: " + p_name);
  4310. ERR_FAIL_COND_MSG(compute_list != nullptr && compute_list->state.dispatch_count > 0, "Capturing timestamps during compute list creation is not allowed. Offending timestamp was: " + p_name);
  4311. ERR_FAIL_COND(frames[frame].timestamp_count >= max_timestamp_query_elements);
  4312. draw_graph.add_capture_timestamp(frames[frame].timestamp_pool, frames[frame].timestamp_count);
  4313. frames[frame].timestamp_names[frames[frame].timestamp_count] = p_name;
  4314. frames[frame].timestamp_cpu_values[frames[frame].timestamp_count] = OS::get_singleton()->get_ticks_usec();
  4315. frames[frame].timestamp_count++;
  4316. }
  4317. uint64_t RenderingDevice::get_driver_resource(DriverResource p_resource, RID p_rid, uint64_t p_index) {
  4318. _THREAD_SAFE_METHOD_
  4319. uint64_t driver_id = 0;
  4320. switch (p_resource) {
  4321. case DRIVER_RESOURCE_LOGICAL_DEVICE:
  4322. case DRIVER_RESOURCE_PHYSICAL_DEVICE:
  4323. case DRIVER_RESOURCE_TOPMOST_OBJECT:
  4324. break;
  4325. case DRIVER_RESOURCE_COMMAND_QUEUE:
  4326. driver_id = main_queue.id;
  4327. break;
  4328. case DRIVER_RESOURCE_QUEUE_FAMILY:
  4329. driver_id = main_queue_family.id;
  4330. break;
  4331. case DRIVER_RESOURCE_TEXTURE:
  4332. case DRIVER_RESOURCE_TEXTURE_VIEW:
  4333. case DRIVER_RESOURCE_TEXTURE_DATA_FORMAT: {
  4334. Texture *tex = texture_owner.get_or_null(p_rid);
  4335. ERR_FAIL_NULL_V(tex, 0);
  4336. driver_id = tex->driver_id.id;
  4337. } break;
  4338. case DRIVER_RESOURCE_SAMPLER: {
  4339. RDD::SamplerID *sampler_driver_id = sampler_owner.get_or_null(p_rid);
  4340. ERR_FAIL_NULL_V(sampler_driver_id, 0);
  4341. driver_id = (*sampler_driver_id).id;
  4342. } break;
  4343. case DRIVER_RESOURCE_UNIFORM_SET: {
  4344. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_rid);
  4345. ERR_FAIL_NULL_V(uniform_set, 0);
  4346. driver_id = uniform_set->driver_id.id;
  4347. } break;
  4348. case DRIVER_RESOURCE_BUFFER: {
  4349. Buffer *buffer = nullptr;
  4350. if (vertex_buffer_owner.owns(p_rid)) {
  4351. buffer = vertex_buffer_owner.get_or_null(p_rid);
  4352. } else if (index_buffer_owner.owns(p_rid)) {
  4353. buffer = index_buffer_owner.get_or_null(p_rid);
  4354. } else if (uniform_buffer_owner.owns(p_rid)) {
  4355. buffer = uniform_buffer_owner.get_or_null(p_rid);
  4356. } else if (texture_buffer_owner.owns(p_rid)) {
  4357. buffer = texture_buffer_owner.get_or_null(p_rid);
  4358. } else if (storage_buffer_owner.owns(p_rid)) {
  4359. buffer = storage_buffer_owner.get_or_null(p_rid);
  4360. }
  4361. ERR_FAIL_NULL_V(buffer, 0);
  4362. driver_id = buffer->driver_id.id;
  4363. } break;
  4364. case DRIVER_RESOURCE_COMPUTE_PIPELINE: {
  4365. ComputePipeline *compute_pipeline = compute_pipeline_owner.get_or_null(p_rid);
  4366. ERR_FAIL_NULL_V(compute_pipeline, 0);
  4367. driver_id = compute_pipeline->driver_id.id;
  4368. } break;
  4369. case DRIVER_RESOURCE_RENDER_PIPELINE: {
  4370. RenderPipeline *render_pipeline = render_pipeline_owner.get_or_null(p_rid);
  4371. ERR_FAIL_NULL_V(render_pipeline, 0);
  4372. driver_id = render_pipeline->driver_id.id;
  4373. } break;
  4374. default: {
  4375. ERR_FAIL_V(0);
  4376. } break;
  4377. }
  4378. return driver->get_resource_native_handle(p_resource, driver_id);
  4379. }
  4380. uint32_t RenderingDevice::get_captured_timestamps_count() const {
  4381. return frames[frame].timestamp_result_count;
  4382. }
  4383. uint64_t RenderingDevice::get_captured_timestamps_frame() const {
  4384. return frames[frame].index;
  4385. }
  4386. uint64_t RenderingDevice::get_captured_timestamp_gpu_time(uint32_t p_index) const {
  4387. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0);
  4388. return driver->timestamp_query_result_to_time(frames[frame].timestamp_result_values[p_index]);
  4389. }
  4390. uint64_t RenderingDevice::get_captured_timestamp_cpu_time(uint32_t p_index) const {
  4391. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0);
  4392. return frames[frame].timestamp_cpu_result_values[p_index];
  4393. }
  4394. String RenderingDevice::get_captured_timestamp_name(uint32_t p_index) const {
  4395. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, String());
  4396. return frames[frame].timestamp_result_names[p_index];
  4397. }
  4398. uint64_t RenderingDevice::limit_get(Limit p_limit) const {
  4399. return driver->limit_get(p_limit);
  4400. }
  4401. void RenderingDevice::finalize() {
  4402. if (!frames.is_empty()) {
  4403. // Wait for all frames to have finished rendering.
  4404. _flush_and_stall_for_all_frames();
  4405. }
  4406. // Delete everything the graph has created.
  4407. draw_graph.finalize();
  4408. // Free all resources.
  4409. _free_rids(render_pipeline_owner, "Pipeline");
  4410. _free_rids(compute_pipeline_owner, "Compute");
  4411. _free_rids(uniform_set_owner, "UniformSet");
  4412. _free_rids(texture_buffer_owner, "TextureBuffer");
  4413. _free_rids(storage_buffer_owner, "StorageBuffer");
  4414. _free_rids(uniform_buffer_owner, "UniformBuffer");
  4415. _free_rids(shader_owner, "Shader");
  4416. _free_rids(index_array_owner, "IndexArray");
  4417. _free_rids(index_buffer_owner, "IndexBuffer");
  4418. _free_rids(vertex_array_owner, "VertexArray");
  4419. _free_rids(vertex_buffer_owner, "VertexBuffer");
  4420. _free_rids(framebuffer_owner, "Framebuffer");
  4421. _free_rids(sampler_owner, "Sampler");
  4422. {
  4423. // For textures it's a bit more difficult because they may be shared.
  4424. List<RID> owned;
  4425. texture_owner.get_owned_list(&owned);
  4426. if (owned.size()) {
  4427. if (owned.size() == 1) {
  4428. WARN_PRINT("1 RID of type \"Texture\" was leaked.");
  4429. } else {
  4430. WARN_PRINT(vformat("%d RIDs of type \"Texture\" were leaked.", owned.size()));
  4431. }
  4432. // Free shared first.
  4433. for (List<RID>::Element *E = owned.front(); E;) {
  4434. List<RID>::Element *N = E->next();
  4435. if (texture_is_shared(E->get())) {
  4436. #ifdef DEV_ENABLED
  4437. if (resource_names.has(E->get())) {
  4438. print_line(String(" - ") + resource_names[E->get()]);
  4439. }
  4440. #endif
  4441. free(E->get());
  4442. owned.erase(E);
  4443. }
  4444. E = N;
  4445. }
  4446. // Free non shared second, this will avoid an error trying to free unexisting textures due to dependencies.
  4447. for (const RID &E : owned) {
  4448. #ifdef DEV_ENABLED
  4449. if (resource_names.has(E)) {
  4450. print_line(String(" - ") + resource_names[E]);
  4451. }
  4452. #endif
  4453. free(E);
  4454. }
  4455. }
  4456. }
  4457. // Free everything pending.
  4458. for (uint32_t i = 0; i < frames.size(); i++) {
  4459. int f = (frame + i) % frames.size();
  4460. _free_pending_resources(f);
  4461. driver->command_pool_free(frames[i].command_pool);
  4462. driver->timestamp_query_pool_free(frames[i].timestamp_pool);
  4463. driver->semaphore_free(frames[i].setup_semaphore);
  4464. driver->semaphore_free(frames[i].draw_semaphore);
  4465. driver->fence_free(frames[i].draw_fence);
  4466. RDG::CommandBufferPool &buffer_pool = frames[i].command_buffer_pool;
  4467. for (uint32_t j = 0; j < buffer_pool.buffers.size(); j++) {
  4468. driver->semaphore_free(buffer_pool.semaphores[j]);
  4469. }
  4470. }
  4471. if (pipeline_cache_enabled) {
  4472. _update_pipeline_cache(true);
  4473. driver->pipeline_cache_free();
  4474. }
  4475. frames.clear();
  4476. for (int i = 0; i < staging_buffer_blocks.size(); i++) {
  4477. driver->buffer_free(staging_buffer_blocks[i].driver_id);
  4478. }
  4479. while (vertex_formats.size()) {
  4480. HashMap<VertexFormatID, VertexDescriptionCache>::Iterator temp = vertex_formats.begin();
  4481. driver->vertex_format_free(temp->value.driver_id);
  4482. vertex_formats.remove(temp);
  4483. }
  4484. for (KeyValue<FramebufferFormatID, FramebufferFormat> &E : framebuffer_formats) {
  4485. driver->render_pass_free(E.value.render_pass);
  4486. }
  4487. framebuffer_formats.clear();
  4488. // Delete the swap chains created for the screens.
  4489. for (const KeyValue<DisplayServer::WindowID, RDD::SwapChainID> &it : screen_swap_chains) {
  4490. driver->swap_chain_free(it.value);
  4491. }
  4492. screen_swap_chains.clear();
  4493. // Delete the command queues.
  4494. if (present_queue) {
  4495. if (main_queue != present_queue) {
  4496. // Only delete the present queue if it's unique.
  4497. driver->command_queue_free(present_queue);
  4498. }
  4499. present_queue = RDD::CommandQueueID();
  4500. }
  4501. if (main_queue) {
  4502. driver->command_queue_free(main_queue);
  4503. main_queue = RDD::CommandQueueID();
  4504. }
  4505. // Delete the driver once everything else has been deleted.
  4506. if (driver != nullptr) {
  4507. context->driver_free(driver);
  4508. driver = nullptr;
  4509. }
  4510. // All these should be clear at this point.
  4511. ERR_FAIL_COND(dependency_map.size());
  4512. ERR_FAIL_COND(reverse_dependency_map.size());
  4513. }
  4514. RenderingDevice *RenderingDevice::create_local_device() {
  4515. RenderingDevice *rd = memnew(RenderingDevice);
  4516. rd->initialize(context);
  4517. return rd;
  4518. }
  4519. bool RenderingDevice::has_feature(const Features p_feature) const {
  4520. return driver->has_feature(p_feature);
  4521. }
  4522. void RenderingDevice::_bind_methods() {
  4523. ClassDB::bind_method(D_METHOD("texture_create", "format", "view", "data"), &RenderingDevice::_texture_create, DEFVAL(Array()));
  4524. ClassDB::bind_method(D_METHOD("texture_create_shared", "view", "with_texture"), &RenderingDevice::_texture_create_shared);
  4525. ClassDB::bind_method(D_METHOD("texture_create_shared_from_slice", "view", "with_texture", "layer", "mipmap", "mipmaps", "slice_type"), &RenderingDevice::_texture_create_shared_from_slice, DEFVAL(1), DEFVAL(TEXTURE_SLICE_2D));
  4526. ClassDB::bind_method(D_METHOD("texture_create_from_extension", "type", "format", "samples", "usage_flags", "image", "width", "height", "depth", "layers"), &RenderingDevice::texture_create_from_extension);
  4527. ClassDB::bind_method(D_METHOD("texture_update", "texture", "layer", "data"), &RenderingDevice::texture_update);
  4528. ClassDB::bind_method(D_METHOD("texture_get_data", "texture", "layer"), &RenderingDevice::texture_get_data);
  4529. ClassDB::bind_method(D_METHOD("texture_is_format_supported_for_usage", "format", "usage_flags"), &RenderingDevice::texture_is_format_supported_for_usage);
  4530. ClassDB::bind_method(D_METHOD("texture_is_shared", "texture"), &RenderingDevice::texture_is_shared);
  4531. ClassDB::bind_method(D_METHOD("texture_is_valid", "texture"), &RenderingDevice::texture_is_valid);
  4532. ClassDB::bind_method(D_METHOD("texture_copy", "from_texture", "to_texture", "from_pos", "to_pos", "size", "src_mipmap", "dst_mipmap", "src_layer", "dst_layer"), &RenderingDevice::texture_copy);
  4533. ClassDB::bind_method(D_METHOD("texture_clear", "texture", "color", "base_mipmap", "mipmap_count", "base_layer", "layer_count"), &RenderingDevice::texture_clear);
  4534. ClassDB::bind_method(D_METHOD("texture_resolve_multisample", "from_texture", "to_texture"), &RenderingDevice::texture_resolve_multisample);
  4535. ClassDB::bind_method(D_METHOD("texture_get_format", "texture"), &RenderingDevice::_texture_get_format);
  4536. #ifndef DISABLE_DEPRECATED
  4537. ClassDB::bind_method(D_METHOD("texture_get_native_handle", "texture"), &RenderingDevice::texture_get_native_handle);
  4538. #endif
  4539. ClassDB::bind_method(D_METHOD("framebuffer_format_create", "attachments", "view_count"), &RenderingDevice::_framebuffer_format_create, DEFVAL(1));
  4540. ClassDB::bind_method(D_METHOD("framebuffer_format_create_multipass", "attachments", "passes", "view_count"), &RenderingDevice::_framebuffer_format_create_multipass, DEFVAL(1));
  4541. ClassDB::bind_method(D_METHOD("framebuffer_format_create_empty", "samples"), &RenderingDevice::framebuffer_format_create_empty, DEFVAL(TEXTURE_SAMPLES_1));
  4542. ClassDB::bind_method(D_METHOD("framebuffer_format_get_texture_samples", "format", "render_pass"), &RenderingDevice::framebuffer_format_get_texture_samples, DEFVAL(0));
  4543. ClassDB::bind_method(D_METHOD("framebuffer_create", "textures", "validate_with_format", "view_count"), &RenderingDevice::_framebuffer_create, DEFVAL(INVALID_FORMAT_ID), DEFVAL(1));
  4544. ClassDB::bind_method(D_METHOD("framebuffer_create_multipass", "textures", "passes", "validate_with_format", "view_count"), &RenderingDevice::_framebuffer_create_multipass, DEFVAL(INVALID_FORMAT_ID), DEFVAL(1));
  4545. ClassDB::bind_method(D_METHOD("framebuffer_create_empty", "size", "samples", "validate_with_format"), &RenderingDevice::framebuffer_create_empty, DEFVAL(TEXTURE_SAMPLES_1), DEFVAL(INVALID_FORMAT_ID));
  4546. ClassDB::bind_method(D_METHOD("framebuffer_get_format", "framebuffer"), &RenderingDevice::framebuffer_get_format);
  4547. ClassDB::bind_method(D_METHOD("framebuffer_is_valid", "framebuffer"), &RenderingDevice::framebuffer_is_valid);
  4548. ClassDB::bind_method(D_METHOD("sampler_create", "state"), &RenderingDevice::_sampler_create);
  4549. ClassDB::bind_method(D_METHOD("sampler_is_format_supported_for_filter", "format", "sampler_filter"), &RenderingDevice::sampler_is_format_supported_for_filter);
  4550. ClassDB::bind_method(D_METHOD("vertex_buffer_create", "size_bytes", "data", "use_as_storage"), &RenderingDevice::vertex_buffer_create, DEFVAL(Vector<uint8_t>()), DEFVAL(false));
  4551. ClassDB::bind_method(D_METHOD("vertex_format_create", "vertex_descriptions"), &RenderingDevice::_vertex_format_create);
  4552. ClassDB::bind_method(D_METHOD("vertex_array_create", "vertex_count", "vertex_format", "src_buffers", "offsets"), &RenderingDevice::_vertex_array_create, DEFVAL(Vector<int64_t>()));
  4553. ClassDB::bind_method(D_METHOD("index_buffer_create", "size_indices", "format", "data", "use_restart_indices"), &RenderingDevice::index_buffer_create, DEFVAL(Vector<uint8_t>()), DEFVAL(false));
  4554. ClassDB::bind_method(D_METHOD("index_array_create", "index_buffer", "index_offset", "index_count"), &RenderingDevice::index_array_create);
  4555. ClassDB::bind_method(D_METHOD("shader_compile_spirv_from_source", "shader_source", "allow_cache"), &RenderingDevice::_shader_compile_spirv_from_source, DEFVAL(true));
  4556. ClassDB::bind_method(D_METHOD("shader_compile_binary_from_spirv", "spirv_data", "name"), &RenderingDevice::_shader_compile_binary_from_spirv, DEFVAL(""));
  4557. ClassDB::bind_method(D_METHOD("shader_create_from_spirv", "spirv_data", "name"), &RenderingDevice::_shader_create_from_spirv, DEFVAL(""));
  4558. ClassDB::bind_method(D_METHOD("shader_create_from_bytecode", "binary_data", "placeholder_rid"), &RenderingDevice::shader_create_from_bytecode, DEFVAL(RID()));
  4559. ClassDB::bind_method(D_METHOD("shader_create_placeholder"), &RenderingDevice::shader_create_placeholder);
  4560. ClassDB::bind_method(D_METHOD("shader_get_vertex_input_attribute_mask", "shader"), &RenderingDevice::shader_get_vertex_input_attribute_mask);
  4561. ClassDB::bind_method(D_METHOD("uniform_buffer_create", "size_bytes", "data"), &RenderingDevice::uniform_buffer_create, DEFVAL(Vector<uint8_t>()));
  4562. ClassDB::bind_method(D_METHOD("storage_buffer_create", "size_bytes", "data", "usage"), &RenderingDevice::storage_buffer_create, DEFVAL(Vector<uint8_t>()), DEFVAL(0));
  4563. ClassDB::bind_method(D_METHOD("texture_buffer_create", "size_bytes", "format", "data"), &RenderingDevice::texture_buffer_create, DEFVAL(Vector<uint8_t>()));
  4564. ClassDB::bind_method(D_METHOD("uniform_set_create", "uniforms", "shader", "shader_set"), &RenderingDevice::_uniform_set_create);
  4565. ClassDB::bind_method(D_METHOD("uniform_set_is_valid", "uniform_set"), &RenderingDevice::uniform_set_is_valid);
  4566. ClassDB::bind_method(D_METHOD("buffer_copy", "src_buffer", "dst_buffer", "src_offset", "dst_offset", "size"), &RenderingDevice::buffer_copy);
  4567. ClassDB::bind_method(D_METHOD("buffer_update", "buffer", "offset", "size_bytes", "data"), &RenderingDevice::_buffer_update_bind);
  4568. ClassDB::bind_method(D_METHOD("buffer_clear", "buffer", "offset", "size_bytes"), &RenderingDevice::buffer_clear);
  4569. ClassDB::bind_method(D_METHOD("buffer_get_data", "buffer", "offset_bytes", "size_bytes"), &RenderingDevice::buffer_get_data, DEFVAL(0), DEFVAL(0));
  4570. ClassDB::bind_method(D_METHOD("render_pipeline_create", "shader", "framebuffer_format", "vertex_format", "primitive", "rasterization_state", "multisample_state", "stencil_state", "color_blend_state", "dynamic_state_flags", "for_render_pass", "specialization_constants"), &RenderingDevice::_render_pipeline_create, DEFVAL(0), DEFVAL(0), DEFVAL(TypedArray<RDPipelineSpecializationConstant>()));
  4571. ClassDB::bind_method(D_METHOD("render_pipeline_is_valid", "render_pipeline"), &RenderingDevice::render_pipeline_is_valid);
  4572. ClassDB::bind_method(D_METHOD("compute_pipeline_create", "shader", "specialization_constants"), &RenderingDevice::_compute_pipeline_create, DEFVAL(TypedArray<RDPipelineSpecializationConstant>()));
  4573. ClassDB::bind_method(D_METHOD("compute_pipeline_is_valid", "compute_pipeline"), &RenderingDevice::compute_pipeline_is_valid);
  4574. ClassDB::bind_method(D_METHOD("screen_get_width", "screen"), &RenderingDevice::screen_get_width, DEFVAL(DisplayServer::MAIN_WINDOW_ID));
  4575. ClassDB::bind_method(D_METHOD("screen_get_height", "screen"), &RenderingDevice::screen_get_height, DEFVAL(DisplayServer::MAIN_WINDOW_ID));
  4576. ClassDB::bind_method(D_METHOD("screen_get_framebuffer_format", "screen"), &RenderingDevice::screen_get_framebuffer_format, DEFVAL(DisplayServer::MAIN_WINDOW_ID));
  4577. ClassDB::bind_method(D_METHOD("draw_list_begin_for_screen", "screen", "clear_color"), &RenderingDevice::draw_list_begin_for_screen, DEFVAL(DisplayServer::MAIN_WINDOW_ID), DEFVAL(Color()));
  4578. ClassDB::bind_method(D_METHOD("draw_list_begin", "framebuffer", "initial_color_action", "final_color_action", "initial_depth_action", "final_depth_action", "clear_color_values", "clear_depth", "clear_stencil", "region"), &RenderingDevice::draw_list_begin, DEFVAL(Vector<Color>()), DEFVAL(1.0), DEFVAL(0), DEFVAL(Rect2()));
  4579. #ifndef DISABLE_DEPRECATED
  4580. ClassDB::bind_method(D_METHOD("draw_list_begin_split", "framebuffer", "splits", "initial_color_action", "final_color_action", "initial_depth_action", "final_depth_action", "clear_color_values", "clear_depth", "clear_stencil", "region", "storage_textures"), &RenderingDevice::_draw_list_begin_split, DEFVAL(Vector<Color>()), DEFVAL(1.0), DEFVAL(0), DEFVAL(Rect2()), DEFVAL(TypedArray<RID>()));
  4581. #endif
  4582. ClassDB::bind_method(D_METHOD("draw_list_set_blend_constants", "draw_list", "color"), &RenderingDevice::draw_list_set_blend_constants);
  4583. ClassDB::bind_method(D_METHOD("draw_list_bind_render_pipeline", "draw_list", "render_pipeline"), &RenderingDevice::draw_list_bind_render_pipeline);
  4584. ClassDB::bind_method(D_METHOD("draw_list_bind_uniform_set", "draw_list", "uniform_set", "set_index"), &RenderingDevice::draw_list_bind_uniform_set);
  4585. ClassDB::bind_method(D_METHOD("draw_list_bind_vertex_array", "draw_list", "vertex_array"), &RenderingDevice::draw_list_bind_vertex_array);
  4586. ClassDB::bind_method(D_METHOD("draw_list_bind_index_array", "draw_list", "index_array"), &RenderingDevice::draw_list_bind_index_array);
  4587. ClassDB::bind_method(D_METHOD("draw_list_set_push_constant", "draw_list", "buffer", "size_bytes"), &RenderingDevice::_draw_list_set_push_constant);
  4588. ClassDB::bind_method(D_METHOD("draw_list_draw", "draw_list", "use_indices", "instances", "procedural_vertex_count"), &RenderingDevice::draw_list_draw, DEFVAL(0));
  4589. ClassDB::bind_method(D_METHOD("draw_list_enable_scissor", "draw_list", "rect"), &RenderingDevice::draw_list_enable_scissor, DEFVAL(Rect2()));
  4590. ClassDB::bind_method(D_METHOD("draw_list_disable_scissor", "draw_list"), &RenderingDevice::draw_list_disable_scissor);
  4591. ClassDB::bind_method(D_METHOD("draw_list_switch_to_next_pass"), &RenderingDevice::draw_list_switch_to_next_pass);
  4592. #ifndef DISABLE_DEPRECATED
  4593. ClassDB::bind_method(D_METHOD("draw_list_switch_to_next_pass_split", "splits"), &RenderingDevice::_draw_list_switch_to_next_pass_split);
  4594. #endif
  4595. ClassDB::bind_method(D_METHOD("draw_list_end"), &RenderingDevice::draw_list_end);
  4596. ClassDB::bind_method(D_METHOD("compute_list_begin"), &RenderingDevice::compute_list_begin);
  4597. ClassDB::bind_method(D_METHOD("compute_list_bind_compute_pipeline", "compute_list", "compute_pipeline"), &RenderingDevice::compute_list_bind_compute_pipeline);
  4598. ClassDB::bind_method(D_METHOD("compute_list_set_push_constant", "compute_list", "buffer", "size_bytes"), &RenderingDevice::_compute_list_set_push_constant);
  4599. ClassDB::bind_method(D_METHOD("compute_list_bind_uniform_set", "compute_list", "uniform_set", "set_index"), &RenderingDevice::compute_list_bind_uniform_set);
  4600. ClassDB::bind_method(D_METHOD("compute_list_dispatch", "compute_list", "x_groups", "y_groups", "z_groups"), &RenderingDevice::compute_list_dispatch);
  4601. ClassDB::bind_method(D_METHOD("compute_list_dispatch_indirect", "compute_list", "buffer", "offset"), &RenderingDevice::compute_list_dispatch_indirect);
  4602. ClassDB::bind_method(D_METHOD("compute_list_add_barrier", "compute_list"), &RenderingDevice::compute_list_add_barrier);
  4603. ClassDB::bind_method(D_METHOD("compute_list_end"), &RenderingDevice::compute_list_end);
  4604. ClassDB::bind_method(D_METHOD("free_rid", "rid"), &RenderingDevice::free);
  4605. ClassDB::bind_method(D_METHOD("capture_timestamp", "name"), &RenderingDevice::capture_timestamp);
  4606. ClassDB::bind_method(D_METHOD("get_captured_timestamps_count"), &RenderingDevice::get_captured_timestamps_count);
  4607. ClassDB::bind_method(D_METHOD("get_captured_timestamps_frame"), &RenderingDevice::get_captured_timestamps_frame);
  4608. ClassDB::bind_method(D_METHOD("get_captured_timestamp_gpu_time", "index"), &RenderingDevice::get_captured_timestamp_gpu_time);
  4609. ClassDB::bind_method(D_METHOD("get_captured_timestamp_cpu_time", "index"), &RenderingDevice::get_captured_timestamp_cpu_time);
  4610. ClassDB::bind_method(D_METHOD("get_captured_timestamp_name", "index"), &RenderingDevice::get_captured_timestamp_name);
  4611. ClassDB::bind_method(D_METHOD("limit_get", "limit"), &RenderingDevice::limit_get);
  4612. ClassDB::bind_method(D_METHOD("get_frame_delay"), &RenderingDevice::get_frame_delay);
  4613. ClassDB::bind_method(D_METHOD("submit"), &RenderingDevice::submit);
  4614. ClassDB::bind_method(D_METHOD("sync"), &RenderingDevice::sync);
  4615. #ifndef DISABLE_DEPRECATED
  4616. ClassDB::bind_method(D_METHOD("barrier", "from", "to"), &RenderingDevice::barrier, DEFVAL(BARRIER_MASK_ALL_BARRIERS), DEFVAL(BARRIER_MASK_ALL_BARRIERS));
  4617. ClassDB::bind_method(D_METHOD("full_barrier"), &RenderingDevice::full_barrier);
  4618. #endif
  4619. ClassDB::bind_method(D_METHOD("create_local_device"), &RenderingDevice::create_local_device);
  4620. ClassDB::bind_method(D_METHOD("set_resource_name", "id", "name"), &RenderingDevice::set_resource_name);
  4621. ClassDB::bind_method(D_METHOD("draw_command_begin_label", "name", "color"), &RenderingDevice::draw_command_begin_label);
  4622. #ifndef DISABLE_DEPRECATED
  4623. ClassDB::bind_method(D_METHOD("draw_command_insert_label", "name", "color"), &RenderingDevice::draw_command_insert_label);
  4624. #endif
  4625. ClassDB::bind_method(D_METHOD("draw_command_end_label"), &RenderingDevice::draw_command_end_label);
  4626. ClassDB::bind_method(D_METHOD("get_device_vendor_name"), &RenderingDevice::get_device_vendor_name);
  4627. ClassDB::bind_method(D_METHOD("get_device_name"), &RenderingDevice::get_device_name);
  4628. ClassDB::bind_method(D_METHOD("get_device_pipeline_cache_uuid"), &RenderingDevice::get_device_pipeline_cache_uuid);
  4629. ClassDB::bind_method(D_METHOD("get_memory_usage", "type"), &RenderingDevice::get_memory_usage);
  4630. ClassDB::bind_method(D_METHOD("get_driver_resource", "resource", "rid", "index"), &RenderingDevice::get_driver_resource);
  4631. BIND_ENUM_CONSTANT(DEVICE_TYPE_OTHER);
  4632. BIND_ENUM_CONSTANT(DEVICE_TYPE_INTEGRATED_GPU);
  4633. BIND_ENUM_CONSTANT(DEVICE_TYPE_DISCRETE_GPU);
  4634. BIND_ENUM_CONSTANT(DEVICE_TYPE_VIRTUAL_GPU);
  4635. BIND_ENUM_CONSTANT(DEVICE_TYPE_CPU);
  4636. BIND_ENUM_CONSTANT(DEVICE_TYPE_MAX);
  4637. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_LOGICAL_DEVICE);
  4638. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_PHYSICAL_DEVICE);
  4639. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_TOPMOST_OBJECT);
  4640. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_COMMAND_QUEUE);
  4641. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_QUEUE_FAMILY);
  4642. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_TEXTURE);
  4643. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_TEXTURE_VIEW);
  4644. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_TEXTURE_DATA_FORMAT);
  4645. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_SAMPLER);
  4646. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_UNIFORM_SET);
  4647. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_BUFFER);
  4648. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_COMPUTE_PIPELINE);
  4649. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_RENDER_PIPELINE);
  4650. #ifndef DISABLE_DEPRECATED
  4651. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_DEVICE);
  4652. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_PHYSICAL_DEVICE);
  4653. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_INSTANCE);
  4654. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_QUEUE);
  4655. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_QUEUE_FAMILY_INDEX);
  4656. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_IMAGE);
  4657. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_IMAGE_VIEW);
  4658. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_IMAGE_NATIVE_TEXTURE_FORMAT);
  4659. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_SAMPLER);
  4660. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_DESCRIPTOR_SET);
  4661. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_BUFFER);
  4662. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_COMPUTE_PIPELINE);
  4663. BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_RENDER_PIPELINE);
  4664. #endif
  4665. BIND_ENUM_CONSTANT(DATA_FORMAT_R4G4_UNORM_PACK8);
  4666. BIND_ENUM_CONSTANT(DATA_FORMAT_R4G4B4A4_UNORM_PACK16);
  4667. BIND_ENUM_CONSTANT(DATA_FORMAT_B4G4R4A4_UNORM_PACK16);
  4668. BIND_ENUM_CONSTANT(DATA_FORMAT_R5G6B5_UNORM_PACK16);
  4669. BIND_ENUM_CONSTANT(DATA_FORMAT_B5G6R5_UNORM_PACK16);
  4670. BIND_ENUM_CONSTANT(DATA_FORMAT_R5G5B5A1_UNORM_PACK16);
  4671. BIND_ENUM_CONSTANT(DATA_FORMAT_B5G5R5A1_UNORM_PACK16);
  4672. BIND_ENUM_CONSTANT(DATA_FORMAT_A1R5G5B5_UNORM_PACK16);
  4673. BIND_ENUM_CONSTANT(DATA_FORMAT_R8_UNORM);
  4674. BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SNORM);
  4675. BIND_ENUM_CONSTANT(DATA_FORMAT_R8_USCALED);
  4676. BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SSCALED);
  4677. BIND_ENUM_CONSTANT(DATA_FORMAT_R8_UINT);
  4678. BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SINT);
  4679. BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SRGB);
  4680. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_UNORM);
  4681. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SNORM);
  4682. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_USCALED);
  4683. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SSCALED);
  4684. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_UINT);
  4685. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SINT);
  4686. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SRGB);
  4687. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_UNORM);
  4688. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SNORM);
  4689. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_USCALED);
  4690. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SSCALED);
  4691. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_UINT);
  4692. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SINT);
  4693. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SRGB);
  4694. BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_UNORM);
  4695. BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SNORM);
  4696. BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_USCALED);
  4697. BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SSCALED);
  4698. BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_UINT);
  4699. BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SINT);
  4700. BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SRGB);
  4701. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_UNORM);
  4702. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SNORM);
  4703. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_USCALED);
  4704. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SSCALED);
  4705. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_UINT);
  4706. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SINT);
  4707. BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SRGB);
  4708. BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_UNORM);
  4709. BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SNORM);
  4710. BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_USCALED);
  4711. BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SSCALED);
  4712. BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_UINT);
  4713. BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SINT);
  4714. BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SRGB);
  4715. BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_UNORM_PACK32);
  4716. BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SNORM_PACK32);
  4717. BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_USCALED_PACK32);
  4718. BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SSCALED_PACK32);
  4719. BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_UINT_PACK32);
  4720. BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SINT_PACK32);
  4721. BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SRGB_PACK32);
  4722. BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_UNORM_PACK32);
  4723. BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_SNORM_PACK32);
  4724. BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_USCALED_PACK32);
  4725. BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_SSCALED_PACK32);
  4726. BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_UINT_PACK32);
  4727. BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_SINT_PACK32);
  4728. BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_UNORM_PACK32);
  4729. BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_SNORM_PACK32);
  4730. BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_USCALED_PACK32);
  4731. BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_SSCALED_PACK32);
  4732. BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_UINT_PACK32);
  4733. BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_SINT_PACK32);
  4734. BIND_ENUM_CONSTANT(DATA_FORMAT_R16_UNORM);
  4735. BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SNORM);
  4736. BIND_ENUM_CONSTANT(DATA_FORMAT_R16_USCALED);
  4737. BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SSCALED);
  4738. BIND_ENUM_CONSTANT(DATA_FORMAT_R16_UINT);
  4739. BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SINT);
  4740. BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SFLOAT);
  4741. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_UNORM);
  4742. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SNORM);
  4743. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_USCALED);
  4744. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SSCALED);
  4745. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_UINT);
  4746. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SINT);
  4747. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SFLOAT);
  4748. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_UNORM);
  4749. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SNORM);
  4750. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_USCALED);
  4751. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SSCALED);
  4752. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_UINT);
  4753. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SINT);
  4754. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SFLOAT);
  4755. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_UNORM);
  4756. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SNORM);
  4757. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_USCALED);
  4758. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SSCALED);
  4759. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_UINT);
  4760. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SINT);
  4761. BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SFLOAT);
  4762. BIND_ENUM_CONSTANT(DATA_FORMAT_R32_UINT);
  4763. BIND_ENUM_CONSTANT(DATA_FORMAT_R32_SINT);
  4764. BIND_ENUM_CONSTANT(DATA_FORMAT_R32_SFLOAT);
  4765. BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32_UINT);
  4766. BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32_SINT);
  4767. BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32_SFLOAT);
  4768. BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32_UINT);
  4769. BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32_SINT);
  4770. BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32_SFLOAT);
  4771. BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32A32_UINT);
  4772. BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32A32_SINT);
  4773. BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32A32_SFLOAT);
  4774. BIND_ENUM_CONSTANT(DATA_FORMAT_R64_UINT);
  4775. BIND_ENUM_CONSTANT(DATA_FORMAT_R64_SINT);
  4776. BIND_ENUM_CONSTANT(DATA_FORMAT_R64_SFLOAT);
  4777. BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64_UINT);
  4778. BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64_SINT);
  4779. BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64_SFLOAT);
  4780. BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64_UINT);
  4781. BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64_SINT);
  4782. BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64_SFLOAT);
  4783. BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64A64_UINT);
  4784. BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64A64_SINT);
  4785. BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64A64_SFLOAT);
  4786. BIND_ENUM_CONSTANT(DATA_FORMAT_B10G11R11_UFLOAT_PACK32);
  4787. BIND_ENUM_CONSTANT(DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32);
  4788. BIND_ENUM_CONSTANT(DATA_FORMAT_D16_UNORM);
  4789. BIND_ENUM_CONSTANT(DATA_FORMAT_X8_D24_UNORM_PACK32);
  4790. BIND_ENUM_CONSTANT(DATA_FORMAT_D32_SFLOAT);
  4791. BIND_ENUM_CONSTANT(DATA_FORMAT_S8_UINT);
  4792. BIND_ENUM_CONSTANT(DATA_FORMAT_D16_UNORM_S8_UINT);
  4793. BIND_ENUM_CONSTANT(DATA_FORMAT_D24_UNORM_S8_UINT);
  4794. BIND_ENUM_CONSTANT(DATA_FORMAT_D32_SFLOAT_S8_UINT);
  4795. BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGB_UNORM_BLOCK);
  4796. BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGB_SRGB_BLOCK);
  4797. BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGBA_UNORM_BLOCK);
  4798. BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGBA_SRGB_BLOCK);
  4799. BIND_ENUM_CONSTANT(DATA_FORMAT_BC2_UNORM_BLOCK);
  4800. BIND_ENUM_CONSTANT(DATA_FORMAT_BC2_SRGB_BLOCK);
  4801. BIND_ENUM_CONSTANT(DATA_FORMAT_BC3_UNORM_BLOCK);
  4802. BIND_ENUM_CONSTANT(DATA_FORMAT_BC3_SRGB_BLOCK);
  4803. BIND_ENUM_CONSTANT(DATA_FORMAT_BC4_UNORM_BLOCK);
  4804. BIND_ENUM_CONSTANT(DATA_FORMAT_BC4_SNORM_BLOCK);
  4805. BIND_ENUM_CONSTANT(DATA_FORMAT_BC5_UNORM_BLOCK);
  4806. BIND_ENUM_CONSTANT(DATA_FORMAT_BC5_SNORM_BLOCK);
  4807. BIND_ENUM_CONSTANT(DATA_FORMAT_BC6H_UFLOAT_BLOCK);
  4808. BIND_ENUM_CONSTANT(DATA_FORMAT_BC6H_SFLOAT_BLOCK);
  4809. BIND_ENUM_CONSTANT(DATA_FORMAT_BC7_UNORM_BLOCK);
  4810. BIND_ENUM_CONSTANT(DATA_FORMAT_BC7_SRGB_BLOCK);
  4811. BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK);
  4812. BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK);
  4813. BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK);
  4814. BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK);
  4815. BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK);
  4816. BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK);
  4817. BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11_UNORM_BLOCK);
  4818. BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11_SNORM_BLOCK);
  4819. BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11G11_UNORM_BLOCK);
  4820. BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11G11_SNORM_BLOCK);
  4821. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_4x4_UNORM_BLOCK);
  4822. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_4x4_SRGB_BLOCK);
  4823. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x4_UNORM_BLOCK);
  4824. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x4_SRGB_BLOCK);
  4825. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x5_UNORM_BLOCK);
  4826. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x5_SRGB_BLOCK);
  4827. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x5_UNORM_BLOCK);
  4828. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x5_SRGB_BLOCK);
  4829. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x6_UNORM_BLOCK);
  4830. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x6_SRGB_BLOCK);
  4831. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x5_UNORM_BLOCK);
  4832. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x5_SRGB_BLOCK);
  4833. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x6_UNORM_BLOCK);
  4834. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x6_SRGB_BLOCK);
  4835. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x8_UNORM_BLOCK);
  4836. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x8_SRGB_BLOCK);
  4837. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x5_UNORM_BLOCK);
  4838. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x5_SRGB_BLOCK);
  4839. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x6_UNORM_BLOCK);
  4840. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x6_SRGB_BLOCK);
  4841. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x8_UNORM_BLOCK);
  4842. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x8_SRGB_BLOCK);
  4843. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x10_UNORM_BLOCK);
  4844. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x10_SRGB_BLOCK);
  4845. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x10_UNORM_BLOCK);
  4846. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x10_SRGB_BLOCK);
  4847. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x12_UNORM_BLOCK);
  4848. BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x12_SRGB_BLOCK);
  4849. BIND_ENUM_CONSTANT(DATA_FORMAT_G8B8G8R8_422_UNORM);
  4850. BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8G8_422_UNORM);
  4851. BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8_R8_3PLANE_420_UNORM);
  4852. BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8R8_2PLANE_420_UNORM);
  4853. BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8_R8_3PLANE_422_UNORM);
  4854. BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8R8_2PLANE_422_UNORM);
  4855. BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8_R8_3PLANE_444_UNORM);
  4856. BIND_ENUM_CONSTANT(DATA_FORMAT_R10X6_UNORM_PACK16);
  4857. BIND_ENUM_CONSTANT(DATA_FORMAT_R10X6G10X6_UNORM_2PACK16);
  4858. BIND_ENUM_CONSTANT(DATA_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16);
  4859. BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16);
  4860. BIND_ENUM_CONSTANT(DATA_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16);
  4861. BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16);
  4862. BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16);
  4863. BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16);
  4864. BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16);
  4865. BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16);
  4866. BIND_ENUM_CONSTANT(DATA_FORMAT_R12X4_UNORM_PACK16);
  4867. BIND_ENUM_CONSTANT(DATA_FORMAT_R12X4G12X4_UNORM_2PACK16);
  4868. BIND_ENUM_CONSTANT(DATA_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16);
  4869. BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16);
  4870. BIND_ENUM_CONSTANT(DATA_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16);
  4871. BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16);
  4872. BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16);
  4873. BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16);
  4874. BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16);
  4875. BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16);
  4876. BIND_ENUM_CONSTANT(DATA_FORMAT_G16B16G16R16_422_UNORM);
  4877. BIND_ENUM_CONSTANT(DATA_FORMAT_B16G16R16G16_422_UNORM);
  4878. BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16_R16_3PLANE_420_UNORM);
  4879. BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16R16_2PLANE_420_UNORM);
  4880. BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16_R16_3PLANE_422_UNORM);
  4881. BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16R16_2PLANE_422_UNORM);
  4882. BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16_R16_3PLANE_444_UNORM);
  4883. BIND_ENUM_CONSTANT(DATA_FORMAT_MAX);
  4884. #ifndef DISABLE_DEPRECATED
  4885. BIND_BITFIELD_FLAG(BARRIER_MASK_VERTEX);
  4886. BIND_BITFIELD_FLAG(BARRIER_MASK_FRAGMENT);
  4887. BIND_BITFIELD_FLAG(BARRIER_MASK_COMPUTE);
  4888. BIND_BITFIELD_FLAG(BARRIER_MASK_TRANSFER);
  4889. BIND_BITFIELD_FLAG(BARRIER_MASK_RASTER);
  4890. BIND_BITFIELD_FLAG(BARRIER_MASK_ALL_BARRIERS);
  4891. BIND_BITFIELD_FLAG(BARRIER_MASK_NO_BARRIER);
  4892. #endif
  4893. BIND_ENUM_CONSTANT(TEXTURE_TYPE_1D);
  4894. BIND_ENUM_CONSTANT(TEXTURE_TYPE_2D);
  4895. BIND_ENUM_CONSTANT(TEXTURE_TYPE_3D);
  4896. BIND_ENUM_CONSTANT(TEXTURE_TYPE_CUBE);
  4897. BIND_ENUM_CONSTANT(TEXTURE_TYPE_1D_ARRAY);
  4898. BIND_ENUM_CONSTANT(TEXTURE_TYPE_2D_ARRAY);
  4899. BIND_ENUM_CONSTANT(TEXTURE_TYPE_CUBE_ARRAY);
  4900. BIND_ENUM_CONSTANT(TEXTURE_TYPE_MAX);
  4901. BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_1);
  4902. BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_2);
  4903. BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_4);
  4904. BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_8);
  4905. BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_16);
  4906. BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_32);
  4907. BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_64);
  4908. BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_MAX);
  4909. BIND_BITFIELD_FLAG(TEXTURE_USAGE_SAMPLING_BIT);
  4910. BIND_BITFIELD_FLAG(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT);
  4911. BIND_BITFIELD_FLAG(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
  4912. BIND_BITFIELD_FLAG(TEXTURE_USAGE_STORAGE_BIT);
  4913. BIND_BITFIELD_FLAG(TEXTURE_USAGE_STORAGE_ATOMIC_BIT);
  4914. BIND_BITFIELD_FLAG(TEXTURE_USAGE_CPU_READ_BIT);
  4915. BIND_BITFIELD_FLAG(TEXTURE_USAGE_CAN_UPDATE_BIT);
  4916. BIND_BITFIELD_FLAG(TEXTURE_USAGE_CAN_COPY_FROM_BIT);
  4917. BIND_BITFIELD_FLAG(TEXTURE_USAGE_CAN_COPY_TO_BIT);
  4918. BIND_BITFIELD_FLAG(TEXTURE_USAGE_INPUT_ATTACHMENT_BIT);
  4919. BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_IDENTITY);
  4920. BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_ZERO);
  4921. BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_ONE);
  4922. BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_R);
  4923. BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_G);
  4924. BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_B);
  4925. BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_A);
  4926. BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_MAX);
  4927. BIND_ENUM_CONSTANT(TEXTURE_SLICE_2D);
  4928. BIND_ENUM_CONSTANT(TEXTURE_SLICE_CUBEMAP);
  4929. BIND_ENUM_CONSTANT(TEXTURE_SLICE_3D);
  4930. BIND_ENUM_CONSTANT(SAMPLER_FILTER_NEAREST);
  4931. BIND_ENUM_CONSTANT(SAMPLER_FILTER_LINEAR);
  4932. BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_REPEAT);
  4933. BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_MIRRORED_REPEAT);
  4934. BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_CLAMP_TO_EDGE);
  4935. BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_CLAMP_TO_BORDER);
  4936. BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_MIRROR_CLAMP_TO_EDGE);
  4937. BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_MAX);
  4938. BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK);
  4939. BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_INT_TRANSPARENT_BLACK);
  4940. BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_FLOAT_OPAQUE_BLACK);
  4941. BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_INT_OPAQUE_BLACK);
  4942. BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_FLOAT_OPAQUE_WHITE);
  4943. BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_INT_OPAQUE_WHITE);
  4944. BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_MAX);
  4945. BIND_ENUM_CONSTANT(VERTEX_FREQUENCY_VERTEX);
  4946. BIND_ENUM_CONSTANT(VERTEX_FREQUENCY_INSTANCE);
  4947. BIND_ENUM_CONSTANT(INDEX_BUFFER_FORMAT_UINT16);
  4948. BIND_ENUM_CONSTANT(INDEX_BUFFER_FORMAT_UINT32);
  4949. BIND_BITFIELD_FLAG(STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT);
  4950. BIND_ENUM_CONSTANT(UNIFORM_TYPE_SAMPLER); //for sampling only (sampler GLSL type)
  4951. BIND_ENUM_CONSTANT(UNIFORM_TYPE_SAMPLER_WITH_TEXTURE); // for sampling only); but includes a texture); (samplerXX GLSL type)); first a sampler then a texture
  4952. BIND_ENUM_CONSTANT(UNIFORM_TYPE_TEXTURE); //only texture); (textureXX GLSL type)
  4953. BIND_ENUM_CONSTANT(UNIFORM_TYPE_IMAGE); // storage image (imageXX GLSL type)); for compute mostly
  4954. BIND_ENUM_CONSTANT(UNIFORM_TYPE_TEXTURE_BUFFER); // buffer texture (or TBO); textureBuffer type)
  4955. BIND_ENUM_CONSTANT(UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER); // buffer texture with a sampler(or TBO); samplerBuffer type)
  4956. BIND_ENUM_CONSTANT(UNIFORM_TYPE_IMAGE_BUFFER); //texel buffer); (imageBuffer type)); for compute mostly
  4957. BIND_ENUM_CONSTANT(UNIFORM_TYPE_UNIFORM_BUFFER); //regular uniform buffer (or UBO).
  4958. BIND_ENUM_CONSTANT(UNIFORM_TYPE_STORAGE_BUFFER); //storage buffer ("buffer" qualifier) like UBO); but supports storage); for compute mostly
  4959. BIND_ENUM_CONSTANT(UNIFORM_TYPE_INPUT_ATTACHMENT); //used for sub-pass read/write); for mobile mostly
  4960. BIND_ENUM_CONSTANT(UNIFORM_TYPE_MAX);
  4961. BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_POINTS);
  4962. BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINES);
  4963. BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINES_WITH_ADJACENCY);
  4964. BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINESTRIPS);
  4965. BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINESTRIPS_WITH_ADJACENCY);
  4966. BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLES);
  4967. BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLES_WITH_ADJACENCY);
  4968. BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLE_STRIPS);
  4969. BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_AJACENCY);
  4970. BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX);
  4971. BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TESSELATION_PATCH);
  4972. BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_MAX);
  4973. BIND_ENUM_CONSTANT(POLYGON_CULL_DISABLED);
  4974. BIND_ENUM_CONSTANT(POLYGON_CULL_FRONT);
  4975. BIND_ENUM_CONSTANT(POLYGON_CULL_BACK);
  4976. BIND_ENUM_CONSTANT(POLYGON_FRONT_FACE_CLOCKWISE);
  4977. BIND_ENUM_CONSTANT(POLYGON_FRONT_FACE_COUNTER_CLOCKWISE);
  4978. BIND_ENUM_CONSTANT(STENCIL_OP_KEEP);
  4979. BIND_ENUM_CONSTANT(STENCIL_OP_ZERO);
  4980. BIND_ENUM_CONSTANT(STENCIL_OP_REPLACE);
  4981. BIND_ENUM_CONSTANT(STENCIL_OP_INCREMENT_AND_CLAMP);
  4982. BIND_ENUM_CONSTANT(STENCIL_OP_DECREMENT_AND_CLAMP);
  4983. BIND_ENUM_CONSTANT(STENCIL_OP_INVERT);
  4984. BIND_ENUM_CONSTANT(STENCIL_OP_INCREMENT_AND_WRAP);
  4985. BIND_ENUM_CONSTANT(STENCIL_OP_DECREMENT_AND_WRAP);
  4986. BIND_ENUM_CONSTANT(STENCIL_OP_MAX); //not an actual operator); just the amount of operators :D
  4987. BIND_ENUM_CONSTANT(COMPARE_OP_NEVER);
  4988. BIND_ENUM_CONSTANT(COMPARE_OP_LESS);
  4989. BIND_ENUM_CONSTANT(COMPARE_OP_EQUAL);
  4990. BIND_ENUM_CONSTANT(COMPARE_OP_LESS_OR_EQUAL);
  4991. BIND_ENUM_CONSTANT(COMPARE_OP_GREATER);
  4992. BIND_ENUM_CONSTANT(COMPARE_OP_NOT_EQUAL);
  4993. BIND_ENUM_CONSTANT(COMPARE_OP_GREATER_OR_EQUAL);
  4994. BIND_ENUM_CONSTANT(COMPARE_OP_ALWAYS);
  4995. BIND_ENUM_CONSTANT(COMPARE_OP_MAX);
  4996. BIND_ENUM_CONSTANT(LOGIC_OP_CLEAR);
  4997. BIND_ENUM_CONSTANT(LOGIC_OP_AND);
  4998. BIND_ENUM_CONSTANT(LOGIC_OP_AND_REVERSE);
  4999. BIND_ENUM_CONSTANT(LOGIC_OP_COPY);
  5000. BIND_ENUM_CONSTANT(LOGIC_OP_AND_INVERTED);
  5001. BIND_ENUM_CONSTANT(LOGIC_OP_NO_OP);
  5002. BIND_ENUM_CONSTANT(LOGIC_OP_XOR);
  5003. BIND_ENUM_CONSTANT(LOGIC_OP_OR);
  5004. BIND_ENUM_CONSTANT(LOGIC_OP_NOR);
  5005. BIND_ENUM_CONSTANT(LOGIC_OP_EQUIVALENT);
  5006. BIND_ENUM_CONSTANT(LOGIC_OP_INVERT);
  5007. BIND_ENUM_CONSTANT(LOGIC_OP_OR_REVERSE);
  5008. BIND_ENUM_CONSTANT(LOGIC_OP_COPY_INVERTED);
  5009. BIND_ENUM_CONSTANT(LOGIC_OP_OR_INVERTED);
  5010. BIND_ENUM_CONSTANT(LOGIC_OP_NAND);
  5011. BIND_ENUM_CONSTANT(LOGIC_OP_SET);
  5012. BIND_ENUM_CONSTANT(LOGIC_OP_MAX); //not an actual operator); just the amount of operators :D
  5013. BIND_ENUM_CONSTANT(BLEND_FACTOR_ZERO);
  5014. BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE);
  5015. BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC_COLOR);
  5016. BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC_COLOR);
  5017. BIND_ENUM_CONSTANT(BLEND_FACTOR_DST_COLOR);
  5018. BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_DST_COLOR);
  5019. BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC_ALPHA);
  5020. BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC_ALPHA);
  5021. BIND_ENUM_CONSTANT(BLEND_FACTOR_DST_ALPHA);
  5022. BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_DST_ALPHA);
  5023. BIND_ENUM_CONSTANT(BLEND_FACTOR_CONSTANT_COLOR);
  5024. BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR);
  5025. BIND_ENUM_CONSTANT(BLEND_FACTOR_CONSTANT_ALPHA);
  5026. BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA);
  5027. BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC_ALPHA_SATURATE);
  5028. BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC1_COLOR);
  5029. BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC1_COLOR);
  5030. BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC1_ALPHA);
  5031. BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA);
  5032. BIND_ENUM_CONSTANT(BLEND_FACTOR_MAX);
  5033. BIND_ENUM_CONSTANT(BLEND_OP_ADD);
  5034. BIND_ENUM_CONSTANT(BLEND_OP_SUBTRACT);
  5035. BIND_ENUM_CONSTANT(BLEND_OP_REVERSE_SUBTRACT);
  5036. BIND_ENUM_CONSTANT(BLEND_OP_MINIMUM);
  5037. BIND_ENUM_CONSTANT(BLEND_OP_MAXIMUM);
  5038. BIND_ENUM_CONSTANT(BLEND_OP_MAX);
  5039. BIND_BITFIELD_FLAG(DYNAMIC_STATE_LINE_WIDTH);
  5040. BIND_BITFIELD_FLAG(DYNAMIC_STATE_DEPTH_BIAS);
  5041. BIND_BITFIELD_FLAG(DYNAMIC_STATE_BLEND_CONSTANTS);
  5042. BIND_BITFIELD_FLAG(DYNAMIC_STATE_DEPTH_BOUNDS);
  5043. BIND_BITFIELD_FLAG(DYNAMIC_STATE_STENCIL_COMPARE_MASK);
  5044. BIND_BITFIELD_FLAG(DYNAMIC_STATE_STENCIL_WRITE_MASK);
  5045. BIND_BITFIELD_FLAG(DYNAMIC_STATE_STENCIL_REFERENCE);
  5046. BIND_ENUM_CONSTANT(INITIAL_ACTION_LOAD);
  5047. BIND_ENUM_CONSTANT(INITIAL_ACTION_CLEAR);
  5048. BIND_ENUM_CONSTANT(INITIAL_ACTION_DISCARD);
  5049. BIND_ENUM_CONSTANT(INITIAL_ACTION_MAX);
  5050. #ifndef DISABLE_DEPRECATED
  5051. BIND_ENUM_CONSTANT(INITIAL_ACTION_CLEAR_REGION);
  5052. BIND_ENUM_CONSTANT(INITIAL_ACTION_CLEAR_REGION_CONTINUE);
  5053. BIND_ENUM_CONSTANT(INITIAL_ACTION_KEEP);
  5054. BIND_ENUM_CONSTANT(INITIAL_ACTION_DROP);
  5055. BIND_ENUM_CONSTANT(INITIAL_ACTION_CONTINUE);
  5056. #endif
  5057. BIND_ENUM_CONSTANT(FINAL_ACTION_STORE);
  5058. BIND_ENUM_CONSTANT(FINAL_ACTION_DISCARD);
  5059. BIND_ENUM_CONSTANT(FINAL_ACTION_MAX);
  5060. #ifndef DISABLE_DEPRECATED
  5061. BIND_ENUM_CONSTANT(FINAL_ACTION_READ);
  5062. BIND_ENUM_CONSTANT(FINAL_ACTION_CONTINUE);
  5063. #endif
  5064. BIND_ENUM_CONSTANT(SHADER_STAGE_VERTEX);
  5065. BIND_ENUM_CONSTANT(SHADER_STAGE_FRAGMENT);
  5066. BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_CONTROL);
  5067. BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_EVALUATION);
  5068. BIND_ENUM_CONSTANT(SHADER_STAGE_COMPUTE);
  5069. BIND_ENUM_CONSTANT(SHADER_STAGE_MAX);
  5070. BIND_ENUM_CONSTANT(SHADER_STAGE_VERTEX_BIT);
  5071. BIND_ENUM_CONSTANT(SHADER_STAGE_FRAGMENT_BIT);
  5072. BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_CONTROL_BIT);
  5073. BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_EVALUATION_BIT);
  5074. BIND_ENUM_CONSTANT(SHADER_STAGE_COMPUTE_BIT);
  5075. BIND_ENUM_CONSTANT(SHADER_LANGUAGE_GLSL);
  5076. BIND_ENUM_CONSTANT(SHADER_LANGUAGE_HLSL);
  5077. BIND_ENUM_CONSTANT(PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL);
  5078. BIND_ENUM_CONSTANT(PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT);
  5079. BIND_ENUM_CONSTANT(PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT);
  5080. BIND_ENUM_CONSTANT(LIMIT_MAX_BOUND_UNIFORM_SETS);
  5081. BIND_ENUM_CONSTANT(LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS);
  5082. BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURES_PER_UNIFORM_SET);
  5083. BIND_ENUM_CONSTANT(LIMIT_MAX_SAMPLERS_PER_UNIFORM_SET);
  5084. BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_BUFFERS_PER_UNIFORM_SET);
  5085. BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_IMAGES_PER_UNIFORM_SET);
  5086. BIND_ENUM_CONSTANT(LIMIT_MAX_UNIFORM_BUFFERS_PER_UNIFORM_SET);
  5087. BIND_ENUM_CONSTANT(LIMIT_MAX_DRAW_INDEXED_INDEX);
  5088. BIND_ENUM_CONSTANT(LIMIT_MAX_FRAMEBUFFER_HEIGHT);
  5089. BIND_ENUM_CONSTANT(LIMIT_MAX_FRAMEBUFFER_WIDTH);
  5090. BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_ARRAY_LAYERS);
  5091. BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_1D);
  5092. BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_2D);
  5093. BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_3D);
  5094. BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_CUBE);
  5095. BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURES_PER_SHADER_STAGE);
  5096. BIND_ENUM_CONSTANT(LIMIT_MAX_SAMPLERS_PER_SHADER_STAGE);
  5097. BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_BUFFERS_PER_SHADER_STAGE);
  5098. BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_IMAGES_PER_SHADER_STAGE);
  5099. BIND_ENUM_CONSTANT(LIMIT_MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE);
  5100. BIND_ENUM_CONSTANT(LIMIT_MAX_PUSH_CONSTANT_SIZE);
  5101. BIND_ENUM_CONSTANT(LIMIT_MAX_UNIFORM_BUFFER_SIZE);
  5102. BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_ATTRIBUTE_OFFSET);
  5103. BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_ATTRIBUTES);
  5104. BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_BINDINGS);
  5105. BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_BINDING_STRIDE);
  5106. BIND_ENUM_CONSTANT(LIMIT_MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT);
  5107. BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_SHARED_MEMORY_SIZE);
  5108. BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X);
  5109. BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y);
  5110. BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z);
  5111. BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_INVOCATIONS);
  5112. BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X);
  5113. BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y);
  5114. BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z);
  5115. BIND_ENUM_CONSTANT(LIMIT_MAX_VIEWPORT_DIMENSIONS_X);
  5116. BIND_ENUM_CONSTANT(LIMIT_MAX_VIEWPORT_DIMENSIONS_Y);
  5117. BIND_ENUM_CONSTANT(MEMORY_TEXTURES);
  5118. BIND_ENUM_CONSTANT(MEMORY_BUFFERS);
  5119. BIND_ENUM_CONSTANT(MEMORY_TOTAL);
  5120. BIND_CONSTANT(INVALID_ID);
  5121. BIND_CONSTANT(INVALID_FORMAT_ID);
  5122. }
  5123. RenderingDevice::~RenderingDevice() {
  5124. finalize();
  5125. if (singleton == this) {
  5126. singleton = nullptr;
  5127. }
  5128. }
  5129. RenderingDevice::RenderingDevice() {
  5130. if (singleton == nullptr) {
  5131. singleton = this;
  5132. }
  5133. }
  5134. /*****************/
  5135. /**** BINDERS ****/
  5136. /*****************/
  5137. RID RenderingDevice::_texture_create(const Ref<RDTextureFormat> &p_format, const Ref<RDTextureView> &p_view, const TypedArray<PackedByteArray> &p_data) {
  5138. ERR_FAIL_COND_V(p_format.is_null(), RID());
  5139. ERR_FAIL_COND_V(p_view.is_null(), RID());
  5140. Vector<Vector<uint8_t>> data;
  5141. for (int i = 0; i < p_data.size(); i++) {
  5142. Vector<uint8_t> byte_slice = p_data[i];
  5143. ERR_FAIL_COND_V(byte_slice.is_empty(), RID());
  5144. data.push_back(byte_slice);
  5145. }
  5146. return texture_create(p_format->base, p_view->base, data);
  5147. }
  5148. RID RenderingDevice::_texture_create_shared(const Ref<RDTextureView> &p_view, RID p_with_texture) {
  5149. ERR_FAIL_COND_V(p_view.is_null(), RID());
  5150. return texture_create_shared(p_view->base, p_with_texture);
  5151. }
  5152. RID RenderingDevice::_texture_create_shared_from_slice(const Ref<RDTextureView> &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps, TextureSliceType p_slice_type) {
  5153. ERR_FAIL_COND_V(p_view.is_null(), RID());
  5154. return texture_create_shared_from_slice(p_view->base, p_with_texture, p_layer, p_mipmap, p_mipmaps, p_slice_type);
  5155. }
  5156. Ref<RDTextureFormat> RenderingDevice::_texture_get_format(RID p_rd_texture) {
  5157. Ref<RDTextureFormat> rtf;
  5158. rtf.instantiate();
  5159. rtf->base = texture_get_format(p_rd_texture);
  5160. return rtf;
  5161. }
  5162. RenderingDevice::FramebufferFormatID RenderingDevice::_framebuffer_format_create(const TypedArray<RDAttachmentFormat> &p_attachments, uint32_t p_view_count) {
  5163. Vector<AttachmentFormat> attachments;
  5164. attachments.resize(p_attachments.size());
  5165. for (int i = 0; i < p_attachments.size(); i++) {
  5166. Ref<RDAttachmentFormat> af = p_attachments[i];
  5167. ERR_FAIL_COND_V(af.is_null(), INVALID_FORMAT_ID);
  5168. attachments.write[i] = af->base;
  5169. }
  5170. return framebuffer_format_create(attachments, p_view_count);
  5171. }
  5172. RenderingDevice::FramebufferFormatID RenderingDevice::_framebuffer_format_create_multipass(const TypedArray<RDAttachmentFormat> &p_attachments, const TypedArray<RDFramebufferPass> &p_passes, uint32_t p_view_count) {
  5173. Vector<AttachmentFormat> attachments;
  5174. attachments.resize(p_attachments.size());
  5175. for (int i = 0; i < p_attachments.size(); i++) {
  5176. Ref<RDAttachmentFormat> af = p_attachments[i];
  5177. ERR_FAIL_COND_V(af.is_null(), INVALID_FORMAT_ID);
  5178. attachments.write[i] = af->base;
  5179. }
  5180. Vector<FramebufferPass> passes;
  5181. for (int i = 0; i < p_passes.size(); i++) {
  5182. Ref<RDFramebufferPass> pass = p_passes[i];
  5183. ERR_CONTINUE(pass.is_null());
  5184. passes.push_back(pass->base);
  5185. }
  5186. return framebuffer_format_create_multipass(attachments, passes, p_view_count);
  5187. }
  5188. RID RenderingDevice::_framebuffer_create(const TypedArray<RID> &p_textures, FramebufferFormatID p_format_check, uint32_t p_view_count) {
  5189. Vector<RID> textures = Variant(p_textures);
  5190. return framebuffer_create(textures, p_format_check, p_view_count);
  5191. }
  5192. RID RenderingDevice::_framebuffer_create_multipass(const TypedArray<RID> &p_textures, const TypedArray<RDFramebufferPass> &p_passes, FramebufferFormatID p_format_check, uint32_t p_view_count) {
  5193. Vector<RID> textures = Variant(p_textures);
  5194. Vector<FramebufferPass> passes;
  5195. for (int i = 0; i < p_passes.size(); i++) {
  5196. Ref<RDFramebufferPass> pass = p_passes[i];
  5197. ERR_CONTINUE(pass.is_null());
  5198. passes.push_back(pass->base);
  5199. }
  5200. return framebuffer_create_multipass(textures, passes, p_format_check, p_view_count);
  5201. }
  5202. RID RenderingDevice::_sampler_create(const Ref<RDSamplerState> &p_state) {
  5203. ERR_FAIL_COND_V(p_state.is_null(), RID());
  5204. return sampler_create(p_state->base);
  5205. }
  5206. RenderingDevice::VertexFormatID RenderingDevice::_vertex_format_create(const TypedArray<RDVertexAttribute> &p_vertex_formats) {
  5207. Vector<VertexAttribute> descriptions;
  5208. descriptions.resize(p_vertex_formats.size());
  5209. for (int i = 0; i < p_vertex_formats.size(); i++) {
  5210. Ref<RDVertexAttribute> af = p_vertex_formats[i];
  5211. ERR_FAIL_COND_V(af.is_null(), INVALID_FORMAT_ID);
  5212. descriptions.write[i] = af->base;
  5213. }
  5214. return vertex_format_create(descriptions);
  5215. }
  5216. RID RenderingDevice::_vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const TypedArray<RID> &p_src_buffers, const Vector<int64_t> &p_offsets) {
  5217. Vector<RID> buffers = Variant(p_src_buffers);
  5218. Vector<uint64_t> offsets;
  5219. offsets.resize(p_offsets.size());
  5220. for (int i = 0; i < p_offsets.size(); i++) {
  5221. offsets.write[i] = p_offsets[i];
  5222. }
  5223. return vertex_array_create(p_vertex_count, p_vertex_format, buffers, offsets);
  5224. }
  5225. Ref<RDShaderSPIRV> RenderingDevice::_shader_compile_spirv_from_source(const Ref<RDShaderSource> &p_source, bool p_allow_cache) {
  5226. ERR_FAIL_COND_V(p_source.is_null(), Ref<RDShaderSPIRV>());
  5227. Ref<RDShaderSPIRV> bytecode;
  5228. bytecode.instantiate();
  5229. for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) {
  5230. String error;
  5231. ShaderStage stage = ShaderStage(i);
  5232. String source = p_source->get_stage_source(stage);
  5233. if (!source.is_empty()) {
  5234. Vector<uint8_t> spirv = shader_compile_spirv_from_source(stage, source, p_source->get_language(), &error, p_allow_cache);
  5235. bytecode->set_stage_bytecode(stage, spirv);
  5236. bytecode->set_stage_compile_error(stage, error);
  5237. }
  5238. }
  5239. return bytecode;
  5240. }
  5241. Vector<uint8_t> RenderingDevice::_shader_compile_binary_from_spirv(const Ref<RDShaderSPIRV> &p_spirv, const String &p_shader_name) {
  5242. ERR_FAIL_COND_V(p_spirv.is_null(), Vector<uint8_t>());
  5243. Vector<ShaderStageSPIRVData> stage_data;
  5244. for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) {
  5245. ShaderStage stage = ShaderStage(i);
  5246. ShaderStageSPIRVData sd;
  5247. sd.shader_stage = stage;
  5248. String error = p_spirv->get_stage_compile_error(stage);
  5249. ERR_FAIL_COND_V_MSG(!error.is_empty(), Vector<uint8_t>(), "Can't create a shader from an errored bytecode. Check errors in source bytecode.");
  5250. sd.spirv = p_spirv->get_stage_bytecode(stage);
  5251. if (sd.spirv.is_empty()) {
  5252. continue;
  5253. }
  5254. stage_data.push_back(sd);
  5255. }
  5256. return shader_compile_binary_from_spirv(stage_data, p_shader_name);
  5257. }
  5258. RID RenderingDevice::_shader_create_from_spirv(const Ref<RDShaderSPIRV> &p_spirv, const String &p_shader_name) {
  5259. ERR_FAIL_COND_V(p_spirv.is_null(), RID());
  5260. Vector<ShaderStageSPIRVData> stage_data;
  5261. for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) {
  5262. ShaderStage stage = ShaderStage(i);
  5263. ShaderStageSPIRVData sd;
  5264. sd.shader_stage = stage;
  5265. String error = p_spirv->get_stage_compile_error(stage);
  5266. ERR_FAIL_COND_V_MSG(!error.is_empty(), RID(), "Can't create a shader from an errored bytecode. Check errors in source bytecode.");
  5267. sd.spirv = p_spirv->get_stage_bytecode(stage);
  5268. if (sd.spirv.is_empty()) {
  5269. continue;
  5270. }
  5271. stage_data.push_back(sd);
  5272. }
  5273. return shader_create_from_spirv(stage_data);
  5274. }
  5275. RID RenderingDevice::_uniform_set_create(const TypedArray<RDUniform> &p_uniforms, RID p_shader, uint32_t p_shader_set) {
  5276. Vector<Uniform> uniforms;
  5277. uniforms.resize(p_uniforms.size());
  5278. for (int i = 0; i < p_uniforms.size(); i++) {
  5279. Ref<RDUniform> uniform = p_uniforms[i];
  5280. ERR_FAIL_COND_V(!uniform.is_valid(), RID());
  5281. uniforms.write[i] = uniform->base;
  5282. }
  5283. return uniform_set_create(uniforms, p_shader, p_shader_set);
  5284. }
  5285. Error RenderingDevice::_buffer_update_bind(RID p_buffer, uint32_t p_offset, uint32_t p_size, const Vector<uint8_t> &p_data) {
  5286. return buffer_update(p_buffer, p_offset, p_size, p_data.ptr());
  5287. }
  5288. static Vector<RenderingDevice::PipelineSpecializationConstant> _get_spec_constants(const TypedArray<RDPipelineSpecializationConstant> &p_constants) {
  5289. Vector<RenderingDevice::PipelineSpecializationConstant> ret;
  5290. ret.resize(p_constants.size());
  5291. for (int i = 0; i < p_constants.size(); i++) {
  5292. Ref<RDPipelineSpecializationConstant> c = p_constants[i];
  5293. ERR_CONTINUE(c.is_null());
  5294. RenderingDevice::PipelineSpecializationConstant &sc = ret.write[i];
  5295. Variant value = c->get_value();
  5296. switch (value.get_type()) {
  5297. case Variant::BOOL: {
  5298. sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL;
  5299. sc.bool_value = value;
  5300. } break;
  5301. case Variant::INT: {
  5302. sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT;
  5303. sc.int_value = value;
  5304. } break;
  5305. case Variant::FLOAT: {
  5306. sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT;
  5307. sc.float_value = value;
  5308. } break;
  5309. default: {
  5310. }
  5311. }
  5312. sc.constant_id = c->get_constant_id();
  5313. }
  5314. return ret;
  5315. }
  5316. RID RenderingDevice::_render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const Ref<RDPipelineRasterizationState> &p_rasterization_state, const Ref<RDPipelineMultisampleState> &p_multisample_state, const Ref<RDPipelineDepthStencilState> &p_depth_stencil_state, const Ref<RDPipelineColorBlendState> &p_blend_state, BitField<PipelineDynamicStateFlags> p_dynamic_state_flags, uint32_t p_for_render_pass, const TypedArray<RDPipelineSpecializationConstant> &p_specialization_constants) {
  5317. PipelineRasterizationState rasterization_state;
  5318. if (p_rasterization_state.is_valid()) {
  5319. rasterization_state = p_rasterization_state->base;
  5320. }
  5321. PipelineMultisampleState multisample_state;
  5322. if (p_multisample_state.is_valid()) {
  5323. multisample_state = p_multisample_state->base;
  5324. for (int i = 0; i < p_multisample_state->sample_masks.size(); i++) {
  5325. int64_t mask = p_multisample_state->sample_masks[i];
  5326. multisample_state.sample_mask.push_back(mask);
  5327. }
  5328. }
  5329. PipelineDepthStencilState depth_stencil_state;
  5330. if (p_depth_stencil_state.is_valid()) {
  5331. depth_stencil_state = p_depth_stencil_state->base;
  5332. }
  5333. PipelineColorBlendState color_blend_state;
  5334. if (p_blend_state.is_valid()) {
  5335. color_blend_state = p_blend_state->base;
  5336. for (int i = 0; i < p_blend_state->attachments.size(); i++) {
  5337. Ref<RDPipelineColorBlendStateAttachment> attachment = p_blend_state->attachments[i];
  5338. if (attachment.is_valid()) {
  5339. color_blend_state.attachments.push_back(attachment->base);
  5340. }
  5341. }
  5342. }
  5343. return render_pipeline_create(p_shader, p_framebuffer_format, p_vertex_format, p_render_primitive, rasterization_state, multisample_state, depth_stencil_state, color_blend_state, p_dynamic_state_flags, p_for_render_pass, _get_spec_constants(p_specialization_constants));
  5344. }
  5345. RID RenderingDevice::_compute_pipeline_create(RID p_shader, const TypedArray<RDPipelineSpecializationConstant> &p_specialization_constants = TypedArray<RDPipelineSpecializationConstant>()) {
  5346. return compute_pipeline_create(p_shader, _get_spec_constants(p_specialization_constants));
  5347. }
  5348. #ifndef DISABLE_DEPRECATED
  5349. Vector<int64_t> RenderingDevice::_draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const TypedArray<RID> &p_storage_textures) {
  5350. ERR_FAIL_V_MSG(Vector<int64_t>(), "Deprecated. Split draw lists are used automatically by RenderingDevice.");
  5351. }
  5352. Vector<int64_t> RenderingDevice::_draw_list_switch_to_next_pass_split(uint32_t p_splits) {
  5353. ERR_FAIL_V_MSG(Vector<int64_t>(), "Deprecated. Split draw lists are used automatically by RenderingDevice.");
  5354. }
  5355. #endif
  5356. void RenderingDevice::_draw_list_set_push_constant(DrawListID p_list, const Vector<uint8_t> &p_data, uint32_t p_data_size) {
  5357. ERR_FAIL_COND(p_data_size > (uint32_t)p_data.size());
  5358. draw_list_set_push_constant(p_list, p_data.ptr(), p_data_size);
  5359. }
  5360. void RenderingDevice::_compute_list_set_push_constant(ComputeListID p_list, const Vector<uint8_t> &p_data, uint32_t p_data_size) {
  5361. ERR_FAIL_COND(p_data_size > (uint32_t)p_data.size());
  5362. compute_list_set_push_constant(p_list, p_data.ptr(), p_data_size);
  5363. }