SDL_gpu_vulkan.c 449 KB

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