SDL_gpu_vulkan.c 423 KB

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