SDL_gpu_d3d11.c 211 KB

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