SDL_gpu_vulkan.c 418 KB

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