SDL_gpu_d3d11.c 220 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #ifdef SDL_GPU_D3D11
  20. #define D3D11_NO_HELPERS
  21. #define CINTERFACE
  22. #define COBJMACROS
  23. #include <d3d11.h>
  24. #include <d3d11_1.h>
  25. #include <dxgi.h>
  26. #include <dxgi1_6.h>
  27. #include <dxgidebug.h>
  28. #include "../SDL_sysgpu.h"
  29. #ifdef __IDXGIInfoQueue_INTERFACE_DEFINED__
  30. #define HAVE_IDXGIINFOQUEUE
  31. #endif
  32. // Function Pointer Signatures
  33. typedef HRESULT(WINAPI *PFN_CREATE_DXGI_FACTORY1)(const GUID *riid, void **ppFactory);
  34. typedef HRESULT(WINAPI *PFN_DXGI_GET_DEBUG_INTERFACE)(const GUID *riid, void **ppDebug);
  35. // IIDs (from https://www.magnumdb.com/)
  36. static const IID D3D_IID_IDXGIFactory1 = { 0x770aae78, 0xf26f, 0x4dba, { 0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87 } };
  37. static const IID D3D_IID_IDXGIFactory4 = { 0x1bc6ea02, 0xef36, 0x464f, { 0xbf, 0x0c, 0x21, 0xca, 0x39, 0xe5, 0x16, 0x8a } };
  38. static const IID D3D_IID_IDXGIFactory5 = { 0x7632e1f5, 0xee65, 0x4dca, { 0x87, 0xfd, 0x84, 0xcd, 0x75, 0xf8, 0x83, 0x8d } };
  39. static const IID D3D_IID_IDXGIFactory6 = { 0xc1b6694f, 0xff09, 0x44a9, { 0xb0, 0x3c, 0x77, 0x90, 0x0a, 0x0a, 0x1d, 0x17 } };
  40. static const IID D3D_IID_IDXGIAdapter1 = { 0x29038f61, 0x3839, 0x4626, { 0x91, 0xfd, 0x08, 0x68, 0x79, 0x01, 0x1a, 0x05 } };
  41. static const IID D3D_IID_IDXGISwapChain3 = { 0x94d99bdb, 0xf1f8, 0x4ab0, { 0xb2, 0x36, 0x7d, 0xa0, 0x17, 0x0e, 0xda, 0xb1 } };
  42. static const IID D3D_IID_ID3D11Texture2D = { 0x6f15aaf2, 0xd208, 0x4e89, { 0x9a, 0xb4, 0x48, 0x95, 0x35, 0xd3, 0x4f, 0x9c } };
  43. static const IID D3D_IID_ID3DUserDefinedAnnotation = { 0xb2daad8b, 0x03d4, 0x4dbf, { 0x95, 0xeb, 0x32, 0xab, 0x4b, 0x63, 0xd0, 0xab } };
  44. static const IID D3D_IID_ID3D11Device1 = { 0xa04bfb29, 0x08ef, 0x43d6, { 0xa4, 0x9c, 0xa9, 0xbd, 0xbd, 0xcb, 0xe6, 0x86 } };
  45. static const IID D3D_IID_IDXGIDebug = { 0x119e7452, 0xde9e, 0x40fe, { 0x88, 0x06, 0x88, 0xf9, 0x0c, 0x12, 0xb4, 0x41 } };
  46. #ifdef HAVE_IDXGIINFOQUEUE
  47. static const IID D3D_IID_IDXGIInfoQueue = { 0xd67441c7, 0x672a, 0x476f, { 0x9e, 0x82, 0xcd, 0x55, 0xb4, 0x49, 0x49, 0xce } };
  48. #endif
  49. static const GUID D3D_IID_D3DDebugObjectName = { 0x429b8c22, 0x9188, 0x4b0c, { 0x87, 0x42, 0xac, 0xb0, 0xbf, 0x85, 0xc2, 0x00 } };
  50. static const GUID D3D_IID_DXGI_DEBUG_ALL = { 0xe48ae283, 0xda80, 0x490b, { 0x87, 0xe6, 0x43, 0xe9, 0xa9, 0xcf, 0xda, 0x08 } };
  51. // Defines
  52. #if defined(_WIN32)
  53. #define D3D11_DLL "d3d11.dll"
  54. #define DXGI_DLL "dxgi.dll"
  55. #define DXGIDEBUG_DLL "dxgidebug.dll"
  56. #elif defined(__APPLE__)
  57. #define D3D11_DLL "libdxvk_d3d11.0.dylib"
  58. #define DXGI_DLL "libdxvk_dxgi.0.dylib"
  59. #define DXGIDEBUG_DLL "libdxvk_dxgidebug.0.dylib"
  60. #else
  61. #define D3D11_DLL "libdxvk_d3d11.so.0"
  62. #define DXGI_DLL "libdxvk_dxgi.so.0"
  63. #define DXGIDEBUG_DLL "libdxvk_dxgidebug.so.0"
  64. #endif
  65. #define D3D11_CREATE_DEVICE_FUNC "D3D11CreateDevice"
  66. #define CREATE_DXGI_FACTORY1_FUNC "CreateDXGIFactory1"
  67. #define DXGI_GET_DEBUG_INTERFACE_FUNC "DXGIGetDebugInterface"
  68. #define WINDOW_PROPERTY_DATA "SDL_GPUD3D11WindowPropertyData"
  69. #define SDL_GPU_SHADERSTAGE_COMPUTE 2
  70. #ifdef _WIN32
  71. #define HRESULT_FMT "(0x%08lX)"
  72. #else
  73. #define HRESULT_FMT "(0x%08X)"
  74. #endif
  75. // Built-in shaders, compiled with compile_shaders.bat
  76. #define g_FullscreenVert D3D11_FullscreenVert
  77. #define g_BlitFrom2D D3D11_BlitFrom2D
  78. #define g_BlitFrom2DArray D3D11_BlitFrom2DArray
  79. #define g_BlitFrom3D D3D11_BlitFrom3D
  80. #define g_BlitFromCube D3D11_BlitFromCube
  81. #define g_BlitFromCubeArray D3D11_BlitFromCubeArray
  82. #include "D3D11_Blit.h"
  83. #undef g_FullscreenVert
  84. #undef g_BlitFrom2D
  85. #undef g_BlitFrom2DArray
  86. #undef g_BlitFrom3D
  87. #undef g_BlitFromCube
  88. #undef g_BlitFromCubeArray
  89. // Macros
  90. #define ERROR_CHECK(msg) \
  91. if (FAILED(res)) { \
  92. D3D11_INTERNAL_LogError(renderer->device, msg, res); \
  93. }
  94. #define ERROR_CHECK_RETURN(msg, ret) \
  95. if (FAILED(res)) { \
  96. D3D11_INTERNAL_LogError(renderer->device, msg, res); \
  97. return ret; \
  98. }
  99. #define TRACK_RESOURCE(resource, type, array, count, capacity) \
  100. Uint32 i; \
  101. \
  102. for (i = 0; i < commandBuffer->count; i += 1) { \
  103. if (commandBuffer->array[i] == resource) { \
  104. return; \
  105. } \
  106. } \
  107. \
  108. if (commandBuffer->count == commandBuffer->capacity) { \
  109. commandBuffer->capacity += 1; \
  110. commandBuffer->array = SDL_realloc( \
  111. commandBuffer->array, \
  112. commandBuffer->capacity * sizeof(type)); \
  113. } \
  114. commandBuffer->array[commandBuffer->count] = resource; \
  115. commandBuffer->count += 1; \
  116. SDL_AtomicIncRef(&resource->referenceCount);
  117. // Forward Declarations
  118. static void D3D11_Wait(SDL_GPURenderer *driverData);
  119. static void D3D11_ReleaseWindow(
  120. SDL_GPURenderer *driverData,
  121. SDL_Window *window);
  122. static void D3D11_INTERNAL_DestroyBlitPipelines(SDL_GPURenderer *driverData);
  123. // Conversions
  124. static SDL_GPUTextureFormat SwapchainCompositionToSDLTextureFormat[] = {
  125. SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, // SDR
  126. SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB, // SDR_SRGB
  127. SDL_GPU_TEXTUREFORMAT_R16G16B16A16_FLOAT, // HDR
  128. SDL_GPU_TEXTUREFORMAT_R10G10B10A2_UNORM, // HDR_ADVANCED
  129. };
  130. static DXGI_FORMAT SwapchainCompositionToTextureFormat[] = {
  131. DXGI_FORMAT_B8G8R8A8_UNORM, // SDR
  132. DXGI_FORMAT_B8G8R8A8_UNORM, /* SDR_SRGB */ // NOTE: The RTV uses the sRGB format
  133. DXGI_FORMAT_R16G16B16A16_FLOAT, // HDR
  134. DXGI_FORMAT_R10G10B10A2_UNORM, // HDR_ADVANCED
  135. };
  136. static DXGI_COLOR_SPACE_TYPE SwapchainCompositionToColorSpace[] = {
  137. DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709, // SDR
  138. DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709, // SDR_SRGB
  139. DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709, // HDR
  140. DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020 // HDR_ADVANCED
  141. };
  142. static DXGI_FORMAT SDLToD3D11_TextureFormat[] = {
  143. DXGI_FORMAT_UNKNOWN, // INVALID
  144. DXGI_FORMAT_A8_UNORM, // A8_UNORM
  145. DXGI_FORMAT_R8_UNORM, // R8_UNORM
  146. DXGI_FORMAT_R8G8_UNORM, // R8G8_UNORM
  147. DXGI_FORMAT_R8G8B8A8_UNORM, // R8G8B8A8_UNORM
  148. DXGI_FORMAT_R16_UNORM, // R16_UNORM
  149. DXGI_FORMAT_R16G16_UNORM, // R16G16_UNORM
  150. DXGI_FORMAT_R16G16B16A16_UNORM, // R16G16B16A16_UNORM
  151. DXGI_FORMAT_R10G10B10A2_UNORM, // R10G10B10A2_UNORM
  152. DXGI_FORMAT_B5G6R5_UNORM, // B5G6R5_UNORM
  153. DXGI_FORMAT_B5G5R5A1_UNORM, // B5G5R5A1_UNORM
  154. DXGI_FORMAT_B4G4R4A4_UNORM, // B4G4R4A4_UNORM
  155. DXGI_FORMAT_B8G8R8A8_UNORM, // B8G8R8A8_UNORM
  156. DXGI_FORMAT_BC1_UNORM, // BC1_UNORM
  157. DXGI_FORMAT_BC2_UNORM, // BC2_UNORM
  158. DXGI_FORMAT_BC3_UNORM, // BC3_UNORM
  159. DXGI_FORMAT_BC4_UNORM, // BC4_UNORM
  160. DXGI_FORMAT_BC5_UNORM, // BC5_UNORM
  161. DXGI_FORMAT_BC7_UNORM, // BC7_UNORM
  162. DXGI_FORMAT_BC6H_SF16, // BC6H_FLOAT
  163. DXGI_FORMAT_BC6H_UF16, // BC6H_UFLOAT
  164. DXGI_FORMAT_R8_SNORM, // R8_SNORM
  165. DXGI_FORMAT_R8G8_SNORM, // R8G8_SNORM
  166. DXGI_FORMAT_R8G8B8A8_SNORM, // R8G8B8A8_SNORM
  167. DXGI_FORMAT_R16_SNORM, // R16_SNORM
  168. DXGI_FORMAT_R16G16_SNORM, // R16G16_SNORM
  169. DXGI_FORMAT_R16G16B16A16_SNORM, // R16G16B16A16_SNORM
  170. DXGI_FORMAT_R16_FLOAT, // R16_FLOAT
  171. DXGI_FORMAT_R16G16_FLOAT, // R16G16_FLOAT
  172. DXGI_FORMAT_R16G16B16A16_FLOAT, // R16G16B16A16_FLOAT
  173. DXGI_FORMAT_R32_FLOAT, // R32_FLOAT
  174. DXGI_FORMAT_R32G32_FLOAT, // R32G32_FLOAT
  175. DXGI_FORMAT_R32G32B32A32_FLOAT, // R32G32B32A32_FLOAT
  176. DXGI_FORMAT_R11G11B10_FLOAT, // R11G11B10_UFLOAT
  177. DXGI_FORMAT_R8_UINT, // R8_UINT
  178. DXGI_FORMAT_R8G8_UINT, // R8G8_UINT
  179. DXGI_FORMAT_R8G8B8A8_UINT, // R8G8B8A8_UINT
  180. DXGI_FORMAT_R16_UINT, // R16_UINT
  181. DXGI_FORMAT_R16G16_UINT, // R16G16_UINT
  182. DXGI_FORMAT_R16G16B16A16_UINT, // R16G16B16A16_UINT
  183. DXGI_FORMAT_R8_SINT, // R8_INT
  184. DXGI_FORMAT_R8G8_SINT, // R8G8_INT
  185. DXGI_FORMAT_R8G8B8A8_SINT, // R8G8B8A8_INT
  186. DXGI_FORMAT_R16_SINT, // R16_INT
  187. DXGI_FORMAT_R16G16_SINT, // R16G16_INT
  188. DXGI_FORMAT_R16G16B16A16_SINT, // R16G16B16A16_INT
  189. DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, // R8G8B8A8_UNORM_SRGB
  190. DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, // B8G8R8A8_UNORM_SRGB
  191. DXGI_FORMAT_BC1_UNORM_SRGB, // BC1_UNORM_SRGB
  192. DXGI_FORMAT_BC2_UNORM_SRGB, // BC2_UNORM_SRGB
  193. DXGI_FORMAT_BC3_UNORM_SRGB, // BC3_UNORM_SRGB
  194. DXGI_FORMAT_BC7_UNORM_SRGB, // BC7_UNORM_SRGB
  195. DXGI_FORMAT_D16_UNORM, // D16_UNORM
  196. DXGI_FORMAT_D24_UNORM_S8_UINT, // D24_UNORM
  197. DXGI_FORMAT_D32_FLOAT, // D32_FLOAT
  198. DXGI_FORMAT_D24_UNORM_S8_UINT, // D24_UNORM_S8_UINT
  199. DXGI_FORMAT_D32_FLOAT_S8X24_UINT, // D32_FLOAT_S8_UINT
  200. };
  201. SDL_COMPILE_TIME_ASSERT(SDLToD3D11_TextureFormat, SDL_arraysize(SDLToD3D11_TextureFormat) == SDL_GPU_TEXTUREFORMAT_MAX_ENUM_VALUE);
  202. static DXGI_FORMAT SDLToD3D11_VertexFormat[] = {
  203. DXGI_FORMAT_UNKNOWN, // INVALID
  204. DXGI_FORMAT_R32_SINT, // INT
  205. DXGI_FORMAT_R32G32_SINT, // INT2
  206. DXGI_FORMAT_R32G32B32_SINT, // INT3
  207. DXGI_FORMAT_R32G32B32A32_SINT, // INT4
  208. DXGI_FORMAT_R32_UINT, // UINT
  209. DXGI_FORMAT_R32G32_UINT, // UINT2
  210. DXGI_FORMAT_R32G32B32_UINT, // UINT3
  211. DXGI_FORMAT_R32G32B32A32_UINT, // UINT4
  212. DXGI_FORMAT_R32_FLOAT, // FLOAT
  213. DXGI_FORMAT_R32G32_FLOAT, // FLOAT2
  214. DXGI_FORMAT_R32G32B32_FLOAT, // FLOAT3
  215. DXGI_FORMAT_R32G32B32A32_FLOAT, // FLOAT4
  216. DXGI_FORMAT_R8G8_SINT, // BYTE2
  217. DXGI_FORMAT_R8G8B8A8_SINT, // BYTE4
  218. DXGI_FORMAT_R8G8_UINT, // UBYTE2
  219. DXGI_FORMAT_R8G8B8A8_UINT, // UBYTE4
  220. DXGI_FORMAT_R8G8_SNORM, // BYTE2_NORM
  221. DXGI_FORMAT_R8G8B8A8_SNORM, // BYTE4_NORM
  222. DXGI_FORMAT_R8G8_UNORM, // UBYTE2_NORM
  223. DXGI_FORMAT_R8G8B8A8_UNORM, // UBYTE4_NORM
  224. DXGI_FORMAT_R16G16_SINT, // SHORT2
  225. DXGI_FORMAT_R16G16B16A16_SINT, // SHORT4
  226. DXGI_FORMAT_R16G16_UINT, // USHORT2
  227. DXGI_FORMAT_R16G16B16A16_UINT, // USHORT4
  228. DXGI_FORMAT_R16G16_SNORM, // SHORT2_NORM
  229. DXGI_FORMAT_R16G16B16A16_SNORM, // SHORT4_NORM
  230. DXGI_FORMAT_R16G16_UNORM, // USHORT2_NORM
  231. DXGI_FORMAT_R16G16B16A16_UNORM, // USHORT4_NORM
  232. DXGI_FORMAT_R16G16_FLOAT, // HALF2
  233. DXGI_FORMAT_R16G16B16A16_FLOAT // HALF4
  234. };
  235. SDL_COMPILE_TIME_ASSERT(SDLToD3D11_VertexFormat, SDL_arraysize(SDLToD3D11_VertexFormat) == SDL_GPU_VERTEXELEMENTFORMAT_MAX_ENUM_VALUE);
  236. static Uint32 SDLToD3D11_SampleCount[] = {
  237. 1, // SDL_GPU_SAMPLECOUNT_1
  238. 2, // SDL_GPU_SAMPLECOUNT_2
  239. 4, // SDL_GPU_SAMPLECOUNT_4
  240. 8 // SDL_GPU_SAMPLECOUNT_8
  241. };
  242. static DXGI_FORMAT SDLToD3D11_IndexType[] = {
  243. DXGI_FORMAT_R16_UINT, // 16BIT
  244. DXGI_FORMAT_R32_UINT // 32BIT
  245. };
  246. static D3D11_PRIMITIVE_TOPOLOGY SDLToD3D11_PrimitiveType[] = {
  247. D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, // TRIANGLELIST
  248. D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, // TRIANGLESTRIP
  249. D3D_PRIMITIVE_TOPOLOGY_LINELIST, // LINELIST
  250. D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, // LINESTRIP
  251. D3D_PRIMITIVE_TOPOLOGY_POINTLIST // POINTLIST
  252. };
  253. static D3D11_CULL_MODE SDLToD3D11_CullMode[] = {
  254. D3D11_CULL_NONE, // NONE
  255. D3D11_CULL_FRONT, // FRONT
  256. D3D11_CULL_BACK // BACK
  257. };
  258. static D3D11_BLEND SDLToD3D11_BlendFactor[] = {
  259. D3D11_BLEND_ZERO, // INVALID
  260. D3D11_BLEND_ZERO, // ZERO
  261. D3D11_BLEND_ONE, // ONE
  262. D3D11_BLEND_SRC_COLOR, // SRC_COLOR
  263. D3D11_BLEND_INV_SRC_COLOR, // ONE_MINUS_SRC_COLOR
  264. D3D11_BLEND_DEST_COLOR, // DST_COLOR
  265. D3D11_BLEND_INV_DEST_COLOR, // ONE_MINUS_DST_COLOR
  266. D3D11_BLEND_SRC_ALPHA, // SRC_ALPHA
  267. D3D11_BLEND_INV_SRC_ALPHA, // ONE_MINUS_SRC_ALPHA
  268. D3D11_BLEND_DEST_ALPHA, // DST_ALPHA
  269. D3D11_BLEND_INV_DEST_ALPHA, // ONE_MINUS_DST_ALPHA
  270. D3D11_BLEND_BLEND_FACTOR, // CONSTANT_COLOR
  271. D3D11_BLEND_INV_BLEND_FACTOR, // ONE_MINUS_CONSTANT_COLOR
  272. D3D11_BLEND_SRC_ALPHA_SAT, // SRC_ALPHA_SATURATE
  273. };
  274. SDL_COMPILE_TIME_ASSERT(SDLToD3D11_BlendFactor, SDL_arraysize(SDLToD3D11_BlendFactor) == SDL_GPU_BLENDFACTOR_MAX_ENUM_VALUE);
  275. static D3D11_BLEND SDLToD3D11_BlendFactorAlpha[] = {
  276. D3D11_BLEND_ZERO, // ALPHA
  277. D3D11_BLEND_ZERO, // ZERO
  278. D3D11_BLEND_ONE, // ONE
  279. D3D11_BLEND_SRC_ALPHA, // SRC_COLOR
  280. D3D11_BLEND_INV_SRC_ALPHA, // ONE_MINUS_SRC_COLOR
  281. D3D11_BLEND_DEST_ALPHA, // DST_COLOR
  282. D3D11_BLEND_INV_DEST_ALPHA, // ONE_MINUS_DST_COLOR
  283. D3D11_BLEND_SRC_ALPHA, // SRC_ALPHA
  284. D3D11_BLEND_INV_SRC_ALPHA, // ONE_MINUS_SRC_ALPHA
  285. D3D11_BLEND_DEST_ALPHA, // DST_ALPHA
  286. D3D11_BLEND_INV_DEST_ALPHA, // ONE_MINUS_DST_ALPHA
  287. D3D11_BLEND_BLEND_FACTOR, // CONSTANT_COLOR
  288. D3D11_BLEND_INV_BLEND_FACTOR, // ONE_MINUS_CONSTANT_COLOR
  289. D3D11_BLEND_SRC_ALPHA_SAT, // SRC_ALPHA_SATURATE
  290. };
  291. SDL_COMPILE_TIME_ASSERT(SDLToD3D11_BlendFactorAlpha, SDL_arraysize(SDLToD3D11_BlendFactorAlpha) == SDL_GPU_BLENDFACTOR_MAX_ENUM_VALUE);
  292. static D3D11_BLEND_OP SDLToD3D11_BlendOp[] = {
  293. D3D11_BLEND_OP_ADD, // INVALID
  294. D3D11_BLEND_OP_ADD, // ADD
  295. D3D11_BLEND_OP_SUBTRACT, // SUBTRACT
  296. D3D11_BLEND_OP_REV_SUBTRACT, // REVERSE_SUBTRACT
  297. D3D11_BLEND_OP_MIN, // MIN
  298. D3D11_BLEND_OP_MAX // MAX
  299. };
  300. SDL_COMPILE_TIME_ASSERT(SDLToD3D11_BlendOp, SDL_arraysize(SDLToD3D11_BlendOp) == SDL_GPU_BLENDOP_MAX_ENUM_VALUE);
  301. static D3D11_COMPARISON_FUNC SDLToD3D11_CompareOp[] = {
  302. D3D11_COMPARISON_NEVER, // INVALID
  303. D3D11_COMPARISON_NEVER, // NEVER
  304. D3D11_COMPARISON_LESS, // LESS
  305. D3D11_COMPARISON_EQUAL, // EQUAL
  306. D3D11_COMPARISON_LESS_EQUAL, // LESS_OR_EQUAL
  307. D3D11_COMPARISON_GREATER, // GREATER
  308. D3D11_COMPARISON_NOT_EQUAL, // NOT_EQUAL
  309. D3D11_COMPARISON_GREATER_EQUAL, // GREATER_OR_EQUAL
  310. D3D11_COMPARISON_ALWAYS // ALWAYS
  311. };
  312. SDL_COMPILE_TIME_ASSERT(SDLToD3D11_CompareOp, SDL_arraysize(SDLToD3D11_CompareOp) == SDL_GPU_COMPAREOP_MAX_ENUM_VALUE);
  313. static D3D11_STENCIL_OP SDLToD3D11_StencilOp[] = {
  314. D3D11_STENCIL_OP_KEEP, // INVALID
  315. D3D11_STENCIL_OP_KEEP, // KEEP
  316. D3D11_STENCIL_OP_ZERO, // ZERO
  317. D3D11_STENCIL_OP_REPLACE, // REPLACE
  318. D3D11_STENCIL_OP_INCR_SAT, // INCREMENT_AND_CLAMP
  319. D3D11_STENCIL_OP_DECR_SAT, // DECREMENT_AND_CLAMP
  320. D3D11_STENCIL_OP_INVERT, // INVERT
  321. D3D11_STENCIL_OP_INCR, // INCREMENT_AND_WRAP
  322. D3D11_STENCIL_OP_DECR // DECREMENT_AND_WRAP
  323. };
  324. SDL_COMPILE_TIME_ASSERT(SDLToD3D11_StencilOp, SDL_arraysize(SDLToD3D11_StencilOp) == SDL_GPU_STENCILOP_MAX_ENUM_VALUE);
  325. static D3D11_INPUT_CLASSIFICATION SDLToD3D11_VertexInputRate[] = {
  326. D3D11_INPUT_PER_VERTEX_DATA, // VERTEX
  327. D3D11_INPUT_PER_INSTANCE_DATA // INSTANCE
  328. };
  329. static D3D11_TEXTURE_ADDRESS_MODE SDLToD3D11_SamplerAddressMode[] = {
  330. D3D11_TEXTURE_ADDRESS_WRAP, // REPEAT
  331. D3D11_TEXTURE_ADDRESS_MIRROR, // MIRRORED_REPEAT
  332. D3D11_TEXTURE_ADDRESS_CLAMP // CLAMP_TO_EDGE
  333. };
  334. static D3D11_FILTER SDLToD3D11_Filter(const SDL_GPUSamplerCreateInfo *createInfo)
  335. {
  336. if (createInfo->min_filter == SDL_GPU_FILTER_LINEAR) {
  337. if (createInfo->mag_filter == SDL_GPU_FILTER_LINEAR) {
  338. if (createInfo->mipmap_mode == SDL_GPU_SAMPLERMIPMAPMODE_LINEAR) {
  339. return D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  340. } else {
  341. return D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT;
  342. }
  343. } else {
  344. if (createInfo->mipmap_mode == SDL_GPU_SAMPLERMIPMAPMODE_LINEAR) {
  345. return D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR;
  346. } else {
  347. return D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT;
  348. }
  349. }
  350. } else {
  351. if (createInfo->mag_filter == SDL_GPU_FILTER_LINEAR) {
  352. if (createInfo->mipmap_mode == SDL_GPU_SAMPLERMIPMAPMODE_LINEAR) {
  353. return D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR;
  354. } else {
  355. return D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT;
  356. }
  357. } else {
  358. if (createInfo->mipmap_mode == SDL_GPU_SAMPLERMIPMAPMODE_LINEAR) {
  359. return D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR;
  360. } else {
  361. return D3D11_FILTER_MIN_MAG_MIP_POINT;
  362. }
  363. }
  364. }
  365. }
  366. // Structs
  367. typedef struct D3D11Texture D3D11Texture;
  368. typedef struct D3D11TextureContainer
  369. {
  370. TextureCommonHeader header;
  371. D3D11Texture *activeTexture;
  372. Uint32 textureCapacity;
  373. Uint32 textureCount;
  374. D3D11Texture **textures;
  375. char *debugName;
  376. bool canBeCycled;
  377. } D3D11TextureContainer;
  378. typedef struct D3D11TextureSubresource
  379. {
  380. D3D11Texture *parent;
  381. Uint32 layer;
  382. Uint32 level;
  383. Uint32 depth; // total depth
  384. Uint32 index;
  385. // One RTV per depth slice
  386. ID3D11RenderTargetView **colorTargetViews; // NULL if not a color target
  387. ID3D11UnorderedAccessView *uav; // NULL if not a storage texture
  388. ID3D11DepthStencilView *depthStencilTargetView; // NULL if not a depth stencil target
  389. } D3D11TextureSubresource;
  390. struct D3D11Texture
  391. {
  392. D3D11TextureContainer *container;
  393. Uint32 containerIndex;
  394. ID3D11Resource *handle; /* ID3D11Texture2D* or ID3D11Texture3D* */
  395. ID3D11ShaderResourceView *shaderView;
  396. D3D11TextureSubresource *subresources;
  397. Uint32 subresourceCount; /* layerCount * num_levels */
  398. SDL_AtomicInt referenceCount;
  399. };
  400. typedef struct D3D11Fence
  401. {
  402. ID3D11Query *handle;
  403. SDL_AtomicInt referenceCount;
  404. } D3D11Fence;
  405. typedef struct D3D11WindowData
  406. {
  407. SDL_Window *window;
  408. IDXGISwapChain *swapchain;
  409. D3D11Texture texture;
  410. D3D11TextureContainer textureContainer;
  411. SDL_GPUPresentMode presentMode;
  412. SDL_GPUSwapchainComposition swapchainComposition;
  413. DXGI_FORMAT swapchainFormat;
  414. DXGI_COLOR_SPACE_TYPE swapchainColorSpace;
  415. SDL_GPUFence *inFlightFences[MAX_FRAMES_IN_FLIGHT];
  416. Uint32 frameCounter;
  417. } D3D11WindowData;
  418. typedef struct D3D11Shader
  419. {
  420. ID3D11DeviceChild *handle; // ID3D11VertexShader, ID3D11PixelShader, ID3D11ComputeShader
  421. void *bytecode;
  422. size_t bytecodeSize;
  423. Uint32 numSamplers;
  424. Uint32 numUniformBuffers;
  425. Uint32 numStorageBuffers;
  426. Uint32 numStorageTextures;
  427. } D3D11Shader;
  428. typedef struct D3D11GraphicsPipeline
  429. {
  430. Sint32 numColorTargets;
  431. DXGI_FORMAT colorTargetFormats[MAX_COLOR_TARGET_BINDINGS];
  432. ID3D11BlendState *colorTargetBlendState;
  433. Uint32 sampleMask;
  434. SDL_GPUMultisampleState multisampleState;
  435. Uint8 hasDepthStencilTarget;
  436. DXGI_FORMAT depthStencilTargetFormat;
  437. ID3D11DepthStencilState *depthStencilState;
  438. SDL_GPUPrimitiveType primitiveType;
  439. ID3D11RasterizerState *rasterizerState;
  440. ID3D11VertexShader *vertexShader;
  441. ID3D11PixelShader *fragmentShader;
  442. ID3D11InputLayout *inputLayout;
  443. Uint32 vertexStrides[MAX_VERTEX_BUFFERS];
  444. Uint32 vertexSamplerCount;
  445. Uint32 vertexUniformBufferCount;
  446. Uint32 vertexStorageBufferCount;
  447. Uint32 vertexStorageTextureCount;
  448. Uint32 fragmentSamplerCount;
  449. Uint32 fragmentUniformBufferCount;
  450. Uint32 fragmentStorageBufferCount;
  451. Uint32 fragmentStorageTextureCount;
  452. } D3D11GraphicsPipeline;
  453. typedef struct D3D11ComputePipeline
  454. {
  455. ID3D11ComputeShader *computeShader;
  456. Uint32 numSamplers;
  457. Uint32 numReadonlyStorageTextures;
  458. Uint32 numWriteonlyStorageTextures;
  459. Uint32 numReadonlyStorageBuffers;
  460. Uint32 numWriteonlyStorageBuffers;
  461. Uint32 numUniformBuffers;
  462. } D3D11ComputePipeline;
  463. typedef struct D3D11Buffer
  464. {
  465. ID3D11Buffer *handle;
  466. ID3D11UnorderedAccessView *uav;
  467. ID3D11ShaderResourceView *srv;
  468. Uint32 size;
  469. SDL_AtomicInt referenceCount;
  470. } D3D11Buffer;
  471. typedef struct D3D11BufferContainer
  472. {
  473. D3D11Buffer *activeBuffer;
  474. Uint32 bufferCapacity;
  475. Uint32 bufferCount;
  476. D3D11Buffer **buffers;
  477. D3D11_BUFFER_DESC bufferDesc;
  478. char *debugName;
  479. } D3D11BufferContainer;
  480. typedef struct D3D11BufferDownload
  481. {
  482. ID3D11Buffer *stagingBuffer;
  483. Uint32 dstOffset;
  484. Uint32 size;
  485. } D3D11BufferDownload;
  486. typedef struct D3D11TextureDownload
  487. {
  488. ID3D11Resource *stagingTexture;
  489. Uint32 width;
  490. Uint32 height;
  491. Uint32 depth;
  492. Uint32 bufferOffset;
  493. Uint32 bytesPerRow;
  494. Uint32 bytesPerDepthSlice;
  495. } D3D11TextureDownload;
  496. typedef struct D3D11TransferBuffer
  497. {
  498. Uint8 *data;
  499. Uint32 size;
  500. SDL_AtomicInt referenceCount;
  501. D3D11BufferDownload *bufferDownloads;
  502. Uint32 bufferDownloadCount;
  503. Uint32 bufferDownloadCapacity;
  504. D3D11TextureDownload *textureDownloads;
  505. Uint32 textureDownloadCount;
  506. Uint32 textureDownloadCapacity;
  507. } D3D11TransferBuffer;
  508. typedef struct D3D11TransferBufferContainer
  509. {
  510. D3D11TransferBuffer *activeBuffer;
  511. /* These are all the buffers that have been used by this container.
  512. * If the resource is bound and then updated with DISCARD, a new resource
  513. * will be added to this list.
  514. * These can be reused after they are submitted and command processing is complete.
  515. */
  516. Uint32 bufferCapacity;
  517. Uint32 bufferCount;
  518. D3D11TransferBuffer **buffers;
  519. } D3D11TransferBufferContainer;
  520. typedef struct D3D11UniformBuffer
  521. {
  522. ID3D11Buffer *buffer;
  523. void *mappedData;
  524. Uint32 drawOffset;
  525. Uint32 writeOffset;
  526. Uint32 currentBlockSize;
  527. } D3D11UniformBuffer;
  528. typedef struct D3D11Sampler
  529. {
  530. ID3D11SamplerState *handle;
  531. } D3D11Sampler;
  532. typedef struct D3D11Renderer D3D11Renderer;
  533. typedef struct D3D11CommandBuffer
  534. {
  535. CommandBufferCommonHeader common;
  536. D3D11Renderer *renderer;
  537. // Deferred Context
  538. ID3D11DeviceContext1 *context;
  539. // Presentation
  540. D3D11WindowData **windowDatas;
  541. Uint32 windowDataCount;
  542. Uint32 windowDataCapacity;
  543. // Render Pass
  544. D3D11GraphicsPipeline *graphicsPipeline;
  545. Uint8 stencilRef;
  546. SDL_FColor blendConstants;
  547. D3D11TextureSubresource *colorTargetSubresources[MAX_COLOR_TARGET_BINDINGS];
  548. D3D11TextureSubresource *colorResolveSubresources[MAX_COLOR_TARGET_BINDINGS];
  549. // Compute Pass
  550. D3D11ComputePipeline *computePipeline;
  551. // Debug Annotation
  552. ID3DUserDefinedAnnotation *annotation;
  553. // Resource slot state
  554. bool needVertexBufferBind;
  555. bool needVertexSamplerBind;
  556. bool needVertexStorageTextureBind;
  557. bool needVertexStorageBufferBind;
  558. bool needVertexUniformBufferBind;
  559. bool needFragmentSamplerBind;
  560. bool needFragmentStorageTextureBind;
  561. bool needFragmentStorageBufferBind;
  562. bool needFragmentUniformBufferBind;
  563. bool needComputeSamplerBind;
  564. bool needComputeReadOnlyTextureBind;
  565. bool needComputeReadOnlyBufferBind;
  566. bool needComputeUniformBufferBind;
  567. // defer OMSetBlendState because it combines three different states
  568. bool needBlendStateSet;
  569. ID3D11Buffer *vertexBuffers[MAX_VERTEX_BUFFERS];
  570. Uint32 vertexBufferOffsets[MAX_VERTEX_BUFFERS];
  571. Uint32 vertexBufferCount;
  572. D3D11Texture *vertexSamplerTextures[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  573. D3D11Sampler *vertexSamplers[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  574. D3D11Texture *vertexStorageTextures[MAX_STORAGE_TEXTURES_PER_STAGE];
  575. D3D11Buffer *vertexStorageBuffers[MAX_STORAGE_BUFFERS_PER_STAGE];
  576. D3D11Texture *fragmentSamplerTextures[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  577. D3D11Sampler *fragmentSamplers[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  578. D3D11Texture *fragmentStorageTextures[MAX_STORAGE_TEXTURES_PER_STAGE];
  579. D3D11Buffer *fragmentStorageBuffers[MAX_STORAGE_BUFFERS_PER_STAGE];
  580. D3D11Texture *computeSamplerTextures[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  581. D3D11Sampler *computeSamplers[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  582. D3D11Texture *computeReadOnlyStorageTextures[MAX_STORAGE_TEXTURES_PER_STAGE];
  583. D3D11Buffer *computeReadOnlyStorageBuffers[MAX_STORAGE_BUFFERS_PER_STAGE];
  584. D3D11TextureSubresource *computeWriteOnlyStorageTextureSubresources[MAX_COMPUTE_WRITE_TEXTURES];
  585. D3D11Buffer *computeWriteOnlyStorageBuffers[MAX_COMPUTE_WRITE_BUFFERS];
  586. // Uniform buffers
  587. D3D11UniformBuffer *vertexUniformBuffers[MAX_UNIFORM_BUFFERS_PER_STAGE];
  588. D3D11UniformBuffer *fragmentUniformBuffers[MAX_UNIFORM_BUFFERS_PER_STAGE];
  589. D3D11UniformBuffer *computeUniformBuffers[MAX_UNIFORM_BUFFERS_PER_STAGE];
  590. // Fences
  591. D3D11Fence *fence;
  592. Uint8 autoReleaseFence;
  593. // Reference Counting
  594. D3D11Buffer **usedBuffers;
  595. Uint32 usedBufferCount;
  596. Uint32 usedBufferCapacity;
  597. D3D11TransferBuffer **usedTransferBuffers;
  598. Uint32 usedTransferBufferCount;
  599. Uint32 usedTransferBufferCapacity;
  600. D3D11Texture **usedTextures;
  601. Uint32 usedTextureCount;
  602. Uint32 usedTextureCapacity;
  603. D3D11UniformBuffer **usedUniformBuffers;
  604. Uint32 usedUniformBufferCount;
  605. Uint32 usedUniformBufferCapacity;
  606. } D3D11CommandBuffer;
  607. struct D3D11Renderer
  608. {
  609. ID3D11Device1 *device;
  610. ID3D11DeviceContext *immediateContext;
  611. IDXGIFactory1 *factory;
  612. IDXGIAdapter1 *adapter;
  613. IDXGIDebug *dxgiDebug;
  614. #ifdef HAVE_IDXGIINFOQUEUE
  615. IDXGIInfoQueue *dxgiInfoQueue;
  616. #endif
  617. void *d3d11_dll;
  618. void *dxgi_dll;
  619. void *dxgidebug_dll;
  620. Uint8 debugMode;
  621. BOOL supportsTearing;
  622. Uint8 supportsFlipDiscard;
  623. SDL_iconv_t iconv;
  624. // Blit
  625. BlitPipelineCacheEntry blitPipelines[5];
  626. SDL_GPUSampler *blitNearestSampler;
  627. SDL_GPUSampler *blitLinearSampler;
  628. // Resource Tracking
  629. D3D11WindowData **claimedWindows;
  630. Uint32 claimedWindowCount;
  631. Uint32 claimedWindowCapacity;
  632. D3D11CommandBuffer **availableCommandBuffers;
  633. Uint32 availableCommandBufferCount;
  634. Uint32 availableCommandBufferCapacity;
  635. D3D11CommandBuffer **submittedCommandBuffers;
  636. Uint32 submittedCommandBufferCount;
  637. Uint32 submittedCommandBufferCapacity;
  638. D3D11Fence **availableFences;
  639. Uint32 availableFenceCount;
  640. Uint32 availableFenceCapacity;
  641. D3D11UniformBuffer **uniformBufferPool;
  642. Uint32 uniformBufferPoolCount;
  643. Uint32 uniformBufferPoolCapacity;
  644. D3D11TransferBufferContainer **transferBufferContainersToDestroy;
  645. Uint32 transferBufferContainersToDestroyCount;
  646. Uint32 transferBufferContainersToDestroyCapacity;
  647. D3D11BufferContainer **bufferContainersToDestroy;
  648. Uint32 bufferContainersToDestroyCount;
  649. Uint32 bufferContainersToDestroyCapacity;
  650. D3D11TextureContainer **textureContainersToDestroy;
  651. Uint32 textureContainersToDestroyCount;
  652. Uint32 textureContainersToDestroyCapacity;
  653. SDL_Mutex *contextLock;
  654. SDL_Mutex *acquireCommandBufferLock;
  655. SDL_Mutex *acquireUniformBufferLock;
  656. SDL_Mutex *fenceLock;
  657. SDL_Mutex *windowLock;
  658. // Null arrays for resetting resource slots
  659. ID3D11RenderTargetView *nullRTVs[MAX_COLOR_TARGET_BINDINGS];
  660. ID3D11ShaderResourceView *nullSRVs[MAX_TEXTURE_SAMPLERS_PER_STAGE * 2 +
  661. MAX_STORAGE_TEXTURES_PER_STAGE +
  662. MAX_STORAGE_BUFFERS_PER_STAGE];
  663. ID3D11SamplerState *nullSamplers[MAX_TEXTURE_SAMPLERS_PER_STAGE * 2];
  664. ID3D11UnorderedAccessView *nullUAVs[MAX_COMPUTE_WRITE_TEXTURES +
  665. MAX_COMPUTE_WRITE_BUFFERS];
  666. };
  667. // Logging
  668. static void D3D11_INTERNAL_LogError(
  669. ID3D11Device1 *device,
  670. const char *msg,
  671. HRESULT res)
  672. {
  673. #define MAX_ERROR_LEN 1024 // FIXME: Arbitrary!
  674. // Buffer for text, ensure space for \0 terminator after buffer
  675. char wszMsgBuff[MAX_ERROR_LEN + 1];
  676. DWORD dwChars; // Number of chars returned.
  677. if (res == DXGI_ERROR_DEVICE_REMOVED) {
  678. res = ID3D11Device_GetDeviceRemovedReason(device);
  679. }
  680. // Try to get the message from the system errors.
  681. #ifdef _WIN32
  682. dwChars = FormatMessageA(
  683. FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  684. NULL,
  685. res,
  686. 0,
  687. wszMsgBuff,
  688. MAX_ERROR_LEN,
  689. NULL);
  690. #else
  691. // FIXME: Do we have error strings in dxvk-native? -flibit
  692. dwChars = 0;
  693. #endif
  694. // No message? Screw it, just post the code.
  695. if (dwChars == 0) {
  696. SDL_LogError(SDL_LOG_CATEGORY_GPU, "%s! Error Code: " HRESULT_FMT, msg, res);
  697. return;
  698. }
  699. // Ensure valid range
  700. dwChars = SDL_min(dwChars, MAX_ERROR_LEN);
  701. // Trim whitespace from tail of message
  702. while (dwChars > 0) {
  703. if (wszMsgBuff[dwChars - 1] <= ' ') {
  704. dwChars--;
  705. } else {
  706. break;
  707. }
  708. }
  709. // Ensure null-terminated string
  710. wszMsgBuff[dwChars] = '\0';
  711. SDL_LogError(SDL_LOG_CATEGORY_GPU, "%s! Error Code: %s " HRESULT_FMT, msg, wszMsgBuff, res);
  712. }
  713. // Helper Functions
  714. static inline Uint32 D3D11_INTERNAL_CalcSubresource(
  715. Uint32 mipLevel,
  716. Uint32 layer,
  717. Uint32 numLevels)
  718. {
  719. return mipLevel + (layer * numLevels);
  720. }
  721. static inline Uint32 D3D11_INTERNAL_NextHighestAlignment(
  722. Uint32 n,
  723. Uint32 align)
  724. {
  725. return align * ((n + align - 1) / align);
  726. }
  727. static DXGI_FORMAT D3D11_INTERNAL_GetTypelessFormat(
  728. DXGI_FORMAT typedFormat)
  729. {
  730. switch (typedFormat) {
  731. case DXGI_FORMAT_D16_UNORM:
  732. return DXGI_FORMAT_R16_TYPELESS;
  733. case DXGI_FORMAT_D32_FLOAT:
  734. return DXGI_FORMAT_R32_TYPELESS;
  735. case DXGI_FORMAT_D24_UNORM_S8_UINT:
  736. return DXGI_FORMAT_R24G8_TYPELESS;
  737. case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
  738. return DXGI_FORMAT_R32G8X24_TYPELESS;
  739. default:
  740. return DXGI_FORMAT_UNKNOWN;
  741. }
  742. }
  743. static DXGI_FORMAT D3D11_INTERNAL_GetSampleableFormat(
  744. DXGI_FORMAT format)
  745. {
  746. switch (format) {
  747. case DXGI_FORMAT_R16_TYPELESS:
  748. return DXGI_FORMAT_R16_UNORM;
  749. case DXGI_FORMAT_R32_TYPELESS:
  750. return DXGI_FORMAT_R32_FLOAT;
  751. case DXGI_FORMAT_R24G8_TYPELESS:
  752. return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
  753. case DXGI_FORMAT_R32G8X24_TYPELESS:
  754. return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
  755. default:
  756. return format;
  757. }
  758. }
  759. // Quit
  760. static void D3D11_INTERNAL_DestroyBufferContainer(
  761. D3D11BufferContainer *container)
  762. {
  763. for (Uint32 i = 0; i < container->bufferCount; i += 1) {
  764. D3D11Buffer *d3d11Buffer = container->buffers[i];
  765. if (d3d11Buffer->uav != NULL) {
  766. ID3D11UnorderedAccessView_Release(d3d11Buffer->uav);
  767. }
  768. if (d3d11Buffer->srv != NULL) {
  769. ID3D11ShaderResourceView_Release(d3d11Buffer->srv);
  770. }
  771. ID3D11Buffer_Release(d3d11Buffer->handle);
  772. SDL_free(d3d11Buffer);
  773. }
  774. SDL_free(container->buffers);
  775. SDL_free(container);
  776. }
  777. static void D3D11_DestroyDevice(
  778. SDL_GPUDevice *device)
  779. {
  780. D3D11Renderer *renderer = (D3D11Renderer *)device->driverData;
  781. // Flush any remaining GPU work...
  782. D3D11_Wait(device->driverData);
  783. // Release the window data
  784. for (Sint32 i = renderer->claimedWindowCount - 1; i >= 0; i -= 1) {
  785. D3D11_ReleaseWindow(device->driverData, renderer->claimedWindows[i]->window);
  786. }
  787. SDL_free(renderer->claimedWindows);
  788. // Release the blit resources
  789. D3D11_INTERNAL_DestroyBlitPipelines(device->driverData);
  790. // Release UBOs
  791. for (Uint32 i = 0; i < renderer->uniformBufferPoolCount; i += 1) {
  792. ID3D11Buffer_Release(renderer->uniformBufferPool[i]->buffer);
  793. SDL_free(renderer->uniformBufferPool[i]);
  794. }
  795. SDL_free(renderer->uniformBufferPool);
  796. // Release command buffer infrastructure
  797. for (Uint32 i = 0; i < renderer->availableCommandBufferCount; i += 1) {
  798. D3D11CommandBuffer *commandBuffer = renderer->availableCommandBuffers[i];
  799. if (commandBuffer->annotation) {
  800. ID3DUserDefinedAnnotation_Release(commandBuffer->annotation);
  801. }
  802. ID3D11DeviceContext_Release(commandBuffer->context);
  803. SDL_free(commandBuffer->usedBuffers);
  804. SDL_free(commandBuffer->usedTransferBuffers);
  805. SDL_free(commandBuffer);
  806. }
  807. SDL_free(renderer->availableCommandBuffers);
  808. SDL_free(renderer->submittedCommandBuffers);
  809. // Release fence infrastructure
  810. for (Uint32 i = 0; i < renderer->availableFenceCount; i += 1) {
  811. D3D11Fence *fence = renderer->availableFences[i];
  812. ID3D11Query_Release(fence->handle);
  813. SDL_free(fence);
  814. }
  815. SDL_free(renderer->availableFences);
  816. // Release the iconv, if applicable
  817. if (renderer->iconv != NULL) {
  818. SDL_iconv_close(renderer->iconv);
  819. }
  820. // Release the mutexes
  821. SDL_DestroyMutex(renderer->acquireCommandBufferLock);
  822. SDL_DestroyMutex(renderer->acquireUniformBufferLock);
  823. SDL_DestroyMutex(renderer->contextLock);
  824. SDL_DestroyMutex(renderer->fenceLock);
  825. SDL_DestroyMutex(renderer->windowLock);
  826. // Release the device and associated objects
  827. ID3D11DeviceContext_Release(renderer->immediateContext);
  828. ID3D11Device_Release(renderer->device);
  829. IDXGIAdapter_Release(renderer->adapter);
  830. IDXGIFactory_Release(renderer->factory);
  831. // Report leaks and clean up debug objects
  832. if (renderer->dxgiDebug) {
  833. IDXGIDebug_ReportLiveObjects(
  834. renderer->dxgiDebug,
  835. D3D_IID_DXGI_DEBUG_ALL,
  836. DXGI_DEBUG_RLO_SUMMARY | DXGI_DEBUG_RLO_DETAIL);
  837. IDXGIDebug_Release(renderer->dxgiDebug);
  838. }
  839. #ifdef HAVE_IDXGIINFOQUEUE
  840. if (renderer->dxgiInfoQueue) {
  841. IDXGIInfoQueue_Release(renderer->dxgiInfoQueue);
  842. }
  843. #endif
  844. // Release the DLLs
  845. SDL_UnloadObject(renderer->d3d11_dll);
  846. SDL_UnloadObject(renderer->dxgi_dll);
  847. if (renderer->dxgidebug_dll) {
  848. SDL_UnloadObject(renderer->dxgidebug_dll);
  849. }
  850. // Free the primary structures
  851. SDL_free(renderer);
  852. SDL_free(device);
  853. }
  854. // Resource tracking
  855. static void D3D11_INTERNAL_TrackBuffer(
  856. D3D11CommandBuffer *commandBuffer,
  857. D3D11Buffer *buffer)
  858. {
  859. TRACK_RESOURCE(
  860. buffer,
  861. D3D11Buffer *,
  862. usedBuffers,
  863. usedBufferCount,
  864. usedBufferCapacity);
  865. }
  866. static void D3D11_INTERNAL_TrackTransferBuffer(
  867. D3D11CommandBuffer *commandBuffer,
  868. D3D11TransferBuffer *buffer)
  869. {
  870. TRACK_RESOURCE(
  871. buffer,
  872. D3D11TransferBuffer *,
  873. usedTransferBuffers,
  874. usedTransferBufferCount,
  875. usedTransferBufferCapacity);
  876. }
  877. static void D3D11_INTERNAL_TrackTexture(
  878. D3D11CommandBuffer *commandBuffer,
  879. D3D11Texture *texture)
  880. {
  881. TRACK_RESOURCE(
  882. texture,
  883. D3D11Texture *,
  884. usedTextures,
  885. usedTextureCount,
  886. usedTextureCapacity);
  887. }
  888. static void D3D11_INTERNAL_TrackUniformBuffer(
  889. D3D11CommandBuffer *commandBuffer,
  890. D3D11UniformBuffer *uniformBuffer)
  891. {
  892. Uint32 i;
  893. for (i = 0; i < commandBuffer->usedUniformBufferCount; i += 1) {
  894. if (commandBuffer->usedUniformBuffers[i] == uniformBuffer) {
  895. return;
  896. }
  897. }
  898. if (commandBuffer->usedUniformBufferCount == commandBuffer->usedUniformBufferCapacity) {
  899. commandBuffer->usedUniformBufferCapacity += 1;
  900. commandBuffer->usedUniformBuffers = SDL_realloc(
  901. commandBuffer->usedUniformBuffers,
  902. commandBuffer->usedUniformBufferCapacity * sizeof(D3D11UniformBuffer *));
  903. }
  904. commandBuffer->usedUniformBuffers[commandBuffer->usedUniformBufferCount] = uniformBuffer;
  905. commandBuffer->usedUniformBufferCount += 1;
  906. }
  907. // Disposal
  908. static void D3D11_INTERNAL_DestroyTexture(D3D11Texture *d3d11Texture)
  909. {
  910. if (d3d11Texture->shaderView) {
  911. ID3D11ShaderResourceView_Release(d3d11Texture->shaderView);
  912. }
  913. for (Uint32 subresourceIndex = 0; subresourceIndex < d3d11Texture->subresourceCount; subresourceIndex += 1) {
  914. if (d3d11Texture->subresources[subresourceIndex].colorTargetViews != NULL) {
  915. for (Uint32 depthIndex = 0; depthIndex < d3d11Texture->subresources[subresourceIndex].depth; depthIndex += 1) {
  916. ID3D11RenderTargetView_Release(d3d11Texture->subresources[subresourceIndex].colorTargetViews[depthIndex]);
  917. }
  918. SDL_free(d3d11Texture->subresources[subresourceIndex].colorTargetViews);
  919. }
  920. if (d3d11Texture->subresources[subresourceIndex].depthStencilTargetView != NULL) {
  921. ID3D11DepthStencilView_Release(d3d11Texture->subresources[subresourceIndex].depthStencilTargetView);
  922. }
  923. if (d3d11Texture->subresources[subresourceIndex].uav != NULL) {
  924. ID3D11UnorderedAccessView_Release(d3d11Texture->subresources[subresourceIndex].uav);
  925. }
  926. }
  927. SDL_free(d3d11Texture->subresources);
  928. ID3D11Resource_Release(d3d11Texture->handle);
  929. }
  930. static void D3D11_INTERNAL_DestroyTextureContainer(
  931. D3D11TextureContainer *container)
  932. {
  933. for (Uint32 i = 0; i < container->textureCount; i += 1) {
  934. D3D11_INTERNAL_DestroyTexture(container->textures[i]);
  935. }
  936. SDL_free(container->textures);
  937. SDL_free(container);
  938. }
  939. static void D3D11_ReleaseTexture(
  940. SDL_GPURenderer *driverData,
  941. SDL_GPUTexture *texture)
  942. {
  943. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  944. D3D11TextureContainer *container = (D3D11TextureContainer *)texture;
  945. SDL_LockMutex(renderer->contextLock);
  946. EXPAND_ARRAY_IF_NEEDED(
  947. renderer->textureContainersToDestroy,
  948. D3D11TextureContainer *,
  949. renderer->textureContainersToDestroyCount + 1,
  950. renderer->textureContainersToDestroyCapacity,
  951. renderer->textureContainersToDestroyCapacity + 1);
  952. renderer->textureContainersToDestroy[renderer->textureContainersToDestroyCount] = container;
  953. renderer->textureContainersToDestroyCount += 1;
  954. SDL_UnlockMutex(renderer->contextLock);
  955. }
  956. static void D3D11_ReleaseSampler(
  957. SDL_GPURenderer *driverData,
  958. SDL_GPUSampler *sampler)
  959. {
  960. (void)driverData; // used by other backends
  961. D3D11Sampler *d3d11Sampler = (D3D11Sampler *)sampler;
  962. ID3D11SamplerState_Release(d3d11Sampler->handle);
  963. SDL_free(d3d11Sampler);
  964. }
  965. static void D3D11_ReleaseBuffer(
  966. SDL_GPURenderer *driverData,
  967. SDL_GPUBuffer *buffer)
  968. {
  969. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  970. D3D11BufferContainer *container = (D3D11BufferContainer *)buffer;
  971. SDL_LockMutex(renderer->contextLock);
  972. EXPAND_ARRAY_IF_NEEDED(
  973. renderer->bufferContainersToDestroy,
  974. D3D11BufferContainer *,
  975. renderer->bufferContainersToDestroyCount + 1,
  976. renderer->bufferContainersToDestroyCapacity,
  977. renderer->bufferContainersToDestroyCapacity + 1);
  978. renderer->bufferContainersToDestroy[renderer->bufferContainersToDestroyCount] = container;
  979. renderer->bufferContainersToDestroyCount += 1;
  980. SDL_UnlockMutex(renderer->contextLock);
  981. }
  982. static void D3D11_ReleaseTransferBuffer(
  983. SDL_GPURenderer *driverData,
  984. SDL_GPUTransferBuffer *transferBuffer)
  985. {
  986. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  987. SDL_LockMutex(renderer->contextLock);
  988. EXPAND_ARRAY_IF_NEEDED(
  989. renderer->transferBufferContainersToDestroy,
  990. D3D11TransferBufferContainer *,
  991. renderer->transferBufferContainersToDestroyCount + 1,
  992. renderer->transferBufferContainersToDestroyCapacity,
  993. renderer->transferBufferContainersToDestroyCapacity + 1);
  994. renderer->transferBufferContainersToDestroy[renderer->transferBufferContainersToDestroyCount] = (D3D11TransferBufferContainer *)transferBuffer;
  995. renderer->transferBufferContainersToDestroyCount += 1;
  996. SDL_UnlockMutex(renderer->contextLock);
  997. }
  998. static void D3D11_INTERNAL_DestroyTransferBufferContainer(
  999. D3D11TransferBufferContainer *transferBufferContainer)
  1000. {
  1001. for (Uint32 i = 0; i < transferBufferContainer->bufferCount; i += 1) {
  1002. if (transferBufferContainer->buffers[i]->bufferDownloadCount > 0) {
  1003. SDL_free(transferBufferContainer->buffers[i]->bufferDownloads);
  1004. }
  1005. if (transferBufferContainer->buffers[i]->textureDownloadCount > 0) {
  1006. SDL_free(transferBufferContainer->buffers[i]->textureDownloads);
  1007. }
  1008. SDL_free(transferBufferContainer->buffers[i]->data);
  1009. SDL_free(transferBufferContainer->buffers[i]);
  1010. }
  1011. SDL_free(transferBufferContainer->buffers);
  1012. }
  1013. static void D3D11_ReleaseShader(
  1014. SDL_GPURenderer *driverData,
  1015. SDL_GPUShader *shader)
  1016. {
  1017. (void)driverData; // used by other backends
  1018. D3D11Shader *d3dShader = (D3D11Shader *)shader;
  1019. ID3D11DeviceChild_Release(d3dShader->handle);
  1020. if (d3dShader->bytecode) {
  1021. SDL_free(d3dShader->bytecode);
  1022. }
  1023. SDL_free(d3dShader);
  1024. }
  1025. static void D3D11_ReleaseComputePipeline(
  1026. SDL_GPURenderer *driverData,
  1027. SDL_GPUComputePipeline *computePipeline)
  1028. {
  1029. D3D11ComputePipeline *d3d11ComputePipeline = (D3D11ComputePipeline *)computePipeline;
  1030. ID3D11ComputeShader_Release(d3d11ComputePipeline->computeShader);
  1031. SDL_free(d3d11ComputePipeline);
  1032. }
  1033. static void D3D11_ReleaseGraphicsPipeline(
  1034. SDL_GPURenderer *driverData,
  1035. SDL_GPUGraphicsPipeline *graphicsPipeline)
  1036. {
  1037. (void)driverData; // used by other backends
  1038. D3D11GraphicsPipeline *d3d11GraphicsPipeline = (D3D11GraphicsPipeline *)graphicsPipeline;
  1039. ID3D11BlendState_Release(d3d11GraphicsPipeline->colorTargetBlendState);
  1040. ID3D11DepthStencilState_Release(d3d11GraphicsPipeline->depthStencilState);
  1041. ID3D11RasterizerState_Release(d3d11GraphicsPipeline->rasterizerState);
  1042. if (d3d11GraphicsPipeline->inputLayout) {
  1043. ID3D11InputLayout_Release(d3d11GraphicsPipeline->inputLayout);
  1044. }
  1045. ID3D11VertexShader_Release(d3d11GraphicsPipeline->vertexShader);
  1046. ID3D11PixelShader_Release(d3d11GraphicsPipeline->fragmentShader);
  1047. SDL_free(d3d11GraphicsPipeline);
  1048. }
  1049. // State Creation
  1050. static ID3D11BlendState *D3D11_INTERNAL_FetchBlendState(
  1051. D3D11Renderer *renderer,
  1052. Uint32 numColorTargets,
  1053. const SDL_GPUColorTargetDescription *colorTargets)
  1054. {
  1055. ID3D11BlendState *result;
  1056. D3D11_BLEND_DESC blendDesc;
  1057. HRESULT res;
  1058. /* Create a new blend state.
  1059. * The spec says the driver will not create duplicate states, so there's no need to cache.
  1060. */
  1061. SDL_zero(blendDesc); // needed for any unused RT entries
  1062. blendDesc.AlphaToCoverageEnable = FALSE;
  1063. blendDesc.IndependentBlendEnable = TRUE;
  1064. for (Uint32 i = 0; i < numColorTargets; i += 1) {
  1065. SDL_GPUColorComponentFlags colorWriteMask = colorTargets[i].blend_state.enable_color_write_mask ?
  1066. colorTargets[i].blend_state.color_write_mask :
  1067. 0xF;
  1068. blendDesc.RenderTarget[i].BlendEnable = colorTargets[i].blend_state.enable_blend;
  1069. blendDesc.RenderTarget[i].BlendOp = SDLToD3D11_BlendOp[colorTargets[i].blend_state.color_blend_op];
  1070. blendDesc.RenderTarget[i].BlendOpAlpha = SDLToD3D11_BlendOp[colorTargets[i].blend_state.alpha_blend_op];
  1071. blendDesc.RenderTarget[i].DestBlend = SDLToD3D11_BlendFactor[colorTargets[i].blend_state.dst_color_blendfactor];
  1072. blendDesc.RenderTarget[i].DestBlendAlpha = SDLToD3D11_BlendFactorAlpha[colorTargets[i].blend_state.dst_alpha_blendfactor];
  1073. blendDesc.RenderTarget[i].RenderTargetWriteMask = colorWriteMask;
  1074. blendDesc.RenderTarget[i].SrcBlend = SDLToD3D11_BlendFactor[colorTargets[i].blend_state.src_color_blendfactor];
  1075. blendDesc.RenderTarget[i].SrcBlendAlpha = SDLToD3D11_BlendFactorAlpha[colorTargets[i].blend_state.src_alpha_blendfactor];
  1076. }
  1077. res = ID3D11Device_CreateBlendState(
  1078. renderer->device,
  1079. &blendDesc,
  1080. &result);
  1081. ERROR_CHECK_RETURN("Could not create blend state", NULL);
  1082. return result;
  1083. }
  1084. static ID3D11DepthStencilState *D3D11_INTERNAL_FetchDepthStencilState(
  1085. D3D11Renderer *renderer,
  1086. SDL_GPUDepthStencilState depthStencilState)
  1087. {
  1088. ID3D11DepthStencilState *result;
  1089. D3D11_DEPTH_STENCIL_DESC dsDesc;
  1090. HRESULT res;
  1091. /* Create a new depth-stencil state.
  1092. * The spec says the driver will not create duplicate states, so there's no need to cache.
  1093. */
  1094. dsDesc.DepthEnable = depthStencilState.enable_depth_test;
  1095. dsDesc.StencilEnable = depthStencilState.enable_stencil_test;
  1096. dsDesc.DepthFunc = SDLToD3D11_CompareOp[depthStencilState.compare_op];
  1097. dsDesc.DepthWriteMask = (depthStencilState.enable_depth_write ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO);
  1098. dsDesc.BackFace.StencilFunc = SDLToD3D11_CompareOp[depthStencilState.back_stencil_state.compare_op];
  1099. dsDesc.BackFace.StencilDepthFailOp = SDLToD3D11_StencilOp[depthStencilState.back_stencil_state.depth_fail_op];
  1100. dsDesc.BackFace.StencilFailOp = SDLToD3D11_StencilOp[depthStencilState.back_stencil_state.fail_op];
  1101. dsDesc.BackFace.StencilPassOp = SDLToD3D11_StencilOp[depthStencilState.back_stencil_state.pass_op];
  1102. dsDesc.FrontFace.StencilFunc = SDLToD3D11_CompareOp[depthStencilState.front_stencil_state.compare_op];
  1103. dsDesc.FrontFace.StencilDepthFailOp = SDLToD3D11_StencilOp[depthStencilState.front_stencil_state.depth_fail_op];
  1104. dsDesc.FrontFace.StencilFailOp = SDLToD3D11_StencilOp[depthStencilState.front_stencil_state.fail_op];
  1105. dsDesc.FrontFace.StencilPassOp = SDLToD3D11_StencilOp[depthStencilState.front_stencil_state.pass_op];
  1106. dsDesc.StencilReadMask = depthStencilState.compare_mask;
  1107. dsDesc.StencilWriteMask = depthStencilState.write_mask;
  1108. res = ID3D11Device_CreateDepthStencilState(
  1109. renderer->device,
  1110. &dsDesc,
  1111. &result);
  1112. ERROR_CHECK_RETURN("Could not create depth-stencil state", NULL);
  1113. return result;
  1114. }
  1115. static ID3D11RasterizerState *D3D11_INTERNAL_FetchRasterizerState(
  1116. D3D11Renderer *renderer,
  1117. SDL_GPURasterizerState rasterizerState)
  1118. {
  1119. ID3D11RasterizerState *result;
  1120. D3D11_RASTERIZER_DESC rasterizerDesc;
  1121. HRESULT res;
  1122. /* Create a new rasterizer state.
  1123. * The spec says the driver will not create duplicate states, so there's no need to cache.
  1124. */
  1125. rasterizerDesc.AntialiasedLineEnable = FALSE;
  1126. rasterizerDesc.CullMode = SDLToD3D11_CullMode[rasterizerState.cull_mode];
  1127. rasterizerDesc.DepthBias = SDL_lroundf(rasterizerState.depth_bias_constant_factor);
  1128. rasterizerDesc.DepthBiasClamp = rasterizerState.depth_bias_clamp;
  1129. rasterizerDesc.DepthClipEnable = TRUE;
  1130. rasterizerDesc.FillMode = (rasterizerState.fill_mode == SDL_GPU_FILLMODE_FILL) ? D3D11_FILL_SOLID : D3D11_FILL_WIREFRAME;
  1131. rasterizerDesc.FrontCounterClockwise = (rasterizerState.front_face == SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE);
  1132. rasterizerDesc.MultisampleEnable = TRUE; // only applies to MSAA render targets
  1133. rasterizerDesc.ScissorEnable = TRUE;
  1134. rasterizerDesc.SlopeScaledDepthBias = rasterizerState.depth_bias_slope_factor;
  1135. res = ID3D11Device_CreateRasterizerState(
  1136. renderer->device,
  1137. &rasterizerDesc,
  1138. &result);
  1139. ERROR_CHECK_RETURN("Could not create rasterizer state", NULL);
  1140. return result;
  1141. }
  1142. static Uint32 D3D11_INTERNAL_FindIndexOfVertexSlot(
  1143. Uint32 targetSlot,
  1144. const SDL_GPUVertexBufferDescription *bufferDescriptions,
  1145. Uint32 numDescriptions)
  1146. {
  1147. for (Uint32 i = 0; i < numDescriptions; i += 1) {
  1148. if (bufferDescriptions[i].slot == targetSlot) {
  1149. return i;
  1150. }
  1151. }
  1152. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Could not find vertex buffer slot %u!", targetSlot);
  1153. return 0;
  1154. }
  1155. static ID3D11InputLayout *D3D11_INTERNAL_FetchInputLayout(
  1156. D3D11Renderer *renderer,
  1157. SDL_GPUVertexInputState inputState,
  1158. void *shaderBytes,
  1159. size_t shaderByteLength)
  1160. {
  1161. ID3D11InputLayout *result = NULL;
  1162. D3D11_INPUT_ELEMENT_DESC *elementDescs;
  1163. Uint32 bindingIndex;
  1164. HRESULT res;
  1165. // Don't bother creating/fetching an input layout if there are no attributes.
  1166. if (inputState.num_vertex_attributes == 0) {
  1167. return NULL;
  1168. }
  1169. // Allocate an array of vertex elements
  1170. elementDescs = SDL_stack_alloc(
  1171. D3D11_INPUT_ELEMENT_DESC,
  1172. inputState.num_vertex_attributes);
  1173. // Create the array of input elements
  1174. for (Uint32 i = 0; i < inputState.num_vertex_attributes; i += 1) {
  1175. elementDescs[i].AlignedByteOffset = inputState.vertex_attributes[i].offset;
  1176. elementDescs[i].Format = SDLToD3D11_VertexFormat[inputState.vertex_attributes[i].format];
  1177. elementDescs[i].InputSlot = inputState.vertex_attributes[i].buffer_slot;
  1178. bindingIndex = D3D11_INTERNAL_FindIndexOfVertexSlot(
  1179. elementDescs[i].InputSlot,
  1180. inputState.vertex_buffer_descriptions,
  1181. inputState.num_vertex_buffers);
  1182. elementDescs[i].InputSlotClass = SDLToD3D11_VertexInputRate[inputState.vertex_buffer_descriptions[bindingIndex].input_rate];
  1183. // The spec requires this to be 0 for per-vertex data
  1184. elementDescs[i].InstanceDataStepRate = (inputState.vertex_buffer_descriptions[bindingIndex].input_rate == SDL_GPU_VERTEXINPUTRATE_INSTANCE)
  1185. ? inputState.vertex_buffer_descriptions[bindingIndex].instance_step_rate
  1186. : 0;
  1187. elementDescs[i].SemanticIndex = inputState.vertex_attributes[i].location;
  1188. elementDescs[i].SemanticName = "TEXCOORD";
  1189. }
  1190. res = ID3D11Device_CreateInputLayout(
  1191. renderer->device,
  1192. elementDescs,
  1193. inputState.num_vertex_attributes,
  1194. shaderBytes,
  1195. shaderByteLength,
  1196. &result);
  1197. if (FAILED(res)) {
  1198. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Could not create input layout! Error: " HRESULT_FMT, res);
  1199. SDL_stack_free(elementDescs);
  1200. return NULL;
  1201. }
  1202. /* FIXME:
  1203. * These are not cached by the driver! Should we cache them, or allow duplicates?
  1204. * If we have one input layout per graphics pipeline maybe that wouldn't be so bad...?
  1205. */
  1206. SDL_stack_free(elementDescs);
  1207. return result;
  1208. }
  1209. // Pipeline Creation
  1210. static ID3D11DeviceChild *D3D11_INTERNAL_CreateID3D11Shader(
  1211. D3D11Renderer *renderer,
  1212. Uint32 stage,
  1213. const Uint8 *code,
  1214. size_t codeSize,
  1215. const char *entrypointName,
  1216. void **pBytecode,
  1217. size_t *pBytecodeSize)
  1218. {
  1219. ID3D11DeviceChild *handle = NULL;
  1220. HRESULT res;
  1221. // Create the shader from the byte blob
  1222. if (stage == SDL_GPU_SHADERSTAGE_VERTEX) {
  1223. res = ID3D11Device_CreateVertexShader(
  1224. renderer->device,
  1225. code,
  1226. codeSize,
  1227. NULL,
  1228. (ID3D11VertexShader **)&handle);
  1229. if (FAILED(res)) {
  1230. D3D11_INTERNAL_LogError(renderer->device, "Could not create vertex shader", res);
  1231. return NULL;
  1232. }
  1233. } else if (stage == SDL_GPU_SHADERSTAGE_FRAGMENT) {
  1234. res = ID3D11Device_CreatePixelShader(
  1235. renderer->device,
  1236. code,
  1237. codeSize,
  1238. NULL,
  1239. (ID3D11PixelShader **)&handle);
  1240. if (FAILED(res)) {
  1241. D3D11_INTERNAL_LogError(renderer->device, "Could not create pixel shader", res);
  1242. return NULL;
  1243. }
  1244. } else if (stage == SDL_GPU_SHADERSTAGE_COMPUTE) {
  1245. res = ID3D11Device_CreateComputeShader(
  1246. renderer->device,
  1247. code,
  1248. codeSize,
  1249. NULL,
  1250. (ID3D11ComputeShader **)&handle);
  1251. if (FAILED(res)) {
  1252. D3D11_INTERNAL_LogError(renderer->device, "Could not create compute shader", res);
  1253. return NULL;
  1254. }
  1255. }
  1256. if (pBytecode != NULL) {
  1257. *pBytecode = SDL_malloc(codeSize);
  1258. SDL_memcpy(*pBytecode, code, codeSize);
  1259. *pBytecodeSize = codeSize;
  1260. }
  1261. return handle;
  1262. }
  1263. static SDL_GPUComputePipeline *D3D11_CreateComputePipeline(
  1264. SDL_GPURenderer *driverData,
  1265. const SDL_GPUComputePipelineCreateInfo *createinfo)
  1266. {
  1267. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  1268. ID3D11ComputeShader *shader;
  1269. D3D11ComputePipeline *pipeline;
  1270. shader = (ID3D11ComputeShader *)D3D11_INTERNAL_CreateID3D11Shader(
  1271. renderer,
  1272. SDL_GPU_SHADERSTAGE_COMPUTE,
  1273. createinfo->code,
  1274. createinfo->code_size,
  1275. createinfo->entrypoint,
  1276. NULL,
  1277. NULL);
  1278. if (shader == NULL) {
  1279. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create compute pipeline!");
  1280. return NULL;
  1281. }
  1282. pipeline = SDL_malloc(sizeof(D3D11ComputePipeline));
  1283. pipeline->computeShader = shader;
  1284. pipeline->numSamplers = createinfo->num_samplers;
  1285. pipeline->numReadonlyStorageTextures = createinfo->num_readonly_storage_textures;
  1286. pipeline->numWriteonlyStorageTextures = createinfo->num_writeonly_storage_textures;
  1287. pipeline->numReadonlyStorageBuffers = createinfo->num_readonly_storage_buffers;
  1288. pipeline->numWriteonlyStorageBuffers = createinfo->num_writeonly_storage_buffers;
  1289. pipeline->numUniformBuffers = createinfo->num_uniform_buffers;
  1290. // thread counts are ignored in d3d11
  1291. return (SDL_GPUComputePipeline *)pipeline;
  1292. }
  1293. static SDL_GPUGraphicsPipeline *D3D11_CreateGraphicsPipeline(
  1294. SDL_GPURenderer *driverData,
  1295. const SDL_GPUGraphicsPipelineCreateInfo *createinfo)
  1296. {
  1297. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  1298. D3D11Shader *vertShader = (D3D11Shader *)createinfo->vertex_shader;
  1299. D3D11Shader *fragShader = (D3D11Shader *)createinfo->fragment_shader;
  1300. D3D11GraphicsPipeline *pipeline = SDL_malloc(sizeof(D3D11GraphicsPipeline));
  1301. // Blend
  1302. pipeline->colorTargetBlendState = D3D11_INTERNAL_FetchBlendState(
  1303. renderer,
  1304. createinfo->target_info.num_color_targets,
  1305. createinfo->target_info.color_target_descriptions);
  1306. pipeline->numColorTargets = createinfo->target_info.num_color_targets;
  1307. for (Sint32 i = 0; i < pipeline->numColorTargets; i += 1) {
  1308. pipeline->colorTargetFormats[i] = SDLToD3D11_TextureFormat[createinfo->target_info.color_target_descriptions[i].format];
  1309. }
  1310. // Multisample
  1311. pipeline->multisampleState = createinfo->multisample_state;
  1312. pipeline->sampleMask = createinfo->multisample_state.enable_mask ?
  1313. createinfo->multisample_state.sample_mask :
  1314. 0xFFFFFFFF;
  1315. // Depth-Stencil
  1316. pipeline->depthStencilState = D3D11_INTERNAL_FetchDepthStencilState(
  1317. renderer,
  1318. createinfo->depth_stencil_state);
  1319. pipeline->hasDepthStencilTarget = createinfo->target_info.has_depth_stencil_target;
  1320. pipeline->depthStencilTargetFormat = SDLToD3D11_TextureFormat[createinfo->target_info.depth_stencil_format];
  1321. // Rasterizer
  1322. pipeline->primitiveType = createinfo->primitive_type;
  1323. pipeline->rasterizerState = D3D11_INTERNAL_FetchRasterizerState(
  1324. renderer,
  1325. createinfo->rasterizer_state);
  1326. // Shaders
  1327. pipeline->vertexShader = (ID3D11VertexShader *)vertShader->handle;
  1328. ID3D11VertexShader_AddRef(pipeline->vertexShader);
  1329. pipeline->fragmentShader = (ID3D11PixelShader *)fragShader->handle;
  1330. ID3D11PixelShader_AddRef(pipeline->fragmentShader);
  1331. // Input Layout
  1332. pipeline->inputLayout = D3D11_INTERNAL_FetchInputLayout(
  1333. renderer,
  1334. createinfo->vertex_input_state,
  1335. vertShader->bytecode,
  1336. vertShader->bytecodeSize);
  1337. SDL_zeroa(pipeline->vertexStrides);
  1338. if (createinfo->vertex_input_state.num_vertex_buffers > 0) {
  1339. for (Uint32 i = 0; i < createinfo->vertex_input_state.num_vertex_buffers; i += 1) {
  1340. pipeline->vertexStrides[createinfo->vertex_input_state.vertex_buffer_descriptions[i].slot] =
  1341. createinfo->vertex_input_state.vertex_buffer_descriptions[i].pitch;
  1342. }
  1343. }
  1344. // Resource layout
  1345. pipeline->vertexSamplerCount = vertShader->numSamplers;
  1346. pipeline->vertexStorageTextureCount = vertShader->numStorageTextures;
  1347. pipeline->vertexStorageBufferCount = vertShader->numStorageBuffers;
  1348. pipeline->vertexUniformBufferCount = vertShader->numUniformBuffers;
  1349. pipeline->fragmentSamplerCount = fragShader->numSamplers;
  1350. pipeline->fragmentStorageTextureCount = fragShader->numStorageTextures;
  1351. pipeline->fragmentStorageBufferCount = fragShader->numStorageBuffers;
  1352. pipeline->fragmentUniformBufferCount = fragShader->numUniformBuffers;
  1353. return (SDL_GPUGraphicsPipeline *)pipeline;
  1354. }
  1355. // Debug Naming
  1356. static void D3D11_INTERNAL_SetBufferName(
  1357. D3D11Renderer *renderer,
  1358. D3D11Buffer *buffer,
  1359. const char *text)
  1360. {
  1361. if (renderer->debugMode) {
  1362. ID3D11DeviceChild_SetPrivateData(
  1363. buffer->handle,
  1364. &D3D_IID_D3DDebugObjectName,
  1365. (UINT)SDL_strlen(text),
  1366. text);
  1367. }
  1368. }
  1369. static void D3D11_SetBufferName(
  1370. SDL_GPURenderer *driverData,
  1371. SDL_GPUBuffer *buffer,
  1372. const char *text)
  1373. {
  1374. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  1375. D3D11BufferContainer *container = (D3D11BufferContainer *)buffer;
  1376. size_t textLength = SDL_strlen(text) + 1;
  1377. if (renderer->debugMode) {
  1378. container->debugName = SDL_realloc(
  1379. container->debugName,
  1380. textLength);
  1381. SDL_utf8strlcpy(
  1382. container->debugName,
  1383. text,
  1384. textLength);
  1385. for (Uint32 i = 0; i < container->bufferCount; i += 1) {
  1386. D3D11_INTERNAL_SetBufferName(
  1387. renderer,
  1388. container->buffers[i],
  1389. text);
  1390. }
  1391. }
  1392. }
  1393. static void D3D11_INTERNAL_SetTextureName(
  1394. D3D11Renderer *renderer,
  1395. D3D11Texture *texture,
  1396. const char *text)
  1397. {
  1398. if (renderer->debugMode) {
  1399. ID3D11DeviceChild_SetPrivateData(
  1400. texture->handle,
  1401. &D3D_IID_D3DDebugObjectName,
  1402. (UINT)SDL_strlen(text),
  1403. text);
  1404. }
  1405. }
  1406. static void D3D11_SetTextureName(
  1407. SDL_GPURenderer *driverData,
  1408. SDL_GPUTexture *texture,
  1409. const char *text)
  1410. {
  1411. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  1412. D3D11TextureContainer *container = (D3D11TextureContainer *)texture;
  1413. size_t textLength = SDL_strlen(text) + 1;
  1414. if (renderer->debugMode) {
  1415. container->debugName = SDL_realloc(
  1416. container->debugName,
  1417. textLength);
  1418. SDL_utf8strlcpy(
  1419. container->debugName,
  1420. text,
  1421. textLength);
  1422. for (Uint32 i = 0; i < container->textureCount; i += 1) {
  1423. D3D11_INTERNAL_SetTextureName(
  1424. renderer,
  1425. container->textures[i],
  1426. text);
  1427. }
  1428. }
  1429. }
  1430. static bool D3D11_INTERNAL_StrToWStr(
  1431. D3D11Renderer *renderer,
  1432. const char *str,
  1433. wchar_t *wstr,
  1434. size_t wstrSize)
  1435. {
  1436. size_t inlen, result;
  1437. size_t outlen = wstrSize;
  1438. if (renderer->iconv == NULL) {
  1439. renderer->iconv = SDL_iconv_open("WCHAR_T", "UTF-8");
  1440. SDL_assert(renderer->iconv);
  1441. }
  1442. // Convert...
  1443. inlen = SDL_strlen(str) + 1;
  1444. result = SDL_iconv(
  1445. renderer->iconv,
  1446. &str,
  1447. &inlen,
  1448. (char **)&wstr,
  1449. &outlen);
  1450. // Check...
  1451. switch (result) {
  1452. case SDL_ICONV_ERROR:
  1453. case SDL_ICONV_E2BIG:
  1454. case SDL_ICONV_EILSEQ:
  1455. case SDL_ICONV_EINVAL:
  1456. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Failed to convert string to wchar_t!");
  1457. return false;
  1458. default:
  1459. break;
  1460. }
  1461. return true;
  1462. }
  1463. static void D3D11_InsertDebugLabel(
  1464. SDL_GPUCommandBuffer *commandBuffer,
  1465. const char *text)
  1466. {
  1467. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  1468. D3D11Renderer *renderer = (D3D11Renderer *)d3d11CommandBuffer->renderer;
  1469. if (d3d11CommandBuffer->annotation == NULL) {
  1470. return;
  1471. }
  1472. wchar_t wstr[256];
  1473. if (!D3D11_INTERNAL_StrToWStr(renderer, text, wstr, sizeof(wstr))) {
  1474. return;
  1475. }
  1476. ID3DUserDefinedAnnotation_SetMarker(d3d11CommandBuffer->annotation, wstr);
  1477. }
  1478. static void D3D11_PushDebugGroup(
  1479. SDL_GPUCommandBuffer *commandBuffer,
  1480. const char *name)
  1481. {
  1482. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  1483. D3D11Renderer *renderer = (D3D11Renderer *)d3d11CommandBuffer->renderer;
  1484. if (d3d11CommandBuffer->annotation == NULL) {
  1485. return;
  1486. }
  1487. wchar_t wstr[256];
  1488. if (!D3D11_INTERNAL_StrToWStr(renderer, name, wstr, sizeof(wstr))) {
  1489. return;
  1490. }
  1491. ID3DUserDefinedAnnotation_BeginEvent(d3d11CommandBuffer->annotation, wstr);
  1492. }
  1493. static void D3D11_PopDebugGroup(
  1494. SDL_GPUCommandBuffer *commandBuffer)
  1495. {
  1496. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  1497. if (d3d11CommandBuffer->annotation == NULL) {
  1498. return;
  1499. }
  1500. ID3DUserDefinedAnnotation_EndEvent(d3d11CommandBuffer->annotation);
  1501. }
  1502. // Resource Creation
  1503. static SDL_GPUSampler *D3D11_CreateSampler(
  1504. SDL_GPURenderer *driverData,
  1505. const SDL_GPUSamplerCreateInfo *createinfo)
  1506. {
  1507. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  1508. D3D11_SAMPLER_DESC samplerDesc;
  1509. ID3D11SamplerState *samplerStateHandle;
  1510. D3D11Sampler *d3d11Sampler;
  1511. HRESULT res;
  1512. samplerDesc.AddressU = SDLToD3D11_SamplerAddressMode[createinfo->address_mode_u];
  1513. samplerDesc.AddressV = SDLToD3D11_SamplerAddressMode[createinfo->address_mode_v];
  1514. samplerDesc.AddressW = SDLToD3D11_SamplerAddressMode[createinfo->address_mode_w];
  1515. samplerDesc.ComparisonFunc = (createinfo->enable_compare ? SDLToD3D11_CompareOp[createinfo->compare_op] : SDLToD3D11_CompareOp[SDL_GPU_COMPAREOP_ALWAYS]);
  1516. samplerDesc.MaxAnisotropy = (createinfo->enable_anisotropy ? (UINT)createinfo->max_anisotropy : 0);
  1517. samplerDesc.Filter = SDLToD3D11_Filter(createinfo);
  1518. samplerDesc.MaxLOD = createinfo->max_lod;
  1519. samplerDesc.MinLOD = createinfo->min_lod;
  1520. samplerDesc.MipLODBias = createinfo->mip_lod_bias;
  1521. SDL_zeroa(samplerDesc.BorderColor); // arbitrary, unused
  1522. res = ID3D11Device_CreateSamplerState(
  1523. renderer->device,
  1524. &samplerDesc,
  1525. &samplerStateHandle);
  1526. ERROR_CHECK_RETURN("Could not create sampler state", NULL);
  1527. d3d11Sampler = (D3D11Sampler *)SDL_malloc(sizeof(D3D11Sampler));
  1528. d3d11Sampler->handle = samplerStateHandle;
  1529. return (SDL_GPUSampler *)d3d11Sampler;
  1530. }
  1531. SDL_GPUShader *D3D11_CreateShader(
  1532. SDL_GPURenderer *driverData,
  1533. const SDL_GPUShaderCreateInfo *createinfo)
  1534. {
  1535. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  1536. ID3D11DeviceChild *handle;
  1537. void *bytecode = NULL;
  1538. size_t bytecodeSize = 0;
  1539. D3D11Shader *shader;
  1540. handle = D3D11_INTERNAL_CreateID3D11Shader(
  1541. renderer,
  1542. createinfo->stage,
  1543. createinfo->code,
  1544. createinfo->code_size,
  1545. createinfo->entrypoint,
  1546. createinfo->stage == SDL_GPU_SHADERSTAGE_VERTEX ? &bytecode : NULL,
  1547. createinfo->stage == SDL_GPU_SHADERSTAGE_VERTEX ? &bytecodeSize : NULL);
  1548. if (!handle) {
  1549. return NULL;
  1550. }
  1551. shader = (D3D11Shader *)SDL_calloc(1, sizeof(D3D11Shader));
  1552. shader->handle = handle;
  1553. shader->numSamplers = createinfo->num_samplers;
  1554. shader->numStorageBuffers = createinfo->num_storage_buffers;
  1555. shader->numStorageTextures = createinfo->num_storage_textures;
  1556. shader->numUniformBuffers = createinfo->num_uniform_buffers;
  1557. if (createinfo->stage == SDL_GPU_SHADERSTAGE_VERTEX) {
  1558. // Store the raw bytecode and its length for creating InputLayouts
  1559. shader->bytecode = bytecode;
  1560. shader->bytecodeSize = bytecodeSize;
  1561. }
  1562. return (SDL_GPUShader *)shader;
  1563. }
  1564. static D3D11Texture *D3D11_INTERNAL_CreateTexture(
  1565. D3D11Renderer *renderer,
  1566. const SDL_GPUTextureCreateInfo *createInfo,
  1567. D3D11_SUBRESOURCE_DATA *initialData)
  1568. {
  1569. Uint8 needsSRV, isColorTarget, isDepthStencil, isMultisample, isStaging, needSubresourceUAV, isMippable;
  1570. DXGI_FORMAT format;
  1571. ID3D11Resource *textureHandle;
  1572. ID3D11ShaderResourceView *srv = NULL;
  1573. D3D11Texture *d3d11Texture;
  1574. HRESULT res;
  1575. isColorTarget = createInfo->usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
  1576. isDepthStencil = createInfo->usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET;
  1577. needsSRV =
  1578. (createInfo->usage & SDL_GPU_TEXTUREUSAGE_SAMPLER) ||
  1579. (createInfo->usage & SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ) ||
  1580. (createInfo->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ);
  1581. needSubresourceUAV =
  1582. (createInfo->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE);
  1583. isMultisample = createInfo->sample_count > SDL_GPU_SAMPLECOUNT_1;
  1584. isStaging = createInfo->usage == 0;
  1585. isMippable =
  1586. createInfo->num_levels > 1 &&
  1587. (createInfo->usage & SDL_GPU_TEXTUREUSAGE_SAMPLER) &&
  1588. (createInfo->usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET);
  1589. format = SDLToD3D11_TextureFormat[createInfo->format];
  1590. if (isDepthStencil) {
  1591. format = D3D11_INTERNAL_GetTypelessFormat(format);
  1592. }
  1593. Uint32 layerCount = createInfo->type == SDL_GPU_TEXTURETYPE_3D ? 1 : createInfo->layer_count_or_depth;
  1594. Uint32 depth = createInfo->type == SDL_GPU_TEXTURETYPE_3D ? createInfo->layer_count_or_depth : 1;
  1595. if (createInfo->type != SDL_GPU_TEXTURETYPE_3D) {
  1596. D3D11_TEXTURE2D_DESC desc2D;
  1597. desc2D.BindFlags = 0;
  1598. if (needsSRV) {
  1599. desc2D.BindFlags |= D3D11_BIND_SHADER_RESOURCE;
  1600. }
  1601. if (needSubresourceUAV) {
  1602. desc2D.BindFlags |= D3D11_BIND_UNORDERED_ACCESS;
  1603. }
  1604. if (isColorTarget) {
  1605. desc2D.BindFlags |= D3D11_BIND_RENDER_TARGET;
  1606. }
  1607. if (isDepthStencil) {
  1608. desc2D.BindFlags |= D3D11_BIND_DEPTH_STENCIL;
  1609. }
  1610. desc2D.Width = createInfo->width;
  1611. desc2D.Height = createInfo->height;
  1612. desc2D.ArraySize = layerCount;
  1613. desc2D.CPUAccessFlags = isStaging ? D3D11_CPU_ACCESS_WRITE : 0;
  1614. desc2D.Format = format;
  1615. desc2D.MipLevels = createInfo->num_levels;
  1616. desc2D.MiscFlags = 0;
  1617. desc2D.SampleDesc.Count = SDLToD3D11_SampleCount[createInfo->sample_count];
  1618. desc2D.SampleDesc.Quality = isMultisample ? D3D11_STANDARD_MULTISAMPLE_PATTERN : 0;
  1619. desc2D.Usage = isStaging ? D3D11_USAGE_STAGING : D3D11_USAGE_DEFAULT;
  1620. if (createInfo->type == SDL_GPU_TEXTURETYPE_CUBE || createInfo->type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  1621. desc2D.MiscFlags |= D3D11_RESOURCE_MISC_TEXTURECUBE;
  1622. }
  1623. if (isMippable) {
  1624. desc2D.MiscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS;
  1625. }
  1626. res = ID3D11Device_CreateTexture2D(
  1627. renderer->device,
  1628. &desc2D,
  1629. initialData,
  1630. (ID3D11Texture2D **)&textureHandle);
  1631. ERROR_CHECK_RETURN("Could not create Texture2D", NULL);
  1632. // Create the SRV, if applicable
  1633. if (needsSRV) {
  1634. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
  1635. srvDesc.Format = D3D11_INTERNAL_GetSampleableFormat(format);
  1636. if (createInfo->type == SDL_GPU_TEXTURETYPE_CUBE) {
  1637. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
  1638. srvDesc.TextureCube.MipLevels = desc2D.MipLevels;
  1639. srvDesc.TextureCube.MostDetailedMip = 0;
  1640. } else if (createInfo->type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  1641. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBEARRAY;
  1642. srvDesc.TextureCubeArray.MipLevels = desc2D.MipLevels;
  1643. srvDesc.TextureCubeArray.MostDetailedMip = 0;
  1644. srvDesc.TextureCubeArray.First2DArrayFace = 0;
  1645. srvDesc.TextureCubeArray.NumCubes = layerCount / 6;
  1646. } else if (createInfo->type == SDL_GPU_TEXTURETYPE_2D_ARRAY) {
  1647. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
  1648. srvDesc.Texture2DArray.MipLevels = desc2D.MipLevels;
  1649. srvDesc.Texture2DArray.MostDetailedMip = 0;
  1650. srvDesc.Texture2DArray.FirstArraySlice = 0;
  1651. srvDesc.Texture2DArray.ArraySize = layerCount;
  1652. } else {
  1653. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
  1654. srvDesc.Texture2D.MipLevels = desc2D.MipLevels;
  1655. srvDesc.Texture2D.MostDetailedMip = 0;
  1656. }
  1657. res = ID3D11Device_CreateShaderResourceView(
  1658. renderer->device,
  1659. textureHandle,
  1660. &srvDesc,
  1661. &srv);
  1662. if (FAILED(res)) {
  1663. ID3D11Resource_Release(textureHandle);
  1664. D3D11_INTERNAL_LogError(renderer->device, "Could not create SRV for 2D texture", res);
  1665. return NULL;
  1666. }
  1667. }
  1668. } else {
  1669. D3D11_TEXTURE3D_DESC desc3D;
  1670. desc3D.BindFlags = 0;
  1671. if (needsSRV) {
  1672. desc3D.BindFlags |= D3D11_BIND_SHADER_RESOURCE;
  1673. }
  1674. if (needSubresourceUAV) {
  1675. desc3D.BindFlags |= D3D11_BIND_UNORDERED_ACCESS;
  1676. }
  1677. if (isColorTarget) {
  1678. desc3D.BindFlags |= D3D11_BIND_RENDER_TARGET;
  1679. }
  1680. desc3D.Width = createInfo->width;
  1681. desc3D.Height = createInfo->height;
  1682. desc3D.Depth = depth;
  1683. desc3D.CPUAccessFlags = isStaging ? D3D11_CPU_ACCESS_WRITE : 0;
  1684. desc3D.Format = format;
  1685. desc3D.MipLevels = createInfo->num_levels;
  1686. desc3D.MiscFlags = isMippable ? D3D11_RESOURCE_MISC_GENERATE_MIPS : 0;
  1687. desc3D.Usage = isStaging ? D3D11_USAGE_STAGING : D3D11_USAGE_DEFAULT;
  1688. res = ID3D11Device_CreateTexture3D(
  1689. renderer->device,
  1690. &desc3D,
  1691. initialData,
  1692. (ID3D11Texture3D **)&textureHandle);
  1693. ERROR_CHECK_RETURN("Could not create Texture3D", NULL);
  1694. // Create the SRV, if applicable
  1695. if (needsSRV) {
  1696. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
  1697. srvDesc.Format = format;
  1698. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D;
  1699. srvDesc.Texture3D.MipLevels = desc3D.MipLevels;
  1700. srvDesc.Texture3D.MostDetailedMip = 0;
  1701. res = ID3D11Device_CreateShaderResourceView(
  1702. renderer->device,
  1703. textureHandle,
  1704. &srvDesc,
  1705. &srv);
  1706. if (FAILED(res)) {
  1707. ID3D11Resource_Release(textureHandle);
  1708. D3D11_INTERNAL_LogError(renderer->device, "Could not create SRV for 3D texture", res);
  1709. return NULL;
  1710. }
  1711. }
  1712. }
  1713. d3d11Texture = (D3D11Texture *)SDL_malloc(sizeof(D3D11Texture));
  1714. d3d11Texture->handle = textureHandle;
  1715. d3d11Texture->shaderView = srv;
  1716. SDL_AtomicSet(&d3d11Texture->referenceCount, 0);
  1717. d3d11Texture->container = NULL;
  1718. d3d11Texture->containerIndex = 0;
  1719. d3d11Texture->subresourceCount = createInfo->num_levels * layerCount;
  1720. d3d11Texture->subresources = SDL_malloc(
  1721. d3d11Texture->subresourceCount * sizeof(D3D11TextureSubresource));
  1722. for (Uint32 layerIndex = 0; layerIndex < layerCount; layerIndex += 1) {
  1723. for (Uint32 levelIndex = 0; levelIndex < createInfo->num_levels; levelIndex += 1) {
  1724. Uint32 subresourceIndex = D3D11_INTERNAL_CalcSubresource(
  1725. levelIndex,
  1726. layerIndex,
  1727. createInfo->num_levels);
  1728. d3d11Texture->subresources[subresourceIndex].parent = d3d11Texture;
  1729. d3d11Texture->subresources[subresourceIndex].layer = layerIndex;
  1730. d3d11Texture->subresources[subresourceIndex].level = levelIndex;
  1731. d3d11Texture->subresources[subresourceIndex].depth = depth;
  1732. d3d11Texture->subresources[subresourceIndex].index = subresourceIndex;
  1733. d3d11Texture->subresources[subresourceIndex].colorTargetViews = NULL;
  1734. d3d11Texture->subresources[subresourceIndex].uav = NULL;
  1735. d3d11Texture->subresources[subresourceIndex].depthStencilTargetView = NULL;
  1736. if (isDepthStencil) {
  1737. D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
  1738. dsvDesc.Format = SDLToD3D11_TextureFormat[createInfo->format];
  1739. dsvDesc.Flags = 0;
  1740. if (isMultisample) {
  1741. dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
  1742. } else {
  1743. dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
  1744. dsvDesc.Texture2D.MipSlice = levelIndex;
  1745. }
  1746. res = ID3D11Device_CreateDepthStencilView(
  1747. renderer->device,
  1748. d3d11Texture->handle,
  1749. &dsvDesc,
  1750. &d3d11Texture->subresources[subresourceIndex].depthStencilTargetView);
  1751. ERROR_CHECK_RETURN("Could not create DSV!", NULL);
  1752. } else if (isColorTarget) {
  1753. d3d11Texture->subresources[subresourceIndex].colorTargetViews = SDL_calloc(depth, sizeof(ID3D11RenderTargetView *));
  1754. for (Uint32 depthIndex = 0; depthIndex < depth; depthIndex += 1) {
  1755. D3D11_RENDER_TARGET_VIEW_DESC rtvDesc;
  1756. rtvDesc.Format = SDLToD3D11_TextureFormat[createInfo->format];
  1757. if (isMultisample) {
  1758. if (createInfo->type == SDL_GPU_TEXTURETYPE_2D) {
  1759. rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS;
  1760. } else if (createInfo->type == SDL_GPU_TEXTURETYPE_2D_ARRAY) {
  1761. rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY;
  1762. rtvDesc.Texture2DMSArray.FirstArraySlice = layerIndex;
  1763. rtvDesc.Texture2DMSArray.ArraySize = 1;
  1764. }
  1765. } else {
  1766. if (createInfo->type == SDL_GPU_TEXTURETYPE_2D_ARRAY || createInfo->type == SDL_GPU_TEXTURETYPE_CUBE || createInfo->type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  1767. rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
  1768. rtvDesc.Texture2DArray.MipSlice = levelIndex;
  1769. rtvDesc.Texture2DArray.FirstArraySlice = layerIndex;
  1770. rtvDesc.Texture2DArray.ArraySize = 1;
  1771. } else if (createInfo->type == SDL_GPU_TEXTURETYPE_3D) {
  1772. rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE3D;
  1773. rtvDesc.Texture3D.MipSlice = levelIndex;
  1774. rtvDesc.Texture3D.FirstWSlice = depthIndex;
  1775. rtvDesc.Texture3D.WSize = 1;
  1776. } else {
  1777. rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
  1778. rtvDesc.Texture2D.MipSlice = levelIndex;
  1779. }
  1780. }
  1781. res = ID3D11Device_CreateRenderTargetView(
  1782. renderer->device,
  1783. d3d11Texture->handle,
  1784. &rtvDesc,
  1785. &d3d11Texture->subresources[subresourceIndex].colorTargetViews[depthIndex]);
  1786. ERROR_CHECK_RETURN("Could not create RTV!", NULL);
  1787. }
  1788. }
  1789. if (needSubresourceUAV) {
  1790. D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc;
  1791. uavDesc.Format = format;
  1792. if (createInfo->type == SDL_GPU_TEXTURETYPE_2D_ARRAY || createInfo->type == SDL_GPU_TEXTURETYPE_CUBE || createInfo->type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  1793. uavDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2DARRAY;
  1794. uavDesc.Texture2DArray.MipSlice = levelIndex;
  1795. uavDesc.Texture2DArray.FirstArraySlice = layerIndex;
  1796. uavDesc.Texture2DArray.ArraySize = 1;
  1797. } else if (createInfo->type == SDL_GPU_TEXTURETYPE_3D) {
  1798. uavDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE3D;
  1799. uavDesc.Texture3D.MipSlice = levelIndex;
  1800. uavDesc.Texture3D.FirstWSlice = 0;
  1801. uavDesc.Texture3D.WSize = depth;
  1802. } else {
  1803. uavDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D;
  1804. uavDesc.Texture2D.MipSlice = levelIndex;
  1805. }
  1806. res = ID3D11Device_CreateUnorderedAccessView(
  1807. renderer->device,
  1808. d3d11Texture->handle,
  1809. &uavDesc,
  1810. &d3d11Texture->subresources[subresourceIndex].uav);
  1811. ERROR_CHECK_RETURN("Could not create UAV!", NULL);
  1812. }
  1813. }
  1814. }
  1815. return d3d11Texture;
  1816. }
  1817. static bool D3D11_SupportsSampleCount(
  1818. SDL_GPURenderer *driverData,
  1819. SDL_GPUTextureFormat format,
  1820. SDL_GPUSampleCount sampleCount)
  1821. {
  1822. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  1823. Uint32 levels;
  1824. HRESULT res = ID3D11Device_CheckMultisampleQualityLevels(
  1825. renderer->device,
  1826. SDLToD3D11_TextureFormat[format],
  1827. SDLToD3D11_SampleCount[sampleCount],
  1828. &levels);
  1829. return SUCCEEDED(res) && levels > 0;
  1830. }
  1831. static SDL_GPUTexture *D3D11_CreateTexture(
  1832. SDL_GPURenderer *driverData,
  1833. const SDL_GPUTextureCreateInfo *createinfo)
  1834. {
  1835. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  1836. D3D11TextureContainer *container;
  1837. D3D11Texture *texture;
  1838. texture = D3D11_INTERNAL_CreateTexture(
  1839. renderer,
  1840. createinfo,
  1841. NULL);
  1842. if (texture == NULL) {
  1843. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create texture!");
  1844. return NULL;
  1845. }
  1846. container = SDL_malloc(sizeof(D3D11TextureContainer));
  1847. container->header.info = *createinfo;
  1848. container->canBeCycled = 1;
  1849. container->activeTexture = texture;
  1850. container->textureCapacity = 1;
  1851. container->textureCount = 1;
  1852. container->textures = SDL_malloc(
  1853. container->textureCapacity * sizeof(D3D11Texture *));
  1854. container->textures[0] = texture;
  1855. container->debugName = NULL;
  1856. texture->container = container;
  1857. texture->containerIndex = 0;
  1858. return (SDL_GPUTexture *)container;
  1859. }
  1860. static void D3D11_INTERNAL_CycleActiveTexture(
  1861. D3D11Renderer *renderer,
  1862. D3D11TextureContainer *container)
  1863. {
  1864. for (Uint32 i = 0; i < container->textureCount; i += 1) {
  1865. if (SDL_AtomicGet(&container->textures[i]->referenceCount) == 0) {
  1866. container->activeTexture = container->textures[i];
  1867. return;
  1868. }
  1869. }
  1870. D3D11Texture *texture = D3D11_INTERNAL_CreateTexture(
  1871. renderer,
  1872. &container->header.info,
  1873. NULL);
  1874. if (texture == NULL) {
  1875. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to cycle active texture!");
  1876. return;
  1877. }
  1878. // No texture is available, generate a new one.
  1879. EXPAND_ARRAY_IF_NEEDED(
  1880. container->textures,
  1881. D3D11Texture *,
  1882. container->textureCount + 1,
  1883. container->textureCapacity,
  1884. container->textureCapacity + 1);
  1885. container->textures[container->textureCount] = texture;
  1886. texture->container = container;
  1887. texture->containerIndex = container->textureCount;
  1888. container->textureCount += 1;
  1889. container->activeTexture = container->textures[container->textureCount - 1];
  1890. if (renderer->debugMode && container->debugName != NULL) {
  1891. D3D11_INTERNAL_SetTextureName(
  1892. renderer,
  1893. container->activeTexture,
  1894. container->debugName);
  1895. }
  1896. }
  1897. static D3D11TextureSubresource *D3D11_INTERNAL_FetchTextureSubresource(
  1898. D3D11TextureContainer *container,
  1899. Uint32 layer,
  1900. Uint32 level)
  1901. {
  1902. Uint32 index = D3D11_INTERNAL_CalcSubresource(
  1903. level,
  1904. layer,
  1905. container->header.info.num_levels);
  1906. return &container->activeTexture->subresources[index];
  1907. }
  1908. static D3D11TextureSubresource *D3D11_INTERNAL_PrepareTextureSubresourceForWrite(
  1909. D3D11Renderer *renderer,
  1910. D3D11TextureContainer *container,
  1911. Uint32 layer,
  1912. Uint32 level,
  1913. bool cycle)
  1914. {
  1915. D3D11TextureSubresource *subresource = D3D11_INTERNAL_FetchTextureSubresource(
  1916. container,
  1917. layer,
  1918. level);
  1919. if (
  1920. container->canBeCycled &&
  1921. cycle &&
  1922. SDL_AtomicGet(&subresource->parent->referenceCount) > 0) {
  1923. D3D11_INTERNAL_CycleActiveTexture(
  1924. renderer,
  1925. container);
  1926. subresource = D3D11_INTERNAL_FetchTextureSubresource(
  1927. container,
  1928. layer,
  1929. level);
  1930. }
  1931. return subresource;
  1932. }
  1933. static D3D11Buffer *D3D11_INTERNAL_CreateBuffer(
  1934. D3D11Renderer *renderer,
  1935. D3D11_BUFFER_DESC *bufferDesc,
  1936. Uint32 size)
  1937. {
  1938. ID3D11Buffer *bufferHandle;
  1939. ID3D11UnorderedAccessView *uav = NULL;
  1940. ID3D11ShaderResourceView *srv = NULL;
  1941. D3D11Buffer *d3d11Buffer;
  1942. HRESULT res;
  1943. // Storage buffers have to be 4-aligned, so might as well align them all
  1944. size = D3D11_INTERNAL_NextHighestAlignment(size, 4);
  1945. res = ID3D11Device_CreateBuffer(
  1946. renderer->device,
  1947. bufferDesc,
  1948. NULL,
  1949. &bufferHandle);
  1950. ERROR_CHECK_RETURN("Could not create buffer", NULL);
  1951. // Storage buffer
  1952. if (bufferDesc->MiscFlags & D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS) {
  1953. // Create a UAV for the buffer
  1954. D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc;
  1955. uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
  1956. uavDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
  1957. uavDesc.Buffer.FirstElement = 0;
  1958. uavDesc.Buffer.NumElements = size / sizeof(Uint32);
  1959. uavDesc.Buffer.Flags = D3D11_BUFFER_UAV_FLAG_RAW;
  1960. res = ID3D11Device_CreateUnorderedAccessView(
  1961. renderer->device,
  1962. (ID3D11Resource *)bufferHandle,
  1963. &uavDesc,
  1964. &uav);
  1965. if (FAILED(res)) {
  1966. ID3D11Buffer_Release(bufferHandle);
  1967. ERROR_CHECK_RETURN("Could not create UAV for buffer!", NULL);
  1968. }
  1969. // Create a SRV for the buffer
  1970. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
  1971. srvDesc.Format = DXGI_FORMAT_R32_TYPELESS;
  1972. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX;
  1973. srvDesc.BufferEx.FirstElement = 0;
  1974. srvDesc.BufferEx.NumElements = size / sizeof(Uint32);
  1975. srvDesc.BufferEx.Flags = D3D11_BUFFEREX_SRV_FLAG_RAW;
  1976. res = ID3D11Device_CreateShaderResourceView(
  1977. renderer->device,
  1978. (ID3D11Resource *)bufferHandle,
  1979. &srvDesc,
  1980. &srv);
  1981. if (FAILED(res)) {
  1982. ID3D11Buffer_Release(bufferHandle);
  1983. ERROR_CHECK_RETURN("Could not create SRV for buffer!", NULL);
  1984. }
  1985. }
  1986. d3d11Buffer = SDL_malloc(sizeof(D3D11Buffer));
  1987. d3d11Buffer->handle = bufferHandle;
  1988. d3d11Buffer->size = size;
  1989. d3d11Buffer->uav = uav;
  1990. d3d11Buffer->srv = srv;
  1991. SDL_AtomicSet(&d3d11Buffer->referenceCount, 0);
  1992. return d3d11Buffer;
  1993. }
  1994. static SDL_GPUBuffer *D3D11_CreateBuffer(
  1995. SDL_GPURenderer *driverData,
  1996. SDL_GPUBufferUsageFlags usageFlags,
  1997. Uint32 size)
  1998. {
  1999. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  2000. D3D11BufferContainer *container;
  2001. D3D11Buffer *buffer;
  2002. D3D11_BUFFER_DESC bufferDesc;
  2003. bufferDesc.BindFlags = 0;
  2004. if (usageFlags & SDL_GPU_BUFFERUSAGE_VERTEX) {
  2005. bufferDesc.BindFlags |= D3D11_BIND_VERTEX_BUFFER;
  2006. }
  2007. if (usageFlags & SDL_GPU_BUFFERUSAGE_INDEX) {
  2008. bufferDesc.BindFlags |= D3D11_BIND_INDEX_BUFFER;
  2009. }
  2010. if (usageFlags & SDL_GPU_BUFFERUSAGE_INDIRECT) {
  2011. bufferDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS;
  2012. }
  2013. if (usageFlags & (SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ |
  2014. SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ |
  2015. SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE)) {
  2016. bufferDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS | D3D11_BIND_SHADER_RESOURCE;
  2017. }
  2018. bufferDesc.ByteWidth = size;
  2019. bufferDesc.Usage = D3D11_USAGE_DEFAULT;
  2020. bufferDesc.CPUAccessFlags = 0;
  2021. bufferDesc.StructureByteStride = 0;
  2022. bufferDesc.MiscFlags = 0;
  2023. if (usageFlags & SDL_GPU_BUFFERUSAGE_INDIRECT) {
  2024. bufferDesc.MiscFlags |= D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS;
  2025. }
  2026. if (usageFlags & (SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ |
  2027. SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ |
  2028. SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE)) {
  2029. bufferDesc.MiscFlags |= D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS;
  2030. }
  2031. buffer = D3D11_INTERNAL_CreateBuffer(
  2032. renderer,
  2033. &bufferDesc,
  2034. size);
  2035. if (buffer == NULL) {
  2036. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create buffer!");
  2037. return NULL;
  2038. }
  2039. container = SDL_malloc(sizeof(D3D11BufferContainer));
  2040. container->activeBuffer = buffer;
  2041. container->bufferCapacity = 1;
  2042. container->bufferCount = 1;
  2043. container->buffers = SDL_malloc(
  2044. container->bufferCapacity * sizeof(D3D11Buffer *));
  2045. container->buffers[0] = container->activeBuffer;
  2046. container->bufferDesc = bufferDesc;
  2047. container->debugName = NULL;
  2048. return (SDL_GPUBuffer *)container;
  2049. }
  2050. static D3D11UniformBuffer *D3D11_INTERNAL_CreateUniformBuffer(
  2051. D3D11Renderer *renderer,
  2052. Uint32 size)
  2053. {
  2054. D3D11UniformBuffer *uniformBuffer;
  2055. ID3D11Buffer *buffer;
  2056. D3D11_BUFFER_DESC bufferDesc;
  2057. HRESULT res;
  2058. bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  2059. bufferDesc.ByteWidth = size;
  2060. bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  2061. bufferDesc.MiscFlags = 0;
  2062. bufferDesc.StructureByteStride = 0;
  2063. bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
  2064. res = ID3D11Device_CreateBuffer(
  2065. renderer->device,
  2066. &bufferDesc,
  2067. NULL,
  2068. &buffer);
  2069. ERROR_CHECK_RETURN("Could not create uniform buffer", NULL)
  2070. uniformBuffer = SDL_malloc(sizeof(D3D11UniformBuffer));
  2071. uniformBuffer->buffer = buffer;
  2072. uniformBuffer->writeOffset = 0;
  2073. uniformBuffer->drawOffset = 0;
  2074. uniformBuffer->currentBlockSize = 0;
  2075. return uniformBuffer;
  2076. }
  2077. static void D3D11_INTERNAL_CycleActiveBuffer(
  2078. D3D11Renderer *renderer,
  2079. D3D11BufferContainer *container)
  2080. {
  2081. Uint32 size = container->activeBuffer->size;
  2082. for (Uint32 i = 0; i < container->bufferCount; i += 1) {
  2083. if (SDL_AtomicGet(&container->buffers[i]->referenceCount) == 0) {
  2084. container->activeBuffer = container->buffers[i];
  2085. return;
  2086. }
  2087. }
  2088. EXPAND_ARRAY_IF_NEEDED(
  2089. container->buffers,
  2090. D3D11Buffer *,
  2091. container->bufferCount + 1,
  2092. container->bufferCapacity,
  2093. container->bufferCapacity + 1);
  2094. container->buffers[container->bufferCount] = D3D11_INTERNAL_CreateBuffer(
  2095. renderer,
  2096. &container->bufferDesc,
  2097. size);
  2098. container->bufferCount += 1;
  2099. container->activeBuffer = container->buffers[container->bufferCount - 1];
  2100. if (renderer->debugMode && container->debugName != NULL) {
  2101. D3D11_INTERNAL_SetBufferName(
  2102. renderer,
  2103. container->activeBuffer,
  2104. container->debugName);
  2105. }
  2106. }
  2107. static D3D11Buffer *D3D11_INTERNAL_PrepareBufferForWrite(
  2108. D3D11Renderer *renderer,
  2109. D3D11BufferContainer *container,
  2110. bool cycle)
  2111. {
  2112. if (
  2113. cycle &&
  2114. SDL_AtomicGet(&container->activeBuffer->referenceCount) > 0) {
  2115. D3D11_INTERNAL_CycleActiveBuffer(
  2116. renderer,
  2117. container);
  2118. }
  2119. return container->activeBuffer;
  2120. }
  2121. static D3D11TransferBuffer *D3D11_INTERNAL_CreateTransferBuffer(
  2122. D3D11Renderer *renderer,
  2123. Uint32 size)
  2124. {
  2125. D3D11TransferBuffer *transferBuffer = SDL_malloc(sizeof(D3D11TransferBuffer));
  2126. transferBuffer->data = (Uint8 *)SDL_malloc(size);
  2127. transferBuffer->size = size;
  2128. SDL_AtomicSet(&transferBuffer->referenceCount, 0);
  2129. transferBuffer->bufferDownloads = NULL;
  2130. transferBuffer->bufferDownloadCount = 0;
  2131. transferBuffer->bufferDownloadCapacity = 0;
  2132. transferBuffer->textureDownloads = NULL;
  2133. transferBuffer->textureDownloadCount = 0;
  2134. transferBuffer->textureDownloadCapacity = 0;
  2135. return transferBuffer;
  2136. }
  2137. // This actually returns a container handle so we can rotate buffers on Cycle.
  2138. static SDL_GPUTransferBuffer *D3D11_CreateTransferBuffer(
  2139. SDL_GPURenderer *driverData,
  2140. SDL_GPUTransferBufferUsage usage, // ignored on D3D11
  2141. Uint32 size)
  2142. {
  2143. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  2144. D3D11TransferBufferContainer *container = (D3D11TransferBufferContainer *)SDL_malloc(sizeof(D3D11TransferBufferContainer));
  2145. container->bufferCapacity = 1;
  2146. container->bufferCount = 1;
  2147. container->buffers = SDL_malloc(
  2148. container->bufferCapacity * sizeof(D3D11TransferBuffer *));
  2149. container->buffers[0] = D3D11_INTERNAL_CreateTransferBuffer(
  2150. renderer,
  2151. size);
  2152. container->activeBuffer = container->buffers[0];
  2153. return (SDL_GPUTransferBuffer *)container;
  2154. }
  2155. // TransferBuffer Data
  2156. static void D3D11_INTERNAL_CycleActiveTransferBuffer(
  2157. D3D11Renderer *renderer,
  2158. D3D11TransferBufferContainer *container)
  2159. {
  2160. Uint32 size = container->activeBuffer->size;
  2161. for (Uint32 i = 0; i < container->bufferCount; i += 1) {
  2162. if (SDL_AtomicGet(&container->buffers[i]->referenceCount) == 0) {
  2163. container->activeBuffer = container->buffers[i];
  2164. return;
  2165. }
  2166. }
  2167. EXPAND_ARRAY_IF_NEEDED(
  2168. container->buffers,
  2169. D3D11TransferBuffer *,
  2170. container->bufferCount + 1,
  2171. container->bufferCapacity,
  2172. container->bufferCapacity + 1);
  2173. container->buffers[container->bufferCount] = D3D11_INTERNAL_CreateTransferBuffer(
  2174. renderer,
  2175. size);
  2176. container->bufferCount += 1;
  2177. container->activeBuffer = container->buffers[container->bufferCount - 1];
  2178. }
  2179. static void *D3D11_MapTransferBuffer(
  2180. SDL_GPURenderer *driverData,
  2181. SDL_GPUTransferBuffer *transferBuffer,
  2182. bool cycle)
  2183. {
  2184. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  2185. D3D11TransferBufferContainer *container = (D3D11TransferBufferContainer *)transferBuffer;
  2186. D3D11TransferBuffer *buffer = container->activeBuffer;
  2187. // Rotate the transfer buffer if necessary
  2188. if (
  2189. cycle &&
  2190. SDL_AtomicGet(&container->activeBuffer->referenceCount) > 0) {
  2191. D3D11_INTERNAL_CycleActiveTransferBuffer(
  2192. renderer,
  2193. container);
  2194. buffer = container->activeBuffer;
  2195. }
  2196. return buffer->data;
  2197. }
  2198. static void D3D11_UnmapTransferBuffer(
  2199. SDL_GPURenderer *driverData,
  2200. SDL_GPUTransferBuffer *transferBuffer)
  2201. {
  2202. // no-op
  2203. (void)driverData;
  2204. (void)transferBuffer;
  2205. }
  2206. // Copy Pass
  2207. static void D3D11_BeginCopyPass(
  2208. SDL_GPUCommandBuffer *commandBuffer)
  2209. {
  2210. // no-op
  2211. }
  2212. static void D3D11_UploadToTexture(
  2213. SDL_GPUCommandBuffer *commandBuffer,
  2214. const SDL_GPUTextureTransferInfo *source,
  2215. const SDL_GPUTextureRegion *destination,
  2216. bool cycle)
  2217. {
  2218. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  2219. D3D11Renderer *renderer = (D3D11Renderer *)d3d11CommandBuffer->renderer;
  2220. D3D11TransferBufferContainer *srcTransferContainer = (D3D11TransferBufferContainer *)source->transfer_buffer;
  2221. D3D11TransferBuffer *srcTransferBuffer = srcTransferContainer->activeBuffer;
  2222. D3D11TextureContainer *dstTextureContainer = (D3D11TextureContainer *)destination->texture;
  2223. SDL_GPUTextureFormat dstFormat = dstTextureContainer->header.info.format;
  2224. Uint32 bufferStride = source->pixels_per_row;
  2225. Uint32 bufferImageHeight = source->rows_per_layer;
  2226. Sint32 w = destination->w;
  2227. Sint32 h = destination->h;
  2228. D3D11Texture *stagingTexture;
  2229. SDL_GPUTextureCreateInfo stagingTextureCreateInfo;
  2230. D3D11_SUBRESOURCE_DATA initialData;
  2231. D3D11TextureSubresource *textureSubresource = D3D11_INTERNAL_PrepareTextureSubresourceForWrite(
  2232. renderer,
  2233. dstTextureContainer,
  2234. destination->layer,
  2235. destination->mip_level,
  2236. cycle);
  2237. Sint32 blockSize = Texture_GetBlockSize(dstFormat);
  2238. if (blockSize > 1) {
  2239. w = (w + blockSize - 1) & ~(blockSize - 1);
  2240. h = (h + blockSize - 1) & ~(blockSize - 1);
  2241. }
  2242. if (bufferStride == 0) {
  2243. bufferStride = w;
  2244. }
  2245. if (bufferImageHeight == 0) {
  2246. bufferImageHeight = h;
  2247. }
  2248. Uint32 bytesPerRow = BytesPerRow(bufferStride, dstFormat);
  2249. Uint32 bytesPerDepthSlice = bytesPerRow * bufferImageHeight;
  2250. /* UpdateSubresource1 is completely busted on AMD, it truncates after X bytes.
  2251. * So we get to do this Fun (Tm) workaround where we create a staging texture
  2252. * with initial data before issuing a copy command.
  2253. */
  2254. stagingTextureCreateInfo.width = w;
  2255. stagingTextureCreateInfo.height = h;
  2256. stagingTextureCreateInfo.layer_count_or_depth = 1;
  2257. stagingTextureCreateInfo.num_levels = 1;
  2258. stagingTextureCreateInfo.type = SDL_GPU_TEXTURETYPE_2D;
  2259. stagingTextureCreateInfo.usage = 0;
  2260. stagingTextureCreateInfo.sample_count = SDL_GPU_SAMPLECOUNT_1;
  2261. stagingTextureCreateInfo.format = dstFormat;
  2262. initialData.pSysMem = srcTransferBuffer->data + source->offset;
  2263. initialData.SysMemPitch = bytesPerRow;
  2264. initialData.SysMemSlicePitch = bytesPerDepthSlice;
  2265. stagingTexture = D3D11_INTERNAL_CreateTexture(
  2266. renderer,
  2267. &stagingTextureCreateInfo,
  2268. &initialData);
  2269. if (stagingTexture == NULL) {
  2270. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Staging texture creation failed");
  2271. return;
  2272. }
  2273. ID3D11DeviceContext_CopySubresourceRegion(
  2274. d3d11CommandBuffer->context,
  2275. textureSubresource->parent->handle,
  2276. textureSubresource->index,
  2277. destination->x,
  2278. destination->y,
  2279. destination->z,
  2280. stagingTexture->handle,
  2281. 0,
  2282. NULL);
  2283. // Clean up the staging texture
  2284. D3D11_INTERNAL_DestroyTexture(stagingTexture);
  2285. D3D11_INTERNAL_TrackTexture(d3d11CommandBuffer, textureSubresource->parent);
  2286. D3D11_INTERNAL_TrackTransferBuffer(d3d11CommandBuffer, srcTransferBuffer);
  2287. }
  2288. static void D3D11_UploadToBuffer(
  2289. SDL_GPUCommandBuffer *commandBuffer,
  2290. const SDL_GPUTransferBufferLocation *source,
  2291. const SDL_GPUBufferRegion *destination,
  2292. bool cycle)
  2293. {
  2294. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  2295. D3D11Renderer *renderer = (D3D11Renderer *)d3d11CommandBuffer->renderer;
  2296. D3D11TransferBufferContainer *transferContainer = (D3D11TransferBufferContainer *)source->transfer_buffer;
  2297. D3D11TransferBuffer *d3d11TransferBuffer = transferContainer->activeBuffer;
  2298. D3D11BufferContainer *bufferContainer = (D3D11BufferContainer *)destination->buffer;
  2299. D3D11Buffer *d3d11Buffer = D3D11_INTERNAL_PrepareBufferForWrite(
  2300. renderer,
  2301. bufferContainer,
  2302. cycle);
  2303. ID3D11Buffer *stagingBuffer;
  2304. D3D11_BUFFER_DESC stagingBufferDesc;
  2305. D3D11_SUBRESOURCE_DATA stagingBufferData;
  2306. HRESULT res;
  2307. // Upload to staging buffer immediately
  2308. stagingBufferDesc.ByteWidth = destination->size;
  2309. stagingBufferDesc.Usage = D3D11_USAGE_STAGING;
  2310. stagingBufferDesc.BindFlags = 0;
  2311. stagingBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  2312. stagingBufferDesc.MiscFlags = 0;
  2313. stagingBufferDesc.StructureByteStride = 0;
  2314. stagingBufferData.pSysMem = d3d11TransferBuffer->data + source->offset;
  2315. stagingBufferData.SysMemPitch = 0;
  2316. stagingBufferData.SysMemSlicePitch = 0;
  2317. res = ID3D11Device_CreateBuffer(
  2318. renderer->device,
  2319. &stagingBufferDesc,
  2320. &stagingBufferData,
  2321. &stagingBuffer);
  2322. ERROR_CHECK_RETURN("Could not create staging buffer", )
  2323. // Copy from staging buffer to buffer
  2324. ID3D11DeviceContext1_CopySubresourceRegion(
  2325. d3d11CommandBuffer->context,
  2326. (ID3D11Resource *)d3d11Buffer->handle,
  2327. 0,
  2328. destination->offset,
  2329. 0,
  2330. 0,
  2331. (ID3D11Resource *)stagingBuffer,
  2332. 0,
  2333. NULL);
  2334. ID3D11Buffer_Release(stagingBuffer);
  2335. D3D11_INTERNAL_TrackBuffer(d3d11CommandBuffer, d3d11Buffer);
  2336. D3D11_INTERNAL_TrackTransferBuffer(d3d11CommandBuffer, d3d11TransferBuffer);
  2337. }
  2338. static void D3D11_DownloadFromTexture(
  2339. SDL_GPUCommandBuffer *commandBuffer,
  2340. const SDL_GPUTextureRegion *source,
  2341. const SDL_GPUTextureTransferInfo *destination)
  2342. {
  2343. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  2344. D3D11Renderer *renderer = d3d11CommandBuffer->renderer;
  2345. D3D11TransferBufferContainer *dstTransferContainer = (D3D11TransferBufferContainer *)destination->transfer_buffer;
  2346. D3D11TransferBuffer *d3d11TransferBuffer = dstTransferContainer->activeBuffer;
  2347. D3D11TextureContainer *srcTextureContainer = (D3D11TextureContainer *)source->texture;
  2348. SDL_GPUTextureFormat srcFormat = srcTextureContainer->header.info.format;
  2349. D3D11_TEXTURE2D_DESC stagingDesc2D;
  2350. D3D11_TEXTURE3D_DESC stagingDesc3D;
  2351. D3D11TextureSubresource *textureSubresource = D3D11_INTERNAL_FetchTextureSubresource(
  2352. srcTextureContainer,
  2353. source->layer,
  2354. source->mip_level);
  2355. D3D11TextureDownload *textureDownload;
  2356. Uint32 bufferStride = destination->pixels_per_row;
  2357. Uint32 bufferImageHeight = destination->rows_per_layer;
  2358. Uint32 bytesPerRow, bytesPerDepthSlice;
  2359. D3D11_BOX srcBox = { source->x, source->y, source->z, source->x + source->w, source->y + source->h, source->z + source->d };
  2360. HRESULT res;
  2361. if (d3d11TransferBuffer->textureDownloadCount >= d3d11TransferBuffer->textureDownloadCapacity) {
  2362. d3d11TransferBuffer->textureDownloadCapacity += 1;
  2363. d3d11TransferBuffer->textureDownloads = SDL_realloc(
  2364. d3d11TransferBuffer->textureDownloads,
  2365. d3d11TransferBuffer->textureDownloadCapacity * sizeof(D3D11TextureDownload));
  2366. }
  2367. textureDownload = &d3d11TransferBuffer->textureDownloads[d3d11TransferBuffer->textureDownloadCount];
  2368. d3d11TransferBuffer->textureDownloadCount += 1;
  2369. if (bufferStride == 0) {
  2370. bufferStride = source->w;
  2371. }
  2372. if (bufferImageHeight == 0) {
  2373. bufferImageHeight = source->h;
  2374. }
  2375. bytesPerRow = BytesPerRow(bufferStride, srcFormat);
  2376. bytesPerDepthSlice = bytesPerRow * bufferImageHeight;
  2377. if (source->d == 1) {
  2378. stagingDesc2D.Width = source->w;
  2379. stagingDesc2D.Height = source->h;
  2380. stagingDesc2D.MipLevels = 1;
  2381. stagingDesc2D.ArraySize = 1;
  2382. stagingDesc2D.Format = SDLToD3D11_TextureFormat[srcFormat];
  2383. stagingDesc2D.SampleDesc.Count = 1;
  2384. stagingDesc2D.SampleDesc.Quality = 0;
  2385. stagingDesc2D.Usage = D3D11_USAGE_STAGING;
  2386. stagingDesc2D.BindFlags = 0;
  2387. stagingDesc2D.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  2388. stagingDesc2D.MiscFlags = 0;
  2389. res = ID3D11Device_CreateTexture2D(
  2390. renderer->device,
  2391. &stagingDesc2D,
  2392. NULL,
  2393. (ID3D11Texture2D **)&textureDownload->stagingTexture);
  2394. ERROR_CHECK_RETURN("Staging texture creation failed", )
  2395. } else {
  2396. stagingDesc3D.Width = source->w;
  2397. stagingDesc3D.Height = source->h;
  2398. stagingDesc3D.Depth = source->d;
  2399. stagingDesc3D.MipLevels = 1;
  2400. stagingDesc3D.Format = SDLToD3D11_TextureFormat[srcFormat];
  2401. stagingDesc3D.Usage = D3D11_USAGE_STAGING;
  2402. stagingDesc3D.BindFlags = 0;
  2403. stagingDesc3D.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  2404. stagingDesc3D.MiscFlags = 0;
  2405. res = ID3D11Device_CreateTexture3D(
  2406. renderer->device,
  2407. &stagingDesc3D,
  2408. NULL,
  2409. (ID3D11Texture3D **)&textureDownload->stagingTexture);
  2410. }
  2411. textureDownload->width = source->w;
  2412. textureDownload->height = source->h;
  2413. textureDownload->depth = source->d;
  2414. textureDownload->bufferOffset = destination->offset;
  2415. textureDownload->bytesPerRow = bytesPerRow;
  2416. textureDownload->bytesPerDepthSlice = bytesPerDepthSlice;
  2417. ID3D11DeviceContext1_CopySubresourceRegion1(
  2418. d3d11CommandBuffer->context,
  2419. textureDownload->stagingTexture,
  2420. 0,
  2421. 0,
  2422. 0,
  2423. 0,
  2424. textureSubresource->parent->handle,
  2425. textureSubresource->index,
  2426. &srcBox,
  2427. D3D11_COPY_NO_OVERWRITE);
  2428. D3D11_INTERNAL_TrackTexture(d3d11CommandBuffer, textureSubresource->parent);
  2429. D3D11_INTERNAL_TrackTransferBuffer(d3d11CommandBuffer, d3d11TransferBuffer);
  2430. }
  2431. static void D3D11_DownloadFromBuffer(
  2432. SDL_GPUCommandBuffer *commandBuffer,
  2433. const SDL_GPUBufferRegion *source,
  2434. const SDL_GPUTransferBufferLocation *destination)
  2435. {
  2436. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  2437. D3D11Renderer *renderer = d3d11CommandBuffer->renderer;
  2438. D3D11TransferBufferContainer *dstTransferContainer = (D3D11TransferBufferContainer *)destination->transfer_buffer;
  2439. D3D11TransferBuffer *d3d11TransferBuffer = dstTransferContainer->activeBuffer;
  2440. D3D11BufferContainer *srcBufferContainer = (D3D11BufferContainer *)source->buffer;
  2441. D3D11BufferDownload *bufferDownload;
  2442. D3D11_BOX srcBox = { source->offset, 0, 0, source->size, 1, 1 };
  2443. D3D11_BUFFER_DESC stagingBufferDesc;
  2444. HRESULT res;
  2445. if (d3d11TransferBuffer->bufferDownloadCount >= d3d11TransferBuffer->bufferDownloadCapacity) {
  2446. d3d11TransferBuffer->bufferDownloadCapacity += 1;
  2447. d3d11TransferBuffer->bufferDownloads = SDL_realloc(
  2448. d3d11TransferBuffer->bufferDownloads,
  2449. d3d11TransferBuffer->bufferDownloadCapacity * sizeof(D3D11BufferDownload));
  2450. }
  2451. bufferDownload = &d3d11TransferBuffer->bufferDownloads[d3d11TransferBuffer->bufferDownloadCount];
  2452. d3d11TransferBuffer->bufferDownloadCount += 1;
  2453. stagingBufferDesc.ByteWidth = source->size;
  2454. stagingBufferDesc.Usage = D3D11_USAGE_STAGING;
  2455. stagingBufferDesc.BindFlags = 0;
  2456. stagingBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  2457. stagingBufferDesc.MiscFlags = 0;
  2458. stagingBufferDesc.StructureByteStride = 0;
  2459. res = ID3D11Device_CreateBuffer(
  2460. renderer->device,
  2461. &stagingBufferDesc,
  2462. NULL,
  2463. &bufferDownload->stagingBuffer);
  2464. ERROR_CHECK_RETURN("Could not create staging buffer", )
  2465. ID3D11DeviceContext1_CopySubresourceRegion1(
  2466. d3d11CommandBuffer->context,
  2467. (ID3D11Resource *)bufferDownload->stagingBuffer,
  2468. 0,
  2469. 0,
  2470. 0,
  2471. 0,
  2472. (ID3D11Resource *)srcBufferContainer->activeBuffer->handle,
  2473. 0,
  2474. &srcBox,
  2475. D3D11_COPY_NO_OVERWRITE);
  2476. bufferDownload->dstOffset = destination->offset;
  2477. bufferDownload->size = source->size;
  2478. D3D11_INTERNAL_TrackBuffer(d3d11CommandBuffer, srcBufferContainer->activeBuffer);
  2479. D3D11_INTERNAL_TrackTransferBuffer(d3d11CommandBuffer, d3d11TransferBuffer);
  2480. }
  2481. static void D3D11_CopyTextureToTexture(
  2482. SDL_GPUCommandBuffer *commandBuffer,
  2483. const SDL_GPUTextureLocation *source,
  2484. const SDL_GPUTextureLocation *destination,
  2485. Uint32 w,
  2486. Uint32 h,
  2487. Uint32 d,
  2488. bool cycle)
  2489. {
  2490. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  2491. D3D11Renderer *renderer = (D3D11Renderer *)d3d11CommandBuffer->renderer;
  2492. D3D11TextureContainer *srcContainer = (D3D11TextureContainer *)source->texture;
  2493. D3D11TextureContainer *dstContainer = (D3D11TextureContainer *)destination->texture;
  2494. D3D11_BOX srcBox = { source->x, source->y, source->z, source->x + w, source->y + h, source->z + d };
  2495. D3D11TextureSubresource *srcSubresource = D3D11_INTERNAL_FetchTextureSubresource(
  2496. srcContainer,
  2497. source->layer,
  2498. source->mip_level);
  2499. D3D11TextureSubresource *dstSubresource = D3D11_INTERNAL_PrepareTextureSubresourceForWrite(
  2500. renderer,
  2501. dstContainer,
  2502. destination->layer,
  2503. destination->mip_level,
  2504. cycle);
  2505. ID3D11DeviceContext1_CopySubresourceRegion(
  2506. d3d11CommandBuffer->context,
  2507. dstSubresource->parent->handle,
  2508. dstSubresource->index,
  2509. destination->x,
  2510. destination->y,
  2511. destination->z,
  2512. srcSubresource->parent->handle,
  2513. srcSubresource->index,
  2514. &srcBox);
  2515. D3D11_INTERNAL_TrackTexture(d3d11CommandBuffer, srcSubresource->parent);
  2516. D3D11_INTERNAL_TrackTexture(d3d11CommandBuffer, dstSubresource->parent);
  2517. }
  2518. static void D3D11_CopyBufferToBuffer(
  2519. SDL_GPUCommandBuffer *commandBuffer,
  2520. const SDL_GPUBufferLocation *source,
  2521. const SDL_GPUBufferLocation *destination,
  2522. Uint32 size,
  2523. bool cycle)
  2524. {
  2525. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  2526. D3D11Renderer *renderer = (D3D11Renderer *)d3d11CommandBuffer->renderer;
  2527. D3D11BufferContainer *srcBufferContainer = (D3D11BufferContainer *)source->buffer;
  2528. D3D11BufferContainer *dstBufferContainer = (D3D11BufferContainer *)destination->buffer;
  2529. D3D11_BOX srcBox = { source->offset, 0, 0, source->offset + size, 1, 1 };
  2530. D3D11Buffer *srcBuffer = srcBufferContainer->activeBuffer;
  2531. D3D11Buffer *dstBuffer = D3D11_INTERNAL_PrepareBufferForWrite(
  2532. renderer,
  2533. dstBufferContainer,
  2534. cycle);
  2535. ID3D11DeviceContext1_CopySubresourceRegion(
  2536. d3d11CommandBuffer->context,
  2537. (ID3D11Resource *)dstBuffer->handle,
  2538. 0,
  2539. destination->offset,
  2540. 0,
  2541. 0,
  2542. (ID3D11Resource *)srcBuffer->handle,
  2543. 0,
  2544. &srcBox);
  2545. D3D11_INTERNAL_TrackBuffer(d3d11CommandBuffer, srcBuffer);
  2546. D3D11_INTERNAL_TrackBuffer(d3d11CommandBuffer, dstBuffer);
  2547. }
  2548. static void D3D11_GenerateMipmaps(
  2549. SDL_GPUCommandBuffer *commandBuffer,
  2550. SDL_GPUTexture *texture)
  2551. {
  2552. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  2553. D3D11TextureContainer *d3d11TextureContainer = (D3D11TextureContainer *)texture;
  2554. ID3D11DeviceContext1_GenerateMips(
  2555. d3d11CommandBuffer->context,
  2556. d3d11TextureContainer->activeTexture->shaderView);
  2557. D3D11_INTERNAL_TrackTexture(
  2558. d3d11CommandBuffer,
  2559. d3d11TextureContainer->activeTexture);
  2560. }
  2561. static void D3D11_EndCopyPass(
  2562. SDL_GPUCommandBuffer *commandBuffer)
  2563. {
  2564. // no-op
  2565. }
  2566. // Graphics State
  2567. static void D3D11_INTERNAL_AllocateCommandBuffers(
  2568. D3D11Renderer *renderer,
  2569. Uint32 allocateCount)
  2570. {
  2571. D3D11CommandBuffer *commandBuffer;
  2572. HRESULT res;
  2573. renderer->availableCommandBufferCapacity += allocateCount;
  2574. renderer->availableCommandBuffers = SDL_realloc(
  2575. renderer->availableCommandBuffers,
  2576. sizeof(D3D11CommandBuffer *) * renderer->availableCommandBufferCapacity);
  2577. for (Uint32 i = 0; i < allocateCount; i += 1) {
  2578. commandBuffer = SDL_calloc(1, sizeof(D3D11CommandBuffer));
  2579. commandBuffer->renderer = renderer;
  2580. // Deferred Device Context
  2581. res = ID3D11Device1_CreateDeferredContext1(
  2582. renderer->device,
  2583. 0,
  2584. &commandBuffer->context);
  2585. ERROR_CHECK("Could not create deferred context");
  2586. // Initialize debug annotation support, if available
  2587. ID3D11DeviceContext_QueryInterface(
  2588. commandBuffer->context,
  2589. &D3D_IID_ID3DUserDefinedAnnotation,
  2590. (void **)&commandBuffer->annotation);
  2591. // Window handling
  2592. commandBuffer->windowDataCapacity = 1;
  2593. commandBuffer->windowDataCount = 0;
  2594. commandBuffer->windowDatas = SDL_malloc(
  2595. commandBuffer->windowDataCapacity * sizeof(D3D11WindowData *));
  2596. // Reference Counting
  2597. commandBuffer->usedBufferCapacity = 4;
  2598. commandBuffer->usedBufferCount = 0;
  2599. commandBuffer->usedBuffers = SDL_malloc(
  2600. commandBuffer->usedBufferCapacity * sizeof(D3D11Buffer *));
  2601. commandBuffer->usedTransferBufferCapacity = 4;
  2602. commandBuffer->usedTransferBufferCount = 0;
  2603. commandBuffer->usedTransferBuffers = SDL_malloc(
  2604. commandBuffer->usedTransferBufferCapacity * sizeof(D3D11TransferBuffer *));
  2605. commandBuffer->usedTextureCapacity = 4;
  2606. commandBuffer->usedTextureCount = 0;
  2607. commandBuffer->usedTextures = SDL_malloc(
  2608. commandBuffer->usedTextureCapacity * sizeof(D3D11Texture *));
  2609. commandBuffer->usedUniformBufferCapacity = 4;
  2610. commandBuffer->usedUniformBufferCount = 0;
  2611. commandBuffer->usedUniformBuffers = SDL_malloc(
  2612. commandBuffer->usedUniformBufferCapacity * sizeof(D3D11UniformBuffer *));
  2613. renderer->availableCommandBuffers[renderer->availableCommandBufferCount] = commandBuffer;
  2614. renderer->availableCommandBufferCount += 1;
  2615. }
  2616. }
  2617. static D3D11CommandBuffer *D3D11_INTERNAL_GetInactiveCommandBufferFromPool(
  2618. D3D11Renderer *renderer)
  2619. {
  2620. D3D11CommandBuffer *commandBuffer;
  2621. if (renderer->availableCommandBufferCount == 0) {
  2622. D3D11_INTERNAL_AllocateCommandBuffers(
  2623. renderer,
  2624. renderer->availableCommandBufferCapacity);
  2625. }
  2626. commandBuffer = renderer->availableCommandBuffers[renderer->availableCommandBufferCount - 1];
  2627. renderer->availableCommandBufferCount -= 1;
  2628. return commandBuffer;
  2629. }
  2630. static bool D3D11_INTERNAL_CreateFence(
  2631. D3D11Renderer *renderer)
  2632. {
  2633. D3D11_QUERY_DESC queryDesc;
  2634. ID3D11Query *queryHandle;
  2635. D3D11Fence *fence;
  2636. HRESULT res;
  2637. queryDesc.Query = D3D11_QUERY_EVENT;
  2638. queryDesc.MiscFlags = 0;
  2639. res = ID3D11Device_CreateQuery(
  2640. renderer->device,
  2641. &queryDesc,
  2642. &queryHandle);
  2643. ERROR_CHECK_RETURN("Could not create query", 0);
  2644. fence = SDL_malloc(sizeof(D3D11Fence));
  2645. fence->handle = queryHandle;
  2646. SDL_AtomicSet(&fence->referenceCount, 0);
  2647. // Add it to the available pool
  2648. if (renderer->availableFenceCount >= renderer->availableFenceCapacity) {
  2649. renderer->availableFenceCapacity *= 2;
  2650. renderer->availableFences = SDL_realloc(
  2651. renderer->availableFences,
  2652. sizeof(D3D11Fence *) * renderer->availableFenceCapacity);
  2653. }
  2654. renderer->availableFences[renderer->availableFenceCount] = fence;
  2655. renderer->availableFenceCount += 1;
  2656. return true;
  2657. }
  2658. static bool D3D11_INTERNAL_AcquireFence(
  2659. D3D11CommandBuffer *commandBuffer)
  2660. {
  2661. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  2662. D3D11Renderer *renderer = (D3D11Renderer *)d3d11CommandBuffer->renderer;
  2663. D3D11Fence *fence;
  2664. // Acquire a fence from the pool
  2665. SDL_LockMutex(renderer->fenceLock);
  2666. if (renderer->availableFenceCount == 0) {
  2667. if (!D3D11_INTERNAL_CreateFence(renderer)) {
  2668. SDL_UnlockMutex(renderer->fenceLock);
  2669. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create fence!");
  2670. return false;
  2671. }
  2672. }
  2673. fence = renderer->availableFences[renderer->availableFenceCount - 1];
  2674. renderer->availableFenceCount -= 1;
  2675. SDL_UnlockMutex(renderer->fenceLock);
  2676. // Associate the fence with the command buffer
  2677. commandBuffer->fence = fence;
  2678. (void)SDL_AtomicIncRef(&commandBuffer->fence->referenceCount);
  2679. return true;
  2680. }
  2681. static SDL_GPUCommandBuffer *D3D11_AcquireCommandBuffer(
  2682. SDL_GPURenderer *driverData)
  2683. {
  2684. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  2685. D3D11CommandBuffer *commandBuffer;
  2686. Uint32 i;
  2687. SDL_LockMutex(renderer->acquireCommandBufferLock);
  2688. commandBuffer = D3D11_INTERNAL_GetInactiveCommandBufferFromPool(renderer);
  2689. commandBuffer->graphicsPipeline = NULL;
  2690. commandBuffer->stencilRef = 0;
  2691. commandBuffer->blendConstants.r = 1.0f;
  2692. commandBuffer->blendConstants.g = 1.0f;
  2693. commandBuffer->blendConstants.b = 1.0f;
  2694. commandBuffer->blendConstants.a = 1.0f;
  2695. commandBuffer->computePipeline = NULL;
  2696. for (i = 0; i < MAX_COLOR_TARGET_BINDINGS; i += 1) {
  2697. commandBuffer->colorTargetSubresources[i] = NULL;
  2698. commandBuffer->colorResolveSubresources[i] = NULL;
  2699. }
  2700. for (i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  2701. commandBuffer->vertexUniformBuffers[i] = NULL;
  2702. commandBuffer->fragmentUniformBuffers[i] = NULL;
  2703. commandBuffer->computeUniformBuffers[i] = NULL;
  2704. }
  2705. commandBuffer->needVertexSamplerBind = true;
  2706. commandBuffer->needVertexStorageTextureBind = true;
  2707. commandBuffer->needVertexStorageBufferBind = true;
  2708. commandBuffer->needVertexUniformBufferBind = true;
  2709. commandBuffer->needFragmentSamplerBind = true;
  2710. commandBuffer->needFragmentStorageTextureBind = true;
  2711. commandBuffer->needFragmentStorageBufferBind = true;
  2712. commandBuffer->needFragmentUniformBufferBind = true;
  2713. commandBuffer->needComputeUniformBufferBind = true;
  2714. commandBuffer->needBlendStateSet = true;
  2715. SDL_zeroa(commandBuffer->vertexSamplers);
  2716. SDL_zeroa(commandBuffer->vertexSamplerTextures);
  2717. SDL_zeroa(commandBuffer->vertexStorageTextures);
  2718. SDL_zeroa(commandBuffer->vertexStorageBuffers);
  2719. SDL_zeroa(commandBuffer->fragmentSamplers);
  2720. SDL_zeroa(commandBuffer->fragmentSamplerTextures);
  2721. SDL_zeroa(commandBuffer->fragmentStorageTextures);
  2722. SDL_zeroa(commandBuffer->fragmentStorageBuffers);
  2723. SDL_zeroa(commandBuffer->computeSamplers);
  2724. SDL_zeroa(commandBuffer->computeSamplerTextures);
  2725. SDL_zeroa(commandBuffer->computeReadOnlyStorageTextures);
  2726. SDL_zeroa(commandBuffer->computeReadOnlyStorageBuffers);
  2727. SDL_zeroa(commandBuffer->computeWriteOnlyStorageTextureSubresources);
  2728. SDL_zeroa(commandBuffer->computeWriteOnlyStorageBuffers);
  2729. D3D11_INTERNAL_AcquireFence(commandBuffer);
  2730. commandBuffer->autoReleaseFence = 1;
  2731. SDL_UnlockMutex(renderer->acquireCommandBufferLock);
  2732. return (SDL_GPUCommandBuffer *)commandBuffer;
  2733. }
  2734. static D3D11UniformBuffer *D3D11_INTERNAL_AcquireUniformBufferFromPool(
  2735. D3D11CommandBuffer *commandBuffer)
  2736. {
  2737. D3D11Renderer *renderer = commandBuffer->renderer;
  2738. D3D11UniformBuffer *uniformBuffer;
  2739. SDL_LockMutex(renderer->acquireUniformBufferLock);
  2740. if (renderer->uniformBufferPoolCount > 0) {
  2741. uniformBuffer = renderer->uniformBufferPool[renderer->uniformBufferPoolCount - 1];
  2742. renderer->uniformBufferPoolCount -= 1;
  2743. } else {
  2744. uniformBuffer = D3D11_INTERNAL_CreateUniformBuffer(
  2745. renderer,
  2746. UNIFORM_BUFFER_SIZE);
  2747. }
  2748. SDL_UnlockMutex(renderer->acquireUniformBufferLock);
  2749. D3D11_INTERNAL_TrackUniformBuffer(commandBuffer, uniformBuffer);
  2750. return uniformBuffer;
  2751. }
  2752. static void D3D11_INTERNAL_ReturnUniformBufferToPool(
  2753. D3D11Renderer *renderer,
  2754. D3D11UniformBuffer *uniformBuffer)
  2755. {
  2756. if (renderer->uniformBufferPoolCount >= renderer->uniformBufferPoolCapacity) {
  2757. renderer->uniformBufferPoolCapacity *= 2;
  2758. renderer->uniformBufferPool = SDL_realloc(
  2759. renderer->uniformBufferPool,
  2760. renderer->uniformBufferPoolCapacity * sizeof(D3D11UniformBuffer *));
  2761. }
  2762. renderer->uniformBufferPool[renderer->uniformBufferPoolCount] = uniformBuffer;
  2763. renderer->uniformBufferPoolCount += 1;
  2764. uniformBuffer->writeOffset = 0;
  2765. uniformBuffer->drawOffset = 0;
  2766. uniformBuffer->mappedData = NULL;
  2767. }
  2768. static void D3D11_INTERNAL_PushUniformData(
  2769. D3D11CommandBuffer *d3d11CommandBuffer,
  2770. SDL_GPUShaderStage shaderStage,
  2771. Uint32 slotIndex,
  2772. const void *data,
  2773. Uint32 length)
  2774. {
  2775. D3D11Renderer *renderer = d3d11CommandBuffer->renderer;
  2776. D3D11UniformBuffer *d3d11UniformBuffer;
  2777. D3D11_MAPPED_SUBRESOURCE subres;
  2778. HRESULT res;
  2779. if (shaderStage == SDL_GPU_SHADERSTAGE_VERTEX) {
  2780. if (d3d11CommandBuffer->vertexUniformBuffers[slotIndex] == NULL) {
  2781. d3d11CommandBuffer->vertexUniformBuffers[slotIndex] = D3D11_INTERNAL_AcquireUniformBufferFromPool(
  2782. d3d11CommandBuffer);
  2783. }
  2784. d3d11UniformBuffer = d3d11CommandBuffer->vertexUniformBuffers[slotIndex];
  2785. } else if (shaderStage == SDL_GPU_SHADERSTAGE_FRAGMENT) {
  2786. if (d3d11CommandBuffer->fragmentUniformBuffers[slotIndex] == NULL) {
  2787. d3d11CommandBuffer->fragmentUniformBuffers[slotIndex] = D3D11_INTERNAL_AcquireUniformBufferFromPool(
  2788. d3d11CommandBuffer);
  2789. }
  2790. d3d11UniformBuffer = d3d11CommandBuffer->fragmentUniformBuffers[slotIndex];
  2791. } else if (shaderStage == SDL_GPU_SHADERSTAGE_COMPUTE) {
  2792. if (d3d11CommandBuffer->computeUniformBuffers[slotIndex] == NULL) {
  2793. d3d11CommandBuffer->computeUniformBuffers[slotIndex] = D3D11_INTERNAL_AcquireUniformBufferFromPool(
  2794. d3d11CommandBuffer);
  2795. }
  2796. d3d11UniformBuffer = d3d11CommandBuffer->computeUniformBuffers[slotIndex];
  2797. } else {
  2798. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized shader stage!");
  2799. return;
  2800. }
  2801. d3d11UniformBuffer->currentBlockSize =
  2802. D3D11_INTERNAL_NextHighestAlignment(
  2803. length,
  2804. 256);
  2805. // If there is no more room, acquire a new uniform buffer
  2806. if (d3d11UniformBuffer->writeOffset + d3d11UniformBuffer->currentBlockSize >= UNIFORM_BUFFER_SIZE) {
  2807. ID3D11DeviceContext_Unmap(
  2808. d3d11CommandBuffer->context,
  2809. (ID3D11Resource *)d3d11UniformBuffer->buffer,
  2810. 0);
  2811. d3d11UniformBuffer->mappedData = NULL;
  2812. d3d11UniformBuffer = D3D11_INTERNAL_AcquireUniformBufferFromPool(d3d11CommandBuffer);
  2813. d3d11UniformBuffer->drawOffset = 0;
  2814. d3d11UniformBuffer->writeOffset = 0;
  2815. if (shaderStage == SDL_GPU_SHADERSTAGE_VERTEX) {
  2816. d3d11CommandBuffer->vertexUniformBuffers[slotIndex] = d3d11UniformBuffer;
  2817. } else if (shaderStage == SDL_GPU_SHADERSTAGE_FRAGMENT) {
  2818. d3d11CommandBuffer->fragmentUniformBuffers[slotIndex] = d3d11UniformBuffer;
  2819. } else if (shaderStage == SDL_GPU_SHADERSTAGE_COMPUTE) {
  2820. d3d11CommandBuffer->computeUniformBuffers[slotIndex] = d3d11UniformBuffer;
  2821. } else {
  2822. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized shader stage!");
  2823. }
  2824. }
  2825. // Map the uniform data on first push
  2826. if (d3d11UniformBuffer->writeOffset == 0) {
  2827. res = ID3D11DeviceContext_Map(
  2828. d3d11CommandBuffer->context,
  2829. (ID3D11Resource *)d3d11UniformBuffer->buffer,
  2830. 0,
  2831. D3D11_MAP_WRITE_DISCARD,
  2832. 0,
  2833. &subres);
  2834. ERROR_CHECK_RETURN("Failed to map uniform buffer", )
  2835. d3d11UniformBuffer->mappedData = subres.pData;
  2836. }
  2837. d3d11UniformBuffer->drawOffset = d3d11UniformBuffer->writeOffset;
  2838. SDL_memcpy(
  2839. (Uint8 *)d3d11UniformBuffer->mappedData + d3d11UniformBuffer->writeOffset,
  2840. data,
  2841. length);
  2842. d3d11UniformBuffer->writeOffset += d3d11UniformBuffer->currentBlockSize;
  2843. if (shaderStage == SDL_GPU_SHADERSTAGE_VERTEX) {
  2844. d3d11CommandBuffer->needVertexUniformBufferBind = true;
  2845. } else if (shaderStage == SDL_GPU_SHADERSTAGE_FRAGMENT) {
  2846. d3d11CommandBuffer->needFragmentUniformBufferBind = true;
  2847. } else if (shaderStage == SDL_GPU_SHADERSTAGE_COMPUTE) {
  2848. d3d11CommandBuffer->needComputeUniformBufferBind = true;
  2849. } else {
  2850. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized shader stage!");
  2851. }
  2852. }
  2853. static void D3D11_SetViewport(
  2854. SDL_GPUCommandBuffer *commandBuffer,
  2855. const SDL_GPUViewport *viewport)
  2856. {
  2857. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  2858. D3D11_VIEWPORT vp = {
  2859. viewport->x,
  2860. viewport->y,
  2861. viewport->w,
  2862. viewport->h,
  2863. viewport->min_depth,
  2864. viewport->max_depth
  2865. };
  2866. ID3D11DeviceContext_RSSetViewports(
  2867. d3d11CommandBuffer->context,
  2868. 1,
  2869. &vp);
  2870. }
  2871. static void D3D11_SetScissor(
  2872. SDL_GPUCommandBuffer *commandBuffer,
  2873. const SDL_Rect *scissor)
  2874. {
  2875. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  2876. D3D11_RECT rect = {
  2877. scissor->x,
  2878. scissor->y,
  2879. scissor->x + scissor->w,
  2880. scissor->y + scissor->h
  2881. };
  2882. ID3D11DeviceContext_RSSetScissorRects(
  2883. d3d11CommandBuffer->context,
  2884. 1,
  2885. &rect);
  2886. }
  2887. static void D3D11_SetBlendConstants(
  2888. SDL_GPUCommandBuffer *commandBuffer,
  2889. SDL_FColor blendConstants)
  2890. {
  2891. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  2892. d3d11CommandBuffer->blendConstants = blendConstants;
  2893. d3d11CommandBuffer->needBlendStateSet = true;
  2894. }
  2895. static void D3D11_SetStencilReference(
  2896. SDL_GPUCommandBuffer *commandBuffer,
  2897. Uint8 reference)
  2898. {
  2899. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  2900. d3d11CommandBuffer->stencilRef = reference;
  2901. if (d3d11CommandBuffer->graphicsPipeline != NULL) {
  2902. ID3D11DeviceContext_OMSetDepthStencilState(
  2903. d3d11CommandBuffer->context,
  2904. d3d11CommandBuffer->graphicsPipeline->depthStencilState,
  2905. reference);
  2906. }
  2907. }
  2908. static void D3D11_BeginRenderPass(
  2909. SDL_GPUCommandBuffer *commandBuffer,
  2910. const SDL_GPUColorTargetInfo *colorTargetInfos,
  2911. Uint32 numColorTargets,
  2912. const SDL_GPUDepthStencilTargetInfo *depthStencilTargetInfo)
  2913. {
  2914. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  2915. D3D11Renderer *renderer = (D3D11Renderer *)d3d11CommandBuffer->renderer;
  2916. ID3D11RenderTargetView *rtvs[MAX_COLOR_TARGET_BINDINGS];
  2917. ID3D11DepthStencilView *dsv = NULL;
  2918. Uint32 vpWidth = SDL_MAX_UINT32;
  2919. Uint32 vpHeight = SDL_MAX_UINT32;
  2920. SDL_GPUViewport viewport;
  2921. SDL_Rect scissorRect;
  2922. // Clear the bound targets for the current command buffer
  2923. for (Uint32 i = 0; i < MAX_COLOR_TARGET_BINDINGS; i += 1) {
  2924. d3d11CommandBuffer->colorTargetSubresources[i] = NULL;
  2925. d3d11CommandBuffer->colorResolveSubresources[i] = NULL;
  2926. }
  2927. // Set up the new color target bindings
  2928. for (Uint32 i = 0; i < numColorTargets; i += 1) {
  2929. D3D11TextureContainer *container = (D3D11TextureContainer *)colorTargetInfos[i].texture;
  2930. D3D11TextureSubresource *subresource = D3D11_INTERNAL_PrepareTextureSubresourceForWrite(
  2931. renderer,
  2932. container,
  2933. container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? 0 : colorTargetInfos[i].layer_or_depth_plane,
  2934. colorTargetInfos[i].mip_level,
  2935. colorTargetInfos[i].cycle);
  2936. Uint32 rtvIndex = container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? colorTargetInfos[i].layer_or_depth_plane : 0;
  2937. rtvs[i] = subresource->colorTargetViews[rtvIndex];
  2938. d3d11CommandBuffer->colorTargetSubresources[i] = subresource;
  2939. if (colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE || colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE_AND_STORE) {
  2940. D3D11TextureContainer *resolveContainer = (D3D11TextureContainer *)colorTargetInfos[i].resolve_texture;
  2941. D3D11TextureSubresource *resolveSubresource = D3D11_INTERNAL_PrepareTextureSubresourceForWrite(
  2942. renderer,
  2943. resolveContainer,
  2944. colorTargetInfos[i].resolve_layer,
  2945. colorTargetInfos[i].resolve_mip_level,
  2946. colorTargetInfos[i].cycle_resolve_texture);
  2947. d3d11CommandBuffer->colorResolveSubresources[i] = resolveSubresource;
  2948. }
  2949. if (colorTargetInfos[i].load_op == SDL_GPU_LOADOP_CLEAR) {
  2950. float clearColor[] = {
  2951. colorTargetInfos[i].clear_color.r,
  2952. colorTargetInfos[i].clear_color.g,
  2953. colorTargetInfos[i].clear_color.b,
  2954. colorTargetInfos[i].clear_color.a
  2955. };
  2956. ID3D11DeviceContext_ClearRenderTargetView(
  2957. d3d11CommandBuffer->context,
  2958. rtvs[i],
  2959. clearColor);
  2960. }
  2961. D3D11_INTERNAL_TrackTexture(
  2962. d3d11CommandBuffer,
  2963. subresource->parent);
  2964. }
  2965. // Get the DSV for the depth stencil target, if applicable
  2966. if (depthStencilTargetInfo != NULL) {
  2967. D3D11TextureContainer *container = (D3D11TextureContainer *)depthStencilTargetInfo->texture;
  2968. D3D11TextureSubresource *subresource = D3D11_INTERNAL_PrepareTextureSubresourceForWrite(
  2969. renderer,
  2970. container,
  2971. 0,
  2972. 0,
  2973. depthStencilTargetInfo->cycle);
  2974. dsv = subresource->depthStencilTargetView;
  2975. D3D11_INTERNAL_TrackTexture(
  2976. d3d11CommandBuffer,
  2977. subresource->parent);
  2978. }
  2979. // Actually set the RTs
  2980. ID3D11DeviceContext_OMSetRenderTargets(
  2981. d3d11CommandBuffer->context,
  2982. numColorTargets,
  2983. numColorTargets > 0 ? rtvs : NULL,
  2984. dsv);
  2985. if (depthStencilTargetInfo != NULL) {
  2986. D3D11_CLEAR_FLAG dsClearFlags = 0;
  2987. if (depthStencilTargetInfo->load_op == SDL_GPU_LOADOP_CLEAR) {
  2988. dsClearFlags |= D3D11_CLEAR_DEPTH;
  2989. }
  2990. if (depthStencilTargetInfo->stencil_load_op == SDL_GPU_LOADOP_CLEAR) {
  2991. dsClearFlags |= D3D11_CLEAR_STENCIL;
  2992. }
  2993. if (dsClearFlags != 0) {
  2994. ID3D11DeviceContext_ClearDepthStencilView(
  2995. d3d11CommandBuffer->context,
  2996. dsv,
  2997. dsClearFlags,
  2998. depthStencilTargetInfo->clear_depth,
  2999. depthStencilTargetInfo->clear_stencil);
  3000. }
  3001. }
  3002. // The viewport cannot be larger than the smallest target.
  3003. for (Uint32 i = 0; i < numColorTargets; i += 1) {
  3004. D3D11TextureContainer *container = (D3D11TextureContainer *)colorTargetInfos[i].texture;
  3005. Uint32 w = container->header.info.width >> colorTargetInfos[i].mip_level;
  3006. Uint32 h = container->header.info.height >> colorTargetInfos[i].mip_level;
  3007. if (w < vpWidth) {
  3008. vpWidth = w;
  3009. }
  3010. if (h < vpHeight) {
  3011. vpHeight = h;
  3012. }
  3013. }
  3014. if (depthStencilTargetInfo != NULL) {
  3015. D3D11TextureContainer *container = (D3D11TextureContainer *)depthStencilTargetInfo->texture;
  3016. Uint32 w = container->header.info.width;
  3017. Uint32 h = container->header.info.height;
  3018. if (w < vpWidth) {
  3019. vpWidth = w;
  3020. }
  3021. if (h < vpHeight) {
  3022. vpHeight = h;
  3023. }
  3024. }
  3025. // Set sensible default states
  3026. viewport.x = 0;
  3027. viewport.y = 0;
  3028. viewport.w = (float)vpWidth;
  3029. viewport.h = (float)vpHeight;
  3030. viewport.min_depth = 0;
  3031. viewport.max_depth = 1;
  3032. D3D11_SetViewport(
  3033. commandBuffer,
  3034. &viewport);
  3035. scissorRect.x = 0;
  3036. scissorRect.y = 0;
  3037. scissorRect.w = (int)vpWidth;
  3038. scissorRect.h = (int)vpHeight;
  3039. D3D11_SetScissor(
  3040. commandBuffer,
  3041. &scissorRect);
  3042. D3D11_SetStencilReference(
  3043. commandBuffer,
  3044. 0);
  3045. SDL_FColor blendConstants;
  3046. blendConstants.r = 1.0f;
  3047. blendConstants.g = 1.0f;
  3048. blendConstants.b = 1.0f;
  3049. blendConstants.a = 1.0f;
  3050. D3D11_SetBlendConstants(
  3051. commandBuffer,
  3052. blendConstants);
  3053. }
  3054. static void D3D11_BindGraphicsPipeline(
  3055. SDL_GPUCommandBuffer *commandBuffer,
  3056. SDL_GPUGraphicsPipeline *graphicsPipeline)
  3057. {
  3058. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3059. D3D11GraphicsPipeline *pipeline = (D3D11GraphicsPipeline *)graphicsPipeline;
  3060. d3d11CommandBuffer->graphicsPipeline = pipeline;
  3061. ID3D11DeviceContext_OMSetDepthStencilState(
  3062. d3d11CommandBuffer->context,
  3063. pipeline->depthStencilState,
  3064. d3d11CommandBuffer->stencilRef);
  3065. ID3D11DeviceContext_IASetPrimitiveTopology(
  3066. d3d11CommandBuffer->context,
  3067. SDLToD3D11_PrimitiveType[pipeline->primitiveType]);
  3068. ID3D11DeviceContext_IASetInputLayout(
  3069. d3d11CommandBuffer->context,
  3070. pipeline->inputLayout);
  3071. ID3D11DeviceContext_RSSetState(
  3072. d3d11CommandBuffer->context,
  3073. pipeline->rasterizerState);
  3074. ID3D11DeviceContext_VSSetShader(
  3075. d3d11CommandBuffer->context,
  3076. pipeline->vertexShader,
  3077. NULL,
  3078. 0);
  3079. ID3D11DeviceContext_PSSetShader(
  3080. d3d11CommandBuffer->context,
  3081. pipeline->fragmentShader,
  3082. NULL,
  3083. 0);
  3084. // Acquire uniform buffers if necessary
  3085. for (Uint32 i = 0; i < pipeline->vertexUniformBufferCount; i += 1) {
  3086. if (d3d11CommandBuffer->vertexUniformBuffers[i] == NULL) {
  3087. d3d11CommandBuffer->vertexUniformBuffers[i] = D3D11_INTERNAL_AcquireUniformBufferFromPool(
  3088. d3d11CommandBuffer);
  3089. }
  3090. }
  3091. for (Uint32 i = 0; i < pipeline->fragmentUniformBufferCount; i += 1) {
  3092. if (d3d11CommandBuffer->fragmentUniformBuffers[i] == NULL) {
  3093. d3d11CommandBuffer->fragmentUniformBuffers[i] = D3D11_INTERNAL_AcquireUniformBufferFromPool(
  3094. d3d11CommandBuffer);
  3095. }
  3096. }
  3097. // Mark that bindings are needed
  3098. d3d11CommandBuffer->needVertexSamplerBind = true;
  3099. d3d11CommandBuffer->needVertexStorageTextureBind = true;
  3100. d3d11CommandBuffer->needVertexStorageBufferBind = true;
  3101. d3d11CommandBuffer->needVertexUniformBufferBind = true;
  3102. d3d11CommandBuffer->needFragmentSamplerBind = true;
  3103. d3d11CommandBuffer->needFragmentStorageTextureBind = true;
  3104. d3d11CommandBuffer->needFragmentStorageBufferBind = true;
  3105. d3d11CommandBuffer->needFragmentUniformBufferBind = true;
  3106. d3d11CommandBuffer->needBlendStateSet = true;
  3107. }
  3108. static void D3D11_BindVertexBuffers(
  3109. SDL_GPUCommandBuffer *commandBuffer,
  3110. Uint32 firstSlot,
  3111. const SDL_GPUBufferBinding *bindings,
  3112. Uint32 numBindings)
  3113. {
  3114. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3115. for (Uint32 i = 0; i < numBindings; i += 1) {
  3116. D3D11Buffer *currentBuffer = ((D3D11BufferContainer *)bindings[i].buffer)->activeBuffer;
  3117. d3d11CommandBuffer->vertexBuffers[firstSlot + i] = currentBuffer->handle;
  3118. d3d11CommandBuffer->vertexBufferOffsets[firstSlot + i] = bindings[i].offset;
  3119. D3D11_INTERNAL_TrackBuffer(d3d11CommandBuffer, currentBuffer);
  3120. }
  3121. d3d11CommandBuffer->vertexBufferCount =
  3122. SDL_max(d3d11CommandBuffer->vertexBufferCount, firstSlot + numBindings);
  3123. d3d11CommandBuffer->needVertexBufferBind = true;
  3124. }
  3125. static void D3D11_BindIndexBuffer(
  3126. SDL_GPUCommandBuffer *commandBuffer,
  3127. const SDL_GPUBufferBinding *binding,
  3128. SDL_GPUIndexElementSize indexElementSize)
  3129. {
  3130. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3131. D3D11Buffer *d3d11Buffer = ((D3D11BufferContainer *)binding->buffer)->activeBuffer;
  3132. D3D11_INTERNAL_TrackBuffer(d3d11CommandBuffer, d3d11Buffer);
  3133. ID3D11DeviceContext_IASetIndexBuffer(
  3134. d3d11CommandBuffer->context,
  3135. d3d11Buffer->handle,
  3136. SDLToD3D11_IndexType[indexElementSize],
  3137. (UINT)binding->offset);
  3138. }
  3139. static void D3D11_BindVertexSamplers(
  3140. SDL_GPUCommandBuffer *commandBuffer,
  3141. Uint32 firstSlot,
  3142. const SDL_GPUTextureSamplerBinding *textureSamplerBindings,
  3143. Uint32 numBindings)
  3144. {
  3145. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3146. for (Uint32 i = 0; i < numBindings; i += 1) {
  3147. D3D11TextureContainer *textureContainer = (D3D11TextureContainer *)textureSamplerBindings[i].texture;
  3148. D3D11_INTERNAL_TrackTexture(
  3149. d3d11CommandBuffer,
  3150. textureContainer->activeTexture);
  3151. d3d11CommandBuffer->vertexSamplers[firstSlot + i] =
  3152. (D3D11Sampler *)textureSamplerBindings[i].sampler;
  3153. d3d11CommandBuffer->vertexSamplerTextures[firstSlot + i] =
  3154. textureContainer->activeTexture;
  3155. }
  3156. d3d11CommandBuffer->needVertexSamplerBind = true;
  3157. }
  3158. static void D3D11_BindVertexStorageTextures(
  3159. SDL_GPUCommandBuffer *commandBuffer,
  3160. Uint32 firstSlot,
  3161. SDL_GPUTexture *const *storageTextures,
  3162. Uint32 numBindings)
  3163. {
  3164. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3165. for (Uint32 i = 0; i < numBindings; i += 1) {
  3166. D3D11TextureContainer *textureContainer = (D3D11TextureContainer *)storageTextures[i];
  3167. D3D11_INTERNAL_TrackTexture(
  3168. d3d11CommandBuffer,
  3169. textureContainer->activeTexture);
  3170. d3d11CommandBuffer->vertexStorageTextures[firstSlot + i] =
  3171. textureContainer->activeTexture;
  3172. }
  3173. d3d11CommandBuffer->needVertexStorageTextureBind = true;
  3174. }
  3175. static void D3D11_BindVertexStorageBuffers(
  3176. SDL_GPUCommandBuffer *commandBuffer,
  3177. Uint32 firstSlot,
  3178. SDL_GPUBuffer *const *storageBuffers,
  3179. Uint32 numBindings)
  3180. {
  3181. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3182. D3D11BufferContainer *bufferContainer;
  3183. Uint32 i;
  3184. for (i = 0; i < numBindings; i += 1) {
  3185. bufferContainer = (D3D11BufferContainer *)storageBuffers[i];
  3186. D3D11_INTERNAL_TrackBuffer(
  3187. d3d11CommandBuffer,
  3188. bufferContainer->activeBuffer);
  3189. d3d11CommandBuffer->vertexStorageBuffers[firstSlot + i] =
  3190. bufferContainer->activeBuffer;
  3191. }
  3192. d3d11CommandBuffer->needVertexStorageBufferBind = true;
  3193. }
  3194. static void D3D11_BindFragmentSamplers(
  3195. SDL_GPUCommandBuffer *commandBuffer,
  3196. Uint32 firstSlot,
  3197. const SDL_GPUTextureSamplerBinding *textureSamplerBindings,
  3198. Uint32 numBindings)
  3199. {
  3200. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3201. for (Uint32 i = 0; i < numBindings; i += 1) {
  3202. D3D11TextureContainer *textureContainer = (D3D11TextureContainer *)textureSamplerBindings[i].texture;
  3203. D3D11_INTERNAL_TrackTexture(
  3204. d3d11CommandBuffer,
  3205. textureContainer->activeTexture);
  3206. d3d11CommandBuffer->fragmentSamplers[firstSlot + i] =
  3207. (D3D11Sampler *)textureSamplerBindings[i].sampler;
  3208. d3d11CommandBuffer->fragmentSamplerTextures[firstSlot + i] =
  3209. (D3D11Texture *)textureContainer->activeTexture;
  3210. }
  3211. d3d11CommandBuffer->needFragmentSamplerBind = true;
  3212. }
  3213. static void D3D11_BindFragmentStorageTextures(
  3214. SDL_GPUCommandBuffer *commandBuffer,
  3215. Uint32 firstSlot,
  3216. SDL_GPUTexture *const *storageTextures,
  3217. Uint32 numBindings)
  3218. {
  3219. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3220. for (Uint32 i = 0; i < numBindings; i += 1) {
  3221. D3D11TextureContainer *textureContainer = (D3D11TextureContainer *)storageTextures[i];
  3222. D3D11_INTERNAL_TrackTexture(
  3223. d3d11CommandBuffer,
  3224. textureContainer->activeTexture);
  3225. d3d11CommandBuffer->fragmentStorageTextures[firstSlot + i] =
  3226. textureContainer->activeTexture;
  3227. }
  3228. d3d11CommandBuffer->needFragmentStorageTextureBind = true;
  3229. }
  3230. static void D3D11_BindFragmentStorageBuffers(
  3231. SDL_GPUCommandBuffer *commandBuffer,
  3232. Uint32 firstSlot,
  3233. SDL_GPUBuffer *const *storageBuffers,
  3234. Uint32 numBindings)
  3235. {
  3236. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3237. D3D11BufferContainer *bufferContainer;
  3238. Uint32 i;
  3239. for (i = 0; i < numBindings; i += 1) {
  3240. bufferContainer = (D3D11BufferContainer *)storageBuffers[i];
  3241. D3D11_INTERNAL_TrackBuffer(
  3242. d3d11CommandBuffer,
  3243. bufferContainer->activeBuffer);
  3244. d3d11CommandBuffer->fragmentStorageBuffers[firstSlot + i] =
  3245. bufferContainer->activeBuffer;
  3246. }
  3247. d3d11CommandBuffer->needFragmentStorageBufferBind = true;
  3248. }
  3249. static void D3D11_INTERNAL_BindGraphicsResources(
  3250. D3D11CommandBuffer *commandBuffer)
  3251. {
  3252. D3D11GraphicsPipeline *graphicsPipeline = commandBuffer->graphicsPipeline;
  3253. ID3D11Buffer *nullBuf = NULL;
  3254. Uint32 offsetInConstants, blockSizeInConstants;
  3255. if (commandBuffer->needVertexBufferBind) {
  3256. ID3D11DeviceContext_IASetVertexBuffers(
  3257. commandBuffer->context,
  3258. 0,
  3259. commandBuffer->vertexBufferCount,
  3260. commandBuffer->vertexBuffers,
  3261. graphicsPipeline->vertexStrides,
  3262. commandBuffer->vertexBufferOffsets);
  3263. }
  3264. if (commandBuffer->needVertexSamplerBind) {
  3265. if (graphicsPipeline->vertexSamplerCount > 0) {
  3266. ID3D11SamplerState *samplerStates[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  3267. ID3D11ShaderResourceView *srvs[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  3268. for (Uint32 i = 0; i < graphicsPipeline->vertexSamplerCount; i += 1) {
  3269. samplerStates[i] = commandBuffer->vertexSamplers[i]->handle;
  3270. srvs[i] = commandBuffer->vertexSamplerTextures[i]->shaderView;
  3271. }
  3272. ID3D11DeviceContext_VSSetSamplers(
  3273. commandBuffer->context,
  3274. 0,
  3275. graphicsPipeline->vertexSamplerCount,
  3276. samplerStates);
  3277. ID3D11DeviceContext_VSSetShaderResources(
  3278. commandBuffer->context,
  3279. 0,
  3280. graphicsPipeline->vertexSamplerCount,
  3281. srvs);
  3282. }
  3283. commandBuffer->needVertexSamplerBind = false;
  3284. }
  3285. if (commandBuffer->needVertexStorageTextureBind) {
  3286. if (graphicsPipeline->vertexStorageTextureCount > 0) {
  3287. ID3D11ShaderResourceView *srvs[MAX_STORAGE_TEXTURES_PER_STAGE];
  3288. for (Uint32 i = 0; i < graphicsPipeline->vertexStorageTextureCount; i += 1) {
  3289. srvs[i] = commandBuffer->vertexStorageTextures[i]->shaderView;
  3290. }
  3291. ID3D11DeviceContext_VSSetShaderResources(
  3292. commandBuffer->context,
  3293. graphicsPipeline->vertexSamplerCount,
  3294. graphicsPipeline->vertexStorageTextureCount,
  3295. srvs);
  3296. }
  3297. commandBuffer->needVertexStorageTextureBind = false;
  3298. }
  3299. if (commandBuffer->needVertexStorageBufferBind) {
  3300. if (graphicsPipeline->vertexStorageBufferCount > 0) {
  3301. ID3D11ShaderResourceView *srvs[MAX_STORAGE_BUFFERS_PER_STAGE];
  3302. for (Uint32 i = 0; i < graphicsPipeline->vertexStorageBufferCount; i += 1) {
  3303. srvs[i] = commandBuffer->vertexStorageBuffers[i]->srv;
  3304. }
  3305. ID3D11DeviceContext_VSSetShaderResources(
  3306. commandBuffer->context,
  3307. graphicsPipeline->vertexSamplerCount + graphicsPipeline->vertexStorageTextureCount,
  3308. graphicsPipeline->vertexStorageBufferCount,
  3309. srvs);
  3310. }
  3311. commandBuffer->needVertexStorageBufferBind = false;
  3312. }
  3313. if (commandBuffer->needVertexUniformBufferBind) {
  3314. for (Uint32 i = 0; i < graphicsPipeline->vertexUniformBufferCount; i += 1) {
  3315. /* stupid workaround for god awful D3D11 drivers
  3316. * see: https://learn.microsoft.com/en-us/windows/win32/api/d3d11_1/nf-d3d11_1-id3d11devicecontext1-vssetconstantbuffers1#calling-vssetconstantbuffers1-with-command-list-emulation
  3317. */
  3318. ID3D11DeviceContext1_VSSetConstantBuffers(
  3319. commandBuffer->context,
  3320. i,
  3321. 1,
  3322. &nullBuf);
  3323. offsetInConstants = commandBuffer->vertexUniformBuffers[i]->drawOffset / 16;
  3324. blockSizeInConstants = commandBuffer->vertexUniformBuffers[i]->currentBlockSize / 16;
  3325. ID3D11DeviceContext1_VSSetConstantBuffers1(
  3326. commandBuffer->context,
  3327. i,
  3328. 1,
  3329. &commandBuffer->vertexUniformBuffers[i]->buffer,
  3330. &offsetInConstants,
  3331. &blockSizeInConstants);
  3332. }
  3333. commandBuffer->needVertexUniformBufferBind = false;
  3334. }
  3335. if (commandBuffer->needFragmentSamplerBind) {
  3336. if (graphicsPipeline->fragmentSamplerCount > 0) {
  3337. ID3D11SamplerState *samplerStates[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  3338. ID3D11ShaderResourceView *srvs[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  3339. for (Uint32 i = 0; i < graphicsPipeline->fragmentSamplerCount; i += 1) {
  3340. samplerStates[i] = commandBuffer->fragmentSamplers[i]->handle;
  3341. srvs[i] = commandBuffer->fragmentSamplerTextures[i]->shaderView;
  3342. }
  3343. ID3D11DeviceContext_PSSetSamplers(
  3344. commandBuffer->context,
  3345. 0,
  3346. graphicsPipeline->fragmentSamplerCount,
  3347. samplerStates);
  3348. ID3D11DeviceContext_PSSetShaderResources(
  3349. commandBuffer->context,
  3350. 0,
  3351. graphicsPipeline->fragmentSamplerCount,
  3352. srvs);
  3353. }
  3354. commandBuffer->needFragmentSamplerBind = false;
  3355. }
  3356. if (commandBuffer->needFragmentStorageTextureBind) {
  3357. if (graphicsPipeline->fragmentStorageTextureCount > 0) {
  3358. ID3D11ShaderResourceView *srvs[MAX_STORAGE_TEXTURES_PER_STAGE];
  3359. for (Uint32 i = 0; i < graphicsPipeline->fragmentStorageTextureCount; i += 1) {
  3360. srvs[i] = commandBuffer->fragmentStorageTextures[i]->shaderView;
  3361. }
  3362. ID3D11DeviceContext_PSSetShaderResources(
  3363. commandBuffer->context,
  3364. graphicsPipeline->fragmentSamplerCount,
  3365. graphicsPipeline->fragmentStorageTextureCount,
  3366. srvs);
  3367. }
  3368. commandBuffer->needFragmentStorageTextureBind = false;
  3369. }
  3370. if (commandBuffer->needFragmentStorageBufferBind) {
  3371. if (graphicsPipeline->fragmentStorageBufferCount > 0) {
  3372. ID3D11ShaderResourceView *srvs[MAX_STORAGE_BUFFERS_PER_STAGE];
  3373. for (Uint32 i = 0; i < graphicsPipeline->fragmentStorageBufferCount; i += 1) {
  3374. srvs[i] = commandBuffer->fragmentStorageBuffers[i]->srv;
  3375. }
  3376. ID3D11DeviceContext_PSSetShaderResources(
  3377. commandBuffer->context,
  3378. graphicsPipeline->fragmentSamplerCount + graphicsPipeline->fragmentStorageTextureCount,
  3379. graphicsPipeline->fragmentStorageBufferCount,
  3380. srvs);
  3381. }
  3382. commandBuffer->needFragmentStorageBufferBind = false;
  3383. }
  3384. if (commandBuffer->needFragmentUniformBufferBind) {
  3385. for (Uint32 i = 0; i < graphicsPipeline->fragmentUniformBufferCount; i += 1) {
  3386. /* stupid workaround for god awful D3D11 drivers
  3387. * see: https://learn.microsoft.com/en-us/windows/win32/api/d3d11_1/nf-d3d11_1-id3d11devicecontext1-pssetconstantbuffers1#calling-pssetconstantbuffers1-with-command-list-emulation
  3388. */
  3389. ID3D11DeviceContext1_PSSetConstantBuffers(
  3390. commandBuffer->context,
  3391. i,
  3392. 1,
  3393. &nullBuf);
  3394. offsetInConstants = commandBuffer->fragmentUniformBuffers[i]->drawOffset / 16;
  3395. blockSizeInConstants = commandBuffer->fragmentUniformBuffers[i]->currentBlockSize / 16;
  3396. ID3D11DeviceContext1_PSSetConstantBuffers1(
  3397. commandBuffer->context,
  3398. i,
  3399. 1,
  3400. &commandBuffer->fragmentUniformBuffers[i]->buffer,
  3401. &offsetInConstants,
  3402. &blockSizeInConstants);
  3403. }
  3404. commandBuffer->needFragmentUniformBufferBind = false;
  3405. }
  3406. if (commandBuffer->needBlendStateSet) {
  3407. FLOAT blendFactor[4] = {
  3408. commandBuffer->blendConstants.r,
  3409. commandBuffer->blendConstants.g,
  3410. commandBuffer->blendConstants.b,
  3411. commandBuffer->blendConstants.a
  3412. };
  3413. ID3D11DeviceContext_OMSetBlendState(
  3414. commandBuffer->context,
  3415. graphicsPipeline->colorTargetBlendState,
  3416. blendFactor,
  3417. graphicsPipeline->sampleMask);
  3418. commandBuffer->needBlendStateSet = false;
  3419. }
  3420. }
  3421. static void D3D11_DrawIndexedPrimitives(
  3422. SDL_GPUCommandBuffer *commandBuffer,
  3423. Uint32 numIndices,
  3424. Uint32 numInstances,
  3425. Uint32 firstIndex,
  3426. Sint32 vertexOffset,
  3427. Uint32 firstInstance)
  3428. {
  3429. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3430. D3D11_INTERNAL_BindGraphicsResources(d3d11CommandBuffer);
  3431. ID3D11DeviceContext_DrawIndexedInstanced(
  3432. d3d11CommandBuffer->context,
  3433. numIndices,
  3434. numInstances,
  3435. firstIndex,
  3436. vertexOffset,
  3437. firstInstance);
  3438. }
  3439. static void D3D11_DrawPrimitives(
  3440. SDL_GPUCommandBuffer *commandBuffer,
  3441. Uint32 numVertices,
  3442. Uint32 numInstances,
  3443. Uint32 firstVertex,
  3444. Uint32 firstInstance)
  3445. {
  3446. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3447. D3D11_INTERNAL_BindGraphicsResources(d3d11CommandBuffer);
  3448. ID3D11DeviceContext_DrawInstanced(
  3449. d3d11CommandBuffer->context,
  3450. numVertices,
  3451. numInstances,
  3452. firstVertex,
  3453. firstInstance);
  3454. }
  3455. static void D3D11_DrawPrimitivesIndirect(
  3456. SDL_GPUCommandBuffer *commandBuffer,
  3457. SDL_GPUBuffer *buffer,
  3458. Uint32 offset,
  3459. Uint32 drawCount)
  3460. {
  3461. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3462. D3D11_INTERNAL_BindGraphicsResources(d3d11CommandBuffer);
  3463. D3D11Buffer *d3d11Buffer = ((D3D11BufferContainer *)buffer)->activeBuffer;
  3464. /* D3D11: "We have multi-draw at home!"
  3465. * Multi-draw at home:
  3466. */
  3467. for (Uint32 i = 0; i < drawCount; i += 1) {
  3468. ID3D11DeviceContext_DrawInstancedIndirect(
  3469. d3d11CommandBuffer->context,
  3470. d3d11Buffer->handle,
  3471. offset + (sizeof(SDL_GPUIndirectDrawCommand) * i));
  3472. }
  3473. D3D11_INTERNAL_TrackBuffer(d3d11CommandBuffer, d3d11Buffer);
  3474. }
  3475. static void D3D11_DrawIndexedPrimitivesIndirect(
  3476. SDL_GPUCommandBuffer *commandBuffer,
  3477. SDL_GPUBuffer *buffer,
  3478. Uint32 offset,
  3479. Uint32 drawCount)
  3480. {
  3481. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3482. D3D11_INTERNAL_BindGraphicsResources(d3d11CommandBuffer);
  3483. D3D11Buffer *d3d11Buffer = ((D3D11BufferContainer *)buffer)->activeBuffer;
  3484. /* D3D11: "We have multi-draw at home!"
  3485. * Multi-draw at home:
  3486. */
  3487. for (Uint32 i = 0; i < drawCount; i += 1) {
  3488. ID3D11DeviceContext_DrawIndexedInstancedIndirect(
  3489. d3d11CommandBuffer->context,
  3490. d3d11Buffer->handle,
  3491. offset + (sizeof(SDL_GPUIndexedIndirectDrawCommand) * i));
  3492. }
  3493. D3D11_INTERNAL_TrackBuffer(d3d11CommandBuffer, d3d11Buffer);
  3494. }
  3495. static void D3D11_EndRenderPass(
  3496. SDL_GPUCommandBuffer *commandBuffer)
  3497. {
  3498. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3499. D3D11Renderer *renderer = d3d11CommandBuffer->renderer;
  3500. Uint32 i;
  3501. // Set render target slots to NULL to avoid NULL set behavior
  3502. // https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11devicecontext-pssetshaderresources
  3503. ID3D11DeviceContext_OMSetRenderTargets(
  3504. d3d11CommandBuffer->context,
  3505. MAX_COLOR_TARGET_BINDINGS,
  3506. renderer->nullRTVs,
  3507. NULL);
  3508. // Resolve MSAA color render targets
  3509. for (i = 0; i < MAX_COLOR_TARGET_BINDINGS; i += 1) {
  3510. if (d3d11CommandBuffer->colorResolveSubresources[i] != NULL) {
  3511. ID3D11DeviceContext_ResolveSubresource(
  3512. d3d11CommandBuffer->context,
  3513. d3d11CommandBuffer->colorResolveSubresources[i]->parent->handle,
  3514. d3d11CommandBuffer->colorResolveSubresources[i]->index,
  3515. d3d11CommandBuffer->colorTargetSubresources[i]->parent->handle,
  3516. d3d11CommandBuffer->colorTargetSubresources[i]->index,
  3517. SDLToD3D11_TextureFormat[d3d11CommandBuffer->colorTargetSubresources[i]->parent->container->header.info.format]);
  3518. }
  3519. }
  3520. ID3D11DeviceContext_VSSetSamplers(
  3521. d3d11CommandBuffer->context,
  3522. 0,
  3523. MAX_TEXTURE_SAMPLERS_PER_STAGE,
  3524. renderer->nullSamplers);
  3525. ID3D11DeviceContext_VSSetShaderResources(
  3526. d3d11CommandBuffer->context,
  3527. 0,
  3528. MAX_TEXTURE_SAMPLERS_PER_STAGE * 2 + MAX_STORAGE_TEXTURES_PER_STAGE + MAX_STORAGE_BUFFERS_PER_STAGE,
  3529. renderer->nullSRVs);
  3530. ID3D11DeviceContext_PSSetSamplers(
  3531. d3d11CommandBuffer->context,
  3532. 0,
  3533. MAX_TEXTURE_SAMPLERS_PER_STAGE,
  3534. renderer->nullSamplers);
  3535. ID3D11DeviceContext_PSSetShaderResources(
  3536. d3d11CommandBuffer->context,
  3537. 0,
  3538. MAX_TEXTURE_SAMPLERS_PER_STAGE * 2 + MAX_STORAGE_TEXTURES_PER_STAGE + MAX_STORAGE_BUFFERS_PER_STAGE,
  3539. renderer->nullSRVs);
  3540. // Reset bind state
  3541. SDL_zeroa(d3d11CommandBuffer->vertexBuffers);
  3542. SDL_zeroa(d3d11CommandBuffer->vertexBufferOffsets);
  3543. d3d11CommandBuffer->vertexBufferCount = 0;
  3544. SDL_zeroa(d3d11CommandBuffer->vertexSamplers);
  3545. SDL_zeroa(d3d11CommandBuffer->vertexSamplerTextures);
  3546. SDL_zeroa(d3d11CommandBuffer->vertexStorageTextures);
  3547. SDL_zeroa(d3d11CommandBuffer->vertexStorageBuffers);
  3548. SDL_zeroa(d3d11CommandBuffer->fragmentSamplers);
  3549. SDL_zeroa(d3d11CommandBuffer->fragmentSamplerTextures);
  3550. SDL_zeroa(d3d11CommandBuffer->fragmentStorageTextures);
  3551. SDL_zeroa(d3d11CommandBuffer->fragmentStorageBuffers);
  3552. }
  3553. static void D3D11_PushVertexUniformData(
  3554. SDL_GPUCommandBuffer *commandBuffer,
  3555. Uint32 slotIndex,
  3556. const void *data,
  3557. Uint32 length)
  3558. {
  3559. D3D11_INTERNAL_PushUniformData(
  3560. (D3D11CommandBuffer *)commandBuffer,
  3561. SDL_GPU_SHADERSTAGE_VERTEX,
  3562. slotIndex,
  3563. data,
  3564. length);
  3565. }
  3566. static void D3D11_PushFragmentUniformData(
  3567. SDL_GPUCommandBuffer *commandBuffer,
  3568. Uint32 slotIndex,
  3569. const void *data,
  3570. Uint32 length)
  3571. {
  3572. D3D11_INTERNAL_PushUniformData(
  3573. (D3D11CommandBuffer *)commandBuffer,
  3574. SDL_GPU_SHADERSTAGE_FRAGMENT,
  3575. slotIndex,
  3576. data,
  3577. length);
  3578. }
  3579. // Blit
  3580. static void D3D11_Blit(
  3581. SDL_GPUCommandBuffer *commandBuffer,
  3582. const SDL_GPUBlitInfo *info)
  3583. {
  3584. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3585. D3D11Renderer *renderer = (D3D11Renderer *)d3d11CommandBuffer->renderer;
  3586. BlitPipelineCacheEntry *blitPipelines = &renderer->blitPipelines[0];
  3587. SDL_GPU_BlitCommon(
  3588. commandBuffer,
  3589. info,
  3590. renderer->blitLinearSampler,
  3591. renderer->blitNearestSampler,
  3592. NULL,
  3593. NULL,
  3594. NULL,
  3595. NULL,
  3596. NULL,
  3597. NULL,
  3598. &blitPipelines,
  3599. NULL,
  3600. NULL);
  3601. }
  3602. // Compute State
  3603. static void D3D11_BeginComputePass(
  3604. SDL_GPUCommandBuffer *commandBuffer,
  3605. const SDL_GPUStorageTextureWriteOnlyBinding *storageTextureBindings,
  3606. Uint32 numStorageTextureBindings,
  3607. const SDL_GPUStorageBufferWriteOnlyBinding *storageBufferBindings,
  3608. Uint32 numStorageBufferBindings)
  3609. {
  3610. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3611. D3D11TextureContainer *textureContainer;
  3612. D3D11TextureSubresource *textureSubresource;
  3613. D3D11BufferContainer *bufferContainer;
  3614. D3D11Buffer *buffer;
  3615. ID3D11UnorderedAccessView *uavs[MAX_COMPUTE_WRITE_TEXTURES + MAX_COMPUTE_WRITE_BUFFERS];
  3616. for (Uint32 i = 0; i < numStorageTextureBindings; i += 1) {
  3617. textureContainer = (D3D11TextureContainer *)storageTextureBindings[i].texture;
  3618. textureSubresource = D3D11_INTERNAL_PrepareTextureSubresourceForWrite(
  3619. d3d11CommandBuffer->renderer,
  3620. textureContainer,
  3621. storageTextureBindings[i].layer,
  3622. storageTextureBindings[i].mip_level,
  3623. storageTextureBindings[i].cycle);
  3624. D3D11_INTERNAL_TrackTexture(
  3625. d3d11CommandBuffer,
  3626. textureSubresource->parent);
  3627. d3d11CommandBuffer->computeWriteOnlyStorageTextureSubresources[i] = textureSubresource;
  3628. }
  3629. for (Uint32 i = 0; i < numStorageBufferBindings; i += 1) {
  3630. bufferContainer = (D3D11BufferContainer *)storageBufferBindings[i].buffer;
  3631. buffer = D3D11_INTERNAL_PrepareBufferForWrite(
  3632. d3d11CommandBuffer->renderer,
  3633. bufferContainer,
  3634. storageBufferBindings[i].cycle);
  3635. D3D11_INTERNAL_TrackBuffer(
  3636. d3d11CommandBuffer,
  3637. buffer);
  3638. d3d11CommandBuffer->computeWriteOnlyStorageBuffers[i] = buffer;
  3639. }
  3640. for (Uint32 i = 0; i < numStorageTextureBindings; i += 1) {
  3641. uavs[i] = d3d11CommandBuffer->computeWriteOnlyStorageTextureSubresources[i]->uav;
  3642. }
  3643. for (Uint32 i = 0; i < numStorageBufferBindings; i += 1) {
  3644. uavs[numStorageTextureBindings + i] = d3d11CommandBuffer->computeWriteOnlyStorageBuffers[i]->uav;
  3645. }
  3646. ID3D11DeviceContext_CSSetUnorderedAccessViews(
  3647. d3d11CommandBuffer->context,
  3648. 0,
  3649. numStorageTextureBindings + numStorageBufferBindings,
  3650. uavs,
  3651. NULL);
  3652. }
  3653. static void D3D11_BindComputePipeline(
  3654. SDL_GPUCommandBuffer *commandBuffer,
  3655. SDL_GPUComputePipeline *computePipeline)
  3656. {
  3657. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3658. D3D11ComputePipeline *pipeline = (D3D11ComputePipeline *)computePipeline;
  3659. d3d11CommandBuffer->computePipeline = pipeline;
  3660. ID3D11DeviceContext_CSSetShader(
  3661. d3d11CommandBuffer->context,
  3662. pipeline->computeShader,
  3663. NULL,
  3664. 0);
  3665. // Acquire uniform buffers if necessary
  3666. for (Uint32 i = 0; i < pipeline->numUniformBuffers; i += 1) {
  3667. if (d3d11CommandBuffer->computeUniformBuffers[i] == NULL) {
  3668. d3d11CommandBuffer->computeUniformBuffers[i] = D3D11_INTERNAL_AcquireUniformBufferFromPool(
  3669. d3d11CommandBuffer);
  3670. }
  3671. }
  3672. d3d11CommandBuffer->needComputeSamplerBind = true;
  3673. d3d11CommandBuffer->needComputeReadOnlyTextureBind = true;
  3674. d3d11CommandBuffer->needComputeReadOnlyBufferBind = true;
  3675. d3d11CommandBuffer->needComputeUniformBufferBind = true;
  3676. }
  3677. static void D3D11_BindComputeSamplers(
  3678. SDL_GPUCommandBuffer *commandBuffer,
  3679. Uint32 firstSlot,
  3680. const SDL_GPUTextureSamplerBinding *textureSamplerBindings,
  3681. Uint32 numBindings)
  3682. {
  3683. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3684. for (Uint32 i = 0; i < numBindings; i += 1) {
  3685. D3D11TextureContainer *textureContainer = (D3D11TextureContainer *)textureSamplerBindings[i].texture;
  3686. D3D11_INTERNAL_TrackTexture(
  3687. d3d11CommandBuffer,
  3688. textureContainer->activeTexture);
  3689. d3d11CommandBuffer->computeSamplers[firstSlot + i] =
  3690. (D3D11Sampler *)textureSamplerBindings[i].sampler;
  3691. d3d11CommandBuffer->computeSamplerTextures[firstSlot + i] =
  3692. textureContainer->activeTexture;
  3693. }
  3694. d3d11CommandBuffer->needComputeSamplerBind = true;
  3695. }
  3696. static void D3D11_BindComputeStorageTextures(
  3697. SDL_GPUCommandBuffer *commandBuffer,
  3698. Uint32 firstSlot,
  3699. SDL_GPUTexture *const *storageTextures,
  3700. Uint32 numBindings)
  3701. {
  3702. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3703. for (Uint32 i = 0; i < numBindings; i += 1) {
  3704. D3D11TextureContainer *textureContainer = (D3D11TextureContainer *)storageTextures[i];
  3705. D3D11_INTERNAL_TrackTexture(
  3706. d3d11CommandBuffer,
  3707. textureContainer->activeTexture);
  3708. d3d11CommandBuffer->computeReadOnlyStorageTextures[firstSlot + i] =
  3709. textureContainer->activeTexture;
  3710. }
  3711. d3d11CommandBuffer->needComputeReadOnlyTextureBind = true;
  3712. }
  3713. static void D3D11_BindComputeStorageBuffers(
  3714. SDL_GPUCommandBuffer *commandBuffer,
  3715. Uint32 firstSlot,
  3716. SDL_GPUBuffer *const *storageBuffers,
  3717. Uint32 numBindings)
  3718. {
  3719. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3720. D3D11BufferContainer *bufferContainer;
  3721. Uint32 i;
  3722. for (i = 0; i < numBindings; i += 1) {
  3723. bufferContainer = (D3D11BufferContainer *)storageBuffers[i];
  3724. D3D11_INTERNAL_TrackBuffer(
  3725. d3d11CommandBuffer,
  3726. bufferContainer->activeBuffer);
  3727. d3d11CommandBuffer->computeReadOnlyStorageBuffers[firstSlot + i] =
  3728. bufferContainer->activeBuffer;
  3729. }
  3730. d3d11CommandBuffer->needComputeReadOnlyBufferBind = true;
  3731. }
  3732. static void D3D11_PushComputeUniformData(
  3733. SDL_GPUCommandBuffer *commandBuffer,
  3734. Uint32 slotIndex,
  3735. const void *data,
  3736. Uint32 length)
  3737. {
  3738. D3D11_INTERNAL_PushUniformData(
  3739. (D3D11CommandBuffer *)commandBuffer,
  3740. SDL_GPU_SHADERSTAGE_COMPUTE,
  3741. slotIndex,
  3742. data,
  3743. length);
  3744. }
  3745. static void D3D11_INTERNAL_BindComputeResources(
  3746. D3D11CommandBuffer *commandBuffer)
  3747. {
  3748. D3D11ComputePipeline *computePipeline = commandBuffer->computePipeline;
  3749. ID3D11Buffer *nullBuf = NULL;
  3750. Uint32 offsetInConstants, blockSizeInConstants;
  3751. if (commandBuffer->needComputeSamplerBind) {
  3752. if (computePipeline->numSamplers > 0) {
  3753. ID3D11SamplerState *samplers[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  3754. ID3D11ShaderResourceView *srvs[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  3755. for (Uint32 i = 0; i < computePipeline->numSamplers; i += 1) {
  3756. samplers[i] = commandBuffer->computeSamplers[i]->handle;
  3757. srvs[i] = commandBuffer->computeSamplerTextures[i]->shaderView;
  3758. }
  3759. ID3D11DeviceContext_CSSetSamplers(
  3760. commandBuffer->context,
  3761. 0,
  3762. computePipeline->numSamplers,
  3763. samplers);
  3764. ID3D11DeviceContext_CSSetShaderResources(
  3765. commandBuffer->context,
  3766. 0,
  3767. computePipeline->numSamplers,
  3768. srvs);
  3769. }
  3770. commandBuffer->needComputeSamplerBind = false;
  3771. }
  3772. if (commandBuffer->needComputeReadOnlyTextureBind) {
  3773. if (computePipeline->numReadonlyStorageTextures > 0) {
  3774. ID3D11ShaderResourceView *srvs[MAX_STORAGE_TEXTURES_PER_STAGE];
  3775. for (Uint32 i = 0; i < computePipeline->numReadonlyStorageTextures; i += 1) {
  3776. srvs[i] = commandBuffer->computeReadOnlyStorageTextures[i]->shaderView;
  3777. }
  3778. ID3D11DeviceContext_CSSetShaderResources(
  3779. commandBuffer->context,
  3780. computePipeline->numSamplers,
  3781. computePipeline->numReadonlyStorageTextures,
  3782. srvs);
  3783. }
  3784. commandBuffer->needComputeReadOnlyTextureBind = false;
  3785. }
  3786. if (commandBuffer->needComputeReadOnlyBufferBind) {
  3787. if (computePipeline->numReadonlyStorageBuffers > 0) {
  3788. ID3D11ShaderResourceView *srvs[MAX_STORAGE_TEXTURES_PER_STAGE];
  3789. for (Uint32 i = 0; i < computePipeline->numReadonlyStorageBuffers; i += 1) {
  3790. srvs[i] = commandBuffer->computeReadOnlyStorageBuffers[i]->srv;
  3791. }
  3792. ID3D11DeviceContext_CSSetShaderResources(
  3793. commandBuffer->context,
  3794. computePipeline->numSamplers + computePipeline->numReadonlyStorageTextures,
  3795. computePipeline->numReadonlyStorageBuffers,
  3796. srvs);
  3797. }
  3798. commandBuffer->needComputeReadOnlyBufferBind = false;
  3799. }
  3800. if (commandBuffer->needComputeUniformBufferBind) {
  3801. for (Uint32 i = 0; i < computePipeline->numUniformBuffers; i += 1) {
  3802. /* stupid workaround for god awful D3D11 drivers
  3803. * see: https://learn.microsoft.com/en-us/windows/win32/api/d3d11_1/nf-d3d11_1-id3d11devicecontext1-vssetconstantbuffers1#calling-vssetconstantbuffers1-with-command-list-emulation
  3804. */
  3805. ID3D11DeviceContext1_CSSetConstantBuffers(
  3806. commandBuffer->context,
  3807. i,
  3808. 1,
  3809. &nullBuf);
  3810. offsetInConstants = commandBuffer->computeUniformBuffers[i]->drawOffset / 16;
  3811. blockSizeInConstants = commandBuffer->computeUniformBuffers[i]->currentBlockSize / 16;
  3812. ID3D11DeviceContext1_CSSetConstantBuffers1(
  3813. commandBuffer->context,
  3814. i,
  3815. 1,
  3816. &commandBuffer->computeUniformBuffers[i]->buffer,
  3817. &offsetInConstants,
  3818. &blockSizeInConstants);
  3819. }
  3820. commandBuffer->needComputeUniformBufferBind = false;
  3821. }
  3822. }
  3823. static void D3D11_DispatchCompute(
  3824. SDL_GPUCommandBuffer *commandBuffer,
  3825. Uint32 groupcountX,
  3826. Uint32 groupcountY,
  3827. Uint32 groupcountZ)
  3828. {
  3829. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3830. D3D11_INTERNAL_BindComputeResources(d3d11CommandBuffer);
  3831. ID3D11DeviceContext_Dispatch(
  3832. d3d11CommandBuffer->context,
  3833. groupcountX,
  3834. groupcountY,
  3835. groupcountZ);
  3836. }
  3837. static void D3D11_DispatchComputeIndirect(
  3838. SDL_GPUCommandBuffer *commandBuffer,
  3839. SDL_GPUBuffer *buffer,
  3840. Uint32 offset)
  3841. {
  3842. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3843. D3D11Buffer *d3d11Buffer = ((D3D11BufferContainer *)buffer)->activeBuffer;
  3844. D3D11_INTERNAL_BindComputeResources(d3d11CommandBuffer);
  3845. ID3D11DeviceContext_DispatchIndirect(
  3846. d3d11CommandBuffer->context,
  3847. d3d11Buffer->handle,
  3848. offset);
  3849. D3D11_INTERNAL_TrackBuffer(d3d11CommandBuffer, d3d11Buffer);
  3850. }
  3851. static void D3D11_EndComputePass(
  3852. SDL_GPUCommandBuffer *commandBuffer)
  3853. {
  3854. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  3855. D3D11Renderer *renderer = d3d11CommandBuffer->renderer;
  3856. // reset UAV slots to avoid NULL set behavior
  3857. // https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11devicecontext-cssetshaderresources
  3858. ID3D11DeviceContext_CSSetUnorderedAccessViews(
  3859. d3d11CommandBuffer->context,
  3860. 0,
  3861. MAX_COMPUTE_WRITE_TEXTURES + MAX_COMPUTE_WRITE_BUFFERS,
  3862. renderer->nullUAVs,
  3863. NULL);
  3864. ID3D11DeviceContext_CSSetSamplers(
  3865. d3d11CommandBuffer->context,
  3866. 0,
  3867. MAX_TEXTURE_SAMPLERS_PER_STAGE,
  3868. renderer->nullSamplers);
  3869. ID3D11DeviceContext_CSSetShaderResources(
  3870. d3d11CommandBuffer->context,
  3871. 0,
  3872. MAX_TEXTURE_SAMPLERS_PER_STAGE + MAX_STORAGE_TEXTURES_PER_STAGE + MAX_STORAGE_BUFFERS_PER_STAGE,
  3873. renderer->nullSRVs);
  3874. d3d11CommandBuffer->computePipeline = NULL;
  3875. // Reset bind state
  3876. SDL_zeroa(d3d11CommandBuffer->computeSamplers);
  3877. SDL_zeroa(d3d11CommandBuffer->computeSamplerTextures);
  3878. SDL_zeroa(d3d11CommandBuffer->computeReadOnlyStorageTextures);
  3879. SDL_zeroa(d3d11CommandBuffer->computeReadOnlyStorageBuffers);
  3880. SDL_zeroa(d3d11CommandBuffer->computeWriteOnlyStorageTextureSubresources);
  3881. SDL_zeroa(d3d11CommandBuffer->computeWriteOnlyStorageBuffers);
  3882. }
  3883. // Fence Cleanup
  3884. static void D3D11_INTERNAL_ReleaseFenceToPool(
  3885. D3D11Renderer *renderer,
  3886. D3D11Fence *fence)
  3887. {
  3888. SDL_LockMutex(renderer->fenceLock);
  3889. if (renderer->availableFenceCount == renderer->availableFenceCapacity) {
  3890. renderer->availableFenceCapacity *= 2;
  3891. renderer->availableFences = SDL_realloc(
  3892. renderer->availableFences,
  3893. renderer->availableFenceCapacity * sizeof(D3D11Fence *));
  3894. }
  3895. renderer->availableFences[renderer->availableFenceCount] = fence;
  3896. renderer->availableFenceCount += 1;
  3897. SDL_UnlockMutex(renderer->fenceLock);
  3898. }
  3899. static void D3D11_ReleaseFence(
  3900. SDL_GPURenderer *driverData,
  3901. SDL_GPUFence *fence)
  3902. {
  3903. D3D11Fence *d3d11Fence = (D3D11Fence *)fence;
  3904. if (SDL_AtomicDecRef(&d3d11Fence->referenceCount)) {
  3905. D3D11_INTERNAL_ReleaseFenceToPool(
  3906. (D3D11Renderer *)driverData,
  3907. d3d11Fence);
  3908. }
  3909. }
  3910. // Cleanup
  3911. /* D3D11 does not provide a deferred texture-to-buffer copy operation,
  3912. * so instead of the transfer buffer containing an actual D3D11 buffer,
  3913. * the transfer buffer data is just a malloc'd pointer.
  3914. * In the download operation we copy data to a staging resource, and
  3915. * wait until the command buffer has finished executing to map the staging resource.
  3916. */
  3917. static void D3D11_INTERNAL_MapAndCopyBufferDownload(
  3918. D3D11Renderer *renderer,
  3919. D3D11TransferBuffer *transferBuffer,
  3920. D3D11BufferDownload *bufferDownload)
  3921. {
  3922. D3D11_MAPPED_SUBRESOURCE subres;
  3923. HRESULT res;
  3924. SDL_LockMutex(renderer->contextLock);
  3925. res = ID3D11DeviceContext_Map(
  3926. renderer->immediateContext,
  3927. (ID3D11Resource *)bufferDownload->stagingBuffer,
  3928. 0,
  3929. D3D11_MAP_READ,
  3930. 0,
  3931. &subres);
  3932. ERROR_CHECK_RETURN("Failed to map staging buffer", )
  3933. SDL_memcpy(
  3934. ((Uint8 *)transferBuffer->data) + bufferDownload->dstOffset,
  3935. ((Uint8 *)subres.pData),
  3936. bufferDownload->size);
  3937. ID3D11DeviceContext_Unmap(
  3938. renderer->immediateContext,
  3939. (ID3D11Resource *)bufferDownload->stagingBuffer,
  3940. 0);
  3941. SDL_UnlockMutex(renderer->contextLock);
  3942. ID3D11Buffer_Release(bufferDownload->stagingBuffer);
  3943. }
  3944. static void D3D11_INTERNAL_MapAndCopyTextureDownload(
  3945. D3D11Renderer *renderer,
  3946. D3D11TransferBuffer *transferBuffer,
  3947. D3D11TextureDownload *textureDownload)
  3948. {
  3949. D3D11_MAPPED_SUBRESOURCE subres;
  3950. HRESULT res;
  3951. Uint32 dataPtrOffset;
  3952. Uint32 depth, row;
  3953. SDL_LockMutex(renderer->contextLock);
  3954. res = ID3D11DeviceContext_Map(
  3955. renderer->immediateContext,
  3956. (ID3D11Resource *)textureDownload->stagingTexture,
  3957. 0,
  3958. D3D11_MAP_READ,
  3959. 0,
  3960. &subres);
  3961. ERROR_CHECK_RETURN("Could not map staging texture", )
  3962. for (depth = 0; depth < textureDownload->depth; depth += 1) {
  3963. dataPtrOffset = textureDownload->bufferOffset + (depth * textureDownload->bytesPerDepthSlice);
  3964. for (row = 0; row < textureDownload->height; row += 1) {
  3965. SDL_memcpy(
  3966. transferBuffer->data + dataPtrOffset,
  3967. (Uint8 *)subres.pData + (depth * subres.DepthPitch) + (row * subres.RowPitch),
  3968. textureDownload->bytesPerRow);
  3969. dataPtrOffset += textureDownload->bytesPerRow;
  3970. }
  3971. }
  3972. ID3D11DeviceContext_Unmap(
  3973. renderer->immediateContext,
  3974. textureDownload->stagingTexture,
  3975. 0);
  3976. SDL_UnlockMutex(renderer->contextLock);
  3977. ID3D11Resource_Release(textureDownload->stagingTexture);
  3978. }
  3979. static void D3D11_INTERNAL_CleanCommandBuffer(
  3980. D3D11Renderer *renderer,
  3981. D3D11CommandBuffer *commandBuffer)
  3982. {
  3983. Uint32 i, j;
  3984. // Perform deferred download map and copy
  3985. for (i = 0; i < commandBuffer->usedTransferBufferCount; i += 1) {
  3986. D3D11TransferBuffer *transferBuffer = commandBuffer->usedTransferBuffers[i];
  3987. for (j = 0; j < transferBuffer->bufferDownloadCount; j += 1) {
  3988. D3D11_INTERNAL_MapAndCopyBufferDownload(
  3989. renderer,
  3990. transferBuffer,
  3991. &transferBuffer->bufferDownloads[j]);
  3992. }
  3993. for (j = 0; j < transferBuffer->textureDownloadCount; j += 1) {
  3994. D3D11_INTERNAL_MapAndCopyTextureDownload(
  3995. renderer,
  3996. transferBuffer,
  3997. &transferBuffer->textureDownloads[j]);
  3998. }
  3999. transferBuffer->bufferDownloadCount = 0;
  4000. transferBuffer->textureDownloadCount = 0;
  4001. }
  4002. // Uniform buffers are now available
  4003. SDL_LockMutex(renderer->acquireUniformBufferLock);
  4004. for (i = 0; i < commandBuffer->usedUniformBufferCount; i += 1) {
  4005. D3D11_INTERNAL_ReturnUniformBufferToPool(
  4006. renderer,
  4007. commandBuffer->usedUniformBuffers[i]);
  4008. }
  4009. commandBuffer->usedUniformBufferCount = 0;
  4010. SDL_UnlockMutex(renderer->acquireUniformBufferLock);
  4011. // Reference Counting
  4012. for (i = 0; i < commandBuffer->usedBufferCount; i += 1) {
  4013. (void)SDL_AtomicDecRef(&commandBuffer->usedBuffers[i]->referenceCount);
  4014. }
  4015. commandBuffer->usedBufferCount = 0;
  4016. for (i = 0; i < commandBuffer->usedTransferBufferCount; i += 1) {
  4017. (void)SDL_AtomicDecRef(&commandBuffer->usedTransferBuffers[i]->referenceCount);
  4018. }
  4019. commandBuffer->usedTransferBufferCount = 0;
  4020. for (i = 0; i < commandBuffer->usedTextureCount; i += 1) {
  4021. (void)SDL_AtomicDecRef(&commandBuffer->usedTextures[i]->referenceCount);
  4022. }
  4023. commandBuffer->usedTextureCount = 0;
  4024. // Reset presentation
  4025. commandBuffer->windowDataCount = 0;
  4026. // The fence is now available (unless SubmitAndAcquireFence was called)
  4027. if (commandBuffer->autoReleaseFence) {
  4028. D3D11_ReleaseFence(
  4029. (SDL_GPURenderer *)renderer,
  4030. (SDL_GPUFence *)commandBuffer->fence);
  4031. }
  4032. // Return command buffer to pool
  4033. SDL_LockMutex(renderer->acquireCommandBufferLock);
  4034. if (renderer->availableCommandBufferCount == renderer->availableCommandBufferCapacity) {
  4035. renderer->availableCommandBufferCapacity += 1;
  4036. renderer->availableCommandBuffers = SDL_realloc(
  4037. renderer->availableCommandBuffers,
  4038. renderer->availableCommandBufferCapacity * sizeof(D3D11CommandBuffer *));
  4039. }
  4040. renderer->availableCommandBuffers[renderer->availableCommandBufferCount] = commandBuffer;
  4041. renderer->availableCommandBufferCount += 1;
  4042. SDL_UnlockMutex(renderer->acquireCommandBufferLock);
  4043. // Remove this command buffer from the submitted list
  4044. for (i = 0; i < renderer->submittedCommandBufferCount; i += 1) {
  4045. if (renderer->submittedCommandBuffers[i] == commandBuffer) {
  4046. renderer->submittedCommandBuffers[i] = renderer->submittedCommandBuffers[renderer->submittedCommandBufferCount - 1];
  4047. renderer->submittedCommandBufferCount -= 1;
  4048. }
  4049. }
  4050. }
  4051. static void D3D11_INTERNAL_PerformPendingDestroys(
  4052. D3D11Renderer *renderer)
  4053. {
  4054. Sint32 referenceCount = 0;
  4055. Sint32 i;
  4056. Uint32 j;
  4057. for (i = renderer->transferBufferContainersToDestroyCount - 1; i >= 0; i -= 1) {
  4058. referenceCount = 0;
  4059. for (j = 0; j < renderer->transferBufferContainersToDestroy[i]->bufferCount; j += 1) {
  4060. referenceCount += SDL_AtomicGet(&renderer->transferBufferContainersToDestroy[i]->buffers[j]->referenceCount);
  4061. }
  4062. if (referenceCount == 0) {
  4063. D3D11_INTERNAL_DestroyTransferBufferContainer(
  4064. renderer->transferBufferContainersToDestroy[i]);
  4065. renderer->transferBufferContainersToDestroy[i] = renderer->transferBufferContainersToDestroy[renderer->transferBufferContainersToDestroyCount - 1];
  4066. renderer->transferBufferContainersToDestroyCount -= 1;
  4067. }
  4068. }
  4069. for (i = renderer->bufferContainersToDestroyCount - 1; i >= 0; i -= 1) {
  4070. referenceCount = 0;
  4071. for (j = 0; j < renderer->bufferContainersToDestroy[i]->bufferCount; j += 1) {
  4072. referenceCount += SDL_AtomicGet(&renderer->bufferContainersToDestroy[i]->buffers[j]->referenceCount);
  4073. }
  4074. if (referenceCount == 0) {
  4075. D3D11_INTERNAL_DestroyBufferContainer(
  4076. renderer->bufferContainersToDestroy[i]);
  4077. renderer->bufferContainersToDestroy[i] = renderer->bufferContainersToDestroy[renderer->bufferContainersToDestroyCount - 1];
  4078. renderer->bufferContainersToDestroyCount -= 1;
  4079. }
  4080. }
  4081. for (i = renderer->textureContainersToDestroyCount - 1; i >= 0; i -= 1) {
  4082. referenceCount = 0;
  4083. for (j = 0; j < renderer->textureContainersToDestroy[i]->textureCount; j += 1) {
  4084. referenceCount += SDL_AtomicGet(&renderer->textureContainersToDestroy[i]->textures[j]->referenceCount);
  4085. }
  4086. if (referenceCount == 0) {
  4087. D3D11_INTERNAL_DestroyTextureContainer(
  4088. renderer->textureContainersToDestroy[i]);
  4089. renderer->textureContainersToDestroy[i] = renderer->textureContainersToDestroy[renderer->textureContainersToDestroyCount - 1];
  4090. renderer->textureContainersToDestroyCount -= 1;
  4091. }
  4092. }
  4093. }
  4094. // Fences
  4095. static void D3D11_INTERNAL_WaitForFence(
  4096. D3D11Renderer *renderer,
  4097. D3D11Fence *fence)
  4098. {
  4099. BOOL queryData;
  4100. HRESULT res;
  4101. SDL_LockMutex(renderer->contextLock);
  4102. do {
  4103. res = ID3D11DeviceContext_GetData(
  4104. renderer->immediateContext,
  4105. (ID3D11Asynchronous *)fence->handle,
  4106. &queryData,
  4107. sizeof(queryData),
  4108. 0);
  4109. } while (res != S_OK); // Spin until we get a result back...
  4110. SDL_UnlockMutex(renderer->contextLock);
  4111. }
  4112. static void D3D11_WaitForFences(
  4113. SDL_GPURenderer *driverData,
  4114. bool waitAll,
  4115. SDL_GPUFence *const *fences,
  4116. Uint32 numFences)
  4117. {
  4118. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  4119. D3D11Fence *fence;
  4120. BOOL queryData;
  4121. HRESULT res = S_FALSE;
  4122. if (waitAll) {
  4123. for (Uint32 i = 0; i < numFences; i += 1) {
  4124. fence = (D3D11Fence *)fences[i];
  4125. D3D11_INTERNAL_WaitForFence(renderer, fence);
  4126. }
  4127. } else {
  4128. SDL_LockMutex(renderer->contextLock);
  4129. while (res != S_OK) {
  4130. for (Uint32 i = 0; i < numFences; i += 1) {
  4131. fence = (D3D11Fence *)fences[i];
  4132. res = ID3D11DeviceContext_GetData(
  4133. renderer->immediateContext,
  4134. (ID3D11Asynchronous *)fence->handle,
  4135. &queryData,
  4136. sizeof(queryData),
  4137. 0);
  4138. if (res == S_OK) {
  4139. break;
  4140. }
  4141. }
  4142. }
  4143. SDL_UnlockMutex(renderer->contextLock);
  4144. }
  4145. SDL_LockMutex(renderer->contextLock);
  4146. // Check if we can perform any cleanups
  4147. for (Sint32 i = renderer->submittedCommandBufferCount - 1; i >= 0; i -= 1) {
  4148. res = ID3D11DeviceContext_GetData(
  4149. renderer->immediateContext,
  4150. (ID3D11Asynchronous *)renderer->submittedCommandBuffers[i]->fence->handle,
  4151. &queryData,
  4152. sizeof(queryData),
  4153. 0);
  4154. if (res == S_OK) {
  4155. D3D11_INTERNAL_CleanCommandBuffer(
  4156. renderer,
  4157. renderer->submittedCommandBuffers[i]);
  4158. }
  4159. }
  4160. D3D11_INTERNAL_PerformPendingDestroys(renderer);
  4161. SDL_UnlockMutex(renderer->contextLock);
  4162. }
  4163. static bool D3D11_QueryFence(
  4164. SDL_GPURenderer *driverData,
  4165. SDL_GPUFence *fence)
  4166. {
  4167. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  4168. D3D11Fence *d3d11Fence = (D3D11Fence *)fence;
  4169. BOOL queryData;
  4170. HRESULT res;
  4171. SDL_LockMutex(renderer->contextLock);
  4172. res = ID3D11DeviceContext_GetData(
  4173. renderer->immediateContext,
  4174. (ID3D11Asynchronous *)d3d11Fence->handle,
  4175. &queryData,
  4176. sizeof(queryData),
  4177. 0);
  4178. SDL_UnlockMutex(renderer->contextLock);
  4179. return res == S_OK;
  4180. }
  4181. // Window and Swapchain Management
  4182. static D3D11WindowData *D3D11_INTERNAL_FetchWindowData(
  4183. SDL_Window *window)
  4184. {
  4185. SDL_PropertiesID properties = SDL_GetWindowProperties(window);
  4186. return (D3D11WindowData *)SDL_GetPointerProperty(properties, WINDOW_PROPERTY_DATA, NULL);
  4187. }
  4188. static bool D3D11_INTERNAL_InitializeSwapchainTexture(
  4189. D3D11Renderer *renderer,
  4190. IDXGISwapChain *swapchain,
  4191. DXGI_FORMAT swapchainFormat,
  4192. DXGI_FORMAT rtvFormat,
  4193. D3D11Texture *pTexture)
  4194. {
  4195. ID3D11Texture2D *swapchainTexture;
  4196. D3D11_RENDER_TARGET_VIEW_DESC rtvDesc;
  4197. ID3D11RenderTargetView *rtv;
  4198. HRESULT res;
  4199. // Clear all the texture data
  4200. SDL_zerop(pTexture);
  4201. // Grab the buffer from the swapchain
  4202. res = IDXGISwapChain_GetBuffer(
  4203. swapchain,
  4204. 0,
  4205. &D3D_IID_ID3D11Texture2D,
  4206. (void **)&swapchainTexture);
  4207. ERROR_CHECK_RETURN("Could not get buffer from swapchain!", 0);
  4208. // Create the RTV for the swapchain
  4209. rtvDesc.Format = rtvFormat;
  4210. rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
  4211. rtvDesc.Texture2D.MipSlice = 0;
  4212. res = ID3D11Device_CreateRenderTargetView(
  4213. renderer->device,
  4214. (ID3D11Resource *)swapchainTexture,
  4215. &rtvDesc,
  4216. &rtv);
  4217. if (FAILED(res)) {
  4218. ID3D11Texture2D_Release(swapchainTexture);
  4219. D3D11_INTERNAL_LogError(renderer->device, "Swapchain RTV creation failed", res);
  4220. return false;
  4221. }
  4222. // Fill out the texture struct
  4223. pTexture->handle = NULL; // This will be set in AcquireSwapchainTexture.
  4224. pTexture->shaderView = NULL; // We don't allow swapchain texture to be sampled
  4225. SDL_AtomicSet(&pTexture->referenceCount, 0);
  4226. pTexture->subresourceCount = 1;
  4227. pTexture->subresources = SDL_malloc(sizeof(D3D11TextureSubresource));
  4228. pTexture->subresources[0].colorTargetViews = SDL_calloc(1, sizeof(ID3D11RenderTargetView *));
  4229. pTexture->subresources[0].colorTargetViews[0] = rtv;
  4230. pTexture->subresources[0].uav = NULL;
  4231. pTexture->subresources[0].depthStencilTargetView = NULL;
  4232. pTexture->subresources[0].layer = 0;
  4233. pTexture->subresources[0].level = 0;
  4234. pTexture->subresources[0].depth = 1;
  4235. pTexture->subresources[0].index = 0;
  4236. pTexture->subresources[0].parent = pTexture;
  4237. // Cleanup
  4238. ID3D11Texture2D_Release(swapchainTexture);
  4239. return true;
  4240. }
  4241. static bool D3D11_INTERNAL_CreateSwapchain(
  4242. D3D11Renderer *renderer,
  4243. D3D11WindowData *windowData,
  4244. SDL_GPUSwapchainComposition swapchainComposition,
  4245. SDL_GPUPresentMode presentMode)
  4246. {
  4247. HWND dxgiHandle;
  4248. int width, height;
  4249. Uint32 i;
  4250. DXGI_SWAP_CHAIN_DESC swapchainDesc;
  4251. DXGI_FORMAT swapchainFormat;
  4252. IDXGIFactory1 *pParent;
  4253. IDXGISwapChain *swapchain;
  4254. IDXGISwapChain3 *swapchain3;
  4255. HRESULT res;
  4256. // Get the DXGI handle
  4257. #ifdef _WIN32
  4258. dxgiHandle = (HWND)SDL_GetPointerProperty(SDL_GetWindowProperties(windowData->window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, NULL);
  4259. #else
  4260. dxgiHandle = (HWND)windowData->window;
  4261. #endif
  4262. // Get the window size
  4263. SDL_GetWindowSize(windowData->window, &width, &height);
  4264. swapchainFormat = SwapchainCompositionToTextureFormat[swapchainComposition];
  4265. // Initialize the swapchain buffer descriptor
  4266. swapchainDesc.BufferDesc.Width = 0;
  4267. swapchainDesc.BufferDesc.Height = 0;
  4268. swapchainDesc.BufferDesc.RefreshRate.Numerator = 0;
  4269. swapchainDesc.BufferDesc.RefreshRate.Denominator = 0;
  4270. swapchainDesc.BufferDesc.Format = swapchainFormat;
  4271. swapchainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
  4272. swapchainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
  4273. // Initialize the rest of the swapchain descriptor
  4274. swapchainDesc.SampleDesc.Count = 1;
  4275. swapchainDesc.SampleDesc.Quality = 0;
  4276. swapchainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  4277. swapchainDesc.BufferCount = 2;
  4278. swapchainDesc.OutputWindow = dxgiHandle;
  4279. swapchainDesc.Windowed = 1;
  4280. if (renderer->supportsTearing) {
  4281. swapchainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
  4282. // We know this is supported because tearing support implies DXGI 1.5+
  4283. swapchainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
  4284. } else {
  4285. swapchainDesc.Flags = 0;
  4286. swapchainDesc.SwapEffect = (renderer->supportsFlipDiscard ? DXGI_SWAP_EFFECT_FLIP_DISCARD : DXGI_SWAP_EFFECT_DISCARD);
  4287. }
  4288. // Create the swapchain!
  4289. res = IDXGIFactory1_CreateSwapChain(
  4290. (IDXGIFactory1 *)renderer->factory,
  4291. (IUnknown *)renderer->device,
  4292. &swapchainDesc,
  4293. &swapchain);
  4294. ERROR_CHECK_RETURN("Could not create swapchain", 0);
  4295. /*
  4296. * The swapchain's parent is a separate factory from the factory that
  4297. * we used to create the swapchain, and only that parent can be used to
  4298. * set the window association. Trying to set an association on our factory
  4299. * will silently fail and doesn't even verify arguments or return errors.
  4300. * See https://gamedev.net/forums/topic/634235-dxgidisabling-altenter/4999955/
  4301. */
  4302. res = IDXGISwapChain_GetParent(
  4303. swapchain,
  4304. &D3D_IID_IDXGIFactory1,
  4305. (void **)&pParent);
  4306. if (FAILED(res)) {
  4307. SDL_LogWarn(
  4308. SDL_LOG_CATEGORY_GPU,
  4309. "Could not get swapchain parent! Error Code: " HRESULT_FMT,
  4310. res);
  4311. } else {
  4312. // Disable DXGI window crap
  4313. res = IDXGIFactory1_MakeWindowAssociation(
  4314. pParent,
  4315. dxgiHandle,
  4316. DXGI_MWA_NO_WINDOW_CHANGES);
  4317. if (FAILED(res)) {
  4318. SDL_LogWarn(
  4319. SDL_LOG_CATEGORY_GPU,
  4320. "MakeWindowAssociation failed! Error Code: " HRESULT_FMT,
  4321. res);
  4322. }
  4323. // We're done with the parent now
  4324. IDXGIFactory1_Release(pParent);
  4325. }
  4326. if (swapchainComposition != SDL_GPU_SWAPCHAINCOMPOSITION_SDR) {
  4327. // Set the color space, support already verified if we hit this block
  4328. IDXGISwapChain3_QueryInterface(
  4329. swapchain,
  4330. &D3D_IID_IDXGISwapChain3,
  4331. (void **)&swapchain3);
  4332. IDXGISwapChain3_SetColorSpace1(
  4333. swapchain3,
  4334. SwapchainCompositionToColorSpace[swapchainComposition]);
  4335. IDXGISwapChain3_Release(swapchain3);
  4336. }
  4337. // Initialize the swapchain data
  4338. windowData->swapchain = swapchain;
  4339. windowData->presentMode = presentMode;
  4340. windowData->swapchainComposition = swapchainComposition;
  4341. windowData->swapchainFormat = swapchainFormat;
  4342. windowData->swapchainColorSpace = SwapchainCompositionToColorSpace[swapchainComposition];
  4343. windowData->frameCounter = 0;
  4344. for (i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  4345. windowData->inFlightFences[i] = NULL;
  4346. }
  4347. /* If a you are using a FLIP model format you can't create the swapchain as DXGI_FORMAT_B8G8R8A8_UNORM_SRGB.
  4348. * You have to create the swapchain as DXGI_FORMAT_B8G8R8A8_UNORM and then set the render target view's format to DXGI_FORMAT_B8G8R8A8_UNORM_SRGB
  4349. */
  4350. if (!D3D11_INTERNAL_InitializeSwapchainTexture(
  4351. renderer,
  4352. swapchain,
  4353. swapchainFormat,
  4354. (swapchainComposition == SDL_GPU_SWAPCHAINCOMPOSITION_SDR_LINEAR) ? DXGI_FORMAT_B8G8R8A8_UNORM_SRGB : windowData->swapchainFormat,
  4355. &windowData->texture)) {
  4356. IDXGISwapChain_Release(swapchain);
  4357. return false;
  4358. }
  4359. // Initialize dummy container, width/height will be filled out in AcquireSwapchainTexture
  4360. SDL_zerop(&windowData->textureContainer);
  4361. windowData->textureContainer.textures = SDL_calloc(1, sizeof(D3D11Texture *));
  4362. windowData->textureContainer.activeTexture = &windowData->texture;
  4363. windowData->textureContainer.textures[0] = &windowData->texture;
  4364. windowData->textureContainer.canBeCycled = false;
  4365. windowData->textureContainer.textureCount = 1;
  4366. windowData->textureContainer.textureCapacity = 1;
  4367. windowData->textureContainer.header.info.layer_count_or_depth = 1;
  4368. windowData->textureContainer.header.info.format = SwapchainCompositionToSDLTextureFormat[windowData->swapchainComposition];
  4369. windowData->textureContainer.header.info.type = SDL_GPU_TEXTURETYPE_2D;
  4370. windowData->textureContainer.header.info.num_levels = 1;
  4371. windowData->textureContainer.header.info.sample_count = SDL_GPU_SAMPLECOUNT_1;
  4372. windowData->textureContainer.header.info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
  4373. windowData->texture.container = &windowData->textureContainer;
  4374. windowData->texture.containerIndex = 0;
  4375. return true;
  4376. }
  4377. static bool D3D11_INTERNAL_ResizeSwapchain(
  4378. D3D11Renderer *renderer,
  4379. D3D11WindowData *windowData,
  4380. Sint32 width,
  4381. Sint32 height)
  4382. {
  4383. // Release the old RTV
  4384. ID3D11RenderTargetView_Release(windowData->texture.subresources[0].colorTargetViews[0]);
  4385. SDL_free(windowData->texture.subresources[0].colorTargetViews);
  4386. SDL_free(windowData->texture.subresources);
  4387. // Resize the swapchain
  4388. HRESULT res = IDXGISwapChain_ResizeBuffers(
  4389. windowData->swapchain,
  4390. 0, // Keep buffer count the same
  4391. width,
  4392. height,
  4393. DXGI_FORMAT_UNKNOWN, // Keep the old format
  4394. renderer->supportsTearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0);
  4395. ERROR_CHECK_RETURN("Could not resize swapchain buffers", 0);
  4396. // Create the texture object for the swapchain
  4397. return D3D11_INTERNAL_InitializeSwapchainTexture(
  4398. renderer,
  4399. windowData->swapchain,
  4400. windowData->swapchainFormat,
  4401. (windowData->swapchainComposition == SDL_GPU_SWAPCHAINCOMPOSITION_SDR_LINEAR) ? DXGI_FORMAT_B8G8R8A8_UNORM_SRGB : windowData->swapchainFormat,
  4402. &windowData->texture);
  4403. }
  4404. static bool D3D11_SupportsSwapchainComposition(
  4405. SDL_GPURenderer *driverData,
  4406. SDL_Window *window,
  4407. SDL_GPUSwapchainComposition swapchainComposition)
  4408. {
  4409. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  4410. DXGI_FORMAT format;
  4411. Uint32 formatSupport = 0;
  4412. IDXGISwapChain3 *swapchain3;
  4413. Uint32 colorSpaceSupport;
  4414. HRESULT res;
  4415. format = SwapchainCompositionToTextureFormat[swapchainComposition];
  4416. res = ID3D11Device_CheckFormatSupport(
  4417. renderer->device,
  4418. format,
  4419. &formatSupport);
  4420. if (FAILED(res)) {
  4421. // Format is apparently unknown
  4422. return false;
  4423. }
  4424. if (!(formatSupport & D3D11_FORMAT_SUPPORT_DISPLAY)) {
  4425. return false;
  4426. }
  4427. D3D11WindowData *windowData = D3D11_INTERNAL_FetchWindowData(window);
  4428. if (windowData == NULL) {
  4429. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Must claim window before querying swapchain composition support!");
  4430. return false;
  4431. }
  4432. // Check the color space support if necessary
  4433. if (swapchainComposition != SDL_GPU_SWAPCHAINCOMPOSITION_SDR) {
  4434. if (SUCCEEDED(IDXGISwapChain3_QueryInterface(
  4435. windowData->swapchain,
  4436. &D3D_IID_IDXGISwapChain3,
  4437. (void **)&swapchain3))) {
  4438. IDXGISwapChain3_CheckColorSpaceSupport(
  4439. swapchain3,
  4440. SwapchainCompositionToColorSpace[swapchainComposition],
  4441. &colorSpaceSupport);
  4442. IDXGISwapChain3_Release(swapchain3);
  4443. if (!(colorSpaceSupport & DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT)) {
  4444. return false;
  4445. }
  4446. } else {
  4447. SDL_LogError(SDL_LOG_CATEGORY_GPU, "DXGI 1.4 not supported, cannot use composition other than SDL_GPU_SWAPCHAINCOMPOSITION_SDR!");
  4448. return false;
  4449. }
  4450. }
  4451. return true;
  4452. }
  4453. static bool D3D11_SupportsPresentMode(
  4454. SDL_GPURenderer *driverData,
  4455. SDL_Window *window,
  4456. SDL_GPUPresentMode presentMode)
  4457. {
  4458. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  4459. (void)window; // used by other backends
  4460. switch (presentMode) {
  4461. case SDL_GPU_PRESENTMODE_IMMEDIATE:
  4462. case SDL_GPU_PRESENTMODE_VSYNC:
  4463. return true;
  4464. case SDL_GPU_PRESENTMODE_MAILBOX:
  4465. return renderer->supportsFlipDiscard;
  4466. }
  4467. SDL_assert(!"Unrecognized present mode");
  4468. return false;
  4469. }
  4470. static bool D3D11_ClaimWindow(
  4471. SDL_GPURenderer *driverData,
  4472. SDL_Window *window)
  4473. {
  4474. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  4475. D3D11WindowData *windowData = D3D11_INTERNAL_FetchWindowData(window);
  4476. if (windowData == NULL) {
  4477. windowData = (D3D11WindowData *)SDL_malloc(sizeof(D3D11WindowData));
  4478. windowData->window = window;
  4479. if (D3D11_INTERNAL_CreateSwapchain(renderer, windowData, SDL_GPU_SWAPCHAINCOMPOSITION_SDR, SDL_GPU_PRESENTMODE_VSYNC)) {
  4480. SDL_SetPointerProperty(SDL_GetWindowProperties(window), WINDOW_PROPERTY_DATA, windowData);
  4481. SDL_LockMutex(renderer->windowLock);
  4482. if (renderer->claimedWindowCount >= renderer->claimedWindowCapacity) {
  4483. renderer->claimedWindowCapacity *= 2;
  4484. renderer->claimedWindows = SDL_realloc(
  4485. renderer->claimedWindows,
  4486. renderer->claimedWindowCapacity * sizeof(D3D11WindowData *));
  4487. }
  4488. renderer->claimedWindows[renderer->claimedWindowCount] = windowData;
  4489. renderer->claimedWindowCount += 1;
  4490. SDL_UnlockMutex(renderer->windowLock);
  4491. return true;
  4492. } else {
  4493. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Could not create swapchain, failed to claim window!");
  4494. SDL_free(windowData);
  4495. return false;
  4496. }
  4497. } else {
  4498. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Window already claimed!");
  4499. return false;
  4500. }
  4501. }
  4502. static void D3D11_INTERNAL_DestroySwapchain(
  4503. D3D11Renderer *renderer,
  4504. D3D11WindowData *windowData)
  4505. {
  4506. Uint32 i;
  4507. D3D11_Wait((SDL_GPURenderer *)renderer);
  4508. ID3D11RenderTargetView_Release(windowData->texture.subresources[0].colorTargetViews[0]);
  4509. SDL_free(windowData->texture.subresources[0].colorTargetViews);
  4510. SDL_free(windowData->texture.subresources);
  4511. SDL_free(windowData->textureContainer.textures);
  4512. IDXGISwapChain_Release(windowData->swapchain);
  4513. // DXGI will crash if we don't flush deferred swapchain destruction
  4514. SDL_LockMutex(renderer->contextLock);
  4515. ID3D11DeviceContext_ClearState(renderer->immediateContext);
  4516. ID3D11DeviceContext_Flush(renderer->immediateContext);
  4517. SDL_UnlockMutex(renderer->contextLock);
  4518. windowData->swapchain = NULL;
  4519. for (i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  4520. if (windowData->inFlightFences[i] != NULL) {
  4521. D3D11_ReleaseFence(
  4522. (SDL_GPURenderer *)renderer,
  4523. windowData->inFlightFences[i]);
  4524. }
  4525. }
  4526. }
  4527. static void D3D11_ReleaseWindow(
  4528. SDL_GPURenderer *driverData,
  4529. SDL_Window *window)
  4530. {
  4531. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  4532. D3D11WindowData *windowData = D3D11_INTERNAL_FetchWindowData(window);
  4533. if (windowData == NULL) {
  4534. return;
  4535. }
  4536. D3D11_INTERNAL_DestroySwapchain(
  4537. renderer,
  4538. windowData);
  4539. SDL_LockMutex(renderer->windowLock);
  4540. for (Uint32 i = 0; i < renderer->claimedWindowCount; i += 1) {
  4541. if (renderer->claimedWindows[i]->window == window) {
  4542. renderer->claimedWindows[i] = renderer->claimedWindows[renderer->claimedWindowCount - 1];
  4543. renderer->claimedWindowCount -= 1;
  4544. break;
  4545. }
  4546. }
  4547. SDL_UnlockMutex(renderer->windowLock);
  4548. SDL_free(windowData);
  4549. SDL_ClearProperty(SDL_GetWindowProperties(window), WINDOW_PROPERTY_DATA);
  4550. }
  4551. static SDL_GPUTexture *D3D11_AcquireSwapchainTexture(
  4552. SDL_GPUCommandBuffer *commandBuffer,
  4553. SDL_Window *window,
  4554. Uint32 *w,
  4555. Uint32 *h)
  4556. {
  4557. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  4558. D3D11Renderer *renderer = (D3D11Renderer *)d3d11CommandBuffer->renderer;
  4559. D3D11WindowData *windowData;
  4560. DXGI_SWAP_CHAIN_DESC swapchainDesc;
  4561. int windowW, windowH;
  4562. HRESULT res;
  4563. windowData = D3D11_INTERNAL_FetchWindowData(window);
  4564. if (windowData == NULL) {
  4565. return NULL;
  4566. }
  4567. // Check for window size changes and resize the swapchain if needed.
  4568. IDXGISwapChain_GetDesc(windowData->swapchain, &swapchainDesc);
  4569. SDL_GetWindowSize(window, &windowW, &windowH);
  4570. if ((UINT)windowW != swapchainDesc.BufferDesc.Width || (UINT)windowH != swapchainDesc.BufferDesc.Height) {
  4571. res = D3D11_INTERNAL_ResizeSwapchain(
  4572. renderer,
  4573. windowData,
  4574. windowW,
  4575. windowH);
  4576. ERROR_CHECK_RETURN("Could not resize swapchain", NULL);
  4577. }
  4578. if (windowData->inFlightFences[windowData->frameCounter] != NULL) {
  4579. if (windowData->presentMode == SDL_GPU_PRESENTMODE_VSYNC) {
  4580. // In VSYNC mode, block until the least recent presented frame is done
  4581. D3D11_WaitForFences(
  4582. (SDL_GPURenderer *)renderer,
  4583. true,
  4584. &windowData->inFlightFences[windowData->frameCounter],
  4585. 1);
  4586. } else {
  4587. if (!D3D11_QueryFence(
  4588. (SDL_GPURenderer *)d3d11CommandBuffer->renderer,
  4589. windowData->inFlightFences[windowData->frameCounter])) {
  4590. /*
  4591. * In MAILBOX or IMMEDIATE mode, if the least recent fence is not signaled,
  4592. * return NULL to indicate that rendering should be skipped
  4593. */
  4594. return NULL;
  4595. }
  4596. }
  4597. D3D11_ReleaseFence(
  4598. (SDL_GPURenderer *)d3d11CommandBuffer->renderer,
  4599. windowData->inFlightFences[windowData->frameCounter]);
  4600. windowData->inFlightFences[windowData->frameCounter] = NULL;
  4601. }
  4602. // Set the handle on the windowData texture data.
  4603. res = IDXGISwapChain_GetBuffer(
  4604. windowData->swapchain,
  4605. 0,
  4606. &D3D_IID_ID3D11Texture2D,
  4607. (void **)&windowData->texture.handle);
  4608. ERROR_CHECK_RETURN("Could not acquire swapchain!", NULL);
  4609. // Send the dimensions to the out parameters.
  4610. *w = windowW;
  4611. *h = windowH;
  4612. // Update the texture container dimensions
  4613. windowData->textureContainer.header.info.width = windowW;
  4614. windowData->textureContainer.header.info.height = windowH;
  4615. // Set up presentation
  4616. if (d3d11CommandBuffer->windowDataCount == d3d11CommandBuffer->windowDataCapacity) {
  4617. d3d11CommandBuffer->windowDataCapacity += 1;
  4618. d3d11CommandBuffer->windowDatas = SDL_realloc(
  4619. d3d11CommandBuffer->windowDatas,
  4620. d3d11CommandBuffer->windowDataCapacity * sizeof(D3D11WindowData *));
  4621. }
  4622. d3d11CommandBuffer->windowDatas[d3d11CommandBuffer->windowDataCount] = windowData;
  4623. d3d11CommandBuffer->windowDataCount += 1;
  4624. // Return the swapchain texture
  4625. return (SDL_GPUTexture *)&windowData->textureContainer;
  4626. }
  4627. static SDL_GPUTextureFormat D3D11_GetSwapchainTextureFormat(
  4628. SDL_GPURenderer *driverData,
  4629. SDL_Window *window)
  4630. {
  4631. D3D11WindowData *windowData = D3D11_INTERNAL_FetchWindowData(window);
  4632. if (windowData == NULL) {
  4633. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Cannot get swapchain format, window has not been claimed!");
  4634. return SDL_GPU_TEXTUREFORMAT_INVALID;
  4635. }
  4636. return windowData->textureContainer.header.info.format;
  4637. }
  4638. static bool D3D11_SetSwapchainParameters(
  4639. SDL_GPURenderer *driverData,
  4640. SDL_Window *window,
  4641. SDL_GPUSwapchainComposition swapchainComposition,
  4642. SDL_GPUPresentMode presentMode)
  4643. {
  4644. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  4645. D3D11WindowData *windowData = D3D11_INTERNAL_FetchWindowData(window);
  4646. if (windowData == NULL) {
  4647. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Cannot set swapchain parameters on unclaimed window!");
  4648. return false;
  4649. }
  4650. if (!D3D11_SupportsSwapchainComposition(driverData, window, swapchainComposition)) {
  4651. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Swapchain composition not supported!");
  4652. return false;
  4653. }
  4654. if (!D3D11_SupportsPresentMode(driverData, window, presentMode)) {
  4655. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Present mode not supported!");
  4656. return false;
  4657. }
  4658. if (
  4659. swapchainComposition != windowData->swapchainComposition ||
  4660. presentMode != windowData->presentMode) {
  4661. D3D11_Wait(driverData);
  4662. // Recreate the swapchain
  4663. D3D11_INTERNAL_DestroySwapchain(
  4664. renderer,
  4665. windowData);
  4666. return D3D11_INTERNAL_CreateSwapchain(
  4667. renderer,
  4668. windowData,
  4669. swapchainComposition,
  4670. presentMode);
  4671. }
  4672. return true;
  4673. }
  4674. // Submission
  4675. static void D3D11_Submit(
  4676. SDL_GPUCommandBuffer *commandBuffer)
  4677. {
  4678. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  4679. D3D11Renderer *renderer = (D3D11Renderer *)d3d11CommandBuffer->renderer;
  4680. ID3D11CommandList *commandList;
  4681. HRESULT res;
  4682. // Unmap uniform buffers
  4683. for (Uint32 i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  4684. if (d3d11CommandBuffer->vertexUniformBuffers[i] != NULL) {
  4685. ID3D11DeviceContext_Unmap(
  4686. d3d11CommandBuffer->context,
  4687. (ID3D11Resource *)d3d11CommandBuffer->vertexUniformBuffers[i]->buffer,
  4688. 0);
  4689. }
  4690. if (d3d11CommandBuffer->fragmentUniformBuffers[i] != NULL) {
  4691. ID3D11DeviceContext_Unmap(
  4692. d3d11CommandBuffer->context,
  4693. (ID3D11Resource *)d3d11CommandBuffer->fragmentUniformBuffers[i]->buffer,
  4694. 0);
  4695. }
  4696. if (d3d11CommandBuffer->computeUniformBuffers[i] != NULL) {
  4697. ID3D11DeviceContext_Unmap(
  4698. d3d11CommandBuffer->context,
  4699. (ID3D11Resource *)d3d11CommandBuffer->computeUniformBuffers[i]->buffer,
  4700. 0);
  4701. }
  4702. }
  4703. SDL_LockMutex(renderer->contextLock);
  4704. // Notify the command buffer completion query that we have completed recording
  4705. ID3D11DeviceContext_End(
  4706. renderer->immediateContext,
  4707. (ID3D11Asynchronous *)d3d11CommandBuffer->fence->handle);
  4708. // Serialize the commands into the command list
  4709. res = ID3D11DeviceContext_FinishCommandList(
  4710. d3d11CommandBuffer->context,
  4711. 0,
  4712. &commandList);
  4713. ERROR_CHECK("Could not finish command list recording!");
  4714. // Submit the command list to the immediate context
  4715. ID3D11DeviceContext_ExecuteCommandList(
  4716. renderer->immediateContext,
  4717. commandList,
  4718. 0);
  4719. ID3D11CommandList_Release(commandList);
  4720. // Mark the command buffer as submitted
  4721. if (renderer->submittedCommandBufferCount >= renderer->submittedCommandBufferCapacity) {
  4722. renderer->submittedCommandBufferCapacity = renderer->submittedCommandBufferCount + 1;
  4723. renderer->submittedCommandBuffers = SDL_realloc(
  4724. renderer->submittedCommandBuffers,
  4725. sizeof(D3D11CommandBuffer *) * renderer->submittedCommandBufferCapacity);
  4726. }
  4727. renderer->submittedCommandBuffers[renderer->submittedCommandBufferCount] = d3d11CommandBuffer;
  4728. renderer->submittedCommandBufferCount += 1;
  4729. // Present, if applicable
  4730. for (Uint32 i = 0; i < d3d11CommandBuffer->windowDataCount; i += 1) {
  4731. D3D11WindowData *windowData = d3d11CommandBuffer->windowDatas[i];
  4732. Uint32 syncInterval = 1;
  4733. if (windowData->presentMode == SDL_GPU_PRESENTMODE_IMMEDIATE ||
  4734. (renderer->supportsFlipDiscard && windowData->presentMode == SDL_GPU_PRESENTMODE_MAILBOX)) {
  4735. syncInterval = 0;
  4736. }
  4737. Uint32 presentFlags = 0;
  4738. if (renderer->supportsTearing &&
  4739. windowData->presentMode == SDL_GPU_PRESENTMODE_IMMEDIATE) {
  4740. presentFlags = DXGI_PRESENT_ALLOW_TEARING;
  4741. }
  4742. IDXGISwapChain_Present(
  4743. windowData->swapchain,
  4744. syncInterval,
  4745. presentFlags);
  4746. ID3D11Texture2D_Release(windowData->texture.handle);
  4747. windowData->inFlightFences[windowData->frameCounter] = (SDL_GPUFence*)d3d11CommandBuffer->fence;
  4748. (void)SDL_AtomicIncRef(&d3d11CommandBuffer->fence->referenceCount);
  4749. windowData->frameCounter = (windowData->frameCounter + 1) % MAX_FRAMES_IN_FLIGHT;
  4750. }
  4751. // Check if we can perform any cleanups
  4752. for (Sint32 i = renderer->submittedCommandBufferCount - 1; i >= 0; i -= 1) {
  4753. BOOL queryData;
  4754. res = ID3D11DeviceContext_GetData(
  4755. renderer->immediateContext,
  4756. (ID3D11Asynchronous *)renderer->submittedCommandBuffers[i]->fence->handle,
  4757. &queryData,
  4758. sizeof(queryData),
  4759. 0);
  4760. if (res == S_OK) {
  4761. D3D11_INTERNAL_CleanCommandBuffer(
  4762. renderer,
  4763. renderer->submittedCommandBuffers[i]);
  4764. }
  4765. }
  4766. D3D11_INTERNAL_PerformPendingDestroys(renderer);
  4767. SDL_UnlockMutex(renderer->contextLock);
  4768. }
  4769. static SDL_GPUFence *D3D11_SubmitAndAcquireFence(
  4770. SDL_GPUCommandBuffer *commandBuffer)
  4771. {
  4772. D3D11CommandBuffer *d3d11CommandBuffer = (D3D11CommandBuffer *)commandBuffer;
  4773. D3D11Fence *fence = d3d11CommandBuffer->fence;
  4774. d3d11CommandBuffer->autoReleaseFence = 0;
  4775. D3D11_Submit(commandBuffer);
  4776. return (SDL_GPUFence *)fence;
  4777. }
  4778. static void D3D11_Wait(
  4779. SDL_GPURenderer *driverData)
  4780. {
  4781. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  4782. D3D11CommandBuffer *commandBuffer;
  4783. /*
  4784. * Wait for all submitted command buffers to complete.
  4785. * Sort of equivalent to vkDeviceWaitIdle.
  4786. */
  4787. for (Uint32 i = 0; i < renderer->submittedCommandBufferCount; i += 1) {
  4788. D3D11_INTERNAL_WaitForFence(
  4789. renderer,
  4790. renderer->submittedCommandBuffers[i]->fence);
  4791. }
  4792. SDL_LockMutex(renderer->contextLock); // This effectively acts as a lock around submittedCommandBuffers
  4793. for (Sint32 i = renderer->submittedCommandBufferCount - 1; i >= 0; i -= 1) {
  4794. commandBuffer = renderer->submittedCommandBuffers[i];
  4795. D3D11_INTERNAL_CleanCommandBuffer(renderer, commandBuffer);
  4796. }
  4797. D3D11_INTERNAL_PerformPendingDestroys(renderer);
  4798. SDL_UnlockMutex(renderer->contextLock);
  4799. }
  4800. // Format Info
  4801. static bool D3D11_SupportsTextureFormat(
  4802. SDL_GPURenderer *driverData,
  4803. SDL_GPUTextureFormat format,
  4804. SDL_GPUTextureType type,
  4805. SDL_GPUTextureUsageFlags usage)
  4806. {
  4807. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  4808. DXGI_FORMAT dxgiFormat = SDLToD3D11_TextureFormat[format];
  4809. DXGI_FORMAT typelessFormat = D3D11_INTERNAL_GetTypelessFormat(dxgiFormat);
  4810. UINT formatSupport, sampleableFormatSupport;
  4811. HRESULT res;
  4812. res = ID3D11Device_CheckFormatSupport(
  4813. renderer->device,
  4814. dxgiFormat,
  4815. &formatSupport);
  4816. if (FAILED(res)) {
  4817. // Format is apparently unknown
  4818. return false;
  4819. }
  4820. /* Depth textures are stored as typeless textures, but interpreted as color textures for sampling.
  4821. * In order to get supported usages for both interpretations, we have to do this.
  4822. */
  4823. if (typelessFormat != DXGI_FORMAT_UNKNOWN) {
  4824. res = ID3D11Device_CheckFormatSupport(
  4825. renderer->device,
  4826. D3D11_INTERNAL_GetSampleableFormat(typelessFormat),
  4827. &sampleableFormatSupport);
  4828. if (SUCCEEDED(res)) {
  4829. formatSupport |= sampleableFormatSupport;
  4830. }
  4831. }
  4832. // Is the texture type supported?
  4833. if (type == SDL_GPU_TEXTURETYPE_2D && !(formatSupport & D3D11_FORMAT_SUPPORT_TEXTURE2D)) {
  4834. return false;
  4835. }
  4836. if (type == SDL_GPU_TEXTURETYPE_2D_ARRAY && !(formatSupport & D3D11_FORMAT_SUPPORT_TEXTURE2D)) {
  4837. return false;
  4838. }
  4839. if (type == SDL_GPU_TEXTURETYPE_3D && !(formatSupport & D3D11_FORMAT_SUPPORT_TEXTURE3D)) {
  4840. return false;
  4841. }
  4842. if (type == SDL_GPU_TEXTURETYPE_CUBE && !(formatSupport & D3D11_FORMAT_SUPPORT_TEXTURECUBE)) {
  4843. return false;
  4844. }
  4845. if (type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY && !(formatSupport & D3D11_FORMAT_SUPPORT_TEXTURECUBE)) {
  4846. return false;
  4847. }
  4848. // Are the usage flags supported?
  4849. if ((usage & SDL_GPU_TEXTUREUSAGE_SAMPLER) && !(formatSupport & D3D11_FORMAT_SUPPORT_SHADER_SAMPLE)) {
  4850. return false;
  4851. }
  4852. if ((usage & (SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ)) && !(formatSupport & D3D11_FORMAT_SUPPORT_SHADER_LOAD)) {
  4853. return false;
  4854. }
  4855. if ((usage & (SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE) && !(formatSupport & D3D11_FORMAT_SUPPORT_TYPED_UNORDERED_ACCESS_VIEW))) {
  4856. // TYPED_UNORDERED_ACCESS_VIEW implies support for typed UAV stores
  4857. return false;
  4858. }
  4859. if ((usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) && !(formatSupport & D3D11_FORMAT_SUPPORT_RENDER_TARGET)) {
  4860. return false;
  4861. }
  4862. if ((usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) && !(formatSupport & D3D11_FORMAT_SUPPORT_DEPTH_STENCIL)) {
  4863. return false;
  4864. }
  4865. return true;
  4866. }
  4867. // Device Creation
  4868. static bool D3D11_PrepareDriver(SDL_VideoDevice *this)
  4869. {
  4870. void *d3d11_dll, *dxgi_dll;
  4871. PFN_D3D11_CREATE_DEVICE D3D11CreateDeviceFunc;
  4872. D3D_FEATURE_LEVEL levels[] = { D3D_FEATURE_LEVEL_11_1 };
  4873. PFN_CREATE_DXGI_FACTORY1 CreateDxgiFactoryFunc;
  4874. HRESULT res;
  4875. // Can we load D3D11?
  4876. d3d11_dll = SDL_LoadObject(D3D11_DLL);
  4877. if (d3d11_dll == NULL) {
  4878. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "D3D11: Could not find " D3D11_DLL);
  4879. return false;
  4880. }
  4881. D3D11CreateDeviceFunc = (PFN_D3D11_CREATE_DEVICE)SDL_LoadFunction(
  4882. d3d11_dll,
  4883. D3D11_CREATE_DEVICE_FUNC);
  4884. if (D3D11CreateDeviceFunc == NULL) {
  4885. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "D3D11: Could not find function " D3D11_CREATE_DEVICE_FUNC " in " D3D11_DLL);
  4886. SDL_UnloadObject(d3d11_dll);
  4887. return false;
  4888. }
  4889. // Can we create a device?
  4890. res = D3D11CreateDeviceFunc(
  4891. NULL,
  4892. D3D_DRIVER_TYPE_HARDWARE,
  4893. NULL,
  4894. D3D11_CREATE_DEVICE_BGRA_SUPPORT,
  4895. levels,
  4896. SDL_arraysize(levels),
  4897. D3D11_SDK_VERSION,
  4898. NULL,
  4899. NULL,
  4900. NULL);
  4901. SDL_UnloadObject(d3d11_dll);
  4902. if (FAILED(res)) {
  4903. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "D3D11: Could not create D3D11Device with feature level 11_1");
  4904. return false;
  4905. }
  4906. // Can we load DXGI?
  4907. dxgi_dll = SDL_LoadObject(DXGI_DLL);
  4908. if (dxgi_dll == NULL) {
  4909. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "D3D11: Could not find " DXGI_DLL);
  4910. return false;
  4911. }
  4912. CreateDxgiFactoryFunc = (PFN_CREATE_DXGI_FACTORY1)SDL_LoadFunction(
  4913. dxgi_dll,
  4914. CREATE_DXGI_FACTORY1_FUNC);
  4915. SDL_UnloadObject(dxgi_dll); // We're not going to call this function, so we can just unload now.
  4916. if (CreateDxgiFactoryFunc == NULL) {
  4917. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "D3D11: Could not find function " CREATE_DXGI_FACTORY1_FUNC " in " DXGI_DLL);
  4918. return false;
  4919. }
  4920. return true;
  4921. }
  4922. static void D3D11_INTERNAL_TryInitializeDXGIDebug(D3D11Renderer *renderer)
  4923. {
  4924. PFN_DXGI_GET_DEBUG_INTERFACE DXGIGetDebugInterfaceFunc;
  4925. HRESULT res;
  4926. renderer->dxgidebug_dll = SDL_LoadObject(DXGIDEBUG_DLL);
  4927. if (renderer->dxgidebug_dll == NULL) {
  4928. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Could not find " DXGIDEBUG_DLL);
  4929. return;
  4930. }
  4931. DXGIGetDebugInterfaceFunc = (PFN_DXGI_GET_DEBUG_INTERFACE)SDL_LoadFunction(
  4932. renderer->dxgidebug_dll,
  4933. DXGI_GET_DEBUG_INTERFACE_FUNC);
  4934. if (DXGIGetDebugInterfaceFunc == NULL) {
  4935. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Could not load function: " DXGI_GET_DEBUG_INTERFACE_FUNC);
  4936. return;
  4937. }
  4938. res = DXGIGetDebugInterfaceFunc(&D3D_IID_IDXGIDebug, (void **)&renderer->dxgiDebug);
  4939. if (FAILED(res)) {
  4940. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Could not get IDXGIDebug interface");
  4941. }
  4942. #ifdef HAVE_IDXGIINFOQUEUE
  4943. res = DXGIGetDebugInterfaceFunc(&D3D_IID_IDXGIInfoQueue, (void **)&renderer->dxgiInfoQueue);
  4944. if (FAILED(res)) {
  4945. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Could not get IDXGIInfoQueue interface");
  4946. }
  4947. #endif
  4948. }
  4949. static void D3D11_INTERNAL_InitBlitPipelines(
  4950. D3D11Renderer *renderer)
  4951. {
  4952. SDL_GPUShaderCreateInfo shaderCreateInfo;
  4953. SDL_GPUShader *fullscreenVertexShader;
  4954. SDL_GPUShader *blitFrom2DPixelShader;
  4955. SDL_GPUShader *blitFrom2DArrayPixelShader;
  4956. SDL_GPUShader *blitFrom3DPixelShader;
  4957. SDL_GPUShader *blitFromCubePixelShader;
  4958. SDL_GPUShader *blitFromCubeArrayPixelShader;
  4959. SDL_GPUGraphicsPipelineCreateInfo blitPipelineCreateInfo;
  4960. SDL_GPUGraphicsPipeline *blitPipeline;
  4961. SDL_GPUSamplerCreateInfo samplerCreateInfo;
  4962. SDL_GPUColorTargetDescription colorTargetDesc;
  4963. // Fullscreen vertex shader
  4964. SDL_zero(shaderCreateInfo);
  4965. shaderCreateInfo.code = (Uint8 *)D3D11_FullscreenVert;
  4966. shaderCreateInfo.code_size = sizeof(D3D11_FullscreenVert);
  4967. shaderCreateInfo.stage = SDL_GPU_SHADERSTAGE_VERTEX;
  4968. shaderCreateInfo.format = SDL_GPU_SHADERFORMAT_DXBC;
  4969. shaderCreateInfo.entrypoint = "main";
  4970. fullscreenVertexShader = D3D11_CreateShader(
  4971. (SDL_GPURenderer *)renderer,
  4972. &shaderCreateInfo);
  4973. if (fullscreenVertexShader == NULL) {
  4974. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile vertex shader for blit!");
  4975. }
  4976. // BlitFrom2D pixel shader
  4977. shaderCreateInfo.code = (Uint8 *)D3D11_BlitFrom2D;
  4978. shaderCreateInfo.code_size = sizeof(D3D11_BlitFrom2D);
  4979. shaderCreateInfo.stage = SDL_GPU_SHADERSTAGE_FRAGMENT;
  4980. shaderCreateInfo.num_samplers = 1;
  4981. shaderCreateInfo.num_uniform_buffers = 1;
  4982. blitFrom2DPixelShader = D3D11_CreateShader(
  4983. (SDL_GPURenderer *)renderer,
  4984. &shaderCreateInfo);
  4985. if (blitFrom2DPixelShader == NULL) {
  4986. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile BlitFrom2D pixel shader!");
  4987. }
  4988. // BlitFrom2DArray pixel shader
  4989. shaderCreateInfo.code = (Uint8 *)D3D11_BlitFrom2DArray;
  4990. shaderCreateInfo.code_size = sizeof(D3D11_BlitFrom2DArray);
  4991. blitFrom2DArrayPixelShader = D3D11_CreateShader(
  4992. (SDL_GPURenderer *)renderer,
  4993. &shaderCreateInfo);
  4994. if (blitFrom2DArrayPixelShader == NULL) {
  4995. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile BlitFrom2DArray pixel shader!");
  4996. }
  4997. // BlitFrom3D pixel shader
  4998. shaderCreateInfo.code = (Uint8 *)D3D11_BlitFrom3D;
  4999. shaderCreateInfo.code_size = sizeof(D3D11_BlitFrom3D);
  5000. blitFrom3DPixelShader = D3D11_CreateShader(
  5001. (SDL_GPURenderer *)renderer,
  5002. &shaderCreateInfo);
  5003. if (blitFrom3DPixelShader == NULL) {
  5004. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile BlitFrom3D pixel shader!");
  5005. }
  5006. // BlitFromCube pixel shader
  5007. shaderCreateInfo.code = (Uint8 *)D3D11_BlitFromCube;
  5008. shaderCreateInfo.code_size = sizeof(D3D11_BlitFromCube);
  5009. blitFromCubePixelShader = D3D11_CreateShader(
  5010. (SDL_GPURenderer *)renderer,
  5011. &shaderCreateInfo);
  5012. if (blitFromCubePixelShader == NULL) {
  5013. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile BlitFromCube pixel shader!");
  5014. }
  5015. // BlitFromCubeArray pixel shader
  5016. shaderCreateInfo.code = (Uint8 *)D3D11_BlitFromCubeArray;
  5017. shaderCreateInfo.code_size = sizeof(D3D11_BlitFromCubeArray);
  5018. blitFromCubeArrayPixelShader = D3D11_CreateShader(
  5019. (SDL_GPURenderer *)renderer,
  5020. &shaderCreateInfo);
  5021. if (blitFromCubeArrayPixelShader == NULL) {
  5022. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile BlitFromCubeArray pixel shader!");
  5023. }
  5024. // BlitFrom2D pipeline
  5025. SDL_zero(blitPipelineCreateInfo);
  5026. SDL_zero(colorTargetDesc);
  5027. colorTargetDesc.blend_state.color_write_mask = 0xF;
  5028. colorTargetDesc.format = SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; // format doesn't matter in d3d11
  5029. blitPipelineCreateInfo.target_info.color_target_descriptions = &colorTargetDesc;
  5030. blitPipelineCreateInfo.target_info.num_color_targets = 1;
  5031. blitPipelineCreateInfo.target_info.depth_stencil_format = SDL_GPU_TEXTUREFORMAT_D16_UNORM; // arbitrary
  5032. blitPipelineCreateInfo.target_info.has_depth_stencil_target = false;
  5033. blitPipelineCreateInfo.vertex_shader = fullscreenVertexShader;
  5034. blitPipelineCreateInfo.fragment_shader = blitFrom2DPixelShader;
  5035. blitPipelineCreateInfo.multisample_state.sample_count = SDL_GPU_SAMPLECOUNT_1;
  5036. blitPipelineCreateInfo.multisample_state.enable_mask = SDL_FALSE;
  5037. blitPipelineCreateInfo.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
  5038. blitPipeline = D3D11_CreateGraphicsPipeline(
  5039. (SDL_GPURenderer *)renderer,
  5040. &blitPipelineCreateInfo);
  5041. if (blitPipeline == NULL) {
  5042. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create BlitFrom2D pipeline!");
  5043. }
  5044. renderer->blitPipelines[SDL_GPU_TEXTURETYPE_2D].pipeline = blitPipeline;
  5045. renderer->blitPipelines[SDL_GPU_TEXTURETYPE_2D].type = SDL_GPU_TEXTURETYPE_2D;
  5046. renderer->blitPipelines[SDL_GPU_TEXTURETYPE_2D].format = SDL_GPU_TEXTUREFORMAT_INVALID;
  5047. // BlitFrom2DArrayPipeline
  5048. blitPipelineCreateInfo.fragment_shader = blitFrom2DArrayPixelShader;
  5049. blitPipeline = D3D11_CreateGraphicsPipeline(
  5050. (SDL_GPURenderer *)renderer,
  5051. &blitPipelineCreateInfo);
  5052. if (blitPipeline == NULL) {
  5053. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create BlitFrom2DArray pipeline!");
  5054. }
  5055. renderer->blitPipelines[SDL_GPU_TEXTURETYPE_2D_ARRAY].pipeline = blitPipeline;
  5056. renderer->blitPipelines[SDL_GPU_TEXTURETYPE_2D_ARRAY].type = SDL_GPU_TEXTURETYPE_2D_ARRAY;
  5057. renderer->blitPipelines[SDL_GPU_TEXTURETYPE_2D_ARRAY].format = SDL_GPU_TEXTUREFORMAT_INVALID;
  5058. // BlitFrom3DPipeline
  5059. blitPipelineCreateInfo.fragment_shader = blitFrom3DPixelShader;
  5060. blitPipeline = D3D11_CreateGraphicsPipeline(
  5061. (SDL_GPURenderer *)renderer,
  5062. &blitPipelineCreateInfo);
  5063. if (blitPipeline == NULL) {
  5064. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create BlitFrom3D pipeline!");
  5065. }
  5066. renderer->blitPipelines[SDL_GPU_TEXTURETYPE_3D].pipeline = blitPipeline;
  5067. renderer->blitPipelines[SDL_GPU_TEXTURETYPE_3D].type = SDL_GPU_TEXTURETYPE_3D;
  5068. renderer->blitPipelines[SDL_GPU_TEXTURETYPE_3D].format = SDL_GPU_TEXTUREFORMAT_INVALID;
  5069. // BlitFromCubePipeline
  5070. blitPipelineCreateInfo.fragment_shader = blitFromCubePixelShader;
  5071. blitPipeline = D3D11_CreateGraphicsPipeline(
  5072. (SDL_GPURenderer *)renderer,
  5073. &blitPipelineCreateInfo);
  5074. if (blitPipeline == NULL) {
  5075. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create BlitFromCube pipeline!");
  5076. }
  5077. renderer->blitPipelines[SDL_GPU_TEXTURETYPE_CUBE].pipeline = blitPipeline;
  5078. renderer->blitPipelines[SDL_GPU_TEXTURETYPE_CUBE].type = SDL_GPU_TEXTURETYPE_CUBE;
  5079. renderer->blitPipelines[SDL_GPU_TEXTURETYPE_CUBE].format = SDL_GPU_TEXTUREFORMAT_INVALID;
  5080. // BlitFromCubeArrayPipeline
  5081. blitPipelineCreateInfo.fragment_shader = blitFromCubeArrayPixelShader;
  5082. blitPipeline = D3D11_CreateGraphicsPipeline(
  5083. (SDL_GPURenderer *)renderer,
  5084. &blitPipelineCreateInfo);
  5085. if (blitPipeline == NULL) {
  5086. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create BlitFromCubeArray pipeline!");
  5087. }
  5088. renderer->blitPipelines[SDL_GPU_TEXTURETYPE_CUBE_ARRAY].pipeline = blitPipeline;
  5089. renderer->blitPipelines[SDL_GPU_TEXTURETYPE_CUBE_ARRAY].type = SDL_GPU_TEXTURETYPE_CUBE_ARRAY;
  5090. renderer->blitPipelines[SDL_GPU_TEXTURETYPE_CUBE_ARRAY].format = SDL_GPU_TEXTUREFORMAT_INVALID;
  5091. // Create samplers
  5092. samplerCreateInfo.address_mode_u = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
  5093. samplerCreateInfo.address_mode_v = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
  5094. samplerCreateInfo.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
  5095. samplerCreateInfo.enable_anisotropy = 0;
  5096. samplerCreateInfo.enable_compare = 0;
  5097. samplerCreateInfo.mag_filter = SDL_GPU_FILTER_NEAREST;
  5098. samplerCreateInfo.min_filter = SDL_GPU_FILTER_NEAREST;
  5099. samplerCreateInfo.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
  5100. samplerCreateInfo.mip_lod_bias = 0.0f;
  5101. samplerCreateInfo.min_lod = 0;
  5102. samplerCreateInfo.max_lod = 1000;
  5103. renderer->blitNearestSampler = D3D11_CreateSampler(
  5104. (SDL_GPURenderer *)renderer,
  5105. &samplerCreateInfo);
  5106. if (renderer->blitNearestSampler == NULL) {
  5107. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create blit nearest sampler!");
  5108. }
  5109. samplerCreateInfo.mag_filter = SDL_GPU_FILTER_LINEAR;
  5110. samplerCreateInfo.min_filter = SDL_GPU_FILTER_LINEAR;
  5111. samplerCreateInfo.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_LINEAR;
  5112. renderer->blitLinearSampler = D3D11_CreateSampler(
  5113. (SDL_GPURenderer *)renderer,
  5114. &samplerCreateInfo);
  5115. if (renderer->blitLinearSampler == NULL) {
  5116. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create blit linear sampler!");
  5117. }
  5118. // Clean up
  5119. D3D11_ReleaseShader((SDL_GPURenderer *)renderer, fullscreenVertexShader);
  5120. D3D11_ReleaseShader((SDL_GPURenderer *)renderer, blitFrom2DPixelShader);
  5121. D3D11_ReleaseShader((SDL_GPURenderer *)renderer, blitFrom2DArrayPixelShader);
  5122. D3D11_ReleaseShader((SDL_GPURenderer *)renderer, blitFrom3DPixelShader);
  5123. D3D11_ReleaseShader((SDL_GPURenderer *)renderer, blitFromCubePixelShader);
  5124. D3D11_ReleaseShader((SDL_GPURenderer *)renderer, blitFromCubeArrayPixelShader);
  5125. }
  5126. static void D3D11_INTERNAL_DestroyBlitPipelines(
  5127. SDL_GPURenderer *driverData)
  5128. {
  5129. D3D11Renderer *renderer = (D3D11Renderer *)driverData;
  5130. D3D11_ReleaseSampler(driverData, renderer->blitLinearSampler);
  5131. D3D11_ReleaseSampler(driverData, renderer->blitNearestSampler);
  5132. for (int i = 0; i < SDL_arraysize(renderer->blitPipelines); i += 1) {
  5133. D3D11_ReleaseGraphicsPipeline(driverData, renderer->blitPipelines[i].pipeline);
  5134. }
  5135. }
  5136. static SDL_GPUDevice *D3D11_CreateDevice(bool debugMode, bool preferLowPower, SDL_PropertiesID props)
  5137. {
  5138. D3D11Renderer *renderer;
  5139. PFN_CREATE_DXGI_FACTORY1 CreateDxgiFactoryFunc;
  5140. PFN_D3D11_CREATE_DEVICE D3D11CreateDeviceFunc;
  5141. D3D_FEATURE_LEVEL levels[] = { D3D_FEATURE_LEVEL_11_1 };
  5142. IDXGIFactory4 *factory4;
  5143. IDXGIFactory5 *factory5;
  5144. IDXGIFactory6 *factory6;
  5145. Uint32 flags;
  5146. DXGI_ADAPTER_DESC1 adapterDesc;
  5147. HRESULT res;
  5148. SDL_GPUDevice *result;
  5149. // Allocate and zero out the renderer
  5150. renderer = (D3D11Renderer *)SDL_calloc(1, sizeof(D3D11Renderer));
  5151. // Load the DXGI library
  5152. renderer->dxgi_dll = SDL_LoadObject(DXGI_DLL);
  5153. if (renderer->dxgi_dll == NULL) {
  5154. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Could not find " DXGI_DLL);
  5155. return NULL;
  5156. }
  5157. // Load the CreateDXGIFactory1 function
  5158. CreateDxgiFactoryFunc = (PFN_CREATE_DXGI_FACTORY1)SDL_LoadFunction(
  5159. renderer->dxgi_dll,
  5160. CREATE_DXGI_FACTORY1_FUNC);
  5161. if (CreateDxgiFactoryFunc == NULL) {
  5162. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Could not load function: " CREATE_DXGI_FACTORY1_FUNC);
  5163. return NULL;
  5164. }
  5165. // Create the DXGI factory
  5166. res = CreateDxgiFactoryFunc(
  5167. &D3D_IID_IDXGIFactory1,
  5168. (void **)&renderer->factory);
  5169. ERROR_CHECK_RETURN("Could not create DXGIFactory", NULL);
  5170. // Check for flip-model discard support (supported on Windows 10+)
  5171. res = IDXGIFactory1_QueryInterface(
  5172. renderer->factory,
  5173. &D3D_IID_IDXGIFactory4,
  5174. (void **)&factory4);
  5175. if (SUCCEEDED(res)) {
  5176. renderer->supportsFlipDiscard = 1;
  5177. IDXGIFactory4_Release(factory4);
  5178. }
  5179. // Check for explicit tearing support
  5180. res = IDXGIFactory1_QueryInterface(
  5181. renderer->factory,
  5182. &D3D_IID_IDXGIFactory5,
  5183. (void **)&factory5);
  5184. if (SUCCEEDED(res)) {
  5185. res = IDXGIFactory5_CheckFeatureSupport(
  5186. factory5,
  5187. DXGI_FEATURE_PRESENT_ALLOW_TEARING,
  5188. &renderer->supportsTearing,
  5189. sizeof(renderer->supportsTearing));
  5190. if (FAILED(res)) {
  5191. renderer->supportsTearing = FALSE;
  5192. }
  5193. IDXGIFactory5_Release(factory5);
  5194. }
  5195. // Select the appropriate device for rendering
  5196. res = IDXGIAdapter1_QueryInterface(
  5197. renderer->factory,
  5198. &D3D_IID_IDXGIFactory6,
  5199. (void **)&factory6);
  5200. if (SUCCEEDED(res)) {
  5201. IDXGIFactory6_EnumAdapterByGpuPreference(
  5202. factory6,
  5203. 0,
  5204. preferLowPower ? DXGI_GPU_PREFERENCE_MINIMUM_POWER : DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE,
  5205. &D3D_IID_IDXGIAdapter1,
  5206. (void **)&renderer->adapter);
  5207. IDXGIFactory6_Release(factory6);
  5208. } else {
  5209. IDXGIFactory1_EnumAdapters1(
  5210. renderer->factory,
  5211. 0,
  5212. &renderer->adapter);
  5213. }
  5214. // Get information about the selected adapter. Used for logging info.
  5215. IDXGIAdapter1_GetDesc1(renderer->adapter, &adapterDesc);
  5216. // Initialize the DXGI debug layer, if applicable
  5217. if (debugMode) {
  5218. D3D11_INTERNAL_TryInitializeDXGIDebug(renderer);
  5219. }
  5220. // Load the D3D library
  5221. renderer->d3d11_dll = SDL_LoadObject(D3D11_DLL);
  5222. if (renderer->d3d11_dll == NULL) {
  5223. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Could not find " D3D11_DLL);
  5224. return NULL;
  5225. }
  5226. // Load the CreateDevice function
  5227. D3D11CreateDeviceFunc = (PFN_D3D11_CREATE_DEVICE)SDL_LoadFunction(
  5228. renderer->d3d11_dll,
  5229. D3D11_CREATE_DEVICE_FUNC);
  5230. if (D3D11CreateDeviceFunc == NULL) {
  5231. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Could not load function: " D3D11_CREATE_DEVICE_FUNC);
  5232. return NULL;
  5233. }
  5234. // Set up device flags
  5235. flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
  5236. if (debugMode) {
  5237. flags |= D3D11_CREATE_DEVICE_DEBUG;
  5238. }
  5239. // Create the device
  5240. ID3D11Device *d3d11Device;
  5241. tryCreateDevice:
  5242. res = D3D11CreateDeviceFunc(
  5243. (IDXGIAdapter *)renderer->adapter,
  5244. D3D_DRIVER_TYPE_UNKNOWN, // Must be UNKNOWN if adapter is non-null according to spec
  5245. NULL,
  5246. flags,
  5247. levels,
  5248. SDL_arraysize(levels),
  5249. D3D11_SDK_VERSION,
  5250. &d3d11Device,
  5251. NULL,
  5252. &renderer->immediateContext);
  5253. if (FAILED(res) && debugMode) {
  5254. // If device creation failed, and we're in debug mode, remove the debug flag and try again.
  5255. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Creating device in debug mode failed with error " HRESULT_FMT ". Trying non-debug.", res);
  5256. flags &= ~D3D11_CREATE_DEVICE_DEBUG;
  5257. debugMode = 0;
  5258. goto tryCreateDevice;
  5259. }
  5260. ERROR_CHECK_RETURN("Could not create D3D11 device", NULL);
  5261. // The actual device we want is the ID3D11Device1 interface...
  5262. res = ID3D11Device_QueryInterface(
  5263. d3d11Device,
  5264. &D3D_IID_ID3D11Device1,
  5265. (void **)&renderer->device);
  5266. ERROR_CHECK_RETURN("Could not get ID3D11Device1 interface", NULL);
  5267. // Release the old device interface, we don't need it anymore
  5268. ID3D11Device_Release(d3d11Device);
  5269. #ifdef HAVE_IDXGIINFOQUEUE
  5270. // Set up the info queue
  5271. if (renderer->dxgiInfoQueue) {
  5272. DXGI_INFO_QUEUE_MESSAGE_SEVERITY sevList[] = {
  5273. DXGI_INFO_QUEUE_MESSAGE_SEVERITY_CORRUPTION,
  5274. DXGI_INFO_QUEUE_MESSAGE_SEVERITY_ERROR,
  5275. DXGI_INFO_QUEUE_MESSAGE_SEVERITY_WARNING,
  5276. // DXGI_INFO_QUEUE_MESSAGE_SEVERITY_INFO, // This can be a bit much, so toggle as needed for debugging.
  5277. DXGI_INFO_QUEUE_MESSAGE_SEVERITY_MESSAGE
  5278. };
  5279. DXGI_INFO_QUEUE_FILTER filter = { 0 };
  5280. filter.AllowList.NumSeverities = SDL_arraysize(sevList);
  5281. filter.AllowList.pSeverityList = sevList;
  5282. IDXGIInfoQueue_PushStorageFilter(
  5283. renderer->dxgiInfoQueue,
  5284. D3D_IID_DXGI_DEBUG_ALL,
  5285. &filter);
  5286. }
  5287. #endif
  5288. // Print driver info
  5289. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "SDL GPU Driver: D3D11");
  5290. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "D3D11 Adapter: %S", adapterDesc.Description);
  5291. // Create mutexes
  5292. renderer->contextLock = SDL_CreateMutex();
  5293. renderer->acquireCommandBufferLock = SDL_CreateMutex();
  5294. renderer->acquireUniformBufferLock = SDL_CreateMutex();
  5295. renderer->fenceLock = SDL_CreateMutex();
  5296. renderer->windowLock = SDL_CreateMutex();
  5297. // Initialize miscellaneous renderer members
  5298. renderer->debugMode = (flags & D3D11_CREATE_DEVICE_DEBUG);
  5299. // Create command buffer pool
  5300. D3D11_INTERNAL_AllocateCommandBuffers(renderer, 2);
  5301. // Create fence pool
  5302. renderer->availableFenceCapacity = 2;
  5303. renderer->availableFences = SDL_malloc(
  5304. sizeof(D3D11Fence *) * renderer->availableFenceCapacity);
  5305. // Create uniform buffer pool
  5306. renderer->uniformBufferPoolCapacity = 32;
  5307. renderer->uniformBufferPoolCount = 32;
  5308. renderer->uniformBufferPool = SDL_malloc(
  5309. renderer->uniformBufferPoolCapacity * sizeof(D3D11UniformBuffer *));
  5310. for (Uint32 i = 0; i < renderer->uniformBufferPoolCount; i += 1) {
  5311. renderer->uniformBufferPool[i] = D3D11_INTERNAL_CreateUniformBuffer(
  5312. renderer,
  5313. UNIFORM_BUFFER_SIZE);
  5314. }
  5315. // Create deferred destroy arrays
  5316. renderer->transferBufferContainersToDestroyCapacity = 2;
  5317. renderer->transferBufferContainersToDestroyCount = 0;
  5318. renderer->transferBufferContainersToDestroy = SDL_malloc(
  5319. renderer->transferBufferContainersToDestroyCapacity * sizeof(D3D11TransferBufferContainer *));
  5320. renderer->bufferContainersToDestroyCapacity = 2;
  5321. renderer->bufferContainersToDestroyCount = 0;
  5322. renderer->bufferContainersToDestroy = SDL_malloc(
  5323. renderer->bufferContainersToDestroyCapacity * sizeof(D3D11BufferContainer *));
  5324. renderer->textureContainersToDestroyCapacity = 2;
  5325. renderer->textureContainersToDestroyCount = 0;
  5326. renderer->textureContainersToDestroy = SDL_malloc(
  5327. renderer->textureContainersToDestroyCapacity * sizeof(D3D11TextureContainer *));
  5328. // Create claimed window list
  5329. renderer->claimedWindowCapacity = 1;
  5330. renderer->claimedWindows = SDL_malloc(
  5331. sizeof(D3D11WindowData *) * renderer->claimedWindowCapacity);
  5332. // Initialize null states
  5333. SDL_zeroa(renderer->nullRTVs);
  5334. SDL_zeroa(renderer->nullSRVs);
  5335. SDL_zeroa(renderer->nullSamplers);
  5336. SDL_zeroa(renderer->nullUAVs);
  5337. // Initialize built-in pipelines
  5338. D3D11_INTERNAL_InitBlitPipelines(renderer);
  5339. // Create the SDL_GPU Device
  5340. result = (SDL_GPUDevice *)SDL_malloc(sizeof(SDL_GPUDevice));
  5341. ASSIGN_DRIVER(D3D11)
  5342. result->driverData = (SDL_GPURenderer *)renderer;
  5343. return result;
  5344. }
  5345. SDL_GPUBootstrap D3D11Driver = {
  5346. "direct3d11",
  5347. SDL_GPU_SHADERFORMAT_DXBC,
  5348. D3D11_PrepareDriver,
  5349. D3D11_CreateDevice
  5350. };
  5351. #endif // SDL_GPU_D3D11