SDL_gpu_vulkan.c 451 KB

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