SDL_gpu_vulkan.c 490 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2026 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #ifdef SDL_GPU_VULKAN
  20. // Needed for VK_KHR_portability_subset
  21. #define VK_ENABLE_BETA_EXTENSIONS
  22. #define VK_NO_PROTOTYPES
  23. #include "../../video/khronos/vulkan/vulkan.h"
  24. #include <SDL3/SDL_vulkan.h>
  25. #include "../SDL_sysgpu.h"
  26. #include "../../events/SDL_windowevents_c.h"
  27. // Global Vulkan Loader Entry Points
  28. static PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL;
  29. #define VULKAN_GLOBAL_FUNCTION(name) \
  30. static PFN_##name name = NULL;
  31. #include "SDL_gpu_vulkan_vkfuncs.h"
  32. typedef struct VulkanExtensions
  33. {
  34. // These extensions are required!
  35. // Globally supported
  36. Uint8 KHR_swapchain;
  37. // Core since 1.1, needed for negative VkViewport::height
  38. Uint8 KHR_maintenance1;
  39. // These extensions are optional!
  40. // Core since 1.2, but requires annoying paperwork to implement
  41. Uint8 KHR_driver_properties;
  42. // Only required for special implementations (i.e. MoltenVK)
  43. Uint8 KHR_portability_subset;
  44. // Only required to detect devices using Dozen D3D12 driver
  45. Uint8 MSFT_layered_driver;
  46. // Only required for decoding HDR ASTC textures
  47. Uint8 EXT_texture_compression_astc_hdr;
  48. } VulkanExtensions;
  49. // Defines
  50. #define SMALL_ALLOCATION_THRESHOLD 2097152 // 2 MiB
  51. #define SMALL_ALLOCATION_SIZE 16777216 // 16 MiB
  52. #define LARGE_ALLOCATION_INCREMENT 67108864 // 64 MiB
  53. #define MAX_UBO_SECTION_SIZE 4096 // 4 KiB
  54. #define DESCRIPTOR_POOL_SIZE 128
  55. #define WINDOW_PROPERTY_DATA "SDL_GPUVulkanWindowPropertyData"
  56. #define IDENTITY_SWIZZLE \
  57. { \
  58. VK_COMPONENT_SWIZZLE_IDENTITY, \
  59. VK_COMPONENT_SWIZZLE_IDENTITY, \
  60. VK_COMPONENT_SWIZZLE_IDENTITY, \
  61. VK_COMPONENT_SWIZZLE_IDENTITY \
  62. }
  63. // Conversions
  64. static VkPresentModeKHR SDLToVK_PresentMode[] = {
  65. VK_PRESENT_MODE_FIFO_KHR,
  66. VK_PRESENT_MODE_IMMEDIATE_KHR,
  67. VK_PRESENT_MODE_MAILBOX_KHR
  68. };
  69. static VkFormat SDLToVK_TextureFormat[] = {
  70. VK_FORMAT_UNDEFINED, // INVALID
  71. VK_FORMAT_R8_UNORM, // A8_UNORM
  72. VK_FORMAT_R8_UNORM, // R8_UNORM
  73. VK_FORMAT_R8G8_UNORM, // R8G8_UNORM
  74. VK_FORMAT_R8G8B8A8_UNORM, // R8G8B8A8_UNORM
  75. VK_FORMAT_R16_UNORM, // R16_UNORM
  76. VK_FORMAT_R16G16_UNORM, // R16G16_UNORM
  77. VK_FORMAT_R16G16B16A16_UNORM, // R16G16B16A16_UNORM
  78. VK_FORMAT_A2B10G10R10_UNORM_PACK32, // R10G10B10A2_UNORM
  79. VK_FORMAT_R5G6B5_UNORM_PACK16, // B5G6R5_UNORM
  80. VK_FORMAT_A1R5G5B5_UNORM_PACK16, // B5G5R5A1_UNORM
  81. VK_FORMAT_B4G4R4A4_UNORM_PACK16, // B4G4R4A4_UNORM
  82. VK_FORMAT_B8G8R8A8_UNORM, // B8G8R8A8_UNORM
  83. VK_FORMAT_BC1_RGBA_UNORM_BLOCK, // BC1_UNORM
  84. VK_FORMAT_BC2_UNORM_BLOCK, // BC2_UNORM
  85. VK_FORMAT_BC3_UNORM_BLOCK, // BC3_UNORM
  86. VK_FORMAT_BC4_UNORM_BLOCK, // BC4_UNORM
  87. VK_FORMAT_BC5_UNORM_BLOCK, // BC5_UNORM
  88. VK_FORMAT_BC7_UNORM_BLOCK, // BC7_UNORM
  89. VK_FORMAT_BC6H_SFLOAT_BLOCK, // BC6H_FLOAT
  90. VK_FORMAT_BC6H_UFLOAT_BLOCK, // BC6H_UFLOAT
  91. VK_FORMAT_R8_SNORM, // R8_SNORM
  92. VK_FORMAT_R8G8_SNORM, // R8G8_SNORM
  93. VK_FORMAT_R8G8B8A8_SNORM, // R8G8B8A8_SNORM
  94. VK_FORMAT_R16_SNORM, // R16_SNORM
  95. VK_FORMAT_R16G16_SNORM, // R16G16_SNORM
  96. VK_FORMAT_R16G16B16A16_SNORM, // R16G16B16A16_SNORM
  97. VK_FORMAT_R16_SFLOAT, // R16_FLOAT
  98. VK_FORMAT_R16G16_SFLOAT, // R16G16_FLOAT
  99. VK_FORMAT_R16G16B16A16_SFLOAT, // R16G16B16A16_FLOAT
  100. VK_FORMAT_R32_SFLOAT, // R32_FLOAT
  101. VK_FORMAT_R32G32_SFLOAT, // R32G32_FLOAT
  102. VK_FORMAT_R32G32B32A32_SFLOAT, // R32G32B32A32_FLOAT
  103. VK_FORMAT_B10G11R11_UFLOAT_PACK32, // R11G11B10_UFLOAT
  104. VK_FORMAT_R8_UINT, // R8_UINT
  105. VK_FORMAT_R8G8_UINT, // R8G8_UINT
  106. VK_FORMAT_R8G8B8A8_UINT, // R8G8B8A8_UINT
  107. VK_FORMAT_R16_UINT, // R16_UINT
  108. VK_FORMAT_R16G16_UINT, // R16G16_UINT
  109. VK_FORMAT_R16G16B16A16_UINT, // R16G16B16A16_UINT
  110. VK_FORMAT_R32_UINT, // R32_UINT
  111. VK_FORMAT_R32G32_UINT, // R32G32_UINT
  112. VK_FORMAT_R32G32B32A32_UINT, // R32G32B32A32_UINT
  113. VK_FORMAT_R8_SINT, // R8_INT
  114. VK_FORMAT_R8G8_SINT, // R8G8_INT
  115. VK_FORMAT_R8G8B8A8_SINT, // R8G8B8A8_INT
  116. VK_FORMAT_R16_SINT, // R16_INT
  117. VK_FORMAT_R16G16_SINT, // R16G16_INT
  118. VK_FORMAT_R16G16B16A16_SINT, // R16G16B16A16_INT
  119. VK_FORMAT_R32_SINT, // R32_INT
  120. VK_FORMAT_R32G32_SINT, // R32G32_INT
  121. VK_FORMAT_R32G32B32A32_SINT, // R32G32B32A32_INT
  122. VK_FORMAT_R8G8B8A8_SRGB, // R8G8B8A8_UNORM_SRGB
  123. VK_FORMAT_B8G8R8A8_SRGB, // B8G8R8A8_UNORM_SRGB
  124. VK_FORMAT_BC1_RGBA_SRGB_BLOCK, // BC1_UNORM_SRGB
  125. VK_FORMAT_BC2_SRGB_BLOCK, // BC3_UNORM_SRGB
  126. VK_FORMAT_BC3_SRGB_BLOCK, // BC3_UNORM_SRGB
  127. VK_FORMAT_BC7_SRGB_BLOCK, // BC7_UNORM_SRGB
  128. VK_FORMAT_D16_UNORM, // D16_UNORM
  129. VK_FORMAT_X8_D24_UNORM_PACK32, // D24_UNORM
  130. VK_FORMAT_D32_SFLOAT, // D32_FLOAT
  131. VK_FORMAT_D24_UNORM_S8_UINT, // D24_UNORM_S8_UINT
  132. VK_FORMAT_D32_SFLOAT_S8_UINT, // D32_FLOAT_S8_UINT
  133. VK_FORMAT_ASTC_4x4_UNORM_BLOCK, // ASTC_4x4_UNORM
  134. VK_FORMAT_ASTC_5x4_UNORM_BLOCK, // ASTC_5x4_UNORM
  135. VK_FORMAT_ASTC_5x5_UNORM_BLOCK, // ASTC_5x5_UNORM
  136. VK_FORMAT_ASTC_6x5_UNORM_BLOCK, // ASTC_6x5_UNORM
  137. VK_FORMAT_ASTC_6x6_UNORM_BLOCK, // ASTC_6x6_UNORM
  138. VK_FORMAT_ASTC_8x5_UNORM_BLOCK, // ASTC_8x5_UNORM
  139. VK_FORMAT_ASTC_8x6_UNORM_BLOCK, // ASTC_8x6_UNORM
  140. VK_FORMAT_ASTC_8x8_UNORM_BLOCK, // ASTC_8x8_UNORM
  141. VK_FORMAT_ASTC_10x5_UNORM_BLOCK, // ASTC_10x5_UNORM
  142. VK_FORMAT_ASTC_10x6_UNORM_BLOCK, // ASTC_10x6_UNORM
  143. VK_FORMAT_ASTC_10x8_UNORM_BLOCK, // ASTC_10x8_UNORM
  144. VK_FORMAT_ASTC_10x10_UNORM_BLOCK, // ASTC_10x10_UNORM
  145. VK_FORMAT_ASTC_12x10_UNORM_BLOCK, // ASTC_12x10_UNORM
  146. VK_FORMAT_ASTC_12x12_UNORM_BLOCK, // ASTC_12x12_UNORM
  147. VK_FORMAT_ASTC_4x4_SRGB_BLOCK, // ASTC_4x4_UNORM_SRGB
  148. VK_FORMAT_ASTC_5x4_SRGB_BLOCK, // ASTC_5x4_UNORM_SRGB
  149. VK_FORMAT_ASTC_5x5_SRGB_BLOCK, // ASTC_5x5_UNORM_SRGB
  150. VK_FORMAT_ASTC_6x5_SRGB_BLOCK, // ASTC_6x5_UNORM_SRGB
  151. VK_FORMAT_ASTC_6x6_SRGB_BLOCK, // ASTC_6x6_UNORM_SRGB
  152. VK_FORMAT_ASTC_8x5_SRGB_BLOCK, // ASTC_8x5_UNORM_SRGB
  153. VK_FORMAT_ASTC_8x6_SRGB_BLOCK, // ASTC_8x6_UNORM_SRGB
  154. VK_FORMAT_ASTC_8x8_SRGB_BLOCK, // ASTC_8x8_UNORM_SRGB
  155. VK_FORMAT_ASTC_10x5_SRGB_BLOCK, // ASTC_10x5_UNORM_SRGB
  156. VK_FORMAT_ASTC_10x6_SRGB_BLOCK, // ASTC_10x6_UNORM_SRGB
  157. VK_FORMAT_ASTC_10x8_SRGB_BLOCK, // ASTC_10x8_UNORM_SRGB
  158. VK_FORMAT_ASTC_10x10_SRGB_BLOCK, // ASTC_10x10_UNORM_SRGB
  159. VK_FORMAT_ASTC_12x10_SRGB_BLOCK, // ASTC_12x10_UNORM_SRGB
  160. VK_FORMAT_ASTC_12x12_SRGB_BLOCK, // ASTC_12x12_UNORM_SRGB
  161. VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT, // ASTC_4x4_FLOAT
  162. VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT, // ASTC_5x4_FLOAT
  163. VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT, // ASTC_5x5_FLOAT
  164. VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT, // ASTC_6x5_FLOAT
  165. VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT, // ASTC_6x6_FLOAT
  166. VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT, // ASTC_8x5_FLOAT
  167. VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT, // ASTC_8x6_FLOAT
  168. VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT, // ASTC_8x8_FLOAT
  169. VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT, // ASTC_10x5_FLOAT
  170. VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT, // ASTC_10x6_FLOAT
  171. VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT, // ASTC_10x8_FLOAT
  172. VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT, // ASTC_10x10_FLOAT
  173. VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT, // ASTC_12x10_FLOAT
  174. VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK // ASTC_12x12_FLOAT
  175. };
  176. SDL_COMPILE_TIME_ASSERT(SDLToVK_TextureFormat, SDL_arraysize(SDLToVK_TextureFormat) == SDL_GPU_TEXTUREFORMAT_MAX_ENUM_VALUE);
  177. static VkComponentMapping SwizzleForSDLFormat(SDL_GPUTextureFormat format)
  178. {
  179. if (format == SDL_GPU_TEXTUREFORMAT_A8_UNORM) {
  180. // TODO: use VK_FORMAT_A8_UNORM_KHR from VK_KHR_maintenance5 when available
  181. return (VkComponentMapping){
  182. VK_COMPONENT_SWIZZLE_ZERO,
  183. VK_COMPONENT_SWIZZLE_ZERO,
  184. VK_COMPONENT_SWIZZLE_ZERO,
  185. VK_COMPONENT_SWIZZLE_R,
  186. };
  187. }
  188. if (format == SDL_GPU_TEXTUREFORMAT_B4G4R4A4_UNORM) {
  189. // ARGB -> BGRA
  190. // TODO: use VK_FORMAT_A4R4G4B4_UNORM_PACK16_EXT from VK_EXT_4444_formats when available
  191. return (VkComponentMapping){
  192. VK_COMPONENT_SWIZZLE_G,
  193. VK_COMPONENT_SWIZZLE_R,
  194. VK_COMPONENT_SWIZZLE_A,
  195. VK_COMPONENT_SWIZZLE_B,
  196. };
  197. }
  198. return (VkComponentMapping)IDENTITY_SWIZZLE;
  199. }
  200. static VkFormat SwapchainCompositionToFormat[] = {
  201. VK_FORMAT_B8G8R8A8_UNORM, // SDR
  202. VK_FORMAT_B8G8R8A8_SRGB, // SDR_LINEAR
  203. VK_FORMAT_R16G16B16A16_SFLOAT, // HDR_EXTENDED_LINEAR
  204. VK_FORMAT_A2B10G10R10_UNORM_PACK32 // HDR10_ST2084
  205. };
  206. static VkFormat SwapchainCompositionToFallbackFormat[] = {
  207. VK_FORMAT_R8G8B8A8_UNORM, // SDR
  208. VK_FORMAT_R8G8B8A8_SRGB, // SDR_LINEAR
  209. VK_FORMAT_UNDEFINED, // HDR_EXTENDED_LINEAR (no fallback)
  210. VK_FORMAT_UNDEFINED // HDR10_ST2084 (no fallback)
  211. };
  212. static SDL_GPUTextureFormat SwapchainCompositionToSDLFormat(
  213. SDL_GPUSwapchainComposition composition,
  214. bool usingFallback)
  215. {
  216. switch (composition) {
  217. case SDL_GPU_SWAPCHAINCOMPOSITION_SDR:
  218. return usingFallback ? SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM : SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM;
  219. case SDL_GPU_SWAPCHAINCOMPOSITION_SDR_LINEAR:
  220. return usingFallback ? SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB : SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB;
  221. case SDL_GPU_SWAPCHAINCOMPOSITION_HDR_EXTENDED_LINEAR:
  222. return SDL_GPU_TEXTUREFORMAT_R16G16B16A16_FLOAT;
  223. case SDL_GPU_SWAPCHAINCOMPOSITION_HDR10_ST2084:
  224. return SDL_GPU_TEXTUREFORMAT_R10G10B10A2_UNORM;
  225. default:
  226. return SDL_GPU_TEXTUREFORMAT_INVALID;
  227. }
  228. }
  229. static VkColorSpaceKHR SwapchainCompositionToColorSpace[] = {
  230. VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, // SDR
  231. VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, // SDR_LINEAR
  232. VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT, // HDR_EXTENDED_LINEAR
  233. VK_COLOR_SPACE_HDR10_ST2084_EXT // HDR10_ST2084
  234. };
  235. static VkComponentMapping SwapchainCompositionSwizzle[] = {
  236. IDENTITY_SWIZZLE, // SDR
  237. IDENTITY_SWIZZLE, // SDR_LINEAR
  238. IDENTITY_SWIZZLE, // HDR_EXTENDED_LINEAR
  239. {
  240. // HDR10_ST2084
  241. VK_COMPONENT_SWIZZLE_R,
  242. VK_COMPONENT_SWIZZLE_G,
  243. VK_COMPONENT_SWIZZLE_B,
  244. VK_COMPONENT_SWIZZLE_A,
  245. }
  246. };
  247. static VkFormat SDLToVK_VertexFormat[] = {
  248. VK_FORMAT_UNDEFINED, // INVALID
  249. VK_FORMAT_R32_SINT, // INT
  250. VK_FORMAT_R32G32_SINT, // INT2
  251. VK_FORMAT_R32G32B32_SINT, // INT3
  252. VK_FORMAT_R32G32B32A32_SINT, // INT4
  253. VK_FORMAT_R32_UINT, // UINT
  254. VK_FORMAT_R32G32_UINT, // UINT2
  255. VK_FORMAT_R32G32B32_UINT, // UINT3
  256. VK_FORMAT_R32G32B32A32_UINT, // UINT4
  257. VK_FORMAT_R32_SFLOAT, // FLOAT
  258. VK_FORMAT_R32G32_SFLOAT, // FLOAT2
  259. VK_FORMAT_R32G32B32_SFLOAT, // FLOAT3
  260. VK_FORMAT_R32G32B32A32_SFLOAT, // FLOAT4
  261. VK_FORMAT_R8G8_SINT, // BYTE2
  262. VK_FORMAT_R8G8B8A8_SINT, // BYTE4
  263. VK_FORMAT_R8G8_UINT, // UBYTE2
  264. VK_FORMAT_R8G8B8A8_UINT, // UBYTE4
  265. VK_FORMAT_R8G8_SNORM, // BYTE2_NORM
  266. VK_FORMAT_R8G8B8A8_SNORM, // BYTE4_NORM
  267. VK_FORMAT_R8G8_UNORM, // UBYTE2_NORM
  268. VK_FORMAT_R8G8B8A8_UNORM, // UBYTE4_NORM
  269. VK_FORMAT_R16G16_SINT, // SHORT2
  270. VK_FORMAT_R16G16B16A16_SINT, // SHORT4
  271. VK_FORMAT_R16G16_UINT, // USHORT2
  272. VK_FORMAT_R16G16B16A16_UINT, // USHORT4
  273. VK_FORMAT_R16G16_SNORM, // SHORT2_NORM
  274. VK_FORMAT_R16G16B16A16_SNORM, // SHORT4_NORM
  275. VK_FORMAT_R16G16_UNORM, // USHORT2_NORM
  276. VK_FORMAT_R16G16B16A16_UNORM, // USHORT4_NORM
  277. VK_FORMAT_R16G16_SFLOAT, // HALF2
  278. VK_FORMAT_R16G16B16A16_SFLOAT // HALF4
  279. };
  280. SDL_COMPILE_TIME_ASSERT(SDLToVK_VertexFormat, SDL_arraysize(SDLToVK_VertexFormat) == SDL_GPU_VERTEXELEMENTFORMAT_MAX_ENUM_VALUE);
  281. static VkIndexType SDLToVK_IndexType[] = {
  282. VK_INDEX_TYPE_UINT16,
  283. VK_INDEX_TYPE_UINT32
  284. };
  285. static VkPrimitiveTopology SDLToVK_PrimitiveType[] = {
  286. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
  287. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
  288. VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
  289. VK_PRIMITIVE_TOPOLOGY_LINE_STRIP,
  290. VK_PRIMITIVE_TOPOLOGY_POINT_LIST
  291. };
  292. static VkCullModeFlags SDLToVK_CullMode[] = {
  293. VK_CULL_MODE_NONE,
  294. VK_CULL_MODE_FRONT_BIT,
  295. VK_CULL_MODE_BACK_BIT,
  296. VK_CULL_MODE_FRONT_AND_BACK
  297. };
  298. static VkFrontFace SDLToVK_FrontFace[] = {
  299. VK_FRONT_FACE_COUNTER_CLOCKWISE,
  300. VK_FRONT_FACE_CLOCKWISE
  301. };
  302. static VkBlendFactor SDLToVK_BlendFactor[] = {
  303. VK_BLEND_FACTOR_ZERO, // INVALID
  304. VK_BLEND_FACTOR_ZERO,
  305. VK_BLEND_FACTOR_ONE,
  306. VK_BLEND_FACTOR_SRC_COLOR,
  307. VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR,
  308. VK_BLEND_FACTOR_DST_COLOR,
  309. VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR,
  310. VK_BLEND_FACTOR_SRC_ALPHA,
  311. VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
  312. VK_BLEND_FACTOR_DST_ALPHA,
  313. VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA,
  314. VK_BLEND_FACTOR_CONSTANT_COLOR,
  315. VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR,
  316. VK_BLEND_FACTOR_SRC_ALPHA_SATURATE
  317. };
  318. SDL_COMPILE_TIME_ASSERT(SDLToVK_BlendFactor, SDL_arraysize(SDLToVK_BlendFactor) == SDL_GPU_BLENDFACTOR_MAX_ENUM_VALUE);
  319. static VkBlendOp SDLToVK_BlendOp[] = {
  320. VK_BLEND_OP_ADD, // INVALID
  321. VK_BLEND_OP_ADD,
  322. VK_BLEND_OP_SUBTRACT,
  323. VK_BLEND_OP_REVERSE_SUBTRACT,
  324. VK_BLEND_OP_MIN,
  325. VK_BLEND_OP_MAX
  326. };
  327. SDL_COMPILE_TIME_ASSERT(SDLToVK_BlendOp, SDL_arraysize(SDLToVK_BlendOp) == SDL_GPU_BLENDOP_MAX_ENUM_VALUE);
  328. static VkCompareOp SDLToVK_CompareOp[] = {
  329. VK_COMPARE_OP_NEVER, // INVALID
  330. VK_COMPARE_OP_NEVER,
  331. VK_COMPARE_OP_LESS,
  332. VK_COMPARE_OP_EQUAL,
  333. VK_COMPARE_OP_LESS_OR_EQUAL,
  334. VK_COMPARE_OP_GREATER,
  335. VK_COMPARE_OP_NOT_EQUAL,
  336. VK_COMPARE_OP_GREATER_OR_EQUAL,
  337. VK_COMPARE_OP_ALWAYS
  338. };
  339. SDL_COMPILE_TIME_ASSERT(SDLToVK_CompareOp, SDL_arraysize(SDLToVK_CompareOp) == SDL_GPU_COMPAREOP_MAX_ENUM_VALUE);
  340. static VkStencilOp SDLToVK_StencilOp[] = {
  341. VK_STENCIL_OP_KEEP, // INVALID
  342. VK_STENCIL_OP_KEEP,
  343. VK_STENCIL_OP_ZERO,
  344. VK_STENCIL_OP_REPLACE,
  345. VK_STENCIL_OP_INCREMENT_AND_CLAMP,
  346. VK_STENCIL_OP_DECREMENT_AND_CLAMP,
  347. VK_STENCIL_OP_INVERT,
  348. VK_STENCIL_OP_INCREMENT_AND_WRAP,
  349. VK_STENCIL_OP_DECREMENT_AND_WRAP
  350. };
  351. SDL_COMPILE_TIME_ASSERT(SDLToVK_StencilOp, SDL_arraysize(SDLToVK_StencilOp) == SDL_GPU_STENCILOP_MAX_ENUM_VALUE);
  352. static VkAttachmentLoadOp SDLToVK_LoadOp[] = {
  353. VK_ATTACHMENT_LOAD_OP_LOAD,
  354. VK_ATTACHMENT_LOAD_OP_CLEAR,
  355. VK_ATTACHMENT_LOAD_OP_DONT_CARE
  356. };
  357. static VkAttachmentStoreOp SDLToVK_StoreOp[] = {
  358. VK_ATTACHMENT_STORE_OP_STORE,
  359. VK_ATTACHMENT_STORE_OP_DONT_CARE,
  360. VK_ATTACHMENT_STORE_OP_DONT_CARE,
  361. VK_ATTACHMENT_STORE_OP_STORE
  362. };
  363. static VkSampleCountFlagBits SDLToVK_SampleCount[] = {
  364. VK_SAMPLE_COUNT_1_BIT,
  365. VK_SAMPLE_COUNT_2_BIT,
  366. VK_SAMPLE_COUNT_4_BIT,
  367. VK_SAMPLE_COUNT_8_BIT
  368. };
  369. static VkVertexInputRate SDLToVK_VertexInputRate[] = {
  370. VK_VERTEX_INPUT_RATE_VERTEX,
  371. VK_VERTEX_INPUT_RATE_INSTANCE
  372. };
  373. static VkFilter SDLToVK_Filter[] = {
  374. VK_FILTER_NEAREST,
  375. VK_FILTER_LINEAR
  376. };
  377. static VkSamplerMipmapMode SDLToVK_SamplerMipmapMode[] = {
  378. VK_SAMPLER_MIPMAP_MODE_NEAREST,
  379. VK_SAMPLER_MIPMAP_MODE_LINEAR
  380. };
  381. static VkSamplerAddressMode SDLToVK_SamplerAddressMode[] = {
  382. VK_SAMPLER_ADDRESS_MODE_REPEAT,
  383. VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT,
  384. VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE
  385. };
  386. // Structures
  387. typedef struct VulkanMemoryAllocation VulkanMemoryAllocation;
  388. typedef struct VulkanBuffer VulkanBuffer;
  389. typedef struct VulkanBufferContainer VulkanBufferContainer;
  390. typedef struct VulkanUniformBuffer VulkanUniformBuffer;
  391. typedef struct VulkanTexture VulkanTexture;
  392. typedef struct VulkanTextureContainer VulkanTextureContainer;
  393. typedef struct VulkanFenceHandle
  394. {
  395. VkFence fence;
  396. SDL_AtomicInt referenceCount;
  397. } VulkanFenceHandle;
  398. // Memory Allocation
  399. typedef struct VulkanMemoryFreeRegion
  400. {
  401. VulkanMemoryAllocation *allocation;
  402. VkDeviceSize offset;
  403. VkDeviceSize size;
  404. Uint32 allocationIndex;
  405. Uint32 sortedIndex;
  406. } VulkanMemoryFreeRegion;
  407. typedef struct VulkanMemoryUsedRegion
  408. {
  409. VulkanMemoryAllocation *allocation;
  410. VkDeviceSize offset;
  411. VkDeviceSize size;
  412. VkDeviceSize resourceOffset; // differs from offset based on alignment
  413. VkDeviceSize resourceSize; // differs from size based on alignment
  414. VkDeviceSize alignment;
  415. Uint8 isBuffer;
  416. union
  417. {
  418. VulkanBuffer *vulkanBuffer;
  419. VulkanTexture *vulkanTexture;
  420. };
  421. } VulkanMemoryUsedRegion;
  422. typedef struct VulkanMemorySubAllocator
  423. {
  424. Uint32 memoryTypeIndex;
  425. VulkanMemoryAllocation **allocations;
  426. Uint32 allocationCount;
  427. VulkanMemoryFreeRegion **sortedFreeRegions;
  428. Uint32 sortedFreeRegionCount;
  429. Uint32 sortedFreeRegionCapacity;
  430. } VulkanMemorySubAllocator;
  431. struct VulkanMemoryAllocation
  432. {
  433. VulkanMemorySubAllocator *allocator;
  434. VkDeviceMemory memory;
  435. VkDeviceSize size;
  436. VulkanMemoryUsedRegion **usedRegions;
  437. Uint32 usedRegionCount;
  438. Uint32 usedRegionCapacity;
  439. VulkanMemoryFreeRegion **freeRegions;
  440. Uint32 freeRegionCount;
  441. Uint32 freeRegionCapacity;
  442. Uint8 availableForAllocation;
  443. VkDeviceSize freeSpace;
  444. VkDeviceSize usedSpace;
  445. Uint8 *mapPointer;
  446. SDL_Mutex *memoryLock;
  447. };
  448. typedef struct VulkanMemoryAllocator
  449. {
  450. VulkanMemorySubAllocator subAllocators[VK_MAX_MEMORY_TYPES];
  451. } VulkanMemoryAllocator;
  452. // Memory structures
  453. typedef enum VulkanBufferType
  454. {
  455. VULKAN_BUFFER_TYPE_GPU,
  456. VULKAN_BUFFER_TYPE_UNIFORM,
  457. VULKAN_BUFFER_TYPE_TRANSFER
  458. } VulkanBufferType;
  459. struct VulkanBuffer
  460. {
  461. VulkanBufferContainer *container;
  462. Uint32 containerIndex;
  463. VkBuffer buffer;
  464. VulkanMemoryUsedRegion *usedRegion;
  465. // Needed for uniforms and defrag
  466. VulkanBufferType type;
  467. SDL_GPUBufferUsageFlags usage;
  468. VkDeviceSize size;
  469. SDL_AtomicInt referenceCount;
  470. bool transitioned;
  471. bool markedForDestroy; // so that defrag doesn't double-free
  472. VulkanUniformBuffer *uniformBufferForDefrag;
  473. };
  474. struct VulkanBufferContainer
  475. {
  476. VulkanBuffer *activeBuffer;
  477. VulkanBuffer **buffers;
  478. Uint32 bufferCapacity;
  479. Uint32 bufferCount;
  480. bool dedicated;
  481. char *debugName;
  482. };
  483. // Renderer Structure
  484. typedef struct QueueFamilyIndices
  485. {
  486. Uint32 graphicsFamily;
  487. Uint32 presentFamily;
  488. Uint32 computeFamily;
  489. Uint32 transferFamily;
  490. } QueueFamilyIndices;
  491. typedef struct VulkanSampler
  492. {
  493. VkSampler sampler;
  494. SDL_AtomicInt referenceCount;
  495. } VulkanSampler;
  496. typedef struct VulkanShader
  497. {
  498. VkShaderModule shaderModule;
  499. char *entrypointName;
  500. SDL_GPUShaderStage stage;
  501. Uint32 numSamplers;
  502. Uint32 numStorageTextures;
  503. Uint32 numStorageBuffers;
  504. Uint32 numUniformBuffers;
  505. SDL_AtomicInt referenceCount;
  506. } VulkanShader;
  507. /* Textures are made up of individual subresources.
  508. * This helps us barrier the resource efficiently.
  509. */
  510. typedef struct VulkanTextureSubresource
  511. {
  512. VulkanTexture *parent;
  513. Uint32 layer;
  514. Uint32 level;
  515. VkImageView *renderTargetViews; // One render target view per depth slice
  516. VkImageView computeWriteView;
  517. VkImageView depthStencilView;
  518. } VulkanTextureSubresource;
  519. struct VulkanTexture
  520. {
  521. VulkanTextureContainer *container;
  522. Uint32 containerIndex;
  523. VulkanMemoryUsedRegion *usedRegion;
  524. VkImage image;
  525. VkImageView fullView; // used for samplers and storage reads
  526. VkComponentMapping swizzle;
  527. VkImageAspectFlags aspectFlags;
  528. Uint32 depth; // used for cleanup only
  529. // FIXME: It'd be nice if we didn't have to have this on the texture...
  530. SDL_GPUTextureUsageFlags usage; // used for defrag transitions only.
  531. Uint32 subresourceCount;
  532. VulkanTextureSubresource *subresources;
  533. bool markedForDestroy; // so that defrag doesn't double-free
  534. SDL_AtomicInt referenceCount;
  535. };
  536. struct VulkanTextureContainer
  537. {
  538. TextureCommonHeader header;
  539. VulkanTexture *activeTexture;
  540. Uint32 textureCapacity;
  541. Uint32 textureCount;
  542. VulkanTexture **textures;
  543. char *debugName;
  544. bool canBeCycled;
  545. };
  546. typedef enum VulkanBufferUsageMode
  547. {
  548. VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE,
  549. VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION,
  550. VULKAN_BUFFER_USAGE_MODE_VERTEX_READ,
  551. VULKAN_BUFFER_USAGE_MODE_INDEX_READ,
  552. VULKAN_BUFFER_USAGE_MODE_INDIRECT,
  553. VULKAN_BUFFER_USAGE_MODE_GRAPHICS_STORAGE_READ,
  554. VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ,
  555. VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE,
  556. } VulkanBufferUsageMode;
  557. typedef enum VulkanTextureUsageMode
  558. {
  559. VULKAN_TEXTURE_USAGE_MODE_UNINITIALIZED,
  560. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  561. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  562. VULKAN_TEXTURE_USAGE_MODE_SAMPLER,
  563. VULKAN_TEXTURE_USAGE_MODE_GRAPHICS_STORAGE_READ,
  564. VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ,
  565. VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE,
  566. VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT,
  567. VULKAN_TEXTURE_USAGE_MODE_DEPTH_STENCIL_ATTACHMENT,
  568. VULKAN_TEXTURE_USAGE_MODE_PRESENT
  569. } VulkanTextureUsageMode;
  570. typedef enum VulkanUniformBufferStage
  571. {
  572. VULKAN_UNIFORM_BUFFER_STAGE_VERTEX,
  573. VULKAN_UNIFORM_BUFFER_STAGE_FRAGMENT,
  574. VULKAN_UNIFORM_BUFFER_STAGE_COMPUTE
  575. } VulkanUniformBufferStage;
  576. typedef struct VulkanFramebuffer
  577. {
  578. VkFramebuffer framebuffer;
  579. SDL_AtomicInt referenceCount;
  580. } VulkanFramebuffer;
  581. typedef struct WindowData
  582. {
  583. SDL_Window *window;
  584. SDL_GPUSwapchainComposition swapchainComposition;
  585. SDL_GPUPresentMode presentMode;
  586. bool needsSwapchainRecreate;
  587. bool needsSurfaceRecreate;
  588. Uint32 swapchainCreateWidth;
  589. Uint32 swapchainCreateHeight;
  590. // Window surface
  591. VkSurfaceKHR surface;
  592. // Swapchain for window surface
  593. VkSwapchainKHR swapchain;
  594. VkFormat format;
  595. VkColorSpaceKHR colorSpace;
  596. VkComponentMapping swapchainSwizzle;
  597. bool usingFallbackFormat;
  598. // Swapchain images
  599. VulkanTextureContainer *textureContainers; // use containers so that swapchain textures can use the same API as other textures
  600. Uint32 imageCount;
  601. Uint32 width;
  602. Uint32 height;
  603. // Synchronization primitives
  604. VkSemaphore imageAvailableSemaphore[MAX_FRAMES_IN_FLIGHT];
  605. VkSemaphore *renderFinishedSemaphore;
  606. SDL_GPUFence *inFlightFences[MAX_FRAMES_IN_FLIGHT];
  607. Uint32 frameCounter;
  608. } WindowData;
  609. typedef struct SwapchainSupportDetails
  610. {
  611. VkSurfaceCapabilitiesKHR capabilities;
  612. VkSurfaceFormatKHR *formats;
  613. Uint32 formatsLength;
  614. VkPresentModeKHR *presentModes;
  615. Uint32 presentModesLength;
  616. } SwapchainSupportDetails;
  617. typedef struct VulkanPresentData
  618. {
  619. WindowData *windowData;
  620. Uint32 swapchainImageIndex;
  621. } VulkanPresentData;
  622. struct VulkanUniformBuffer
  623. {
  624. VulkanBuffer *buffer;
  625. Uint32 drawOffset;
  626. Uint32 writeOffset;
  627. };
  628. typedef struct VulkanDescriptorInfo
  629. {
  630. VkDescriptorType descriptorType;
  631. VkShaderStageFlagBits stageFlag;
  632. } VulkanDescriptorInfo;
  633. typedef struct DescriptorSetPool
  634. {
  635. // It's a pool... of pools!!!
  636. Uint32 poolCount;
  637. VkDescriptorPool *descriptorPools;
  638. // We'll just manage the descriptor sets ourselves instead of freeing the sets
  639. VkDescriptorSet *descriptorSets;
  640. Uint32 descriptorSetCount;
  641. Uint32 descriptorSetIndex;
  642. } DescriptorSetPool;
  643. // A command buffer acquires a cache at command buffer acquisition time
  644. typedef struct DescriptorSetCache
  645. {
  646. // Pools are indexed by DescriptorSetLayoutID which increases monotonically
  647. // There's only a certain number of maximum layouts possible since we de-duplicate them.
  648. DescriptorSetPool *pools;
  649. Uint32 poolCount;
  650. } DescriptorSetCache;
  651. typedef struct DescriptorSetLayoutHashTableKey
  652. {
  653. VkShaderStageFlagBits shaderStage;
  654. // Category 1: read resources
  655. Uint32 samplerCount;
  656. Uint32 storageBufferCount;
  657. Uint32 storageTextureCount;
  658. // Category 2: write resources
  659. Uint32 writeStorageBufferCount;
  660. Uint32 writeStorageTextureCount;
  661. // Category 3: uniform buffers
  662. Uint32 uniformBufferCount;
  663. } DescriptorSetLayoutHashTableKey;
  664. typedef uint32_t DescriptorSetLayoutID;
  665. typedef struct DescriptorSetLayout
  666. {
  667. DescriptorSetLayoutID ID;
  668. VkDescriptorSetLayout descriptorSetLayout;
  669. // Category 1: read resources
  670. Uint32 samplerCount;
  671. Uint32 storageBufferCount;
  672. Uint32 storageTextureCount;
  673. // Category 2: write resources
  674. Uint32 writeStorageBufferCount;
  675. Uint32 writeStorageTextureCount;
  676. // Category 3: uniform buffers
  677. Uint32 uniformBufferCount;
  678. } DescriptorSetLayout;
  679. typedef struct GraphicsPipelineResourceLayoutHashTableKey
  680. {
  681. Uint32 vertexSamplerCount;
  682. Uint32 vertexStorageTextureCount;
  683. Uint32 vertexStorageBufferCount;
  684. Uint32 vertexUniformBufferCount;
  685. Uint32 fragmentSamplerCount;
  686. Uint32 fragmentStorageTextureCount;
  687. Uint32 fragmentStorageBufferCount;
  688. Uint32 fragmentUniformBufferCount;
  689. } GraphicsPipelineResourceLayoutHashTableKey;
  690. typedef struct VulkanGraphicsPipelineResourceLayout
  691. {
  692. VkPipelineLayout pipelineLayout;
  693. /*
  694. * Descriptor set layout is as follows:
  695. * 0: vertex resources
  696. * 1: vertex uniform buffers
  697. * 2: fragment resources
  698. * 3: fragment uniform buffers
  699. */
  700. DescriptorSetLayout *descriptorSetLayouts[4];
  701. Uint32 vertexSamplerCount;
  702. Uint32 vertexStorageTextureCount;
  703. Uint32 vertexStorageBufferCount;
  704. Uint32 vertexUniformBufferCount;
  705. Uint32 fragmentSamplerCount;
  706. Uint32 fragmentStorageTextureCount;
  707. Uint32 fragmentStorageBufferCount;
  708. Uint32 fragmentUniformBufferCount;
  709. } VulkanGraphicsPipelineResourceLayout;
  710. typedef struct VulkanGraphicsPipeline
  711. {
  712. GraphicsPipelineCommonHeader header;
  713. VkPipeline pipeline;
  714. SDL_GPUPrimitiveType primitiveType;
  715. VulkanGraphicsPipelineResourceLayout *resourceLayout;
  716. VulkanShader *vertexShader;
  717. VulkanShader *fragmentShader;
  718. SDL_AtomicInt referenceCount;
  719. } VulkanGraphicsPipeline;
  720. typedef struct ComputePipelineResourceLayoutHashTableKey
  721. {
  722. Uint32 samplerCount;
  723. Uint32 readonlyStorageTextureCount;
  724. Uint32 readonlyStorageBufferCount;
  725. Uint32 readWriteStorageTextureCount;
  726. Uint32 readWriteStorageBufferCount;
  727. Uint32 uniformBufferCount;
  728. } ComputePipelineResourceLayoutHashTableKey;
  729. typedef struct VulkanComputePipelineResourceLayout
  730. {
  731. VkPipelineLayout pipelineLayout;
  732. /*
  733. * Descriptor set layout is as follows:
  734. * 0: samplers, then read-only textures, then read-only buffers
  735. * 1: write-only textures, then write-only buffers
  736. * 2: uniform buffers
  737. */
  738. DescriptorSetLayout *descriptorSetLayouts[3];
  739. Uint32 numSamplers;
  740. Uint32 numReadonlyStorageTextures;
  741. Uint32 numReadonlyStorageBuffers;
  742. Uint32 numReadWriteStorageTextures;
  743. Uint32 numReadWriteStorageBuffers;
  744. Uint32 numUniformBuffers;
  745. } VulkanComputePipelineResourceLayout;
  746. typedef struct VulkanComputePipeline
  747. {
  748. ComputePipelineCommonHeader header;
  749. VkShaderModule shaderModule;
  750. VkPipeline pipeline;
  751. VulkanComputePipelineResourceLayout *resourceLayout;
  752. SDL_AtomicInt referenceCount;
  753. } VulkanComputePipeline;
  754. typedef struct RenderPassColorTargetDescription
  755. {
  756. VkFormat format;
  757. SDL_GPULoadOp loadOp;
  758. SDL_GPUStoreOp storeOp;
  759. } RenderPassColorTargetDescription;
  760. typedef struct RenderPassDepthStencilTargetDescription
  761. {
  762. VkFormat format;
  763. SDL_GPULoadOp loadOp;
  764. SDL_GPUStoreOp storeOp;
  765. SDL_GPULoadOp stencilLoadOp;
  766. SDL_GPUStoreOp stencilStoreOp;
  767. } RenderPassDepthStencilTargetDescription;
  768. typedef struct CommandPoolHashTableKey
  769. {
  770. SDL_ThreadID threadID;
  771. } CommandPoolHashTableKey;
  772. typedef struct RenderPassHashTableKey
  773. {
  774. RenderPassColorTargetDescription colorTargetDescriptions[MAX_COLOR_TARGET_BINDINGS];
  775. Uint32 numColorTargets;
  776. VkFormat resolveTargetFormats[MAX_COLOR_TARGET_BINDINGS];
  777. Uint32 numResolveTargets;
  778. RenderPassDepthStencilTargetDescription depthStencilTargetDescription;
  779. VkSampleCountFlagBits sampleCount;
  780. } RenderPassHashTableKey;
  781. typedef struct VulkanRenderPassHashTableValue
  782. {
  783. VkRenderPass handle;
  784. } VulkanRenderPassHashTableValue;
  785. typedef struct FramebufferHashTableKey
  786. {
  787. VkImageView colorAttachmentViews[MAX_COLOR_TARGET_BINDINGS];
  788. Uint32 numColorTargets;
  789. VkImageView resolveAttachmentViews[MAX_COLOR_TARGET_BINDINGS];
  790. Uint32 numResolveAttachments;
  791. VkImageView depthStencilAttachmentView;
  792. Uint32 width;
  793. Uint32 height;
  794. } FramebufferHashTableKey;
  795. // Command structures
  796. typedef struct VulkanFencePool
  797. {
  798. SDL_Mutex *lock;
  799. VulkanFenceHandle **availableFences;
  800. Uint32 availableFenceCount;
  801. Uint32 availableFenceCapacity;
  802. } VulkanFencePool;
  803. typedef struct VulkanCommandPool VulkanCommandPool;
  804. typedef struct VulkanRenderer VulkanRenderer;
  805. typedef struct VulkanCommandBuffer
  806. {
  807. CommandBufferCommonHeader common;
  808. VulkanRenderer *renderer;
  809. VkCommandBuffer commandBuffer;
  810. VulkanCommandPool *commandPool;
  811. VulkanPresentData *presentDatas;
  812. Uint32 presentDataCount;
  813. Uint32 presentDataCapacity;
  814. VkSemaphore *waitSemaphores;
  815. Uint32 waitSemaphoreCount;
  816. Uint32 waitSemaphoreCapacity;
  817. VkSemaphore *signalSemaphores;
  818. Uint32 signalSemaphoreCount;
  819. Uint32 signalSemaphoreCapacity;
  820. VulkanComputePipeline *currentComputePipeline;
  821. VulkanGraphicsPipeline *currentGraphicsPipeline;
  822. // Keep track of resources transitioned away from their default state to barrier them on pass end
  823. VulkanTextureSubresource *colorAttachmentSubresources[MAX_COLOR_TARGET_BINDINGS];
  824. Uint32 colorAttachmentSubresourceCount;
  825. VulkanTextureSubresource *resolveAttachmentSubresources[MAX_COLOR_TARGET_BINDINGS];
  826. Uint32 resolveAttachmentSubresourceCount;
  827. VulkanTextureSubresource *depthStencilAttachmentSubresource; // may be NULL
  828. // Dynamic state
  829. VkViewport currentViewport;
  830. VkRect2D currentScissor;
  831. float blendConstants[4];
  832. Uint8 stencilRef;
  833. // Resource bind state
  834. DescriptorSetCache *descriptorSetCache; // acquired when command buffer is acquired
  835. bool needNewVertexResourceDescriptorSet;
  836. bool needNewVertexUniformDescriptorSet;
  837. bool needNewVertexUniformOffsets;
  838. bool needNewFragmentResourceDescriptorSet;
  839. bool needNewFragmentUniformDescriptorSet;
  840. bool needNewFragmentUniformOffsets;
  841. bool needNewComputeReadOnlyDescriptorSet;
  842. bool needNewComputeReadWriteDescriptorSet;
  843. bool needNewComputeUniformDescriptorSet;
  844. bool needNewComputeUniformOffsets;
  845. VkDescriptorSet vertexResourceDescriptorSet;
  846. VkDescriptorSet vertexUniformDescriptorSet;
  847. VkDescriptorSet fragmentResourceDescriptorSet;
  848. VkDescriptorSet fragmentUniformDescriptorSet;
  849. VkDescriptorSet computeReadOnlyDescriptorSet;
  850. VkDescriptorSet computeReadWriteDescriptorSet;
  851. VkDescriptorSet computeUniformDescriptorSet;
  852. VkBuffer vertexBuffers[MAX_VERTEX_BUFFERS];
  853. VkDeviceSize vertexBufferOffsets[MAX_VERTEX_BUFFERS];
  854. Uint32 vertexBufferCount;
  855. bool needVertexBufferBind;
  856. VkImageView vertexSamplerTextureViewBindings[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  857. VkSampler vertexSamplerBindings[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  858. VkImageView vertexStorageTextureViewBindings[MAX_STORAGE_TEXTURES_PER_STAGE];
  859. VkBuffer vertexStorageBufferBindings[MAX_STORAGE_BUFFERS_PER_STAGE];
  860. VkImageView fragmentSamplerTextureViewBindings[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  861. VkSampler fragmentSamplerBindings[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  862. VkImageView fragmentStorageTextureViewBindings[MAX_STORAGE_TEXTURES_PER_STAGE];
  863. VkBuffer fragmentStorageBufferBindings[MAX_STORAGE_BUFFERS_PER_STAGE];
  864. VkImageView computeSamplerTextureViewBindings[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  865. VkSampler computeSamplerBindings[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  866. VkImageView readOnlyComputeStorageTextureViewBindings[MAX_STORAGE_TEXTURES_PER_STAGE];
  867. VkBuffer readOnlyComputeStorageBufferBindings[MAX_STORAGE_BUFFERS_PER_STAGE];
  868. // Track these separately because barriers can happen mid compute pass
  869. VulkanTexture *readOnlyComputeStorageTextures[MAX_STORAGE_TEXTURES_PER_STAGE];
  870. VulkanBuffer *readOnlyComputeStorageBuffers[MAX_STORAGE_BUFFERS_PER_STAGE];
  871. VkImageView readWriteComputeStorageTextureViewBindings[MAX_COMPUTE_WRITE_TEXTURES];
  872. VkBuffer readWriteComputeStorageBufferBindings[MAX_COMPUTE_WRITE_BUFFERS];
  873. // Track these separately because they are barriered when the compute pass begins
  874. VulkanTextureSubresource *readWriteComputeStorageTextureSubresources[MAX_COMPUTE_WRITE_TEXTURES];
  875. Uint32 readWriteComputeStorageTextureSubresourceCount;
  876. VulkanBuffer *readWriteComputeStorageBuffers[MAX_COMPUTE_WRITE_BUFFERS];
  877. // Uniform buffers
  878. VulkanUniformBuffer *vertexUniformBuffers[MAX_UNIFORM_BUFFERS_PER_STAGE];
  879. VulkanUniformBuffer *fragmentUniformBuffers[MAX_UNIFORM_BUFFERS_PER_STAGE];
  880. VulkanUniformBuffer *computeUniformBuffers[MAX_UNIFORM_BUFFERS_PER_STAGE];
  881. // Track used resources
  882. VulkanBuffer **usedBuffers;
  883. Sint32 usedBufferCount;
  884. Sint32 usedBufferCapacity;
  885. VulkanTexture **usedTextures;
  886. Sint32 usedTextureCount;
  887. Sint32 usedTextureCapacity;
  888. VulkanSampler **usedSamplers;
  889. Sint32 usedSamplerCount;
  890. Sint32 usedSamplerCapacity;
  891. VulkanGraphicsPipeline **usedGraphicsPipelines;
  892. Sint32 usedGraphicsPipelineCount;
  893. Sint32 usedGraphicsPipelineCapacity;
  894. VulkanComputePipeline **usedComputePipelines;
  895. Sint32 usedComputePipelineCount;
  896. Sint32 usedComputePipelineCapacity;
  897. VulkanFramebuffer **usedFramebuffers;
  898. Sint32 usedFramebufferCount;
  899. Sint32 usedFramebufferCapacity;
  900. VulkanUniformBuffer **usedUniformBuffers;
  901. Sint32 usedUniformBufferCount;
  902. Sint32 usedUniformBufferCapacity;
  903. VulkanFenceHandle *inFlightFence;
  904. bool autoReleaseFence;
  905. bool swapchainRequested;
  906. bool isDefrag; // Whether this CB was created for defragging
  907. } VulkanCommandBuffer;
  908. struct VulkanCommandPool
  909. {
  910. SDL_ThreadID threadID;
  911. VkCommandPool commandPool;
  912. VulkanCommandBuffer **inactiveCommandBuffers;
  913. Uint32 inactiveCommandBufferCapacity;
  914. Uint32 inactiveCommandBufferCount;
  915. };
  916. // Feature Checks
  917. typedef struct VulkanFeatures
  918. {
  919. Uint32 desiredApiVersion;
  920. VkPhysicalDeviceFeatures desiredVulkan10DeviceFeatures;
  921. VkPhysicalDeviceVulkan11Features desiredVulkan11DeviceFeatures;
  922. VkPhysicalDeviceVulkan12Features desiredVulkan12DeviceFeatures;
  923. VkPhysicalDeviceVulkan13Features desiredVulkan13DeviceFeatures;
  924. bool usesCustomVulkanOptions;
  925. Uint32 additionalDeviceExtensionCount;
  926. const char **additionalDeviceExtensionNames;
  927. Uint32 additionalInstanceExtensionCount;
  928. const char **additionalInstanceExtensionNames;
  929. } VulkanFeatures;
  930. // Context
  931. struct VulkanRenderer
  932. {
  933. VkInstance instance;
  934. VkPhysicalDevice physicalDevice;
  935. VkPhysicalDeviceProperties2KHR physicalDeviceProperties;
  936. VkPhysicalDeviceDriverPropertiesKHR physicalDeviceDriverProperties;
  937. VkDevice logicalDevice;
  938. Uint8 integratedMemoryNotification;
  939. Uint8 outOfDeviceLocalMemoryWarning;
  940. Uint8 outofBARMemoryWarning;
  941. Uint8 fillModeOnlyWarning;
  942. bool debugMode;
  943. bool preferLowPower;
  944. bool requireHardwareAcceleration;
  945. SDL_PropertiesID props;
  946. Uint32 allowedFramesInFlight;
  947. VulkanExtensions supports;
  948. bool supportsDebugUtils;
  949. bool supportsColorspace;
  950. bool supportsPhysicalDeviceProperties2;
  951. bool supportsFillModeNonSolid;
  952. bool supportsMultiDrawIndirect;
  953. VulkanMemoryAllocator *memoryAllocator;
  954. VkPhysicalDeviceMemoryProperties memoryProperties;
  955. bool checkEmptyAllocations;
  956. WindowData **claimedWindows;
  957. Uint32 claimedWindowCount;
  958. Uint32 claimedWindowCapacity;
  959. Uint32 queueFamilyIndex;
  960. VkQueue unifiedQueue;
  961. VulkanCommandBuffer **submittedCommandBuffers;
  962. Uint32 submittedCommandBufferCount;
  963. Uint32 submittedCommandBufferCapacity;
  964. VulkanFencePool fencePool;
  965. SDL_HashTable *commandPoolHashTable;
  966. SDL_HashTable *renderPassHashTable;
  967. SDL_HashTable *framebufferHashTable;
  968. SDL_HashTable *graphicsPipelineResourceLayoutHashTable;
  969. SDL_HashTable *computePipelineResourceLayoutHashTable;
  970. SDL_HashTable *descriptorSetLayoutHashTable;
  971. VulkanUniformBuffer **uniformBufferPool;
  972. Uint32 uniformBufferPoolCount;
  973. Uint32 uniformBufferPoolCapacity;
  974. DescriptorSetCache **descriptorSetCachePool;
  975. Uint32 descriptorSetCachePoolCount;
  976. Uint32 descriptorSetCachePoolCapacity;
  977. SDL_AtomicInt layoutResourceID;
  978. Uint32 minUBOAlignment;
  979. // Deferred resource destruction
  980. VulkanTexture **texturesToDestroy;
  981. Uint32 texturesToDestroyCount;
  982. Uint32 texturesToDestroyCapacity;
  983. VulkanBuffer **buffersToDestroy;
  984. Uint32 buffersToDestroyCount;
  985. Uint32 buffersToDestroyCapacity;
  986. VulkanSampler **samplersToDestroy;
  987. Uint32 samplersToDestroyCount;
  988. Uint32 samplersToDestroyCapacity;
  989. VulkanGraphicsPipeline **graphicsPipelinesToDestroy;
  990. Uint32 graphicsPipelinesToDestroyCount;
  991. Uint32 graphicsPipelinesToDestroyCapacity;
  992. VulkanComputePipeline **computePipelinesToDestroy;
  993. Uint32 computePipelinesToDestroyCount;
  994. Uint32 computePipelinesToDestroyCapacity;
  995. VulkanShader **shadersToDestroy;
  996. Uint32 shadersToDestroyCount;
  997. Uint32 shadersToDestroyCapacity;
  998. VulkanFramebuffer **framebuffersToDestroy;
  999. Uint32 framebuffersToDestroyCount;
  1000. Uint32 framebuffersToDestroyCapacity;
  1001. SDL_Mutex *allocatorLock;
  1002. SDL_Mutex *disposeLock;
  1003. SDL_Mutex *submitLock;
  1004. SDL_Mutex *acquireCommandBufferLock;
  1005. SDL_Mutex *acquireUniformBufferLock;
  1006. SDL_Mutex *renderPassFetchLock;
  1007. SDL_Mutex *framebufferFetchLock;
  1008. SDL_Mutex *graphicsPipelineLayoutFetchLock;
  1009. SDL_Mutex *computePipelineLayoutFetchLock;
  1010. SDL_Mutex *descriptorSetLayoutFetchLock;
  1011. SDL_Mutex *windowLock;
  1012. Uint8 defragInProgress;
  1013. VulkanMemoryAllocation **allocationsToDefrag;
  1014. Uint32 allocationsToDefragCount;
  1015. Uint32 allocationsToDefragCapacity;
  1016. #define VULKAN_INSTANCE_FUNCTION(func) \
  1017. PFN_##func func;
  1018. #define VULKAN_DEVICE_FUNCTION(func) \
  1019. PFN_##func func;
  1020. #include "SDL_gpu_vulkan_vkfuncs.h"
  1021. };
  1022. // Forward declarations
  1023. static bool VULKAN_INTERNAL_DefragmentMemory(VulkanRenderer *renderer, VulkanCommandBuffer *commandBuffer);
  1024. static bool VULKAN_INTERNAL_BeginCommandBuffer(VulkanRenderer *renderer, VulkanCommandBuffer *commandBuffer);
  1025. static void VULKAN_ReleaseWindow(SDL_GPURenderer *driverData, SDL_Window *window);
  1026. static bool VULKAN_Wait(SDL_GPURenderer *driverData);
  1027. static bool VULKAN_WaitForFences(SDL_GPURenderer *driverData, bool waitAll, SDL_GPUFence *const *fences, Uint32 numFences);
  1028. static bool VULKAN_Submit(SDL_GPUCommandBuffer *commandBuffer);
  1029. static SDL_GPUCommandBuffer *VULKAN_AcquireCommandBuffer(SDL_GPURenderer *driverData);
  1030. // Error Handling
  1031. static inline const char *VkErrorMessages(VkResult code)
  1032. {
  1033. #define ERR_TO_STR(e) \
  1034. case e: \
  1035. return #e;
  1036. switch (code) {
  1037. ERR_TO_STR(VK_ERROR_OUT_OF_HOST_MEMORY)
  1038. ERR_TO_STR(VK_ERROR_OUT_OF_DEVICE_MEMORY)
  1039. ERR_TO_STR(VK_ERROR_FRAGMENTED_POOL)
  1040. ERR_TO_STR(VK_ERROR_OUT_OF_POOL_MEMORY)
  1041. ERR_TO_STR(VK_ERROR_INITIALIZATION_FAILED)
  1042. ERR_TO_STR(VK_ERROR_LAYER_NOT_PRESENT)
  1043. ERR_TO_STR(VK_ERROR_EXTENSION_NOT_PRESENT)
  1044. ERR_TO_STR(VK_ERROR_FEATURE_NOT_PRESENT)
  1045. ERR_TO_STR(VK_ERROR_TOO_MANY_OBJECTS)
  1046. ERR_TO_STR(VK_ERROR_DEVICE_LOST)
  1047. ERR_TO_STR(VK_ERROR_INCOMPATIBLE_DRIVER)
  1048. ERR_TO_STR(VK_ERROR_OUT_OF_DATE_KHR)
  1049. ERR_TO_STR(VK_ERROR_SURFACE_LOST_KHR)
  1050. ERR_TO_STR(VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT)
  1051. ERR_TO_STR(VK_SUBOPTIMAL_KHR)
  1052. ERR_TO_STR(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR)
  1053. ERR_TO_STR(VK_ERROR_INVALID_SHADER_NV)
  1054. default:
  1055. return "Unhandled VkResult!";
  1056. }
  1057. #undef ERR_TO_STR
  1058. }
  1059. #define SET_ERROR(fmt, msg) \
  1060. do { \
  1061. if (renderer->debugMode) { \
  1062. SDL_LogError(SDL_LOG_CATEGORY_GPU, fmt, msg); \
  1063. } \
  1064. SDL_SetError((fmt), (msg)); \
  1065. } while (0)
  1066. #define SET_STRING_ERROR(msg) SET_ERROR("%s", msg)
  1067. #define SET_ERROR_AND_RETURN(fmt, msg, ret) \
  1068. do { \
  1069. SET_ERROR(fmt, msg); \
  1070. return ret; \
  1071. } while (0)
  1072. #define SET_STRING_ERROR_AND_RETURN(msg, ret) SET_ERROR_AND_RETURN("%s", msg, ret)
  1073. #define CHECK_VULKAN_ERROR_AND_RETURN(res, fn, ret) \
  1074. do { \
  1075. if ((res) != VK_SUCCESS) { \
  1076. if (renderer->debugMode) { \
  1077. SDL_LogError(SDL_LOG_CATEGORY_GPU, "%s %s", #fn, VkErrorMessages(res)); \
  1078. } \
  1079. SDL_SetError("%s %s", #fn, VkErrorMessages(res)); \
  1080. return (ret); \
  1081. } \
  1082. } while (0)
  1083. // Utility
  1084. static inline VkPolygonMode SDLToVK_PolygonMode(
  1085. VulkanRenderer *renderer,
  1086. SDL_GPUFillMode mode)
  1087. {
  1088. if (mode == SDL_GPU_FILLMODE_FILL) {
  1089. return VK_POLYGON_MODE_FILL; // always available!
  1090. }
  1091. if (renderer->supportsFillModeNonSolid && mode == SDL_GPU_FILLMODE_LINE) {
  1092. return VK_POLYGON_MODE_LINE;
  1093. }
  1094. if (!renderer->fillModeOnlyWarning) {
  1095. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Unsupported fill mode requested, using FILL!");
  1096. renderer->fillModeOnlyWarning = 1;
  1097. }
  1098. return VK_POLYGON_MODE_FILL;
  1099. }
  1100. // Memory Management
  1101. // Vulkan: Memory Allocation
  1102. static inline VkDeviceSize VULKAN_INTERNAL_NextHighestAlignment(
  1103. VkDeviceSize n,
  1104. VkDeviceSize align)
  1105. {
  1106. return align * ((n + align - 1) / align);
  1107. }
  1108. static inline Uint32 VULKAN_INTERNAL_NextHighestAlignment32(
  1109. Uint32 n,
  1110. Uint32 align)
  1111. {
  1112. return align * ((n + align - 1) / align);
  1113. }
  1114. static void VULKAN_INTERNAL_MakeMemoryUnavailable(
  1115. VulkanMemoryAllocation *allocation)
  1116. {
  1117. Uint32 i, j;
  1118. VulkanMemoryFreeRegion *freeRegion;
  1119. allocation->availableForAllocation = 0;
  1120. for (i = 0; i < allocation->freeRegionCount; i += 1) {
  1121. freeRegion = allocation->freeRegions[i];
  1122. // close the gap in the sorted list
  1123. if (allocation->allocator->sortedFreeRegionCount > 1) {
  1124. for (j = freeRegion->sortedIndex; j < allocation->allocator->sortedFreeRegionCount - 1; j += 1) {
  1125. allocation->allocator->sortedFreeRegions[j] =
  1126. allocation->allocator->sortedFreeRegions[j + 1];
  1127. allocation->allocator->sortedFreeRegions[j]->sortedIndex = j;
  1128. }
  1129. }
  1130. allocation->allocator->sortedFreeRegionCount -= 1;
  1131. }
  1132. }
  1133. static void VULKAN_INTERNAL_MarkAllocationsForDefrag(
  1134. VulkanRenderer *renderer)
  1135. {
  1136. Uint32 memoryType, allocationIndex;
  1137. VulkanMemorySubAllocator *currentAllocator;
  1138. for (memoryType = 0; memoryType < VK_MAX_MEMORY_TYPES; memoryType += 1) {
  1139. currentAllocator = &renderer->memoryAllocator->subAllocators[memoryType];
  1140. for (allocationIndex = 0; allocationIndex < currentAllocator->allocationCount; allocationIndex += 1) {
  1141. if (currentAllocator->allocations[allocationIndex]->availableForAllocation == 1) {
  1142. if (currentAllocator->allocations[allocationIndex]->freeRegionCount > 1) {
  1143. EXPAND_ARRAY_IF_NEEDED(
  1144. renderer->allocationsToDefrag,
  1145. VulkanMemoryAllocation *,
  1146. renderer->allocationsToDefragCount + 1,
  1147. renderer->allocationsToDefragCapacity,
  1148. renderer->allocationsToDefragCapacity * 2);
  1149. renderer->allocationsToDefrag[renderer->allocationsToDefragCount] =
  1150. currentAllocator->allocations[allocationIndex];
  1151. renderer->allocationsToDefragCount += 1;
  1152. VULKAN_INTERNAL_MakeMemoryUnavailable(
  1153. currentAllocator->allocations[allocationIndex]);
  1154. }
  1155. }
  1156. }
  1157. }
  1158. }
  1159. static void VULKAN_INTERNAL_RemoveMemoryFreeRegion(
  1160. VulkanRenderer *renderer,
  1161. VulkanMemoryFreeRegion *freeRegion)
  1162. {
  1163. Uint32 i;
  1164. SDL_LockMutex(renderer->allocatorLock);
  1165. if (freeRegion->allocation->availableForAllocation) {
  1166. // close the gap in the sorted list
  1167. if (freeRegion->allocation->allocator->sortedFreeRegionCount > 1) {
  1168. for (i = freeRegion->sortedIndex; i < freeRegion->allocation->allocator->sortedFreeRegionCount - 1; i += 1) {
  1169. freeRegion->allocation->allocator->sortedFreeRegions[i] =
  1170. freeRegion->allocation->allocator->sortedFreeRegions[i + 1];
  1171. freeRegion->allocation->allocator->sortedFreeRegions[i]->sortedIndex = i;
  1172. }
  1173. }
  1174. freeRegion->allocation->allocator->sortedFreeRegionCount -= 1;
  1175. }
  1176. // close the gap in the buffer list
  1177. if (freeRegion->allocation->freeRegionCount > 1 && freeRegion->allocationIndex != freeRegion->allocation->freeRegionCount - 1) {
  1178. freeRegion->allocation->freeRegions[freeRegion->allocationIndex] =
  1179. freeRegion->allocation->freeRegions[freeRegion->allocation->freeRegionCount - 1];
  1180. freeRegion->allocation->freeRegions[freeRegion->allocationIndex]->allocationIndex =
  1181. freeRegion->allocationIndex;
  1182. }
  1183. freeRegion->allocation->freeRegionCount -= 1;
  1184. freeRegion->allocation->freeSpace -= freeRegion->size;
  1185. SDL_free(freeRegion);
  1186. SDL_UnlockMutex(renderer->allocatorLock);
  1187. }
  1188. static void VULKAN_INTERNAL_NewMemoryFreeRegion(
  1189. VulkanRenderer *renderer,
  1190. VulkanMemoryAllocation *allocation,
  1191. VkDeviceSize offset,
  1192. VkDeviceSize size)
  1193. {
  1194. VulkanMemoryFreeRegion *newFreeRegion;
  1195. VkDeviceSize newOffset, newSize;
  1196. Sint32 insertionIndex = 0;
  1197. SDL_LockMutex(renderer->allocatorLock);
  1198. // look for an adjacent region to merge
  1199. for (Sint32 i = allocation->freeRegionCount - 1; i >= 0; i -= 1) {
  1200. // check left side
  1201. if (allocation->freeRegions[i]->offset + allocation->freeRegions[i]->size == offset) {
  1202. newOffset = allocation->freeRegions[i]->offset;
  1203. newSize = allocation->freeRegions[i]->size + size;
  1204. VULKAN_INTERNAL_RemoveMemoryFreeRegion(renderer, allocation->freeRegions[i]);
  1205. VULKAN_INTERNAL_NewMemoryFreeRegion(renderer, allocation, newOffset, newSize);
  1206. SDL_UnlockMutex(renderer->allocatorLock);
  1207. return;
  1208. }
  1209. // check right side
  1210. if (allocation->freeRegions[i]->offset == offset + size) {
  1211. newOffset = offset;
  1212. newSize = allocation->freeRegions[i]->size + size;
  1213. VULKAN_INTERNAL_RemoveMemoryFreeRegion(renderer, allocation->freeRegions[i]);
  1214. VULKAN_INTERNAL_NewMemoryFreeRegion(renderer, allocation, newOffset, newSize);
  1215. SDL_UnlockMutex(renderer->allocatorLock);
  1216. return;
  1217. }
  1218. }
  1219. // region is not contiguous with another free region, make a new one
  1220. allocation->freeRegionCount += 1;
  1221. if (allocation->freeRegionCount > allocation->freeRegionCapacity) {
  1222. allocation->freeRegionCapacity *= 2;
  1223. allocation->freeRegions = SDL_realloc(
  1224. allocation->freeRegions,
  1225. sizeof(VulkanMemoryFreeRegion *) * allocation->freeRegionCapacity);
  1226. }
  1227. newFreeRegion = SDL_malloc(sizeof(VulkanMemoryFreeRegion));
  1228. newFreeRegion->offset = offset;
  1229. newFreeRegion->size = size;
  1230. newFreeRegion->allocation = allocation;
  1231. allocation->freeSpace += size;
  1232. allocation->freeRegions[allocation->freeRegionCount - 1] = newFreeRegion;
  1233. newFreeRegion->allocationIndex = allocation->freeRegionCount - 1;
  1234. if (allocation->availableForAllocation) {
  1235. for (Uint32 i = 0; i < allocation->allocator->sortedFreeRegionCount; i += 1) {
  1236. if (allocation->allocator->sortedFreeRegions[i]->size < size) {
  1237. // this is where the new region should go
  1238. break;
  1239. }
  1240. insertionIndex += 1;
  1241. }
  1242. if (allocation->allocator->sortedFreeRegionCount + 1 > allocation->allocator->sortedFreeRegionCapacity) {
  1243. allocation->allocator->sortedFreeRegionCapacity *= 2;
  1244. allocation->allocator->sortedFreeRegions = SDL_realloc(
  1245. allocation->allocator->sortedFreeRegions,
  1246. sizeof(VulkanMemoryFreeRegion *) * allocation->allocator->sortedFreeRegionCapacity);
  1247. }
  1248. // perform insertion sort
  1249. if (allocation->allocator->sortedFreeRegionCount > 0 && (Uint32)insertionIndex != allocation->allocator->sortedFreeRegionCount) {
  1250. for (Sint32 i = allocation->allocator->sortedFreeRegionCount; i > insertionIndex && i > 0; i -= 1) {
  1251. allocation->allocator->sortedFreeRegions[i] = allocation->allocator->sortedFreeRegions[i - 1];
  1252. allocation->allocator->sortedFreeRegions[i]->sortedIndex = i;
  1253. }
  1254. }
  1255. allocation->allocator->sortedFreeRegionCount += 1;
  1256. allocation->allocator->sortedFreeRegions[insertionIndex] = newFreeRegion;
  1257. newFreeRegion->sortedIndex = insertionIndex;
  1258. }
  1259. SDL_UnlockMutex(renderer->allocatorLock);
  1260. }
  1261. static VulkanMemoryUsedRegion *VULKAN_INTERNAL_NewMemoryUsedRegion(
  1262. VulkanRenderer *renderer,
  1263. VulkanMemoryAllocation *allocation,
  1264. VkDeviceSize offset,
  1265. VkDeviceSize size,
  1266. VkDeviceSize resourceOffset,
  1267. VkDeviceSize resourceSize,
  1268. VkDeviceSize alignment)
  1269. {
  1270. VulkanMemoryUsedRegion *memoryUsedRegion;
  1271. SDL_LockMutex(renderer->allocatorLock);
  1272. if (allocation->usedRegionCount == allocation->usedRegionCapacity) {
  1273. allocation->usedRegionCapacity *= 2;
  1274. allocation->usedRegions = SDL_realloc(
  1275. allocation->usedRegions,
  1276. allocation->usedRegionCapacity * sizeof(VulkanMemoryUsedRegion *));
  1277. }
  1278. memoryUsedRegion = SDL_malloc(sizeof(VulkanMemoryUsedRegion));
  1279. memoryUsedRegion->allocation = allocation;
  1280. memoryUsedRegion->offset = offset;
  1281. memoryUsedRegion->size = size;
  1282. memoryUsedRegion->resourceOffset = resourceOffset;
  1283. memoryUsedRegion->resourceSize = resourceSize;
  1284. memoryUsedRegion->alignment = alignment;
  1285. allocation->usedSpace += size;
  1286. allocation->usedRegions[allocation->usedRegionCount] = memoryUsedRegion;
  1287. allocation->usedRegionCount += 1;
  1288. SDL_UnlockMutex(renderer->allocatorLock);
  1289. return memoryUsedRegion;
  1290. }
  1291. static void VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  1292. VulkanRenderer *renderer,
  1293. VulkanMemoryUsedRegion *usedRegion)
  1294. {
  1295. Uint32 i;
  1296. SDL_LockMutex(renderer->allocatorLock);
  1297. for (i = 0; i < usedRegion->allocation->usedRegionCount; i += 1) {
  1298. if (usedRegion->allocation->usedRegions[i] == usedRegion) {
  1299. // plug the hole
  1300. if (i != usedRegion->allocation->usedRegionCount - 1) {
  1301. usedRegion->allocation->usedRegions[i] = usedRegion->allocation->usedRegions[usedRegion->allocation->usedRegionCount - 1];
  1302. }
  1303. break;
  1304. }
  1305. }
  1306. usedRegion->allocation->usedSpace -= usedRegion->size;
  1307. usedRegion->allocation->usedRegionCount -= 1;
  1308. VULKAN_INTERNAL_NewMemoryFreeRegion(
  1309. renderer,
  1310. usedRegion->allocation,
  1311. usedRegion->offset,
  1312. usedRegion->size);
  1313. if (usedRegion->allocation->usedRegionCount == 0) {
  1314. renderer->checkEmptyAllocations = true;
  1315. }
  1316. SDL_free(usedRegion);
  1317. SDL_UnlockMutex(renderer->allocatorLock);
  1318. }
  1319. static bool VULKAN_INTERNAL_CheckMemoryTypeArrayUnique(
  1320. Uint32 memoryTypeIndex,
  1321. const Uint32 *memoryTypeIndexArray,
  1322. Uint32 count)
  1323. {
  1324. Uint32 i = 0;
  1325. for (i = 0; i < count; i += 1) {
  1326. if (memoryTypeIndexArray[i] == memoryTypeIndex) {
  1327. return false;
  1328. }
  1329. }
  1330. return true;
  1331. }
  1332. /* Returns an array of memory type indices in order of preference.
  1333. * Memory types are requested with the following three guidelines:
  1334. *
  1335. * Required: Absolutely necessary
  1336. * Preferred: Nice to have, but not necessary
  1337. * Tolerable: Can be allowed if there are no other options
  1338. *
  1339. * We return memory types in this order:
  1340. * 1. Required and preferred. This is the best category.
  1341. * 2. Required only.
  1342. * 3. Required, preferred, and tolerable.
  1343. * 4. Required and tolerable. This is the worst category.
  1344. */
  1345. static Uint32 *VULKAN_INTERNAL_FindBestMemoryTypes(
  1346. VulkanRenderer *renderer,
  1347. Uint32 typeFilter,
  1348. VkMemoryPropertyFlags requiredProperties,
  1349. VkMemoryPropertyFlags preferredProperties,
  1350. VkMemoryPropertyFlags tolerableProperties,
  1351. Uint32 *pCount)
  1352. {
  1353. Uint32 i;
  1354. Uint32 index = 0;
  1355. Uint32 *result = SDL_malloc(sizeof(Uint32) * renderer->memoryProperties.memoryTypeCount);
  1356. // required + preferred + !tolerable
  1357. for (i = 0; i < renderer->memoryProperties.memoryTypeCount; i += 1) {
  1358. if ((typeFilter & (1 << i)) &&
  1359. (renderer->memoryProperties.memoryTypes[i].propertyFlags & requiredProperties) == requiredProperties &&
  1360. (renderer->memoryProperties.memoryTypes[i].propertyFlags & preferredProperties) == preferredProperties &&
  1361. (renderer->memoryProperties.memoryTypes[i].propertyFlags & tolerableProperties) == 0) {
  1362. if (VULKAN_INTERNAL_CheckMemoryTypeArrayUnique(
  1363. i,
  1364. result,
  1365. index)) {
  1366. result[index] = i;
  1367. index += 1;
  1368. }
  1369. }
  1370. }
  1371. // required + !preferred + !tolerable
  1372. for (i = 0; i < renderer->memoryProperties.memoryTypeCount; i += 1) {
  1373. if ((typeFilter & (1 << i)) &&
  1374. (renderer->memoryProperties.memoryTypes[i].propertyFlags & requiredProperties) == requiredProperties &&
  1375. (renderer->memoryProperties.memoryTypes[i].propertyFlags & preferredProperties) == 0 &&
  1376. (renderer->memoryProperties.memoryTypes[i].propertyFlags & tolerableProperties) == 0) {
  1377. if (VULKAN_INTERNAL_CheckMemoryTypeArrayUnique(
  1378. i,
  1379. result,
  1380. index)) {
  1381. result[index] = i;
  1382. index += 1;
  1383. }
  1384. }
  1385. }
  1386. // required + preferred + tolerable
  1387. for (i = 0; i < renderer->memoryProperties.memoryTypeCount; i += 1) {
  1388. if ((typeFilter & (1 << i)) &&
  1389. (renderer->memoryProperties.memoryTypes[i].propertyFlags & requiredProperties) == requiredProperties &&
  1390. (renderer->memoryProperties.memoryTypes[i].propertyFlags & preferredProperties) == preferredProperties &&
  1391. (renderer->memoryProperties.memoryTypes[i].propertyFlags & tolerableProperties) == tolerableProperties) {
  1392. if (VULKAN_INTERNAL_CheckMemoryTypeArrayUnique(
  1393. i,
  1394. result,
  1395. index)) {
  1396. result[index] = i;
  1397. index += 1;
  1398. }
  1399. }
  1400. }
  1401. // required + !preferred + tolerable
  1402. for (i = 0; i < renderer->memoryProperties.memoryTypeCount; i += 1) {
  1403. if ((typeFilter & (1 << i)) &&
  1404. (renderer->memoryProperties.memoryTypes[i].propertyFlags & requiredProperties) == requiredProperties &&
  1405. (renderer->memoryProperties.memoryTypes[i].propertyFlags & preferredProperties) == 0 &&
  1406. (renderer->memoryProperties.memoryTypes[i].propertyFlags & tolerableProperties) == tolerableProperties) {
  1407. if (VULKAN_INTERNAL_CheckMemoryTypeArrayUnique(
  1408. i,
  1409. result,
  1410. index)) {
  1411. result[index] = i;
  1412. index += 1;
  1413. }
  1414. }
  1415. }
  1416. *pCount = index;
  1417. return result;
  1418. }
  1419. static Uint32 *VULKAN_INTERNAL_FindBestBufferMemoryTypes(
  1420. VulkanRenderer *renderer,
  1421. VkBuffer buffer,
  1422. VkMemoryPropertyFlags requiredMemoryProperties,
  1423. VkMemoryPropertyFlags preferredMemoryProperties,
  1424. VkMemoryPropertyFlags tolerableMemoryProperties,
  1425. VkMemoryRequirements *pMemoryRequirements,
  1426. Uint32 *pCount)
  1427. {
  1428. renderer->vkGetBufferMemoryRequirements(
  1429. renderer->logicalDevice,
  1430. buffer,
  1431. pMemoryRequirements);
  1432. return VULKAN_INTERNAL_FindBestMemoryTypes(
  1433. renderer,
  1434. pMemoryRequirements->memoryTypeBits,
  1435. requiredMemoryProperties,
  1436. preferredMemoryProperties,
  1437. tolerableMemoryProperties,
  1438. pCount);
  1439. }
  1440. static Uint32 *VULKAN_INTERNAL_FindBestImageMemoryTypes(
  1441. VulkanRenderer *renderer,
  1442. VkImage image,
  1443. VkMemoryPropertyFlags preferredMemoryPropertyFlags,
  1444. VkMemoryRequirements *pMemoryRequirements,
  1445. Uint32 *pCount)
  1446. {
  1447. renderer->vkGetImageMemoryRequirements(
  1448. renderer->logicalDevice,
  1449. image,
  1450. pMemoryRequirements);
  1451. return VULKAN_INTERNAL_FindBestMemoryTypes(
  1452. renderer,
  1453. pMemoryRequirements->memoryTypeBits,
  1454. 0,
  1455. preferredMemoryPropertyFlags,
  1456. 0,
  1457. pCount);
  1458. }
  1459. static void VULKAN_INTERNAL_DeallocateMemory(
  1460. VulkanRenderer *renderer,
  1461. VulkanMemorySubAllocator *allocator,
  1462. Uint32 allocationIndex)
  1463. {
  1464. Uint32 i;
  1465. VulkanMemoryAllocation *allocation = allocator->allocations[allocationIndex];
  1466. SDL_LockMutex(renderer->allocatorLock);
  1467. // If this allocation was marked for defrag, cancel that
  1468. for (i = 0; i < renderer->allocationsToDefragCount; i += 1) {
  1469. if (allocation == renderer->allocationsToDefrag[i]) {
  1470. renderer->allocationsToDefrag[i] = renderer->allocationsToDefrag[renderer->allocationsToDefragCount - 1];
  1471. renderer->allocationsToDefragCount -= 1;
  1472. break;
  1473. }
  1474. }
  1475. for (i = 0; i < allocation->freeRegionCount; i += 1) {
  1476. VULKAN_INTERNAL_RemoveMemoryFreeRegion(
  1477. renderer,
  1478. allocation->freeRegions[i]);
  1479. }
  1480. SDL_free(allocation->freeRegions);
  1481. /* no need to iterate used regions because deallocate
  1482. * only happens when there are 0 used regions
  1483. */
  1484. SDL_free(allocation->usedRegions);
  1485. renderer->vkFreeMemory(
  1486. renderer->logicalDevice,
  1487. allocation->memory,
  1488. NULL);
  1489. SDL_DestroyMutex(allocation->memoryLock);
  1490. SDL_free(allocation);
  1491. if (allocationIndex != allocator->allocationCount - 1) {
  1492. allocator->allocations[allocationIndex] = allocator->allocations[allocator->allocationCount - 1];
  1493. }
  1494. allocator->allocationCount -= 1;
  1495. SDL_UnlockMutex(renderer->allocatorLock);
  1496. }
  1497. static Uint8 VULKAN_INTERNAL_AllocateMemory(
  1498. VulkanRenderer *renderer,
  1499. Uint32 memoryTypeIndex,
  1500. VkDeviceSize allocationSize,
  1501. Uint8 isHostVisible,
  1502. VulkanMemoryAllocation **pMemoryAllocation)
  1503. {
  1504. VulkanMemoryAllocation *allocation;
  1505. VulkanMemorySubAllocator *allocator = &renderer->memoryAllocator->subAllocators[memoryTypeIndex];
  1506. VkMemoryAllocateInfo allocInfo;
  1507. VkResult result;
  1508. allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  1509. allocInfo.pNext = NULL;
  1510. allocInfo.memoryTypeIndex = memoryTypeIndex;
  1511. allocInfo.allocationSize = allocationSize;
  1512. allocation = SDL_malloc(sizeof(VulkanMemoryAllocation));
  1513. allocation->size = allocationSize;
  1514. allocation->freeSpace = 0; // added by FreeRegions
  1515. allocation->usedSpace = 0; // added by UsedRegions
  1516. allocation->memoryLock = SDL_CreateMutex();
  1517. allocator->allocationCount += 1;
  1518. allocator->allocations = SDL_realloc(
  1519. allocator->allocations,
  1520. sizeof(VulkanMemoryAllocation *) * allocator->allocationCount);
  1521. allocator->allocations[allocator->allocationCount - 1] = allocation;
  1522. allocInfo.pNext = NULL;
  1523. allocation->availableForAllocation = 1;
  1524. allocation->usedRegions = SDL_malloc(sizeof(VulkanMemoryUsedRegion *));
  1525. allocation->usedRegionCount = 0;
  1526. allocation->usedRegionCapacity = 1;
  1527. allocation->freeRegions = SDL_malloc(sizeof(VulkanMemoryFreeRegion *));
  1528. allocation->freeRegionCount = 0;
  1529. allocation->freeRegionCapacity = 1;
  1530. allocation->allocator = allocator;
  1531. result = renderer->vkAllocateMemory(
  1532. renderer->logicalDevice,
  1533. &allocInfo,
  1534. NULL,
  1535. &allocation->memory);
  1536. if (result != VK_SUCCESS) {
  1537. // Uh oh, we couldn't allocate, time to clean up
  1538. SDL_free(allocation->freeRegions);
  1539. allocator->allocationCount -= 1;
  1540. allocator->allocations = SDL_realloc(
  1541. allocator->allocations,
  1542. sizeof(VulkanMemoryAllocation *) * allocator->allocationCount);
  1543. SDL_free(allocation);
  1544. return 0;
  1545. }
  1546. // Persistent mapping for host-visible memory
  1547. if (isHostVisible) {
  1548. result = renderer->vkMapMemory(
  1549. renderer->logicalDevice,
  1550. allocation->memory,
  1551. 0,
  1552. VK_WHOLE_SIZE,
  1553. 0,
  1554. (void **)&allocation->mapPointer);
  1555. CHECK_VULKAN_ERROR_AND_RETURN(result, vkMapMemory, 0);
  1556. } else {
  1557. allocation->mapPointer = NULL;
  1558. }
  1559. VULKAN_INTERNAL_NewMemoryFreeRegion(
  1560. renderer,
  1561. allocation,
  1562. 0,
  1563. allocation->size);
  1564. *pMemoryAllocation = allocation;
  1565. return 1;
  1566. }
  1567. static Uint8 VULKAN_INTERNAL_BindBufferMemory(
  1568. VulkanRenderer *renderer,
  1569. VulkanMemoryUsedRegion *usedRegion,
  1570. VkDeviceSize alignedOffset,
  1571. VkBuffer buffer)
  1572. {
  1573. VkResult vulkanResult;
  1574. SDL_LockMutex(usedRegion->allocation->memoryLock);
  1575. vulkanResult = renderer->vkBindBufferMemory(
  1576. renderer->logicalDevice,
  1577. buffer,
  1578. usedRegion->allocation->memory,
  1579. alignedOffset);
  1580. SDL_UnlockMutex(usedRegion->allocation->memoryLock);
  1581. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkBindBufferMemory, 0);
  1582. return 1;
  1583. }
  1584. static Uint8 VULKAN_INTERNAL_BindImageMemory(
  1585. VulkanRenderer *renderer,
  1586. VulkanMemoryUsedRegion *usedRegion,
  1587. VkDeviceSize alignedOffset,
  1588. VkImage image)
  1589. {
  1590. VkResult vulkanResult;
  1591. SDL_LockMutex(usedRegion->allocation->memoryLock);
  1592. vulkanResult = renderer->vkBindImageMemory(
  1593. renderer->logicalDevice,
  1594. image,
  1595. usedRegion->allocation->memory,
  1596. alignedOffset);
  1597. SDL_UnlockMutex(usedRegion->allocation->memoryLock);
  1598. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkBindImageMemory, 0);
  1599. return 1;
  1600. }
  1601. static Uint8 VULKAN_INTERNAL_BindResourceMemory(
  1602. VulkanRenderer *renderer,
  1603. Uint32 memoryTypeIndex,
  1604. VkMemoryRequirements *memoryRequirements,
  1605. VkDeviceSize resourceSize, // may be different from requirements size!
  1606. bool dedicated, // the entire memory allocation should be used for this resource
  1607. VkBuffer buffer, // may be VK_NULL_HANDLE
  1608. VkImage image, // may be VK_NULL_HANDLE
  1609. VulkanMemoryUsedRegion **pMemoryUsedRegion)
  1610. {
  1611. VulkanMemoryAllocation *allocation;
  1612. VulkanMemorySubAllocator *allocator;
  1613. VulkanMemoryFreeRegion *region;
  1614. VulkanMemoryFreeRegion *selectedRegion;
  1615. VulkanMemoryUsedRegion *usedRegion;
  1616. VkDeviceSize requiredSize, allocationSize;
  1617. VkDeviceSize alignedOffset = 0;
  1618. VkDeviceSize newRegionSize, newRegionOffset;
  1619. Uint8 isHostVisible, smallAllocation, allocationResult;
  1620. Sint32 i;
  1621. isHostVisible =
  1622. (renderer->memoryProperties.memoryTypes[memoryTypeIndex].propertyFlags &
  1623. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0;
  1624. allocator = &renderer->memoryAllocator->subAllocators[memoryTypeIndex];
  1625. requiredSize = memoryRequirements->size;
  1626. smallAllocation = requiredSize <= SMALL_ALLOCATION_THRESHOLD;
  1627. if ((buffer == VK_NULL_HANDLE && image == VK_NULL_HANDLE) ||
  1628. (buffer != VK_NULL_HANDLE && image != VK_NULL_HANDLE)) {
  1629. SDL_LogError(SDL_LOG_CATEGORY_GPU, "BindResourceMemory must be given either a VulkanBuffer or a VulkanTexture");
  1630. return 0;
  1631. }
  1632. SDL_LockMutex(renderer->allocatorLock);
  1633. selectedRegion = NULL;
  1634. if (dedicated) {
  1635. // Force an allocation
  1636. allocationSize = requiredSize;
  1637. } else {
  1638. // Search for a suitable existing free region
  1639. for (i = allocator->sortedFreeRegionCount - 1; i >= 0; i -= 1) {
  1640. region = allocator->sortedFreeRegions[i];
  1641. if (smallAllocation && region->allocation->size != SMALL_ALLOCATION_SIZE) {
  1642. // region is not in a small allocation
  1643. continue;
  1644. }
  1645. if (!smallAllocation && region->allocation->size == SMALL_ALLOCATION_SIZE) {
  1646. // allocation is not small and current region is in a small allocation
  1647. continue;
  1648. }
  1649. alignedOffset = VULKAN_INTERNAL_NextHighestAlignment(
  1650. region->offset,
  1651. memoryRequirements->alignment);
  1652. if (alignedOffset + requiredSize <= region->offset + region->size) {
  1653. selectedRegion = region;
  1654. break;
  1655. }
  1656. }
  1657. if (selectedRegion != NULL) {
  1658. region = selectedRegion;
  1659. allocation = region->allocation;
  1660. usedRegion = VULKAN_INTERNAL_NewMemoryUsedRegion(
  1661. renderer,
  1662. allocation,
  1663. region->offset,
  1664. requiredSize + (alignedOffset - region->offset),
  1665. alignedOffset,
  1666. resourceSize,
  1667. memoryRequirements->alignment);
  1668. usedRegion->isBuffer = buffer != VK_NULL_HANDLE;
  1669. newRegionSize = region->size - ((alignedOffset - region->offset) + requiredSize);
  1670. newRegionOffset = alignedOffset + requiredSize;
  1671. // remove and add modified region to re-sort
  1672. VULKAN_INTERNAL_RemoveMemoryFreeRegion(renderer, region);
  1673. // if size is 0, no need to re-insert
  1674. if (newRegionSize != 0) {
  1675. VULKAN_INTERNAL_NewMemoryFreeRegion(
  1676. renderer,
  1677. allocation,
  1678. newRegionOffset,
  1679. newRegionSize);
  1680. }
  1681. SDL_UnlockMutex(renderer->allocatorLock);
  1682. if (buffer != VK_NULL_HANDLE) {
  1683. if (!VULKAN_INTERNAL_BindBufferMemory(
  1684. renderer,
  1685. usedRegion,
  1686. alignedOffset,
  1687. buffer)) {
  1688. VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  1689. renderer,
  1690. usedRegion);
  1691. return 0;
  1692. }
  1693. } else if (image != VK_NULL_HANDLE) {
  1694. if (!VULKAN_INTERNAL_BindImageMemory(
  1695. renderer,
  1696. usedRegion,
  1697. alignedOffset,
  1698. image)) {
  1699. VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  1700. renderer,
  1701. usedRegion);
  1702. return 0;
  1703. }
  1704. }
  1705. *pMemoryUsedRegion = usedRegion;
  1706. return 1;
  1707. }
  1708. // No suitable free regions exist, allocate a new memory region
  1709. if (
  1710. renderer->allocationsToDefragCount == 0 &&
  1711. !renderer->defragInProgress) {
  1712. // Mark currently fragmented allocations for defrag
  1713. VULKAN_INTERNAL_MarkAllocationsForDefrag(renderer);
  1714. }
  1715. if (requiredSize > SMALL_ALLOCATION_THRESHOLD) {
  1716. // allocate a page of required size aligned to LARGE_ALLOCATION_INCREMENT increments
  1717. allocationSize =
  1718. VULKAN_INTERNAL_NextHighestAlignment(requiredSize, LARGE_ALLOCATION_INCREMENT);
  1719. } else {
  1720. allocationSize = SMALL_ALLOCATION_SIZE;
  1721. }
  1722. }
  1723. allocationResult = VULKAN_INTERNAL_AllocateMemory(
  1724. renderer,
  1725. memoryTypeIndex,
  1726. allocationSize,
  1727. isHostVisible,
  1728. &allocation);
  1729. // Uh oh, we're out of memory
  1730. if (allocationResult == 0) {
  1731. SDL_UnlockMutex(renderer->allocatorLock);
  1732. // Responsibility of the caller to handle being out of memory
  1733. return 2;
  1734. }
  1735. usedRegion = VULKAN_INTERNAL_NewMemoryUsedRegion(
  1736. renderer,
  1737. allocation,
  1738. 0,
  1739. requiredSize,
  1740. 0,
  1741. resourceSize,
  1742. memoryRequirements->alignment);
  1743. usedRegion->isBuffer = buffer != VK_NULL_HANDLE;
  1744. region = allocation->freeRegions[0];
  1745. newRegionOffset = region->offset + requiredSize;
  1746. newRegionSize = region->size - requiredSize;
  1747. VULKAN_INTERNAL_RemoveMemoryFreeRegion(renderer, region);
  1748. if (newRegionSize != 0) {
  1749. VULKAN_INTERNAL_NewMemoryFreeRegion(
  1750. renderer,
  1751. allocation,
  1752. newRegionOffset,
  1753. newRegionSize);
  1754. }
  1755. SDL_UnlockMutex(renderer->allocatorLock);
  1756. if (buffer != VK_NULL_HANDLE) {
  1757. if (!VULKAN_INTERNAL_BindBufferMemory(
  1758. renderer,
  1759. usedRegion,
  1760. 0,
  1761. buffer)) {
  1762. VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  1763. renderer,
  1764. usedRegion);
  1765. return 0;
  1766. }
  1767. } else if (image != VK_NULL_HANDLE) {
  1768. if (!VULKAN_INTERNAL_BindImageMemory(
  1769. renderer,
  1770. usedRegion,
  1771. 0,
  1772. image)) {
  1773. VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  1774. renderer,
  1775. usedRegion);
  1776. return 0;
  1777. }
  1778. }
  1779. *pMemoryUsedRegion = usedRegion;
  1780. return 1;
  1781. }
  1782. static Uint8 VULKAN_INTERNAL_BindMemoryForImage(
  1783. VulkanRenderer *renderer,
  1784. VkImage image,
  1785. VulkanMemoryUsedRegion **usedRegion)
  1786. {
  1787. Uint8 bindResult = 0;
  1788. Uint32 memoryTypeCount = 0;
  1789. Uint32 *memoryTypesToTry = NULL;
  1790. Uint32 selectedMemoryTypeIndex = 0;
  1791. Uint32 i;
  1792. VkMemoryPropertyFlags preferredMemoryPropertyFlags;
  1793. VkMemoryRequirements memoryRequirements;
  1794. /* Vulkan memory types have several memory properties.
  1795. *
  1796. * Unlike buffers, images are always optimally stored device-local,
  1797. * so that is the only property we prefer here.
  1798. *
  1799. * If memory is constrained, it is fine for the texture to not
  1800. * be device-local.
  1801. */
  1802. preferredMemoryPropertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  1803. memoryTypesToTry = VULKAN_INTERNAL_FindBestImageMemoryTypes(
  1804. renderer,
  1805. image,
  1806. preferredMemoryPropertyFlags,
  1807. &memoryRequirements,
  1808. &memoryTypeCount);
  1809. for (i = 0; i < memoryTypeCount; i += 1) {
  1810. bindResult = VULKAN_INTERNAL_BindResourceMemory(
  1811. renderer,
  1812. memoryTypesToTry[i],
  1813. &memoryRequirements,
  1814. memoryRequirements.size,
  1815. false,
  1816. VK_NULL_HANDLE,
  1817. image,
  1818. usedRegion);
  1819. if (bindResult == 1) {
  1820. selectedMemoryTypeIndex = memoryTypesToTry[i];
  1821. break;
  1822. }
  1823. }
  1824. SDL_free(memoryTypesToTry);
  1825. // Check for warnings on success
  1826. if (bindResult == 1) {
  1827. if (!renderer->outOfDeviceLocalMemoryWarning) {
  1828. if ((renderer->memoryProperties.memoryTypes[selectedMemoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0) {
  1829. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Out of device-local memory, allocating textures on host-local memory!");
  1830. renderer->outOfDeviceLocalMemoryWarning = 1;
  1831. }
  1832. }
  1833. }
  1834. return bindResult;
  1835. }
  1836. static Uint8 VULKAN_INTERNAL_BindMemoryForBuffer(
  1837. VulkanRenderer *renderer,
  1838. VkBuffer buffer,
  1839. VkDeviceSize size,
  1840. VulkanBufferType type,
  1841. bool dedicated,
  1842. VulkanMemoryUsedRegion **usedRegion)
  1843. {
  1844. Uint8 bindResult = 0;
  1845. Uint32 memoryTypeCount = 0;
  1846. Uint32 *memoryTypesToTry = NULL;
  1847. Uint32 selectedMemoryTypeIndex = 0;
  1848. Uint32 i;
  1849. VkMemoryPropertyFlags requiredMemoryPropertyFlags = 0;
  1850. VkMemoryPropertyFlags preferredMemoryPropertyFlags = 0;
  1851. VkMemoryPropertyFlags tolerableMemoryPropertyFlags = 0;
  1852. VkMemoryRequirements memoryRequirements;
  1853. /* Buffers need to be optimally bound to a memory type
  1854. * based on their use case and the architecture of the system.
  1855. *
  1856. * It is important to understand the distinction between device and host.
  1857. *
  1858. * On a traditional high-performance desktop computer,
  1859. * the "device" would be the GPU, and the "host" would be the CPU.
  1860. * Memory being copied between these two must cross the PCI bus.
  1861. * On these systems we have to be concerned about bandwidth limitations
  1862. * and causing memory stalls, so we have taken a great deal of care
  1863. * to structure this API to guide the client towards optimal usage.
  1864. *
  1865. * Other kinds of devices do not necessarily have this distinction.
  1866. * On an iPhone or Nintendo Switch, all memory is accessible both to the
  1867. * GPU and the CPU at all times. These kinds of systems are known as
  1868. * UMA, or Unified Memory Architecture. A desktop computer using the
  1869. * CPU's integrated graphics can also be thought of as UMA.
  1870. *
  1871. * Vulkan memory types have several memory properties.
  1872. * The relevant memory properties are as follows:
  1873. *
  1874. * DEVICE_LOCAL:
  1875. * This memory is on-device and most efficient for device access.
  1876. * On UMA systems all memory is device-local.
  1877. * If memory is not device-local, then it is host-local.
  1878. *
  1879. * HOST_VISIBLE:
  1880. * This memory can be mapped for host access, meaning we can obtain
  1881. * a pointer to directly access the memory.
  1882. *
  1883. * HOST_COHERENT:
  1884. * Host-coherent memory does not require cache management operations
  1885. * when mapped, so we always set this alongside HOST_VISIBLE
  1886. * to avoid extra record keeping.
  1887. *
  1888. * HOST_CACHED:
  1889. * Host-cached memory is faster to access than uncached memory
  1890. * but memory of this type might not always be available.
  1891. *
  1892. * GPU buffers, like vertex buffers, indirect buffers, etc
  1893. * are optimally stored in device-local memory.
  1894. * However, if device-local memory is low, these buffers
  1895. * can be accessed from host-local memory with a performance penalty.
  1896. *
  1897. * Uniform buffers must be host-visible and coherent because
  1898. * the client uses them to quickly push small amounts of data.
  1899. * We prefer uniform buffers to also be device-local because
  1900. * they are accessed by shaders, but the amount of memory
  1901. * that is both device-local and host-visible
  1902. * is often constrained, particularly on low-end devices.
  1903. *
  1904. * Transfer buffers must be host-visible and coherent because
  1905. * the client uses them to stage data to be transferred
  1906. * to device-local memory, or to read back data transferred
  1907. * from the device. We prefer the cache bit for performance
  1908. * but it isn't strictly necessary. We tolerate device-local
  1909. * memory in this situation because, as mentioned above,
  1910. * on certain devices all memory is device-local, and even
  1911. * though the transfer isn't strictly necessary it is still
  1912. * useful for correctly timelining data.
  1913. */
  1914. if (type == VULKAN_BUFFER_TYPE_GPU) {
  1915. preferredMemoryPropertyFlags |=
  1916. VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  1917. } else if (type == VULKAN_BUFFER_TYPE_UNIFORM) {
  1918. requiredMemoryPropertyFlags |=
  1919. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
  1920. VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
  1921. preferredMemoryPropertyFlags |=
  1922. VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  1923. } else if (type == VULKAN_BUFFER_TYPE_TRANSFER) {
  1924. requiredMemoryPropertyFlags |=
  1925. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
  1926. VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
  1927. preferredMemoryPropertyFlags |=
  1928. VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
  1929. tolerableMemoryPropertyFlags |=
  1930. VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  1931. } else {
  1932. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized buffer type!");
  1933. return 0;
  1934. }
  1935. memoryTypesToTry = VULKAN_INTERNAL_FindBestBufferMemoryTypes(
  1936. renderer,
  1937. buffer,
  1938. requiredMemoryPropertyFlags,
  1939. preferredMemoryPropertyFlags,
  1940. tolerableMemoryPropertyFlags,
  1941. &memoryRequirements,
  1942. &memoryTypeCount);
  1943. for (i = 0; i < memoryTypeCount; i += 1) {
  1944. bindResult = VULKAN_INTERNAL_BindResourceMemory(
  1945. renderer,
  1946. memoryTypesToTry[i],
  1947. &memoryRequirements,
  1948. size,
  1949. dedicated,
  1950. buffer,
  1951. VK_NULL_HANDLE,
  1952. usedRegion);
  1953. if (bindResult == 1) {
  1954. selectedMemoryTypeIndex = memoryTypesToTry[i];
  1955. break;
  1956. }
  1957. }
  1958. SDL_free(memoryTypesToTry);
  1959. // Check for warnings on success
  1960. if (bindResult == 1) {
  1961. if (type == VULKAN_BUFFER_TYPE_GPU) {
  1962. if (!renderer->outOfDeviceLocalMemoryWarning) {
  1963. if ((renderer->memoryProperties.memoryTypes[selectedMemoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0) {
  1964. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Out of device-local memory, allocating buffers on host-local memory, expect degraded performance!");
  1965. renderer->outOfDeviceLocalMemoryWarning = 1;
  1966. }
  1967. }
  1968. } else if (type == VULKAN_BUFFER_TYPE_UNIFORM) {
  1969. if (!renderer->outofBARMemoryWarning) {
  1970. if ((renderer->memoryProperties.memoryTypes[selectedMemoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0) {
  1971. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Out of BAR memory, allocating uniform buffers on host-local memory, expect degraded performance!");
  1972. renderer->outofBARMemoryWarning = 1;
  1973. }
  1974. }
  1975. } else if (type == VULKAN_BUFFER_TYPE_TRANSFER) {
  1976. if (!renderer->integratedMemoryNotification) {
  1977. if ((renderer->memoryProperties.memoryTypes[selectedMemoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
  1978. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "Integrated memory detected, allocating TransferBuffers on device-local memory!");
  1979. renderer->integratedMemoryNotification = 1;
  1980. }
  1981. }
  1982. }
  1983. }
  1984. return bindResult;
  1985. }
  1986. // Resource tracking
  1987. #define TRACK_RESOURCE(resource, type, array, count, capacity) \
  1988. for (Sint32 i = commandBuffer->count - 1; i >= 0; i -= 1) { \
  1989. if (commandBuffer->array[i] == resource) { \
  1990. return; \
  1991. } \
  1992. } \
  1993. \
  1994. if (commandBuffer->count == commandBuffer->capacity) { \
  1995. commandBuffer->capacity += 1; \
  1996. commandBuffer->array = SDL_realloc( \
  1997. commandBuffer->array, \
  1998. commandBuffer->capacity * sizeof(type)); \
  1999. } \
  2000. commandBuffer->array[commandBuffer->count] = resource; \
  2001. commandBuffer->count += 1; \
  2002. SDL_AtomicIncRef(&resource->referenceCount);
  2003. static void VULKAN_INTERNAL_TrackBuffer(
  2004. VulkanCommandBuffer *commandBuffer,
  2005. VulkanBuffer *buffer)
  2006. {
  2007. TRACK_RESOURCE(
  2008. buffer,
  2009. VulkanBuffer *,
  2010. usedBuffers,
  2011. usedBufferCount,
  2012. usedBufferCapacity)
  2013. }
  2014. static void VULKAN_INTERNAL_TrackTexture(
  2015. VulkanCommandBuffer *commandBuffer,
  2016. VulkanTexture *texture)
  2017. {
  2018. TRACK_RESOURCE(
  2019. texture,
  2020. VulkanTexture *,
  2021. usedTextures,
  2022. usedTextureCount,
  2023. usedTextureCapacity)
  2024. }
  2025. static void VULKAN_INTERNAL_TrackSampler(
  2026. VulkanCommandBuffer *commandBuffer,
  2027. VulkanSampler *sampler)
  2028. {
  2029. TRACK_RESOURCE(
  2030. sampler,
  2031. VulkanSampler *,
  2032. usedSamplers,
  2033. usedSamplerCount,
  2034. usedSamplerCapacity)
  2035. }
  2036. static void VULKAN_INTERNAL_TrackGraphicsPipeline(
  2037. VulkanCommandBuffer *commandBuffer,
  2038. VulkanGraphicsPipeline *graphicsPipeline)
  2039. {
  2040. TRACK_RESOURCE(
  2041. graphicsPipeline,
  2042. VulkanGraphicsPipeline *,
  2043. usedGraphicsPipelines,
  2044. usedGraphicsPipelineCount,
  2045. usedGraphicsPipelineCapacity)
  2046. }
  2047. static void VULKAN_INTERNAL_TrackComputePipeline(
  2048. VulkanCommandBuffer *commandBuffer,
  2049. VulkanComputePipeline *computePipeline)
  2050. {
  2051. TRACK_RESOURCE(
  2052. computePipeline,
  2053. VulkanComputePipeline *,
  2054. usedComputePipelines,
  2055. usedComputePipelineCount,
  2056. usedComputePipelineCapacity)
  2057. }
  2058. static void VULKAN_INTERNAL_TrackFramebuffer(
  2059. VulkanCommandBuffer *commandBuffer,
  2060. VulkanFramebuffer *framebuffer)
  2061. {
  2062. TRACK_RESOURCE(
  2063. framebuffer,
  2064. VulkanFramebuffer *,
  2065. usedFramebuffers,
  2066. usedFramebufferCount,
  2067. usedFramebufferCapacity);
  2068. }
  2069. static void VULKAN_INTERNAL_TrackUniformBuffer(
  2070. VulkanCommandBuffer *commandBuffer,
  2071. VulkanUniformBuffer *uniformBuffer)
  2072. {
  2073. for (Sint32 i = commandBuffer->usedUniformBufferCount - 1; i >= 0; i -= 1) {
  2074. if (commandBuffer->usedUniformBuffers[i] == uniformBuffer) {
  2075. return;
  2076. }
  2077. }
  2078. if (commandBuffer->usedUniformBufferCount == commandBuffer->usedUniformBufferCapacity) {
  2079. commandBuffer->usedUniformBufferCapacity += 1;
  2080. commandBuffer->usedUniformBuffers = SDL_realloc(
  2081. commandBuffer->usedUniformBuffers,
  2082. commandBuffer->usedUniformBufferCapacity * sizeof(VulkanUniformBuffer *));
  2083. }
  2084. commandBuffer->usedUniformBuffers[commandBuffer->usedUniformBufferCount] = uniformBuffer;
  2085. commandBuffer->usedUniformBufferCount += 1;
  2086. VULKAN_INTERNAL_TrackBuffer(
  2087. commandBuffer,
  2088. uniformBuffer->buffer);
  2089. }
  2090. #undef TRACK_RESOURCE
  2091. // Memory Barriers
  2092. /*
  2093. * In Vulkan, we must manually synchronize operations that write to resources on the GPU
  2094. * so that read-after-write, write-after-read, and write-after-write hazards do not occur.
  2095. * Additionally, textures are required to be in specific layouts for specific use cases.
  2096. * Both of these tasks are accomplished with vkCmdPipelineBarrier.
  2097. *
  2098. * To insert the correct barriers, we keep track of "usage modes" for buffers and textures.
  2099. * These indicate the current usage of that resource on the command buffer.
  2100. * The transition from one usage mode to another indicates how the barrier should be constructed.
  2101. *
  2102. * Pipeline barriers cannot be inserted during a render pass, but they can be inserted
  2103. * during a compute or copy pass.
  2104. *
  2105. * This means that the "default" usage mode of any given resource should be that it should be
  2106. * ready for a graphics-read operation, because we cannot barrier during a render pass.
  2107. * In the case where a resource is only used in compute, its default usage mode can be compute-read.
  2108. * This strategy allows us to avoid expensive record keeping of command buffer/resource usage mode pairs,
  2109. * and it fully covers synchronization between all combinations of stages.
  2110. *
  2111. * In Upload and Copy functions, we transition the resource immediately before and after the copy command.
  2112. *
  2113. * When binding a resource for compute, we transition when the Bind functions are called.
  2114. * If a bind slot containing a resource is overwritten, we transition the resource in that slot back to its default.
  2115. * When EndComputePass is called we transition all bound resources back to their default state.
  2116. *
  2117. * When binding a texture as a render pass attachment, we transition the resource on BeginRenderPass
  2118. * and transition it back to its default on EndRenderPass.
  2119. *
  2120. * This strategy imposes certain limitations on resource usage flags.
  2121. * For example, a texture cannot have both the SAMPLER and GRAPHICS_STORAGE usage flags,
  2122. * because then it is impossible for the backend to infer which default usage mode the texture should use.
  2123. *
  2124. * Sync hazards can be detected by setting VK_KHRONOS_VALIDATION_VALIDATE_SYNC=1 when using validation layers.
  2125. */
  2126. static void VULKAN_INTERNAL_BufferMemoryBarrier(
  2127. VulkanRenderer *renderer,
  2128. VulkanCommandBuffer *commandBuffer,
  2129. VulkanBufferUsageMode sourceUsageMode,
  2130. VulkanBufferUsageMode destinationUsageMode,
  2131. VulkanBuffer *buffer)
  2132. {
  2133. VkPipelineStageFlags srcStages = 0;
  2134. VkPipelineStageFlags dstStages = 0;
  2135. VkBufferMemoryBarrier memoryBarrier;
  2136. memoryBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
  2137. memoryBarrier.pNext = NULL;
  2138. memoryBarrier.srcAccessMask = 0;
  2139. memoryBarrier.dstAccessMask = 0;
  2140. memoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2141. memoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2142. memoryBarrier.buffer = buffer->buffer;
  2143. memoryBarrier.offset = 0;
  2144. memoryBarrier.size = buffer->size;
  2145. if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE) {
  2146. srcStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2147. memoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2148. } else if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION) {
  2149. srcStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2150. memoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2151. } else if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_VERTEX_READ) {
  2152. srcStages = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  2153. memoryBarrier.srcAccessMask = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
  2154. } else if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_INDEX_READ) {
  2155. srcStages = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  2156. memoryBarrier.srcAccessMask = VK_ACCESS_INDEX_READ_BIT;
  2157. } else if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_INDIRECT) {
  2158. srcStages = VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
  2159. memoryBarrier.srcAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
  2160. } else if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_GRAPHICS_STORAGE_READ) {
  2161. srcStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2162. memoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2163. } else if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ) {
  2164. srcStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2165. memoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2166. } else if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE) {
  2167. srcStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2168. memoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2169. } else {
  2170. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized buffer source barrier type!");
  2171. return;
  2172. }
  2173. if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE) {
  2174. dstStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2175. memoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2176. } else if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION) {
  2177. dstStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2178. memoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2179. } else if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_VERTEX_READ) {
  2180. dstStages = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  2181. memoryBarrier.dstAccessMask = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
  2182. } else if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_INDEX_READ) {
  2183. dstStages = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  2184. memoryBarrier.dstAccessMask = VK_ACCESS_INDEX_READ_BIT;
  2185. } else if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_INDIRECT) {
  2186. dstStages = VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
  2187. memoryBarrier.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
  2188. } else if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_GRAPHICS_STORAGE_READ) {
  2189. dstStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2190. memoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2191. } else if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ) {
  2192. dstStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2193. memoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2194. } else if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE) {
  2195. dstStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2196. memoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2197. } else {
  2198. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized buffer destination barrier type!");
  2199. return;
  2200. }
  2201. renderer->vkCmdPipelineBarrier(
  2202. commandBuffer->commandBuffer,
  2203. srcStages,
  2204. dstStages,
  2205. 0,
  2206. 0,
  2207. NULL,
  2208. 1,
  2209. &memoryBarrier,
  2210. 0,
  2211. NULL);
  2212. buffer->transitioned = true;
  2213. }
  2214. static void VULKAN_INTERNAL_TextureSubresourceMemoryBarrier(
  2215. VulkanRenderer *renderer,
  2216. VulkanCommandBuffer *commandBuffer,
  2217. VulkanTextureUsageMode sourceUsageMode,
  2218. VulkanTextureUsageMode destinationUsageMode,
  2219. VulkanTextureSubresource *textureSubresource)
  2220. {
  2221. VkPipelineStageFlags srcStages = 0;
  2222. VkPipelineStageFlags dstStages = 0;
  2223. VkImageMemoryBarrier memoryBarrier;
  2224. memoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2225. memoryBarrier.pNext = NULL;
  2226. memoryBarrier.srcAccessMask = 0;
  2227. memoryBarrier.dstAccessMask = 0;
  2228. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2229. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2230. memoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2231. memoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2232. memoryBarrier.image = textureSubresource->parent->image;
  2233. memoryBarrier.subresourceRange.aspectMask = textureSubresource->parent->aspectFlags;
  2234. memoryBarrier.subresourceRange.baseArrayLayer = textureSubresource->layer;
  2235. memoryBarrier.subresourceRange.layerCount = 1;
  2236. memoryBarrier.subresourceRange.baseMipLevel = textureSubresource->level;
  2237. memoryBarrier.subresourceRange.levelCount = 1;
  2238. if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_UNINITIALIZED) {
  2239. srcStages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  2240. memoryBarrier.srcAccessMask = 0;
  2241. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2242. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE) {
  2243. srcStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2244. memoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2245. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2246. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION) {
  2247. srcStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2248. memoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2249. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2250. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_SAMPLER) {
  2251. srcStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2252. memoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2253. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  2254. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_GRAPHICS_STORAGE_READ) {
  2255. srcStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2256. memoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2257. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
  2258. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ) {
  2259. srcStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2260. memoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2261. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
  2262. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE) {
  2263. srcStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2264. memoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2265. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
  2266. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT) {
  2267. srcStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  2268. memoryBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  2269. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  2270. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_DEPTH_STENCIL_ATTACHMENT) {
  2271. srcStages = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  2272. memoryBarrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  2273. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  2274. } else {
  2275. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized texture source barrier type!");
  2276. return;
  2277. }
  2278. if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE) {
  2279. dstStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2280. memoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2281. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2282. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION) {
  2283. dstStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2284. memoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2285. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2286. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_SAMPLER) {
  2287. dstStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2288. memoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2289. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  2290. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_GRAPHICS_STORAGE_READ) {
  2291. dstStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2292. memoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2293. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  2294. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ) {
  2295. dstStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2296. memoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2297. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  2298. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE) {
  2299. dstStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2300. memoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2301. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  2302. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT) {
  2303. dstStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  2304. memoryBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  2305. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  2306. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_DEPTH_STENCIL_ATTACHMENT) {
  2307. dstStages = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  2308. memoryBarrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  2309. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  2310. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_PRESENT) {
  2311. dstStages = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2312. memoryBarrier.dstAccessMask = 0;
  2313. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
  2314. } else {
  2315. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized texture destination barrier type!");
  2316. return;
  2317. }
  2318. renderer->vkCmdPipelineBarrier(
  2319. commandBuffer->commandBuffer,
  2320. srcStages,
  2321. dstStages,
  2322. 0,
  2323. 0,
  2324. NULL,
  2325. 0,
  2326. NULL,
  2327. 1,
  2328. &memoryBarrier);
  2329. }
  2330. static VulkanBufferUsageMode VULKAN_INTERNAL_DefaultBufferUsageMode(
  2331. VulkanBuffer *buffer)
  2332. {
  2333. // NOTE: order matters here!
  2334. if (buffer->usage & SDL_GPU_BUFFERUSAGE_VERTEX) {
  2335. return VULKAN_BUFFER_USAGE_MODE_VERTEX_READ;
  2336. } else if (buffer->usage & SDL_GPU_BUFFERUSAGE_INDEX) {
  2337. return VULKAN_BUFFER_USAGE_MODE_INDEX_READ;
  2338. } else if (buffer->usage & SDL_GPU_BUFFERUSAGE_INDIRECT) {
  2339. return VULKAN_BUFFER_USAGE_MODE_INDIRECT;
  2340. } else if (buffer->usage & SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ) {
  2341. return VULKAN_BUFFER_USAGE_MODE_GRAPHICS_STORAGE_READ;
  2342. } else if (buffer->usage & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ) {
  2343. return VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ;
  2344. } else if (buffer->usage & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE) {
  2345. return VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE;
  2346. } else {
  2347. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Buffer has no default usage mode!");
  2348. return VULKAN_BUFFER_USAGE_MODE_VERTEX_READ;
  2349. }
  2350. }
  2351. static VulkanTextureUsageMode VULKAN_INTERNAL_DefaultTextureUsageMode(
  2352. VulkanTexture *texture)
  2353. {
  2354. // NOTE: order matters here!
  2355. // NOTE: graphics storage bits and sampler bit are mutually exclusive!
  2356. if (texture->usage & SDL_GPU_TEXTUREUSAGE_SAMPLER) {
  2357. return VULKAN_TEXTURE_USAGE_MODE_SAMPLER;
  2358. } else if (texture->usage & SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ) {
  2359. return VULKAN_TEXTURE_USAGE_MODE_GRAPHICS_STORAGE_READ;
  2360. } else if (texture->usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) {
  2361. return VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT;
  2362. } else if (texture->usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) {
  2363. return VULKAN_TEXTURE_USAGE_MODE_DEPTH_STENCIL_ATTACHMENT;
  2364. } else if (texture->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ) {
  2365. return VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ;
  2366. } else if (texture->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE) {
  2367. return VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE;
  2368. } else if (texture->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE) {
  2369. return VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE;
  2370. } else {
  2371. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Texture has no default usage mode!");
  2372. return VULKAN_TEXTURE_USAGE_MODE_SAMPLER;
  2373. }
  2374. }
  2375. static void VULKAN_INTERNAL_BufferTransitionFromDefaultUsage(
  2376. VulkanRenderer *renderer,
  2377. VulkanCommandBuffer *commandBuffer,
  2378. VulkanBufferUsageMode destinationUsageMode,
  2379. VulkanBuffer *buffer)
  2380. {
  2381. VULKAN_INTERNAL_BufferMemoryBarrier(
  2382. renderer,
  2383. commandBuffer,
  2384. VULKAN_INTERNAL_DefaultBufferUsageMode(buffer),
  2385. destinationUsageMode,
  2386. buffer);
  2387. }
  2388. static void VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  2389. VulkanRenderer *renderer,
  2390. VulkanCommandBuffer *commandBuffer,
  2391. VulkanBufferUsageMode sourceUsageMode,
  2392. VulkanBuffer *buffer)
  2393. {
  2394. VULKAN_INTERNAL_BufferMemoryBarrier(
  2395. renderer,
  2396. commandBuffer,
  2397. sourceUsageMode,
  2398. VULKAN_INTERNAL_DefaultBufferUsageMode(buffer),
  2399. buffer);
  2400. }
  2401. static void VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  2402. VulkanRenderer *renderer,
  2403. VulkanCommandBuffer *commandBuffer,
  2404. VulkanTextureUsageMode destinationUsageMode,
  2405. VulkanTextureSubresource *textureSubresource)
  2406. {
  2407. VULKAN_INTERNAL_TextureSubresourceMemoryBarrier(
  2408. renderer,
  2409. commandBuffer,
  2410. VULKAN_INTERNAL_DefaultTextureUsageMode(textureSubresource->parent),
  2411. destinationUsageMode,
  2412. textureSubresource);
  2413. }
  2414. static void VULKAN_INTERNAL_TextureTransitionFromDefaultUsage(
  2415. VulkanRenderer *renderer,
  2416. VulkanCommandBuffer *commandBuffer,
  2417. VulkanTextureUsageMode destinationUsageMode,
  2418. VulkanTexture *texture)
  2419. {
  2420. for (Uint32 i = 0; i < texture->subresourceCount; i += 1) {
  2421. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  2422. renderer,
  2423. commandBuffer,
  2424. destinationUsageMode,
  2425. &texture->subresources[i]);
  2426. }
  2427. }
  2428. static void VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  2429. VulkanRenderer *renderer,
  2430. VulkanCommandBuffer *commandBuffer,
  2431. VulkanTextureUsageMode sourceUsageMode,
  2432. VulkanTextureSubresource *textureSubresource)
  2433. {
  2434. VULKAN_INTERNAL_TextureSubresourceMemoryBarrier(
  2435. renderer,
  2436. commandBuffer,
  2437. sourceUsageMode,
  2438. VULKAN_INTERNAL_DefaultTextureUsageMode(textureSubresource->parent),
  2439. textureSubresource);
  2440. }
  2441. static void VULKAN_INTERNAL_TextureTransitionToDefaultUsage(
  2442. VulkanRenderer *renderer,
  2443. VulkanCommandBuffer *commandBuffer,
  2444. VulkanTextureUsageMode sourceUsageMode,
  2445. VulkanTexture *texture)
  2446. {
  2447. // FIXME: could optimize this barrier
  2448. for (Uint32 i = 0; i < texture->subresourceCount; i += 1) {
  2449. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  2450. renderer,
  2451. commandBuffer,
  2452. sourceUsageMode,
  2453. &texture->subresources[i]);
  2454. }
  2455. }
  2456. // Resource Disposal
  2457. static void VULKAN_INTERNAL_ReleaseFramebuffer(
  2458. VulkanRenderer *renderer,
  2459. VulkanFramebuffer *framebuffer)
  2460. {
  2461. SDL_LockMutex(renderer->disposeLock);
  2462. EXPAND_ARRAY_IF_NEEDED(
  2463. renderer->framebuffersToDestroy,
  2464. VulkanFramebuffer *,
  2465. renderer->framebuffersToDestroyCount + 1,
  2466. renderer->framebuffersToDestroyCapacity,
  2467. renderer->framebuffersToDestroyCapacity * 2);
  2468. renderer->framebuffersToDestroy[renderer->framebuffersToDestroyCount] = framebuffer;
  2469. renderer->framebuffersToDestroyCount += 1;
  2470. SDL_UnlockMutex(renderer->disposeLock);
  2471. }
  2472. static void VULKAN_INTERNAL_DestroyFramebuffer(
  2473. VulkanRenderer *renderer,
  2474. VulkanFramebuffer *framebuffer)
  2475. {
  2476. renderer->vkDestroyFramebuffer(
  2477. renderer->logicalDevice,
  2478. framebuffer->framebuffer,
  2479. NULL);
  2480. SDL_free(framebuffer);
  2481. }
  2482. typedef struct CheckOneFramebufferForRemovalData
  2483. {
  2484. Uint32 keysToRemoveCapacity;
  2485. Uint32 keysToRemoveCount;
  2486. FramebufferHashTableKey **keysToRemove;
  2487. VkImageView view;
  2488. } CheckOneFramebufferForRemovalData;
  2489. static bool SDLCALL CheckOneFramebufferForRemoval(void *userdata, const SDL_HashTable *table, const void *vkey, const void *vvalue)
  2490. {
  2491. CheckOneFramebufferForRemovalData *data = (CheckOneFramebufferForRemovalData *) userdata;
  2492. FramebufferHashTableKey *key = (FramebufferHashTableKey *) vkey;
  2493. VkImageView view = data->view;
  2494. bool remove = false;
  2495. for (Uint32 i = 0; i < key->numColorTargets; i += 1) {
  2496. if (key->colorAttachmentViews[i] == view) {
  2497. remove = true;
  2498. }
  2499. }
  2500. for (Uint32 i = 0; i < key->numResolveAttachments; i += 1) {
  2501. if (key->resolveAttachmentViews[i] == view) {
  2502. remove = true;
  2503. }
  2504. }
  2505. if (key->depthStencilAttachmentView == view) {
  2506. remove = true;
  2507. }
  2508. if (remove) {
  2509. if (data->keysToRemoveCount == data->keysToRemoveCapacity) {
  2510. data->keysToRemoveCapacity *= 2;
  2511. void *ptr = SDL_realloc(data->keysToRemove, data->keysToRemoveCapacity * sizeof(FramebufferHashTableKey *));
  2512. if (!ptr) {
  2513. return false; // ugh, stop iterating. We're in trouble.
  2514. }
  2515. data->keysToRemove = (FramebufferHashTableKey **) ptr;
  2516. }
  2517. data->keysToRemove[data->keysToRemoveCount] = key;
  2518. data->keysToRemoveCount++;
  2519. }
  2520. return true; // keep iterating.
  2521. }
  2522. static void VULKAN_INTERNAL_RemoveFramebuffersContainingView(
  2523. VulkanRenderer *renderer,
  2524. VkImageView view)
  2525. {
  2526. // Can't remove while iterating!
  2527. CheckOneFramebufferForRemovalData data = { 8, 0, NULL, view };
  2528. data.keysToRemove = (FramebufferHashTableKey **) SDL_malloc(data.keysToRemoveCapacity * sizeof(FramebufferHashTableKey *));
  2529. if (!data.keysToRemove) {
  2530. return; // uhoh.
  2531. }
  2532. SDL_LockMutex(renderer->framebufferFetchLock);
  2533. SDL_IterateHashTable(renderer->framebufferHashTable, CheckOneFramebufferForRemoval, &data);
  2534. for (Uint32 i = 0; i < data.keysToRemoveCount; i += 1) {
  2535. SDL_RemoveFromHashTable(renderer->framebufferHashTable, (void *)data.keysToRemove[i]);
  2536. }
  2537. SDL_UnlockMutex(renderer->framebufferFetchLock);
  2538. SDL_free(data.keysToRemove);
  2539. }
  2540. static void VULKAN_INTERNAL_DestroyTexture(
  2541. VulkanRenderer *renderer,
  2542. VulkanTexture *texture)
  2543. {
  2544. // Clean up subresources
  2545. for (Uint32 subresourceIndex = 0; subresourceIndex < texture->subresourceCount; subresourceIndex += 1) {
  2546. if (texture->subresources[subresourceIndex].renderTargetViews != NULL) {
  2547. for (Uint32 depthIndex = 0; depthIndex < texture->depth; depthIndex += 1) {
  2548. VULKAN_INTERNAL_RemoveFramebuffersContainingView(
  2549. renderer,
  2550. texture->subresources[subresourceIndex].renderTargetViews[depthIndex]);
  2551. }
  2552. for (Uint32 depthIndex = 0; depthIndex < texture->depth; depthIndex += 1) {
  2553. renderer->vkDestroyImageView(
  2554. renderer->logicalDevice,
  2555. texture->subresources[subresourceIndex].renderTargetViews[depthIndex],
  2556. NULL);
  2557. }
  2558. SDL_free(texture->subresources[subresourceIndex].renderTargetViews);
  2559. }
  2560. if (texture->subresources[subresourceIndex].computeWriteView != VK_NULL_HANDLE) {
  2561. renderer->vkDestroyImageView(
  2562. renderer->logicalDevice,
  2563. texture->subresources[subresourceIndex].computeWriteView,
  2564. NULL);
  2565. }
  2566. if (texture->subresources[subresourceIndex].depthStencilView != VK_NULL_HANDLE) {
  2567. VULKAN_INTERNAL_RemoveFramebuffersContainingView(
  2568. renderer,
  2569. texture->subresources[subresourceIndex].depthStencilView);
  2570. renderer->vkDestroyImageView(
  2571. renderer->logicalDevice,
  2572. texture->subresources[subresourceIndex].depthStencilView,
  2573. NULL);
  2574. }
  2575. }
  2576. SDL_free(texture->subresources);
  2577. if (texture->fullView) {
  2578. renderer->vkDestroyImageView(
  2579. renderer->logicalDevice,
  2580. texture->fullView,
  2581. NULL);
  2582. }
  2583. if (texture->image) {
  2584. renderer->vkDestroyImage(
  2585. renderer->logicalDevice,
  2586. texture->image,
  2587. NULL);
  2588. }
  2589. if (texture->usedRegion) {
  2590. VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  2591. renderer,
  2592. texture->usedRegion);
  2593. }
  2594. SDL_free(texture);
  2595. }
  2596. static void VULKAN_INTERNAL_DestroyBuffer(
  2597. VulkanRenderer *renderer,
  2598. VulkanBuffer *buffer)
  2599. {
  2600. renderer->vkDestroyBuffer(
  2601. renderer->logicalDevice,
  2602. buffer->buffer,
  2603. NULL);
  2604. VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  2605. renderer,
  2606. buffer->usedRegion);
  2607. SDL_free(buffer);
  2608. }
  2609. static void VULKAN_INTERNAL_DestroyCommandPool(
  2610. VulkanRenderer *renderer,
  2611. VulkanCommandPool *commandPool)
  2612. {
  2613. Uint32 i;
  2614. VulkanCommandBuffer *commandBuffer;
  2615. renderer->vkDestroyCommandPool(
  2616. renderer->logicalDevice,
  2617. commandPool->commandPool,
  2618. NULL);
  2619. for (i = 0; i < commandPool->inactiveCommandBufferCount; i += 1) {
  2620. commandBuffer = commandPool->inactiveCommandBuffers[i];
  2621. SDL_free(commandBuffer->presentDatas);
  2622. SDL_free(commandBuffer->waitSemaphores);
  2623. SDL_free(commandBuffer->signalSemaphores);
  2624. SDL_free(commandBuffer->usedBuffers);
  2625. SDL_free(commandBuffer->usedTextures);
  2626. SDL_free(commandBuffer->usedSamplers);
  2627. SDL_free(commandBuffer->usedGraphicsPipelines);
  2628. SDL_free(commandBuffer->usedComputePipelines);
  2629. SDL_free(commandBuffer->usedFramebuffers);
  2630. SDL_free(commandBuffer->usedUniformBuffers);
  2631. SDL_free(commandBuffer);
  2632. }
  2633. SDL_free(commandPool->inactiveCommandBuffers);
  2634. SDL_free(commandPool);
  2635. }
  2636. static void VULKAN_INTERNAL_DestroyDescriptorSetLayout(
  2637. VulkanRenderer *renderer,
  2638. DescriptorSetLayout *layout)
  2639. {
  2640. if (layout == NULL) {
  2641. return;
  2642. }
  2643. if (layout->descriptorSetLayout != VK_NULL_HANDLE) {
  2644. renderer->vkDestroyDescriptorSetLayout(
  2645. renderer->logicalDevice,
  2646. layout->descriptorSetLayout,
  2647. NULL);
  2648. }
  2649. SDL_free(layout);
  2650. }
  2651. static void VULKAN_INTERNAL_DestroyGraphicsPipeline(
  2652. VulkanRenderer *renderer,
  2653. VulkanGraphicsPipeline *graphicsPipeline)
  2654. {
  2655. renderer->vkDestroyPipeline(
  2656. renderer->logicalDevice,
  2657. graphicsPipeline->pipeline,
  2658. NULL);
  2659. (void)SDL_AtomicDecRef(&graphicsPipeline->vertexShader->referenceCount);
  2660. (void)SDL_AtomicDecRef(&graphicsPipeline->fragmentShader->referenceCount);
  2661. SDL_free(graphicsPipeline);
  2662. }
  2663. static void VULKAN_INTERNAL_DestroyComputePipeline(
  2664. VulkanRenderer *renderer,
  2665. VulkanComputePipeline *computePipeline)
  2666. {
  2667. if (computePipeline->pipeline != VK_NULL_HANDLE) {
  2668. renderer->vkDestroyPipeline(
  2669. renderer->logicalDevice,
  2670. computePipeline->pipeline,
  2671. NULL);
  2672. }
  2673. if (computePipeline->shaderModule != VK_NULL_HANDLE) {
  2674. renderer->vkDestroyShaderModule(
  2675. renderer->logicalDevice,
  2676. computePipeline->shaderModule,
  2677. NULL);
  2678. }
  2679. SDL_free(computePipeline);
  2680. }
  2681. static void VULKAN_INTERNAL_DestroyShader(
  2682. VulkanRenderer *renderer,
  2683. VulkanShader *vulkanShader)
  2684. {
  2685. renderer->vkDestroyShaderModule(
  2686. renderer->logicalDevice,
  2687. vulkanShader->shaderModule,
  2688. NULL);
  2689. SDL_free(vulkanShader->entrypointName);
  2690. SDL_free(vulkanShader);
  2691. }
  2692. static void VULKAN_INTERNAL_DestroySampler(
  2693. VulkanRenderer *renderer,
  2694. VulkanSampler *vulkanSampler)
  2695. {
  2696. renderer->vkDestroySampler(
  2697. renderer->logicalDevice,
  2698. vulkanSampler->sampler,
  2699. NULL);
  2700. SDL_free(vulkanSampler);
  2701. }
  2702. static void VULKAN_INTERNAL_DestroySwapchainImage(
  2703. VulkanRenderer *renderer,
  2704. WindowData *windowData)
  2705. {
  2706. Uint32 i;
  2707. if (windowData == NULL) {
  2708. return;
  2709. }
  2710. for (i = 0; i < windowData->imageCount; i += 1) {
  2711. VULKAN_INTERNAL_RemoveFramebuffersContainingView(
  2712. renderer,
  2713. windowData->textureContainers[i].activeTexture->subresources[0].renderTargetViews[0]);
  2714. renderer->vkDestroyImageView(
  2715. renderer->logicalDevice,
  2716. windowData->textureContainers[i].activeTexture->subresources[0].renderTargetViews[0],
  2717. NULL);
  2718. SDL_free(windowData->textureContainers[i].activeTexture->subresources[0].renderTargetViews);
  2719. SDL_free(windowData->textureContainers[i].activeTexture->subresources);
  2720. SDL_free(windowData->textureContainers[i].activeTexture);
  2721. }
  2722. SDL_free(windowData->textureContainers);
  2723. windowData->textureContainers = NULL;
  2724. for (i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  2725. if (windowData->imageAvailableSemaphore[i]) {
  2726. renderer->vkDestroySemaphore(
  2727. renderer->logicalDevice,
  2728. windowData->imageAvailableSemaphore[i],
  2729. NULL);
  2730. windowData->imageAvailableSemaphore[i] = VK_NULL_HANDLE;
  2731. }
  2732. }
  2733. for (i = 0; i < windowData->imageCount; i += 1) {
  2734. if (windowData->renderFinishedSemaphore[i]) {
  2735. renderer->vkDestroySemaphore(
  2736. renderer->logicalDevice,
  2737. windowData->renderFinishedSemaphore[i],
  2738. NULL);
  2739. windowData->renderFinishedSemaphore[i] = VK_NULL_HANDLE;
  2740. }
  2741. }
  2742. SDL_free(windowData->renderFinishedSemaphore);
  2743. windowData->renderFinishedSemaphore = NULL;
  2744. windowData->imageCount = 0;
  2745. }
  2746. static void VULKAN_INTERNAL_DestroySwapchain(
  2747. VulkanRenderer *renderer,
  2748. WindowData *windowData)
  2749. {
  2750. if (windowData == NULL) {
  2751. return;
  2752. }
  2753. VULKAN_INTERNAL_DestroySwapchainImage(renderer, windowData);
  2754. if (windowData->swapchain) {
  2755. renderer->vkDestroySwapchainKHR(
  2756. renderer->logicalDevice,
  2757. windowData->swapchain,
  2758. NULL);
  2759. windowData->swapchain = VK_NULL_HANDLE;
  2760. }
  2761. }
  2762. static void VULKAN_INTERNAL_DestroyGraphicsPipelineResourceLayout(
  2763. VulkanRenderer *renderer,
  2764. VulkanGraphicsPipelineResourceLayout *resourceLayout)
  2765. {
  2766. if (resourceLayout->pipelineLayout != VK_NULL_HANDLE) {
  2767. renderer->vkDestroyPipelineLayout(
  2768. renderer->logicalDevice,
  2769. resourceLayout->pipelineLayout,
  2770. NULL);
  2771. }
  2772. SDL_free(resourceLayout);
  2773. }
  2774. static void VULKAN_INTERNAL_DestroyComputePipelineResourceLayout(
  2775. VulkanRenderer *renderer,
  2776. VulkanComputePipelineResourceLayout *resourceLayout)
  2777. {
  2778. if (resourceLayout->pipelineLayout != VK_NULL_HANDLE) {
  2779. renderer->vkDestroyPipelineLayout(
  2780. renderer->logicalDevice,
  2781. resourceLayout->pipelineLayout,
  2782. NULL);
  2783. }
  2784. SDL_free(resourceLayout);
  2785. }
  2786. static void VULKAN_INTERNAL_DestroyDescriptorSetCache(
  2787. VulkanRenderer *renderer,
  2788. DescriptorSetCache *descriptorSetCache)
  2789. {
  2790. for (Uint32 i = 0; i < descriptorSetCache->poolCount; i += 1) {
  2791. for (Uint32 j = 0; j < descriptorSetCache->pools[i].poolCount; j += 1) {
  2792. renderer->vkDestroyDescriptorPool(
  2793. renderer->logicalDevice,
  2794. descriptorSetCache->pools[i].descriptorPools[j],
  2795. NULL);
  2796. }
  2797. SDL_free(descriptorSetCache->pools[i].descriptorSets);
  2798. SDL_free(descriptorSetCache->pools[i].descriptorPools);
  2799. }
  2800. SDL_free(descriptorSetCache->pools);
  2801. SDL_free(descriptorSetCache);
  2802. }
  2803. // Hashtable functions
  2804. static Uint32 SDLCALL VULKAN_INTERNAL_GraphicsPipelineResourceLayoutHashFunction(void *userdata, const void *key)
  2805. {
  2806. GraphicsPipelineResourceLayoutHashTableKey *hashTableKey = (GraphicsPipelineResourceLayoutHashTableKey *)key;
  2807. /* The algorithm for this hashing function
  2808. * is taken from Josh Bloch's "Effective Java".
  2809. * (https://stackoverflow.com/a/113600/12492383)
  2810. */
  2811. const Uint32 hashFactor = 31;
  2812. Uint32 result = 1;
  2813. result = result * hashFactor + hashTableKey->vertexSamplerCount;
  2814. result = result * hashFactor + hashTableKey->vertexStorageBufferCount;
  2815. result = result * hashFactor + hashTableKey->vertexStorageTextureCount;
  2816. result = result * hashFactor + hashTableKey->vertexUniformBufferCount;
  2817. result = result * hashFactor + hashTableKey->fragmentSamplerCount;
  2818. result = result * hashFactor + hashTableKey->fragmentStorageBufferCount;
  2819. result = result * hashFactor + hashTableKey->fragmentStorageTextureCount;
  2820. result = result * hashFactor + hashTableKey->fragmentUniformBufferCount;
  2821. return result;
  2822. }
  2823. static bool SDLCALL VULKAN_INTERNAL_GraphicsPipelineResourceLayoutHashKeyMatch(void *userdata, const void *aKey, const void *bKey)
  2824. {
  2825. return SDL_memcmp(aKey, bKey, sizeof(GraphicsPipelineResourceLayoutHashTableKey)) == 0;
  2826. }
  2827. static void SDLCALL VULKAN_INTERNAL_GraphicsPipelineResourceLayoutHashDestroy(void *userdata, const void *key, const void *value)
  2828. {
  2829. VulkanRenderer *renderer = (VulkanRenderer *)userdata;
  2830. VulkanGraphicsPipelineResourceLayout *resourceLayout = (VulkanGraphicsPipelineResourceLayout *)value;
  2831. VULKAN_INTERNAL_DestroyGraphicsPipelineResourceLayout(renderer, resourceLayout);
  2832. SDL_free((void *)key);
  2833. }
  2834. static Uint32 SDLCALL VULKAN_INTERNAL_ComputePipelineResourceLayoutHashFunction(void *userdata, const void *key)
  2835. {
  2836. ComputePipelineResourceLayoutHashTableKey *hashTableKey = (ComputePipelineResourceLayoutHashTableKey *)key;
  2837. /* The algorithm for this hashing function
  2838. * is taken from Josh Bloch's "Effective Java".
  2839. * (https://stackoverflow.com/a/113600/12492383)
  2840. */
  2841. const Uint32 hashFactor = 31;
  2842. Uint32 result = 1;
  2843. result = result * hashFactor + hashTableKey->samplerCount;
  2844. result = result * hashFactor + hashTableKey->readonlyStorageTextureCount;
  2845. result = result * hashFactor + hashTableKey->readonlyStorageBufferCount;
  2846. result = result * hashFactor + hashTableKey->readWriteStorageTextureCount;
  2847. result = result * hashFactor + hashTableKey->readWriteStorageBufferCount;
  2848. result = result * hashFactor + hashTableKey->uniformBufferCount;
  2849. return result;
  2850. }
  2851. static bool SDLCALL VULKAN_INTERNAL_ComputePipelineResourceLayoutHashKeyMatch(void *userdata, const void *aKey, const void *bKey)
  2852. {
  2853. return SDL_memcmp(aKey, bKey, sizeof(ComputePipelineResourceLayoutHashTableKey)) == 0;
  2854. }
  2855. static void SDLCALL VULKAN_INTERNAL_ComputePipelineResourceLayoutHashDestroy(void *userdata, const void *key, const void *value)
  2856. {
  2857. VulkanRenderer *renderer = (VulkanRenderer *)userdata;
  2858. VulkanComputePipelineResourceLayout *resourceLayout = (VulkanComputePipelineResourceLayout *)value;
  2859. VULKAN_INTERNAL_DestroyComputePipelineResourceLayout(renderer, resourceLayout);
  2860. SDL_free((void *)key);
  2861. }
  2862. static Uint32 SDLCALL VULKAN_INTERNAL_DescriptorSetLayoutHashFunction(void *userdata, const void *key)
  2863. {
  2864. DescriptorSetLayoutHashTableKey *hashTableKey = (DescriptorSetLayoutHashTableKey *)key;
  2865. /* The algorithm for this hashing function
  2866. * is taken from Josh Bloch's "Effective Java".
  2867. * (https://stackoverflow.com/a/113600/12492383)
  2868. */
  2869. const Uint32 hashFactor = 31;
  2870. Uint32 result = 1;
  2871. result = result * hashFactor + hashTableKey->shaderStage;
  2872. result = result * hashFactor + hashTableKey->samplerCount;
  2873. result = result * hashFactor + hashTableKey->storageTextureCount;
  2874. result = result * hashFactor + hashTableKey->storageBufferCount;
  2875. result = result * hashFactor + hashTableKey->writeStorageTextureCount;
  2876. result = result * hashFactor + hashTableKey->writeStorageBufferCount;
  2877. result = result * hashFactor + hashTableKey->uniformBufferCount;
  2878. return result;
  2879. }
  2880. static bool SDLCALL VULKAN_INTERNAL_DescriptorSetLayoutHashKeyMatch(void *userdata, const void *aKey, const void *bKey)
  2881. {
  2882. return SDL_memcmp(aKey, bKey, sizeof(DescriptorSetLayoutHashTableKey)) == 0;
  2883. }
  2884. static void SDLCALL VULKAN_INTERNAL_DescriptorSetLayoutHashDestroy(void *userdata, const void *key, const void *value)
  2885. {
  2886. VulkanRenderer *renderer = (VulkanRenderer *)userdata;
  2887. DescriptorSetLayout *layout = (DescriptorSetLayout *)value;
  2888. VULKAN_INTERNAL_DestroyDescriptorSetLayout(renderer, layout);
  2889. SDL_free((void *)key);
  2890. }
  2891. static Uint32 SDLCALL VULKAN_INTERNAL_CommandPoolHashFunction(void *userdata, const void *key)
  2892. {
  2893. return (Uint32)((CommandPoolHashTableKey *)key)->threadID;
  2894. }
  2895. static bool SDLCALL VULKAN_INTERNAL_CommandPoolHashKeyMatch(void *userdata, const void *aKey, const void *bKey)
  2896. {
  2897. CommandPoolHashTableKey *a = (CommandPoolHashTableKey *)aKey;
  2898. CommandPoolHashTableKey *b = (CommandPoolHashTableKey *)bKey;
  2899. return a->threadID == b->threadID;
  2900. }
  2901. static void SDLCALL VULKAN_INTERNAL_CommandPoolHashDestroy(void *userdata, const void *key, const void *value)
  2902. {
  2903. VulkanRenderer *renderer = (VulkanRenderer *)userdata;
  2904. VulkanCommandPool *pool = (VulkanCommandPool *)value;
  2905. VULKAN_INTERNAL_DestroyCommandPool(renderer, pool);
  2906. SDL_free((void *)key);
  2907. }
  2908. static Uint32 SDLCALL VULKAN_INTERNAL_RenderPassHashFunction(void *userdata, const void *key)
  2909. {
  2910. RenderPassHashTableKey *hashTableKey = (RenderPassHashTableKey *)key;
  2911. /* The algorithm for this hashing function
  2912. * is taken from Josh Bloch's "Effective Java".
  2913. * (https://stackoverflow.com/a/113600/12492383)
  2914. */
  2915. const Uint32 hashFactor = 31;
  2916. Uint32 result = 1;
  2917. for (Uint32 i = 0; i < hashTableKey->numColorTargets; i += 1) {
  2918. result = result * hashFactor + hashTableKey->colorTargetDescriptions[i].loadOp;
  2919. result = result * hashFactor + hashTableKey->colorTargetDescriptions[i].storeOp;
  2920. result = result * hashFactor + hashTableKey->colorTargetDescriptions[i].format;
  2921. }
  2922. for (Uint32 i = 0; i < hashTableKey->numResolveTargets; i += 1) {
  2923. result = result * hashFactor + hashTableKey->resolveTargetFormats[i];
  2924. }
  2925. result = result * hashFactor + hashTableKey->depthStencilTargetDescription.loadOp;
  2926. result = result * hashFactor + hashTableKey->depthStencilTargetDescription.storeOp;
  2927. result = result * hashFactor + hashTableKey->depthStencilTargetDescription.stencilLoadOp;
  2928. result = result * hashFactor + hashTableKey->depthStencilTargetDescription.stencilStoreOp;
  2929. result = result * hashFactor + hashTableKey->depthStencilTargetDescription.format;
  2930. result = result * hashFactor + hashTableKey->sampleCount;
  2931. return result;
  2932. }
  2933. static bool SDLCALL VULKAN_INTERNAL_RenderPassHashKeyMatch(void *userdata, const void *aKey, const void *bKey)
  2934. {
  2935. RenderPassHashTableKey *a = (RenderPassHashTableKey *)aKey;
  2936. RenderPassHashTableKey *b = (RenderPassHashTableKey *)bKey;
  2937. if (a->numColorTargets != b->numColorTargets) {
  2938. return 0;
  2939. }
  2940. if (a->numResolveTargets != b->numResolveTargets) {
  2941. return 0;
  2942. }
  2943. if (a->sampleCount != b->sampleCount) {
  2944. return 0;
  2945. }
  2946. for (Uint32 i = 0; i < a->numColorTargets; i += 1) {
  2947. if (a->colorTargetDescriptions[i].format != b->colorTargetDescriptions[i].format) {
  2948. return 0;
  2949. }
  2950. if (a->colorTargetDescriptions[i].loadOp != b->colorTargetDescriptions[i].loadOp) {
  2951. return 0;
  2952. }
  2953. if (a->colorTargetDescriptions[i].storeOp != b->colorTargetDescriptions[i].storeOp) {
  2954. return 0;
  2955. }
  2956. }
  2957. for (Uint32 i = 0; i < a->numResolveTargets; i += 1) {
  2958. if (a->resolveTargetFormats[i] != b->resolveTargetFormats[i]) {
  2959. return 0;
  2960. }
  2961. }
  2962. if (a->depthStencilTargetDescription.format != b->depthStencilTargetDescription.format) {
  2963. return 0;
  2964. }
  2965. if (a->depthStencilTargetDescription.loadOp != b->depthStencilTargetDescription.loadOp) {
  2966. return 0;
  2967. }
  2968. if (a->depthStencilTargetDescription.storeOp != b->depthStencilTargetDescription.storeOp) {
  2969. return 0;
  2970. }
  2971. if (a->depthStencilTargetDescription.stencilLoadOp != b->depthStencilTargetDescription.stencilLoadOp) {
  2972. return 0;
  2973. }
  2974. if (a->depthStencilTargetDescription.stencilStoreOp != b->depthStencilTargetDescription.stencilStoreOp) {
  2975. return 0;
  2976. }
  2977. return 1;
  2978. }
  2979. static void SDLCALL VULKAN_INTERNAL_RenderPassHashDestroy(void *userdata, const void *key, const void *value)
  2980. {
  2981. VulkanRenderer *renderer = (VulkanRenderer *)userdata;
  2982. VulkanRenderPassHashTableValue *renderPassWrapper = (VulkanRenderPassHashTableValue *)value;
  2983. renderer->vkDestroyRenderPass(
  2984. renderer->logicalDevice,
  2985. renderPassWrapper->handle,
  2986. NULL);
  2987. SDL_free(renderPassWrapper);
  2988. SDL_free((void *)key);
  2989. }
  2990. static Uint32 SDLCALL VULKAN_INTERNAL_FramebufferHashFunction(void *userdata, const void *key)
  2991. {
  2992. FramebufferHashTableKey *hashTableKey = (FramebufferHashTableKey *)key;
  2993. /* The algorithm for this hashing function
  2994. * is taken from Josh Bloch's "Effective Java".
  2995. * (https://stackoverflow.com/a/113600/12492383)
  2996. */
  2997. const Uint32 hashFactor = 31;
  2998. Uint32 result = 1;
  2999. for (Uint32 i = 0; i < hashTableKey->numColorTargets; i += 1) {
  3000. result = result * hashFactor + (Uint32)(uintptr_t)hashTableKey->colorAttachmentViews[i];
  3001. }
  3002. for (Uint32 i = 0; i < hashTableKey->numResolveAttachments; i += 1) {
  3003. result = result * hashFactor + (Uint32)(uintptr_t)hashTableKey->resolveAttachmentViews[i];
  3004. }
  3005. result = result * hashFactor + (Uint32)(uintptr_t)hashTableKey->depthStencilAttachmentView;
  3006. result = result * hashFactor + hashTableKey->width;
  3007. result = result * hashFactor + hashTableKey->height;
  3008. return result;
  3009. }
  3010. static bool SDLCALL VULKAN_INTERNAL_FramebufferHashKeyMatch(void *userdata, const void *aKey, const void *bKey)
  3011. {
  3012. FramebufferHashTableKey *a = (FramebufferHashTableKey *)aKey;
  3013. FramebufferHashTableKey *b = (FramebufferHashTableKey *)bKey;
  3014. if (a->numColorTargets != b->numColorTargets) {
  3015. return 0;
  3016. }
  3017. if (a->numResolveAttachments != b->numResolveAttachments) {
  3018. return 0;
  3019. }
  3020. for (Uint32 i = 0; i < a->numColorTargets; i += 1) {
  3021. if (a->colorAttachmentViews[i] != b->colorAttachmentViews[i]) {
  3022. return 0;
  3023. }
  3024. }
  3025. for (Uint32 i = 0; i < a->numResolveAttachments; i += 1) {
  3026. if (a->resolveAttachmentViews[i] != b->resolveAttachmentViews[i]) {
  3027. return 0;
  3028. }
  3029. }
  3030. if (a->depthStencilAttachmentView != b->depthStencilAttachmentView) {
  3031. return 0;
  3032. }
  3033. if (a->width != b->width) {
  3034. return 0;
  3035. }
  3036. if (a->height != b->height) {
  3037. return 0;
  3038. }
  3039. return 1;
  3040. }
  3041. static void SDLCALL VULKAN_INTERNAL_FramebufferHashDestroy(void *userdata, const void *key, const void *value)
  3042. {
  3043. VulkanRenderer *renderer = (VulkanRenderer *)userdata;
  3044. VulkanFramebuffer *framebuffer = (VulkanFramebuffer *)value;
  3045. VULKAN_INTERNAL_ReleaseFramebuffer(renderer, framebuffer);
  3046. SDL_free((void *)key);
  3047. }
  3048. // Descriptor pools
  3049. static bool VULKAN_INTERNAL_AllocateDescriptorSets(
  3050. VulkanRenderer *renderer,
  3051. VkDescriptorPool descriptorPool,
  3052. VkDescriptorSetLayout descriptorSetLayout,
  3053. Uint32 descriptorSetCount,
  3054. VkDescriptorSet *descriptorSetArray)
  3055. {
  3056. VkDescriptorSetAllocateInfo descriptorSetAllocateInfo;
  3057. VkDescriptorSetLayout *descriptorSetLayouts = SDL_stack_alloc(VkDescriptorSetLayout, descriptorSetCount);
  3058. VkResult vulkanResult;
  3059. Uint32 i;
  3060. for (i = 0; i < descriptorSetCount; i += 1) {
  3061. descriptorSetLayouts[i] = descriptorSetLayout;
  3062. }
  3063. descriptorSetAllocateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
  3064. descriptorSetAllocateInfo.pNext = NULL;
  3065. descriptorSetAllocateInfo.descriptorPool = descriptorPool;
  3066. descriptorSetAllocateInfo.descriptorSetCount = descriptorSetCount;
  3067. descriptorSetAllocateInfo.pSetLayouts = descriptorSetLayouts;
  3068. vulkanResult = renderer->vkAllocateDescriptorSets(
  3069. renderer->logicalDevice,
  3070. &descriptorSetAllocateInfo,
  3071. descriptorSetArray);
  3072. SDL_stack_free(descriptorSetLayouts);
  3073. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkAllocateDescriptorSets, false);
  3074. return true;
  3075. }
  3076. static bool VULKAN_INTERNAL_AllocateDescriptorsFromPool(
  3077. VulkanRenderer *renderer,
  3078. DescriptorSetLayout *descriptorSetLayout,
  3079. DescriptorSetPool *descriptorSetPool)
  3080. {
  3081. VkDescriptorPoolSize descriptorPoolSizes[
  3082. MAX_TEXTURE_SAMPLERS_PER_STAGE +
  3083. MAX_STORAGE_TEXTURES_PER_STAGE +
  3084. MAX_STORAGE_BUFFERS_PER_STAGE +
  3085. MAX_COMPUTE_WRITE_TEXTURES +
  3086. MAX_COMPUTE_WRITE_BUFFERS +
  3087. MAX_UNIFORM_BUFFERS_PER_STAGE];
  3088. VkDescriptorPoolCreateInfo descriptorPoolInfo;
  3089. VkDescriptorPool pool;
  3090. VkResult vulkanResult;
  3091. // Category 1
  3092. for (Uint32 i = 0; i < descriptorSetLayout->samplerCount; i += 1) {
  3093. descriptorPoolSizes[i].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  3094. descriptorPoolSizes[i].descriptorCount = DESCRIPTOR_POOL_SIZE;
  3095. }
  3096. for (Uint32 i = descriptorSetLayout->samplerCount; i < descriptorSetLayout->samplerCount + descriptorSetLayout->storageTextureCount; i += 1) {
  3097. descriptorPoolSizes[i].type = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; // Yes, we are declaring the storage image as a sampled image, because shaders are stupid.
  3098. descriptorPoolSizes[i].descriptorCount = DESCRIPTOR_POOL_SIZE;
  3099. }
  3100. for (Uint32 i = descriptorSetLayout->samplerCount + descriptorSetLayout->storageTextureCount; i < descriptorSetLayout->samplerCount + descriptorSetLayout->storageTextureCount + descriptorSetLayout->storageBufferCount; i += 1) {
  3101. descriptorPoolSizes[i].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  3102. descriptorPoolSizes[i].descriptorCount = DESCRIPTOR_POOL_SIZE;
  3103. }
  3104. // Category 2
  3105. for (Uint32 i = 0; i < descriptorSetLayout->writeStorageTextureCount; i += 1) {
  3106. descriptorPoolSizes[i].type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  3107. descriptorPoolSizes[i].descriptorCount = DESCRIPTOR_POOL_SIZE;
  3108. }
  3109. for (Uint32 i = descriptorSetLayout->writeStorageTextureCount; i < descriptorSetLayout->writeStorageTextureCount + descriptorSetLayout->writeStorageBufferCount; i += 1) {
  3110. descriptorPoolSizes[i].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  3111. descriptorPoolSizes[i].descriptorCount = DESCRIPTOR_POOL_SIZE;
  3112. }
  3113. // Category 3
  3114. for (Uint32 i = 0; i < descriptorSetLayout->uniformBufferCount; i += 1) {
  3115. descriptorPoolSizes[i].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
  3116. descriptorPoolSizes[i].descriptorCount = DESCRIPTOR_POOL_SIZE;
  3117. }
  3118. descriptorPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
  3119. descriptorPoolInfo.pNext = NULL;
  3120. descriptorPoolInfo.flags = 0;
  3121. descriptorPoolInfo.maxSets = DESCRIPTOR_POOL_SIZE;
  3122. descriptorPoolInfo.poolSizeCount =
  3123. descriptorSetLayout->samplerCount +
  3124. descriptorSetLayout->storageTextureCount +
  3125. descriptorSetLayout->storageBufferCount +
  3126. descriptorSetLayout->writeStorageTextureCount +
  3127. descriptorSetLayout->writeStorageBufferCount +
  3128. descriptorSetLayout->uniformBufferCount;
  3129. descriptorPoolInfo.pPoolSizes = descriptorPoolSizes;
  3130. vulkanResult = renderer->vkCreateDescriptorPool(
  3131. renderer->logicalDevice,
  3132. &descriptorPoolInfo,
  3133. NULL,
  3134. &pool);
  3135. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateDescriptorPool, false);
  3136. descriptorSetPool->poolCount += 1;
  3137. descriptorSetPool->descriptorPools = SDL_realloc(
  3138. descriptorSetPool->descriptorPools,
  3139. sizeof(VkDescriptorPool) * descriptorSetPool->poolCount);
  3140. descriptorSetPool->descriptorPools[descriptorSetPool->poolCount - 1] = pool;
  3141. descriptorSetPool->descriptorSets = SDL_realloc(
  3142. descriptorSetPool->descriptorSets,
  3143. sizeof(VkDescriptorSet) * descriptorSetPool->poolCount * DESCRIPTOR_POOL_SIZE);
  3144. if (!VULKAN_INTERNAL_AllocateDescriptorSets(
  3145. renderer,
  3146. pool,
  3147. descriptorSetLayout->descriptorSetLayout,
  3148. DESCRIPTOR_POOL_SIZE,
  3149. &descriptorSetPool->descriptorSets[descriptorSetPool->descriptorSetCount])) {
  3150. return false;
  3151. }
  3152. descriptorSetPool->descriptorSetCount += DESCRIPTOR_POOL_SIZE;
  3153. return true;
  3154. }
  3155. // NOTE: these categories should be mutually exclusive
  3156. static DescriptorSetLayout *VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3157. VulkanRenderer *renderer,
  3158. VkShaderStageFlagBits shaderStage,
  3159. // Category 1: read resources
  3160. Uint32 samplerCount,
  3161. Uint32 storageTextureCount,
  3162. Uint32 storageBufferCount,
  3163. // Category 2: write resources
  3164. Uint32 writeStorageTextureCount,
  3165. Uint32 writeStorageBufferCount,
  3166. // Category 3: uniform buffers
  3167. Uint32 uniformBufferCount)
  3168. {
  3169. DescriptorSetLayoutHashTableKey key;
  3170. SDL_zero(key);
  3171. DescriptorSetLayout *layout = NULL;
  3172. key.shaderStage = shaderStage;
  3173. key.samplerCount = samplerCount;
  3174. key.storageTextureCount = storageTextureCount;
  3175. key.storageBufferCount = storageBufferCount;
  3176. key.writeStorageTextureCount = writeStorageTextureCount;
  3177. key.writeStorageBufferCount = writeStorageBufferCount;
  3178. key.uniformBufferCount = uniformBufferCount;
  3179. SDL_LockMutex(renderer->descriptorSetLayoutFetchLock);
  3180. if (SDL_FindInHashTable(
  3181. renderer->descriptorSetLayoutHashTable,
  3182. (const void *)&key,
  3183. (const void **)&layout)) {
  3184. SDL_UnlockMutex(renderer->descriptorSetLayoutFetchLock);
  3185. return layout;
  3186. }
  3187. VkDescriptorSetLayout descriptorSetLayout;
  3188. VkDescriptorSetLayoutBinding descriptorSetLayoutBindings[
  3189. MAX_TEXTURE_SAMPLERS_PER_STAGE +
  3190. MAX_STORAGE_TEXTURES_PER_STAGE +
  3191. MAX_STORAGE_BUFFERS_PER_STAGE +
  3192. MAX_COMPUTE_WRITE_TEXTURES +
  3193. MAX_COMPUTE_WRITE_BUFFERS];
  3194. VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo;
  3195. descriptorSetLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
  3196. descriptorSetLayoutCreateInfo.pNext = NULL;
  3197. descriptorSetLayoutCreateInfo.flags = 0;
  3198. // Category 1
  3199. for (Uint32 i = 0; i < samplerCount; i += 1) {
  3200. descriptorSetLayoutBindings[i].binding = i;
  3201. descriptorSetLayoutBindings[i].descriptorCount = 1;
  3202. descriptorSetLayoutBindings[i].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  3203. descriptorSetLayoutBindings[i].stageFlags = shaderStage;
  3204. descriptorSetLayoutBindings[i].pImmutableSamplers = NULL;
  3205. }
  3206. for (Uint32 i = samplerCount; i < samplerCount + storageTextureCount; i += 1) {
  3207. descriptorSetLayoutBindings[i].binding = i;
  3208. descriptorSetLayoutBindings[i].descriptorCount = 1;
  3209. descriptorSetLayoutBindings[i].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; // Yes, we are declaring the storage image as a sampled image, because shaders are stupid.
  3210. descriptorSetLayoutBindings[i].stageFlags = shaderStage;
  3211. descriptorSetLayoutBindings[i].pImmutableSamplers = NULL;
  3212. }
  3213. for (Uint32 i = samplerCount + storageTextureCount; i < samplerCount + storageTextureCount + storageBufferCount; i += 1) {
  3214. descriptorSetLayoutBindings[i].binding = i;
  3215. descriptorSetLayoutBindings[i].descriptorCount = 1;
  3216. descriptorSetLayoutBindings[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  3217. descriptorSetLayoutBindings[i].stageFlags = shaderStage;
  3218. descriptorSetLayoutBindings[i].pImmutableSamplers = NULL;
  3219. }
  3220. // Category 2
  3221. for (Uint32 i = 0; i < writeStorageTextureCount; i += 1) {
  3222. descriptorSetLayoutBindings[i].binding = i;
  3223. descriptorSetLayoutBindings[i].descriptorCount = 1;
  3224. descriptorSetLayoutBindings[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  3225. descriptorSetLayoutBindings[i].stageFlags = shaderStage;
  3226. descriptorSetLayoutBindings[i].pImmutableSamplers = NULL;
  3227. }
  3228. for (Uint32 i = writeStorageTextureCount; i < writeStorageTextureCount + writeStorageBufferCount; i += 1) {
  3229. descriptorSetLayoutBindings[i].binding = i;
  3230. descriptorSetLayoutBindings[i].descriptorCount = 1;
  3231. descriptorSetLayoutBindings[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  3232. descriptorSetLayoutBindings[i].stageFlags = shaderStage;
  3233. descriptorSetLayoutBindings[i].pImmutableSamplers = NULL;
  3234. }
  3235. // Category 3
  3236. for (Uint32 i = 0; i < uniformBufferCount; i += 1) {
  3237. descriptorSetLayoutBindings[i].binding = i;
  3238. descriptorSetLayoutBindings[i].descriptorCount = 1;
  3239. descriptorSetLayoutBindings[i].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
  3240. descriptorSetLayoutBindings[i].stageFlags = shaderStage;
  3241. descriptorSetLayoutBindings[i].pImmutableSamplers = NULL;
  3242. }
  3243. descriptorSetLayoutCreateInfo.pBindings = descriptorSetLayoutBindings;
  3244. descriptorSetLayoutCreateInfo.bindingCount =
  3245. samplerCount +
  3246. storageTextureCount +
  3247. storageBufferCount +
  3248. writeStorageTextureCount +
  3249. writeStorageBufferCount +
  3250. uniformBufferCount;
  3251. VkResult vulkanResult = renderer->vkCreateDescriptorSetLayout(
  3252. renderer->logicalDevice,
  3253. &descriptorSetLayoutCreateInfo,
  3254. NULL,
  3255. &descriptorSetLayout);
  3256. if (vulkanResult != VK_SUCCESS) {
  3257. SDL_UnlockMutex(renderer->descriptorSetLayoutFetchLock);
  3258. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateDescriptorSetLayout, NULL);
  3259. }
  3260. layout = SDL_malloc(sizeof(DescriptorSetLayout));
  3261. layout->descriptorSetLayout = descriptorSetLayout;
  3262. layout->samplerCount = samplerCount;
  3263. layout->storageBufferCount = storageBufferCount;
  3264. layout->storageTextureCount = storageTextureCount;
  3265. layout->writeStorageBufferCount = writeStorageBufferCount;
  3266. layout->writeStorageTextureCount = writeStorageTextureCount;
  3267. layout->uniformBufferCount = uniformBufferCount;
  3268. layout->ID = SDL_AtomicIncRef(&renderer->layoutResourceID);
  3269. DescriptorSetLayoutHashTableKey *allocedKey = SDL_malloc(sizeof(DescriptorSetLayoutHashTableKey));
  3270. SDL_memcpy(allocedKey, &key, sizeof(DescriptorSetLayoutHashTableKey));
  3271. SDL_InsertIntoHashTable(
  3272. renderer->descriptorSetLayoutHashTable,
  3273. (const void *)allocedKey,
  3274. (const void *)layout, true);
  3275. SDL_UnlockMutex(renderer->descriptorSetLayoutFetchLock);
  3276. return layout;
  3277. }
  3278. static VulkanGraphicsPipelineResourceLayout *VULKAN_INTERNAL_FetchGraphicsPipelineResourceLayout(
  3279. VulkanRenderer *renderer,
  3280. VulkanShader *vertexShader,
  3281. VulkanShader *fragmentShader)
  3282. {
  3283. GraphicsPipelineResourceLayoutHashTableKey key;
  3284. SDL_zero(key);
  3285. VulkanGraphicsPipelineResourceLayout *pipelineResourceLayout = NULL;
  3286. key.vertexSamplerCount = vertexShader->numSamplers;
  3287. key.vertexStorageTextureCount = vertexShader->numStorageTextures;
  3288. key.vertexStorageBufferCount = vertexShader->numStorageBuffers;
  3289. key.vertexUniformBufferCount = vertexShader->numUniformBuffers;
  3290. key.fragmentSamplerCount = fragmentShader->numSamplers;
  3291. key.fragmentStorageTextureCount = fragmentShader->numStorageTextures;
  3292. key.fragmentStorageBufferCount = fragmentShader->numStorageBuffers;
  3293. key.fragmentUniformBufferCount = fragmentShader->numUniformBuffers;
  3294. SDL_LockMutex(renderer->graphicsPipelineLayoutFetchLock);
  3295. if (SDL_FindInHashTable(
  3296. renderer->graphicsPipelineResourceLayoutHashTable,
  3297. (const void *)&key,
  3298. (const void **)&pipelineResourceLayout)) {
  3299. SDL_UnlockMutex(renderer->graphicsPipelineLayoutFetchLock);
  3300. return pipelineResourceLayout;
  3301. }
  3302. VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo;
  3303. VkDescriptorSetLayout descriptorSetLayouts[4];
  3304. VkResult vulkanResult;
  3305. pipelineResourceLayout = SDL_calloc(1, sizeof(VulkanGraphicsPipelineResourceLayout));
  3306. pipelineResourceLayout->descriptorSetLayouts[0] = VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3307. renderer,
  3308. VK_SHADER_STAGE_VERTEX_BIT,
  3309. vertexShader->numSamplers,
  3310. vertexShader->numStorageTextures,
  3311. vertexShader->numStorageBuffers,
  3312. 0,
  3313. 0,
  3314. 0);
  3315. pipelineResourceLayout->descriptorSetLayouts[1] = VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3316. renderer,
  3317. VK_SHADER_STAGE_VERTEX_BIT,
  3318. 0,
  3319. 0,
  3320. 0,
  3321. 0,
  3322. 0,
  3323. vertexShader->numUniformBuffers);
  3324. pipelineResourceLayout->descriptorSetLayouts[2] = VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3325. renderer,
  3326. VK_SHADER_STAGE_FRAGMENT_BIT,
  3327. fragmentShader->numSamplers,
  3328. fragmentShader->numStorageTextures,
  3329. fragmentShader->numStorageBuffers,
  3330. 0,
  3331. 0,
  3332. 0);
  3333. pipelineResourceLayout->descriptorSetLayouts[3] = VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3334. renderer,
  3335. VK_SHADER_STAGE_FRAGMENT_BIT,
  3336. 0,
  3337. 0,
  3338. 0,
  3339. 0,
  3340. 0,
  3341. fragmentShader->numUniformBuffers);
  3342. descriptorSetLayouts[0] = pipelineResourceLayout->descriptorSetLayouts[0]->descriptorSetLayout;
  3343. descriptorSetLayouts[1] = pipelineResourceLayout->descriptorSetLayouts[1]->descriptorSetLayout;
  3344. descriptorSetLayouts[2] = pipelineResourceLayout->descriptorSetLayouts[2]->descriptorSetLayout;
  3345. descriptorSetLayouts[3] = pipelineResourceLayout->descriptorSetLayouts[3]->descriptorSetLayout;
  3346. pipelineResourceLayout->vertexSamplerCount = vertexShader->numSamplers;
  3347. pipelineResourceLayout->vertexStorageTextureCount = vertexShader->numStorageTextures;
  3348. pipelineResourceLayout->vertexStorageBufferCount = vertexShader->numStorageBuffers;
  3349. pipelineResourceLayout->vertexUniformBufferCount = vertexShader->numUniformBuffers;
  3350. pipelineResourceLayout->fragmentSamplerCount = fragmentShader->numSamplers;
  3351. pipelineResourceLayout->fragmentStorageTextureCount = fragmentShader->numStorageTextures;
  3352. pipelineResourceLayout->fragmentStorageBufferCount = fragmentShader->numStorageBuffers;
  3353. pipelineResourceLayout->fragmentUniformBufferCount = fragmentShader->numUniformBuffers;
  3354. // Create the pipeline layout
  3355. pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  3356. pipelineLayoutCreateInfo.pNext = NULL;
  3357. pipelineLayoutCreateInfo.flags = 0;
  3358. pipelineLayoutCreateInfo.setLayoutCount = 4;
  3359. pipelineLayoutCreateInfo.pSetLayouts = descriptorSetLayouts;
  3360. pipelineLayoutCreateInfo.pushConstantRangeCount = 0;
  3361. pipelineLayoutCreateInfo.pPushConstantRanges = NULL;
  3362. vulkanResult = renderer->vkCreatePipelineLayout(
  3363. renderer->logicalDevice,
  3364. &pipelineLayoutCreateInfo,
  3365. NULL,
  3366. &pipelineResourceLayout->pipelineLayout);
  3367. if (vulkanResult != VK_SUCCESS) {
  3368. VULKAN_INTERNAL_DestroyGraphicsPipelineResourceLayout(renderer, pipelineResourceLayout);
  3369. SDL_UnlockMutex(renderer->graphicsPipelineLayoutFetchLock);
  3370. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreatePipelineLayout, NULL);
  3371. }
  3372. GraphicsPipelineResourceLayoutHashTableKey *allocedKey = SDL_malloc(sizeof(GraphicsPipelineResourceLayoutHashTableKey));
  3373. SDL_memcpy(allocedKey, &key, sizeof(GraphicsPipelineResourceLayoutHashTableKey));
  3374. SDL_InsertIntoHashTable(
  3375. renderer->graphicsPipelineResourceLayoutHashTable,
  3376. (const void *)allocedKey,
  3377. (const void *)pipelineResourceLayout, true);
  3378. SDL_UnlockMutex(renderer->graphicsPipelineLayoutFetchLock);
  3379. return pipelineResourceLayout;
  3380. }
  3381. static VulkanComputePipelineResourceLayout *VULKAN_INTERNAL_FetchComputePipelineResourceLayout(
  3382. VulkanRenderer *renderer,
  3383. const SDL_GPUComputePipelineCreateInfo *createinfo)
  3384. {
  3385. ComputePipelineResourceLayoutHashTableKey key;
  3386. SDL_zero(key);
  3387. VulkanComputePipelineResourceLayout *pipelineResourceLayout = NULL;
  3388. key.samplerCount = createinfo->num_samplers;
  3389. key.readonlyStorageTextureCount = createinfo->num_readonly_storage_textures;
  3390. key.readonlyStorageBufferCount = createinfo->num_readonly_storage_buffers;
  3391. key.readWriteStorageTextureCount = createinfo->num_readwrite_storage_textures;
  3392. key.readWriteStorageBufferCount = createinfo->num_readwrite_storage_buffers;
  3393. key.uniformBufferCount = createinfo->num_uniform_buffers;
  3394. SDL_LockMutex(renderer->computePipelineLayoutFetchLock);
  3395. if (SDL_FindInHashTable(
  3396. renderer->computePipelineResourceLayoutHashTable,
  3397. (const void *)&key,
  3398. (const void **)&pipelineResourceLayout)) {
  3399. SDL_UnlockMutex(renderer->computePipelineLayoutFetchLock);
  3400. return pipelineResourceLayout;
  3401. }
  3402. VkDescriptorSetLayout descriptorSetLayouts[3];
  3403. VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo;
  3404. VkResult vulkanResult;
  3405. pipelineResourceLayout = SDL_calloc(1, sizeof(VulkanComputePipelineResourceLayout));
  3406. pipelineResourceLayout->descriptorSetLayouts[0] = VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3407. renderer,
  3408. VK_SHADER_STAGE_COMPUTE_BIT,
  3409. createinfo->num_samplers,
  3410. createinfo->num_readonly_storage_textures,
  3411. createinfo->num_readonly_storage_buffers,
  3412. 0,
  3413. 0,
  3414. 0);
  3415. pipelineResourceLayout->descriptorSetLayouts[1] = VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3416. renderer,
  3417. VK_SHADER_STAGE_COMPUTE_BIT,
  3418. 0,
  3419. 0,
  3420. 0,
  3421. createinfo->num_readwrite_storage_textures,
  3422. createinfo->num_readwrite_storage_buffers,
  3423. 0);
  3424. pipelineResourceLayout->descriptorSetLayouts[2] = VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3425. renderer,
  3426. VK_SHADER_STAGE_COMPUTE_BIT,
  3427. 0,
  3428. 0,
  3429. 0,
  3430. 0,
  3431. 0,
  3432. createinfo->num_uniform_buffers);
  3433. descriptorSetLayouts[0] = pipelineResourceLayout->descriptorSetLayouts[0]->descriptorSetLayout;
  3434. descriptorSetLayouts[1] = pipelineResourceLayout->descriptorSetLayouts[1]->descriptorSetLayout;
  3435. descriptorSetLayouts[2] = pipelineResourceLayout->descriptorSetLayouts[2]->descriptorSetLayout;
  3436. pipelineResourceLayout->numSamplers = createinfo->num_samplers;
  3437. pipelineResourceLayout->numReadonlyStorageTextures = createinfo->num_readonly_storage_textures;
  3438. pipelineResourceLayout->numReadonlyStorageBuffers = createinfo->num_readonly_storage_buffers;
  3439. pipelineResourceLayout->numReadWriteStorageTextures = createinfo->num_readwrite_storage_textures;
  3440. pipelineResourceLayout->numReadWriteStorageBuffers = createinfo->num_readwrite_storage_buffers;
  3441. pipelineResourceLayout->numUniformBuffers = createinfo->num_uniform_buffers;
  3442. // Create the pipeline layout
  3443. pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  3444. pipelineLayoutCreateInfo.pNext = NULL;
  3445. pipelineLayoutCreateInfo.flags = 0;
  3446. pipelineLayoutCreateInfo.setLayoutCount = 3;
  3447. pipelineLayoutCreateInfo.pSetLayouts = descriptorSetLayouts;
  3448. pipelineLayoutCreateInfo.pushConstantRangeCount = 0;
  3449. pipelineLayoutCreateInfo.pPushConstantRanges = NULL;
  3450. vulkanResult = renderer->vkCreatePipelineLayout(
  3451. renderer->logicalDevice,
  3452. &pipelineLayoutCreateInfo,
  3453. NULL,
  3454. &pipelineResourceLayout->pipelineLayout);
  3455. if (vulkanResult != VK_SUCCESS) {
  3456. VULKAN_INTERNAL_DestroyComputePipelineResourceLayout(renderer, pipelineResourceLayout);
  3457. SDL_UnlockMutex(renderer->computePipelineLayoutFetchLock);
  3458. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreatePipelineLayout, NULL);
  3459. }
  3460. ComputePipelineResourceLayoutHashTableKey *allocedKey = SDL_malloc(sizeof(ComputePipelineResourceLayoutHashTableKey));
  3461. SDL_memcpy(allocedKey, &key, sizeof(ComputePipelineResourceLayoutHashTableKey));
  3462. SDL_InsertIntoHashTable(
  3463. renderer->computePipelineResourceLayoutHashTable,
  3464. (const void *)allocedKey,
  3465. (const void *)pipelineResourceLayout, true);
  3466. SDL_UnlockMutex(renderer->computePipelineLayoutFetchLock);
  3467. return pipelineResourceLayout;
  3468. }
  3469. // Data Buffer
  3470. static VulkanBuffer *VULKAN_INTERNAL_CreateBuffer(
  3471. VulkanRenderer *renderer,
  3472. VkDeviceSize size,
  3473. SDL_GPUBufferUsageFlags usageFlags,
  3474. VulkanBufferType type,
  3475. bool dedicated,
  3476. const char *debugName)
  3477. {
  3478. VulkanBuffer *buffer;
  3479. VkResult vulkanResult;
  3480. VkBufferCreateInfo createinfo;
  3481. VkBufferUsageFlags vulkanUsageFlags = 0;
  3482. Uint8 bindResult;
  3483. if (usageFlags & SDL_GPU_BUFFERUSAGE_VERTEX) {
  3484. vulkanUsageFlags |= VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
  3485. }
  3486. if (usageFlags & SDL_GPU_BUFFERUSAGE_INDEX) {
  3487. vulkanUsageFlags |= VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
  3488. }
  3489. if (usageFlags & (SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ |
  3490. SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ |
  3491. SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE)) {
  3492. vulkanUsageFlags |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
  3493. }
  3494. if (usageFlags & SDL_GPU_BUFFERUSAGE_INDIRECT) {
  3495. vulkanUsageFlags |= VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
  3496. }
  3497. if (type == VULKAN_BUFFER_TYPE_UNIFORM) {
  3498. vulkanUsageFlags |= VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
  3499. } else {
  3500. // GPU buffers need transfer bits for defrag, transfer buffers need them for transfers
  3501. vulkanUsageFlags |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  3502. }
  3503. buffer = SDL_calloc(1, sizeof(VulkanBuffer));
  3504. buffer->size = size;
  3505. buffer->usage = usageFlags;
  3506. buffer->type = type;
  3507. buffer->markedForDestroy = false;
  3508. buffer->transitioned = false;
  3509. createinfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  3510. createinfo.pNext = NULL;
  3511. createinfo.flags = 0;
  3512. createinfo.size = size;
  3513. createinfo.usage = vulkanUsageFlags;
  3514. createinfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  3515. createinfo.queueFamilyIndexCount = 1;
  3516. createinfo.pQueueFamilyIndices = &renderer->queueFamilyIndex;
  3517. // Set transfer bits so we can defrag
  3518. createinfo.usage |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  3519. vulkanResult = renderer->vkCreateBuffer(
  3520. renderer->logicalDevice,
  3521. &createinfo,
  3522. NULL,
  3523. &buffer->buffer);
  3524. if (vulkanResult != VK_SUCCESS) {
  3525. SDL_free(buffer);
  3526. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateBuffer, NULL);
  3527. }
  3528. bindResult = VULKAN_INTERNAL_BindMemoryForBuffer(
  3529. renderer,
  3530. buffer->buffer,
  3531. buffer->size,
  3532. buffer->type,
  3533. dedicated,
  3534. &buffer->usedRegion);
  3535. if (bindResult != 1) {
  3536. renderer->vkDestroyBuffer(
  3537. renderer->logicalDevice,
  3538. buffer->buffer,
  3539. NULL);
  3540. SDL_free(buffer);
  3541. SET_STRING_ERROR_AND_RETURN("Failed to bind memory for buffer!", NULL);
  3542. }
  3543. buffer->usedRegion->vulkanBuffer = buffer; // lol
  3544. SDL_SetAtomicInt(&buffer->referenceCount, 0);
  3545. if (renderer->debugMode && renderer->supportsDebugUtils && debugName != NULL) {
  3546. VkDebugUtilsObjectNameInfoEXT nameInfo;
  3547. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  3548. nameInfo.pNext = NULL;
  3549. nameInfo.pObjectName = debugName;
  3550. nameInfo.objectType = VK_OBJECT_TYPE_BUFFER;
  3551. nameInfo.objectHandle = (uint64_t)buffer->buffer;
  3552. renderer->vkSetDebugUtilsObjectNameEXT(
  3553. renderer->logicalDevice,
  3554. &nameInfo);
  3555. }
  3556. return buffer;
  3557. }
  3558. static VulkanBufferContainer *VULKAN_INTERNAL_CreateBufferContainer(
  3559. VulkanRenderer *renderer,
  3560. VkDeviceSize size,
  3561. SDL_GPUBufferUsageFlags usageFlags,
  3562. VulkanBufferType type,
  3563. bool dedicated,
  3564. const char *debugName)
  3565. {
  3566. VulkanBufferContainer *bufferContainer;
  3567. VulkanBuffer *buffer;
  3568. buffer = VULKAN_INTERNAL_CreateBuffer(
  3569. renderer,
  3570. size,
  3571. usageFlags,
  3572. type,
  3573. dedicated,
  3574. debugName);
  3575. if (buffer == NULL) {
  3576. return NULL;
  3577. }
  3578. bufferContainer = SDL_calloc(1, sizeof(VulkanBufferContainer));
  3579. bufferContainer->activeBuffer = buffer;
  3580. buffer->container = bufferContainer;
  3581. buffer->containerIndex = 0;
  3582. bufferContainer->bufferCapacity = 1;
  3583. bufferContainer->bufferCount = 1;
  3584. bufferContainer->buffers = SDL_calloc(bufferContainer->bufferCapacity, sizeof(VulkanBuffer *));
  3585. bufferContainer->buffers[0] = bufferContainer->activeBuffer;
  3586. bufferContainer->dedicated = dedicated;
  3587. bufferContainer->debugName = NULL;
  3588. if (debugName != NULL) {
  3589. bufferContainer->debugName = SDL_strdup(debugName);
  3590. }
  3591. return bufferContainer;
  3592. }
  3593. // Texture Subresource Utilities
  3594. static Uint32 VULKAN_INTERNAL_GetTextureSubresourceIndex(
  3595. Uint32 mipLevel,
  3596. Uint32 layer,
  3597. Uint32 numLevels)
  3598. {
  3599. return mipLevel + (layer * numLevels);
  3600. }
  3601. static VulkanTextureSubresource *VULKAN_INTERNAL_FetchTextureSubresource(
  3602. VulkanTextureContainer *textureContainer,
  3603. Uint32 layer,
  3604. Uint32 level)
  3605. {
  3606. Uint32 index = VULKAN_INTERNAL_GetTextureSubresourceIndex(
  3607. level,
  3608. layer,
  3609. textureContainer->header.info.num_levels);
  3610. return &textureContainer->activeTexture->subresources[index];
  3611. }
  3612. static bool VULKAN_INTERNAL_CreateRenderTargetView(
  3613. VulkanRenderer *renderer,
  3614. VulkanTexture *texture,
  3615. Uint32 layerOrDepth,
  3616. Uint32 level,
  3617. VkFormat format,
  3618. VkComponentMapping swizzle,
  3619. VkImageView *pView)
  3620. {
  3621. VkResult vulkanResult;
  3622. VkImageViewCreateInfo imageViewCreateInfo;
  3623. // create framebuffer compatible views for RenderTarget
  3624. imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  3625. imageViewCreateInfo.pNext = NULL;
  3626. imageViewCreateInfo.flags = 0;
  3627. imageViewCreateInfo.image = texture->image;
  3628. imageViewCreateInfo.format = format;
  3629. imageViewCreateInfo.components = swizzle;
  3630. imageViewCreateInfo.subresourceRange.aspectMask = texture->aspectFlags;
  3631. imageViewCreateInfo.subresourceRange.baseMipLevel = level;
  3632. imageViewCreateInfo.subresourceRange.levelCount = 1;
  3633. imageViewCreateInfo.subresourceRange.baseArrayLayer = layerOrDepth;
  3634. imageViewCreateInfo.subresourceRange.layerCount = 1;
  3635. imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  3636. vulkanResult = renderer->vkCreateImageView(
  3637. renderer->logicalDevice,
  3638. &imageViewCreateInfo,
  3639. NULL,
  3640. pView);
  3641. if (vulkanResult != VK_SUCCESS) {
  3642. *pView = (VkImageView)VK_NULL_HANDLE;
  3643. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateImageView, false);
  3644. }
  3645. return true;
  3646. }
  3647. static bool VULKAN_INTERNAL_CreateSubresourceView(
  3648. VulkanRenderer *renderer,
  3649. const SDL_GPUTextureCreateInfo *createinfo,
  3650. VulkanTexture *texture,
  3651. Uint32 layer,
  3652. Uint32 level,
  3653. VkComponentMapping swizzle,
  3654. VkImageView *pView)
  3655. {
  3656. VkResult vulkanResult;
  3657. VkImageViewCreateInfo imageViewCreateInfo;
  3658. // create framebuffer compatible views for RenderTarget
  3659. imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  3660. imageViewCreateInfo.pNext = NULL;
  3661. imageViewCreateInfo.flags = 0;
  3662. imageViewCreateInfo.image = texture->image;
  3663. imageViewCreateInfo.format = SDLToVK_TextureFormat[createinfo->format];
  3664. imageViewCreateInfo.components = swizzle;
  3665. imageViewCreateInfo.subresourceRange.aspectMask = texture->aspectFlags;
  3666. imageViewCreateInfo.subresourceRange.baseMipLevel = level;
  3667. imageViewCreateInfo.subresourceRange.levelCount = 1;
  3668. imageViewCreateInfo.subresourceRange.baseArrayLayer = layer;
  3669. imageViewCreateInfo.subresourceRange.layerCount = 1;
  3670. imageViewCreateInfo.viewType = (createinfo->type == SDL_GPU_TEXTURETYPE_3D) ? VK_IMAGE_VIEW_TYPE_3D : VK_IMAGE_VIEW_TYPE_2D;
  3671. vulkanResult = renderer->vkCreateImageView(
  3672. renderer->logicalDevice,
  3673. &imageViewCreateInfo,
  3674. NULL,
  3675. pView);
  3676. if (vulkanResult != VK_SUCCESS) {
  3677. *pView = (VkImageView)VK_NULL_HANDLE;
  3678. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateImageView, false);
  3679. }
  3680. return true;
  3681. }
  3682. // Swapchain
  3683. static bool VULKAN_INTERNAL_QuerySwapchainSupport(
  3684. VulkanRenderer *renderer,
  3685. VkPhysicalDevice physicalDevice,
  3686. VkSurfaceKHR surface,
  3687. SwapchainSupportDetails *outputDetails)
  3688. {
  3689. VkResult result;
  3690. VkBool32 supportsPresent;
  3691. renderer->vkGetPhysicalDeviceSurfaceSupportKHR(
  3692. physicalDevice,
  3693. renderer->queueFamilyIndex,
  3694. surface,
  3695. &supportsPresent);
  3696. // Initialize these in case anything fails
  3697. outputDetails->formats = NULL;
  3698. outputDetails->formatsLength = 0;
  3699. outputDetails->presentModes = NULL;
  3700. outputDetails->presentModesLength = 0;
  3701. if (!supportsPresent) {
  3702. SET_STRING_ERROR_AND_RETURN("This surface does not support presenting!", false);
  3703. }
  3704. // Run the device surface queries
  3705. result = renderer->vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
  3706. physicalDevice,
  3707. surface,
  3708. &outputDetails->capabilities);
  3709. CHECK_VULKAN_ERROR_AND_RETURN(result, vkGetPhysicalDeviceSurfaceCapabilitiesKHR, false);
  3710. if (!(outputDetails->capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR)) {
  3711. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Opaque presentation unsupported! Expect weird transparency bugs!");
  3712. }
  3713. result = renderer->vkGetPhysicalDeviceSurfaceFormatsKHR(
  3714. physicalDevice,
  3715. surface,
  3716. &outputDetails->formatsLength,
  3717. NULL);
  3718. if (result != VK_SUCCESS) {
  3719. // Make sure the driver didn't mess up this value.
  3720. outputDetails->formatsLength = 0;
  3721. CHECK_VULKAN_ERROR_AND_RETURN(result, vkGetPhysicalDeviceSurfaceFormatsKHR, false);
  3722. }
  3723. result = renderer->vkGetPhysicalDeviceSurfacePresentModesKHR(
  3724. physicalDevice,
  3725. surface,
  3726. &outputDetails->presentModesLength,
  3727. NULL);
  3728. if (result != VK_SUCCESS) {
  3729. // Make sure the driver didn't mess up this value.
  3730. outputDetails->presentModesLength = 0;
  3731. // Reset this one, too.
  3732. outputDetails->formatsLength = 0;
  3733. CHECK_VULKAN_ERROR_AND_RETURN(result, vkGetPhysicalDeviceSurfacePresentModesKHR, false);
  3734. }
  3735. // Generate the arrays, if applicable
  3736. if (outputDetails->formatsLength != 0) {
  3737. outputDetails->formats = (VkSurfaceFormatKHR *)SDL_malloc(
  3738. sizeof(VkSurfaceFormatKHR) * outputDetails->formatsLength);
  3739. if (!outputDetails->formats) { // OOM
  3740. outputDetails->formatsLength = 0;
  3741. outputDetails->presentModesLength = 0;
  3742. return false;
  3743. }
  3744. result = renderer->vkGetPhysicalDeviceSurfaceFormatsKHR(
  3745. physicalDevice,
  3746. surface,
  3747. &outputDetails->formatsLength,
  3748. outputDetails->formats);
  3749. if (result != VK_SUCCESS) {
  3750. SDL_free(outputDetails->formats);
  3751. outputDetails->formats = NULL;
  3752. outputDetails->formatsLength = 0;
  3753. outputDetails->presentModesLength = 0;
  3754. CHECK_VULKAN_ERROR_AND_RETURN(result, vkGetPhysicalDeviceSurfaceFormatsKHR, false);
  3755. }
  3756. }
  3757. if (outputDetails->presentModesLength != 0) {
  3758. outputDetails->presentModes = (VkPresentModeKHR *)SDL_malloc(
  3759. sizeof(VkPresentModeKHR) * outputDetails->presentModesLength);
  3760. if (!outputDetails->presentModes) { // OOM
  3761. SDL_free(outputDetails->formats);
  3762. outputDetails->formats = NULL;
  3763. outputDetails->formatsLength = 0;
  3764. outputDetails->presentModesLength = 0;
  3765. return false;
  3766. }
  3767. result = renderer->vkGetPhysicalDeviceSurfacePresentModesKHR(
  3768. physicalDevice,
  3769. surface,
  3770. &outputDetails->presentModesLength,
  3771. outputDetails->presentModes);
  3772. if (result != VK_SUCCESS) {
  3773. SDL_free(outputDetails->formats);
  3774. SDL_free(outputDetails->presentModes);
  3775. outputDetails->formats = NULL;
  3776. outputDetails->presentModes = NULL;
  3777. outputDetails->formatsLength = 0;
  3778. outputDetails->presentModesLength = 0;
  3779. CHECK_VULKAN_ERROR_AND_RETURN(result, vkGetPhysicalDeviceSurfacePresentModesKHR, false);
  3780. }
  3781. }
  3782. /* If we made it here, all the queries were successful. This does NOT
  3783. * necessarily mean there are any supported formats or present modes!
  3784. */
  3785. return true;
  3786. }
  3787. static bool VULKAN_INTERNAL_VerifySwapSurfaceFormat(
  3788. VkFormat desiredFormat,
  3789. VkColorSpaceKHR desiredColorSpace,
  3790. VkSurfaceFormatKHR *availableFormats,
  3791. Uint32 availableFormatsLength)
  3792. {
  3793. Uint32 i;
  3794. for (i = 0; i < availableFormatsLength; i += 1) {
  3795. if (availableFormats[i].format == desiredFormat &&
  3796. availableFormats[i].colorSpace == desiredColorSpace) {
  3797. return true;
  3798. }
  3799. }
  3800. return false;
  3801. }
  3802. static bool VULKAN_INTERNAL_VerifySwapPresentMode(
  3803. VkPresentModeKHR presentMode,
  3804. const VkPresentModeKHR *availablePresentModes,
  3805. Uint32 availablePresentModesLength)
  3806. {
  3807. Uint32 i;
  3808. for (i = 0; i < availablePresentModesLength; i += 1) {
  3809. if (availablePresentModes[i] == presentMode) {
  3810. return true;
  3811. }
  3812. }
  3813. return false;
  3814. }
  3815. /* It would be nice if VULKAN_INTERNAL_CreateSwapchain could return a bool.
  3816. * Unfortunately, some Win32 NVIDIA drivers are stupid
  3817. * and will return surface extents of (0, 0)
  3818. * in certain edge cases, and the swapchain extents are not allowed to be 0.
  3819. * In this case, the client probably still wants to claim the window
  3820. * or recreate the swapchain, so we should return 2 to indicate retry.
  3821. * -cosmonaut
  3822. */
  3823. #define VULKAN_INTERNAL_TRY_AGAIN 2
  3824. static Uint32 VULKAN_INTERNAL_CreateSwapchain(
  3825. VulkanRenderer *renderer,
  3826. WindowData *windowData)
  3827. {
  3828. VkResult vulkanResult;
  3829. VkSwapchainCreateInfoKHR swapchainCreateInfo;
  3830. VkImage *swapchainImages;
  3831. VkSemaphoreCreateInfo semaphoreCreateInfo;
  3832. SwapchainSupportDetails swapchainSupportDetails;
  3833. bool hasValidSwapchainComposition, hasValidPresentMode;
  3834. VkCompositeAlphaFlagsKHR compositeAlphaFlag = 0;
  3835. Uint32 i;
  3836. windowData->frameCounter = 0;
  3837. if (!VULKAN_INTERNAL_QuerySwapchainSupport(
  3838. renderer,
  3839. renderer->physicalDevice,
  3840. windowData->surface,
  3841. &swapchainSupportDetails)) {
  3842. return false;
  3843. }
  3844. // Verify that we can use the requested composition and present mode
  3845. windowData->format = SwapchainCompositionToFormat[windowData->swapchainComposition];
  3846. windowData->colorSpace = SwapchainCompositionToColorSpace[windowData->swapchainComposition];
  3847. windowData->swapchainSwizzle = SwapchainCompositionSwizzle[windowData->swapchainComposition];
  3848. windowData->usingFallbackFormat = false;
  3849. hasValidSwapchainComposition = VULKAN_INTERNAL_VerifySwapSurfaceFormat(
  3850. windowData->format,
  3851. windowData->colorSpace,
  3852. swapchainSupportDetails.formats,
  3853. swapchainSupportDetails.formatsLength);
  3854. if (!hasValidSwapchainComposition) {
  3855. // Let's try again with the fallback format...
  3856. windowData->format = SwapchainCompositionToFallbackFormat[windowData->swapchainComposition];
  3857. windowData->usingFallbackFormat = true;
  3858. hasValidSwapchainComposition = VULKAN_INTERNAL_VerifySwapSurfaceFormat(
  3859. windowData->format,
  3860. windowData->colorSpace,
  3861. swapchainSupportDetails.formats,
  3862. swapchainSupportDetails.formatsLength);
  3863. }
  3864. hasValidPresentMode = VULKAN_INTERNAL_VerifySwapPresentMode(
  3865. SDLToVK_PresentMode[windowData->presentMode],
  3866. swapchainSupportDetails.presentModes,
  3867. swapchainSupportDetails.presentModesLength);
  3868. if (!hasValidSwapchainComposition || !hasValidPresentMode) {
  3869. if (swapchainSupportDetails.formatsLength > 0) {
  3870. SDL_free(swapchainSupportDetails.formats);
  3871. }
  3872. if (swapchainSupportDetails.presentModesLength > 0) {
  3873. SDL_free(swapchainSupportDetails.presentModes);
  3874. }
  3875. if (!hasValidSwapchainComposition) {
  3876. SET_STRING_ERROR_AND_RETURN("Device does not support requested swapchain composition!", false);
  3877. }
  3878. if (!hasValidPresentMode) {
  3879. SET_STRING_ERROR_AND_RETURN("Device does not support requested present_mode!", false);
  3880. }
  3881. return false;
  3882. }
  3883. // NVIDIA + Win32 can return 0 extent when the window is minimized. Try again!
  3884. if (swapchainSupportDetails.capabilities.currentExtent.width == 0 ||
  3885. swapchainSupportDetails.capabilities.currentExtent.height == 0) {
  3886. if (swapchainSupportDetails.formatsLength > 0) {
  3887. SDL_free(swapchainSupportDetails.formats);
  3888. }
  3889. if (swapchainSupportDetails.presentModesLength > 0) {
  3890. SDL_free(swapchainSupportDetails.presentModes);
  3891. }
  3892. return VULKAN_INTERNAL_TRY_AGAIN;
  3893. }
  3894. Uint32 requestedImageCount = renderer->allowedFramesInFlight;
  3895. #ifdef SDL_PLATFORM_APPLE
  3896. windowData->width = swapchainSupportDetails.capabilities.currentExtent.width;
  3897. windowData->height = swapchainSupportDetails.capabilities.currentExtent.height;
  3898. #else
  3899. windowData->width = SDL_clamp(
  3900. windowData->swapchainCreateWidth,
  3901. swapchainSupportDetails.capabilities.minImageExtent.width,
  3902. swapchainSupportDetails.capabilities.maxImageExtent.width);
  3903. windowData->height = SDL_clamp(windowData->swapchainCreateHeight,
  3904. swapchainSupportDetails.capabilities.minImageExtent.height,
  3905. swapchainSupportDetails.capabilities.maxImageExtent.height);
  3906. #endif
  3907. if (swapchainSupportDetails.capabilities.maxImageCount > 0 &&
  3908. requestedImageCount > swapchainSupportDetails.capabilities.maxImageCount) {
  3909. requestedImageCount = swapchainSupportDetails.capabilities.maxImageCount;
  3910. }
  3911. if (requestedImageCount < swapchainSupportDetails.capabilities.minImageCount) {
  3912. requestedImageCount = swapchainSupportDetails.capabilities.minImageCount;
  3913. }
  3914. if (windowData->presentMode == SDL_GPU_PRESENTMODE_MAILBOX) {
  3915. /* Required for proper triple-buffering.
  3916. * Note that this is below the above maxImageCount check!
  3917. * If the driver advertises MAILBOX but does not support 3 swap
  3918. * images, it's not real mailbox support, so let it fail hard.
  3919. * -flibit
  3920. */
  3921. requestedImageCount = SDL_max(requestedImageCount, 3);
  3922. }
  3923. // Default to opaque, if available, followed by inherit, and overwrite with a value that supports transparency, if necessary.
  3924. if (swapchainSupportDetails.capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR) {
  3925. compositeAlphaFlag = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  3926. } else if (swapchainSupportDetails.capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR) {
  3927. compositeAlphaFlag = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
  3928. }
  3929. if ((windowData->window->flags & SDL_WINDOW_TRANSPARENT) || !compositeAlphaFlag) {
  3930. if (swapchainSupportDetails.capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR) {
  3931. compositeAlphaFlag = VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR;
  3932. } else if (swapchainSupportDetails.capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR) {
  3933. compositeAlphaFlag = VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR;
  3934. } else if (swapchainSupportDetails.capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR) {
  3935. compositeAlphaFlag = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
  3936. } else {
  3937. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "SDL_WINDOW_TRANSPARENT flag set, but no suitable swapchain composite alpha value supported!");
  3938. }
  3939. }
  3940. swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
  3941. swapchainCreateInfo.pNext = NULL;
  3942. swapchainCreateInfo.flags = 0;
  3943. swapchainCreateInfo.surface = windowData->surface;
  3944. swapchainCreateInfo.minImageCount = requestedImageCount;
  3945. swapchainCreateInfo.imageFormat = windowData->format;
  3946. swapchainCreateInfo.imageColorSpace = windowData->colorSpace;
  3947. swapchainCreateInfo.imageExtent.width = windowData->width;
  3948. swapchainCreateInfo.imageExtent.height = windowData->height;
  3949. swapchainCreateInfo.imageArrayLayers = 1;
  3950. swapchainCreateInfo.imageUsage =
  3951. VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
  3952. VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  3953. swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
  3954. swapchainCreateInfo.queueFamilyIndexCount = 0;
  3955. swapchainCreateInfo.pQueueFamilyIndices = NULL;
  3956. #ifdef SDL_PLATFORM_ANDROID
  3957. swapchainCreateInfo.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
  3958. #else
  3959. swapchainCreateInfo.preTransform = swapchainSupportDetails.capabilities.currentTransform;
  3960. #endif
  3961. swapchainCreateInfo.compositeAlpha = compositeAlphaFlag;
  3962. swapchainCreateInfo.presentMode = SDLToVK_PresentMode[windowData->presentMode];
  3963. swapchainCreateInfo.clipped = VK_TRUE;
  3964. // The old swapchain could belong to a surface that no longer exists due to app switching.
  3965. swapchainCreateInfo.oldSwapchain = windowData->needsSurfaceRecreate ? (VkSwapchainKHR)0 : windowData->swapchain;
  3966. vulkanResult = renderer->vkCreateSwapchainKHR(
  3967. renderer->logicalDevice,
  3968. &swapchainCreateInfo,
  3969. NULL,
  3970. &windowData->swapchain);
  3971. if (swapchainCreateInfo.oldSwapchain != VK_NULL_HANDLE) {
  3972. renderer->vkDestroySwapchainKHR(renderer->logicalDevice, swapchainCreateInfo.oldSwapchain, NULL);
  3973. }
  3974. if (swapchainSupportDetails.formatsLength > 0) {
  3975. SDL_free(swapchainSupportDetails.formats);
  3976. }
  3977. if (swapchainSupportDetails.presentModesLength > 0) {
  3978. SDL_free(swapchainSupportDetails.presentModes);
  3979. }
  3980. if (vulkanResult != VK_SUCCESS) {
  3981. windowData->swapchain = VK_NULL_HANDLE;
  3982. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateSwapchainKHR, false);
  3983. }
  3984. vulkanResult = renderer->vkGetSwapchainImagesKHR(
  3985. renderer->logicalDevice,
  3986. windowData->swapchain,
  3987. &windowData->imageCount,
  3988. NULL);
  3989. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkGetSwapchainImagesKHR, false);
  3990. windowData->textureContainers = SDL_malloc(
  3991. sizeof(VulkanTextureContainer) * windowData->imageCount);
  3992. if (!windowData->textureContainers) { // OOM
  3993. renderer->vkDestroySwapchainKHR(
  3994. renderer->logicalDevice,
  3995. windowData->swapchain,
  3996. NULL);
  3997. windowData->swapchain = VK_NULL_HANDLE;
  3998. return false;
  3999. }
  4000. swapchainImages = SDL_stack_alloc(VkImage, windowData->imageCount);
  4001. vulkanResult = renderer->vkGetSwapchainImagesKHR(
  4002. renderer->logicalDevice,
  4003. windowData->swapchain,
  4004. &windowData->imageCount,
  4005. swapchainImages);
  4006. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkGetSwapchainImagesKHR, false);
  4007. for (i = 0; i < windowData->imageCount; i += 1) {
  4008. // Initialize dummy container
  4009. SDL_zero(windowData->textureContainers[i]);
  4010. windowData->textureContainers[i].canBeCycled = false;
  4011. windowData->textureContainers[i].header.info.width = windowData->width;
  4012. windowData->textureContainers[i].header.info.height = windowData->height;
  4013. windowData->textureContainers[i].header.info.layer_count_or_depth = 1;
  4014. windowData->textureContainers[i].header.info.format = SwapchainCompositionToSDLFormat(
  4015. windowData->swapchainComposition,
  4016. windowData->usingFallbackFormat);
  4017. windowData->textureContainers[i].header.info.type = SDL_GPU_TEXTURETYPE_2D;
  4018. windowData->textureContainers[i].header.info.num_levels = 1;
  4019. windowData->textureContainers[i].header.info.sample_count = SDL_GPU_SAMPLECOUNT_1;
  4020. windowData->textureContainers[i].header.info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
  4021. windowData->textureContainers[i].activeTexture = SDL_malloc(sizeof(VulkanTexture));
  4022. windowData->textureContainers[i].activeTexture->image = swapchainImages[i];
  4023. // Swapchain memory is managed by the driver
  4024. windowData->textureContainers[i].activeTexture->usedRegion = NULL;
  4025. windowData->textureContainers[i].activeTexture->swizzle = windowData->swapchainSwizzle;
  4026. windowData->textureContainers[i].activeTexture->aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT;
  4027. windowData->textureContainers[i].activeTexture->depth = 1;
  4028. windowData->textureContainers[i].activeTexture->usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
  4029. windowData->textureContainers[i].activeTexture->container = &windowData->textureContainers[i];
  4030. SDL_SetAtomicInt(&windowData->textureContainers[i].activeTexture->referenceCount, 0);
  4031. // Create slice
  4032. windowData->textureContainers[i].activeTexture->subresourceCount = 1;
  4033. windowData->textureContainers[i].activeTexture->subresources = SDL_malloc(sizeof(VulkanTextureSubresource));
  4034. windowData->textureContainers[i].activeTexture->subresources[0].parent = windowData->textureContainers[i].activeTexture;
  4035. windowData->textureContainers[i].activeTexture->subresources[0].layer = 0;
  4036. windowData->textureContainers[i].activeTexture->subresources[0].level = 0;
  4037. windowData->textureContainers[i].activeTexture->subresources[0].renderTargetViews = SDL_malloc(sizeof(VkImageView));
  4038. if (!VULKAN_INTERNAL_CreateRenderTargetView(
  4039. renderer,
  4040. windowData->textureContainers[i].activeTexture,
  4041. 0,
  4042. 0,
  4043. windowData->format,
  4044. windowData->swapchainSwizzle,
  4045. &windowData->textureContainers[i].activeTexture->subresources[0].renderTargetViews[0])) {
  4046. renderer->vkDestroySwapchainKHR(
  4047. renderer->logicalDevice,
  4048. windowData->swapchain,
  4049. NULL);
  4050. windowData->swapchain = VK_NULL_HANDLE;
  4051. return false;
  4052. }
  4053. }
  4054. SDL_stack_free(swapchainImages);
  4055. semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  4056. semaphoreCreateInfo.pNext = NULL;
  4057. semaphoreCreateInfo.flags = 0;
  4058. for (i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  4059. vulkanResult = renderer->vkCreateSemaphore(
  4060. renderer->logicalDevice,
  4061. &semaphoreCreateInfo,
  4062. NULL,
  4063. &windowData->imageAvailableSemaphore[i]);
  4064. if (vulkanResult != VK_SUCCESS) {
  4065. renderer->vkDestroySwapchainKHR(
  4066. renderer->logicalDevice,
  4067. windowData->swapchain,
  4068. NULL);
  4069. windowData->swapchain = VK_NULL_HANDLE;
  4070. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateSemaphore, false);
  4071. }
  4072. windowData->inFlightFences[i] = NULL;
  4073. }
  4074. windowData->renderFinishedSemaphore = SDL_malloc(
  4075. sizeof(VkSemaphore) * windowData->imageCount);
  4076. for (i = 0; i < windowData->imageCount; i += 1) {
  4077. vulkanResult = renderer->vkCreateSemaphore(
  4078. renderer->logicalDevice,
  4079. &semaphoreCreateInfo,
  4080. NULL,
  4081. &windowData->renderFinishedSemaphore[i]);
  4082. if (vulkanResult != VK_SUCCESS) {
  4083. renderer->vkDestroySwapchainKHR(
  4084. renderer->logicalDevice,
  4085. windowData->swapchain,
  4086. NULL);
  4087. windowData->swapchain = VK_NULL_HANDLE;
  4088. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateSemaphore, false);
  4089. }
  4090. }
  4091. windowData->needsSwapchainRecreate = false;
  4092. return true;
  4093. }
  4094. // Command Buffers
  4095. static bool VULKAN_INTERNAL_BeginCommandBuffer(
  4096. VulkanRenderer *renderer,
  4097. VulkanCommandBuffer *commandBuffer)
  4098. {
  4099. VkCommandBufferBeginInfo beginInfo;
  4100. VkResult result;
  4101. beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  4102. beginInfo.pNext = NULL;
  4103. beginInfo.flags = 0;
  4104. beginInfo.pInheritanceInfo = NULL;
  4105. beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  4106. result = renderer->vkBeginCommandBuffer(
  4107. commandBuffer->commandBuffer,
  4108. &beginInfo);
  4109. CHECK_VULKAN_ERROR_AND_RETURN(result, vkBeginCommandBuffer, false);
  4110. return true;
  4111. }
  4112. static bool VULKAN_INTERNAL_EndCommandBuffer(
  4113. VulkanRenderer *renderer,
  4114. VulkanCommandBuffer *commandBuffer)
  4115. {
  4116. VkResult result = renderer->vkEndCommandBuffer(
  4117. commandBuffer->commandBuffer);
  4118. CHECK_VULKAN_ERROR_AND_RETURN(result, vkEndCommandBuffer, false);
  4119. return true;
  4120. }
  4121. static void VULKAN_DestroyDevice(
  4122. SDL_GPUDevice *device)
  4123. {
  4124. VulkanRenderer *renderer = (VulkanRenderer *)device->driverData;
  4125. VulkanMemorySubAllocator *allocator;
  4126. VULKAN_Wait(device->driverData);
  4127. for (Sint32 i = renderer->claimedWindowCount - 1; i >= 0; i -= 1) {
  4128. VULKAN_ReleaseWindow(device->driverData, renderer->claimedWindows[i]->window);
  4129. }
  4130. SDL_free(renderer->claimedWindows);
  4131. VULKAN_Wait(device->driverData);
  4132. SDL_free(renderer->submittedCommandBuffers);
  4133. for (Uint32 i = 0; i < renderer->uniformBufferPoolCount; i += 1) {
  4134. VULKAN_INTERNAL_DestroyBuffer(
  4135. renderer,
  4136. renderer->uniformBufferPool[i]->buffer);
  4137. SDL_free(renderer->uniformBufferPool[i]);
  4138. }
  4139. SDL_free(renderer->uniformBufferPool);
  4140. for (Uint32 i = 0; i < renderer->descriptorSetCachePoolCount; i += 1) {
  4141. VULKAN_INTERNAL_DestroyDescriptorSetCache(
  4142. renderer,
  4143. renderer->descriptorSetCachePool[i]);
  4144. }
  4145. SDL_free(renderer->descriptorSetCachePool);
  4146. for (Uint32 i = 0; i < renderer->fencePool.availableFenceCount; i += 1) {
  4147. renderer->vkDestroyFence(
  4148. renderer->logicalDevice,
  4149. renderer->fencePool.availableFences[i]->fence,
  4150. NULL);
  4151. SDL_free(renderer->fencePool.availableFences[i]);
  4152. }
  4153. SDL_free(renderer->fencePool.availableFences);
  4154. SDL_DestroyMutex(renderer->fencePool.lock);
  4155. SDL_DestroyHashTable(renderer->commandPoolHashTable);
  4156. SDL_DestroyHashTable(renderer->renderPassHashTable);
  4157. SDL_DestroyHashTable(renderer->framebufferHashTable);
  4158. SDL_DestroyHashTable(renderer->graphicsPipelineResourceLayoutHashTable);
  4159. SDL_DestroyHashTable(renderer->computePipelineResourceLayoutHashTable);
  4160. SDL_DestroyHashTable(renderer->descriptorSetLayoutHashTable);
  4161. for (Uint32 i = 0; i < VK_MAX_MEMORY_TYPES; i += 1) {
  4162. allocator = &renderer->memoryAllocator->subAllocators[i];
  4163. for (Sint32 j = allocator->allocationCount - 1; j >= 0; j -= 1) {
  4164. for (Sint32 k = allocator->allocations[j]->usedRegionCount - 1; k >= 0; k -= 1) {
  4165. VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  4166. renderer,
  4167. allocator->allocations[j]->usedRegions[k]);
  4168. }
  4169. VULKAN_INTERNAL_DeallocateMemory(
  4170. renderer,
  4171. allocator,
  4172. j);
  4173. }
  4174. SDL_free(renderer->memoryAllocator->subAllocators[i].allocations);
  4175. SDL_free(renderer->memoryAllocator->subAllocators[i].sortedFreeRegions);
  4176. }
  4177. SDL_free(renderer->memoryAllocator);
  4178. SDL_free(renderer->texturesToDestroy);
  4179. SDL_free(renderer->buffersToDestroy);
  4180. SDL_free(renderer->graphicsPipelinesToDestroy);
  4181. SDL_free(renderer->computePipelinesToDestroy);
  4182. SDL_free(renderer->shadersToDestroy);
  4183. SDL_free(renderer->samplersToDestroy);
  4184. SDL_free(renderer->framebuffersToDestroy);
  4185. SDL_free(renderer->allocationsToDefrag);
  4186. SDL_DestroyMutex(renderer->allocatorLock);
  4187. SDL_DestroyMutex(renderer->disposeLock);
  4188. SDL_DestroyMutex(renderer->submitLock);
  4189. SDL_DestroyMutex(renderer->acquireCommandBufferLock);
  4190. SDL_DestroyMutex(renderer->acquireUniformBufferLock);
  4191. SDL_DestroyMutex(renderer->renderPassFetchLock);
  4192. SDL_DestroyMutex(renderer->framebufferFetchLock);
  4193. SDL_DestroyMutex(renderer->graphicsPipelineLayoutFetchLock);
  4194. SDL_DestroyMutex(renderer->computePipelineLayoutFetchLock);
  4195. SDL_DestroyMutex(renderer->descriptorSetLayoutFetchLock);
  4196. SDL_DestroyMutex(renderer->windowLock);
  4197. renderer->vkDestroyDevice(renderer->logicalDevice, NULL);
  4198. renderer->vkDestroyInstance(renderer->instance, NULL);
  4199. SDL_DestroyProperties(renderer->props);
  4200. SDL_free(renderer);
  4201. SDL_free(device);
  4202. SDL_Vulkan_UnloadLibrary();
  4203. }
  4204. static SDL_PropertiesID VULKAN_GetDeviceProperties(
  4205. SDL_GPUDevice *device)
  4206. {
  4207. VulkanRenderer *renderer = (VulkanRenderer *)device->driverData;
  4208. return renderer->props;
  4209. }
  4210. static DescriptorSetCache *VULKAN_INTERNAL_AcquireDescriptorSetCache(
  4211. VulkanRenderer *renderer)
  4212. {
  4213. DescriptorSetCache *cache;
  4214. if (renderer->descriptorSetCachePoolCount == 0) {
  4215. cache = SDL_malloc(sizeof(DescriptorSetCache));
  4216. cache->poolCount = 0;
  4217. cache->pools = NULL;
  4218. } else {
  4219. cache = renderer->descriptorSetCachePool[renderer->descriptorSetCachePoolCount - 1];
  4220. renderer->descriptorSetCachePoolCount -= 1;
  4221. }
  4222. return cache;
  4223. }
  4224. static void VULKAN_INTERNAL_ReturnDescriptorSetCacheToPool(
  4225. VulkanRenderer *renderer,
  4226. DescriptorSetCache *descriptorSetCache)
  4227. {
  4228. EXPAND_ARRAY_IF_NEEDED(
  4229. renderer->descriptorSetCachePool,
  4230. DescriptorSetCache *,
  4231. renderer->descriptorSetCachePoolCount + 1,
  4232. renderer->descriptorSetCachePoolCapacity,
  4233. renderer->descriptorSetCachePoolCapacity * 2);
  4234. renderer->descriptorSetCachePool[renderer->descriptorSetCachePoolCount] = descriptorSetCache;
  4235. renderer->descriptorSetCachePoolCount += 1;
  4236. for (Uint32 i = 0; i < descriptorSetCache->poolCount; i += 1) {
  4237. descriptorSetCache->pools[i].descriptorSetIndex = 0;
  4238. }
  4239. }
  4240. static VkDescriptorSet VULKAN_INTERNAL_FetchDescriptorSet(
  4241. VulkanRenderer *renderer,
  4242. VulkanCommandBuffer *vulkanCommandBuffer,
  4243. DescriptorSetLayout *descriptorSetLayout)
  4244. {
  4245. // Grow the pool to meet the descriptor set layout ID
  4246. if (descriptorSetLayout->ID >= vulkanCommandBuffer->descriptorSetCache->poolCount) {
  4247. vulkanCommandBuffer->descriptorSetCache->pools = SDL_realloc(
  4248. vulkanCommandBuffer->descriptorSetCache->pools,
  4249. sizeof(DescriptorSetPool) * (descriptorSetLayout->ID + 1));
  4250. for (Uint32 i = vulkanCommandBuffer->descriptorSetCache->poolCount; i < descriptorSetLayout->ID + 1; i += 1) {
  4251. SDL_zero(vulkanCommandBuffer->descriptorSetCache->pools[i]);
  4252. }
  4253. vulkanCommandBuffer->descriptorSetCache->poolCount = descriptorSetLayout->ID + 1;
  4254. }
  4255. DescriptorSetPool *pool =
  4256. &vulkanCommandBuffer->descriptorSetCache->pools[descriptorSetLayout->ID];
  4257. if (pool->descriptorSetIndex == pool->descriptorSetCount) {
  4258. if (!VULKAN_INTERNAL_AllocateDescriptorsFromPool(
  4259. renderer,
  4260. descriptorSetLayout,
  4261. pool)) {
  4262. return VK_NULL_HANDLE;
  4263. }
  4264. }
  4265. VkDescriptorSet descriptorSet = pool->descriptorSets[pool->descriptorSetIndex];
  4266. pool->descriptorSetIndex += 1;
  4267. return descriptorSet;
  4268. }
  4269. static void VULKAN_INTERNAL_BindGraphicsDescriptorSets(
  4270. VulkanRenderer *renderer,
  4271. VulkanCommandBuffer *commandBuffer)
  4272. {
  4273. VulkanGraphicsPipelineResourceLayout *resourceLayout;
  4274. DescriptorSetLayout *descriptorSetLayout;
  4275. VkWriteDescriptorSet writeDescriptorSets[
  4276. (MAX_TEXTURE_SAMPLERS_PER_STAGE +
  4277. MAX_STORAGE_TEXTURES_PER_STAGE +
  4278. MAX_STORAGE_BUFFERS_PER_STAGE +
  4279. MAX_UNIFORM_BUFFERS_PER_STAGE) * 2];
  4280. VkDescriptorBufferInfo bufferInfos[MAX_STORAGE_BUFFERS_PER_STAGE * 2];
  4281. VkDescriptorImageInfo imageInfos[(MAX_TEXTURE_SAMPLERS_PER_STAGE + MAX_STORAGE_TEXTURES_PER_STAGE) * 2];
  4282. Uint32 dynamicOffsets[MAX_UNIFORM_BUFFERS_PER_STAGE * 2];
  4283. Uint32 writeCount = 0;
  4284. Uint32 bufferInfoCount = 0;
  4285. Uint32 imageInfoCount = 0;
  4286. Uint32 dynamicOffsetCount = 0;
  4287. if (
  4288. !commandBuffer->needVertexBufferBind &&
  4289. !commandBuffer->needNewVertexResourceDescriptorSet &&
  4290. !commandBuffer->needNewVertexUniformDescriptorSet &&
  4291. !commandBuffer->needNewVertexUniformOffsets &&
  4292. !commandBuffer->needNewFragmentResourceDescriptorSet &&
  4293. !commandBuffer->needNewFragmentUniformDescriptorSet &&
  4294. !commandBuffer->needNewFragmentUniformOffsets
  4295. ) {
  4296. return;
  4297. }
  4298. if (commandBuffer->needVertexBufferBind && commandBuffer->vertexBufferCount > 0) {
  4299. renderer->vkCmdBindVertexBuffers(
  4300. commandBuffer->commandBuffer,
  4301. 0,
  4302. commandBuffer->vertexBufferCount,
  4303. commandBuffer->vertexBuffers,
  4304. commandBuffer->vertexBufferOffsets);
  4305. commandBuffer->needVertexBufferBind = false;
  4306. }
  4307. resourceLayout = commandBuffer->currentGraphicsPipeline->resourceLayout;
  4308. if (commandBuffer->needNewVertexResourceDescriptorSet) {
  4309. descriptorSetLayout = resourceLayout->descriptorSetLayouts[0];
  4310. commandBuffer->vertexResourceDescriptorSet = VULKAN_INTERNAL_FetchDescriptorSet(
  4311. renderer,
  4312. commandBuffer,
  4313. descriptorSetLayout);
  4314. for (Uint32 i = 0; i < resourceLayout->vertexSamplerCount; i += 1) {
  4315. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4316. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4317. currentWriteDescriptorSet->pNext = NULL;
  4318. currentWriteDescriptorSet->descriptorCount = 1;
  4319. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  4320. currentWriteDescriptorSet->dstArrayElement = 0;
  4321. currentWriteDescriptorSet->dstBinding = i;
  4322. currentWriteDescriptorSet->dstSet = commandBuffer->vertexResourceDescriptorSet;
  4323. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4324. currentWriteDescriptorSet->pBufferInfo = NULL;
  4325. imageInfos[imageInfoCount].sampler = commandBuffer->vertexSamplerBindings[i];
  4326. imageInfos[imageInfoCount].imageView = commandBuffer->vertexSamplerTextureViewBindings[i];
  4327. imageInfos[imageInfoCount].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  4328. currentWriteDescriptorSet->pImageInfo = &imageInfos[imageInfoCount];
  4329. writeCount += 1;
  4330. imageInfoCount += 1;
  4331. }
  4332. for (Uint32 i = 0; i < resourceLayout->vertexStorageTextureCount; i += 1) {
  4333. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4334. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4335. currentWriteDescriptorSet->pNext = NULL;
  4336. currentWriteDescriptorSet->descriptorCount = 1;
  4337. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; // Yes, we are declaring a storage image as a sampled image, because shaders are stupid.
  4338. currentWriteDescriptorSet->dstArrayElement = 0;
  4339. currentWriteDescriptorSet->dstBinding = resourceLayout->vertexSamplerCount + i;
  4340. currentWriteDescriptorSet->dstSet = commandBuffer->vertexResourceDescriptorSet;
  4341. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4342. currentWriteDescriptorSet->pBufferInfo = NULL;
  4343. imageInfos[imageInfoCount].sampler = VK_NULL_HANDLE;
  4344. imageInfos[imageInfoCount].imageView = commandBuffer->vertexStorageTextureViewBindings[i];
  4345. imageInfos[imageInfoCount].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
  4346. currentWriteDescriptorSet->pImageInfo = &imageInfos[imageInfoCount];
  4347. writeCount += 1;
  4348. imageInfoCount += 1;
  4349. }
  4350. for (Uint32 i = 0; i < resourceLayout->vertexStorageBufferCount; i += 1) {
  4351. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4352. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4353. currentWriteDescriptorSet->pNext = NULL;
  4354. currentWriteDescriptorSet->descriptorCount = 1;
  4355. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  4356. currentWriteDescriptorSet->dstArrayElement = 0;
  4357. currentWriteDescriptorSet->dstBinding = resourceLayout->vertexSamplerCount + resourceLayout->vertexStorageTextureCount + i;
  4358. currentWriteDescriptorSet->dstSet = commandBuffer->vertexResourceDescriptorSet;
  4359. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4360. currentWriteDescriptorSet->pImageInfo = NULL;
  4361. bufferInfos[bufferInfoCount].buffer = commandBuffer->vertexStorageBufferBindings[i];
  4362. bufferInfos[bufferInfoCount].offset = 0;
  4363. bufferInfos[bufferInfoCount].range = VK_WHOLE_SIZE;
  4364. currentWriteDescriptorSet->pBufferInfo = &bufferInfos[bufferInfoCount];
  4365. writeCount += 1;
  4366. bufferInfoCount += 1;
  4367. }
  4368. commandBuffer->needNewVertexResourceDescriptorSet = false;
  4369. }
  4370. if (commandBuffer->needNewVertexUniformDescriptorSet) {
  4371. descriptorSetLayout = resourceLayout->descriptorSetLayouts[1];
  4372. commandBuffer->vertexUniformDescriptorSet = VULKAN_INTERNAL_FetchDescriptorSet(
  4373. renderer,
  4374. commandBuffer,
  4375. descriptorSetLayout);
  4376. for (Uint32 i = 0; i < resourceLayout->vertexUniformBufferCount; i += 1) {
  4377. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4378. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4379. currentWriteDescriptorSet->pNext = NULL;
  4380. currentWriteDescriptorSet->descriptorCount = 1;
  4381. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
  4382. currentWriteDescriptorSet->dstArrayElement = 0;
  4383. currentWriteDescriptorSet->dstBinding = i;
  4384. currentWriteDescriptorSet->dstSet = commandBuffer->vertexUniformDescriptorSet;
  4385. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4386. currentWriteDescriptorSet->pImageInfo = NULL;
  4387. bufferInfos[bufferInfoCount].buffer = commandBuffer->vertexUniformBuffers[i]->buffer->buffer;
  4388. bufferInfos[bufferInfoCount].offset = 0;
  4389. bufferInfos[bufferInfoCount].range = MAX_UBO_SECTION_SIZE;
  4390. currentWriteDescriptorSet->pBufferInfo = &bufferInfos[bufferInfoCount];
  4391. writeCount += 1;
  4392. bufferInfoCount += 1;
  4393. }
  4394. commandBuffer->needNewVertexUniformDescriptorSet = false;
  4395. }
  4396. for (Uint32 i = 0; i < resourceLayout->vertexUniformBufferCount; i += 1) {
  4397. dynamicOffsets[dynamicOffsetCount] = commandBuffer->vertexUniformBuffers[i]->drawOffset;
  4398. dynamicOffsetCount += 1;
  4399. }
  4400. if (commandBuffer->needNewFragmentResourceDescriptorSet) {
  4401. descriptorSetLayout = resourceLayout->descriptorSetLayouts[2];
  4402. commandBuffer->fragmentResourceDescriptorSet = VULKAN_INTERNAL_FetchDescriptorSet(
  4403. renderer,
  4404. commandBuffer,
  4405. descriptorSetLayout);
  4406. for (Uint32 i = 0; i < resourceLayout->fragmentSamplerCount; i += 1) {
  4407. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4408. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4409. currentWriteDescriptorSet->pNext = NULL;
  4410. currentWriteDescriptorSet->descriptorCount = 1;
  4411. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  4412. currentWriteDescriptorSet->dstArrayElement = 0;
  4413. currentWriteDescriptorSet->dstBinding = i;
  4414. currentWriteDescriptorSet->dstSet = commandBuffer->fragmentResourceDescriptorSet;
  4415. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4416. currentWriteDescriptorSet->pBufferInfo = NULL;
  4417. imageInfos[imageInfoCount].sampler = commandBuffer->fragmentSamplerBindings[i];
  4418. imageInfos[imageInfoCount].imageView = commandBuffer->fragmentSamplerTextureViewBindings[i];
  4419. imageInfos[imageInfoCount].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  4420. currentWriteDescriptorSet->pImageInfo = &imageInfos[imageInfoCount];
  4421. writeCount += 1;
  4422. imageInfoCount += 1;
  4423. }
  4424. for (Uint32 i = 0; i < resourceLayout->fragmentStorageTextureCount; i += 1) {
  4425. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4426. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4427. currentWriteDescriptorSet->pNext = NULL;
  4428. currentWriteDescriptorSet->descriptorCount = 1;
  4429. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; // Yes, we are declaring a storage image as a sampled image, because shaders are stupid.
  4430. currentWriteDescriptorSet->dstArrayElement = 0;
  4431. currentWriteDescriptorSet->dstBinding = resourceLayout->fragmentSamplerCount + i;
  4432. currentWriteDescriptorSet->dstSet = commandBuffer->fragmentResourceDescriptorSet;
  4433. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4434. currentWriteDescriptorSet->pBufferInfo = NULL;
  4435. imageInfos[imageInfoCount].sampler = VK_NULL_HANDLE;
  4436. imageInfos[imageInfoCount].imageView = commandBuffer->fragmentStorageTextureViewBindings[i];
  4437. imageInfos[imageInfoCount].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
  4438. currentWriteDescriptorSet->pImageInfo = &imageInfos[imageInfoCount];
  4439. writeCount += 1;
  4440. imageInfoCount += 1;
  4441. }
  4442. for (Uint32 i = 0; i < resourceLayout->fragmentStorageBufferCount; i += 1) {
  4443. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4444. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4445. currentWriteDescriptorSet->pNext = NULL;
  4446. currentWriteDescriptorSet->descriptorCount = 1;
  4447. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  4448. currentWriteDescriptorSet->dstArrayElement = 0;
  4449. currentWriteDescriptorSet->dstBinding = resourceLayout->fragmentSamplerCount + resourceLayout->fragmentStorageTextureCount + i;
  4450. currentWriteDescriptorSet->dstSet = commandBuffer->fragmentResourceDescriptorSet;
  4451. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4452. currentWriteDescriptorSet->pImageInfo = NULL;
  4453. bufferInfos[bufferInfoCount].buffer = commandBuffer->fragmentStorageBufferBindings[i];
  4454. bufferInfos[bufferInfoCount].offset = 0;
  4455. bufferInfos[bufferInfoCount].range = VK_WHOLE_SIZE;
  4456. currentWriteDescriptorSet->pBufferInfo = &bufferInfos[bufferInfoCount];
  4457. writeCount += 1;
  4458. bufferInfoCount += 1;
  4459. }
  4460. commandBuffer->needNewFragmentResourceDescriptorSet = false;
  4461. }
  4462. if (commandBuffer->needNewFragmentUniformDescriptorSet) {
  4463. descriptorSetLayout = resourceLayout->descriptorSetLayouts[3];
  4464. commandBuffer->fragmentUniformDescriptorSet = VULKAN_INTERNAL_FetchDescriptorSet(
  4465. renderer,
  4466. commandBuffer,
  4467. descriptorSetLayout);
  4468. for (Uint32 i = 0; i < resourceLayout->fragmentUniformBufferCount; i += 1) {
  4469. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4470. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4471. currentWriteDescriptorSet->pNext = NULL;
  4472. currentWriteDescriptorSet->descriptorCount = 1;
  4473. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
  4474. currentWriteDescriptorSet->dstArrayElement = 0;
  4475. currentWriteDescriptorSet->dstBinding = i;
  4476. currentWriteDescriptorSet->dstSet = commandBuffer->fragmentUniformDescriptorSet;
  4477. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4478. currentWriteDescriptorSet->pImageInfo = NULL;
  4479. bufferInfos[bufferInfoCount].buffer = commandBuffer->fragmentUniformBuffers[i]->buffer->buffer;
  4480. bufferInfos[bufferInfoCount].offset = 0;
  4481. bufferInfos[bufferInfoCount].range = MAX_UBO_SECTION_SIZE;
  4482. currentWriteDescriptorSet->pBufferInfo = &bufferInfos[bufferInfoCount];
  4483. writeCount += 1;
  4484. bufferInfoCount += 1;
  4485. }
  4486. commandBuffer->needNewFragmentUniformDescriptorSet = false;
  4487. }
  4488. for (Uint32 i = 0; i < resourceLayout->fragmentUniformBufferCount; i += 1) {
  4489. dynamicOffsets[dynamicOffsetCount] = commandBuffer->fragmentUniformBuffers[i]->drawOffset;
  4490. dynamicOffsetCount += 1;
  4491. }
  4492. renderer->vkUpdateDescriptorSets(
  4493. renderer->logicalDevice,
  4494. writeCount,
  4495. writeDescriptorSets,
  4496. 0,
  4497. NULL);
  4498. VkDescriptorSet sets[4];
  4499. sets[0] = commandBuffer->vertexResourceDescriptorSet;
  4500. sets[1] = commandBuffer->vertexUniformDescriptorSet;
  4501. sets[2] = commandBuffer->fragmentResourceDescriptorSet;
  4502. sets[3] = commandBuffer->fragmentUniformDescriptorSet;
  4503. renderer->vkCmdBindDescriptorSets(
  4504. commandBuffer->commandBuffer,
  4505. VK_PIPELINE_BIND_POINT_GRAPHICS,
  4506. resourceLayout->pipelineLayout,
  4507. 0,
  4508. 4,
  4509. sets,
  4510. dynamicOffsetCount,
  4511. dynamicOffsets);
  4512. commandBuffer->needNewVertexUniformOffsets = false;
  4513. commandBuffer->needNewFragmentUniformOffsets = false;
  4514. }
  4515. static void VULKAN_DrawIndexedPrimitives(
  4516. SDL_GPUCommandBuffer *commandBuffer,
  4517. Uint32 numIndices,
  4518. Uint32 numInstances,
  4519. Uint32 firstIndex,
  4520. Sint32 vertexOffset,
  4521. Uint32 firstInstance)
  4522. {
  4523. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  4524. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  4525. VULKAN_INTERNAL_BindGraphicsDescriptorSets(renderer, vulkanCommandBuffer);
  4526. renderer->vkCmdDrawIndexed(
  4527. vulkanCommandBuffer->commandBuffer,
  4528. numIndices,
  4529. numInstances,
  4530. firstIndex,
  4531. vertexOffset,
  4532. firstInstance);
  4533. }
  4534. static void VULKAN_DrawPrimitives(
  4535. SDL_GPUCommandBuffer *commandBuffer,
  4536. Uint32 numVertices,
  4537. Uint32 numInstances,
  4538. Uint32 firstVertex,
  4539. Uint32 firstInstance)
  4540. {
  4541. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  4542. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  4543. VULKAN_INTERNAL_BindGraphicsDescriptorSets(renderer, vulkanCommandBuffer);
  4544. renderer->vkCmdDraw(
  4545. vulkanCommandBuffer->commandBuffer,
  4546. numVertices,
  4547. numInstances,
  4548. firstVertex,
  4549. firstInstance);
  4550. }
  4551. static void VULKAN_DrawPrimitivesIndirect(
  4552. SDL_GPUCommandBuffer *commandBuffer,
  4553. SDL_GPUBuffer *buffer,
  4554. Uint32 offset,
  4555. Uint32 drawCount)
  4556. {
  4557. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  4558. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  4559. VulkanBuffer *vulkanBuffer = ((VulkanBufferContainer *)buffer)->activeBuffer;
  4560. Uint32 pitch = sizeof(SDL_GPUIndirectDrawCommand);
  4561. Uint32 i;
  4562. VULKAN_INTERNAL_BindGraphicsDescriptorSets(renderer, vulkanCommandBuffer);
  4563. if (renderer->supportsMultiDrawIndirect) {
  4564. // Real multi-draw!
  4565. renderer->vkCmdDrawIndirect(
  4566. vulkanCommandBuffer->commandBuffer,
  4567. vulkanBuffer->buffer,
  4568. offset,
  4569. drawCount,
  4570. pitch);
  4571. } else {
  4572. // Fake multi-draw...
  4573. for (i = 0; i < drawCount; i += 1) {
  4574. renderer->vkCmdDrawIndirect(
  4575. vulkanCommandBuffer->commandBuffer,
  4576. vulkanBuffer->buffer,
  4577. offset + (pitch * i),
  4578. 1,
  4579. pitch);
  4580. }
  4581. }
  4582. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, vulkanBuffer);
  4583. }
  4584. static void VULKAN_DrawIndexedPrimitivesIndirect(
  4585. SDL_GPUCommandBuffer *commandBuffer,
  4586. SDL_GPUBuffer *buffer,
  4587. Uint32 offset,
  4588. Uint32 drawCount)
  4589. {
  4590. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  4591. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  4592. VulkanBuffer *vulkanBuffer = ((VulkanBufferContainer *)buffer)->activeBuffer;
  4593. Uint32 pitch = sizeof(SDL_GPUIndexedIndirectDrawCommand);
  4594. Uint32 i;
  4595. VULKAN_INTERNAL_BindGraphicsDescriptorSets(renderer, vulkanCommandBuffer);
  4596. if (renderer->supportsMultiDrawIndirect) {
  4597. // Real multi-draw!
  4598. renderer->vkCmdDrawIndexedIndirect(
  4599. vulkanCommandBuffer->commandBuffer,
  4600. vulkanBuffer->buffer,
  4601. offset,
  4602. drawCount,
  4603. pitch);
  4604. } else {
  4605. // Fake multi-draw...
  4606. for (i = 0; i < drawCount; i += 1) {
  4607. renderer->vkCmdDrawIndexedIndirect(
  4608. vulkanCommandBuffer->commandBuffer,
  4609. vulkanBuffer->buffer,
  4610. offset + (pitch * i),
  4611. 1,
  4612. pitch);
  4613. }
  4614. }
  4615. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, vulkanBuffer);
  4616. }
  4617. // Debug Naming
  4618. static void VULKAN_INTERNAL_SetBufferName(
  4619. VulkanRenderer *renderer,
  4620. VulkanBuffer *buffer,
  4621. const char *text)
  4622. {
  4623. VkDebugUtilsObjectNameInfoEXT nameInfo;
  4624. if (renderer->debugMode && renderer->supportsDebugUtils) {
  4625. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  4626. nameInfo.pNext = NULL;
  4627. nameInfo.pObjectName = text;
  4628. nameInfo.objectType = VK_OBJECT_TYPE_BUFFER;
  4629. nameInfo.objectHandle = (uint64_t)buffer->buffer;
  4630. renderer->vkSetDebugUtilsObjectNameEXT(
  4631. renderer->logicalDevice,
  4632. &nameInfo);
  4633. }
  4634. }
  4635. static void VULKAN_SetBufferName(
  4636. SDL_GPURenderer *driverData,
  4637. SDL_GPUBuffer *buffer,
  4638. const char *text)
  4639. {
  4640. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  4641. VulkanBufferContainer *container = (VulkanBufferContainer *)buffer;
  4642. size_t textLength = SDL_strlen(text) + 1;
  4643. if (renderer->debugMode && renderer->supportsDebugUtils) {
  4644. container->debugName = SDL_realloc(
  4645. container->debugName,
  4646. textLength);
  4647. SDL_utf8strlcpy(
  4648. container->debugName,
  4649. text,
  4650. textLength);
  4651. for (Uint32 i = 0; i < container->bufferCount; i += 1) {
  4652. VULKAN_INTERNAL_SetBufferName(
  4653. renderer,
  4654. container->buffers[i],
  4655. text);
  4656. }
  4657. }
  4658. }
  4659. static void VULKAN_INTERNAL_SetTextureName(
  4660. VulkanRenderer *renderer,
  4661. VulkanTexture *texture,
  4662. const char *text)
  4663. {
  4664. VkDebugUtilsObjectNameInfoEXT nameInfo;
  4665. if (renderer->debugMode && renderer->supportsDebugUtils) {
  4666. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  4667. nameInfo.pNext = NULL;
  4668. nameInfo.pObjectName = text;
  4669. nameInfo.objectType = VK_OBJECT_TYPE_IMAGE;
  4670. nameInfo.objectHandle = (uint64_t)texture->image;
  4671. renderer->vkSetDebugUtilsObjectNameEXT(
  4672. renderer->logicalDevice,
  4673. &nameInfo);
  4674. }
  4675. }
  4676. static void VULKAN_SetTextureName(
  4677. SDL_GPURenderer *driverData,
  4678. SDL_GPUTexture *texture,
  4679. const char *text)
  4680. {
  4681. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  4682. VulkanTextureContainer *container = (VulkanTextureContainer *)texture;
  4683. size_t textLength = SDL_strlen(text) + 1;
  4684. if (renderer->debugMode && renderer->supportsDebugUtils) {
  4685. container->debugName = SDL_realloc(
  4686. container->debugName,
  4687. textLength);
  4688. SDL_utf8strlcpy(
  4689. container->debugName,
  4690. text,
  4691. textLength);
  4692. for (Uint32 i = 0; i < container->textureCount; i += 1) {
  4693. VULKAN_INTERNAL_SetTextureName(
  4694. renderer,
  4695. container->textures[i],
  4696. text);
  4697. }
  4698. }
  4699. }
  4700. static void VULKAN_InsertDebugLabel(
  4701. SDL_GPUCommandBuffer *commandBuffer,
  4702. const char *text)
  4703. {
  4704. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  4705. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  4706. VkDebugUtilsLabelEXT labelInfo;
  4707. if (renderer->supportsDebugUtils) {
  4708. SDL_zero(labelInfo);
  4709. labelInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
  4710. labelInfo.pLabelName = text;
  4711. renderer->vkCmdInsertDebugUtilsLabelEXT(
  4712. vulkanCommandBuffer->commandBuffer,
  4713. &labelInfo);
  4714. }
  4715. }
  4716. static void VULKAN_PushDebugGroup(
  4717. SDL_GPUCommandBuffer *commandBuffer,
  4718. const char *name)
  4719. {
  4720. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  4721. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  4722. VkDebugUtilsLabelEXT labelInfo;
  4723. if (renderer->supportsDebugUtils) {
  4724. SDL_zero(labelInfo);
  4725. labelInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
  4726. labelInfo.pLabelName = name;
  4727. renderer->vkCmdBeginDebugUtilsLabelEXT(
  4728. vulkanCommandBuffer->commandBuffer,
  4729. &labelInfo);
  4730. }
  4731. }
  4732. static void VULKAN_PopDebugGroup(
  4733. SDL_GPUCommandBuffer *commandBuffer)
  4734. {
  4735. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  4736. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  4737. if (renderer->supportsDebugUtils) {
  4738. renderer->vkCmdEndDebugUtilsLabelEXT(vulkanCommandBuffer->commandBuffer);
  4739. }
  4740. }
  4741. static VulkanTexture *VULKAN_INTERNAL_CreateTexture(
  4742. VulkanRenderer *renderer,
  4743. bool transitionToDefaultLayout,
  4744. const SDL_GPUTextureCreateInfo *createinfo)
  4745. {
  4746. VkResult vulkanResult;
  4747. VkImageCreateInfo imageCreateInfo;
  4748. VkImageCreateFlags imageCreateFlags = 0;
  4749. VkImageViewCreateInfo imageViewCreateInfo;
  4750. Uint8 bindResult;
  4751. VkImageUsageFlags vkUsageFlags = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  4752. Uint32 layerCount = (createinfo->type == SDL_GPU_TEXTURETYPE_3D) ? 1 : createinfo->layer_count_or_depth;
  4753. Uint32 depth = (createinfo->type == SDL_GPU_TEXTURETYPE_3D) ? createinfo->layer_count_or_depth : 1;
  4754. VulkanTexture *texture = SDL_calloc(1, sizeof(VulkanTexture));
  4755. texture->swizzle = SwizzleForSDLFormat(createinfo->format);
  4756. texture->depth = depth;
  4757. texture->usage = createinfo->usage;
  4758. SDL_SetAtomicInt(&texture->referenceCount, 0);
  4759. if (IsDepthFormat(createinfo->format)) {
  4760. texture->aspectFlags = VK_IMAGE_ASPECT_DEPTH_BIT;
  4761. if (IsStencilFormat(createinfo->format)) {
  4762. texture->aspectFlags |= VK_IMAGE_ASPECT_STENCIL_BIT;
  4763. }
  4764. } else {
  4765. texture->aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT;
  4766. }
  4767. if (createinfo->type == SDL_GPU_TEXTURETYPE_CUBE || createinfo->type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  4768. imageCreateFlags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
  4769. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_3D) {
  4770. imageCreateFlags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT;
  4771. }
  4772. if (createinfo->usage & (SDL_GPU_TEXTUREUSAGE_SAMPLER |
  4773. SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ |
  4774. SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ)) {
  4775. vkUsageFlags |= VK_IMAGE_USAGE_SAMPLED_BIT;
  4776. }
  4777. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) {
  4778. vkUsageFlags |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  4779. }
  4780. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) {
  4781. vkUsageFlags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  4782. }
  4783. if (createinfo->usage & (SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE |
  4784. SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE)) {
  4785. vkUsageFlags |= VK_IMAGE_USAGE_STORAGE_BIT;
  4786. }
  4787. imageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  4788. imageCreateInfo.pNext = NULL;
  4789. imageCreateInfo.flags = imageCreateFlags;
  4790. imageCreateInfo.imageType = createinfo->type == SDL_GPU_TEXTURETYPE_3D ? VK_IMAGE_TYPE_3D : VK_IMAGE_TYPE_2D;
  4791. imageCreateInfo.format = SDLToVK_TextureFormat[createinfo->format];
  4792. imageCreateInfo.extent.width = createinfo->width;
  4793. imageCreateInfo.extent.height = createinfo->height;
  4794. imageCreateInfo.extent.depth = depth;
  4795. imageCreateInfo.mipLevels = createinfo->num_levels;
  4796. imageCreateInfo.arrayLayers = layerCount;
  4797. imageCreateInfo.samples = SDLToVK_SampleCount[createinfo->sample_count];
  4798. imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  4799. imageCreateInfo.usage = vkUsageFlags;
  4800. imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  4801. imageCreateInfo.queueFamilyIndexCount = 0;
  4802. imageCreateInfo.pQueueFamilyIndices = NULL;
  4803. imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  4804. vulkanResult = renderer->vkCreateImage(
  4805. renderer->logicalDevice,
  4806. &imageCreateInfo,
  4807. NULL,
  4808. &texture->image);
  4809. if (vulkanResult != VK_SUCCESS) {
  4810. VULKAN_INTERNAL_DestroyTexture(renderer, texture);
  4811. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateImage, NULL);
  4812. }
  4813. bindResult = VULKAN_INTERNAL_BindMemoryForImage(
  4814. renderer,
  4815. texture->image,
  4816. &texture->usedRegion);
  4817. if (bindResult != 1) {
  4818. renderer->vkDestroyImage(
  4819. renderer->logicalDevice,
  4820. texture->image,
  4821. NULL);
  4822. VULKAN_INTERNAL_DestroyTexture(renderer, texture);
  4823. SET_STRING_ERROR_AND_RETURN("Unable to bind memory for texture!", NULL);
  4824. }
  4825. texture->usedRegion->vulkanTexture = texture; // lol
  4826. if (createinfo->usage & (SDL_GPU_TEXTUREUSAGE_SAMPLER | SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ)) {
  4827. imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  4828. imageViewCreateInfo.pNext = NULL;
  4829. imageViewCreateInfo.flags = 0;
  4830. imageViewCreateInfo.image = texture->image;
  4831. imageViewCreateInfo.format = SDLToVK_TextureFormat[createinfo->format];
  4832. imageViewCreateInfo.components = texture->swizzle;
  4833. imageViewCreateInfo.subresourceRange.aspectMask = texture->aspectFlags & ~VK_IMAGE_ASPECT_STENCIL_BIT; // Can't sample stencil values
  4834. imageViewCreateInfo.subresourceRange.baseMipLevel = 0;
  4835. imageViewCreateInfo.subresourceRange.levelCount = createinfo->num_levels;
  4836. imageViewCreateInfo.subresourceRange.baseArrayLayer = 0;
  4837. imageViewCreateInfo.subresourceRange.layerCount = layerCount;
  4838. if (createinfo->type == SDL_GPU_TEXTURETYPE_CUBE) {
  4839. imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_CUBE;
  4840. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  4841. imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_CUBE_ARRAY;
  4842. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_3D) {
  4843. imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_3D;
  4844. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_2D_ARRAY) {
  4845. imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY;
  4846. } else {
  4847. imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  4848. }
  4849. vulkanResult = renderer->vkCreateImageView(
  4850. renderer->logicalDevice,
  4851. &imageViewCreateInfo,
  4852. NULL,
  4853. &texture->fullView);
  4854. if (vulkanResult != VK_SUCCESS) {
  4855. VULKAN_INTERNAL_DestroyTexture(renderer, texture);
  4856. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, "vkCreateImageView", NULL);
  4857. }
  4858. }
  4859. // Define slices
  4860. texture->subresourceCount = layerCount * createinfo->num_levels;
  4861. texture->subresources = SDL_calloc(
  4862. texture->subresourceCount,
  4863. sizeof(VulkanTextureSubresource));
  4864. for (Uint32 i = 0; i < layerCount; i += 1) {
  4865. for (Uint32 j = 0; j < createinfo->num_levels; j += 1) {
  4866. Uint32 subresourceIndex = VULKAN_INTERNAL_GetTextureSubresourceIndex(
  4867. j,
  4868. i,
  4869. createinfo->num_levels);
  4870. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) {
  4871. texture->subresources[subresourceIndex].renderTargetViews = SDL_malloc(
  4872. depth * sizeof(VkImageView));
  4873. if (depth > 1) {
  4874. for (Uint32 k = 0; k < depth; k += 1) {
  4875. if (!VULKAN_INTERNAL_CreateRenderTargetView(
  4876. renderer,
  4877. texture,
  4878. k,
  4879. j,
  4880. SDLToVK_TextureFormat[createinfo->format],
  4881. texture->swizzle,
  4882. &texture->subresources[subresourceIndex].renderTargetViews[k])) {
  4883. VULKAN_INTERNAL_DestroyTexture(renderer, texture);
  4884. return NULL;
  4885. }
  4886. }
  4887. } else {
  4888. if (!VULKAN_INTERNAL_CreateRenderTargetView(
  4889. renderer,
  4890. texture,
  4891. i,
  4892. j,
  4893. SDLToVK_TextureFormat[createinfo->format],
  4894. texture->swizzle,
  4895. &texture->subresources[subresourceIndex].renderTargetViews[0])) {
  4896. VULKAN_INTERNAL_DestroyTexture(renderer, texture);
  4897. return NULL;
  4898. }
  4899. }
  4900. }
  4901. if ((createinfo->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE) || (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE)) {
  4902. if (!VULKAN_INTERNAL_CreateSubresourceView(
  4903. renderer,
  4904. createinfo,
  4905. texture,
  4906. i,
  4907. j,
  4908. texture->swizzle,
  4909. &texture->subresources[subresourceIndex].computeWriteView)) {
  4910. VULKAN_INTERNAL_DestroyTexture(renderer, texture);
  4911. return NULL;
  4912. }
  4913. }
  4914. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) {
  4915. if (!VULKAN_INTERNAL_CreateSubresourceView(
  4916. renderer,
  4917. createinfo,
  4918. texture,
  4919. i,
  4920. j,
  4921. texture->swizzle,
  4922. &texture->subresources[subresourceIndex].depthStencilView)) {
  4923. VULKAN_INTERNAL_DestroyTexture(renderer, texture);
  4924. return NULL;
  4925. }
  4926. }
  4927. texture->subresources[subresourceIndex].parent = texture;
  4928. texture->subresources[subresourceIndex].layer = i;
  4929. texture->subresources[subresourceIndex].level = j;
  4930. }
  4931. }
  4932. // Set debug name if applicable
  4933. if (renderer->debugMode && renderer->supportsDebugUtils && SDL_HasProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_NAME_STRING)) {
  4934. VkDebugUtilsObjectNameInfoEXT nameInfo;
  4935. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  4936. nameInfo.pNext = NULL;
  4937. nameInfo.pObjectName = SDL_GetStringProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_NAME_STRING, NULL);
  4938. nameInfo.objectType = VK_OBJECT_TYPE_IMAGE;
  4939. nameInfo.objectHandle = (uint64_t)texture->image;
  4940. renderer->vkSetDebugUtilsObjectNameEXT(
  4941. renderer->logicalDevice,
  4942. &nameInfo);
  4943. }
  4944. if (transitionToDefaultLayout) {
  4945. // Let's transition to the default barrier state, because for some reason Vulkan doesn't let us do that with initialLayout.
  4946. VulkanCommandBuffer *barrierCommandBuffer = (VulkanCommandBuffer *)VULKAN_AcquireCommandBuffer((SDL_GPURenderer *)renderer);
  4947. VULKAN_INTERNAL_TextureTransitionToDefaultUsage(
  4948. renderer,
  4949. barrierCommandBuffer,
  4950. VULKAN_TEXTURE_USAGE_MODE_UNINITIALIZED,
  4951. texture);
  4952. VULKAN_INTERNAL_TrackTexture(barrierCommandBuffer, texture);
  4953. if (!VULKAN_Submit((SDL_GPUCommandBuffer *)barrierCommandBuffer)) {
  4954. VULKAN_INTERNAL_DestroyTexture(renderer, texture);
  4955. return NULL;
  4956. }
  4957. }
  4958. return texture;
  4959. }
  4960. static void VULKAN_INTERNAL_CycleActiveBuffer(
  4961. VulkanRenderer *renderer,
  4962. VulkanBufferContainer *container)
  4963. {
  4964. VulkanBuffer *buffer;
  4965. // If a previously-cycled buffer is available, we can use that.
  4966. for (Uint32 i = 0; i < container->bufferCount; i += 1) {
  4967. buffer = container->buffers[i];
  4968. if (SDL_GetAtomicInt(&buffer->referenceCount) == 0) {
  4969. container->activeBuffer = buffer;
  4970. return;
  4971. }
  4972. }
  4973. // No buffer handle is available, create a new one.
  4974. buffer = VULKAN_INTERNAL_CreateBuffer(
  4975. renderer,
  4976. container->activeBuffer->size,
  4977. container->activeBuffer->usage,
  4978. container->activeBuffer->type,
  4979. container->dedicated,
  4980. container->debugName);
  4981. if (!buffer) {
  4982. return;
  4983. }
  4984. EXPAND_ARRAY_IF_NEEDED(
  4985. container->buffers,
  4986. VulkanBuffer *,
  4987. container->bufferCount + 1,
  4988. container->bufferCapacity,
  4989. container->bufferCapacity * 2);
  4990. container->buffers[container->bufferCount] = buffer;
  4991. buffer->container = container;
  4992. buffer->containerIndex = container->bufferCount;
  4993. container->bufferCount += 1;
  4994. container->activeBuffer = buffer;
  4995. }
  4996. static void VULKAN_INTERNAL_CycleActiveTexture(
  4997. VulkanRenderer *renderer,
  4998. VulkanCommandBuffer *commandBuffer,
  4999. VulkanTextureContainer *container)
  5000. {
  5001. VulkanTexture *texture;
  5002. // If a previously-cycled texture is available, we can use that.
  5003. for (Uint32 i = 0; i < container->textureCount; i += 1) {
  5004. texture = container->textures[i];
  5005. if (SDL_GetAtomicInt(&texture->referenceCount) == 0) {
  5006. container->activeTexture = texture;
  5007. return;
  5008. }
  5009. }
  5010. // No texture is available, generate a new one.
  5011. texture = VULKAN_INTERNAL_CreateTexture(
  5012. renderer,
  5013. false,
  5014. &container->header.info);
  5015. VULKAN_INTERNAL_TextureTransitionToDefaultUsage(
  5016. renderer,
  5017. commandBuffer,
  5018. VULKAN_TEXTURE_USAGE_MODE_UNINITIALIZED,
  5019. texture);
  5020. if (!texture) {
  5021. return;
  5022. }
  5023. EXPAND_ARRAY_IF_NEEDED(
  5024. container->textures,
  5025. VulkanTexture *,
  5026. container->textureCount + 1,
  5027. container->textureCapacity,
  5028. container->textureCapacity * 2);
  5029. container->textures[container->textureCount] = texture;
  5030. texture->container = container;
  5031. texture->containerIndex = container->textureCount;
  5032. container->textureCount += 1;
  5033. container->activeTexture = texture;
  5034. }
  5035. static VulkanBuffer *VULKAN_INTERNAL_PrepareBufferForWrite(
  5036. VulkanRenderer *renderer,
  5037. VulkanCommandBuffer *commandBuffer,
  5038. VulkanBufferContainer *bufferContainer,
  5039. bool cycle,
  5040. VulkanBufferUsageMode destinationUsageMode)
  5041. {
  5042. if (
  5043. cycle &&
  5044. SDL_GetAtomicInt(&bufferContainer->activeBuffer->referenceCount) > 0) {
  5045. VULKAN_INTERNAL_CycleActiveBuffer(
  5046. renderer,
  5047. bufferContainer);
  5048. }
  5049. VULKAN_INTERNAL_BufferTransitionFromDefaultUsage(
  5050. renderer,
  5051. commandBuffer,
  5052. destinationUsageMode,
  5053. bufferContainer->activeBuffer);
  5054. return bufferContainer->activeBuffer;
  5055. }
  5056. static VulkanTextureSubresource *VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  5057. VulkanRenderer *renderer,
  5058. VulkanCommandBuffer *commandBuffer,
  5059. VulkanTextureContainer *textureContainer,
  5060. Uint32 layer,
  5061. Uint32 level,
  5062. bool cycle,
  5063. VulkanTextureUsageMode destinationUsageMode)
  5064. {
  5065. VulkanTextureSubresource *textureSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  5066. textureContainer,
  5067. layer,
  5068. level);
  5069. if (
  5070. cycle &&
  5071. textureContainer->canBeCycled &&
  5072. SDL_GetAtomicInt(&textureContainer->activeTexture->referenceCount) > 0) {
  5073. VULKAN_INTERNAL_CycleActiveTexture(
  5074. renderer,
  5075. commandBuffer,
  5076. textureContainer);
  5077. textureSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  5078. textureContainer,
  5079. layer,
  5080. level);
  5081. }
  5082. // always do barrier because of layout transitions
  5083. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  5084. renderer,
  5085. commandBuffer,
  5086. destinationUsageMode,
  5087. textureSubresource);
  5088. return textureSubresource;
  5089. }
  5090. static VkRenderPass VULKAN_INTERNAL_CreateRenderPass(
  5091. VulkanRenderer *renderer,
  5092. const SDL_GPUColorTargetInfo *colorTargetInfos,
  5093. Uint32 numColorTargets,
  5094. const SDL_GPUDepthStencilTargetInfo *depthStencilTargetInfo)
  5095. {
  5096. VkResult vulkanResult;
  5097. VkAttachmentDescription attachmentDescriptions[2 * MAX_COLOR_TARGET_BINDINGS + 1 /* depth */];
  5098. VkAttachmentReference colorAttachmentReferences[MAX_COLOR_TARGET_BINDINGS];
  5099. VkAttachmentReference resolveReferences[MAX_COLOR_TARGET_BINDINGS];
  5100. VkAttachmentReference depthStencilAttachmentReference;
  5101. VkRenderPassCreateInfo renderPassCreateInfo;
  5102. VkSubpassDescription subpass;
  5103. VkRenderPass renderPass;
  5104. Uint32 i;
  5105. Uint32 attachmentDescriptionCount = 0;
  5106. Uint32 colorAttachmentReferenceCount = 0;
  5107. Uint32 resolveReferenceCount = 0;
  5108. for (i = 0; i < numColorTargets; i += 1) {
  5109. VulkanTextureContainer *container = (VulkanTextureContainer *)colorTargetInfos[i].texture;
  5110. attachmentDescriptions[attachmentDescriptionCount].flags = 0;
  5111. attachmentDescriptions[attachmentDescriptionCount].format = SDLToVK_TextureFormat[container->header.info.format];
  5112. attachmentDescriptions[attachmentDescriptionCount].samples = SDLToVK_SampleCount[container->header.info.sample_count];
  5113. attachmentDescriptions[attachmentDescriptionCount].loadOp = SDLToVK_LoadOp[colorTargetInfos[i].load_op];
  5114. attachmentDescriptions[attachmentDescriptionCount].storeOp = SDLToVK_StoreOp[colorTargetInfos[i].store_op];
  5115. attachmentDescriptions[attachmentDescriptionCount].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  5116. attachmentDescriptions[attachmentDescriptionCount].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  5117. attachmentDescriptions[attachmentDescriptionCount].initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5118. attachmentDescriptions[attachmentDescriptionCount].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5119. colorAttachmentReferences[colorAttachmentReferenceCount].attachment = attachmentDescriptionCount;
  5120. colorAttachmentReferences[colorAttachmentReferenceCount].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5121. attachmentDescriptionCount += 1;
  5122. if (colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE || colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE_AND_STORE) {
  5123. VulkanTextureContainer *resolveContainer = (VulkanTextureContainer *)colorTargetInfos[i].resolve_texture;
  5124. attachmentDescriptions[attachmentDescriptionCount].flags = 0;
  5125. attachmentDescriptions[attachmentDescriptionCount].format = SDLToVK_TextureFormat[resolveContainer->header.info.format];
  5126. attachmentDescriptions[attachmentDescriptionCount].samples = SDLToVK_SampleCount[resolveContainer->header.info.sample_count];
  5127. attachmentDescriptions[attachmentDescriptionCount].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; // The texture will be overwritten anyway
  5128. attachmentDescriptions[attachmentDescriptionCount].storeOp = VK_ATTACHMENT_STORE_OP_STORE; // Always store the resolve texture
  5129. attachmentDescriptions[attachmentDescriptionCount].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  5130. attachmentDescriptions[attachmentDescriptionCount].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  5131. attachmentDescriptions[attachmentDescriptionCount].initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5132. attachmentDescriptions[attachmentDescriptionCount].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5133. resolveReferences[colorAttachmentReferenceCount].attachment = attachmentDescriptionCount;
  5134. resolveReferences[colorAttachmentReferenceCount].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5135. attachmentDescriptionCount += 1;
  5136. resolveReferenceCount += 1;
  5137. } else {
  5138. resolveReferences[colorAttachmentReferenceCount].attachment = VK_ATTACHMENT_UNUSED;
  5139. }
  5140. colorAttachmentReferenceCount += 1;
  5141. }
  5142. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  5143. subpass.flags = 0;
  5144. subpass.inputAttachmentCount = 0;
  5145. subpass.pInputAttachments = NULL;
  5146. subpass.colorAttachmentCount = numColorTargets;
  5147. subpass.pColorAttachments = colorAttachmentReferences;
  5148. subpass.preserveAttachmentCount = 0;
  5149. subpass.pPreserveAttachments = NULL;
  5150. if (depthStencilTargetInfo == NULL) {
  5151. subpass.pDepthStencilAttachment = NULL;
  5152. } else {
  5153. VulkanTextureContainer *container = (VulkanTextureContainer *)depthStencilTargetInfo->texture;
  5154. attachmentDescriptions[attachmentDescriptionCount].flags = 0;
  5155. attachmentDescriptions[attachmentDescriptionCount].format = SDLToVK_TextureFormat[container->header.info.format];
  5156. attachmentDescriptions[attachmentDescriptionCount].samples = SDLToVK_SampleCount[container->header.info.sample_count];
  5157. attachmentDescriptions[attachmentDescriptionCount].loadOp = SDLToVK_LoadOp[depthStencilTargetInfo->load_op];
  5158. attachmentDescriptions[attachmentDescriptionCount].storeOp = SDLToVK_StoreOp[depthStencilTargetInfo->store_op];
  5159. attachmentDescriptions[attachmentDescriptionCount].stencilLoadOp = SDLToVK_LoadOp[depthStencilTargetInfo->stencil_load_op];
  5160. attachmentDescriptions[attachmentDescriptionCount].stencilStoreOp = SDLToVK_StoreOp[depthStencilTargetInfo->stencil_store_op];
  5161. attachmentDescriptions[attachmentDescriptionCount].initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  5162. attachmentDescriptions[attachmentDescriptionCount].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  5163. depthStencilAttachmentReference.attachment = attachmentDescriptionCount;
  5164. depthStencilAttachmentReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  5165. subpass.pDepthStencilAttachment = &depthStencilAttachmentReference;
  5166. attachmentDescriptionCount += 1;
  5167. }
  5168. if (resolveReferenceCount > 0) {
  5169. subpass.pResolveAttachments = resolveReferences;
  5170. } else {
  5171. subpass.pResolveAttachments = NULL;
  5172. }
  5173. renderPassCreateInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  5174. renderPassCreateInfo.pNext = NULL;
  5175. renderPassCreateInfo.flags = 0;
  5176. renderPassCreateInfo.pAttachments = attachmentDescriptions;
  5177. renderPassCreateInfo.attachmentCount = attachmentDescriptionCount;
  5178. renderPassCreateInfo.subpassCount = 1;
  5179. renderPassCreateInfo.pSubpasses = &subpass;
  5180. renderPassCreateInfo.dependencyCount = 0;
  5181. renderPassCreateInfo.pDependencies = NULL;
  5182. vulkanResult = renderer->vkCreateRenderPass(
  5183. renderer->logicalDevice,
  5184. &renderPassCreateInfo,
  5185. NULL,
  5186. &renderPass);
  5187. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateRenderPass, VK_NULL_HANDLE);
  5188. return renderPass;
  5189. }
  5190. static VkRenderPass VULKAN_INTERNAL_CreateTransientRenderPass(
  5191. VulkanRenderer *renderer,
  5192. SDL_GPUGraphicsPipelineTargetInfo targetInfo,
  5193. VkSampleCountFlagBits sampleCount)
  5194. {
  5195. VkAttachmentDescription attachmentDescriptions[MAX_COLOR_TARGET_BINDINGS + 1 /* depth */];
  5196. VkAttachmentReference colorAttachmentReferences[MAX_COLOR_TARGET_BINDINGS];
  5197. VkAttachmentReference depthStencilAttachmentReference;
  5198. SDL_GPUColorTargetDescription attachmentDescription;
  5199. VkSubpassDescription subpass;
  5200. VkRenderPassCreateInfo renderPassCreateInfo;
  5201. VkRenderPass renderPass;
  5202. VkResult result;
  5203. Uint32 attachmentDescriptionCount = 0;
  5204. Uint32 colorAttachmentReferenceCount = 0;
  5205. Uint32 i;
  5206. for (i = 0; i < targetInfo.num_color_targets; i += 1) {
  5207. attachmentDescription = targetInfo.color_target_descriptions[i];
  5208. attachmentDescriptions[attachmentDescriptionCount].flags = 0;
  5209. attachmentDescriptions[attachmentDescriptionCount].format = SDLToVK_TextureFormat[attachmentDescription.format];
  5210. attachmentDescriptions[attachmentDescriptionCount].samples = sampleCount;
  5211. attachmentDescriptions[attachmentDescriptionCount].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  5212. attachmentDescriptions[attachmentDescriptionCount].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  5213. attachmentDescriptions[attachmentDescriptionCount].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  5214. attachmentDescriptions[attachmentDescriptionCount].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  5215. attachmentDescriptions[attachmentDescriptionCount].initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5216. attachmentDescriptions[attachmentDescriptionCount].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5217. colorAttachmentReferences[colorAttachmentReferenceCount].attachment = attachmentDescriptionCount;
  5218. colorAttachmentReferences[colorAttachmentReferenceCount].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5219. attachmentDescriptionCount += 1;
  5220. colorAttachmentReferenceCount += 1;
  5221. }
  5222. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  5223. subpass.flags = 0;
  5224. subpass.inputAttachmentCount = 0;
  5225. subpass.pInputAttachments = NULL;
  5226. subpass.colorAttachmentCount = targetInfo.num_color_targets;
  5227. subpass.pColorAttachments = colorAttachmentReferences;
  5228. subpass.preserveAttachmentCount = 0;
  5229. subpass.pPreserveAttachments = NULL;
  5230. if (targetInfo.has_depth_stencil_target) {
  5231. attachmentDescriptions[attachmentDescriptionCount].flags = 0;
  5232. attachmentDescriptions[attachmentDescriptionCount].format = SDLToVK_TextureFormat[targetInfo.depth_stencil_format];
  5233. attachmentDescriptions[attachmentDescriptionCount].samples = sampleCount;
  5234. attachmentDescriptions[attachmentDescriptionCount].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  5235. attachmentDescriptions[attachmentDescriptionCount].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  5236. attachmentDescriptions[attachmentDescriptionCount].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  5237. attachmentDescriptions[attachmentDescriptionCount].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  5238. attachmentDescriptions[attachmentDescriptionCount].initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  5239. attachmentDescriptions[attachmentDescriptionCount].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  5240. depthStencilAttachmentReference.attachment = attachmentDescriptionCount;
  5241. depthStencilAttachmentReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  5242. subpass.pDepthStencilAttachment = &depthStencilAttachmentReference;
  5243. attachmentDescriptionCount += 1;
  5244. } else {
  5245. subpass.pDepthStencilAttachment = NULL;
  5246. }
  5247. // Resolve attachments aren't needed for transient passes
  5248. subpass.pResolveAttachments = NULL;
  5249. renderPassCreateInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  5250. renderPassCreateInfo.pNext = NULL;
  5251. renderPassCreateInfo.flags = 0;
  5252. renderPassCreateInfo.pAttachments = attachmentDescriptions;
  5253. renderPassCreateInfo.attachmentCount = attachmentDescriptionCount;
  5254. renderPassCreateInfo.subpassCount = 1;
  5255. renderPassCreateInfo.pSubpasses = &subpass;
  5256. renderPassCreateInfo.dependencyCount = 0;
  5257. renderPassCreateInfo.pDependencies = NULL;
  5258. result = renderer->vkCreateRenderPass(
  5259. renderer->logicalDevice,
  5260. &renderPassCreateInfo,
  5261. NULL,
  5262. &renderPass);
  5263. CHECK_VULKAN_ERROR_AND_RETURN(result, vkCreateRenderPass, VK_NULL_HANDLE);
  5264. return renderPass;
  5265. }
  5266. static SDL_GPUGraphicsPipeline *VULKAN_CreateGraphicsPipeline(
  5267. SDL_GPURenderer *driverData,
  5268. const SDL_GPUGraphicsPipelineCreateInfo *createinfo)
  5269. {
  5270. VkResult vulkanResult;
  5271. Uint32 i;
  5272. VulkanGraphicsPipeline *graphicsPipeline = (VulkanGraphicsPipeline *)SDL_malloc(sizeof(VulkanGraphicsPipeline));
  5273. VkGraphicsPipelineCreateInfo vkPipelineCreateInfo;
  5274. VkPipelineShaderStageCreateInfo shaderStageCreateInfos[2];
  5275. VkPipelineVertexInputStateCreateInfo vertexInputStateCreateInfo;
  5276. VkVertexInputBindingDescription *vertexInputBindingDescriptions = SDL_stack_alloc(VkVertexInputBindingDescription, createinfo->vertex_input_state.num_vertex_buffers);
  5277. VkVertexInputAttributeDescription *vertexInputAttributeDescriptions = SDL_stack_alloc(VkVertexInputAttributeDescription, createinfo->vertex_input_state.num_vertex_attributes);
  5278. VkPipelineInputAssemblyStateCreateInfo inputAssemblyStateCreateInfo;
  5279. VkPipelineViewportStateCreateInfo viewportStateCreateInfo;
  5280. VkPipelineRasterizationStateCreateInfo rasterizationStateCreateInfo;
  5281. VkPipelineMultisampleStateCreateInfo multisampleStateCreateInfo;
  5282. VkPipelineDepthStencilStateCreateInfo depthStencilStateCreateInfo;
  5283. VkStencilOpState frontStencilState;
  5284. VkStencilOpState backStencilState;
  5285. VkPipelineColorBlendStateCreateInfo colorBlendStateCreateInfo;
  5286. VkPipelineColorBlendAttachmentState *colorBlendAttachmentStates = SDL_stack_alloc(
  5287. VkPipelineColorBlendAttachmentState,
  5288. createinfo->target_info.num_color_targets);
  5289. static const VkDynamicState dynamicStates[] = {
  5290. VK_DYNAMIC_STATE_VIEWPORT,
  5291. VK_DYNAMIC_STATE_SCISSOR,
  5292. VK_DYNAMIC_STATE_BLEND_CONSTANTS,
  5293. VK_DYNAMIC_STATE_STENCIL_REFERENCE
  5294. };
  5295. VkPipelineDynamicStateCreateInfo dynamicStateCreateInfo;
  5296. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5297. // Create a "compatible" render pass
  5298. VkRenderPass transientRenderPass = VULKAN_INTERNAL_CreateTransientRenderPass(
  5299. renderer,
  5300. createinfo->target_info,
  5301. SDLToVK_SampleCount[createinfo->multisample_state.sample_count]);
  5302. // Dynamic state
  5303. dynamicStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
  5304. dynamicStateCreateInfo.pNext = NULL;
  5305. dynamicStateCreateInfo.flags = 0;
  5306. dynamicStateCreateInfo.dynamicStateCount = SDL_arraysize(dynamicStates);
  5307. dynamicStateCreateInfo.pDynamicStates = dynamicStates;
  5308. // Shader stages
  5309. graphicsPipeline->vertexShader = (VulkanShader *)createinfo->vertex_shader;
  5310. SDL_AtomicIncRef(&graphicsPipeline->vertexShader->referenceCount);
  5311. shaderStageCreateInfos[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  5312. shaderStageCreateInfos[0].pNext = NULL;
  5313. shaderStageCreateInfos[0].flags = 0;
  5314. shaderStageCreateInfos[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
  5315. shaderStageCreateInfos[0].module = graphicsPipeline->vertexShader->shaderModule;
  5316. shaderStageCreateInfos[0].pName = graphicsPipeline->vertexShader->entrypointName;
  5317. shaderStageCreateInfos[0].pSpecializationInfo = NULL;
  5318. graphicsPipeline->fragmentShader = (VulkanShader *)createinfo->fragment_shader;
  5319. SDL_AtomicIncRef(&graphicsPipeline->fragmentShader->referenceCount);
  5320. shaderStageCreateInfos[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  5321. shaderStageCreateInfos[1].pNext = NULL;
  5322. shaderStageCreateInfos[1].flags = 0;
  5323. shaderStageCreateInfos[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
  5324. shaderStageCreateInfos[1].module = graphicsPipeline->fragmentShader->shaderModule;
  5325. shaderStageCreateInfos[1].pName = graphicsPipeline->fragmentShader->entrypointName;
  5326. shaderStageCreateInfos[1].pSpecializationInfo = NULL;
  5327. if (renderer->debugMode) {
  5328. if (graphicsPipeline->vertexShader->stage != SDL_GPU_SHADERSTAGE_VERTEX) {
  5329. SDL_assert_release(!"CreateGraphicsPipeline was passed a fragment shader for the vertex stage");
  5330. }
  5331. if (graphicsPipeline->fragmentShader->stage != SDL_GPU_SHADERSTAGE_FRAGMENT) {
  5332. SDL_assert_release(!"CreateGraphicsPipeline was passed a vertex shader for the fragment stage");
  5333. }
  5334. }
  5335. // Vertex input
  5336. for (i = 0; i < createinfo->vertex_input_state.num_vertex_buffers; i += 1) {
  5337. vertexInputBindingDescriptions[i].binding = createinfo->vertex_input_state.vertex_buffer_descriptions[i].slot;
  5338. vertexInputBindingDescriptions[i].inputRate = SDLToVK_VertexInputRate[createinfo->vertex_input_state.vertex_buffer_descriptions[i].input_rate];
  5339. vertexInputBindingDescriptions[i].stride = createinfo->vertex_input_state.vertex_buffer_descriptions[i].pitch;
  5340. }
  5341. for (i = 0; i < createinfo->vertex_input_state.num_vertex_attributes; i += 1) {
  5342. vertexInputAttributeDescriptions[i].binding = createinfo->vertex_input_state.vertex_attributes[i].buffer_slot;
  5343. vertexInputAttributeDescriptions[i].format = SDLToVK_VertexFormat[createinfo->vertex_input_state.vertex_attributes[i].format];
  5344. vertexInputAttributeDescriptions[i].location = createinfo->vertex_input_state.vertex_attributes[i].location;
  5345. vertexInputAttributeDescriptions[i].offset = createinfo->vertex_input_state.vertex_attributes[i].offset;
  5346. }
  5347. vertexInputStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  5348. vertexInputStateCreateInfo.pNext = NULL;
  5349. vertexInputStateCreateInfo.flags = 0;
  5350. vertexInputStateCreateInfo.vertexBindingDescriptionCount = createinfo->vertex_input_state.num_vertex_buffers;
  5351. vertexInputStateCreateInfo.pVertexBindingDescriptions = vertexInputBindingDescriptions;
  5352. vertexInputStateCreateInfo.vertexAttributeDescriptionCount = createinfo->vertex_input_state.num_vertex_attributes;
  5353. vertexInputStateCreateInfo.pVertexAttributeDescriptions = vertexInputAttributeDescriptions;
  5354. // Topology
  5355. inputAssemblyStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  5356. inputAssemblyStateCreateInfo.pNext = NULL;
  5357. inputAssemblyStateCreateInfo.flags = 0;
  5358. inputAssemblyStateCreateInfo.primitiveRestartEnable = VK_FALSE;
  5359. inputAssemblyStateCreateInfo.topology = SDLToVK_PrimitiveType[createinfo->primitive_type];
  5360. graphicsPipeline->primitiveType = createinfo->primitive_type;
  5361. // Viewport
  5362. // NOTE: viewport and scissor are dynamic, and must be set using the command buffer
  5363. viewportStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  5364. viewportStateCreateInfo.pNext = NULL;
  5365. viewportStateCreateInfo.flags = 0;
  5366. viewportStateCreateInfo.viewportCount = 1;
  5367. viewportStateCreateInfo.pViewports = NULL;
  5368. viewportStateCreateInfo.scissorCount = 1;
  5369. viewportStateCreateInfo.pScissors = NULL;
  5370. // Rasterization
  5371. rasterizationStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  5372. rasterizationStateCreateInfo.pNext = NULL;
  5373. rasterizationStateCreateInfo.flags = 0;
  5374. rasterizationStateCreateInfo.depthClampEnable = !createinfo->rasterizer_state.enable_depth_clip;
  5375. rasterizationStateCreateInfo.rasterizerDiscardEnable = VK_FALSE;
  5376. rasterizationStateCreateInfo.polygonMode = SDLToVK_PolygonMode(
  5377. renderer,
  5378. createinfo->rasterizer_state.fill_mode);
  5379. rasterizationStateCreateInfo.cullMode = SDLToVK_CullMode[createinfo->rasterizer_state.cull_mode];
  5380. rasterizationStateCreateInfo.frontFace = SDLToVK_FrontFace[createinfo->rasterizer_state.front_face];
  5381. rasterizationStateCreateInfo.depthBiasEnable =
  5382. createinfo->rasterizer_state.enable_depth_bias;
  5383. rasterizationStateCreateInfo.depthBiasConstantFactor =
  5384. createinfo->rasterizer_state.depth_bias_constant_factor;
  5385. rasterizationStateCreateInfo.depthBiasClamp =
  5386. createinfo->rasterizer_state.depth_bias_clamp;
  5387. rasterizationStateCreateInfo.depthBiasSlopeFactor =
  5388. createinfo->rasterizer_state.depth_bias_slope_factor;
  5389. rasterizationStateCreateInfo.lineWidth = 1.0f;
  5390. // Multisample
  5391. Uint32 sampleMask = 0xFFFFFFFF;
  5392. multisampleStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  5393. multisampleStateCreateInfo.pNext = NULL;
  5394. multisampleStateCreateInfo.flags = 0;
  5395. multisampleStateCreateInfo.rasterizationSamples = SDLToVK_SampleCount[createinfo->multisample_state.sample_count];
  5396. multisampleStateCreateInfo.sampleShadingEnable = VK_FALSE;
  5397. multisampleStateCreateInfo.minSampleShading = 1.0f;
  5398. multisampleStateCreateInfo.pSampleMask = &sampleMask;
  5399. multisampleStateCreateInfo.alphaToCoverageEnable = createinfo->multisample_state.enable_alpha_to_coverage;
  5400. multisampleStateCreateInfo.alphaToOneEnable = VK_FALSE;
  5401. // Depth Stencil State
  5402. frontStencilState.failOp = SDLToVK_StencilOp[createinfo->depth_stencil_state.front_stencil_state.fail_op];
  5403. frontStencilState.passOp = SDLToVK_StencilOp[createinfo->depth_stencil_state.front_stencil_state.pass_op];
  5404. frontStencilState.depthFailOp = SDLToVK_StencilOp[createinfo->depth_stencil_state.front_stencil_state.depth_fail_op];
  5405. frontStencilState.compareOp = SDLToVK_CompareOp[createinfo->depth_stencil_state.front_stencil_state.compare_op];
  5406. frontStencilState.compareMask =
  5407. createinfo->depth_stencil_state.compare_mask;
  5408. frontStencilState.writeMask =
  5409. createinfo->depth_stencil_state.write_mask;
  5410. frontStencilState.reference = 0;
  5411. backStencilState.failOp = SDLToVK_StencilOp[createinfo->depth_stencil_state.back_stencil_state.fail_op];
  5412. backStencilState.passOp = SDLToVK_StencilOp[createinfo->depth_stencil_state.back_stencil_state.pass_op];
  5413. backStencilState.depthFailOp = SDLToVK_StencilOp[createinfo->depth_stencil_state.back_stencil_state.depth_fail_op];
  5414. backStencilState.compareOp = SDLToVK_CompareOp[createinfo->depth_stencil_state.back_stencil_state.compare_op];
  5415. backStencilState.compareMask =
  5416. createinfo->depth_stencil_state.compare_mask;
  5417. backStencilState.writeMask =
  5418. createinfo->depth_stencil_state.write_mask;
  5419. backStencilState.reference = 0;
  5420. depthStencilStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
  5421. depthStencilStateCreateInfo.pNext = NULL;
  5422. depthStencilStateCreateInfo.flags = 0;
  5423. depthStencilStateCreateInfo.depthTestEnable =
  5424. createinfo->depth_stencil_state.enable_depth_test;
  5425. depthStencilStateCreateInfo.depthWriteEnable =
  5426. createinfo->depth_stencil_state.enable_depth_write;
  5427. depthStencilStateCreateInfo.depthCompareOp = SDLToVK_CompareOp[createinfo->depth_stencil_state.compare_op];
  5428. depthStencilStateCreateInfo.depthBoundsTestEnable = VK_FALSE;
  5429. depthStencilStateCreateInfo.stencilTestEnable =
  5430. createinfo->depth_stencil_state.enable_stencil_test;
  5431. depthStencilStateCreateInfo.front = frontStencilState;
  5432. depthStencilStateCreateInfo.back = backStencilState;
  5433. depthStencilStateCreateInfo.minDepthBounds = 0; // unused
  5434. depthStencilStateCreateInfo.maxDepthBounds = 0; // unused
  5435. // Color Blend
  5436. for (i = 0; i < createinfo->target_info.num_color_targets; i += 1) {
  5437. SDL_GPUColorTargetBlendState blendState = createinfo->target_info.color_target_descriptions[i].blend_state;
  5438. SDL_GPUColorComponentFlags colorWriteMask = blendState.enable_color_write_mask ?
  5439. blendState.color_write_mask :
  5440. 0xF;
  5441. colorBlendAttachmentStates[i].blendEnable =
  5442. blendState.enable_blend;
  5443. colorBlendAttachmentStates[i].srcColorBlendFactor = SDLToVK_BlendFactor[blendState.src_color_blendfactor];
  5444. colorBlendAttachmentStates[i].dstColorBlendFactor = SDLToVK_BlendFactor[blendState.dst_color_blendfactor];
  5445. colorBlendAttachmentStates[i].colorBlendOp = SDLToVK_BlendOp[blendState.color_blend_op];
  5446. colorBlendAttachmentStates[i].srcAlphaBlendFactor = SDLToVK_BlendFactor[blendState.src_alpha_blendfactor];
  5447. colorBlendAttachmentStates[i].dstAlphaBlendFactor = SDLToVK_BlendFactor[blendState.dst_alpha_blendfactor];
  5448. colorBlendAttachmentStates[i].alphaBlendOp = SDLToVK_BlendOp[blendState.alpha_blend_op];
  5449. colorBlendAttachmentStates[i].colorWriteMask =
  5450. colorWriteMask;
  5451. }
  5452. colorBlendStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  5453. colorBlendStateCreateInfo.pNext = NULL;
  5454. colorBlendStateCreateInfo.flags = 0;
  5455. colorBlendStateCreateInfo.attachmentCount =
  5456. createinfo->target_info.num_color_targets;
  5457. colorBlendStateCreateInfo.pAttachments =
  5458. colorBlendAttachmentStates;
  5459. colorBlendStateCreateInfo.blendConstants[0] = 1.0f;
  5460. colorBlendStateCreateInfo.blendConstants[1] = 1.0f;
  5461. colorBlendStateCreateInfo.blendConstants[2] = 1.0f;
  5462. colorBlendStateCreateInfo.blendConstants[3] = 1.0f;
  5463. // We don't support LogicOp, so this is easy.
  5464. colorBlendStateCreateInfo.logicOpEnable = VK_FALSE;
  5465. colorBlendStateCreateInfo.logicOp = 0;
  5466. // Pipeline Layout
  5467. graphicsPipeline->resourceLayout =
  5468. VULKAN_INTERNAL_FetchGraphicsPipelineResourceLayout(
  5469. renderer,
  5470. graphicsPipeline->vertexShader,
  5471. graphicsPipeline->fragmentShader);
  5472. if (graphicsPipeline->resourceLayout == NULL) {
  5473. SDL_stack_free(vertexInputBindingDescriptions);
  5474. SDL_stack_free(vertexInputAttributeDescriptions);
  5475. SDL_stack_free(colorBlendAttachmentStates);
  5476. SDL_free(graphicsPipeline);
  5477. SET_STRING_ERROR_AND_RETURN("Failed to initialize pipeline resource layout!", NULL);
  5478. }
  5479. // Pipeline
  5480. vkPipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  5481. vkPipelineCreateInfo.pNext = NULL;
  5482. vkPipelineCreateInfo.flags = 0;
  5483. vkPipelineCreateInfo.stageCount = 2;
  5484. vkPipelineCreateInfo.pStages = shaderStageCreateInfos;
  5485. vkPipelineCreateInfo.pVertexInputState = &vertexInputStateCreateInfo;
  5486. vkPipelineCreateInfo.pInputAssemblyState = &inputAssemblyStateCreateInfo;
  5487. vkPipelineCreateInfo.pTessellationState = VK_NULL_HANDLE;
  5488. vkPipelineCreateInfo.pViewportState = &viewportStateCreateInfo;
  5489. vkPipelineCreateInfo.pRasterizationState = &rasterizationStateCreateInfo;
  5490. vkPipelineCreateInfo.pMultisampleState = &multisampleStateCreateInfo;
  5491. vkPipelineCreateInfo.pDepthStencilState = &depthStencilStateCreateInfo;
  5492. vkPipelineCreateInfo.pColorBlendState = &colorBlendStateCreateInfo;
  5493. vkPipelineCreateInfo.pDynamicState = &dynamicStateCreateInfo;
  5494. vkPipelineCreateInfo.layout = graphicsPipeline->resourceLayout->pipelineLayout;
  5495. vkPipelineCreateInfo.renderPass = transientRenderPass;
  5496. vkPipelineCreateInfo.subpass = 0;
  5497. vkPipelineCreateInfo.basePipelineHandle = VK_NULL_HANDLE;
  5498. vkPipelineCreateInfo.basePipelineIndex = 0;
  5499. // TODO: enable pipeline caching
  5500. vulkanResult = renderer->vkCreateGraphicsPipelines(
  5501. renderer->logicalDevice,
  5502. VK_NULL_HANDLE,
  5503. 1,
  5504. &vkPipelineCreateInfo,
  5505. NULL,
  5506. &graphicsPipeline->pipeline);
  5507. SDL_stack_free(vertexInputBindingDescriptions);
  5508. SDL_stack_free(vertexInputAttributeDescriptions);
  5509. SDL_stack_free(colorBlendAttachmentStates);
  5510. renderer->vkDestroyRenderPass(
  5511. renderer->logicalDevice,
  5512. transientRenderPass,
  5513. NULL);
  5514. if (vulkanResult != VK_SUCCESS) {
  5515. SDL_free(graphicsPipeline);
  5516. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateGraphicsPipelines, NULL);
  5517. }
  5518. SDL_SetAtomicInt(&graphicsPipeline->referenceCount, 0);
  5519. if (renderer->debugMode && renderer->supportsDebugUtils && SDL_HasProperty(createinfo->props, SDL_PROP_GPU_GRAPHICSPIPELINE_CREATE_NAME_STRING)) {
  5520. VkDebugUtilsObjectNameInfoEXT nameInfo;
  5521. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  5522. nameInfo.pNext = NULL;
  5523. nameInfo.pObjectName = SDL_GetStringProperty(createinfo->props, SDL_PROP_GPU_GRAPHICSPIPELINE_CREATE_NAME_STRING, NULL);
  5524. nameInfo.objectType = VK_OBJECT_TYPE_PIPELINE;
  5525. nameInfo.objectHandle = (uint64_t)graphicsPipeline->pipeline;
  5526. renderer->vkSetDebugUtilsObjectNameEXT(
  5527. renderer->logicalDevice,
  5528. &nameInfo);
  5529. }
  5530. // Put this data in the pipeline we can do validation in gpu.c
  5531. graphicsPipeline->header.num_vertex_samplers = graphicsPipeline->resourceLayout->vertexSamplerCount;
  5532. graphicsPipeline->header.num_vertex_storage_buffers = graphicsPipeline->resourceLayout->vertexStorageBufferCount;
  5533. graphicsPipeline->header.num_vertex_storage_textures = graphicsPipeline->resourceLayout->vertexStorageTextureCount;
  5534. graphicsPipeline->header.num_vertex_uniform_buffers = graphicsPipeline->resourceLayout->vertexUniformBufferCount;
  5535. graphicsPipeline->header.num_fragment_samplers = graphicsPipeline->resourceLayout->fragmentSamplerCount;
  5536. graphicsPipeline->header.num_fragment_storage_buffers = graphicsPipeline->resourceLayout->fragmentStorageBufferCount;
  5537. graphicsPipeline->header.num_fragment_storage_textures = graphicsPipeline->resourceLayout->fragmentStorageTextureCount;
  5538. graphicsPipeline->header.num_fragment_uniform_buffers = graphicsPipeline->resourceLayout->fragmentUniformBufferCount;
  5539. return (SDL_GPUGraphicsPipeline *)graphicsPipeline;
  5540. }
  5541. static bool VULKAN_INTERNAL_IsValidShaderBytecode(
  5542. const Uint8 *code,
  5543. size_t codeSize)
  5544. {
  5545. // SPIR-V bytecode has a 4 byte header containing 0x07230203. SPIR-V is
  5546. // defined as a stream of words and not a stream of bytes so both byte
  5547. // orders need to be considered.
  5548. //
  5549. // FIXME: It is uncertain if drivers are able to load both byte orders. If
  5550. // needed we may need to do an optional swizzle internally so apps can
  5551. // continue to treat shader code as an opaque blob.
  5552. if (codeSize < 4 || code == NULL) {
  5553. return false;
  5554. }
  5555. const Uint32 magic = 0x07230203;
  5556. const Uint32 magicInv = 0x03022307;
  5557. return SDL_memcmp(code, &magic, 4) == 0 || SDL_memcmp(code, &magicInv, 4) == 0;
  5558. }
  5559. static SDL_GPUComputePipeline *VULKAN_CreateComputePipeline(
  5560. SDL_GPURenderer *driverData,
  5561. const SDL_GPUComputePipelineCreateInfo *createinfo)
  5562. {
  5563. VkShaderModuleCreateInfo shaderModuleCreateInfo;
  5564. VkComputePipelineCreateInfo vkShaderCreateInfo;
  5565. VkPipelineShaderStageCreateInfo pipelineShaderStageCreateInfo;
  5566. VkResult vulkanResult;
  5567. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5568. VulkanComputePipeline *vulkanComputePipeline;
  5569. if (createinfo->format != SDL_GPU_SHADERFORMAT_SPIRV) {
  5570. SET_STRING_ERROR_AND_RETURN("Incompatible shader format for Vulkan!", NULL);
  5571. }
  5572. if (!VULKAN_INTERNAL_IsValidShaderBytecode(createinfo->code, createinfo->code_size)) {
  5573. SET_STRING_ERROR_AND_RETURN("The provided shader code is not valid SPIR-V!", NULL);
  5574. }
  5575. vulkanComputePipeline = SDL_malloc(sizeof(VulkanComputePipeline));
  5576. shaderModuleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  5577. shaderModuleCreateInfo.pNext = NULL;
  5578. shaderModuleCreateInfo.flags = 0;
  5579. shaderModuleCreateInfo.codeSize = createinfo->code_size;
  5580. shaderModuleCreateInfo.pCode = (Uint32 *)createinfo->code;
  5581. vulkanResult = renderer->vkCreateShaderModule(
  5582. renderer->logicalDevice,
  5583. &shaderModuleCreateInfo,
  5584. NULL,
  5585. &vulkanComputePipeline->shaderModule);
  5586. if (vulkanResult != VK_SUCCESS) {
  5587. SDL_free(vulkanComputePipeline);
  5588. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateShaderModule, NULL);
  5589. }
  5590. pipelineShaderStageCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  5591. pipelineShaderStageCreateInfo.pNext = NULL;
  5592. pipelineShaderStageCreateInfo.flags = 0;
  5593. pipelineShaderStageCreateInfo.stage = VK_SHADER_STAGE_COMPUTE_BIT;
  5594. pipelineShaderStageCreateInfo.module = vulkanComputePipeline->shaderModule;
  5595. pipelineShaderStageCreateInfo.pName = createinfo->entrypoint;
  5596. pipelineShaderStageCreateInfo.pSpecializationInfo = NULL;
  5597. vulkanComputePipeline->resourceLayout = VULKAN_INTERNAL_FetchComputePipelineResourceLayout(
  5598. renderer,
  5599. createinfo);
  5600. if (vulkanComputePipeline->resourceLayout == NULL) {
  5601. renderer->vkDestroyShaderModule(
  5602. renderer->logicalDevice,
  5603. vulkanComputePipeline->shaderModule,
  5604. NULL);
  5605. SDL_free(vulkanComputePipeline);
  5606. return NULL;
  5607. }
  5608. vkShaderCreateInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
  5609. vkShaderCreateInfo.pNext = NULL;
  5610. vkShaderCreateInfo.flags = 0;
  5611. vkShaderCreateInfo.stage = pipelineShaderStageCreateInfo;
  5612. vkShaderCreateInfo.layout = vulkanComputePipeline->resourceLayout->pipelineLayout;
  5613. vkShaderCreateInfo.basePipelineHandle = (VkPipeline)VK_NULL_HANDLE;
  5614. vkShaderCreateInfo.basePipelineIndex = 0;
  5615. vulkanResult = renderer->vkCreateComputePipelines(
  5616. renderer->logicalDevice,
  5617. (VkPipelineCache)VK_NULL_HANDLE,
  5618. 1,
  5619. &vkShaderCreateInfo,
  5620. NULL,
  5621. &vulkanComputePipeline->pipeline);
  5622. if (vulkanResult != VK_SUCCESS) {
  5623. VULKAN_INTERNAL_DestroyComputePipeline(renderer, vulkanComputePipeline);
  5624. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateComputePipeline, NULL);
  5625. return NULL;
  5626. }
  5627. SDL_SetAtomicInt(&vulkanComputePipeline->referenceCount, 0);
  5628. if (renderer->debugMode && renderer->supportsDebugUtils && SDL_HasProperty(createinfo->props, SDL_PROP_GPU_COMPUTEPIPELINE_CREATE_NAME_STRING)) {
  5629. VkDebugUtilsObjectNameInfoEXT nameInfo;
  5630. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  5631. nameInfo.pNext = NULL;
  5632. nameInfo.pObjectName = SDL_GetStringProperty(createinfo->props, SDL_PROP_GPU_COMPUTEPIPELINE_CREATE_NAME_STRING, NULL);
  5633. nameInfo.objectType = VK_OBJECT_TYPE_PIPELINE;
  5634. nameInfo.objectHandle = (uint64_t)vulkanComputePipeline->pipeline;
  5635. renderer->vkSetDebugUtilsObjectNameEXT(
  5636. renderer->logicalDevice,
  5637. &nameInfo);
  5638. }
  5639. // Track these here for debug layer
  5640. vulkanComputePipeline->header.numSamplers = vulkanComputePipeline->resourceLayout->numSamplers;
  5641. vulkanComputePipeline->header.numReadonlyStorageTextures = vulkanComputePipeline->resourceLayout->numReadonlyStorageTextures;
  5642. vulkanComputePipeline->header.numReadonlyStorageBuffers = vulkanComputePipeline->resourceLayout->numReadonlyStorageBuffers;
  5643. vulkanComputePipeline->header.numReadWriteStorageTextures = vulkanComputePipeline->resourceLayout->numReadWriteStorageTextures;
  5644. vulkanComputePipeline->header.numReadWriteStorageBuffers = vulkanComputePipeline->resourceLayout->numReadWriteStorageBuffers;
  5645. vulkanComputePipeline->header.numUniformBuffers = vulkanComputePipeline->resourceLayout->numUniformBuffers;
  5646. return (SDL_GPUComputePipeline *)vulkanComputePipeline;
  5647. }
  5648. static SDL_GPUSampler *VULKAN_CreateSampler(
  5649. SDL_GPURenderer *driverData,
  5650. const SDL_GPUSamplerCreateInfo *createinfo)
  5651. {
  5652. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5653. VulkanSampler *vulkanSampler = SDL_malloc(sizeof(VulkanSampler));
  5654. VkResult vulkanResult;
  5655. VkSamplerCreateInfo vkSamplerCreateInfo;
  5656. vkSamplerCreateInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  5657. vkSamplerCreateInfo.pNext = NULL;
  5658. vkSamplerCreateInfo.flags = 0;
  5659. vkSamplerCreateInfo.magFilter = SDLToVK_Filter[createinfo->mag_filter];
  5660. vkSamplerCreateInfo.minFilter = SDLToVK_Filter[createinfo->min_filter];
  5661. vkSamplerCreateInfo.mipmapMode = SDLToVK_SamplerMipmapMode[createinfo->mipmap_mode];
  5662. vkSamplerCreateInfo.addressModeU = SDLToVK_SamplerAddressMode[createinfo->address_mode_u];
  5663. vkSamplerCreateInfo.addressModeV = SDLToVK_SamplerAddressMode[createinfo->address_mode_v];
  5664. vkSamplerCreateInfo.addressModeW = SDLToVK_SamplerAddressMode[createinfo->address_mode_w];
  5665. vkSamplerCreateInfo.mipLodBias = createinfo->mip_lod_bias;
  5666. vkSamplerCreateInfo.anisotropyEnable = createinfo->enable_anisotropy;
  5667. vkSamplerCreateInfo.maxAnisotropy = createinfo->max_anisotropy;
  5668. vkSamplerCreateInfo.compareEnable = createinfo->enable_compare;
  5669. vkSamplerCreateInfo.compareOp = SDLToVK_CompareOp[createinfo->compare_op];
  5670. vkSamplerCreateInfo.minLod = createinfo->min_lod;
  5671. vkSamplerCreateInfo.maxLod = createinfo->max_lod;
  5672. vkSamplerCreateInfo.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; // arbitrary, unused
  5673. vkSamplerCreateInfo.unnormalizedCoordinates = VK_FALSE;
  5674. vulkanResult = renderer->vkCreateSampler(
  5675. renderer->logicalDevice,
  5676. &vkSamplerCreateInfo,
  5677. NULL,
  5678. &vulkanSampler->sampler);
  5679. if (vulkanResult != VK_SUCCESS) {
  5680. SDL_free(vulkanSampler);
  5681. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateSampler, NULL);
  5682. }
  5683. SDL_SetAtomicInt(&vulkanSampler->referenceCount, 0);
  5684. if (renderer->debugMode && renderer->supportsDebugUtils && SDL_HasProperty(createinfo->props, SDL_PROP_GPU_SAMPLER_CREATE_NAME_STRING)) {
  5685. VkDebugUtilsObjectNameInfoEXT nameInfo;
  5686. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  5687. nameInfo.pNext = NULL;
  5688. nameInfo.pObjectName = SDL_GetStringProperty(createinfo->props, SDL_PROP_GPU_SAMPLER_CREATE_NAME_STRING, NULL);
  5689. nameInfo.objectType = VK_OBJECT_TYPE_SAMPLER;
  5690. nameInfo.objectHandle = (uint64_t)vulkanSampler->sampler;
  5691. renderer->vkSetDebugUtilsObjectNameEXT(
  5692. renderer->logicalDevice,
  5693. &nameInfo);
  5694. }
  5695. return (SDL_GPUSampler *)vulkanSampler;
  5696. }
  5697. static SDL_GPUShader *VULKAN_CreateShader(
  5698. SDL_GPURenderer *driverData,
  5699. const SDL_GPUShaderCreateInfo *createinfo)
  5700. {
  5701. VulkanShader *vulkanShader;
  5702. VkResult vulkanResult;
  5703. VkShaderModuleCreateInfo vkShaderModuleCreateInfo;
  5704. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5705. if (!VULKAN_INTERNAL_IsValidShaderBytecode(createinfo->code, createinfo->code_size)) {
  5706. SET_STRING_ERROR_AND_RETURN("The provided shader code is not valid SPIR-V!", NULL);
  5707. }
  5708. vulkanShader = SDL_malloc(sizeof(VulkanShader));
  5709. vkShaderModuleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  5710. vkShaderModuleCreateInfo.pNext = NULL;
  5711. vkShaderModuleCreateInfo.flags = 0;
  5712. vkShaderModuleCreateInfo.codeSize = createinfo->code_size;
  5713. vkShaderModuleCreateInfo.pCode = (Uint32 *)createinfo->code;
  5714. vulkanResult = renderer->vkCreateShaderModule(
  5715. renderer->logicalDevice,
  5716. &vkShaderModuleCreateInfo,
  5717. NULL,
  5718. &vulkanShader->shaderModule);
  5719. if (vulkanResult != VK_SUCCESS) {
  5720. SDL_free(vulkanShader);
  5721. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateShaderModule, NULL);
  5722. }
  5723. const char *entrypoint = createinfo->entrypoint;
  5724. if (!entrypoint) {
  5725. entrypoint = "main";
  5726. }
  5727. vulkanShader->entrypointName = SDL_strdup(entrypoint);
  5728. vulkanShader->stage = createinfo->stage;
  5729. vulkanShader->numSamplers = createinfo->num_samplers;
  5730. vulkanShader->numStorageTextures = createinfo->num_storage_textures;
  5731. vulkanShader->numStorageBuffers = createinfo->num_storage_buffers;
  5732. vulkanShader->numUniformBuffers = createinfo->num_uniform_buffers;
  5733. SDL_SetAtomicInt(&vulkanShader->referenceCount, 0);
  5734. if (renderer->debugMode && SDL_HasProperty(createinfo->props, SDL_PROP_GPU_SHADER_CREATE_NAME_STRING)) {
  5735. VkDebugUtilsObjectNameInfoEXT nameInfo;
  5736. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  5737. nameInfo.pNext = NULL;
  5738. nameInfo.pObjectName = SDL_GetStringProperty(createinfo->props, SDL_PROP_GPU_SHADER_CREATE_NAME_STRING, NULL);
  5739. nameInfo.objectType = VK_OBJECT_TYPE_SHADER_MODULE;
  5740. nameInfo.objectHandle = (uint64_t)vulkanShader->shaderModule;
  5741. renderer->vkSetDebugUtilsObjectNameEXT(
  5742. renderer->logicalDevice,
  5743. &nameInfo);
  5744. }
  5745. return (SDL_GPUShader *)vulkanShader;
  5746. }
  5747. static bool VULKAN_SupportsSampleCount(
  5748. SDL_GPURenderer *driverData,
  5749. SDL_GPUTextureFormat format,
  5750. SDL_GPUSampleCount sampleCount)
  5751. {
  5752. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5753. VkSampleCountFlags bits = IsDepthFormat(format) ? renderer->physicalDeviceProperties.properties.limits.framebufferDepthSampleCounts : renderer->physicalDeviceProperties.properties.limits.framebufferColorSampleCounts;
  5754. VkSampleCountFlagBits vkSampleCount = SDLToVK_SampleCount[sampleCount];
  5755. return !!(bits & vkSampleCount);
  5756. }
  5757. static SDL_GPUTexture *VULKAN_CreateTexture(
  5758. SDL_GPURenderer *driverData,
  5759. const SDL_GPUTextureCreateInfo *createinfo)
  5760. {
  5761. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5762. VulkanTexture *texture;
  5763. VulkanTextureContainer *container;
  5764. texture = VULKAN_INTERNAL_CreateTexture(
  5765. renderer,
  5766. true,
  5767. createinfo);
  5768. if (texture == NULL) {
  5769. return NULL;
  5770. }
  5771. container = SDL_malloc(sizeof(VulkanTextureContainer));
  5772. // Copy properties so we don't lose information when the client destroys them
  5773. container->header.info = *createinfo;
  5774. container->header.info.props = SDL_CreateProperties();
  5775. if (createinfo->props) {
  5776. SDL_CopyProperties(createinfo->props, container->header.info.props);
  5777. }
  5778. container->canBeCycled = true;
  5779. container->activeTexture = texture;
  5780. container->textureCapacity = 1;
  5781. container->textureCount = 1;
  5782. container->textures = SDL_malloc(
  5783. container->textureCapacity * sizeof(VulkanTexture *));
  5784. container->textures[0] = container->activeTexture;
  5785. container->debugName = NULL;
  5786. if (SDL_HasProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_NAME_STRING)) {
  5787. container->debugName = SDL_strdup(SDL_GetStringProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_NAME_STRING, NULL));
  5788. }
  5789. texture->container = container;
  5790. texture->containerIndex = 0;
  5791. return (SDL_GPUTexture *)container;
  5792. }
  5793. static SDL_GPUBuffer *VULKAN_CreateBuffer(
  5794. SDL_GPURenderer *driverData,
  5795. SDL_GPUBufferUsageFlags usageFlags,
  5796. Uint32 size,
  5797. const char *debugName)
  5798. {
  5799. return (SDL_GPUBuffer *)VULKAN_INTERNAL_CreateBufferContainer(
  5800. (VulkanRenderer *)driverData,
  5801. (VkDeviceSize)size,
  5802. usageFlags,
  5803. VULKAN_BUFFER_TYPE_GPU,
  5804. false,
  5805. debugName);
  5806. }
  5807. static VulkanUniformBuffer *VULKAN_INTERNAL_CreateUniformBuffer(
  5808. VulkanRenderer *renderer,
  5809. Uint32 size)
  5810. {
  5811. VulkanUniformBuffer *uniformBuffer = SDL_calloc(1, sizeof(VulkanUniformBuffer));
  5812. uniformBuffer->buffer = VULKAN_INTERNAL_CreateBuffer(
  5813. renderer,
  5814. (VkDeviceSize)size,
  5815. 0,
  5816. VULKAN_BUFFER_TYPE_UNIFORM,
  5817. false,
  5818. NULL);
  5819. uniformBuffer->drawOffset = 0;
  5820. uniformBuffer->writeOffset = 0;
  5821. uniformBuffer->buffer->uniformBufferForDefrag = uniformBuffer;
  5822. return uniformBuffer;
  5823. }
  5824. static SDL_GPUTransferBuffer *VULKAN_CreateTransferBuffer(
  5825. SDL_GPURenderer *driverData,
  5826. SDL_GPUTransferBufferUsage usage,
  5827. Uint32 size,
  5828. const char *debugName)
  5829. {
  5830. return (SDL_GPUTransferBuffer *)VULKAN_INTERNAL_CreateBufferContainer(
  5831. (VulkanRenderer *)driverData,
  5832. (VkDeviceSize)size,
  5833. 0,
  5834. VULKAN_BUFFER_TYPE_TRANSFER,
  5835. true, // Dedicated allocations preserve the data even if a defrag is triggered.
  5836. debugName);
  5837. }
  5838. static void VULKAN_INTERNAL_ReleaseTexture(
  5839. VulkanRenderer *renderer,
  5840. VulkanTexture *vulkanTexture)
  5841. {
  5842. if (vulkanTexture->markedForDestroy) {
  5843. return;
  5844. }
  5845. SDL_LockMutex(renderer->disposeLock);
  5846. EXPAND_ARRAY_IF_NEEDED(
  5847. renderer->texturesToDestroy,
  5848. VulkanTexture *,
  5849. renderer->texturesToDestroyCount + 1,
  5850. renderer->texturesToDestroyCapacity,
  5851. renderer->texturesToDestroyCapacity * 2);
  5852. renderer->texturesToDestroy[renderer->texturesToDestroyCount] = vulkanTexture;
  5853. renderer->texturesToDestroyCount += 1;
  5854. vulkanTexture->markedForDestroy = true;
  5855. SDL_UnlockMutex(renderer->disposeLock);
  5856. }
  5857. static void VULKAN_ReleaseTexture(
  5858. SDL_GPURenderer *driverData,
  5859. SDL_GPUTexture *texture)
  5860. {
  5861. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5862. VulkanTextureContainer *vulkanTextureContainer = (VulkanTextureContainer *)texture;
  5863. Uint32 i;
  5864. SDL_LockMutex(renderer->disposeLock);
  5865. for (i = 0; i < vulkanTextureContainer->textureCount; i += 1) {
  5866. VULKAN_INTERNAL_ReleaseTexture(renderer, vulkanTextureContainer->textures[i]);
  5867. }
  5868. SDL_DestroyProperties(vulkanTextureContainer->header.info.props);
  5869. // Containers are just client handles, so we can destroy immediately
  5870. SDL_free(vulkanTextureContainer->debugName);
  5871. SDL_free(vulkanTextureContainer->textures);
  5872. SDL_free(vulkanTextureContainer);
  5873. SDL_UnlockMutex(renderer->disposeLock);
  5874. }
  5875. static void VULKAN_ReleaseSampler(
  5876. SDL_GPURenderer *driverData,
  5877. SDL_GPUSampler *sampler)
  5878. {
  5879. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5880. VulkanSampler *vulkanSampler = (VulkanSampler *)sampler;
  5881. SDL_LockMutex(renderer->disposeLock);
  5882. EXPAND_ARRAY_IF_NEEDED(
  5883. renderer->samplersToDestroy,
  5884. VulkanSampler *,
  5885. renderer->samplersToDestroyCount + 1,
  5886. renderer->samplersToDestroyCapacity,
  5887. renderer->samplersToDestroyCapacity * 2);
  5888. renderer->samplersToDestroy[renderer->samplersToDestroyCount] = vulkanSampler;
  5889. renderer->samplersToDestroyCount += 1;
  5890. SDL_UnlockMutex(renderer->disposeLock);
  5891. }
  5892. static void VULKAN_INTERNAL_ReleaseBuffer(
  5893. VulkanRenderer *renderer,
  5894. VulkanBuffer *vulkanBuffer)
  5895. {
  5896. if (vulkanBuffer->markedForDestroy) {
  5897. return;
  5898. }
  5899. SDL_LockMutex(renderer->disposeLock);
  5900. EXPAND_ARRAY_IF_NEEDED(
  5901. renderer->buffersToDestroy,
  5902. VulkanBuffer *,
  5903. renderer->buffersToDestroyCount + 1,
  5904. renderer->buffersToDestroyCapacity,
  5905. renderer->buffersToDestroyCapacity * 2);
  5906. renderer->buffersToDestroy[renderer->buffersToDestroyCount] = vulkanBuffer;
  5907. renderer->buffersToDestroyCount += 1;
  5908. vulkanBuffer->markedForDestroy = true;
  5909. vulkanBuffer->container = NULL;
  5910. SDL_UnlockMutex(renderer->disposeLock);
  5911. }
  5912. static void VULKAN_INTERNAL_ReleaseBufferContainer(
  5913. VulkanRenderer *renderer,
  5914. VulkanBufferContainer *bufferContainer)
  5915. {
  5916. Uint32 i;
  5917. SDL_LockMutex(renderer->disposeLock);
  5918. for (i = 0; i < bufferContainer->bufferCount; i += 1) {
  5919. VULKAN_INTERNAL_ReleaseBuffer(renderer, bufferContainer->buffers[i]);
  5920. }
  5921. // Containers are just client handles, so we can free immediately
  5922. if (bufferContainer->debugName != NULL) {
  5923. SDL_free(bufferContainer->debugName);
  5924. bufferContainer->debugName = NULL;
  5925. }
  5926. SDL_free(bufferContainer->buffers);
  5927. SDL_free(bufferContainer);
  5928. SDL_UnlockMutex(renderer->disposeLock);
  5929. }
  5930. static void VULKAN_ReleaseBuffer(
  5931. SDL_GPURenderer *driverData,
  5932. SDL_GPUBuffer *buffer)
  5933. {
  5934. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5935. VulkanBufferContainer *vulkanBufferContainer = (VulkanBufferContainer *)buffer;
  5936. VULKAN_INTERNAL_ReleaseBufferContainer(
  5937. renderer,
  5938. vulkanBufferContainer);
  5939. }
  5940. static void VULKAN_ReleaseTransferBuffer(
  5941. SDL_GPURenderer *driverData,
  5942. SDL_GPUTransferBuffer *transferBuffer)
  5943. {
  5944. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5945. VulkanBufferContainer *transferBufferContainer = (VulkanBufferContainer *)transferBuffer;
  5946. VULKAN_INTERNAL_ReleaseBufferContainer(
  5947. renderer,
  5948. transferBufferContainer);
  5949. }
  5950. static void VULKAN_ReleaseShader(
  5951. SDL_GPURenderer *driverData,
  5952. SDL_GPUShader *shader)
  5953. {
  5954. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5955. VulkanShader *vulkanShader = (VulkanShader *)shader;
  5956. SDL_LockMutex(renderer->disposeLock);
  5957. EXPAND_ARRAY_IF_NEEDED(
  5958. renderer->shadersToDestroy,
  5959. VulkanShader *,
  5960. renderer->shadersToDestroyCount + 1,
  5961. renderer->shadersToDestroyCapacity,
  5962. renderer->shadersToDestroyCapacity * 2);
  5963. renderer->shadersToDestroy[renderer->shadersToDestroyCount] = vulkanShader;
  5964. renderer->shadersToDestroyCount += 1;
  5965. SDL_UnlockMutex(renderer->disposeLock);
  5966. }
  5967. static void VULKAN_ReleaseComputePipeline(
  5968. SDL_GPURenderer *driverData,
  5969. SDL_GPUComputePipeline *computePipeline)
  5970. {
  5971. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5972. VulkanComputePipeline *vulkanComputePipeline = (VulkanComputePipeline *)computePipeline;
  5973. SDL_LockMutex(renderer->disposeLock);
  5974. EXPAND_ARRAY_IF_NEEDED(
  5975. renderer->computePipelinesToDestroy,
  5976. VulkanComputePipeline *,
  5977. renderer->computePipelinesToDestroyCount + 1,
  5978. renderer->computePipelinesToDestroyCapacity,
  5979. renderer->computePipelinesToDestroyCapacity * 2);
  5980. renderer->computePipelinesToDestroy[renderer->computePipelinesToDestroyCount] = vulkanComputePipeline;
  5981. renderer->computePipelinesToDestroyCount += 1;
  5982. SDL_UnlockMutex(renderer->disposeLock);
  5983. }
  5984. static void VULKAN_ReleaseGraphicsPipeline(
  5985. SDL_GPURenderer *driverData,
  5986. SDL_GPUGraphicsPipeline *graphicsPipeline)
  5987. {
  5988. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5989. VulkanGraphicsPipeline *vulkanGraphicsPipeline = (VulkanGraphicsPipeline *)graphicsPipeline;
  5990. SDL_LockMutex(renderer->disposeLock);
  5991. EXPAND_ARRAY_IF_NEEDED(
  5992. renderer->graphicsPipelinesToDestroy,
  5993. VulkanGraphicsPipeline *,
  5994. renderer->graphicsPipelinesToDestroyCount + 1,
  5995. renderer->graphicsPipelinesToDestroyCapacity,
  5996. renderer->graphicsPipelinesToDestroyCapacity * 2);
  5997. renderer->graphicsPipelinesToDestroy[renderer->graphicsPipelinesToDestroyCount] = vulkanGraphicsPipeline;
  5998. renderer->graphicsPipelinesToDestroyCount += 1;
  5999. SDL_UnlockMutex(renderer->disposeLock);
  6000. }
  6001. // Command Buffer render state
  6002. static VkRenderPass VULKAN_INTERNAL_FetchRenderPass(
  6003. VulkanRenderer *renderer,
  6004. const SDL_GPUColorTargetInfo *colorTargetInfos,
  6005. Uint32 numColorTargets,
  6006. const SDL_GPUDepthStencilTargetInfo *depthStencilTargetInfo)
  6007. {
  6008. VulkanRenderPassHashTableValue *renderPassWrapper = NULL;
  6009. VkRenderPass renderPassHandle;
  6010. RenderPassHashTableKey key;
  6011. Uint32 i;
  6012. SDL_zero(key);
  6013. for (i = 0; i < numColorTargets; i += 1) {
  6014. key.colorTargetDescriptions[i].format = SDLToVK_TextureFormat[((VulkanTextureContainer *)colorTargetInfos[i].texture)->header.info.format];
  6015. key.colorTargetDescriptions[i].loadOp = colorTargetInfos[i].load_op;
  6016. key.colorTargetDescriptions[i].storeOp = colorTargetInfos[i].store_op;
  6017. if (colorTargetInfos[i].resolve_texture != NULL) {
  6018. key.resolveTargetFormats[key.numResolveTargets] = SDLToVK_TextureFormat[((VulkanTextureContainer *)colorTargetInfos[i].resolve_texture)->header.info.format];
  6019. key.numResolveTargets += 1;
  6020. }
  6021. }
  6022. key.sampleCount = VK_SAMPLE_COUNT_1_BIT;
  6023. if (numColorTargets > 0) {
  6024. key.sampleCount = SDLToVK_SampleCount[((VulkanTextureContainer *)colorTargetInfos[0].texture)->header.info.sample_count];
  6025. } else if (numColorTargets == 0 && depthStencilTargetInfo != NULL) {
  6026. key.sampleCount = SDLToVK_SampleCount[((VulkanTextureContainer *)depthStencilTargetInfo->texture)->header.info.sample_count];
  6027. }
  6028. key.numColorTargets = numColorTargets;
  6029. if (depthStencilTargetInfo == NULL) {
  6030. key.depthStencilTargetDescription.format = 0;
  6031. key.depthStencilTargetDescription.loadOp = SDL_GPU_LOADOP_DONT_CARE;
  6032. key.depthStencilTargetDescription.storeOp = SDL_GPU_STOREOP_DONT_CARE;
  6033. key.depthStencilTargetDescription.stencilLoadOp = SDL_GPU_LOADOP_DONT_CARE;
  6034. key.depthStencilTargetDescription.stencilStoreOp = SDL_GPU_STOREOP_DONT_CARE;
  6035. } else {
  6036. key.depthStencilTargetDescription.format = SDLToVK_TextureFormat[((VulkanTextureContainer *)depthStencilTargetInfo->texture)->header.info.format];
  6037. key.depthStencilTargetDescription.loadOp = depthStencilTargetInfo->load_op;
  6038. key.depthStencilTargetDescription.storeOp = depthStencilTargetInfo->store_op;
  6039. key.depthStencilTargetDescription.stencilLoadOp = depthStencilTargetInfo->stencil_load_op;
  6040. key.depthStencilTargetDescription.stencilStoreOp = depthStencilTargetInfo->stencil_store_op;
  6041. }
  6042. SDL_LockMutex(renderer->renderPassFetchLock);
  6043. bool result = SDL_FindInHashTable(
  6044. renderer->renderPassHashTable,
  6045. (const void *)&key,
  6046. (const void **)&renderPassWrapper);
  6047. if (result) {
  6048. SDL_UnlockMutex(renderer->renderPassFetchLock);
  6049. return renderPassWrapper->handle;
  6050. }
  6051. renderPassHandle = VULKAN_INTERNAL_CreateRenderPass(
  6052. renderer,
  6053. colorTargetInfos,
  6054. numColorTargets,
  6055. depthStencilTargetInfo);
  6056. if (renderPassHandle == VK_NULL_HANDLE) {
  6057. SDL_UnlockMutex(renderer->renderPassFetchLock);
  6058. return VK_NULL_HANDLE;
  6059. }
  6060. // Have to malloc the key to store it in the hashtable
  6061. RenderPassHashTableKey *allocedKey = SDL_malloc(sizeof(RenderPassHashTableKey));
  6062. SDL_memcpy(allocedKey, &key, sizeof(RenderPassHashTableKey));
  6063. renderPassWrapper = SDL_malloc(sizeof(VulkanRenderPassHashTableValue));
  6064. renderPassWrapper->handle = renderPassHandle;
  6065. SDL_InsertIntoHashTable(
  6066. renderer->renderPassHashTable,
  6067. (const void *)allocedKey,
  6068. (const void *)renderPassWrapper, true);
  6069. SDL_UnlockMutex(renderer->renderPassFetchLock);
  6070. return renderPassHandle;
  6071. }
  6072. static VulkanFramebuffer *VULKAN_INTERNAL_FetchFramebuffer(
  6073. VulkanRenderer *renderer,
  6074. VkRenderPass renderPass,
  6075. const SDL_GPUColorTargetInfo *colorTargetInfos,
  6076. Uint32 numColorTargets,
  6077. const SDL_GPUDepthStencilTargetInfo *depthStencilTargetInfo,
  6078. Uint32 width,
  6079. Uint32 height)
  6080. {
  6081. VulkanFramebuffer *vulkanFramebuffer = NULL;
  6082. VkFramebufferCreateInfo framebufferInfo;
  6083. VkResult result;
  6084. VkImageView imageViewAttachments[2 * MAX_COLOR_TARGET_BINDINGS + 1 /* depth */];
  6085. FramebufferHashTableKey key;
  6086. Uint32 attachmentCount = 0;
  6087. Uint32 i;
  6088. SDL_zero(imageViewAttachments);
  6089. SDL_zero(key);
  6090. key.numColorTargets = numColorTargets;
  6091. for (i = 0; i < numColorTargets; i += 1) {
  6092. VulkanTextureContainer *container = (VulkanTextureContainer *)colorTargetInfos[i].texture;
  6093. VulkanTextureSubresource *subresource = VULKAN_INTERNAL_FetchTextureSubresource(
  6094. container,
  6095. container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? 0 : colorTargetInfos[i].layer_or_depth_plane,
  6096. colorTargetInfos[i].mip_level);
  6097. Uint32 rtvIndex =
  6098. container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? colorTargetInfos[i].layer_or_depth_plane : 0;
  6099. key.colorAttachmentViews[i] = subresource->renderTargetViews[rtvIndex];
  6100. if (colorTargetInfos[i].resolve_texture != NULL) {
  6101. VulkanTextureContainer *resolveTextureContainer = (VulkanTextureContainer *)colorTargetInfos[i].resolve_texture;
  6102. VulkanTextureSubresource *resolveSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  6103. resolveTextureContainer,
  6104. colorTargetInfos[i].layer_or_depth_plane,
  6105. colorTargetInfos[i].mip_level);
  6106. key.resolveAttachmentViews[key.numResolveAttachments] = resolveSubresource->renderTargetViews[0];
  6107. key.numResolveAttachments += 1;
  6108. }
  6109. }
  6110. if (depthStencilTargetInfo == NULL) {
  6111. key.depthStencilAttachmentView = VK_NULL_HANDLE;
  6112. } else {
  6113. VulkanTextureSubresource *subresource = VULKAN_INTERNAL_FetchTextureSubresource(
  6114. (VulkanTextureContainer *)depthStencilTargetInfo->texture,
  6115. depthStencilTargetInfo->layer,
  6116. depthStencilTargetInfo->mip_level);
  6117. key.depthStencilAttachmentView = subresource->depthStencilView;
  6118. }
  6119. key.width = width;
  6120. key.height = height;
  6121. SDL_LockMutex(renderer->framebufferFetchLock);
  6122. bool findResult = SDL_FindInHashTable(
  6123. renderer->framebufferHashTable,
  6124. (const void *)&key,
  6125. (const void **)&vulkanFramebuffer);
  6126. if (findResult) {
  6127. SDL_UnlockMutex(renderer->framebufferFetchLock);
  6128. return vulkanFramebuffer;
  6129. }
  6130. vulkanFramebuffer = SDL_malloc(sizeof(VulkanFramebuffer));
  6131. SDL_SetAtomicInt(&vulkanFramebuffer->referenceCount, 0);
  6132. // Create a new framebuffer
  6133. for (i = 0; i < numColorTargets; i += 1) {
  6134. VulkanTextureContainer *container = (VulkanTextureContainer *)colorTargetInfos[i].texture;
  6135. VulkanTextureSubresource *subresource = VULKAN_INTERNAL_FetchTextureSubresource(
  6136. container,
  6137. container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? 0 : colorTargetInfos[i].layer_or_depth_plane,
  6138. colorTargetInfos[i].mip_level);
  6139. Uint32 rtvIndex =
  6140. container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? colorTargetInfos[i].layer_or_depth_plane : 0;
  6141. imageViewAttachments[attachmentCount] = subresource->renderTargetViews[rtvIndex];
  6142. attachmentCount += 1;
  6143. if (colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE || colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE_AND_STORE) {
  6144. VulkanTextureContainer *resolveContainer = (VulkanTextureContainer *)colorTargetInfos[i].resolve_texture;
  6145. VulkanTextureSubresource *resolveSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  6146. resolveContainer,
  6147. colorTargetInfos[i].resolve_layer,
  6148. colorTargetInfos[i].resolve_mip_level);
  6149. imageViewAttachments[attachmentCount] = resolveSubresource->renderTargetViews[0];
  6150. attachmentCount += 1;
  6151. }
  6152. }
  6153. if (depthStencilTargetInfo != NULL) {
  6154. VulkanTextureSubresource *subresource = VULKAN_INTERNAL_FetchTextureSubresource(
  6155. (VulkanTextureContainer *)depthStencilTargetInfo->texture,
  6156. depthStencilTargetInfo->layer,
  6157. depthStencilTargetInfo->mip_level);
  6158. imageViewAttachments[attachmentCount] = subresource->depthStencilView;
  6159. attachmentCount += 1;
  6160. }
  6161. framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  6162. framebufferInfo.pNext = NULL;
  6163. framebufferInfo.flags = 0;
  6164. framebufferInfo.renderPass = renderPass;
  6165. framebufferInfo.attachmentCount = attachmentCount;
  6166. framebufferInfo.pAttachments = imageViewAttachments;
  6167. framebufferInfo.width = key.width;
  6168. framebufferInfo.height = key.height;
  6169. framebufferInfo.layers = 1;
  6170. result = renderer->vkCreateFramebuffer(
  6171. renderer->logicalDevice,
  6172. &framebufferInfo,
  6173. NULL,
  6174. &vulkanFramebuffer->framebuffer);
  6175. if (result == VK_SUCCESS) {
  6176. // Have to malloc the key to store it in the hashtable
  6177. FramebufferHashTableKey *allocedKey = SDL_malloc(sizeof(FramebufferHashTableKey));
  6178. SDL_memcpy(allocedKey, &key, sizeof(FramebufferHashTableKey));
  6179. SDL_InsertIntoHashTable(
  6180. renderer->framebufferHashTable,
  6181. (const void *)allocedKey,
  6182. (const void *)vulkanFramebuffer, true);
  6183. } else {
  6184. SDL_free(vulkanFramebuffer);
  6185. SDL_UnlockMutex(renderer->framebufferFetchLock);
  6186. CHECK_VULKAN_ERROR_AND_RETURN(result, vkCreateFramebuffer, NULL);
  6187. }
  6188. SDL_UnlockMutex(renderer->framebufferFetchLock);
  6189. return vulkanFramebuffer;
  6190. }
  6191. static void VULKAN_INTERNAL_SetCurrentViewport(
  6192. VulkanCommandBuffer *commandBuffer,
  6193. const SDL_GPUViewport *viewport)
  6194. {
  6195. VulkanCommandBuffer *vulkanCommandBuffer = commandBuffer;
  6196. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6197. vulkanCommandBuffer->currentViewport.x = viewport->x;
  6198. vulkanCommandBuffer->currentViewport.width = viewport->w;
  6199. vulkanCommandBuffer->currentViewport.minDepth = viewport->min_depth;
  6200. vulkanCommandBuffer->currentViewport.maxDepth = viewport->max_depth;
  6201. // Viewport flip for consistency with other backends
  6202. vulkanCommandBuffer->currentViewport.y = viewport->y + viewport->h;
  6203. vulkanCommandBuffer->currentViewport.height = -viewport->h;
  6204. renderer->vkCmdSetViewport(
  6205. vulkanCommandBuffer->commandBuffer,
  6206. 0,
  6207. 1,
  6208. &vulkanCommandBuffer->currentViewport);
  6209. }
  6210. static void VULKAN_SetViewport(
  6211. SDL_GPUCommandBuffer *commandBuffer,
  6212. const SDL_GPUViewport *viewport)
  6213. {
  6214. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6215. VULKAN_INTERNAL_SetCurrentViewport(
  6216. vulkanCommandBuffer,
  6217. viewport);
  6218. }
  6219. static void VULKAN_INTERNAL_SetCurrentScissor(
  6220. VulkanCommandBuffer *vulkanCommandBuffer,
  6221. const SDL_Rect *scissor)
  6222. {
  6223. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6224. vulkanCommandBuffer->currentScissor.offset.x = scissor->x;
  6225. vulkanCommandBuffer->currentScissor.offset.y = scissor->y;
  6226. vulkanCommandBuffer->currentScissor.extent.width = scissor->w;
  6227. vulkanCommandBuffer->currentScissor.extent.height = scissor->h;
  6228. renderer->vkCmdSetScissor(
  6229. vulkanCommandBuffer->commandBuffer,
  6230. 0,
  6231. 1,
  6232. &vulkanCommandBuffer->currentScissor);
  6233. }
  6234. static void VULKAN_SetScissor(
  6235. SDL_GPUCommandBuffer *commandBuffer,
  6236. const SDL_Rect *scissor)
  6237. {
  6238. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6239. VULKAN_INTERNAL_SetCurrentScissor(
  6240. vulkanCommandBuffer,
  6241. scissor);
  6242. }
  6243. static void VULKAN_INTERNAL_SetCurrentBlendConstants(
  6244. VulkanCommandBuffer *vulkanCommandBuffer,
  6245. SDL_FColor blendConstants)
  6246. {
  6247. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6248. vulkanCommandBuffer->blendConstants[0] = blendConstants.r;
  6249. vulkanCommandBuffer->blendConstants[1] = blendConstants.g;
  6250. vulkanCommandBuffer->blendConstants[2] = blendConstants.b;
  6251. vulkanCommandBuffer->blendConstants[3] = blendConstants.a;
  6252. renderer->vkCmdSetBlendConstants(
  6253. vulkanCommandBuffer->commandBuffer,
  6254. vulkanCommandBuffer->blendConstants);
  6255. }
  6256. static void VULKAN_SetBlendConstants(
  6257. SDL_GPUCommandBuffer *commandBuffer,
  6258. SDL_FColor blendConstants)
  6259. {
  6260. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6261. VULKAN_INTERNAL_SetCurrentBlendConstants(
  6262. vulkanCommandBuffer,
  6263. blendConstants);
  6264. }
  6265. static void VULKAN_INTERNAL_SetCurrentStencilReference(
  6266. VulkanCommandBuffer *vulkanCommandBuffer,
  6267. Uint8 reference)
  6268. {
  6269. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6270. vulkanCommandBuffer->stencilRef = reference;
  6271. renderer->vkCmdSetStencilReference(
  6272. vulkanCommandBuffer->commandBuffer,
  6273. VK_STENCIL_FACE_FRONT_AND_BACK,
  6274. vulkanCommandBuffer->stencilRef);
  6275. }
  6276. static void VULKAN_SetStencilReference(
  6277. SDL_GPUCommandBuffer *commandBuffer,
  6278. Uint8 reference)
  6279. {
  6280. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6281. VULKAN_INTERNAL_SetCurrentStencilReference(
  6282. vulkanCommandBuffer,
  6283. reference);
  6284. }
  6285. static void VULKAN_BindVertexSamplers(
  6286. SDL_GPUCommandBuffer *commandBuffer,
  6287. Uint32 firstSlot,
  6288. const SDL_GPUTextureSamplerBinding *textureSamplerBindings,
  6289. Uint32 numBindings)
  6290. {
  6291. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6292. for (Uint32 i = 0; i < numBindings; i += 1) {
  6293. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)textureSamplerBindings[i].texture;
  6294. VulkanSampler *sampler = (VulkanSampler *)textureSamplerBindings[i].sampler;
  6295. if (vulkanCommandBuffer->vertexSamplerBindings[firstSlot + i] != sampler->sampler) {
  6296. VULKAN_INTERNAL_TrackSampler(
  6297. vulkanCommandBuffer,
  6298. (VulkanSampler *)textureSamplerBindings[i].sampler);
  6299. vulkanCommandBuffer->vertexSamplerBindings[firstSlot + i] = sampler->sampler;
  6300. vulkanCommandBuffer->needNewVertexResourceDescriptorSet = true;
  6301. }
  6302. if (vulkanCommandBuffer->vertexSamplerTextureViewBindings[firstSlot + i] != textureContainer->activeTexture->fullView) {
  6303. VULKAN_INTERNAL_TrackTexture(
  6304. vulkanCommandBuffer,
  6305. textureContainer->activeTexture);
  6306. vulkanCommandBuffer->vertexSamplerTextureViewBindings[firstSlot + i] = textureContainer->activeTexture->fullView;
  6307. vulkanCommandBuffer->needNewVertexResourceDescriptorSet = true;
  6308. }
  6309. }
  6310. }
  6311. static void VULKAN_BindVertexStorageTextures(
  6312. SDL_GPUCommandBuffer *commandBuffer,
  6313. Uint32 firstSlot,
  6314. SDL_GPUTexture *const *storageTextures,
  6315. Uint32 numBindings)
  6316. {
  6317. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6318. for (Uint32 i = 0; i < numBindings; i += 1) {
  6319. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)storageTextures[i];
  6320. if (vulkanCommandBuffer->vertexStorageTextureViewBindings[firstSlot + i] != textureContainer->activeTexture->fullView) {
  6321. VULKAN_INTERNAL_TrackTexture(
  6322. vulkanCommandBuffer,
  6323. textureContainer->activeTexture);
  6324. vulkanCommandBuffer->vertexStorageTextureViewBindings[firstSlot + i] = textureContainer->activeTexture->fullView;
  6325. vulkanCommandBuffer->needNewVertexResourceDescriptorSet = true;
  6326. }
  6327. }
  6328. }
  6329. static void VULKAN_BindVertexStorageBuffers(
  6330. SDL_GPUCommandBuffer *commandBuffer,
  6331. Uint32 firstSlot,
  6332. SDL_GPUBuffer *const *storageBuffers,
  6333. Uint32 numBindings)
  6334. {
  6335. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6336. for (Uint32 i = 0; i < numBindings; i += 1) {
  6337. VulkanBufferContainer *bufferContainer = (VulkanBufferContainer *)storageBuffers[i];
  6338. if (vulkanCommandBuffer->vertexStorageBufferBindings[firstSlot + i] != bufferContainer->activeBuffer->buffer) {
  6339. VULKAN_INTERNAL_TrackBuffer(
  6340. vulkanCommandBuffer,
  6341. bufferContainer->activeBuffer);
  6342. vulkanCommandBuffer->vertexStorageBufferBindings[firstSlot + i] = bufferContainer->activeBuffer->buffer;
  6343. vulkanCommandBuffer->needNewVertexResourceDescriptorSet = true;
  6344. }
  6345. }
  6346. }
  6347. static void VULKAN_BindFragmentSamplers(
  6348. SDL_GPUCommandBuffer *commandBuffer,
  6349. Uint32 firstSlot,
  6350. const SDL_GPUTextureSamplerBinding *textureSamplerBindings,
  6351. Uint32 numBindings)
  6352. {
  6353. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6354. for (Uint32 i = 0; i < numBindings; i += 1) {
  6355. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)textureSamplerBindings[i].texture;
  6356. VulkanSampler *sampler = (VulkanSampler *)textureSamplerBindings[i].sampler;
  6357. if (vulkanCommandBuffer->fragmentSamplerBindings[firstSlot + i] != sampler->sampler) {
  6358. VULKAN_INTERNAL_TrackSampler(
  6359. vulkanCommandBuffer,
  6360. (VulkanSampler *)textureSamplerBindings[i].sampler);
  6361. vulkanCommandBuffer->fragmentSamplerBindings[firstSlot + i] = sampler->sampler;
  6362. vulkanCommandBuffer->needNewFragmentResourceDescriptorSet = true;
  6363. }
  6364. if (vulkanCommandBuffer->fragmentSamplerTextureViewBindings[firstSlot + i] != textureContainer->activeTexture->fullView) {
  6365. VULKAN_INTERNAL_TrackTexture(
  6366. vulkanCommandBuffer,
  6367. textureContainer->activeTexture);
  6368. vulkanCommandBuffer->fragmentSamplerTextureViewBindings[firstSlot + i] = textureContainer->activeTexture->fullView;
  6369. vulkanCommandBuffer->needNewFragmentResourceDescriptorSet = true;
  6370. }
  6371. }
  6372. }
  6373. static void VULKAN_BindFragmentStorageTextures(
  6374. SDL_GPUCommandBuffer *commandBuffer,
  6375. Uint32 firstSlot,
  6376. SDL_GPUTexture *const *storageTextures,
  6377. Uint32 numBindings)
  6378. {
  6379. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6380. for (Uint32 i = 0; i < numBindings; i += 1) {
  6381. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)storageTextures[i];
  6382. if (vulkanCommandBuffer->fragmentStorageTextureViewBindings[firstSlot + i] != textureContainer->activeTexture->fullView) {
  6383. VULKAN_INTERNAL_TrackTexture(
  6384. vulkanCommandBuffer,
  6385. textureContainer->activeTexture);
  6386. vulkanCommandBuffer->fragmentStorageTextureViewBindings[firstSlot + i] = textureContainer->activeTexture->fullView;
  6387. vulkanCommandBuffer->needNewFragmentResourceDescriptorSet = true;
  6388. }
  6389. }
  6390. }
  6391. static void VULKAN_BindFragmentStorageBuffers(
  6392. SDL_GPUCommandBuffer *commandBuffer,
  6393. Uint32 firstSlot,
  6394. SDL_GPUBuffer *const *storageBuffers,
  6395. Uint32 numBindings)
  6396. {
  6397. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6398. VulkanBufferContainer *bufferContainer;
  6399. Uint32 i;
  6400. for (i = 0; i < numBindings; i += 1) {
  6401. bufferContainer = (VulkanBufferContainer *)storageBuffers[i];
  6402. if (vulkanCommandBuffer->fragmentStorageBufferBindings[firstSlot + i] != bufferContainer->activeBuffer->buffer) {
  6403. VULKAN_INTERNAL_TrackBuffer(
  6404. vulkanCommandBuffer,
  6405. bufferContainer->activeBuffer);
  6406. vulkanCommandBuffer->fragmentStorageBufferBindings[firstSlot + i] = bufferContainer->activeBuffer->buffer;
  6407. vulkanCommandBuffer->needNewFragmentResourceDescriptorSet = true;
  6408. }
  6409. }
  6410. }
  6411. static VulkanUniformBuffer *VULKAN_INTERNAL_AcquireUniformBufferFromPool(
  6412. VulkanCommandBuffer *commandBuffer)
  6413. {
  6414. VulkanRenderer *renderer = commandBuffer->renderer;
  6415. VulkanUniformBuffer *uniformBuffer;
  6416. SDL_LockMutex(renderer->acquireUniformBufferLock);
  6417. if (renderer->uniformBufferPoolCount > 0) {
  6418. uniformBuffer = renderer->uniformBufferPool[renderer->uniformBufferPoolCount - 1];
  6419. renderer->uniformBufferPoolCount -= 1;
  6420. } else {
  6421. uniformBuffer = VULKAN_INTERNAL_CreateUniformBuffer(
  6422. renderer,
  6423. UNIFORM_BUFFER_SIZE);
  6424. }
  6425. SDL_UnlockMutex(renderer->acquireUniformBufferLock);
  6426. VULKAN_INTERNAL_TrackUniformBuffer(commandBuffer, uniformBuffer);
  6427. return uniformBuffer;
  6428. }
  6429. static void VULKAN_INTERNAL_ReturnUniformBufferToPool(
  6430. VulkanRenderer *renderer,
  6431. VulkanUniformBuffer *uniformBuffer)
  6432. {
  6433. if (renderer->uniformBufferPoolCount >= renderer->uniformBufferPoolCapacity) {
  6434. renderer->uniformBufferPoolCapacity *= 2;
  6435. renderer->uniformBufferPool = SDL_realloc(
  6436. renderer->uniformBufferPool,
  6437. renderer->uniformBufferPoolCapacity * sizeof(VulkanUniformBuffer *));
  6438. }
  6439. renderer->uniformBufferPool[renderer->uniformBufferPoolCount] = uniformBuffer;
  6440. renderer->uniformBufferPoolCount += 1;
  6441. uniformBuffer->writeOffset = 0;
  6442. uniformBuffer->drawOffset = 0;
  6443. }
  6444. static void VULKAN_INTERNAL_PushUniformData(
  6445. VulkanCommandBuffer *commandBuffer,
  6446. VulkanUniformBufferStage uniformBufferStage,
  6447. Uint32 slotIndex,
  6448. const void *data,
  6449. Uint32 length)
  6450. {
  6451. Uint32 blockSize =
  6452. VULKAN_INTERNAL_NextHighestAlignment32(
  6453. length,
  6454. commandBuffer->renderer->minUBOAlignment);
  6455. VulkanUniformBuffer *uniformBuffer;
  6456. if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_VERTEX) {
  6457. if (commandBuffer->vertexUniformBuffers[slotIndex] == NULL) {
  6458. commandBuffer->vertexUniformBuffers[slotIndex] = VULKAN_INTERNAL_AcquireUniformBufferFromPool(
  6459. commandBuffer);
  6460. }
  6461. uniformBuffer = commandBuffer->vertexUniformBuffers[slotIndex];
  6462. } else if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_FRAGMENT) {
  6463. if (commandBuffer->fragmentUniformBuffers[slotIndex] == NULL) {
  6464. commandBuffer->fragmentUniformBuffers[slotIndex] = VULKAN_INTERNAL_AcquireUniformBufferFromPool(
  6465. commandBuffer);
  6466. }
  6467. uniformBuffer = commandBuffer->fragmentUniformBuffers[slotIndex];
  6468. } else if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_COMPUTE) {
  6469. if (commandBuffer->computeUniformBuffers[slotIndex] == NULL) {
  6470. commandBuffer->computeUniformBuffers[slotIndex] = VULKAN_INTERNAL_AcquireUniformBufferFromPool(
  6471. commandBuffer);
  6472. }
  6473. uniformBuffer = commandBuffer->computeUniformBuffers[slotIndex];
  6474. } else {
  6475. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized shader stage!");
  6476. return;
  6477. }
  6478. // If there is no more room, acquire a new uniform buffer
  6479. if (uniformBuffer->writeOffset + blockSize + MAX_UBO_SECTION_SIZE >= uniformBuffer->buffer->size) {
  6480. uniformBuffer = VULKAN_INTERNAL_AcquireUniformBufferFromPool(commandBuffer);
  6481. uniformBuffer->drawOffset = 0;
  6482. uniformBuffer->writeOffset = 0;
  6483. if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_VERTEX) {
  6484. commandBuffer->vertexUniformBuffers[slotIndex] = uniformBuffer;
  6485. commandBuffer->needNewVertexUniformDescriptorSet = true;
  6486. } else if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_FRAGMENT) {
  6487. commandBuffer->fragmentUniformBuffers[slotIndex] = uniformBuffer;
  6488. commandBuffer->needNewFragmentUniformDescriptorSet = true;
  6489. } else if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_COMPUTE) {
  6490. commandBuffer->computeUniformBuffers[slotIndex] = uniformBuffer;
  6491. commandBuffer->needNewComputeUniformDescriptorSet = true;
  6492. } else {
  6493. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized shader stage!");
  6494. return;
  6495. }
  6496. }
  6497. uniformBuffer->drawOffset = uniformBuffer->writeOffset;
  6498. Uint8 *dst =
  6499. uniformBuffer->buffer->usedRegion->allocation->mapPointer +
  6500. uniformBuffer->buffer->usedRegion->resourceOffset +
  6501. uniformBuffer->writeOffset;
  6502. SDL_memcpy(
  6503. dst,
  6504. data,
  6505. length);
  6506. uniformBuffer->writeOffset += blockSize;
  6507. if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_VERTEX) {
  6508. commandBuffer->needNewVertexUniformOffsets = true;
  6509. } else if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_FRAGMENT) {
  6510. commandBuffer->needNewFragmentUniformOffsets = true;
  6511. } else if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_COMPUTE) {
  6512. commandBuffer->needNewComputeUniformOffsets = true;
  6513. } else {
  6514. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized shader stage!");
  6515. return;
  6516. }
  6517. }
  6518. static void VULKAN_BeginRenderPass(
  6519. SDL_GPUCommandBuffer *commandBuffer,
  6520. const SDL_GPUColorTargetInfo *colorTargetInfos,
  6521. Uint32 numColorTargets,
  6522. const SDL_GPUDepthStencilTargetInfo *depthStencilTargetInfo)
  6523. {
  6524. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6525. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6526. VkRenderPass renderPass;
  6527. VulkanFramebuffer *framebuffer;
  6528. Uint32 w, h;
  6529. VkClearValue *clearValues;
  6530. Uint32 clearCount = 0;
  6531. Uint32 totalColorAttachmentCount = 0;
  6532. Uint32 i;
  6533. SDL_GPUViewport defaultViewport;
  6534. SDL_Rect defaultScissor;
  6535. SDL_FColor defaultBlendConstants;
  6536. Uint32 framebufferWidth = SDL_MAX_UINT32;
  6537. Uint32 framebufferHeight = SDL_MAX_UINT32;
  6538. for (i = 0; i < numColorTargets; i += 1) {
  6539. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)colorTargetInfos[i].texture;
  6540. w = textureContainer->header.info.width >> colorTargetInfos[i].mip_level;
  6541. h = textureContainer->header.info.height >> colorTargetInfos[i].mip_level;
  6542. // The framebuffer cannot be larger than the smallest attachment.
  6543. if (w < framebufferWidth) {
  6544. framebufferWidth = w;
  6545. }
  6546. if (h < framebufferHeight) {
  6547. framebufferHeight = h;
  6548. }
  6549. }
  6550. if (depthStencilTargetInfo != NULL) {
  6551. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)depthStencilTargetInfo->texture;
  6552. w = textureContainer->header.info.width >> depthStencilTargetInfo->mip_level;
  6553. h = textureContainer->header.info.height >> depthStencilTargetInfo->mip_level;
  6554. // The framebuffer cannot be larger than the smallest attachment.
  6555. if (w < framebufferWidth) {
  6556. framebufferWidth = w;
  6557. }
  6558. if (h < framebufferHeight) {
  6559. framebufferHeight = h;
  6560. }
  6561. }
  6562. for (i = 0; i < numColorTargets; i += 1) {
  6563. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)colorTargetInfos[i].texture;
  6564. VulkanTextureSubresource *subresource = VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  6565. renderer,
  6566. vulkanCommandBuffer,
  6567. textureContainer,
  6568. textureContainer->header.info.type == SDL_GPU_TEXTURETYPE_3D ? 0 : colorTargetInfos[i].layer_or_depth_plane,
  6569. colorTargetInfos[i].mip_level,
  6570. colorTargetInfos[i].cycle,
  6571. VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT);
  6572. vulkanCommandBuffer->colorAttachmentSubresources[vulkanCommandBuffer->colorAttachmentSubresourceCount] = subresource;
  6573. vulkanCommandBuffer->colorAttachmentSubresourceCount += 1;
  6574. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, subresource->parent);
  6575. totalColorAttachmentCount += 1;
  6576. clearCount += 1;
  6577. if (colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE || colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE_AND_STORE) {
  6578. VulkanTextureContainer *resolveContainer = (VulkanTextureContainer *)colorTargetInfos[i].resolve_texture;
  6579. VulkanTextureSubresource *resolveSubresource = VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  6580. renderer,
  6581. vulkanCommandBuffer,
  6582. resolveContainer,
  6583. colorTargetInfos[i].resolve_layer,
  6584. colorTargetInfos[i].resolve_mip_level,
  6585. colorTargetInfos[i].cycle_resolve_texture,
  6586. VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT);
  6587. vulkanCommandBuffer->resolveAttachmentSubresources[vulkanCommandBuffer->resolveAttachmentSubresourceCount] = resolveSubresource;
  6588. vulkanCommandBuffer->resolveAttachmentSubresourceCount += 1;
  6589. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, resolveSubresource->parent);
  6590. totalColorAttachmentCount += 1;
  6591. clearCount += 1;
  6592. }
  6593. }
  6594. if (depthStencilTargetInfo != NULL) {
  6595. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)depthStencilTargetInfo->texture;
  6596. VulkanTextureSubresource *subresource = VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  6597. renderer,
  6598. vulkanCommandBuffer,
  6599. textureContainer,
  6600. depthStencilTargetInfo->layer,
  6601. depthStencilTargetInfo->mip_level,
  6602. depthStencilTargetInfo->cycle,
  6603. VULKAN_TEXTURE_USAGE_MODE_DEPTH_STENCIL_ATTACHMENT);
  6604. vulkanCommandBuffer->depthStencilAttachmentSubresource = subresource;
  6605. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, subresource->parent);
  6606. clearCount += 1;
  6607. }
  6608. // Fetch required render objects
  6609. renderPass = VULKAN_INTERNAL_FetchRenderPass(
  6610. renderer,
  6611. colorTargetInfos,
  6612. numColorTargets,
  6613. depthStencilTargetInfo);
  6614. if (renderPass == VK_NULL_HANDLE) {
  6615. return;
  6616. }
  6617. framebuffer = VULKAN_INTERNAL_FetchFramebuffer(
  6618. renderer,
  6619. renderPass,
  6620. colorTargetInfos,
  6621. numColorTargets,
  6622. depthStencilTargetInfo,
  6623. framebufferWidth,
  6624. framebufferHeight);
  6625. if (framebuffer == NULL) {
  6626. return;
  6627. }
  6628. VULKAN_INTERNAL_TrackFramebuffer(vulkanCommandBuffer, framebuffer);
  6629. // Set clear values
  6630. clearValues = SDL_stack_alloc(VkClearValue, clearCount);
  6631. int clearIndex = 0;
  6632. for (i = 0; i < numColorTargets; i += 1) {
  6633. clearValues[clearIndex].color.float32[0] = colorTargetInfos[i].clear_color.r;
  6634. clearValues[clearIndex].color.float32[1] = colorTargetInfos[i].clear_color.g;
  6635. clearValues[clearIndex].color.float32[2] = colorTargetInfos[i].clear_color.b;
  6636. clearValues[clearIndex].color.float32[3] = colorTargetInfos[i].clear_color.a;
  6637. clearIndex += 1;
  6638. if (colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE || colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE_AND_STORE) {
  6639. // Skip over the resolve texture, we're not clearing it
  6640. clearIndex += 1;
  6641. }
  6642. }
  6643. if (depthStencilTargetInfo != NULL) {
  6644. clearValues[totalColorAttachmentCount].depthStencil.depth =
  6645. depthStencilTargetInfo->clear_depth;
  6646. clearValues[totalColorAttachmentCount].depthStencil.stencil =
  6647. depthStencilTargetInfo->clear_stencil;
  6648. }
  6649. VkRenderPassBeginInfo renderPassBeginInfo;
  6650. renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  6651. renderPassBeginInfo.pNext = NULL;
  6652. renderPassBeginInfo.renderPass = renderPass;
  6653. renderPassBeginInfo.framebuffer = framebuffer->framebuffer;
  6654. renderPassBeginInfo.pClearValues = clearValues;
  6655. renderPassBeginInfo.clearValueCount = clearCount;
  6656. renderPassBeginInfo.renderArea.extent.width = framebufferWidth;
  6657. renderPassBeginInfo.renderArea.extent.height = framebufferHeight;
  6658. renderPassBeginInfo.renderArea.offset.x = 0;
  6659. renderPassBeginInfo.renderArea.offset.y = 0;
  6660. renderer->vkCmdBeginRenderPass(
  6661. vulkanCommandBuffer->commandBuffer,
  6662. &renderPassBeginInfo,
  6663. VK_SUBPASS_CONTENTS_INLINE);
  6664. SDL_stack_free(clearValues);
  6665. // Set sensible default states
  6666. defaultViewport.x = 0;
  6667. defaultViewport.y = 0;
  6668. defaultViewport.w = (float)framebufferWidth;
  6669. defaultViewport.h = (float)framebufferHeight;
  6670. defaultViewport.min_depth = 0;
  6671. defaultViewport.max_depth = 1;
  6672. VULKAN_INTERNAL_SetCurrentViewport(
  6673. vulkanCommandBuffer,
  6674. &defaultViewport);
  6675. defaultScissor.x = 0;
  6676. defaultScissor.y = 0;
  6677. defaultScissor.w = (Sint32)framebufferWidth;
  6678. defaultScissor.h = (Sint32)framebufferHeight;
  6679. VULKAN_INTERNAL_SetCurrentScissor(
  6680. vulkanCommandBuffer,
  6681. &defaultScissor);
  6682. defaultBlendConstants.r = 1.0f;
  6683. defaultBlendConstants.g = 1.0f;
  6684. defaultBlendConstants.b = 1.0f;
  6685. defaultBlendConstants.a = 1.0f;
  6686. VULKAN_INTERNAL_SetCurrentBlendConstants(
  6687. vulkanCommandBuffer,
  6688. defaultBlendConstants);
  6689. VULKAN_INTERNAL_SetCurrentStencilReference(
  6690. vulkanCommandBuffer,
  6691. 0);
  6692. }
  6693. static void VULKAN_BindGraphicsPipeline(
  6694. SDL_GPUCommandBuffer *commandBuffer,
  6695. SDL_GPUGraphicsPipeline *graphicsPipeline)
  6696. {
  6697. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6698. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6699. VulkanGraphicsPipeline *pipeline = (VulkanGraphicsPipeline *)graphicsPipeline;
  6700. renderer->vkCmdBindPipeline(
  6701. vulkanCommandBuffer->commandBuffer,
  6702. VK_PIPELINE_BIND_POINT_GRAPHICS,
  6703. pipeline->pipeline);
  6704. vulkanCommandBuffer->currentGraphicsPipeline = pipeline;
  6705. VULKAN_INTERNAL_TrackGraphicsPipeline(vulkanCommandBuffer, pipeline);
  6706. // Acquire uniform buffers if necessary
  6707. for (Uint32 i = 0; i < pipeline->resourceLayout->vertexUniformBufferCount; i += 1) {
  6708. if (vulkanCommandBuffer->vertexUniformBuffers[i] == NULL) {
  6709. vulkanCommandBuffer->vertexUniformBuffers[i] = VULKAN_INTERNAL_AcquireUniformBufferFromPool(
  6710. vulkanCommandBuffer);
  6711. }
  6712. }
  6713. for (Uint32 i = 0; i < pipeline->resourceLayout->fragmentUniformBufferCount; i += 1) {
  6714. if (vulkanCommandBuffer->fragmentUniformBuffers[i] == NULL) {
  6715. vulkanCommandBuffer->fragmentUniformBuffers[i] = VULKAN_INTERNAL_AcquireUniformBufferFromPool(
  6716. vulkanCommandBuffer);
  6717. }
  6718. }
  6719. // Mark bindings as needed
  6720. vulkanCommandBuffer->needNewVertexResourceDescriptorSet = true;
  6721. vulkanCommandBuffer->needNewFragmentResourceDescriptorSet = true;
  6722. vulkanCommandBuffer->needNewVertexUniformDescriptorSet = true;
  6723. vulkanCommandBuffer->needNewFragmentUniformDescriptorSet = true;
  6724. vulkanCommandBuffer->needNewVertexUniformOffsets = true;
  6725. vulkanCommandBuffer->needNewFragmentUniformOffsets = true;
  6726. }
  6727. static void VULKAN_BindVertexBuffers(
  6728. SDL_GPUCommandBuffer *commandBuffer,
  6729. Uint32 firstSlot,
  6730. const SDL_GPUBufferBinding *bindings,
  6731. Uint32 numBindings)
  6732. {
  6733. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6734. for (Uint32 i = 0; i < numBindings; i += 1) {
  6735. VulkanBuffer *buffer = ((VulkanBufferContainer *)bindings[i].buffer)->activeBuffer;
  6736. if (vulkanCommandBuffer->vertexBuffers[firstSlot + i] != buffer->buffer || vulkanCommandBuffer->vertexBufferOffsets[firstSlot + i] != bindings[i].offset) {
  6737. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, buffer);
  6738. vulkanCommandBuffer->vertexBuffers[firstSlot + i] = buffer->buffer;
  6739. vulkanCommandBuffer->vertexBufferOffsets[firstSlot + i] = bindings[i].offset;
  6740. vulkanCommandBuffer->needVertexBufferBind = true;
  6741. }
  6742. }
  6743. vulkanCommandBuffer->vertexBufferCount =
  6744. SDL_max(vulkanCommandBuffer->vertexBufferCount, firstSlot + numBindings);
  6745. }
  6746. static void VULKAN_BindIndexBuffer(
  6747. SDL_GPUCommandBuffer *commandBuffer,
  6748. const SDL_GPUBufferBinding *binding,
  6749. SDL_GPUIndexElementSize indexElementSize)
  6750. {
  6751. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6752. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6753. VulkanBuffer *vulkanBuffer = ((VulkanBufferContainer *)binding->buffer)->activeBuffer;
  6754. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, vulkanBuffer);
  6755. renderer->vkCmdBindIndexBuffer(
  6756. vulkanCommandBuffer->commandBuffer,
  6757. vulkanBuffer->buffer,
  6758. (VkDeviceSize)binding->offset,
  6759. SDLToVK_IndexType[indexElementSize]);
  6760. }
  6761. static void VULKAN_PushVertexUniformData(
  6762. SDL_GPUCommandBuffer *commandBuffer,
  6763. Uint32 slotIndex,
  6764. const void *data,
  6765. Uint32 length)
  6766. {
  6767. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6768. VULKAN_INTERNAL_PushUniformData(
  6769. vulkanCommandBuffer,
  6770. VULKAN_UNIFORM_BUFFER_STAGE_VERTEX,
  6771. slotIndex,
  6772. data,
  6773. length);
  6774. }
  6775. static void VULKAN_PushFragmentUniformData(
  6776. SDL_GPUCommandBuffer *commandBuffer,
  6777. Uint32 slotIndex,
  6778. const void *data,
  6779. Uint32 length)
  6780. {
  6781. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6782. VULKAN_INTERNAL_PushUniformData(
  6783. vulkanCommandBuffer,
  6784. VULKAN_UNIFORM_BUFFER_STAGE_FRAGMENT,
  6785. slotIndex,
  6786. data,
  6787. length);
  6788. }
  6789. static void VULKAN_EndRenderPass(
  6790. SDL_GPUCommandBuffer *commandBuffer)
  6791. {
  6792. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6793. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6794. Uint32 i;
  6795. renderer->vkCmdEndRenderPass(
  6796. vulkanCommandBuffer->commandBuffer);
  6797. for (i = 0; i < vulkanCommandBuffer->colorAttachmentSubresourceCount; i += 1) {
  6798. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  6799. renderer,
  6800. vulkanCommandBuffer,
  6801. VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT,
  6802. vulkanCommandBuffer->colorAttachmentSubresources[i]);
  6803. }
  6804. vulkanCommandBuffer->colorAttachmentSubresourceCount = 0;
  6805. for (i = 0; i < vulkanCommandBuffer->resolveAttachmentSubresourceCount; i += 1) {
  6806. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  6807. renderer,
  6808. vulkanCommandBuffer,
  6809. VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT,
  6810. vulkanCommandBuffer->resolveAttachmentSubresources[i]);
  6811. }
  6812. vulkanCommandBuffer->resolveAttachmentSubresourceCount = 0;
  6813. if (vulkanCommandBuffer->depthStencilAttachmentSubresource != NULL) {
  6814. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  6815. renderer,
  6816. vulkanCommandBuffer,
  6817. VULKAN_TEXTURE_USAGE_MODE_DEPTH_STENCIL_ATTACHMENT,
  6818. vulkanCommandBuffer->depthStencilAttachmentSubresource);
  6819. vulkanCommandBuffer->depthStencilAttachmentSubresource = NULL;
  6820. }
  6821. vulkanCommandBuffer->currentGraphicsPipeline = NULL;
  6822. vulkanCommandBuffer->vertexResourceDescriptorSet = VK_NULL_HANDLE;
  6823. vulkanCommandBuffer->vertexUniformDescriptorSet = VK_NULL_HANDLE;
  6824. vulkanCommandBuffer->fragmentResourceDescriptorSet = VK_NULL_HANDLE;
  6825. vulkanCommandBuffer->fragmentUniformDescriptorSet = VK_NULL_HANDLE;
  6826. // Reset bind state
  6827. SDL_zeroa(vulkanCommandBuffer->colorAttachmentSubresources);
  6828. SDL_zeroa(vulkanCommandBuffer->resolveAttachmentSubresources);
  6829. vulkanCommandBuffer->depthStencilAttachmentSubresource = NULL;
  6830. SDL_zeroa(vulkanCommandBuffer->vertexBuffers);
  6831. SDL_zeroa(vulkanCommandBuffer->vertexBufferOffsets);
  6832. vulkanCommandBuffer->vertexBufferCount = 0;
  6833. SDL_zeroa(vulkanCommandBuffer->vertexSamplerBindings);
  6834. SDL_zeroa(vulkanCommandBuffer->vertexSamplerTextureViewBindings);
  6835. SDL_zeroa(vulkanCommandBuffer->vertexStorageTextureViewBindings);
  6836. SDL_zeroa(vulkanCommandBuffer->vertexStorageBufferBindings);
  6837. SDL_zeroa(vulkanCommandBuffer->fragmentSamplerBindings);
  6838. SDL_zeroa(vulkanCommandBuffer->fragmentSamplerTextureViewBindings);
  6839. SDL_zeroa(vulkanCommandBuffer->fragmentStorageTextureViewBindings);
  6840. SDL_zeroa(vulkanCommandBuffer->fragmentStorageBufferBindings);
  6841. }
  6842. static void VULKAN_BeginComputePass(
  6843. SDL_GPUCommandBuffer *commandBuffer,
  6844. const SDL_GPUStorageTextureReadWriteBinding *storageTextureBindings,
  6845. Uint32 numStorageTextureBindings,
  6846. const SDL_GPUStorageBufferReadWriteBinding *storageBufferBindings,
  6847. Uint32 numStorageBufferBindings)
  6848. {
  6849. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6850. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6851. VulkanBufferContainer *bufferContainer;
  6852. VulkanBuffer *buffer;
  6853. Uint32 i;
  6854. vulkanCommandBuffer->readWriteComputeStorageTextureSubresourceCount = numStorageTextureBindings;
  6855. for (i = 0; i < numStorageTextureBindings; i += 1) {
  6856. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)storageTextureBindings[i].texture;
  6857. VulkanTextureSubresource *subresource = VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  6858. renderer,
  6859. vulkanCommandBuffer,
  6860. textureContainer,
  6861. storageTextureBindings[i].layer,
  6862. storageTextureBindings[i].mip_level,
  6863. storageTextureBindings[i].cycle,
  6864. VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE);
  6865. vulkanCommandBuffer->readWriteComputeStorageTextureSubresources[i] = subresource;
  6866. vulkanCommandBuffer->readWriteComputeStorageTextureViewBindings[i] = subresource->computeWriteView;
  6867. VULKAN_INTERNAL_TrackTexture(
  6868. vulkanCommandBuffer,
  6869. subresource->parent);
  6870. }
  6871. for (i = 0; i < numStorageBufferBindings; i += 1) {
  6872. bufferContainer = (VulkanBufferContainer *)storageBufferBindings[i].buffer;
  6873. buffer = VULKAN_INTERNAL_PrepareBufferForWrite(
  6874. renderer,
  6875. vulkanCommandBuffer,
  6876. bufferContainer,
  6877. storageBufferBindings[i].cycle,
  6878. VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE);
  6879. vulkanCommandBuffer->readWriteComputeStorageBuffers[i] = buffer;
  6880. vulkanCommandBuffer->readWriteComputeStorageBufferBindings[i] = buffer->buffer;
  6881. VULKAN_INTERNAL_TrackBuffer(
  6882. vulkanCommandBuffer,
  6883. buffer);
  6884. }
  6885. }
  6886. static void VULKAN_BindComputePipeline(
  6887. SDL_GPUCommandBuffer *commandBuffer,
  6888. SDL_GPUComputePipeline *computePipeline)
  6889. {
  6890. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6891. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6892. VulkanComputePipeline *vulkanComputePipeline = (VulkanComputePipeline *)computePipeline;
  6893. renderer->vkCmdBindPipeline(
  6894. vulkanCommandBuffer->commandBuffer,
  6895. VK_PIPELINE_BIND_POINT_COMPUTE,
  6896. vulkanComputePipeline->pipeline);
  6897. vulkanCommandBuffer->currentComputePipeline = vulkanComputePipeline;
  6898. VULKAN_INTERNAL_TrackComputePipeline(vulkanCommandBuffer, vulkanComputePipeline);
  6899. // Acquire uniform buffers if necessary
  6900. for (Uint32 i = 0; i < vulkanComputePipeline->resourceLayout->numUniformBuffers; i += 1) {
  6901. if (vulkanCommandBuffer->computeUniformBuffers[i] == NULL) {
  6902. vulkanCommandBuffer->computeUniformBuffers[i] = VULKAN_INTERNAL_AcquireUniformBufferFromPool(
  6903. vulkanCommandBuffer);
  6904. }
  6905. }
  6906. // Mark binding as needed
  6907. vulkanCommandBuffer->needNewComputeReadWriteDescriptorSet = true;
  6908. vulkanCommandBuffer->needNewComputeReadOnlyDescriptorSet = true;
  6909. vulkanCommandBuffer->needNewComputeUniformDescriptorSet = true;
  6910. vulkanCommandBuffer->needNewComputeUniformOffsets = true;
  6911. }
  6912. static void VULKAN_BindComputeSamplers(
  6913. SDL_GPUCommandBuffer *commandBuffer,
  6914. Uint32 firstSlot,
  6915. const SDL_GPUTextureSamplerBinding *textureSamplerBindings,
  6916. Uint32 numBindings)
  6917. {
  6918. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6919. for (Uint32 i = 0; i < numBindings; i += 1) {
  6920. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)textureSamplerBindings[i].texture;
  6921. VulkanSampler *sampler = (VulkanSampler *)textureSamplerBindings[i].sampler;
  6922. if (vulkanCommandBuffer->computeSamplerBindings[firstSlot + i] != sampler->sampler) {
  6923. VULKAN_INTERNAL_TrackSampler(
  6924. vulkanCommandBuffer,
  6925. sampler);
  6926. vulkanCommandBuffer->computeSamplerBindings[firstSlot + i] = sampler->sampler;
  6927. vulkanCommandBuffer->needNewComputeReadOnlyDescriptorSet = true;
  6928. }
  6929. if (vulkanCommandBuffer->computeSamplerTextureViewBindings[firstSlot + i] != textureContainer->activeTexture->fullView) {
  6930. VULKAN_INTERNAL_TrackTexture(
  6931. vulkanCommandBuffer,
  6932. textureContainer->activeTexture);
  6933. vulkanCommandBuffer->computeSamplerTextureViewBindings[firstSlot + i] = textureContainer->activeTexture->fullView;
  6934. vulkanCommandBuffer->needNewComputeReadOnlyDescriptorSet = true;
  6935. }
  6936. }
  6937. }
  6938. static void VULKAN_BindComputeStorageTextures(
  6939. SDL_GPUCommandBuffer *commandBuffer,
  6940. Uint32 firstSlot,
  6941. SDL_GPUTexture *const *storageTextures,
  6942. Uint32 numBindings)
  6943. {
  6944. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6945. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6946. for (Uint32 i = 0; i < numBindings; i += 1) {
  6947. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)storageTextures[i];
  6948. if (vulkanCommandBuffer->readOnlyComputeStorageTextures[firstSlot + i] != textureContainer->activeTexture) {
  6949. /* If a different texture as in this slot, transition it back to its default usage */
  6950. if (vulkanCommandBuffer->readOnlyComputeStorageTextures[firstSlot + i] != NULL) {
  6951. VULKAN_INTERNAL_TextureTransitionToDefaultUsage(
  6952. renderer,
  6953. vulkanCommandBuffer,
  6954. VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ,
  6955. vulkanCommandBuffer->readOnlyComputeStorageTextures[firstSlot + i]);
  6956. }
  6957. /* Then transition the new texture and prepare it for binding */
  6958. VULKAN_INTERNAL_TextureTransitionFromDefaultUsage(
  6959. renderer,
  6960. vulkanCommandBuffer,
  6961. VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ,
  6962. textureContainer->activeTexture);
  6963. VULKAN_INTERNAL_TrackTexture(
  6964. vulkanCommandBuffer,
  6965. textureContainer->activeTexture);
  6966. vulkanCommandBuffer->readOnlyComputeStorageTextures[firstSlot + i] = textureContainer->activeTexture;
  6967. vulkanCommandBuffer->readOnlyComputeStorageTextureViewBindings[firstSlot + i] = textureContainer->activeTexture->fullView;
  6968. vulkanCommandBuffer->needNewComputeReadOnlyDescriptorSet = true;
  6969. }
  6970. }
  6971. }
  6972. static void VULKAN_BindComputeStorageBuffers(
  6973. SDL_GPUCommandBuffer *commandBuffer,
  6974. Uint32 firstSlot,
  6975. SDL_GPUBuffer *const *storageBuffers,
  6976. Uint32 numBindings)
  6977. {
  6978. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6979. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6980. for (Uint32 i = 0; i < numBindings; i += 1) {
  6981. VulkanBufferContainer *bufferContainer = (VulkanBufferContainer *)storageBuffers[i];
  6982. if (vulkanCommandBuffer->readOnlyComputeStorageBuffers[firstSlot + i] != bufferContainer->activeBuffer) {
  6983. /* If a different buffer was in this slot, transition it back to its default usage */
  6984. if (vulkanCommandBuffer->readOnlyComputeStorageBuffers[firstSlot + i] != NULL) {
  6985. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  6986. renderer,
  6987. vulkanCommandBuffer,
  6988. VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ,
  6989. vulkanCommandBuffer->readOnlyComputeStorageBuffers[firstSlot + i]);
  6990. }
  6991. /* Then transition the new buffer and prepare it for binding */
  6992. VULKAN_INTERNAL_BufferTransitionFromDefaultUsage(
  6993. renderer,
  6994. vulkanCommandBuffer,
  6995. VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ,
  6996. bufferContainer->activeBuffer);
  6997. VULKAN_INTERNAL_TrackBuffer(
  6998. vulkanCommandBuffer,
  6999. bufferContainer->activeBuffer);
  7000. vulkanCommandBuffer->readOnlyComputeStorageBuffers[firstSlot + i] = bufferContainer->activeBuffer;
  7001. vulkanCommandBuffer->readOnlyComputeStorageBufferBindings[firstSlot + i] = bufferContainer->activeBuffer->buffer;
  7002. vulkanCommandBuffer->needNewComputeReadOnlyDescriptorSet = true;
  7003. }
  7004. }
  7005. }
  7006. static void VULKAN_PushComputeUniformData(
  7007. SDL_GPUCommandBuffer *commandBuffer,
  7008. Uint32 slotIndex,
  7009. const void *data,
  7010. Uint32 length)
  7011. {
  7012. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7013. VULKAN_INTERNAL_PushUniformData(
  7014. vulkanCommandBuffer,
  7015. VULKAN_UNIFORM_BUFFER_STAGE_COMPUTE,
  7016. slotIndex,
  7017. data,
  7018. length);
  7019. }
  7020. static void VULKAN_INTERNAL_BindComputeDescriptorSets(
  7021. VulkanRenderer *renderer,
  7022. VulkanCommandBuffer *commandBuffer)
  7023. {
  7024. VulkanComputePipelineResourceLayout *resourceLayout;
  7025. DescriptorSetLayout *descriptorSetLayout;
  7026. VkWriteDescriptorSet writeDescriptorSets[
  7027. MAX_TEXTURE_SAMPLERS_PER_STAGE +
  7028. MAX_STORAGE_TEXTURES_PER_STAGE +
  7029. MAX_STORAGE_BUFFERS_PER_STAGE +
  7030. MAX_COMPUTE_WRITE_TEXTURES +
  7031. MAX_COMPUTE_WRITE_BUFFERS +
  7032. MAX_UNIFORM_BUFFERS_PER_STAGE];
  7033. VkDescriptorBufferInfo bufferInfos[MAX_STORAGE_BUFFERS_PER_STAGE + MAX_COMPUTE_WRITE_BUFFERS + MAX_UNIFORM_BUFFERS_PER_STAGE];
  7034. VkDescriptorImageInfo imageInfos[MAX_TEXTURE_SAMPLERS_PER_STAGE + MAX_STORAGE_TEXTURES_PER_STAGE + MAX_COMPUTE_WRITE_TEXTURES];
  7035. Uint32 dynamicOffsets[MAX_UNIFORM_BUFFERS_PER_STAGE];
  7036. Uint32 writeCount = 0;
  7037. Uint32 bufferInfoCount = 0;
  7038. Uint32 imageInfoCount = 0;
  7039. Uint32 dynamicOffsetCount = 0;
  7040. if (
  7041. !commandBuffer->needNewComputeReadOnlyDescriptorSet &&
  7042. !commandBuffer->needNewComputeReadWriteDescriptorSet &&
  7043. !commandBuffer->needNewComputeUniformDescriptorSet &&
  7044. !commandBuffer->needNewComputeUniformOffsets
  7045. ) {
  7046. return;
  7047. }
  7048. resourceLayout = commandBuffer->currentComputePipeline->resourceLayout;
  7049. if (commandBuffer->needNewComputeReadOnlyDescriptorSet) {
  7050. descriptorSetLayout = resourceLayout->descriptorSetLayouts[0];
  7051. commandBuffer->computeReadOnlyDescriptorSet = VULKAN_INTERNAL_FetchDescriptorSet(
  7052. renderer,
  7053. commandBuffer,
  7054. descriptorSetLayout);
  7055. for (Uint32 i = 0; i < resourceLayout->numSamplers; i += 1) {
  7056. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  7057. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  7058. currentWriteDescriptorSet->pNext = NULL;
  7059. currentWriteDescriptorSet->descriptorCount = 1;
  7060. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  7061. currentWriteDescriptorSet->dstArrayElement = 0;
  7062. currentWriteDescriptorSet->dstBinding = i;
  7063. currentWriteDescriptorSet->dstSet = commandBuffer->computeReadOnlyDescriptorSet;
  7064. currentWriteDescriptorSet->pTexelBufferView = NULL;
  7065. currentWriteDescriptorSet->pBufferInfo = NULL;
  7066. imageInfos[imageInfoCount].sampler = commandBuffer->computeSamplerBindings[i];
  7067. imageInfos[imageInfoCount].imageView = commandBuffer->computeSamplerTextureViewBindings[i];
  7068. imageInfos[imageInfoCount].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  7069. currentWriteDescriptorSet->pImageInfo = &imageInfos[imageInfoCount];
  7070. writeCount += 1;
  7071. imageInfoCount += 1;
  7072. }
  7073. for (Uint32 i = 0; i < resourceLayout->numReadonlyStorageTextures; i += 1) {
  7074. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  7075. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  7076. currentWriteDescriptorSet->pNext = NULL;
  7077. currentWriteDescriptorSet->descriptorCount = 1;
  7078. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; // Yes, we are declaring the readonly storage texture as a sampled image, because shaders are stupid.
  7079. currentWriteDescriptorSet->dstArrayElement = 0;
  7080. currentWriteDescriptorSet->dstBinding = resourceLayout->numSamplers + i;
  7081. currentWriteDescriptorSet->dstSet = commandBuffer->computeReadOnlyDescriptorSet;
  7082. currentWriteDescriptorSet->pTexelBufferView = NULL;
  7083. currentWriteDescriptorSet->pBufferInfo = NULL;
  7084. imageInfos[imageInfoCount].sampler = VK_NULL_HANDLE;
  7085. imageInfos[imageInfoCount].imageView = commandBuffer->readOnlyComputeStorageTextureViewBindings[i];
  7086. imageInfos[imageInfoCount].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
  7087. currentWriteDescriptorSet->pImageInfo = &imageInfos[imageInfoCount];
  7088. writeCount += 1;
  7089. imageInfoCount += 1;
  7090. }
  7091. for (Uint32 i = 0; i < resourceLayout->numReadonlyStorageBuffers; i += 1) {
  7092. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  7093. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  7094. currentWriteDescriptorSet->pNext = NULL;
  7095. currentWriteDescriptorSet->descriptorCount = 1;
  7096. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  7097. currentWriteDescriptorSet->dstArrayElement = 0;
  7098. currentWriteDescriptorSet->dstBinding = resourceLayout->numSamplers + resourceLayout->numReadonlyStorageTextures + i;
  7099. currentWriteDescriptorSet->dstSet = commandBuffer->computeReadOnlyDescriptorSet;
  7100. currentWriteDescriptorSet->pTexelBufferView = NULL;
  7101. currentWriteDescriptorSet->pImageInfo = NULL;
  7102. bufferInfos[bufferInfoCount].buffer = commandBuffer->readOnlyComputeStorageBufferBindings[i];
  7103. bufferInfos[bufferInfoCount].offset = 0;
  7104. bufferInfos[bufferInfoCount].range = VK_WHOLE_SIZE;
  7105. currentWriteDescriptorSet->pBufferInfo = &bufferInfos[bufferInfoCount];
  7106. writeCount += 1;
  7107. bufferInfoCount += 1;
  7108. }
  7109. commandBuffer->needNewComputeReadOnlyDescriptorSet = false;
  7110. }
  7111. if (commandBuffer->needNewComputeReadWriteDescriptorSet) {
  7112. descriptorSetLayout = resourceLayout->descriptorSetLayouts[1];
  7113. commandBuffer->computeReadWriteDescriptorSet = VULKAN_INTERNAL_FetchDescriptorSet(
  7114. renderer,
  7115. commandBuffer,
  7116. descriptorSetLayout);
  7117. for (Uint32 i = 0; i < resourceLayout->numReadWriteStorageTextures; i += 1) {
  7118. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  7119. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  7120. currentWriteDescriptorSet->pNext = NULL;
  7121. currentWriteDescriptorSet->descriptorCount = 1;
  7122. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  7123. currentWriteDescriptorSet->dstArrayElement = 0;
  7124. currentWriteDescriptorSet->dstBinding = i;
  7125. currentWriteDescriptorSet->dstSet = commandBuffer->computeReadWriteDescriptorSet;
  7126. currentWriteDescriptorSet->pTexelBufferView = NULL;
  7127. currentWriteDescriptorSet->pBufferInfo = NULL;
  7128. imageInfos[imageInfoCount].sampler = VK_NULL_HANDLE;
  7129. imageInfos[imageInfoCount].imageView = commandBuffer->readWriteComputeStorageTextureViewBindings[i];
  7130. imageInfos[imageInfoCount].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
  7131. currentWriteDescriptorSet->pImageInfo = &imageInfos[imageInfoCount];
  7132. writeCount += 1;
  7133. imageInfoCount += 1;
  7134. }
  7135. for (Uint32 i = 0; i < resourceLayout->numReadWriteStorageBuffers; i += 1) {
  7136. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  7137. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  7138. currentWriteDescriptorSet->pNext = NULL;
  7139. currentWriteDescriptorSet->descriptorCount = 1;
  7140. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  7141. currentWriteDescriptorSet->dstArrayElement = 0;
  7142. currentWriteDescriptorSet->dstBinding = resourceLayout->numReadWriteStorageTextures + i;
  7143. currentWriteDescriptorSet->dstSet = commandBuffer->computeReadWriteDescriptorSet;
  7144. currentWriteDescriptorSet->pTexelBufferView = NULL;
  7145. currentWriteDescriptorSet->pImageInfo = NULL;
  7146. bufferInfos[bufferInfoCount].buffer = commandBuffer->readWriteComputeStorageBufferBindings[i];
  7147. bufferInfos[bufferInfoCount].offset = 0;
  7148. bufferInfos[bufferInfoCount].range = VK_WHOLE_SIZE;
  7149. currentWriteDescriptorSet->pBufferInfo = &bufferInfos[bufferInfoCount];
  7150. writeCount += 1;
  7151. bufferInfoCount += 1;
  7152. }
  7153. commandBuffer->needNewComputeReadWriteDescriptorSet = false;
  7154. }
  7155. if (commandBuffer->needNewComputeUniformDescriptorSet) {
  7156. descriptorSetLayout = resourceLayout->descriptorSetLayouts[2];
  7157. commandBuffer->computeUniformDescriptorSet = VULKAN_INTERNAL_FetchDescriptorSet(
  7158. renderer,
  7159. commandBuffer,
  7160. descriptorSetLayout);
  7161. for (Uint32 i = 0; i < resourceLayout->numUniformBuffers; i += 1) {
  7162. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  7163. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  7164. currentWriteDescriptorSet->pNext = NULL;
  7165. currentWriteDescriptorSet->descriptorCount = 1;
  7166. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
  7167. currentWriteDescriptorSet->dstArrayElement = 0;
  7168. currentWriteDescriptorSet->dstBinding = i;
  7169. currentWriteDescriptorSet->dstSet = commandBuffer->computeUniformDescriptorSet;
  7170. currentWriteDescriptorSet->pTexelBufferView = NULL;
  7171. currentWriteDescriptorSet->pImageInfo = NULL;
  7172. bufferInfos[bufferInfoCount].buffer = commandBuffer->computeUniformBuffers[i]->buffer->buffer;
  7173. bufferInfos[bufferInfoCount].offset = 0;
  7174. bufferInfos[bufferInfoCount].range = MAX_UBO_SECTION_SIZE;
  7175. currentWriteDescriptorSet->pBufferInfo = &bufferInfos[bufferInfoCount];
  7176. writeCount += 1;
  7177. bufferInfoCount += 1;
  7178. }
  7179. commandBuffer->needNewComputeUniformDescriptorSet = false;
  7180. }
  7181. for (Uint32 i = 0; i < resourceLayout->numUniformBuffers; i += 1) {
  7182. dynamicOffsets[i] = commandBuffer->computeUniformBuffers[i]->drawOffset;
  7183. dynamicOffsetCount += 1;
  7184. }
  7185. renderer->vkUpdateDescriptorSets(
  7186. renderer->logicalDevice,
  7187. writeCount,
  7188. writeDescriptorSets,
  7189. 0,
  7190. NULL);
  7191. VkDescriptorSet sets[3];
  7192. sets[0] = commandBuffer->computeReadOnlyDescriptorSet;
  7193. sets[1] = commandBuffer->computeReadWriteDescriptorSet;
  7194. sets[2] = commandBuffer->computeUniformDescriptorSet;
  7195. renderer->vkCmdBindDescriptorSets(
  7196. commandBuffer->commandBuffer,
  7197. VK_PIPELINE_BIND_POINT_COMPUTE,
  7198. resourceLayout->pipelineLayout,
  7199. 0,
  7200. 3,
  7201. sets,
  7202. dynamicOffsetCount,
  7203. dynamicOffsets);
  7204. commandBuffer->needNewComputeUniformOffsets = false;
  7205. }
  7206. static void VULKAN_DispatchCompute(
  7207. SDL_GPUCommandBuffer *commandBuffer,
  7208. Uint32 groupcountX,
  7209. Uint32 groupcountY,
  7210. Uint32 groupcountZ)
  7211. {
  7212. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7213. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7214. VULKAN_INTERNAL_BindComputeDescriptorSets(renderer, vulkanCommandBuffer);
  7215. renderer->vkCmdDispatch(
  7216. vulkanCommandBuffer->commandBuffer,
  7217. groupcountX,
  7218. groupcountY,
  7219. groupcountZ);
  7220. }
  7221. static void VULKAN_DispatchComputeIndirect(
  7222. SDL_GPUCommandBuffer *commandBuffer,
  7223. SDL_GPUBuffer *buffer,
  7224. Uint32 offset)
  7225. {
  7226. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7227. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7228. VulkanBuffer *vulkanBuffer = ((VulkanBufferContainer *)buffer)->activeBuffer;
  7229. VULKAN_INTERNAL_BindComputeDescriptorSets(renderer, vulkanCommandBuffer);
  7230. renderer->vkCmdDispatchIndirect(
  7231. vulkanCommandBuffer->commandBuffer,
  7232. vulkanBuffer->buffer,
  7233. offset);
  7234. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, vulkanBuffer);
  7235. }
  7236. static void VULKAN_EndComputePass(
  7237. SDL_GPUCommandBuffer *commandBuffer)
  7238. {
  7239. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7240. Uint32 i;
  7241. for (i = 0; i < vulkanCommandBuffer->readWriteComputeStorageTextureSubresourceCount; i += 1) {
  7242. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7243. vulkanCommandBuffer->renderer,
  7244. vulkanCommandBuffer,
  7245. VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE,
  7246. vulkanCommandBuffer->readWriteComputeStorageTextureSubresources[i]);
  7247. vulkanCommandBuffer->readWriteComputeStorageTextureSubresources[i] = NULL;
  7248. }
  7249. vulkanCommandBuffer->readWriteComputeStorageTextureSubresourceCount = 0;
  7250. for (i = 0; i < MAX_COMPUTE_WRITE_BUFFERS; i += 1) {
  7251. if (vulkanCommandBuffer->readWriteComputeStorageBuffers[i] != NULL) {
  7252. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  7253. vulkanCommandBuffer->renderer,
  7254. vulkanCommandBuffer,
  7255. VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE,
  7256. vulkanCommandBuffer->readWriteComputeStorageBuffers[i]);
  7257. vulkanCommandBuffer->readWriteComputeStorageBuffers[i] = NULL;
  7258. }
  7259. }
  7260. for (i = 0; i < MAX_STORAGE_TEXTURES_PER_STAGE; i += 1) {
  7261. if (vulkanCommandBuffer->readOnlyComputeStorageTextures[i] != NULL) {
  7262. VULKAN_INTERNAL_TextureTransitionToDefaultUsage(
  7263. vulkanCommandBuffer->renderer,
  7264. vulkanCommandBuffer,
  7265. VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ,
  7266. vulkanCommandBuffer->readOnlyComputeStorageTextures[i]);
  7267. vulkanCommandBuffer->readOnlyComputeStorageTextures[i] = NULL;
  7268. }
  7269. }
  7270. for (i = 0; i < MAX_STORAGE_BUFFERS_PER_STAGE; i += 1) {
  7271. if (vulkanCommandBuffer->readOnlyComputeStorageBuffers[i] != NULL) {
  7272. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  7273. vulkanCommandBuffer->renderer,
  7274. vulkanCommandBuffer,
  7275. VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ,
  7276. vulkanCommandBuffer->readOnlyComputeStorageBuffers[i]);
  7277. vulkanCommandBuffer->readOnlyComputeStorageBuffers[i] = NULL;
  7278. }
  7279. }
  7280. // we don't need a barrier for sampler resources because sampler state is always the default if sampler bit is set
  7281. SDL_zeroa(vulkanCommandBuffer->computeSamplerTextureViewBindings);
  7282. SDL_zeroa(vulkanCommandBuffer->computeSamplerBindings);
  7283. SDL_zeroa(vulkanCommandBuffer->readWriteComputeStorageTextureViewBindings);
  7284. SDL_zeroa(vulkanCommandBuffer->readWriteComputeStorageBufferBindings);
  7285. vulkanCommandBuffer->currentComputePipeline = NULL;
  7286. vulkanCommandBuffer->computeReadOnlyDescriptorSet = VK_NULL_HANDLE;
  7287. vulkanCommandBuffer->computeReadWriteDescriptorSet = VK_NULL_HANDLE;
  7288. vulkanCommandBuffer->computeUniformDescriptorSet = VK_NULL_HANDLE;
  7289. }
  7290. static void *VULKAN_MapTransferBuffer(
  7291. SDL_GPURenderer *driverData,
  7292. SDL_GPUTransferBuffer *transferBuffer,
  7293. bool cycle)
  7294. {
  7295. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  7296. VulkanBufferContainer *transferBufferContainer = (VulkanBufferContainer *)transferBuffer;
  7297. if (
  7298. cycle &&
  7299. SDL_GetAtomicInt(&transferBufferContainer->activeBuffer->referenceCount) > 0) {
  7300. VULKAN_INTERNAL_CycleActiveBuffer(
  7301. renderer,
  7302. transferBufferContainer);
  7303. }
  7304. Uint8 *bufferPointer =
  7305. transferBufferContainer->activeBuffer->usedRegion->allocation->mapPointer +
  7306. transferBufferContainer->activeBuffer->usedRegion->resourceOffset;
  7307. return bufferPointer;
  7308. }
  7309. static void VULKAN_UnmapTransferBuffer(
  7310. SDL_GPURenderer *driverData,
  7311. SDL_GPUTransferBuffer *transferBuffer)
  7312. {
  7313. // no-op because transfer buffers are persistently mapped
  7314. (void)driverData;
  7315. (void)transferBuffer;
  7316. }
  7317. static void VULKAN_BeginCopyPass(
  7318. SDL_GPUCommandBuffer *commandBuffer)
  7319. {
  7320. // no-op
  7321. (void)commandBuffer;
  7322. }
  7323. static void VULKAN_UploadToTexture(
  7324. SDL_GPUCommandBuffer *commandBuffer,
  7325. const SDL_GPUTextureTransferInfo *source,
  7326. const SDL_GPUTextureRegion *destination,
  7327. bool cycle)
  7328. {
  7329. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7330. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7331. VulkanBufferContainer *transferBufferContainer = (VulkanBufferContainer *)source->transfer_buffer;
  7332. VulkanTextureContainer *vulkanTextureContainer = (VulkanTextureContainer *)destination->texture;
  7333. VulkanTextureSubresource *vulkanTextureSubresource;
  7334. VkBufferImageCopy imageCopy;
  7335. // Note that the transfer buffer does not need a barrier, as it is synced by the client
  7336. vulkanTextureSubresource = VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  7337. renderer,
  7338. vulkanCommandBuffer,
  7339. vulkanTextureContainer,
  7340. destination->layer,
  7341. destination->mip_level,
  7342. cycle,
  7343. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION);
  7344. imageCopy.imageExtent.width = destination->w;
  7345. imageCopy.imageExtent.height = destination->h;
  7346. imageCopy.imageExtent.depth = destination->d;
  7347. imageCopy.imageOffset.x = destination->x;
  7348. imageCopy.imageOffset.y = destination->y;
  7349. imageCopy.imageOffset.z = destination->z;
  7350. imageCopy.imageSubresource.aspectMask = vulkanTextureSubresource->parent->aspectFlags;
  7351. imageCopy.imageSubresource.baseArrayLayer = destination->layer;
  7352. imageCopy.imageSubresource.layerCount = 1;
  7353. imageCopy.imageSubresource.mipLevel = destination->mip_level;
  7354. imageCopy.bufferOffset = source->offset;
  7355. imageCopy.bufferRowLength = source->pixels_per_row;
  7356. imageCopy.bufferImageHeight = source->rows_per_layer;
  7357. renderer->vkCmdCopyBufferToImage(
  7358. vulkanCommandBuffer->commandBuffer,
  7359. transferBufferContainer->activeBuffer->buffer,
  7360. vulkanTextureSubresource->parent->image,
  7361. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  7362. 1,
  7363. &imageCopy);
  7364. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7365. renderer,
  7366. vulkanCommandBuffer,
  7367. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  7368. vulkanTextureSubresource);
  7369. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, transferBufferContainer->activeBuffer);
  7370. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, vulkanTextureSubresource->parent);
  7371. }
  7372. static void VULKAN_UploadToBuffer(
  7373. SDL_GPUCommandBuffer *commandBuffer,
  7374. const SDL_GPUTransferBufferLocation *source,
  7375. const SDL_GPUBufferRegion *destination,
  7376. bool cycle)
  7377. {
  7378. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7379. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7380. VulkanBufferContainer *transferBufferContainer = (VulkanBufferContainer *)source->transfer_buffer;
  7381. VulkanBufferContainer *bufferContainer = (VulkanBufferContainer *)destination->buffer;
  7382. VkBufferCopy bufferCopy;
  7383. // Note that the transfer buffer does not need a barrier, as it is synced by the client
  7384. VulkanBuffer *vulkanBuffer = VULKAN_INTERNAL_PrepareBufferForWrite(
  7385. renderer,
  7386. vulkanCommandBuffer,
  7387. bufferContainer,
  7388. cycle,
  7389. VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION);
  7390. bufferCopy.srcOffset = source->offset;
  7391. bufferCopy.dstOffset = destination->offset;
  7392. bufferCopy.size = destination->size;
  7393. renderer->vkCmdCopyBuffer(
  7394. vulkanCommandBuffer->commandBuffer,
  7395. transferBufferContainer->activeBuffer->buffer,
  7396. vulkanBuffer->buffer,
  7397. 1,
  7398. &bufferCopy);
  7399. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  7400. renderer,
  7401. vulkanCommandBuffer,
  7402. VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION,
  7403. vulkanBuffer);
  7404. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, transferBufferContainer->activeBuffer);
  7405. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, vulkanBuffer);
  7406. }
  7407. // Readback
  7408. static void VULKAN_DownloadFromTexture(
  7409. SDL_GPUCommandBuffer *commandBuffer,
  7410. const SDL_GPUTextureRegion *source,
  7411. const SDL_GPUTextureTransferInfo *destination)
  7412. {
  7413. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7414. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7415. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)source->texture;
  7416. VulkanTextureSubresource *vulkanTextureSubresource;
  7417. VulkanBufferContainer *transferBufferContainer = (VulkanBufferContainer *)destination->transfer_buffer;
  7418. VkBufferImageCopy imageCopy;
  7419. vulkanTextureSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  7420. textureContainer,
  7421. source->layer,
  7422. source->mip_level);
  7423. // Note that the transfer buffer does not need a barrier, as it is synced by the client
  7424. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  7425. renderer,
  7426. vulkanCommandBuffer,
  7427. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7428. vulkanTextureSubresource);
  7429. imageCopy.imageExtent.width = source->w;
  7430. imageCopy.imageExtent.height = source->h;
  7431. imageCopy.imageExtent.depth = source->d;
  7432. imageCopy.imageOffset.x = source->x;
  7433. imageCopy.imageOffset.y = source->y;
  7434. imageCopy.imageOffset.z = source->z;
  7435. imageCopy.imageSubresource.aspectMask = vulkanTextureSubresource->parent->aspectFlags;
  7436. imageCopy.imageSubresource.baseArrayLayer = source->layer;
  7437. imageCopy.imageSubresource.layerCount = 1;
  7438. imageCopy.imageSubresource.mipLevel = source->mip_level;
  7439. imageCopy.bufferOffset = destination->offset;
  7440. imageCopy.bufferRowLength = destination->pixels_per_row;
  7441. imageCopy.bufferImageHeight = destination->rows_per_layer;
  7442. renderer->vkCmdCopyImageToBuffer(
  7443. vulkanCommandBuffer->commandBuffer,
  7444. vulkanTextureSubresource->parent->image,
  7445. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  7446. transferBufferContainer->activeBuffer->buffer,
  7447. 1,
  7448. &imageCopy);
  7449. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7450. renderer,
  7451. vulkanCommandBuffer,
  7452. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7453. vulkanTextureSubresource);
  7454. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, transferBufferContainer->activeBuffer);
  7455. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, vulkanTextureSubresource->parent);
  7456. }
  7457. static void VULKAN_DownloadFromBuffer(
  7458. SDL_GPUCommandBuffer *commandBuffer,
  7459. const SDL_GPUBufferRegion *source,
  7460. const SDL_GPUTransferBufferLocation *destination)
  7461. {
  7462. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7463. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7464. VulkanBufferContainer *bufferContainer = (VulkanBufferContainer *)source->buffer;
  7465. VulkanBufferContainer *transferBufferContainer = (VulkanBufferContainer *)destination->transfer_buffer;
  7466. VkBufferCopy bufferCopy;
  7467. // Note that transfer buffer does not need a barrier, as it is synced by the client
  7468. VULKAN_INTERNAL_BufferTransitionFromDefaultUsage(
  7469. renderer,
  7470. vulkanCommandBuffer,
  7471. VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE,
  7472. bufferContainer->activeBuffer);
  7473. bufferCopy.srcOffset = source->offset;
  7474. bufferCopy.dstOffset = destination->offset;
  7475. bufferCopy.size = source->size;
  7476. renderer->vkCmdCopyBuffer(
  7477. vulkanCommandBuffer->commandBuffer,
  7478. bufferContainer->activeBuffer->buffer,
  7479. transferBufferContainer->activeBuffer->buffer,
  7480. 1,
  7481. &bufferCopy);
  7482. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  7483. renderer,
  7484. vulkanCommandBuffer,
  7485. VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE,
  7486. bufferContainer->activeBuffer);
  7487. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, transferBufferContainer->activeBuffer);
  7488. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, bufferContainer->activeBuffer);
  7489. }
  7490. static void VULKAN_CopyTextureToTexture(
  7491. SDL_GPUCommandBuffer *commandBuffer,
  7492. const SDL_GPUTextureLocation *source,
  7493. const SDL_GPUTextureLocation *destination,
  7494. Uint32 w,
  7495. Uint32 h,
  7496. Uint32 d,
  7497. bool cycle)
  7498. {
  7499. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7500. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7501. VulkanTextureSubresource *srcSubresource;
  7502. VulkanTextureSubresource *dstSubresource;
  7503. VkImageCopy imageCopy;
  7504. srcSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  7505. (VulkanTextureContainer *)source->texture,
  7506. source->layer,
  7507. source->mip_level);
  7508. dstSubresource = VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  7509. renderer,
  7510. vulkanCommandBuffer,
  7511. (VulkanTextureContainer *)destination->texture,
  7512. destination->layer,
  7513. destination->mip_level,
  7514. cycle,
  7515. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION);
  7516. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  7517. renderer,
  7518. vulkanCommandBuffer,
  7519. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7520. srcSubresource);
  7521. imageCopy.srcOffset.x = source->x;
  7522. imageCopy.srcOffset.y = source->y;
  7523. imageCopy.srcOffset.z = source->z;
  7524. imageCopy.srcSubresource.aspectMask = srcSubresource->parent->aspectFlags;
  7525. imageCopy.srcSubresource.baseArrayLayer = source->layer;
  7526. imageCopy.srcSubresource.layerCount = 1;
  7527. imageCopy.srcSubresource.mipLevel = source->mip_level;
  7528. imageCopy.dstOffset.x = destination->x;
  7529. imageCopy.dstOffset.y = destination->y;
  7530. imageCopy.dstOffset.z = destination->z;
  7531. imageCopy.dstSubresource.aspectMask = dstSubresource->parent->aspectFlags;
  7532. imageCopy.dstSubresource.baseArrayLayer = destination->layer;
  7533. imageCopy.dstSubresource.layerCount = 1;
  7534. imageCopy.dstSubresource.mipLevel = destination->mip_level;
  7535. imageCopy.extent.width = w;
  7536. imageCopy.extent.height = h;
  7537. imageCopy.extent.depth = d;
  7538. renderer->vkCmdCopyImage(
  7539. vulkanCommandBuffer->commandBuffer,
  7540. srcSubresource->parent->image,
  7541. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  7542. dstSubresource->parent->image,
  7543. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  7544. 1,
  7545. &imageCopy);
  7546. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7547. renderer,
  7548. vulkanCommandBuffer,
  7549. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7550. srcSubresource);
  7551. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7552. renderer,
  7553. vulkanCommandBuffer,
  7554. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  7555. dstSubresource);
  7556. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, srcSubresource->parent);
  7557. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, dstSubresource->parent);
  7558. }
  7559. static void VULKAN_CopyBufferToBuffer(
  7560. SDL_GPUCommandBuffer *commandBuffer,
  7561. const SDL_GPUBufferLocation *source,
  7562. const SDL_GPUBufferLocation *destination,
  7563. Uint32 size,
  7564. bool cycle)
  7565. {
  7566. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7567. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7568. VulkanBufferContainer *srcContainer = (VulkanBufferContainer *)source->buffer;
  7569. VulkanBufferContainer *dstContainer = (VulkanBufferContainer *)destination->buffer;
  7570. VkBufferCopy bufferCopy;
  7571. VulkanBuffer *dstBuffer = VULKAN_INTERNAL_PrepareBufferForWrite(
  7572. renderer,
  7573. vulkanCommandBuffer,
  7574. dstContainer,
  7575. cycle,
  7576. VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION);
  7577. VULKAN_INTERNAL_BufferTransitionFromDefaultUsage(
  7578. renderer,
  7579. vulkanCommandBuffer,
  7580. VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE,
  7581. srcContainer->activeBuffer);
  7582. bufferCopy.srcOffset = source->offset;
  7583. bufferCopy.dstOffset = destination->offset;
  7584. bufferCopy.size = size;
  7585. renderer->vkCmdCopyBuffer(
  7586. vulkanCommandBuffer->commandBuffer,
  7587. srcContainer->activeBuffer->buffer,
  7588. dstBuffer->buffer,
  7589. 1,
  7590. &bufferCopy);
  7591. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  7592. renderer,
  7593. vulkanCommandBuffer,
  7594. VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE,
  7595. srcContainer->activeBuffer);
  7596. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  7597. renderer,
  7598. vulkanCommandBuffer,
  7599. VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION,
  7600. dstBuffer);
  7601. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, srcContainer->activeBuffer);
  7602. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, dstBuffer);
  7603. }
  7604. static void VULKAN_GenerateMipmaps(
  7605. SDL_GPUCommandBuffer *commandBuffer,
  7606. SDL_GPUTexture *texture)
  7607. {
  7608. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7609. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7610. VulkanTextureContainer *container = (VulkanTextureContainer *)texture;
  7611. VulkanTextureSubresource *srcTextureSubresource;
  7612. VulkanTextureSubresource *dstTextureSubresource;
  7613. VkImageBlit blit;
  7614. // Blit each slice sequentially. Barriers, barriers everywhere!
  7615. for (Uint32 layerOrDepthIndex = 0; layerOrDepthIndex < container->header.info.layer_count_or_depth; layerOrDepthIndex += 1)
  7616. for (Uint32 level = 1; level < container->header.info.num_levels; level += 1) {
  7617. Uint32 layer = container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? 0 : layerOrDepthIndex;
  7618. Uint32 depth = container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? layerOrDepthIndex : 0;
  7619. Uint32 srcSubresourceIndex = VULKAN_INTERNAL_GetTextureSubresourceIndex(
  7620. level - 1,
  7621. layer,
  7622. container->header.info.num_levels);
  7623. Uint32 dstSubresourceIndex = VULKAN_INTERNAL_GetTextureSubresourceIndex(
  7624. level,
  7625. layer,
  7626. container->header.info.num_levels);
  7627. srcTextureSubresource = &container->activeTexture->subresources[srcSubresourceIndex];
  7628. dstTextureSubresource = &container->activeTexture->subresources[dstSubresourceIndex];
  7629. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  7630. renderer,
  7631. vulkanCommandBuffer,
  7632. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7633. srcTextureSubresource);
  7634. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  7635. renderer,
  7636. vulkanCommandBuffer,
  7637. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  7638. dstTextureSubresource);
  7639. blit.srcOffsets[0].x = 0;
  7640. blit.srcOffsets[0].y = 0;
  7641. blit.srcOffsets[0].z = depth;
  7642. blit.srcOffsets[1].x = container->header.info.width >> (level - 1);
  7643. blit.srcOffsets[1].y = container->header.info.height >> (level - 1);
  7644. blit.srcOffsets[1].z = depth + 1;
  7645. blit.dstOffsets[0].x = 0;
  7646. blit.dstOffsets[0].y = 0;
  7647. blit.dstOffsets[0].z = depth;
  7648. blit.dstOffsets[1].x = container->header.info.width >> level;
  7649. blit.dstOffsets[1].y = container->header.info.height >> level;
  7650. blit.dstOffsets[1].z = depth + 1;
  7651. blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  7652. blit.srcSubresource.baseArrayLayer = layer;
  7653. blit.srcSubresource.layerCount = 1;
  7654. blit.srcSubresource.mipLevel = level - 1;
  7655. blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  7656. blit.dstSubresource.baseArrayLayer = layer;
  7657. blit.dstSubresource.layerCount = 1;
  7658. blit.dstSubresource.mipLevel = level;
  7659. renderer->vkCmdBlitImage(
  7660. vulkanCommandBuffer->commandBuffer,
  7661. container->activeTexture->image,
  7662. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  7663. container->activeTexture->image,
  7664. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  7665. 1,
  7666. &blit,
  7667. VK_FILTER_LINEAR);
  7668. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7669. renderer,
  7670. vulkanCommandBuffer,
  7671. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7672. srcTextureSubresource);
  7673. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7674. renderer,
  7675. vulkanCommandBuffer,
  7676. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  7677. dstTextureSubresource);
  7678. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, srcTextureSubresource->parent);
  7679. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, dstTextureSubresource->parent);
  7680. }
  7681. }
  7682. static void VULKAN_EndCopyPass(
  7683. SDL_GPUCommandBuffer *commandBuffer)
  7684. {
  7685. // no-op
  7686. (void)commandBuffer;
  7687. }
  7688. static void VULKAN_Blit(
  7689. SDL_GPUCommandBuffer *commandBuffer,
  7690. const SDL_GPUBlitInfo *info)
  7691. {
  7692. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7693. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7694. TextureCommonHeader *srcHeader = (TextureCommonHeader *)info->source.texture;
  7695. TextureCommonHeader *dstHeader = (TextureCommonHeader *)info->destination.texture;
  7696. VkImageBlit region;
  7697. Uint32 srcLayer = srcHeader->info.type == SDL_GPU_TEXTURETYPE_3D ? 0 : info->source.layer_or_depth_plane;
  7698. Uint32 srcDepth = srcHeader->info.type == SDL_GPU_TEXTURETYPE_3D ? info->source.layer_or_depth_plane : 0;
  7699. Uint32 dstLayer = dstHeader->info.type == SDL_GPU_TEXTURETYPE_3D ? 0 : info->destination.layer_or_depth_plane;
  7700. Uint32 dstDepth = dstHeader->info.type == SDL_GPU_TEXTURETYPE_3D ? info->destination.layer_or_depth_plane : 0;
  7701. int32_t swap;
  7702. // Using BeginRenderPass to clear because vkCmdClearColorImage requires barriers anyway
  7703. if (info->load_op == SDL_GPU_LOADOP_CLEAR) {
  7704. SDL_GPUColorTargetInfo targetInfo;
  7705. SDL_zero(targetInfo);
  7706. targetInfo.texture = info->destination.texture;
  7707. targetInfo.mip_level = info->destination.mip_level;
  7708. targetInfo.layer_or_depth_plane = info->destination.layer_or_depth_plane;
  7709. targetInfo.load_op = SDL_GPU_LOADOP_CLEAR;
  7710. targetInfo.store_op = SDL_GPU_STOREOP_STORE;
  7711. targetInfo.clear_color = info->clear_color;
  7712. targetInfo.cycle = info->cycle;
  7713. VULKAN_BeginRenderPass(
  7714. commandBuffer,
  7715. &targetInfo,
  7716. 1,
  7717. NULL);
  7718. VULKAN_EndRenderPass(commandBuffer);
  7719. }
  7720. VulkanTextureSubresource *srcSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  7721. (VulkanTextureContainer *)info->source.texture,
  7722. srcLayer,
  7723. info->source.mip_level);
  7724. VulkanTextureSubresource *dstSubresource = VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  7725. renderer,
  7726. vulkanCommandBuffer,
  7727. (VulkanTextureContainer *)info->destination.texture,
  7728. dstLayer,
  7729. info->destination.mip_level,
  7730. info->cycle,
  7731. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION);
  7732. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  7733. renderer,
  7734. vulkanCommandBuffer,
  7735. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7736. srcSubresource);
  7737. region.srcSubresource.aspectMask = srcSubresource->parent->aspectFlags;
  7738. region.srcSubresource.baseArrayLayer = srcSubresource->layer;
  7739. region.srcSubresource.layerCount = 1;
  7740. region.srcSubresource.mipLevel = srcSubresource->level;
  7741. region.srcOffsets[0].x = info->source.x;
  7742. region.srcOffsets[0].y = info->source.y;
  7743. region.srcOffsets[0].z = srcDepth;
  7744. region.srcOffsets[1].x = info->source.x + info->source.w;
  7745. region.srcOffsets[1].y = info->source.y + info->source.h;
  7746. region.srcOffsets[1].z = srcDepth + 1;
  7747. if (info->flip_mode & SDL_FLIP_HORIZONTAL) {
  7748. // flip the x positions
  7749. swap = region.srcOffsets[0].x;
  7750. region.srcOffsets[0].x = region.srcOffsets[1].x;
  7751. region.srcOffsets[1].x = swap;
  7752. }
  7753. if (info->flip_mode & SDL_FLIP_VERTICAL) {
  7754. // flip the y positions
  7755. swap = region.srcOffsets[0].y;
  7756. region.srcOffsets[0].y = region.srcOffsets[1].y;
  7757. region.srcOffsets[1].y = swap;
  7758. }
  7759. region.dstSubresource.aspectMask = dstSubresource->parent->aspectFlags;
  7760. region.dstSubresource.baseArrayLayer = dstSubresource->layer;
  7761. region.dstSubresource.layerCount = 1;
  7762. region.dstSubresource.mipLevel = dstSubresource->level;
  7763. region.dstOffsets[0].x = info->destination.x;
  7764. region.dstOffsets[0].y = info->destination.y;
  7765. region.dstOffsets[0].z = dstDepth;
  7766. region.dstOffsets[1].x = info->destination.x + info->destination.w;
  7767. region.dstOffsets[1].y = info->destination.y + info->destination.h;
  7768. region.dstOffsets[1].z = dstDepth + 1;
  7769. renderer->vkCmdBlitImage(
  7770. vulkanCommandBuffer->commandBuffer,
  7771. srcSubresource->parent->image,
  7772. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  7773. dstSubresource->parent->image,
  7774. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  7775. 1,
  7776. &region,
  7777. SDLToVK_Filter[info->filter]);
  7778. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7779. renderer,
  7780. vulkanCommandBuffer,
  7781. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7782. srcSubresource);
  7783. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7784. renderer,
  7785. vulkanCommandBuffer,
  7786. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  7787. dstSubresource);
  7788. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, srcSubresource->parent);
  7789. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, dstSubresource->parent);
  7790. }
  7791. static bool VULKAN_INTERNAL_AllocateCommandBuffer(
  7792. VulkanRenderer *renderer,
  7793. VulkanCommandPool *vulkanCommandPool)
  7794. {
  7795. VkCommandBufferAllocateInfo allocateInfo;
  7796. VkResult vulkanResult;
  7797. VkCommandBuffer commandBufferHandle;
  7798. VulkanCommandBuffer *commandBuffer;
  7799. vulkanCommandPool->inactiveCommandBufferCapacity += 1;
  7800. vulkanCommandPool->inactiveCommandBuffers = SDL_realloc(
  7801. vulkanCommandPool->inactiveCommandBuffers,
  7802. sizeof(VulkanCommandBuffer *) *
  7803. vulkanCommandPool->inactiveCommandBufferCapacity);
  7804. allocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  7805. allocateInfo.pNext = NULL;
  7806. allocateInfo.commandPool = vulkanCommandPool->commandPool;
  7807. allocateInfo.commandBufferCount = 1;
  7808. allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  7809. vulkanResult = renderer->vkAllocateCommandBuffers(
  7810. renderer->logicalDevice,
  7811. &allocateInfo,
  7812. &commandBufferHandle);
  7813. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkAllocateCommandBuffers, false);
  7814. commandBuffer = SDL_malloc(sizeof(VulkanCommandBuffer));
  7815. commandBuffer->renderer = renderer;
  7816. commandBuffer->commandPool = vulkanCommandPool;
  7817. commandBuffer->commandBuffer = commandBufferHandle;
  7818. commandBuffer->inFlightFence = VK_NULL_HANDLE;
  7819. // Presentation tracking
  7820. commandBuffer->presentDataCapacity = 1;
  7821. commandBuffer->presentDataCount = 0;
  7822. commandBuffer->presentDatas = SDL_malloc(
  7823. commandBuffer->presentDataCapacity * sizeof(VulkanPresentData));
  7824. commandBuffer->waitSemaphoreCapacity = 1;
  7825. commandBuffer->waitSemaphoreCount = 0;
  7826. commandBuffer->waitSemaphores = SDL_malloc(
  7827. commandBuffer->waitSemaphoreCapacity * sizeof(VkSemaphore));
  7828. commandBuffer->signalSemaphoreCapacity = 1;
  7829. commandBuffer->signalSemaphoreCount = 0;
  7830. commandBuffer->signalSemaphores = SDL_malloc(
  7831. commandBuffer->signalSemaphoreCapacity * sizeof(VkSemaphore));
  7832. // Resource bind tracking
  7833. commandBuffer->needVertexBufferBind = false;
  7834. commandBuffer->needNewVertexResourceDescriptorSet = true;
  7835. commandBuffer->needNewVertexUniformDescriptorSet = true;
  7836. commandBuffer->needNewVertexUniformOffsets = true;
  7837. commandBuffer->needNewFragmentResourceDescriptorSet = true;
  7838. commandBuffer->needNewFragmentUniformDescriptorSet = true;
  7839. commandBuffer->needNewFragmentUniformOffsets = true;
  7840. commandBuffer->needNewComputeReadWriteDescriptorSet = true;
  7841. commandBuffer->needNewComputeReadOnlyDescriptorSet = true;
  7842. commandBuffer->needNewComputeUniformDescriptorSet = true;
  7843. commandBuffer->needNewComputeUniformOffsets = true;
  7844. commandBuffer->vertexResourceDescriptorSet = VK_NULL_HANDLE;
  7845. commandBuffer->vertexUniformDescriptorSet = VK_NULL_HANDLE;
  7846. commandBuffer->fragmentResourceDescriptorSet = VK_NULL_HANDLE;
  7847. commandBuffer->fragmentUniformDescriptorSet = VK_NULL_HANDLE;
  7848. commandBuffer->computeReadOnlyDescriptorSet = VK_NULL_HANDLE;
  7849. commandBuffer->computeReadWriteDescriptorSet = VK_NULL_HANDLE;
  7850. commandBuffer->computeUniformDescriptorSet = VK_NULL_HANDLE;
  7851. // Resource tracking
  7852. commandBuffer->usedBufferCapacity = 4;
  7853. commandBuffer->usedBufferCount = 0;
  7854. commandBuffer->usedBuffers = SDL_malloc(
  7855. commandBuffer->usedBufferCapacity * sizeof(VulkanBuffer *));
  7856. commandBuffer->usedTextureCapacity = 4;
  7857. commandBuffer->usedTextureCount = 0;
  7858. commandBuffer->usedTextures = SDL_malloc(
  7859. commandBuffer->usedTextureCapacity * sizeof(VulkanTexture *));
  7860. commandBuffer->usedSamplerCapacity = 4;
  7861. commandBuffer->usedSamplerCount = 0;
  7862. commandBuffer->usedSamplers = SDL_malloc(
  7863. commandBuffer->usedSamplerCapacity * sizeof(VulkanSampler *));
  7864. commandBuffer->usedGraphicsPipelineCapacity = 4;
  7865. commandBuffer->usedGraphicsPipelineCount = 0;
  7866. commandBuffer->usedGraphicsPipelines = SDL_malloc(
  7867. commandBuffer->usedGraphicsPipelineCapacity * sizeof(VulkanGraphicsPipeline *));
  7868. commandBuffer->usedComputePipelineCapacity = 4;
  7869. commandBuffer->usedComputePipelineCount = 0;
  7870. commandBuffer->usedComputePipelines = SDL_malloc(
  7871. commandBuffer->usedComputePipelineCapacity * sizeof(VulkanComputePipeline *));
  7872. commandBuffer->usedFramebufferCapacity = 4;
  7873. commandBuffer->usedFramebufferCount = 0;
  7874. commandBuffer->usedFramebuffers = SDL_malloc(
  7875. commandBuffer->usedFramebufferCapacity * sizeof(VulkanFramebuffer *));
  7876. commandBuffer->usedUniformBufferCapacity = 4;
  7877. commandBuffer->usedUniformBufferCount = 0;
  7878. commandBuffer->usedUniformBuffers = SDL_malloc(
  7879. commandBuffer->usedUniformBufferCapacity * sizeof(VulkanUniformBuffer *));
  7880. commandBuffer->swapchainRequested = false;
  7881. // Pool it!
  7882. vulkanCommandPool->inactiveCommandBuffers[vulkanCommandPool->inactiveCommandBufferCount] = commandBuffer;
  7883. vulkanCommandPool->inactiveCommandBufferCount += 1;
  7884. return true;
  7885. }
  7886. static VulkanCommandPool *VULKAN_INTERNAL_FetchCommandPool(
  7887. VulkanRenderer *renderer,
  7888. SDL_ThreadID threadID)
  7889. {
  7890. VulkanCommandPool *vulkanCommandPool = NULL;
  7891. VkCommandPoolCreateInfo commandPoolCreateInfo;
  7892. VkResult vulkanResult;
  7893. CommandPoolHashTableKey key;
  7894. key.threadID = threadID;
  7895. bool result = SDL_FindInHashTable(
  7896. renderer->commandPoolHashTable,
  7897. (const void *)&key,
  7898. (const void **)&vulkanCommandPool);
  7899. if (result) {
  7900. return vulkanCommandPool;
  7901. }
  7902. vulkanCommandPool = (VulkanCommandPool *)SDL_malloc(sizeof(VulkanCommandPool));
  7903. commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  7904. commandPoolCreateInfo.pNext = NULL;
  7905. commandPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  7906. commandPoolCreateInfo.queueFamilyIndex = renderer->queueFamilyIndex;
  7907. vulkanResult = renderer->vkCreateCommandPool(
  7908. renderer->logicalDevice,
  7909. &commandPoolCreateInfo,
  7910. NULL,
  7911. &vulkanCommandPool->commandPool);
  7912. if (vulkanResult != VK_SUCCESS) {
  7913. SDL_free(vulkanCommandPool);
  7914. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateCommandPool, NULL);
  7915. return NULL;
  7916. }
  7917. vulkanCommandPool->threadID = threadID;
  7918. vulkanCommandPool->inactiveCommandBufferCapacity = 0;
  7919. vulkanCommandPool->inactiveCommandBufferCount = 0;
  7920. vulkanCommandPool->inactiveCommandBuffers = NULL;
  7921. if (!VULKAN_INTERNAL_AllocateCommandBuffer(
  7922. renderer,
  7923. vulkanCommandPool)) {
  7924. VULKAN_INTERNAL_DestroyCommandPool(renderer, vulkanCommandPool);
  7925. return NULL;
  7926. }
  7927. CommandPoolHashTableKey *allocedKey = SDL_malloc(sizeof(CommandPoolHashTableKey));
  7928. allocedKey->threadID = threadID;
  7929. SDL_InsertIntoHashTable(
  7930. renderer->commandPoolHashTable,
  7931. (const void *)allocedKey,
  7932. (const void *)vulkanCommandPool, true);
  7933. return vulkanCommandPool;
  7934. }
  7935. static VulkanCommandBuffer *VULKAN_INTERNAL_GetInactiveCommandBufferFromPool(
  7936. VulkanRenderer *renderer,
  7937. SDL_ThreadID threadID)
  7938. {
  7939. VulkanCommandPool *commandPool =
  7940. VULKAN_INTERNAL_FetchCommandPool(renderer, threadID);
  7941. VulkanCommandBuffer *commandBuffer;
  7942. if (commandPool == NULL) {
  7943. return NULL;
  7944. }
  7945. if (commandPool->inactiveCommandBufferCount == 0) {
  7946. if (!VULKAN_INTERNAL_AllocateCommandBuffer(
  7947. renderer,
  7948. commandPool)) {
  7949. return NULL;
  7950. }
  7951. }
  7952. commandBuffer = commandPool->inactiveCommandBuffers[commandPool->inactiveCommandBufferCount - 1];
  7953. commandPool->inactiveCommandBufferCount -= 1;
  7954. return commandBuffer;
  7955. }
  7956. static SDL_GPUCommandBuffer *VULKAN_AcquireCommandBuffer(
  7957. SDL_GPURenderer *driverData)
  7958. {
  7959. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  7960. VkResult result;
  7961. Uint32 i;
  7962. SDL_ThreadID threadID = SDL_GetCurrentThreadID();
  7963. SDL_LockMutex(renderer->acquireCommandBufferLock);
  7964. VulkanCommandBuffer *commandBuffer =
  7965. VULKAN_INTERNAL_GetInactiveCommandBufferFromPool(renderer, threadID);
  7966. DescriptorSetCache *descriptorSetCache =
  7967. VULKAN_INTERNAL_AcquireDescriptorSetCache(renderer);
  7968. SDL_UnlockMutex(renderer->acquireCommandBufferLock);
  7969. if (commandBuffer == NULL) {
  7970. return NULL;
  7971. }
  7972. commandBuffer->descriptorSetCache = descriptorSetCache;
  7973. // Reset state
  7974. commandBuffer->currentComputePipeline = NULL;
  7975. commandBuffer->currentGraphicsPipeline = NULL;
  7976. SDL_zeroa(commandBuffer->colorAttachmentSubresources);
  7977. SDL_zeroa(commandBuffer->resolveAttachmentSubresources);
  7978. commandBuffer->depthStencilAttachmentSubresource = NULL;
  7979. commandBuffer->colorAttachmentSubresourceCount = 0;
  7980. commandBuffer->resolveAttachmentSubresourceCount = 0;
  7981. for (i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  7982. commandBuffer->vertexUniformBuffers[i] = NULL;
  7983. commandBuffer->fragmentUniformBuffers[i] = NULL;
  7984. commandBuffer->computeUniformBuffers[i] = NULL;
  7985. }
  7986. commandBuffer->needVertexBufferBind = false;
  7987. commandBuffer->needNewVertexResourceDescriptorSet = true;
  7988. commandBuffer->needNewVertexUniformDescriptorSet = true;
  7989. commandBuffer->needNewVertexUniformOffsets = true;
  7990. commandBuffer->needNewFragmentResourceDescriptorSet = true;
  7991. commandBuffer->needNewFragmentUniformDescriptorSet = true;
  7992. commandBuffer->needNewFragmentUniformOffsets = true;
  7993. commandBuffer->needNewComputeReadOnlyDescriptorSet = true;
  7994. commandBuffer->needNewComputeUniformDescriptorSet = true;
  7995. commandBuffer->needNewComputeUniformOffsets = true;
  7996. commandBuffer->vertexResourceDescriptorSet = VK_NULL_HANDLE;
  7997. commandBuffer->vertexUniformDescriptorSet = VK_NULL_HANDLE;
  7998. commandBuffer->fragmentResourceDescriptorSet = VK_NULL_HANDLE;
  7999. commandBuffer->fragmentUniformDescriptorSet = VK_NULL_HANDLE;
  8000. commandBuffer->computeReadOnlyDescriptorSet = VK_NULL_HANDLE;
  8001. commandBuffer->computeReadWriteDescriptorSet = VK_NULL_HANDLE;
  8002. commandBuffer->computeUniformDescriptorSet = VK_NULL_HANDLE;
  8003. SDL_zeroa(commandBuffer->vertexBuffers);
  8004. SDL_zeroa(commandBuffer->vertexBufferOffsets);
  8005. commandBuffer->vertexBufferCount = 0;
  8006. SDL_zeroa(commandBuffer->vertexSamplerTextureViewBindings);
  8007. SDL_zeroa(commandBuffer->vertexSamplerBindings);
  8008. SDL_zeroa(commandBuffer->vertexStorageTextureViewBindings);
  8009. SDL_zeroa(commandBuffer->vertexStorageBufferBindings);
  8010. SDL_zeroa(commandBuffer->fragmentSamplerTextureViewBindings);
  8011. SDL_zeroa(commandBuffer->fragmentSamplerBindings);
  8012. SDL_zeroa(commandBuffer->fragmentStorageTextureViewBindings);
  8013. SDL_zeroa(commandBuffer->fragmentStorageBufferBindings);
  8014. SDL_zeroa(commandBuffer->readWriteComputeStorageTextureSubresources);
  8015. commandBuffer->readWriteComputeStorageTextureSubresourceCount = 0;
  8016. SDL_zeroa(commandBuffer->readWriteComputeStorageBuffers);
  8017. SDL_zeroa(commandBuffer->computeSamplerTextureViewBindings);
  8018. SDL_zeroa(commandBuffer->computeSamplerBindings);
  8019. SDL_zeroa(commandBuffer->readOnlyComputeStorageTextureViewBindings);
  8020. SDL_zeroa(commandBuffer->readOnlyComputeStorageBufferBindings);
  8021. SDL_zeroa(commandBuffer->readOnlyComputeStorageTextures);
  8022. SDL_zeroa(commandBuffer->readOnlyComputeStorageBuffers);
  8023. commandBuffer->autoReleaseFence = true;
  8024. commandBuffer->swapchainRequested = false;
  8025. commandBuffer->isDefrag = 0;
  8026. /* Reset the command buffer here to avoid resets being called
  8027. * from a separate thread than where the command buffer was acquired
  8028. */
  8029. result = renderer->vkResetCommandBuffer(
  8030. commandBuffer->commandBuffer,
  8031. VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT);
  8032. CHECK_VULKAN_ERROR_AND_RETURN(result, vkResetCommandBuffer, NULL);
  8033. if (!VULKAN_INTERNAL_BeginCommandBuffer(renderer, commandBuffer)) {
  8034. return NULL;
  8035. }
  8036. return (SDL_GPUCommandBuffer *)commandBuffer;
  8037. }
  8038. static bool VULKAN_QueryFence(
  8039. SDL_GPURenderer *driverData,
  8040. SDL_GPUFence *fence)
  8041. {
  8042. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8043. VkResult result;
  8044. result = renderer->vkGetFenceStatus(
  8045. renderer->logicalDevice,
  8046. ((VulkanFenceHandle *)fence)->fence);
  8047. if (result == VK_SUCCESS) {
  8048. return true;
  8049. } else if (result == VK_NOT_READY) {
  8050. return false;
  8051. } else {
  8052. SET_ERROR_AND_RETURN("vkGetFenceStatus: %s", VkErrorMessages(result), false);
  8053. }
  8054. }
  8055. static void VULKAN_INTERNAL_ReturnFenceToPool(
  8056. VulkanRenderer *renderer,
  8057. VulkanFenceHandle *fenceHandle)
  8058. {
  8059. SDL_LockMutex(renderer->fencePool.lock);
  8060. EXPAND_ARRAY_IF_NEEDED(
  8061. renderer->fencePool.availableFences,
  8062. VulkanFenceHandle *,
  8063. renderer->fencePool.availableFenceCount + 1,
  8064. renderer->fencePool.availableFenceCapacity,
  8065. renderer->fencePool.availableFenceCapacity * 2);
  8066. renderer->fencePool.availableFences[renderer->fencePool.availableFenceCount] = fenceHandle;
  8067. renderer->fencePool.availableFenceCount += 1;
  8068. SDL_UnlockMutex(renderer->fencePool.lock);
  8069. }
  8070. static void VULKAN_ReleaseFence(
  8071. SDL_GPURenderer *driverData,
  8072. SDL_GPUFence *fence)
  8073. {
  8074. VulkanFenceHandle *handle = (VulkanFenceHandle *)fence;
  8075. if (SDL_AtomicDecRef(&handle->referenceCount)) {
  8076. VULKAN_INTERNAL_ReturnFenceToPool((VulkanRenderer *)driverData, handle);
  8077. }
  8078. }
  8079. static WindowData *VULKAN_INTERNAL_FetchWindowData(
  8080. SDL_Window *window)
  8081. {
  8082. SDL_PropertiesID properties = SDL_GetWindowProperties(window);
  8083. return (WindowData *)SDL_GetPointerProperty(properties, WINDOW_PROPERTY_DATA, NULL);
  8084. }
  8085. static bool VULKAN_INTERNAL_OnWindowResize(void *userdata, SDL_Event *e)
  8086. {
  8087. SDL_Window *w = (SDL_Window *)userdata;
  8088. WindowData *data;
  8089. if (e->type == SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED && e->window.windowID == SDL_GetWindowID(w)) {
  8090. data = VULKAN_INTERNAL_FetchWindowData(w);
  8091. data->needsSwapchainRecreate = true;
  8092. data->swapchainCreateWidth = e->window.data1;
  8093. data->swapchainCreateHeight = e->window.data2;
  8094. }
  8095. return true;
  8096. }
  8097. static bool VULKAN_SupportsSwapchainComposition(
  8098. SDL_GPURenderer *driverData,
  8099. SDL_Window *window,
  8100. SDL_GPUSwapchainComposition swapchainComposition)
  8101. {
  8102. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8103. WindowData *windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8104. VkSurfaceKHR surface;
  8105. SwapchainSupportDetails supportDetails;
  8106. bool result = false;
  8107. if (windowData == NULL) {
  8108. SET_STRING_ERROR_AND_RETURN("Must claim window before querying swapchain composition support!", false);
  8109. }
  8110. surface = windowData->surface;
  8111. if (!surface) {
  8112. SET_STRING_ERROR_AND_RETURN("Window has no Vulkan surface", false);
  8113. }
  8114. if (VULKAN_INTERNAL_QuerySwapchainSupport(
  8115. renderer,
  8116. renderer->physicalDevice,
  8117. surface,
  8118. &supportDetails)) {
  8119. result = VULKAN_INTERNAL_VerifySwapSurfaceFormat(
  8120. SwapchainCompositionToFormat[swapchainComposition],
  8121. SwapchainCompositionToColorSpace[swapchainComposition],
  8122. supportDetails.formats,
  8123. supportDetails.formatsLength);
  8124. if (!result) {
  8125. // Let's try again with the fallback format...
  8126. result = VULKAN_INTERNAL_VerifySwapSurfaceFormat(
  8127. SwapchainCompositionToFallbackFormat[swapchainComposition],
  8128. SwapchainCompositionToColorSpace[swapchainComposition],
  8129. supportDetails.formats,
  8130. supportDetails.formatsLength);
  8131. }
  8132. SDL_free(supportDetails.formats);
  8133. SDL_free(supportDetails.presentModes);
  8134. }
  8135. return result;
  8136. }
  8137. static bool VULKAN_SupportsPresentMode(
  8138. SDL_GPURenderer *driverData,
  8139. SDL_Window *window,
  8140. SDL_GPUPresentMode presentMode)
  8141. {
  8142. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8143. WindowData *windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8144. VkSurfaceKHR surface;
  8145. SwapchainSupportDetails supportDetails;
  8146. bool result = false;
  8147. if (windowData == NULL) {
  8148. SET_STRING_ERROR_AND_RETURN("Must claim window before querying present mode support!", false);
  8149. }
  8150. surface = windowData->surface;
  8151. if (!surface) {
  8152. SET_STRING_ERROR_AND_RETURN("Window has no Vulkan surface", false);
  8153. }
  8154. if (VULKAN_INTERNAL_QuerySwapchainSupport(
  8155. renderer,
  8156. renderer->physicalDevice,
  8157. surface,
  8158. &supportDetails)) {
  8159. result = VULKAN_INTERNAL_VerifySwapPresentMode(
  8160. SDLToVK_PresentMode[presentMode],
  8161. supportDetails.presentModes,
  8162. supportDetails.presentModesLength);
  8163. SDL_free(supportDetails.formats);
  8164. SDL_free(supportDetails.presentModes);
  8165. }
  8166. return result;
  8167. }
  8168. static bool VULKAN_ClaimWindow(
  8169. SDL_GPURenderer *driverData,
  8170. SDL_Window *window)
  8171. {
  8172. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8173. WindowData *windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8174. if (windowData == NULL) {
  8175. windowData = SDL_calloc(1, sizeof(WindowData));
  8176. windowData->window = window;
  8177. windowData->presentMode = SDL_GPU_PRESENTMODE_VSYNC;
  8178. windowData->swapchainComposition = SDL_GPU_SWAPCHAINCOMPOSITION_SDR;
  8179. // On non-Apple platforms the swapchain capability currentExtent can be different from the window,
  8180. // so we have to query the window size.
  8181. #ifndef SDL_PLATFORM_APPLE
  8182. int w, h;
  8183. SDL_SyncWindow(window);
  8184. SDL_GetWindowSizeInPixels(window, &w, &h);
  8185. windowData->swapchainCreateWidth = w;
  8186. windowData->swapchainCreateHeight = h;
  8187. #endif
  8188. SDL_VideoDevice *videoDevice = SDL_GetVideoDevice();
  8189. if (!videoDevice)
  8190. {
  8191. SDL_SetError("No video device found!");
  8192. SDL_free(windowData);
  8193. return false;
  8194. }
  8195. if (!videoDevice->Vulkan_CreateSurface)
  8196. {
  8197. SDL_SetError("Video device does not have Vulkan_CreateSurface implemented!");
  8198. SDL_free(windowData);
  8199. return false;
  8200. }
  8201. // Each window must have its own surface.
  8202. if (!videoDevice->Vulkan_CreateSurface(
  8203. videoDevice,
  8204. windowData->window,
  8205. renderer->instance,
  8206. NULL, // FIXME: VAllocationCallbacks
  8207. &windowData->surface)) {
  8208. SDL_SetError("Failed to create Vulkan surface!");
  8209. SDL_free(windowData);
  8210. return false;
  8211. }
  8212. Uint32 createSwapchainResult = VULKAN_INTERNAL_CreateSwapchain(renderer, windowData);
  8213. if (createSwapchainResult == 1) {
  8214. SDL_SetPointerProperty(SDL_GetWindowProperties(window), WINDOW_PROPERTY_DATA, windowData);
  8215. SDL_LockMutex(renderer->windowLock);
  8216. if (renderer->claimedWindowCount >= renderer->claimedWindowCapacity) {
  8217. renderer->claimedWindowCapacity *= 2;
  8218. renderer->claimedWindows = SDL_realloc(
  8219. renderer->claimedWindows,
  8220. renderer->claimedWindowCapacity * sizeof(WindowData *));
  8221. }
  8222. renderer->claimedWindows[renderer->claimedWindowCount] = windowData;
  8223. renderer->claimedWindowCount += 1;
  8224. SDL_UnlockMutex(renderer->windowLock);
  8225. SDL_AddWindowEventWatch(SDL_WINDOW_EVENT_WATCH_NORMAL, VULKAN_INTERNAL_OnWindowResize, window);
  8226. return true;
  8227. } else if (createSwapchainResult == VULKAN_INTERNAL_TRY_AGAIN) {
  8228. windowData->needsSwapchainRecreate = true;
  8229. return true;
  8230. } else {
  8231. // Failed to create swapchain, destroy surface and free data
  8232. renderer->vkDestroySurfaceKHR(
  8233. renderer->instance,
  8234. windowData->surface,
  8235. NULL);
  8236. SDL_free(windowData);
  8237. return false;
  8238. }
  8239. } else {
  8240. SET_STRING_ERROR_AND_RETURN("Window already claimed!", false);
  8241. }
  8242. }
  8243. static void VULKAN_ReleaseWindow(
  8244. SDL_GPURenderer *driverData,
  8245. SDL_Window *window)
  8246. {
  8247. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8248. WindowData *windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8249. Uint32 i;
  8250. if (windowData == NULL) {
  8251. return;
  8252. }
  8253. VULKAN_Wait(driverData);
  8254. for (i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  8255. if (windowData->inFlightFences[i] != NULL) {
  8256. VULKAN_ReleaseFence(
  8257. driverData,
  8258. windowData->inFlightFences[i]);
  8259. }
  8260. }
  8261. VULKAN_INTERNAL_DestroySwapchain(
  8262. (VulkanRenderer *)driverData,
  8263. windowData);
  8264. renderer->vkDestroySurfaceKHR(
  8265. renderer->instance,
  8266. windowData->surface,
  8267. NULL);
  8268. windowData->surface = VK_NULL_HANDLE;
  8269. SDL_LockMutex(renderer->windowLock);
  8270. for (i = 0; i < renderer->claimedWindowCount; i += 1) {
  8271. if (renderer->claimedWindows[i]->window == window) {
  8272. renderer->claimedWindows[i] = renderer->claimedWindows[renderer->claimedWindowCount - 1];
  8273. renderer->claimedWindowCount -= 1;
  8274. break;
  8275. }
  8276. }
  8277. SDL_UnlockMutex(renderer->windowLock);
  8278. SDL_free(windowData);
  8279. SDL_ClearProperty(SDL_GetWindowProperties(window), WINDOW_PROPERTY_DATA);
  8280. SDL_RemoveWindowEventWatch(SDL_WINDOW_EVENT_WATCH_NORMAL, VULKAN_INTERNAL_OnWindowResize, window);
  8281. }
  8282. static Uint32 VULKAN_INTERNAL_RecreateSwapchain(
  8283. VulkanRenderer *renderer,
  8284. WindowData *windowData)
  8285. {
  8286. Uint32 i;
  8287. if (!VULKAN_Wait((SDL_GPURenderer *)renderer)) {
  8288. return false;
  8289. }
  8290. for (i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  8291. if (windowData->inFlightFences[i] != NULL) {
  8292. VULKAN_ReleaseFence(
  8293. (SDL_GPURenderer *)renderer,
  8294. windowData->inFlightFences[i]);
  8295. windowData->inFlightFences[i] = NULL;
  8296. }
  8297. }
  8298. #ifdef SDL_VIDEO_DRIVER_PRIVATE
  8299. // Private platforms also invalidate the window, so don't try to preserve the surface/swapchain
  8300. VULKAN_INTERNAL_DestroySwapchain(renderer, windowData);
  8301. #else
  8302. VULKAN_INTERNAL_DestroySwapchainImage(renderer, windowData);
  8303. #endif
  8304. return VULKAN_INTERNAL_CreateSwapchain(renderer, windowData);
  8305. }
  8306. static bool VULKAN_WaitForSwapchain(
  8307. SDL_GPURenderer *driverData,
  8308. SDL_Window *window)
  8309. {
  8310. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8311. WindowData *windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8312. if (windowData == NULL) {
  8313. SET_STRING_ERROR_AND_RETURN("Cannot wait for a swapchain from an unclaimed window!", false);
  8314. }
  8315. if (windowData->inFlightFences[windowData->frameCounter] != NULL) {
  8316. if (!VULKAN_WaitForFences(
  8317. driverData,
  8318. true,
  8319. &windowData->inFlightFences[windowData->frameCounter],
  8320. 1)) {
  8321. return false;
  8322. }
  8323. }
  8324. return true;
  8325. }
  8326. static bool VULKAN_INTERNAL_AcquireSwapchainTexture(
  8327. bool block,
  8328. SDL_GPUCommandBuffer *commandBuffer,
  8329. SDL_Window *window,
  8330. SDL_GPUTexture **swapchainTexture,
  8331. Uint32 *swapchainTextureWidth,
  8332. Uint32 *swapchainTextureHeight)
  8333. {
  8334. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  8335. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  8336. Uint32 swapchainImageIndex;
  8337. WindowData *windowData;
  8338. VkResult acquireResult = VK_SUCCESS;
  8339. VulkanTextureContainer *swapchainTextureContainer = NULL;
  8340. VulkanPresentData *presentData;
  8341. *swapchainTexture = NULL;
  8342. if (swapchainTextureWidth) {
  8343. *swapchainTextureWidth = 0;
  8344. }
  8345. if (swapchainTextureHeight) {
  8346. *swapchainTextureHeight = 0;
  8347. }
  8348. windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8349. if (windowData == NULL) {
  8350. SET_STRING_ERROR_AND_RETURN("Cannot acquire a swapchain texture from an unclaimed window!", false);
  8351. }
  8352. // The command buffer is flagged for cleanup when the swapchain is requested as a cleanup timing mechanism
  8353. vulkanCommandBuffer->swapchainRequested = true;
  8354. if (window->flags & SDL_WINDOW_HIDDEN) {
  8355. // Edge case, texture is filled in with NULL but not an error
  8356. return true;
  8357. }
  8358. if (windowData->needsSurfaceRecreate) {
  8359. SDL_VideoDevice *videoDevice = SDL_GetVideoDevice();
  8360. SDL_assert(videoDevice);
  8361. SDL_assert(videoDevice->Vulkan_CreateSurface);
  8362. renderer->vkDestroySurfaceKHR(
  8363. renderer->instance,
  8364. windowData->surface,
  8365. NULL);
  8366. if (!videoDevice->Vulkan_CreateSurface(
  8367. videoDevice,
  8368. windowData->window,
  8369. renderer->instance,
  8370. NULL, // FIXME: VAllocationCallbacks
  8371. &windowData->surface)) {
  8372. SET_STRING_ERROR_AND_RETURN("Failed to recreate Vulkan surface!", false);
  8373. }
  8374. }
  8375. // If window data marked as needing swapchain recreate, try to recreate
  8376. if (windowData->needsSwapchainRecreate) {
  8377. Uint32 recreateSwapchainResult = VULKAN_INTERNAL_RecreateSwapchain(renderer, windowData);
  8378. if (!recreateSwapchainResult) {
  8379. return false;
  8380. } else if (recreateSwapchainResult == VULKAN_INTERNAL_TRY_AGAIN) {
  8381. // Edge case, texture is filled in with NULL but not an error
  8382. if (windowData->inFlightFences[windowData->frameCounter] != NULL) {
  8383. VULKAN_ReleaseFence(
  8384. (SDL_GPURenderer *)renderer,
  8385. windowData->inFlightFences[windowData->frameCounter]);
  8386. windowData->inFlightFences[windowData->frameCounter] = NULL;
  8387. }
  8388. return true;
  8389. }
  8390. // Unset this flag until after the swapchain has been recreated to let VULKAN_INTERNAL_CreateSwapchain()
  8391. // know whether it needs to pass the old swapchain or not.
  8392. windowData->needsSurfaceRecreate = false;
  8393. }
  8394. if (windowData->inFlightFences[windowData->frameCounter] != NULL) {
  8395. if (block) {
  8396. // If we are blocking, just wait for the fence!
  8397. if (!VULKAN_WaitForFences(
  8398. (SDL_GPURenderer *)renderer,
  8399. true,
  8400. &windowData->inFlightFences[windowData->frameCounter],
  8401. 1)) {
  8402. return false;
  8403. }
  8404. } else {
  8405. // If we are not blocking and the least recent fence is not signaled,
  8406. // return true to indicate that there is no error but rendering should be skipped.
  8407. if (!VULKAN_QueryFence(
  8408. (SDL_GPURenderer *)renderer,
  8409. windowData->inFlightFences[windowData->frameCounter])) {
  8410. return true;
  8411. }
  8412. }
  8413. VULKAN_ReleaseFence(
  8414. (SDL_GPURenderer *)renderer,
  8415. windowData->inFlightFences[windowData->frameCounter]);
  8416. windowData->inFlightFences[windowData->frameCounter] = NULL;
  8417. }
  8418. // Finally, try to acquire!
  8419. while (true) {
  8420. acquireResult = renderer->vkAcquireNextImageKHR(
  8421. renderer->logicalDevice,
  8422. windowData->swapchain,
  8423. SDL_MAX_UINT64,
  8424. windowData->imageAvailableSemaphore[windowData->frameCounter],
  8425. VK_NULL_HANDLE,
  8426. &swapchainImageIndex);
  8427. if (acquireResult == VK_SUCCESS || acquireResult == VK_SUBOPTIMAL_KHR) {
  8428. break; // we got the next image!
  8429. }
  8430. // If acquisition is invalid, let's try to recreate
  8431. Uint32 recreateSwapchainResult = VULKAN_INTERNAL_RecreateSwapchain(renderer, windowData);
  8432. if (!recreateSwapchainResult) {
  8433. return false;
  8434. } else if (recreateSwapchainResult == VULKAN_INTERNAL_TRY_AGAIN) {
  8435. // Edge case, texture is filled in with NULL but not an error
  8436. return true;
  8437. }
  8438. }
  8439. if (swapchainTextureWidth) {
  8440. *swapchainTextureWidth = windowData->width;
  8441. }
  8442. if (swapchainTextureHeight) {
  8443. *swapchainTextureHeight = windowData->height;
  8444. }
  8445. swapchainTextureContainer = &windowData->textureContainers[swapchainImageIndex];
  8446. // We need a special execution dependency with pWaitDstStageMask or image transition can start before acquire finishes
  8447. VkImageMemoryBarrier imageBarrier;
  8448. imageBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  8449. imageBarrier.pNext = NULL;
  8450. imageBarrier.srcAccessMask = 0;
  8451. imageBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  8452. imageBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  8453. imageBarrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  8454. imageBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  8455. imageBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  8456. imageBarrier.image = swapchainTextureContainer->activeTexture->image;
  8457. imageBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  8458. imageBarrier.subresourceRange.baseMipLevel = 0;
  8459. imageBarrier.subresourceRange.levelCount = 1;
  8460. imageBarrier.subresourceRange.baseArrayLayer = 0;
  8461. imageBarrier.subresourceRange.layerCount = 1;
  8462. renderer->vkCmdPipelineBarrier(
  8463. vulkanCommandBuffer->commandBuffer,
  8464. VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
  8465. VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
  8466. 0,
  8467. 0,
  8468. NULL,
  8469. 0,
  8470. NULL,
  8471. 1,
  8472. &imageBarrier);
  8473. // Set up present struct
  8474. if (vulkanCommandBuffer->presentDataCount == vulkanCommandBuffer->presentDataCapacity) {
  8475. vulkanCommandBuffer->presentDataCapacity += 1;
  8476. vulkanCommandBuffer->presentDatas = SDL_realloc(
  8477. vulkanCommandBuffer->presentDatas,
  8478. vulkanCommandBuffer->presentDataCapacity * sizeof(VulkanPresentData));
  8479. }
  8480. presentData = &vulkanCommandBuffer->presentDatas[vulkanCommandBuffer->presentDataCount];
  8481. vulkanCommandBuffer->presentDataCount += 1;
  8482. presentData->windowData = windowData;
  8483. presentData->swapchainImageIndex = swapchainImageIndex;
  8484. // Set up present semaphores
  8485. if (vulkanCommandBuffer->waitSemaphoreCount == vulkanCommandBuffer->waitSemaphoreCapacity) {
  8486. vulkanCommandBuffer->waitSemaphoreCapacity += 1;
  8487. vulkanCommandBuffer->waitSemaphores = SDL_realloc(
  8488. vulkanCommandBuffer->waitSemaphores,
  8489. vulkanCommandBuffer->waitSemaphoreCapacity * sizeof(VkSemaphore));
  8490. }
  8491. vulkanCommandBuffer->waitSemaphores[vulkanCommandBuffer->waitSemaphoreCount] =
  8492. windowData->imageAvailableSemaphore[windowData->frameCounter];
  8493. vulkanCommandBuffer->waitSemaphoreCount += 1;
  8494. if (vulkanCommandBuffer->signalSemaphoreCount == vulkanCommandBuffer->signalSemaphoreCapacity) {
  8495. vulkanCommandBuffer->signalSemaphoreCapacity += 1;
  8496. vulkanCommandBuffer->signalSemaphores = SDL_realloc(
  8497. vulkanCommandBuffer->signalSemaphores,
  8498. vulkanCommandBuffer->signalSemaphoreCapacity * sizeof(VkSemaphore));
  8499. }
  8500. vulkanCommandBuffer->signalSemaphores[vulkanCommandBuffer->signalSemaphoreCount] =
  8501. windowData->renderFinishedSemaphore[swapchainImageIndex];
  8502. vulkanCommandBuffer->signalSemaphoreCount += 1;
  8503. *swapchainTexture = (SDL_GPUTexture *)swapchainTextureContainer;
  8504. return true;
  8505. }
  8506. static bool VULKAN_AcquireSwapchainTexture(
  8507. SDL_GPUCommandBuffer *command_buffer,
  8508. SDL_Window *window,
  8509. SDL_GPUTexture **swapchain_texture,
  8510. Uint32 *swapchain_texture_width,
  8511. Uint32 *swapchain_texture_height
  8512. ) {
  8513. return VULKAN_INTERNAL_AcquireSwapchainTexture(
  8514. false,
  8515. command_buffer,
  8516. window,
  8517. swapchain_texture,
  8518. swapchain_texture_width,
  8519. swapchain_texture_height);
  8520. }
  8521. static bool VULKAN_WaitAndAcquireSwapchainTexture(
  8522. SDL_GPUCommandBuffer *command_buffer,
  8523. SDL_Window *window,
  8524. SDL_GPUTexture **swapchain_texture,
  8525. Uint32 *swapchain_texture_width,
  8526. Uint32 *swapchain_texture_height
  8527. ) {
  8528. return VULKAN_INTERNAL_AcquireSwapchainTexture(
  8529. true,
  8530. command_buffer,
  8531. window,
  8532. swapchain_texture,
  8533. swapchain_texture_width,
  8534. swapchain_texture_height);
  8535. }
  8536. static SDL_GPUTextureFormat VULKAN_GetSwapchainTextureFormat(
  8537. SDL_GPURenderer *driverData,
  8538. SDL_Window *window)
  8539. {
  8540. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8541. WindowData *windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8542. if (windowData == NULL) {
  8543. SET_STRING_ERROR_AND_RETURN("Cannot get swapchain format, window has not been claimed!", SDL_GPU_TEXTUREFORMAT_INVALID);
  8544. }
  8545. return SwapchainCompositionToSDLFormat(
  8546. windowData->swapchainComposition,
  8547. windowData->usingFallbackFormat);
  8548. }
  8549. static bool VULKAN_SetSwapchainParameters(
  8550. SDL_GPURenderer *driverData,
  8551. SDL_Window *window,
  8552. SDL_GPUSwapchainComposition swapchainComposition,
  8553. SDL_GPUPresentMode presentMode)
  8554. {
  8555. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8556. WindowData *windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8557. if (windowData == NULL) {
  8558. SET_STRING_ERROR_AND_RETURN("Cannot set swapchain parameters on unclaimed window!", false);
  8559. }
  8560. if (!VULKAN_SupportsSwapchainComposition(driverData, window, swapchainComposition)) {
  8561. SET_STRING_ERROR_AND_RETURN("Swapchain composition not supported!", false);
  8562. }
  8563. if (!VULKAN_SupportsPresentMode(driverData, window, presentMode)) {
  8564. SET_STRING_ERROR_AND_RETURN("Present mode not supported!", false);
  8565. }
  8566. windowData->presentMode = presentMode;
  8567. windowData->swapchainComposition = swapchainComposition;
  8568. Uint32 recreateSwapchainResult = VULKAN_INTERNAL_RecreateSwapchain(renderer, windowData);
  8569. if (!recreateSwapchainResult) {
  8570. return false;
  8571. } else if (recreateSwapchainResult == VULKAN_INTERNAL_TRY_AGAIN) {
  8572. // Edge case, swapchain extent is (0, 0) but this is not an error
  8573. windowData->needsSwapchainRecreate = true;
  8574. return true;
  8575. }
  8576. return true;
  8577. }
  8578. static bool VULKAN_SetAllowedFramesInFlight(
  8579. SDL_GPURenderer *driverData,
  8580. Uint32 allowedFramesInFlight)
  8581. {
  8582. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8583. renderer->allowedFramesInFlight = allowedFramesInFlight;
  8584. for (Uint32 i = 0; i < renderer->claimedWindowCount; i += 1) {
  8585. WindowData *windowData = renderer->claimedWindows[i];
  8586. Uint32 recreateResult = VULKAN_INTERNAL_RecreateSwapchain(renderer, windowData);
  8587. if (!recreateResult) {
  8588. return false;
  8589. } else if (recreateResult == VULKAN_INTERNAL_TRY_AGAIN) {
  8590. // Edge case, swapchain extent is (0, 0) but this is not an error
  8591. windowData->needsSwapchainRecreate = true;
  8592. }
  8593. }
  8594. return true;
  8595. }
  8596. // Submission structure
  8597. static VulkanFenceHandle *VULKAN_INTERNAL_AcquireFenceFromPool(
  8598. VulkanRenderer *renderer)
  8599. {
  8600. VulkanFenceHandle *handle;
  8601. VkFenceCreateInfo fenceCreateInfo;
  8602. VkFence fence;
  8603. VkResult vulkanResult;
  8604. if (renderer->fencePool.availableFenceCount == 0) {
  8605. // Create fence
  8606. fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  8607. fenceCreateInfo.pNext = NULL;
  8608. fenceCreateInfo.flags = 0;
  8609. vulkanResult = renderer->vkCreateFence(
  8610. renderer->logicalDevice,
  8611. &fenceCreateInfo,
  8612. NULL,
  8613. &fence);
  8614. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateFence, NULL);
  8615. handle = SDL_malloc(sizeof(VulkanFenceHandle));
  8616. handle->fence = fence;
  8617. SDL_SetAtomicInt(&handle->referenceCount, 0);
  8618. return handle;
  8619. }
  8620. SDL_LockMutex(renderer->fencePool.lock);
  8621. handle = renderer->fencePool.availableFences[renderer->fencePool.availableFenceCount - 1];
  8622. renderer->fencePool.availableFenceCount -= 1;
  8623. vulkanResult = renderer->vkResetFences(
  8624. renderer->logicalDevice,
  8625. 1,
  8626. &handle->fence);
  8627. SDL_UnlockMutex(renderer->fencePool.lock);
  8628. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkResetFences, NULL);
  8629. return handle;
  8630. }
  8631. static void VULKAN_INTERNAL_PerformPendingDestroys(
  8632. VulkanRenderer *renderer)
  8633. {
  8634. SDL_LockMutex(renderer->disposeLock);
  8635. for (Sint32 i = renderer->texturesToDestroyCount - 1; i >= 0; i -= 1) {
  8636. if (SDL_GetAtomicInt(&renderer->texturesToDestroy[i]->referenceCount) == 0) {
  8637. VULKAN_INTERNAL_DestroyTexture(
  8638. renderer,
  8639. renderer->texturesToDestroy[i]);
  8640. renderer->texturesToDestroy[i] = renderer->texturesToDestroy[renderer->texturesToDestroyCount - 1];
  8641. renderer->texturesToDestroyCount -= 1;
  8642. }
  8643. }
  8644. for (Sint32 i = renderer->buffersToDestroyCount - 1; i >= 0; i -= 1) {
  8645. if (SDL_GetAtomicInt(&renderer->buffersToDestroy[i]->referenceCount) == 0) {
  8646. VULKAN_INTERNAL_DestroyBuffer(
  8647. renderer,
  8648. renderer->buffersToDestroy[i]);
  8649. renderer->buffersToDestroy[i] = renderer->buffersToDestroy[renderer->buffersToDestroyCount - 1];
  8650. renderer->buffersToDestroyCount -= 1;
  8651. }
  8652. }
  8653. for (Sint32 i = renderer->graphicsPipelinesToDestroyCount - 1; i >= 0; i -= 1) {
  8654. if (SDL_GetAtomicInt(&renderer->graphicsPipelinesToDestroy[i]->referenceCount) == 0) {
  8655. VULKAN_INTERNAL_DestroyGraphicsPipeline(
  8656. renderer,
  8657. renderer->graphicsPipelinesToDestroy[i]);
  8658. renderer->graphicsPipelinesToDestroy[i] = renderer->graphicsPipelinesToDestroy[renderer->graphicsPipelinesToDestroyCount - 1];
  8659. renderer->graphicsPipelinesToDestroyCount -= 1;
  8660. }
  8661. }
  8662. for (Sint32 i = renderer->computePipelinesToDestroyCount - 1; i >= 0; i -= 1) {
  8663. if (SDL_GetAtomicInt(&renderer->computePipelinesToDestroy[i]->referenceCount) == 0) {
  8664. VULKAN_INTERNAL_DestroyComputePipeline(
  8665. renderer,
  8666. renderer->computePipelinesToDestroy[i]);
  8667. renderer->computePipelinesToDestroy[i] = renderer->computePipelinesToDestroy[renderer->computePipelinesToDestroyCount - 1];
  8668. renderer->computePipelinesToDestroyCount -= 1;
  8669. }
  8670. }
  8671. for (Sint32 i = renderer->shadersToDestroyCount - 1; i >= 0; i -= 1) {
  8672. if (SDL_GetAtomicInt(&renderer->shadersToDestroy[i]->referenceCount) == 0) {
  8673. VULKAN_INTERNAL_DestroyShader(
  8674. renderer,
  8675. renderer->shadersToDestroy[i]);
  8676. renderer->shadersToDestroy[i] = renderer->shadersToDestroy[renderer->shadersToDestroyCount - 1];
  8677. renderer->shadersToDestroyCount -= 1;
  8678. }
  8679. }
  8680. for (Sint32 i = renderer->samplersToDestroyCount - 1; i >= 0; i -= 1) {
  8681. if (SDL_GetAtomicInt(&renderer->samplersToDestroy[i]->referenceCount) == 0) {
  8682. VULKAN_INTERNAL_DestroySampler(
  8683. renderer,
  8684. renderer->samplersToDestroy[i]);
  8685. renderer->samplersToDestroy[i] = renderer->samplersToDestroy[renderer->samplersToDestroyCount - 1];
  8686. renderer->samplersToDestroyCount -= 1;
  8687. }
  8688. }
  8689. for (Sint32 i = renderer->framebuffersToDestroyCount - 1; i >= 0; i -= 1) {
  8690. if (SDL_GetAtomicInt(&renderer->framebuffersToDestroy[i]->referenceCount) == 0) {
  8691. VULKAN_INTERNAL_DestroyFramebuffer(
  8692. renderer,
  8693. renderer->framebuffersToDestroy[i]);
  8694. renderer->framebuffersToDestroy[i] = renderer->framebuffersToDestroy[renderer->framebuffersToDestroyCount - 1];
  8695. renderer->framebuffersToDestroyCount -= 1;
  8696. }
  8697. }
  8698. SDL_UnlockMutex(renderer->disposeLock);
  8699. }
  8700. static void VULKAN_INTERNAL_CleanCommandBuffer(
  8701. VulkanRenderer *renderer,
  8702. VulkanCommandBuffer *commandBuffer,
  8703. bool cancel)
  8704. {
  8705. if (commandBuffer->autoReleaseFence) {
  8706. VULKAN_ReleaseFence(
  8707. (SDL_GPURenderer *)renderer,
  8708. (SDL_GPUFence *)commandBuffer->inFlightFence);
  8709. commandBuffer->inFlightFence = NULL;
  8710. }
  8711. // Uniform buffers are now available
  8712. SDL_LockMutex(renderer->acquireUniformBufferLock);
  8713. for (Sint32 i = 0; i < commandBuffer->usedUniformBufferCount; i += 1) {
  8714. VULKAN_INTERNAL_ReturnUniformBufferToPool(
  8715. renderer,
  8716. commandBuffer->usedUniformBuffers[i]);
  8717. }
  8718. commandBuffer->usedUniformBufferCount = 0;
  8719. SDL_UnlockMutex(renderer->acquireUniformBufferLock);
  8720. // Decrement reference counts
  8721. for (Sint32 i = 0; i < commandBuffer->usedBufferCount; i += 1) {
  8722. (void)SDL_AtomicDecRef(&commandBuffer->usedBuffers[i]->referenceCount);
  8723. }
  8724. commandBuffer->usedBufferCount = 0;
  8725. for (Sint32 i = 0; i < commandBuffer->usedTextureCount; i += 1) {
  8726. (void)SDL_AtomicDecRef(&commandBuffer->usedTextures[i]->referenceCount);
  8727. }
  8728. commandBuffer->usedTextureCount = 0;
  8729. for (Sint32 i = 0; i < commandBuffer->usedSamplerCount; i += 1) {
  8730. (void)SDL_AtomicDecRef(&commandBuffer->usedSamplers[i]->referenceCount);
  8731. }
  8732. commandBuffer->usedSamplerCount = 0;
  8733. for (Sint32 i = 0; i < commandBuffer->usedGraphicsPipelineCount; i += 1) {
  8734. (void)SDL_AtomicDecRef(&commandBuffer->usedGraphicsPipelines[i]->referenceCount);
  8735. }
  8736. commandBuffer->usedGraphicsPipelineCount = 0;
  8737. for (Sint32 i = 0; i < commandBuffer->usedComputePipelineCount; i += 1) {
  8738. (void)SDL_AtomicDecRef(&commandBuffer->usedComputePipelines[i]->referenceCount);
  8739. }
  8740. commandBuffer->usedComputePipelineCount = 0;
  8741. for (Sint32 i = 0; i < commandBuffer->usedFramebufferCount; i += 1) {
  8742. (void)SDL_AtomicDecRef(&commandBuffer->usedFramebuffers[i]->referenceCount);
  8743. }
  8744. commandBuffer->usedFramebufferCount = 0;
  8745. // Reset presentation data
  8746. commandBuffer->presentDataCount = 0;
  8747. commandBuffer->waitSemaphoreCount = 0;
  8748. commandBuffer->signalSemaphoreCount = 0;
  8749. commandBuffer->swapchainRequested = false;
  8750. // Reset defrag state
  8751. if (commandBuffer->isDefrag) {
  8752. renderer->defragInProgress = 0;
  8753. }
  8754. // Return command buffer to pool
  8755. SDL_LockMutex(renderer->acquireCommandBufferLock);
  8756. if (commandBuffer->commandPool->inactiveCommandBufferCount == commandBuffer->commandPool->inactiveCommandBufferCapacity) {
  8757. commandBuffer->commandPool->inactiveCommandBufferCapacity += 1;
  8758. commandBuffer->commandPool->inactiveCommandBuffers = SDL_realloc(
  8759. commandBuffer->commandPool->inactiveCommandBuffers,
  8760. commandBuffer->commandPool->inactiveCommandBufferCapacity * sizeof(VulkanCommandBuffer *));
  8761. }
  8762. commandBuffer->commandPool->inactiveCommandBuffers[commandBuffer->commandPool->inactiveCommandBufferCount] = commandBuffer;
  8763. commandBuffer->commandPool->inactiveCommandBufferCount += 1;
  8764. // Release descriptor set cache
  8765. VULKAN_INTERNAL_ReturnDescriptorSetCacheToPool(
  8766. renderer,
  8767. commandBuffer->descriptorSetCache);
  8768. commandBuffer->descriptorSetCache = NULL;
  8769. SDL_UnlockMutex(renderer->acquireCommandBufferLock);
  8770. // Remove this command buffer from the submitted list
  8771. if (!cancel) {
  8772. for (Uint32 i = 0; i < renderer->submittedCommandBufferCount; i += 1) {
  8773. if (renderer->submittedCommandBuffers[i] == commandBuffer) {
  8774. renderer->submittedCommandBuffers[i] = renderer->submittedCommandBuffers[renderer->submittedCommandBufferCount - 1];
  8775. renderer->submittedCommandBufferCount -= 1;
  8776. }
  8777. }
  8778. }
  8779. }
  8780. static bool VULKAN_WaitForFences(
  8781. SDL_GPURenderer *driverData,
  8782. bool waitAll,
  8783. SDL_GPUFence *const *fences,
  8784. Uint32 numFences)
  8785. {
  8786. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8787. VkFence *vkFences = SDL_stack_alloc(VkFence, numFences);
  8788. VkResult result;
  8789. for (Uint32 i = 0; i < numFences; i += 1) {
  8790. vkFences[i] = ((VulkanFenceHandle *)fences[i])->fence;
  8791. }
  8792. result = renderer->vkWaitForFences(
  8793. renderer->logicalDevice,
  8794. numFences,
  8795. vkFences,
  8796. waitAll,
  8797. SDL_MAX_UINT64);
  8798. CHECK_VULKAN_ERROR_AND_RETURN(result, vkWaitForFences, false);
  8799. SDL_stack_free(vkFences);
  8800. SDL_LockMutex(renderer->submitLock);
  8801. for (Sint32 i = renderer->submittedCommandBufferCount - 1; i >= 0; i -= 1) {
  8802. result = renderer->vkGetFenceStatus(
  8803. renderer->logicalDevice,
  8804. renderer->submittedCommandBuffers[i]->inFlightFence->fence);
  8805. if (result == VK_SUCCESS) {
  8806. VULKAN_INTERNAL_CleanCommandBuffer(
  8807. renderer,
  8808. renderer->submittedCommandBuffers[i],
  8809. false);
  8810. }
  8811. }
  8812. VULKAN_INTERNAL_PerformPendingDestroys(renderer);
  8813. SDL_UnlockMutex(renderer->submitLock);
  8814. return true;
  8815. }
  8816. static bool VULKAN_Wait(
  8817. SDL_GPURenderer *driverData)
  8818. {
  8819. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8820. VulkanCommandBuffer *commandBuffer;
  8821. VkResult result;
  8822. Sint32 i;
  8823. SDL_LockMutex(renderer->submitLock);
  8824. result = renderer->vkDeviceWaitIdle(renderer->logicalDevice);
  8825. if (result != VK_SUCCESS) {
  8826. if (renderer->debugMode) {
  8827. SDL_LogError(SDL_LOG_CATEGORY_GPU, "%s %s", "vkDeviceWaitIdle", VkErrorMessages(result));
  8828. }
  8829. SDL_SetError("%s %s", "vkDeviceWaitIdle", VkErrorMessages(result));
  8830. SDL_UnlockMutex(renderer->submitLock);
  8831. return false;
  8832. }
  8833. for (i = renderer->submittedCommandBufferCount - 1; i >= 0; i -= 1) {
  8834. commandBuffer = renderer->submittedCommandBuffers[i];
  8835. VULKAN_INTERNAL_CleanCommandBuffer(renderer, commandBuffer, false);
  8836. }
  8837. VULKAN_INTERNAL_PerformPendingDestroys(renderer);
  8838. SDL_UnlockMutex(renderer->submitLock);
  8839. return true;
  8840. }
  8841. static SDL_GPUFence *VULKAN_SubmitAndAcquireFence(
  8842. SDL_GPUCommandBuffer *commandBuffer)
  8843. {
  8844. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  8845. vulkanCommandBuffer->autoReleaseFence = false;
  8846. if (!VULKAN_Submit(commandBuffer)) {
  8847. return NULL;
  8848. }
  8849. return (SDL_GPUFence *)vulkanCommandBuffer->inFlightFence;
  8850. }
  8851. static void VULKAN_INTERNAL_ReleaseCommandBuffer(VulkanCommandBuffer *vulkanCommandBuffer)
  8852. {
  8853. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  8854. if (renderer->submittedCommandBufferCount + 1 >= renderer->submittedCommandBufferCapacity) {
  8855. renderer->submittedCommandBufferCapacity = renderer->submittedCommandBufferCount + 1;
  8856. renderer->submittedCommandBuffers = SDL_realloc(
  8857. renderer->submittedCommandBuffers,
  8858. sizeof(VulkanCommandBuffer *) * renderer->submittedCommandBufferCapacity);
  8859. }
  8860. renderer->submittedCommandBuffers[renderer->submittedCommandBufferCount] = vulkanCommandBuffer;
  8861. renderer->submittedCommandBufferCount += 1;
  8862. }
  8863. static bool VULKAN_Submit(
  8864. SDL_GPUCommandBuffer *commandBuffer)
  8865. {
  8866. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  8867. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  8868. VkSubmitInfo submitInfo;
  8869. VkPresentInfoKHR presentInfo;
  8870. VulkanPresentData *presentData;
  8871. VkResult vulkanResult, presentResult = VK_SUCCESS;
  8872. VkPipelineStageFlags waitStages[MAX_PRESENT_COUNT];
  8873. Uint32 swapchainImageIndex;
  8874. VulkanTextureSubresource *swapchainTextureSubresource;
  8875. VulkanMemorySubAllocator *allocator;
  8876. bool performCleanups =
  8877. (renderer->claimedWindowCount > 0 && vulkanCommandBuffer->swapchainRequested) ||
  8878. renderer->claimedWindowCount == 0;
  8879. SDL_LockMutex(renderer->submitLock);
  8880. // FIXME: Can this just be permanent?
  8881. for (Uint32 i = 0; i < MAX_PRESENT_COUNT; i += 1) {
  8882. waitStages[i] = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  8883. }
  8884. for (Uint32 j = 0; j < vulkanCommandBuffer->presentDataCount; j += 1) {
  8885. swapchainImageIndex = vulkanCommandBuffer->presentDatas[j].swapchainImageIndex;
  8886. swapchainTextureSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  8887. &vulkanCommandBuffer->presentDatas[j].windowData->textureContainers[swapchainImageIndex],
  8888. 0,
  8889. 0);
  8890. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  8891. renderer,
  8892. vulkanCommandBuffer,
  8893. VULKAN_TEXTURE_USAGE_MODE_PRESENT,
  8894. swapchainTextureSubresource);
  8895. }
  8896. if (performCleanups &&
  8897. renderer->allocationsToDefragCount > 0 &&
  8898. !renderer->defragInProgress) {
  8899. if (!VULKAN_INTERNAL_DefragmentMemory(renderer, vulkanCommandBuffer))
  8900. {
  8901. SDL_LogError(SDL_LOG_CATEGORY_GPU, "%s", "Failed to defragment memory, likely OOM!");
  8902. }
  8903. }
  8904. if (!VULKAN_INTERNAL_EndCommandBuffer(renderer, vulkanCommandBuffer)) {
  8905. SDL_UnlockMutex(renderer->submitLock);
  8906. return false;
  8907. }
  8908. vulkanCommandBuffer->inFlightFence = VULKAN_INTERNAL_AcquireFenceFromPool(renderer);
  8909. if (vulkanCommandBuffer->inFlightFence == NULL) {
  8910. SDL_UnlockMutex(renderer->submitLock);
  8911. return false;
  8912. }
  8913. // Command buffer has a reference to the in-flight fence
  8914. (void)SDL_AtomicIncRef(&vulkanCommandBuffer->inFlightFence->referenceCount);
  8915. submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  8916. submitInfo.pNext = NULL;
  8917. submitInfo.commandBufferCount = 1;
  8918. submitInfo.pCommandBuffers = &vulkanCommandBuffer->commandBuffer;
  8919. submitInfo.pWaitDstStageMask = waitStages;
  8920. submitInfo.pWaitSemaphores = vulkanCommandBuffer->waitSemaphores;
  8921. submitInfo.waitSemaphoreCount = vulkanCommandBuffer->waitSemaphoreCount;
  8922. submitInfo.pSignalSemaphores = vulkanCommandBuffer->signalSemaphores;
  8923. submitInfo.signalSemaphoreCount = vulkanCommandBuffer->signalSemaphoreCount;
  8924. vulkanResult = renderer->vkQueueSubmit(
  8925. renderer->unifiedQueue,
  8926. 1,
  8927. &submitInfo,
  8928. vulkanCommandBuffer->inFlightFence->fence);
  8929. if (vulkanResult != VK_SUCCESS) {
  8930. SDL_UnlockMutex(renderer->submitLock);
  8931. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkQueueSubmit, false);
  8932. }
  8933. // Present, if applicable
  8934. for (Uint32 j = 0; j < vulkanCommandBuffer->presentDataCount; j += 1) {
  8935. presentData = &vulkanCommandBuffer->presentDatas[j];
  8936. presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
  8937. presentInfo.pNext = NULL;
  8938. presentInfo.pWaitSemaphores =
  8939. &presentData->windowData->renderFinishedSemaphore[presentData->swapchainImageIndex];
  8940. presentInfo.waitSemaphoreCount = 1;
  8941. presentInfo.pSwapchains = &presentData->windowData->swapchain;
  8942. presentInfo.swapchainCount = 1;
  8943. presentInfo.pImageIndices = &presentData->swapchainImageIndex;
  8944. presentInfo.pResults = NULL;
  8945. presentResult = renderer->vkQueuePresentKHR(
  8946. renderer->unifiedQueue,
  8947. &presentInfo);
  8948. if (presentResult == VK_SUCCESS || presentResult == VK_SUBOPTIMAL_KHR || presentResult == VK_ERROR_OUT_OF_DATE_KHR) {
  8949. // If presenting, the swapchain is using the in-flight fence
  8950. presentData->windowData->inFlightFences[presentData->windowData->frameCounter] = (SDL_GPUFence *)vulkanCommandBuffer->inFlightFence;
  8951. (void)SDL_AtomicIncRef(&vulkanCommandBuffer->inFlightFence->referenceCount);
  8952. // On the Android platform, VK_SUBOPTIMAL_KHR is returned whenever the device is rotated. We'll just ignore this for now.
  8953. #ifndef SDL_PLATFORM_ANDROID
  8954. if (presentResult == VK_SUBOPTIMAL_KHR) {
  8955. presentData->windowData->needsSwapchainRecreate = true;
  8956. }
  8957. #endif
  8958. if (presentResult == VK_ERROR_OUT_OF_DATE_KHR) {
  8959. presentData->windowData->needsSwapchainRecreate = true;
  8960. }
  8961. } else if (presentResult == VK_ERROR_SURFACE_LOST_KHR) {
  8962. // Android can destroy the surface at any time when the app goes into the background,
  8963. // even after successfully acquiring a swapchain texture and before presenting it.
  8964. presentData->windowData->needsSwapchainRecreate = true;
  8965. presentData->windowData->needsSurfaceRecreate = true;
  8966. } else {
  8967. if (presentResult != VK_SUCCESS) {
  8968. VULKAN_INTERNAL_ReleaseCommandBuffer(vulkanCommandBuffer);
  8969. SDL_UnlockMutex(renderer->submitLock);
  8970. }
  8971. CHECK_VULKAN_ERROR_AND_RETURN(presentResult, vkQueuePresentKHR, false);
  8972. }
  8973. presentData->windowData->frameCounter =
  8974. (presentData->windowData->frameCounter + 1) % renderer->allowedFramesInFlight;
  8975. }
  8976. if (performCleanups) {
  8977. for (Sint32 i = renderer->submittedCommandBufferCount - 1; i >= 0; i -= 1) {
  8978. vulkanResult = renderer->vkGetFenceStatus(
  8979. renderer->logicalDevice,
  8980. renderer->submittedCommandBuffers[i]->inFlightFence->fence);
  8981. if (vulkanResult == VK_SUCCESS) {
  8982. VULKAN_INTERNAL_CleanCommandBuffer(
  8983. renderer,
  8984. renderer->submittedCommandBuffers[i],
  8985. false);
  8986. }
  8987. }
  8988. if (renderer->checkEmptyAllocations) {
  8989. SDL_LockMutex(renderer->allocatorLock);
  8990. for (Uint32 i = 0; i < VK_MAX_MEMORY_TYPES; i += 1) {
  8991. allocator = &renderer->memoryAllocator->subAllocators[i];
  8992. for (Sint32 j = allocator->allocationCount - 1; j >= 0; j -= 1) {
  8993. if (allocator->allocations[j]->usedRegionCount == 0) {
  8994. VULKAN_INTERNAL_DeallocateMemory(
  8995. renderer,
  8996. allocator,
  8997. j);
  8998. }
  8999. }
  9000. }
  9001. renderer->checkEmptyAllocations = false;
  9002. SDL_UnlockMutex(renderer->allocatorLock);
  9003. }
  9004. VULKAN_INTERNAL_PerformPendingDestroys(renderer);
  9005. }
  9006. // Mark command buffer as submitted
  9007. VULKAN_INTERNAL_ReleaseCommandBuffer(vulkanCommandBuffer);
  9008. SDL_UnlockMutex(renderer->submitLock);
  9009. return true;
  9010. }
  9011. static bool VULKAN_Cancel(
  9012. SDL_GPUCommandBuffer *commandBuffer)
  9013. {
  9014. VulkanRenderer *renderer;
  9015. VulkanCommandBuffer *vulkanCommandBuffer;
  9016. VkResult result;
  9017. vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  9018. renderer = vulkanCommandBuffer->renderer;
  9019. result = renderer->vkResetCommandBuffer(
  9020. vulkanCommandBuffer->commandBuffer,
  9021. VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT);
  9022. CHECK_VULKAN_ERROR_AND_RETURN(result, vkResetCommandBuffer, false);
  9023. vulkanCommandBuffer->autoReleaseFence = false;
  9024. SDL_LockMutex(renderer->submitLock);
  9025. VULKAN_INTERNAL_CleanCommandBuffer(renderer, vulkanCommandBuffer, true);
  9026. SDL_UnlockMutex(renderer->submitLock);
  9027. return true;
  9028. }
  9029. static bool VULKAN_INTERNAL_DefragmentMemory(
  9030. VulkanRenderer *renderer,
  9031. VulkanCommandBuffer *commandBuffer)
  9032. {
  9033. renderer->defragInProgress = 1;
  9034. commandBuffer->isDefrag = 1;
  9035. SDL_LockMutex(renderer->allocatorLock);
  9036. VulkanMemoryAllocation *allocation = renderer->allocationsToDefrag[renderer->allocationsToDefragCount - 1];
  9037. renderer->allocationsToDefragCount -= 1;
  9038. /* For each used region in the allocation
  9039. * create a new resource, copy the data
  9040. * and re-point the resource containers
  9041. */
  9042. for (Uint32 i = 0; i < allocation->usedRegionCount; i += 1) {
  9043. VulkanMemoryUsedRegion *currentRegion = allocation->usedRegions[i];
  9044. if (currentRegion->isBuffer && !currentRegion->vulkanBuffer->markedForDestroy) {
  9045. VulkanBuffer *newBuffer = VULKAN_INTERNAL_CreateBuffer(
  9046. renderer,
  9047. currentRegion->vulkanBuffer->size,
  9048. currentRegion->vulkanBuffer->usage,
  9049. currentRegion->vulkanBuffer->type,
  9050. false,
  9051. currentRegion->vulkanBuffer->container != NULL ? currentRegion->vulkanBuffer->container->debugName : NULL);
  9052. if (newBuffer == NULL) {
  9053. SDL_UnlockMutex(renderer->allocatorLock);
  9054. SDL_LogError(SDL_LOG_CATEGORY_GPU, "%s", "Failed to allocate defrag buffer!");
  9055. return false;
  9056. }
  9057. // Copy buffer contents if necessary
  9058. if (
  9059. currentRegion->vulkanBuffer->type == VULKAN_BUFFER_TYPE_GPU && currentRegion->vulkanBuffer->transitioned) {
  9060. VULKAN_INTERNAL_BufferTransitionFromDefaultUsage(
  9061. renderer,
  9062. commandBuffer,
  9063. VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE,
  9064. currentRegion->vulkanBuffer);
  9065. VULKAN_INTERNAL_BufferTransitionFromDefaultUsage(
  9066. renderer,
  9067. commandBuffer,
  9068. VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION,
  9069. newBuffer);
  9070. VkBufferCopy bufferCopy;
  9071. bufferCopy.srcOffset = 0;
  9072. bufferCopy.dstOffset = 0;
  9073. bufferCopy.size = currentRegion->resourceSize;
  9074. renderer->vkCmdCopyBuffer(
  9075. commandBuffer->commandBuffer,
  9076. currentRegion->vulkanBuffer->buffer,
  9077. newBuffer->buffer,
  9078. 1,
  9079. &bufferCopy);
  9080. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  9081. renderer,
  9082. commandBuffer,
  9083. VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION,
  9084. newBuffer);
  9085. VULKAN_INTERNAL_TrackBuffer(commandBuffer, currentRegion->vulkanBuffer);
  9086. VULKAN_INTERNAL_TrackBuffer(commandBuffer, newBuffer);
  9087. }
  9088. // re-point original container to new buffer
  9089. newBuffer->container = currentRegion->vulkanBuffer->container;
  9090. newBuffer->containerIndex = currentRegion->vulkanBuffer->containerIndex;
  9091. if (newBuffer->type == VULKAN_BUFFER_TYPE_UNIFORM) {
  9092. currentRegion->vulkanBuffer->uniformBufferForDefrag->buffer = newBuffer;
  9093. } else {
  9094. newBuffer->container->buffers[newBuffer->containerIndex] = newBuffer;
  9095. if (newBuffer->container->activeBuffer == currentRegion->vulkanBuffer) {
  9096. newBuffer->container->activeBuffer = newBuffer;
  9097. }
  9098. }
  9099. if (currentRegion->vulkanBuffer->uniformBufferForDefrag) {
  9100. newBuffer->uniformBufferForDefrag = currentRegion->vulkanBuffer->uniformBufferForDefrag;
  9101. }
  9102. VULKAN_INTERNAL_ReleaseBuffer(renderer, currentRegion->vulkanBuffer);
  9103. } else if (!currentRegion->isBuffer && !currentRegion->vulkanTexture->markedForDestroy) {
  9104. VulkanTexture *newTexture = VULKAN_INTERNAL_CreateTexture(
  9105. renderer,
  9106. false,
  9107. &currentRegion->vulkanTexture->container->header.info);
  9108. if (newTexture == NULL) {
  9109. SDL_UnlockMutex(renderer->allocatorLock);
  9110. SDL_LogError(SDL_LOG_CATEGORY_GPU, "%s", "Failed to allocate defrag buffer!");
  9111. return false;
  9112. }
  9113. SDL_GPUTextureCreateInfo info = currentRegion->vulkanTexture->container->header.info;
  9114. for (Uint32 subresourceIndex = 0; subresourceIndex < currentRegion->vulkanTexture->subresourceCount; subresourceIndex += 1) {
  9115. // copy subresource if necessary
  9116. VulkanTextureSubresource *srcSubresource = &currentRegion->vulkanTexture->subresources[subresourceIndex];
  9117. VulkanTextureSubresource *dstSubresource = &newTexture->subresources[subresourceIndex];
  9118. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  9119. renderer,
  9120. commandBuffer,
  9121. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  9122. srcSubresource);
  9123. VULKAN_INTERNAL_TextureSubresourceMemoryBarrier(
  9124. renderer,
  9125. commandBuffer,
  9126. VULKAN_TEXTURE_USAGE_MODE_UNINITIALIZED,
  9127. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  9128. dstSubresource);
  9129. VkImageCopy imageCopy;
  9130. imageCopy.srcOffset.x = 0;
  9131. imageCopy.srcOffset.y = 0;
  9132. imageCopy.srcOffset.z = 0;
  9133. imageCopy.srcSubresource.aspectMask = srcSubresource->parent->aspectFlags;
  9134. imageCopy.srcSubresource.baseArrayLayer = srcSubresource->layer;
  9135. imageCopy.srcSubresource.layerCount = 1;
  9136. imageCopy.srcSubresource.mipLevel = srcSubresource->level;
  9137. imageCopy.extent.width = SDL_max(1, info.width >> srcSubresource->level);
  9138. imageCopy.extent.height = SDL_max(1, info.height >> srcSubresource->level);
  9139. imageCopy.extent.depth = info.type == SDL_GPU_TEXTURETYPE_3D ? info.layer_count_or_depth : 1;
  9140. imageCopy.dstOffset.x = 0;
  9141. imageCopy.dstOffset.y = 0;
  9142. imageCopy.dstOffset.z = 0;
  9143. imageCopy.dstSubresource.aspectMask = dstSubresource->parent->aspectFlags;
  9144. imageCopy.dstSubresource.baseArrayLayer = dstSubresource->layer;
  9145. imageCopy.dstSubresource.layerCount = 1;
  9146. imageCopy.dstSubresource.mipLevel = dstSubresource->level;
  9147. renderer->vkCmdCopyImage(
  9148. commandBuffer->commandBuffer,
  9149. currentRegion->vulkanTexture->image,
  9150. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  9151. newTexture->image,
  9152. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  9153. 1,
  9154. &imageCopy);
  9155. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  9156. renderer,
  9157. commandBuffer,
  9158. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  9159. dstSubresource);
  9160. VULKAN_INTERNAL_TrackTexture(commandBuffer, srcSubresource->parent);
  9161. VULKAN_INTERNAL_TrackTexture(commandBuffer, dstSubresource->parent);
  9162. }
  9163. // re-point original container to new texture
  9164. newTexture->container = currentRegion->vulkanTexture->container;
  9165. newTexture->containerIndex = currentRegion->vulkanTexture->containerIndex;
  9166. newTexture->container->textures[currentRegion->vulkanTexture->containerIndex] = newTexture;
  9167. if (currentRegion->vulkanTexture == currentRegion->vulkanTexture->container->activeTexture) {
  9168. newTexture->container->activeTexture = newTexture;
  9169. }
  9170. VULKAN_INTERNAL_ReleaseTexture(renderer, currentRegion->vulkanTexture);
  9171. }
  9172. }
  9173. SDL_UnlockMutex(renderer->allocatorLock);
  9174. return true;
  9175. }
  9176. // Format Info
  9177. static bool VULKAN_SupportsTextureFormat(
  9178. SDL_GPURenderer *driverData,
  9179. SDL_GPUTextureFormat format,
  9180. SDL_GPUTextureType type,
  9181. SDL_GPUTextureUsageFlags usage)
  9182. {
  9183. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  9184. VkFormat vulkanFormat = SDLToVK_TextureFormat[format];
  9185. VkImageUsageFlags vulkanUsage = 0;
  9186. VkImageCreateFlags createFlags = 0;
  9187. VkImageFormatProperties properties;
  9188. VkResult vulkanResult;
  9189. if (usage & SDL_GPU_TEXTUREUSAGE_SAMPLER) {
  9190. vulkanUsage |= VK_IMAGE_USAGE_SAMPLED_BIT;
  9191. }
  9192. if (usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) {
  9193. vulkanUsage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  9194. }
  9195. if (usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) {
  9196. vulkanUsage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  9197. }
  9198. if (usage & (SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ |
  9199. SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ |
  9200. SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE |
  9201. SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE)) {
  9202. vulkanUsage |= VK_IMAGE_USAGE_STORAGE_BIT;
  9203. }
  9204. if (type == SDL_GPU_TEXTURETYPE_CUBE || type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  9205. createFlags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
  9206. }
  9207. vulkanResult = renderer->vkGetPhysicalDeviceImageFormatProperties(
  9208. renderer->physicalDevice,
  9209. vulkanFormat,
  9210. (type == SDL_GPU_TEXTURETYPE_3D) ? VK_IMAGE_TYPE_3D : VK_IMAGE_TYPE_2D,
  9211. VK_IMAGE_TILING_OPTIMAL,
  9212. vulkanUsage,
  9213. createFlags,
  9214. &properties);
  9215. return vulkanResult == VK_SUCCESS;
  9216. }
  9217. // Device instantiation
  9218. static inline Uint8 CheckDeviceExtensions(
  9219. VkExtensionProperties *extensions,
  9220. Uint32 numExtensions,
  9221. VulkanExtensions *supports)
  9222. {
  9223. Uint32 i;
  9224. SDL_memset(supports, '\0', sizeof(VulkanExtensions));
  9225. for (i = 0; i < numExtensions; i += 1) {
  9226. const char *name = extensions[i].extensionName;
  9227. #define CHECK(ext) \
  9228. if (SDL_strcmp(name, "VK_" #ext) == 0) { \
  9229. supports->ext = 1; \
  9230. }
  9231. CHECK(KHR_swapchain)
  9232. else CHECK(KHR_maintenance1) else CHECK(KHR_driver_properties) else CHECK(KHR_portability_subset) else CHECK(MSFT_layered_driver) else CHECK(EXT_texture_compression_astc_hdr)
  9233. #undef CHECK
  9234. }
  9235. return (supports->KHR_swapchain &&
  9236. supports->KHR_maintenance1);
  9237. }
  9238. static inline Uint32 GetDeviceExtensionCount(VulkanExtensions *supports)
  9239. {
  9240. return (
  9241. supports->KHR_swapchain +
  9242. supports->KHR_maintenance1 +
  9243. supports->KHR_driver_properties +
  9244. supports->KHR_portability_subset +
  9245. supports->MSFT_layered_driver +
  9246. supports->EXT_texture_compression_astc_hdr);
  9247. }
  9248. static inline void CreateDeviceExtensionArray(
  9249. VulkanExtensions *supports,
  9250. const char **extensions)
  9251. {
  9252. Uint8 cur = 0;
  9253. #define CHECK(ext) \
  9254. if (supports->ext) { \
  9255. extensions[cur++] = "VK_" #ext; \
  9256. }
  9257. CHECK(KHR_swapchain)
  9258. CHECK(KHR_maintenance1)
  9259. CHECK(KHR_driver_properties)
  9260. CHECK(KHR_portability_subset)
  9261. CHECK(MSFT_layered_driver)
  9262. CHECK(EXT_texture_compression_astc_hdr)
  9263. #undef CHECK
  9264. }
  9265. static inline Uint8 SupportsInstanceExtension(
  9266. const char *ext,
  9267. VkExtensionProperties *availableExtensions,
  9268. Uint32 numAvailableExtensions)
  9269. {
  9270. Uint32 i;
  9271. for (i = 0; i < numAvailableExtensions; i += 1) {
  9272. if (SDL_strcmp(ext, availableExtensions[i].extensionName) == 0) {
  9273. return 1;
  9274. }
  9275. }
  9276. return 0;
  9277. }
  9278. static Uint8 VULKAN_INTERNAL_CheckInstanceExtensions(
  9279. const char **requiredExtensions,
  9280. Uint32 requiredExtensionsLength,
  9281. bool *supportsDebugUtils,
  9282. bool *supportsColorspace,
  9283. bool *supportsPhysicalDeviceProperties2,
  9284. int *firstUnsupportedExtensionIndex)
  9285. {
  9286. Uint32 extensionCount, i;
  9287. VkExtensionProperties *availableExtensions;
  9288. Uint8 allExtensionsSupported = 1;
  9289. vkEnumerateInstanceExtensionProperties(
  9290. NULL,
  9291. &extensionCount,
  9292. NULL);
  9293. availableExtensions = SDL_malloc(
  9294. extensionCount * sizeof(VkExtensionProperties));
  9295. vkEnumerateInstanceExtensionProperties(
  9296. NULL,
  9297. &extensionCount,
  9298. availableExtensions);
  9299. for (i = 0; i < requiredExtensionsLength; i += 1) {
  9300. if (!SupportsInstanceExtension(
  9301. requiredExtensions[i],
  9302. availableExtensions,
  9303. extensionCount)) {
  9304. allExtensionsSupported = 0;
  9305. *firstUnsupportedExtensionIndex = i;
  9306. break;
  9307. }
  9308. }
  9309. // This is optional, but nice to have!
  9310. *supportsDebugUtils = SupportsInstanceExtension(
  9311. VK_EXT_DEBUG_UTILS_EXTENSION_NAME,
  9312. availableExtensions,
  9313. extensionCount);
  9314. // Also optional and nice to have!
  9315. *supportsColorspace = SupportsInstanceExtension(
  9316. VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME,
  9317. availableExtensions,
  9318. extensionCount);
  9319. // Only needed for KHR_driver_properties!
  9320. *supportsPhysicalDeviceProperties2 = SupportsInstanceExtension(
  9321. VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,
  9322. availableExtensions,
  9323. extensionCount);
  9324. SDL_free(availableExtensions);
  9325. return allExtensionsSupported;
  9326. }
  9327. static Uint8 CheckOptInDeviceExtensions(VulkanFeatures *features,
  9328. Uint32 numExtensions,
  9329. VkExtensionProperties *availableExtensions,
  9330. const char **missingExtensionName) {
  9331. Uint8 supportsAll = 1;
  9332. for (Uint32 extensionIdx = 0; extensionIdx < features->additionalDeviceExtensionCount; extensionIdx++) {
  9333. bool found = false;
  9334. for (Uint32 searchIdx = 0; searchIdx < numExtensions; searchIdx++) {
  9335. if (SDL_strcmp(features->additionalDeviceExtensionNames[extensionIdx], availableExtensions[searchIdx].extensionName) == 0) {
  9336. found = true;
  9337. break;
  9338. }
  9339. }
  9340. if (!found) {
  9341. supportsAll = 0;
  9342. *missingExtensionName = features->additionalDeviceExtensionNames[extensionIdx];
  9343. break;
  9344. }
  9345. }
  9346. return supportsAll;
  9347. }
  9348. static Uint8 VULKAN_INTERNAL_CheckDeviceExtensions(
  9349. VulkanRenderer *renderer,
  9350. VulkanFeatures *features,
  9351. VkPhysicalDevice physicalDevice,
  9352. VulkanExtensions *physicalDeviceExtensions)
  9353. {
  9354. Uint32 extensionCount;
  9355. VkExtensionProperties *availableExtensions;
  9356. Uint8 allExtensionsSupported;
  9357. renderer->vkEnumerateDeviceExtensionProperties(
  9358. physicalDevice,
  9359. NULL,
  9360. &extensionCount,
  9361. NULL);
  9362. availableExtensions = (VkExtensionProperties *)SDL_malloc(
  9363. extensionCount * sizeof(VkExtensionProperties));
  9364. renderer->vkEnumerateDeviceExtensionProperties(
  9365. physicalDevice,
  9366. NULL,
  9367. &extensionCount,
  9368. availableExtensions);
  9369. allExtensionsSupported = CheckDeviceExtensions(
  9370. availableExtensions,
  9371. extensionCount,
  9372. physicalDeviceExtensions);
  9373. if (features->usesCustomVulkanOptions) {
  9374. const char *missingExtensionName;
  9375. if (!CheckOptInDeviceExtensions(features, extensionCount, availableExtensions, &missingExtensionName)) {
  9376. SDL_assert(missingExtensionName);
  9377. if (renderer->debugMode) {
  9378. SDL_LogError(SDL_LOG_CATEGORY_GPU,
  9379. "Required Vulkan device extension '%s' not supported",
  9380. missingExtensionName);
  9381. }
  9382. allExtensionsSupported = 0;
  9383. }
  9384. }
  9385. SDL_free(availableExtensions);
  9386. return allExtensionsSupported;
  9387. }
  9388. static Uint8 VULKAN_INTERNAL_CheckValidationLayers(
  9389. const char **validationLayers,
  9390. Uint32 validationLayersLength)
  9391. {
  9392. Uint32 layerCount;
  9393. VkLayerProperties *availableLayers;
  9394. Uint32 i, j;
  9395. Uint8 layerFound = 0;
  9396. vkEnumerateInstanceLayerProperties(&layerCount, NULL);
  9397. availableLayers = (VkLayerProperties *)SDL_malloc(
  9398. layerCount * sizeof(VkLayerProperties));
  9399. vkEnumerateInstanceLayerProperties(&layerCount, availableLayers);
  9400. for (i = 0; i < validationLayersLength; i += 1) {
  9401. layerFound = 0;
  9402. for (j = 0; j < layerCount; j += 1) {
  9403. if (SDL_strcmp(validationLayers[i], availableLayers[j].layerName) == 0) {
  9404. layerFound = 1;
  9405. break;
  9406. }
  9407. }
  9408. if (!layerFound) {
  9409. break;
  9410. }
  9411. }
  9412. SDL_free(availableLayers);
  9413. return layerFound;
  9414. }
  9415. #define CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, feature, result) \
  9416. if (requested->feature && !supported->feature) { \
  9417. SDL_LogVerbose( \
  9418. SDL_LOG_CATEGORY_GPU, \
  9419. "SDL GPU Vulkan: Application requested unsupported physical device feature '" #feature "'"); \
  9420. result = false; \
  9421. }
  9422. static bool VULKAN_INTERNAL_ValidateOptInVulkan10Features(VkPhysicalDeviceFeatures *requested, VkPhysicalDeviceFeatures *supported)
  9423. {
  9424. if (requested && supported) {
  9425. bool result = true;
  9426. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, robustBufferAccess, result)
  9427. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, fullDrawIndexUint32, result)
  9428. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, imageCubeArray, result)
  9429. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, independentBlend, result)
  9430. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, geometryShader, result)
  9431. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, tessellationShader, result)
  9432. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, sampleRateShading, result)
  9433. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, dualSrcBlend, result)
  9434. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, logicOp, result)
  9435. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, multiDrawIndirect, result)
  9436. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, drawIndirectFirstInstance, result)
  9437. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, depthClamp, result)
  9438. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, depthBiasClamp, result)
  9439. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, fillModeNonSolid, result)
  9440. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, depthBounds, result)
  9441. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, wideLines, result)
  9442. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, largePoints, result)
  9443. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, alphaToOne, result)
  9444. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, multiViewport, result)
  9445. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, samplerAnisotropy, result)
  9446. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, textureCompressionETC2, result)
  9447. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, textureCompressionASTC_LDR, result)
  9448. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, textureCompressionBC, result)
  9449. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, occlusionQueryPrecise, result)
  9450. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, pipelineStatisticsQuery, result)
  9451. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, vertexPipelineStoresAndAtomics, result)
  9452. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, fragmentStoresAndAtomics, result)
  9453. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderTessellationAndGeometryPointSize, result)
  9454. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderImageGatherExtended, result)
  9455. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderStorageImageExtendedFormats, result)
  9456. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderStorageImageMultisample, result)
  9457. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderStorageImageReadWithoutFormat, result)
  9458. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderStorageImageWriteWithoutFormat, result)
  9459. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderUniformBufferArrayDynamicIndexing, result)
  9460. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderSampledImageArrayDynamicIndexing, result)
  9461. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderStorageBufferArrayDynamicIndexing, result)
  9462. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderStorageImageArrayDynamicIndexing, result)
  9463. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderClipDistance, result)
  9464. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderCullDistance, result)
  9465. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderFloat64, result)
  9466. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderInt64, result)
  9467. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderInt16, result)
  9468. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderResourceResidency, result)
  9469. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderResourceMinLod, result)
  9470. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, sparseBinding, result)
  9471. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, sparseResidencyBuffer, result)
  9472. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, sparseResidencyImage2D, result)
  9473. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, sparseResidencyImage3D, result)
  9474. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, sparseResidency2Samples, result)
  9475. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, sparseResidency4Samples, result)
  9476. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, sparseResidency8Samples, result)
  9477. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, sparseResidency16Samples, result)
  9478. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, sparseResidencyAliased, result)
  9479. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, variableMultisampleRate, result)
  9480. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, inheritedQueries, result)
  9481. return result;
  9482. } else {
  9483. return false;
  9484. }
  9485. }
  9486. static bool VULKAN_INTERNAL_ValidateOptInVulkan11Features(VkPhysicalDeviceVulkan11Features *requested, VkPhysicalDeviceVulkan11Features *supported)
  9487. {
  9488. if (requested && supported) {
  9489. bool result = true;
  9490. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, storageBuffer16BitAccess, result)
  9491. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, uniformAndStorageBuffer16BitAccess, result)
  9492. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, storagePushConstant16, result)
  9493. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, storageInputOutput16, result)
  9494. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, multiview, result)
  9495. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, multiviewGeometryShader, result)
  9496. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, multiviewTessellationShader, result)
  9497. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, variablePointersStorageBuffer, result)
  9498. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, variablePointers, result)
  9499. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, protectedMemory, result)
  9500. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, samplerYcbcrConversion, result)
  9501. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderDrawParameters, result)
  9502. return result;
  9503. } else {
  9504. return false;
  9505. }
  9506. }
  9507. static bool VULKAN_INTERNAL_ValidateOptInVulkan12Features(VkPhysicalDeviceVulkan12Features *requested, VkPhysicalDeviceVulkan12Features *supported)
  9508. {
  9509. if (requested && supported) {
  9510. bool result = true;
  9511. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, samplerMirrorClampToEdge, result)
  9512. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, drawIndirectCount, result)
  9513. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, storageBuffer8BitAccess, result)
  9514. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, uniformAndStorageBuffer8BitAccess, result)
  9515. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, storagePushConstant8, result)
  9516. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderBufferInt64Atomics, result)
  9517. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderSharedInt64Atomics, result)
  9518. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderFloat16, result)
  9519. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderInt8, result)
  9520. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, descriptorIndexing, result)
  9521. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderInputAttachmentArrayDynamicIndexing, result)
  9522. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderUniformTexelBufferArrayDynamicIndexing, result)
  9523. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderStorageTexelBufferArrayDynamicIndexing, result)
  9524. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderUniformBufferArrayNonUniformIndexing, result)
  9525. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderSampledImageArrayNonUniformIndexing, result)
  9526. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderStorageBufferArrayNonUniformIndexing, result)
  9527. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderStorageImageArrayNonUniformIndexing, result)
  9528. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderInputAttachmentArrayNonUniformIndexing, result)
  9529. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderUniformTexelBufferArrayNonUniformIndexing, result)
  9530. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderStorageTexelBufferArrayNonUniformIndexing, result)
  9531. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, descriptorBindingUniformBufferUpdateAfterBind, result)
  9532. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, descriptorBindingSampledImageUpdateAfterBind, result)
  9533. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, descriptorBindingStorageImageUpdateAfterBind, result)
  9534. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, descriptorBindingStorageBufferUpdateAfterBind, result)
  9535. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, descriptorBindingUniformTexelBufferUpdateAfterBind, result)
  9536. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, descriptorBindingStorageTexelBufferUpdateAfterBind, result)
  9537. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, descriptorBindingUpdateUnusedWhilePending, result)
  9538. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, descriptorBindingPartiallyBound, result)
  9539. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, descriptorBindingVariableDescriptorCount, result)
  9540. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, runtimeDescriptorArray, result)
  9541. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, samplerFilterMinmax, result)
  9542. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, scalarBlockLayout, result)
  9543. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, imagelessFramebuffer, result)
  9544. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, uniformBufferStandardLayout, result)
  9545. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderSubgroupExtendedTypes, result)
  9546. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, separateDepthStencilLayouts, result)
  9547. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, hostQueryReset, result)
  9548. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, timelineSemaphore, result)
  9549. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, bufferDeviceAddress, result)
  9550. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, bufferDeviceAddressCaptureReplay, result)
  9551. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, bufferDeviceAddressMultiDevice, result)
  9552. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, vulkanMemoryModel, result)
  9553. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, vulkanMemoryModelDeviceScope, result)
  9554. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, vulkanMemoryModelAvailabilityVisibilityChains, result)
  9555. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderOutputViewportIndex, result)
  9556. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderOutputLayer, result)
  9557. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, subgroupBroadcastDynamicId, result)
  9558. return result;
  9559. } else {
  9560. return false;
  9561. }
  9562. }
  9563. static bool VULKAN_INTERNAL_ValidateOptInVulkan13Features(VkPhysicalDeviceVulkan13Features *requested, VkPhysicalDeviceVulkan13Features *supported)
  9564. {
  9565. if (requested && supported) {
  9566. bool result = true;
  9567. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, robustImageAccess, result)
  9568. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, inlineUniformBlock, result)
  9569. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, descriptorBindingInlineUniformBlockUpdateAfterBind, result)
  9570. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, pipelineCreationCacheControl, result)
  9571. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, privateData, result)
  9572. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderDemoteToHelperInvocation, result)
  9573. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderTerminateInvocation, result)
  9574. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, subgroupSizeControl, result)
  9575. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, computeFullSubgroups, result)
  9576. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, synchronization2, result)
  9577. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, textureCompressionASTC_HDR, result)
  9578. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderZeroInitializeWorkgroupMemory, result)
  9579. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, dynamicRendering, result)
  9580. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, shaderIntegerDotProduct, result)
  9581. CHECK_OPTIONAL_DEVICE_FEATURE(requested, supported, maintenance4, result)
  9582. return result;
  9583. } else {
  9584. return false;
  9585. }
  9586. }
  9587. #undef CHECK_OPTIONAL_DEVICE_FEATURE
  9588. static bool VULKAN_INTERNAL_ValidateOptInFeatures(VulkanRenderer *renderer, VulkanFeatures *features, VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures *vk10Features)
  9589. {
  9590. bool supportsAllFeatures = true;
  9591. int minorVersion = VK_API_VERSION_MINOR(features->desiredApiVersion);
  9592. if (minorVersion < 1) {
  9593. supportsAllFeatures &= VULKAN_INTERNAL_ValidateOptInVulkan10Features(&features->desiredVulkan10DeviceFeatures, vk10Features);
  9594. } else if (minorVersion < 2) {
  9595. // Query device features using the pre-1.2 structures
  9596. VkPhysicalDevice16BitStorageFeatures storage = { 0 };
  9597. storage.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES;
  9598. VkPhysicalDeviceMultiviewFeatures multiview = { 0 };
  9599. multiview.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES;
  9600. VkPhysicalDeviceProtectedMemoryFeatures protectedMem = { 0 };
  9601. protectedMem.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES;
  9602. VkPhysicalDeviceSamplerYcbcrConversionFeatures ycbcr = { 0 };
  9603. ycbcr.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES;
  9604. VkPhysicalDeviceShaderDrawParametersFeatures drawParams = { 0 };
  9605. drawParams.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES;
  9606. VkPhysicalDeviceVariablePointersFeatures varPointers = { 0 };
  9607. varPointers.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES;
  9608. VkPhysicalDeviceFeatures2 supportedFeatureList = { 0 };
  9609. supportedFeatureList.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  9610. supportedFeatureList.pNext = &storage;
  9611. storage.pNext = &multiview;
  9612. multiview.pNext = &protectedMem;
  9613. protectedMem.pNext = &ycbcr;
  9614. ycbcr.pNext = &drawParams;
  9615. drawParams.pNext = &varPointers;
  9616. renderer->vkGetPhysicalDeviceFeatures2(physicalDevice, &supportedFeatureList);
  9617. // Pack the results into the post-1.2 structure for easier checking
  9618. VkPhysicalDeviceVulkan11Features vk11Features = { 0 };
  9619. vk11Features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  9620. vk11Features.storageBuffer16BitAccess = storage.storageBuffer16BitAccess;
  9621. vk11Features.uniformAndStorageBuffer16BitAccess = storage.uniformAndStorageBuffer16BitAccess;
  9622. vk11Features.storagePushConstant16 = storage.storagePushConstant16;
  9623. vk11Features.storageInputOutput16 = storage.storageInputOutput16;
  9624. vk11Features.multiview = multiview.multiview;
  9625. vk11Features.multiviewGeometryShader = multiview.multiviewGeometryShader;
  9626. vk11Features.multiviewTessellationShader = multiview.multiviewTessellationShader;
  9627. vk11Features.protectedMemory = protectedMem.protectedMemory;
  9628. vk11Features.samplerYcbcrConversion = ycbcr.samplerYcbcrConversion;
  9629. vk11Features.shaderDrawParameters = drawParams.shaderDrawParameters;
  9630. vk11Features.variablePointers = varPointers.variablePointers;
  9631. vk11Features.variablePointersStorageBuffer = varPointers.variablePointersStorageBuffer;
  9632. // Check support
  9633. supportsAllFeatures &= VULKAN_INTERNAL_ValidateOptInVulkan10Features(&features->desiredVulkan10DeviceFeatures, vk10Features);
  9634. supportsAllFeatures &= VULKAN_INTERNAL_ValidateOptInVulkan11Features(&features->desiredVulkan11DeviceFeatures, &vk11Features);
  9635. } else {
  9636. VkPhysicalDeviceVulkan11Features vk11Features = { 0 };
  9637. vk11Features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  9638. VkPhysicalDeviceVulkan12Features vk12Features = { 0 };
  9639. vk12Features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  9640. VkPhysicalDeviceVulkan13Features vk13Features = { 0 };
  9641. vk13Features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES;
  9642. VkPhysicalDeviceFeatures2 supportedFeatureList = { 0 };
  9643. supportedFeatureList.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  9644. supportedFeatureList.pNext = &vk11Features;
  9645. vk11Features.pNext = &vk12Features;
  9646. vk12Features.pNext = &vk13Features;
  9647. renderer->vkGetPhysicalDeviceFeatures2(physicalDevice, &supportedFeatureList);
  9648. supportsAllFeatures &= VULKAN_INTERNAL_ValidateOptInVulkan10Features(&features->desiredVulkan10DeviceFeatures, vk10Features);
  9649. supportsAllFeatures &= VULKAN_INTERNAL_ValidateOptInVulkan11Features(&features->desiredVulkan11DeviceFeatures, &vk11Features);
  9650. supportsAllFeatures &= VULKAN_INTERNAL_ValidateOptInVulkan12Features(&features->desiredVulkan12DeviceFeatures, &vk12Features);
  9651. supportsAllFeatures &= VULKAN_INTERNAL_ValidateOptInVulkan13Features(&features->desiredVulkan13DeviceFeatures, &vk13Features);
  9652. }
  9653. return supportsAllFeatures;
  9654. }
  9655. static void VULKAN_INTERNAL_AddDeviceFeatures(VkBool32 *firstFeature, VkBool32 *lastFeature, VkBool32 *firstFeatureToAdd)
  9656. {
  9657. while (firstFeature <= lastFeature) {
  9658. *firstFeature = (*firstFeature | *firstFeatureToAdd);
  9659. firstFeature++;
  9660. firstFeatureToAdd++;
  9661. }
  9662. }
  9663. static bool VULKAN_INTERNAL_TryAddDeviceFeatures_Vulkan_11(VkPhysicalDeviceFeatures *dst10,
  9664. VkPhysicalDeviceVulkan11Features *dst11,
  9665. VkBaseOutStructure *src)
  9666. {
  9667. bool hasAdded = false;
  9668. switch (src->sType) {
  9669. case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2:
  9670. {
  9671. VkPhysicalDeviceFeatures2 *newFeatures = (VkPhysicalDeviceFeatures2 *)src;
  9672. VULKAN_INTERNAL_AddDeviceFeatures(&dst10->robustBufferAccess,
  9673. &dst10->inheritedQueries,
  9674. &newFeatures->features.robustBufferAccess);
  9675. hasAdded = true;
  9676. } break;
  9677. case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES:
  9678. {
  9679. VkPhysicalDevice16BitStorageFeatures *newFeatures = (VkPhysicalDevice16BitStorageFeatures *)src;
  9680. dst11->storageBuffer16BitAccess |= newFeatures->storageBuffer16BitAccess;
  9681. dst11->uniformAndStorageBuffer16BitAccess |= newFeatures->uniformAndStorageBuffer16BitAccess;
  9682. dst11->storagePushConstant16 |= newFeatures->storagePushConstant16;
  9683. dst11->storageInputOutput16 |= newFeatures->storageInputOutput16;
  9684. hasAdded = true;
  9685. } break;
  9686. case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES:
  9687. {
  9688. VkPhysicalDeviceMultiviewFeatures *newFeatures = (VkPhysicalDeviceMultiviewFeatures *)src;
  9689. dst11->multiview |= newFeatures->multiview;
  9690. dst11->multiviewGeometryShader |= newFeatures->multiviewGeometryShader;
  9691. dst11->multiviewTessellationShader |= newFeatures->multiviewTessellationShader;
  9692. hasAdded = true;
  9693. } break;
  9694. case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES:
  9695. {
  9696. VkPhysicalDeviceProtectedMemoryFeatures *newFeatures = (VkPhysicalDeviceProtectedMemoryFeatures *)src;
  9697. dst11->protectedMemory |= newFeatures->protectedMemory;
  9698. hasAdded = true;
  9699. } break;
  9700. case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES:
  9701. {
  9702. VkPhysicalDeviceSamplerYcbcrConversionFeatures *newFeatures = (VkPhysicalDeviceSamplerYcbcrConversionFeatures *)src;
  9703. dst11->samplerYcbcrConversion |= newFeatures->samplerYcbcrConversion;
  9704. hasAdded = true;
  9705. } break;
  9706. case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES:
  9707. {
  9708. VkPhysicalDeviceShaderDrawParametersFeatures *newFeatures = (VkPhysicalDeviceShaderDrawParametersFeatures *)src;
  9709. dst11->shaderDrawParameters |= newFeatures->shaderDrawParameters;
  9710. hasAdded = true;
  9711. } break;
  9712. case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES:
  9713. {
  9714. VkPhysicalDeviceVariablePointersFeatures *newFeatures = (VkPhysicalDeviceVariablePointersFeatures *)src;
  9715. dst11->variablePointers |= newFeatures->variablePointers;
  9716. dst11->variablePointersStorageBuffer |= newFeatures->variablePointersStorageBuffer;
  9717. hasAdded = true;
  9718. } break;
  9719. default:
  9720. break;
  9721. }
  9722. return hasAdded;
  9723. }
  9724. static bool VULKAN_INTERNAL_TryAddDeviceFeatures_Vulkan_12_Or_Later(VkPhysicalDeviceFeatures *dst10,
  9725. VkPhysicalDeviceVulkan11Features *dst11,
  9726. VkPhysicalDeviceVulkan12Features *dst12,
  9727. VkPhysicalDeviceVulkan13Features *dst13,
  9728. Uint32 apiVersion,
  9729. VkBaseOutStructure *src)
  9730. {
  9731. int minorVersion = VK_API_VERSION_MINOR(apiVersion);
  9732. SDL_assert(apiVersion >= 2);
  9733. bool hasAdded = VULKAN_INTERNAL_TryAddDeviceFeatures_Vulkan_11(dst10, dst11, src);
  9734. if (!hasAdded) {
  9735. switch (src->sType) {
  9736. case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES:
  9737. {
  9738. VkPhysicalDeviceVulkan11Features *newFeatures = (VkPhysicalDeviceVulkan11Features *)src;
  9739. VULKAN_INTERNAL_AddDeviceFeatures(&dst11->storageBuffer16BitAccess,
  9740. &dst11->shaderDrawParameters,
  9741. &newFeatures->storageBuffer16BitAccess);
  9742. hasAdded = true;
  9743. } break;
  9744. case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES:
  9745. {
  9746. VkPhysicalDeviceVulkan12Features *newFeatures = (VkPhysicalDeviceVulkan12Features *)src;
  9747. VULKAN_INTERNAL_AddDeviceFeatures(&dst12->samplerMirrorClampToEdge,
  9748. &dst12->subgroupBroadcastDynamicId,
  9749. &newFeatures->samplerMirrorClampToEdge);
  9750. hasAdded = true;
  9751. } break;
  9752. case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES:
  9753. {
  9754. if (minorVersion >= 3) {
  9755. VkPhysicalDeviceVulkan13Features *newFeatures = (VkPhysicalDeviceVulkan13Features *)src;
  9756. VULKAN_INTERNAL_AddDeviceFeatures(&dst13->robustImageAccess,
  9757. &dst13->maintenance4,
  9758. &newFeatures->robustImageAccess);
  9759. hasAdded = true;
  9760. }
  9761. } break;
  9762. default:
  9763. break;
  9764. }
  9765. }
  9766. return hasAdded;
  9767. }
  9768. static void VULKAN_INTERNAL_AddOptInVulkanOptions(SDL_PropertiesID props, VulkanRenderer *renderer, VulkanFeatures *features)
  9769. {
  9770. if (SDL_HasProperty(props, SDL_PROP_GPU_DEVICE_CREATE_VULKAN_OPTIONS_POINTER)) {
  9771. SDL_GPUVulkanOptions *options = (SDL_GPUVulkanOptions *)SDL_GetPointerProperty(props, SDL_PROP_GPU_DEVICE_CREATE_VULKAN_OPTIONS_POINTER, NULL);
  9772. if (options) {
  9773. features->usesCustomVulkanOptions = true;
  9774. features->desiredApiVersion = options->vulkan_api_version;
  9775. SDL_zero(features->desiredVulkan11DeviceFeatures);
  9776. SDL_zero(features->desiredVulkan12DeviceFeatures);
  9777. SDL_zero(features->desiredVulkan13DeviceFeatures);
  9778. features->desiredVulkan11DeviceFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  9779. features->desiredVulkan12DeviceFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  9780. features->desiredVulkan13DeviceFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES;
  9781. // Handle requested device features
  9782. VkPhysicalDeviceFeatures *vk10Features = &features->desiredVulkan10DeviceFeatures;
  9783. VkPhysicalDeviceVulkan11Features *vk11Features = &features->desiredVulkan11DeviceFeatures;
  9784. VkPhysicalDeviceVulkan12Features *vk12Features = &features->desiredVulkan12DeviceFeatures;
  9785. VkPhysicalDeviceVulkan13Features *vk13Features = &features->desiredVulkan13DeviceFeatures;
  9786. if (options->vulkan_10_physical_device_features) {
  9787. VkPhysicalDeviceFeatures *deviceFeatures = (VkPhysicalDeviceFeatures *)options->vulkan_10_physical_device_features;
  9788. VULKAN_INTERNAL_AddDeviceFeatures(&vk10Features->robustBufferAccess,
  9789. &vk10Features->inheritedQueries,
  9790. &deviceFeatures->robustBufferAccess);
  9791. }
  9792. int minorVersion = VK_API_VERSION_MINOR(features->desiredApiVersion);
  9793. bool supportsHigherLevelFeatures = minorVersion > 0;
  9794. if (supportsHigherLevelFeatures && options->feature_list) {
  9795. if (minorVersion < 2) {
  9796. // Iterate through the entire list and combine all requested features
  9797. VkBaseOutStructure *nextStructure = (VkBaseOutStructure *)options->feature_list;
  9798. while (nextStructure) {
  9799. VULKAN_INTERNAL_TryAddDeviceFeatures_Vulkan_11(vk10Features, vk11Features, nextStructure);
  9800. nextStructure = nextStructure->pNext;
  9801. }
  9802. } else {
  9803. // Iterate through the entire list and combine all requested features
  9804. VkBaseOutStructure *nextStructure = (VkBaseOutStructure *)options->feature_list;
  9805. while (nextStructure) {
  9806. VULKAN_INTERNAL_TryAddDeviceFeatures_Vulkan_12_Or_Later(vk10Features,
  9807. vk11Features,
  9808. vk12Features,
  9809. vk13Features,
  9810. features->desiredApiVersion,
  9811. nextStructure);
  9812. nextStructure = nextStructure->pNext;
  9813. }
  9814. }
  9815. }
  9816. features->additionalDeviceExtensionCount = options->device_extension_count;
  9817. features->additionalDeviceExtensionNames = options->device_extension_names;
  9818. features->additionalInstanceExtensionCount = options->instance_extension_count;
  9819. features->additionalInstanceExtensionNames = options->instance_extension_names;
  9820. } else if (renderer->debugMode) {
  9821. SDL_LogWarn(SDL_LOG_CATEGORY_GPU,
  9822. "VULKAN_INTERNAL_AddOptInVulkanOptions: Additional options property was set, but value was null. This may be a bug.");
  9823. }
  9824. }
  9825. }
  9826. static Uint8 VULKAN_INTERNAL_CreateInstance(VulkanRenderer *renderer, VulkanFeatures *features)
  9827. {
  9828. VkResult vulkanResult;
  9829. VkApplicationInfo appInfo;
  9830. VkInstanceCreateFlags createFlags;
  9831. const char *const *originalInstanceExtensionNames;
  9832. const char **instanceExtensionNames;
  9833. Uint32 instanceExtensionCount;
  9834. VkInstanceCreateInfo createInfo;
  9835. static const char *layerNames[] = { "VK_LAYER_KHRONOS_validation" };
  9836. appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
  9837. appInfo.pNext = NULL;
  9838. appInfo.pApplicationName = NULL;
  9839. appInfo.applicationVersion = 0;
  9840. appInfo.pEngineName = "SDLGPU";
  9841. appInfo.engineVersion = SDL_VERSION;
  9842. appInfo.apiVersion = features->usesCustomVulkanOptions
  9843. ? features->desiredApiVersion
  9844. : VK_MAKE_VERSION(1, 0, 0);
  9845. createFlags = 0;
  9846. originalInstanceExtensionNames = SDL_Vulkan_GetInstanceExtensions(&instanceExtensionCount);
  9847. if (!originalInstanceExtensionNames) {
  9848. SDL_LogError(
  9849. SDL_LOG_CATEGORY_GPU,
  9850. "SDL_Vulkan_GetInstanceExtensions(): getExtensionCount: %s",
  9851. SDL_GetError());
  9852. return 0;
  9853. }
  9854. Uint32 extraInstanceExtensionCount = features->additionalInstanceExtensionCount;
  9855. const char** extraInstanceExtensionNames = features->additionalInstanceExtensionNames;
  9856. /* Extra space for the following extensions:
  9857. * VK_KHR_get_physical_device_properties2
  9858. * VK_EXT_swapchain_colorspace
  9859. * VK_EXT_debug_utils
  9860. * VK_KHR_portability_enumeration
  9861. *
  9862. * Plus additional opt-in extensions.
  9863. */
  9864. instanceExtensionNames = SDL_stack_alloc(
  9865. const char *,
  9866. instanceExtensionCount + 4 + extraInstanceExtensionCount);
  9867. const char** nextInstanceExtensionNamePtr = instanceExtensionNames;
  9868. SDL_memcpy((void *)nextInstanceExtensionNamePtr, originalInstanceExtensionNames, instanceExtensionCount * sizeof(const char *));
  9869. nextInstanceExtensionNamePtr += instanceExtensionCount;
  9870. if (extraInstanceExtensionCount > 0) {
  9871. SDL_memcpy((void *)nextInstanceExtensionNamePtr, extraInstanceExtensionNames, extraInstanceExtensionCount * sizeof(const char *));
  9872. nextInstanceExtensionNamePtr += extraInstanceExtensionCount;
  9873. }
  9874. #ifdef SDL_PLATFORM_APPLE
  9875. *nextInstanceExtensionNamePtr++ = VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME;
  9876. instanceExtensionCount++;
  9877. createFlags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;
  9878. #endif
  9879. int firstUnsupportedExtensionIndex = 0;
  9880. if (!VULKAN_INTERNAL_CheckInstanceExtensions(
  9881. instanceExtensionNames,
  9882. instanceExtensionCount + extraInstanceExtensionCount,
  9883. &renderer->supportsDebugUtils,
  9884. &renderer->supportsColorspace,
  9885. &renderer->supportsPhysicalDeviceProperties2,
  9886. &firstUnsupportedExtensionIndex)) {
  9887. if (renderer->debugMode) {
  9888. SDL_LogError(SDL_LOG_CATEGORY_GPU,
  9889. "Required Vulkan instance extension '%s' not supported",
  9890. instanceExtensionNames[firstUnsupportedExtensionIndex]);
  9891. }
  9892. SDL_SetError("Required Vulkan instance extension '%s' not supported",
  9893. instanceExtensionNames[firstUnsupportedExtensionIndex]);
  9894. SDL_stack_free((char *)instanceExtensionNames);
  9895. return false;
  9896. }
  9897. if (renderer->supportsDebugUtils) {
  9898. // Append the debug extension
  9899. *nextInstanceExtensionNamePtr++ = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
  9900. instanceExtensionCount++;
  9901. } else {
  9902. SDL_LogWarn(
  9903. SDL_LOG_CATEGORY_GPU,
  9904. "%s is not supported!",
  9905. VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
  9906. }
  9907. if (renderer->supportsColorspace) {
  9908. // Append colorspace extension
  9909. *nextInstanceExtensionNamePtr++ = VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME;
  9910. instanceExtensionCount++;
  9911. }
  9912. if (renderer->supportsPhysicalDeviceProperties2) {
  9913. // Append KHR_physical_device_properties2 extension
  9914. *nextInstanceExtensionNamePtr++ = VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME;
  9915. instanceExtensionCount++;
  9916. }
  9917. createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  9918. createInfo.pNext = NULL;
  9919. createInfo.flags = createFlags;
  9920. createInfo.pApplicationInfo = &appInfo;
  9921. createInfo.ppEnabledLayerNames = layerNames;
  9922. createInfo.enabledExtensionCount = instanceExtensionCount + extraInstanceExtensionCount;
  9923. createInfo.ppEnabledExtensionNames = instanceExtensionNames;
  9924. if (renderer->debugMode) {
  9925. createInfo.enabledLayerCount = SDL_arraysize(layerNames);
  9926. if (!VULKAN_INTERNAL_CheckValidationLayers(
  9927. layerNames,
  9928. createInfo.enabledLayerCount)) {
  9929. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Validation layers not found, continuing without validation");
  9930. createInfo.enabledLayerCount = 0;
  9931. } else {
  9932. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "Validation layers enabled, expect debug level performance!");
  9933. }
  9934. } else {
  9935. createInfo.enabledLayerCount = 0;
  9936. }
  9937. vulkanResult = vkCreateInstance(&createInfo, NULL, &renderer->instance);
  9938. SDL_stack_free((char *)instanceExtensionNames);
  9939. if (vulkanResult != VK_SUCCESS) {
  9940. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateInstance, 0);
  9941. }
  9942. return 1;
  9943. }
  9944. static bool VULKAN_INTERNAL_GetDeviceRank(
  9945. VulkanRenderer *renderer,
  9946. VkPhysicalDevice physicalDevice,
  9947. VulkanExtensions *physicalDeviceExtensions,
  9948. Uint64 *deviceRank)
  9949. {
  9950. static const Uint8 DEVICE_PRIORITY_HIGHPERFORMANCE[] = {
  9951. 0, // VK_PHYSICAL_DEVICE_TYPE_OTHER
  9952. 3, // VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU
  9953. 4, // VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU
  9954. 2, // VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU
  9955. 1 // VK_PHYSICAL_DEVICE_TYPE_CPU
  9956. };
  9957. static const Uint8 DEVICE_PRIORITY_LOWPOWER[] = {
  9958. 0, // VK_PHYSICAL_DEVICE_TYPE_OTHER
  9959. 4, // VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU
  9960. 3, // VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU
  9961. 2, // VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU
  9962. 1 // VK_PHYSICAL_DEVICE_TYPE_CPU
  9963. };
  9964. const Uint8 *devicePriority = renderer->preferLowPower ? DEVICE_PRIORITY_LOWPOWER : DEVICE_PRIORITY_HIGHPERFORMANCE;
  9965. VkPhysicalDeviceType deviceType;
  9966. if (physicalDeviceExtensions->MSFT_layered_driver) {
  9967. VkPhysicalDeviceProperties2KHR physicalDeviceProperties;
  9968. VkPhysicalDeviceLayeredDriverPropertiesMSFT physicalDeviceLayeredDriverProperties;
  9969. physicalDeviceProperties.sType =
  9970. VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
  9971. physicalDeviceProperties.pNext = &physicalDeviceLayeredDriverProperties;
  9972. physicalDeviceLayeredDriverProperties.sType =
  9973. VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_LAYERED_DRIVER_PROPERTIES_MSFT;
  9974. physicalDeviceLayeredDriverProperties.pNext = NULL;
  9975. renderer->vkGetPhysicalDeviceProperties2KHR(
  9976. physicalDevice,
  9977. &physicalDeviceProperties);
  9978. if (physicalDeviceLayeredDriverProperties.underlyingAPI != VK_LAYERED_DRIVER_UNDERLYING_API_NONE_MSFT) {
  9979. deviceType = VK_PHYSICAL_DEVICE_TYPE_OTHER;
  9980. } else {
  9981. deviceType = physicalDeviceProperties.properties.deviceType;
  9982. }
  9983. } else {
  9984. VkPhysicalDeviceProperties physicalDeviceProperties;
  9985. renderer->vkGetPhysicalDeviceProperties(
  9986. physicalDevice,
  9987. &physicalDeviceProperties);
  9988. deviceType = physicalDeviceProperties.deviceType;
  9989. }
  9990. if (renderer->requireHardwareAcceleration) {
  9991. if (deviceType != VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU &&
  9992. deviceType != VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU &&
  9993. deviceType != VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU) {
  9994. // In addition to CPU, "Other" drivers (including layered drivers) don't count as hardware-accelerated
  9995. return 0;
  9996. }
  9997. }
  9998. /* Apply a large bias on the devicePriority so that we always respect the order in the priority arrays.
  9999. * We also rank by e.g. VRAM which should have less influence than the device type.
  10000. */
  10001. Uint64 devicePriorityValue = devicePriority[deviceType] * 1000000;
  10002. if (*deviceRank < devicePriorityValue) {
  10003. /* This device outranks the best device we've found so far!
  10004. * This includes a dedicated GPU that has less features than an
  10005. * integrated GPU, because this is a freak case that is almost
  10006. * never intentionally desired by the end user
  10007. */
  10008. *deviceRank = devicePriorityValue;
  10009. } else if (*deviceRank > devicePriorityValue) {
  10010. /* Device is outranked by a previous device, don't even try to
  10011. * run a query and reset the rank to avoid overwrites
  10012. */
  10013. *deviceRank = 0;
  10014. return false;
  10015. }
  10016. /* If we prefer high performance, sum up all device local memory (rounded to megabytes)
  10017. * to deviceRank. In the niche case of someone having multiple dedicated GPUs in the same
  10018. * system, this theoretically picks the most powerful one (or at least the one with the
  10019. * most memory!)
  10020. *
  10021. * We do this *after* discarding all non suitable devices, which means if this computer
  10022. * has multiple dedicated GPUs that all meet our criteria, *and* the user asked for high
  10023. * performance, then we always pick the GPU with more VRAM.
  10024. */
  10025. if (!renderer->preferLowPower) {
  10026. Uint32 i;
  10027. Uint64 videoMemory = 0;
  10028. VkPhysicalDeviceMemoryProperties deviceMemory;
  10029. renderer->vkGetPhysicalDeviceMemoryProperties(physicalDevice, &deviceMemory);
  10030. for (i = 0; i < deviceMemory.memoryHeapCount; i++) {
  10031. VkMemoryHeap heap = deviceMemory.memoryHeaps[i];
  10032. if (heap.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) {
  10033. videoMemory += heap.size;
  10034. }
  10035. }
  10036. // Round it to megabytes (as per the vulkan spec videoMemory is in bytes)
  10037. Uint64 videoMemoryRounded = videoMemory / 1024 / 1024;
  10038. *deviceRank += videoMemoryRounded;
  10039. }
  10040. return true;
  10041. }
  10042. static Uint8 VULKAN_INTERNAL_IsDeviceSuitable(
  10043. VulkanRenderer *renderer,
  10044. VulkanFeatures *features,
  10045. VkPhysicalDevice physicalDevice,
  10046. VulkanExtensions *physicalDeviceExtensions,
  10047. Uint32 *queueFamilyIndex)
  10048. {
  10049. Uint32 queueFamilyCount, queueFamilyRank, queueFamilyBest;
  10050. VkQueueFamilyProperties *queueProps;
  10051. bool supportsPresent;
  10052. VkPhysicalDeviceFeatures deviceFeatures;
  10053. Uint32 i;
  10054. renderer->vkGetPhysicalDeviceFeatures(
  10055. physicalDevice,
  10056. &deviceFeatures);
  10057. if ((!deviceFeatures.independentBlend && features->desiredVulkan10DeviceFeatures.independentBlend) ||
  10058. (!deviceFeatures.imageCubeArray && features->desiredVulkan10DeviceFeatures.imageCubeArray) ||
  10059. (!deviceFeatures.depthClamp && features->desiredVulkan10DeviceFeatures.depthClamp) ||
  10060. (!deviceFeatures.shaderClipDistance && features->desiredVulkan10DeviceFeatures.shaderClipDistance) ||
  10061. (!deviceFeatures.drawIndirectFirstInstance && features->desiredVulkan10DeviceFeatures.drawIndirectFirstInstance) ||
  10062. (!deviceFeatures.sampleRateShading && features->desiredVulkan10DeviceFeatures.sampleRateShading) ||
  10063. (!deviceFeatures.samplerAnisotropy && features->desiredVulkan10DeviceFeatures.samplerAnisotropy)) {
  10064. return 0;
  10065. }
  10066. // Check opt-in device features
  10067. if (features->usesCustomVulkanOptions) {
  10068. bool supportsAllFeatures = VULKAN_INTERNAL_ValidateOptInFeatures(renderer, features, physicalDevice, &deviceFeatures);
  10069. if (!supportsAllFeatures) {
  10070. return 0;
  10071. }
  10072. }
  10073. if (!VULKAN_INTERNAL_CheckDeviceExtensions(
  10074. renderer,
  10075. features,
  10076. physicalDevice,
  10077. physicalDeviceExtensions)) {
  10078. return 0;
  10079. }
  10080. renderer->vkGetPhysicalDeviceQueueFamilyProperties(
  10081. physicalDevice,
  10082. &queueFamilyCount,
  10083. NULL);
  10084. queueProps = SDL_stack_alloc(
  10085. VkQueueFamilyProperties,
  10086. queueFamilyCount);
  10087. renderer->vkGetPhysicalDeviceQueueFamilyProperties(
  10088. physicalDevice,
  10089. &queueFamilyCount,
  10090. queueProps);
  10091. queueFamilyBest = 0;
  10092. *queueFamilyIndex = SDL_MAX_UINT32;
  10093. for (i = 0; i < queueFamilyCount; i += 1) {
  10094. supportsPresent = SDL_Vulkan_GetPresentationSupport(
  10095. renderer->instance,
  10096. physicalDevice,
  10097. i);
  10098. if (!supportsPresent ||
  10099. !(queueProps[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) {
  10100. // Not a graphics family, ignore.
  10101. continue;
  10102. }
  10103. /* The queue family bitflags are kind of annoying.
  10104. *
  10105. * We of course need a graphics family, but we ideally want the
  10106. * _primary_ graphics family. The spec states that at least one
  10107. * graphics family must also be a compute family, so generally
  10108. * drivers make that the first one. But hey, maybe something
  10109. * genuinely can't do compute or something, and FNA doesn't
  10110. * need it, so we'll be open to a non-compute queue family.
  10111. *
  10112. * Additionally, it's common to see the primary queue family
  10113. * have the transfer bit set, which is great! But this is
  10114. * actually optional; it's impossible to NOT have transfers in
  10115. * graphics/compute but it _is_ possible for a graphics/compute
  10116. * family, even the primary one, to just decide not to set the
  10117. * bitflag. Admittedly, a driver may want to isolate transfer
  10118. * queues to a dedicated family so that queues made solely for
  10119. * transfers can have an optimized DMA queue.
  10120. *
  10121. * That, or the driver author got lazy and decided not to set
  10122. * the bit. Looking at you, Android.
  10123. *
  10124. * -flibit
  10125. */
  10126. if (queueProps[i].queueFlags & VK_QUEUE_COMPUTE_BIT) {
  10127. if (queueProps[i].queueFlags & VK_QUEUE_TRANSFER_BIT) {
  10128. // Has all attribs!
  10129. queueFamilyRank = 3;
  10130. } else {
  10131. // Probably has a DMA transfer queue family
  10132. queueFamilyRank = 2;
  10133. }
  10134. } else {
  10135. // Just a graphics family, probably has something better
  10136. queueFamilyRank = 1;
  10137. }
  10138. if (queueFamilyRank > queueFamilyBest) {
  10139. *queueFamilyIndex = i;
  10140. queueFamilyBest = queueFamilyRank;
  10141. }
  10142. }
  10143. SDL_stack_free(queueProps);
  10144. if (*queueFamilyIndex == SDL_MAX_UINT32) {
  10145. // Somehow no graphics queues existed. Compute-only device?
  10146. return 0;
  10147. }
  10148. // FIXME: Need better structure for checking vs storing swapchain support details
  10149. return 1;
  10150. }
  10151. static Uint8 VULKAN_INTERNAL_DeterminePhysicalDevice(VulkanRenderer *renderer, VulkanFeatures *features)
  10152. {
  10153. VkResult vulkanResult;
  10154. VkPhysicalDevice *physicalDevices;
  10155. VulkanExtensions *physicalDeviceExtensions;
  10156. Uint32 i, physicalDeviceCount;
  10157. Sint32 suitableIndex;
  10158. Uint32 suitableQueueFamilyIndex;
  10159. Uint64 highestRank;
  10160. vulkanResult = renderer->vkEnumeratePhysicalDevices(
  10161. renderer->instance,
  10162. &physicalDeviceCount,
  10163. NULL);
  10164. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkEnumeratePhysicalDevices, 0);
  10165. if (physicalDeviceCount == 0) {
  10166. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "Failed to find any GPUs with Vulkan support");
  10167. return 0;
  10168. }
  10169. physicalDevices = SDL_stack_alloc(VkPhysicalDevice, physicalDeviceCount);
  10170. physicalDeviceExtensions = SDL_stack_alloc(VulkanExtensions, physicalDeviceCount);
  10171. vulkanResult = renderer->vkEnumeratePhysicalDevices(
  10172. renderer->instance,
  10173. &physicalDeviceCount,
  10174. physicalDevices);
  10175. /* This should be impossible to hit, but from what I can tell this can
  10176. * be triggered not because the array is too small, but because there
  10177. * were drivers that turned out to be bogus, so this is the loader's way
  10178. * of telling us that the list is now smaller than expected :shrug:
  10179. */
  10180. if (vulkanResult == VK_INCOMPLETE) {
  10181. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "vkEnumeratePhysicalDevices returned VK_INCOMPLETE, will keep trying anyway...");
  10182. vulkanResult = VK_SUCCESS;
  10183. }
  10184. if (vulkanResult != VK_SUCCESS) {
  10185. SDL_LogWarn(
  10186. SDL_LOG_CATEGORY_GPU,
  10187. "vkEnumeratePhysicalDevices failed: %s",
  10188. VkErrorMessages(vulkanResult));
  10189. SDL_stack_free(physicalDevices);
  10190. SDL_stack_free(physicalDeviceExtensions);
  10191. return 0;
  10192. }
  10193. // Any suitable device will do, but we'd like the best
  10194. suitableIndex = -1;
  10195. suitableQueueFamilyIndex = 0;
  10196. highestRank = 0;
  10197. for (i = 0; i < physicalDeviceCount; i += 1) {
  10198. Uint32 queueFamilyIndex;
  10199. Uint64 deviceRank;
  10200. if (!VULKAN_INTERNAL_IsDeviceSuitable(
  10201. renderer,
  10202. features,
  10203. physicalDevices[i],
  10204. &physicalDeviceExtensions[i],
  10205. &queueFamilyIndex)) {
  10206. // Device does not meet the minimum requirements, skip it entirely
  10207. continue;
  10208. }
  10209. deviceRank = highestRank;
  10210. if (VULKAN_INTERNAL_GetDeviceRank(
  10211. renderer,
  10212. physicalDevices[i],
  10213. &physicalDeviceExtensions[i],
  10214. &deviceRank)) {
  10215. /* Use this for rendering.
  10216. * Note that this may override a previous device that
  10217. * supports rendering, but shares the same device rank.
  10218. */
  10219. suitableIndex = i;
  10220. suitableQueueFamilyIndex = queueFamilyIndex;
  10221. highestRank = deviceRank;
  10222. }
  10223. }
  10224. if (suitableIndex != -1) {
  10225. renderer->supports = physicalDeviceExtensions[suitableIndex];
  10226. renderer->physicalDevice = physicalDevices[suitableIndex];
  10227. renderer->queueFamilyIndex = suitableQueueFamilyIndex;
  10228. } else {
  10229. SDL_stack_free(physicalDevices);
  10230. SDL_stack_free(physicalDeviceExtensions);
  10231. return 0;
  10232. }
  10233. renderer->physicalDeviceProperties.sType =
  10234. VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
  10235. if (renderer->supports.KHR_driver_properties) {
  10236. renderer->physicalDeviceDriverProperties.sType =
  10237. VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;
  10238. renderer->physicalDeviceDriverProperties.pNext = NULL;
  10239. renderer->physicalDeviceProperties.pNext =
  10240. &renderer->physicalDeviceDriverProperties;
  10241. renderer->vkGetPhysicalDeviceProperties2KHR(
  10242. renderer->physicalDevice,
  10243. &renderer->physicalDeviceProperties);
  10244. /* FIXME: This is very much a last resort to avoid WIP drivers.
  10245. *
  10246. * As far as I know, the only drivers available to users that are also
  10247. * non-conformant are incomplete Mesa drivers. hasvk is one example.
  10248. *
  10249. * It'd be nice to detect this sooner, but if this device is truly the
  10250. * best device on the system, it's the same outcome anyhow.
  10251. * -flibit
  10252. */
  10253. if (renderer->physicalDeviceDriverProperties.conformanceVersion.major < 1) {
  10254. SDL_stack_free(physicalDevices);
  10255. SDL_stack_free(physicalDeviceExtensions);
  10256. return 0;
  10257. }
  10258. } else {
  10259. renderer->physicalDeviceProperties.pNext = NULL;
  10260. renderer->vkGetPhysicalDeviceProperties(
  10261. renderer->physicalDevice,
  10262. &renderer->physicalDeviceProperties.properties);
  10263. }
  10264. renderer->vkGetPhysicalDeviceMemoryProperties(
  10265. renderer->physicalDevice,
  10266. &renderer->memoryProperties);
  10267. SDL_stack_free(physicalDevices);
  10268. SDL_stack_free(physicalDeviceExtensions);
  10269. return 1;
  10270. }
  10271. static Uint8 VULKAN_INTERNAL_CreateLogicalDevice(
  10272. VulkanRenderer *renderer,
  10273. VulkanFeatures *features)
  10274. {
  10275. VkResult vulkanResult;
  10276. VkDeviceCreateInfo deviceCreateInfo;
  10277. VkPhysicalDeviceFeatures haveDeviceFeatures;
  10278. VkPhysicalDevicePortabilitySubsetFeaturesKHR portabilityFeatures;
  10279. const char **deviceExtensions;
  10280. VkDeviceQueueCreateInfo queueCreateInfo;
  10281. float queuePriority = 1.0f;
  10282. queueCreateInfo.sType =
  10283. VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  10284. queueCreateInfo.pNext = NULL;
  10285. queueCreateInfo.flags = 0;
  10286. queueCreateInfo.queueFamilyIndex = renderer->queueFamilyIndex;
  10287. queueCreateInfo.queueCount = 1;
  10288. queueCreateInfo.pQueuePriorities = &queuePriority;
  10289. // check feature support
  10290. renderer->vkGetPhysicalDeviceFeatures(
  10291. renderer->physicalDevice,
  10292. &haveDeviceFeatures);
  10293. // specifying used device features
  10294. if (haveDeviceFeatures.fillModeNonSolid) {
  10295. features->desiredVulkan10DeviceFeatures.fillModeNonSolid = VK_TRUE;
  10296. renderer->supportsFillModeNonSolid = true;
  10297. }
  10298. if (haveDeviceFeatures.multiDrawIndirect) {
  10299. features->desiredVulkan10DeviceFeatures.multiDrawIndirect = VK_TRUE;
  10300. renderer->supportsMultiDrawIndirect = true;
  10301. }
  10302. // creating the logical device
  10303. deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
  10304. if (renderer->supports.KHR_portability_subset) {
  10305. portabilityFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PORTABILITY_SUBSET_FEATURES_KHR;
  10306. portabilityFeatures.pNext = NULL;
  10307. portabilityFeatures.constantAlphaColorBlendFactors = VK_FALSE;
  10308. portabilityFeatures.events = VK_FALSE;
  10309. portabilityFeatures.imageViewFormatReinterpretation = VK_FALSE;
  10310. portabilityFeatures.imageViewFormatSwizzle = VK_TRUE;
  10311. portabilityFeatures.imageView2DOn3DImage = VK_FALSE;
  10312. portabilityFeatures.multisampleArrayImage = VK_FALSE;
  10313. portabilityFeatures.mutableComparisonSamplers = VK_FALSE;
  10314. portabilityFeatures.pointPolygons = VK_FALSE;
  10315. portabilityFeatures.samplerMipLodBias = VK_FALSE; // Technically should be true, but eh
  10316. portabilityFeatures.separateStencilMaskRef = VK_FALSE;
  10317. portabilityFeatures.shaderSampleRateInterpolationFunctions = VK_FALSE;
  10318. portabilityFeatures.tessellationIsolines = VK_FALSE;
  10319. portabilityFeatures.tessellationPointMode = VK_FALSE;
  10320. portabilityFeatures.triangleFans = VK_FALSE;
  10321. portabilityFeatures.vertexAttributeAccessBeyondStride = VK_FALSE;
  10322. deviceCreateInfo.pNext = &portabilityFeatures;
  10323. } else {
  10324. deviceCreateInfo.pNext = NULL;
  10325. }
  10326. deviceCreateInfo.flags = 0;
  10327. deviceCreateInfo.queueCreateInfoCount = 1;
  10328. deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo;
  10329. deviceCreateInfo.enabledLayerCount = 0;
  10330. deviceCreateInfo.ppEnabledLayerNames = NULL;
  10331. deviceCreateInfo.enabledExtensionCount = GetDeviceExtensionCount(
  10332. &renderer->supports);
  10333. deviceExtensions = SDL_stack_alloc(
  10334. const char *,
  10335. deviceCreateInfo.enabledExtensionCount);
  10336. CreateDeviceExtensionArray(&renderer->supports, deviceExtensions);
  10337. deviceCreateInfo.ppEnabledExtensionNames = deviceExtensions;
  10338. VkPhysicalDeviceFeatures2 featureList;
  10339. int minor = VK_VERSION_MINOR(features->desiredApiVersion);
  10340. struct {
  10341. VkPhysicalDevice16BitStorageFeatures storage;
  10342. VkPhysicalDeviceMultiviewFeatures multiview;
  10343. VkPhysicalDeviceProtectedMemoryFeatures protectedMem;
  10344. VkPhysicalDeviceSamplerYcbcrConversionFeatures ycbcr;
  10345. VkPhysicalDeviceShaderDrawParametersFeatures drawParams;
  10346. VkPhysicalDeviceVariablePointersFeatures varPointers;
  10347. } legacyFeatures;
  10348. if (features->usesCustomVulkanOptions && minor > 0) {
  10349. featureList.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  10350. featureList.features = features->desiredVulkan10DeviceFeatures;
  10351. if (minor > 1) {
  10352. featureList.pNext = &features->desiredVulkan11DeviceFeatures;
  10353. features->desiredVulkan11DeviceFeatures.pNext = &features->desiredVulkan12DeviceFeatures;
  10354. features->desiredVulkan12DeviceFeatures.pNext = minor > 2 ? &features->desiredVulkan13DeviceFeatures : NULL;
  10355. features->desiredVulkan13DeviceFeatures.pNext = NULL;
  10356. } else {
  10357. // Break VkPhysicalDeviceVulkan11Features into pre 1.2 structures for Vulkan 1.1 Support
  10358. SDL_zero(legacyFeatures);
  10359. legacyFeatures.storage.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES;
  10360. legacyFeatures.storage.storageBuffer16BitAccess = features->desiredVulkan11DeviceFeatures.storageBuffer16BitAccess;
  10361. legacyFeatures.storage.storageInputOutput16 = features->desiredVulkan11DeviceFeatures.storageInputOutput16;
  10362. legacyFeatures.storage.storagePushConstant16 = features->desiredVulkan11DeviceFeatures.storagePushConstant16;
  10363. legacyFeatures.storage.uniformAndStorageBuffer16BitAccess = features->desiredVulkan11DeviceFeatures.uniformAndStorageBuffer16BitAccess;
  10364. legacyFeatures.multiview.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES;
  10365. legacyFeatures.multiview.multiview = features->desiredVulkan11DeviceFeatures.multiview;
  10366. legacyFeatures.multiview.multiviewGeometryShader = features->desiredVulkan11DeviceFeatures.multiviewGeometryShader;
  10367. legacyFeatures.multiview.multiviewTessellationShader = features->desiredVulkan11DeviceFeatures.multiviewTessellationShader;
  10368. legacyFeatures.protectedMem.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES;
  10369. legacyFeatures.protectedMem.protectedMemory = features->desiredVulkan11DeviceFeatures.protectedMemory;
  10370. legacyFeatures.ycbcr.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES;
  10371. legacyFeatures.ycbcr.samplerYcbcrConversion = features->desiredVulkan11DeviceFeatures.samplerYcbcrConversion;
  10372. legacyFeatures.drawParams.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES;
  10373. legacyFeatures.drawParams.shaderDrawParameters = features->desiredVulkan11DeviceFeatures.shaderDrawParameters;
  10374. legacyFeatures.varPointers.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES;
  10375. legacyFeatures.varPointers.variablePointers = features->desiredVulkan11DeviceFeatures.variablePointers;
  10376. legacyFeatures.varPointers.variablePointersStorageBuffer = features->desiredVulkan11DeviceFeatures.variablePointersStorageBuffer;
  10377. featureList.pNext = &legacyFeatures.storage;
  10378. legacyFeatures.storage.pNext = &legacyFeatures.multiview;
  10379. legacyFeatures.multiview.pNext = &legacyFeatures.protectedMem;
  10380. legacyFeatures.protectedMem.pNext = &legacyFeatures.ycbcr;
  10381. legacyFeatures.ycbcr.pNext = &legacyFeatures.drawParams;
  10382. legacyFeatures.drawParams.pNext = &legacyFeatures.varPointers;
  10383. }
  10384. deviceCreateInfo.pEnabledFeatures = NULL;
  10385. deviceCreateInfo.pNext = &featureList;
  10386. } else {
  10387. deviceCreateInfo.pEnabledFeatures = &features->desiredVulkan10DeviceFeatures;
  10388. }
  10389. vulkanResult = renderer->vkCreateDevice(
  10390. renderer->physicalDevice,
  10391. &deviceCreateInfo,
  10392. NULL,
  10393. &renderer->logicalDevice);
  10394. SDL_stack_free((void *)deviceExtensions);
  10395. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateDevice, 0);
  10396. // Load vkDevice entry points
  10397. #define VULKAN_DEVICE_FUNCTION(func) \
  10398. renderer->func = (PFN_##func) \
  10399. renderer->vkGetDeviceProcAddr( \
  10400. renderer->logicalDevice, \
  10401. #func);
  10402. #include "SDL_gpu_vulkan_vkfuncs.h"
  10403. renderer->vkGetDeviceQueue(
  10404. renderer->logicalDevice,
  10405. renderer->queueFamilyIndex,
  10406. 0,
  10407. &renderer->unifiedQueue);
  10408. return 1;
  10409. }
  10410. static void VULKAN_INTERNAL_LoadEntryPoints(void)
  10411. {
  10412. // Required for MoltenVK support
  10413. SDL_setenv_unsafe("MVK_CONFIG_FULL_IMAGE_VIEW_SWIZZLE", "1", 1);
  10414. // Load Vulkan entry points
  10415. if (!SDL_Vulkan_LoadLibrary(NULL)) {
  10416. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Vulkan: SDL_Vulkan_LoadLibrary failed!");
  10417. return;
  10418. }
  10419. #ifdef HAVE_GCC_DIAGNOSTIC_PRAGMA
  10420. #pragma GCC diagnostic push
  10421. #pragma GCC diagnostic ignored "-Wpedantic"
  10422. #endif
  10423. vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_Vulkan_GetVkGetInstanceProcAddr();
  10424. #ifdef HAVE_GCC_DIAGNOSTIC_PRAGMA
  10425. #pragma GCC diagnostic pop
  10426. #endif
  10427. if (vkGetInstanceProcAddr == NULL) {
  10428. SDL_LogWarn(
  10429. SDL_LOG_CATEGORY_GPU,
  10430. "SDL_Vulkan_GetVkGetInstanceProcAddr(): %s",
  10431. SDL_GetError());
  10432. return;
  10433. }
  10434. #define VULKAN_GLOBAL_FUNCTION(name) \
  10435. name = (PFN_##name)vkGetInstanceProcAddr(VK_NULL_HANDLE, #name); \
  10436. if (name == NULL) { \
  10437. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "vkGetInstanceProcAddr(VK_NULL_HANDLE, \"" #name "\") failed"); \
  10438. return; \
  10439. }
  10440. #include "SDL_gpu_vulkan_vkfuncs.h"
  10441. }
  10442. static bool VULKAN_INTERNAL_PrepareVulkan(
  10443. VulkanRenderer *renderer,
  10444. VulkanFeatures *features,
  10445. SDL_PropertiesID props)
  10446. {
  10447. VULKAN_INTERNAL_LoadEntryPoints();
  10448. SDL_zerop(features);
  10449. // Opt out device features (higher compatibility in exchange for reduced functionality)
  10450. features->desiredVulkan10DeviceFeatures.samplerAnisotropy = SDL_GetBooleanProperty(props, SDL_PROP_GPU_DEVICE_CREATE_FEATURE_ANISOTROPY_BOOLEAN, true) ? VK_TRUE : VK_FALSE;
  10451. features->desiredVulkan10DeviceFeatures.depthClamp = SDL_GetBooleanProperty(props, SDL_PROP_GPU_DEVICE_CREATE_FEATURE_DEPTH_CLAMPING_BOOLEAN, true) ? VK_TRUE : VK_FALSE;
  10452. features->desiredVulkan10DeviceFeatures.shaderClipDistance = SDL_GetBooleanProperty(props, SDL_PROP_GPU_DEVICE_CREATE_FEATURE_CLIP_DISTANCE_BOOLEAN, true) ? VK_TRUE : VK_FALSE;
  10453. features->desiredVulkan10DeviceFeatures.drawIndirectFirstInstance = SDL_GetBooleanProperty(props, SDL_PROP_GPU_DEVICE_CREATE_FEATURE_INDIRECT_DRAW_FIRST_INSTANCE_BOOLEAN, true) ? VK_TRUE : VK_FALSE;
  10454. // These features have near universal support so they are always enabled
  10455. features->desiredVulkan10DeviceFeatures.independentBlend = VK_TRUE;
  10456. features->desiredVulkan10DeviceFeatures.sampleRateShading = VK_TRUE;
  10457. features->desiredVulkan10DeviceFeatures.imageCubeArray = VK_TRUE;
  10458. // Handle opt-in device features
  10459. VULKAN_INTERNAL_AddOptInVulkanOptions(props, renderer, features);
  10460. renderer->requireHardwareAcceleration = SDL_GetBooleanProperty(props, SDL_PROP_GPU_DEVICE_CREATE_VULKAN_REQUIRE_HARDWARE_ACCELERATION_BOOLEAN, false);
  10461. if (!VULKAN_INTERNAL_CreateInstance(renderer, features)) {
  10462. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Vulkan: Could not create Vulkan instance");
  10463. return false;
  10464. }
  10465. #define VULKAN_INSTANCE_FUNCTION(func) \
  10466. renderer->func = (PFN_##func)vkGetInstanceProcAddr(renderer->instance, #func);
  10467. #include "SDL_gpu_vulkan_vkfuncs.h"
  10468. if (!VULKAN_INTERNAL_DeterminePhysicalDevice(renderer, features)) {
  10469. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Vulkan: Failed to determine a suitable physical device");
  10470. return false;
  10471. }
  10472. return true;
  10473. }
  10474. static bool VULKAN_PrepareDriver(SDL_VideoDevice *_this, SDL_PropertiesID props)
  10475. {
  10476. // Set up dummy VulkanRenderer
  10477. VulkanRenderer *renderer;
  10478. VulkanFeatures features;
  10479. bool result = false;
  10480. if (!SDL_GetBooleanProperty(props, SDL_PROP_GPU_DEVICE_CREATE_SHADERS_SPIRV_BOOLEAN, false)) {
  10481. return false;
  10482. }
  10483. if (_this->Vulkan_CreateSurface == NULL) {
  10484. return false;
  10485. }
  10486. if (!SDL_Vulkan_LoadLibrary(NULL)) {
  10487. return false;
  10488. }
  10489. renderer = (VulkanRenderer *)SDL_calloc(1, sizeof(*renderer));
  10490. if (renderer) {
  10491. // This needs to be set early for log filtering
  10492. renderer->debugMode = SDL_GetBooleanProperty(props, SDL_PROP_GPU_DEVICE_CREATE_DEBUGMODE_BOOLEAN, false);
  10493. renderer->preferLowPower = SDL_GetBooleanProperty(props, SDL_PROP_GPU_DEVICE_CREATE_PREFERLOWPOWER_BOOLEAN, false);
  10494. result = VULKAN_INTERNAL_PrepareVulkan(renderer, &features, props);
  10495. if (result) {
  10496. renderer->vkDestroyInstance(renderer->instance, NULL);
  10497. }
  10498. SDL_free(renderer);
  10499. }
  10500. SDL_Vulkan_UnloadLibrary();
  10501. return result;
  10502. }
  10503. static SDL_GPUDevice *VULKAN_CreateDevice(bool debugMode, bool preferLowPower, SDL_PropertiesID props)
  10504. {
  10505. VulkanRenderer *renderer;
  10506. VulkanFeatures features;
  10507. SDL_GPUDevice *result;
  10508. Uint32 i;
  10509. bool verboseLogs = SDL_GetBooleanProperty(
  10510. props,
  10511. SDL_PROP_GPU_DEVICE_CREATE_VERBOSE_BOOLEAN,
  10512. true);
  10513. if (!SDL_Vulkan_LoadLibrary(NULL)) {
  10514. SDL_assert(!"This should have failed in PrepareDevice first!");
  10515. return NULL;
  10516. }
  10517. renderer = (VulkanRenderer *)SDL_calloc(1, sizeof(*renderer));
  10518. if (!renderer) {
  10519. SDL_Vulkan_UnloadLibrary();
  10520. return NULL;
  10521. }
  10522. renderer->debugMode = debugMode;
  10523. renderer->preferLowPower = preferLowPower;
  10524. renderer->allowedFramesInFlight = 2;
  10525. if (!VULKAN_INTERNAL_PrepareVulkan(renderer, &features, props)) {
  10526. SET_STRING_ERROR("Failed to initialize Vulkan!");
  10527. SDL_free(renderer);
  10528. SDL_Vulkan_UnloadLibrary();
  10529. return NULL;
  10530. }
  10531. renderer->props = SDL_CreateProperties();
  10532. if (verboseLogs) {
  10533. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "SDL_GPU Driver: Vulkan");
  10534. }
  10535. // Record device name
  10536. const char *deviceName = renderer->physicalDeviceProperties.properties.deviceName;
  10537. SDL_SetStringProperty(
  10538. renderer->props,
  10539. SDL_PROP_GPU_DEVICE_NAME_STRING,
  10540. deviceName);
  10541. if (verboseLogs) {
  10542. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "Vulkan Device: %s", deviceName);
  10543. }
  10544. // Record driver version. This is provided as a backup if
  10545. // VK_KHR_driver_properties is not available but as most drivers support it
  10546. // this property should be rarely used.
  10547. //
  10548. // This uses a vendor-specific encoding and it isn't well documented. The
  10549. // vendor ID is the registered PCI ID of the vendor and can be found in
  10550. // online databases.
  10551. char driverVer[64];
  10552. Uint32 rawDriverVer = renderer->physicalDeviceProperties.properties.driverVersion;
  10553. Uint32 vendorId = renderer->physicalDeviceProperties.properties.vendorID;
  10554. if (vendorId == 0x10de) {
  10555. // Nvidia uses 10|8|8|6 encoding.
  10556. (void)SDL_snprintf(
  10557. driverVer,
  10558. SDL_arraysize(driverVer),
  10559. "%d.%d.%d.%d",
  10560. (rawDriverVer >> 22) & 0x3ff,
  10561. (rawDriverVer >> 14) & 0xff,
  10562. (rawDriverVer >> 6) & 0xff,
  10563. rawDriverVer & 0x3f);
  10564. }
  10565. #ifdef SDL_PLATFORM_WINDOWS
  10566. else if (vendorId == 0x8086) {
  10567. // Intel uses 18|14 encoding on Windows only.
  10568. (void)SDL_snprintf(
  10569. driverVer,
  10570. SDL_arraysize(driverVer),
  10571. "%d.%d",
  10572. (rawDriverVer >> 14) & 0x3ffff,
  10573. rawDriverVer & 0x3fff);
  10574. }
  10575. #endif
  10576. else {
  10577. // Assume standard Vulkan 10|10|12 encoding for everything else. AMD and
  10578. // Mesa are known to use this encoding.
  10579. (void)SDL_snprintf(
  10580. driverVer,
  10581. SDL_arraysize(driverVer),
  10582. "%d.%d.%d",
  10583. (rawDriverVer >> 22) & 0x3ff,
  10584. (rawDriverVer >> 12) & 0x3ff,
  10585. rawDriverVer & 0xfff);
  10586. }
  10587. SDL_SetStringProperty(
  10588. renderer->props,
  10589. SDL_PROP_GPU_DEVICE_DRIVER_VERSION_STRING,
  10590. driverVer);
  10591. // Log this only if VK_KHR_driver_properties is not available.
  10592. if (renderer->supports.KHR_driver_properties) {
  10593. // Record driver name and version
  10594. const char *driverName = renderer->physicalDeviceDriverProperties.driverName;
  10595. const char *driverInfo = renderer->physicalDeviceDriverProperties.driverInfo;
  10596. SDL_SetStringProperty(
  10597. renderer->props,
  10598. SDL_PROP_GPU_DEVICE_DRIVER_NAME_STRING,
  10599. driverName);
  10600. SDL_SetStringProperty(
  10601. renderer->props,
  10602. SDL_PROP_GPU_DEVICE_DRIVER_INFO_STRING,
  10603. driverInfo);
  10604. if (verboseLogs) {
  10605. // FIXME: driverInfo can be a multiline string.
  10606. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "Vulkan Driver: %s %s", driverName, driverInfo);
  10607. }
  10608. // Record conformance level
  10609. if (verboseLogs) {
  10610. char conformance[64];
  10611. (void)SDL_snprintf(
  10612. conformance,
  10613. SDL_arraysize(conformance),
  10614. "%u.%u.%u.%u",
  10615. renderer->physicalDeviceDriverProperties.conformanceVersion.major,
  10616. renderer->physicalDeviceDriverProperties.conformanceVersion.minor,
  10617. renderer->physicalDeviceDriverProperties.conformanceVersion.subminor,
  10618. renderer->physicalDeviceDriverProperties.conformanceVersion.patch);
  10619. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "Vulkan Conformance: %s", conformance);
  10620. }
  10621. } else {
  10622. if (verboseLogs) {
  10623. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "Vulkan Driver: %s", driverVer);
  10624. }
  10625. }
  10626. if (!VULKAN_INTERNAL_CreateLogicalDevice(renderer, &features)) {
  10627. SET_STRING_ERROR("Failed to create logical device!");
  10628. SDL_free(renderer);
  10629. SDL_Vulkan_UnloadLibrary();
  10630. return NULL;
  10631. }
  10632. // FIXME: just move this into this function
  10633. result = (SDL_GPUDevice *)SDL_calloc(1, sizeof(SDL_GPUDevice));
  10634. ASSIGN_DRIVER(VULKAN)
  10635. result->driverData = (SDL_GPURenderer *)renderer;
  10636. result->shader_formats = SDL_GPU_SHADERFORMAT_SPIRV;
  10637. /*
  10638. * Create initial swapchain array
  10639. */
  10640. renderer->claimedWindowCapacity = 1;
  10641. renderer->claimedWindowCount = 0;
  10642. renderer->claimedWindows = SDL_malloc(
  10643. renderer->claimedWindowCapacity * sizeof(WindowData *));
  10644. // Threading
  10645. renderer->allocatorLock = SDL_CreateMutex();
  10646. renderer->disposeLock = SDL_CreateMutex();
  10647. renderer->submitLock = SDL_CreateMutex();
  10648. renderer->acquireCommandBufferLock = SDL_CreateMutex();
  10649. renderer->acquireUniformBufferLock = SDL_CreateMutex();
  10650. renderer->renderPassFetchLock = SDL_CreateMutex();
  10651. renderer->framebufferFetchLock = SDL_CreateMutex();
  10652. renderer->graphicsPipelineLayoutFetchLock = SDL_CreateMutex();
  10653. renderer->computePipelineLayoutFetchLock = SDL_CreateMutex();
  10654. renderer->descriptorSetLayoutFetchLock = SDL_CreateMutex();
  10655. renderer->windowLock = SDL_CreateMutex();
  10656. /*
  10657. * Create submitted command buffer list
  10658. */
  10659. renderer->submittedCommandBufferCapacity = 16;
  10660. renderer->submittedCommandBufferCount = 0;
  10661. renderer->submittedCommandBuffers = SDL_malloc(sizeof(VulkanCommandBuffer *) * renderer->submittedCommandBufferCapacity);
  10662. // Memory Allocator
  10663. renderer->memoryAllocator = (VulkanMemoryAllocator *)SDL_malloc(
  10664. sizeof(VulkanMemoryAllocator));
  10665. for (i = 0; i < VK_MAX_MEMORY_TYPES; i += 1) {
  10666. renderer->memoryAllocator->subAllocators[i].memoryTypeIndex = i;
  10667. renderer->memoryAllocator->subAllocators[i].allocations = NULL;
  10668. renderer->memoryAllocator->subAllocators[i].allocationCount = 0;
  10669. renderer->memoryAllocator->subAllocators[i].sortedFreeRegions = SDL_malloc(
  10670. sizeof(VulkanMemoryFreeRegion *) * 4);
  10671. renderer->memoryAllocator->subAllocators[i].sortedFreeRegionCount = 0;
  10672. renderer->memoryAllocator->subAllocators[i].sortedFreeRegionCapacity = 4;
  10673. }
  10674. // Create uniform buffer pool
  10675. renderer->uniformBufferPoolCount = 32;
  10676. renderer->uniformBufferPoolCapacity = 32;
  10677. renderer->uniformBufferPool = SDL_malloc(
  10678. renderer->uniformBufferPoolCapacity * sizeof(VulkanUniformBuffer *));
  10679. for (i = 0; i < renderer->uniformBufferPoolCount; i += 1) {
  10680. renderer->uniformBufferPool[i] = VULKAN_INTERNAL_CreateUniformBuffer(
  10681. renderer,
  10682. UNIFORM_BUFFER_SIZE);
  10683. }
  10684. renderer->descriptorSetCachePoolCapacity = 8;
  10685. renderer->descriptorSetCachePoolCount = 0;
  10686. renderer->descriptorSetCachePool = SDL_calloc(renderer->descriptorSetCachePoolCapacity, sizeof(DescriptorSetCache *));
  10687. SDL_SetAtomicInt(&renderer->layoutResourceID, 0);
  10688. // Device limits
  10689. renderer->minUBOAlignment = (Uint32)renderer->physicalDeviceProperties.properties.limits.minUniformBufferOffsetAlignment;
  10690. // Initialize caches
  10691. renderer->commandPoolHashTable = SDL_CreateHashTable(
  10692. 0, // !!! FIXME: a real guess here, for a _minimum_ if not a maximum, could be useful.
  10693. false, // manually synchronized due to submission timing
  10694. VULKAN_INTERNAL_CommandPoolHashFunction,
  10695. VULKAN_INTERNAL_CommandPoolHashKeyMatch,
  10696. VULKAN_INTERNAL_CommandPoolHashDestroy,
  10697. (void *)renderer);
  10698. renderer->renderPassHashTable = SDL_CreateHashTable(
  10699. 0, // !!! FIXME: a real guess here, for a _minimum_ if not a maximum, could be useful.
  10700. false, // manually synchronized due to lookup timing
  10701. VULKAN_INTERNAL_RenderPassHashFunction,
  10702. VULKAN_INTERNAL_RenderPassHashKeyMatch,
  10703. VULKAN_INTERNAL_RenderPassHashDestroy,
  10704. (void *)renderer);
  10705. renderer->framebufferHashTable = SDL_CreateHashTable(
  10706. 0, // !!! FIXME: a real guess here, for a _minimum_ if not a maximum, could be useful.
  10707. false, // manually synchronized due to iteration
  10708. VULKAN_INTERNAL_FramebufferHashFunction,
  10709. VULKAN_INTERNAL_FramebufferHashKeyMatch,
  10710. VULKAN_INTERNAL_FramebufferHashDestroy,
  10711. (void *)renderer);
  10712. renderer->graphicsPipelineResourceLayoutHashTable = SDL_CreateHashTable(
  10713. 0, // !!! FIXME: a real guess here, for a _minimum_ if not a maximum, could be useful.
  10714. false, // manually synchronized due to lookup timing
  10715. VULKAN_INTERNAL_GraphicsPipelineResourceLayoutHashFunction,
  10716. VULKAN_INTERNAL_GraphicsPipelineResourceLayoutHashKeyMatch,
  10717. VULKAN_INTERNAL_GraphicsPipelineResourceLayoutHashDestroy,
  10718. (void *)renderer);
  10719. renderer->computePipelineResourceLayoutHashTable = SDL_CreateHashTable(
  10720. 0, // !!! FIXME: a real guess here, for a _minimum_ if not a maximum, could be useful.
  10721. false, // manually synchronized due to lookup timing
  10722. VULKAN_INTERNAL_ComputePipelineResourceLayoutHashFunction,
  10723. VULKAN_INTERNAL_ComputePipelineResourceLayoutHashKeyMatch,
  10724. VULKAN_INTERNAL_ComputePipelineResourceLayoutHashDestroy,
  10725. (void *)renderer);
  10726. renderer->descriptorSetLayoutHashTable = SDL_CreateHashTable(
  10727. 0, // !!! FIXME: a real guess here, for a _minimum_ if not a maximum, could be useful.
  10728. false, // manually synchronized due to lookup timing
  10729. VULKAN_INTERNAL_DescriptorSetLayoutHashFunction,
  10730. VULKAN_INTERNAL_DescriptorSetLayoutHashKeyMatch,
  10731. VULKAN_INTERNAL_DescriptorSetLayoutHashDestroy,
  10732. (void *)renderer);
  10733. // Initialize fence pool
  10734. renderer->fencePool.lock = SDL_CreateMutex();
  10735. renderer->fencePool.availableFenceCapacity = 4;
  10736. renderer->fencePool.availableFenceCount = 0;
  10737. renderer->fencePool.availableFences = SDL_malloc(
  10738. renderer->fencePool.availableFenceCapacity * sizeof(VulkanFenceHandle *));
  10739. // Deferred destroy storage
  10740. renderer->texturesToDestroyCapacity = 16;
  10741. renderer->texturesToDestroyCount = 0;
  10742. renderer->texturesToDestroy = (VulkanTexture **)SDL_malloc(
  10743. sizeof(VulkanTexture *) *
  10744. renderer->texturesToDestroyCapacity);
  10745. renderer->buffersToDestroyCapacity = 16;
  10746. renderer->buffersToDestroyCount = 0;
  10747. renderer->buffersToDestroy = SDL_malloc(
  10748. sizeof(VulkanBuffer *) *
  10749. renderer->buffersToDestroyCapacity);
  10750. renderer->samplersToDestroyCapacity = 16;
  10751. renderer->samplersToDestroyCount = 0;
  10752. renderer->samplersToDestroy = SDL_malloc(
  10753. sizeof(VulkanSampler *) *
  10754. renderer->samplersToDestroyCapacity);
  10755. renderer->graphicsPipelinesToDestroyCapacity = 16;
  10756. renderer->graphicsPipelinesToDestroyCount = 0;
  10757. renderer->graphicsPipelinesToDestroy = SDL_malloc(
  10758. sizeof(VulkanGraphicsPipeline *) *
  10759. renderer->graphicsPipelinesToDestroyCapacity);
  10760. renderer->computePipelinesToDestroyCapacity = 16;
  10761. renderer->computePipelinesToDestroyCount = 0;
  10762. renderer->computePipelinesToDestroy = SDL_malloc(
  10763. sizeof(VulkanComputePipeline *) *
  10764. renderer->computePipelinesToDestroyCapacity);
  10765. renderer->shadersToDestroyCapacity = 16;
  10766. renderer->shadersToDestroyCount = 0;
  10767. renderer->shadersToDestroy = SDL_malloc(
  10768. sizeof(VulkanShader *) *
  10769. renderer->shadersToDestroyCapacity);
  10770. renderer->framebuffersToDestroyCapacity = 16;
  10771. renderer->framebuffersToDestroyCount = 0;
  10772. renderer->framebuffersToDestroy = SDL_malloc(
  10773. sizeof(VulkanFramebuffer *) *
  10774. renderer->framebuffersToDestroyCapacity);
  10775. // Defrag state
  10776. renderer->defragInProgress = 0;
  10777. renderer->allocationsToDefragCount = 0;
  10778. renderer->allocationsToDefragCapacity = 4;
  10779. renderer->allocationsToDefrag = SDL_malloc(
  10780. renderer->allocationsToDefragCapacity * sizeof(VulkanMemoryAllocation *));
  10781. return result;
  10782. }
  10783. SDL_GPUBootstrap VulkanDriver = {
  10784. "vulkan",
  10785. VULKAN_PrepareDriver,
  10786. VULKAN_CreateDevice
  10787. };
  10788. #endif // SDL_GPU_VULKAN