SDL_gpu_vulkan.c 434 KB

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