SDL_gpu_d3d11.c 221 KB

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