SDL_gpu_vulkan.c 437 KB

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