rendering_device_vulkan.cpp 385 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519
  1. /*************************************************************************/
  2. /* rendering_device_vulkan.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "rendering_device_vulkan.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/compression.h"
  33. #include "core/io/file_access.h"
  34. #include "core/io/marshalls.h"
  35. #include "core/os/os.h"
  36. #include "core/templates/hashfuncs.h"
  37. #include "drivers/vulkan/vulkan_context.h"
  38. #include "thirdparty/misc/smolv.h"
  39. #include "thirdparty/spirv-reflect/spirv_reflect.h"
  40. //#define FORCE_FULL_BARRIER
  41. static const uint32_t SMALL_ALLOCATION_MAX_SIZE = 4096;
  42. // Get the Vulkan object information and possible stage access types (bitwise OR'd with incoming values)
  43. RenderingDeviceVulkan::Buffer *RenderingDeviceVulkan::_get_buffer_from_owner(RID p_buffer, VkPipelineStageFlags &r_stage_mask, VkAccessFlags &r_access_mask, uint32_t p_post_barrier) {
  44. Buffer *buffer = nullptr;
  45. if (vertex_buffer_owner.owns(p_buffer)) {
  46. buffer = vertex_buffer_owner.get_or_null(p_buffer);
  47. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  48. r_access_mask |= VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
  49. if (buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) {
  50. if (p_post_barrier & BARRIER_MASK_RASTER) {
  51. r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  52. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  53. }
  54. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  55. r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  56. r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  57. }
  58. }
  59. } else if (index_buffer_owner.owns(p_buffer)) {
  60. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  61. r_access_mask |= VK_ACCESS_INDEX_READ_BIT;
  62. buffer = index_buffer_owner.get_or_null(p_buffer);
  63. } else if (uniform_buffer_owner.owns(p_buffer)) {
  64. if (p_post_barrier & BARRIER_MASK_RASTER) {
  65. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  66. }
  67. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  68. r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  69. }
  70. r_access_mask |= VK_ACCESS_UNIFORM_READ_BIT;
  71. buffer = uniform_buffer_owner.get_or_null(p_buffer);
  72. } else if (texture_buffer_owner.owns(p_buffer)) {
  73. if (p_post_barrier & BARRIER_MASK_RASTER) {
  74. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  75. r_access_mask |= VK_ACCESS_SHADER_READ_BIT;
  76. }
  77. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  78. r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  79. r_access_mask |= VK_ACCESS_SHADER_READ_BIT;
  80. }
  81. buffer = &texture_buffer_owner.get_or_null(p_buffer)->buffer;
  82. } else if (storage_buffer_owner.owns(p_buffer)) {
  83. buffer = storage_buffer_owner.get_or_null(p_buffer);
  84. if (p_post_barrier & BARRIER_MASK_RASTER) {
  85. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  86. r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  87. }
  88. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  89. r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  90. r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  91. }
  92. if (buffer->usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) {
  93. r_stage_mask |= VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
  94. r_access_mask |= VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
  95. }
  96. }
  97. return buffer;
  98. }
  99. static void update_external_dependency_for_store(VkSubpassDependency &dependency, bool is_sampled, bool is_storage, bool is_depth) {
  100. // Transitioning from write to read, protect the shaders that may use this next
  101. // Allow for copies/image layout transitions
  102. dependency.dstStageMask |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  103. dependency.dstAccessMask |= VK_ACCESS_TRANSFER_READ_BIT;
  104. if (is_sampled) {
  105. dependency.dstStageMask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  106. dependency.dstAccessMask |= VK_ACCESS_SHADER_READ_BIT;
  107. } else if (is_storage) {
  108. dependency.dstStageMask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  109. dependency.dstAccessMask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  110. } else {
  111. dependency.dstStageMask |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  112. dependency.dstAccessMask |= VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  113. }
  114. if (is_depth) {
  115. // Depth resources have additional stages that may be interested in them
  116. dependency.dstStageMask |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  117. dependency.dstAccessMask |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  118. }
  119. }
  120. void RenderingDeviceVulkan::_add_dependency(RID p_id, RID p_depends_on) {
  121. if (!dependency_map.has(p_depends_on)) {
  122. dependency_map[p_depends_on] = RBSet<RID>();
  123. }
  124. dependency_map[p_depends_on].insert(p_id);
  125. if (!reverse_dependency_map.has(p_id)) {
  126. reverse_dependency_map[p_id] = RBSet<RID>();
  127. }
  128. reverse_dependency_map[p_id].insert(p_depends_on);
  129. }
  130. void RenderingDeviceVulkan::_free_dependencies(RID p_id) {
  131. //direct dependencies must be freed
  132. HashMap<RID, RBSet<RID>>::Iterator E = dependency_map.find(p_id);
  133. if (E) {
  134. while (E->value.size()) {
  135. free(E->value.front()->get());
  136. }
  137. dependency_map.remove(E);
  138. }
  139. //reverse dependencies must be unreferenced
  140. E = reverse_dependency_map.find(p_id);
  141. if (E) {
  142. for (const RID &F : E->value) {
  143. HashMap<RID, RBSet<RID>>::Iterator G = dependency_map.find(F);
  144. ERR_CONTINUE(!G);
  145. ERR_CONTINUE(!G->value.has(p_id));
  146. G->value.erase(p_id);
  147. }
  148. reverse_dependency_map.remove(E);
  149. }
  150. }
  151. const VkFormat RenderingDeviceVulkan::vulkan_formats[RenderingDevice::DATA_FORMAT_MAX] = {
  152. VK_FORMAT_R4G4_UNORM_PACK8,
  153. VK_FORMAT_R4G4B4A4_UNORM_PACK16,
  154. VK_FORMAT_B4G4R4A4_UNORM_PACK16,
  155. VK_FORMAT_R5G6B5_UNORM_PACK16,
  156. VK_FORMAT_B5G6R5_UNORM_PACK16,
  157. VK_FORMAT_R5G5B5A1_UNORM_PACK16,
  158. VK_FORMAT_B5G5R5A1_UNORM_PACK16,
  159. VK_FORMAT_A1R5G5B5_UNORM_PACK16,
  160. VK_FORMAT_R8_UNORM,
  161. VK_FORMAT_R8_SNORM,
  162. VK_FORMAT_R8_USCALED,
  163. VK_FORMAT_R8_SSCALED,
  164. VK_FORMAT_R8_UINT,
  165. VK_FORMAT_R8_SINT,
  166. VK_FORMAT_R8_SRGB,
  167. VK_FORMAT_R8G8_UNORM,
  168. VK_FORMAT_R8G8_SNORM,
  169. VK_FORMAT_R8G8_USCALED,
  170. VK_FORMAT_R8G8_SSCALED,
  171. VK_FORMAT_R8G8_UINT,
  172. VK_FORMAT_R8G8_SINT,
  173. VK_FORMAT_R8G8_SRGB,
  174. VK_FORMAT_R8G8B8_UNORM,
  175. VK_FORMAT_R8G8B8_SNORM,
  176. VK_FORMAT_R8G8B8_USCALED,
  177. VK_FORMAT_R8G8B8_SSCALED,
  178. VK_FORMAT_R8G8B8_UINT,
  179. VK_FORMAT_R8G8B8_SINT,
  180. VK_FORMAT_R8G8B8_SRGB,
  181. VK_FORMAT_B8G8R8_UNORM,
  182. VK_FORMAT_B8G8R8_SNORM,
  183. VK_FORMAT_B8G8R8_USCALED,
  184. VK_FORMAT_B8G8R8_SSCALED,
  185. VK_FORMAT_B8G8R8_UINT,
  186. VK_FORMAT_B8G8R8_SINT,
  187. VK_FORMAT_B8G8R8_SRGB,
  188. VK_FORMAT_R8G8B8A8_UNORM,
  189. VK_FORMAT_R8G8B8A8_SNORM,
  190. VK_FORMAT_R8G8B8A8_USCALED,
  191. VK_FORMAT_R8G8B8A8_SSCALED,
  192. VK_FORMAT_R8G8B8A8_UINT,
  193. VK_FORMAT_R8G8B8A8_SINT,
  194. VK_FORMAT_R8G8B8A8_SRGB,
  195. VK_FORMAT_B8G8R8A8_UNORM,
  196. VK_FORMAT_B8G8R8A8_SNORM,
  197. VK_FORMAT_B8G8R8A8_USCALED,
  198. VK_FORMAT_B8G8R8A8_SSCALED,
  199. VK_FORMAT_B8G8R8A8_UINT,
  200. VK_FORMAT_B8G8R8A8_SINT,
  201. VK_FORMAT_B8G8R8A8_SRGB,
  202. VK_FORMAT_A8B8G8R8_UNORM_PACK32,
  203. VK_FORMAT_A8B8G8R8_SNORM_PACK32,
  204. VK_FORMAT_A8B8G8R8_USCALED_PACK32,
  205. VK_FORMAT_A8B8G8R8_SSCALED_PACK32,
  206. VK_FORMAT_A8B8G8R8_UINT_PACK32,
  207. VK_FORMAT_A8B8G8R8_SINT_PACK32,
  208. VK_FORMAT_A8B8G8R8_SRGB_PACK32,
  209. VK_FORMAT_A2R10G10B10_UNORM_PACK32,
  210. VK_FORMAT_A2R10G10B10_SNORM_PACK32,
  211. VK_FORMAT_A2R10G10B10_USCALED_PACK32,
  212. VK_FORMAT_A2R10G10B10_SSCALED_PACK32,
  213. VK_FORMAT_A2R10G10B10_UINT_PACK32,
  214. VK_FORMAT_A2R10G10B10_SINT_PACK32,
  215. VK_FORMAT_A2B10G10R10_UNORM_PACK32,
  216. VK_FORMAT_A2B10G10R10_SNORM_PACK32,
  217. VK_FORMAT_A2B10G10R10_USCALED_PACK32,
  218. VK_FORMAT_A2B10G10R10_SSCALED_PACK32,
  219. VK_FORMAT_A2B10G10R10_UINT_PACK32,
  220. VK_FORMAT_A2B10G10R10_SINT_PACK32,
  221. VK_FORMAT_R16_UNORM,
  222. VK_FORMAT_R16_SNORM,
  223. VK_FORMAT_R16_USCALED,
  224. VK_FORMAT_R16_SSCALED,
  225. VK_FORMAT_R16_UINT,
  226. VK_FORMAT_R16_SINT,
  227. VK_FORMAT_R16_SFLOAT,
  228. VK_FORMAT_R16G16_UNORM,
  229. VK_FORMAT_R16G16_SNORM,
  230. VK_FORMAT_R16G16_USCALED,
  231. VK_FORMAT_R16G16_SSCALED,
  232. VK_FORMAT_R16G16_UINT,
  233. VK_FORMAT_R16G16_SINT,
  234. VK_FORMAT_R16G16_SFLOAT,
  235. VK_FORMAT_R16G16B16_UNORM,
  236. VK_FORMAT_R16G16B16_SNORM,
  237. VK_FORMAT_R16G16B16_USCALED,
  238. VK_FORMAT_R16G16B16_SSCALED,
  239. VK_FORMAT_R16G16B16_UINT,
  240. VK_FORMAT_R16G16B16_SINT,
  241. VK_FORMAT_R16G16B16_SFLOAT,
  242. VK_FORMAT_R16G16B16A16_UNORM,
  243. VK_FORMAT_R16G16B16A16_SNORM,
  244. VK_FORMAT_R16G16B16A16_USCALED,
  245. VK_FORMAT_R16G16B16A16_SSCALED,
  246. VK_FORMAT_R16G16B16A16_UINT,
  247. VK_FORMAT_R16G16B16A16_SINT,
  248. VK_FORMAT_R16G16B16A16_SFLOAT,
  249. VK_FORMAT_R32_UINT,
  250. VK_FORMAT_R32_SINT,
  251. VK_FORMAT_R32_SFLOAT,
  252. VK_FORMAT_R32G32_UINT,
  253. VK_FORMAT_R32G32_SINT,
  254. VK_FORMAT_R32G32_SFLOAT,
  255. VK_FORMAT_R32G32B32_UINT,
  256. VK_FORMAT_R32G32B32_SINT,
  257. VK_FORMAT_R32G32B32_SFLOAT,
  258. VK_FORMAT_R32G32B32A32_UINT,
  259. VK_FORMAT_R32G32B32A32_SINT,
  260. VK_FORMAT_R32G32B32A32_SFLOAT,
  261. VK_FORMAT_R64_UINT,
  262. VK_FORMAT_R64_SINT,
  263. VK_FORMAT_R64_SFLOAT,
  264. VK_FORMAT_R64G64_UINT,
  265. VK_FORMAT_R64G64_SINT,
  266. VK_FORMAT_R64G64_SFLOAT,
  267. VK_FORMAT_R64G64B64_UINT,
  268. VK_FORMAT_R64G64B64_SINT,
  269. VK_FORMAT_R64G64B64_SFLOAT,
  270. VK_FORMAT_R64G64B64A64_UINT,
  271. VK_FORMAT_R64G64B64A64_SINT,
  272. VK_FORMAT_R64G64B64A64_SFLOAT,
  273. VK_FORMAT_B10G11R11_UFLOAT_PACK32,
  274. VK_FORMAT_E5B9G9R9_UFLOAT_PACK32,
  275. VK_FORMAT_D16_UNORM,
  276. VK_FORMAT_X8_D24_UNORM_PACK32,
  277. VK_FORMAT_D32_SFLOAT,
  278. VK_FORMAT_S8_UINT,
  279. VK_FORMAT_D16_UNORM_S8_UINT,
  280. VK_FORMAT_D24_UNORM_S8_UINT,
  281. VK_FORMAT_D32_SFLOAT_S8_UINT,
  282. VK_FORMAT_BC1_RGB_UNORM_BLOCK,
  283. VK_FORMAT_BC1_RGB_SRGB_BLOCK,
  284. VK_FORMAT_BC1_RGBA_UNORM_BLOCK,
  285. VK_FORMAT_BC1_RGBA_SRGB_BLOCK,
  286. VK_FORMAT_BC2_UNORM_BLOCK,
  287. VK_FORMAT_BC2_SRGB_BLOCK,
  288. VK_FORMAT_BC3_UNORM_BLOCK,
  289. VK_FORMAT_BC3_SRGB_BLOCK,
  290. VK_FORMAT_BC4_UNORM_BLOCK,
  291. VK_FORMAT_BC4_SNORM_BLOCK,
  292. VK_FORMAT_BC5_UNORM_BLOCK,
  293. VK_FORMAT_BC5_SNORM_BLOCK,
  294. VK_FORMAT_BC6H_UFLOAT_BLOCK,
  295. VK_FORMAT_BC6H_SFLOAT_BLOCK,
  296. VK_FORMAT_BC7_UNORM_BLOCK,
  297. VK_FORMAT_BC7_SRGB_BLOCK,
  298. VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK,
  299. VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK,
  300. VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK,
  301. VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK,
  302. VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK,
  303. VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK,
  304. VK_FORMAT_EAC_R11_UNORM_BLOCK,
  305. VK_FORMAT_EAC_R11_SNORM_BLOCK,
  306. VK_FORMAT_EAC_R11G11_UNORM_BLOCK,
  307. VK_FORMAT_EAC_R11G11_SNORM_BLOCK,
  308. VK_FORMAT_ASTC_4x4_UNORM_BLOCK,
  309. VK_FORMAT_ASTC_4x4_SRGB_BLOCK,
  310. VK_FORMAT_ASTC_5x4_UNORM_BLOCK,
  311. VK_FORMAT_ASTC_5x4_SRGB_BLOCK,
  312. VK_FORMAT_ASTC_5x5_UNORM_BLOCK,
  313. VK_FORMAT_ASTC_5x5_SRGB_BLOCK,
  314. VK_FORMAT_ASTC_6x5_UNORM_BLOCK,
  315. VK_FORMAT_ASTC_6x5_SRGB_BLOCK,
  316. VK_FORMAT_ASTC_6x6_UNORM_BLOCK,
  317. VK_FORMAT_ASTC_6x6_SRGB_BLOCK,
  318. VK_FORMAT_ASTC_8x5_UNORM_BLOCK,
  319. VK_FORMAT_ASTC_8x5_SRGB_BLOCK,
  320. VK_FORMAT_ASTC_8x6_UNORM_BLOCK,
  321. VK_FORMAT_ASTC_8x6_SRGB_BLOCK,
  322. VK_FORMAT_ASTC_8x8_UNORM_BLOCK,
  323. VK_FORMAT_ASTC_8x8_SRGB_BLOCK,
  324. VK_FORMAT_ASTC_10x5_UNORM_BLOCK,
  325. VK_FORMAT_ASTC_10x5_SRGB_BLOCK,
  326. VK_FORMAT_ASTC_10x6_UNORM_BLOCK,
  327. VK_FORMAT_ASTC_10x6_SRGB_BLOCK,
  328. VK_FORMAT_ASTC_10x8_UNORM_BLOCK,
  329. VK_FORMAT_ASTC_10x8_SRGB_BLOCK,
  330. VK_FORMAT_ASTC_10x10_UNORM_BLOCK,
  331. VK_FORMAT_ASTC_10x10_SRGB_BLOCK,
  332. VK_FORMAT_ASTC_12x10_UNORM_BLOCK,
  333. VK_FORMAT_ASTC_12x10_SRGB_BLOCK,
  334. VK_FORMAT_ASTC_12x12_UNORM_BLOCK,
  335. VK_FORMAT_ASTC_12x12_SRGB_BLOCK,
  336. VK_FORMAT_G8B8G8R8_422_UNORM,
  337. VK_FORMAT_B8G8R8G8_422_UNORM,
  338. VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM,
  339. VK_FORMAT_G8_B8R8_2PLANE_420_UNORM,
  340. VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM,
  341. VK_FORMAT_G8_B8R8_2PLANE_422_UNORM,
  342. VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM,
  343. VK_FORMAT_R10X6_UNORM_PACK16,
  344. VK_FORMAT_R10X6G10X6_UNORM_2PACK16,
  345. VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
  346. VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16,
  347. VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16,
  348. VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16,
  349. VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16,
  350. VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16,
  351. VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16,
  352. VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16,
  353. VK_FORMAT_R12X4_UNORM_PACK16,
  354. VK_FORMAT_R12X4G12X4_UNORM_2PACK16,
  355. VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16,
  356. VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16,
  357. VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16,
  358. VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16,
  359. VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16,
  360. VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16,
  361. VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16,
  362. VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16,
  363. VK_FORMAT_G16B16G16R16_422_UNORM,
  364. VK_FORMAT_B16G16R16G16_422_UNORM,
  365. VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM,
  366. VK_FORMAT_G16_B16R16_2PLANE_420_UNORM,
  367. VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM,
  368. VK_FORMAT_G16_B16R16_2PLANE_422_UNORM,
  369. VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM,
  370. };
  371. const char *RenderingDeviceVulkan::named_formats[RenderingDevice::DATA_FORMAT_MAX] = {
  372. "R4G4_Unorm_Pack8",
  373. "R4G4B4A4_Unorm_Pack16",
  374. "B4G4R4A4_Unorm_Pack16",
  375. "R5G6B5_Unorm_Pack16",
  376. "B5G6R5_Unorm_Pack16",
  377. "R5G5B5A1_Unorm_Pack16",
  378. "B5G5R5A1_Unorm_Pack16",
  379. "A1R5G5B5_Unorm_Pack16",
  380. "R8_Unorm",
  381. "R8_Snorm",
  382. "R8_Uscaled",
  383. "R8_Sscaled",
  384. "R8_Uint",
  385. "R8_Sint",
  386. "R8_Srgb",
  387. "R8G8_Unorm",
  388. "R8G8_Snorm",
  389. "R8G8_Uscaled",
  390. "R8G8_Sscaled",
  391. "R8G8_Uint",
  392. "R8G8_Sint",
  393. "R8G8_Srgb",
  394. "R8G8B8_Unorm",
  395. "R8G8B8_Snorm",
  396. "R8G8B8_Uscaled",
  397. "R8G8B8_Sscaled",
  398. "R8G8B8_Uint",
  399. "R8G8B8_Sint",
  400. "R8G8B8_Srgb",
  401. "B8G8R8_Unorm",
  402. "B8G8R8_Snorm",
  403. "B8G8R8_Uscaled",
  404. "B8G8R8_Sscaled",
  405. "B8G8R8_Uint",
  406. "B8G8R8_Sint",
  407. "B8G8R8_Srgb",
  408. "R8G8B8A8_Unorm",
  409. "R8G8B8A8_Snorm",
  410. "R8G8B8A8_Uscaled",
  411. "R8G8B8A8_Sscaled",
  412. "R8G8B8A8_Uint",
  413. "R8G8B8A8_Sint",
  414. "R8G8B8A8_Srgb",
  415. "B8G8R8A8_Unorm",
  416. "B8G8R8A8_Snorm",
  417. "B8G8R8A8_Uscaled",
  418. "B8G8R8A8_Sscaled",
  419. "B8G8R8A8_Uint",
  420. "B8G8R8A8_Sint",
  421. "B8G8R8A8_Srgb",
  422. "A8B8G8R8_Unorm_Pack32",
  423. "A8B8G8R8_Snorm_Pack32",
  424. "A8B8G8R8_Uscaled_Pack32",
  425. "A8B8G8R8_Sscaled_Pack32",
  426. "A8B8G8R8_Uint_Pack32",
  427. "A8B8G8R8_Sint_Pack32",
  428. "A8B8G8R8_Srgb_Pack32",
  429. "A2R10G10B10_Unorm_Pack32",
  430. "A2R10G10B10_Snorm_Pack32",
  431. "A2R10G10B10_Uscaled_Pack32",
  432. "A2R10G10B10_Sscaled_Pack32",
  433. "A2R10G10B10_Uint_Pack32",
  434. "A2R10G10B10_Sint_Pack32",
  435. "A2B10G10R10_Unorm_Pack32",
  436. "A2B10G10R10_Snorm_Pack32",
  437. "A2B10G10R10_Uscaled_Pack32",
  438. "A2B10G10R10_Sscaled_Pack32",
  439. "A2B10G10R10_Uint_Pack32",
  440. "A2B10G10R10_Sint_Pack32",
  441. "R16_Unorm",
  442. "R16_Snorm",
  443. "R16_Uscaled",
  444. "R16_Sscaled",
  445. "R16_Uint",
  446. "R16_Sint",
  447. "R16_Sfloat",
  448. "R16G16_Unorm",
  449. "R16G16_Snorm",
  450. "R16G16_Uscaled",
  451. "R16G16_Sscaled",
  452. "R16G16_Uint",
  453. "R16G16_Sint",
  454. "R16G16_Sfloat",
  455. "R16G16B16_Unorm",
  456. "R16G16B16_Snorm",
  457. "R16G16B16_Uscaled",
  458. "R16G16B16_Sscaled",
  459. "R16G16B16_Uint",
  460. "R16G16B16_Sint",
  461. "R16G16B16_Sfloat",
  462. "R16G16B16A16_Unorm",
  463. "R16G16B16A16_Snorm",
  464. "R16G16B16A16_Uscaled",
  465. "R16G16B16A16_Sscaled",
  466. "R16G16B16A16_Uint",
  467. "R16G16B16A16_Sint",
  468. "R16G16B16A16_Sfloat",
  469. "R32_Uint",
  470. "R32_Sint",
  471. "R32_Sfloat",
  472. "R32G32_Uint",
  473. "R32G32_Sint",
  474. "R32G32_Sfloat",
  475. "R32G32B32_Uint",
  476. "R32G32B32_Sint",
  477. "R32G32B32_Sfloat",
  478. "R32G32B32A32_Uint",
  479. "R32G32B32A32_Sint",
  480. "R32G32B32A32_Sfloat",
  481. "R64_Uint",
  482. "R64_Sint",
  483. "R64_Sfloat",
  484. "R64G64_Uint",
  485. "R64G64_Sint",
  486. "R64G64_Sfloat",
  487. "R64G64B64_Uint",
  488. "R64G64B64_Sint",
  489. "R64G64B64_Sfloat",
  490. "R64G64B64A64_Uint",
  491. "R64G64B64A64_Sint",
  492. "R64G64B64A64_Sfloat",
  493. "B10G11R11_Ufloat_Pack32",
  494. "E5B9G9R9_Ufloat_Pack32",
  495. "D16_Unorm",
  496. "X8_D24_Unorm_Pack32",
  497. "D32_Sfloat",
  498. "S8_Uint",
  499. "D16_Unorm_S8_Uint",
  500. "D24_Unorm_S8_Uint",
  501. "D32_Sfloat_S8_Uint",
  502. "Bc1_Rgb_Unorm_Block",
  503. "Bc1_Rgb_Srgb_Block",
  504. "Bc1_Rgba_Unorm_Block",
  505. "Bc1_Rgba_Srgb_Block",
  506. "Bc2_Unorm_Block",
  507. "Bc2_Srgb_Block",
  508. "Bc3_Unorm_Block",
  509. "Bc3_Srgb_Block",
  510. "Bc4_Unorm_Block",
  511. "Bc4_Snorm_Block",
  512. "Bc5_Unorm_Block",
  513. "Bc5_Snorm_Block",
  514. "Bc6H_Ufloat_Block",
  515. "Bc6H_Sfloat_Block",
  516. "Bc7_Unorm_Block",
  517. "Bc7_Srgb_Block",
  518. "Etc2_R8G8B8_Unorm_Block",
  519. "Etc2_R8G8B8_Srgb_Block",
  520. "Etc2_R8G8B8A1_Unorm_Block",
  521. "Etc2_R8G8B8A1_Srgb_Block",
  522. "Etc2_R8G8B8A8_Unorm_Block",
  523. "Etc2_R8G8B8A8_Srgb_Block",
  524. "Eac_R11_Unorm_Block",
  525. "Eac_R11_Snorm_Block",
  526. "Eac_R11G11_Unorm_Block",
  527. "Eac_R11G11_Snorm_Block",
  528. "Astc_4X4_Unorm_Block",
  529. "Astc_4X4_Srgb_Block",
  530. "Astc_5X4_Unorm_Block",
  531. "Astc_5X4_Srgb_Block",
  532. "Astc_5X5_Unorm_Block",
  533. "Astc_5X5_Srgb_Block",
  534. "Astc_6X5_Unorm_Block",
  535. "Astc_6X5_Srgb_Block",
  536. "Astc_6X6_Unorm_Block",
  537. "Astc_6X6_Srgb_Block",
  538. "Astc_8X5_Unorm_Block",
  539. "Astc_8X5_Srgb_Block",
  540. "Astc_8X6_Unorm_Block",
  541. "Astc_8X6_Srgb_Block",
  542. "Astc_8X8_Unorm_Block",
  543. "Astc_8X8_Srgb_Block",
  544. "Astc_10X5_Unorm_Block",
  545. "Astc_10X5_Srgb_Block",
  546. "Astc_10X6_Unorm_Block",
  547. "Astc_10X6_Srgb_Block",
  548. "Astc_10X8_Unorm_Block",
  549. "Astc_10X8_Srgb_Block",
  550. "Astc_10X10_Unorm_Block",
  551. "Astc_10X10_Srgb_Block",
  552. "Astc_12X10_Unorm_Block",
  553. "Astc_12X10_Srgb_Block",
  554. "Astc_12X12_Unorm_Block",
  555. "Astc_12X12_Srgb_Block",
  556. "G8B8G8R8_422_Unorm",
  557. "B8G8R8G8_422_Unorm",
  558. "G8_B8_R8_3Plane_420_Unorm",
  559. "G8_B8R8_2Plane_420_Unorm",
  560. "G8_B8_R8_3Plane_422_Unorm",
  561. "G8_B8R8_2Plane_422_Unorm",
  562. "G8_B8_R8_3Plane_444_Unorm",
  563. "R10X6_Unorm_Pack16",
  564. "R10X6G10X6_Unorm_2Pack16",
  565. "R10X6G10X6B10X6A10X6_Unorm_4Pack16",
  566. "G10X6B10X6G10X6R10X6_422_Unorm_4Pack16",
  567. "B10X6G10X6R10X6G10X6_422_Unorm_4Pack16",
  568. "G10X6_B10X6_R10X6_3Plane_420_Unorm_3Pack16",
  569. "G10X6_B10X6R10X6_2Plane_420_Unorm_3Pack16",
  570. "G10X6_B10X6_R10X6_3Plane_422_Unorm_3Pack16",
  571. "G10X6_B10X6R10X6_2Plane_422_Unorm_3Pack16",
  572. "G10X6_B10X6_R10X6_3Plane_444_Unorm_3Pack16",
  573. "R12X4_Unorm_Pack16",
  574. "R12X4G12X4_Unorm_2Pack16",
  575. "R12X4G12X4B12X4A12X4_Unorm_4Pack16",
  576. "G12X4B12X4G12X4R12X4_422_Unorm_4Pack16",
  577. "B12X4G12X4R12X4G12X4_422_Unorm_4Pack16",
  578. "G12X4_B12X4_R12X4_3Plane_420_Unorm_3Pack16",
  579. "G12X4_B12X4R12X4_2Plane_420_Unorm_3Pack16",
  580. "G12X4_B12X4_R12X4_3Plane_422_Unorm_3Pack16",
  581. "G12X4_B12X4R12X4_2Plane_422_Unorm_3Pack16",
  582. "G12X4_B12X4_R12X4_3Plane_444_Unorm_3Pack16",
  583. "G16B16G16R16_422_Unorm",
  584. "B16G16R16G16_422_Unorm",
  585. "G16_B16_R16_3Plane_420_Unorm",
  586. "G16_B16R16_2Plane_420_Unorm",
  587. "G16_B16_R16_3Plane_422_Unorm",
  588. "G16_B16R16_2Plane_422_Unorm",
  589. "G16_B16_R16_3Plane_444_Unorm",
  590. };
  591. int RenderingDeviceVulkan::get_format_vertex_size(DataFormat p_format) {
  592. switch (p_format) {
  593. case DATA_FORMAT_R8_UNORM:
  594. case DATA_FORMAT_R8_SNORM:
  595. case DATA_FORMAT_R8_UINT:
  596. case DATA_FORMAT_R8_SINT:
  597. case DATA_FORMAT_R8G8_UNORM:
  598. case DATA_FORMAT_R8G8_SNORM:
  599. case DATA_FORMAT_R8G8_UINT:
  600. case DATA_FORMAT_R8G8_SINT:
  601. case DATA_FORMAT_R8G8B8_UNORM:
  602. case DATA_FORMAT_R8G8B8_SNORM:
  603. case DATA_FORMAT_R8G8B8_UINT:
  604. case DATA_FORMAT_R8G8B8_SINT:
  605. case DATA_FORMAT_B8G8R8_UNORM:
  606. case DATA_FORMAT_B8G8R8_SNORM:
  607. case DATA_FORMAT_B8G8R8_UINT:
  608. case DATA_FORMAT_B8G8R8_SINT:
  609. case DATA_FORMAT_R8G8B8A8_UNORM:
  610. case DATA_FORMAT_R8G8B8A8_SNORM:
  611. case DATA_FORMAT_R8G8B8A8_UINT:
  612. case DATA_FORMAT_R8G8B8A8_SINT:
  613. case DATA_FORMAT_B8G8R8A8_UNORM:
  614. case DATA_FORMAT_B8G8R8A8_SNORM:
  615. case DATA_FORMAT_B8G8R8A8_UINT:
  616. case DATA_FORMAT_B8G8R8A8_SINT:
  617. case DATA_FORMAT_A2B10G10R10_UNORM_PACK32:
  618. return 4;
  619. case DATA_FORMAT_R16_UNORM:
  620. case DATA_FORMAT_R16_SNORM:
  621. case DATA_FORMAT_R16_UINT:
  622. case DATA_FORMAT_R16_SINT:
  623. case DATA_FORMAT_R16_SFLOAT:
  624. return 4;
  625. case DATA_FORMAT_R16G16_UNORM:
  626. case DATA_FORMAT_R16G16_SNORM:
  627. case DATA_FORMAT_R16G16_UINT:
  628. case DATA_FORMAT_R16G16_SINT:
  629. case DATA_FORMAT_R16G16_SFLOAT:
  630. return 4;
  631. case DATA_FORMAT_R16G16B16_UNORM:
  632. case DATA_FORMAT_R16G16B16_SNORM:
  633. case DATA_FORMAT_R16G16B16_UINT:
  634. case DATA_FORMAT_R16G16B16_SINT:
  635. case DATA_FORMAT_R16G16B16_SFLOAT:
  636. return 8;
  637. case DATA_FORMAT_R16G16B16A16_UNORM:
  638. case DATA_FORMAT_R16G16B16A16_SNORM:
  639. case DATA_FORMAT_R16G16B16A16_UINT:
  640. case DATA_FORMAT_R16G16B16A16_SINT:
  641. case DATA_FORMAT_R16G16B16A16_SFLOAT:
  642. return 8;
  643. case DATA_FORMAT_R32_UINT:
  644. case DATA_FORMAT_R32_SINT:
  645. case DATA_FORMAT_R32_SFLOAT:
  646. return 4;
  647. case DATA_FORMAT_R32G32_UINT:
  648. case DATA_FORMAT_R32G32_SINT:
  649. case DATA_FORMAT_R32G32_SFLOAT:
  650. return 8;
  651. case DATA_FORMAT_R32G32B32_UINT:
  652. case DATA_FORMAT_R32G32B32_SINT:
  653. case DATA_FORMAT_R32G32B32_SFLOAT:
  654. return 12;
  655. case DATA_FORMAT_R32G32B32A32_UINT:
  656. case DATA_FORMAT_R32G32B32A32_SINT:
  657. case DATA_FORMAT_R32G32B32A32_SFLOAT:
  658. return 16;
  659. case DATA_FORMAT_R64_UINT:
  660. case DATA_FORMAT_R64_SINT:
  661. case DATA_FORMAT_R64_SFLOAT:
  662. return 8;
  663. case DATA_FORMAT_R64G64_UINT:
  664. case DATA_FORMAT_R64G64_SINT:
  665. case DATA_FORMAT_R64G64_SFLOAT:
  666. return 16;
  667. case DATA_FORMAT_R64G64B64_UINT:
  668. case DATA_FORMAT_R64G64B64_SINT:
  669. case DATA_FORMAT_R64G64B64_SFLOAT:
  670. return 24;
  671. case DATA_FORMAT_R64G64B64A64_UINT:
  672. case DATA_FORMAT_R64G64B64A64_SINT:
  673. case DATA_FORMAT_R64G64B64A64_SFLOAT:
  674. return 32;
  675. default:
  676. return 0;
  677. }
  678. }
  679. uint32_t RenderingDeviceVulkan::get_image_format_pixel_size(DataFormat p_format) {
  680. switch (p_format) {
  681. case DATA_FORMAT_R4G4_UNORM_PACK8:
  682. return 1;
  683. case DATA_FORMAT_R4G4B4A4_UNORM_PACK16:
  684. case DATA_FORMAT_B4G4R4A4_UNORM_PACK16:
  685. case DATA_FORMAT_R5G6B5_UNORM_PACK16:
  686. case DATA_FORMAT_B5G6R5_UNORM_PACK16:
  687. case DATA_FORMAT_R5G5B5A1_UNORM_PACK16:
  688. case DATA_FORMAT_B5G5R5A1_UNORM_PACK16:
  689. case DATA_FORMAT_A1R5G5B5_UNORM_PACK16:
  690. return 2;
  691. case DATA_FORMAT_R8_UNORM:
  692. case DATA_FORMAT_R8_SNORM:
  693. case DATA_FORMAT_R8_USCALED:
  694. case DATA_FORMAT_R8_SSCALED:
  695. case DATA_FORMAT_R8_UINT:
  696. case DATA_FORMAT_R8_SINT:
  697. case DATA_FORMAT_R8_SRGB:
  698. return 1;
  699. case DATA_FORMAT_R8G8_UNORM:
  700. case DATA_FORMAT_R8G8_SNORM:
  701. case DATA_FORMAT_R8G8_USCALED:
  702. case DATA_FORMAT_R8G8_SSCALED:
  703. case DATA_FORMAT_R8G8_UINT:
  704. case DATA_FORMAT_R8G8_SINT:
  705. case DATA_FORMAT_R8G8_SRGB:
  706. return 2;
  707. case DATA_FORMAT_R8G8B8_UNORM:
  708. case DATA_FORMAT_R8G8B8_SNORM:
  709. case DATA_FORMAT_R8G8B8_USCALED:
  710. case DATA_FORMAT_R8G8B8_SSCALED:
  711. case DATA_FORMAT_R8G8B8_UINT:
  712. case DATA_FORMAT_R8G8B8_SINT:
  713. case DATA_FORMAT_R8G8B8_SRGB:
  714. case DATA_FORMAT_B8G8R8_UNORM:
  715. case DATA_FORMAT_B8G8R8_SNORM:
  716. case DATA_FORMAT_B8G8R8_USCALED:
  717. case DATA_FORMAT_B8G8R8_SSCALED:
  718. case DATA_FORMAT_B8G8R8_UINT:
  719. case DATA_FORMAT_B8G8R8_SINT:
  720. case DATA_FORMAT_B8G8R8_SRGB:
  721. return 3;
  722. case DATA_FORMAT_R8G8B8A8_UNORM:
  723. case DATA_FORMAT_R8G8B8A8_SNORM:
  724. case DATA_FORMAT_R8G8B8A8_USCALED:
  725. case DATA_FORMAT_R8G8B8A8_SSCALED:
  726. case DATA_FORMAT_R8G8B8A8_UINT:
  727. case DATA_FORMAT_R8G8B8A8_SINT:
  728. case DATA_FORMAT_R8G8B8A8_SRGB:
  729. case DATA_FORMAT_B8G8R8A8_UNORM:
  730. case DATA_FORMAT_B8G8R8A8_SNORM:
  731. case DATA_FORMAT_B8G8R8A8_USCALED:
  732. case DATA_FORMAT_B8G8R8A8_SSCALED:
  733. case DATA_FORMAT_B8G8R8A8_UINT:
  734. case DATA_FORMAT_B8G8R8A8_SINT:
  735. case DATA_FORMAT_B8G8R8A8_SRGB:
  736. return 4;
  737. case DATA_FORMAT_A8B8G8R8_UNORM_PACK32:
  738. case DATA_FORMAT_A8B8G8R8_SNORM_PACK32:
  739. case DATA_FORMAT_A8B8G8R8_USCALED_PACK32:
  740. case DATA_FORMAT_A8B8G8R8_SSCALED_PACK32:
  741. case DATA_FORMAT_A8B8G8R8_UINT_PACK32:
  742. case DATA_FORMAT_A8B8G8R8_SINT_PACK32:
  743. case DATA_FORMAT_A8B8G8R8_SRGB_PACK32:
  744. case DATA_FORMAT_A2R10G10B10_UNORM_PACK32:
  745. case DATA_FORMAT_A2R10G10B10_SNORM_PACK32:
  746. case DATA_FORMAT_A2R10G10B10_USCALED_PACK32:
  747. case DATA_FORMAT_A2R10G10B10_SSCALED_PACK32:
  748. case DATA_FORMAT_A2R10G10B10_UINT_PACK32:
  749. case DATA_FORMAT_A2R10G10B10_SINT_PACK32:
  750. case DATA_FORMAT_A2B10G10R10_UNORM_PACK32:
  751. case DATA_FORMAT_A2B10G10R10_SNORM_PACK32:
  752. case DATA_FORMAT_A2B10G10R10_USCALED_PACK32:
  753. case DATA_FORMAT_A2B10G10R10_SSCALED_PACK32:
  754. case DATA_FORMAT_A2B10G10R10_UINT_PACK32:
  755. case DATA_FORMAT_A2B10G10R10_SINT_PACK32:
  756. return 4;
  757. case DATA_FORMAT_R16_UNORM:
  758. case DATA_FORMAT_R16_SNORM:
  759. case DATA_FORMAT_R16_USCALED:
  760. case DATA_FORMAT_R16_SSCALED:
  761. case DATA_FORMAT_R16_UINT:
  762. case DATA_FORMAT_R16_SINT:
  763. case DATA_FORMAT_R16_SFLOAT:
  764. return 2;
  765. case DATA_FORMAT_R16G16_UNORM:
  766. case DATA_FORMAT_R16G16_SNORM:
  767. case DATA_FORMAT_R16G16_USCALED:
  768. case DATA_FORMAT_R16G16_SSCALED:
  769. case DATA_FORMAT_R16G16_UINT:
  770. case DATA_FORMAT_R16G16_SINT:
  771. case DATA_FORMAT_R16G16_SFLOAT:
  772. return 4;
  773. case DATA_FORMAT_R16G16B16_UNORM:
  774. case DATA_FORMAT_R16G16B16_SNORM:
  775. case DATA_FORMAT_R16G16B16_USCALED:
  776. case DATA_FORMAT_R16G16B16_SSCALED:
  777. case DATA_FORMAT_R16G16B16_UINT:
  778. case DATA_FORMAT_R16G16B16_SINT:
  779. case DATA_FORMAT_R16G16B16_SFLOAT:
  780. return 6;
  781. case DATA_FORMAT_R16G16B16A16_UNORM:
  782. case DATA_FORMAT_R16G16B16A16_SNORM:
  783. case DATA_FORMAT_R16G16B16A16_USCALED:
  784. case DATA_FORMAT_R16G16B16A16_SSCALED:
  785. case DATA_FORMAT_R16G16B16A16_UINT:
  786. case DATA_FORMAT_R16G16B16A16_SINT:
  787. case DATA_FORMAT_R16G16B16A16_SFLOAT:
  788. return 8;
  789. case DATA_FORMAT_R32_UINT:
  790. case DATA_FORMAT_R32_SINT:
  791. case DATA_FORMAT_R32_SFLOAT:
  792. return 4;
  793. case DATA_FORMAT_R32G32_UINT:
  794. case DATA_FORMAT_R32G32_SINT:
  795. case DATA_FORMAT_R32G32_SFLOAT:
  796. return 8;
  797. case DATA_FORMAT_R32G32B32_UINT:
  798. case DATA_FORMAT_R32G32B32_SINT:
  799. case DATA_FORMAT_R32G32B32_SFLOAT:
  800. return 12;
  801. case DATA_FORMAT_R32G32B32A32_UINT:
  802. case DATA_FORMAT_R32G32B32A32_SINT:
  803. case DATA_FORMAT_R32G32B32A32_SFLOAT:
  804. return 16;
  805. case DATA_FORMAT_R64_UINT:
  806. case DATA_FORMAT_R64_SINT:
  807. case DATA_FORMAT_R64_SFLOAT:
  808. return 8;
  809. case DATA_FORMAT_R64G64_UINT:
  810. case DATA_FORMAT_R64G64_SINT:
  811. case DATA_FORMAT_R64G64_SFLOAT:
  812. return 16;
  813. case DATA_FORMAT_R64G64B64_UINT:
  814. case DATA_FORMAT_R64G64B64_SINT:
  815. case DATA_FORMAT_R64G64B64_SFLOAT:
  816. return 24;
  817. case DATA_FORMAT_R64G64B64A64_UINT:
  818. case DATA_FORMAT_R64G64B64A64_SINT:
  819. case DATA_FORMAT_R64G64B64A64_SFLOAT:
  820. return 32;
  821. case DATA_FORMAT_B10G11R11_UFLOAT_PACK32:
  822. case DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32:
  823. return 4;
  824. case DATA_FORMAT_D16_UNORM:
  825. return 2;
  826. case DATA_FORMAT_X8_D24_UNORM_PACK32:
  827. return 4;
  828. case DATA_FORMAT_D32_SFLOAT:
  829. return 4;
  830. case DATA_FORMAT_S8_UINT:
  831. return 1;
  832. case DATA_FORMAT_D16_UNORM_S8_UINT:
  833. return 4;
  834. case DATA_FORMAT_D24_UNORM_S8_UINT:
  835. return 4;
  836. case DATA_FORMAT_D32_SFLOAT_S8_UINT:
  837. return 5; //?
  838. case DATA_FORMAT_BC1_RGB_UNORM_BLOCK:
  839. case DATA_FORMAT_BC1_RGB_SRGB_BLOCK:
  840. case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK:
  841. case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK:
  842. case DATA_FORMAT_BC2_UNORM_BLOCK:
  843. case DATA_FORMAT_BC2_SRGB_BLOCK:
  844. case DATA_FORMAT_BC3_UNORM_BLOCK:
  845. case DATA_FORMAT_BC3_SRGB_BLOCK:
  846. case DATA_FORMAT_BC4_UNORM_BLOCK:
  847. case DATA_FORMAT_BC4_SNORM_BLOCK:
  848. case DATA_FORMAT_BC5_UNORM_BLOCK:
  849. case DATA_FORMAT_BC5_SNORM_BLOCK:
  850. case DATA_FORMAT_BC6H_UFLOAT_BLOCK:
  851. case DATA_FORMAT_BC6H_SFLOAT_BLOCK:
  852. case DATA_FORMAT_BC7_UNORM_BLOCK:
  853. case DATA_FORMAT_BC7_SRGB_BLOCK:
  854. return 1;
  855. case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK:
  856. case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK:
  857. case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK:
  858. case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK:
  859. case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK:
  860. case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK:
  861. return 1;
  862. case DATA_FORMAT_EAC_R11_UNORM_BLOCK:
  863. case DATA_FORMAT_EAC_R11_SNORM_BLOCK:
  864. case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK:
  865. case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK:
  866. return 1;
  867. case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK:
  868. case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK:
  869. case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK:
  870. case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK:
  871. case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK:
  872. case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK:
  873. case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK:
  874. case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK:
  875. case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK:
  876. case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK:
  877. case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK:
  878. case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK:
  879. case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK:
  880. case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK:
  881. case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK:
  882. case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK:
  883. case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK:
  884. case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK:
  885. case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK:
  886. case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK:
  887. case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK:
  888. case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK:
  889. case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK:
  890. case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK:
  891. case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK:
  892. case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK:
  893. case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK:
  894. case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK:
  895. return 1;
  896. case DATA_FORMAT_G8B8G8R8_422_UNORM:
  897. case DATA_FORMAT_B8G8R8G8_422_UNORM:
  898. return 4;
  899. case DATA_FORMAT_G8_B8_R8_3PLANE_420_UNORM:
  900. case DATA_FORMAT_G8_B8R8_2PLANE_420_UNORM:
  901. case DATA_FORMAT_G8_B8_R8_3PLANE_422_UNORM:
  902. case DATA_FORMAT_G8_B8R8_2PLANE_422_UNORM:
  903. case DATA_FORMAT_G8_B8_R8_3PLANE_444_UNORM:
  904. return 4;
  905. case DATA_FORMAT_R10X6_UNORM_PACK16:
  906. case DATA_FORMAT_R10X6G10X6_UNORM_2PACK16:
  907. case DATA_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
  908. case DATA_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16:
  909. case DATA_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16:
  910. case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16:
  911. case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16:
  912. case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16:
  913. case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16:
  914. case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16:
  915. case DATA_FORMAT_R12X4_UNORM_PACK16:
  916. case DATA_FORMAT_R12X4G12X4_UNORM_2PACK16:
  917. case DATA_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16:
  918. case DATA_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16:
  919. case DATA_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16:
  920. case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16:
  921. case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16:
  922. case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16:
  923. case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16:
  924. case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16:
  925. return 2;
  926. case DATA_FORMAT_G16B16G16R16_422_UNORM:
  927. case DATA_FORMAT_B16G16R16G16_422_UNORM:
  928. case DATA_FORMAT_G16_B16_R16_3PLANE_420_UNORM:
  929. case DATA_FORMAT_G16_B16R16_2PLANE_420_UNORM:
  930. case DATA_FORMAT_G16_B16_R16_3PLANE_422_UNORM:
  931. case DATA_FORMAT_G16_B16R16_2PLANE_422_UNORM:
  932. case DATA_FORMAT_G16_B16_R16_3PLANE_444_UNORM:
  933. return 8;
  934. default: {
  935. ERR_PRINT("Format not handled, bug");
  936. }
  937. }
  938. return 1;
  939. }
  940. // https://www.khronos.org/registry/DataFormat/specs/1.1/dataformat.1.1.pdf
  941. void RenderingDeviceVulkan::get_compressed_image_format_block_dimensions(DataFormat p_format, uint32_t &r_w, uint32_t &r_h) {
  942. switch (p_format) {
  943. case DATA_FORMAT_BC1_RGB_UNORM_BLOCK:
  944. case DATA_FORMAT_BC1_RGB_SRGB_BLOCK:
  945. case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK:
  946. case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK:
  947. case DATA_FORMAT_BC2_UNORM_BLOCK:
  948. case DATA_FORMAT_BC2_SRGB_BLOCK:
  949. case DATA_FORMAT_BC3_UNORM_BLOCK:
  950. case DATA_FORMAT_BC3_SRGB_BLOCK:
  951. case DATA_FORMAT_BC4_UNORM_BLOCK:
  952. case DATA_FORMAT_BC4_SNORM_BLOCK:
  953. case DATA_FORMAT_BC5_UNORM_BLOCK:
  954. case DATA_FORMAT_BC5_SNORM_BLOCK:
  955. case DATA_FORMAT_BC6H_UFLOAT_BLOCK:
  956. case DATA_FORMAT_BC6H_SFLOAT_BLOCK:
  957. case DATA_FORMAT_BC7_UNORM_BLOCK:
  958. case DATA_FORMAT_BC7_SRGB_BLOCK:
  959. case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK:
  960. case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK:
  961. case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK:
  962. case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK:
  963. case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK:
  964. case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK:
  965. case DATA_FORMAT_EAC_R11_UNORM_BLOCK:
  966. case DATA_FORMAT_EAC_R11_SNORM_BLOCK:
  967. case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK:
  968. case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK:
  969. case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK: //again, not sure about astc
  970. case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK:
  971. case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK:
  972. case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK:
  973. case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK:
  974. case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK:
  975. case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK:
  976. case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK:
  977. case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK:
  978. case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK:
  979. case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK:
  980. case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK:
  981. case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK:
  982. case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK:
  983. case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK:
  984. case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK:
  985. case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK:
  986. case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK:
  987. case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK:
  988. case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK:
  989. case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK:
  990. case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK:
  991. case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK:
  992. case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK:
  993. case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK:
  994. case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK:
  995. case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK:
  996. case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK:
  997. r_w = 4;
  998. r_h = 4;
  999. return;
  1000. default: {
  1001. r_w = 1;
  1002. r_h = 1;
  1003. }
  1004. }
  1005. }
  1006. uint32_t RenderingDeviceVulkan::get_compressed_image_format_block_byte_size(DataFormat p_format) {
  1007. switch (p_format) {
  1008. case DATA_FORMAT_BC1_RGB_UNORM_BLOCK:
  1009. case DATA_FORMAT_BC1_RGB_SRGB_BLOCK:
  1010. case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK:
  1011. case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK:
  1012. return 8;
  1013. case DATA_FORMAT_BC2_UNORM_BLOCK:
  1014. case DATA_FORMAT_BC2_SRGB_BLOCK:
  1015. return 16;
  1016. case DATA_FORMAT_BC3_UNORM_BLOCK:
  1017. case DATA_FORMAT_BC3_SRGB_BLOCK:
  1018. return 16;
  1019. case DATA_FORMAT_BC4_UNORM_BLOCK:
  1020. case DATA_FORMAT_BC4_SNORM_BLOCK:
  1021. return 8;
  1022. case DATA_FORMAT_BC5_UNORM_BLOCK:
  1023. case DATA_FORMAT_BC5_SNORM_BLOCK:
  1024. return 16;
  1025. case DATA_FORMAT_BC6H_UFLOAT_BLOCK:
  1026. case DATA_FORMAT_BC6H_SFLOAT_BLOCK:
  1027. return 16;
  1028. case DATA_FORMAT_BC7_UNORM_BLOCK:
  1029. case DATA_FORMAT_BC7_SRGB_BLOCK:
  1030. return 16;
  1031. case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK:
  1032. case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK:
  1033. return 8;
  1034. case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK:
  1035. case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK:
  1036. return 8;
  1037. case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK:
  1038. case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK:
  1039. return 16;
  1040. case DATA_FORMAT_EAC_R11_UNORM_BLOCK:
  1041. case DATA_FORMAT_EAC_R11_SNORM_BLOCK:
  1042. return 8;
  1043. case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK:
  1044. case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK:
  1045. return 16;
  1046. case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK: //again, not sure about astc
  1047. case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK:
  1048. case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK:
  1049. case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK:
  1050. case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK:
  1051. case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK:
  1052. case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK:
  1053. case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK:
  1054. case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK:
  1055. case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK:
  1056. case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK:
  1057. case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK:
  1058. case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK:
  1059. case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK:
  1060. case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK:
  1061. case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK:
  1062. case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK:
  1063. case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK:
  1064. case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK:
  1065. case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK:
  1066. case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK:
  1067. case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK:
  1068. case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK:
  1069. case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK:
  1070. case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK:
  1071. case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK:
  1072. case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK:
  1073. case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK:
  1074. return 8; //wrong
  1075. default: {
  1076. }
  1077. }
  1078. return 1;
  1079. }
  1080. uint32_t RenderingDeviceVulkan::get_compressed_image_format_pixel_rshift(DataFormat p_format) {
  1081. switch (p_format) {
  1082. case DATA_FORMAT_BC1_RGB_UNORM_BLOCK: //these formats are half byte size, so rshift is 1
  1083. case DATA_FORMAT_BC1_RGB_SRGB_BLOCK:
  1084. case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK:
  1085. case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK:
  1086. case DATA_FORMAT_BC4_UNORM_BLOCK:
  1087. case DATA_FORMAT_BC4_SNORM_BLOCK:
  1088. case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK:
  1089. case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK:
  1090. case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK:
  1091. case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK:
  1092. case DATA_FORMAT_EAC_R11_UNORM_BLOCK:
  1093. case DATA_FORMAT_EAC_R11_SNORM_BLOCK:
  1094. return 1;
  1095. default: {
  1096. }
  1097. }
  1098. return 0;
  1099. }
  1100. bool RenderingDeviceVulkan::format_has_stencil(DataFormat p_format) {
  1101. switch (p_format) {
  1102. case DATA_FORMAT_S8_UINT:
  1103. case DATA_FORMAT_D16_UNORM_S8_UINT:
  1104. case DATA_FORMAT_D24_UNORM_S8_UINT:
  1105. case DATA_FORMAT_D32_SFLOAT_S8_UINT: {
  1106. return true;
  1107. }
  1108. default: {
  1109. }
  1110. }
  1111. return false;
  1112. }
  1113. uint32_t RenderingDeviceVulkan::get_image_format_required_size(DataFormat p_format, uint32_t p_width, uint32_t p_height, uint32_t p_depth, uint32_t p_mipmaps, uint32_t *r_blockw, uint32_t *r_blockh, uint32_t *r_depth) {
  1114. ERR_FAIL_COND_V(p_mipmaps == 0, 0);
  1115. uint32_t w = p_width;
  1116. uint32_t h = p_height;
  1117. uint32_t d = p_depth;
  1118. uint32_t size = 0;
  1119. uint32_t pixel_size = get_image_format_pixel_size(p_format);
  1120. uint32_t pixel_rshift = get_compressed_image_format_pixel_rshift(p_format);
  1121. uint32_t blockw, blockh;
  1122. get_compressed_image_format_block_dimensions(p_format, blockw, blockh);
  1123. for (uint32_t i = 0; i < p_mipmaps; i++) {
  1124. uint32_t bw = w % blockw != 0 ? w + (blockw - w % blockw) : w;
  1125. uint32_t bh = h % blockh != 0 ? h + (blockh - h % blockh) : h;
  1126. uint32_t s = bw * bh;
  1127. s *= pixel_size;
  1128. s >>= pixel_rshift;
  1129. size += s * d;
  1130. if (r_blockw) {
  1131. *r_blockw = bw;
  1132. }
  1133. if (r_blockh) {
  1134. *r_blockh = bh;
  1135. }
  1136. if (r_depth) {
  1137. *r_depth = d;
  1138. }
  1139. w = MAX(blockw, w >> 1);
  1140. h = MAX(blockh, h >> 1);
  1141. d = MAX(1u, d >> 1);
  1142. }
  1143. return size;
  1144. }
  1145. uint32_t RenderingDeviceVulkan::get_image_required_mipmaps(uint32_t p_width, uint32_t p_height, uint32_t p_depth) {
  1146. //formats and block size don't really matter here since they can all go down to 1px (even if block is larger)
  1147. uint32_t w = p_width;
  1148. uint32_t h = p_height;
  1149. uint32_t d = p_depth;
  1150. uint32_t mipmaps = 1;
  1151. while (true) {
  1152. if (w == 1 && h == 1 && d == 1) {
  1153. break;
  1154. }
  1155. w = MAX(1u, w >> 1);
  1156. h = MAX(1u, h >> 1);
  1157. d = MAX(1u, d >> 1);
  1158. mipmaps++;
  1159. }
  1160. return mipmaps;
  1161. }
  1162. ///////////////////////
  1163. const VkCompareOp RenderingDeviceVulkan::compare_operators[RenderingDevice::COMPARE_OP_MAX] = {
  1164. VK_COMPARE_OP_NEVER,
  1165. VK_COMPARE_OP_LESS,
  1166. VK_COMPARE_OP_EQUAL,
  1167. VK_COMPARE_OP_LESS_OR_EQUAL,
  1168. VK_COMPARE_OP_GREATER,
  1169. VK_COMPARE_OP_NOT_EQUAL,
  1170. VK_COMPARE_OP_GREATER_OR_EQUAL,
  1171. VK_COMPARE_OP_ALWAYS
  1172. };
  1173. const VkStencilOp RenderingDeviceVulkan::stencil_operations[RenderingDevice::STENCIL_OP_MAX] = {
  1174. VK_STENCIL_OP_KEEP,
  1175. VK_STENCIL_OP_ZERO,
  1176. VK_STENCIL_OP_REPLACE,
  1177. VK_STENCIL_OP_INCREMENT_AND_CLAMP,
  1178. VK_STENCIL_OP_DECREMENT_AND_CLAMP,
  1179. VK_STENCIL_OP_INVERT,
  1180. VK_STENCIL_OP_INCREMENT_AND_WRAP,
  1181. VK_STENCIL_OP_DECREMENT_AND_WRAP
  1182. };
  1183. const VkSampleCountFlagBits RenderingDeviceVulkan::rasterization_sample_count[RenderingDevice::TEXTURE_SAMPLES_MAX] = {
  1184. VK_SAMPLE_COUNT_1_BIT,
  1185. VK_SAMPLE_COUNT_2_BIT,
  1186. VK_SAMPLE_COUNT_4_BIT,
  1187. VK_SAMPLE_COUNT_8_BIT,
  1188. VK_SAMPLE_COUNT_16_BIT,
  1189. VK_SAMPLE_COUNT_32_BIT,
  1190. VK_SAMPLE_COUNT_64_BIT,
  1191. };
  1192. const VkLogicOp RenderingDeviceVulkan::logic_operations[RenderingDevice::LOGIC_OP_MAX] = {
  1193. VK_LOGIC_OP_CLEAR,
  1194. VK_LOGIC_OP_AND,
  1195. VK_LOGIC_OP_AND_REVERSE,
  1196. VK_LOGIC_OP_COPY,
  1197. VK_LOGIC_OP_AND_INVERTED,
  1198. VK_LOGIC_OP_NO_OP,
  1199. VK_LOGIC_OP_XOR,
  1200. VK_LOGIC_OP_OR,
  1201. VK_LOGIC_OP_NOR,
  1202. VK_LOGIC_OP_EQUIVALENT,
  1203. VK_LOGIC_OP_INVERT,
  1204. VK_LOGIC_OP_OR_REVERSE,
  1205. VK_LOGIC_OP_COPY_INVERTED,
  1206. VK_LOGIC_OP_OR_INVERTED,
  1207. VK_LOGIC_OP_NAND,
  1208. VK_LOGIC_OP_SET
  1209. };
  1210. const VkBlendFactor RenderingDeviceVulkan::blend_factors[RenderingDevice::BLEND_FACTOR_MAX] = {
  1211. VK_BLEND_FACTOR_ZERO,
  1212. VK_BLEND_FACTOR_ONE,
  1213. VK_BLEND_FACTOR_SRC_COLOR,
  1214. VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR,
  1215. VK_BLEND_FACTOR_DST_COLOR,
  1216. VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR,
  1217. VK_BLEND_FACTOR_SRC_ALPHA,
  1218. VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
  1219. VK_BLEND_FACTOR_DST_ALPHA,
  1220. VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA,
  1221. VK_BLEND_FACTOR_CONSTANT_COLOR,
  1222. VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR,
  1223. VK_BLEND_FACTOR_CONSTANT_ALPHA,
  1224. VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA,
  1225. VK_BLEND_FACTOR_SRC_ALPHA_SATURATE,
  1226. VK_BLEND_FACTOR_SRC1_COLOR,
  1227. VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR,
  1228. VK_BLEND_FACTOR_SRC1_ALPHA,
  1229. VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA
  1230. };
  1231. const VkBlendOp RenderingDeviceVulkan::blend_operations[RenderingDevice::BLEND_OP_MAX] = {
  1232. VK_BLEND_OP_ADD,
  1233. VK_BLEND_OP_SUBTRACT,
  1234. VK_BLEND_OP_REVERSE_SUBTRACT,
  1235. VK_BLEND_OP_MIN,
  1236. VK_BLEND_OP_MAX
  1237. };
  1238. const VkSamplerAddressMode RenderingDeviceVulkan::address_modes[RenderingDevice::SAMPLER_REPEAT_MODE_MAX] = {
  1239. VK_SAMPLER_ADDRESS_MODE_REPEAT,
  1240. VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT,
  1241. VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
  1242. VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
  1243. VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE
  1244. };
  1245. const VkBorderColor RenderingDeviceVulkan::sampler_border_colors[RenderingDevice::SAMPLER_BORDER_COLOR_MAX] = {
  1246. VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK,
  1247. VK_BORDER_COLOR_INT_TRANSPARENT_BLACK,
  1248. VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK,
  1249. VK_BORDER_COLOR_INT_OPAQUE_BLACK,
  1250. VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
  1251. VK_BORDER_COLOR_INT_OPAQUE_WHITE
  1252. };
  1253. const VkImageType RenderingDeviceVulkan::vulkan_image_type[RenderingDevice::TEXTURE_TYPE_MAX] = {
  1254. VK_IMAGE_TYPE_1D,
  1255. VK_IMAGE_TYPE_2D,
  1256. VK_IMAGE_TYPE_3D,
  1257. VK_IMAGE_TYPE_2D,
  1258. VK_IMAGE_TYPE_1D,
  1259. VK_IMAGE_TYPE_2D,
  1260. VK_IMAGE_TYPE_2D
  1261. };
  1262. /***************************/
  1263. /**** BUFFER MANAGEMENT ****/
  1264. /***************************/
  1265. Error RenderingDeviceVulkan::_buffer_allocate(Buffer *p_buffer, uint32_t p_size, uint32_t p_usage, VmaMemoryUsage p_mem_usage, VmaAllocationCreateFlags p_mem_flags) {
  1266. VkBufferCreateInfo bufferInfo;
  1267. bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  1268. bufferInfo.pNext = nullptr;
  1269. bufferInfo.flags = 0;
  1270. bufferInfo.size = p_size;
  1271. bufferInfo.usage = p_usage;
  1272. bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1273. bufferInfo.queueFamilyIndexCount = 0;
  1274. bufferInfo.pQueueFamilyIndices = nullptr;
  1275. VmaAllocationCreateInfo allocInfo;
  1276. allocInfo.flags = p_mem_flags;
  1277. allocInfo.usage = p_mem_usage;
  1278. allocInfo.requiredFlags = 0;
  1279. allocInfo.preferredFlags = 0;
  1280. allocInfo.memoryTypeBits = 0;
  1281. allocInfo.pool = nullptr;
  1282. allocInfo.pUserData = nullptr;
  1283. if (p_size <= SMALL_ALLOCATION_MAX_SIZE) {
  1284. uint32_t mem_type_index = 0;
  1285. vmaFindMemoryTypeIndexForBufferInfo(allocator, &bufferInfo, &allocInfo, &mem_type_index);
  1286. allocInfo.pool = _find_or_create_small_allocs_pool(mem_type_index);
  1287. }
  1288. VkResult err = vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &p_buffer->buffer, &p_buffer->allocation, nullptr);
  1289. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "Can't create buffer of size: " + itos(p_size) + ", error " + itos(err) + ".");
  1290. p_buffer->size = p_size;
  1291. p_buffer->buffer_info.buffer = p_buffer->buffer;
  1292. p_buffer->buffer_info.offset = 0;
  1293. p_buffer->buffer_info.range = p_size;
  1294. p_buffer->usage = p_usage;
  1295. buffer_memory += p_size;
  1296. return OK;
  1297. }
  1298. Error RenderingDeviceVulkan::_buffer_free(Buffer *p_buffer) {
  1299. ERR_FAIL_COND_V(p_buffer->size == 0, ERR_INVALID_PARAMETER);
  1300. buffer_memory -= p_buffer->size;
  1301. vmaDestroyBuffer(allocator, p_buffer->buffer, p_buffer->allocation);
  1302. p_buffer->buffer = VK_NULL_HANDLE;
  1303. p_buffer->allocation = nullptr;
  1304. p_buffer->size = 0;
  1305. return OK;
  1306. }
  1307. Error RenderingDeviceVulkan::_insert_staging_block() {
  1308. VkBufferCreateInfo bufferInfo;
  1309. bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  1310. bufferInfo.pNext = nullptr;
  1311. bufferInfo.flags = 0;
  1312. bufferInfo.size = staging_buffer_block_size;
  1313. bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  1314. bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1315. bufferInfo.queueFamilyIndexCount = 0;
  1316. bufferInfo.pQueueFamilyIndices = nullptr;
  1317. VmaAllocationCreateInfo allocInfo;
  1318. allocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
  1319. allocInfo.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST;
  1320. allocInfo.requiredFlags = 0;
  1321. allocInfo.preferredFlags = 0;
  1322. allocInfo.memoryTypeBits = 0;
  1323. allocInfo.pool = nullptr;
  1324. allocInfo.pUserData = nullptr;
  1325. StagingBufferBlock block;
  1326. VkResult err = vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &block.buffer, &block.allocation, nullptr);
  1327. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vmaCreateBuffer failed with error " + itos(err) + ".");
  1328. block.frame_used = 0;
  1329. block.fill_amount = 0;
  1330. staging_buffer_blocks.insert(staging_buffer_current, block);
  1331. return OK;
  1332. }
  1333. Error RenderingDeviceVulkan::_staging_buffer_allocate(uint32_t p_amount, uint32_t p_required_align, uint32_t &r_alloc_offset, uint32_t &r_alloc_size, bool p_can_segment, bool p_on_draw_command_buffer) {
  1334. //determine a block to use
  1335. r_alloc_size = p_amount;
  1336. while (true) {
  1337. r_alloc_offset = 0;
  1338. //see if we can use current block
  1339. if (staging_buffer_blocks[staging_buffer_current].frame_used == frames_drawn) {
  1340. //we used this block this frame, let's see if there is still room
  1341. uint32_t write_from = staging_buffer_blocks[staging_buffer_current].fill_amount;
  1342. {
  1343. uint32_t align_remainder = write_from % p_required_align;
  1344. if (align_remainder != 0) {
  1345. write_from += p_required_align - align_remainder;
  1346. }
  1347. }
  1348. int32_t available_bytes = int32_t(staging_buffer_block_size) - int32_t(write_from);
  1349. if ((int32_t)p_amount < available_bytes) {
  1350. //all is good, we should be ok, all will fit
  1351. r_alloc_offset = write_from;
  1352. } else if (p_can_segment && available_bytes >= (int32_t)p_required_align) {
  1353. //ok all won't fit but at least we can fit a chunkie
  1354. //all is good, update what needs to be written to
  1355. r_alloc_offset = write_from;
  1356. r_alloc_size = available_bytes - (available_bytes % p_required_align);
  1357. } else {
  1358. //can't fit it into this buffer.
  1359. //will need to try next buffer
  1360. staging_buffer_current = (staging_buffer_current + 1) % staging_buffer_blocks.size();
  1361. // before doing anything, though, let's check that we didn't manage to fill all blocks
  1362. // possible in a single frame
  1363. if (staging_buffer_blocks[staging_buffer_current].frame_used == frames_drawn) {
  1364. //guess we did.. ok, let's see if we can insert a new block..
  1365. if ((uint64_t)staging_buffer_blocks.size() * staging_buffer_block_size < staging_buffer_max_size) {
  1366. //we can, so we are safe
  1367. Error err = _insert_staging_block();
  1368. if (err) {
  1369. return err;
  1370. }
  1371. //claim for this frame
  1372. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  1373. } else {
  1374. // Ok, worst case scenario, all the staging buffers belong to this frame
  1375. // and this frame is not even done.
  1376. // If this is the main thread, it means the user is likely loading a lot of resources at once,
  1377. // otherwise, the thread should just be blocked until the next frame (currently unimplemented)
  1378. if (false) { //separate thread from render
  1379. //block_until_next_frame()
  1380. continue;
  1381. } else {
  1382. //flush EVERYTHING including setup commands. IF not immediate, also need to flush the draw commands
  1383. _flush(true);
  1384. //clear the whole staging buffer
  1385. for (int i = 0; i < staging_buffer_blocks.size(); i++) {
  1386. staging_buffer_blocks.write[i].frame_used = 0;
  1387. staging_buffer_blocks.write[i].fill_amount = 0;
  1388. }
  1389. //claim current
  1390. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  1391. }
  1392. }
  1393. } else {
  1394. //not from current frame, so continue and try again
  1395. continue;
  1396. }
  1397. }
  1398. } else if (staging_buffer_blocks[staging_buffer_current].frame_used <= frames_drawn - frame_count) {
  1399. //this is an old block, which was already processed, let's reuse
  1400. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  1401. staging_buffer_blocks.write[staging_buffer_current].fill_amount = 0;
  1402. } else {
  1403. //this block may still be in use, let's not touch it unless we have to, so.. can we create a new one?
  1404. if ((uint64_t)staging_buffer_blocks.size() * staging_buffer_block_size < staging_buffer_max_size) {
  1405. //we are still allowed to create a new block, so let's do that and insert it for current pos
  1406. Error err = _insert_staging_block();
  1407. if (err) {
  1408. return err;
  1409. }
  1410. //claim for this frame
  1411. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  1412. } else {
  1413. // oops, we are out of room and we can't create more.
  1414. // let's flush older frames.
  1415. // 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.
  1416. // If loading from a separate thread, we can block that thread until next frame when more room is made (not currently implemented, though).
  1417. if (false) {
  1418. //separate thread from render
  1419. //block_until_next_frame()
  1420. continue; //and try again
  1421. } else {
  1422. _flush(false);
  1423. for (int i = 0; i < staging_buffer_blocks.size(); i++) {
  1424. //clear all blocks but the ones from this frame
  1425. int block_idx = (i + staging_buffer_current) % staging_buffer_blocks.size();
  1426. if (staging_buffer_blocks[block_idx].frame_used == frames_drawn) {
  1427. break; //ok, we reached something from this frame, abort
  1428. }
  1429. staging_buffer_blocks.write[block_idx].frame_used = 0;
  1430. staging_buffer_blocks.write[block_idx].fill_amount = 0;
  1431. }
  1432. //claim for current frame
  1433. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  1434. }
  1435. }
  1436. }
  1437. //all was good, break
  1438. break;
  1439. }
  1440. staging_buffer_used = true;
  1441. return OK;
  1442. }
  1443. Error RenderingDeviceVulkan::_buffer_update(Buffer *p_buffer, size_t p_offset, const uint8_t *p_data, size_t p_data_size, bool p_use_draw_command_buffer, uint32_t p_required_align) {
  1444. //submitting may get chunked for various reasons, so convert this to a task
  1445. size_t to_submit = p_data_size;
  1446. size_t submit_from = 0;
  1447. while (to_submit > 0) {
  1448. uint32_t block_write_offset;
  1449. uint32_t block_write_amount;
  1450. Error err = _staging_buffer_allocate(MIN(to_submit, staging_buffer_block_size), p_required_align, block_write_offset, block_write_amount, p_use_draw_command_buffer);
  1451. if (err) {
  1452. return err;
  1453. }
  1454. //map staging buffer (It's CPU and coherent)
  1455. void *data_ptr = nullptr;
  1456. {
  1457. VkResult vkerr = vmaMapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation, &data_ptr);
  1458. ERR_FAIL_COND_V_MSG(vkerr, ERR_CANT_CREATE, "vmaMapMemory failed with error " + itos(vkerr) + ".");
  1459. }
  1460. //copy to staging buffer
  1461. memcpy(((uint8_t *)data_ptr) + block_write_offset, p_data + submit_from, block_write_amount);
  1462. //unmap
  1463. vmaUnmapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation);
  1464. //insert a command to copy this
  1465. VkBufferCopy region;
  1466. region.srcOffset = block_write_offset;
  1467. region.dstOffset = submit_from + p_offset;
  1468. region.size = block_write_amount;
  1469. vkCmdCopyBuffer(p_use_draw_command_buffer ? frames[frame].draw_command_buffer : frames[frame].setup_command_buffer, staging_buffer_blocks[staging_buffer_current].buffer, p_buffer->buffer, 1, &region);
  1470. staging_buffer_blocks.write[staging_buffer_current].fill_amount = block_write_offset + block_write_amount;
  1471. to_submit -= block_write_amount;
  1472. submit_from += block_write_amount;
  1473. }
  1474. return OK;
  1475. }
  1476. void RenderingDeviceVulkan::_memory_barrier(VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_sccess, bool p_sync_with_draw) {
  1477. VkMemoryBarrier mem_barrier;
  1478. mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  1479. mem_barrier.pNext = nullptr;
  1480. mem_barrier.srcAccessMask = p_src_access;
  1481. mem_barrier.dstAccessMask = p_dst_sccess;
  1482. if (p_src_stage_mask == 0 || p_dst_stage_mask == 0) {
  1483. return; //no barrier, since this is invalid
  1484. }
  1485. vkCmdPipelineBarrier(p_sync_with_draw ? frames[frame].draw_command_buffer : frames[frame].setup_command_buffer, p_src_stage_mask, p_dst_stage_mask, 0, 1, &mem_barrier, 0, nullptr, 0, nullptr);
  1486. }
  1487. void RenderingDeviceVulkan::_full_barrier(bool p_sync_with_draw) {
  1488. //used for debug
  1489. _memory_barrier(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
  1490. VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  1491. VK_ACCESS_INDEX_READ_BIT |
  1492. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  1493. VK_ACCESS_UNIFORM_READ_BIT |
  1494. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  1495. VK_ACCESS_SHADER_READ_BIT |
  1496. VK_ACCESS_SHADER_WRITE_BIT |
  1497. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  1498. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  1499. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  1500. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  1501. VK_ACCESS_TRANSFER_READ_BIT |
  1502. VK_ACCESS_TRANSFER_WRITE_BIT |
  1503. VK_ACCESS_HOST_READ_BIT |
  1504. VK_ACCESS_HOST_WRITE_BIT,
  1505. VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  1506. VK_ACCESS_INDEX_READ_BIT |
  1507. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  1508. VK_ACCESS_UNIFORM_READ_BIT |
  1509. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  1510. VK_ACCESS_SHADER_READ_BIT |
  1511. VK_ACCESS_SHADER_WRITE_BIT |
  1512. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  1513. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  1514. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  1515. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  1516. VK_ACCESS_TRANSFER_READ_BIT |
  1517. VK_ACCESS_TRANSFER_WRITE_BIT |
  1518. VK_ACCESS_HOST_READ_BIT |
  1519. VK_ACCESS_HOST_WRITE_BIT,
  1520. p_sync_with_draw);
  1521. }
  1522. void RenderingDeviceVulkan::_buffer_memory_barrier(VkBuffer buffer, uint64_t p_from, uint64_t p_size, VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_sccess, bool p_sync_with_draw) {
  1523. VkBufferMemoryBarrier buffer_mem_barrier;
  1524. buffer_mem_barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
  1525. buffer_mem_barrier.pNext = nullptr;
  1526. buffer_mem_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  1527. buffer_mem_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  1528. buffer_mem_barrier.srcAccessMask = p_src_access;
  1529. buffer_mem_barrier.dstAccessMask = p_dst_sccess;
  1530. buffer_mem_barrier.buffer = buffer;
  1531. buffer_mem_barrier.offset = p_from;
  1532. buffer_mem_barrier.size = p_size;
  1533. vkCmdPipelineBarrier(p_sync_with_draw ? frames[frame].draw_command_buffer : frames[frame].setup_command_buffer, p_src_stage_mask, p_dst_stage_mask, 0, 0, nullptr, 1, &buffer_mem_barrier, 0, nullptr);
  1534. }
  1535. /*****************/
  1536. /**** TEXTURE ****/
  1537. /*****************/
  1538. RID RenderingDeviceVulkan::texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector<Vector<uint8_t>> &p_data) {
  1539. _THREAD_SAFE_METHOD_
  1540. VkImageCreateInfo image_create_info;
  1541. image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  1542. image_create_info.pNext = nullptr;
  1543. image_create_info.flags = 0;
  1544. #ifndef _MSC_VER
  1545. #warning TODO check for support via RenderingDevice to enable on mobile when possible
  1546. #endif
  1547. #ifndef ANDROID_ENABLED
  1548. // vkCreateImage fails with format list on Android (VK_ERROR_OUT_OF_HOST_MEMORY)
  1549. VkImageFormatListCreateInfoKHR format_list_create_info; //keep out of the if, needed for creation
  1550. Vector<VkFormat> allowed_formats; //keep out of the if, needed for creation
  1551. #endif
  1552. if (p_format.shareable_formats.size()) {
  1553. image_create_info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
  1554. #ifndef ANDROID_ENABLED
  1555. for (int i = 0; i < p_format.shareable_formats.size(); i++) {
  1556. allowed_formats.push_back(vulkan_formats[p_format.shareable_formats[i]]);
  1557. }
  1558. format_list_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO_KHR;
  1559. format_list_create_info.pNext = nullptr;
  1560. format_list_create_info.viewFormatCount = allowed_formats.size();
  1561. format_list_create_info.pViewFormats = allowed_formats.ptr();
  1562. image_create_info.pNext = &format_list_create_info;
  1563. ERR_FAIL_COND_V_MSG(p_format.shareable_formats.find(p_format.format) == -1, RID(),
  1564. "If supplied a list of shareable formats, the current format must be present in the list");
  1565. ERR_FAIL_COND_V_MSG(p_view.format_override != DATA_FORMAT_MAX && p_format.shareable_formats.find(p_view.format_override) == -1, RID(),
  1566. "If supplied a list of shareable formats, the current view format override must be present in the list");
  1567. #endif
  1568. }
  1569. if (p_format.texture_type == TEXTURE_TYPE_CUBE || p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY) {
  1570. image_create_info.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
  1571. }
  1572. /*if (p_format.type == TEXTURE_TYPE_2D || p_format.type == TEXTURE_TYPE_2D_ARRAY) {
  1573. image_create_info.flags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT;
  1574. }*/
  1575. ERR_FAIL_INDEX_V(p_format.texture_type, TEXTURE_TYPE_MAX, RID());
  1576. image_create_info.imageType = vulkan_image_type[p_format.texture_type];
  1577. ERR_FAIL_COND_V_MSG(p_format.width < 1, RID(), "Width must be equal or greater than 1 for all textures");
  1578. image_create_info.format = vulkan_formats[p_format.format];
  1579. image_create_info.extent.width = p_format.width;
  1580. if (image_create_info.imageType == VK_IMAGE_TYPE_3D || image_create_info.imageType == VK_IMAGE_TYPE_2D) {
  1581. ERR_FAIL_COND_V_MSG(p_format.height < 1, RID(), "Height must be equal or greater than 1 for 2D and 3D textures");
  1582. image_create_info.extent.height = p_format.height;
  1583. } else {
  1584. image_create_info.extent.height = 1;
  1585. }
  1586. if (image_create_info.imageType == VK_IMAGE_TYPE_3D) {
  1587. ERR_FAIL_COND_V_MSG(p_format.depth < 1, RID(), "Depth must be equal or greater than 1 for 3D textures");
  1588. image_create_info.extent.depth = p_format.depth;
  1589. } else {
  1590. image_create_info.extent.depth = 1;
  1591. }
  1592. ERR_FAIL_COND_V(p_format.mipmaps < 1, RID());
  1593. image_create_info.mipLevels = p_format.mipmaps;
  1594. if (p_format.texture_type == TEXTURE_TYPE_1D_ARRAY || p_format.texture_type == TEXTURE_TYPE_2D_ARRAY || p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || p_format.texture_type == TEXTURE_TYPE_CUBE) {
  1595. ERR_FAIL_COND_V_MSG(p_format.array_layers < 1, RID(),
  1596. "Amount of layers must be equal or greater than 1 for arrays and cubemaps.");
  1597. ERR_FAIL_COND_V_MSG((p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || p_format.texture_type == TEXTURE_TYPE_CUBE) && (p_format.array_layers % 6) != 0, RID(),
  1598. "Cubemap and cubemap array textures must provide a layer number that is multiple of 6");
  1599. image_create_info.arrayLayers = p_format.array_layers;
  1600. } else {
  1601. image_create_info.arrayLayers = 1;
  1602. }
  1603. ERR_FAIL_INDEX_V(p_format.samples, TEXTURE_SAMPLES_MAX, RID());
  1604. image_create_info.samples = rasterization_sample_count[p_format.samples];
  1605. image_create_info.tiling = (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) ? VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
  1606. //usage
  1607. image_create_info.usage = 0;
  1608. if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) {
  1609. image_create_info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
  1610. }
  1611. if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) {
  1612. image_create_info.usage |= VK_IMAGE_USAGE_STORAGE_BIT;
  1613. }
  1614. if (p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  1615. image_create_info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  1616. }
  1617. if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1618. image_create_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  1619. }
  1620. if (p_format.usage_bits & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT) {
  1621. image_create_info.usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
  1622. }
  1623. if (p_format.usage_bits & TEXTURE_USAGE_CAN_UPDATE_BIT) {
  1624. image_create_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1625. }
  1626. if (p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_FROM_BIT) {
  1627. image_create_info.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
  1628. }
  1629. if (p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_TO_BIT) {
  1630. image_create_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1631. }
  1632. image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1633. image_create_info.queueFamilyIndexCount = 0;
  1634. image_create_info.pQueueFamilyIndices = nullptr;
  1635. image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  1636. uint32_t required_mipmaps = get_image_required_mipmaps(image_create_info.extent.width, image_create_info.extent.height, image_create_info.extent.depth);
  1637. ERR_FAIL_COND_V_MSG(required_mipmaps < image_create_info.mipLevels, RID(),
  1638. "Too many mipmaps requested for texture format and dimensions (" + itos(image_create_info.mipLevels) + "), maximum allowed: (" + itos(required_mipmaps) + ").");
  1639. if (p_data.size()) {
  1640. ERR_FAIL_COND_V_MSG(!(p_format.usage_bits & TEXTURE_USAGE_CAN_UPDATE_BIT), RID(),
  1641. "Texture needs the TEXTURE_USAGE_CAN_UPDATE_BIT usage flag in order to be updated at initialization or later");
  1642. int expected_images = image_create_info.arrayLayers;
  1643. ERR_FAIL_COND_V_MSG(p_data.size() != expected_images, RID(),
  1644. "Default supplied data for image format is of invalid length (" + itos(p_data.size()) + "), should be (" + itos(expected_images) + ").");
  1645. for (uint32_t i = 0; i < image_create_info.arrayLayers; i++) {
  1646. uint32_t required_size = get_image_format_required_size(p_format.format, image_create_info.extent.width, image_create_info.extent.height, image_create_info.extent.depth, image_create_info.mipLevels);
  1647. ERR_FAIL_COND_V_MSG((uint32_t)p_data[i].size() != required_size, RID(),
  1648. "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) + ").");
  1649. }
  1650. }
  1651. {
  1652. //validate that this image is supported for the intended use
  1653. VkFormatProperties properties;
  1654. vkGetPhysicalDeviceFormatProperties(context->get_physical_device(), image_create_info.format, &properties);
  1655. VkFormatFeatureFlags flags;
  1656. String format_text = "'" + String(named_formats[p_format.format]) + "'";
  1657. if (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) {
  1658. flags = properties.linearTilingFeatures;
  1659. format_text += " (with CPU read bit)";
  1660. } else {
  1661. flags = properties.optimalTilingFeatures;
  1662. }
  1663. if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT && !(flags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) {
  1664. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as sampling texture.");
  1665. }
  1666. if (p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) {
  1667. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as color attachment.");
  1668. }
  1669. if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  1670. printf("vkformat: %x\n", image_create_info.format);
  1671. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as depth-stencil attachment.");
  1672. }
  1673. if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) {
  1674. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as storage image.");
  1675. }
  1676. if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_ATOMIC_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT)) {
  1677. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as atomic storage image.");
  1678. }
  1679. }
  1680. //some view validation
  1681. if (p_view.format_override != DATA_FORMAT_MAX) {
  1682. ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());
  1683. }
  1684. ERR_FAIL_INDEX_V(p_view.swizzle_r, TEXTURE_SWIZZLE_MAX, RID());
  1685. ERR_FAIL_INDEX_V(p_view.swizzle_g, TEXTURE_SWIZZLE_MAX, RID());
  1686. ERR_FAIL_INDEX_V(p_view.swizzle_b, TEXTURE_SWIZZLE_MAX, RID());
  1687. ERR_FAIL_INDEX_V(p_view.swizzle_a, TEXTURE_SWIZZLE_MAX, RID());
  1688. //allocate memory
  1689. uint32_t width, height;
  1690. uint32_t image_size = get_image_format_required_size(p_format.format, p_format.width, p_format.height, p_format.depth, p_format.mipmaps, &width, &height);
  1691. VmaAllocationCreateInfo allocInfo;
  1692. allocInfo.flags = (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) ? VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT : 0;
  1693. allocInfo.pool = nullptr;
  1694. allocInfo.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE;
  1695. allocInfo.requiredFlags = 0;
  1696. allocInfo.preferredFlags = 0;
  1697. allocInfo.memoryTypeBits = 0;
  1698. allocInfo.pUserData = nullptr;
  1699. if (image_size <= SMALL_ALLOCATION_MAX_SIZE) {
  1700. uint32_t mem_type_index = 0;
  1701. vmaFindMemoryTypeIndexForImageInfo(allocator, &image_create_info, &allocInfo, &mem_type_index);
  1702. allocInfo.pool = _find_or_create_small_allocs_pool(mem_type_index);
  1703. }
  1704. Texture texture;
  1705. VkResult err = vmaCreateImage(allocator, &image_create_info, &allocInfo, &texture.image, &texture.allocation, &texture.allocation_info);
  1706. ERR_FAIL_COND_V_MSG(err, RID(), "vmaCreateImage failed with error " + itos(err) + ".");
  1707. image_memory += texture.allocation_info.size;
  1708. texture.type = p_format.texture_type;
  1709. texture.format = p_format.format;
  1710. texture.width = image_create_info.extent.width;
  1711. texture.height = image_create_info.extent.height;
  1712. texture.depth = image_create_info.extent.depth;
  1713. texture.layers = image_create_info.arrayLayers;
  1714. texture.mipmaps = image_create_info.mipLevels;
  1715. texture.base_mipmap = 0;
  1716. texture.base_layer = 0;
  1717. texture.usage_flags = p_format.usage_bits;
  1718. texture.samples = p_format.samples;
  1719. texture.allowed_shared_formats = p_format.shareable_formats;
  1720. //set base layout based on usage priority
  1721. if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) {
  1722. //first priority, readable
  1723. texture.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  1724. } else if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) {
  1725. //second priority, storage
  1726. texture.layout = VK_IMAGE_LAYOUT_GENERAL;
  1727. } else if (p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  1728. //third priority, color or depth
  1729. texture.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1730. } else if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1731. texture.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  1732. } else {
  1733. texture.layout = VK_IMAGE_LAYOUT_GENERAL;
  1734. }
  1735. if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1736. texture.read_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1737. texture.barrier_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1738. if (format_has_stencil(p_format.format)) {
  1739. texture.barrier_aspect_mask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  1740. }
  1741. } else {
  1742. texture.read_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT;
  1743. texture.barrier_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT;
  1744. }
  1745. texture.bound = false;
  1746. //create view
  1747. VkImageViewCreateInfo image_view_create_info;
  1748. image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1749. image_view_create_info.pNext = nullptr;
  1750. image_view_create_info.flags = 0;
  1751. image_view_create_info.image = texture.image;
  1752. static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = {
  1753. VK_IMAGE_VIEW_TYPE_1D,
  1754. VK_IMAGE_VIEW_TYPE_2D,
  1755. VK_IMAGE_VIEW_TYPE_3D,
  1756. VK_IMAGE_VIEW_TYPE_CUBE,
  1757. VK_IMAGE_VIEW_TYPE_1D_ARRAY,
  1758. VK_IMAGE_VIEW_TYPE_2D_ARRAY,
  1759. VK_IMAGE_VIEW_TYPE_CUBE_ARRAY,
  1760. };
  1761. image_view_create_info.viewType = view_types[p_format.texture_type];
  1762. if (p_view.format_override == DATA_FORMAT_MAX) {
  1763. image_view_create_info.format = image_create_info.format;
  1764. } else {
  1765. image_view_create_info.format = vulkan_formats[p_view.format_override];
  1766. }
  1767. static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  1768. VK_COMPONENT_SWIZZLE_IDENTITY,
  1769. VK_COMPONENT_SWIZZLE_ZERO,
  1770. VK_COMPONENT_SWIZZLE_ONE,
  1771. VK_COMPONENT_SWIZZLE_R,
  1772. VK_COMPONENT_SWIZZLE_G,
  1773. VK_COMPONENT_SWIZZLE_B,
  1774. VK_COMPONENT_SWIZZLE_A
  1775. };
  1776. image_view_create_info.components.r = component_swizzles[p_view.swizzle_r];
  1777. image_view_create_info.components.g = component_swizzles[p_view.swizzle_g];
  1778. image_view_create_info.components.b = component_swizzles[p_view.swizzle_b];
  1779. image_view_create_info.components.a = component_swizzles[p_view.swizzle_a];
  1780. image_view_create_info.subresourceRange.baseMipLevel = 0;
  1781. image_view_create_info.subresourceRange.levelCount = image_create_info.mipLevels;
  1782. image_view_create_info.subresourceRange.baseArrayLayer = 0;
  1783. image_view_create_info.subresourceRange.layerCount = image_create_info.arrayLayers;
  1784. if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1785. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1786. } else {
  1787. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  1788. }
  1789. err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view);
  1790. if (err) {
  1791. vmaDestroyImage(allocator, texture.image, texture.allocation);
  1792. ERR_FAIL_V_MSG(RID(), "vkCreateImageView failed with error " + itos(err) + ".");
  1793. }
  1794. //barrier to set layout
  1795. {
  1796. VkImageMemoryBarrier image_memory_barrier;
  1797. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  1798. image_memory_barrier.pNext = nullptr;
  1799. image_memory_barrier.srcAccessMask = 0;
  1800. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  1801. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  1802. image_memory_barrier.newLayout = texture.layout;
  1803. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  1804. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  1805. image_memory_barrier.image = texture.image;
  1806. image_memory_barrier.subresourceRange.aspectMask = texture.barrier_aspect_mask;
  1807. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  1808. image_memory_barrier.subresourceRange.levelCount = image_create_info.mipLevels;
  1809. image_memory_barrier.subresourceRange.baseArrayLayer = 0;
  1810. image_memory_barrier.subresourceRange.layerCount = image_create_info.arrayLayers;
  1811. vkCmdPipelineBarrier(frames[frame].setup_command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  1812. }
  1813. RID id = texture_owner.make_rid(texture);
  1814. if (p_data.size()) {
  1815. for (uint32_t i = 0; i < image_create_info.arrayLayers; i++) {
  1816. _texture_update(id, i, p_data[i], RD::BARRIER_MASK_ALL, true);
  1817. }
  1818. }
  1819. return id;
  1820. }
  1821. RID RenderingDeviceVulkan::texture_create_shared(const TextureView &p_view, RID p_with_texture) {
  1822. _THREAD_SAFE_METHOD_
  1823. Texture *src_texture = texture_owner.get_or_null(p_with_texture);
  1824. ERR_FAIL_COND_V(!src_texture, RID());
  1825. if (src_texture->owner.is_valid()) { //ahh this is a share
  1826. p_with_texture = src_texture->owner;
  1827. src_texture = texture_owner.get_or_null(src_texture->owner);
  1828. ERR_FAIL_COND_V(!src_texture, RID()); //this is a bug
  1829. }
  1830. //create view
  1831. Texture texture = *src_texture;
  1832. VkImageViewCreateInfo image_view_create_info;
  1833. image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1834. image_view_create_info.pNext = nullptr;
  1835. image_view_create_info.flags = 0;
  1836. image_view_create_info.image = texture.image;
  1837. static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = {
  1838. VK_IMAGE_VIEW_TYPE_1D,
  1839. VK_IMAGE_VIEW_TYPE_2D,
  1840. VK_IMAGE_VIEW_TYPE_3D,
  1841. VK_IMAGE_VIEW_TYPE_CUBE,
  1842. VK_IMAGE_VIEW_TYPE_1D_ARRAY,
  1843. VK_IMAGE_VIEW_TYPE_2D_ARRAY,
  1844. VK_IMAGE_VIEW_TYPE_CUBE_ARRAY,
  1845. };
  1846. image_view_create_info.viewType = view_types[texture.type];
  1847. if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) {
  1848. image_view_create_info.format = vulkan_formats[texture.format];
  1849. } else {
  1850. ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());
  1851. ERR_FAIL_COND_V_MSG(texture.allowed_shared_formats.find(p_view.format_override) == -1, RID(),
  1852. "Format override is not in the list of allowed shareable formats for original texture.");
  1853. image_view_create_info.format = vulkan_formats[p_view.format_override];
  1854. }
  1855. static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  1856. VK_COMPONENT_SWIZZLE_IDENTITY,
  1857. VK_COMPONENT_SWIZZLE_ZERO,
  1858. VK_COMPONENT_SWIZZLE_ONE,
  1859. VK_COMPONENT_SWIZZLE_R,
  1860. VK_COMPONENT_SWIZZLE_G,
  1861. VK_COMPONENT_SWIZZLE_B,
  1862. VK_COMPONENT_SWIZZLE_A
  1863. };
  1864. image_view_create_info.components.r = component_swizzles[p_view.swizzle_r];
  1865. image_view_create_info.components.g = component_swizzles[p_view.swizzle_g];
  1866. image_view_create_info.components.b = component_swizzles[p_view.swizzle_b];
  1867. image_view_create_info.components.a = component_swizzles[p_view.swizzle_a];
  1868. image_view_create_info.subresourceRange.baseMipLevel = 0;
  1869. image_view_create_info.subresourceRange.levelCount = texture.mipmaps;
  1870. image_view_create_info.subresourceRange.layerCount = texture.layers;
  1871. image_view_create_info.subresourceRange.baseArrayLayer = 0;
  1872. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1873. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1874. } else {
  1875. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  1876. }
  1877. VkImageViewUsageCreateInfo usage_info;
  1878. usage_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO;
  1879. usage_info.pNext = nullptr;
  1880. if (p_view.format_override != DATA_FORMAT_MAX) {
  1881. //need to validate usage with vulkan
  1882. usage_info.usage = 0;
  1883. if (texture.usage_flags & TEXTURE_USAGE_SAMPLING_BIT) {
  1884. usage_info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
  1885. }
  1886. if (texture.usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  1887. if (texture_is_format_supported_for_usage(p_view.format_override, TEXTURE_USAGE_STORAGE_BIT)) {
  1888. usage_info.usage |= VK_IMAGE_USAGE_STORAGE_BIT;
  1889. }
  1890. }
  1891. if (texture.usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  1892. if (texture_is_format_supported_for_usage(p_view.format_override, TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) {
  1893. usage_info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  1894. }
  1895. }
  1896. if (texture.usage_flags & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT) {
  1897. usage_info.usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
  1898. }
  1899. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1900. usage_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  1901. }
  1902. if (texture.usage_flags & TEXTURE_USAGE_CAN_UPDATE_BIT) {
  1903. usage_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1904. }
  1905. if (texture.usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT) {
  1906. usage_info.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
  1907. }
  1908. if (texture.usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT) {
  1909. usage_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1910. }
  1911. image_view_create_info.pNext = &usage_info;
  1912. }
  1913. VkResult err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view);
  1914. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateImageView failed with error " + itos(err) + ".");
  1915. texture.owner = p_with_texture;
  1916. RID id = texture_owner.make_rid(texture);
  1917. _add_dependency(id, p_with_texture);
  1918. return id;
  1919. }
  1920. RID RenderingDeviceVulkan::texture_create_from_extension(TextureType p_type, DataFormat p_format, TextureSamples p_samples, uint64_t p_flags, uint64_t p_image, uint64_t p_width, uint64_t p_height, uint64_t p_depth, uint64_t p_layers) {
  1921. _THREAD_SAFE_METHOD_
  1922. // This method creates a texture object using a VkImage created by an extension, module or other external source (OpenXR uses this).
  1923. VkImage image = (VkImage)p_image;
  1924. Texture texture;
  1925. texture.image = image;
  1926. // if we leave texture.allocation as a nullptr, would that be enough to detect we don't "own" the image?
  1927. // also leave texture.allocation_info alone
  1928. // we'll set texture.view later on
  1929. texture.type = p_type;
  1930. texture.format = p_format;
  1931. texture.samples = p_samples;
  1932. texture.width = p_width;
  1933. texture.height = p_height;
  1934. texture.depth = p_depth;
  1935. texture.layers = p_layers;
  1936. texture.mipmaps = 0; // maybe make this settable too?
  1937. texture.usage_flags = p_flags;
  1938. texture.base_mipmap = 0;
  1939. texture.base_layer = 0;
  1940. texture.allowed_shared_formats.push_back(RD::DATA_FORMAT_R8G8B8A8_UNORM);
  1941. texture.allowed_shared_formats.push_back(RD::DATA_FORMAT_R8G8B8A8_SRGB);
  1942. // Do we need to do something with texture.layout ?
  1943. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1944. texture.read_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1945. texture.barrier_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1946. // if (format_has_stencil(p_format.format)) {
  1947. // texture.barrier_aspect_mask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  1948. // }
  1949. } else {
  1950. texture.read_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT;
  1951. texture.barrier_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT;
  1952. }
  1953. // Create a view for us to use
  1954. VkImageViewCreateInfo image_view_create_info;
  1955. image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1956. image_view_create_info.pNext = nullptr;
  1957. image_view_create_info.flags = 0;
  1958. image_view_create_info.image = texture.image;
  1959. static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = {
  1960. VK_IMAGE_VIEW_TYPE_1D,
  1961. VK_IMAGE_VIEW_TYPE_2D,
  1962. VK_IMAGE_VIEW_TYPE_3D,
  1963. VK_IMAGE_VIEW_TYPE_CUBE,
  1964. VK_IMAGE_VIEW_TYPE_1D_ARRAY,
  1965. VK_IMAGE_VIEW_TYPE_2D_ARRAY,
  1966. VK_IMAGE_VIEW_TYPE_CUBE_ARRAY,
  1967. };
  1968. image_view_create_info.viewType = view_types[texture.type];
  1969. image_view_create_info.format = vulkan_formats[texture.format];
  1970. static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  1971. VK_COMPONENT_SWIZZLE_IDENTITY,
  1972. VK_COMPONENT_SWIZZLE_ZERO,
  1973. VK_COMPONENT_SWIZZLE_ONE,
  1974. VK_COMPONENT_SWIZZLE_R,
  1975. VK_COMPONENT_SWIZZLE_G,
  1976. VK_COMPONENT_SWIZZLE_B,
  1977. VK_COMPONENT_SWIZZLE_A
  1978. };
  1979. // hardcode for now, maybe make this settable from outside..
  1980. image_view_create_info.components.r = component_swizzles[TEXTURE_SWIZZLE_R];
  1981. image_view_create_info.components.g = component_swizzles[TEXTURE_SWIZZLE_G];
  1982. image_view_create_info.components.b = component_swizzles[TEXTURE_SWIZZLE_B];
  1983. image_view_create_info.components.a = component_swizzles[TEXTURE_SWIZZLE_A];
  1984. image_view_create_info.subresourceRange.baseMipLevel = 0;
  1985. image_view_create_info.subresourceRange.levelCount = texture.mipmaps;
  1986. image_view_create_info.subresourceRange.baseArrayLayer = 0;
  1987. image_view_create_info.subresourceRange.layerCount = texture.layers;
  1988. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1989. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1990. } else {
  1991. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  1992. }
  1993. VkResult err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view);
  1994. if (err) {
  1995. // vmaDestroyImage(allocator, texture.image, texture.allocation);
  1996. ERR_FAIL_V_MSG(RID(), "vkCreateImageView failed with error " + itos(err) + ".");
  1997. }
  1998. //barrier to set layout
  1999. {
  2000. VkImageMemoryBarrier image_memory_barrier;
  2001. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2002. image_memory_barrier.pNext = nullptr;
  2003. image_memory_barrier.srcAccessMask = 0;
  2004. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2005. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2006. image_memory_barrier.newLayout = texture.layout;
  2007. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2008. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2009. image_memory_barrier.image = texture.image;
  2010. image_memory_barrier.subresourceRange.aspectMask = texture.barrier_aspect_mask;
  2011. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2012. image_memory_barrier.subresourceRange.levelCount = texture.mipmaps;
  2013. image_memory_barrier.subresourceRange.baseArrayLayer = 0;
  2014. image_memory_barrier.subresourceRange.layerCount = texture.layers;
  2015. vkCmdPipelineBarrier(frames[frame].setup_command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2016. }
  2017. RID id = texture_owner.make_rid(texture);
  2018. return id;
  2019. }
  2020. RID RenderingDeviceVulkan::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) {
  2021. _THREAD_SAFE_METHOD_
  2022. Texture *src_texture = texture_owner.get_or_null(p_with_texture);
  2023. ERR_FAIL_COND_V(!src_texture, RID());
  2024. if (src_texture->owner.is_valid()) { //ahh this is a share
  2025. p_with_texture = src_texture->owner;
  2026. src_texture = texture_owner.get_or_null(src_texture->owner);
  2027. ERR_FAIL_COND_V(!src_texture, RID()); //this is a bug
  2028. }
  2029. 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(),
  2030. "Can only create a cubemap slice from a cubemap or cubemap array mipmap");
  2031. ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_3D && src_texture->type != TEXTURE_TYPE_3D, RID(),
  2032. "Can only create a 3D slice from a 3D texture");
  2033. ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_2D_ARRAY && (src_texture->type != TEXTURE_TYPE_2D_ARRAY), RID(),
  2034. "Can only create an array slice from a 2D array mipmap");
  2035. //create view
  2036. ERR_FAIL_UNSIGNED_INDEX_V(p_mipmap, src_texture->mipmaps, RID());
  2037. ERR_FAIL_COND_V(p_mipmap + p_mipmaps > src_texture->mipmaps, RID());
  2038. ERR_FAIL_UNSIGNED_INDEX_V(p_layer, src_texture->layers, RID());
  2039. int slice_layers = 1;
  2040. if (p_slice_type == TEXTURE_SLICE_2D_ARRAY) {
  2041. ERR_FAIL_COND_V_MSG(p_layer != 0, RID(), "layer must be 0 when obtaining a 2D array mipmap slice");
  2042. slice_layers = src_texture->layers;
  2043. } else if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {
  2044. slice_layers = 6;
  2045. }
  2046. Texture texture = *src_texture;
  2047. get_image_format_required_size(texture.format, texture.width, texture.height, texture.depth, p_mipmap + 1, &texture.width, &texture.height);
  2048. texture.mipmaps = p_mipmaps;
  2049. texture.layers = slice_layers;
  2050. texture.base_mipmap = p_mipmap;
  2051. texture.base_layer = p_layer;
  2052. VkImageViewCreateInfo image_view_create_info;
  2053. image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  2054. image_view_create_info.pNext = nullptr;
  2055. image_view_create_info.flags = 0;
  2056. image_view_create_info.image = texture.image;
  2057. static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = {
  2058. VK_IMAGE_VIEW_TYPE_1D,
  2059. VK_IMAGE_VIEW_TYPE_2D,
  2060. VK_IMAGE_VIEW_TYPE_2D,
  2061. VK_IMAGE_VIEW_TYPE_2D,
  2062. VK_IMAGE_VIEW_TYPE_1D,
  2063. VK_IMAGE_VIEW_TYPE_2D,
  2064. VK_IMAGE_VIEW_TYPE_2D,
  2065. };
  2066. image_view_create_info.viewType = view_types[texture.type];
  2067. if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {
  2068. image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_CUBE;
  2069. } else if (p_slice_type == TEXTURE_SLICE_3D) {
  2070. image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_3D;
  2071. } else if (p_slice_type == TEXTURE_SLICE_2D_ARRAY) {
  2072. image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY;
  2073. }
  2074. if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) {
  2075. image_view_create_info.format = vulkan_formats[texture.format];
  2076. } else {
  2077. ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());
  2078. ERR_FAIL_COND_V_MSG(texture.allowed_shared_formats.find(p_view.format_override) == -1, RID(),
  2079. "Format override is not in the list of allowed shareable formats for original texture.");
  2080. image_view_create_info.format = vulkan_formats[p_view.format_override];
  2081. }
  2082. static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  2083. VK_COMPONENT_SWIZZLE_IDENTITY,
  2084. VK_COMPONENT_SWIZZLE_ZERO,
  2085. VK_COMPONENT_SWIZZLE_ONE,
  2086. VK_COMPONENT_SWIZZLE_R,
  2087. VK_COMPONENT_SWIZZLE_G,
  2088. VK_COMPONENT_SWIZZLE_B,
  2089. VK_COMPONENT_SWIZZLE_A
  2090. };
  2091. image_view_create_info.components.r = component_swizzles[p_view.swizzle_r];
  2092. image_view_create_info.components.g = component_swizzles[p_view.swizzle_g];
  2093. image_view_create_info.components.b = component_swizzles[p_view.swizzle_b];
  2094. image_view_create_info.components.a = component_swizzles[p_view.swizzle_a];
  2095. if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {
  2096. ERR_FAIL_COND_V_MSG(p_layer >= src_texture->layers, RID(),
  2097. "Specified layer is invalid for cubemap");
  2098. ERR_FAIL_COND_V_MSG((p_layer % 6) != 0, RID(),
  2099. "Specified layer must be a multiple of 6.");
  2100. }
  2101. image_view_create_info.subresourceRange.baseMipLevel = p_mipmap;
  2102. image_view_create_info.subresourceRange.levelCount = p_mipmaps;
  2103. image_view_create_info.subresourceRange.layerCount = slice_layers;
  2104. image_view_create_info.subresourceRange.baseArrayLayer = p_layer;
  2105. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2106. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  2107. } else {
  2108. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2109. }
  2110. VkResult err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view);
  2111. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateImageView failed with error " + itos(err) + ".");
  2112. texture.owner = p_with_texture;
  2113. RID id = texture_owner.make_rid(texture);
  2114. _add_dependency(id, p_with_texture);
  2115. return id;
  2116. }
  2117. Error RenderingDeviceVulkan::texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, uint32_t p_post_barrier) {
  2118. return _texture_update(p_texture, p_layer, p_data, p_post_barrier, false);
  2119. }
  2120. Error RenderingDeviceVulkan::_texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, uint32_t p_post_barrier, bool p_use_setup_queue) {
  2121. _THREAD_SAFE_METHOD_
  2122. ERR_FAIL_COND_V_MSG((draw_list || compute_list) && !p_use_setup_queue, ERR_INVALID_PARAMETER,
  2123. "Updating textures is forbidden during creation of a draw or compute list");
  2124. Texture *texture = texture_owner.get_or_null(p_texture);
  2125. ERR_FAIL_COND_V(!texture, ERR_INVALID_PARAMETER);
  2126. if (texture->owner != RID()) {
  2127. p_texture = texture->owner;
  2128. texture = texture_owner.get_or_null(texture->owner);
  2129. ERR_FAIL_COND_V(!texture, ERR_BUG); //this is a bug
  2130. }
  2131. ERR_FAIL_COND_V_MSG(texture->bound, ERR_CANT_ACQUIRE_RESOURCE,
  2132. "Texture can't be updated while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2133. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_CAN_UPDATE_BIT), ERR_INVALID_PARAMETER,
  2134. "Texture requires the TEXTURE_USAGE_CAN_UPDATE_BIT in order to be updatable.");
  2135. uint32_t layer_count = texture->layers;
  2136. if (texture->type == TEXTURE_TYPE_CUBE || texture->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2137. layer_count *= 6;
  2138. }
  2139. ERR_FAIL_COND_V(p_layer >= layer_count, ERR_INVALID_PARAMETER);
  2140. uint32_t width, height;
  2141. uint32_t image_size = get_image_format_required_size(texture->format, texture->width, texture->height, texture->depth, texture->mipmaps, &width, &height);
  2142. uint32_t required_size = image_size;
  2143. uint32_t required_align = get_compressed_image_format_block_byte_size(texture->format);
  2144. if (required_align == 1) {
  2145. required_align = get_image_format_pixel_size(texture->format);
  2146. }
  2147. if ((required_align % 4) != 0) { //alignment rules are really strange
  2148. required_align *= 4;
  2149. }
  2150. ERR_FAIL_COND_V_MSG(required_size != (uint32_t)p_data.size(), ERR_INVALID_PARAMETER,
  2151. "Required size for texture update (" + itos(required_size) + ") does not match data supplied size (" + itos(p_data.size()) + ").");
  2152. uint32_t region_size = texture_upload_region_size_px;
  2153. const uint8_t *r = p_data.ptr();
  2154. VkCommandBuffer command_buffer = p_use_setup_queue ? frames[frame].setup_command_buffer : frames[frame].draw_command_buffer;
  2155. //barrier to transfer
  2156. {
  2157. VkImageMemoryBarrier image_memory_barrier;
  2158. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2159. image_memory_barrier.pNext = nullptr;
  2160. image_memory_barrier.srcAccessMask = 0;
  2161. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2162. image_memory_barrier.oldLayout = texture->layout;
  2163. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2164. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2165. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2166. image_memory_barrier.image = texture->image;
  2167. image_memory_barrier.subresourceRange.aspectMask = texture->barrier_aspect_mask;
  2168. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2169. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  2170. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2171. image_memory_barrier.subresourceRange.layerCount = 1;
  2172. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2173. }
  2174. uint32_t mipmap_offset = 0;
  2175. uint32_t logic_width = texture->width;
  2176. uint32_t logic_height = texture->height;
  2177. for (uint32_t mm_i = 0; mm_i < texture->mipmaps; mm_i++) {
  2178. uint32_t depth;
  2179. uint32_t image_total = get_image_format_required_size(texture->format, texture->width, texture->height, texture->depth, mm_i + 1, &width, &height, &depth);
  2180. const uint8_t *read_ptr_mipmap = r + mipmap_offset;
  2181. image_size = image_total - mipmap_offset;
  2182. for (uint32_t z = 0; z < depth; z++) { //for 3D textures, depth may be > 0
  2183. const uint8_t *read_ptr = read_ptr_mipmap + image_size * z / depth;
  2184. for (uint32_t x = 0; x < width; x += region_size) {
  2185. for (uint32_t y = 0; y < height; y += region_size) {
  2186. uint32_t region_w = MIN(region_size, width - x);
  2187. uint32_t region_h = MIN(region_size, height - y);
  2188. uint32_t region_logic_w = MIN(region_size, logic_width - x);
  2189. uint32_t region_logic_h = MIN(region_size, logic_height - y);
  2190. uint32_t pixel_size = get_image_format_pixel_size(texture->format);
  2191. uint32_t to_allocate = region_w * region_h * pixel_size;
  2192. to_allocate >>= get_compressed_image_format_pixel_rshift(texture->format);
  2193. uint32_t alloc_offset, alloc_size;
  2194. Error err = _staging_buffer_allocate(to_allocate, required_align, alloc_offset, alloc_size, false, !p_use_setup_queue);
  2195. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  2196. uint8_t *write_ptr;
  2197. { //map
  2198. void *data_ptr = nullptr;
  2199. VkResult vkerr = vmaMapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation, &data_ptr);
  2200. ERR_FAIL_COND_V_MSG(vkerr, ERR_CANT_CREATE, "vmaMapMemory failed with error " + itos(vkerr) + ".");
  2201. write_ptr = (uint8_t *)data_ptr;
  2202. write_ptr += alloc_offset;
  2203. }
  2204. uint32_t block_w, block_h;
  2205. get_compressed_image_format_block_dimensions(texture->format, block_w, block_h);
  2206. ERR_FAIL_COND_V(region_w % block_w, ERR_BUG);
  2207. ERR_FAIL_COND_V(region_h % block_h, ERR_BUG);
  2208. if (block_w != 1 || block_h != 1) {
  2209. //compressed image (blocks)
  2210. //must copy a block region
  2211. uint32_t block_size = get_compressed_image_format_block_byte_size(texture->format);
  2212. //re-create current variables in blocky format
  2213. uint32_t xb = x / block_w;
  2214. uint32_t yb = y / block_h;
  2215. uint32_t wb = width / block_w;
  2216. //uint32_t hb = height / block_h;
  2217. uint32_t region_wb = region_w / block_w;
  2218. uint32_t region_hb = region_h / block_h;
  2219. for (uint32_t xr = 0; xr < region_wb; xr++) {
  2220. for (uint32_t yr = 0; yr < region_hb; yr++) {
  2221. uint32_t src_offset = ((yr + yb) * wb + xr + xb) * block_size;
  2222. uint32_t dst_offset = (yr * region_wb + xr) * block_size;
  2223. //copy block
  2224. for (uint32_t i = 0; i < block_size; i++) {
  2225. write_ptr[dst_offset + i] = read_ptr[src_offset + i];
  2226. }
  2227. }
  2228. }
  2229. } else {
  2230. //regular image (pixels)
  2231. //must copy a pixel region
  2232. for (uint32_t xr = 0; xr < region_w; xr++) {
  2233. for (uint32_t yr = 0; yr < region_h; yr++) {
  2234. uint32_t src_offset = ((yr + y) * width + xr + x) * pixel_size;
  2235. uint32_t dst_offset = (yr * region_w + xr) * pixel_size;
  2236. //copy block
  2237. for (uint32_t i = 0; i < pixel_size; i++) {
  2238. write_ptr[dst_offset + i] = read_ptr[src_offset + i];
  2239. }
  2240. }
  2241. }
  2242. }
  2243. { //unmap
  2244. vmaUnmapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation);
  2245. }
  2246. VkBufferImageCopy buffer_image_copy;
  2247. buffer_image_copy.bufferOffset = alloc_offset;
  2248. buffer_image_copy.bufferRowLength = 0; //tightly packed
  2249. buffer_image_copy.bufferImageHeight = 0; //tightly packed
  2250. buffer_image_copy.imageSubresource.aspectMask = texture->read_aspect_mask;
  2251. buffer_image_copy.imageSubresource.mipLevel = mm_i;
  2252. buffer_image_copy.imageSubresource.baseArrayLayer = p_layer;
  2253. buffer_image_copy.imageSubresource.layerCount = 1;
  2254. buffer_image_copy.imageOffset.x = x;
  2255. buffer_image_copy.imageOffset.y = y;
  2256. buffer_image_copy.imageOffset.z = z;
  2257. buffer_image_copy.imageExtent.width = region_logic_w;
  2258. buffer_image_copy.imageExtent.height = region_logic_h;
  2259. buffer_image_copy.imageExtent.depth = 1;
  2260. vkCmdCopyBufferToImage(command_buffer, staging_buffer_blocks[staging_buffer_current].buffer, texture->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buffer_image_copy);
  2261. staging_buffer_blocks.write[staging_buffer_current].fill_amount += alloc_size;
  2262. }
  2263. }
  2264. }
  2265. mipmap_offset = image_total;
  2266. logic_width = MAX(1u, logic_width >> 1);
  2267. logic_height = MAX(1u, logic_height >> 1);
  2268. }
  2269. //barrier to restore layout
  2270. {
  2271. uint32_t barrier_flags = 0;
  2272. uint32_t access_flags = 0;
  2273. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2274. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2275. access_flags |= VK_ACCESS_SHADER_READ_BIT;
  2276. }
  2277. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2278. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2279. access_flags |= VK_ACCESS_SHADER_READ_BIT;
  2280. }
  2281. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2282. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2283. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2284. }
  2285. if (barrier_flags == 0) {
  2286. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2287. }
  2288. VkImageMemoryBarrier image_memory_barrier;
  2289. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2290. image_memory_barrier.pNext = nullptr;
  2291. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2292. image_memory_barrier.dstAccessMask = access_flags;
  2293. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2294. image_memory_barrier.newLayout = texture->layout;
  2295. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2296. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2297. image_memory_barrier.image = texture->image;
  2298. image_memory_barrier.subresourceRange.aspectMask = texture->barrier_aspect_mask;
  2299. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2300. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  2301. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2302. image_memory_barrier.subresourceRange.layerCount = 1;
  2303. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2304. }
  2305. if (texture->used_in_frame != frames_drawn) {
  2306. texture->used_in_raster = false;
  2307. texture->used_in_compute = false;
  2308. texture->used_in_frame = frames_drawn;
  2309. }
  2310. texture->used_in_transfer = true;
  2311. return OK;
  2312. }
  2313. Vector<uint8_t> RenderingDeviceVulkan::_texture_get_data_from_image(Texture *tex, VkImage p_image, VmaAllocation p_allocation, uint32_t p_layer, bool p_2d) {
  2314. uint32_t width, height, depth;
  2315. uint32_t image_size = get_image_format_required_size(tex->format, tex->width, tex->height, p_2d ? 1 : tex->depth, tex->mipmaps, &width, &height, &depth);
  2316. Vector<uint8_t> image_data;
  2317. image_data.resize(image_size);
  2318. void *img_mem;
  2319. vmaMapMemory(allocator, p_allocation, &img_mem);
  2320. uint32_t blockw, blockh;
  2321. get_compressed_image_format_block_dimensions(tex->format, blockw, blockh);
  2322. uint32_t block_size = get_compressed_image_format_block_byte_size(tex->format);
  2323. uint32_t pixel_size = get_image_format_pixel_size(tex->format);
  2324. {
  2325. uint8_t *w = image_data.ptrw();
  2326. uint32_t mipmap_offset = 0;
  2327. for (uint32_t mm_i = 0; mm_i < tex->mipmaps; mm_i++) {
  2328. 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);
  2329. uint8_t *write_ptr_mipmap = w + mipmap_offset;
  2330. image_size = image_total - mipmap_offset;
  2331. VkImageSubresource image_sub_resorce;
  2332. image_sub_resorce.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2333. image_sub_resorce.arrayLayer = p_layer;
  2334. image_sub_resorce.mipLevel = mm_i;
  2335. VkSubresourceLayout layout;
  2336. vkGetImageSubresourceLayout(device, p_image, &image_sub_resorce, &layout);
  2337. for (uint32_t z = 0; z < depth; z++) {
  2338. uint8_t *write_ptr = write_ptr_mipmap + z * image_size / depth;
  2339. const uint8_t *slice_read_ptr = ((uint8_t *)img_mem) + layout.offset + z * layout.depthPitch;
  2340. if (block_size > 1) {
  2341. //compressed
  2342. uint32_t line_width = (block_size * (width / blockw));
  2343. for (uint32_t y = 0; y < height / blockh; y++) {
  2344. const uint8_t *rptr = slice_read_ptr + y * layout.rowPitch;
  2345. uint8_t *wptr = write_ptr + y * line_width;
  2346. memcpy(wptr, rptr, line_width);
  2347. }
  2348. } else {
  2349. //uncompressed
  2350. for (uint32_t y = 0; y < height; y++) {
  2351. const uint8_t *rptr = slice_read_ptr + y * layout.rowPitch;
  2352. uint8_t *wptr = write_ptr + y * pixel_size * width;
  2353. memcpy(wptr, rptr, (uint64_t)pixel_size * width);
  2354. }
  2355. }
  2356. }
  2357. mipmap_offset = image_total;
  2358. }
  2359. }
  2360. vmaUnmapMemory(allocator, p_allocation);
  2361. return image_data;
  2362. }
  2363. Vector<uint8_t> RenderingDeviceVulkan::texture_get_data(RID p_texture, uint32_t p_layer) {
  2364. _THREAD_SAFE_METHOD_
  2365. Texture *tex = texture_owner.get_or_null(p_texture);
  2366. ERR_FAIL_COND_V(!tex, Vector<uint8_t>());
  2367. ERR_FAIL_COND_V_MSG(tex->bound, Vector<uint8_t>(),
  2368. "Texture can't be retrieved while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2369. ERR_FAIL_COND_V_MSG(!(tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), Vector<uint8_t>(),
  2370. "Texture requires the TEXTURE_USAGE_CAN_COPY_FROM_BIT in order to be retrieved.");
  2371. uint32_t layer_count = tex->layers;
  2372. if (tex->type == TEXTURE_TYPE_CUBE || tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2373. layer_count *= 6;
  2374. }
  2375. ERR_FAIL_COND_V(p_layer >= layer_count, Vector<uint8_t>());
  2376. if (tex->usage_flags & TEXTURE_USAGE_CPU_READ_BIT) {
  2377. //does not need anything fancy, map and read.
  2378. return _texture_get_data_from_image(tex, tex->image, tex->allocation, p_layer);
  2379. } else {
  2380. //compute total image size
  2381. uint32_t width, height, depth;
  2382. uint32_t buffer_size = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, tex->mipmaps, &width, &height, &depth);
  2383. //allocate buffer
  2384. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer; //makes more sense to retrieve
  2385. Buffer tmp_buffer;
  2386. _buffer_allocate(&tmp_buffer, buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_HOST, VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT);
  2387. { //Source image barrier
  2388. VkImageMemoryBarrier image_memory_barrier;
  2389. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2390. image_memory_barrier.pNext = nullptr;
  2391. image_memory_barrier.srcAccessMask = 0;
  2392. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2393. image_memory_barrier.oldLayout = tex->layout;
  2394. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2395. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2396. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2397. image_memory_barrier.image = tex->image;
  2398. image_memory_barrier.subresourceRange.aspectMask = tex->barrier_aspect_mask;
  2399. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2400. image_memory_barrier.subresourceRange.levelCount = tex->mipmaps;
  2401. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2402. image_memory_barrier.subresourceRange.layerCount = 1;
  2403. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2404. }
  2405. uint32_t computed_w = tex->width;
  2406. uint32_t computed_h = tex->height;
  2407. uint32_t computed_d = tex->depth;
  2408. uint32_t prev_size = 0;
  2409. uint32_t offset = 0;
  2410. for (uint32_t i = 0; i < tex->mipmaps; i++) {
  2411. VkBufferImageCopy buffer_image_copy;
  2412. uint32_t image_size = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, i + 1);
  2413. uint32_t size = image_size - prev_size;
  2414. prev_size = image_size;
  2415. buffer_image_copy.bufferOffset = offset;
  2416. buffer_image_copy.bufferImageHeight = 0;
  2417. buffer_image_copy.bufferRowLength = 0;
  2418. buffer_image_copy.imageSubresource.aspectMask = tex->read_aspect_mask;
  2419. buffer_image_copy.imageSubresource.baseArrayLayer = p_layer;
  2420. buffer_image_copy.imageSubresource.layerCount = 1;
  2421. buffer_image_copy.imageSubresource.mipLevel = i;
  2422. buffer_image_copy.imageOffset.x = 0;
  2423. buffer_image_copy.imageOffset.y = 0;
  2424. buffer_image_copy.imageOffset.z = 0;
  2425. buffer_image_copy.imageExtent.width = computed_w;
  2426. buffer_image_copy.imageExtent.height = computed_h;
  2427. buffer_image_copy.imageExtent.depth = computed_d;
  2428. vkCmdCopyImageToBuffer(command_buffer, tex->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, tmp_buffer.buffer, 1, &buffer_image_copy);
  2429. computed_w = MAX(1u, computed_w >> 1);
  2430. computed_h = MAX(1u, computed_h >> 1);
  2431. computed_d = MAX(1u, computed_d >> 1);
  2432. offset += size;
  2433. }
  2434. { //restore src
  2435. VkImageMemoryBarrier image_memory_barrier;
  2436. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2437. image_memory_barrier.pNext = nullptr;
  2438. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2439. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2440. if (tex->usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  2441. image_memory_barrier.dstAccessMask |= VK_ACCESS_SHADER_WRITE_BIT;
  2442. }
  2443. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2444. image_memory_barrier.newLayout = tex->layout;
  2445. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2446. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2447. image_memory_barrier.image = tex->image;
  2448. image_memory_barrier.subresourceRange.aspectMask = tex->barrier_aspect_mask;
  2449. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2450. image_memory_barrier.subresourceRange.levelCount = tex->mipmaps;
  2451. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2452. image_memory_barrier.subresourceRange.layerCount = 1;
  2453. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2454. }
  2455. _flush(true);
  2456. void *buffer_mem;
  2457. VkResult vkerr = vmaMapMemory(allocator, tmp_buffer.allocation, &buffer_mem);
  2458. ERR_FAIL_COND_V_MSG(vkerr, Vector<uint8_t>(), "vmaMapMemory failed with error " + itos(vkerr) + ".");
  2459. Vector<uint8_t> buffer_data;
  2460. {
  2461. buffer_data.resize(buffer_size);
  2462. uint8_t *w = buffer_data.ptrw();
  2463. memcpy(w, buffer_mem, buffer_size);
  2464. }
  2465. vmaUnmapMemory(allocator, tmp_buffer.allocation);
  2466. _buffer_free(&tmp_buffer);
  2467. return buffer_data;
  2468. }
  2469. }
  2470. bool RenderingDeviceVulkan::texture_is_shared(RID p_texture) {
  2471. _THREAD_SAFE_METHOD_
  2472. Texture *tex = texture_owner.get_or_null(p_texture);
  2473. ERR_FAIL_COND_V(!tex, false);
  2474. return tex->owner.is_valid();
  2475. }
  2476. bool RenderingDeviceVulkan::texture_is_valid(RID p_texture) {
  2477. return texture_owner.owns(p_texture);
  2478. }
  2479. Size2i RenderingDeviceVulkan::texture_size(RID p_texture) {
  2480. _THREAD_SAFE_METHOD_
  2481. Texture *tex = texture_owner.get_or_null(p_texture);
  2482. ERR_FAIL_COND_V(!tex, Size2i());
  2483. return Size2i(tex->width, tex->height);
  2484. }
  2485. Error RenderingDeviceVulkan::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, uint32_t p_post_barrier) {
  2486. _THREAD_SAFE_METHOD_
  2487. Texture *src_tex = texture_owner.get_or_null(p_from_texture);
  2488. ERR_FAIL_COND_V(!src_tex, ERR_INVALID_PARAMETER);
  2489. ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,
  2490. "Source texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2491. ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), ERR_INVALID_PARAMETER,
  2492. "Source texture requires the TEXTURE_USAGE_CAN_COPY_FROM_BIT in order to be retrieved.");
  2493. uint32_t src_layer_count = src_tex->layers;
  2494. uint32_t src_width, src_height, src_depth;
  2495. 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);
  2496. if (src_tex->type == TEXTURE_TYPE_CUBE || src_tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2497. src_layer_count *= 6;
  2498. }
  2499. ERR_FAIL_COND_V(p_from.x < 0 || p_from.x + p_size.x > src_width, ERR_INVALID_PARAMETER);
  2500. ERR_FAIL_COND_V(p_from.y < 0 || p_from.y + p_size.y > src_height, ERR_INVALID_PARAMETER);
  2501. ERR_FAIL_COND_V(p_from.z < 0 || p_from.z + p_size.z > src_depth, ERR_INVALID_PARAMETER);
  2502. ERR_FAIL_COND_V(p_src_mipmap >= src_tex->mipmaps, ERR_INVALID_PARAMETER);
  2503. ERR_FAIL_COND_V(p_src_layer >= src_layer_count, ERR_INVALID_PARAMETER);
  2504. Texture *dst_tex = texture_owner.get_or_null(p_to_texture);
  2505. ERR_FAIL_COND_V(!dst_tex, ERR_INVALID_PARAMETER);
  2506. ERR_FAIL_COND_V_MSG(dst_tex->bound, ERR_INVALID_PARAMETER,
  2507. "Destination texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2508. ERR_FAIL_COND_V_MSG(!(dst_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,
  2509. "Destination texture requires the TEXTURE_USAGE_CAN_COPY_TO_BIT in order to be retrieved.");
  2510. uint32_t dst_layer_count = dst_tex->layers;
  2511. uint32_t dst_width, dst_height, dst_depth;
  2512. 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);
  2513. if (dst_tex->type == TEXTURE_TYPE_CUBE || dst_tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2514. dst_layer_count *= 6;
  2515. }
  2516. ERR_FAIL_COND_V(p_to.x < 0 || p_to.x + p_size.x > dst_width, ERR_INVALID_PARAMETER);
  2517. ERR_FAIL_COND_V(p_to.y < 0 || p_to.y + p_size.y > dst_height, ERR_INVALID_PARAMETER);
  2518. ERR_FAIL_COND_V(p_to.z < 0 || p_to.z + p_size.z > dst_depth, ERR_INVALID_PARAMETER);
  2519. ERR_FAIL_COND_V(p_dst_mipmap >= dst_tex->mipmaps, ERR_INVALID_PARAMETER);
  2520. ERR_FAIL_COND_V(p_dst_layer >= dst_layer_count, ERR_INVALID_PARAMETER);
  2521. ERR_FAIL_COND_V_MSG(src_tex->read_aspect_mask != dst_tex->read_aspect_mask, ERR_INVALID_PARAMETER,
  2522. "Source and destination texture must be of the same type (color or depth).");
  2523. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  2524. {
  2525. //PRE Copy the image
  2526. { //Source
  2527. VkImageMemoryBarrier image_memory_barrier;
  2528. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2529. image_memory_barrier.pNext = nullptr;
  2530. image_memory_barrier.srcAccessMask = 0;
  2531. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2532. image_memory_barrier.oldLayout = src_tex->layout;
  2533. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2534. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2535. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2536. image_memory_barrier.image = src_tex->image;
  2537. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2538. image_memory_barrier.subresourceRange.baseMipLevel = p_src_mipmap;
  2539. image_memory_barrier.subresourceRange.levelCount = 1;
  2540. image_memory_barrier.subresourceRange.baseArrayLayer = p_src_layer;
  2541. image_memory_barrier.subresourceRange.layerCount = 1;
  2542. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2543. }
  2544. { //Dest
  2545. VkImageMemoryBarrier image_memory_barrier;
  2546. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2547. image_memory_barrier.pNext = nullptr;
  2548. image_memory_barrier.srcAccessMask = 0;
  2549. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2550. image_memory_barrier.oldLayout = dst_tex->layout;
  2551. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2552. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2553. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2554. image_memory_barrier.image = dst_tex->image;
  2555. image_memory_barrier.subresourceRange.aspectMask = dst_tex->read_aspect_mask;
  2556. image_memory_barrier.subresourceRange.baseMipLevel = p_dst_mipmap;
  2557. image_memory_barrier.subresourceRange.levelCount = 1;
  2558. image_memory_barrier.subresourceRange.baseArrayLayer = p_dst_layer;
  2559. image_memory_barrier.subresourceRange.layerCount = 1;
  2560. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2561. }
  2562. //COPY
  2563. {
  2564. VkImageCopy image_copy_region;
  2565. image_copy_region.srcSubresource.aspectMask = src_tex->read_aspect_mask;
  2566. image_copy_region.srcSubresource.baseArrayLayer = p_src_layer;
  2567. image_copy_region.srcSubresource.layerCount = 1;
  2568. image_copy_region.srcSubresource.mipLevel = p_src_mipmap;
  2569. image_copy_region.srcOffset.x = p_from.x;
  2570. image_copy_region.srcOffset.y = p_from.y;
  2571. image_copy_region.srcOffset.z = p_from.z;
  2572. image_copy_region.dstSubresource.aspectMask = dst_tex->read_aspect_mask;
  2573. image_copy_region.dstSubresource.baseArrayLayer = p_dst_layer;
  2574. image_copy_region.dstSubresource.layerCount = 1;
  2575. image_copy_region.dstSubresource.mipLevel = p_dst_mipmap;
  2576. image_copy_region.dstOffset.x = p_to.x;
  2577. image_copy_region.dstOffset.y = p_to.y;
  2578. image_copy_region.dstOffset.z = p_to.z;
  2579. image_copy_region.extent.width = p_size.x;
  2580. image_copy_region.extent.height = p_size.y;
  2581. image_copy_region.extent.depth = p_size.z;
  2582. vkCmdCopyImage(command_buffer, src_tex->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst_tex->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy_region);
  2583. }
  2584. // RESTORE LAYOUT for SRC and DST
  2585. uint32_t barrier_flags = 0;
  2586. uint32_t access_flags = 0;
  2587. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2588. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2589. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2590. }
  2591. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2592. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2593. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2594. }
  2595. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2596. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2597. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2598. }
  2599. if (barrier_flags == 0) {
  2600. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2601. }
  2602. { //restore src
  2603. VkImageMemoryBarrier image_memory_barrier;
  2604. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2605. image_memory_barrier.pNext = nullptr;
  2606. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2607. image_memory_barrier.dstAccessMask = access_flags;
  2608. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2609. image_memory_barrier.newLayout = src_tex->layout;
  2610. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2611. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2612. image_memory_barrier.image = src_tex->image;
  2613. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2614. image_memory_barrier.subresourceRange.baseMipLevel = p_src_mipmap;
  2615. image_memory_barrier.subresourceRange.levelCount = src_tex->mipmaps;
  2616. image_memory_barrier.subresourceRange.baseArrayLayer = p_src_layer;
  2617. image_memory_barrier.subresourceRange.layerCount = 1;
  2618. vkCmdPipelineBarrier(command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2619. }
  2620. { //make dst readable
  2621. VkImageMemoryBarrier image_memory_barrier;
  2622. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2623. image_memory_barrier.pNext = nullptr;
  2624. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2625. image_memory_barrier.dstAccessMask = access_flags;
  2626. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2627. image_memory_barrier.newLayout = dst_tex->layout;
  2628. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2629. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2630. image_memory_barrier.image = dst_tex->image;
  2631. image_memory_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2632. image_memory_barrier.subresourceRange.baseMipLevel = p_src_mipmap;
  2633. image_memory_barrier.subresourceRange.levelCount = 1;
  2634. image_memory_barrier.subresourceRange.baseArrayLayer = p_src_layer;
  2635. image_memory_barrier.subresourceRange.layerCount = 1;
  2636. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2637. }
  2638. }
  2639. return OK;
  2640. }
  2641. Error RenderingDeviceVulkan::texture_resolve_multisample(RID p_from_texture, RID p_to_texture, uint32_t p_post_barrier) {
  2642. _THREAD_SAFE_METHOD_
  2643. Texture *src_tex = texture_owner.get_or_null(p_from_texture);
  2644. ERR_FAIL_COND_V(!src_tex, ERR_INVALID_PARAMETER);
  2645. ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,
  2646. "Source texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2647. ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), ERR_INVALID_PARAMETER,
  2648. "Source texture requires the TEXTURE_USAGE_CAN_COPY_FROM_BIT in order to be retrieved.");
  2649. 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)");
  2650. ERR_FAIL_COND_V_MSG(src_tex->samples == TEXTURE_SAMPLES_1, ERR_INVALID_PARAMETER, "Source texture must be multisampled.");
  2651. Texture *dst_tex = texture_owner.get_or_null(p_to_texture);
  2652. ERR_FAIL_COND_V(!dst_tex, ERR_INVALID_PARAMETER);
  2653. ERR_FAIL_COND_V_MSG(dst_tex->bound, ERR_INVALID_PARAMETER,
  2654. "Destination texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2655. ERR_FAIL_COND_V_MSG(!(dst_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,
  2656. "Destination texture requires the TEXTURE_USAGE_CAN_COPY_TO_BIT in order to be retrieved.");
  2657. 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).");
  2658. ERR_FAIL_COND_V_MSG(dst_tex->samples != TEXTURE_SAMPLES_1, ERR_INVALID_PARAMETER, "Destination texture must not be multisampled.");
  2659. ERR_FAIL_COND_V_MSG(src_tex->format != dst_tex->format, ERR_INVALID_PARAMETER, "Source and Destination textures must be the same format.");
  2660. 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.");
  2661. ERR_FAIL_COND_V_MSG(src_tex->read_aspect_mask != dst_tex->read_aspect_mask, ERR_INVALID_PARAMETER,
  2662. "Source and destination texture must be of the same type (color or depth).");
  2663. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  2664. {
  2665. //PRE Copy the image
  2666. { //Source
  2667. VkImageMemoryBarrier image_memory_barrier;
  2668. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2669. image_memory_barrier.pNext = nullptr;
  2670. image_memory_barrier.srcAccessMask = 0;
  2671. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2672. image_memory_barrier.oldLayout = src_tex->layout;
  2673. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2674. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2675. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2676. image_memory_barrier.image = src_tex->image;
  2677. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2678. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap;
  2679. image_memory_barrier.subresourceRange.levelCount = 1;
  2680. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer;
  2681. image_memory_barrier.subresourceRange.layerCount = 1;
  2682. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2683. }
  2684. { //Dest
  2685. VkImageMemoryBarrier image_memory_barrier;
  2686. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2687. image_memory_barrier.pNext = nullptr;
  2688. image_memory_barrier.srcAccessMask = 0;
  2689. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2690. image_memory_barrier.oldLayout = dst_tex->layout;
  2691. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2692. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2693. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2694. image_memory_barrier.image = dst_tex->image;
  2695. image_memory_barrier.subresourceRange.aspectMask = dst_tex->read_aspect_mask;
  2696. image_memory_barrier.subresourceRange.baseMipLevel = dst_tex->base_mipmap;
  2697. image_memory_barrier.subresourceRange.levelCount = 1;
  2698. image_memory_barrier.subresourceRange.baseArrayLayer = dst_tex->base_layer;
  2699. image_memory_barrier.subresourceRange.layerCount = 1;
  2700. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2701. }
  2702. //COPY
  2703. {
  2704. VkImageResolve image_copy_region;
  2705. image_copy_region.srcSubresource.aspectMask = src_tex->read_aspect_mask;
  2706. image_copy_region.srcSubresource.baseArrayLayer = src_tex->base_layer;
  2707. image_copy_region.srcSubresource.layerCount = 1;
  2708. image_copy_region.srcSubresource.mipLevel = src_tex->base_mipmap;
  2709. image_copy_region.srcOffset.x = 0;
  2710. image_copy_region.srcOffset.y = 0;
  2711. image_copy_region.srcOffset.z = 0;
  2712. image_copy_region.dstSubresource.aspectMask = dst_tex->read_aspect_mask;
  2713. image_copy_region.dstSubresource.baseArrayLayer = dst_tex->base_layer;
  2714. image_copy_region.dstSubresource.layerCount = 1;
  2715. image_copy_region.dstSubresource.mipLevel = dst_tex->base_mipmap;
  2716. image_copy_region.dstOffset.x = 0;
  2717. image_copy_region.dstOffset.y = 0;
  2718. image_copy_region.dstOffset.z = 0;
  2719. image_copy_region.extent.width = src_tex->width;
  2720. image_copy_region.extent.height = src_tex->height;
  2721. image_copy_region.extent.depth = src_tex->depth;
  2722. vkCmdResolveImage(command_buffer, src_tex->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst_tex->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy_region);
  2723. }
  2724. // RESTORE LAYOUT for SRC and DST
  2725. uint32_t barrier_flags = 0;
  2726. uint32_t access_flags = 0;
  2727. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2728. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2729. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2730. }
  2731. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2732. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2733. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2734. }
  2735. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2736. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2737. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2738. }
  2739. if (barrier_flags == 0) {
  2740. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2741. }
  2742. { //restore src
  2743. VkImageMemoryBarrier image_memory_barrier;
  2744. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2745. image_memory_barrier.pNext = nullptr;
  2746. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2747. image_memory_barrier.dstAccessMask = access_flags;
  2748. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2749. image_memory_barrier.newLayout = src_tex->layout;
  2750. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2751. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2752. image_memory_barrier.image = src_tex->image;
  2753. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2754. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap;
  2755. image_memory_barrier.subresourceRange.levelCount = 1;
  2756. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer;
  2757. image_memory_barrier.subresourceRange.layerCount = 1;
  2758. vkCmdPipelineBarrier(command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2759. }
  2760. { //make dst readable
  2761. VkImageMemoryBarrier image_memory_barrier;
  2762. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2763. image_memory_barrier.pNext = nullptr;
  2764. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2765. image_memory_barrier.dstAccessMask = access_flags;
  2766. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2767. image_memory_barrier.newLayout = dst_tex->layout;
  2768. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2769. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2770. image_memory_barrier.image = dst_tex->image;
  2771. image_memory_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2772. image_memory_barrier.subresourceRange.baseMipLevel = dst_tex->base_mipmap;
  2773. image_memory_barrier.subresourceRange.levelCount = 1;
  2774. image_memory_barrier.subresourceRange.baseArrayLayer = dst_tex->base_layer;
  2775. image_memory_barrier.subresourceRange.layerCount = 1;
  2776. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2777. }
  2778. }
  2779. return OK;
  2780. }
  2781. Error RenderingDeviceVulkan::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, uint32_t p_post_barrier) {
  2782. _THREAD_SAFE_METHOD_
  2783. Texture *src_tex = texture_owner.get_or_null(p_texture);
  2784. ERR_FAIL_COND_V(!src_tex, ERR_INVALID_PARAMETER);
  2785. ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,
  2786. "Source texture can't be cleared while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2787. ERR_FAIL_COND_V(p_layers == 0, ERR_INVALID_PARAMETER);
  2788. ERR_FAIL_COND_V(p_mipmaps == 0, ERR_INVALID_PARAMETER);
  2789. ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,
  2790. "Source texture requires the TEXTURE_USAGE_CAN_COPY_TO_BIT in order to be cleared.");
  2791. uint32_t src_layer_count = src_tex->layers;
  2792. if (src_tex->type == TEXTURE_TYPE_CUBE || src_tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2793. src_layer_count *= 6;
  2794. }
  2795. ERR_FAIL_COND_V(p_base_mipmap + p_mipmaps > src_tex->mipmaps, ERR_INVALID_PARAMETER);
  2796. ERR_FAIL_COND_V(p_base_layer + p_layers > src_layer_count, ERR_INVALID_PARAMETER);
  2797. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  2798. VkImageLayout clear_layout = (src_tex->layout == VK_IMAGE_LAYOUT_GENERAL) ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2799. // NOTE: Perhaps the valid stages/accesses for a given owner should be a property of the owner. (Here and places like _get_buffer_from_owner)
  2800. const VkPipelineStageFlags valid_texture_stages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2801. constexpr VkAccessFlags read_access = VK_ACCESS_SHADER_READ_BIT;
  2802. constexpr VkAccessFlags read_write_access = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2803. const VkAccessFlags valid_texture_access = (src_tex->usage_flags & TEXTURE_USAGE_STORAGE_BIT) ? read_write_access : read_access;
  2804. { // Barrier from previous access with optional layout change (see clear_layout logic above)
  2805. VkImageMemoryBarrier image_memory_barrier;
  2806. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2807. image_memory_barrier.pNext = nullptr;
  2808. image_memory_barrier.srcAccessMask = valid_texture_access;
  2809. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2810. image_memory_barrier.oldLayout = src_tex->layout;
  2811. image_memory_barrier.newLayout = clear_layout;
  2812. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2813. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2814. image_memory_barrier.image = src_tex->image;
  2815. image_memory_barrier.subresourceRange.aspectMask = src_tex->read_aspect_mask;
  2816. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap + p_base_mipmap;
  2817. image_memory_barrier.subresourceRange.levelCount = p_mipmaps;
  2818. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer + p_base_layer;
  2819. image_memory_barrier.subresourceRange.layerCount = p_layers;
  2820. vkCmdPipelineBarrier(command_buffer, valid_texture_stages, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2821. }
  2822. VkClearColorValue clear_color;
  2823. clear_color.float32[0] = p_color.r;
  2824. clear_color.float32[1] = p_color.g;
  2825. clear_color.float32[2] = p_color.b;
  2826. clear_color.float32[3] = p_color.a;
  2827. VkImageSubresourceRange range;
  2828. range.aspectMask = src_tex->read_aspect_mask;
  2829. range.baseArrayLayer = src_tex->base_layer + p_base_layer;
  2830. range.layerCount = p_layers;
  2831. range.baseMipLevel = src_tex->base_mipmap + p_base_mipmap;
  2832. range.levelCount = p_mipmaps;
  2833. vkCmdClearColorImage(command_buffer, src_tex->image, clear_layout, &clear_color, 1, &range);
  2834. { // Barrier to post clear accesses (changing back the layout if needed)
  2835. uint32_t barrier_flags = 0;
  2836. uint32_t access_flags = 0;
  2837. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2838. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2839. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2840. }
  2841. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2842. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2843. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2844. }
  2845. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2846. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2847. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2848. }
  2849. if (barrier_flags == 0) {
  2850. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2851. }
  2852. VkImageMemoryBarrier image_memory_barrier;
  2853. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2854. image_memory_barrier.pNext = nullptr;
  2855. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2856. image_memory_barrier.dstAccessMask = access_flags;
  2857. image_memory_barrier.oldLayout = clear_layout;
  2858. image_memory_barrier.newLayout = src_tex->layout;
  2859. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2860. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2861. image_memory_barrier.image = src_tex->image;
  2862. image_memory_barrier.subresourceRange.aspectMask = src_tex->read_aspect_mask;
  2863. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap + p_base_mipmap;
  2864. image_memory_barrier.subresourceRange.levelCount = p_mipmaps;
  2865. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer + p_base_layer;
  2866. image_memory_barrier.subresourceRange.layerCount = p_layers;
  2867. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2868. }
  2869. if (src_tex->used_in_frame != frames_drawn) {
  2870. src_tex->used_in_raster = false;
  2871. src_tex->used_in_compute = false;
  2872. src_tex->used_in_frame = frames_drawn;
  2873. }
  2874. src_tex->used_in_transfer = true;
  2875. return OK;
  2876. }
  2877. bool RenderingDeviceVulkan::texture_is_format_supported_for_usage(DataFormat p_format, uint32_t p_usage) const {
  2878. ERR_FAIL_INDEX_V(p_format, DATA_FORMAT_MAX, false);
  2879. _THREAD_SAFE_METHOD_
  2880. //validate that this image is supported for the intended use
  2881. VkFormatProperties properties;
  2882. vkGetPhysicalDeviceFormatProperties(context->get_physical_device(), vulkan_formats[p_format], &properties);
  2883. VkFormatFeatureFlags flags;
  2884. if (p_usage & TEXTURE_USAGE_CPU_READ_BIT) {
  2885. flags = properties.linearTilingFeatures;
  2886. } else {
  2887. flags = properties.optimalTilingFeatures;
  2888. }
  2889. if (p_usage & TEXTURE_USAGE_SAMPLING_BIT && !(flags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) {
  2890. return false;
  2891. }
  2892. if (p_usage & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) {
  2893. return false;
  2894. }
  2895. if (p_usage & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  2896. return false;
  2897. }
  2898. if (p_usage & TEXTURE_USAGE_STORAGE_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) {
  2899. return false;
  2900. }
  2901. if (p_usage & TEXTURE_USAGE_STORAGE_ATOMIC_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT)) {
  2902. return false;
  2903. }
  2904. return true;
  2905. }
  2906. /********************/
  2907. /**** ATTACHMENT ****/
  2908. /********************/
  2909. VkRenderPass RenderingDeviceVulkan::_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) {
  2910. // Set up dependencies from/to external equivalent to the default (implicit) one, and then amend them
  2911. const VkPipelineStageFlags default_access_mask = VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  2912. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  2913. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  2914. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  2915. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; // From Section 7.1 of Vulkan API Spec v1.1.148
  2916. VkPipelineStageFlags reading_stages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT;
  2917. VkSubpassDependency dependencies[2] = { { VK_SUBPASS_EXTERNAL, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, default_access_mask, 0 },
  2918. { 0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, default_access_mask, 0, 0 } };
  2919. VkSubpassDependency &dependency_from_external = dependencies[0];
  2920. VkSubpassDependency &dependency_to_external = dependencies[1];
  2921. LocalVector<int32_t> attachment_last_pass;
  2922. attachment_last_pass.resize(p_attachments.size());
  2923. Vector<VkAttachmentDescription> attachments;
  2924. Vector<int> attachment_remap;
  2925. for (int i = 0; i < p_attachments.size(); i++) {
  2926. if (p_attachments[i].usage_flags == AttachmentFormat::UNUSED_ATTACHMENT) {
  2927. attachment_remap.push_back(VK_ATTACHMENT_UNUSED);
  2928. continue;
  2929. }
  2930. ERR_FAIL_INDEX_V(p_attachments[i].format, DATA_FORMAT_MAX, VK_NULL_HANDLE);
  2931. ERR_FAIL_INDEX_V(p_attachments[i].samples, TEXTURE_SAMPLES_MAX, VK_NULL_HANDLE);
  2932. 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)),
  2933. VK_NULL_HANDLE, "Texture format for index (" + itos(i) + ") requires an attachment (color, depth, input or stencil) bit set.");
  2934. VkAttachmentDescription description = {};
  2935. description.flags = 0;
  2936. description.format = vulkan_formats[p_attachments[i].format];
  2937. description.samples = rasterization_sample_count[p_attachments[i].samples];
  2938. bool is_sampled = p_attachments[i].usage_flags & TEXTURE_USAGE_SAMPLING_BIT;
  2939. bool is_storage = p_attachments[i].usage_flags & TEXTURE_USAGE_STORAGE_BIT;
  2940. bool is_depth = p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  2941. // For each UNDEFINED, assume the prior use was a *read*, as we'd be discarding the output of a write
  2942. // Also, each UNDEFINED will do an immediate layout transition (write), s.t. we must ensure execution synchronization vs.
  2943. // the read. If this is a performance issue, one could track the actual last accessor of each resource, adding only that
  2944. // stage
  2945. switch (is_depth ? p_initial_depth_action : p_initial_action) {
  2946. case INITIAL_ACTION_CLEAR_REGION:
  2947. case INITIAL_ACTION_CLEAR: {
  2948. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2949. description.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  2950. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  2951. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2952. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2953. description.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  2954. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  2955. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  2956. dependency_from_external.srcStageMask |= reading_stages;
  2957. } else {
  2958. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2959. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2960. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2961. dependency_from_external.srcStageMask |= reading_stages;
  2962. }
  2963. } break;
  2964. case INITIAL_ACTION_KEEP: {
  2965. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2966. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2967. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  2968. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2969. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2970. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2971. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  2972. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2973. dependency_from_external.srcStageMask |= reading_stages;
  2974. } else {
  2975. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2976. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2977. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2978. dependency_from_external.srcStageMask |= reading_stages;
  2979. }
  2980. } break;
  2981. case INITIAL_ACTION_DROP: {
  2982. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2983. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2984. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  2985. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2986. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2987. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2988. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2989. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2990. dependency_from_external.srcStageMask |= reading_stages;
  2991. } else {
  2992. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2993. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2994. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2995. dependency_from_external.srcStageMask |= reading_stages;
  2996. }
  2997. } break;
  2998. case INITIAL_ACTION_CLEAR_REGION_CONTINUE:
  2999. case INITIAL_ACTION_CONTINUE: {
  3000. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3001. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3002. description.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  3003. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3004. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3005. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3006. description.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  3007. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3008. } else {
  3009. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3010. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3011. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  3012. dependency_from_external.srcStageMask |= reading_stages;
  3013. }
  3014. } break;
  3015. default: {
  3016. ERR_FAIL_V(VK_NULL_HANDLE); //should never reach here
  3017. }
  3018. }
  3019. bool used_last = false;
  3020. {
  3021. int last_pass = p_passes.size() - 1;
  3022. if (is_depth) {
  3023. //likely missing depth resolve?
  3024. if (p_passes[last_pass].depth_attachment == i) {
  3025. used_last = true;
  3026. }
  3027. } else {
  3028. if (p_passes[last_pass].resolve_attachments.size()) {
  3029. //if using resolve attachments, check resolve attachments
  3030. for (int j = 0; j < p_passes[last_pass].resolve_attachments.size(); j++) {
  3031. if (p_passes[last_pass].resolve_attachments[j] == i) {
  3032. used_last = true;
  3033. break;
  3034. }
  3035. }
  3036. } else {
  3037. for (int j = 0; j < p_passes[last_pass].color_attachments.size(); j++) {
  3038. if (p_passes[last_pass].color_attachments[j] == i) {
  3039. used_last = true;
  3040. break;
  3041. }
  3042. }
  3043. }
  3044. }
  3045. if (!used_last) {
  3046. for (int j = 0; j < p_passes[last_pass].preserve_attachments.size(); j++) {
  3047. if (p_passes[last_pass].preserve_attachments[j] == i) {
  3048. used_last = true;
  3049. break;
  3050. }
  3051. }
  3052. }
  3053. }
  3054. FinalAction final_action = p_final_action;
  3055. FinalAction final_depth_action = p_final_depth_action;
  3056. if (!used_last) {
  3057. if (is_depth) {
  3058. final_depth_action = FINAL_ACTION_DISCARD;
  3059. } else {
  3060. final_action = FINAL_ACTION_DISCARD;
  3061. }
  3062. }
  3063. switch (is_depth ? final_depth_action : final_action) {
  3064. case FINAL_ACTION_READ: {
  3065. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3066. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3067. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3068. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  3069. update_external_dependency_for_store(dependency_to_external, is_sampled, is_storage, false);
  3070. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3071. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3072. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
  3073. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  3074. update_external_dependency_for_store(dependency_to_external, is_sampled, is_storage, true);
  3075. } else {
  3076. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3077. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3078. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  3079. // TODO: What does this mean about the next usage (and thus appropriate dependency masks
  3080. }
  3081. } break;
  3082. case FINAL_ACTION_DISCARD: {
  3083. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3084. description.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3085. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3086. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  3087. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3088. description.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3089. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3090. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  3091. } else {
  3092. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3093. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3094. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  3095. }
  3096. } break;
  3097. case FINAL_ACTION_CONTINUE: {
  3098. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3099. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3100. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3101. description.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  3102. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3103. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3104. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
  3105. description.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  3106. } else {
  3107. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3108. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3109. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  3110. }
  3111. } break;
  3112. default: {
  3113. ERR_FAIL_V(VK_NULL_HANDLE); //should never reach here
  3114. }
  3115. }
  3116. attachment_last_pass[i] = -1;
  3117. attachment_remap.push_back(attachments.size());
  3118. attachments.push_back(description);
  3119. }
  3120. LocalVector<VkSubpassDescription> subpasses;
  3121. LocalVector<LocalVector<VkAttachmentReference>> color_reference_array;
  3122. LocalVector<LocalVector<VkAttachmentReference>> input_reference_array;
  3123. LocalVector<LocalVector<VkAttachmentReference>> resolve_reference_array;
  3124. LocalVector<LocalVector<uint32_t>> preserve_reference_array;
  3125. LocalVector<VkAttachmentReference> depth_reference_array;
  3126. subpasses.resize(p_passes.size());
  3127. color_reference_array.resize(p_passes.size());
  3128. input_reference_array.resize(p_passes.size());
  3129. resolve_reference_array.resize(p_passes.size());
  3130. preserve_reference_array.resize(p_passes.size());
  3131. depth_reference_array.resize(p_passes.size());
  3132. LocalVector<VkSubpassDependency> subpass_dependencies;
  3133. for (int i = 0; i < p_passes.size(); i++) {
  3134. const FramebufferPass *pass = &p_passes[i];
  3135. LocalVector<VkAttachmentReference> &color_references = color_reference_array[i];
  3136. TextureSamples texture_samples = TEXTURE_SAMPLES_1;
  3137. bool is_multisample_first = true;
  3138. for (int j = 0; j < pass->color_attachments.size(); j++) {
  3139. int32_t attachment = pass->color_attachments[j];
  3140. VkAttachmentReference reference;
  3141. if (attachment == FramebufferPass::ATTACHMENT_UNUSED) {
  3142. reference.attachment = VK_ATTACHMENT_UNUSED;
  3143. reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3144. } else {
  3145. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), color attachment (" + itos(j) + ").");
  3146. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not usable as color attachment.");
  3147. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  3148. if (is_multisample_first) {
  3149. texture_samples = p_attachments[attachment].samples;
  3150. is_multisample_first = false;
  3151. } else {
  3152. ERR_FAIL_COND_V_MSG(texture_samples != p_attachments[attachment].samples, VK_NULL_HANDLE, "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.");
  3153. }
  3154. reference.attachment = attachment_remap[attachment];
  3155. reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  3156. attachment_last_pass[attachment] = i;
  3157. }
  3158. color_references.push_back(reference);
  3159. }
  3160. LocalVector<VkAttachmentReference> &input_references = input_reference_array[i];
  3161. for (int j = 0; j < pass->input_attachments.size(); j++) {
  3162. int32_t attachment = pass->input_attachments[j];
  3163. VkAttachmentReference reference;
  3164. if (attachment == FramebufferPass::ATTACHMENT_UNUSED) {
  3165. reference.attachment = VK_ATTACHMENT_UNUSED;
  3166. reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3167. } else {
  3168. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), input attachment (" + itos(j) + ").");
  3169. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it isn't marked as an input texture.");
  3170. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  3171. reference.attachment = attachment_remap[attachment];
  3172. reference.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  3173. attachment_last_pass[attachment] = i;
  3174. }
  3175. input_references.push_back(reference);
  3176. }
  3177. LocalVector<VkAttachmentReference> &resolve_references = resolve_reference_array[i];
  3178. if (pass->resolve_attachments.size() > 0) {
  3179. ERR_FAIL_COND_V_MSG(pass->resolve_attachments.size() != pass->color_attachments.size(), VK_NULL_HANDLE, "The amount of resolve attachments (" + itos(pass->resolve_attachments.size()) + ") must match the number of color attachments (" + itos(pass->color_attachments.size()) + ").");
  3180. ERR_FAIL_COND_V_MSG(texture_samples == TEXTURE_SAMPLES_1, VK_NULL_HANDLE, "Resolve attachments specified, but color attachments are not multisample.");
  3181. }
  3182. for (int j = 0; j < pass->resolve_attachments.size(); j++) {
  3183. int32_t attachment = pass->resolve_attachments[j];
  3184. VkAttachmentReference reference;
  3185. if (attachment == FramebufferPass::ATTACHMENT_UNUSED) {
  3186. reference.attachment = VK_ATTACHMENT_UNUSED;
  3187. reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3188. } else {
  3189. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + ").");
  3190. ERR_FAIL_COND_V_MSG(pass->color_attachments[j] == FramebufferPass::ATTACHMENT_UNUSED, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + "), the respective color attachment is marked as unused.");
  3191. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment, it isn't marked as a color texture.");
  3192. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  3193. bool multisample = p_attachments[attachment].samples > TEXTURE_SAMPLES_1;
  3194. ERR_FAIL_COND_V_MSG(multisample, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachments can't be multisample.");
  3195. reference.attachment = attachment_remap[attachment];
  3196. reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  3197. attachment_last_pass[attachment] = i;
  3198. }
  3199. resolve_references.push_back(reference);
  3200. }
  3201. VkAttachmentReference &depth_stencil_reference = depth_reference_array[i];
  3202. if (pass->depth_attachment != FramebufferPass::ATTACHMENT_UNUSED) {
  3203. int32_t attachment = pass->depth_attachment;
  3204. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), depth attachment.");
  3205. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not a depth attachment.");
  3206. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  3207. depth_stencil_reference.attachment = attachment_remap[attachment];
  3208. depth_stencil_reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  3209. attachment_last_pass[attachment] = i;
  3210. if (is_multisample_first) {
  3211. texture_samples = p_attachments[attachment].samples;
  3212. is_multisample_first = false;
  3213. } else {
  3214. ERR_FAIL_COND_V_MSG(texture_samples != p_attachments[attachment].samples, VK_NULL_HANDLE, "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.");
  3215. }
  3216. } else {
  3217. depth_stencil_reference.attachment = VK_ATTACHMENT_UNUSED;
  3218. depth_stencil_reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3219. }
  3220. LocalVector<uint32_t> &preserve_references = preserve_reference_array[i];
  3221. for (int j = 0; j < pass->preserve_attachments.size(); j++) {
  3222. int32_t attachment = pass->preserve_attachments[j];
  3223. ERR_FAIL_COND_V_MSG(attachment == FramebufferPass::ATTACHMENT_UNUSED, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + "). Preserve attachments can't be unused.");
  3224. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + ").");
  3225. if (attachment_last_pass[attachment] != i) {
  3226. //preserve can still be used to keep depth or color from being discarded after use
  3227. attachment_last_pass[attachment] = i;
  3228. preserve_references.push_back(attachment);
  3229. }
  3230. }
  3231. VkSubpassDescription &subpass = subpasses[i];
  3232. subpass.flags = 0;
  3233. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  3234. subpass.inputAttachmentCount = input_references.size();
  3235. if (input_references.size()) {
  3236. subpass.pInputAttachments = input_references.ptr();
  3237. } else {
  3238. subpass.pInputAttachments = nullptr;
  3239. }
  3240. subpass.colorAttachmentCount = color_references.size();
  3241. if (color_references.size()) {
  3242. subpass.pColorAttachments = color_references.ptr();
  3243. } else {
  3244. subpass.pColorAttachments = nullptr;
  3245. }
  3246. if (depth_stencil_reference.attachment != VK_ATTACHMENT_UNUSED) {
  3247. subpass.pDepthStencilAttachment = &depth_stencil_reference;
  3248. } else {
  3249. subpass.pDepthStencilAttachment = nullptr;
  3250. }
  3251. if (resolve_references.size()) {
  3252. subpass.pResolveAttachments = resolve_references.ptr();
  3253. } else {
  3254. subpass.pResolveAttachments = nullptr;
  3255. }
  3256. subpass.preserveAttachmentCount = preserve_references.size();
  3257. if (preserve_references.size()) {
  3258. subpass.pPreserveAttachments = preserve_references.ptr();
  3259. } else {
  3260. subpass.pPreserveAttachments = nullptr;
  3261. }
  3262. if (r_samples) {
  3263. r_samples->push_back(texture_samples);
  3264. }
  3265. if (i > 0) {
  3266. VkSubpassDependency dependency;
  3267. dependency.srcSubpass = i - 1;
  3268. dependency.dstSubpass = i;
  3269. dependency.srcStageMask = 0;
  3270. dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  3271. dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  3272. dependency.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  3273. dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
  3274. dependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
  3275. subpass_dependencies.push_back(dependency);
  3276. }
  3277. /*
  3278. // NOTE: Big Mallet Approach -- any layout transition causes a full barrier
  3279. if (reference.layout != description.initialLayout) {
  3280. // NOTE: this should be smarter based on the texture's knowledge of its previous role
  3281. dependency_from_external.srcStageMask |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
  3282. dependency_from_external.srcAccessMask |= VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
  3283. }
  3284. if (reference.layout != description.finalLayout) {
  3285. // NOTE: this should be smarter based on the texture's knowledge of its subsequent role
  3286. dependency_to_external.dstStageMask |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
  3287. dependency_to_external.dstAccessMask |= VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
  3288. }
  3289. */
  3290. }
  3291. VkRenderPassCreateInfo render_pass_create_info;
  3292. render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  3293. render_pass_create_info.pNext = nullptr;
  3294. render_pass_create_info.flags = 0;
  3295. render_pass_create_info.attachmentCount = attachments.size();
  3296. render_pass_create_info.pAttachments = attachments.ptr();
  3297. render_pass_create_info.subpassCount = subpasses.size();
  3298. render_pass_create_info.pSubpasses = subpasses.ptr();
  3299. // Commenting this because it seems it just avoids raster and compute to work at the same time.
  3300. // Other barriers seem to be protecting the render pass fine.
  3301. // render_pass_create_info.dependencyCount = 2;
  3302. // render_pass_create_info.pDependencies = dependencies;
  3303. render_pass_create_info.dependencyCount = subpass_dependencies.size();
  3304. if (subpass_dependencies.size()) {
  3305. render_pass_create_info.pDependencies = subpass_dependencies.ptr();
  3306. } else {
  3307. render_pass_create_info.pDependencies = nullptr;
  3308. }
  3309. // These are only used if we use multiview but we need to define them in scope.
  3310. const uint32_t view_mask = (1 << p_view_count) - 1;
  3311. const uint32_t correlation_mask = (1 << p_view_count) - 1;
  3312. Vector<uint32_t> view_masks;
  3313. VkRenderPassMultiviewCreateInfo render_pass_multiview_create_info;
  3314. if (p_view_count > 1) {
  3315. const VulkanContext::MultiviewCapabilities capabilities = context->get_multiview_capabilities();
  3316. // For now this only works with multiview!
  3317. ERR_FAIL_COND_V_MSG(!capabilities.is_supported, VK_NULL_HANDLE, "Multiview not supported");
  3318. // Make sure we limit this to the number of views we support.
  3319. ERR_FAIL_COND_V_MSG(p_view_count > capabilities.max_view_count, VK_NULL_HANDLE, "Hardware does not support requested number of views for Multiview render pass");
  3320. // Set view masks for each subpass
  3321. for (uint32_t i = 0; i < subpasses.size(); i++) {
  3322. view_masks.push_back(view_mask);
  3323. }
  3324. render_pass_multiview_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO;
  3325. render_pass_multiview_create_info.pNext = nullptr;
  3326. render_pass_multiview_create_info.subpassCount = subpasses.size();
  3327. render_pass_multiview_create_info.pViewMasks = view_masks.ptr();
  3328. render_pass_multiview_create_info.dependencyCount = 0;
  3329. render_pass_multiview_create_info.pViewOffsets = nullptr;
  3330. render_pass_multiview_create_info.correlationMaskCount = 1;
  3331. render_pass_multiview_create_info.pCorrelationMasks = &correlation_mask;
  3332. render_pass_create_info.pNext = &render_pass_multiview_create_info;
  3333. }
  3334. VkRenderPass render_pass;
  3335. VkResult res = vkCreateRenderPass(device, &render_pass_create_info, nullptr, &render_pass);
  3336. ERR_FAIL_COND_V_MSG(res, VK_NULL_HANDLE, "vkCreateRenderPass failed with error " + itos(res) + ".");
  3337. return render_pass;
  3338. }
  3339. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create(const Vector<AttachmentFormat> &p_format, uint32_t p_view_count) {
  3340. FramebufferPass pass;
  3341. for (int i = 0; i < p_format.size(); i++) {
  3342. if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3343. pass.depth_attachment = i;
  3344. } else {
  3345. pass.color_attachments.push_back(i);
  3346. }
  3347. }
  3348. Vector<FramebufferPass> passes;
  3349. passes.push_back(pass);
  3350. return framebuffer_format_create_multipass(p_format, passes, p_view_count);
  3351. }
  3352. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create_multipass(const Vector<AttachmentFormat> &p_attachments, Vector<FramebufferPass> &p_passes, uint32_t p_view_count) {
  3353. _THREAD_SAFE_METHOD_
  3354. FramebufferFormatKey key;
  3355. key.attachments = p_attachments;
  3356. key.passes = p_passes;
  3357. key.view_count = p_view_count;
  3358. const RBMap<FramebufferFormatKey, FramebufferFormatID>::Element *E = framebuffer_format_cache.find(key);
  3359. if (E) {
  3360. //exists, return
  3361. return E->get();
  3362. }
  3363. Vector<TextureSamples> samples;
  3364. VkRenderPass render_pass = _render_pass_create(p_attachments, p_passes, INITIAL_ACTION_CLEAR, FINAL_ACTION_READ, INITIAL_ACTION_CLEAR, FINAL_ACTION_READ, p_view_count, &samples); //actions don't matter for this use case
  3365. if (render_pass == VK_NULL_HANDLE) { //was likely invalid
  3366. return INVALID_ID;
  3367. }
  3368. FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT));
  3369. E = framebuffer_format_cache.insert(key, id);
  3370. FramebufferFormat fb_format;
  3371. fb_format.E = E;
  3372. fb_format.render_pass = render_pass;
  3373. fb_format.pass_samples = samples;
  3374. fb_format.view_count = p_view_count;
  3375. framebuffer_formats[id] = fb_format;
  3376. return id;
  3377. }
  3378. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create_empty(TextureSamples p_samples) {
  3379. FramebufferFormatKey key;
  3380. key.passes.push_back(FramebufferPass());
  3381. const RBMap<FramebufferFormatKey, FramebufferFormatID>::Element *E = framebuffer_format_cache.find(key);
  3382. if (E) {
  3383. //exists, return
  3384. return E->get();
  3385. }
  3386. VkSubpassDescription subpass;
  3387. subpass.flags = 0;
  3388. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  3389. subpass.inputAttachmentCount = 0; //unsupported for now
  3390. subpass.pInputAttachments = nullptr;
  3391. subpass.colorAttachmentCount = 0;
  3392. subpass.pColorAttachments = nullptr;
  3393. subpass.pDepthStencilAttachment = nullptr;
  3394. subpass.pResolveAttachments = nullptr;
  3395. subpass.preserveAttachmentCount = 0;
  3396. subpass.pPreserveAttachments = nullptr;
  3397. VkRenderPassCreateInfo render_pass_create_info;
  3398. render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  3399. render_pass_create_info.pNext = nullptr;
  3400. render_pass_create_info.flags = 0;
  3401. render_pass_create_info.attachmentCount = 0;
  3402. render_pass_create_info.pAttachments = nullptr;
  3403. render_pass_create_info.subpassCount = 1;
  3404. render_pass_create_info.pSubpasses = &subpass;
  3405. render_pass_create_info.dependencyCount = 0;
  3406. render_pass_create_info.pDependencies = nullptr;
  3407. VkRenderPass render_pass;
  3408. VkResult res = vkCreateRenderPass(device, &render_pass_create_info, nullptr, &render_pass);
  3409. ERR_FAIL_COND_V_MSG(res, 0, "vkCreateRenderPass for empty fb failed with error " + itos(res) + ".");
  3410. if (render_pass == VK_NULL_HANDLE) { //was likely invalid
  3411. return INVALID_ID;
  3412. }
  3413. FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT));
  3414. E = framebuffer_format_cache.insert(key, id);
  3415. FramebufferFormat fb_format;
  3416. fb_format.E = E;
  3417. fb_format.render_pass = render_pass;
  3418. fb_format.pass_samples.push_back(p_samples);
  3419. framebuffer_formats[id] = fb_format;
  3420. return id;
  3421. }
  3422. RenderingDevice::TextureSamples RenderingDeviceVulkan::framebuffer_format_get_texture_samples(FramebufferFormatID p_format, uint32_t p_pass) {
  3423. HashMap<FramebufferFormatID, FramebufferFormat>::Iterator E = framebuffer_formats.find(p_format);
  3424. ERR_FAIL_COND_V(!E, TEXTURE_SAMPLES_1);
  3425. ERR_FAIL_COND_V(p_pass >= uint32_t(E->value.pass_samples.size()), TEXTURE_SAMPLES_1);
  3426. return E->value.pass_samples[p_pass];
  3427. }
  3428. /***********************/
  3429. /**** RENDER TARGET ****/
  3430. /***********************/
  3431. RID RenderingDeviceVulkan::framebuffer_create_empty(const Size2i &p_size, TextureSamples p_samples, FramebufferFormatID p_format_check) {
  3432. _THREAD_SAFE_METHOD_
  3433. Framebuffer framebuffer;
  3434. framebuffer.format_id = framebuffer_format_create_empty(p_samples);
  3435. ERR_FAIL_COND_V(p_format_check != INVALID_FORMAT_ID && framebuffer.format_id != p_format_check, RID());
  3436. framebuffer.size = p_size;
  3437. framebuffer.view_count = 1;
  3438. return framebuffer_owner.make_rid(framebuffer);
  3439. }
  3440. RID RenderingDeviceVulkan::framebuffer_create(const Vector<RID> &p_texture_attachments, FramebufferFormatID p_format_check, uint32_t p_view_count) {
  3441. _THREAD_SAFE_METHOD_
  3442. FramebufferPass pass;
  3443. for (int i = 0; i < p_texture_attachments.size(); i++) {
  3444. Texture *texture = texture_owner.get_or_null(p_texture_attachments[i]);
  3445. ERR_FAIL_COND_V_MSG(texture && texture->layers != p_view_count, RID(), "Layers of our texture doesn't match view count for this framebuffer");
  3446. if (texture && texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3447. pass.depth_attachment = i;
  3448. } else {
  3449. pass.color_attachments.push_back(texture ? i : FramebufferPass::ATTACHMENT_UNUSED);
  3450. }
  3451. }
  3452. Vector<FramebufferPass> passes;
  3453. passes.push_back(pass);
  3454. return framebuffer_create_multipass(p_texture_attachments, passes, p_format_check, p_view_count);
  3455. }
  3456. RID RenderingDeviceVulkan::framebuffer_create_multipass(const Vector<RID> &p_texture_attachments, Vector<FramebufferPass> &p_passes, FramebufferFormatID p_format_check, uint32_t p_view_count) {
  3457. _THREAD_SAFE_METHOD_
  3458. Vector<AttachmentFormat> attachments;
  3459. attachments.resize(p_texture_attachments.size());
  3460. Size2i size;
  3461. bool size_set = false;
  3462. for (int i = 0; i < p_texture_attachments.size(); i++) {
  3463. AttachmentFormat af;
  3464. Texture *texture = texture_owner.get_or_null(p_texture_attachments[i]);
  3465. if (!texture) {
  3466. af.usage_flags = AttachmentFormat::UNUSED_ATTACHMENT;
  3467. } else {
  3468. ERR_FAIL_COND_V_MSG(texture->layers != p_view_count, RID(), "Layers of our texture doesn't match view count for this framebuffer");
  3469. if (!size_set) {
  3470. size.width = texture->width;
  3471. size.height = texture->height;
  3472. size_set = true;
  3473. } else {
  3474. ERR_FAIL_COND_V_MSG((uint32_t)size.width != texture->width || (uint32_t)size.height != texture->height, RID(),
  3475. "All textures in a framebuffer should be the same size.");
  3476. }
  3477. af.format = texture->format;
  3478. af.samples = texture->samples;
  3479. af.usage_flags = texture->usage_flags;
  3480. }
  3481. attachments.write[i] = af;
  3482. }
  3483. ERR_FAIL_COND_V_MSG(!size_set, RID(), "All attachments unused.");
  3484. FramebufferFormatID format_id = framebuffer_format_create_multipass(attachments, p_passes, p_view_count);
  3485. if (format_id == INVALID_ID) {
  3486. return RID();
  3487. }
  3488. ERR_FAIL_COND_V_MSG(p_format_check != INVALID_ID && format_id != p_format_check, RID(),
  3489. "The format used to check this framebuffer differs from the intended framebuffer format.");
  3490. Framebuffer framebuffer;
  3491. framebuffer.format_id = format_id;
  3492. framebuffer.texture_ids = p_texture_attachments;
  3493. framebuffer.size = size;
  3494. framebuffer.view_count = p_view_count;
  3495. RID id = framebuffer_owner.make_rid(framebuffer);
  3496. for (int i = 0; i < p_texture_attachments.size(); i++) {
  3497. if (p_texture_attachments[i].is_valid()) {
  3498. _add_dependency(id, p_texture_attachments[i]);
  3499. }
  3500. }
  3501. return id;
  3502. }
  3503. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_get_format(RID p_framebuffer) {
  3504. _THREAD_SAFE_METHOD_
  3505. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  3506. ERR_FAIL_COND_V(!framebuffer, INVALID_ID);
  3507. return framebuffer->format_id;
  3508. }
  3509. /*****************/
  3510. /**** SAMPLER ****/
  3511. /*****************/
  3512. RID RenderingDeviceVulkan::sampler_create(const SamplerState &p_state) {
  3513. _THREAD_SAFE_METHOD_
  3514. VkSamplerCreateInfo sampler_create_info;
  3515. sampler_create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  3516. sampler_create_info.pNext = nullptr;
  3517. sampler_create_info.flags = 0;
  3518. sampler_create_info.magFilter = p_state.mag_filter == SAMPLER_FILTER_LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
  3519. sampler_create_info.minFilter = p_state.min_filter == SAMPLER_FILTER_LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
  3520. sampler_create_info.mipmapMode = p_state.mip_filter == SAMPLER_FILTER_LINEAR ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST;
  3521. ERR_FAIL_INDEX_V(p_state.repeat_u, SAMPLER_REPEAT_MODE_MAX, RID());
  3522. sampler_create_info.addressModeU = address_modes[p_state.repeat_u];
  3523. ERR_FAIL_INDEX_V(p_state.repeat_v, SAMPLER_REPEAT_MODE_MAX, RID());
  3524. sampler_create_info.addressModeV = address_modes[p_state.repeat_v];
  3525. ERR_FAIL_INDEX_V(p_state.repeat_w, SAMPLER_REPEAT_MODE_MAX, RID());
  3526. sampler_create_info.addressModeW = address_modes[p_state.repeat_w];
  3527. sampler_create_info.mipLodBias = p_state.lod_bias;
  3528. sampler_create_info.anisotropyEnable = p_state.use_anisotropy;
  3529. sampler_create_info.maxAnisotropy = p_state.anisotropy_max;
  3530. sampler_create_info.compareEnable = p_state.enable_compare;
  3531. ERR_FAIL_INDEX_V(p_state.compare_op, COMPARE_OP_MAX, RID());
  3532. sampler_create_info.compareOp = compare_operators[p_state.compare_op];
  3533. sampler_create_info.minLod = p_state.min_lod;
  3534. sampler_create_info.maxLod = p_state.max_lod;
  3535. ERR_FAIL_INDEX_V(p_state.border_color, SAMPLER_BORDER_COLOR_MAX, RID());
  3536. sampler_create_info.borderColor = sampler_border_colors[p_state.border_color];
  3537. sampler_create_info.unnormalizedCoordinates = p_state.unnormalized_uvw;
  3538. VkSampler sampler;
  3539. VkResult res = vkCreateSampler(device, &sampler_create_info, nullptr, &sampler);
  3540. ERR_FAIL_COND_V_MSG(res, RID(), "vkCreateSampler failed with error " + itos(res) + ".");
  3541. return sampler_owner.make_rid(sampler);
  3542. }
  3543. /**********************/
  3544. /**** VERTEX ARRAY ****/
  3545. /**********************/
  3546. RID RenderingDeviceVulkan::vertex_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data, bool p_use_as_storage) {
  3547. _THREAD_SAFE_METHOD_
  3548. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  3549. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  3550. "Creating buffers with data is forbidden during creation of a draw list");
  3551. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  3552. "Creating buffers with data is forbidden during creation of a draw list");
  3553. uint32_t usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
  3554. if (p_use_as_storage) {
  3555. usage |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
  3556. }
  3557. Buffer buffer;
  3558. _buffer_allocate(&buffer, p_size_bytes, usage, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0);
  3559. if (p_data.size()) {
  3560. uint64_t data_size = p_data.size();
  3561. const uint8_t *r = p_data.ptr();
  3562. _buffer_update(&buffer, 0, r, data_size);
  3563. _buffer_memory_barrier(buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, false);
  3564. }
  3565. return vertex_buffer_owner.make_rid(buffer);
  3566. }
  3567. // 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
  3568. RenderingDevice::VertexFormatID RenderingDeviceVulkan::vertex_format_create(const Vector<VertexAttribute> &p_vertex_formats) {
  3569. _THREAD_SAFE_METHOD_
  3570. VertexDescriptionKey key;
  3571. key.vertex_formats = p_vertex_formats;
  3572. VertexFormatID *idptr = vertex_format_cache.getptr(key);
  3573. if (idptr) {
  3574. return *idptr;
  3575. }
  3576. //does not exist, create one and cache it
  3577. VertexDescriptionCache vdcache;
  3578. vdcache.bindings = memnew_arr(VkVertexInputBindingDescription, p_vertex_formats.size());
  3579. vdcache.attributes = memnew_arr(VkVertexInputAttributeDescription, p_vertex_formats.size());
  3580. RBSet<int> used_locations;
  3581. for (int i = 0; i < p_vertex_formats.size(); i++) {
  3582. ERR_CONTINUE(p_vertex_formats[i].format >= DATA_FORMAT_MAX);
  3583. ERR_FAIL_COND_V(used_locations.has(p_vertex_formats[i].location), INVALID_ID);
  3584. ERR_FAIL_COND_V_MSG(get_format_vertex_size(p_vertex_formats[i].format) == 0, INVALID_ID,
  3585. "Data format for attachment (" + itos(i) + "), '" + named_formats[p_vertex_formats[i].format] + "', is not valid for a vertex array.");
  3586. vdcache.bindings[i].binding = i;
  3587. vdcache.bindings[i].stride = p_vertex_formats[i].stride;
  3588. vdcache.bindings[i].inputRate = p_vertex_formats[i].frequency == VERTEX_FREQUENCY_INSTANCE ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX;
  3589. vdcache.attributes[i].binding = i;
  3590. vdcache.attributes[i].location = p_vertex_formats[i].location;
  3591. vdcache.attributes[i].format = vulkan_formats[p_vertex_formats[i].format];
  3592. vdcache.attributes[i].offset = p_vertex_formats[i].offset;
  3593. used_locations.insert(p_vertex_formats[i].location);
  3594. }
  3595. vdcache.create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  3596. vdcache.create_info.pNext = nullptr;
  3597. vdcache.create_info.flags = 0;
  3598. vdcache.create_info.vertexAttributeDescriptionCount = p_vertex_formats.size();
  3599. vdcache.create_info.pVertexAttributeDescriptions = vdcache.attributes;
  3600. vdcache.create_info.vertexBindingDescriptionCount = p_vertex_formats.size();
  3601. vdcache.create_info.pVertexBindingDescriptions = vdcache.bindings;
  3602. vdcache.vertex_formats = p_vertex_formats;
  3603. VertexFormatID id = VertexFormatID(vertex_format_cache.size()) | (VertexFormatID(ID_TYPE_VERTEX_FORMAT) << ID_BASE_SHIFT);
  3604. vertex_format_cache[key] = id;
  3605. vertex_formats[id] = vdcache;
  3606. return id;
  3607. }
  3608. RID RenderingDeviceVulkan::vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector<RID> &p_src_buffers) {
  3609. _THREAD_SAFE_METHOD_
  3610. ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID());
  3611. const VertexDescriptionCache &vd = vertex_formats[p_vertex_format];
  3612. ERR_FAIL_COND_V(vd.vertex_formats.size() != p_src_buffers.size(), RID());
  3613. for (int i = 0; i < p_src_buffers.size(); i++) {
  3614. ERR_FAIL_COND_V(!vertex_buffer_owner.owns(p_src_buffers[i]), RID());
  3615. }
  3616. VertexArray vertex_array;
  3617. vertex_array.vertex_count = p_vertex_count;
  3618. vertex_array.description = p_vertex_format;
  3619. vertex_array.max_instances_allowed = 0xFFFFFFFF; //by default as many as you want
  3620. for (int i = 0; i < p_src_buffers.size(); i++) {
  3621. Buffer *buffer = vertex_buffer_owner.get_or_null(p_src_buffers[i]);
  3622. //validate with buffer
  3623. {
  3624. const VertexAttribute &atf = vd.vertex_formats[i];
  3625. uint32_t element_size = get_format_vertex_size(atf.format);
  3626. ERR_FAIL_COND_V(element_size == 0, RID()); //should never happens since this was prevalidated
  3627. if (atf.frequency == VERTEX_FREQUENCY_VERTEX) {
  3628. //validate size for regular drawing
  3629. uint64_t total_size = uint64_t(atf.stride) * (p_vertex_count - 1) + atf.offset + element_size;
  3630. ERR_FAIL_COND_V_MSG(total_size > buffer->size, RID(),
  3631. "Attachment (" + itos(i) + ") will read past the end of the buffer.");
  3632. } else {
  3633. //validate size for instances drawing
  3634. uint64_t available = buffer->size - atf.offset;
  3635. ERR_FAIL_COND_V_MSG(available < element_size, RID(),
  3636. "Attachment (" + itos(i) + ") uses instancing, but it's just too small.");
  3637. uint32_t instances_allowed = available / atf.stride;
  3638. vertex_array.max_instances_allowed = MIN(instances_allowed, vertex_array.max_instances_allowed);
  3639. }
  3640. }
  3641. vertex_array.buffers.push_back(buffer->buffer);
  3642. vertex_array.offsets.push_back(0); //offset unused, but passing anyway
  3643. }
  3644. RID id = vertex_array_owner.make_rid(vertex_array);
  3645. for (int i = 0; i < p_src_buffers.size(); i++) {
  3646. _add_dependency(id, p_src_buffers[i]);
  3647. }
  3648. return id;
  3649. }
  3650. RID RenderingDeviceVulkan::index_buffer_create(uint32_t p_index_count, IndexBufferFormat p_format, const Vector<uint8_t> &p_data, bool p_use_restart_indices) {
  3651. _THREAD_SAFE_METHOD_
  3652. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  3653. "Creating buffers with data is forbidden during creation of a draw list");
  3654. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  3655. "Creating buffers with data is forbidden during creation of a draw list");
  3656. ERR_FAIL_COND_V(p_index_count == 0, RID());
  3657. IndexBuffer index_buffer;
  3658. index_buffer.index_type = (p_format == INDEX_BUFFER_FORMAT_UINT16) ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32;
  3659. index_buffer.supports_restart_indices = p_use_restart_indices;
  3660. index_buffer.index_count = p_index_count;
  3661. uint32_t size_bytes = p_index_count * ((p_format == INDEX_BUFFER_FORMAT_UINT16) ? 2 : 4);
  3662. #ifdef DEBUG_ENABLED
  3663. if (p_data.size()) {
  3664. index_buffer.max_index = 0;
  3665. ERR_FAIL_COND_V_MSG((uint32_t)p_data.size() != size_bytes, RID(),
  3666. "Default index buffer initializer array size (" + itos(p_data.size()) + ") does not match format required size (" + itos(size_bytes) + ").");
  3667. const uint8_t *r = p_data.ptr();
  3668. if (p_format == INDEX_BUFFER_FORMAT_UINT16) {
  3669. const uint16_t *index16 = (const uint16_t *)r;
  3670. for (uint32_t i = 0; i < p_index_count; i++) {
  3671. if (p_use_restart_indices && index16[i] == 0xFFFF) {
  3672. continue; //restart index, ignore
  3673. }
  3674. index_buffer.max_index = MAX(index16[i], index_buffer.max_index);
  3675. }
  3676. } else {
  3677. const uint32_t *index32 = (const uint32_t *)r;
  3678. for (uint32_t i = 0; i < p_index_count; i++) {
  3679. if (p_use_restart_indices && index32[i] == 0xFFFFFFFF) {
  3680. continue; //restart index, ignore
  3681. }
  3682. index_buffer.max_index = MAX(index32[i], index_buffer.max_index);
  3683. }
  3684. }
  3685. } else {
  3686. index_buffer.max_index = 0xFFFFFFFF;
  3687. }
  3688. #else
  3689. index_buffer.max_index = 0xFFFFFFFF;
  3690. #endif
  3691. _buffer_allocate(&index_buffer, size_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0);
  3692. if (p_data.size()) {
  3693. uint64_t data_size = p_data.size();
  3694. const uint8_t *r = p_data.ptr();
  3695. _buffer_update(&index_buffer, 0, r, data_size);
  3696. _buffer_memory_barrier(index_buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_INDEX_READ_BIT, false);
  3697. }
  3698. return index_buffer_owner.make_rid(index_buffer);
  3699. }
  3700. RID RenderingDeviceVulkan::index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count) {
  3701. _THREAD_SAFE_METHOD_
  3702. ERR_FAIL_COND_V(!index_buffer_owner.owns(p_index_buffer), RID());
  3703. IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_index_buffer);
  3704. ERR_FAIL_COND_V(p_index_count == 0, RID());
  3705. ERR_FAIL_COND_V(p_index_offset + p_index_count > index_buffer->index_count, RID());
  3706. IndexArray index_array;
  3707. index_array.max_index = index_buffer->max_index;
  3708. index_array.buffer = index_buffer->buffer;
  3709. index_array.offset = p_index_offset;
  3710. index_array.indices = p_index_count;
  3711. index_array.index_type = index_buffer->index_type;
  3712. index_array.supports_restart_indices = index_buffer->supports_restart_indices;
  3713. RID id = index_array_owner.make_rid(index_array);
  3714. _add_dependency(id, p_index_buffer);
  3715. return id;
  3716. }
  3717. /****************/
  3718. /**** SHADER ****/
  3719. /****************/
  3720. static const char *shader_stage_names[RenderingDevice::SHADER_STAGE_MAX] = {
  3721. "Vertex",
  3722. "Fragment",
  3723. "TesselationControl",
  3724. "TesselationEvaluation",
  3725. "Compute"
  3726. };
  3727. static const char *shader_uniform_names[RenderingDevice::UNIFORM_TYPE_MAX] = {
  3728. "Sampler", "CombinedSampler", "Texture", "Image", "TextureBuffer", "SamplerTextureBuffer", "ImageBuffer", "UniformBuffer", "StorageBuffer", "InputAttachment"
  3729. };
  3730. static VkShaderStageFlagBits shader_stage_masks[RenderingDevice::SHADER_STAGE_MAX] = {
  3731. VK_SHADER_STAGE_VERTEX_BIT,
  3732. VK_SHADER_STAGE_FRAGMENT_BIT,
  3733. VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT,
  3734. VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
  3735. VK_SHADER_STAGE_COMPUTE_BIT,
  3736. };
  3737. String RenderingDeviceVulkan::_shader_uniform_debug(RID p_shader, int p_set) {
  3738. String ret;
  3739. const Shader *shader = shader_owner.get_or_null(p_shader);
  3740. ERR_FAIL_COND_V(!shader, String());
  3741. for (int i = 0; i < shader->sets.size(); i++) {
  3742. if (p_set >= 0 && i != p_set) {
  3743. continue;
  3744. }
  3745. for (int j = 0; j < shader->sets[i].uniform_info.size(); j++) {
  3746. const UniformInfo &ui = shader->sets[i].uniform_info[j];
  3747. if (!ret.is_empty()) {
  3748. ret += "\n";
  3749. }
  3750. ret += "Set: " + itos(i) + " Binding: " + itos(ui.binding) + " Type: " + shader_uniform_names[ui.type] + " Length: " + itos(ui.length);
  3751. }
  3752. }
  3753. return ret;
  3754. }
  3755. #if 0
  3756. bool RenderingDeviceVulkan::_uniform_add_binding(Vector<Vector<VkDescriptorSetLayoutBinding> > &bindings, Vector<Vector<UniformInfo> > &uniform_infos, const glslang::TObjectReflection &reflection, RenderingDevice::ShaderStage p_stage, Shader::PushConstant &push_constant, String *r_error) {
  3757. VkDescriptorSetLayoutBinding layout_binding;
  3758. UniformInfo info;
  3759. switch (reflection.getType()->getBasicType()) {
  3760. case glslang::EbtSampler: {
  3761. //print_line("DEBUG: IsSampler");
  3762. if (reflection.getType()->getSampler().dim == glslang::EsdBuffer) {
  3763. //texture buffers
  3764. if (reflection.getType()->getSampler().isCombined()) {
  3765. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  3766. info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER;
  3767. //print_line("DEBUG: SAMPLER: texel combined");
  3768. } else if (reflection.getType()->getSampler().isTexture()) {
  3769. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  3770. info.type = UNIFORM_TYPE_TEXTURE_BUFFER;
  3771. //print_line("DEBUG: SAMPLER: texel alone");
  3772. } else if (reflection.getType()->getSampler().isImage()) {
  3773. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
  3774. info.type = UNIFORM_TYPE_IMAGE_BUFFER;
  3775. //print_line("DEBUG: SAMPLER: texel buffer");
  3776. } else {
  3777. if (r_error) {
  3778. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' is of unsupported buffer type.";
  3779. }
  3780. return false;
  3781. }
  3782. } else if (reflection.getType()->getSampler().isCombined()) {
  3783. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  3784. info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
  3785. //print_line("DEBUG: SAMPLER: combined");
  3786. } else if (reflection.getType()->getSampler().isPureSampler()) {
  3787. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
  3788. info.type = UNIFORM_TYPE_SAMPLER;
  3789. //print_line("DEBUG: SAMPLER: sampler");
  3790. } else if (reflection.getType()->getSampler().isTexture()) {
  3791. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  3792. info.type = UNIFORM_TYPE_TEXTURE;
  3793. //print_line("DEBUG: SAMPLER: image");
  3794. } else if (reflection.getType()->getSampler().isImage()) {
  3795. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  3796. info.type = UNIFORM_TYPE_IMAGE;
  3797. //print_line("DEBUG: SAMPLER: storage image");
  3798. } else {
  3799. //print_line("DEBUG: sampler unknown");
  3800. if (r_error) {
  3801. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' is of unsupported sampler type.";
  3802. }
  3803. return false;
  3804. }
  3805. if (reflection.getType()->isArray()) {
  3806. layout_binding.descriptorCount = reflection.getType()->getArraySizes()->getCumulativeSize();
  3807. //print_line("DEBUG: array of size: " + itos(layout_binding.descriptorCount));
  3808. } else {
  3809. layout_binding.descriptorCount = 1;
  3810. }
  3811. info.length = layout_binding.descriptorCount;
  3812. } break;
  3813. /*case glslang::EbtStruct: {
  3814. print_line("DEBUG: Struct");
  3815. } break;*/
  3816. case glslang::EbtBlock: {
  3817. //print_line("DEBUG: Block");
  3818. if (reflection.getType()->getQualifier().storage == glslang::EvqUniform) {
  3819. if (reflection.getType()->getQualifier().layoutPushConstant) {
  3820. uint32_t len = reflection.size;
  3821. if (push_constant.push_constant_size != 0 && push_constant.push_constant_size != len) {
  3822. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' push constants for different stages should all be the same size.";
  3823. return false;
  3824. }
  3825. push_constant.push_constant_size = len;
  3826. push_constant.push_constants_vk_stage |= shader_stage_masks[p_stage];
  3827. return true;
  3828. }
  3829. //print_line("DEBUG: Uniform buffer");
  3830. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  3831. info.type = UNIFORM_TYPE_UNIFORM_BUFFER;
  3832. } else if (reflection.getType()->getQualifier().storage == glslang::EvqBuffer) {
  3833. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  3834. info.type = UNIFORM_TYPE_STORAGE_BUFFER;
  3835. //print_line("DEBUG: Storage buffer");
  3836. } else {
  3837. if (r_error) {
  3838. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' is of unsupported block type: (" + itos(reflection.getType()->getQualifier().storage) + ").";
  3839. }
  3840. return false;
  3841. }
  3842. if (reflection.getType()->isArray()) {
  3843. layout_binding.descriptorCount = reflection.getType()->getArraySizes()->getCumulativeSize();
  3844. //print_line("DEBUG: array of size: " + itos(layout_binding.descriptorCount));
  3845. } else {
  3846. layout_binding.descriptorCount = 1;
  3847. }
  3848. info.length = reflection.size;
  3849. } break;
  3850. /*case glslang::EbtReference: {
  3851. } break;*/
  3852. /*case glslang::EbtAtomicUint: {
  3853. } break;*/
  3854. default: {
  3855. if (reflection.getType()->getQualifier().hasOffset() || reflection.name.find(".") != std::string::npos) {
  3856. //member of uniform block?
  3857. return true;
  3858. }
  3859. if (r_error) {
  3860. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' unsupported uniform type.";
  3861. }
  3862. return false;
  3863. }
  3864. }
  3865. if (!reflection.getType()->getQualifier().hasBinding()) {
  3866. if (r_error) {
  3867. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' lacks a binding number.";
  3868. }
  3869. return false;
  3870. }
  3871. uint32_t set = reflection.getType()->getQualifier().hasSet() ? reflection.getType()->getQualifier().layoutSet : 0;
  3872. if (set >= MAX_UNIFORM_SETS) {
  3873. if (r_error) {
  3874. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' uses a set (" + itos(set) + ") index larger than what is supported (" + itos(MAX_UNIFORM_SETS) + ").";
  3875. }
  3876. return false;
  3877. }
  3878. if (set >= limits.maxBoundDescriptorSets) {
  3879. if (r_error) {
  3880. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' uses a set (" + itos(set) + ") index larger than what is supported by the hardware (" + itos(limits.maxBoundDescriptorSets) + ").";
  3881. }
  3882. return false;
  3883. }
  3884. uint32_t binding = reflection.getType()->getQualifier().layoutBinding;
  3885. if (set < (uint32_t)bindings.size()) {
  3886. //check if this already exists
  3887. for (int i = 0; i < bindings[set].size(); i++) {
  3888. if (bindings[set][i].binding == binding) {
  3889. //already exists, verify that it's the same type
  3890. if (bindings[set][i].descriptorType != layout_binding.descriptorType) {
  3891. if (r_error) {
  3892. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' trying to re-use location for set=" + itos(set) + ", binding=" + itos(binding) + " with different uniform type.";
  3893. }
  3894. return false;
  3895. }
  3896. //also, verify that it's the same size
  3897. if (bindings[set][i].descriptorCount != layout_binding.descriptorCount || uniform_infos[set][i].length != info.length) {
  3898. if (r_error) {
  3899. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' trying to re-use location for set=" + itos(set) + ", binding=" + itos(binding) + " with different uniform size.";
  3900. }
  3901. return false;
  3902. }
  3903. //just append stage mask and return
  3904. bindings.write[set].write[i].stageFlags |= shader_stage_masks[p_stage];
  3905. uniform_infos.write[set].write[i].stages |= 1 << p_stage;
  3906. return true;
  3907. }
  3908. }
  3909. }
  3910. layout_binding.binding = binding;
  3911. layout_binding.stageFlags = shader_stage_masks[p_stage];
  3912. layout_binding.pImmutableSamplers = nullptr; //no support for this yet
  3913. info.stages = 1 << p_stage;
  3914. info.binding = binding;
  3915. if (set >= (uint32_t)bindings.size()) {
  3916. bindings.resize(set + 1);
  3917. uniform_infos.resize(set + 1);
  3918. }
  3919. #if 0
  3920. print_line("stage: " + String(shader_stage_names[p_stage]) + " set: " + itos(set) + " binding: " + itos(info.binding) + " type:" + shader_uniform_names[info.type] + " length: " + itos(info.length));
  3921. #endif
  3922. bindings.write[set].push_back(layout_binding);
  3923. uniform_infos.write[set].push_back(info);
  3924. return true;
  3925. }
  3926. #endif
  3927. //version 1: initial
  3928. //version 2: Added shader name
  3929. #define SHADER_BINARY_VERSION 2
  3930. String RenderingDeviceVulkan::shader_get_binary_cache_key() const {
  3931. return "Vulkan-SV" + itos(SHADER_BINARY_VERSION);
  3932. }
  3933. struct RenderingDeviceVulkanShaderBinaryDataBinding {
  3934. uint32_t type;
  3935. uint32_t binding;
  3936. uint32_t stages;
  3937. uint32_t length; //size of arrays (in total elements), or ubos (in bytes * total elements)
  3938. };
  3939. struct RenderingDeviceVulkanShaderBinarySpecializationConstant {
  3940. uint32_t type;
  3941. uint32_t constant_id;
  3942. union {
  3943. uint32_t int_value;
  3944. float float_value;
  3945. bool bool_value;
  3946. };
  3947. uint32_t stage_flags;
  3948. };
  3949. struct RenderingDeviceVulkanShaderBinaryData {
  3950. uint32_t vertex_input_mask;
  3951. uint32_t fragment_outputs;
  3952. uint32_t specialization_constant_count;
  3953. uint32_t is_compute;
  3954. uint32_t compute_local_size[3];
  3955. uint32_t set_count;
  3956. uint32_t push_constant_size;
  3957. uint32_t push_constants_vk_stage;
  3958. uint32_t stage_count;
  3959. uint32_t shader_name_len;
  3960. };
  3961. Vector<uint8_t> RenderingDeviceVulkan::shader_compile_binary_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv, const String &p_shader_name) {
  3962. RenderingDeviceVulkanShaderBinaryData binary_data;
  3963. binary_data.vertex_input_mask = 0;
  3964. binary_data.fragment_outputs = 0;
  3965. binary_data.specialization_constant_count = 0;
  3966. binary_data.is_compute = 0;
  3967. binary_data.compute_local_size[0] = 0;
  3968. binary_data.compute_local_size[1] = 0;
  3969. binary_data.compute_local_size[2] = 0;
  3970. binary_data.set_count = 0;
  3971. binary_data.push_constant_size = 0;
  3972. binary_data.push_constants_vk_stage = 0;
  3973. Vector<Vector<RenderingDeviceVulkanShaderBinaryDataBinding>> uniform_info; //set bindings
  3974. Vector<RenderingDeviceVulkanShaderBinarySpecializationConstant> specialization_constants;
  3975. uint32_t stages_processed = 0;
  3976. for (int i = 0; i < p_spirv.size(); i++) {
  3977. if (p_spirv[i].shader_stage == SHADER_STAGE_COMPUTE) {
  3978. binary_data.is_compute = true;
  3979. ERR_FAIL_COND_V_MSG(p_spirv.size() != 1, Vector<uint8_t>(),
  3980. "Compute shaders can only receive one stage, dedicated to compute.");
  3981. }
  3982. ERR_FAIL_COND_V_MSG(stages_processed & (1 << p_spirv[i].shader_stage), Vector<uint8_t>(),
  3983. "Stage " + String(shader_stage_names[p_spirv[i].shader_stage]) + " submitted more than once.");
  3984. {
  3985. SpvReflectShaderModule module;
  3986. const uint8_t *spirv = p_spirv[i].spir_v.ptr();
  3987. SpvReflectResult result = spvReflectCreateShaderModule(p_spirv[i].spir_v.size(), spirv, &module);
  3988. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  3989. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed parsing shader.");
  3990. if (binary_data.is_compute) {
  3991. binary_data.compute_local_size[0] = module.entry_points->local_size.x;
  3992. binary_data.compute_local_size[1] = module.entry_points->local_size.y;
  3993. binary_data.compute_local_size[2] = module.entry_points->local_size.z;
  3994. }
  3995. uint32_t binding_count = 0;
  3996. result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, nullptr);
  3997. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  3998. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating descriptor bindings.");
  3999. uint32_t stage = p_spirv[i].shader_stage;
  4000. if (binding_count > 0) {
  4001. //Parse bindings
  4002. Vector<SpvReflectDescriptorBinding *> bindings;
  4003. bindings.resize(binding_count);
  4004. result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, bindings.ptrw());
  4005. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4006. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed getting descriptor bindings.");
  4007. for (uint32_t j = 0; j < binding_count; j++) {
  4008. const SpvReflectDescriptorBinding &binding = *bindings[j];
  4009. RenderingDeviceVulkanShaderBinaryDataBinding info;
  4010. bool need_array_dimensions = false;
  4011. bool need_block_size = false;
  4012. switch (binding.descriptor_type) {
  4013. case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLER: {
  4014. info.type = UNIFORM_TYPE_SAMPLER;
  4015. need_array_dimensions = true;
  4016. } break;
  4017. case SPV_REFLECT_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: {
  4018. info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
  4019. need_array_dimensions = true;
  4020. } break;
  4021. case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLED_IMAGE: {
  4022. info.type = UNIFORM_TYPE_TEXTURE;
  4023. need_array_dimensions = true;
  4024. } break;
  4025. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
  4026. info.type = UNIFORM_TYPE_IMAGE;
  4027. need_array_dimensions = true;
  4028. } break;
  4029. case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: {
  4030. info.type = UNIFORM_TYPE_TEXTURE_BUFFER;
  4031. need_array_dimensions = true;
  4032. } break;
  4033. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: {
  4034. info.type = UNIFORM_TYPE_IMAGE_BUFFER;
  4035. need_array_dimensions = true;
  4036. } break;
  4037. case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER: {
  4038. info.type = UNIFORM_TYPE_UNIFORM_BUFFER;
  4039. need_block_size = true;
  4040. } break;
  4041. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER: {
  4042. info.type = UNIFORM_TYPE_STORAGE_BUFFER;
  4043. need_block_size = true;
  4044. } break;
  4045. case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: {
  4046. ERR_PRINT("Dynamic uniform buffer not supported.");
  4047. continue;
  4048. } break;
  4049. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {
  4050. ERR_PRINT("Dynamic storage buffer not supported.");
  4051. continue;
  4052. } break;
  4053. case SPV_REFLECT_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: {
  4054. info.type = UNIFORM_TYPE_INPUT_ATTACHMENT;
  4055. need_array_dimensions = true;
  4056. } break;
  4057. case SPV_REFLECT_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR: {
  4058. ERR_PRINT("Acceleration structure not supported.");
  4059. continue;
  4060. } break;
  4061. }
  4062. if (need_array_dimensions) {
  4063. if (binding.array.dims_count == 0) {
  4064. info.length = 1;
  4065. } else {
  4066. for (uint32_t k = 0; k < binding.array.dims_count; k++) {
  4067. if (k == 0) {
  4068. info.length = binding.array.dims[0];
  4069. } else {
  4070. info.length *= binding.array.dims[k];
  4071. }
  4072. }
  4073. }
  4074. } else if (need_block_size) {
  4075. info.length = binding.block.size;
  4076. } else {
  4077. info.length = 0;
  4078. }
  4079. info.binding = binding.binding;
  4080. uint32_t set = binding.set;
  4081. ERR_FAIL_COND_V_MSG(set >= MAX_UNIFORM_SETS, Vector<uint8_t>(),
  4082. "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' uses a set (" + itos(set) + ") index larger than what is supported (" + itos(MAX_UNIFORM_SETS) + ").");
  4083. ERR_FAIL_COND_V_MSG(set >= limits.maxBoundDescriptorSets, Vector<uint8_t>(),
  4084. "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' uses a set (" + itos(set) + ") index larger than what is supported by the hardware (" + itos(limits.maxBoundDescriptorSets) + ").");
  4085. if (set < (uint32_t)uniform_info.size()) {
  4086. //check if this already exists
  4087. bool exists = false;
  4088. for (int k = 0; k < uniform_info[set].size(); k++) {
  4089. if (uniform_info[set][k].binding == (uint32_t)info.binding) {
  4090. //already exists, verify that it's the same type
  4091. ERR_FAIL_COND_V_MSG(uniform_info[set][k].type != info.type, Vector<uint8_t>(),
  4092. "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' trying to re-use location for set=" + itos(set) + ", binding=" + itos(info.binding) + " with different uniform type.");
  4093. //also, verify that it's the same size
  4094. ERR_FAIL_COND_V_MSG(uniform_info[set][k].length != info.length, Vector<uint8_t>(),
  4095. "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' trying to re-use location for set=" + itos(set) + ", binding=" + itos(info.binding) + " with different uniform size.");
  4096. //just append stage mask and return
  4097. uniform_info.write[set].write[k].stages |= 1 << stage;
  4098. exists = true;
  4099. }
  4100. }
  4101. if (exists) {
  4102. continue; //merged
  4103. }
  4104. }
  4105. info.stages = 1 << stage;
  4106. if (set >= (uint32_t)uniform_info.size()) {
  4107. uniform_info.resize(set + 1);
  4108. }
  4109. uniform_info.write[set].push_back(info);
  4110. }
  4111. }
  4112. {
  4113. //specialization constants
  4114. uint32_t sc_count = 0;
  4115. result = spvReflectEnumerateSpecializationConstants(&module, &sc_count, nullptr);
  4116. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4117. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating specialization constants.");
  4118. if (sc_count) {
  4119. Vector<SpvReflectSpecializationConstant *> spec_constants;
  4120. spec_constants.resize(sc_count);
  4121. result = spvReflectEnumerateSpecializationConstants(&module, &sc_count, spec_constants.ptrw());
  4122. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4123. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining specialization constants.");
  4124. for (uint32_t j = 0; j < sc_count; j++) {
  4125. int32_t existing = -1;
  4126. RenderingDeviceVulkanShaderBinarySpecializationConstant sconst;
  4127. SpvReflectSpecializationConstant *spc = spec_constants[j];
  4128. sconst.constant_id = spc->constant_id;
  4129. sconst.int_value = 0.0; // clear previous value JIC
  4130. switch (spc->constant_type) {
  4131. case SPV_REFLECT_SPECIALIZATION_CONSTANT_BOOL: {
  4132. sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL;
  4133. sconst.bool_value = spc->default_value.int_bool_value != 0;
  4134. } break;
  4135. case SPV_REFLECT_SPECIALIZATION_CONSTANT_INT: {
  4136. sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT;
  4137. sconst.int_value = spc->default_value.int_bool_value;
  4138. } break;
  4139. case SPV_REFLECT_SPECIALIZATION_CONSTANT_FLOAT: {
  4140. sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT;
  4141. sconst.float_value = spc->default_value.float_value;
  4142. } break;
  4143. }
  4144. sconst.stage_flags = 1 << p_spirv[i].shader_stage;
  4145. for (int k = 0; k < specialization_constants.size(); k++) {
  4146. if (specialization_constants[k].constant_id == sconst.constant_id) {
  4147. ERR_FAIL_COND_V_MSG(specialization_constants[k].type != sconst.type, Vector<uint8_t>(), "More than one specialization constant used for id (" + itos(sconst.constant_id) + "), but their types differ.");
  4148. ERR_FAIL_COND_V_MSG(specialization_constants[k].int_value != sconst.int_value, Vector<uint8_t>(), "More than one specialization constant used for id (" + itos(sconst.constant_id) + "), but their default values differ.");
  4149. existing = k;
  4150. break;
  4151. }
  4152. }
  4153. if (existing > 0) {
  4154. specialization_constants.write[existing].stage_flags |= sconst.stage_flags;
  4155. } else {
  4156. specialization_constants.push_back(sconst);
  4157. }
  4158. }
  4159. }
  4160. }
  4161. if (stage == SHADER_STAGE_VERTEX) {
  4162. uint32_t iv_count = 0;
  4163. result = spvReflectEnumerateInputVariables(&module, &iv_count, nullptr);
  4164. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4165. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating input variables.");
  4166. if (iv_count) {
  4167. Vector<SpvReflectInterfaceVariable *> input_vars;
  4168. input_vars.resize(iv_count);
  4169. result = spvReflectEnumerateInputVariables(&module, &iv_count, input_vars.ptrw());
  4170. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4171. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining input variables.");
  4172. for (uint32_t j = 0; j < iv_count; j++) {
  4173. if (input_vars[j] && input_vars[j]->decoration_flags == 0) { //regular input
  4174. binary_data.vertex_input_mask |= (1 << uint32_t(input_vars[j]->location));
  4175. }
  4176. }
  4177. }
  4178. }
  4179. if (stage == SHADER_STAGE_FRAGMENT) {
  4180. uint32_t ov_count = 0;
  4181. result = spvReflectEnumerateOutputVariables(&module, &ov_count, nullptr);
  4182. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4183. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating output variables.");
  4184. if (ov_count) {
  4185. Vector<SpvReflectInterfaceVariable *> output_vars;
  4186. output_vars.resize(ov_count);
  4187. result = spvReflectEnumerateOutputVariables(&module, &ov_count, output_vars.ptrw());
  4188. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4189. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining output variables.");
  4190. for (uint32_t j = 0; j < ov_count; j++) {
  4191. const SpvReflectInterfaceVariable *refvar = output_vars[j];
  4192. if (refvar != nullptr && refvar->built_in != SpvBuiltInFragDepth) {
  4193. binary_data.fragment_outputs |= 1 << refvar->location;
  4194. }
  4195. }
  4196. }
  4197. }
  4198. uint32_t pc_count = 0;
  4199. result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, nullptr);
  4200. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4201. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating push constants.");
  4202. if (pc_count) {
  4203. ERR_FAIL_COND_V_MSG(pc_count > 1, Vector<uint8_t>(),
  4204. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "': Only one push constant is supported, which should be the same across shader stages.");
  4205. Vector<SpvReflectBlockVariable *> pconstants;
  4206. pconstants.resize(pc_count);
  4207. result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, pconstants.ptrw());
  4208. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4209. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining push constants.");
  4210. #if 0
  4211. if (pconstants[0] == nullptr) {
  4212. Ref<FileAccess> f = FileAccess::open("res://popo.spv", FileAccess::WRITE);
  4213. f->store_buffer((const uint8_t *)&SpirV[0], SpirV.size() * sizeof(uint32_t));
  4214. }
  4215. #endif
  4216. ERR_FAIL_COND_V_MSG(binary_data.push_constant_size && binary_data.push_constant_size != pconstants[0]->size, Vector<uint8_t>(),
  4217. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "': Push constant block must be the same across shader stages.");
  4218. binary_data.push_constant_size = pconstants[0]->size;
  4219. binary_data.push_constants_vk_stage |= shader_stage_masks[stage];
  4220. //print_line("Stage: " + String(shader_stage_names[stage]) + " push constant of size=" + itos(push_constant.push_constant_size));
  4221. }
  4222. // Destroy the reflection data when no longer required.
  4223. spvReflectDestroyShaderModule(&module);
  4224. }
  4225. stages_processed |= (1 << p_spirv[i].shader_stage);
  4226. }
  4227. Vector<Vector<uint8_t>> compressed_stages;
  4228. Vector<uint32_t> smolv_size;
  4229. Vector<uint32_t> zstd_size; //if 0, stdno t used
  4230. uint32_t stages_binary_size = 0;
  4231. bool strip_debug = false;
  4232. for (int i = 0; i < p_spirv.size(); i++) {
  4233. smolv::ByteArray smolv;
  4234. if (!smolv::Encode(p_spirv[i].spir_v.ptr(), p_spirv[i].spir_v.size(), smolv, strip_debug ? smolv::kEncodeFlagStripDebugInfo : 0)) {
  4235. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Error compressing shader stage :" + String(shader_stage_names[p_spirv[i].shader_stage]));
  4236. } else {
  4237. smolv_size.push_back(smolv.size());
  4238. { //zstd
  4239. Vector<uint8_t> zstd;
  4240. zstd.resize(Compression::get_max_compressed_buffer_size(smolv.size(), Compression::MODE_ZSTD));
  4241. int dst_size = Compression::compress(zstd.ptrw(), &smolv[0], smolv.size(), Compression::MODE_ZSTD);
  4242. if (dst_size > 0 && (uint32_t)dst_size < smolv.size()) {
  4243. zstd_size.push_back(dst_size);
  4244. zstd.resize(dst_size);
  4245. compressed_stages.push_back(zstd);
  4246. } else {
  4247. Vector<uint8_t> smv;
  4248. smv.resize(smolv.size());
  4249. memcpy(smv.ptrw(), &smolv[0], smolv.size());
  4250. zstd_size.push_back(0); //not using zstd
  4251. compressed_stages.push_back(smv);
  4252. }
  4253. }
  4254. }
  4255. uint32_t s = compressed_stages[i].size();
  4256. if (s % 4 != 0) {
  4257. s += 4 - (s % 4);
  4258. }
  4259. stages_binary_size += s;
  4260. }
  4261. binary_data.specialization_constant_count = specialization_constants.size();
  4262. binary_data.set_count = uniform_info.size();
  4263. binary_data.stage_count = p_spirv.size();
  4264. CharString shader_name_utf = p_shader_name.utf8();
  4265. binary_data.shader_name_len = shader_name_utf.length();
  4266. uint32_t total_size = sizeof(uint32_t) * 3; //header + version + main datasize;
  4267. total_size += sizeof(RenderingDeviceVulkanShaderBinaryData);
  4268. total_size += binary_data.shader_name_len;
  4269. if ((binary_data.shader_name_len % 4) != 0) { //alignment rules are really strange
  4270. total_size += 4 - (binary_data.shader_name_len % 4);
  4271. }
  4272. for (int i = 0; i < uniform_info.size(); i++) {
  4273. total_size += sizeof(uint32_t);
  4274. total_size += uniform_info[i].size() * sizeof(RenderingDeviceVulkanShaderBinaryDataBinding);
  4275. }
  4276. total_size += sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) * specialization_constants.size();
  4277. total_size += compressed_stages.size() * sizeof(uint32_t) * 3; //sizes
  4278. total_size += stages_binary_size;
  4279. Vector<uint8_t> ret;
  4280. ret.resize(total_size);
  4281. {
  4282. uint32_t offset = 0;
  4283. uint8_t *binptr = ret.ptrw();
  4284. binptr[0] = 'G';
  4285. binptr[1] = 'V';
  4286. binptr[2] = 'B';
  4287. binptr[3] = 'D'; //godot vulkan binary data
  4288. offset += 4;
  4289. encode_uint32(SHADER_BINARY_VERSION, binptr + offset);
  4290. offset += sizeof(uint32_t);
  4291. encode_uint32(sizeof(RenderingDeviceVulkanShaderBinaryData), binptr + offset);
  4292. offset += sizeof(uint32_t);
  4293. memcpy(binptr + offset, &binary_data, sizeof(RenderingDeviceVulkanShaderBinaryData));
  4294. offset += sizeof(RenderingDeviceVulkanShaderBinaryData);
  4295. memcpy(binptr + offset, shader_name_utf.ptr(), binary_data.shader_name_len);
  4296. offset += binary_data.shader_name_len;
  4297. if ((binary_data.shader_name_len % 4) != 0) { //alignment rules are really strange
  4298. offset += 4 - (binary_data.shader_name_len % 4);
  4299. }
  4300. for (int i = 0; i < uniform_info.size(); i++) {
  4301. int count = uniform_info[i].size();
  4302. encode_uint32(count, binptr + offset);
  4303. offset += sizeof(uint32_t);
  4304. if (count > 0) {
  4305. memcpy(binptr + offset, uniform_info[i].ptr(), sizeof(RenderingDeviceVulkanShaderBinaryDataBinding) * count);
  4306. offset += sizeof(RenderingDeviceVulkanShaderBinaryDataBinding) * count;
  4307. }
  4308. }
  4309. if (specialization_constants.size()) {
  4310. memcpy(binptr + offset, specialization_constants.ptr(), sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) * specialization_constants.size());
  4311. offset += sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) * specialization_constants.size();
  4312. }
  4313. for (int i = 0; i < compressed_stages.size(); i++) {
  4314. encode_uint32(p_spirv[i].shader_stage, binptr + offset);
  4315. offset += sizeof(uint32_t);
  4316. encode_uint32(smolv_size[i], binptr + offset);
  4317. offset += sizeof(uint32_t);
  4318. encode_uint32(zstd_size[i], binptr + offset);
  4319. offset += sizeof(uint32_t);
  4320. memcpy(binptr + offset, compressed_stages[i].ptr(), compressed_stages[i].size());
  4321. uint32_t s = compressed_stages[i].size();
  4322. if (s % 4 != 0) {
  4323. s += 4 - (s % 4);
  4324. }
  4325. offset += s;
  4326. }
  4327. ERR_FAIL_COND_V(offset != (uint32_t)ret.size(), Vector<uint8_t>());
  4328. }
  4329. return ret;
  4330. }
  4331. RID RenderingDeviceVulkan::shader_create_from_bytecode(const Vector<uint8_t> &p_shader_binary) {
  4332. const uint8_t *binptr = p_shader_binary.ptr();
  4333. uint32_t binsize = p_shader_binary.size();
  4334. uint32_t read_offset = 0;
  4335. //consistency check
  4336. ERR_FAIL_COND_V(binsize < sizeof(uint32_t) * 3 + sizeof(RenderingDeviceVulkanShaderBinaryData), RID());
  4337. ERR_FAIL_COND_V(binptr[0] != 'G' || binptr[1] != 'V' || binptr[2] != 'B' || binptr[3] != 'D', RID());
  4338. uint32_t bin_version = decode_uint32(binptr + 4);
  4339. ERR_FAIL_COND_V(bin_version > SHADER_BINARY_VERSION, RID());
  4340. uint32_t bin_data_size = decode_uint32(binptr + 8);
  4341. const RenderingDeviceVulkanShaderBinaryData &binary_data = *(reinterpret_cast<const RenderingDeviceVulkanShaderBinaryData *>(binptr + 12));
  4342. Shader::PushConstant push_constant;
  4343. push_constant.push_constant_size = binary_data.push_constant_size;
  4344. push_constant.push_constants_vk_stage = binary_data.push_constants_vk_stage;
  4345. uint32_t vertex_input_mask = binary_data.vertex_input_mask;
  4346. uint32_t fragment_outputs = binary_data.fragment_outputs;
  4347. bool is_compute = binary_data.is_compute;
  4348. const uint32_t compute_local_size[3] = { binary_data.compute_local_size[0], binary_data.compute_local_size[1], binary_data.compute_local_size[2] };
  4349. read_offset += sizeof(uint32_t) * 3 + bin_data_size;
  4350. String name;
  4351. if (binary_data.shader_name_len) {
  4352. name.parse_utf8((const char *)(binptr + read_offset), binary_data.shader_name_len);
  4353. read_offset += binary_data.shader_name_len;
  4354. if ((binary_data.shader_name_len % 4) != 0) { //alignment rules are really strange
  4355. read_offset += 4 - (binary_data.shader_name_len % 4);
  4356. }
  4357. }
  4358. Vector<Vector<VkDescriptorSetLayoutBinding>> set_bindings;
  4359. Vector<Vector<UniformInfo>> uniform_info;
  4360. set_bindings.resize(binary_data.set_count);
  4361. uniform_info.resize(binary_data.set_count);
  4362. for (uint32_t i = 0; i < binary_data.set_count; i++) {
  4363. ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) >= binsize, RID());
  4364. uint32_t set_count = decode_uint32(binptr + read_offset);
  4365. read_offset += sizeof(uint32_t);
  4366. const RenderingDeviceVulkanShaderBinaryDataBinding *set_ptr = reinterpret_cast<const RenderingDeviceVulkanShaderBinaryDataBinding *>(binptr + read_offset);
  4367. uint32_t set_size = set_count * sizeof(RenderingDeviceVulkanShaderBinaryDataBinding);
  4368. ERR_FAIL_COND_V(read_offset + set_size >= binsize, RID());
  4369. for (uint32_t j = 0; j < set_count; j++) {
  4370. UniformInfo info;
  4371. info.type = UniformType(set_ptr[j].type);
  4372. info.length = set_ptr[j].length;
  4373. info.binding = set_ptr[j].binding;
  4374. info.stages = set_ptr[j].stages;
  4375. VkDescriptorSetLayoutBinding layout_binding;
  4376. layout_binding.pImmutableSamplers = nullptr;
  4377. layout_binding.binding = set_ptr[j].binding;
  4378. layout_binding.descriptorCount = 1;
  4379. layout_binding.stageFlags = 0;
  4380. for (uint32_t k = 0; k < SHADER_STAGE_MAX; k++) {
  4381. if (set_ptr[j].stages & (1 << k)) {
  4382. layout_binding.stageFlags |= shader_stage_masks[k];
  4383. }
  4384. }
  4385. switch (info.type) {
  4386. case UNIFORM_TYPE_SAMPLER: {
  4387. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
  4388. layout_binding.descriptorCount = set_ptr[j].length;
  4389. } break;
  4390. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {
  4391. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  4392. layout_binding.descriptorCount = set_ptr[j].length;
  4393. } break;
  4394. case UNIFORM_TYPE_TEXTURE: {
  4395. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  4396. layout_binding.descriptorCount = set_ptr[j].length;
  4397. } break;
  4398. case UNIFORM_TYPE_IMAGE: {
  4399. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  4400. layout_binding.descriptorCount = set_ptr[j].length;
  4401. } break;
  4402. case UNIFORM_TYPE_TEXTURE_BUFFER: {
  4403. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  4404. layout_binding.descriptorCount = set_ptr[j].length;
  4405. } break;
  4406. case UNIFORM_TYPE_IMAGE_BUFFER: {
  4407. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
  4408. } break;
  4409. case UNIFORM_TYPE_UNIFORM_BUFFER: {
  4410. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  4411. } break;
  4412. case UNIFORM_TYPE_STORAGE_BUFFER: {
  4413. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  4414. } break;
  4415. case UNIFORM_TYPE_INPUT_ATTACHMENT: {
  4416. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
  4417. } break;
  4418. default: {
  4419. ERR_FAIL_V(RID());
  4420. }
  4421. }
  4422. set_bindings.write[i].push_back(layout_binding);
  4423. uniform_info.write[i].push_back(info);
  4424. }
  4425. read_offset += set_size;
  4426. }
  4427. ERR_FAIL_COND_V(read_offset + binary_data.specialization_constant_count * sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) >= binsize, RID());
  4428. Vector<Shader::SpecializationConstant> specialization_constants;
  4429. for (uint32_t i = 0; i < binary_data.specialization_constant_count; i++) {
  4430. const RenderingDeviceVulkanShaderBinarySpecializationConstant &src_sc = *(reinterpret_cast<const RenderingDeviceVulkanShaderBinarySpecializationConstant *>(binptr + read_offset));
  4431. Shader::SpecializationConstant sc;
  4432. sc.constant.int_value = src_sc.int_value;
  4433. sc.constant.type = PipelineSpecializationConstantType(src_sc.type);
  4434. sc.constant.constant_id = src_sc.constant_id;
  4435. sc.stage_flags = src_sc.stage_flags;
  4436. specialization_constants.push_back(sc);
  4437. read_offset += sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant);
  4438. }
  4439. Vector<Vector<uint8_t>> stage_spirv_data;
  4440. Vector<ShaderStage> stage_type;
  4441. for (uint32_t i = 0; i < binary_data.stage_count; i++) {
  4442. ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) * 3 >= binsize, RID());
  4443. uint32_t stage = decode_uint32(binptr + read_offset);
  4444. read_offset += sizeof(uint32_t);
  4445. uint32_t smolv_size = decode_uint32(binptr + read_offset);
  4446. read_offset += sizeof(uint32_t);
  4447. uint32_t zstd_size = decode_uint32(binptr + read_offset);
  4448. read_offset += sizeof(uint32_t);
  4449. uint32_t buf_size = (zstd_size > 0) ? zstd_size : smolv_size;
  4450. Vector<uint8_t> smolv;
  4451. const uint8_t *src_smolv = nullptr;
  4452. if (zstd_size > 0) {
  4453. //decompress to smolv
  4454. smolv.resize(smolv_size);
  4455. int dec_smolv_size = Compression::decompress(smolv.ptrw(), smolv.size(), binptr + read_offset, zstd_size, Compression::MODE_ZSTD);
  4456. ERR_FAIL_COND_V(dec_smolv_size != (int32_t)smolv_size, RID());
  4457. src_smolv = smolv.ptr();
  4458. } else {
  4459. src_smolv = binptr + read_offset;
  4460. }
  4461. Vector<uint8_t> spirv;
  4462. uint32_t spirv_size = smolv::GetDecodedBufferSize(src_smolv, smolv_size);
  4463. spirv.resize(spirv_size);
  4464. if (!smolv::Decode(src_smolv, smolv_size, spirv.ptrw(), spirv_size)) {
  4465. ERR_FAIL_V_MSG(RID(), "Malformed smolv input uncompressing shader stage:" + String(shader_stage_names[stage]));
  4466. }
  4467. stage_spirv_data.push_back(spirv);
  4468. stage_type.push_back(ShaderStage(stage));
  4469. if (buf_size % 4 != 0) {
  4470. buf_size += 4 - (buf_size % 4);
  4471. }
  4472. ERR_FAIL_COND_V(read_offset + buf_size > binsize, RID());
  4473. read_offset += buf_size;
  4474. }
  4475. ERR_FAIL_COND_V(read_offset != binsize, RID());
  4476. //all good, let's create modules
  4477. _THREAD_SAFE_METHOD_
  4478. Shader shader;
  4479. shader.vertex_input_mask = vertex_input_mask;
  4480. shader.fragment_output_mask = fragment_outputs;
  4481. shader.push_constant = push_constant;
  4482. shader.is_compute = is_compute;
  4483. shader.compute_local_size[0] = compute_local_size[0];
  4484. shader.compute_local_size[1] = compute_local_size[1];
  4485. shader.compute_local_size[2] = compute_local_size[2];
  4486. shader.specialization_constants = specialization_constants;
  4487. shader.name = name;
  4488. String error_text;
  4489. bool success = true;
  4490. for (int i = 0; i < stage_spirv_data.size(); i++) {
  4491. VkShaderModuleCreateInfo shader_module_create_info;
  4492. shader_module_create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  4493. shader_module_create_info.pNext = nullptr;
  4494. shader_module_create_info.flags = 0;
  4495. shader_module_create_info.codeSize = stage_spirv_data[i].size();
  4496. const uint8_t *r = stage_spirv_data[i].ptr();
  4497. shader_module_create_info.pCode = (const uint32_t *)r;
  4498. VkShaderModule module;
  4499. VkResult res = vkCreateShaderModule(device, &shader_module_create_info, nullptr, &module);
  4500. if (res) {
  4501. success = false;
  4502. error_text = "Error (" + itos(res) + ") creating shader module for stage: " + String(shader_stage_names[stage_type[i]]);
  4503. break;
  4504. }
  4505. const VkShaderStageFlagBits shader_stage_bits[SHADER_STAGE_MAX] = {
  4506. VK_SHADER_STAGE_VERTEX_BIT,
  4507. VK_SHADER_STAGE_FRAGMENT_BIT,
  4508. VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT,
  4509. VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
  4510. VK_SHADER_STAGE_COMPUTE_BIT,
  4511. };
  4512. VkPipelineShaderStageCreateInfo shader_stage;
  4513. shader_stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  4514. shader_stage.pNext = nullptr;
  4515. shader_stage.flags = 0;
  4516. shader_stage.stage = shader_stage_bits[stage_type[i]];
  4517. shader_stage.module = module;
  4518. shader_stage.pName = "main";
  4519. shader_stage.pSpecializationInfo = nullptr;
  4520. shader.pipeline_stages.push_back(shader_stage);
  4521. }
  4522. //proceed to create descriptor sets
  4523. if (success) {
  4524. for (int i = 0; i < set_bindings.size(); i++) {
  4525. //empty ones are fine if they were not used according to spec (binding count will be 0)
  4526. VkDescriptorSetLayoutCreateInfo layout_create_info;
  4527. layout_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
  4528. layout_create_info.pNext = nullptr;
  4529. layout_create_info.flags = 0;
  4530. layout_create_info.bindingCount = set_bindings[i].size();
  4531. layout_create_info.pBindings = set_bindings[i].ptr();
  4532. VkDescriptorSetLayout layout;
  4533. VkResult res = vkCreateDescriptorSetLayout(device, &layout_create_info, nullptr, &layout);
  4534. if (res) {
  4535. error_text = "Error (" + itos(res) + ") creating descriptor set layout for set " + itos(i);
  4536. success = false;
  4537. break;
  4538. }
  4539. Shader::Set set;
  4540. set.descriptor_set_layout = layout;
  4541. set.uniform_info = uniform_info[i];
  4542. //sort and hash
  4543. set.uniform_info.sort();
  4544. uint32_t format = 0; //no format, default
  4545. if (set.uniform_info.size()) {
  4546. //has data, needs an actual format;
  4547. UniformSetFormat usformat;
  4548. usformat.uniform_info = set.uniform_info;
  4549. RBMap<UniformSetFormat, uint32_t>::Element *E = uniform_set_format_cache.find(usformat);
  4550. if (E) {
  4551. format = E->get();
  4552. } else {
  4553. format = uniform_set_format_cache.size() + 1;
  4554. uniform_set_format_cache.insert(usformat, format);
  4555. }
  4556. }
  4557. shader.sets.push_back(set);
  4558. shader.set_formats.push_back(format);
  4559. }
  4560. }
  4561. if (success) {
  4562. //create pipeline layout
  4563. VkPipelineLayoutCreateInfo pipeline_layout_create_info;
  4564. pipeline_layout_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  4565. pipeline_layout_create_info.pNext = nullptr;
  4566. pipeline_layout_create_info.flags = 0;
  4567. pipeline_layout_create_info.setLayoutCount = shader.sets.size();
  4568. Vector<VkDescriptorSetLayout> layouts;
  4569. layouts.resize(shader.sets.size());
  4570. for (int i = 0; i < layouts.size(); i++) {
  4571. layouts.write[i] = shader.sets[i].descriptor_set_layout;
  4572. }
  4573. pipeline_layout_create_info.pSetLayouts = layouts.ptr();
  4574. // Needs to be declared in this outer scope, otherwise it may not outlive its assignment
  4575. // to pipeline_layout_create_info.
  4576. VkPushConstantRange push_constant_range;
  4577. if (push_constant.push_constant_size) {
  4578. push_constant_range.stageFlags = push_constant.push_constants_vk_stage;
  4579. push_constant_range.offset = 0;
  4580. push_constant_range.size = push_constant.push_constant_size;
  4581. pipeline_layout_create_info.pushConstantRangeCount = 1;
  4582. pipeline_layout_create_info.pPushConstantRanges = &push_constant_range;
  4583. } else {
  4584. pipeline_layout_create_info.pushConstantRangeCount = 0;
  4585. pipeline_layout_create_info.pPushConstantRanges = nullptr;
  4586. }
  4587. VkResult err = vkCreatePipelineLayout(device, &pipeline_layout_create_info, nullptr, &shader.pipeline_layout);
  4588. if (err) {
  4589. error_text = "Error (" + itos(err) + ") creating pipeline layout.";
  4590. success = false;
  4591. }
  4592. }
  4593. if (!success) {
  4594. //clean up if failed
  4595. for (int i = 0; i < shader.pipeline_stages.size(); i++) {
  4596. vkDestroyShaderModule(device, shader.pipeline_stages[i].module, nullptr);
  4597. }
  4598. for (int i = 0; i < shader.sets.size(); i++) {
  4599. vkDestroyDescriptorSetLayout(device, shader.sets[i].descriptor_set_layout, nullptr);
  4600. }
  4601. ERR_FAIL_V_MSG(RID(), error_text);
  4602. }
  4603. return shader_owner.make_rid(shader);
  4604. }
  4605. uint32_t RenderingDeviceVulkan::shader_get_vertex_input_attribute_mask(RID p_shader) {
  4606. _THREAD_SAFE_METHOD_
  4607. const Shader *shader = shader_owner.get_or_null(p_shader);
  4608. ERR_FAIL_COND_V(!shader, 0);
  4609. return shader->vertex_input_mask;
  4610. }
  4611. /******************/
  4612. /**** UNIFORMS ****/
  4613. /******************/
  4614. RID RenderingDeviceVulkan::uniform_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data) {
  4615. _THREAD_SAFE_METHOD_
  4616. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  4617. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  4618. "Creating buffers with data is forbidden during creation of a draw list");
  4619. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  4620. "Creating buffers with data is forbidden during creation of a draw list");
  4621. Buffer buffer;
  4622. Error err = _buffer_allocate(&buffer, p_size_bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0);
  4623. ERR_FAIL_COND_V(err != OK, RID());
  4624. if (p_data.size()) {
  4625. uint64_t data_size = p_data.size();
  4626. const uint8_t *r = p_data.ptr();
  4627. _buffer_update(&buffer, 0, r, data_size);
  4628. _buffer_memory_barrier(buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_UNIFORM_READ_BIT, false);
  4629. }
  4630. return uniform_buffer_owner.make_rid(buffer);
  4631. }
  4632. RID RenderingDeviceVulkan::storage_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data, uint32_t p_usage) {
  4633. _THREAD_SAFE_METHOD_
  4634. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  4635. "Creating buffers with data is forbidden during creation of a draw list");
  4636. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  4637. "Creating buffers with data is forbidden during creation of a draw list");
  4638. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  4639. Buffer buffer;
  4640. buffer.usage = p_usage;
  4641. uint32_t flags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
  4642. if (p_usage & STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT) {
  4643. flags |= VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
  4644. }
  4645. Error err = _buffer_allocate(&buffer, p_size_bytes, flags, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0);
  4646. ERR_FAIL_COND_V(err != OK, RID());
  4647. if (p_data.size()) {
  4648. uint64_t data_size = p_data.size();
  4649. const uint8_t *r = p_data.ptr();
  4650. _buffer_update(&buffer, 0, r, data_size);
  4651. _buffer_memory_barrier(buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, false);
  4652. }
  4653. return storage_buffer_owner.make_rid(buffer);
  4654. }
  4655. RID RenderingDeviceVulkan::texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector<uint8_t> &p_data) {
  4656. _THREAD_SAFE_METHOD_
  4657. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  4658. "Creating buffers with data is forbidden during creation of a draw list");
  4659. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  4660. "Creating buffers with data is forbidden during creation of a draw list");
  4661. uint32_t element_size = get_format_vertex_size(p_format);
  4662. ERR_FAIL_COND_V_MSG(element_size == 0, RID(), "Format requested is not supported for texture buffers");
  4663. uint64_t size_bytes = uint64_t(element_size) * p_size_elements;
  4664. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != size_bytes, RID());
  4665. TextureBuffer texture_buffer;
  4666. Error err = _buffer_allocate(&texture_buffer.buffer, size_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0);
  4667. ERR_FAIL_COND_V(err != OK, RID());
  4668. if (p_data.size()) {
  4669. uint64_t data_size = p_data.size();
  4670. const uint8_t *r = p_data.ptr();
  4671. _buffer_update(&texture_buffer.buffer, 0, r, data_size);
  4672. _buffer_memory_barrier(texture_buffer.buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, false);
  4673. }
  4674. VkBufferViewCreateInfo view_create_info;
  4675. view_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;
  4676. view_create_info.pNext = nullptr;
  4677. view_create_info.flags = 0;
  4678. view_create_info.buffer = texture_buffer.buffer.buffer;
  4679. view_create_info.format = vulkan_formats[p_format];
  4680. view_create_info.offset = 0;
  4681. view_create_info.range = size_bytes;
  4682. texture_buffer.view = VK_NULL_HANDLE;
  4683. VkResult res = vkCreateBufferView(device, &view_create_info, nullptr, &texture_buffer.view);
  4684. if (res) {
  4685. _buffer_free(&texture_buffer.buffer);
  4686. ERR_FAIL_V_MSG(RID(), "Unable to create buffer view, error " + itos(res) + ".");
  4687. }
  4688. //allocate the view
  4689. return texture_buffer_owner.make_rid(texture_buffer);
  4690. }
  4691. RenderingDeviceVulkan::DescriptorPool *RenderingDeviceVulkan::_descriptor_pool_allocate(const DescriptorPoolKey &p_key) {
  4692. if (!descriptor_pools.has(p_key)) {
  4693. descriptor_pools[p_key] = RBSet<DescriptorPool *>();
  4694. }
  4695. DescriptorPool *pool = nullptr;
  4696. for (DescriptorPool *E : descriptor_pools[p_key]) {
  4697. if (E->usage < max_descriptors_per_pool) {
  4698. pool = E;
  4699. break;
  4700. }
  4701. }
  4702. if (!pool) {
  4703. //create a new one
  4704. pool = memnew(DescriptorPool);
  4705. pool->usage = 0;
  4706. VkDescriptorPoolCreateInfo descriptor_pool_create_info;
  4707. descriptor_pool_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
  4708. descriptor_pool_create_info.pNext = nullptr;
  4709. descriptor_pool_create_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; // can't think how somebody may NOT need this flag..
  4710. descriptor_pool_create_info.maxSets = max_descriptors_per_pool;
  4711. Vector<VkDescriptorPoolSize> sizes;
  4712. //here comes more vulkan API strangeness
  4713. if (p_key.uniform_type[UNIFORM_TYPE_SAMPLER]) {
  4714. VkDescriptorPoolSize s;
  4715. s.type = VK_DESCRIPTOR_TYPE_SAMPLER;
  4716. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_SAMPLER] * max_descriptors_per_pool;
  4717. sizes.push_back(s);
  4718. }
  4719. if (p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE]) {
  4720. VkDescriptorPoolSize s;
  4721. s.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  4722. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE] * max_descriptors_per_pool;
  4723. sizes.push_back(s);
  4724. }
  4725. if (p_key.uniform_type[UNIFORM_TYPE_TEXTURE]) {
  4726. VkDescriptorPoolSize s;
  4727. s.type = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  4728. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_TEXTURE] * max_descriptors_per_pool;
  4729. sizes.push_back(s);
  4730. }
  4731. if (p_key.uniform_type[UNIFORM_TYPE_IMAGE]) {
  4732. VkDescriptorPoolSize s;
  4733. s.type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  4734. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_IMAGE] * max_descriptors_per_pool;
  4735. sizes.push_back(s);
  4736. }
  4737. if (p_key.uniform_type[UNIFORM_TYPE_TEXTURE_BUFFER] || p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER]) {
  4738. VkDescriptorPoolSize s;
  4739. s.type = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  4740. s.descriptorCount = (p_key.uniform_type[UNIFORM_TYPE_TEXTURE_BUFFER] + p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER]) * max_descriptors_per_pool;
  4741. sizes.push_back(s);
  4742. }
  4743. if (p_key.uniform_type[UNIFORM_TYPE_IMAGE_BUFFER]) {
  4744. VkDescriptorPoolSize s;
  4745. s.type = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
  4746. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_IMAGE_BUFFER] * max_descriptors_per_pool;
  4747. sizes.push_back(s);
  4748. }
  4749. if (p_key.uniform_type[UNIFORM_TYPE_UNIFORM_BUFFER]) {
  4750. VkDescriptorPoolSize s;
  4751. s.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  4752. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_UNIFORM_BUFFER] * max_descriptors_per_pool;
  4753. sizes.push_back(s);
  4754. }
  4755. if (p_key.uniform_type[UNIFORM_TYPE_STORAGE_BUFFER]) {
  4756. VkDescriptorPoolSize s;
  4757. s.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  4758. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_STORAGE_BUFFER] * max_descriptors_per_pool;
  4759. sizes.push_back(s);
  4760. }
  4761. if (p_key.uniform_type[UNIFORM_TYPE_INPUT_ATTACHMENT]) {
  4762. VkDescriptorPoolSize s;
  4763. s.type = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
  4764. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_INPUT_ATTACHMENT] * max_descriptors_per_pool;
  4765. sizes.push_back(s);
  4766. }
  4767. descriptor_pool_create_info.poolSizeCount = sizes.size();
  4768. descriptor_pool_create_info.pPoolSizes = sizes.ptr();
  4769. VkResult res = vkCreateDescriptorPool(device, &descriptor_pool_create_info, nullptr, &pool->pool);
  4770. if (res) {
  4771. memdelete(pool);
  4772. ERR_FAIL_COND_V_MSG(res, nullptr, "vkCreateDescriptorPool failed with error " + itos(res) + ".");
  4773. }
  4774. descriptor_pools[p_key].insert(pool);
  4775. }
  4776. pool->usage++;
  4777. return pool;
  4778. }
  4779. void RenderingDeviceVulkan::_descriptor_pool_free(const DescriptorPoolKey &p_key, DescriptorPool *p_pool) {
  4780. #ifdef DEBUG_ENABLED
  4781. ERR_FAIL_COND(!descriptor_pools[p_key].has(p_pool));
  4782. #endif
  4783. ERR_FAIL_COND(p_pool->usage == 0);
  4784. p_pool->usage--;
  4785. if (p_pool->usage == 0) {
  4786. vkDestroyDescriptorPool(device, p_pool->pool, nullptr);
  4787. descriptor_pools[p_key].erase(p_pool);
  4788. memdelete(p_pool);
  4789. if (descriptor_pools[p_key].is_empty()) {
  4790. descriptor_pools.erase(p_key);
  4791. }
  4792. }
  4793. }
  4794. RID RenderingDeviceVulkan::uniform_set_create(const Vector<Uniform> &p_uniforms, RID p_shader, uint32_t p_shader_set) {
  4795. _THREAD_SAFE_METHOD_
  4796. ERR_FAIL_COND_V(p_uniforms.size() == 0, RID());
  4797. Shader *shader = shader_owner.get_or_null(p_shader);
  4798. ERR_FAIL_COND_V(!shader, RID());
  4799. ERR_FAIL_COND_V_MSG(p_shader_set >= (uint32_t)shader->sets.size() || shader->sets[p_shader_set].uniform_info.size() == 0, RID(),
  4800. "Desired set (" + itos(p_shader_set) + ") not used by shader.");
  4801. //see that all sets in shader are satisfied
  4802. const Shader::Set &set = shader->sets[p_shader_set];
  4803. uint32_t uniform_count = p_uniforms.size();
  4804. const Uniform *uniforms = p_uniforms.ptr();
  4805. uint32_t set_uniform_count = set.uniform_info.size();
  4806. const UniformInfo *set_uniforms = set.uniform_info.ptr();
  4807. Vector<VkWriteDescriptorSet> writes;
  4808. DescriptorPoolKey pool_key;
  4809. //to keep them alive until update call
  4810. List<Vector<VkDescriptorBufferInfo>> buffer_infos;
  4811. List<Vector<VkBufferView>> buffer_views;
  4812. List<Vector<VkDescriptorImageInfo>> image_infos;
  4813. //used for verification to make sure a uniform set does not use a framebuffer bound texture
  4814. LocalVector<UniformSet::AttachableTexture> attachable_textures;
  4815. Vector<Texture *> mutable_sampled_textures;
  4816. Vector<Texture *> mutable_storage_textures;
  4817. for (uint32_t i = 0; i < set_uniform_count; i++) {
  4818. const UniformInfo &set_uniform = set_uniforms[i];
  4819. int uniform_idx = -1;
  4820. for (int j = 0; j < (int)uniform_count; j++) {
  4821. if (uniforms[j].binding == set_uniform.binding) {
  4822. uniform_idx = j;
  4823. }
  4824. }
  4825. ERR_FAIL_COND_V_MSG(uniform_idx == -1, RID(),
  4826. "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.");
  4827. const Uniform &uniform = uniforms[uniform_idx];
  4828. ERR_FAIL_COND_V_MSG(uniform.uniform_type != set_uniform.type, RID(),
  4829. "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] + "'.");
  4830. VkWriteDescriptorSet write; //common header
  4831. write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4832. write.pNext = nullptr;
  4833. write.dstSet = VK_NULL_HANDLE; //will assign afterwards when everything is valid
  4834. write.dstBinding = set_uniform.binding;
  4835. write.dstArrayElement = 0;
  4836. write.descriptorCount = 0;
  4837. write.descriptorType = VK_DESCRIPTOR_TYPE_MAX_ENUM; //Invalid value.
  4838. write.pImageInfo = nullptr;
  4839. write.pBufferInfo = nullptr;
  4840. write.pTexelBufferView = nullptr;
  4841. uint32_t type_size = 1;
  4842. switch (uniform.uniform_type) {
  4843. case UNIFORM_TYPE_SAMPLER: {
  4844. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  4845. if (set_uniform.length > 1) {
  4846. 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()) + ").");
  4847. } else {
  4848. ERR_FAIL_V_MSG(RID(), "Sampler (binding: " + itos(uniform.binding) + ") should provide one ID referencing a sampler (IDs provided: " + itos(uniform.get_id_count()) + ").");
  4849. }
  4850. }
  4851. Vector<VkDescriptorImageInfo> image_info;
  4852. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  4853. VkSampler *sampler = sampler_owner.get_or_null(uniform.get_id(j));
  4854. ERR_FAIL_COND_V_MSG(!sampler, RID(), "Sampler (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid sampler.");
  4855. VkDescriptorImageInfo img_info;
  4856. img_info.sampler = *sampler;
  4857. img_info.imageView = VK_NULL_HANDLE;
  4858. img_info.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  4859. image_info.push_back(img_info);
  4860. }
  4861. write.dstArrayElement = 0;
  4862. write.descriptorCount = uniform.get_id_count();
  4863. write.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
  4864. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  4865. write.pBufferInfo = nullptr;
  4866. write.pTexelBufferView = nullptr;
  4867. type_size = uniform.get_id_count();
  4868. } break;
  4869. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {
  4870. if (uniform.get_id_count() != (uint32_t)set_uniform.length * 2) {
  4871. if (set_uniform.length > 1) {
  4872. 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()) + ").");
  4873. } else {
  4874. 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()) + ").");
  4875. }
  4876. }
  4877. Vector<VkDescriptorImageInfo> image_info;
  4878. for (uint32_t j = 0; j < uniform.get_id_count(); j += 2) {
  4879. VkSampler *sampler = sampler_owner.get_or_null(uniform.get_id(j + 0));
  4880. ERR_FAIL_COND_V_MSG(!sampler, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler.");
  4881. Texture *texture = texture_owner.get_or_null(uniform.get_id(j + 1));
  4882. ERR_FAIL_COND_V_MSG(!texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  4883. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  4884. "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  4885. VkDescriptorImageInfo img_info;
  4886. img_info.sampler = *sampler;
  4887. img_info.imageView = texture->view;
  4888. if (texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT)) {
  4889. UniformSet::AttachableTexture attachable_texture;
  4890. attachable_texture.bind = set_uniform.binding;
  4891. attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.get_id(j + 1);
  4892. attachable_textures.push_back(attachable_texture);
  4893. }
  4894. if (texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  4895. //can also be used as storage, add to mutable sampled
  4896. mutable_sampled_textures.push_back(texture);
  4897. }
  4898. if (texture->owner.is_valid()) {
  4899. texture = texture_owner.get_or_null(texture->owner);
  4900. ERR_FAIL_COND_V(!texture, RID()); //bug, should never happen
  4901. }
  4902. img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  4903. image_info.push_back(img_info);
  4904. }
  4905. write.dstArrayElement = 0;
  4906. write.descriptorCount = uniform.get_id_count() / 2;
  4907. write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  4908. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  4909. write.pBufferInfo = nullptr;
  4910. write.pTexelBufferView = nullptr;
  4911. type_size = uniform.get_id_count() / 2;
  4912. } break;
  4913. case UNIFORM_TYPE_TEXTURE: {
  4914. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  4915. if (set_uniform.length > 1) {
  4916. 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()) + ").");
  4917. } else {
  4918. ERR_FAIL_V_MSG(RID(), "Texture (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");
  4919. }
  4920. }
  4921. Vector<VkDescriptorImageInfo> image_info;
  4922. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  4923. Texture *texture = texture_owner.get_or_null(uniform.get_id(j));
  4924. ERR_FAIL_COND_V_MSG(!texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  4925. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  4926. "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  4927. VkDescriptorImageInfo img_info;
  4928. img_info.sampler = VK_NULL_HANDLE;
  4929. img_info.imageView = texture->view;
  4930. if (texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT)) {
  4931. UniformSet::AttachableTexture attachable_texture;
  4932. attachable_texture.bind = set_uniform.binding;
  4933. attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.get_id(j);
  4934. attachable_textures.push_back(attachable_texture);
  4935. }
  4936. if (texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  4937. //can also be used as storage, add to mutable sampled
  4938. mutable_sampled_textures.push_back(texture);
  4939. }
  4940. if (texture->owner.is_valid()) {
  4941. texture = texture_owner.get_or_null(texture->owner);
  4942. ERR_FAIL_COND_V(!texture, RID()); //bug, should never happen
  4943. }
  4944. img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  4945. image_info.push_back(img_info);
  4946. }
  4947. write.dstArrayElement = 0;
  4948. write.descriptorCount = uniform.get_id_count();
  4949. write.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  4950. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  4951. write.pBufferInfo = nullptr;
  4952. write.pTexelBufferView = nullptr;
  4953. type_size = uniform.get_id_count();
  4954. } break;
  4955. case UNIFORM_TYPE_IMAGE: {
  4956. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  4957. if (set_uniform.length > 1) {
  4958. 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()) + ").");
  4959. } else {
  4960. ERR_FAIL_V_MSG(RID(), "Image (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");
  4961. }
  4962. }
  4963. Vector<VkDescriptorImageInfo> image_info;
  4964. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  4965. Texture *texture = texture_owner.get_or_null(uniform.get_id(j));
  4966. ERR_FAIL_COND_V_MSG(!texture, RID(),
  4967. "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  4968. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT), RID(),
  4969. "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_STORAGE_BIT usage flag set in order to be used as uniform.");
  4970. VkDescriptorImageInfo img_info;
  4971. img_info.sampler = VK_NULL_HANDLE;
  4972. img_info.imageView = texture->view;
  4973. if (texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT) {
  4974. //can also be used as storage, add to mutable sampled
  4975. mutable_storage_textures.push_back(texture);
  4976. }
  4977. if (texture->owner.is_valid()) {
  4978. texture = texture_owner.get_or_null(texture->owner);
  4979. ERR_FAIL_COND_V(!texture, RID()); //bug, should never happen
  4980. }
  4981. img_info.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
  4982. image_info.push_back(img_info);
  4983. }
  4984. write.dstArrayElement = 0;
  4985. write.descriptorCount = uniform.get_id_count();
  4986. write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  4987. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  4988. write.pBufferInfo = nullptr;
  4989. write.pTexelBufferView = nullptr;
  4990. type_size = uniform.get_id_count();
  4991. } break;
  4992. case UNIFORM_TYPE_TEXTURE_BUFFER: {
  4993. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  4994. if (set_uniform.length > 1) {
  4995. 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()) + ").");
  4996. } else {
  4997. 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()) + ").");
  4998. }
  4999. }
  5000. Vector<VkDescriptorBufferInfo> buffer_info;
  5001. Vector<VkBufferView> buffer_view;
  5002. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  5003. TextureBuffer *buffer = texture_buffer_owner.get_or_null(uniform.get_id(j));
  5004. ERR_FAIL_COND_V_MSG(!buffer, RID(), "Texture Buffer (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture buffer.");
  5005. buffer_info.push_back(buffer->buffer.buffer_info);
  5006. buffer_view.push_back(buffer->view);
  5007. }
  5008. write.dstArrayElement = 0;
  5009. write.descriptorCount = uniform.get_id_count();
  5010. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  5011. write.pImageInfo = nullptr;
  5012. write.pBufferInfo = buffer_infos.push_back(buffer_info)->get().ptr();
  5013. write.pTexelBufferView = buffer_views.push_back(buffer_view)->get().ptr();
  5014. type_size = uniform.get_id_count();
  5015. } break;
  5016. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: {
  5017. if (uniform.get_id_count() != (uint32_t)set_uniform.length * 2) {
  5018. if (set_uniform.length > 1) {
  5019. 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()) + ").");
  5020. } else {
  5021. 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()) + ").");
  5022. }
  5023. }
  5024. Vector<VkDescriptorImageInfo> image_info;
  5025. Vector<VkDescriptorBufferInfo> buffer_info;
  5026. Vector<VkBufferView> buffer_view;
  5027. for (uint32_t j = 0; j < uniform.get_id_count(); j += 2) {
  5028. VkSampler *sampler = sampler_owner.get_or_null(uniform.get_id(j + 0));
  5029. ERR_FAIL_COND_V_MSG(!sampler, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler.");
  5030. TextureBuffer *buffer = texture_buffer_owner.get_or_null(uniform.get_id(j + 1));
  5031. VkDescriptorImageInfo img_info;
  5032. img_info.sampler = *sampler;
  5033. img_info.imageView = VK_NULL_HANDLE;
  5034. img_info.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  5035. image_info.push_back(img_info);
  5036. ERR_FAIL_COND_V_MSG(!buffer, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid texture buffer.");
  5037. buffer_info.push_back(buffer->buffer.buffer_info);
  5038. buffer_view.push_back(buffer->view);
  5039. }
  5040. write.dstArrayElement = 0;
  5041. write.descriptorCount = uniform.get_id_count() / 2;
  5042. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  5043. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  5044. write.pBufferInfo = buffer_infos.push_back(buffer_info)->get().ptr();
  5045. write.pTexelBufferView = buffer_views.push_back(buffer_view)->get().ptr();
  5046. type_size = uniform.get_id_count() / 2;
  5047. } break;
  5048. case UNIFORM_TYPE_IMAGE_BUFFER: {
  5049. //todo
  5050. } break;
  5051. case UNIFORM_TYPE_UNIFORM_BUFFER: {
  5052. ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(),
  5053. "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.get_id_count()) + " provided).");
  5054. Buffer *buffer = uniform_buffer_owner.get_or_null(uniform.get_id(0));
  5055. ERR_FAIL_COND_V_MSG(!buffer, RID(), "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") is invalid.");
  5056. ERR_FAIL_COND_V_MSG(buffer->size != (uint32_t)set_uniform.length, RID(),
  5057. "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " does not match size of shader uniform: (" + itos(set_uniform.length) + ").");
  5058. write.dstArrayElement = 0;
  5059. write.descriptorCount = 1;
  5060. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  5061. write.pImageInfo = nullptr;
  5062. write.pBufferInfo = &buffer->buffer_info;
  5063. write.pTexelBufferView = nullptr;
  5064. } break;
  5065. case UNIFORM_TYPE_STORAGE_BUFFER: {
  5066. ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(),
  5067. "Storage buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.get_id_count()) + " provided).");
  5068. Buffer *buffer = nullptr;
  5069. if (storage_buffer_owner.owns(uniform.get_id(0))) {
  5070. buffer = storage_buffer_owner.get_or_null(uniform.get_id(0));
  5071. } else if (vertex_buffer_owner.owns(uniform.get_id(0))) {
  5072. buffer = vertex_buffer_owner.get_or_null(uniform.get_id(0));
  5073. ERR_FAIL_COND_V_MSG(!(buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT), RID(), "Vertex buffer supplied (binding: " + itos(uniform.binding) + ") was not created with storage flag.");
  5074. }
  5075. ERR_FAIL_COND_V_MSG(!buffer, RID(), "Storage buffer supplied (binding: " + itos(uniform.binding) + ") is invalid.");
  5076. //if 0, then it's sized on link time
  5077. ERR_FAIL_COND_V_MSG(set_uniform.length > 0 && buffer->size != (uint32_t)set_uniform.length, RID(),
  5078. "Storage buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " does not match size of shader uniform: (" + itos(set_uniform.length) + ").");
  5079. write.dstArrayElement = 0;
  5080. write.descriptorCount = 1;
  5081. write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  5082. write.pImageInfo = nullptr;
  5083. write.pBufferInfo = &buffer->buffer_info;
  5084. write.pTexelBufferView = nullptr;
  5085. } break;
  5086. case UNIFORM_TYPE_INPUT_ATTACHMENT: {
  5087. ERR_FAIL_COND_V_MSG(shader->is_compute, RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") supplied for compute shader (this is not allowed).");
  5088. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  5089. if (set_uniform.length > 1) {
  5090. 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()) + ").");
  5091. } else {
  5092. ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5093. }
  5094. }
  5095. Vector<VkDescriptorImageInfo> image_info;
  5096. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  5097. Texture *texture = texture_owner.get_or_null(uniform.get_id(j));
  5098. ERR_FAIL_COND_V_MSG(!texture, RID(),
  5099. "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  5100. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  5101. "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  5102. VkDescriptorImageInfo img_info;
  5103. img_info.sampler = VK_NULL_HANDLE;
  5104. img_info.imageView = texture->view;
  5105. if (texture->owner.is_valid()) {
  5106. texture = texture_owner.get_or_null(texture->owner);
  5107. ERR_FAIL_COND_V(!texture, RID()); //bug, should never happen
  5108. }
  5109. img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  5110. image_info.push_back(img_info);
  5111. }
  5112. write.dstArrayElement = 0;
  5113. write.descriptorCount = uniform.get_id_count();
  5114. write.descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
  5115. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  5116. write.pBufferInfo = nullptr;
  5117. write.pTexelBufferView = nullptr;
  5118. type_size = uniform.get_id_count();
  5119. } break;
  5120. default: {
  5121. }
  5122. }
  5123. writes.push_back(write);
  5124. ERR_FAIL_COND_V_MSG(pool_key.uniform_type[set_uniform.type] == MAX_DESCRIPTOR_POOL_ELEMENT, RID(),
  5125. "Uniform set reached the limit of bindings for the same type (" + itos(MAX_DESCRIPTOR_POOL_ELEMENT) + ").");
  5126. pool_key.uniform_type[set_uniform.type] += type_size;
  5127. }
  5128. //need a descriptor pool
  5129. DescriptorPool *pool = _descriptor_pool_allocate(pool_key);
  5130. ERR_FAIL_COND_V(!pool, RID());
  5131. VkDescriptorSetAllocateInfo descriptor_set_allocate_info;
  5132. descriptor_set_allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
  5133. descriptor_set_allocate_info.pNext = nullptr;
  5134. descriptor_set_allocate_info.descriptorPool = pool->pool;
  5135. descriptor_set_allocate_info.descriptorSetCount = 1;
  5136. descriptor_set_allocate_info.pSetLayouts = &shader->sets[p_shader_set].descriptor_set_layout;
  5137. VkDescriptorSet descriptor_set;
  5138. VkResult res = vkAllocateDescriptorSets(device, &descriptor_set_allocate_info, &descriptor_set);
  5139. if (res) {
  5140. _descriptor_pool_free(pool_key, pool); // meh
  5141. ERR_FAIL_V_MSG(RID(), "Cannot allocate descriptor sets, error " + itos(res) + ".");
  5142. }
  5143. UniformSet uniform_set;
  5144. uniform_set.pool = pool;
  5145. uniform_set.pool_key = pool_key;
  5146. uniform_set.descriptor_set = descriptor_set;
  5147. uniform_set.format = shader->set_formats[p_shader_set];
  5148. uniform_set.attachable_textures = attachable_textures;
  5149. uniform_set.mutable_sampled_textures = mutable_sampled_textures;
  5150. uniform_set.mutable_storage_textures = mutable_storage_textures;
  5151. uniform_set.shader_set = p_shader_set;
  5152. uniform_set.shader_id = p_shader;
  5153. RID id = uniform_set_owner.make_rid(uniform_set);
  5154. //add dependencies
  5155. _add_dependency(id, p_shader);
  5156. for (uint32_t i = 0; i < uniform_count; i++) {
  5157. const Uniform &uniform = uniforms[i];
  5158. int id_count = uniform.get_id_count();
  5159. for (int j = 0; j < id_count; j++) {
  5160. _add_dependency(id, uniform.get_id(j));
  5161. }
  5162. }
  5163. //write the contents
  5164. if (writes.size()) {
  5165. for (int i = 0; i < writes.size(); i++) {
  5166. writes.write[i].dstSet = descriptor_set;
  5167. }
  5168. vkUpdateDescriptorSets(device, writes.size(), writes.ptr(), 0, nullptr);
  5169. }
  5170. return id;
  5171. }
  5172. bool RenderingDeviceVulkan::uniform_set_is_valid(RID p_uniform_set) {
  5173. return uniform_set_owner.owns(p_uniform_set);
  5174. }
  5175. void RenderingDeviceVulkan::uniform_set_set_invalidation_callback(RID p_uniform_set, UniformSetInvalidatedCallback p_callback, void *p_userdata) {
  5176. UniformSet *us = uniform_set_owner.get_or_null(p_uniform_set);
  5177. ERR_FAIL_COND(!us);
  5178. us->invalidated_callback = p_callback;
  5179. us->invalidated_callback_userdata = p_userdata;
  5180. }
  5181. Error RenderingDeviceVulkan::buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, uint32_t p_post_barrier) {
  5182. _THREAD_SAFE_METHOD_
  5183. ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER,
  5184. "Updating buffers is forbidden during creation of a draw list");
  5185. ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER,
  5186. "Updating buffers is forbidden during creation of a compute list");
  5187. VkPipelineStageFlags dst_stage_mask = 0;
  5188. VkAccessFlags dst_access = 0;
  5189. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  5190. // Protect subsequent updates...
  5191. dst_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT;
  5192. dst_access = VK_ACCESS_TRANSFER_WRITE_BIT;
  5193. }
  5194. Buffer *buffer = _get_buffer_from_owner(p_buffer, dst_stage_mask, dst_access, p_post_barrier);
  5195. if (!buffer) {
  5196. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type.");
  5197. }
  5198. ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER,
  5199. "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end.");
  5200. // no barrier should be needed here
  5201. // _buffer_memory_barrier(buffer->buffer, p_offset, p_size, dst_stage_mask, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_access, VK_ACCESS_TRANSFER_WRITE_BIT, true);
  5202. Error err = _buffer_update(buffer, p_offset, (uint8_t *)p_data, p_size, p_post_barrier);
  5203. if (err) {
  5204. return err;
  5205. }
  5206. #ifdef FORCE_FULL_BARRIER
  5207. _full_barrier(true);
  5208. #else
  5209. if (dst_stage_mask == 0) {
  5210. dst_stage_mask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  5211. }
  5212. if (p_post_barrier != RD::BARRIER_MASK_NO_BARRIER) {
  5213. _buffer_memory_barrier(buffer->buffer, p_offset, p_size, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_stage_mask, VK_ACCESS_TRANSFER_WRITE_BIT, dst_access, true);
  5214. }
  5215. #endif
  5216. return err;
  5217. }
  5218. Error RenderingDeviceVulkan::buffer_clear(RID p_buffer, uint32_t p_offset, uint32_t p_size, uint32_t p_post_barrier) {
  5219. _THREAD_SAFE_METHOD_
  5220. ERR_FAIL_COND_V_MSG((p_size % 4) != 0, ERR_INVALID_PARAMETER,
  5221. "Size must be a multiple of four");
  5222. ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER,
  5223. "Updating buffers in is forbidden during creation of a draw list");
  5224. ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER,
  5225. "Updating buffers is forbidden during creation of a compute list");
  5226. VkPipelineStageFlags dst_stage_mask = 0;
  5227. VkAccessFlags dst_access = 0;
  5228. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  5229. // Protect subsequent updates...
  5230. dst_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT;
  5231. dst_access = VK_ACCESS_TRANSFER_WRITE_BIT;
  5232. }
  5233. Buffer *buffer = _get_buffer_from_owner(p_buffer, dst_stage_mask, dst_access, p_post_barrier);
  5234. if (!buffer) {
  5235. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type.");
  5236. }
  5237. ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER,
  5238. "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end.");
  5239. // should not be needed
  5240. // _buffer_memory_barrier(buffer->buffer, p_offset, p_size, dst_stage_mask, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_access, VK_ACCESS_TRANSFER_WRITE_BIT, p_post_barrier);
  5241. vkCmdFillBuffer(frames[frame].draw_command_buffer, buffer->buffer, p_offset, p_size, 0);
  5242. #ifdef FORCE_FULL_BARRIER
  5243. _full_barrier(true);
  5244. #else
  5245. if (dst_stage_mask == 0) {
  5246. dst_stage_mask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  5247. }
  5248. _buffer_memory_barrier(buffer->buffer, p_offset, p_size, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_stage_mask, VK_ACCESS_TRANSFER_WRITE_BIT, dst_access, dst_stage_mask);
  5249. #endif
  5250. return OK;
  5251. }
  5252. Vector<uint8_t> RenderingDeviceVulkan::buffer_get_data(RID p_buffer) {
  5253. _THREAD_SAFE_METHOD_
  5254. // It could be this buffer was just created
  5255. VkPipelineShaderStageCreateFlags src_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT;
  5256. VkAccessFlags src_access_mask = VK_ACCESS_TRANSFER_WRITE_BIT;
  5257. // Get the vulkan buffer and the potential stage/access possible
  5258. Buffer *buffer = _get_buffer_from_owner(p_buffer, src_stage_mask, src_access_mask, BARRIER_MASK_ALL);
  5259. if (!buffer) {
  5260. 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.");
  5261. }
  5262. // Make sure no one is using the buffer -- the "false" gets us to the same command buffer as below.
  5263. _buffer_memory_barrier(buffer->buffer, 0, buffer->size, src_stage_mask, src_access_mask, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT, false);
  5264. VkCommandBuffer command_buffer = frames[frame].setup_command_buffer;
  5265. Buffer tmp_buffer;
  5266. _buffer_allocate(&tmp_buffer, buffer->size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_HOST, VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT);
  5267. VkBufferCopy region;
  5268. region.srcOffset = 0;
  5269. region.dstOffset = 0;
  5270. region.size = buffer->size;
  5271. vkCmdCopyBuffer(command_buffer, buffer->buffer, tmp_buffer.buffer, 1, &region); //dst buffer is in CPU, but I wonder if src buffer needs a barrier for this..
  5272. //flush everything so memory can be safely mapped
  5273. _flush(true);
  5274. void *buffer_mem;
  5275. VkResult vkerr = vmaMapMemory(allocator, tmp_buffer.allocation, &buffer_mem);
  5276. ERR_FAIL_COND_V_MSG(vkerr, Vector<uint8_t>(), "vmaMapMemory failed with error " + itos(vkerr) + ".");
  5277. Vector<uint8_t> buffer_data;
  5278. {
  5279. buffer_data.resize(buffer->size);
  5280. uint8_t *w = buffer_data.ptrw();
  5281. memcpy(w, buffer_mem, buffer->size);
  5282. }
  5283. vmaUnmapMemory(allocator, tmp_buffer.allocation);
  5284. _buffer_free(&tmp_buffer);
  5285. return buffer_data;
  5286. }
  5287. /*************************/
  5288. /**** RENDER PIPELINE ****/
  5289. /*************************/
  5290. RID RenderingDeviceVulkan::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, int p_dynamic_state_flags, uint32_t p_for_render_pass, const Vector<PipelineSpecializationConstant> &p_specialization_constants) {
  5291. _THREAD_SAFE_METHOD_
  5292. //needs a shader
  5293. Shader *shader = shader_owner.get_or_null(p_shader);
  5294. ERR_FAIL_COND_V(!shader, RID());
  5295. ERR_FAIL_COND_V_MSG(shader->is_compute, RID(),
  5296. "Compute shaders can't be used in render pipelines");
  5297. if (p_framebuffer_format == INVALID_ID) {
  5298. //if nothing provided, use an empty one (no attachments)
  5299. p_framebuffer_format = framebuffer_format_create(Vector<AttachmentFormat>());
  5300. }
  5301. ERR_FAIL_COND_V(!framebuffer_formats.has(p_framebuffer_format), RID());
  5302. const FramebufferFormat &fb_format = framebuffer_formats[p_framebuffer_format];
  5303. { //validate shader vs framebuffer
  5304. 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");
  5305. const FramebufferPass &pass = fb_format.E->key().passes[p_for_render_pass];
  5306. uint32_t output_mask = 0;
  5307. for (int i = 0; i < pass.color_attachments.size(); i++) {
  5308. if (pass.color_attachments[i] != FramebufferPass::ATTACHMENT_UNUSED) {
  5309. output_mask |= 1 << i;
  5310. }
  5311. }
  5312. ERR_FAIL_COND_V_MSG(shader->fragment_output_mask != output_mask, RID(),
  5313. "Mismatch fragment shader output mask (" + itos(shader->fragment_output_mask) + ") and framebuffer color output mask (" + itos(output_mask) + ") when binding both in render pipeline.");
  5314. }
  5315. //vertex
  5316. VkPipelineVertexInputStateCreateInfo pipeline_vertex_input_state_create_info;
  5317. if (p_vertex_format != INVALID_ID) {
  5318. //uses vertices, else it does not
  5319. ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID());
  5320. const VertexDescriptionCache &vd = vertex_formats[p_vertex_format];
  5321. pipeline_vertex_input_state_create_info = vd.create_info;
  5322. //validate with inputs
  5323. for (uint32_t i = 0; i < 32; i++) {
  5324. if (!(shader->vertex_input_mask & (1UL << i))) {
  5325. continue;
  5326. }
  5327. bool found = false;
  5328. for (int j = 0; j < vd.vertex_formats.size(); j++) {
  5329. if (vd.vertex_formats[j].location == i) {
  5330. found = true;
  5331. }
  5332. }
  5333. ERR_FAIL_COND_V_MSG(!found, RID(),
  5334. "Shader vertex input location (" + itos(i) + ") not provided in vertex input description for pipeline creation.");
  5335. }
  5336. } else {
  5337. //does not use vertices
  5338. pipeline_vertex_input_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  5339. pipeline_vertex_input_state_create_info.pNext = nullptr;
  5340. pipeline_vertex_input_state_create_info.flags = 0;
  5341. pipeline_vertex_input_state_create_info.vertexBindingDescriptionCount = 0;
  5342. pipeline_vertex_input_state_create_info.pVertexBindingDescriptions = nullptr;
  5343. pipeline_vertex_input_state_create_info.vertexAttributeDescriptionCount = 0;
  5344. pipeline_vertex_input_state_create_info.pVertexAttributeDescriptions = nullptr;
  5345. ERR_FAIL_COND_V_MSG(shader->vertex_input_mask != 0, RID(),
  5346. "Shader contains vertex inputs, but no vertex input description was provided for pipeline creation.");
  5347. }
  5348. //input assembly
  5349. ERR_FAIL_INDEX_V(p_render_primitive, RENDER_PRIMITIVE_MAX, RID());
  5350. VkPipelineInputAssemblyStateCreateInfo input_assembly_create_info;
  5351. input_assembly_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  5352. input_assembly_create_info.pNext = nullptr;
  5353. input_assembly_create_info.flags = 0;
  5354. static const VkPrimitiveTopology topology_list[RENDER_PRIMITIVE_MAX] = {
  5355. VK_PRIMITIVE_TOPOLOGY_POINT_LIST,
  5356. VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
  5357. VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY,
  5358. VK_PRIMITIVE_TOPOLOGY_LINE_STRIP,
  5359. VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY,
  5360. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
  5361. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY,
  5362. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
  5363. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY,
  5364. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
  5365. VK_PRIMITIVE_TOPOLOGY_PATCH_LIST
  5366. };
  5367. input_assembly_create_info.topology = topology_list[p_render_primitive];
  5368. input_assembly_create_info.primitiveRestartEnable = (p_render_primitive == RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX);
  5369. //tessellation
  5370. VkPipelineTessellationStateCreateInfo tessellation_create_info;
  5371. tessellation_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO;
  5372. tessellation_create_info.pNext = nullptr;
  5373. tessellation_create_info.flags = 0;
  5374. ERR_FAIL_COND_V(limits.maxTessellationPatchSize > 0 && (p_rasterization_state.patch_control_points < 1 || p_rasterization_state.patch_control_points > limits.maxTessellationPatchSize), RID());
  5375. tessellation_create_info.patchControlPoints = p_rasterization_state.patch_control_points;
  5376. VkPipelineViewportStateCreateInfo viewport_state_create_info;
  5377. viewport_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  5378. viewport_state_create_info.pNext = nullptr;
  5379. viewport_state_create_info.flags = 0;
  5380. viewport_state_create_info.viewportCount = 1; //if VR extensions are supported at some point, this will have to be customizable in the framebuffer format
  5381. viewport_state_create_info.pViewports = nullptr;
  5382. viewport_state_create_info.scissorCount = 1;
  5383. viewport_state_create_info.pScissors = nullptr;
  5384. //rasterization
  5385. VkPipelineRasterizationStateCreateInfo rasterization_state_create_info;
  5386. rasterization_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  5387. rasterization_state_create_info.pNext = nullptr;
  5388. rasterization_state_create_info.flags = 0;
  5389. rasterization_state_create_info.depthClampEnable = p_rasterization_state.enable_depth_clamp;
  5390. rasterization_state_create_info.rasterizerDiscardEnable = p_rasterization_state.discard_primitives;
  5391. rasterization_state_create_info.polygonMode = (p_rasterization_state.wireframe ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL);
  5392. static const VkCullModeFlags cull_mode[3] = {
  5393. VK_CULL_MODE_NONE,
  5394. VK_CULL_MODE_FRONT_BIT,
  5395. VK_CULL_MODE_BACK_BIT
  5396. };
  5397. ERR_FAIL_INDEX_V(p_rasterization_state.cull_mode, 3, RID());
  5398. rasterization_state_create_info.cullMode = cull_mode[p_rasterization_state.cull_mode];
  5399. rasterization_state_create_info.frontFace = (p_rasterization_state.front_face == POLYGON_FRONT_FACE_CLOCKWISE ? VK_FRONT_FACE_CLOCKWISE : VK_FRONT_FACE_COUNTER_CLOCKWISE);
  5400. rasterization_state_create_info.depthBiasEnable = p_rasterization_state.depth_bias_enable;
  5401. rasterization_state_create_info.depthBiasConstantFactor = p_rasterization_state.depth_bias_constant_factor;
  5402. rasterization_state_create_info.depthBiasClamp = p_rasterization_state.depth_bias_clamp;
  5403. rasterization_state_create_info.depthBiasSlopeFactor = p_rasterization_state.depth_bias_slope_factor;
  5404. rasterization_state_create_info.lineWidth = p_rasterization_state.line_width;
  5405. //multisample
  5406. VkPipelineMultisampleStateCreateInfo multisample_state_create_info;
  5407. multisample_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  5408. multisample_state_create_info.pNext = nullptr;
  5409. multisample_state_create_info.flags = 0;
  5410. multisample_state_create_info.rasterizationSamples = rasterization_sample_count[p_multisample_state.sample_count];
  5411. multisample_state_create_info.sampleShadingEnable = p_multisample_state.enable_sample_shading;
  5412. multisample_state_create_info.minSampleShading = p_multisample_state.min_sample_shading;
  5413. Vector<VkSampleMask> sample_mask;
  5414. if (p_multisample_state.sample_mask.size()) {
  5415. //use sample mask
  5416. const int rasterization_sample_mask_expected_size[TEXTURE_SAMPLES_MAX] = {
  5417. 1, 2, 4, 8, 16, 32, 64
  5418. };
  5419. ERR_FAIL_COND_V(rasterization_sample_mask_expected_size[p_multisample_state.sample_count] != p_multisample_state.sample_mask.size(), RID());
  5420. sample_mask.resize(p_multisample_state.sample_mask.size());
  5421. for (int i = 0; i < p_multisample_state.sample_mask.size(); i++) {
  5422. VkSampleMask mask = p_multisample_state.sample_mask[i];
  5423. sample_mask.push_back(mask);
  5424. }
  5425. multisample_state_create_info.pSampleMask = sample_mask.ptr();
  5426. } else {
  5427. multisample_state_create_info.pSampleMask = nullptr;
  5428. }
  5429. multisample_state_create_info.alphaToCoverageEnable = p_multisample_state.enable_alpha_to_coverage;
  5430. multisample_state_create_info.alphaToOneEnable = p_multisample_state.enable_alpha_to_one;
  5431. //depth stencil
  5432. VkPipelineDepthStencilStateCreateInfo depth_stencil_state_create_info;
  5433. depth_stencil_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
  5434. depth_stencil_state_create_info.pNext = nullptr;
  5435. depth_stencil_state_create_info.flags = 0;
  5436. depth_stencil_state_create_info.depthTestEnable = p_depth_stencil_state.enable_depth_test;
  5437. depth_stencil_state_create_info.depthWriteEnable = p_depth_stencil_state.enable_depth_write;
  5438. ERR_FAIL_INDEX_V(p_depth_stencil_state.depth_compare_operator, COMPARE_OP_MAX, RID());
  5439. depth_stencil_state_create_info.depthCompareOp = compare_operators[p_depth_stencil_state.depth_compare_operator];
  5440. depth_stencil_state_create_info.depthBoundsTestEnable = p_depth_stencil_state.enable_depth_range;
  5441. depth_stencil_state_create_info.stencilTestEnable = p_depth_stencil_state.enable_stencil;
  5442. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.fail, STENCIL_OP_MAX, RID());
  5443. depth_stencil_state_create_info.front.failOp = stencil_operations[p_depth_stencil_state.front_op.fail];
  5444. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.pass, STENCIL_OP_MAX, RID());
  5445. depth_stencil_state_create_info.front.passOp = stencil_operations[p_depth_stencil_state.front_op.pass];
  5446. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.depth_fail, STENCIL_OP_MAX, RID());
  5447. depth_stencil_state_create_info.front.depthFailOp = stencil_operations[p_depth_stencil_state.front_op.depth_fail];
  5448. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.compare, COMPARE_OP_MAX, RID());
  5449. depth_stencil_state_create_info.front.compareOp = compare_operators[p_depth_stencil_state.front_op.compare];
  5450. depth_stencil_state_create_info.front.compareMask = p_depth_stencil_state.front_op.compare_mask;
  5451. depth_stencil_state_create_info.front.writeMask = p_depth_stencil_state.front_op.write_mask;
  5452. depth_stencil_state_create_info.front.reference = p_depth_stencil_state.front_op.reference;
  5453. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.fail, STENCIL_OP_MAX, RID());
  5454. depth_stencil_state_create_info.back.failOp = stencil_operations[p_depth_stencil_state.back_op.fail];
  5455. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.pass, STENCIL_OP_MAX, RID());
  5456. depth_stencil_state_create_info.back.passOp = stencil_operations[p_depth_stencil_state.back_op.pass];
  5457. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.depth_fail, STENCIL_OP_MAX, RID());
  5458. depth_stencil_state_create_info.back.depthFailOp = stencil_operations[p_depth_stencil_state.back_op.depth_fail];
  5459. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.compare, COMPARE_OP_MAX, RID());
  5460. depth_stencil_state_create_info.back.compareOp = compare_operators[p_depth_stencil_state.back_op.compare];
  5461. depth_stencil_state_create_info.back.compareMask = p_depth_stencil_state.back_op.compare_mask;
  5462. depth_stencil_state_create_info.back.writeMask = p_depth_stencil_state.back_op.write_mask;
  5463. depth_stencil_state_create_info.back.reference = p_depth_stencil_state.back_op.reference;
  5464. depth_stencil_state_create_info.minDepthBounds = p_depth_stencil_state.depth_range_min;
  5465. depth_stencil_state_create_info.maxDepthBounds = p_depth_stencil_state.depth_range_max;
  5466. //blend state
  5467. VkPipelineColorBlendStateCreateInfo color_blend_state_create_info;
  5468. color_blend_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  5469. color_blend_state_create_info.pNext = nullptr;
  5470. color_blend_state_create_info.flags = 0;
  5471. color_blend_state_create_info.logicOpEnable = p_blend_state.enable_logic_op;
  5472. ERR_FAIL_INDEX_V(p_blend_state.logic_op, LOGIC_OP_MAX, RID());
  5473. color_blend_state_create_info.logicOp = logic_operations[p_blend_state.logic_op];
  5474. Vector<VkPipelineColorBlendAttachmentState> attachment_states;
  5475. {
  5476. const FramebufferPass &pass = fb_format.E->key().passes[p_for_render_pass];
  5477. attachment_states.resize(pass.color_attachments.size());
  5478. ERR_FAIL_COND_V(p_blend_state.attachments.size() < pass.color_attachments.size(), RID());
  5479. for (int i = 0; i < pass.color_attachments.size(); i++) {
  5480. VkPipelineColorBlendAttachmentState state;
  5481. if (pass.color_attachments[i] == FramebufferPass::ATTACHMENT_UNUSED) {
  5482. state.blendEnable = false;
  5483. state.srcColorBlendFactor = VK_BLEND_FACTOR_ZERO;
  5484. state.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO;
  5485. state.colorBlendOp = VK_BLEND_OP_ADD;
  5486. state.srcAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
  5487. state.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
  5488. state.alphaBlendOp = VK_BLEND_OP_ADD;
  5489. state.colorWriteMask = 0;
  5490. } else {
  5491. state.blendEnable = p_blend_state.attachments[i].enable_blend;
  5492. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_color_blend_factor, BLEND_FACTOR_MAX, RID());
  5493. state.srcColorBlendFactor = blend_factors[p_blend_state.attachments[i].src_color_blend_factor];
  5494. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_color_blend_factor, BLEND_FACTOR_MAX, RID());
  5495. state.dstColorBlendFactor = blend_factors[p_blend_state.attachments[i].dst_color_blend_factor];
  5496. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].color_blend_op, BLEND_OP_MAX, RID());
  5497. state.colorBlendOp = blend_operations[p_blend_state.attachments[i].color_blend_op];
  5498. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_alpha_blend_factor, BLEND_FACTOR_MAX, RID());
  5499. state.srcAlphaBlendFactor = blend_factors[p_blend_state.attachments[i].src_alpha_blend_factor];
  5500. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_alpha_blend_factor, BLEND_FACTOR_MAX, RID());
  5501. state.dstAlphaBlendFactor = blend_factors[p_blend_state.attachments[i].dst_alpha_blend_factor];
  5502. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].alpha_blend_op, BLEND_OP_MAX, RID());
  5503. state.alphaBlendOp = blend_operations[p_blend_state.attachments[i].alpha_blend_op];
  5504. state.colorWriteMask = 0;
  5505. if (p_blend_state.attachments[i].write_r) {
  5506. state.colorWriteMask |= VK_COLOR_COMPONENT_R_BIT;
  5507. }
  5508. if (p_blend_state.attachments[i].write_g) {
  5509. state.colorWriteMask |= VK_COLOR_COMPONENT_G_BIT;
  5510. }
  5511. if (p_blend_state.attachments[i].write_b) {
  5512. state.colorWriteMask |= VK_COLOR_COMPONENT_B_BIT;
  5513. }
  5514. if (p_blend_state.attachments[i].write_a) {
  5515. state.colorWriteMask |= VK_COLOR_COMPONENT_A_BIT;
  5516. }
  5517. }
  5518. attachment_states.write[i] = state;
  5519. }
  5520. }
  5521. color_blend_state_create_info.attachmentCount = attachment_states.size();
  5522. color_blend_state_create_info.pAttachments = attachment_states.ptr();
  5523. color_blend_state_create_info.blendConstants[0] = p_blend_state.blend_constant.r;
  5524. color_blend_state_create_info.blendConstants[1] = p_blend_state.blend_constant.g;
  5525. color_blend_state_create_info.blendConstants[2] = p_blend_state.blend_constant.b;
  5526. color_blend_state_create_info.blendConstants[3] = p_blend_state.blend_constant.a;
  5527. //dynamic state
  5528. VkPipelineDynamicStateCreateInfo dynamic_state_create_info;
  5529. dynamic_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
  5530. dynamic_state_create_info.pNext = nullptr;
  5531. dynamic_state_create_info.flags = 0;
  5532. Vector<VkDynamicState> dynamic_states; //vulkan is weird..
  5533. dynamic_states.push_back(VK_DYNAMIC_STATE_VIEWPORT); //viewport and scissor are always dynamic
  5534. dynamic_states.push_back(VK_DYNAMIC_STATE_SCISSOR);
  5535. if (p_dynamic_state_flags & DYNAMIC_STATE_LINE_WIDTH) {
  5536. dynamic_states.push_back(VK_DYNAMIC_STATE_LINE_WIDTH);
  5537. }
  5538. if (p_dynamic_state_flags & DYNAMIC_STATE_DEPTH_BIAS) {
  5539. dynamic_states.push_back(VK_DYNAMIC_STATE_DEPTH_BIAS);
  5540. }
  5541. if (p_dynamic_state_flags & DYNAMIC_STATE_BLEND_CONSTANTS) {
  5542. dynamic_states.push_back(VK_DYNAMIC_STATE_BLEND_CONSTANTS);
  5543. }
  5544. if (p_dynamic_state_flags & DYNAMIC_STATE_DEPTH_BOUNDS) {
  5545. dynamic_states.push_back(VK_DYNAMIC_STATE_DEPTH_BOUNDS);
  5546. }
  5547. if (p_dynamic_state_flags & DYNAMIC_STATE_STENCIL_COMPARE_MASK) {
  5548. dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK);
  5549. }
  5550. if (p_dynamic_state_flags & DYNAMIC_STATE_STENCIL_WRITE_MASK) {
  5551. dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_WRITE_MASK);
  5552. }
  5553. if (p_dynamic_state_flags & DYNAMIC_STATE_STENCIL_REFERENCE) {
  5554. dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_REFERENCE);
  5555. }
  5556. dynamic_state_create_info.dynamicStateCount = dynamic_states.size();
  5557. dynamic_state_create_info.pDynamicStates = dynamic_states.ptr();
  5558. //finally, pipeline create info
  5559. VkGraphicsPipelineCreateInfo graphics_pipeline_create_info;
  5560. graphics_pipeline_create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  5561. graphics_pipeline_create_info.pNext = nullptr;
  5562. graphics_pipeline_create_info.flags = 0;
  5563. Vector<VkPipelineShaderStageCreateInfo> pipeline_stages = shader->pipeline_stages;
  5564. Vector<VkSpecializationInfo> specialization_info;
  5565. Vector<Vector<VkSpecializationMapEntry>> specialization_map_entries;
  5566. Vector<uint32_t> specialization_constant_data;
  5567. if (shader->specialization_constants.size()) {
  5568. specialization_constant_data.resize(shader->specialization_constants.size());
  5569. uint32_t *data_ptr = specialization_constant_data.ptrw();
  5570. specialization_info.resize(pipeline_stages.size());
  5571. specialization_map_entries.resize(pipeline_stages.size());
  5572. for (int i = 0; i < shader->specialization_constants.size(); i++) {
  5573. //see if overridden
  5574. const Shader::SpecializationConstant &sc = shader->specialization_constants[i];
  5575. data_ptr[i] = sc.constant.int_value; //just copy the 32 bits
  5576. for (int j = 0; j < p_specialization_constants.size(); j++) {
  5577. const PipelineSpecializationConstant &psc = p_specialization_constants[j];
  5578. if (psc.constant_id == sc.constant.constant_id) {
  5579. ERR_FAIL_COND_V_MSG(psc.type != sc.constant.type, RID(), "Specialization constant provided for id (" + itos(sc.constant.constant_id) + ") is of the wrong type.");
  5580. data_ptr[i] = psc.int_value;
  5581. break;
  5582. }
  5583. }
  5584. VkSpecializationMapEntry entry;
  5585. entry.constantID = sc.constant.constant_id;
  5586. entry.offset = i * sizeof(uint32_t);
  5587. entry.size = sizeof(uint32_t);
  5588. for (int j = 0; j < SHADER_STAGE_MAX; j++) {
  5589. if (sc.stage_flags & (1 << j)) {
  5590. VkShaderStageFlagBits stage = shader_stage_masks[j];
  5591. for (int k = 0; k < pipeline_stages.size(); k++) {
  5592. if (pipeline_stages[k].stage == stage) {
  5593. specialization_map_entries.write[k].push_back(entry);
  5594. }
  5595. }
  5596. }
  5597. }
  5598. }
  5599. for (int i = 0; i < pipeline_stages.size(); i++) {
  5600. if (specialization_map_entries[i].size()) {
  5601. specialization_info.write[i].dataSize = specialization_constant_data.size() * sizeof(uint32_t);
  5602. specialization_info.write[i].pData = data_ptr;
  5603. specialization_info.write[i].mapEntryCount = specialization_map_entries[i].size();
  5604. specialization_info.write[i].pMapEntries = specialization_map_entries[i].ptr();
  5605. pipeline_stages.write[i].pSpecializationInfo = specialization_info.ptr() + i;
  5606. }
  5607. }
  5608. }
  5609. graphics_pipeline_create_info.stageCount = pipeline_stages.size();
  5610. graphics_pipeline_create_info.pStages = pipeline_stages.ptr();
  5611. graphics_pipeline_create_info.pVertexInputState = &pipeline_vertex_input_state_create_info;
  5612. graphics_pipeline_create_info.pInputAssemblyState = &input_assembly_create_info;
  5613. graphics_pipeline_create_info.pTessellationState = &tessellation_create_info;
  5614. graphics_pipeline_create_info.pViewportState = &viewport_state_create_info;
  5615. graphics_pipeline_create_info.pRasterizationState = &rasterization_state_create_info;
  5616. graphics_pipeline_create_info.pMultisampleState = &multisample_state_create_info;
  5617. graphics_pipeline_create_info.pDepthStencilState = &depth_stencil_state_create_info;
  5618. graphics_pipeline_create_info.pColorBlendState = &color_blend_state_create_info;
  5619. graphics_pipeline_create_info.pDynamicState = &dynamic_state_create_info;
  5620. graphics_pipeline_create_info.layout = shader->pipeline_layout;
  5621. graphics_pipeline_create_info.renderPass = fb_format.render_pass;
  5622. graphics_pipeline_create_info.subpass = p_for_render_pass;
  5623. graphics_pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE;
  5624. graphics_pipeline_create_info.basePipelineIndex = 0;
  5625. RenderPipeline pipeline;
  5626. VkResult err = vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &graphics_pipeline_create_info, nullptr, &pipeline.pipeline);
  5627. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateGraphicsPipelines failed with error " + itos(err) + " for shader '" + shader->name + "'.");
  5628. pipeline.set_formats = shader->set_formats;
  5629. pipeline.push_constant_stages = shader->push_constant.push_constants_vk_stage;
  5630. pipeline.pipeline_layout = shader->pipeline_layout;
  5631. pipeline.shader = p_shader;
  5632. pipeline.push_constant_size = shader->push_constant.push_constant_size;
  5633. #ifdef DEBUG_ENABLED
  5634. pipeline.validation.dynamic_state = p_dynamic_state_flags;
  5635. pipeline.validation.framebuffer_format = p_framebuffer_format;
  5636. pipeline.validation.render_pass = p_for_render_pass;
  5637. pipeline.validation.vertex_format = p_vertex_format;
  5638. pipeline.validation.uses_restart_indices = input_assembly_create_info.primitiveRestartEnable;
  5639. static const uint32_t primitive_divisor[RENDER_PRIMITIVE_MAX] = {
  5640. 1, 2, 1, 1, 1, 3, 1, 1, 1, 1, 1
  5641. };
  5642. pipeline.validation.primitive_divisor = primitive_divisor[p_render_primitive];
  5643. static const uint32_t primitive_minimum[RENDER_PRIMITIVE_MAX] = {
  5644. 1,
  5645. 2,
  5646. 2,
  5647. 2,
  5648. 2,
  5649. 3,
  5650. 3,
  5651. 3,
  5652. 3,
  5653. 3,
  5654. 1,
  5655. };
  5656. pipeline.validation.primitive_minimum = primitive_minimum[p_render_primitive];
  5657. #endif
  5658. //create ID to associate with this pipeline
  5659. RID id = render_pipeline_owner.make_rid(pipeline);
  5660. //now add all the dependencies
  5661. _add_dependency(id, p_shader);
  5662. return id;
  5663. }
  5664. bool RenderingDeviceVulkan::render_pipeline_is_valid(RID p_pipeline) {
  5665. _THREAD_SAFE_METHOD_
  5666. return render_pipeline_owner.owns(p_pipeline);
  5667. }
  5668. /**************************/
  5669. /**** COMPUTE PIPELINE ****/
  5670. /**************************/
  5671. RID RenderingDeviceVulkan::compute_pipeline_create(RID p_shader, const Vector<PipelineSpecializationConstant> &p_specialization_constants) {
  5672. _THREAD_SAFE_METHOD_
  5673. //needs a shader
  5674. Shader *shader = shader_owner.get_or_null(p_shader);
  5675. ERR_FAIL_COND_V(!shader, RID());
  5676. ERR_FAIL_COND_V_MSG(!shader->is_compute, RID(),
  5677. "Non-compute shaders can't be used in compute pipelines");
  5678. //finally, pipeline create info
  5679. VkComputePipelineCreateInfo compute_pipeline_create_info;
  5680. compute_pipeline_create_info.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
  5681. compute_pipeline_create_info.pNext = nullptr;
  5682. compute_pipeline_create_info.flags = 0;
  5683. compute_pipeline_create_info.stage = shader->pipeline_stages[0];
  5684. compute_pipeline_create_info.layout = shader->pipeline_layout;
  5685. compute_pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE;
  5686. compute_pipeline_create_info.basePipelineIndex = 0;
  5687. VkSpecializationInfo specialization_info;
  5688. Vector<VkSpecializationMapEntry> specialization_map_entries;
  5689. Vector<uint32_t> specialization_constant_data;
  5690. if (shader->specialization_constants.size()) {
  5691. specialization_constant_data.resize(shader->specialization_constants.size());
  5692. uint32_t *data_ptr = specialization_constant_data.ptrw();
  5693. for (int i = 0; i < shader->specialization_constants.size(); i++) {
  5694. //see if overridden
  5695. const Shader::SpecializationConstant &sc = shader->specialization_constants[i];
  5696. data_ptr[i] = sc.constant.int_value; //just copy the 32 bits
  5697. for (int j = 0; j < p_specialization_constants.size(); j++) {
  5698. const PipelineSpecializationConstant &psc = p_specialization_constants[j];
  5699. if (psc.constant_id == sc.constant.constant_id) {
  5700. ERR_FAIL_COND_V_MSG(psc.type != sc.constant.type, RID(), "Specialization constant provided for id (" + itos(sc.constant.constant_id) + ") is of the wrong type.");
  5701. data_ptr[i] = sc.constant.int_value;
  5702. break;
  5703. }
  5704. }
  5705. VkSpecializationMapEntry entry;
  5706. entry.constantID = sc.constant.constant_id;
  5707. entry.offset = i * sizeof(uint32_t);
  5708. entry.size = sizeof(uint32_t);
  5709. specialization_map_entries.push_back(entry);
  5710. }
  5711. specialization_info.dataSize = specialization_constant_data.size() * sizeof(uint32_t);
  5712. specialization_info.pData = data_ptr;
  5713. specialization_info.mapEntryCount = specialization_map_entries.size();
  5714. specialization_info.pMapEntries = specialization_map_entries.ptr();
  5715. compute_pipeline_create_info.stage.pSpecializationInfo = &specialization_info;
  5716. }
  5717. ComputePipeline pipeline;
  5718. VkResult err = vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute_pipeline_create_info, nullptr, &pipeline.pipeline);
  5719. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateComputePipelines failed with error " + itos(err) + ".");
  5720. pipeline.set_formats = shader->set_formats;
  5721. pipeline.push_constant_stages = shader->push_constant.push_constants_vk_stage;
  5722. pipeline.pipeline_layout = shader->pipeline_layout;
  5723. pipeline.shader = p_shader;
  5724. pipeline.push_constant_size = shader->push_constant.push_constant_size;
  5725. pipeline.local_group_size[0] = shader->compute_local_size[0];
  5726. pipeline.local_group_size[1] = shader->compute_local_size[1];
  5727. pipeline.local_group_size[2] = shader->compute_local_size[2];
  5728. //create ID to associate with this pipeline
  5729. RID id = compute_pipeline_owner.make_rid(pipeline);
  5730. //now add all the dependencies
  5731. _add_dependency(id, p_shader);
  5732. return id;
  5733. }
  5734. bool RenderingDeviceVulkan::compute_pipeline_is_valid(RID p_pipeline) {
  5735. return compute_pipeline_owner.owns(p_pipeline);
  5736. }
  5737. /****************/
  5738. /**** SCREEN ****/
  5739. /****************/
  5740. int RenderingDeviceVulkan::screen_get_width(DisplayServer::WindowID p_screen) const {
  5741. _THREAD_SAFE_METHOD_
  5742. ERR_FAIL_COND_V_MSG(local_device.is_valid(), -1, "Local devices have no screen");
  5743. return context->window_get_width(p_screen);
  5744. }
  5745. int RenderingDeviceVulkan::screen_get_height(DisplayServer::WindowID p_screen) const {
  5746. _THREAD_SAFE_METHOD_
  5747. ERR_FAIL_COND_V_MSG(local_device.is_valid(), -1, "Local devices have no screen");
  5748. return context->window_get_height(p_screen);
  5749. }
  5750. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::screen_get_framebuffer_format() const {
  5751. _THREAD_SAFE_METHOD_
  5752. ERR_FAIL_COND_V_MSG(local_device.is_valid(), INVALID_ID, "Local devices have no screen");
  5753. //very hacky, but not used often per frame so I guess ok
  5754. VkFormat vkformat = context->get_screen_format();
  5755. DataFormat format = DATA_FORMAT_MAX;
  5756. for (int i = 0; i < DATA_FORMAT_MAX; i++) {
  5757. if (vkformat == vulkan_formats[i]) {
  5758. format = DataFormat(i);
  5759. break;
  5760. }
  5761. }
  5762. ERR_FAIL_COND_V(format == DATA_FORMAT_MAX, INVALID_ID);
  5763. AttachmentFormat attachment;
  5764. attachment.format = format;
  5765. attachment.samples = TEXTURE_SAMPLES_1;
  5766. attachment.usage_flags = TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  5767. Vector<AttachmentFormat> screen_attachment;
  5768. screen_attachment.push_back(attachment);
  5769. return const_cast<RenderingDeviceVulkan *>(this)->framebuffer_format_create(screen_attachment);
  5770. }
  5771. /*******************/
  5772. /**** DRAW LIST ****/
  5773. /*******************/
  5774. RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_begin_for_screen(DisplayServer::WindowID p_screen, const Color &p_clear_color) {
  5775. _THREAD_SAFE_METHOD_
  5776. ERR_FAIL_COND_V_MSG(local_device.is_valid(), INVALID_ID, "Local devices have no screen");
  5777. ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  5778. ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  5779. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  5780. if (!context->window_is_valid_swapchain(p_screen)) {
  5781. return INVALID_ID;
  5782. }
  5783. Size2i size = Size2i(context->window_get_width(p_screen), context->window_get_height(p_screen));
  5784. _draw_list_allocate(Rect2i(Vector2i(), size), 0, 0);
  5785. #ifdef DEBUG_ENABLED
  5786. draw_list_framebuffer_format = screen_get_framebuffer_format();
  5787. #endif
  5788. draw_list_subpass_count = 1;
  5789. VkRenderPassBeginInfo render_pass_begin;
  5790. render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  5791. render_pass_begin.pNext = nullptr;
  5792. render_pass_begin.renderPass = context->window_get_render_pass(p_screen);
  5793. render_pass_begin.framebuffer = context->window_get_framebuffer(p_screen);
  5794. render_pass_begin.renderArea.extent.width = size.width;
  5795. render_pass_begin.renderArea.extent.height = size.height;
  5796. render_pass_begin.renderArea.offset.x = 0;
  5797. render_pass_begin.renderArea.offset.y = 0;
  5798. render_pass_begin.clearValueCount = 1;
  5799. VkClearValue clear_value;
  5800. clear_value.color.float32[0] = p_clear_color.r;
  5801. clear_value.color.float32[1] = p_clear_color.g;
  5802. clear_value.color.float32[2] = p_clear_color.b;
  5803. clear_value.color.float32[3] = p_clear_color.a;
  5804. render_pass_begin.pClearValues = &clear_value;
  5805. vkCmdBeginRenderPass(command_buffer, &render_pass_begin, VK_SUBPASS_CONTENTS_INLINE);
  5806. uint32_t size_x = screen_get_width(p_screen);
  5807. uint32_t size_y = screen_get_height(p_screen);
  5808. VkViewport viewport;
  5809. viewport.x = 0;
  5810. viewport.y = 0;
  5811. viewport.width = size_x;
  5812. viewport.height = size_y;
  5813. viewport.minDepth = 0;
  5814. viewport.maxDepth = 1.0;
  5815. vkCmdSetViewport(command_buffer, 0, 1, &viewport);
  5816. VkRect2D scissor;
  5817. scissor.offset.x = 0;
  5818. scissor.offset.y = 0;
  5819. scissor.extent.width = size_x;
  5820. scissor.extent.height = size_y;
  5821. vkCmdSetScissor(command_buffer, 0, 1, &scissor);
  5822. return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;
  5823. }
  5824. Error RenderingDeviceVulkan::_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, VkFramebuffer *r_framebuffer, VkRenderPass *r_render_pass, uint32_t *r_subpass_count) {
  5825. Framebuffer::VersionKey vk;
  5826. vk.initial_color_action = p_initial_color_action;
  5827. vk.final_color_action = p_final_color_action;
  5828. vk.initial_depth_action = p_initial_depth_action;
  5829. vk.final_depth_action = p_final_depth_action;
  5830. vk.view_count = p_framebuffer->view_count;
  5831. if (!p_framebuffer->framebuffers.has(vk)) {
  5832. //need to create this version
  5833. Framebuffer::Version version;
  5834. 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);
  5835. VkFramebufferCreateInfo framebuffer_create_info;
  5836. framebuffer_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  5837. framebuffer_create_info.pNext = nullptr;
  5838. framebuffer_create_info.flags = 0;
  5839. framebuffer_create_info.renderPass = version.render_pass;
  5840. Vector<VkImageView> attachments;
  5841. for (int i = 0; i < p_framebuffer->texture_ids.size(); i++) {
  5842. Texture *texture = texture_owner.get_or_null(p_framebuffer->texture_ids[i]);
  5843. if (texture) {
  5844. attachments.push_back(texture->view);
  5845. ERR_FAIL_COND_V(texture->width != p_framebuffer->size.width, ERR_BUG);
  5846. ERR_FAIL_COND_V(texture->height != p_framebuffer->size.height, ERR_BUG);
  5847. }
  5848. }
  5849. framebuffer_create_info.attachmentCount = attachments.size();
  5850. framebuffer_create_info.pAttachments = attachments.ptr();
  5851. framebuffer_create_info.width = p_framebuffer->size.width;
  5852. framebuffer_create_info.height = p_framebuffer->size.height;
  5853. framebuffer_create_info.layers = 1;
  5854. VkResult err = vkCreateFramebuffer(device, &framebuffer_create_info, nullptr, &version.framebuffer);
  5855. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vkCreateFramebuffer failed with error " + itos(err) + ".");
  5856. version.subpass_count = framebuffer_formats[p_framebuffer->format_id].E->key().passes.size();
  5857. p_framebuffer->framebuffers.insert(vk, version);
  5858. }
  5859. const Framebuffer::Version &version = p_framebuffer->framebuffers[vk];
  5860. *r_framebuffer = version.framebuffer;
  5861. *r_render_pass = version.render_pass;
  5862. *r_subpass_count = version.subpass_count;
  5863. return OK;
  5864. }
  5865. Error RenderingDeviceVulkan::_draw_list_render_pass_begin(Framebuffer *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 viewport_offset, Point2i viewport_size, VkFramebuffer vkframebuffer, VkRenderPass render_pass, VkCommandBuffer command_buffer, VkSubpassContents subpass_contents, const Vector<RID> &p_storage_textures) {
  5866. VkRenderPassBeginInfo render_pass_begin;
  5867. render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  5868. render_pass_begin.pNext = nullptr;
  5869. render_pass_begin.renderPass = render_pass;
  5870. render_pass_begin.framebuffer = vkframebuffer;
  5871. /*
  5872. * Given how API works, it makes sense to always fully operate on the whole framebuffer.
  5873. * This allows better continue operations for operations like shadowmapping.
  5874. render_pass_begin.renderArea.extent.width = viewport_size.width;
  5875. render_pass_begin.renderArea.extent.height = viewport_size.height;
  5876. render_pass_begin.renderArea.offset.x = viewport_offset.x;
  5877. render_pass_begin.renderArea.offset.y = viewport_offset.y;
  5878. */
  5879. render_pass_begin.renderArea.extent.width = framebuffer->size.width;
  5880. render_pass_begin.renderArea.extent.height = framebuffer->size.height;
  5881. render_pass_begin.renderArea.offset.x = 0;
  5882. render_pass_begin.renderArea.offset.y = 0;
  5883. Vector<VkClearValue> clear_values;
  5884. clear_values.resize(framebuffer->texture_ids.size());
  5885. int clear_values_count = 0;
  5886. {
  5887. int color_index = 0;
  5888. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  5889. VkClearValue clear_value;
  5890. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  5891. if (!texture) {
  5892. color_index++;
  5893. continue;
  5894. }
  5895. if (color_index < p_clear_colors.size() && texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  5896. ERR_FAIL_INDEX_V(color_index, p_clear_colors.size(), ERR_BUG); //a bug
  5897. Color clear_color = p_clear_colors[color_index];
  5898. clear_value.color.float32[0] = clear_color.r;
  5899. clear_value.color.float32[1] = clear_color.g;
  5900. clear_value.color.float32[2] = clear_color.b;
  5901. clear_value.color.float32[3] = clear_color.a;
  5902. color_index++;
  5903. } else if (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  5904. clear_value.depthStencil.depth = p_clear_depth;
  5905. clear_value.depthStencil.stencil = p_clear_stencil;
  5906. } else {
  5907. clear_value.color.float32[0] = 0;
  5908. clear_value.color.float32[1] = 0;
  5909. clear_value.color.float32[2] = 0;
  5910. clear_value.color.float32[3] = 0;
  5911. }
  5912. clear_values.write[clear_values_count++] = clear_value;
  5913. }
  5914. }
  5915. render_pass_begin.clearValueCount = clear_values_count;
  5916. render_pass_begin.pClearValues = clear_values.ptr();
  5917. for (int i = 0; i < p_storage_textures.size(); i++) {
  5918. Texture *texture = texture_owner.get_or_null(p_storage_textures[i]);
  5919. if (!texture) {
  5920. continue;
  5921. }
  5922. ERR_CONTINUE_MSG(!(texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT), "Supplied storage texture " + itos(i) + " for draw list is not set to be used for storage.");
  5923. if (texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT) {
  5924. //must change layout to general
  5925. VkImageMemoryBarrier image_memory_barrier;
  5926. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  5927. image_memory_barrier.pNext = nullptr;
  5928. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  5929. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  5930. image_memory_barrier.oldLayout = texture->layout;
  5931. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  5932. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  5933. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  5934. image_memory_barrier.image = texture->image;
  5935. image_memory_barrier.subresourceRange.aspectMask = texture->read_aspect_mask;
  5936. image_memory_barrier.subresourceRange.baseMipLevel = texture->base_mipmap;
  5937. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  5938. image_memory_barrier.subresourceRange.baseArrayLayer = texture->base_layer;
  5939. image_memory_barrier.subresourceRange.layerCount = texture->layers;
  5940. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  5941. texture->layout = VK_IMAGE_LAYOUT_GENERAL;
  5942. draw_list_storage_textures.push_back(p_storage_textures[i]);
  5943. }
  5944. }
  5945. vkCmdBeginRenderPass(command_buffer, &render_pass_begin, subpass_contents);
  5946. //mark textures as bound
  5947. draw_list_bound_textures.clear();
  5948. draw_list_unbind_color_textures = p_final_color_action != FINAL_ACTION_CONTINUE;
  5949. draw_list_unbind_depth_textures = p_final_depth_action != FINAL_ACTION_CONTINUE;
  5950. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  5951. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  5952. if (!texture) {
  5953. continue;
  5954. }
  5955. texture->bound = true;
  5956. draw_list_bound_textures.push_back(framebuffer->texture_ids[i]);
  5957. }
  5958. return OK;
  5959. }
  5960. void RenderingDeviceVulkan::_draw_list_insert_clear_region(DrawList *draw_list, Framebuffer *framebuffer, Point2i viewport_offset, Point2i viewport_size, bool p_clear_color, const Vector<Color> &p_clear_colors, bool p_clear_depth, float p_depth, uint32_t p_stencil) {
  5961. ERR_FAIL_COND_MSG(p_clear_color && p_clear_colors.size() != framebuffer->texture_ids.size(), "Clear color values supplied (" + itos(p_clear_colors.size()) + ") differ from the amount required for framebuffer color attachments (" + itos(framebuffer->texture_ids.size()) + ").");
  5962. Vector<VkClearAttachment> clear_attachments;
  5963. int color_index = 0;
  5964. int texture_index = 0;
  5965. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  5966. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  5967. if (!texture) {
  5968. texture_index++;
  5969. continue;
  5970. }
  5971. VkClearAttachment clear_at = {};
  5972. if (p_clear_color && texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  5973. Color clear_color = p_clear_colors[texture_index++];
  5974. clear_at.clearValue.color.float32[0] = clear_color.r;
  5975. clear_at.clearValue.color.float32[1] = clear_color.g;
  5976. clear_at.clearValue.color.float32[2] = clear_color.b;
  5977. clear_at.clearValue.color.float32[3] = clear_color.a;
  5978. clear_at.colorAttachment = color_index++;
  5979. clear_at.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  5980. } else if (p_clear_depth && texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  5981. clear_at.clearValue.depthStencil.depth = p_depth;
  5982. clear_at.clearValue.depthStencil.stencil = p_stencil;
  5983. clear_at.colorAttachment = 0;
  5984. clear_at.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  5985. if (format_has_stencil(texture->format)) {
  5986. clear_at.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  5987. }
  5988. } else {
  5989. ERR_CONTINUE(true);
  5990. }
  5991. clear_attachments.push_back(clear_at);
  5992. }
  5993. VkClearRect cr;
  5994. cr.baseArrayLayer = 0;
  5995. cr.layerCount = 1;
  5996. cr.rect.offset.x = viewport_offset.x;
  5997. cr.rect.offset.y = viewport_offset.y;
  5998. cr.rect.extent.width = viewport_size.width;
  5999. cr.rect.extent.height = viewport_size.height;
  6000. vkCmdClearAttachments(draw_list->command_buffer, clear_attachments.size(), clear_attachments.ptr(), 1, &cr);
  6001. }
  6002. RenderingDevice::DrawListID RenderingDeviceVulkan::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, const Vector<RID> &p_storage_textures) {
  6003. _THREAD_SAFE_METHOD_
  6004. ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  6005. ERR_FAIL_COND_V_MSG(compute_list != nullptr && !compute_list->state.allow_draw_overlap, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  6006. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  6007. ERR_FAIL_COND_V(!framebuffer, INVALID_ID);
  6008. Point2i viewport_offset;
  6009. Point2i viewport_size = framebuffer->size;
  6010. bool needs_clear_color = false;
  6011. bool needs_clear_depth = false;
  6012. if (p_region != Rect2() && p_region != Rect2(Vector2(), viewport_size)) { //check custom region
  6013. Rect2i viewport(viewport_offset, viewport_size);
  6014. Rect2i regioni = p_region;
  6015. if (!(regioni.position.x >= viewport.position.x) && (regioni.position.y >= viewport.position.y) &&
  6016. ((regioni.position.x + regioni.size.x) <= (viewport.position.x + viewport.size.x)) &&
  6017. ((regioni.position.y + regioni.size.y) <= (viewport.position.y + viewport.size.y))) {
  6018. ERR_FAIL_V_MSG(INVALID_ID, "When supplying a custom region, it must be contained within the framebuffer rectangle");
  6019. }
  6020. viewport_offset = regioni.position;
  6021. viewport_size = regioni.size;
  6022. if (p_initial_color_action == INITIAL_ACTION_CLEAR_REGION_CONTINUE) {
  6023. needs_clear_color = true;
  6024. p_initial_color_action = INITIAL_ACTION_CONTINUE;
  6025. }
  6026. if (p_initial_depth_action == INITIAL_ACTION_CLEAR_REGION_CONTINUE) {
  6027. needs_clear_depth = true;
  6028. p_initial_depth_action = INITIAL_ACTION_CONTINUE;
  6029. }
  6030. if (p_initial_color_action == INITIAL_ACTION_CLEAR_REGION) {
  6031. needs_clear_color = true;
  6032. p_initial_color_action = INITIAL_ACTION_KEEP;
  6033. }
  6034. if (p_initial_depth_action == INITIAL_ACTION_CLEAR_REGION) {
  6035. needs_clear_depth = true;
  6036. p_initial_depth_action = INITIAL_ACTION_KEEP;
  6037. }
  6038. }
  6039. if (p_initial_color_action == INITIAL_ACTION_CLEAR) { //check clear values
  6040. int color_count = 0;
  6041. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  6042. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  6043. if (!texture || !(texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  6044. color_count++;
  6045. }
  6046. }
  6047. 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) + ").");
  6048. }
  6049. VkFramebuffer vkframebuffer;
  6050. VkRenderPass render_pass;
  6051. Error err = _draw_list_setup_framebuffer(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, &vkframebuffer, &render_pass, &draw_list_subpass_count);
  6052. ERR_FAIL_COND_V(err != OK, INVALID_ID);
  6053. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  6054. 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, vkframebuffer, render_pass, command_buffer, VK_SUBPASS_CONTENTS_INLINE, p_storage_textures);
  6055. if (err != OK) {
  6056. return INVALID_ID;
  6057. }
  6058. draw_list_render_pass = render_pass;
  6059. draw_list_vkframebuffer = vkframebuffer;
  6060. _draw_list_allocate(Rect2i(viewport_offset, viewport_size), 0, 0);
  6061. #ifdef DEBUG_ENABLED
  6062. draw_list_framebuffer_format = framebuffer->format_id;
  6063. #endif
  6064. draw_list_current_subpass = 0;
  6065. if (needs_clear_color || needs_clear_depth) {
  6066. _draw_list_insert_clear_region(draw_list, framebuffer, viewport_offset, viewport_size, needs_clear_color, p_clear_color_values, needs_clear_depth, p_clear_depth, p_clear_stencil);
  6067. }
  6068. VkViewport viewport;
  6069. viewport.x = viewport_offset.x;
  6070. viewport.y = viewport_offset.y;
  6071. viewport.width = viewport_size.width;
  6072. viewport.height = viewport_size.height;
  6073. viewport.minDepth = 0;
  6074. viewport.maxDepth = 1.0;
  6075. vkCmdSetViewport(command_buffer, 0, 1, &viewport);
  6076. VkRect2D scissor;
  6077. scissor.offset.x = viewport_offset.x;
  6078. scissor.offset.y = viewport_offset.y;
  6079. scissor.extent.width = viewport_size.width;
  6080. scissor.extent.height = viewport_size.height;
  6081. vkCmdSetScissor(command_buffer, 0, 1, &scissor);
  6082. return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;
  6083. }
  6084. Error RenderingDeviceVulkan::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) {
  6085. _THREAD_SAFE_METHOD_
  6086. ERR_FAIL_COND_V(p_splits < 1, ERR_INVALID_DECLARATION);
  6087. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  6088. ERR_FAIL_COND_V(!framebuffer, ERR_INVALID_DECLARATION);
  6089. Point2i viewport_offset;
  6090. Point2i viewport_size = framebuffer->size;
  6091. bool needs_clear_color = false;
  6092. bool needs_clear_depth = false;
  6093. if (p_region != Rect2() && p_region != Rect2(Vector2(), viewport_size)) { //check custom region
  6094. Rect2i viewport(viewport_offset, viewport_size);
  6095. Rect2i regioni = p_region;
  6096. if (!(regioni.position.x >= viewport.position.x) && (regioni.position.y >= viewport.position.y) &&
  6097. ((regioni.position.x + regioni.size.x) <= (viewport.position.x + viewport.size.x)) &&
  6098. ((regioni.position.y + regioni.size.y) <= (viewport.position.y + viewport.size.y))) {
  6099. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "When supplying a custom region, it must be contained within the framebuffer rectangle");
  6100. }
  6101. viewport_offset = regioni.position;
  6102. viewport_size = regioni.size;
  6103. if (p_initial_color_action == INITIAL_ACTION_CLEAR_REGION) {
  6104. needs_clear_color = true;
  6105. p_initial_color_action = INITIAL_ACTION_KEEP;
  6106. }
  6107. if (p_initial_depth_action == INITIAL_ACTION_CLEAR_REGION) {
  6108. needs_clear_depth = true;
  6109. p_initial_depth_action = INITIAL_ACTION_KEEP;
  6110. }
  6111. }
  6112. if (p_initial_color_action == INITIAL_ACTION_CLEAR) { //check clear values
  6113. int color_count = 0;
  6114. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  6115. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  6116. if (!texture || !(texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  6117. color_count++;
  6118. }
  6119. }
  6120. ERR_FAIL_COND_V_MSG(p_clear_color_values.size() != color_count, ERR_INVALID_PARAMETER,
  6121. "Clear color values supplied (" + itos(p_clear_color_values.size()) + ") differ from the amount required for framebuffer (" + itos(color_count) + ").");
  6122. }
  6123. VkFramebuffer vkframebuffer;
  6124. VkRenderPass render_pass;
  6125. Error err = _draw_list_setup_framebuffer(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, &vkframebuffer, &render_pass, &draw_list_subpass_count);
  6126. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  6127. VkCommandBuffer frame_command_buffer = frames[frame].draw_command_buffer;
  6128. 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, vkframebuffer, render_pass, frame_command_buffer, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS, p_storage_textures);
  6129. if (err != OK) {
  6130. return ERR_CANT_CREATE;
  6131. }
  6132. draw_list_current_subpass = 0;
  6133. #ifdef DEBUG_ENABLED
  6134. draw_list_framebuffer_format = framebuffer->format_id;
  6135. #endif
  6136. draw_list_render_pass = render_pass;
  6137. draw_list_vkframebuffer = vkframebuffer;
  6138. err = _draw_list_allocate(Rect2i(viewport_offset, viewport_size), p_splits, 0);
  6139. if (err != OK) {
  6140. return err;
  6141. }
  6142. if (needs_clear_color || needs_clear_depth) {
  6143. _draw_list_insert_clear_region(&draw_list[0], framebuffer, viewport_offset, viewport_size, needs_clear_color, p_clear_color_values, needs_clear_depth, p_clear_depth, p_clear_stencil);
  6144. }
  6145. for (uint32_t i = 0; i < p_splits; i++) {
  6146. VkViewport viewport;
  6147. viewport.x = viewport_offset.x;
  6148. viewport.y = viewport_offset.y;
  6149. viewport.width = viewport_size.width;
  6150. viewport.height = viewport_size.height;
  6151. viewport.minDepth = 0;
  6152. viewport.maxDepth = 1.0;
  6153. vkCmdSetViewport(draw_list[i].command_buffer, 0, 1, &viewport);
  6154. VkRect2D scissor;
  6155. scissor.offset.x = viewport_offset.x;
  6156. scissor.offset.y = viewport_offset.y;
  6157. scissor.extent.width = viewport_size.width;
  6158. scissor.extent.height = viewport_size.height;
  6159. vkCmdSetScissor(draw_list[i].command_buffer, 0, 1, &scissor);
  6160. r_split_ids[i] = (int64_t(ID_TYPE_SPLIT_DRAW_LIST) << ID_BASE_SHIFT) + i;
  6161. }
  6162. return OK;
  6163. }
  6164. RenderingDeviceVulkan::DrawList *RenderingDeviceVulkan::_get_draw_list_ptr(DrawListID p_id) {
  6165. if (p_id < 0) {
  6166. return nullptr;
  6167. }
  6168. if (!draw_list) {
  6169. return nullptr;
  6170. } else if (p_id == (int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT)) {
  6171. if (draw_list_split) {
  6172. return nullptr;
  6173. }
  6174. return draw_list;
  6175. } else if (p_id >> DrawListID(ID_BASE_SHIFT) == ID_TYPE_SPLIT_DRAW_LIST) {
  6176. if (!draw_list_split) {
  6177. return nullptr;
  6178. }
  6179. uint64_t index = p_id & ((DrawListID(1) << DrawListID(ID_BASE_SHIFT)) - 1); //mask
  6180. if (index >= draw_list_count) {
  6181. return nullptr;
  6182. }
  6183. return &draw_list[index];
  6184. } else {
  6185. return nullptr;
  6186. }
  6187. }
  6188. void RenderingDeviceVulkan::draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline) {
  6189. DrawList *dl = _get_draw_list_ptr(p_list);
  6190. ERR_FAIL_COND(!dl);
  6191. #ifdef DEBUG_ENABLED
  6192. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6193. #endif
  6194. const RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_render_pipeline);
  6195. ERR_FAIL_COND(!pipeline);
  6196. #ifdef DEBUG_ENABLED
  6197. ERR_FAIL_COND(pipeline->validation.framebuffer_format != draw_list_framebuffer_format && pipeline->validation.render_pass != draw_list_current_subpass);
  6198. #endif
  6199. if (p_render_pipeline == dl->state.pipeline) {
  6200. return; //redundant state, return.
  6201. }
  6202. dl->state.pipeline = p_render_pipeline;
  6203. dl->state.pipeline_layout = pipeline->pipeline_layout;
  6204. vkCmdBindPipeline(dl->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline);
  6205. if (dl->state.pipeline_shader != pipeline->shader) {
  6206. // shader changed, so descriptor sets may become incompatible.
  6207. //go through ALL sets, and unbind them (and all those above) if the format is different
  6208. uint32_t pcount = pipeline->set_formats.size(); //formats count in this pipeline
  6209. dl->state.set_count = MAX(dl->state.set_count, pcount);
  6210. const uint32_t *pformats = pipeline->set_formats.ptr(); //pipeline set formats
  6211. bool sets_valid = true; //once invalid, all above become invalid
  6212. for (uint32_t i = 0; i < pcount; i++) {
  6213. //if a part of the format is different, invalidate it (and the rest)
  6214. if (!sets_valid || dl->state.sets[i].pipeline_expected_format != pformats[i]) {
  6215. dl->state.sets[i].bound = false;
  6216. dl->state.sets[i].pipeline_expected_format = pformats[i];
  6217. sets_valid = false;
  6218. }
  6219. }
  6220. for (uint32_t i = pcount; i < dl->state.set_count; i++) {
  6221. //unbind the ones above (not used) if exist
  6222. dl->state.sets[i].bound = false;
  6223. }
  6224. dl->state.set_count = pcount; //update set count
  6225. if (pipeline->push_constant_size) {
  6226. dl->state.pipeline_push_constant_stages = pipeline->push_constant_stages;
  6227. #ifdef DEBUG_ENABLED
  6228. dl->validation.pipeline_push_constant_supplied = false;
  6229. #endif
  6230. }
  6231. dl->state.pipeline_shader = pipeline->shader;
  6232. }
  6233. #ifdef DEBUG_ENABLED
  6234. //update render pass pipeline info
  6235. dl->validation.pipeline_active = true;
  6236. dl->validation.pipeline_dynamic_state = pipeline->validation.dynamic_state;
  6237. dl->validation.pipeline_vertex_format = pipeline->validation.vertex_format;
  6238. dl->validation.pipeline_uses_restart_indices = pipeline->validation.uses_restart_indices;
  6239. dl->validation.pipeline_primitive_divisor = pipeline->validation.primitive_divisor;
  6240. dl->validation.pipeline_primitive_minimum = pipeline->validation.primitive_minimum;
  6241. dl->validation.pipeline_push_constant_size = pipeline->push_constant_size;
  6242. #endif
  6243. }
  6244. void RenderingDeviceVulkan::draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index) {
  6245. #ifdef DEBUG_ENABLED
  6246. ERR_FAIL_COND_MSG(p_index >= limits.maxBoundDescriptorSets || p_index >= MAX_UNIFORM_SETS,
  6247. "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(limits.maxBoundDescriptorSets) + ").");
  6248. #endif
  6249. DrawList *dl = _get_draw_list_ptr(p_list);
  6250. ERR_FAIL_COND(!dl);
  6251. #ifdef DEBUG_ENABLED
  6252. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6253. #endif
  6254. const UniformSet *uniform_set = uniform_set_owner.get_or_null(p_uniform_set);
  6255. ERR_FAIL_COND(!uniform_set);
  6256. if (p_index > dl->state.set_count) {
  6257. dl->state.set_count = p_index;
  6258. }
  6259. dl->state.sets[p_index].descriptor_set = uniform_set->descriptor_set; //update set pointer
  6260. dl->state.sets[p_index].bound = false; //needs rebind
  6261. dl->state.sets[p_index].uniform_set_format = uniform_set->format;
  6262. dl->state.sets[p_index].uniform_set = p_uniform_set;
  6263. uint32_t mst_count = uniform_set->mutable_storage_textures.size();
  6264. if (mst_count) {
  6265. Texture **mst_textures = const_cast<UniformSet *>(uniform_set)->mutable_storage_textures.ptrw();
  6266. for (uint32_t i = 0; i < mst_count; i++) {
  6267. if (mst_textures[i]->used_in_frame != frames_drawn) {
  6268. mst_textures[i]->used_in_frame = frames_drawn;
  6269. mst_textures[i]->used_in_transfer = false;
  6270. mst_textures[i]->used_in_compute = false;
  6271. }
  6272. mst_textures[i]->used_in_raster = true;
  6273. }
  6274. }
  6275. #ifdef DEBUG_ENABLED
  6276. { //validate that textures bound are not attached as framebuffer bindings
  6277. uint32_t attachable_count = uniform_set->attachable_textures.size();
  6278. const UniformSet::AttachableTexture *attachable_ptr = uniform_set->attachable_textures.ptr();
  6279. uint32_t bound_count = draw_list_bound_textures.size();
  6280. const RID *bound_ptr = draw_list_bound_textures.ptr();
  6281. for (uint32_t i = 0; i < attachable_count; i++) {
  6282. for (uint32_t j = 0; j < bound_count; j++) {
  6283. ERR_FAIL_COND_MSG(attachable_ptr[i].texture == bound_ptr[j],
  6284. "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.");
  6285. }
  6286. }
  6287. }
  6288. #endif
  6289. }
  6290. void RenderingDeviceVulkan::draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array) {
  6291. DrawList *dl = _get_draw_list_ptr(p_list);
  6292. ERR_FAIL_COND(!dl);
  6293. #ifdef DEBUG_ENABLED
  6294. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6295. #endif
  6296. const VertexArray *vertex_array = vertex_array_owner.get_or_null(p_vertex_array);
  6297. ERR_FAIL_COND(!vertex_array);
  6298. if (dl->state.vertex_array == p_vertex_array) {
  6299. return; //already set
  6300. }
  6301. dl->state.vertex_array = p_vertex_array;
  6302. #ifdef DEBUG_ENABLED
  6303. dl->validation.vertex_format = vertex_array->description;
  6304. dl->validation.vertex_max_instances_allowed = vertex_array->max_instances_allowed;
  6305. #endif
  6306. dl->validation.vertex_array_size = vertex_array->vertex_count;
  6307. vkCmdBindVertexBuffers(dl->command_buffer, 0, vertex_array->buffers.size(), vertex_array->buffers.ptr(), vertex_array->offsets.ptr());
  6308. }
  6309. void RenderingDeviceVulkan::draw_list_bind_index_array(DrawListID p_list, RID p_index_array) {
  6310. DrawList *dl = _get_draw_list_ptr(p_list);
  6311. ERR_FAIL_COND(!dl);
  6312. #ifdef DEBUG_ENABLED
  6313. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6314. #endif
  6315. const IndexArray *index_array = index_array_owner.get_or_null(p_index_array);
  6316. ERR_FAIL_COND(!index_array);
  6317. if (dl->state.index_array == p_index_array) {
  6318. return; //already set
  6319. }
  6320. dl->state.index_array = p_index_array;
  6321. #ifdef DEBUG_ENABLED
  6322. dl->validation.index_array_max_index = index_array->max_index;
  6323. #endif
  6324. dl->validation.index_array_size = index_array->indices;
  6325. dl->validation.index_array_offset = index_array->offset;
  6326. vkCmdBindIndexBuffer(dl->command_buffer, index_array->buffer, index_array->offset, index_array->index_type);
  6327. }
  6328. void RenderingDeviceVulkan::draw_list_set_line_width(DrawListID p_list, float p_width) {
  6329. DrawList *dl = _get_draw_list_ptr(p_list);
  6330. ERR_FAIL_COND(!dl);
  6331. #ifdef DEBUG_ENABLED
  6332. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6333. #endif
  6334. vkCmdSetLineWidth(dl->command_buffer, p_width);
  6335. }
  6336. void RenderingDeviceVulkan::draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size) {
  6337. DrawList *dl = _get_draw_list_ptr(p_list);
  6338. ERR_FAIL_COND(!dl);
  6339. #ifdef DEBUG_ENABLED
  6340. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6341. #endif
  6342. #ifdef DEBUG_ENABLED
  6343. ERR_FAIL_COND_MSG(p_data_size != dl->validation.pipeline_push_constant_size,
  6344. "This render pipeline requires (" + itos(dl->validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")");
  6345. #endif
  6346. vkCmdPushConstants(dl->command_buffer, dl->state.pipeline_layout, dl->state.pipeline_push_constant_stages, 0, p_data_size, p_data);
  6347. #ifdef DEBUG_ENABLED
  6348. dl->validation.pipeline_push_constant_supplied = true;
  6349. #endif
  6350. }
  6351. void RenderingDeviceVulkan::draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances, uint32_t p_procedural_vertices) {
  6352. DrawList *dl = _get_draw_list_ptr(p_list);
  6353. ERR_FAIL_COND(!dl);
  6354. #ifdef DEBUG_ENABLED
  6355. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6356. #endif
  6357. #ifdef DEBUG_ENABLED
  6358. ERR_FAIL_COND_MSG(!dl->validation.pipeline_active,
  6359. "No render pipeline was set before attempting to draw.");
  6360. if (dl->validation.pipeline_vertex_format != INVALID_ID) {
  6361. //pipeline uses vertices, validate format
  6362. ERR_FAIL_COND_MSG(dl->validation.vertex_format == INVALID_ID,
  6363. "No vertex array was bound, and render pipeline expects vertices.");
  6364. //make sure format is right
  6365. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format != dl->validation.vertex_format,
  6366. "The vertex format used to create the pipeline does not match the vertex format bound.");
  6367. //make sure number of instances is valid
  6368. ERR_FAIL_COND_MSG(p_instances > dl->validation.vertex_max_instances_allowed,
  6369. "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) + ").");
  6370. }
  6371. if (dl->validation.pipeline_push_constant_size > 0) {
  6372. //using push constants, check that they were supplied
  6373. ERR_FAIL_COND_MSG(!dl->validation.pipeline_push_constant_supplied,
  6374. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  6375. }
  6376. #endif
  6377. //Bind descriptor sets
  6378. for (uint32_t i = 0; i < dl->state.set_count; i++) {
  6379. if (dl->state.sets[i].pipeline_expected_format == 0) {
  6380. continue; //nothing expected by this pipeline
  6381. }
  6382. #ifdef DEBUG_ENABLED
  6383. if (dl->state.sets[i].pipeline_expected_format != dl->state.sets[i].uniform_set_format) {
  6384. if (dl->state.sets[i].uniform_set_format == 0) {
  6385. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline");
  6386. } else if (uniform_set_owner.owns(dl->state.sets[i].uniform_set)) {
  6387. UniformSet *us = uniform_set_owner.get_or_null(dl->state.sets[i].uniform_set);
  6388. 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));
  6389. } else {
  6390. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was 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));
  6391. }
  6392. }
  6393. #endif
  6394. if (!dl->state.sets[i].bound) {
  6395. //All good, see if this requires re-binding
  6396. vkCmdBindDescriptorSets(dl->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, dl->state.pipeline_layout, i, 1, &dl->state.sets[i].descriptor_set, 0, nullptr);
  6397. dl->state.sets[i].bound = true;
  6398. }
  6399. }
  6400. if (p_use_indices) {
  6401. #ifdef DEBUG_ENABLED
  6402. ERR_FAIL_COND_MSG(p_procedural_vertices > 0,
  6403. "Procedural vertices can't be used together with indices.");
  6404. ERR_FAIL_COND_MSG(!dl->validation.index_array_size,
  6405. "Draw command requested indices, but no index buffer was set.");
  6406. if (dl->validation.pipeline_vertex_format != INVALID_ID) {
  6407. //uses vertices, do some vertex validations
  6408. ERR_FAIL_COND_MSG(dl->validation.vertex_array_size < dl->validation.index_array_max_index,
  6409. "Index array references (max index: " + itos(dl->validation.index_array_max_index) + ") indices beyond the vertex array size (" + itos(dl->validation.vertex_array_size) + ").");
  6410. }
  6411. ERR_FAIL_COND_MSG(dl->validation.pipeline_uses_restart_indices != dl->validation.index_buffer_uses_restart_indices,
  6412. "The usage of restart indices in index buffer does not match the render primitive in the pipeline.");
  6413. #endif
  6414. uint32_t to_draw = dl->validation.index_array_size;
  6415. #ifdef DEBUG_ENABLED
  6416. ERR_FAIL_COND_MSG(to_draw < dl->validation.pipeline_primitive_minimum,
  6417. "Too few indices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(dl->validation.pipeline_primitive_minimum) + ").");
  6418. ERR_FAIL_COND_MSG((to_draw % dl->validation.pipeline_primitive_divisor) != 0,
  6419. "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) + ").");
  6420. #endif
  6421. vkCmdDrawIndexed(dl->command_buffer, to_draw, p_instances, dl->validation.index_array_offset, 0, 0);
  6422. } else {
  6423. uint32_t to_draw;
  6424. if (p_procedural_vertices > 0) {
  6425. #ifdef DEBUG_ENABLED
  6426. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format != INVALID_ID,
  6427. "Procedural vertices requested, but pipeline expects a vertex array.");
  6428. #endif
  6429. to_draw = p_procedural_vertices;
  6430. } else {
  6431. #ifdef DEBUG_ENABLED
  6432. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format == INVALID_ID,
  6433. "Draw command lacks indices, but pipeline format does not use vertices.");
  6434. #endif
  6435. to_draw = dl->validation.vertex_array_size;
  6436. }
  6437. #ifdef DEBUG_ENABLED
  6438. ERR_FAIL_COND_MSG(to_draw < dl->validation.pipeline_primitive_minimum,
  6439. "Too few vertices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(dl->validation.pipeline_primitive_minimum) + ").");
  6440. ERR_FAIL_COND_MSG((to_draw % dl->validation.pipeline_primitive_divisor) != 0,
  6441. "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) + ").");
  6442. #endif
  6443. vkCmdDraw(dl->command_buffer, to_draw, p_instances, 0, 0);
  6444. }
  6445. }
  6446. void RenderingDeviceVulkan::draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect) {
  6447. DrawList *dl = _get_draw_list_ptr(p_list);
  6448. ERR_FAIL_COND(!dl);
  6449. #ifdef DEBUG_ENABLED
  6450. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6451. #endif
  6452. Rect2i rect = p_rect;
  6453. rect.position += dl->viewport.position;
  6454. rect = dl->viewport.intersection(rect);
  6455. if (rect.get_area() == 0) {
  6456. return;
  6457. }
  6458. VkRect2D scissor;
  6459. scissor.offset.x = rect.position.x;
  6460. scissor.offset.y = rect.position.y;
  6461. scissor.extent.width = rect.size.width;
  6462. scissor.extent.height = rect.size.height;
  6463. vkCmdSetScissor(dl->command_buffer, 0, 1, &scissor);
  6464. }
  6465. void RenderingDeviceVulkan::draw_list_disable_scissor(DrawListID p_list) {
  6466. DrawList *dl = _get_draw_list_ptr(p_list);
  6467. ERR_FAIL_COND(!dl);
  6468. #ifdef DEBUG_ENABLED
  6469. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6470. #endif
  6471. VkRect2D scissor;
  6472. scissor.offset.x = dl->viewport.position.x;
  6473. scissor.offset.y = dl->viewport.position.y;
  6474. scissor.extent.width = dl->viewport.size.width;
  6475. scissor.extent.height = dl->viewport.size.height;
  6476. vkCmdSetScissor(dl->command_buffer, 0, 1, &scissor);
  6477. }
  6478. uint32_t RenderingDeviceVulkan::draw_list_get_current_pass() {
  6479. return draw_list_current_subpass;
  6480. }
  6481. RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_switch_to_next_pass() {
  6482. ERR_FAIL_COND_V(draw_list == nullptr, INVALID_ID);
  6483. ERR_FAIL_COND_V(draw_list_current_subpass >= draw_list_subpass_count - 1, INVALID_FORMAT_ID);
  6484. draw_list_current_subpass++;
  6485. Rect2i viewport;
  6486. _draw_list_free(&viewport);
  6487. vkCmdNextSubpass(frames[frame].draw_command_buffer, VK_SUBPASS_CONTENTS_INLINE);
  6488. _draw_list_allocate(viewport, 0, draw_list_current_subpass);
  6489. return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;
  6490. }
  6491. Error RenderingDeviceVulkan::draw_list_switch_to_next_pass_split(uint32_t p_splits, DrawListID *r_split_ids) {
  6492. ERR_FAIL_COND_V(draw_list == nullptr, ERR_INVALID_PARAMETER);
  6493. ERR_FAIL_COND_V(draw_list_current_subpass >= draw_list_subpass_count - 1, ERR_INVALID_PARAMETER);
  6494. draw_list_current_subpass++;
  6495. Rect2i viewport;
  6496. _draw_list_free(&viewport);
  6497. vkCmdNextSubpass(frames[frame].draw_command_buffer, VK_SUBPASS_CONTENTS_INLINE);
  6498. _draw_list_allocate(viewport, p_splits, draw_list_current_subpass);
  6499. for (uint32_t i = 0; i < p_splits; i++) {
  6500. r_split_ids[i] = (int64_t(ID_TYPE_SPLIT_DRAW_LIST) << ID_BASE_SHIFT) + i;
  6501. }
  6502. return OK;
  6503. }
  6504. Error RenderingDeviceVulkan::_draw_list_allocate(const Rect2i &p_viewport, uint32_t p_splits, uint32_t p_subpass) {
  6505. // Lock while draw_list is active
  6506. _THREAD_SAFE_LOCK_
  6507. if (p_splits == 0) {
  6508. draw_list = memnew(DrawList);
  6509. draw_list->command_buffer = frames[frame].draw_command_buffer;
  6510. draw_list->viewport = p_viewport;
  6511. draw_list_count = 0;
  6512. draw_list_split = false;
  6513. } else {
  6514. if (p_splits > (uint32_t)split_draw_list_allocators.size()) {
  6515. uint32_t from = split_draw_list_allocators.size();
  6516. split_draw_list_allocators.resize(p_splits);
  6517. for (uint32_t i = from; i < p_splits; i++) {
  6518. VkCommandPoolCreateInfo cmd_pool_info;
  6519. cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  6520. cmd_pool_info.pNext = nullptr;
  6521. cmd_pool_info.queueFamilyIndex = context->get_graphics_queue_family_index();
  6522. cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  6523. VkResult res = vkCreateCommandPool(device, &cmd_pool_info, nullptr, &split_draw_list_allocators.write[i].command_pool);
  6524. ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "vkCreateCommandPool failed with error " + itos(res) + ".");
  6525. for (int j = 0; j < frame_count; j++) {
  6526. VkCommandBuffer command_buffer;
  6527. VkCommandBufferAllocateInfo cmdbuf;
  6528. //no command buffer exists, create it.
  6529. cmdbuf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  6530. cmdbuf.pNext = nullptr;
  6531. cmdbuf.commandPool = split_draw_list_allocators[i].command_pool;
  6532. cmdbuf.level = VK_COMMAND_BUFFER_LEVEL_SECONDARY;
  6533. cmdbuf.commandBufferCount = 1;
  6534. VkResult err = vkAllocateCommandBuffers(device, &cmdbuf, &command_buffer);
  6535. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vkAllocateCommandBuffers failed with error " + itos(err) + ".");
  6536. split_draw_list_allocators.write[i].command_buffers.push_back(command_buffer);
  6537. }
  6538. }
  6539. }
  6540. draw_list = memnew_arr(DrawList, p_splits);
  6541. draw_list_count = p_splits;
  6542. draw_list_split = true;
  6543. for (uint32_t i = 0; i < p_splits; i++) {
  6544. //take a command buffer and initialize it
  6545. VkCommandBuffer command_buffer = split_draw_list_allocators[i].command_buffers[frame];
  6546. VkCommandBufferInheritanceInfo inheritance_info;
  6547. inheritance_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO;
  6548. inheritance_info.pNext = nullptr;
  6549. inheritance_info.renderPass = draw_list_render_pass;
  6550. inheritance_info.subpass = p_subpass;
  6551. inheritance_info.framebuffer = draw_list_vkframebuffer;
  6552. inheritance_info.occlusionQueryEnable = false;
  6553. inheritance_info.queryFlags = 0; //?
  6554. inheritance_info.pipelineStatistics = 0;
  6555. VkCommandBufferBeginInfo cmdbuf_begin;
  6556. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  6557. cmdbuf_begin.pNext = nullptr;
  6558. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT;
  6559. cmdbuf_begin.pInheritanceInfo = &inheritance_info;
  6560. VkResult res = vkResetCommandBuffer(command_buffer, 0);
  6561. if (res) {
  6562. memdelete_arr(draw_list);
  6563. draw_list = nullptr;
  6564. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "vkResetCommandBuffer failed with error " + itos(res) + ".");
  6565. }
  6566. res = vkBeginCommandBuffer(command_buffer, &cmdbuf_begin);
  6567. if (res) {
  6568. memdelete_arr(draw_list);
  6569. draw_list = nullptr;
  6570. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "vkBeginCommandBuffer failed with error " + itos(res) + ".");
  6571. }
  6572. draw_list[i].command_buffer = command_buffer;
  6573. draw_list[i].viewport = p_viewport;
  6574. }
  6575. }
  6576. return OK;
  6577. }
  6578. void RenderingDeviceVulkan::_draw_list_free(Rect2i *r_last_viewport) {
  6579. if (draw_list_split) {
  6580. //send all command buffers
  6581. VkCommandBuffer *command_buffers = (VkCommandBuffer *)alloca(sizeof(VkCommandBuffer) * draw_list_count);
  6582. for (uint32_t i = 0; i < draw_list_count; i++) {
  6583. vkEndCommandBuffer(draw_list[i].command_buffer);
  6584. command_buffers[i] = draw_list[i].command_buffer;
  6585. if (r_last_viewport) {
  6586. if (i == 0 || draw_list[i].viewport_set) {
  6587. *r_last_viewport = draw_list[i].viewport;
  6588. }
  6589. }
  6590. }
  6591. vkCmdExecuteCommands(frames[frame].draw_command_buffer, draw_list_count, command_buffers);
  6592. memdelete_arr(draw_list);
  6593. draw_list = nullptr;
  6594. } else {
  6595. if (r_last_viewport) {
  6596. *r_last_viewport = draw_list->viewport;
  6597. }
  6598. //just end the list
  6599. memdelete(draw_list);
  6600. draw_list = nullptr;
  6601. }
  6602. // draw_list is no longer active
  6603. _THREAD_SAFE_UNLOCK_
  6604. }
  6605. void RenderingDeviceVulkan::draw_list_end(uint32_t p_post_barrier) {
  6606. _THREAD_SAFE_METHOD_
  6607. ERR_FAIL_COND_MSG(!draw_list, "Immediate draw list is already inactive.");
  6608. _draw_list_free();
  6609. vkCmdEndRenderPass(frames[frame].draw_command_buffer);
  6610. for (int i = 0; i < draw_list_bound_textures.size(); i++) {
  6611. Texture *texture = texture_owner.get_or_null(draw_list_bound_textures[i]);
  6612. ERR_CONTINUE(!texture); //wtf
  6613. if (draw_list_unbind_color_textures && (texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) {
  6614. texture->bound = false;
  6615. }
  6616. if (draw_list_unbind_depth_textures && (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  6617. texture->bound = false;
  6618. }
  6619. }
  6620. uint32_t barrier_flags = 0;
  6621. uint32_t access_flags = 0;
  6622. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  6623. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  6624. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6625. }
  6626. if (p_post_barrier & BARRIER_MASK_RASTER) {
  6627. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT /*| VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT*/;
  6628. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT /*| VK_ACCESS_INDIRECT_COMMAND_READ_BIT*/;
  6629. }
  6630. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  6631. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  6632. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  6633. }
  6634. if (barrier_flags == 0) {
  6635. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  6636. }
  6637. draw_list_bound_textures.clear();
  6638. VkImageMemoryBarrier *image_barriers = nullptr;
  6639. uint32_t image_barrier_count = draw_list_storage_textures.size();
  6640. if (image_barrier_count) {
  6641. image_barriers = (VkImageMemoryBarrier *)alloca(sizeof(VkImageMemoryBarrier) * draw_list_storage_textures.size());
  6642. }
  6643. uint32_t src_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  6644. uint32_t src_access = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  6645. if (image_barrier_count) {
  6646. src_stage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  6647. src_access |= VK_ACCESS_SHADER_WRITE_BIT;
  6648. }
  6649. for (uint32_t i = 0; i < image_barrier_count; i++) {
  6650. Texture *texture = texture_owner.get_or_null(draw_list_storage_textures[i]);
  6651. VkImageMemoryBarrier &image_memory_barrier = image_barriers[i];
  6652. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  6653. image_memory_barrier.pNext = nullptr;
  6654. image_memory_barrier.srcAccessMask = src_access;
  6655. image_memory_barrier.dstAccessMask = access_flags;
  6656. image_memory_barrier.oldLayout = texture->layout;
  6657. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  6658. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6659. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6660. image_memory_barrier.image = texture->image;
  6661. image_memory_barrier.subresourceRange.aspectMask = texture->read_aspect_mask;
  6662. image_memory_barrier.subresourceRange.baseMipLevel = texture->base_mipmap;
  6663. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  6664. image_memory_barrier.subresourceRange.baseArrayLayer = texture->base_layer;
  6665. image_memory_barrier.subresourceRange.layerCount = texture->layers;
  6666. texture->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  6667. }
  6668. draw_list_storage_textures.clear();
  6669. // To ensure proper synchronization, we must make sure rendering is done before:
  6670. // * Some buffer is copied
  6671. // * Another render pass happens (since we may be done)
  6672. #ifdef FORCE_FULL_BARRIER
  6673. _full_barrier(true);
  6674. #else
  6675. VkMemoryBarrier mem_barrier;
  6676. mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  6677. mem_barrier.pNext = nullptr;
  6678. mem_barrier.srcAccessMask = src_access;
  6679. mem_barrier.dstAccessMask = access_flags;
  6680. if (image_barrier_count > 0 || p_post_barrier != BARRIER_MASK_NO_BARRIER) {
  6681. vkCmdPipelineBarrier(frames[frame].draw_command_buffer, src_stage, barrier_flags, 0, 1, &mem_barrier, 0, nullptr, image_barrier_count, image_barriers);
  6682. }
  6683. #endif
  6684. }
  6685. /***********************/
  6686. /**** COMPUTE LISTS ****/
  6687. /***********************/
  6688. RenderingDevice::ComputeListID RenderingDeviceVulkan::compute_list_begin(bool p_allow_draw_overlap) {
  6689. ERR_FAIL_COND_V_MSG(!p_allow_draw_overlap && draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  6690. ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  6691. // Lock while compute_list is active
  6692. _THREAD_SAFE_LOCK_
  6693. compute_list = memnew(ComputeList);
  6694. compute_list->command_buffer = frames[frame].draw_command_buffer;
  6695. compute_list->state.allow_draw_overlap = p_allow_draw_overlap;
  6696. return ID_TYPE_COMPUTE_LIST;
  6697. }
  6698. void RenderingDeviceVulkan::compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline) {
  6699. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6700. ERR_FAIL_COND(!compute_list);
  6701. ComputeList *cl = compute_list;
  6702. const ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_compute_pipeline);
  6703. ERR_FAIL_COND(!pipeline);
  6704. if (p_compute_pipeline == cl->state.pipeline) {
  6705. return; //redundant state, return.
  6706. }
  6707. cl->state.pipeline = p_compute_pipeline;
  6708. cl->state.pipeline_layout = pipeline->pipeline_layout;
  6709. vkCmdBindPipeline(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline->pipeline);
  6710. if (cl->state.pipeline_shader != pipeline->shader) {
  6711. // shader changed, so descriptor sets may become incompatible.
  6712. //go through ALL sets, and unbind them (and all those above) if the format is different
  6713. uint32_t pcount = pipeline->set_formats.size(); //formats count in this pipeline
  6714. cl->state.set_count = MAX(cl->state.set_count, pcount);
  6715. const uint32_t *pformats = pipeline->set_formats.ptr(); //pipeline set formats
  6716. bool sets_valid = true; //once invalid, all above become invalid
  6717. for (uint32_t i = 0; i < pcount; i++) {
  6718. //if a part of the format is different, invalidate it (and the rest)
  6719. if (!sets_valid || cl->state.sets[i].pipeline_expected_format != pformats[i]) {
  6720. cl->state.sets[i].bound = false;
  6721. cl->state.sets[i].pipeline_expected_format = pformats[i];
  6722. sets_valid = false;
  6723. }
  6724. }
  6725. for (uint32_t i = pcount; i < cl->state.set_count; i++) {
  6726. //unbind the ones above (not used) if exist
  6727. cl->state.sets[i].bound = false;
  6728. }
  6729. cl->state.set_count = pcount; //update set count
  6730. if (pipeline->push_constant_size) {
  6731. cl->state.pipeline_push_constant_stages = pipeline->push_constant_stages;
  6732. #ifdef DEBUG_ENABLED
  6733. cl->validation.pipeline_push_constant_supplied = false;
  6734. #endif
  6735. }
  6736. cl->state.pipeline_shader = pipeline->shader;
  6737. cl->state.local_group_size[0] = pipeline->local_group_size[0];
  6738. cl->state.local_group_size[1] = pipeline->local_group_size[1];
  6739. cl->state.local_group_size[2] = pipeline->local_group_size[2];
  6740. }
  6741. #ifdef DEBUG_ENABLED
  6742. //update compute pass pipeline info
  6743. cl->validation.pipeline_active = true;
  6744. cl->validation.pipeline_push_constant_size = pipeline->push_constant_size;
  6745. #endif
  6746. }
  6747. void RenderingDeviceVulkan::compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index) {
  6748. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6749. ERR_FAIL_COND(!compute_list);
  6750. ComputeList *cl = compute_list;
  6751. #ifdef DEBUG_ENABLED
  6752. ERR_FAIL_COND_MSG(p_index >= limits.maxBoundDescriptorSets || p_index >= MAX_UNIFORM_SETS,
  6753. "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(limits.maxBoundDescriptorSets) + ").");
  6754. #endif
  6755. #ifdef DEBUG_ENABLED
  6756. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  6757. #endif
  6758. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_uniform_set);
  6759. ERR_FAIL_COND(!uniform_set);
  6760. if (p_index > cl->state.set_count) {
  6761. cl->state.set_count = p_index;
  6762. }
  6763. cl->state.sets[p_index].descriptor_set = uniform_set->descriptor_set; //update set pointer
  6764. cl->state.sets[p_index].bound = false; //needs rebind
  6765. cl->state.sets[p_index].uniform_set_format = uniform_set->format;
  6766. cl->state.sets[p_index].uniform_set = p_uniform_set;
  6767. uint32_t textures_to_sampled_count = uniform_set->mutable_sampled_textures.size();
  6768. uint32_t textures_to_storage_count = uniform_set->mutable_storage_textures.size();
  6769. Texture **textures_to_sampled = uniform_set->mutable_sampled_textures.ptrw();
  6770. VkImageMemoryBarrier *texture_barriers = nullptr;
  6771. if (textures_to_sampled_count + textures_to_storage_count) {
  6772. texture_barriers = (VkImageMemoryBarrier *)alloca(sizeof(VkImageMemoryBarrier) * (textures_to_sampled_count + textures_to_storage_count));
  6773. }
  6774. uint32_t texture_barrier_count = 0;
  6775. uint32_t src_stage_flags = 0;
  6776. for (uint32_t i = 0; i < textures_to_sampled_count; i++) {
  6777. if (textures_to_sampled[i]->layout != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
  6778. src_stage_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  6779. VkImageMemoryBarrier &image_memory_barrier = texture_barriers[texture_barrier_count++];
  6780. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  6781. image_memory_barrier.pNext = nullptr;
  6782. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6783. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6784. image_memory_barrier.oldLayout = textures_to_sampled[i]->layout;
  6785. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  6786. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6787. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6788. image_memory_barrier.image = textures_to_sampled[i]->image;
  6789. image_memory_barrier.subresourceRange.aspectMask = textures_to_sampled[i]->read_aspect_mask;
  6790. image_memory_barrier.subresourceRange.baseMipLevel = textures_to_sampled[i]->base_mipmap;
  6791. image_memory_barrier.subresourceRange.levelCount = textures_to_sampled[i]->mipmaps;
  6792. image_memory_barrier.subresourceRange.baseArrayLayer = textures_to_sampled[i]->base_layer;
  6793. image_memory_barrier.subresourceRange.layerCount = textures_to_sampled[i]->layers;
  6794. textures_to_sampled[i]->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  6795. cl->state.textures_to_sampled_layout.erase(textures_to_sampled[i]);
  6796. }
  6797. if (textures_to_sampled[i]->used_in_frame != frames_drawn) {
  6798. textures_to_sampled[i]->used_in_frame = frames_drawn;
  6799. textures_to_sampled[i]->used_in_transfer = false;
  6800. textures_to_sampled[i]->used_in_raster = false;
  6801. }
  6802. textures_to_sampled[i]->used_in_compute = true;
  6803. }
  6804. Texture **textures_to_storage = uniform_set->mutable_storage_textures.ptrw();
  6805. for (uint32_t i = 0; i < textures_to_storage_count; i++) {
  6806. if (textures_to_storage[i]->layout != VK_IMAGE_LAYOUT_GENERAL) {
  6807. uint32_t src_access_flags = 0;
  6808. if (textures_to_storage[i]->used_in_frame == frames_drawn) {
  6809. if (textures_to_storage[i]->used_in_compute) {
  6810. src_stage_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  6811. src_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6812. }
  6813. if (textures_to_storage[i]->used_in_raster) {
  6814. src_stage_flags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT;
  6815. src_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6816. }
  6817. if (textures_to_storage[i]->used_in_transfer) {
  6818. src_stage_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  6819. src_access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  6820. }
  6821. textures_to_storage[i]->used_in_compute = false;
  6822. textures_to_storage[i]->used_in_raster = false;
  6823. textures_to_storage[i]->used_in_transfer = false;
  6824. } else {
  6825. src_access_flags = 0;
  6826. textures_to_storage[i]->used_in_compute = false;
  6827. textures_to_storage[i]->used_in_raster = false;
  6828. textures_to_storage[i]->used_in_transfer = false;
  6829. textures_to_storage[i]->used_in_frame = frames_drawn;
  6830. }
  6831. VkImageMemoryBarrier &image_memory_barrier = texture_barriers[texture_barrier_count++];
  6832. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  6833. image_memory_barrier.pNext = nullptr;
  6834. image_memory_barrier.srcAccessMask = src_access_flags;
  6835. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6836. image_memory_barrier.oldLayout = textures_to_storage[i]->layout;
  6837. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  6838. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6839. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6840. image_memory_barrier.image = textures_to_storage[i]->image;
  6841. image_memory_barrier.subresourceRange.aspectMask = textures_to_storage[i]->read_aspect_mask;
  6842. image_memory_barrier.subresourceRange.baseMipLevel = textures_to_storage[i]->base_mipmap;
  6843. image_memory_barrier.subresourceRange.levelCount = textures_to_storage[i]->mipmaps;
  6844. image_memory_barrier.subresourceRange.baseArrayLayer = textures_to_storage[i]->base_layer;
  6845. image_memory_barrier.subresourceRange.layerCount = textures_to_storage[i]->layers;
  6846. textures_to_storage[i]->layout = VK_IMAGE_LAYOUT_GENERAL;
  6847. cl->state.textures_to_sampled_layout.insert(textures_to_storage[i]); //needs to go back to sampled layout afterwards
  6848. }
  6849. }
  6850. if (texture_barrier_count) {
  6851. if (src_stage_flags == 0) {
  6852. src_stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  6853. }
  6854. vkCmdPipelineBarrier(cl->command_buffer, src_stage_flags, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, texture_barrier_count, texture_barriers);
  6855. }
  6856. #if 0
  6857. { //validate that textures bound are not attached as framebuffer bindings
  6858. uint32_t attachable_count = uniform_set->attachable_textures.size();
  6859. const RID *attachable_ptr = uniform_set->attachable_textures.ptr();
  6860. uint32_t bound_count = draw_list_bound_textures.size();
  6861. const RID *bound_ptr = draw_list_bound_textures.ptr();
  6862. for (uint32_t i = 0; i < attachable_count; i++) {
  6863. for (uint32_t j = 0; j < bound_count; j++) {
  6864. ERR_FAIL_COND_MSG(attachable_ptr[i] == bound_ptr[j],
  6865. "Attempted to use the same texture in framebuffer attachment and a uniform set, this is not allowed.");
  6866. }
  6867. }
  6868. }
  6869. #endif
  6870. }
  6871. void RenderingDeviceVulkan::compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size) {
  6872. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6873. ERR_FAIL_COND(!compute_list);
  6874. ComputeList *cl = compute_list;
  6875. #ifdef DEBUG_ENABLED
  6876. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  6877. #endif
  6878. #ifdef DEBUG_ENABLED
  6879. ERR_FAIL_COND_MSG(p_data_size != cl->validation.pipeline_push_constant_size,
  6880. "This compute pipeline requires (" + itos(cl->validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")");
  6881. #endif
  6882. vkCmdPushConstants(cl->command_buffer, cl->state.pipeline_layout, cl->state.pipeline_push_constant_stages, 0, p_data_size, p_data);
  6883. #ifdef DEBUG_ENABLED
  6884. cl->validation.pipeline_push_constant_supplied = true;
  6885. #endif
  6886. }
  6887. void RenderingDeviceVulkan::compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) {
  6888. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6889. ERR_FAIL_COND(!compute_list);
  6890. ComputeList *cl = compute_list;
  6891. #ifdef DEBUG_ENABLED
  6892. ERR_FAIL_COND_MSG(p_x_groups == 0, "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is zero.");
  6893. ERR_FAIL_COND_MSG(p_z_groups == 0, "Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is zero.");
  6894. ERR_FAIL_COND_MSG(p_y_groups == 0, "Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is zero.");
  6895. ERR_FAIL_COND_MSG(p_x_groups > limits.maxComputeWorkGroupCount[0],
  6896. "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[0]) + ")");
  6897. ERR_FAIL_COND_MSG(p_y_groups > limits.maxComputeWorkGroupCount[1],
  6898. "Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[1]) + ")");
  6899. ERR_FAIL_COND_MSG(p_z_groups > limits.maxComputeWorkGroupCount[2],
  6900. "Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[2]) + ")");
  6901. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  6902. #endif
  6903. #ifdef DEBUG_ENABLED
  6904. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  6905. if (cl->validation.pipeline_push_constant_size > 0) {
  6906. //using push constants, check that they were supplied
  6907. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  6908. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  6909. }
  6910. #endif
  6911. //Bind descriptor sets
  6912. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  6913. if (cl->state.sets[i].pipeline_expected_format == 0) {
  6914. continue; //nothing expected by this pipeline
  6915. }
  6916. #ifdef DEBUG_ENABLED
  6917. if (cl->state.sets[i].pipeline_expected_format != cl->state.sets[i].uniform_set_format) {
  6918. if (cl->state.sets[i].uniform_set_format == 0) {
  6919. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline");
  6920. } else if (uniform_set_owner.owns(cl->state.sets[i].uniform_set)) {
  6921. UniformSet *us = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set);
  6922. 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));
  6923. } else {
  6924. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was 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));
  6925. }
  6926. }
  6927. #endif
  6928. if (!cl->state.sets[i].bound) {
  6929. //All good, see if this requires re-binding
  6930. vkCmdBindDescriptorSets(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, cl->state.pipeline_layout, i, 1, &cl->state.sets[i].descriptor_set, 0, nullptr);
  6931. cl->state.sets[i].bound = true;
  6932. }
  6933. }
  6934. vkCmdDispatch(cl->command_buffer, p_x_groups, p_y_groups, p_z_groups);
  6935. }
  6936. void RenderingDeviceVulkan::compute_list_dispatch_threads(ComputeListID p_list, uint32_t p_x_threads, uint32_t p_y_threads, uint32_t p_z_threads) {
  6937. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6938. ERR_FAIL_COND(!compute_list);
  6939. #ifdef DEBUG_ENABLED
  6940. ERR_FAIL_COND_MSG(p_x_threads == 0, "Dispatch amount of X compute threads (" + itos(p_x_threads) + ") is zero.");
  6941. ERR_FAIL_COND_MSG(p_y_threads == 0, "Dispatch amount of Y compute threads (" + itos(p_y_threads) + ") is zero.");
  6942. ERR_FAIL_COND_MSG(p_z_threads == 0, "Dispatch amount of Z compute threads (" + itos(p_z_threads) + ") is zero.");
  6943. #endif
  6944. ComputeList *cl = compute_list;
  6945. #ifdef DEBUG_ENABLED
  6946. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  6947. if (cl->validation.pipeline_push_constant_size > 0) {
  6948. //using push constants, check that they were supplied
  6949. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  6950. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  6951. }
  6952. #endif
  6953. compute_list_dispatch(p_list, (p_x_threads - 1) / cl->state.local_group_size[0] + 1, (p_y_threads - 1) / cl->state.local_group_size[1] + 1, (p_z_threads - 1) / cl->state.local_group_size[2] + 1);
  6954. }
  6955. void RenderingDeviceVulkan::compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset) {
  6956. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6957. ERR_FAIL_COND(!compute_list);
  6958. ComputeList *cl = compute_list;
  6959. Buffer *buffer = storage_buffer_owner.get_or_null(p_buffer);
  6960. ERR_FAIL_COND(!buffer);
  6961. ERR_FAIL_COND_MSG(!(buffer->usage & STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT), "Buffer provided was not created to do indirect dispatch.");
  6962. ERR_FAIL_COND_MSG(p_offset + 12 > buffer->size, "Offset provided (+12) is past the end of buffer.");
  6963. #ifdef DEBUG_ENABLED
  6964. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  6965. #endif
  6966. #ifdef DEBUG_ENABLED
  6967. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  6968. if (cl->validation.pipeline_push_constant_size > 0) {
  6969. //using push constants, check that they were supplied
  6970. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  6971. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  6972. }
  6973. #endif
  6974. //Bind descriptor sets
  6975. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  6976. if (cl->state.sets[i].pipeline_expected_format == 0) {
  6977. continue; //nothing expected by this pipeline
  6978. }
  6979. #ifdef DEBUG_ENABLED
  6980. if (cl->state.sets[i].pipeline_expected_format != cl->state.sets[i].uniform_set_format) {
  6981. if (cl->state.sets[i].uniform_set_format == 0) {
  6982. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline");
  6983. } else if (uniform_set_owner.owns(cl->state.sets[i].uniform_set)) {
  6984. UniformSet *us = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set);
  6985. 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));
  6986. } else {
  6987. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was 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));
  6988. }
  6989. }
  6990. #endif
  6991. if (!cl->state.sets[i].bound) {
  6992. //All good, see if this requires re-binding
  6993. vkCmdBindDescriptorSets(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, cl->state.pipeline_layout, i, 1, &cl->state.sets[i].descriptor_set, 0, nullptr);
  6994. cl->state.sets[i].bound = true;
  6995. }
  6996. }
  6997. vkCmdDispatchIndirect(cl->command_buffer, buffer->buffer, p_offset);
  6998. }
  6999. void RenderingDeviceVulkan::compute_list_add_barrier(ComputeListID p_list) {
  7000. #ifdef FORCE_FULL_BARRIER
  7001. _full_barrier(true);
  7002. #else
  7003. _memory_barrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, true);
  7004. #endif
  7005. }
  7006. void RenderingDeviceVulkan::compute_list_end(uint32_t p_post_barrier) {
  7007. ERR_FAIL_COND(!compute_list);
  7008. uint32_t barrier_flags = 0;
  7009. uint32_t access_flags = 0;
  7010. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  7011. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  7012. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7013. }
  7014. if (p_post_barrier & BARRIER_MASK_RASTER) {
  7015. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
  7016. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
  7017. }
  7018. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  7019. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  7020. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  7021. }
  7022. if (barrier_flags == 0) {
  7023. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  7024. }
  7025. VkImageMemoryBarrier *image_barriers = nullptr;
  7026. uint32_t image_barrier_count = compute_list->state.textures_to_sampled_layout.size();
  7027. if (image_barrier_count) {
  7028. image_barriers = (VkImageMemoryBarrier *)alloca(sizeof(VkImageMemoryBarrier) * image_barrier_count);
  7029. }
  7030. uint32_t barrier_idx = 0;
  7031. for (Texture *E : compute_list->state.textures_to_sampled_layout) {
  7032. VkImageMemoryBarrier &image_memory_barrier = image_barriers[barrier_idx++];
  7033. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  7034. image_memory_barrier.pNext = nullptr;
  7035. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7036. image_memory_barrier.dstAccessMask = access_flags;
  7037. image_memory_barrier.oldLayout = E->layout;
  7038. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  7039. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  7040. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  7041. image_memory_barrier.image = E->image;
  7042. image_memory_barrier.subresourceRange.aspectMask = E->read_aspect_mask;
  7043. image_memory_barrier.subresourceRange.baseMipLevel = E->base_mipmap;
  7044. image_memory_barrier.subresourceRange.levelCount = E->mipmaps;
  7045. image_memory_barrier.subresourceRange.baseArrayLayer = E->base_layer;
  7046. image_memory_barrier.subresourceRange.layerCount = E->layers;
  7047. E->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  7048. if (E->used_in_frame != frames_drawn) {
  7049. E->used_in_transfer = false;
  7050. E->used_in_raster = false;
  7051. E->used_in_compute = false;
  7052. E->used_in_frame = frames_drawn;
  7053. }
  7054. }
  7055. #ifdef FORCE_FULL_BARRIER
  7056. _full_barrier(true);
  7057. #else
  7058. VkMemoryBarrier mem_barrier;
  7059. mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  7060. mem_barrier.pNext = nullptr;
  7061. mem_barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
  7062. mem_barrier.dstAccessMask = access_flags;
  7063. if (image_barrier_count > 0 || p_post_barrier != BARRIER_MASK_NO_BARRIER) {
  7064. vkCmdPipelineBarrier(compute_list->command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, barrier_flags, 0, 1, &mem_barrier, 0, nullptr, image_barrier_count, image_barriers);
  7065. }
  7066. #endif
  7067. memdelete(compute_list);
  7068. compute_list = nullptr;
  7069. // compute_list is no longer active
  7070. _THREAD_SAFE_UNLOCK_
  7071. }
  7072. void RenderingDeviceVulkan::barrier(uint32_t p_from, uint32_t p_to) {
  7073. uint32_t src_barrier_flags = 0;
  7074. uint32_t src_access_flags = 0;
  7075. if (p_from & BARRIER_MASK_COMPUTE) {
  7076. src_barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  7077. src_access_flags |= VK_ACCESS_SHADER_WRITE_BIT;
  7078. }
  7079. if (p_from & BARRIER_MASK_RASTER) {
  7080. src_barrier_flags |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  7081. src_access_flags |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  7082. }
  7083. if (p_from & BARRIER_MASK_TRANSFER) {
  7084. src_barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  7085. src_access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  7086. }
  7087. if (p_from == 0) {
  7088. src_barrier_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  7089. }
  7090. uint32_t dst_barrier_flags = 0;
  7091. uint32_t dst_access_flags = 0;
  7092. if (p_to & BARRIER_MASK_COMPUTE) {
  7093. dst_barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  7094. dst_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7095. }
  7096. if (p_to & BARRIER_MASK_RASTER) {
  7097. dst_barrier_flags |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
  7098. dst_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
  7099. }
  7100. if (p_to & BARRIER_MASK_TRANSFER) {
  7101. dst_barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  7102. dst_access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  7103. }
  7104. if (p_to == 0) {
  7105. dst_barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  7106. }
  7107. _memory_barrier(src_barrier_flags, dst_barrier_flags, src_access_flags, dst_access_flags, true);
  7108. }
  7109. void RenderingDeviceVulkan::full_barrier() {
  7110. #ifndef DEBUG_ENABLED
  7111. ERR_PRINT("Full barrier is debug-only, should not be used in production");
  7112. #endif
  7113. _full_barrier(true);
  7114. }
  7115. #if 0
  7116. void RenderingDeviceVulkan::draw_list_render_secondary_to_framebuffer(ID p_framebuffer, ID *p_draw_lists, uint32_t p_draw_list_count, InitialAction p_initial_action, FinalAction p_final_action, const Vector<Variant> &p_clear_colors) {
  7117. VkCommandBuffer frame_cmdbuf = frames[frame].frame_buffer;
  7118. ERR_FAIL_COND(!frame_cmdbuf);
  7119. VkRenderPassBeginInfo render_pass_begin;
  7120. render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  7121. render_pass_begin.pNext = nullptr;
  7122. render_pass_begin.renderPass = context->get_render_pass();
  7123. render_pass_begin.framebuffer = context->get_frame_framebuffer(frame);
  7124. render_pass_begin.renderArea.extent.width = context->get_screen_width(p_screen);
  7125. render_pass_begin.renderArea.extent.height = context->get_screen_height(p_screen);
  7126. render_pass_begin.renderArea.offset.x = 0;
  7127. render_pass_begin.renderArea.offset.y = 0;
  7128. render_pass_begin.clearValueCount = 1;
  7129. VkClearValue clear_value;
  7130. clear_value.color.float32[0] = p_clear_color.r;
  7131. clear_value.color.float32[1] = p_clear_color.g;
  7132. clear_value.color.float32[2] = p_clear_color.b;
  7133. clear_value.color.float32[3] = p_clear_color.a;
  7134. render_pass_begin.pClearValues = &clear_value;
  7135. vkCmdBeginRenderPass(frame_cmdbuf, &render_pass_begin, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS);
  7136. ID screen_format = screen_get_framebuffer_format();
  7137. {
  7138. VkCommandBuffer *command_buffers = (VkCommandBuffer *)alloca(sizeof(VkCommandBuffer) * p_draw_list_count);
  7139. uint32_t command_buffer_count = 0;
  7140. for (uint32_t i = 0; i < p_draw_list_count; i++) {
  7141. DrawList *dl = _get_draw_list_ptr(p_draw_lists[i]);
  7142. ERR_CONTINUE_MSG(!dl, "Draw list index (" + itos(i) + ") is not a valid draw list ID.");
  7143. ERR_CONTINUE_MSG(dl->validation.framebuffer_format != p_format_check,
  7144. "Draw list index (" + itos(i) + ") is created with a framebuffer format incompatible with this render pass.");
  7145. if (dl->validation.active) {
  7146. //needs to be closed, so close it.
  7147. vkEndCommandBuffer(dl->command_buffer);
  7148. dl->validation.active = false;
  7149. }
  7150. command_buffers[command_buffer_count++] = dl->command_buffer;
  7151. }
  7152. print_line("to draw: " + itos(command_buffer_count));
  7153. vkCmdExecuteCommands(p_primary, command_buffer_count, command_buffers);
  7154. }
  7155. vkCmdEndRenderPass(frame_cmdbuf);
  7156. }
  7157. #endif
  7158. void RenderingDeviceVulkan::_free_internal(RID p_id) {
  7159. //push everything so it's disposed of next time this frame index is processed (means, it's safe to do it)
  7160. if (texture_owner.owns(p_id)) {
  7161. Texture *texture = texture_owner.get_or_null(p_id);
  7162. frames[frame].textures_to_dispose_of.push_back(*texture);
  7163. texture_owner.free(p_id);
  7164. } else if (framebuffer_owner.owns(p_id)) {
  7165. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_id);
  7166. frames[frame].framebuffers_to_dispose_of.push_back(*framebuffer);
  7167. framebuffer_owner.free(p_id);
  7168. } else if (sampler_owner.owns(p_id)) {
  7169. VkSampler *sampler = sampler_owner.get_or_null(p_id);
  7170. frames[frame].samplers_to_dispose_of.push_back(*sampler);
  7171. sampler_owner.free(p_id);
  7172. } else if (vertex_buffer_owner.owns(p_id)) {
  7173. Buffer *vertex_buffer = vertex_buffer_owner.get_or_null(p_id);
  7174. frames[frame].buffers_to_dispose_of.push_back(*vertex_buffer);
  7175. vertex_buffer_owner.free(p_id);
  7176. } else if (vertex_array_owner.owns(p_id)) {
  7177. vertex_array_owner.free(p_id);
  7178. } else if (index_buffer_owner.owns(p_id)) {
  7179. IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_id);
  7180. Buffer b;
  7181. b.allocation = index_buffer->allocation;
  7182. b.buffer = index_buffer->buffer;
  7183. b.size = index_buffer->size;
  7184. b.buffer_info = {};
  7185. frames[frame].buffers_to_dispose_of.push_back(b);
  7186. index_buffer_owner.free(p_id);
  7187. } else if (index_array_owner.owns(p_id)) {
  7188. index_array_owner.free(p_id);
  7189. } else if (shader_owner.owns(p_id)) {
  7190. Shader *shader = shader_owner.get_or_null(p_id);
  7191. frames[frame].shaders_to_dispose_of.push_back(*shader);
  7192. shader_owner.free(p_id);
  7193. } else if (uniform_buffer_owner.owns(p_id)) {
  7194. Buffer *uniform_buffer = uniform_buffer_owner.get_or_null(p_id);
  7195. frames[frame].buffers_to_dispose_of.push_back(*uniform_buffer);
  7196. uniform_buffer_owner.free(p_id);
  7197. } else if (texture_buffer_owner.owns(p_id)) {
  7198. TextureBuffer *texture_buffer = texture_buffer_owner.get_or_null(p_id);
  7199. frames[frame].buffers_to_dispose_of.push_back(texture_buffer->buffer);
  7200. frames[frame].buffer_views_to_dispose_of.push_back(texture_buffer->view);
  7201. texture_buffer_owner.free(p_id);
  7202. } else if (storage_buffer_owner.owns(p_id)) {
  7203. Buffer *storage_buffer = storage_buffer_owner.get_or_null(p_id);
  7204. frames[frame].buffers_to_dispose_of.push_back(*storage_buffer);
  7205. storage_buffer_owner.free(p_id);
  7206. } else if (uniform_set_owner.owns(p_id)) {
  7207. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id);
  7208. frames[frame].uniform_sets_to_dispose_of.push_back(*uniform_set);
  7209. uniform_set_owner.free(p_id);
  7210. if (uniform_set->invalidated_callback != nullptr) {
  7211. uniform_set->invalidated_callback(uniform_set->invalidated_callback_userdata);
  7212. }
  7213. } else if (render_pipeline_owner.owns(p_id)) {
  7214. RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_id);
  7215. frames[frame].render_pipelines_to_dispose_of.push_back(*pipeline);
  7216. render_pipeline_owner.free(p_id);
  7217. } else if (compute_pipeline_owner.owns(p_id)) {
  7218. ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_id);
  7219. frames[frame].compute_pipelines_to_dispose_of.push_back(*pipeline);
  7220. compute_pipeline_owner.free(p_id);
  7221. } else {
  7222. ERR_PRINT("Attempted to free invalid ID: " + itos(p_id.get_id()));
  7223. }
  7224. }
  7225. void RenderingDeviceVulkan::free(RID p_id) {
  7226. _THREAD_SAFE_METHOD_
  7227. _free_dependencies(p_id); //recursively erase dependencies first, to avoid potential API problems
  7228. _free_internal(p_id);
  7229. }
  7230. // The full list of resources that can be named is in the VkObjectType enum
  7231. // We just expose the resources that are owned and can be accessed easily.
  7232. void RenderingDeviceVulkan::set_resource_name(RID p_id, const String p_name) {
  7233. if (texture_owner.owns(p_id)) {
  7234. Texture *texture = texture_owner.get_or_null(p_id);
  7235. if (texture->owner.is_null()) {
  7236. // Don't set the source texture's name when calling on a texture view
  7237. context->set_object_name(VK_OBJECT_TYPE_IMAGE, uint64_t(texture->image), p_name);
  7238. }
  7239. context->set_object_name(VK_OBJECT_TYPE_IMAGE_VIEW, uint64_t(texture->view), p_name + " View");
  7240. } else if (framebuffer_owner.owns(p_id)) {
  7241. //Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_id);
  7242. // Not implemented for now as the relationship between Framebuffer and RenderPass is very complex
  7243. } else if (sampler_owner.owns(p_id)) {
  7244. VkSampler *sampler = sampler_owner.get_or_null(p_id);
  7245. context->set_object_name(VK_OBJECT_TYPE_SAMPLER, uint64_t(*sampler), p_name);
  7246. } else if (vertex_buffer_owner.owns(p_id)) {
  7247. Buffer *vertex_buffer = vertex_buffer_owner.get_or_null(p_id);
  7248. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(vertex_buffer->buffer), p_name);
  7249. } else if (index_buffer_owner.owns(p_id)) {
  7250. IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_id);
  7251. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(index_buffer->buffer), p_name);
  7252. } else if (shader_owner.owns(p_id)) {
  7253. Shader *shader = shader_owner.get_or_null(p_id);
  7254. context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, uint64_t(shader->pipeline_layout), p_name + " Pipeline Layout");
  7255. for (int i = 0; i < shader->sets.size(); i++) {
  7256. context->set_object_name(VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, uint64_t(shader->sets[i].descriptor_set_layout), p_name);
  7257. }
  7258. } else if (uniform_buffer_owner.owns(p_id)) {
  7259. Buffer *uniform_buffer = uniform_buffer_owner.get_or_null(p_id);
  7260. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(uniform_buffer->buffer), p_name);
  7261. } else if (texture_buffer_owner.owns(p_id)) {
  7262. TextureBuffer *texture_buffer = texture_buffer_owner.get_or_null(p_id);
  7263. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(texture_buffer->buffer.buffer), p_name);
  7264. context->set_object_name(VK_OBJECT_TYPE_BUFFER_VIEW, uint64_t(texture_buffer->view), p_name + " View");
  7265. } else if (storage_buffer_owner.owns(p_id)) {
  7266. Buffer *storage_buffer = storage_buffer_owner.get_or_null(p_id);
  7267. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(storage_buffer->buffer), p_name);
  7268. } else if (uniform_set_owner.owns(p_id)) {
  7269. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id);
  7270. context->set_object_name(VK_OBJECT_TYPE_DESCRIPTOR_SET, uint64_t(uniform_set->descriptor_set), p_name);
  7271. } else if (render_pipeline_owner.owns(p_id)) {
  7272. RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_id);
  7273. context->set_object_name(VK_OBJECT_TYPE_PIPELINE, uint64_t(pipeline->pipeline), p_name);
  7274. context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, uint64_t(pipeline->pipeline_layout), p_name + " Layout");
  7275. } else if (compute_pipeline_owner.owns(p_id)) {
  7276. ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_id);
  7277. context->set_object_name(VK_OBJECT_TYPE_PIPELINE, uint64_t(pipeline->pipeline), p_name);
  7278. context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, uint64_t(pipeline->pipeline_layout), p_name + " Layout");
  7279. } else {
  7280. ERR_PRINT("Attempted to name invalid ID: " + itos(p_id.get_id()));
  7281. }
  7282. }
  7283. void RenderingDeviceVulkan::draw_command_begin_label(String p_label_name, const Color p_color) {
  7284. context->command_begin_label(frames[frame].draw_command_buffer, p_label_name, p_color);
  7285. }
  7286. void RenderingDeviceVulkan::draw_command_insert_label(String p_label_name, const Color p_color) {
  7287. context->command_insert_label(frames[frame].draw_command_buffer, p_label_name, p_color);
  7288. }
  7289. void RenderingDeviceVulkan::draw_command_end_label() {
  7290. context->command_end_label(frames[frame].draw_command_buffer);
  7291. }
  7292. String RenderingDeviceVulkan::get_device_vendor_name() const {
  7293. return context->get_device_vendor_name();
  7294. }
  7295. String RenderingDeviceVulkan::get_device_name() const {
  7296. return context->get_device_name();
  7297. }
  7298. RenderingDevice::DeviceType RenderingDeviceVulkan::get_device_type() const {
  7299. return context->get_device_type();
  7300. }
  7301. String RenderingDeviceVulkan::get_device_api_version() const {
  7302. return context->get_device_api_version();
  7303. }
  7304. String RenderingDeviceVulkan::get_device_pipeline_cache_uuid() const {
  7305. return context->get_device_pipeline_cache_uuid();
  7306. }
  7307. void RenderingDeviceVulkan::_finalize_command_bufers() {
  7308. if (draw_list) {
  7309. ERR_PRINT("Found open draw list at the end of the frame, this should never happen (further drawing will likely not work).");
  7310. }
  7311. if (compute_list) {
  7312. ERR_PRINT("Found open compute list at the end of the frame, this should never happen (further compute will likely not work).");
  7313. }
  7314. { //complete the setup buffer (that needs to be processed before anything else)
  7315. vkEndCommandBuffer(frames[frame].setup_command_buffer);
  7316. vkEndCommandBuffer(frames[frame].draw_command_buffer);
  7317. }
  7318. }
  7319. void RenderingDeviceVulkan::_begin_frame() {
  7320. //erase pending resources
  7321. _free_pending_resources(frame);
  7322. //create setup command buffer and set as the setup buffer
  7323. {
  7324. VkCommandBufferBeginInfo cmdbuf_begin;
  7325. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7326. cmdbuf_begin.pNext = nullptr;
  7327. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7328. cmdbuf_begin.pInheritanceInfo = nullptr;
  7329. VkResult err = vkResetCommandBuffer(frames[frame].setup_command_buffer, 0);
  7330. ERR_FAIL_COND_MSG(err, "vkResetCommandBuffer failed with error " + itos(err) + ".");
  7331. err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin);
  7332. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7333. err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin);
  7334. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7335. if (local_device.is_null()) {
  7336. context->append_command_buffer(frames[frame].draw_command_buffer);
  7337. context->set_setup_buffer(frames[frame].setup_command_buffer); //append now so it's added before everything else
  7338. }
  7339. }
  7340. //advance current frame
  7341. frames_drawn++;
  7342. //advance staging buffer if used
  7343. if (staging_buffer_used) {
  7344. staging_buffer_current = (staging_buffer_current + 1) % staging_buffer_blocks.size();
  7345. staging_buffer_used = false;
  7346. }
  7347. if (frames[frame].timestamp_count) {
  7348. vkGetQueryPoolResults(device, frames[frame].timestamp_pool, 0, frames[frame].timestamp_count, sizeof(uint64_t) * max_timestamp_query_elements, frames[frame].timestamp_result_values, sizeof(uint64_t), VK_QUERY_RESULT_64_BIT);
  7349. vkCmdResetQueryPool(frames[frame].setup_command_buffer, frames[frame].timestamp_pool, 0, frames[frame].timestamp_count);
  7350. SWAP(frames[frame].timestamp_names, frames[frame].timestamp_result_names);
  7351. SWAP(frames[frame].timestamp_cpu_values, frames[frame].timestamp_cpu_result_values);
  7352. }
  7353. frames[frame].timestamp_result_count = frames[frame].timestamp_count;
  7354. frames[frame].timestamp_count = 0;
  7355. frames[frame].index = Engine::get_singleton()->get_frames_drawn();
  7356. }
  7357. void RenderingDeviceVulkan::swap_buffers() {
  7358. ERR_FAIL_COND_MSG(local_device.is_valid(), "Local devices can't swap buffers.");
  7359. _THREAD_SAFE_METHOD_
  7360. _finalize_command_bufers();
  7361. screen_prepared = false;
  7362. //swap buffers
  7363. context->swap_buffers();
  7364. frame = (frame + 1) % frame_count;
  7365. _begin_frame();
  7366. }
  7367. void RenderingDeviceVulkan::submit() {
  7368. ERR_FAIL_COND_MSG(local_device.is_null(), "Only local devices can submit and sync.");
  7369. ERR_FAIL_COND_MSG(local_device_processing, "device already submitted, call sync to wait until done.");
  7370. _finalize_command_bufers();
  7371. VkCommandBuffer command_buffers[2] = { frames[frame].setup_command_buffer, frames[frame].draw_command_buffer };
  7372. context->local_device_push_command_buffers(local_device, command_buffers, 2);
  7373. local_device_processing = true;
  7374. }
  7375. void RenderingDeviceVulkan::sync() {
  7376. ERR_FAIL_COND_MSG(local_device.is_null(), "Only local devices can submit and sync.");
  7377. ERR_FAIL_COND_MSG(!local_device_processing, "sync can only be called after a submit");
  7378. context->local_device_sync(local_device);
  7379. _begin_frame();
  7380. local_device_processing = false;
  7381. }
  7382. VmaPool RenderingDeviceVulkan::_find_or_create_small_allocs_pool(uint32_t p_mem_type_index) {
  7383. if (small_allocs_pools.has(p_mem_type_index)) {
  7384. return small_allocs_pools[p_mem_type_index];
  7385. }
  7386. print_verbose("Creating VMA small objects pool for memory type index " + itos(p_mem_type_index));
  7387. VmaPoolCreateInfo pci;
  7388. pci.memoryTypeIndex = p_mem_type_index;
  7389. pci.flags = 0;
  7390. pci.blockSize = 0;
  7391. pci.minBlockCount = 0;
  7392. pci.maxBlockCount = SIZE_MAX;
  7393. pci.priority = 0.5f;
  7394. pci.minAllocationAlignment = 0;
  7395. pci.pMemoryAllocateNext = nullptr;
  7396. VmaPool pool = VK_NULL_HANDLE;
  7397. VkResult res = vmaCreatePool(allocator, &pci, &pool);
  7398. small_allocs_pools[p_mem_type_index] = pool; // Don't try to create it again if failed the first time
  7399. ERR_FAIL_COND_V_MSG(res, pool, "vmaCreatePool failed with error " + itos(res) + ".");
  7400. return pool;
  7401. }
  7402. void RenderingDeviceVulkan::_free_pending_resources(int p_frame) {
  7403. //free in dependency usage order, so nothing weird happens
  7404. //pipelines
  7405. while (frames[p_frame].render_pipelines_to_dispose_of.front()) {
  7406. RenderPipeline *pipeline = &frames[p_frame].render_pipelines_to_dispose_of.front()->get();
  7407. vkDestroyPipeline(device, pipeline->pipeline, nullptr);
  7408. frames[p_frame].render_pipelines_to_dispose_of.pop_front();
  7409. }
  7410. while (frames[p_frame].compute_pipelines_to_dispose_of.front()) {
  7411. ComputePipeline *pipeline = &frames[p_frame].compute_pipelines_to_dispose_of.front()->get();
  7412. vkDestroyPipeline(device, pipeline->pipeline, nullptr);
  7413. frames[p_frame].compute_pipelines_to_dispose_of.pop_front();
  7414. }
  7415. //uniform sets
  7416. while (frames[p_frame].uniform_sets_to_dispose_of.front()) {
  7417. UniformSet *uniform_set = &frames[p_frame].uniform_sets_to_dispose_of.front()->get();
  7418. vkFreeDescriptorSets(device, uniform_set->pool->pool, 1, &uniform_set->descriptor_set);
  7419. _descriptor_pool_free(uniform_set->pool_key, uniform_set->pool);
  7420. frames[p_frame].uniform_sets_to_dispose_of.pop_front();
  7421. }
  7422. //buffer views
  7423. while (frames[p_frame].buffer_views_to_dispose_of.front()) {
  7424. VkBufferView buffer_view = frames[p_frame].buffer_views_to_dispose_of.front()->get();
  7425. vkDestroyBufferView(device, buffer_view, nullptr);
  7426. frames[p_frame].buffer_views_to_dispose_of.pop_front();
  7427. }
  7428. //shaders
  7429. while (frames[p_frame].shaders_to_dispose_of.front()) {
  7430. Shader *shader = &frames[p_frame].shaders_to_dispose_of.front()->get();
  7431. //descriptor set layout for each set
  7432. for (int i = 0; i < shader->sets.size(); i++) {
  7433. vkDestroyDescriptorSetLayout(device, shader->sets[i].descriptor_set_layout, nullptr);
  7434. }
  7435. //pipeline layout
  7436. vkDestroyPipelineLayout(device, shader->pipeline_layout, nullptr);
  7437. //shaders themselves
  7438. for (int i = 0; i < shader->pipeline_stages.size(); i++) {
  7439. vkDestroyShaderModule(device, shader->pipeline_stages[i].module, nullptr);
  7440. }
  7441. frames[p_frame].shaders_to_dispose_of.pop_front();
  7442. }
  7443. //samplers
  7444. while (frames[p_frame].samplers_to_dispose_of.front()) {
  7445. VkSampler sampler = frames[p_frame].samplers_to_dispose_of.front()->get();
  7446. vkDestroySampler(device, sampler, nullptr);
  7447. frames[p_frame].samplers_to_dispose_of.pop_front();
  7448. }
  7449. //framebuffers
  7450. while (frames[p_frame].framebuffers_to_dispose_of.front()) {
  7451. Framebuffer *framebuffer = &frames[p_frame].framebuffers_to_dispose_of.front()->get();
  7452. for (const KeyValue<Framebuffer::VersionKey, Framebuffer::Version> &E : framebuffer->framebuffers) {
  7453. //first framebuffer, then render pass because it depends on it
  7454. vkDestroyFramebuffer(device, E.value.framebuffer, nullptr);
  7455. vkDestroyRenderPass(device, E.value.render_pass, nullptr);
  7456. }
  7457. frames[p_frame].framebuffers_to_dispose_of.pop_front();
  7458. }
  7459. //textures
  7460. while (frames[p_frame].textures_to_dispose_of.front()) {
  7461. Texture *texture = &frames[p_frame].textures_to_dispose_of.front()->get();
  7462. if (texture->bound) {
  7463. WARN_PRINT("Deleted a texture while it was bound..");
  7464. }
  7465. vkDestroyImageView(device, texture->view, nullptr);
  7466. if (texture->owner.is_null()) {
  7467. //actually owns the image and the allocation too
  7468. image_memory -= texture->allocation_info.size;
  7469. vmaDestroyImage(allocator, texture->image, texture->allocation);
  7470. }
  7471. frames[p_frame].textures_to_dispose_of.pop_front();
  7472. }
  7473. //buffers
  7474. while (frames[p_frame].buffers_to_dispose_of.front()) {
  7475. _buffer_free(&frames[p_frame].buffers_to_dispose_of.front()->get());
  7476. frames[p_frame].buffers_to_dispose_of.pop_front();
  7477. }
  7478. }
  7479. void RenderingDeviceVulkan::prepare_screen_for_drawing() {
  7480. _THREAD_SAFE_METHOD_
  7481. context->prepare_buffers();
  7482. screen_prepared = true;
  7483. }
  7484. uint32_t RenderingDeviceVulkan::get_frame_delay() const {
  7485. return frame_count;
  7486. }
  7487. uint64_t RenderingDeviceVulkan::get_memory_usage(MemoryType p_type) const {
  7488. if (p_type == MEMORY_BUFFERS) {
  7489. return buffer_memory;
  7490. } else if (p_type == MEMORY_TEXTURES) {
  7491. return image_memory;
  7492. } else {
  7493. VmaTotalStatistics stats;
  7494. vmaCalculateStatistics(allocator, &stats);
  7495. return stats.total.statistics.allocationBytes;
  7496. }
  7497. }
  7498. void RenderingDeviceVulkan::_flush(bool p_current_frame) {
  7499. if (local_device.is_valid() && !p_current_frame) {
  7500. return; //flushing previous frames has no effect with local device
  7501. }
  7502. //not doing this crashes RADV (undefined behavior)
  7503. if (p_current_frame) {
  7504. vkEndCommandBuffer(frames[frame].setup_command_buffer);
  7505. vkEndCommandBuffer(frames[frame].draw_command_buffer);
  7506. }
  7507. if (local_device.is_valid()) {
  7508. VkCommandBuffer command_buffers[2] = { frames[frame].setup_command_buffer, frames[frame].draw_command_buffer };
  7509. context->local_device_push_command_buffers(local_device, command_buffers, 2);
  7510. context->local_device_sync(local_device);
  7511. VkCommandBufferBeginInfo cmdbuf_begin;
  7512. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7513. cmdbuf_begin.pNext = nullptr;
  7514. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7515. cmdbuf_begin.pInheritanceInfo = nullptr;
  7516. VkResult err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin);
  7517. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7518. err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin);
  7519. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7520. } else {
  7521. context->flush(p_current_frame, p_current_frame);
  7522. //re-create the setup command
  7523. if (p_current_frame) {
  7524. VkCommandBufferBeginInfo cmdbuf_begin;
  7525. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7526. cmdbuf_begin.pNext = nullptr;
  7527. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7528. cmdbuf_begin.pInheritanceInfo = nullptr;
  7529. VkResult err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin);
  7530. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7531. context->set_setup_buffer(frames[frame].setup_command_buffer); //append now so it's added before everything else
  7532. }
  7533. if (p_current_frame) {
  7534. VkCommandBufferBeginInfo cmdbuf_begin;
  7535. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7536. cmdbuf_begin.pNext = nullptr;
  7537. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7538. cmdbuf_begin.pInheritanceInfo = nullptr;
  7539. VkResult err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin);
  7540. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7541. context->append_command_buffer(frames[frame].draw_command_buffer);
  7542. }
  7543. }
  7544. }
  7545. void RenderingDeviceVulkan::initialize(VulkanContext *p_context, bool p_local_device) {
  7546. // get our device capabilities
  7547. {
  7548. device_capabilities.version_major = p_context->get_vulkan_major();
  7549. device_capabilities.version_minor = p_context->get_vulkan_minor();
  7550. // get info about subgroups
  7551. VulkanContext::SubgroupCapabilities subgroup_capabilities = p_context->get_subgroup_capabilities();
  7552. device_capabilities.subgroup_size = subgroup_capabilities.size;
  7553. device_capabilities.subgroup_in_shaders = subgroup_capabilities.supported_stages_flags_rd();
  7554. device_capabilities.subgroup_operations = subgroup_capabilities.supported_operations_flags_rd();
  7555. // get info about further features
  7556. VulkanContext::MultiviewCapabilities multiview_capabilies = p_context->get_multiview_capabilities();
  7557. device_capabilities.supports_multiview = multiview_capabilies.is_supported && multiview_capabilies.max_view_count > 1;
  7558. device_capabilities.supports_fsr_half_float = p_context->get_shader_capabilities().shader_float16_is_supported && p_context->get_storage_buffer_capabilities().storage_buffer_16_bit_access_is_supported;
  7559. }
  7560. context = p_context;
  7561. device = p_context->get_device();
  7562. if (p_local_device) {
  7563. frame_count = 1;
  7564. local_device = p_context->local_device_create();
  7565. device = p_context->local_device_get_vk_device(local_device);
  7566. } else {
  7567. frame_count = p_context->get_swapchain_image_count() + 1; //always need one extra to ensure it's unused at any time, without having to use a fence for this.
  7568. }
  7569. limits = p_context->get_device_limits();
  7570. max_timestamp_query_elements = 256;
  7571. { //initialize allocator
  7572. VmaAllocatorCreateInfo allocatorInfo;
  7573. memset(&allocatorInfo, 0, sizeof(VmaAllocatorCreateInfo));
  7574. allocatorInfo.physicalDevice = p_context->get_physical_device();
  7575. allocatorInfo.device = device;
  7576. allocatorInfo.instance = p_context->get_instance();
  7577. vmaCreateAllocator(&allocatorInfo, &allocator);
  7578. }
  7579. frames = memnew_arr(Frame, frame_count);
  7580. frame = 0;
  7581. //create setup and frame buffers
  7582. for (int i = 0; i < frame_count; i++) {
  7583. frames[i].index = 0;
  7584. { //create command pool, one per frame is recommended
  7585. VkCommandPoolCreateInfo cmd_pool_info;
  7586. cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  7587. cmd_pool_info.pNext = nullptr;
  7588. cmd_pool_info.queueFamilyIndex = p_context->get_graphics_queue_family_index();
  7589. cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  7590. VkResult res = vkCreateCommandPool(device, &cmd_pool_info, nullptr, &frames[i].command_pool);
  7591. ERR_FAIL_COND_MSG(res, "vkCreateCommandPool failed with error " + itos(res) + ".");
  7592. }
  7593. { //create command buffers
  7594. VkCommandBufferAllocateInfo cmdbuf;
  7595. //no command buffer exists, create it.
  7596. cmdbuf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  7597. cmdbuf.pNext = nullptr;
  7598. cmdbuf.commandPool = frames[i].command_pool;
  7599. cmdbuf.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  7600. cmdbuf.commandBufferCount = 1;
  7601. VkResult err = vkAllocateCommandBuffers(device, &cmdbuf, &frames[i].setup_command_buffer);
  7602. ERR_CONTINUE_MSG(err, "vkAllocateCommandBuffers failed with error " + itos(err) + ".");
  7603. err = vkAllocateCommandBuffers(device, &cmdbuf, &frames[i].draw_command_buffer);
  7604. ERR_CONTINUE_MSG(err, "vkAllocateCommandBuffers failed with error " + itos(err) + ".");
  7605. }
  7606. {
  7607. //create query pool
  7608. VkQueryPoolCreateInfo query_pool_create_info;
  7609. query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
  7610. query_pool_create_info.flags = 0;
  7611. query_pool_create_info.pNext = nullptr;
  7612. query_pool_create_info.queryType = VK_QUERY_TYPE_TIMESTAMP;
  7613. query_pool_create_info.queryCount = max_timestamp_query_elements;
  7614. query_pool_create_info.pipelineStatistics = 0;
  7615. vkCreateQueryPool(device, &query_pool_create_info, nullptr, &frames[i].timestamp_pool);
  7616. frames[i].timestamp_names = memnew_arr(String, max_timestamp_query_elements);
  7617. frames[i].timestamp_cpu_values = memnew_arr(uint64_t, max_timestamp_query_elements);
  7618. frames[i].timestamp_count = 0;
  7619. frames[i].timestamp_result_names = memnew_arr(String, max_timestamp_query_elements);
  7620. frames[i].timestamp_cpu_result_values = memnew_arr(uint64_t, max_timestamp_query_elements);
  7621. frames[i].timestamp_result_values = memnew_arr(uint64_t, max_timestamp_query_elements);
  7622. frames[i].timestamp_result_count = 0;
  7623. }
  7624. }
  7625. {
  7626. //begin the first command buffer for the first frame, so
  7627. //setting up things can be done in the meantime until swap_buffers(), which is called before advance.
  7628. VkCommandBufferBeginInfo cmdbuf_begin;
  7629. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7630. cmdbuf_begin.pNext = nullptr;
  7631. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7632. cmdbuf_begin.pInheritanceInfo = nullptr;
  7633. VkResult err = vkBeginCommandBuffer(frames[0].setup_command_buffer, &cmdbuf_begin);
  7634. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7635. err = vkBeginCommandBuffer(frames[0].draw_command_buffer, &cmdbuf_begin);
  7636. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7637. if (local_device.is_null()) {
  7638. context->set_setup_buffer(frames[0].setup_command_buffer); //append now so it's added before everything else
  7639. context->append_command_buffer(frames[0].draw_command_buffer);
  7640. }
  7641. }
  7642. // Note: If adding new project settings here, also duplicate their definition in
  7643. // rendering_server.cpp for headless doctool.
  7644. staging_buffer_block_size = GLOBAL_DEF("rendering/vulkan/staging_buffer/block_size_kb", 256);
  7645. staging_buffer_block_size = MAX(4u, staging_buffer_block_size);
  7646. staging_buffer_block_size *= 1024; //kb -> bytes
  7647. staging_buffer_max_size = GLOBAL_DEF("rendering/vulkan/staging_buffer/max_size_mb", 128);
  7648. staging_buffer_max_size = MAX(1u, staging_buffer_max_size);
  7649. staging_buffer_max_size *= 1024 * 1024;
  7650. if (staging_buffer_max_size < staging_buffer_block_size * 4) {
  7651. //validate enough blocks
  7652. staging_buffer_max_size = staging_buffer_block_size * 4;
  7653. }
  7654. texture_upload_region_size_px = GLOBAL_DEF("rendering/vulkan/staging_buffer/texture_upload_region_size_px", 64);
  7655. texture_upload_region_size_px = nearest_power_of_2_templated(texture_upload_region_size_px);
  7656. frames_drawn = frame_count; //start from frame count, so everything else is immediately old
  7657. //ensure current staging block is valid and at least one per frame exists
  7658. staging_buffer_current = 0;
  7659. staging_buffer_used = false;
  7660. for (int i = 0; i < frame_count; i++) {
  7661. //staging was never used, create a block
  7662. Error err = _insert_staging_block();
  7663. ERR_CONTINUE(err != OK);
  7664. }
  7665. max_descriptors_per_pool = GLOBAL_DEF("rendering/vulkan/descriptor_pools/max_descriptors_per_pool", 64);
  7666. //check to make sure DescriptorPoolKey is good
  7667. static_assert(sizeof(uint64_t) * 3 >= UNIFORM_TYPE_MAX * sizeof(uint16_t));
  7668. draw_list = nullptr;
  7669. draw_list_count = 0;
  7670. draw_list_split = false;
  7671. compute_list = nullptr;
  7672. }
  7673. template <class T>
  7674. void RenderingDeviceVulkan::_free_rids(T &p_owner, const char *p_type) {
  7675. List<RID> owned;
  7676. p_owner.get_owned_list(&owned);
  7677. if (owned.size()) {
  7678. if (owned.size() == 1) {
  7679. WARN_PRINT(vformat("1 RID of type \"%s\" was leaked.", p_type));
  7680. } else {
  7681. WARN_PRINT(vformat("%d RIDs of type \"%s\" were leaked.", owned.size(), p_type));
  7682. }
  7683. for (const RID &E : owned) {
  7684. free(E);
  7685. }
  7686. }
  7687. }
  7688. void RenderingDeviceVulkan::capture_timestamp(const String &p_name) {
  7689. ERR_FAIL_COND_MSG(draw_list != nullptr, "Capturing timestamps during draw list creation is not allowed. Offending timestamp was: " + p_name);
  7690. ERR_FAIL_COND(frames[frame].timestamp_count >= max_timestamp_query_elements);
  7691. //this should be optional for profiling, else it will slow things down
  7692. {
  7693. VkMemoryBarrier memoryBarrier;
  7694. memoryBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  7695. memoryBarrier.pNext = nullptr;
  7696. memoryBarrier.srcAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  7697. VK_ACCESS_INDEX_READ_BIT |
  7698. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  7699. VK_ACCESS_UNIFORM_READ_BIT |
  7700. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  7701. VK_ACCESS_SHADER_READ_BIT |
  7702. VK_ACCESS_SHADER_WRITE_BIT |
  7703. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  7704. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  7705. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  7706. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  7707. VK_ACCESS_TRANSFER_READ_BIT |
  7708. VK_ACCESS_TRANSFER_WRITE_BIT |
  7709. VK_ACCESS_HOST_READ_BIT |
  7710. VK_ACCESS_HOST_WRITE_BIT;
  7711. memoryBarrier.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  7712. VK_ACCESS_INDEX_READ_BIT |
  7713. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  7714. VK_ACCESS_UNIFORM_READ_BIT |
  7715. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  7716. VK_ACCESS_SHADER_READ_BIT |
  7717. VK_ACCESS_SHADER_WRITE_BIT |
  7718. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  7719. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  7720. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  7721. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  7722. VK_ACCESS_TRANSFER_READ_BIT |
  7723. VK_ACCESS_TRANSFER_WRITE_BIT |
  7724. VK_ACCESS_HOST_READ_BIT |
  7725. VK_ACCESS_HOST_WRITE_BIT;
  7726. vkCmdPipelineBarrier(frames[frame].draw_command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &memoryBarrier, 0, nullptr, 0, nullptr);
  7727. }
  7728. vkCmdWriteTimestamp(frames[frame].draw_command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, frames[frame].timestamp_pool, frames[frame].timestamp_count);
  7729. frames[frame].timestamp_names[frames[frame].timestamp_count] = p_name;
  7730. frames[frame].timestamp_cpu_values[frames[frame].timestamp_count] = OS::get_singleton()->get_ticks_usec();
  7731. frames[frame].timestamp_count++;
  7732. }
  7733. uint64_t RenderingDeviceVulkan::get_driver_resource(DriverResource p_resource, RID p_rid, uint64_t p_index) {
  7734. _THREAD_SAFE_METHOD_
  7735. switch (p_resource) {
  7736. case DRIVER_RESOURCE_VULKAN_DEVICE: {
  7737. return (uint64_t)context->get_device();
  7738. } break;
  7739. case DRIVER_RESOURCE_VULKAN_PHYSICAL_DEVICE: {
  7740. return (uint64_t)context->get_physical_device();
  7741. } break;
  7742. case DRIVER_RESOURCE_VULKAN_INSTANCE: {
  7743. return (uint64_t)context->get_instance();
  7744. } break;
  7745. case DRIVER_RESOURCE_VULKAN_QUEUE: {
  7746. return (uint64_t)context->get_graphics_queue();
  7747. } break;
  7748. case DRIVER_RESOURCE_VULKAN_QUEUE_FAMILY_INDEX: {
  7749. return context->get_graphics_queue_family_index();
  7750. } break;
  7751. case DRIVER_RESOURCE_VULKAN_IMAGE: {
  7752. Texture *tex = texture_owner.get_or_null(p_rid);
  7753. ERR_FAIL_NULL_V(tex, 0);
  7754. return (uint64_t)tex->image;
  7755. } break;
  7756. case DRIVER_RESOURCE_VULKAN_IMAGE_VIEW: {
  7757. Texture *tex = texture_owner.get_or_null(p_rid);
  7758. ERR_FAIL_NULL_V(tex, 0);
  7759. return (uint64_t)tex->view;
  7760. } break;
  7761. case DRIVER_RESOURCE_VULKAN_IMAGE_NATIVE_TEXTURE_FORMAT: {
  7762. Texture *tex = texture_owner.get_or_null(p_rid);
  7763. ERR_FAIL_NULL_V(tex, 0);
  7764. return vulkan_formats[tex->format];
  7765. } break;
  7766. case DRIVER_RESOURCE_VULKAN_SAMPLER: {
  7767. VkSampler *sampler = sampler_owner.get_or_null(p_rid);
  7768. ERR_FAIL_NULL_V(sampler, 0);
  7769. return uint64_t(*sampler);
  7770. } break;
  7771. case DRIVER_RESOURCE_VULKAN_DESCRIPTOR_SET: {
  7772. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_rid);
  7773. ERR_FAIL_NULL_V(uniform_set, 0);
  7774. return uint64_t(uniform_set->descriptor_set);
  7775. } break;
  7776. case DRIVER_RESOURCE_VULKAN_BUFFER: {
  7777. Buffer *buffer = nullptr;
  7778. if (vertex_buffer_owner.owns(p_rid)) {
  7779. buffer = vertex_buffer_owner.get_or_null(p_rid);
  7780. } else if (index_buffer_owner.owns(p_rid)) {
  7781. buffer = index_buffer_owner.get_or_null(p_rid);
  7782. } else if (uniform_buffer_owner.owns(p_rid)) {
  7783. buffer = uniform_buffer_owner.get_or_null(p_rid);
  7784. } else if (texture_buffer_owner.owns(p_rid)) {
  7785. buffer = &texture_buffer_owner.get_or_null(p_rid)->buffer;
  7786. } else if (storage_buffer_owner.owns(p_rid)) {
  7787. buffer = storage_buffer_owner.get_or_null(p_rid);
  7788. }
  7789. ERR_FAIL_NULL_V(buffer, 0);
  7790. return uint64_t(buffer->buffer);
  7791. } break;
  7792. case DRIVER_RESOURCE_VULKAN_COMPUTE_PIPELINE: {
  7793. ComputePipeline *compute_pipeline = compute_pipeline_owner.get_or_null(p_rid);
  7794. ERR_FAIL_NULL_V(compute_pipeline, 0);
  7795. return uint64_t(compute_pipeline->pipeline);
  7796. } break;
  7797. case DRIVER_RESOURCE_VULKAN_RENDER_PIPELINE: {
  7798. RenderPipeline *render_pipeline = render_pipeline_owner.get_or_null(p_rid);
  7799. ERR_FAIL_NULL_V(render_pipeline, 0);
  7800. return uint64_t(render_pipeline->pipeline);
  7801. } break;
  7802. default: {
  7803. // not supported for this driver
  7804. return 0;
  7805. } break;
  7806. }
  7807. }
  7808. uint32_t RenderingDeviceVulkan::get_captured_timestamps_count() const {
  7809. return frames[frame].timestamp_result_count;
  7810. }
  7811. uint64_t RenderingDeviceVulkan::get_captured_timestamps_frame() const {
  7812. return frames[frame].index;
  7813. }
  7814. static void mult64to128(uint64_t u, uint64_t v, uint64_t &h, uint64_t &l) {
  7815. uint64_t u1 = (u & 0xffffffff);
  7816. uint64_t v1 = (v & 0xffffffff);
  7817. uint64_t t = (u1 * v1);
  7818. uint64_t w3 = (t & 0xffffffff);
  7819. uint64_t k = (t >> 32);
  7820. u >>= 32;
  7821. t = (u * v1) + k;
  7822. k = (t & 0xffffffff);
  7823. uint64_t w1 = (t >> 32);
  7824. v >>= 32;
  7825. t = (u1 * v) + k;
  7826. k = (t >> 32);
  7827. h = (u * v) + w1 + k;
  7828. l = (t << 32) + w3;
  7829. }
  7830. uint64_t RenderingDeviceVulkan::get_captured_timestamp_gpu_time(uint32_t p_index) const {
  7831. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0);
  7832. // this sucks because timestampPeriod multiplier is a float, while the timestamp is 64 bits nanosecs.
  7833. // so, in cases like nvidia which give you enormous numbers and 1 as multiplier, multiplying is next to impossible
  7834. // need to do 128 bits fixed point multiplication to get the right value
  7835. uint64_t shift_bits = 16;
  7836. uint64_t h, l;
  7837. mult64to128(frames[frame].timestamp_result_values[p_index], uint64_t(double(limits.timestampPeriod) * double(1 << shift_bits)), h, l);
  7838. l >>= shift_bits;
  7839. l |= h << (64 - shift_bits);
  7840. return l;
  7841. }
  7842. uint64_t RenderingDeviceVulkan::get_captured_timestamp_cpu_time(uint32_t p_index) const {
  7843. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0);
  7844. return frames[frame].timestamp_cpu_result_values[p_index];
  7845. }
  7846. String RenderingDeviceVulkan::get_captured_timestamp_name(uint32_t p_index) const {
  7847. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, String());
  7848. return frames[frame].timestamp_result_names[p_index];
  7849. }
  7850. uint64_t RenderingDeviceVulkan::limit_get(Limit p_limit) {
  7851. switch (p_limit) {
  7852. case LIMIT_MAX_BOUND_UNIFORM_SETS:
  7853. return limits.maxBoundDescriptorSets;
  7854. case LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS:
  7855. return limits.maxColorAttachments;
  7856. case LIMIT_MAX_TEXTURES_PER_UNIFORM_SET:
  7857. return limits.maxDescriptorSetSampledImages;
  7858. case LIMIT_MAX_SAMPLERS_PER_UNIFORM_SET:
  7859. return limits.maxDescriptorSetSamplers;
  7860. case LIMIT_MAX_STORAGE_BUFFERS_PER_UNIFORM_SET:
  7861. return limits.maxDescriptorSetStorageBuffers;
  7862. case LIMIT_MAX_STORAGE_IMAGES_PER_UNIFORM_SET:
  7863. return limits.maxDescriptorSetStorageImages;
  7864. case LIMIT_MAX_UNIFORM_BUFFERS_PER_UNIFORM_SET:
  7865. return limits.maxDescriptorSetUniformBuffers;
  7866. case LIMIT_MAX_DRAW_INDEXED_INDEX:
  7867. return limits.maxDrawIndexedIndexValue;
  7868. case LIMIT_MAX_FRAMEBUFFER_HEIGHT:
  7869. return limits.maxFramebufferHeight;
  7870. case LIMIT_MAX_FRAMEBUFFER_WIDTH:
  7871. return limits.maxFramebufferWidth;
  7872. case LIMIT_MAX_TEXTURE_ARRAY_LAYERS:
  7873. return limits.maxImageArrayLayers;
  7874. case LIMIT_MAX_TEXTURE_SIZE_1D:
  7875. return limits.maxImageDimension1D;
  7876. case LIMIT_MAX_TEXTURE_SIZE_2D:
  7877. return limits.maxImageDimension2D;
  7878. case LIMIT_MAX_TEXTURE_SIZE_3D:
  7879. return limits.maxImageDimension3D;
  7880. case LIMIT_MAX_TEXTURE_SIZE_CUBE:
  7881. return limits.maxImageDimensionCube;
  7882. case LIMIT_MAX_TEXTURES_PER_SHADER_STAGE:
  7883. return limits.maxPerStageDescriptorSampledImages;
  7884. case LIMIT_MAX_SAMPLERS_PER_SHADER_STAGE:
  7885. return limits.maxPerStageDescriptorSamplers;
  7886. case LIMIT_MAX_STORAGE_BUFFERS_PER_SHADER_STAGE:
  7887. return limits.maxPerStageDescriptorStorageBuffers;
  7888. case LIMIT_MAX_STORAGE_IMAGES_PER_SHADER_STAGE:
  7889. return limits.maxPerStageDescriptorStorageImages;
  7890. case LIMIT_MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE:
  7891. return limits.maxPerStageDescriptorUniformBuffers;
  7892. case LIMIT_MAX_PUSH_CONSTANT_SIZE:
  7893. return limits.maxPushConstantsSize;
  7894. case LIMIT_MAX_UNIFORM_BUFFER_SIZE:
  7895. return limits.maxUniformBufferRange;
  7896. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTE_OFFSET:
  7897. return limits.maxVertexInputAttributeOffset;
  7898. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTES:
  7899. return limits.maxVertexInputAttributes;
  7900. case LIMIT_MAX_VERTEX_INPUT_BINDINGS:
  7901. return limits.maxVertexInputBindings;
  7902. case LIMIT_MAX_VERTEX_INPUT_BINDING_STRIDE:
  7903. return limits.maxVertexInputBindingStride;
  7904. case LIMIT_MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
  7905. return limits.minUniformBufferOffsetAlignment;
  7906. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X:
  7907. return limits.maxComputeWorkGroupCount[0];
  7908. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y:
  7909. return limits.maxComputeWorkGroupCount[1];
  7910. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z:
  7911. return limits.maxComputeWorkGroupCount[2];
  7912. case LIMIT_MAX_COMPUTE_WORKGROUP_INVOCATIONS:
  7913. return limits.maxComputeWorkGroupInvocations;
  7914. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X:
  7915. return limits.maxComputeWorkGroupSize[0];
  7916. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y:
  7917. return limits.maxComputeWorkGroupSize[1];
  7918. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z:
  7919. return limits.maxComputeWorkGroupSize[2];
  7920. default:
  7921. ERR_FAIL_V(0);
  7922. }
  7923. return 0;
  7924. }
  7925. void RenderingDeviceVulkan::finalize() {
  7926. //free all resources
  7927. _flush(false);
  7928. _free_rids(render_pipeline_owner, "Pipeline");
  7929. _free_rids(compute_pipeline_owner, "Compute");
  7930. _free_rids(uniform_set_owner, "UniformSet");
  7931. _free_rids(texture_buffer_owner, "TextureBuffer");
  7932. _free_rids(storage_buffer_owner, "StorageBuffer");
  7933. _free_rids(uniform_buffer_owner, "UniformBuffer");
  7934. _free_rids(shader_owner, "Shader");
  7935. _free_rids(index_array_owner, "IndexArray");
  7936. _free_rids(index_buffer_owner, "IndexBuffer");
  7937. _free_rids(vertex_array_owner, "VertexArray");
  7938. _free_rids(vertex_buffer_owner, "VertexBuffer");
  7939. _free_rids(framebuffer_owner, "Framebuffer");
  7940. _free_rids(sampler_owner, "Sampler");
  7941. {
  7942. //for textures it's a bit more difficult because they may be shared
  7943. List<RID> owned;
  7944. texture_owner.get_owned_list(&owned);
  7945. if (owned.size()) {
  7946. if (owned.size() == 1) {
  7947. WARN_PRINT("1 RID of type \"Texture\" was leaked.");
  7948. } else {
  7949. WARN_PRINT(vformat("%d RIDs of type \"Texture\" were leaked.", owned.size()));
  7950. }
  7951. //free shared first
  7952. for (List<RID>::Element *E = owned.front(); E;) {
  7953. List<RID>::Element *N = E->next();
  7954. if (texture_is_shared(E->get())) {
  7955. free(E->get());
  7956. owned.erase(E);
  7957. }
  7958. E = N;
  7959. }
  7960. //free non shared second, this will avoid an error trying to free unexisting textures due to dependencies.
  7961. for (const RID &E : owned) {
  7962. free(E);
  7963. }
  7964. }
  7965. }
  7966. //free everything pending
  7967. for (int i = 0; i < frame_count; i++) {
  7968. int f = (frame + i) % frame_count;
  7969. _free_pending_resources(f);
  7970. vkDestroyCommandPool(device, frames[i].command_pool, nullptr);
  7971. vkDestroyQueryPool(device, frames[i].timestamp_pool, nullptr);
  7972. memdelete_arr(frames[i].timestamp_names);
  7973. memdelete_arr(frames[i].timestamp_cpu_values);
  7974. memdelete_arr(frames[i].timestamp_result_names);
  7975. memdelete_arr(frames[i].timestamp_result_values);
  7976. memdelete_arr(frames[i].timestamp_cpu_result_values);
  7977. }
  7978. for (int i = 0; i < split_draw_list_allocators.size(); i++) {
  7979. vkDestroyCommandPool(device, split_draw_list_allocators[i].command_pool, nullptr);
  7980. }
  7981. memdelete_arr(frames);
  7982. for (int i = 0; i < staging_buffer_blocks.size(); i++) {
  7983. vmaDestroyBuffer(allocator, staging_buffer_blocks[i].buffer, staging_buffer_blocks[i].allocation);
  7984. }
  7985. while (small_allocs_pools.size()) {
  7986. HashMap<uint32_t, VmaPool>::Iterator E = small_allocs_pools.begin();
  7987. vmaDestroyPool(allocator, E->value);
  7988. small_allocs_pools.remove(E);
  7989. }
  7990. vmaDestroyAllocator(allocator);
  7991. while (vertex_formats.size()) {
  7992. HashMap<VertexFormatID, VertexDescriptionCache>::Iterator temp = vertex_formats.begin();
  7993. memdelete_arr(temp->value.bindings);
  7994. memdelete_arr(temp->value.attributes);
  7995. vertex_formats.remove(temp);
  7996. }
  7997. for (KeyValue<FramebufferFormatID, FramebufferFormat> &E : framebuffer_formats) {
  7998. vkDestroyRenderPass(device, E.value.render_pass, nullptr);
  7999. }
  8000. framebuffer_formats.clear();
  8001. //all these should be clear at this point
  8002. ERR_FAIL_COND(descriptor_pools.size());
  8003. ERR_FAIL_COND(dependency_map.size());
  8004. ERR_FAIL_COND(reverse_dependency_map.size());
  8005. }
  8006. RenderingDevice *RenderingDeviceVulkan::create_local_device() {
  8007. RenderingDeviceVulkan *rd = memnew(RenderingDeviceVulkan);
  8008. rd->initialize(context, true);
  8009. return rd;
  8010. }
  8011. RenderingDeviceVulkan::RenderingDeviceVulkan() {
  8012. device_capabilities.device_family = DEVICE_VULKAN;
  8013. }
  8014. RenderingDeviceVulkan::~RenderingDeviceVulkan() {
  8015. if (local_device.is_valid()) {
  8016. finalize();
  8017. context->local_device_free(local_device);
  8018. }
  8019. }