SDL_gpu_d3d12.c 308 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515
  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_D3D12
  20. #include "../../core/windows/SDL_windows.h"
  21. #include "../../video/directx/SDL_d3d12.h"
  22. #include "../SDL_sysgpu.h"
  23. #include "SDL_hashtable.h"
  24. #ifdef __IDXGIInfoQueue_INTERFACE_DEFINED__
  25. #define HAVE_IDXGIINFOQUEUE
  26. #endif
  27. // Built-in shaders, compiled with compile_shaders.bat
  28. #define g_FullscreenVert D3D12_FullscreenVert
  29. #define g_BlitFrom2D D3D12_BlitFrom2D
  30. #define g_BlitFrom2DArray D3D12_BlitFrom2DArray
  31. #define g_BlitFrom3D D3D12_BlitFrom3D
  32. #define g_BlitFromCube D3D12_BlitFromCube
  33. #define g_BlitFromCubeArray D3D12_BlitFromCubeArray
  34. #if defined(SDL_PLATFORM_XBOXSERIES)
  35. #include "D3D12_Blit_Series.h"
  36. #elif defined(SDL_PLATFORM_XBOXONE)
  37. #include "D3D12_Blit_One.h"
  38. #else
  39. #include "D3D12_Blit.h"
  40. #endif
  41. #undef g_FullscreenVert
  42. #undef g_BlitFrom2D
  43. #undef g_BlitFrom2DArray
  44. #undef g_BlitFrom3D
  45. #undef g_BlitFromCube
  46. #undef g_BlitFromCubeArray
  47. // Macros
  48. #define SET_ERROR(fmt, msg) \
  49. if (renderer->debug_mode) { \
  50. SDL_LogError(SDL_LOG_CATEGORY_GPU, fmt, msg); \
  51. } \
  52. SDL_SetError(fmt, msg);
  53. #define SET_ERROR_AND_RETURN(fmt, msg, ret) \
  54. if (renderer->debug_mode) { \
  55. SDL_LogError(SDL_LOG_CATEGORY_GPU, fmt, msg); \
  56. } \
  57. SDL_SetError(fmt, msg); \
  58. return ret; \
  59. #define SET_STRING_ERROR_AND_RETURN(msg, ret) SET_ERROR_AND_RETURN("%s", msg, ret)
  60. #define CHECK_D3D12_ERROR_AND_RETURN(msg, ret) \
  61. if (FAILED(res)) { \
  62. D3D12_INTERNAL_SetError(renderer, msg, res); \
  63. return ret; \
  64. }
  65. // Defines
  66. #if defined(_WIN32)
  67. #if defined(SDL_PLATFORM_XBOXSERIES)
  68. #define D3D12_DLL "d3d12_xs.dll"
  69. #elif defined(SDL_PLATFORM_XBOXONE)
  70. #define D3D12_DLL "d3d12_x.dll"
  71. #else
  72. #define D3D12_DLL "d3d12.dll"
  73. #endif
  74. #define DXGI_DLL "dxgi.dll"
  75. #define DXGIDEBUG_DLL "dxgidebug.dll"
  76. #elif defined(__APPLE__)
  77. #define D3D12_DLL "libdxvk_d3d12.dylib"
  78. #define DXGI_DLL "libdxvk_dxgi.dylib"
  79. #define DXGIDEBUG_DLL "libdxvk_dxgidebug.dylib"
  80. #else
  81. #define D3D12_DLL "libdxvk_d3d12.so"
  82. #define DXGI_DLL "libdxvk_dxgi.so"
  83. #define DXGIDEBUG_DLL "libdxvk_dxgidebug.so"
  84. #endif
  85. #define D3D12_CREATE_DEVICE_FUNC "D3D12CreateDevice"
  86. #define D3D12_SERIALIZE_ROOT_SIGNATURE_FUNC "D3D12SerializeRootSignature"
  87. #define CREATE_DXGI_FACTORY1_FUNC "CreateDXGIFactory1"
  88. #define DXGI_GET_DEBUG_INTERFACE_FUNC "DXGIGetDebugInterface"
  89. #define D3D12_GET_DEBUG_INTERFACE_FUNC "D3D12GetDebugInterface"
  90. #define WINDOW_PROPERTY_DATA "SDL_GPUD3D12WindowPropertyData"
  91. #define D3D_FEATURE_LEVEL_CHOICE D3D_FEATURE_LEVEL_11_1
  92. #define D3D_FEATURE_LEVEL_CHOICE_STR "11_1"
  93. // FIXME: just use sysgpu.h defines
  94. #define MAX_ROOT_SIGNATURE_PARAMETERS 64
  95. #define VIEW_GPU_DESCRIPTOR_COUNT 65536
  96. #define SAMPLER_GPU_DESCRIPTOR_COUNT 2048
  97. #define VIEW_SAMPLER_STAGING_DESCRIPTOR_COUNT 1000000
  98. #define TARGET_STAGING_DESCRIPTOR_COUNT 1000000
  99. #define D3D12_FENCE_UNSIGNALED_VALUE 0
  100. #define D3D12_FENCE_SIGNAL_VALUE 1
  101. #define SDL_GPU_SHADERSTAGE_COMPUTE (SDL_GPUShaderStage)2
  102. #define EXPAND_ELEMENTS_IF_NEEDED(arr, initialValue, type) \
  103. if (arr->count == arr->capacity) { \
  104. if (arr->capacity == 0) { \
  105. arr->capacity = initialValue; \
  106. } else { \
  107. arr->capacity *= 2; \
  108. } \
  109. arr->elements = (type *)SDL_realloc( \
  110. arr->elements, \
  111. arr->capacity * sizeof(type)); \
  112. }
  113. #ifdef _WIN32
  114. #define HRESULT_FMT "(0x%08lX)"
  115. #else
  116. #define HRESULT_FMT "(0x%08X)"
  117. #endif
  118. // Function Pointer Signatures
  119. typedef HRESULT(WINAPI *PFN_CREATE_DXGI_FACTORY1)(const GUID *riid, void **ppFactory);
  120. typedef HRESULT(WINAPI *PFN_DXGI_GET_DEBUG_INTERFACE)(const GUID *riid, void **ppDebug);
  121. // IIDs (from https://www.magnumdb.com/)
  122. static const IID D3D_IID_IDXGIFactory1 = { 0x770aae78, 0xf26f, 0x4dba, { 0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87 } };
  123. static const IID D3D_IID_IDXGIFactory4 = { 0x1bc6ea02, 0xef36, 0x464f, { 0xbf, 0x0c, 0x21, 0xca, 0x39, 0xe5, 0x16, 0x8a } };
  124. static const IID D3D_IID_IDXGIFactory5 = { 0x7632e1f5, 0xee65, 0x4dca, { 0x87, 0xfd, 0x84, 0xcd, 0x75, 0xf8, 0x83, 0x8d } };
  125. static const IID D3D_IID_IDXGIFactory6 = { 0xc1b6694f, 0xff09, 0x44a9, { 0xb0, 0x3c, 0x77, 0x90, 0x0a, 0x0a, 0x1d, 0x17 } };
  126. static const IID D3D_IID_IDXGIAdapter1 = { 0x29038f61, 0x3839, 0x4626, { 0x91, 0xfd, 0x08, 0x68, 0x79, 0x01, 0x1a, 0x05 } };
  127. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  128. static const IID D3D_IID_IDXGIDevice1 = { 0x77db970f, 0x6276, 0x48ba, { 0xba, 0x28, 0x07, 0x01, 0x43, 0xb4, 0x39, 0x2c } };
  129. #endif
  130. static const IID D3D_IID_IDXGISwapChain3 = { 0x94d99bdb, 0xf1f8, 0x4ab0, { 0xb2, 0x36, 0x7d, 0xa0, 0x17, 0x0e, 0xda, 0xb1 } };
  131. #ifdef HAVE_IDXGIINFOQUEUE
  132. static const IID D3D_IID_IDXGIDebug = { 0x119e7452, 0xde9e, 0x40fe, { 0x88, 0x06, 0x88, 0xf9, 0x0c, 0x12, 0xb4, 0x41 } };
  133. static const IID D3D_IID_IDXGIInfoQueue = { 0xd67441c7, 0x672a, 0x476f, { 0x9e, 0x82, 0xcd, 0x55, 0xb4, 0x49, 0x49, 0xce } };
  134. #endif
  135. static const GUID D3D_IID_DXGI_DEBUG_ALL = { 0xe48ae283, 0xda80, 0x490b, { 0x87, 0xe6, 0x43, 0xe9, 0xa9, 0xcf, 0xda, 0x08 } };
  136. static const GUID D3D_IID_D3DDebugObjectName = { 0x429b8c22, 0x9188, 0x4b0c, { 0x87, 0x42, 0xac, 0xb0, 0xbf, 0x85, 0xc2, 0x00 } };
  137. static const IID D3D_IID_ID3D12Device = { 0x189819f1, 0x1db6, 0x4b57, { 0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7 } };
  138. static const IID D3D_IID_ID3D12CommandQueue = { 0x0ec870a6, 0x5d7e, 0x4c22, { 0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed } };
  139. static const IID D3D_IID_ID3D12DescriptorHeap = { 0x8efb471d, 0x616c, 0x4f49, { 0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51 } };
  140. static const IID D3D_IID_ID3D12Resource = { 0x696442be, 0xa72e, 0x4059, { 0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad } };
  141. static const IID D3D_IID_ID3D12CommandAllocator = { 0x6102dee4, 0xaf59, 0x4b09, { 0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24 } };
  142. static const IID D3D_IID_ID3D12CommandList = { 0x7116d91c, 0xe7e4, 0x47ce, { 0xb8, 0xc6, 0xec, 0x81, 0x68, 0xf4, 0x37, 0xe5 } };
  143. static const IID D3D_IID_ID3D12GraphicsCommandList = { 0x5b160d0f, 0xac1b, 0x4185, { 0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55 } };
  144. static const IID D3D_IID_ID3D12Fence = { 0x0a753dcf, 0xc4d8, 0x4b91, { 0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76 } };
  145. static const IID D3D_IID_ID3D12RootSignature = { 0xc54a6b66, 0x72df, 0x4ee8, { 0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14 } };
  146. static const IID D3D_IID_ID3D12CommandSignature = { 0xc36a797c, 0xec80, 0x4f0a, { 0x89, 0x85, 0xa7, 0xb2, 0x47, 0x50, 0x82, 0xd1 } };
  147. static const IID D3D_IID_ID3D12PipelineState = { 0x765a30f3, 0xf624, 0x4c6f, { 0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45 } };
  148. static const IID D3D_IID_ID3D12Debug = { 0x344488b7, 0x6846, 0x474b, { 0xb9, 0x89, 0xf0, 0x27, 0x44, 0x82, 0x45, 0xe0 } };
  149. static const IID D3D_IID_ID3D12InfoQueue = { 0x0742a90b, 0xc387, 0x483f, { 0xb9, 0x46, 0x30, 0xa7, 0xe4, 0xe6, 0x14, 0x58 } };
  150. // Enums
  151. typedef enum D3D12BufferType
  152. {
  153. D3D12_BUFFER_TYPE_GPU,
  154. D3D12_BUFFER_TYPE_UNIFORM,
  155. D3D12_BUFFER_TYPE_UPLOAD,
  156. D3D12_BUFFER_TYPE_DOWNLOAD
  157. } D3D12BufferType;
  158. // Conversions
  159. static SDL_GPUTextureFormat SwapchainCompositionToSDLTextureFormat[] = {
  160. SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, // SDR
  161. SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB, // SDR_SRGB
  162. SDL_GPU_TEXTUREFORMAT_R16G16B16A16_FLOAT, // HDR
  163. SDL_GPU_TEXTUREFORMAT_R10G10B10A2_UNORM, // HDR_ADVANCED
  164. };
  165. static DXGI_FORMAT SwapchainCompositionToTextureFormat[] = {
  166. DXGI_FORMAT_B8G8R8A8_UNORM, // SDR
  167. DXGI_FORMAT_B8G8R8A8_UNORM, /* SDR_SRGB */ // NOTE: The RTV uses the sRGB format
  168. DXGI_FORMAT_R16G16B16A16_FLOAT, // HDR
  169. DXGI_FORMAT_R10G10B10A2_UNORM, // HDR_ADVANCED
  170. };
  171. static DXGI_COLOR_SPACE_TYPE SwapchainCompositionToColorSpace[] = {
  172. DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709, // SDR
  173. DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709, // SDR_SRGB
  174. DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709, // HDR
  175. DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020 // HDR_ADVANCED
  176. };
  177. static D3D12_BLEND SDLToD3D12_BlendFactor[] = {
  178. D3D12_BLEND_ZERO, // INVALID
  179. D3D12_BLEND_ZERO, // ZERO
  180. D3D12_BLEND_ONE, // ONE
  181. D3D12_BLEND_SRC_COLOR, // SRC_COLOR
  182. D3D12_BLEND_INV_SRC_COLOR, // ONE_MINUS_SRC_COLOR
  183. D3D12_BLEND_DEST_COLOR, // DST_COLOR
  184. D3D12_BLEND_INV_DEST_COLOR, // ONE_MINUS_DST_COLOR
  185. D3D12_BLEND_SRC_ALPHA, // SRC_ALPHA
  186. D3D12_BLEND_INV_SRC_ALPHA, // ONE_MINUS_SRC_ALPHA
  187. D3D12_BLEND_DEST_ALPHA, // DST_ALPHA
  188. D3D12_BLEND_INV_DEST_ALPHA, // ONE_MINUS_DST_ALPHA
  189. D3D12_BLEND_BLEND_FACTOR, // CONSTANT_COLOR
  190. D3D12_BLEND_INV_BLEND_FACTOR, // ONE_MINUS_CONSTANT_COLOR
  191. D3D12_BLEND_SRC_ALPHA_SAT, // SRC_ALPHA_SATURATE
  192. };
  193. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_BlendFactor, SDL_arraysize(SDLToD3D12_BlendFactor) == SDL_GPU_BLENDFACTOR_MAX_ENUM_VALUE);
  194. static D3D12_BLEND SDLToD3D12_BlendFactorAlpha[] = {
  195. D3D12_BLEND_ZERO, // INVALID
  196. D3D12_BLEND_ZERO, // ZERO
  197. D3D12_BLEND_ONE, // ONE
  198. D3D12_BLEND_SRC_ALPHA, // SRC_COLOR
  199. D3D12_BLEND_INV_SRC_ALPHA, // ONE_MINUS_SRC_COLOR
  200. D3D12_BLEND_DEST_ALPHA, // DST_COLOR
  201. D3D12_BLEND_INV_DEST_ALPHA, // ONE_MINUS_DST_COLOR
  202. D3D12_BLEND_SRC_ALPHA, // SRC_ALPHA
  203. D3D12_BLEND_INV_SRC_ALPHA, // ONE_MINUS_SRC_ALPHA
  204. D3D12_BLEND_DEST_ALPHA, // DST_ALPHA
  205. D3D12_BLEND_INV_DEST_ALPHA, // ONE_MINUS_DST_ALPHA
  206. D3D12_BLEND_BLEND_FACTOR, // CONSTANT_COLOR
  207. D3D12_BLEND_INV_BLEND_FACTOR, // ONE_MINUS_CONSTANT_COLOR
  208. D3D12_BLEND_SRC_ALPHA_SAT, // SRC_ALPHA_SATURATE
  209. };
  210. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_BlendFactorAlpha, SDL_arraysize(SDLToD3D12_BlendFactorAlpha) == SDL_GPU_BLENDFACTOR_MAX_ENUM_VALUE);
  211. static D3D12_BLEND_OP SDLToD3D12_BlendOp[] = {
  212. D3D12_BLEND_OP_ADD, // INVALID
  213. D3D12_BLEND_OP_ADD, // ADD
  214. D3D12_BLEND_OP_SUBTRACT, // SUBTRACT
  215. D3D12_BLEND_OP_REV_SUBTRACT, // REVERSE_SUBTRACT
  216. D3D12_BLEND_OP_MIN, // MIN
  217. D3D12_BLEND_OP_MAX // MAX
  218. };
  219. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_BlendOp, SDL_arraysize(SDLToD3D12_BlendOp) == SDL_GPU_BLENDOP_MAX_ENUM_VALUE);
  220. static DXGI_FORMAT SDLToD3D12_TextureFormat[] = {
  221. DXGI_FORMAT_UNKNOWN, // INVALID
  222. DXGI_FORMAT_A8_UNORM, // A8_UNORM
  223. DXGI_FORMAT_R8_UNORM, // R8_UNORM
  224. DXGI_FORMAT_R8G8_UNORM, // R8G8_UNORM
  225. DXGI_FORMAT_R8G8B8A8_UNORM, // R8G8B8A8_UNORM
  226. DXGI_FORMAT_R16_UNORM, // R16_UNORM
  227. DXGI_FORMAT_R16G16_UNORM, // R16G16_UNORM
  228. DXGI_FORMAT_R16G16B16A16_UNORM, // R16G16B16A16_UNORM
  229. DXGI_FORMAT_R10G10B10A2_UNORM, // R10G10B10A2_UNORM
  230. DXGI_FORMAT_B5G6R5_UNORM, // B5G6R5_UNORM
  231. DXGI_FORMAT_B5G5R5A1_UNORM, // B5G5R5A1_UNORM
  232. DXGI_FORMAT_B4G4R4A4_UNORM, // B4G4R4A4_UNORM
  233. DXGI_FORMAT_B8G8R8A8_UNORM, // B8G8R8A8_UNORM
  234. DXGI_FORMAT_BC1_UNORM, // BC1_UNORM
  235. DXGI_FORMAT_BC2_UNORM, // BC2_UNORM
  236. DXGI_FORMAT_BC3_UNORM, // BC3_UNORM
  237. DXGI_FORMAT_BC4_UNORM, // BC4_UNORM
  238. DXGI_FORMAT_BC5_UNORM, // BC5_UNORM
  239. DXGI_FORMAT_BC7_UNORM, // BC7_UNORM
  240. DXGI_FORMAT_BC6H_SF16, // BC6H_FLOAT
  241. DXGI_FORMAT_BC6H_UF16, // BC6H_UFLOAT
  242. DXGI_FORMAT_R8_SNORM, // R8_SNORM
  243. DXGI_FORMAT_R8G8_SNORM, // R8G8_SNORM
  244. DXGI_FORMAT_R8G8B8A8_SNORM, // R8G8B8A8_SNORM
  245. DXGI_FORMAT_R16_SNORM, // R16_SNORM
  246. DXGI_FORMAT_R16G16_SNORM, // R16G16_SNORM
  247. DXGI_FORMAT_R16G16B16A16_SNORM, // R16G16B16A16_SNORM
  248. DXGI_FORMAT_R16_FLOAT, // R16_FLOAT
  249. DXGI_FORMAT_R16G16_FLOAT, // R16G16_FLOAT
  250. DXGI_FORMAT_R16G16B16A16_FLOAT, // R16G16B16A16_FLOAT
  251. DXGI_FORMAT_R32_FLOAT, // R32_FLOAT
  252. DXGI_FORMAT_R32G32_FLOAT, // R32G32_FLOAT
  253. DXGI_FORMAT_R32G32B32A32_FLOAT, // R32G32B32A32_FLOAT
  254. DXGI_FORMAT_R11G11B10_FLOAT, // R11G11B10_UFLOAT
  255. DXGI_FORMAT_R8_UINT, // R8_UINT
  256. DXGI_FORMAT_R8G8_UINT, // R8G8_UINT
  257. DXGI_FORMAT_R8G8B8A8_UINT, // R8G8B8A8_UINT
  258. DXGI_FORMAT_R16_UINT, // R16_UINT
  259. DXGI_FORMAT_R16G16_UINT, // R16G16_UINT
  260. DXGI_FORMAT_R16G16B16A16_UINT, // R16G16B16A16_UINT
  261. DXGI_FORMAT_R32_UINT, // R32_UINT
  262. DXGI_FORMAT_R32G32_UINT, // R32G32_UINT
  263. DXGI_FORMAT_R32G32B32A32_UINT, // R32G32B32A32_UINT
  264. DXGI_FORMAT_R8_SINT, // R8_INT
  265. DXGI_FORMAT_R8G8_SINT, // R8G8_INT
  266. DXGI_FORMAT_R8G8B8A8_SINT, // R8G8B8A8_INT
  267. DXGI_FORMAT_R16_SINT, // R16_INT
  268. DXGI_FORMAT_R16G16_SINT, // R16G16_INT
  269. DXGI_FORMAT_R16G16B16A16_SINT, // R16G16B16A16_INT
  270. DXGI_FORMAT_R32_SINT, // R32_INT
  271. DXGI_FORMAT_R32G32_SINT, // R32G32_INT
  272. DXGI_FORMAT_R32G32B32A32_SINT, // R32G32B32A32_INT
  273. DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, // R8G8B8A8_UNORM_SRGB
  274. DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, // B8G8R8A8_UNORM_SRGB
  275. DXGI_FORMAT_BC1_UNORM_SRGB, // BC1_UNORM_SRGB
  276. DXGI_FORMAT_BC2_UNORM_SRGB, // BC2_UNORM_SRGB
  277. DXGI_FORMAT_BC3_UNORM_SRGB, // BC3_UNORM_SRGB
  278. DXGI_FORMAT_BC7_UNORM_SRGB, // BC7_UNORM_SRGB
  279. DXGI_FORMAT_D16_UNORM, // D16_UNORM
  280. DXGI_FORMAT_D24_UNORM_S8_UINT, // D24_UNORM
  281. DXGI_FORMAT_D32_FLOAT, // D32_FLOAT
  282. DXGI_FORMAT_D24_UNORM_S8_UINT, // D24_UNORM_S8_UINT
  283. DXGI_FORMAT_D32_FLOAT_S8X24_UINT, // D32_FLOAT_S8_UINT
  284. };
  285. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_TextureFormat, SDL_arraysize(SDLToD3D12_TextureFormat) == SDL_GPU_TEXTUREFORMAT_MAX_ENUM_VALUE);
  286. static D3D12_COMPARISON_FUNC SDLToD3D12_CompareOp[] = {
  287. D3D12_COMPARISON_FUNC_NEVER, // INVALID
  288. D3D12_COMPARISON_FUNC_NEVER, // NEVER
  289. D3D12_COMPARISON_FUNC_LESS, // LESS
  290. D3D12_COMPARISON_FUNC_EQUAL, // EQUAL
  291. D3D12_COMPARISON_FUNC_LESS_EQUAL, // LESS_OR_EQUAL
  292. D3D12_COMPARISON_FUNC_GREATER, // GREATER
  293. D3D12_COMPARISON_FUNC_NOT_EQUAL, // NOT_EQUAL
  294. D3D12_COMPARISON_FUNC_GREATER_EQUAL, // GREATER_OR_EQUAL
  295. D3D12_COMPARISON_FUNC_ALWAYS // ALWAYS
  296. };
  297. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_CompareOp, SDL_arraysize(SDLToD3D12_CompareOp) == SDL_GPU_COMPAREOP_MAX_ENUM_VALUE);
  298. static D3D12_STENCIL_OP SDLToD3D12_StencilOp[] = {
  299. D3D12_STENCIL_OP_KEEP, // INVALID
  300. D3D12_STENCIL_OP_KEEP, // KEEP
  301. D3D12_STENCIL_OP_ZERO, // ZERO
  302. D3D12_STENCIL_OP_REPLACE, // REPLACE
  303. D3D12_STENCIL_OP_INCR_SAT, // INCREMENT_AND_CLAMP
  304. D3D12_STENCIL_OP_DECR_SAT, // DECREMENT_AND_CLAMP
  305. D3D12_STENCIL_OP_INVERT, // INVERT
  306. D3D12_STENCIL_OP_INCR, // INCREMENT_AND_WRAP
  307. D3D12_STENCIL_OP_DECR // DECREMENT_AND_WRAP
  308. };
  309. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_StencilOp, SDL_arraysize(SDLToD3D12_StencilOp) == SDL_GPU_STENCILOP_MAX_ENUM_VALUE);
  310. static D3D12_CULL_MODE SDLToD3D12_CullMode[] = {
  311. D3D12_CULL_MODE_NONE, // NONE
  312. D3D12_CULL_MODE_FRONT, // FRONT
  313. D3D12_CULL_MODE_BACK // BACK
  314. };
  315. static D3D12_FILL_MODE SDLToD3D12_FillMode[] = {
  316. D3D12_FILL_MODE_SOLID, // FILL
  317. D3D12_FILL_MODE_WIREFRAME // LINE
  318. };
  319. static D3D12_INPUT_CLASSIFICATION SDLToD3D12_InputRate[] = {
  320. D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, // VERTEX
  321. D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA // INSTANCE
  322. };
  323. static DXGI_FORMAT SDLToD3D12_VertexFormat[] = {
  324. DXGI_FORMAT_UNKNOWN, // UNKNOWN
  325. DXGI_FORMAT_R32_SINT, // INT
  326. DXGI_FORMAT_R32G32_SINT, // INT2
  327. DXGI_FORMAT_R32G32B32_SINT, // INT3
  328. DXGI_FORMAT_R32G32B32A32_SINT, // INT4
  329. DXGI_FORMAT_R32_UINT, // UINT
  330. DXGI_FORMAT_R32G32_UINT, // UINT2
  331. DXGI_FORMAT_R32G32B32_UINT, // UINT3
  332. DXGI_FORMAT_R32G32B32A32_UINT, // UINT4
  333. DXGI_FORMAT_R32_FLOAT, // FLOAT
  334. DXGI_FORMAT_R32G32_FLOAT, // FLOAT2
  335. DXGI_FORMAT_R32G32B32_FLOAT, // FLOAT3
  336. DXGI_FORMAT_R32G32B32A32_FLOAT, // FLOAT4
  337. DXGI_FORMAT_R8G8_SINT, // BYTE2
  338. DXGI_FORMAT_R8G8B8A8_SINT, // BYTE4
  339. DXGI_FORMAT_R8G8_UINT, // UBYTE2
  340. DXGI_FORMAT_R8G8B8A8_UINT, // UBYTE4
  341. DXGI_FORMAT_R8G8_SNORM, // BYTE2_NORM
  342. DXGI_FORMAT_R8G8B8A8_SNORM, // BYTE4_NORM
  343. DXGI_FORMAT_R8G8_UNORM, // UBYTE2_NORM
  344. DXGI_FORMAT_R8G8B8A8_UNORM, // UBYTE4_NORM
  345. DXGI_FORMAT_R16G16_SINT, // SHORT2
  346. DXGI_FORMAT_R16G16B16A16_SINT, // SHORT4
  347. DXGI_FORMAT_R16G16_UINT, // USHORT2
  348. DXGI_FORMAT_R16G16B16A16_UINT, // USHORT4
  349. DXGI_FORMAT_R16G16_SNORM, // SHORT2_NORM
  350. DXGI_FORMAT_R16G16B16A16_SNORM, // SHORT4_NORM
  351. DXGI_FORMAT_R16G16_UNORM, // USHORT2_NORM
  352. DXGI_FORMAT_R16G16B16A16_UNORM, // USHORT4_NORM
  353. DXGI_FORMAT_R16G16_FLOAT, // HALF2
  354. DXGI_FORMAT_R16G16B16A16_FLOAT // HALF4
  355. };
  356. SDL_COMPILE_TIME_ASSERT(SDLToD3D12_VertexFormat, SDL_arraysize(SDLToD3D12_VertexFormat) == SDL_GPU_VERTEXELEMENTFORMAT_MAX_ENUM_VALUE);
  357. static Uint32 SDLToD3D12_SampleCount[] = {
  358. 1, // SDL_GPU_SAMPLECOUNT_1
  359. 2, // SDL_GPU_SAMPLECOUNT_2
  360. 4, // SDL_GPU_SAMPLECOUNT_4
  361. 8, // SDL_GPU_SAMPLECOUNT_8
  362. };
  363. static D3D12_PRIMITIVE_TOPOLOGY SDLToD3D12_PrimitiveType[] = {
  364. D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, // TRIANGLELIST
  365. D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, // TRIANGLESTRIP
  366. D3D_PRIMITIVE_TOPOLOGY_LINELIST, // LINELIST
  367. D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, // LINESTRIP
  368. D3D_PRIMITIVE_TOPOLOGY_POINTLIST // POINTLIST
  369. };
  370. static D3D12_TEXTURE_ADDRESS_MODE SDLToD3D12_SamplerAddressMode[] = {
  371. D3D12_TEXTURE_ADDRESS_MODE_WRAP, // REPEAT
  372. D3D12_TEXTURE_ADDRESS_MODE_MIRROR, // MIRRORED_REPEAT
  373. D3D12_TEXTURE_ADDRESS_MODE_CLAMP // CLAMP_TO_EDGE
  374. };
  375. static D3D12_FILTER SDLToD3D12_Filter(
  376. SDL_GPUFilter minFilter,
  377. SDL_GPUFilter magFilter,
  378. SDL_GPUSamplerMipmapMode mipmapMode,
  379. bool comparisonEnabled,
  380. bool anisotropyEnabled)
  381. {
  382. D3D12_FILTER result = D3D12_ENCODE_BASIC_FILTER(
  383. (minFilter == SDL_GPU_FILTER_LINEAR) ? 1 : 0,
  384. (magFilter == SDL_GPU_FILTER_LINEAR) ? 1 : 0,
  385. (mipmapMode == SDL_GPU_SAMPLERMIPMAPMODE_LINEAR) ? 1 : 0,
  386. comparisonEnabled ? 1 : 0);
  387. if (anisotropyEnabled) {
  388. result = (D3D12_FILTER)(result | D3D12_ANISOTROPIC_FILTERING_BIT);
  389. }
  390. return result;
  391. }
  392. // Structures
  393. typedef struct D3D12Renderer D3D12Renderer;
  394. typedef struct D3D12CommandBufferPool D3D12CommandBufferPool;
  395. typedef struct D3D12CommandBuffer D3D12CommandBuffer;
  396. typedef struct D3D12Texture D3D12Texture;
  397. typedef struct D3D12Shader D3D12Shader;
  398. typedef struct D3D12GraphicsPipeline D3D12GraphicsPipeline;
  399. typedef struct D3D12ComputePipeline D3D12ComputePipeline;
  400. typedef struct D3D12Buffer D3D12Buffer;
  401. typedef struct D3D12BufferContainer D3D12BufferContainer;
  402. typedef struct D3D12UniformBuffer D3D12UniformBuffer;
  403. typedef struct D3D12DescriptorHeap D3D12DescriptorHeap;
  404. typedef struct D3D12TextureDownload D3D12TextureDownload;
  405. typedef struct D3D12Fence
  406. {
  407. ID3D12Fence *handle;
  408. HANDLE event; // used for blocking
  409. SDL_AtomicInt referenceCount;
  410. } D3D12Fence;
  411. struct D3D12DescriptorHeap
  412. {
  413. ID3D12DescriptorHeap *handle;
  414. D3D12_DESCRIPTOR_HEAP_TYPE heapType;
  415. D3D12_CPU_DESCRIPTOR_HANDLE descriptorHeapCPUStart;
  416. D3D12_GPU_DESCRIPTOR_HANDLE descriptorHeapGPUStart; // only exists if staging is true
  417. Uint32 maxDescriptors;
  418. Uint32 descriptorSize;
  419. bool staging;
  420. Uint32 currentDescriptorIndex;
  421. Uint32 *inactiveDescriptorIndices; // only exists if staging is true
  422. Uint32 inactiveDescriptorCount;
  423. };
  424. typedef struct D3D12DescriptorHeapPool
  425. {
  426. Uint32 capacity;
  427. Uint32 count;
  428. D3D12DescriptorHeap **heaps;
  429. SDL_Mutex *lock;
  430. } D3D12DescriptorHeapPool;
  431. typedef struct D3D12CPUDescriptor
  432. {
  433. D3D12DescriptorHeap *heap;
  434. D3D12_CPU_DESCRIPTOR_HANDLE cpuHandle;
  435. Uint32 cpuHandleIndex;
  436. } D3D12CPUDescriptor;
  437. typedef struct D3D12TextureContainer
  438. {
  439. TextureCommonHeader header;
  440. D3D12Texture *activeTexture;
  441. D3D12Texture **textures;
  442. Uint32 textureCapacity;
  443. Uint32 textureCount;
  444. // Swapchain images cannot be cycled
  445. bool canBeCycled;
  446. char *debugName;
  447. } D3D12TextureContainer;
  448. // Null views represent by heap = NULL
  449. typedef struct D3D12TextureSubresource
  450. {
  451. D3D12Texture *parent;
  452. Uint32 layer;
  453. Uint32 level;
  454. Uint32 depth;
  455. Uint32 index;
  456. // One per depth slice
  457. D3D12CPUDescriptor *rtvHandles; // NULL if not a color target
  458. D3D12CPUDescriptor uavHandle; // NULL if not a compute storage write texture
  459. D3D12CPUDescriptor dsvHandle; // NULL if not a depth stencil target
  460. } D3D12TextureSubresource;
  461. struct D3D12Texture
  462. {
  463. D3D12TextureContainer *container;
  464. Uint32 containerIndex;
  465. D3D12TextureSubresource *subresources;
  466. Uint32 subresourceCount; /* layerCount * num_levels */
  467. ID3D12Resource *resource;
  468. D3D12CPUDescriptor srvHandle;
  469. SDL_AtomicInt referenceCount;
  470. };
  471. typedef struct D3D12Sampler
  472. {
  473. SDL_GPUSamplerCreateInfo createInfo;
  474. D3D12CPUDescriptor handle;
  475. SDL_AtomicInt referenceCount;
  476. } D3D12Sampler;
  477. typedef struct D3D12WindowData
  478. {
  479. SDL_Window *window;
  480. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  481. D3D12XBOX_FRAME_PIPELINE_TOKEN frameToken;
  482. #else
  483. IDXGISwapChain3 *swapchain;
  484. #endif
  485. SDL_GPUPresentMode present_mode;
  486. SDL_GPUSwapchainComposition swapchainComposition;
  487. DXGI_COLOR_SPACE_TYPE swapchainColorSpace;
  488. Uint32 frameCounter;
  489. D3D12TextureContainer textureContainers[MAX_FRAMES_IN_FLIGHT];
  490. SDL_GPUFence *inFlightFences[MAX_FRAMES_IN_FLIGHT];
  491. bool needsSwapchainRecreate;
  492. } D3D12WindowData;
  493. typedef struct D3D12PresentData
  494. {
  495. D3D12WindowData *windowData;
  496. Uint32 swapchainImageIndex;
  497. } D3D12PresentData;
  498. struct D3D12Renderer
  499. {
  500. // Reference to the parent device
  501. SDL_GPUDevice *sdlGPUDevice;
  502. #if !(defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  503. IDXGIDebug *dxgiDebug;
  504. IDXGIFactory4 *factory;
  505. #ifdef HAVE_IDXGIINFOQUEUE
  506. IDXGIInfoQueue *dxgiInfoQueue;
  507. #endif
  508. IDXGIAdapter1 *adapter;
  509. void *dxgi_dll;
  510. void *dxgidebug_dll;
  511. #endif
  512. ID3D12Debug *d3d12Debug;
  513. bool supportsTearing;
  514. void *d3d12_dll;
  515. ID3D12Device *device;
  516. PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignature_func;
  517. const char *semantic;
  518. SDL_iconv_t iconv;
  519. ID3D12CommandQueue *commandQueue;
  520. bool debug_mode;
  521. bool GPUUploadHeapSupported;
  522. // FIXME: these might not be necessary since we're not using custom heaps
  523. bool UMA;
  524. bool UMACacheCoherent;
  525. // Indirect command signatures
  526. ID3D12CommandSignature *indirectDrawCommandSignature;
  527. ID3D12CommandSignature *indirectIndexedDrawCommandSignature;
  528. ID3D12CommandSignature *indirectDispatchCommandSignature;
  529. // Blit
  530. SDL_GPUShader *blitVertexShader;
  531. SDL_GPUShader *blitFrom2DShader;
  532. SDL_GPUShader *blitFrom2DArrayShader;
  533. SDL_GPUShader *blitFrom3DShader;
  534. SDL_GPUShader *blitFromCubeShader;
  535. SDL_GPUShader *blitFromCubeArrayShader;
  536. SDL_GPUSampler *blitNearestSampler;
  537. SDL_GPUSampler *blitLinearSampler;
  538. BlitPipelineCacheEntry *blitPipelines;
  539. Uint32 blitPipelineCount;
  540. Uint32 blitPipelineCapacity;
  541. // Resources
  542. D3D12CommandBuffer **availableCommandBuffers;
  543. Uint32 availableCommandBufferCount;
  544. Uint32 availableCommandBufferCapacity;
  545. D3D12CommandBuffer **submittedCommandBuffers;
  546. Uint32 submittedCommandBufferCount;
  547. Uint32 submittedCommandBufferCapacity;
  548. D3D12UniformBuffer **uniformBufferPool;
  549. Uint32 uniformBufferPoolCount;
  550. Uint32 uniformBufferPoolCapacity;
  551. D3D12WindowData **claimedWindows;
  552. Uint32 claimedWindowCount;
  553. Uint32 claimedWindowCapacity;
  554. D3D12Fence **availableFences;
  555. Uint32 availableFenceCount;
  556. Uint32 availableFenceCapacity;
  557. D3D12DescriptorHeap *stagingDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES];
  558. D3D12DescriptorHeapPool descriptorHeapPools[2];
  559. // Deferred resource releasing
  560. D3D12Buffer **buffersToDestroy;
  561. Uint32 buffersToDestroyCount;
  562. Uint32 buffersToDestroyCapacity;
  563. D3D12Texture **texturesToDestroy;
  564. Uint32 texturesToDestroyCount;
  565. Uint32 texturesToDestroyCapacity;
  566. D3D12Sampler **samplersToDestroy;
  567. Uint32 samplersToDestroyCount;
  568. Uint32 samplersToDestroyCapacity;
  569. D3D12GraphicsPipeline **graphicsPipelinesToDestroy;
  570. Uint32 graphicsPipelinesToDestroyCount;
  571. Uint32 graphicsPipelinesToDestroyCapacity;
  572. D3D12ComputePipeline **computePipelinesToDestroy;
  573. Uint32 computePipelinesToDestroyCount;
  574. Uint32 computePipelinesToDestroyCapacity;
  575. // Locks
  576. SDL_Mutex *stagingDescriptorHeapLock;
  577. SDL_Mutex *acquireCommandBufferLock;
  578. SDL_Mutex *acquireUniformBufferLock;
  579. SDL_Mutex *submitLock;
  580. SDL_Mutex *windowLock;
  581. SDL_Mutex *fenceLock;
  582. SDL_Mutex *disposeLock;
  583. };
  584. struct D3D12CommandBuffer
  585. {
  586. // reserved for SDL_gpu
  587. CommandBufferCommonHeader common;
  588. // non owning parent reference
  589. D3D12Renderer *renderer;
  590. ID3D12CommandAllocator *commandAllocator;
  591. ID3D12GraphicsCommandList *graphicsCommandList;
  592. D3D12Fence *inFlightFence;
  593. bool autoReleaseFence;
  594. // Presentation data
  595. D3D12PresentData *presentDatas;
  596. Uint32 presentDataCount;
  597. Uint32 presentDataCapacity;
  598. D3D12TextureSubresource *colorTargetSubresources[MAX_COLOR_TARGET_BINDINGS];
  599. D3D12TextureSubresource *colorResolveSubresources[MAX_COLOR_TARGET_BINDINGS];
  600. D3D12TextureSubresource *depthStencilTextureSubresource;
  601. D3D12GraphicsPipeline *currentGraphicsPipeline;
  602. D3D12ComputePipeline *currentComputePipeline;
  603. // Set at acquire time
  604. D3D12DescriptorHeap *gpuDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER + 1];
  605. D3D12UniformBuffer **usedUniformBuffers;
  606. Uint32 usedUniformBufferCount;
  607. Uint32 usedUniformBufferCapacity;
  608. // Resource slot state
  609. bool needVertexBufferBind;
  610. bool needVertexSamplerBind;
  611. bool needVertexStorageTextureBind;
  612. bool needVertexStorageBufferBind;
  613. bool needVertexUniformBufferBind[MAX_UNIFORM_BUFFERS_PER_STAGE];
  614. bool needFragmentSamplerBind;
  615. bool needFragmentStorageTextureBind;
  616. bool needFragmentStorageBufferBind;
  617. bool needFragmentUniformBufferBind[MAX_UNIFORM_BUFFERS_PER_STAGE];
  618. bool needComputeSamplerBind;
  619. bool needComputeReadOnlyStorageTextureBind;
  620. bool needComputeReadOnlyStorageBufferBind;
  621. bool needComputeUniformBufferBind[MAX_UNIFORM_BUFFERS_PER_STAGE];
  622. D3D12Buffer *vertexBuffers[MAX_VERTEX_BUFFERS];
  623. Uint32 vertexBufferOffsets[MAX_VERTEX_BUFFERS];
  624. Uint32 vertexBufferCount;
  625. D3D12Texture *vertexSamplerTextures[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  626. D3D12Sampler *vertexSamplers[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  627. D3D12Texture *vertexStorageTextures[MAX_STORAGE_TEXTURES_PER_STAGE];
  628. D3D12Buffer *vertexStorageBuffers[MAX_STORAGE_BUFFERS_PER_STAGE];
  629. D3D12UniformBuffer *vertexUniformBuffers[MAX_UNIFORM_BUFFERS_PER_STAGE];
  630. D3D12Texture *fragmentSamplerTextures[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  631. D3D12Sampler *fragmentSamplers[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  632. D3D12Texture *fragmentStorageTextures[MAX_STORAGE_TEXTURES_PER_STAGE];
  633. D3D12Buffer *fragmentStorageBuffers[MAX_STORAGE_BUFFERS_PER_STAGE];
  634. D3D12UniformBuffer *fragmentUniformBuffers[MAX_UNIFORM_BUFFERS_PER_STAGE];
  635. D3D12Texture *computeSamplerTextures[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  636. D3D12Sampler *computeSamplers[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  637. D3D12Texture *computeReadOnlyStorageTextures[MAX_STORAGE_TEXTURES_PER_STAGE];
  638. D3D12Buffer *computeReadOnlyStorageBuffers[MAX_STORAGE_BUFFERS_PER_STAGE];
  639. D3D12TextureSubresource *computeReadWriteStorageTextureSubresources[MAX_COMPUTE_WRITE_TEXTURES];
  640. Uint32 computeReadWriteStorageTextureSubresourceCount;
  641. D3D12Buffer *computeReadWriteStorageBuffers[MAX_COMPUTE_WRITE_BUFFERS];
  642. Uint32 computeReadWriteStorageBufferCount;
  643. D3D12UniformBuffer *computeUniformBuffers[MAX_UNIFORM_BUFFERS_PER_STAGE];
  644. // Resource tracking
  645. D3D12Texture **usedTextures;
  646. Uint32 usedTextureCount;
  647. Uint32 usedTextureCapacity;
  648. D3D12Buffer **usedBuffers;
  649. Uint32 usedBufferCount;
  650. Uint32 usedBufferCapacity;
  651. D3D12Sampler **usedSamplers;
  652. Uint32 usedSamplerCount;
  653. Uint32 usedSamplerCapacity;
  654. D3D12GraphicsPipeline **usedGraphicsPipelines;
  655. Uint32 usedGraphicsPipelineCount;
  656. Uint32 usedGraphicsPipelineCapacity;
  657. D3D12ComputePipeline **usedComputePipelines;
  658. Uint32 usedComputePipelineCount;
  659. Uint32 usedComputePipelineCapacity;
  660. // Used for texture pitch hack
  661. D3D12TextureDownload **textureDownloads;
  662. Uint32 textureDownloadCount;
  663. Uint32 textureDownloadCapacity;
  664. };
  665. struct D3D12Shader
  666. {
  667. // todo cleanup
  668. void *bytecode;
  669. size_t bytecodeSize;
  670. Uint32 num_samplers;
  671. Uint32 numUniformBuffers;
  672. Uint32 numStorageBuffers;
  673. Uint32 numStorageTextures;
  674. };
  675. typedef struct D3D12GraphicsRootSignature
  676. {
  677. ID3D12RootSignature *handle;
  678. Sint32 vertexSamplerRootIndex;
  679. Sint32 vertexSamplerTextureRootIndex;
  680. Sint32 vertexStorageTextureRootIndex;
  681. Sint32 vertexStorageBufferRootIndex;
  682. Sint32 vertexUniformBufferRootIndex[MAX_UNIFORM_BUFFERS_PER_STAGE];
  683. Sint32 fragmentSamplerRootIndex;
  684. Sint32 fragmentSamplerTextureRootIndex;
  685. Sint32 fragmentStorageTextureRootIndex;
  686. Sint32 fragmentStorageBufferRootIndex;
  687. Sint32 fragmentUniformBufferRootIndex[MAX_UNIFORM_BUFFERS_PER_STAGE];
  688. } D3D12GraphicsRootSignature;
  689. struct D3D12GraphicsPipeline
  690. {
  691. ID3D12PipelineState *pipelineState;
  692. D3D12GraphicsRootSignature *rootSignature;
  693. SDL_GPUPrimitiveType primitiveType;
  694. Uint32 vertexStrides[MAX_VERTEX_BUFFERS];
  695. Uint32 vertexSamplerCount;
  696. Uint32 vertexUniformBufferCount;
  697. Uint32 vertexStorageBufferCount;
  698. Uint32 vertexStorageTextureCount;
  699. Uint32 fragmentSamplerCount;
  700. Uint32 fragmentUniformBufferCount;
  701. Uint32 fragmentStorageBufferCount;
  702. Uint32 fragmentStorageTextureCount;
  703. SDL_AtomicInt referenceCount;
  704. };
  705. typedef struct D3D12ComputeRootSignature
  706. {
  707. ID3D12RootSignature *handle;
  708. Sint32 samplerRootIndex;
  709. Sint32 samplerTextureRootIndex;
  710. Sint32 readOnlyStorageTextureRootIndex;
  711. Sint32 readOnlyStorageBufferRootIndex;
  712. Sint32 readWriteStorageTextureRootIndex;
  713. Sint32 readWriteStorageBufferRootIndex;
  714. Sint32 uniformBufferRootIndex[MAX_UNIFORM_BUFFERS_PER_STAGE];
  715. } D3D12ComputeRootSignature;
  716. struct D3D12ComputePipeline
  717. {
  718. ID3D12PipelineState *pipelineState;
  719. D3D12ComputeRootSignature *rootSignature;
  720. Uint32 numSamplers;
  721. Uint32 numReadOnlyStorageTextures;
  722. Uint32 numReadOnlyStorageBuffers;
  723. Uint32 numReadWriteStorageTextures;
  724. Uint32 numReadWriteStorageBuffers;
  725. Uint32 numUniformBuffers;
  726. SDL_AtomicInt referenceCount;
  727. };
  728. struct D3D12TextureDownload
  729. {
  730. D3D12Buffer *destinationBuffer;
  731. D3D12Buffer *temporaryBuffer;
  732. Uint32 width;
  733. Uint32 height;
  734. Uint32 depth;
  735. Uint32 bufferOffset;
  736. Uint32 bytesPerRow;
  737. Uint32 bytesPerDepthSlice;
  738. Uint32 alignedBytesPerRow;
  739. };
  740. struct D3D12Buffer
  741. {
  742. D3D12BufferContainer *container;
  743. Uint32 containerIndex;
  744. ID3D12Resource *handle;
  745. D3D12CPUDescriptor uavDescriptor;
  746. D3D12CPUDescriptor srvDescriptor;
  747. D3D12CPUDescriptor cbvDescriptor;
  748. D3D12_GPU_VIRTUAL_ADDRESS virtualAddress;
  749. Uint8 *mapPointer; // NULL except for upload buffers and fast uniform buffers
  750. SDL_AtomicInt referenceCount;
  751. bool transitioned; // used for initial resource barrier
  752. };
  753. struct D3D12BufferContainer
  754. {
  755. SDL_GPUBufferUsageFlags usage;
  756. Uint32 size;
  757. D3D12BufferType type;
  758. D3D12Buffer *activeBuffer;
  759. D3D12Buffer **buffers;
  760. Uint32 bufferCapacity;
  761. Uint32 bufferCount;
  762. D3D12_RESOURCE_DESC bufferDesc;
  763. char *debugName;
  764. };
  765. struct D3D12UniformBuffer
  766. {
  767. D3D12Buffer *buffer;
  768. Uint32 writeOffset;
  769. Uint32 drawOffset;
  770. Uint32 currentBlockSize;
  771. };
  772. // Forward function declarations
  773. static void D3D12_ReleaseWindow(SDL_GPURenderer *driverData, SDL_Window *window);
  774. static bool D3D12_Wait(SDL_GPURenderer *driverData);
  775. static bool D3D12_WaitForFences(SDL_GPURenderer *driverData, bool waitAll, SDL_GPUFence *const *fences, Uint32 numFences);
  776. static void D3D12_INTERNAL_ReleaseBlitPipelines(SDL_GPURenderer *driverData);
  777. // Helpers
  778. static Uint32 D3D12_INTERNAL_Align(Uint32 location, Uint32 alignment)
  779. {
  780. return (location + (alignment - 1)) & ~(alignment - 1);
  781. }
  782. // Xbox Hack
  783. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  784. // FIXME: This is purely to work around a presentation bug when recreating the device/command queue.
  785. static ID3D12Device *s_Device;
  786. static ID3D12CommandQueue *s_CommandQueue;
  787. #endif
  788. #if defined(SDL_PLATFORM_XBOXONE)
  789. // These are not defined in d3d12_x.h.
  790. typedef HRESULT (D3DAPI* PFN_D3D12_XBOX_CREATE_DEVICE)(_In_opt_ IGraphicsUnknown*, _In_ const D3D12XBOX_CREATE_DEVICE_PARAMETERS*, _In_ REFIID, _Outptr_opt_ void**);
  791. #define D3D12_STANDARD_MULTISAMPLE_PATTERN DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN
  792. #endif
  793. // Logging
  794. static void D3D12_INTERNAL_SetError(
  795. D3D12Renderer *renderer,
  796. const char *msg,
  797. HRESULT res)
  798. {
  799. #define MAX_ERROR_LEN 1024 // FIXME: Arbitrary!
  800. // Buffer for text, ensure space for \0 terminator after buffer
  801. char wszMsgBuff[MAX_ERROR_LEN + 1];
  802. DWORD dwChars; // Number of chars returned.
  803. if (res == DXGI_ERROR_DEVICE_REMOVED) {
  804. if (renderer->device) {
  805. res = ID3D12Device_GetDeviceRemovedReason(renderer->device);
  806. }
  807. }
  808. // Try to get the message from the system errors.
  809. dwChars = FormatMessageA(
  810. FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  811. NULL,
  812. res,
  813. 0,
  814. wszMsgBuff,
  815. MAX_ERROR_LEN,
  816. NULL);
  817. // No message? Screw it, just post the code.
  818. if (dwChars == 0) {
  819. if (renderer->debug_mode) {
  820. SDL_LogError(SDL_LOG_CATEGORY_GPU, "%s! Error Code: " HRESULT_FMT, msg, res);
  821. }
  822. SDL_SetError("%s! Error Code: " HRESULT_FMT, msg, res);
  823. return;
  824. }
  825. // Ensure valid range
  826. dwChars = SDL_min(dwChars, MAX_ERROR_LEN);
  827. // Trim whitespace from tail of message
  828. while (dwChars > 0) {
  829. if (wszMsgBuff[dwChars - 1] <= ' ') {
  830. dwChars--;
  831. } else {
  832. break;
  833. }
  834. }
  835. // Ensure null-terminated string
  836. wszMsgBuff[dwChars] = '\0';
  837. if (renderer->debug_mode) {
  838. SDL_LogError(SDL_LOG_CATEGORY_GPU, "%s! Error Code: %s " HRESULT_FMT, msg, wszMsgBuff, res);
  839. }
  840. SDL_SetError("%s! Error Code: %s " HRESULT_FMT, msg, wszMsgBuff, res);
  841. }
  842. // Debug Naming
  843. static void D3D12_INTERNAL_SetResourceName(
  844. D3D12Renderer *renderer,
  845. ID3D12Resource *resource,
  846. const char *text)
  847. {
  848. if (renderer->debug_mode) {
  849. ID3D12DeviceChild_SetPrivateData(
  850. resource,
  851. D3D_GUID(D3D_IID_D3DDebugObjectName),
  852. (UINT)SDL_strlen(text),
  853. text);
  854. }
  855. }
  856. // Release / Cleanup
  857. // TODO: call this when releasing resources
  858. static void D3D12_INTERNAL_ReleaseCpuDescriptorHandle(
  859. D3D12Renderer *renderer,
  860. D3D12CPUDescriptor *cpuDescriptor)
  861. {
  862. D3D12DescriptorHeap *heap = cpuDescriptor->heap;
  863. if (heap != NULL) {
  864. SDL_LockMutex(renderer->stagingDescriptorHeapLock);
  865. heap->inactiveDescriptorIndices[heap->inactiveDescriptorCount] = cpuDescriptor->cpuHandleIndex;
  866. heap->inactiveDescriptorCount += 1;
  867. SDL_UnlockMutex(renderer->stagingDescriptorHeapLock);
  868. }
  869. cpuDescriptor->heap = NULL;
  870. cpuDescriptor->cpuHandle.ptr = 0;
  871. cpuDescriptor->cpuHandleIndex = SDL_MAX_UINT32;
  872. }
  873. static void D3D12_INTERNAL_DestroyBuffer(
  874. D3D12Renderer *renderer,
  875. D3D12Buffer *buffer)
  876. {
  877. if (!buffer) {
  878. return;
  879. }
  880. if (buffer->mapPointer != NULL) {
  881. ID3D12Resource_Unmap(
  882. buffer->handle,
  883. 0,
  884. NULL);
  885. }
  886. D3D12_INTERNAL_ReleaseCpuDescriptorHandle(
  887. renderer,
  888. &buffer->srvDescriptor);
  889. D3D12_INTERNAL_ReleaseCpuDescriptorHandle(
  890. renderer,
  891. &buffer->uavDescriptor);
  892. D3D12_INTERNAL_ReleaseCpuDescriptorHandle(
  893. renderer,
  894. &buffer->cbvDescriptor);
  895. if (buffer->handle) {
  896. ID3D12Resource_Release(buffer->handle);
  897. }
  898. SDL_free(buffer);
  899. }
  900. static void D3D12_INTERNAL_ReleaseBuffer(
  901. D3D12Renderer *renderer,
  902. D3D12Buffer *buffer)
  903. {
  904. SDL_LockMutex(renderer->disposeLock);
  905. EXPAND_ARRAY_IF_NEEDED(
  906. renderer->buffersToDestroy,
  907. D3D12Buffer *,
  908. renderer->buffersToDestroyCount + 1,
  909. renderer->buffersToDestroyCapacity,
  910. renderer->buffersToDestroyCapacity * 2)
  911. renderer->buffersToDestroy[renderer->buffersToDestroyCount] = buffer;
  912. renderer->buffersToDestroyCount += 1;
  913. SDL_UnlockMutex(renderer->disposeLock);
  914. }
  915. static void D3D12_INTERNAL_ReleaseBufferContainer(
  916. D3D12Renderer *renderer,
  917. D3D12BufferContainer *container)
  918. {
  919. SDL_LockMutex(renderer->disposeLock);
  920. for (Uint32 i = 0; i < container->bufferCount; i += 1) {
  921. D3D12_INTERNAL_ReleaseBuffer(
  922. renderer,
  923. container->buffers[i]);
  924. }
  925. // Containers are just client handles, so we can free immediately
  926. if (container->debugName) {
  927. SDL_free(container->debugName);
  928. }
  929. SDL_free(container->buffers);
  930. SDL_free(container);
  931. SDL_UnlockMutex(renderer->disposeLock);
  932. }
  933. static void D3D12_INTERNAL_DestroyTexture(
  934. D3D12Renderer *renderer,
  935. D3D12Texture *texture)
  936. {
  937. if (!texture) {
  938. return;
  939. }
  940. for (Uint32 i = 0; i < texture->subresourceCount; i += 1) {
  941. D3D12TextureSubresource *subresource = &texture->subresources[i];
  942. if (subresource->rtvHandles) {
  943. for (Uint32 depthIndex = 0; depthIndex < subresource->depth; depthIndex += 1) {
  944. D3D12_INTERNAL_ReleaseCpuDescriptorHandle(
  945. renderer,
  946. &subresource->rtvHandles[depthIndex]);
  947. }
  948. SDL_free(subresource->rtvHandles);
  949. }
  950. D3D12_INTERNAL_ReleaseCpuDescriptorHandle(
  951. renderer,
  952. &subresource->uavHandle);
  953. D3D12_INTERNAL_ReleaseCpuDescriptorHandle(
  954. renderer,
  955. &subresource->dsvHandle);
  956. }
  957. SDL_free(texture->subresources);
  958. D3D12_INTERNAL_ReleaseCpuDescriptorHandle(
  959. renderer,
  960. &texture->srvHandle);
  961. if (texture->resource) {
  962. ID3D12Resource_Release(texture->resource);
  963. }
  964. SDL_free(texture);
  965. }
  966. static void D3D12_INTERNAL_ReleaseTexture(
  967. D3D12Renderer *renderer,
  968. D3D12Texture *texture)
  969. {
  970. SDL_LockMutex(renderer->disposeLock);
  971. EXPAND_ARRAY_IF_NEEDED(
  972. renderer->texturesToDestroy,
  973. D3D12Texture *,
  974. renderer->texturesToDestroyCount + 1,
  975. renderer->texturesToDestroyCapacity,
  976. renderer->texturesToDestroyCapacity * 2)
  977. renderer->texturesToDestroy[renderer->texturesToDestroyCount] = texture;
  978. renderer->texturesToDestroyCount += 1;
  979. SDL_UnlockMutex(renderer->disposeLock);
  980. }
  981. static void D3D12_INTERNAL_ReleaseTextureContainer(
  982. D3D12Renderer *renderer,
  983. D3D12TextureContainer *container)
  984. {
  985. SDL_LockMutex(renderer->disposeLock);
  986. for (Uint32 i = 0; i < container->textureCount; i += 1) {
  987. D3D12_INTERNAL_ReleaseTexture(
  988. renderer,
  989. container->textures[i]);
  990. }
  991. // Containers are just client handles, so we can destroy immediately
  992. if (container->debugName) {
  993. SDL_free(container->debugName);
  994. }
  995. SDL_free(container->textures);
  996. SDL_free(container);
  997. SDL_UnlockMutex(renderer->disposeLock);
  998. }
  999. static void D3D12_INTERNAL_DestroySampler(
  1000. D3D12Renderer *renderer,
  1001. D3D12Sampler *sampler)
  1002. {
  1003. D3D12_INTERNAL_ReleaseCpuDescriptorHandle(
  1004. renderer,
  1005. &sampler->handle);
  1006. SDL_free(sampler);
  1007. }
  1008. static void D3D12_INTERNAL_DestroyGraphicsRootSignature(
  1009. D3D12GraphicsRootSignature *rootSignature)
  1010. {
  1011. if (!rootSignature) {
  1012. return;
  1013. }
  1014. if (rootSignature->handle) {
  1015. ID3D12RootSignature_Release(rootSignature->handle);
  1016. }
  1017. SDL_free(rootSignature);
  1018. }
  1019. static void D3D12_INTERNAL_DestroyGraphicsPipeline(
  1020. D3D12GraphicsPipeline *graphicsPipeline)
  1021. {
  1022. if (graphicsPipeline->pipelineState) {
  1023. ID3D12PipelineState_Release(graphicsPipeline->pipelineState);
  1024. }
  1025. D3D12_INTERNAL_DestroyGraphicsRootSignature(graphicsPipeline->rootSignature);
  1026. SDL_free(graphicsPipeline);
  1027. }
  1028. static void D3D12_INTERNAL_DestroyComputeRootSignature(
  1029. D3D12ComputeRootSignature *rootSignature)
  1030. {
  1031. if (!rootSignature) {
  1032. return;
  1033. }
  1034. if (rootSignature->handle) {
  1035. ID3D12RootSignature_Release(rootSignature->handle);
  1036. }
  1037. SDL_free(rootSignature);
  1038. }
  1039. static void D3D12_INTERNAL_DestroyComputePipeline(
  1040. D3D12ComputePipeline *computePipeline)
  1041. {
  1042. if (computePipeline->pipelineState) {
  1043. ID3D12PipelineState_Release(computePipeline->pipelineState);
  1044. }
  1045. D3D12_INTERNAL_DestroyComputeRootSignature(computePipeline->rootSignature);
  1046. SDL_free(computePipeline);
  1047. }
  1048. static void D3D12_INTERNAL_ReleaseFenceToPool(
  1049. D3D12Renderer *renderer,
  1050. D3D12Fence *fence)
  1051. {
  1052. SDL_LockMutex(renderer->fenceLock);
  1053. EXPAND_ARRAY_IF_NEEDED(
  1054. renderer->availableFences,
  1055. D3D12Fence *,
  1056. renderer->availableFenceCount + 1,
  1057. renderer->availableFenceCapacity,
  1058. renderer->availableFenceCapacity * 2);
  1059. renderer->availableFences[renderer->availableFenceCount] = fence;
  1060. renderer->availableFenceCount += 1;
  1061. SDL_UnlockMutex(renderer->fenceLock);
  1062. }
  1063. static void D3D12_ReleaseFence(
  1064. SDL_GPURenderer *driverData,
  1065. SDL_GPUFence *fence)
  1066. {
  1067. D3D12Fence *d3d12Fence = (D3D12Fence *)fence;
  1068. if (SDL_AtomicDecRef(&d3d12Fence->referenceCount)) {
  1069. D3D12_INTERNAL_ReleaseFenceToPool(
  1070. (D3D12Renderer *)driverData,
  1071. d3d12Fence);
  1072. }
  1073. }
  1074. static bool D3D12_QueryFence(
  1075. SDL_GPURenderer *driverData,
  1076. SDL_GPUFence *fence)
  1077. {
  1078. D3D12Fence *d3d12Fence = (D3D12Fence *)fence;
  1079. return ID3D12Fence_GetCompletedValue(d3d12Fence->handle) == D3D12_FENCE_SIGNAL_VALUE;
  1080. }
  1081. static void D3D12_INTERNAL_DestroyDescriptorHeap(D3D12DescriptorHeap *descriptorHeap)
  1082. {
  1083. if (!descriptorHeap) {
  1084. return;
  1085. }
  1086. SDL_free(descriptorHeap->inactiveDescriptorIndices);
  1087. if (descriptorHeap->handle) {
  1088. ID3D12DescriptorHeap_Release(descriptorHeap->handle);
  1089. }
  1090. SDL_free(descriptorHeap);
  1091. }
  1092. static void D3D12_INTERNAL_DestroyCommandBuffer(D3D12CommandBuffer *commandBuffer)
  1093. {
  1094. if (!commandBuffer) {
  1095. return;
  1096. }
  1097. if (commandBuffer->graphicsCommandList) {
  1098. ID3D12GraphicsCommandList_Release(commandBuffer->graphicsCommandList);
  1099. }
  1100. if (commandBuffer->commandAllocator) {
  1101. ID3D12CommandAllocator_Release(commandBuffer->commandAllocator);
  1102. }
  1103. SDL_free(commandBuffer->presentDatas);
  1104. SDL_free(commandBuffer->usedTextures);
  1105. SDL_free(commandBuffer->usedBuffers);
  1106. SDL_free(commandBuffer->usedSamplers);
  1107. SDL_free(commandBuffer->usedGraphicsPipelines);
  1108. SDL_free(commandBuffer->usedComputePipelines);
  1109. SDL_free(commandBuffer->usedUniformBuffers);
  1110. SDL_free(commandBuffer->textureDownloads);
  1111. SDL_free(commandBuffer);
  1112. }
  1113. static void D3D12_INTERNAL_DestroyFence(D3D12Fence *fence)
  1114. {
  1115. if (!fence) {
  1116. return;
  1117. }
  1118. if (fence->handle) {
  1119. ID3D12Fence_Release(fence->handle);
  1120. }
  1121. if (fence->event) {
  1122. CloseHandle(fence->event);
  1123. }
  1124. SDL_free(fence);
  1125. }
  1126. static void D3D12_INTERNAL_DestroyRenderer(D3D12Renderer *renderer)
  1127. {
  1128. // Release uniform buffers
  1129. for (Uint32 i = 0; i < renderer->uniformBufferPoolCount; i += 1) {
  1130. D3D12_INTERNAL_DestroyBuffer(
  1131. renderer,
  1132. renderer->uniformBufferPool[i]->buffer);
  1133. SDL_free(renderer->uniformBufferPool[i]);
  1134. }
  1135. // Clean up descriptor heaps
  1136. for (Uint32 i = 0; i < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; i += 1) {
  1137. if (renderer->stagingDescriptorHeaps[i]) {
  1138. D3D12_INTERNAL_DestroyDescriptorHeap(renderer->stagingDescriptorHeaps[i]);
  1139. renderer->stagingDescriptorHeaps[i] = NULL;
  1140. }
  1141. }
  1142. for (Uint32 i = 0; i < 2; i += 1) {
  1143. if (renderer->descriptorHeapPools[i].heaps) {
  1144. for (Uint32 j = 0; j < renderer->descriptorHeapPools[i].count; j += 1) {
  1145. if (renderer->descriptorHeapPools[i].heaps[j]) {
  1146. D3D12_INTERNAL_DestroyDescriptorHeap(renderer->descriptorHeapPools[i].heaps[j]);
  1147. renderer->descriptorHeapPools[i].heaps[j] = NULL;
  1148. }
  1149. }
  1150. SDL_free(renderer->descriptorHeapPools[i].heaps);
  1151. }
  1152. if (renderer->descriptorHeapPools[i].lock) {
  1153. SDL_DestroyMutex(renderer->descriptorHeapPools[i].lock);
  1154. renderer->descriptorHeapPools[i].lock = NULL;
  1155. }
  1156. }
  1157. // Release command buffers
  1158. for (Uint32 i = 0; i < renderer->availableCommandBufferCount; i += 1) {
  1159. if (renderer->availableCommandBuffers[i]) {
  1160. D3D12_INTERNAL_DestroyCommandBuffer(renderer->availableCommandBuffers[i]);
  1161. renderer->availableCommandBuffers[i] = NULL;
  1162. }
  1163. }
  1164. // Release fences
  1165. for (Uint32 i = 0; i < renderer->availableFenceCount; i += 1) {
  1166. if (renderer->availableFences[i]) {
  1167. D3D12_INTERNAL_DestroyFence(renderer->availableFences[i]);
  1168. renderer->availableFences[i] = NULL;
  1169. }
  1170. }
  1171. // Clean up allocations
  1172. SDL_free(renderer->availableCommandBuffers);
  1173. SDL_free(renderer->submittedCommandBuffers);
  1174. SDL_free(renderer->uniformBufferPool);
  1175. SDL_free(renderer->claimedWindows);
  1176. SDL_free(renderer->availableFences);
  1177. SDL_free(renderer->buffersToDestroy);
  1178. SDL_free(renderer->texturesToDestroy);
  1179. SDL_free(renderer->samplersToDestroy);
  1180. SDL_free(renderer->graphicsPipelinesToDestroy);
  1181. SDL_free(renderer->computePipelinesToDestroy);
  1182. // Tear down D3D12 objects
  1183. if (renderer->indirectDrawCommandSignature) {
  1184. ID3D12CommandSignature_Release(renderer->indirectDrawCommandSignature);
  1185. renderer->indirectDrawCommandSignature = NULL;
  1186. }
  1187. if (renderer->indirectIndexedDrawCommandSignature) {
  1188. ID3D12CommandSignature_Release(renderer->indirectIndexedDrawCommandSignature);
  1189. renderer->indirectIndexedDrawCommandSignature = NULL;
  1190. }
  1191. if (renderer->indirectDispatchCommandSignature) {
  1192. ID3D12CommandSignature_Release(renderer->indirectDispatchCommandSignature);
  1193. renderer->indirectDispatchCommandSignature = NULL;
  1194. }
  1195. #if !(defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  1196. if (renderer->commandQueue) {
  1197. ID3D12CommandQueue_Release(renderer->commandQueue);
  1198. renderer->commandQueue = NULL;
  1199. }
  1200. if (renderer->device) {
  1201. ID3D12Device_Release(renderer->device);
  1202. renderer->device = NULL;
  1203. }
  1204. if (renderer->adapter) {
  1205. IDXGIAdapter1_Release(renderer->adapter);
  1206. renderer->adapter = NULL;
  1207. }
  1208. if (renderer->factory) {
  1209. IDXGIFactory4_Release(renderer->factory);
  1210. renderer->factory = NULL;
  1211. }
  1212. if (renderer->dxgiDebug) {
  1213. IDXGIDebug_ReportLiveObjects(
  1214. renderer->dxgiDebug,
  1215. D3D_IID_DXGI_DEBUG_ALL,
  1216. (DXGI_DEBUG_RLO_FLAGS)(DXGI_DEBUG_RLO_SUMMARY | DXGI_DEBUG_RLO_DETAIL));
  1217. IDXGIDebug_Release(renderer->dxgiDebug);
  1218. renderer->dxgiDebug = NULL;
  1219. }
  1220. #endif
  1221. if (renderer->d3d12_dll) {
  1222. SDL_UnloadObject(renderer->d3d12_dll);
  1223. renderer->d3d12_dll = NULL;
  1224. }
  1225. #if !(defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  1226. if (renderer->dxgi_dll) {
  1227. SDL_UnloadObject(renderer->dxgi_dll);
  1228. renderer->dxgi_dll = NULL;
  1229. }
  1230. if (renderer->dxgidebug_dll) {
  1231. SDL_UnloadObject(renderer->dxgidebug_dll);
  1232. renderer->dxgidebug_dll = NULL;
  1233. }
  1234. #endif
  1235. renderer->D3D12SerializeRootSignature_func = NULL;
  1236. if (renderer->iconv) {
  1237. SDL_iconv_close(renderer->iconv);
  1238. }
  1239. SDL_DestroyMutex(renderer->stagingDescriptorHeapLock);
  1240. SDL_DestroyMutex(renderer->acquireCommandBufferLock);
  1241. SDL_DestroyMutex(renderer->acquireUniformBufferLock);
  1242. SDL_DestroyMutex(renderer->submitLock);
  1243. SDL_DestroyMutex(renderer->windowLock);
  1244. SDL_DestroyMutex(renderer->fenceLock);
  1245. SDL_DestroyMutex(renderer->disposeLock);
  1246. SDL_free(renderer);
  1247. }
  1248. static void D3D12_DestroyDevice(SDL_GPUDevice *device)
  1249. {
  1250. D3D12Renderer *renderer = (D3D12Renderer *)device->driverData;
  1251. // Release blit pipeline structures
  1252. D3D12_INTERNAL_ReleaseBlitPipelines((SDL_GPURenderer *)renderer);
  1253. // Flush any remaining GPU work...
  1254. D3D12_Wait((SDL_GPURenderer *)renderer);
  1255. // Release window data
  1256. for (Sint32 i = renderer->claimedWindowCount - 1; i >= 0; i -= 1) {
  1257. D3D12_ReleaseWindow((SDL_GPURenderer *)renderer, renderer->claimedWindows[i]->window);
  1258. }
  1259. D3D12_INTERNAL_DestroyRenderer(renderer);
  1260. SDL_free(device);
  1261. }
  1262. // Barriers
  1263. static inline Uint32 D3D12_INTERNAL_CalcSubresource(
  1264. Uint32 mipLevel,
  1265. Uint32 layer,
  1266. Uint32 numLevels)
  1267. {
  1268. return mipLevel + (layer * numLevels);
  1269. }
  1270. static void D3D12_INTERNAL_ResourceBarrier(
  1271. D3D12CommandBuffer *commandBuffer,
  1272. D3D12_RESOURCE_STATES sourceState,
  1273. D3D12_RESOURCE_STATES destinationState,
  1274. ID3D12Resource *resource,
  1275. Uint32 subresourceIndex,
  1276. bool needsUavBarrier)
  1277. {
  1278. D3D12_RESOURCE_BARRIER barrierDesc[2];
  1279. Uint32 numBarriers = 0;
  1280. // No transition barrier is needed if the state is not changing.
  1281. if (sourceState != destinationState) {
  1282. barrierDesc[numBarriers].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  1283. barrierDesc[numBarriers].Flags = (D3D12_RESOURCE_BARRIER_FLAGS)0;
  1284. barrierDesc[numBarriers].Transition.StateBefore = sourceState;
  1285. barrierDesc[numBarriers].Transition.StateAfter = destinationState;
  1286. barrierDesc[numBarriers].Transition.pResource = resource;
  1287. barrierDesc[numBarriers].Transition.Subresource = subresourceIndex;
  1288. numBarriers += 1;
  1289. }
  1290. if (needsUavBarrier) {
  1291. barrierDesc[numBarriers].Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
  1292. barrierDesc[numBarriers].Flags = (D3D12_RESOURCE_BARRIER_FLAGS)0;
  1293. barrierDesc[numBarriers].UAV.pResource = resource;
  1294. numBarriers += 1;
  1295. }
  1296. if (numBarriers > 0) {
  1297. ID3D12GraphicsCommandList_ResourceBarrier(
  1298. commandBuffer->graphicsCommandList,
  1299. numBarriers,
  1300. barrierDesc);
  1301. }
  1302. }
  1303. static void D3D12_INTERNAL_TextureSubresourceBarrier(
  1304. D3D12CommandBuffer *commandBuffer,
  1305. D3D12_RESOURCE_STATES sourceState,
  1306. D3D12_RESOURCE_STATES destinationState,
  1307. D3D12TextureSubresource *textureSubresource)
  1308. {
  1309. bool needsUAVBarrier =
  1310. (textureSubresource->parent->container->header.info.usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE) ||
  1311. (textureSubresource->parent->container->header.info.usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE);
  1312. D3D12_INTERNAL_ResourceBarrier(
  1313. commandBuffer,
  1314. sourceState,
  1315. destinationState,
  1316. textureSubresource->parent->resource,
  1317. textureSubresource->index,
  1318. needsUAVBarrier);
  1319. }
  1320. static D3D12_RESOURCE_STATES D3D12_INTERNAL_DefaultTextureResourceState(
  1321. SDL_GPUTextureUsageFlags usageFlags)
  1322. {
  1323. // NOTE: order matters here!
  1324. if (usageFlags & SDL_GPU_TEXTUREUSAGE_SAMPLER) {
  1325. return D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE;
  1326. } else if (usageFlags & SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ) {
  1327. return D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE;
  1328. } else if (usageFlags & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) {
  1329. return D3D12_RESOURCE_STATE_RENDER_TARGET;
  1330. } else if (usageFlags & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) {
  1331. return D3D12_RESOURCE_STATE_DEPTH_WRITE;
  1332. } else if (usageFlags & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ) {
  1333. return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
  1334. } else if (usageFlags & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE) {
  1335. return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  1336. } else if (usageFlags & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE) {
  1337. return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  1338. } else {
  1339. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Texture has no default usage mode!");
  1340. return D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE;
  1341. }
  1342. }
  1343. static void D3D12_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  1344. D3D12CommandBuffer *commandBuffer,
  1345. D3D12_RESOURCE_STATES destinationUsageMode,
  1346. D3D12TextureSubresource *textureSubresource)
  1347. {
  1348. D3D12_INTERNAL_TextureSubresourceBarrier(
  1349. commandBuffer,
  1350. D3D12_INTERNAL_DefaultTextureResourceState(textureSubresource->parent->container->header.info.usage),
  1351. destinationUsageMode,
  1352. textureSubresource);
  1353. }
  1354. static void D3D12_INTERNAL_TextureTransitionFromDefaultUsage(
  1355. D3D12CommandBuffer *commandBuffer,
  1356. D3D12_RESOURCE_STATES destinationUsageMode,
  1357. D3D12Texture *texture)
  1358. {
  1359. for (Uint32 i = 0; i < texture->subresourceCount; i += 1) {
  1360. D3D12_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  1361. commandBuffer,
  1362. destinationUsageMode,
  1363. &texture->subresources[i]);
  1364. }
  1365. }
  1366. static void D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  1367. D3D12CommandBuffer *commandBuffer,
  1368. D3D12_RESOURCE_STATES sourceUsageMode,
  1369. D3D12TextureSubresource *textureSubresource)
  1370. {
  1371. D3D12_INTERNAL_TextureSubresourceBarrier(
  1372. commandBuffer,
  1373. sourceUsageMode,
  1374. D3D12_INTERNAL_DefaultTextureResourceState(textureSubresource->parent->container->header.info.usage),
  1375. textureSubresource);
  1376. }
  1377. static void D3D12_INTERNAL_TextureTransitionToDefaultUsage(
  1378. D3D12CommandBuffer *commandBuffer,
  1379. D3D12_RESOURCE_STATES sourceUsageMode,
  1380. D3D12Texture *texture)
  1381. {
  1382. for (Uint32 i = 0; i < texture->subresourceCount; i += 1) {
  1383. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  1384. commandBuffer,
  1385. sourceUsageMode,
  1386. &texture->subresources[i]);
  1387. }
  1388. }
  1389. static D3D12_RESOURCE_STATES D3D12_INTERNAL_DefaultBufferResourceState(
  1390. D3D12Buffer *buffer)
  1391. {
  1392. if (buffer->container->usage & SDL_GPU_BUFFERUSAGE_VERTEX) {
  1393. return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
  1394. } else if (buffer->container->usage & SDL_GPU_BUFFERUSAGE_INDEX) {
  1395. return D3D12_RESOURCE_STATE_INDEX_BUFFER;
  1396. } else if (buffer->container->usage & SDL_GPU_BUFFERUSAGE_INDIRECT) {
  1397. return D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
  1398. } else if (buffer->container->usage & SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ) {
  1399. return D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE;
  1400. } else if (buffer->container->usage & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ) {
  1401. return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
  1402. } else if (buffer->container->usage & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE) {
  1403. return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  1404. } else {
  1405. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Buffer has no default usage mode!");
  1406. return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
  1407. }
  1408. }
  1409. static void D3D12_INTERNAL_BufferBarrier(
  1410. D3D12CommandBuffer *commandBuffer,
  1411. D3D12_RESOURCE_STATES sourceState,
  1412. D3D12_RESOURCE_STATES destinationState,
  1413. D3D12Buffer *buffer)
  1414. {
  1415. D3D12_INTERNAL_ResourceBarrier(
  1416. commandBuffer,
  1417. buffer->transitioned ? sourceState : D3D12_RESOURCE_STATE_COMMON,
  1418. destinationState,
  1419. buffer->handle,
  1420. 0,
  1421. buffer->container->usage & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE);
  1422. buffer->transitioned = true;
  1423. }
  1424. static void D3D12_INTERNAL_BufferTransitionFromDefaultUsage(
  1425. D3D12CommandBuffer *commandBuffer,
  1426. D3D12_RESOURCE_STATES destinationState,
  1427. D3D12Buffer *buffer)
  1428. {
  1429. D3D12_INTERNAL_BufferBarrier(
  1430. commandBuffer,
  1431. D3D12_INTERNAL_DefaultBufferResourceState(buffer),
  1432. destinationState,
  1433. buffer);
  1434. }
  1435. static void D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  1436. D3D12CommandBuffer *commandBuffer,
  1437. D3D12_RESOURCE_STATES sourceState,
  1438. D3D12Buffer *buffer)
  1439. {
  1440. D3D12_INTERNAL_BufferBarrier(
  1441. commandBuffer,
  1442. sourceState,
  1443. D3D12_INTERNAL_DefaultBufferResourceState(buffer),
  1444. buffer);
  1445. }
  1446. // Resource tracking
  1447. #define TRACK_RESOURCE(resource, type, array, count, capacity) \
  1448. Uint32 i; \
  1449. \
  1450. for (i = 0; i < commandBuffer->count; i += 1) { \
  1451. if (commandBuffer->array[i] == resource) { \
  1452. return; \
  1453. } \
  1454. } \
  1455. \
  1456. if (commandBuffer->count == commandBuffer->capacity) { \
  1457. commandBuffer->capacity += 1; \
  1458. commandBuffer->array = (type *)SDL_realloc( \
  1459. commandBuffer->array, \
  1460. commandBuffer->capacity * sizeof(type)); \
  1461. } \
  1462. commandBuffer->array[commandBuffer->count] = resource; \
  1463. commandBuffer->count += 1; \
  1464. SDL_AtomicIncRef(&resource->referenceCount);
  1465. static void D3D12_INTERNAL_TrackTexture(
  1466. D3D12CommandBuffer *commandBuffer,
  1467. D3D12Texture *texture)
  1468. {
  1469. TRACK_RESOURCE(
  1470. texture,
  1471. D3D12Texture *,
  1472. usedTextures,
  1473. usedTextureCount,
  1474. usedTextureCapacity)
  1475. }
  1476. static void D3D12_INTERNAL_TrackBuffer(
  1477. D3D12CommandBuffer *commandBuffer,
  1478. D3D12Buffer *buffer)
  1479. {
  1480. TRACK_RESOURCE(
  1481. buffer,
  1482. D3D12Buffer *,
  1483. usedBuffers,
  1484. usedBufferCount,
  1485. usedBufferCapacity)
  1486. }
  1487. static void D3D12_INTERNAL_TrackSampler(
  1488. D3D12CommandBuffer *commandBuffer,
  1489. D3D12Sampler *sampler)
  1490. {
  1491. TRACK_RESOURCE(
  1492. sampler,
  1493. D3D12Sampler *,
  1494. usedSamplers,
  1495. usedSamplerCount,
  1496. usedSamplerCapacity)
  1497. }
  1498. static void D3D12_INTERNAL_TrackGraphicsPipeline(
  1499. D3D12CommandBuffer *commandBuffer,
  1500. D3D12GraphicsPipeline *graphicsPipeline)
  1501. {
  1502. TRACK_RESOURCE(
  1503. graphicsPipeline,
  1504. D3D12GraphicsPipeline *,
  1505. usedGraphicsPipelines,
  1506. usedGraphicsPipelineCount,
  1507. usedGraphicsPipelineCapacity)
  1508. }
  1509. static void D3D12_INTERNAL_TrackComputePipeline(
  1510. D3D12CommandBuffer *commandBuffer,
  1511. D3D12ComputePipeline *computePipeline)
  1512. {
  1513. TRACK_RESOURCE(
  1514. computePipeline,
  1515. D3D12ComputePipeline *,
  1516. usedComputePipelines,
  1517. usedComputePipelineCount,
  1518. usedComputePipelineCapacity)
  1519. }
  1520. #undef TRACK_RESOURCE
  1521. // State Creation
  1522. static D3D12DescriptorHeap *D3D12_INTERNAL_CreateDescriptorHeap(
  1523. D3D12Renderer *renderer,
  1524. D3D12_DESCRIPTOR_HEAP_TYPE type,
  1525. Uint32 descriptorCount,
  1526. bool staging)
  1527. {
  1528. D3D12DescriptorHeap *heap;
  1529. ID3D12DescriptorHeap *handle;
  1530. D3D12_DESCRIPTOR_HEAP_DESC heapDesc;
  1531. HRESULT res;
  1532. heap = (D3D12DescriptorHeap *)SDL_calloc(1, sizeof(D3D12DescriptorHeap));
  1533. if (!heap) {
  1534. return NULL;
  1535. }
  1536. heap->currentDescriptorIndex = 0;
  1537. heap->inactiveDescriptorCount = 0;
  1538. heap->inactiveDescriptorIndices = NULL;
  1539. if (staging) {
  1540. heap->inactiveDescriptorIndices = (Uint32 *)SDL_calloc(descriptorCount, sizeof(Uint32));
  1541. if (!heap->inactiveDescriptorIndices) {
  1542. D3D12_INTERNAL_DestroyDescriptorHeap(heap);
  1543. return NULL;
  1544. }
  1545. }
  1546. heapDesc.NumDescriptors = descriptorCount;
  1547. heapDesc.Type = type;
  1548. heapDesc.Flags = staging ? D3D12_DESCRIPTOR_HEAP_FLAG_NONE : D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  1549. heapDesc.NodeMask = 0;
  1550. res = ID3D12Device_CreateDescriptorHeap(
  1551. renderer->device,
  1552. &heapDesc,
  1553. D3D_GUID(D3D_IID_ID3D12DescriptorHeap),
  1554. (void **)&handle);
  1555. if (FAILED(res)) {
  1556. D3D12_INTERNAL_SetError(renderer, "Failed to create descriptor heap!", res);
  1557. D3D12_INTERNAL_DestroyDescriptorHeap(heap);
  1558. return NULL;
  1559. }
  1560. heap->handle = handle;
  1561. heap->heapType = type;
  1562. heap->maxDescriptors = descriptorCount;
  1563. heap->staging = staging;
  1564. heap->descriptorSize = ID3D12Device_GetDescriptorHandleIncrementSize(renderer->device, type);
  1565. D3D_CALL_RET(handle, GetCPUDescriptorHandleForHeapStart, &heap->descriptorHeapCPUStart);
  1566. if (!staging) {
  1567. D3D_CALL_RET(handle, GetGPUDescriptorHandleForHeapStart, &heap->descriptorHeapGPUStart);
  1568. }
  1569. return heap;
  1570. }
  1571. static D3D12DescriptorHeap *D3D12_INTERNAL_AcquireDescriptorHeapFromPool(
  1572. D3D12CommandBuffer *commandBuffer,
  1573. D3D12_DESCRIPTOR_HEAP_TYPE descriptorHeapType)
  1574. {
  1575. D3D12DescriptorHeap *result;
  1576. D3D12Renderer *renderer = commandBuffer->renderer;
  1577. D3D12DescriptorHeapPool *pool = &renderer->descriptorHeapPools[descriptorHeapType];
  1578. SDL_LockMutex(pool->lock);
  1579. if (pool->count > 0) {
  1580. result = pool->heaps[pool->count - 1];
  1581. pool->count -= 1;
  1582. } else {
  1583. result = D3D12_INTERNAL_CreateDescriptorHeap(
  1584. renderer,
  1585. descriptorHeapType,
  1586. descriptorHeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ? VIEW_GPU_DESCRIPTOR_COUNT : SAMPLER_GPU_DESCRIPTOR_COUNT,
  1587. false);
  1588. }
  1589. SDL_UnlockMutex(pool->lock);
  1590. return result;
  1591. }
  1592. static void D3D12_INTERNAL_ReturnDescriptorHeapToPool(
  1593. D3D12Renderer *renderer,
  1594. D3D12DescriptorHeap *heap)
  1595. {
  1596. D3D12DescriptorHeapPool *pool = &renderer->descriptorHeapPools[heap->heapType];
  1597. heap->currentDescriptorIndex = 0;
  1598. SDL_LockMutex(pool->lock);
  1599. if (pool->count >= pool->capacity) {
  1600. pool->capacity *= 2;
  1601. pool->heaps = (D3D12DescriptorHeap **)SDL_realloc(
  1602. pool->heaps,
  1603. pool->capacity * sizeof(D3D12DescriptorHeap *));
  1604. }
  1605. pool->heaps[pool->count] = heap;
  1606. pool->count += 1;
  1607. SDL_UnlockMutex(pool->lock);
  1608. }
  1609. /*
  1610. * The root signature lets us define "root parameters" which are essentially bind points for resources.
  1611. * These let us define the register ranges as well as the register "space".
  1612. * The register space is akin to the descriptor set index in Vulkan, which allows us to group resources
  1613. * by stage so that the registers from the vertex and fragment shaders don't clobber each other.
  1614. *
  1615. * Most of our root parameters are implemented as "descriptor tables" so we can
  1616. * copy and then point to contiguous descriptor regions.
  1617. * Uniform buffers are the exception - these have to be implemented as raw "root descriptors" so
  1618. * that we can dynamically update the address that the constant buffer view points to.
  1619. *
  1620. * The root signature has a maximum size of 64 DWORDs.
  1621. * A descriptor table uses 1 DWORD.
  1622. * A root descriptor uses 2 DWORDS.
  1623. * This means our biggest root signature uses 24 DWORDs total, well under the limit.
  1624. *
  1625. * The root parameter indices are created dynamically and stored in the D3D12GraphicsRootSignature struct.
  1626. */
  1627. static D3D12GraphicsRootSignature *D3D12_INTERNAL_CreateGraphicsRootSignature(
  1628. D3D12Renderer *renderer,
  1629. D3D12Shader *vertexShader,
  1630. D3D12Shader *fragmentShader)
  1631. {
  1632. // FIXME: I think the max can be smaller...
  1633. D3D12_ROOT_PARAMETER rootParameters[MAX_ROOT_SIGNATURE_PARAMETERS];
  1634. D3D12_DESCRIPTOR_RANGE descriptorRanges[MAX_ROOT_SIGNATURE_PARAMETERS];
  1635. Uint32 parameterCount = 0;
  1636. Uint32 rangeCount = 0;
  1637. D3D12_DESCRIPTOR_RANGE descriptorRange;
  1638. D3D12_ROOT_PARAMETER rootParameter;
  1639. D3D12GraphicsRootSignature *d3d12GraphicsRootSignature =
  1640. (D3D12GraphicsRootSignature *)SDL_calloc(1, sizeof(D3D12GraphicsRootSignature));
  1641. if (!d3d12GraphicsRootSignature) {
  1642. return NULL;
  1643. }
  1644. SDL_zeroa(rootParameters);
  1645. SDL_zeroa(descriptorRanges);
  1646. SDL_zero(rootParameter);
  1647. d3d12GraphicsRootSignature->vertexSamplerRootIndex = -1;
  1648. d3d12GraphicsRootSignature->vertexSamplerTextureRootIndex = -1;
  1649. d3d12GraphicsRootSignature->vertexStorageTextureRootIndex = -1;
  1650. d3d12GraphicsRootSignature->vertexStorageBufferRootIndex = -1;
  1651. d3d12GraphicsRootSignature->fragmentSamplerRootIndex = -1;
  1652. d3d12GraphicsRootSignature->fragmentSamplerTextureRootIndex = -1;
  1653. d3d12GraphicsRootSignature->fragmentStorageTextureRootIndex = -1;
  1654. d3d12GraphicsRootSignature->fragmentStorageBufferRootIndex = -1;
  1655. for (Uint32 i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  1656. d3d12GraphicsRootSignature->vertexUniformBufferRootIndex[i] = -1;
  1657. d3d12GraphicsRootSignature->fragmentUniformBufferRootIndex[i] = -1;
  1658. }
  1659. if (vertexShader->num_samplers > 0) {
  1660. // Vertex Samplers
  1661. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER;
  1662. descriptorRange.NumDescriptors = vertexShader->num_samplers;
  1663. descriptorRange.BaseShaderRegister = 0;
  1664. descriptorRange.RegisterSpace = 0;
  1665. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  1666. descriptorRanges[rangeCount] = descriptorRange;
  1667. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  1668. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  1669. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  1670. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  1671. rootParameters[parameterCount] = rootParameter;
  1672. d3d12GraphicsRootSignature->vertexSamplerRootIndex = parameterCount;
  1673. rangeCount += 1;
  1674. parameterCount += 1;
  1675. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  1676. descriptorRange.NumDescriptors = vertexShader->num_samplers;
  1677. descriptorRange.BaseShaderRegister = 0;
  1678. descriptorRange.RegisterSpace = 0;
  1679. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  1680. descriptorRanges[rangeCount] = descriptorRange;
  1681. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  1682. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  1683. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  1684. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  1685. rootParameters[parameterCount] = rootParameter;
  1686. d3d12GraphicsRootSignature->vertexSamplerTextureRootIndex = parameterCount;
  1687. rangeCount += 1;
  1688. parameterCount += 1;
  1689. }
  1690. if (vertexShader->numStorageTextures) {
  1691. // Vertex storage textures
  1692. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  1693. descriptorRange.NumDescriptors = vertexShader->numStorageTextures;
  1694. descriptorRange.BaseShaderRegister = vertexShader->num_samplers;
  1695. descriptorRange.RegisterSpace = 0;
  1696. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  1697. descriptorRanges[rangeCount] = descriptorRange;
  1698. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  1699. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  1700. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  1701. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  1702. rootParameters[parameterCount] = rootParameter;
  1703. d3d12GraphicsRootSignature->vertexStorageTextureRootIndex = parameterCount;
  1704. rangeCount += 1;
  1705. parameterCount += 1;
  1706. }
  1707. if (vertexShader->numStorageBuffers) {
  1708. // Vertex storage buffers
  1709. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  1710. descriptorRange.NumDescriptors = vertexShader->numStorageBuffers;
  1711. descriptorRange.BaseShaderRegister = vertexShader->num_samplers + vertexShader->numStorageTextures;
  1712. descriptorRange.RegisterSpace = 0;
  1713. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  1714. descriptorRanges[rangeCount] = descriptorRange;
  1715. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  1716. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  1717. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  1718. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  1719. rootParameters[parameterCount] = rootParameter;
  1720. d3d12GraphicsRootSignature->vertexStorageBufferRootIndex = parameterCount;
  1721. rangeCount += 1;
  1722. parameterCount += 1;
  1723. }
  1724. // Vertex Uniforms
  1725. for (Uint32 i = 0; i < vertexShader->numUniformBuffers; i += 1) {
  1726. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
  1727. rootParameter.Descriptor.ShaderRegister = i;
  1728. rootParameter.Descriptor.RegisterSpace = 1;
  1729. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  1730. rootParameters[parameterCount] = rootParameter;
  1731. d3d12GraphicsRootSignature->vertexUniformBufferRootIndex[i] = parameterCount;
  1732. parameterCount += 1;
  1733. }
  1734. if (fragmentShader->num_samplers) {
  1735. // Fragment Samplers
  1736. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER;
  1737. descriptorRange.NumDescriptors = fragmentShader->num_samplers;
  1738. descriptorRange.BaseShaderRegister = 0;
  1739. descriptorRange.RegisterSpace = 2;
  1740. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  1741. descriptorRanges[rangeCount] = descriptorRange;
  1742. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  1743. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  1744. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  1745. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  1746. rootParameters[parameterCount] = rootParameter;
  1747. d3d12GraphicsRootSignature->fragmentSamplerRootIndex = parameterCount;
  1748. rangeCount += 1;
  1749. parameterCount += 1;
  1750. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  1751. descriptorRange.NumDescriptors = fragmentShader->num_samplers;
  1752. descriptorRange.BaseShaderRegister = 0;
  1753. descriptorRange.RegisterSpace = 2;
  1754. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  1755. descriptorRanges[rangeCount] = descriptorRange;
  1756. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  1757. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  1758. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  1759. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  1760. rootParameters[parameterCount] = rootParameter;
  1761. d3d12GraphicsRootSignature->fragmentSamplerTextureRootIndex = parameterCount;
  1762. rangeCount += 1;
  1763. parameterCount += 1;
  1764. }
  1765. if (fragmentShader->numStorageTextures) {
  1766. // Fragment Storage Textures
  1767. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  1768. descriptorRange.NumDescriptors = fragmentShader->numStorageTextures;
  1769. descriptorRange.BaseShaderRegister = fragmentShader->num_samplers;
  1770. descriptorRange.RegisterSpace = 2;
  1771. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  1772. descriptorRanges[rangeCount] = descriptorRange;
  1773. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  1774. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  1775. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  1776. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  1777. rootParameters[parameterCount] = rootParameter;
  1778. d3d12GraphicsRootSignature->fragmentStorageTextureRootIndex = parameterCount;
  1779. rangeCount += 1;
  1780. parameterCount += 1;
  1781. }
  1782. if (fragmentShader->numStorageBuffers) {
  1783. // Fragment Storage Buffers
  1784. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  1785. descriptorRange.NumDescriptors = fragmentShader->numStorageBuffers;
  1786. descriptorRange.BaseShaderRegister = fragmentShader->num_samplers + fragmentShader->numStorageTextures;
  1787. descriptorRange.RegisterSpace = 2;
  1788. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  1789. descriptorRanges[rangeCount] = descriptorRange;
  1790. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  1791. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  1792. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  1793. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  1794. rootParameters[parameterCount] = rootParameter;
  1795. d3d12GraphicsRootSignature->fragmentStorageBufferRootIndex = parameterCount;
  1796. rangeCount += 1;
  1797. parameterCount += 1;
  1798. }
  1799. // Fragment Uniforms
  1800. for (Uint32 i = 0; i < fragmentShader->numUniformBuffers; i += 1) {
  1801. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
  1802. rootParameter.Descriptor.ShaderRegister = i;
  1803. rootParameter.Descriptor.RegisterSpace = 3;
  1804. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  1805. rootParameters[parameterCount] = rootParameter;
  1806. d3d12GraphicsRootSignature->fragmentUniformBufferRootIndex[i] = parameterCount;
  1807. parameterCount += 1;
  1808. }
  1809. // FIXME: shouldn't have to assert here
  1810. SDL_assert(parameterCount <= MAX_ROOT_SIGNATURE_PARAMETERS);
  1811. SDL_assert(rangeCount <= MAX_ROOT_SIGNATURE_PARAMETERS);
  1812. // Create the root signature description
  1813. D3D12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  1814. rootSignatureDesc.NumParameters = parameterCount;
  1815. rootSignatureDesc.pParameters = rootParameters;
  1816. rootSignatureDesc.NumStaticSamplers = 0;
  1817. rootSignatureDesc.pStaticSamplers = NULL;
  1818. rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
  1819. // Serialize the root signature
  1820. ID3DBlob *serializedRootSignature;
  1821. ID3DBlob *errorBlob;
  1822. HRESULT res = renderer->D3D12SerializeRootSignature_func(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &serializedRootSignature, &errorBlob);
  1823. if (FAILED(res)) {
  1824. if (errorBlob) {
  1825. SET_ERROR("Failed to serialize RootSignature: %s", (const char *)ID3D10Blob_GetBufferPointer(errorBlob));
  1826. ID3D10Blob_Release(errorBlob);
  1827. }
  1828. D3D12_INTERNAL_DestroyGraphicsRootSignature(d3d12GraphicsRootSignature);
  1829. return NULL;
  1830. }
  1831. // Create the root signature
  1832. ID3D12RootSignature *rootSignature;
  1833. res = ID3D12Device_CreateRootSignature(
  1834. renderer->device,
  1835. 0,
  1836. ID3D10Blob_GetBufferPointer(serializedRootSignature),
  1837. ID3D10Blob_GetBufferSize(serializedRootSignature),
  1838. D3D_GUID(D3D_IID_ID3D12RootSignature),
  1839. (void **)&rootSignature);
  1840. if (FAILED(res)) {
  1841. if (errorBlob) {
  1842. SET_ERROR("Failed to create RootSignature: %s", (const char *)ID3D10Blob_GetBufferPointer(errorBlob));
  1843. ID3D10Blob_Release(errorBlob);
  1844. }
  1845. D3D12_INTERNAL_DestroyGraphicsRootSignature(d3d12GraphicsRootSignature);
  1846. return NULL;
  1847. }
  1848. d3d12GraphicsRootSignature->handle = rootSignature;
  1849. return d3d12GraphicsRootSignature;
  1850. }
  1851. static bool D3D12_INTERNAL_CreateShaderBytecode(
  1852. D3D12Renderer *renderer,
  1853. Uint32 stage,
  1854. SDL_GPUShaderFormat format,
  1855. const Uint8 *code,
  1856. size_t codeSize,
  1857. const char *entrypointName,
  1858. void **pBytecode,
  1859. size_t *pBytecodeSize)
  1860. {
  1861. if (pBytecode != NULL) {
  1862. *pBytecode = SDL_malloc(codeSize);
  1863. if (!*pBytecode) {
  1864. return false;
  1865. }
  1866. SDL_memcpy(*pBytecode, code, codeSize);
  1867. *pBytecodeSize = codeSize;
  1868. }
  1869. return true;
  1870. }
  1871. static D3D12ComputeRootSignature *D3D12_INTERNAL_CreateComputeRootSignature(
  1872. D3D12Renderer *renderer,
  1873. const SDL_GPUComputePipelineCreateInfo *createInfo)
  1874. {
  1875. // FIXME: I think the max can be smaller...
  1876. D3D12_ROOT_PARAMETER rootParameters[MAX_ROOT_SIGNATURE_PARAMETERS];
  1877. D3D12_DESCRIPTOR_RANGE descriptorRanges[MAX_ROOT_SIGNATURE_PARAMETERS];
  1878. Uint32 parameterCount = 0;
  1879. Uint32 rangeCount = 0;
  1880. D3D12_DESCRIPTOR_RANGE descriptorRange;
  1881. D3D12_ROOT_PARAMETER rootParameter;
  1882. D3D12ComputeRootSignature *d3d12ComputeRootSignature =
  1883. (D3D12ComputeRootSignature *)SDL_calloc(1, sizeof(D3D12ComputeRootSignature));
  1884. if (!d3d12ComputeRootSignature) {
  1885. return NULL;
  1886. }
  1887. SDL_zeroa(rootParameters);
  1888. SDL_zeroa(descriptorRanges);
  1889. SDL_zero(rootParameter);
  1890. d3d12ComputeRootSignature->samplerRootIndex = -1;
  1891. d3d12ComputeRootSignature->samplerTextureRootIndex = -1;
  1892. d3d12ComputeRootSignature->readOnlyStorageTextureRootIndex = -1;
  1893. d3d12ComputeRootSignature->readOnlyStorageBufferRootIndex = -1;
  1894. d3d12ComputeRootSignature->readWriteStorageTextureRootIndex = -1;
  1895. d3d12ComputeRootSignature->readWriteStorageBufferRootIndex = -1;
  1896. for (Uint32 i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  1897. d3d12ComputeRootSignature->uniformBufferRootIndex[i] = -1;
  1898. }
  1899. if (createInfo->num_samplers) {
  1900. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER;
  1901. descriptorRange.NumDescriptors = createInfo->num_samplers;
  1902. descriptorRange.BaseShaderRegister = 0;
  1903. descriptorRange.RegisterSpace = 0;
  1904. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  1905. descriptorRanges[rangeCount] = descriptorRange;
  1906. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  1907. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  1908. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  1909. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // ALL is used for compute
  1910. rootParameters[parameterCount] = rootParameter;
  1911. d3d12ComputeRootSignature->samplerRootIndex = parameterCount;
  1912. rangeCount += 1;
  1913. parameterCount += 1;
  1914. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  1915. descriptorRange.NumDescriptors = createInfo->num_samplers;
  1916. descriptorRange.BaseShaderRegister = 0;
  1917. descriptorRange.RegisterSpace = 0;
  1918. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  1919. descriptorRanges[rangeCount] = descriptorRange;
  1920. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  1921. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  1922. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  1923. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // ALL is used for compute
  1924. rootParameters[parameterCount] = rootParameter;
  1925. d3d12ComputeRootSignature->samplerTextureRootIndex = parameterCount;
  1926. rangeCount += 1;
  1927. parameterCount += 1;
  1928. }
  1929. if (createInfo->num_readonly_storage_textures) {
  1930. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  1931. descriptorRange.NumDescriptors = createInfo->num_readonly_storage_textures;
  1932. descriptorRange.BaseShaderRegister = createInfo->num_samplers;
  1933. descriptorRange.RegisterSpace = 0;
  1934. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  1935. descriptorRanges[rangeCount] = descriptorRange;
  1936. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  1937. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  1938. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  1939. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // ALL is used for compute
  1940. rootParameters[parameterCount] = rootParameter;
  1941. d3d12ComputeRootSignature->readOnlyStorageTextureRootIndex = parameterCount;
  1942. rangeCount += 1;
  1943. parameterCount += 1;
  1944. }
  1945. if (createInfo->num_readonly_storage_buffers) {
  1946. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  1947. descriptorRange.NumDescriptors = createInfo->num_readonly_storage_buffers;
  1948. descriptorRange.BaseShaderRegister = createInfo->num_samplers + createInfo->num_readonly_storage_textures;
  1949. descriptorRange.RegisterSpace = 0;
  1950. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  1951. descriptorRanges[rangeCount] = descriptorRange;
  1952. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  1953. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  1954. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  1955. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // ALL is used for compute
  1956. rootParameters[parameterCount] = rootParameter;
  1957. d3d12ComputeRootSignature->readOnlyStorageBufferRootIndex = parameterCount;
  1958. rangeCount += 1;
  1959. parameterCount += 1;
  1960. }
  1961. if (createInfo->num_readwrite_storage_textures) {
  1962. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
  1963. descriptorRange.NumDescriptors = createInfo->num_readwrite_storage_textures;
  1964. descriptorRange.BaseShaderRegister = 0;
  1965. descriptorRange.RegisterSpace = 1;
  1966. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  1967. descriptorRanges[rangeCount] = descriptorRange;
  1968. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  1969. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  1970. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  1971. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // ALL is used for compute
  1972. rootParameters[parameterCount] = rootParameter;
  1973. d3d12ComputeRootSignature->readWriteStorageTextureRootIndex = parameterCount;
  1974. rangeCount += 1;
  1975. parameterCount += 1;
  1976. }
  1977. if (createInfo->num_readwrite_storage_buffers) {
  1978. descriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
  1979. descriptorRange.NumDescriptors = createInfo->num_readwrite_storage_buffers;
  1980. descriptorRange.BaseShaderRegister = createInfo->num_readwrite_storage_textures;
  1981. descriptorRange.RegisterSpace = 1;
  1982. descriptorRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
  1983. descriptorRanges[rangeCount] = descriptorRange;
  1984. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  1985. rootParameter.DescriptorTable.NumDescriptorRanges = 1;
  1986. rootParameter.DescriptorTable.pDescriptorRanges = &descriptorRanges[rangeCount];
  1987. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // ALL is used for compute
  1988. rootParameters[parameterCount] = rootParameter;
  1989. d3d12ComputeRootSignature->readWriteStorageBufferRootIndex = parameterCount;
  1990. rangeCount += 1;
  1991. parameterCount += 1;
  1992. }
  1993. for (Uint32 i = 0; i < createInfo->num_uniform_buffers; i += 1) {
  1994. rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
  1995. rootParameter.Descriptor.ShaderRegister = i;
  1996. rootParameter.Descriptor.RegisterSpace = 2;
  1997. rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // ALL is used for compute
  1998. rootParameters[parameterCount] = rootParameter;
  1999. d3d12ComputeRootSignature->uniformBufferRootIndex[i] = parameterCount;
  2000. parameterCount += 1;
  2001. }
  2002. D3D12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  2003. rootSignatureDesc.NumParameters = parameterCount;
  2004. rootSignatureDesc.pParameters = rootParameters;
  2005. rootSignatureDesc.NumStaticSamplers = 0;
  2006. rootSignatureDesc.pStaticSamplers = NULL;
  2007. rootSignatureDesc.Flags = (D3D12_ROOT_SIGNATURE_FLAGS)0;
  2008. ID3DBlob *serializedRootSignature;
  2009. ID3DBlob *errorBlob;
  2010. HRESULT res = renderer->D3D12SerializeRootSignature_func(
  2011. &rootSignatureDesc,
  2012. D3D_ROOT_SIGNATURE_VERSION_1,
  2013. &serializedRootSignature,
  2014. &errorBlob);
  2015. if (FAILED(res)) {
  2016. if (errorBlob) {
  2017. SET_ERROR("Failed to serialize RootSignature: %s", (const char *)ID3D10Blob_GetBufferPointer(errorBlob));
  2018. ID3D10Blob_Release(errorBlob);
  2019. }
  2020. D3D12_INTERNAL_DestroyComputeRootSignature(d3d12ComputeRootSignature);
  2021. return NULL;
  2022. }
  2023. ID3D12RootSignature *rootSignature;
  2024. res = ID3D12Device_CreateRootSignature(
  2025. renderer->device,
  2026. 0,
  2027. ID3D10Blob_GetBufferPointer(serializedRootSignature),
  2028. ID3D10Blob_GetBufferSize(serializedRootSignature),
  2029. D3D_GUID(D3D_IID_ID3D12RootSignature),
  2030. (void **)&rootSignature);
  2031. if (FAILED(res)) {
  2032. if (errorBlob) {
  2033. SET_ERROR("Failed to create RootSignature: %s", (const char *)ID3D10Blob_GetBufferPointer(errorBlob));
  2034. ID3D10Blob_Release(errorBlob);
  2035. }
  2036. D3D12_INTERNAL_DestroyComputeRootSignature(d3d12ComputeRootSignature);
  2037. return NULL;
  2038. }
  2039. d3d12ComputeRootSignature->handle = rootSignature;
  2040. return d3d12ComputeRootSignature;
  2041. }
  2042. static SDL_GPUComputePipeline *D3D12_CreateComputePipeline(
  2043. SDL_GPURenderer *driverData,
  2044. const SDL_GPUComputePipelineCreateInfo *createinfo)
  2045. {
  2046. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  2047. void *bytecode;
  2048. size_t bytecodeSize;
  2049. ID3D12PipelineState *pipelineState;
  2050. if (!D3D12_INTERNAL_CreateShaderBytecode(
  2051. renderer,
  2052. SDL_GPU_SHADERSTAGE_COMPUTE,
  2053. createinfo->format,
  2054. createinfo->code,
  2055. createinfo->code_size,
  2056. createinfo->entrypoint,
  2057. &bytecode,
  2058. &bytecodeSize)) {
  2059. return NULL;
  2060. }
  2061. D3D12ComputeRootSignature *rootSignature = D3D12_INTERNAL_CreateComputeRootSignature(
  2062. renderer,
  2063. createinfo);
  2064. if (rootSignature == NULL) {
  2065. SDL_free(bytecode);
  2066. SET_STRING_ERROR_AND_RETURN("Could not create root signature!", NULL)
  2067. }
  2068. D3D12_COMPUTE_PIPELINE_STATE_DESC pipelineDesc;
  2069. pipelineDesc.CS.pShaderBytecode = bytecode;
  2070. pipelineDesc.CS.BytecodeLength = bytecodeSize;
  2071. pipelineDesc.pRootSignature = rootSignature->handle;
  2072. pipelineDesc.CachedPSO.CachedBlobSizeInBytes = 0;
  2073. pipelineDesc.CachedPSO.pCachedBlob = NULL;
  2074. pipelineDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
  2075. pipelineDesc.NodeMask = 0;
  2076. HRESULT res = ID3D12Device_CreateComputePipelineState(
  2077. renderer->device,
  2078. &pipelineDesc,
  2079. D3D_GUID(D3D_IID_ID3D12PipelineState),
  2080. (void **)&pipelineState);
  2081. if (FAILED(res)) {
  2082. D3D12_INTERNAL_SetError(renderer, "Could not create compute pipeline state", res);
  2083. SDL_free(bytecode);
  2084. return NULL;
  2085. }
  2086. D3D12ComputePipeline *computePipeline =
  2087. (D3D12ComputePipeline *)SDL_calloc(1, sizeof(D3D12ComputePipeline));
  2088. if (!computePipeline) {
  2089. ID3D12PipelineState_Release(pipelineState);
  2090. SDL_free(bytecode);
  2091. return NULL;
  2092. }
  2093. computePipeline->pipelineState = pipelineState;
  2094. computePipeline->rootSignature = rootSignature;
  2095. computePipeline->numSamplers = createinfo->num_samplers;
  2096. computePipeline->numReadOnlyStorageTextures = createinfo->num_readonly_storage_textures;
  2097. computePipeline->numReadOnlyStorageBuffers = createinfo->num_readonly_storage_buffers;
  2098. computePipeline->numReadWriteStorageTextures = createinfo->num_readwrite_storage_textures;
  2099. computePipeline->numReadWriteStorageBuffers = createinfo->num_readwrite_storage_buffers;
  2100. computePipeline->numUniformBuffers = createinfo->num_uniform_buffers;
  2101. SDL_SetAtomicInt(&computePipeline->referenceCount, 0);
  2102. return (SDL_GPUComputePipeline *)computePipeline;
  2103. }
  2104. static bool D3D12_INTERNAL_ConvertRasterizerState(SDL_GPURasterizerState rasterizerState, D3D12_RASTERIZER_DESC *desc)
  2105. {
  2106. if (!desc) {
  2107. return false;
  2108. }
  2109. desc->FillMode = SDLToD3D12_FillMode[rasterizerState.fill_mode];
  2110. desc->CullMode = SDLToD3D12_CullMode[rasterizerState.cull_mode];
  2111. switch (rasterizerState.front_face) {
  2112. case SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE:
  2113. desc->FrontCounterClockwise = TRUE;
  2114. break;
  2115. case SDL_GPU_FRONTFACE_CLOCKWISE:
  2116. desc->FrontCounterClockwise = FALSE;
  2117. break;
  2118. default:
  2119. return false;
  2120. }
  2121. if (rasterizerState.enable_depth_bias) {
  2122. desc->DepthBias = SDL_lroundf(rasterizerState.depth_bias_constant_factor);
  2123. desc->DepthBiasClamp = rasterizerState.depth_bias_clamp;
  2124. desc->SlopeScaledDepthBias = rasterizerState.depth_bias_slope_factor;
  2125. } else {
  2126. desc->DepthBias = 0;
  2127. desc->DepthBiasClamp = 0.0f;
  2128. desc->SlopeScaledDepthBias = 0.0f;
  2129. }
  2130. desc->DepthClipEnable = rasterizerState.enable_depth_clip;
  2131. desc->MultisampleEnable = FALSE;
  2132. desc->AntialiasedLineEnable = FALSE;
  2133. desc->ForcedSampleCount = 0;
  2134. desc->ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
  2135. return true;
  2136. }
  2137. static bool D3D12_INTERNAL_ConvertBlendState(
  2138. const SDL_GPUGraphicsPipelineCreateInfo *pipelineInfo,
  2139. D3D12_BLEND_DESC *blendDesc)
  2140. {
  2141. if (!blendDesc) {
  2142. return false;
  2143. }
  2144. SDL_zerop(blendDesc);
  2145. blendDesc->AlphaToCoverageEnable = FALSE;
  2146. blendDesc->IndependentBlendEnable = FALSE;
  2147. for (UINT i = 0; i < MAX_COLOR_TARGET_BINDINGS; i += 1) {
  2148. D3D12_RENDER_TARGET_BLEND_DESC rtBlendDesc;
  2149. rtBlendDesc.BlendEnable = FALSE;
  2150. rtBlendDesc.LogicOpEnable = FALSE;
  2151. rtBlendDesc.SrcBlend = D3D12_BLEND_ONE;
  2152. rtBlendDesc.DestBlend = D3D12_BLEND_ZERO;
  2153. rtBlendDesc.BlendOp = D3D12_BLEND_OP_ADD;
  2154. rtBlendDesc.SrcBlendAlpha = D3D12_BLEND_ONE;
  2155. rtBlendDesc.DestBlendAlpha = D3D12_BLEND_ZERO;
  2156. rtBlendDesc.BlendOpAlpha = D3D12_BLEND_OP_ADD;
  2157. rtBlendDesc.LogicOp = D3D12_LOGIC_OP_NOOP;
  2158. rtBlendDesc.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
  2159. // If target_info has more blend states, you can set IndependentBlendEnable to TRUE and assign different blend states to each render target slot
  2160. if (i < pipelineInfo->target_info.num_color_targets) {
  2161. SDL_GPUColorTargetBlendState sdlBlendState = pipelineInfo->target_info.color_target_descriptions[i].blend_state;
  2162. SDL_GPUColorComponentFlags colorWriteMask = sdlBlendState.enable_color_write_mask ?
  2163. sdlBlendState.color_write_mask :
  2164. 0xF;
  2165. rtBlendDesc.BlendEnable = sdlBlendState.enable_blend;
  2166. rtBlendDesc.SrcBlend = SDLToD3D12_BlendFactor[sdlBlendState.src_color_blendfactor];
  2167. rtBlendDesc.DestBlend = SDLToD3D12_BlendFactor[sdlBlendState.dst_color_blendfactor];
  2168. rtBlendDesc.BlendOp = SDLToD3D12_BlendOp[sdlBlendState.color_blend_op];
  2169. rtBlendDesc.SrcBlendAlpha = SDLToD3D12_BlendFactorAlpha[sdlBlendState.src_alpha_blendfactor];
  2170. rtBlendDesc.DestBlendAlpha = SDLToD3D12_BlendFactorAlpha[sdlBlendState.dst_alpha_blendfactor];
  2171. rtBlendDesc.BlendOpAlpha = SDLToD3D12_BlendOp[sdlBlendState.alpha_blend_op];
  2172. rtBlendDesc.RenderTargetWriteMask = colorWriteMask;
  2173. if (i > 0) {
  2174. blendDesc->IndependentBlendEnable = TRUE;
  2175. }
  2176. }
  2177. blendDesc->RenderTarget[i] = rtBlendDesc;
  2178. }
  2179. return true;
  2180. }
  2181. static bool D3D12_INTERNAL_ConvertDepthStencilState(SDL_GPUDepthStencilState depthStencilState, D3D12_DEPTH_STENCIL_DESC *desc)
  2182. {
  2183. if (desc == NULL) {
  2184. return false;
  2185. }
  2186. desc->DepthEnable = depthStencilState.enable_depth_test == true ? TRUE : FALSE;
  2187. desc->DepthWriteMask = depthStencilState.enable_depth_write == true ? D3D12_DEPTH_WRITE_MASK_ALL : D3D12_DEPTH_WRITE_MASK_ZERO;
  2188. desc->DepthFunc = SDLToD3D12_CompareOp[depthStencilState.compare_op];
  2189. desc->StencilEnable = depthStencilState.enable_stencil_test == true ? TRUE : FALSE;
  2190. desc->StencilReadMask = depthStencilState.compare_mask;
  2191. desc->StencilWriteMask = depthStencilState.write_mask;
  2192. desc->FrontFace.StencilFailOp = SDLToD3D12_StencilOp[depthStencilState.front_stencil_state.fail_op];
  2193. desc->FrontFace.StencilDepthFailOp = SDLToD3D12_StencilOp[depthStencilState.front_stencil_state.depth_fail_op];
  2194. desc->FrontFace.StencilPassOp = SDLToD3D12_StencilOp[depthStencilState.front_stencil_state.pass_op];
  2195. desc->FrontFace.StencilFunc = SDLToD3D12_CompareOp[depthStencilState.front_stencil_state.compare_op];
  2196. desc->BackFace.StencilFailOp = SDLToD3D12_StencilOp[depthStencilState.back_stencil_state.fail_op];
  2197. desc->BackFace.StencilDepthFailOp = SDLToD3D12_StencilOp[depthStencilState.back_stencil_state.depth_fail_op];
  2198. desc->BackFace.StencilPassOp = SDLToD3D12_StencilOp[depthStencilState.back_stencil_state.pass_op];
  2199. desc->BackFace.StencilFunc = SDLToD3D12_CompareOp[depthStencilState.back_stencil_state.compare_op];
  2200. return true;
  2201. }
  2202. static bool D3D12_INTERNAL_ConvertVertexInputState(SDL_GPUVertexInputState vertexInputState, D3D12_INPUT_ELEMENT_DESC *desc, const char *semantic)
  2203. {
  2204. if (desc == NULL || vertexInputState.num_vertex_attributes == 0) {
  2205. return false;
  2206. }
  2207. for (Uint32 i = 0; i < vertexInputState.num_vertex_attributes; i += 1) {
  2208. SDL_GPUVertexAttribute attribute = vertexInputState.vertex_attributes[i];
  2209. desc[i].SemanticName = semantic;
  2210. desc[i].SemanticIndex = attribute.location;
  2211. desc[i].Format = SDLToD3D12_VertexFormat[attribute.format];
  2212. desc[i].InputSlot = attribute.buffer_slot;
  2213. desc[i].AlignedByteOffset = attribute.offset;
  2214. desc[i].InputSlotClass = SDLToD3D12_InputRate[vertexInputState.vertex_buffer_descriptions[attribute.buffer_slot].input_rate];
  2215. desc[i].InstanceDataStepRate = (vertexInputState.vertex_buffer_descriptions[attribute.buffer_slot].input_rate == SDL_GPU_VERTEXINPUTRATE_INSTANCE)
  2216. ? vertexInputState.vertex_buffer_descriptions[attribute.buffer_slot].instance_step_rate
  2217. : 0;
  2218. }
  2219. return true;
  2220. }
  2221. static void D3D12_INTERNAL_AssignCpuDescriptorHandle(
  2222. D3D12Renderer *renderer,
  2223. D3D12_DESCRIPTOR_HEAP_TYPE heapType,
  2224. D3D12CPUDescriptor *cpuDescriptor)
  2225. {
  2226. D3D12DescriptorHeap *heap = renderer->stagingDescriptorHeaps[heapType];
  2227. Uint32 descriptorIndex;
  2228. cpuDescriptor->heap = heap;
  2229. SDL_LockMutex(renderer->stagingDescriptorHeapLock);
  2230. if (heap->inactiveDescriptorCount > 0) {
  2231. descriptorIndex = heap->inactiveDescriptorIndices[heap->inactiveDescriptorCount - 1];
  2232. heap->inactiveDescriptorCount -= 1;
  2233. } else if (heap->currentDescriptorIndex < heap->maxDescriptors) {
  2234. descriptorIndex = heap->currentDescriptorIndex;
  2235. heap->currentDescriptorIndex += 1;
  2236. } else {
  2237. cpuDescriptor->cpuHandleIndex = SDL_MAX_UINT32;
  2238. cpuDescriptor->cpuHandle.ptr = 0;
  2239. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Out of CPU descriptor handles, many bad things are going to happen!");
  2240. SDL_UnlockMutex(renderer->stagingDescriptorHeapLock);
  2241. return;
  2242. }
  2243. SDL_UnlockMutex(renderer->stagingDescriptorHeapLock);
  2244. cpuDescriptor->cpuHandleIndex = descriptorIndex;
  2245. cpuDescriptor->cpuHandle.ptr = heap->descriptorHeapCPUStart.ptr + (descriptorIndex * heap->descriptorSize);
  2246. }
  2247. static SDL_GPUGraphicsPipeline *D3D12_CreateGraphicsPipeline(
  2248. SDL_GPURenderer *driverData,
  2249. const SDL_GPUGraphicsPipelineCreateInfo *createinfo)
  2250. {
  2251. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  2252. D3D12Shader *vertShader = (D3D12Shader *)createinfo->vertex_shader;
  2253. D3D12Shader *fragShader = (D3D12Shader *)createinfo->fragment_shader;
  2254. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
  2255. SDL_zero(psoDesc);
  2256. psoDesc.VS.pShaderBytecode = vertShader->bytecode;
  2257. psoDesc.VS.BytecodeLength = vertShader->bytecodeSize;
  2258. psoDesc.PS.pShaderBytecode = fragShader->bytecode;
  2259. psoDesc.PS.BytecodeLength = fragShader->bytecodeSize;
  2260. D3D12_INPUT_ELEMENT_DESC inputElementDescs[D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT];
  2261. if (createinfo->vertex_input_state.num_vertex_attributes > 0) {
  2262. psoDesc.InputLayout.pInputElementDescs = inputElementDescs;
  2263. psoDesc.InputLayout.NumElements = createinfo->vertex_input_state.num_vertex_attributes;
  2264. D3D12_INTERNAL_ConvertVertexInputState(createinfo->vertex_input_state, inputElementDescs, renderer->semantic);
  2265. }
  2266. psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  2267. if (!D3D12_INTERNAL_ConvertRasterizerState(createinfo->rasterizer_state, &psoDesc.RasterizerState)) {
  2268. return NULL;
  2269. }
  2270. if (!D3D12_INTERNAL_ConvertBlendState(createinfo, &psoDesc.BlendState)) {
  2271. return NULL;
  2272. }
  2273. if (!D3D12_INTERNAL_ConvertDepthStencilState(createinfo->depth_stencil_state, &psoDesc.DepthStencilState)) {
  2274. return NULL;
  2275. }
  2276. D3D12GraphicsPipeline *pipeline = (D3D12GraphicsPipeline *)SDL_calloc(1, sizeof(D3D12GraphicsPipeline));
  2277. if (!pipeline) {
  2278. return NULL;
  2279. }
  2280. Uint32 sampleMask = createinfo->multisample_state.enable_mask ?
  2281. createinfo->multisample_state.sample_mask :
  2282. 0xFFFFFFFF;
  2283. psoDesc.SampleMask = sampleMask;
  2284. psoDesc.SampleDesc.Count = SDLToD3D12_SampleCount[createinfo->multisample_state.sample_count];
  2285. psoDesc.SampleDesc.Quality = (createinfo->multisample_state.sample_count > SDL_GPU_SAMPLECOUNT_1) ? D3D12_STANDARD_MULTISAMPLE_PATTERN : 0;
  2286. psoDesc.DSVFormat = SDLToD3D12_TextureFormat[createinfo->target_info.depth_stencil_format];
  2287. psoDesc.NumRenderTargets = createinfo->target_info.num_color_targets;
  2288. for (uint32_t i = 0; i < createinfo->target_info.num_color_targets; i += 1) {
  2289. psoDesc.RTVFormats[i] = SDLToD3D12_TextureFormat[createinfo->target_info.color_target_descriptions[i].format];
  2290. }
  2291. // Assuming some default values or further initialization
  2292. psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
  2293. psoDesc.CachedPSO.CachedBlobSizeInBytes = 0;
  2294. psoDesc.CachedPSO.pCachedBlob = NULL;
  2295. psoDesc.NodeMask = 0;
  2296. D3D12GraphicsRootSignature *rootSignature = D3D12_INTERNAL_CreateGraphicsRootSignature(
  2297. renderer,
  2298. vertShader,
  2299. fragShader);
  2300. if (rootSignature == NULL) {
  2301. D3D12_INTERNAL_DestroyGraphicsPipeline(pipeline);
  2302. return NULL;
  2303. }
  2304. pipeline->rootSignature = rootSignature;
  2305. psoDesc.pRootSignature = rootSignature->handle;
  2306. ID3D12PipelineState *pipelineState;
  2307. HRESULT res = ID3D12Device_CreateGraphicsPipelineState(
  2308. renderer->device,
  2309. &psoDesc,
  2310. D3D_GUID(D3D_IID_ID3D12PipelineState),
  2311. (void **)&pipelineState);
  2312. if (FAILED(res)) {
  2313. D3D12_INTERNAL_SetError(renderer, "Could not create graphics pipeline state", res);
  2314. D3D12_INTERNAL_DestroyGraphicsPipeline(pipeline);
  2315. return NULL;
  2316. }
  2317. pipeline->pipelineState = pipelineState;
  2318. for (Uint32 i = 0; i < createinfo->vertex_input_state.num_vertex_buffers; i += 1) {
  2319. pipeline->vertexStrides[createinfo->vertex_input_state.vertex_buffer_descriptions[i].slot] =
  2320. createinfo->vertex_input_state.vertex_buffer_descriptions[i].pitch;
  2321. }
  2322. pipeline->primitiveType = createinfo->primitive_type;
  2323. pipeline->vertexSamplerCount = vertShader->num_samplers;
  2324. pipeline->vertexStorageTextureCount = vertShader->numStorageTextures;
  2325. pipeline->vertexStorageBufferCount = vertShader->numStorageBuffers;
  2326. pipeline->vertexUniformBufferCount = vertShader->numUniformBuffers;
  2327. pipeline->fragmentSamplerCount = fragShader->num_samplers;
  2328. pipeline->fragmentStorageTextureCount = fragShader->numStorageTextures;
  2329. pipeline->fragmentStorageBufferCount = fragShader->numStorageBuffers;
  2330. pipeline->fragmentUniformBufferCount = fragShader->numUniformBuffers;
  2331. SDL_SetAtomicInt(&pipeline->referenceCount, 0);
  2332. return (SDL_GPUGraphicsPipeline *)pipeline;
  2333. }
  2334. static SDL_GPUSampler *D3D12_CreateSampler(
  2335. SDL_GPURenderer *driverData,
  2336. const SDL_GPUSamplerCreateInfo *createinfo)
  2337. {
  2338. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  2339. D3D12Sampler *sampler = (D3D12Sampler *)SDL_calloc(1, sizeof(D3D12Sampler));
  2340. if (!sampler) {
  2341. return NULL;
  2342. }
  2343. D3D12_SAMPLER_DESC samplerDesc;
  2344. samplerDesc.Filter = SDLToD3D12_Filter(
  2345. createinfo->min_filter,
  2346. createinfo->mag_filter,
  2347. createinfo->mipmap_mode,
  2348. createinfo->enable_compare,
  2349. createinfo->enable_anisotropy);
  2350. samplerDesc.AddressU = SDLToD3D12_SamplerAddressMode[createinfo->address_mode_u];
  2351. samplerDesc.AddressV = SDLToD3D12_SamplerAddressMode[createinfo->address_mode_v];
  2352. samplerDesc.AddressW = SDLToD3D12_SamplerAddressMode[createinfo->address_mode_w];
  2353. samplerDesc.MaxAnisotropy = (Uint32)createinfo->max_anisotropy;
  2354. samplerDesc.ComparisonFunc = SDLToD3D12_CompareOp[createinfo->compare_op];
  2355. samplerDesc.MinLOD = createinfo->min_lod;
  2356. samplerDesc.MaxLOD = createinfo->max_lod;
  2357. samplerDesc.MipLODBias = createinfo->mip_lod_bias;
  2358. samplerDesc.BorderColor[0] = 0;
  2359. samplerDesc.BorderColor[1] = 0;
  2360. samplerDesc.BorderColor[2] = 0;
  2361. samplerDesc.BorderColor[3] = 0;
  2362. D3D12_INTERNAL_AssignCpuDescriptorHandle(
  2363. renderer,
  2364. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
  2365. &sampler->handle);
  2366. ID3D12Device_CreateSampler(
  2367. renderer->device,
  2368. &samplerDesc,
  2369. sampler->handle.cpuHandle);
  2370. sampler->createInfo = *createinfo;
  2371. SDL_SetAtomicInt(&sampler->referenceCount, 0);
  2372. return (SDL_GPUSampler *)sampler;
  2373. }
  2374. static SDL_GPUShader *D3D12_CreateShader(
  2375. SDL_GPURenderer *driverData,
  2376. const SDL_GPUShaderCreateInfo *createinfo)
  2377. {
  2378. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  2379. void *bytecode;
  2380. size_t bytecodeSize;
  2381. D3D12Shader *shader;
  2382. if (!D3D12_INTERNAL_CreateShaderBytecode(
  2383. renderer,
  2384. createinfo->stage,
  2385. createinfo->format,
  2386. createinfo->code,
  2387. createinfo->code_size,
  2388. createinfo->entrypoint,
  2389. &bytecode,
  2390. &bytecodeSize)) {
  2391. return NULL;
  2392. }
  2393. shader = (D3D12Shader *)SDL_calloc(1, sizeof(D3D12Shader));
  2394. if (!shader) {
  2395. SDL_free(bytecode);
  2396. return NULL;
  2397. }
  2398. shader->num_samplers = createinfo->num_samplers;
  2399. shader->numStorageBuffers = createinfo->num_storage_buffers;
  2400. shader->numStorageTextures = createinfo->num_storage_textures;
  2401. shader->numUniformBuffers = createinfo->num_uniform_buffers;
  2402. shader->bytecode = bytecode;
  2403. shader->bytecodeSize = bytecodeSize;
  2404. return (SDL_GPUShader *)shader;
  2405. }
  2406. static D3D12Texture *D3D12_INTERNAL_CreateTexture(
  2407. D3D12Renderer *renderer,
  2408. const SDL_GPUTextureCreateInfo *createinfo,
  2409. bool isSwapchainTexture)
  2410. {
  2411. D3D12Texture *texture;
  2412. ID3D12Resource *handle;
  2413. D3D12_HEAP_PROPERTIES heapProperties;
  2414. D3D12_HEAP_FLAGS heapFlags = (D3D12_HEAP_FLAGS)0;
  2415. D3D12_RESOURCE_DESC desc;
  2416. D3D12_RESOURCE_FLAGS resourceFlags = (D3D12_RESOURCE_FLAGS)0;
  2417. D3D12_RESOURCE_STATES initialState = (D3D12_RESOURCE_STATES)0;
  2418. D3D12_CLEAR_VALUE clearValue;
  2419. bool useClearValue = false;
  2420. bool needsUAV =
  2421. (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE) ||
  2422. (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE);
  2423. HRESULT res;
  2424. texture = (D3D12Texture *)SDL_calloc(1, sizeof(D3D12Texture));
  2425. if (!texture) {
  2426. return NULL;
  2427. }
  2428. Uint32 layerCount = createinfo->type == SDL_GPU_TEXTURETYPE_3D ? 1 : createinfo->layer_count_or_depth;
  2429. Uint32 depth = createinfo->type == SDL_GPU_TEXTURETYPE_3D ? createinfo->layer_count_or_depth : 1;
  2430. bool isMultisample = createinfo->sample_count > SDL_GPU_SAMPLECOUNT_1;
  2431. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) {
  2432. resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
  2433. useClearValue = true;
  2434. clearValue.Color[0] = SDL_GetFloatProperty(createinfo->props, SDL_PROP_GPU_CREATETEXTURE_D3D12_CLEAR_R_FLOAT, 0);
  2435. clearValue.Color[1] = SDL_GetFloatProperty(createinfo->props, SDL_PROP_GPU_CREATETEXTURE_D3D12_CLEAR_G_FLOAT, 0);
  2436. clearValue.Color[2] = SDL_GetFloatProperty(createinfo->props, SDL_PROP_GPU_CREATETEXTURE_D3D12_CLEAR_B_FLOAT, 0);
  2437. clearValue.Color[3] = SDL_GetFloatProperty(createinfo->props, SDL_PROP_GPU_CREATETEXTURE_D3D12_CLEAR_A_FLOAT, 0);
  2438. }
  2439. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) {
  2440. resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
  2441. useClearValue = true;
  2442. clearValue.DepthStencil.Depth = SDL_GetFloatProperty(createinfo->props, SDL_PROP_GPU_CREATETEXTURE_D3D12_CLEAR_DEPTH_FLOAT, 0);
  2443. clearValue.DepthStencil.Stencil = (UINT8)SDL_GetNumberProperty(createinfo->props, SDL_PROP_GPU_CREATETEXTURE_D3D12_CLEAR_STENCIL_UINT8, 0);
  2444. }
  2445. if (needsUAV) {
  2446. resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
  2447. }
  2448. heapProperties.Type = D3D12_HEAP_TYPE_DEFAULT;
  2449. heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  2450. heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  2451. heapProperties.CreationNodeMask = 0; // We don't do multi-adapter operation
  2452. heapProperties.VisibleNodeMask = 0; // We don't do multi-adapter operation
  2453. heapFlags = isSwapchainTexture ? D3D12_HEAP_FLAG_ALLOW_DISPLAY : D3D12_HEAP_FLAG_NONE;
  2454. if (createinfo->type != SDL_GPU_TEXTURETYPE_3D) {
  2455. desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  2456. desc.Alignment = isSwapchainTexture ? 0 : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
  2457. desc.Width = createinfo->width;
  2458. desc.Height = createinfo->height;
  2459. desc.DepthOrArraySize = (UINT16)createinfo->layer_count_or_depth;
  2460. desc.MipLevels = (UINT16)createinfo->num_levels;
  2461. desc.Format = SDLToD3D12_TextureFormat[createinfo->format];
  2462. desc.SampleDesc.Count = SDLToD3D12_SampleCount[createinfo->sample_count];
  2463. desc.SampleDesc.Quality = isMultisample ? D3D12_STANDARD_MULTISAMPLE_PATTERN : 0;
  2464. desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // Apparently this is the most efficient choice
  2465. desc.Flags = resourceFlags;
  2466. } else {
  2467. desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D;
  2468. desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
  2469. desc.Width = createinfo->width;
  2470. desc.Height = createinfo->height;
  2471. desc.DepthOrArraySize = (UINT16)createinfo->layer_count_or_depth;
  2472. desc.MipLevels = (UINT16)createinfo->num_levels;
  2473. desc.Format = SDLToD3D12_TextureFormat[createinfo->format];
  2474. desc.SampleDesc.Count = 1;
  2475. desc.SampleDesc.Quality = 0;
  2476. desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  2477. desc.Flags = resourceFlags;
  2478. }
  2479. initialState = isSwapchainTexture ? D3D12_RESOURCE_STATE_PRESENT : D3D12_INTERNAL_DefaultTextureResourceState(createinfo->usage);
  2480. clearValue.Format = desc.Format;
  2481. res = ID3D12Device_CreateCommittedResource(
  2482. renderer->device,
  2483. &heapProperties,
  2484. heapFlags,
  2485. &desc,
  2486. initialState,
  2487. useClearValue ? &clearValue : NULL,
  2488. D3D_GUID(D3D_IID_ID3D12Resource),
  2489. (void **)&handle);
  2490. if (FAILED(res)) {
  2491. D3D12_INTERNAL_SetError(renderer, "Failed to create texture!", res);
  2492. D3D12_INTERNAL_DestroyTexture(renderer, texture);
  2493. return NULL;
  2494. }
  2495. texture->resource = handle;
  2496. // Create the SRV if applicable
  2497. if ((createinfo->usage & SDL_GPU_TEXTUREUSAGE_SAMPLER) ||
  2498. (createinfo->usage & SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ) ||
  2499. (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ)) {
  2500. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  2501. D3D12_INTERNAL_AssignCpuDescriptorHandle(
  2502. renderer,
  2503. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  2504. &texture->srvHandle);
  2505. srvDesc.Format = SDLToD3D12_TextureFormat[createinfo->format];
  2506. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  2507. if (createinfo->type == SDL_GPU_TEXTURETYPE_CUBE) {
  2508. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE;
  2509. srvDesc.TextureCube.MipLevels = createinfo->num_levels;
  2510. srvDesc.TextureCube.MostDetailedMip = 0;
  2511. srvDesc.TextureCube.ResourceMinLODClamp = 0;
  2512. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  2513. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBEARRAY;
  2514. srvDesc.TextureCubeArray.MipLevels = createinfo->num_levels;
  2515. srvDesc.TextureCubeArray.MostDetailedMip = 0;
  2516. srvDesc.TextureCubeArray.First2DArrayFace = 0;
  2517. srvDesc.TextureCubeArray.NumCubes = createinfo->layer_count_or_depth / 6;
  2518. srvDesc.TextureCubeArray.ResourceMinLODClamp = 0;
  2519. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_2D_ARRAY) {
  2520. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
  2521. srvDesc.Texture2DArray.MipLevels = createinfo->num_levels;
  2522. srvDesc.Texture2DArray.MostDetailedMip = 0;
  2523. srvDesc.Texture2DArray.FirstArraySlice = 0;
  2524. srvDesc.Texture2DArray.ArraySize = layerCount;
  2525. srvDesc.Texture2DArray.ResourceMinLODClamp = 0;
  2526. srvDesc.Texture2DArray.PlaneSlice = 0;
  2527. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_3D) {
  2528. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D;
  2529. srvDesc.Texture3D.MipLevels = createinfo->num_levels;
  2530. srvDesc.Texture3D.MostDetailedMip = 0;
  2531. srvDesc.Texture3D.ResourceMinLODClamp = 0; // default behavior
  2532. } else {
  2533. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  2534. srvDesc.Texture2D.MipLevels = createinfo->num_levels;
  2535. srvDesc.Texture2D.MostDetailedMip = 0;
  2536. srvDesc.Texture2D.PlaneSlice = 0;
  2537. srvDesc.Texture2D.ResourceMinLODClamp = 0; // default behavior
  2538. }
  2539. ID3D12Device_CreateShaderResourceView(
  2540. renderer->device,
  2541. handle,
  2542. &srvDesc,
  2543. texture->srvHandle.cpuHandle);
  2544. }
  2545. SDL_SetAtomicInt(&texture->referenceCount, 0);
  2546. texture->subresourceCount = createinfo->num_levels * layerCount;
  2547. texture->subresources = (D3D12TextureSubresource *)SDL_calloc(
  2548. texture->subresourceCount, sizeof(D3D12TextureSubresource));
  2549. if (!texture->subresources) {
  2550. D3D12_INTERNAL_DestroyTexture(renderer, texture);
  2551. return NULL;
  2552. }
  2553. for (Uint32 layerIndex = 0; layerIndex < layerCount; layerIndex += 1) {
  2554. for (Uint32 levelIndex = 0; levelIndex < createinfo->num_levels; levelIndex += 1) {
  2555. Uint32 subresourceIndex = D3D12_INTERNAL_CalcSubresource(
  2556. levelIndex,
  2557. layerIndex,
  2558. createinfo->num_levels);
  2559. texture->subresources[subresourceIndex].parent = texture;
  2560. texture->subresources[subresourceIndex].layer = layerIndex;
  2561. texture->subresources[subresourceIndex].level = levelIndex;
  2562. texture->subresources[subresourceIndex].depth = depth;
  2563. texture->subresources[subresourceIndex].index = subresourceIndex;
  2564. texture->subresources[subresourceIndex].rtvHandles = NULL;
  2565. texture->subresources[subresourceIndex].uavHandle.heap = NULL;
  2566. texture->subresources[subresourceIndex].dsvHandle.heap = NULL;
  2567. // Create RTV if needed
  2568. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) {
  2569. texture->subresources[subresourceIndex].rtvHandles = (D3D12CPUDescriptor *)SDL_calloc(depth, sizeof(D3D12CPUDescriptor));
  2570. for (Uint32 depthIndex = 0; depthIndex < depth; depthIndex += 1) {
  2571. D3D12_RENDER_TARGET_VIEW_DESC rtvDesc;
  2572. D3D12_INTERNAL_AssignCpuDescriptorHandle(
  2573. renderer,
  2574. D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  2575. &texture->subresources[subresourceIndex].rtvHandles[depthIndex]);
  2576. rtvDesc.Format = SDLToD3D12_TextureFormat[createinfo->format];
  2577. if (createinfo->type == SDL_GPU_TEXTURETYPE_2D_ARRAY || createinfo->type == SDL_GPU_TEXTURETYPE_CUBE || createinfo->type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  2578. rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
  2579. rtvDesc.Texture2DArray.MipSlice = levelIndex;
  2580. rtvDesc.Texture2DArray.FirstArraySlice = layerIndex;
  2581. rtvDesc.Texture2DArray.ArraySize = 1;
  2582. rtvDesc.Texture2DArray.PlaneSlice = 0;
  2583. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_3D) {
  2584. rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D;
  2585. rtvDesc.Texture3D.MipSlice = levelIndex;
  2586. rtvDesc.Texture3D.FirstWSlice = depthIndex;
  2587. rtvDesc.Texture3D.WSize = 1;
  2588. } else if (isMultisample) {
  2589. rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS;
  2590. } else {
  2591. rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
  2592. rtvDesc.Texture2D.MipSlice = levelIndex;
  2593. rtvDesc.Texture2D.PlaneSlice = 0;
  2594. }
  2595. ID3D12Device_CreateRenderTargetView(
  2596. renderer->device,
  2597. texture->resource,
  2598. &rtvDesc,
  2599. texture->subresources[subresourceIndex].rtvHandles[depthIndex].cpuHandle);
  2600. }
  2601. }
  2602. // Create DSV if needed
  2603. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) {
  2604. D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc;
  2605. D3D12_INTERNAL_AssignCpuDescriptorHandle(
  2606. renderer,
  2607. D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  2608. &texture->subresources[subresourceIndex].dsvHandle);
  2609. dsvDesc.Format = SDLToD3D12_TextureFormat[createinfo->format];
  2610. dsvDesc.Flags = (D3D12_DSV_FLAGS)0;
  2611. if (isMultisample) {
  2612. dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMS;
  2613. } else {
  2614. dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
  2615. dsvDesc.Texture2D.MipSlice = levelIndex;
  2616. }
  2617. ID3D12Device_CreateDepthStencilView(
  2618. renderer->device,
  2619. texture->resource,
  2620. &dsvDesc,
  2621. texture->subresources[subresourceIndex].dsvHandle.cpuHandle);
  2622. }
  2623. // Create subresource UAV if necessary
  2624. if (needsUAV) {
  2625. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc;
  2626. D3D12_INTERNAL_AssignCpuDescriptorHandle(
  2627. renderer,
  2628. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  2629. &texture->subresources[subresourceIndex].uavHandle);
  2630. uavDesc.Format = SDLToD3D12_TextureFormat[createinfo->format];
  2631. if (createinfo->type == SDL_GPU_TEXTURETYPE_2D_ARRAY || createinfo->type == SDL_GPU_TEXTURETYPE_CUBE || createinfo->type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  2632. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
  2633. uavDesc.Texture2DArray.MipSlice = levelIndex;
  2634. uavDesc.Texture2DArray.FirstArraySlice = layerIndex;
  2635. uavDesc.Texture2DArray.ArraySize = 1;
  2636. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_3D) {
  2637. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D;
  2638. uavDesc.Texture3D.MipSlice = levelIndex;
  2639. uavDesc.Texture3D.FirstWSlice = 0;
  2640. uavDesc.Texture3D.WSize = depth;
  2641. } else {
  2642. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
  2643. uavDesc.Texture2D.MipSlice = levelIndex;
  2644. uavDesc.Texture2D.PlaneSlice = 0;
  2645. }
  2646. ID3D12Device_CreateUnorderedAccessView(
  2647. renderer->device,
  2648. texture->resource,
  2649. NULL,
  2650. &uavDesc,
  2651. texture->subresources[subresourceIndex].uavHandle.cpuHandle);
  2652. }
  2653. }
  2654. }
  2655. return texture;
  2656. }
  2657. static SDL_GPUTexture *D3D12_CreateTexture(
  2658. SDL_GPURenderer *driverData,
  2659. const SDL_GPUTextureCreateInfo *createinfo)
  2660. {
  2661. D3D12TextureContainer *container = (D3D12TextureContainer *)SDL_calloc(1, sizeof(D3D12TextureContainer));
  2662. if (!container) {
  2663. return NULL;
  2664. }
  2665. container->header.info = *createinfo;
  2666. container->textureCapacity = 1;
  2667. container->textureCount = 1;
  2668. container->textures = (D3D12Texture **)SDL_calloc(
  2669. container->textureCapacity, sizeof(D3D12Texture *));
  2670. if (!container->textures) {
  2671. SDL_free(container);
  2672. return NULL;
  2673. }
  2674. container->debugName = NULL;
  2675. container->canBeCycled = true;
  2676. D3D12Texture *texture = D3D12_INTERNAL_CreateTexture(
  2677. (D3D12Renderer *)driverData,
  2678. createinfo,
  2679. false);
  2680. if (!texture) {
  2681. SDL_free(container->textures);
  2682. SDL_free(container);
  2683. return NULL;
  2684. }
  2685. container->textures[0] = texture;
  2686. container->activeTexture = texture;
  2687. texture->container = container;
  2688. texture->containerIndex = 0;
  2689. return (SDL_GPUTexture *)container;
  2690. }
  2691. static D3D12Buffer *D3D12_INTERNAL_CreateBuffer(
  2692. D3D12Renderer *renderer,
  2693. SDL_GPUBufferUsageFlags usageFlags,
  2694. Uint32 size,
  2695. D3D12BufferType type)
  2696. {
  2697. D3D12Buffer *buffer;
  2698. ID3D12Resource *handle;
  2699. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc;
  2700. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  2701. D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc;
  2702. D3D12_HEAP_PROPERTIES heapProperties;
  2703. D3D12_RESOURCE_DESC desc;
  2704. D3D12_HEAP_FLAGS heapFlags = (D3D12_HEAP_FLAGS)0;
  2705. D3D12_RESOURCE_FLAGS resourceFlags = (D3D12_RESOURCE_FLAGS)0;
  2706. D3D12_RESOURCE_STATES initialState = D3D12_RESOURCE_STATE_COMMON;
  2707. HRESULT res;
  2708. buffer = (D3D12Buffer *)SDL_calloc(1, sizeof(D3D12Buffer));
  2709. if (!buffer) {
  2710. return NULL;
  2711. }
  2712. if (usageFlags & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE) {
  2713. resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
  2714. }
  2715. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  2716. if (usageFlags & SDL_GPU_BUFFERUSAGE_INDIRECT) {
  2717. resourceFlags |= D3D12XBOX_RESOURCE_FLAG_ALLOW_INDIRECT_BUFFER;
  2718. }
  2719. #endif
  2720. heapProperties.CreationNodeMask = 0; // We don't do multi-adapter operation
  2721. heapProperties.VisibleNodeMask = 0; // We don't do multi-adapter operation
  2722. if (type == D3D12_BUFFER_TYPE_GPU) {
  2723. heapProperties.Type = D3D12_HEAP_TYPE_DEFAULT;
  2724. heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  2725. heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  2726. heapFlags = D3D12_HEAP_FLAG_NONE;
  2727. } else if (type == D3D12_BUFFER_TYPE_UPLOAD) {
  2728. heapProperties.Type = D3D12_HEAP_TYPE_UPLOAD;
  2729. heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  2730. heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  2731. heapFlags = D3D12_HEAP_FLAG_NONE;
  2732. initialState = D3D12_RESOURCE_STATE_GENERIC_READ;
  2733. } else if (type == D3D12_BUFFER_TYPE_DOWNLOAD) {
  2734. heapProperties.Type = D3D12_HEAP_TYPE_READBACK;
  2735. heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  2736. heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  2737. heapFlags = D3D12_HEAP_FLAG_NONE;
  2738. initialState = D3D12_RESOURCE_STATE_COPY_DEST;
  2739. } else if (type == D3D12_BUFFER_TYPE_UNIFORM) {
  2740. // D3D12 is badly designed, so we have to check if the fast path for uniform buffers is enabled
  2741. if (renderer->GPUUploadHeapSupported) {
  2742. heapProperties.Type = D3D12_HEAP_TYPE_GPU_UPLOAD;
  2743. heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  2744. heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  2745. } else {
  2746. heapProperties.Type = D3D12_HEAP_TYPE_UPLOAD;
  2747. heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  2748. heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  2749. initialState = D3D12_RESOURCE_STATE_GENERIC_READ;
  2750. }
  2751. heapFlags = D3D12_HEAP_FLAG_NONE;
  2752. } else {
  2753. SET_STRING_ERROR_AND_RETURN("Unrecognized buffer type!", NULL)
  2754. }
  2755. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  2756. desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
  2757. desc.Width = size;
  2758. desc.Height = 1;
  2759. desc.DepthOrArraySize = 1;
  2760. desc.MipLevels = 1;
  2761. desc.Format = DXGI_FORMAT_UNKNOWN;
  2762. desc.SampleDesc.Count = 1;
  2763. desc.SampleDesc.Quality = 0;
  2764. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  2765. desc.Flags = resourceFlags;
  2766. res = ID3D12Device_CreateCommittedResource(
  2767. renderer->device,
  2768. &heapProperties,
  2769. heapFlags,
  2770. &desc,
  2771. initialState,
  2772. NULL,
  2773. D3D_GUID(D3D_IID_ID3D12Resource),
  2774. (void **)&handle);
  2775. if (FAILED(res)) {
  2776. D3D12_INTERNAL_SetError(renderer, "Could not create buffer!", res);
  2777. D3D12_INTERNAL_DestroyBuffer(renderer, buffer);
  2778. return NULL;
  2779. }
  2780. buffer->handle = handle;
  2781. SDL_SetAtomicInt(&buffer->referenceCount, 0);
  2782. buffer->uavDescriptor.heap = NULL;
  2783. buffer->srvDescriptor.heap = NULL;
  2784. buffer->cbvDescriptor.heap = NULL;
  2785. if (usageFlags & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE) {
  2786. D3D12_INTERNAL_AssignCpuDescriptorHandle(
  2787. renderer,
  2788. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  2789. &buffer->uavDescriptor);
  2790. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  2791. uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
  2792. uavDesc.Buffer.FirstElement = 0;
  2793. uavDesc.Buffer.NumElements = size / sizeof(Uint32);
  2794. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  2795. uavDesc.Buffer.CounterOffsetInBytes = 0; // TODO: support counters?
  2796. uavDesc.Buffer.StructureByteStride = 0;
  2797. // Create UAV
  2798. ID3D12Device_CreateUnorderedAccessView(
  2799. renderer->device,
  2800. handle,
  2801. NULL, // TODO: support counters?
  2802. &uavDesc,
  2803. buffer->uavDescriptor.cpuHandle);
  2804. }
  2805. if (
  2806. (usageFlags & SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ) ||
  2807. (usageFlags & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ)) {
  2808. D3D12_INTERNAL_AssignCpuDescriptorHandle(
  2809. renderer,
  2810. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  2811. &buffer->srvDescriptor);
  2812. srvDesc.Format = DXGI_FORMAT_R32_TYPELESS;
  2813. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  2814. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
  2815. srvDesc.Buffer.FirstElement = 0;
  2816. srvDesc.Buffer.NumElements = size / sizeof(Uint32);
  2817. srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW;
  2818. srvDesc.Buffer.StructureByteStride = 0;
  2819. // Create SRV
  2820. ID3D12Device_CreateShaderResourceView(
  2821. renderer->device,
  2822. handle,
  2823. &srvDesc,
  2824. buffer->srvDescriptor.cpuHandle);
  2825. }
  2826. // FIXME: we may not need a CBV since we use root descriptors
  2827. if (type == D3D12_BUFFER_TYPE_UNIFORM) {
  2828. D3D12_INTERNAL_AssignCpuDescriptorHandle(
  2829. renderer,
  2830. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  2831. &buffer->cbvDescriptor);
  2832. cbvDesc.BufferLocation = ID3D12Resource_GetGPUVirtualAddress(handle);
  2833. cbvDesc.SizeInBytes = size;
  2834. // Create CBV
  2835. ID3D12Device_CreateConstantBufferView(
  2836. renderer->device,
  2837. &cbvDesc,
  2838. buffer->cbvDescriptor.cpuHandle);
  2839. }
  2840. buffer->virtualAddress = 0;
  2841. if (type == D3D12_BUFFER_TYPE_GPU || type == D3D12_BUFFER_TYPE_UNIFORM) {
  2842. buffer->virtualAddress = ID3D12Resource_GetGPUVirtualAddress(buffer->handle);
  2843. }
  2844. buffer->mapPointer = NULL;
  2845. // Persistently map upload buffers
  2846. if (type == D3D12_BUFFER_TYPE_UPLOAD) {
  2847. res = ID3D12Resource_Map(
  2848. buffer->handle,
  2849. 0,
  2850. NULL,
  2851. (void **)&buffer->mapPointer);
  2852. if (FAILED(res)) {
  2853. D3D12_INTERNAL_SetError(renderer, "Failed to map upload buffer!", res);
  2854. D3D12_INTERNAL_DestroyBuffer(renderer, buffer);
  2855. return NULL;
  2856. }
  2857. }
  2858. buffer->container = NULL;
  2859. buffer->containerIndex = 0;
  2860. buffer->transitioned = initialState != D3D12_RESOURCE_STATE_COMMON;
  2861. SDL_SetAtomicInt(&buffer->referenceCount, 0);
  2862. return buffer;
  2863. }
  2864. static D3D12BufferContainer *D3D12_INTERNAL_CreateBufferContainer(
  2865. D3D12Renderer *renderer,
  2866. SDL_GPUBufferUsageFlags usageFlags,
  2867. Uint32 size,
  2868. D3D12BufferType type)
  2869. {
  2870. D3D12BufferContainer *container;
  2871. D3D12Buffer *buffer;
  2872. container = (D3D12BufferContainer *)SDL_calloc(1, sizeof(D3D12BufferContainer));
  2873. if (!container) {
  2874. return NULL;
  2875. }
  2876. container->usage = usageFlags;
  2877. container->size = size;
  2878. container->type = type;
  2879. container->bufferCapacity = 1;
  2880. container->bufferCount = 1;
  2881. container->buffers = (D3D12Buffer **)SDL_calloc(
  2882. container->bufferCapacity, sizeof(D3D12Buffer *));
  2883. if (!container->buffers) {
  2884. SDL_free(container);
  2885. return NULL;
  2886. }
  2887. container->debugName = NULL;
  2888. buffer = D3D12_INTERNAL_CreateBuffer(
  2889. renderer,
  2890. usageFlags,
  2891. size,
  2892. type);
  2893. if (buffer == NULL) {
  2894. SDL_free(container->buffers);
  2895. SDL_free(container);
  2896. return NULL;
  2897. }
  2898. container->activeBuffer = buffer;
  2899. container->buffers[0] = buffer;
  2900. buffer->container = container;
  2901. buffer->containerIndex = 0;
  2902. return container;
  2903. }
  2904. static SDL_GPUBuffer *D3D12_CreateBuffer(
  2905. SDL_GPURenderer *driverData,
  2906. SDL_GPUBufferUsageFlags usageFlags,
  2907. Uint32 size)
  2908. {
  2909. return (SDL_GPUBuffer *)D3D12_INTERNAL_CreateBufferContainer(
  2910. (D3D12Renderer *)driverData,
  2911. usageFlags,
  2912. size,
  2913. D3D12_BUFFER_TYPE_GPU);
  2914. }
  2915. static SDL_GPUTransferBuffer *D3D12_CreateTransferBuffer(
  2916. SDL_GPURenderer *driverData,
  2917. SDL_GPUTransferBufferUsage usage,
  2918. Uint32 size)
  2919. {
  2920. return (SDL_GPUTransferBuffer *)D3D12_INTERNAL_CreateBufferContainer(
  2921. (D3D12Renderer *)driverData,
  2922. 0,
  2923. size,
  2924. usage == SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD ? D3D12_BUFFER_TYPE_UPLOAD : D3D12_BUFFER_TYPE_DOWNLOAD);
  2925. }
  2926. // Debug Naming
  2927. static void D3D12_SetBufferName(
  2928. SDL_GPURenderer *driverData,
  2929. SDL_GPUBuffer *buffer,
  2930. const char *text)
  2931. {
  2932. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  2933. D3D12BufferContainer *container = (D3D12BufferContainer *)buffer;
  2934. size_t textLength = SDL_strlen(text) + 1;
  2935. if (renderer->debug_mode) {
  2936. container->debugName = (char *)SDL_realloc(
  2937. container->debugName,
  2938. textLength);
  2939. SDL_utf8strlcpy(
  2940. container->debugName,
  2941. text,
  2942. textLength);
  2943. for (Uint32 i = 0; i < container->bufferCount; i += 1) {
  2944. D3D12_INTERNAL_SetResourceName(
  2945. renderer,
  2946. container->buffers[i]->handle,
  2947. text);
  2948. }
  2949. }
  2950. }
  2951. static void D3D12_SetTextureName(
  2952. SDL_GPURenderer *driverData,
  2953. SDL_GPUTexture *texture,
  2954. const char *text)
  2955. {
  2956. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  2957. D3D12TextureContainer *container = (D3D12TextureContainer *)texture;
  2958. size_t textLength = SDL_strlen(text) + 1;
  2959. if (renderer->debug_mode) {
  2960. container->debugName = (char *)SDL_realloc(
  2961. container->debugName,
  2962. textLength);
  2963. SDL_utf8strlcpy(
  2964. container->debugName,
  2965. text,
  2966. textLength);
  2967. for (Uint32 i = 0; i < container->textureCount; i += 1) {
  2968. D3D12_INTERNAL_SetResourceName(
  2969. renderer,
  2970. container->textures[i]->resource,
  2971. text);
  2972. }
  2973. }
  2974. }
  2975. /* These debug functions are all marked as "for internal usage only"
  2976. * on D3D12... works on renderdoc!
  2977. */
  2978. static bool D3D12_INTERNAL_StrToWStr(
  2979. D3D12Renderer *renderer,
  2980. const char *str,
  2981. wchar_t *wstr,
  2982. size_t wstrSize,
  2983. Uint32 *outSize)
  2984. {
  2985. size_t inlen, result;
  2986. size_t outlen = wstrSize;
  2987. if (renderer->iconv == NULL) {
  2988. renderer->iconv = SDL_iconv_open("WCHAR_T", "UTF-8");
  2989. SDL_assert(renderer->iconv);
  2990. }
  2991. // Convert...
  2992. inlen = SDL_strlen(str) + 1;
  2993. result = SDL_iconv(
  2994. renderer->iconv,
  2995. &str,
  2996. &inlen,
  2997. (char **)&wstr,
  2998. &outlen);
  2999. *outSize = (Uint32)outlen;
  3000. // Check...
  3001. switch (result) {
  3002. case SDL_ICONV_ERROR:
  3003. case SDL_ICONV_E2BIG:
  3004. case SDL_ICONV_EILSEQ:
  3005. case SDL_ICONV_EINVAL:
  3006. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Failed to convert string to wchar_t!");
  3007. return false;
  3008. default:
  3009. break;
  3010. }
  3011. return true;
  3012. }
  3013. static void D3D12_InsertDebugLabel(
  3014. SDL_GPUCommandBuffer *commandBuffer,
  3015. const char *text)
  3016. {
  3017. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3018. wchar_t wstr[256];
  3019. Uint32 convSize;
  3020. if (!D3D12_INTERNAL_StrToWStr(
  3021. d3d12CommandBuffer->renderer,
  3022. text,
  3023. wstr,
  3024. sizeof(wstr),
  3025. &convSize)) {
  3026. return;
  3027. }
  3028. ID3D12GraphicsCommandList_SetMarker(
  3029. d3d12CommandBuffer->graphicsCommandList,
  3030. 0,
  3031. wstr,
  3032. convSize);
  3033. }
  3034. static void D3D12_PushDebugGroup(
  3035. SDL_GPUCommandBuffer *commandBuffer,
  3036. const char *name)
  3037. {
  3038. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3039. wchar_t wstr[256];
  3040. Uint32 convSize;
  3041. if (!D3D12_INTERNAL_StrToWStr(
  3042. d3d12CommandBuffer->renderer,
  3043. name,
  3044. wstr,
  3045. sizeof(wstr),
  3046. &convSize)) {
  3047. return;
  3048. }
  3049. ID3D12GraphicsCommandList_BeginEvent(
  3050. d3d12CommandBuffer->graphicsCommandList,
  3051. 0,
  3052. wstr,
  3053. convSize);
  3054. }
  3055. static void D3D12_PopDebugGroup(
  3056. SDL_GPUCommandBuffer *commandBuffer)
  3057. {
  3058. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3059. ID3D12GraphicsCommandList_EndEvent(d3d12CommandBuffer->graphicsCommandList);
  3060. }
  3061. // Disposal
  3062. static void D3D12_ReleaseTexture(
  3063. SDL_GPURenderer *driverData,
  3064. SDL_GPUTexture *texture)
  3065. {
  3066. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  3067. D3D12TextureContainer *container = (D3D12TextureContainer *)texture;
  3068. D3D12_INTERNAL_ReleaseTextureContainer(
  3069. renderer,
  3070. container);
  3071. }
  3072. static void D3D12_ReleaseSampler(
  3073. SDL_GPURenderer *driverData,
  3074. SDL_GPUSampler *sampler)
  3075. {
  3076. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  3077. D3D12Sampler *d3d12Sampler = (D3D12Sampler *)sampler;
  3078. SDL_LockMutex(renderer->disposeLock);
  3079. EXPAND_ARRAY_IF_NEEDED(
  3080. renderer->samplersToDestroy,
  3081. D3D12Sampler *,
  3082. renderer->samplersToDestroyCount + 1,
  3083. renderer->samplersToDestroyCapacity,
  3084. renderer->samplersToDestroyCapacity * 2)
  3085. renderer->samplersToDestroy[renderer->samplersToDestroyCount] = d3d12Sampler;
  3086. renderer->samplersToDestroyCount += 1;
  3087. SDL_UnlockMutex(renderer->disposeLock);
  3088. }
  3089. static void D3D12_ReleaseBuffer(
  3090. SDL_GPURenderer *driverData,
  3091. SDL_GPUBuffer *buffer)
  3092. {
  3093. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  3094. D3D12BufferContainer *bufferContainer = (D3D12BufferContainer *)buffer;
  3095. D3D12_INTERNAL_ReleaseBufferContainer(
  3096. renderer,
  3097. bufferContainer);
  3098. }
  3099. static void D3D12_ReleaseTransferBuffer(
  3100. SDL_GPURenderer *driverData,
  3101. SDL_GPUTransferBuffer *transferBuffer)
  3102. {
  3103. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  3104. D3D12BufferContainer *transferBufferContainer = (D3D12BufferContainer *)transferBuffer;
  3105. D3D12_INTERNAL_ReleaseBufferContainer(
  3106. renderer,
  3107. transferBufferContainer);
  3108. }
  3109. static void D3D12_ReleaseShader(
  3110. SDL_GPURenderer *driverData,
  3111. SDL_GPUShader *shader)
  3112. {
  3113. /* D3D12Renderer *renderer = (D3D12Renderer *)driverData; */
  3114. D3D12Shader *d3d12shader = (D3D12Shader *)shader;
  3115. if (d3d12shader->bytecode) {
  3116. SDL_free(d3d12shader->bytecode);
  3117. d3d12shader->bytecode = NULL;
  3118. }
  3119. SDL_free(d3d12shader);
  3120. }
  3121. static void D3D12_ReleaseComputePipeline(
  3122. SDL_GPURenderer *driverData,
  3123. SDL_GPUComputePipeline *computePipeline)
  3124. {
  3125. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  3126. D3D12ComputePipeline *d3d12ComputePipeline = (D3D12ComputePipeline *)computePipeline;
  3127. SDL_LockMutex(renderer->disposeLock);
  3128. EXPAND_ARRAY_IF_NEEDED(
  3129. renderer->computePipelinesToDestroy,
  3130. D3D12ComputePipeline *,
  3131. renderer->computePipelinesToDestroyCount + 1,
  3132. renderer->computePipelinesToDestroyCapacity,
  3133. renderer->computePipelinesToDestroyCapacity * 2)
  3134. renderer->computePipelinesToDestroy[renderer->computePipelinesToDestroyCount] = d3d12ComputePipeline;
  3135. renderer->computePipelinesToDestroyCount += 1;
  3136. SDL_UnlockMutex(renderer->disposeLock);
  3137. }
  3138. static void D3D12_ReleaseGraphicsPipeline(
  3139. SDL_GPURenderer *driverData,
  3140. SDL_GPUGraphicsPipeline *graphicsPipeline)
  3141. {
  3142. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  3143. D3D12GraphicsPipeline *d3d12GraphicsPipeline = (D3D12GraphicsPipeline *)graphicsPipeline;
  3144. SDL_LockMutex(renderer->disposeLock);
  3145. EXPAND_ARRAY_IF_NEEDED(
  3146. renderer->graphicsPipelinesToDestroy,
  3147. D3D12GraphicsPipeline *,
  3148. renderer->graphicsPipelinesToDestroyCount + 1,
  3149. renderer->graphicsPipelinesToDestroyCapacity,
  3150. renderer->graphicsPipelinesToDestroyCapacity * 2)
  3151. renderer->graphicsPipelinesToDestroy[renderer->graphicsPipelinesToDestroyCount] = d3d12GraphicsPipeline;
  3152. renderer->graphicsPipelinesToDestroyCount += 1;
  3153. SDL_UnlockMutex(renderer->disposeLock);
  3154. }
  3155. static void D3D12_INTERNAL_ReleaseBlitPipelines(SDL_GPURenderer *driverData)
  3156. {
  3157. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  3158. D3D12_ReleaseSampler(driverData, renderer->blitLinearSampler);
  3159. D3D12_ReleaseSampler(driverData, renderer->blitNearestSampler);
  3160. D3D12_ReleaseShader(driverData, renderer->blitVertexShader);
  3161. D3D12_ReleaseShader(driverData, renderer->blitFrom2DShader);
  3162. D3D12_ReleaseShader(driverData, renderer->blitFrom2DArrayShader);
  3163. D3D12_ReleaseShader(driverData, renderer->blitFrom3DShader);
  3164. D3D12_ReleaseShader(driverData, renderer->blitFromCubeShader);
  3165. D3D12_ReleaseShader(driverData, renderer->blitFromCubeArrayShader);
  3166. for (Uint32 i = 0; i < renderer->blitPipelineCount; i += 1) {
  3167. D3D12_ReleaseGraphicsPipeline(driverData, renderer->blitPipelines[i].pipeline);
  3168. }
  3169. SDL_free(renderer->blitPipelines);
  3170. }
  3171. // Render Pass
  3172. static void D3D12_SetViewport(
  3173. SDL_GPUCommandBuffer *commandBuffer,
  3174. const SDL_GPUViewport *viewport)
  3175. {
  3176. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3177. D3D12_VIEWPORT d3d12Viewport;
  3178. d3d12Viewport.TopLeftX = viewport->x;
  3179. d3d12Viewport.TopLeftY = viewport->y;
  3180. d3d12Viewport.Width = viewport->w;
  3181. d3d12Viewport.Height = viewport->h;
  3182. d3d12Viewport.MinDepth = viewport->min_depth;
  3183. d3d12Viewport.MaxDepth = viewport->max_depth;
  3184. ID3D12GraphicsCommandList_RSSetViewports(d3d12CommandBuffer->graphicsCommandList, 1, &d3d12Viewport);
  3185. }
  3186. static void D3D12_SetScissor(
  3187. SDL_GPUCommandBuffer *commandBuffer,
  3188. const SDL_Rect *scissor)
  3189. {
  3190. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3191. D3D12_RECT scissorRect;
  3192. scissorRect.left = scissor->x;
  3193. scissorRect.top = scissor->y;
  3194. scissorRect.right = scissor->x + scissor->w;
  3195. scissorRect.bottom = scissor->y + scissor->h;
  3196. ID3D12GraphicsCommandList_RSSetScissorRects(d3d12CommandBuffer->graphicsCommandList, 1, &scissorRect);
  3197. }
  3198. static void D3D12_SetBlendConstants(
  3199. SDL_GPUCommandBuffer *commandBuffer,
  3200. SDL_FColor blendConstants)
  3201. {
  3202. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3203. FLOAT blendFactor[4] = { blendConstants.r, blendConstants.g, blendConstants.b, blendConstants.a };
  3204. ID3D12GraphicsCommandList_OMSetBlendFactor(d3d12CommandBuffer->graphicsCommandList, blendFactor);
  3205. }
  3206. static void D3D12_SetStencilReference(
  3207. SDL_GPUCommandBuffer *commandBuffer,
  3208. Uint8 reference
  3209. ) {
  3210. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3211. ID3D12GraphicsCommandList_OMSetStencilRef(d3d12CommandBuffer->graphicsCommandList, reference);
  3212. }
  3213. static D3D12TextureSubresource *D3D12_INTERNAL_FetchTextureSubresource(
  3214. D3D12TextureContainer *container,
  3215. Uint32 layer,
  3216. Uint32 level)
  3217. {
  3218. Uint32 index = D3D12_INTERNAL_CalcSubresource(
  3219. level,
  3220. layer,
  3221. container->header.info.num_levels);
  3222. return &container->activeTexture->subresources[index];
  3223. }
  3224. static void D3D12_INTERNAL_CycleActiveTexture(
  3225. D3D12Renderer *renderer,
  3226. D3D12TextureContainer *container)
  3227. {
  3228. D3D12Texture *texture;
  3229. // If a previously-cycled texture is available, we can use that.
  3230. for (Uint32 i = 0; i < container->textureCount; i += 1) {
  3231. texture = container->textures[i];
  3232. if (SDL_GetAtomicInt(&texture->referenceCount) == 0) {
  3233. container->activeTexture = texture;
  3234. return;
  3235. }
  3236. }
  3237. // No texture is available, generate a new one.
  3238. texture = D3D12_INTERNAL_CreateTexture(
  3239. renderer,
  3240. &container->header.info,
  3241. false);
  3242. if (!texture) {
  3243. return;
  3244. }
  3245. EXPAND_ARRAY_IF_NEEDED(
  3246. container->textures,
  3247. D3D12Texture *,
  3248. container->textureCount + 1,
  3249. container->textureCapacity,
  3250. container->textureCapacity * 2);
  3251. container->textures[container->textureCount] = texture;
  3252. texture->container = container;
  3253. texture->containerIndex = container->textureCount;
  3254. container->textureCount += 1;
  3255. container->activeTexture = texture;
  3256. if (renderer->debug_mode && container->debugName != NULL) {
  3257. D3D12_INTERNAL_SetResourceName(
  3258. renderer,
  3259. container->activeTexture->resource,
  3260. container->debugName);
  3261. }
  3262. }
  3263. static D3D12TextureSubresource *D3D12_INTERNAL_PrepareTextureSubresourceForWrite(
  3264. D3D12CommandBuffer *commandBuffer,
  3265. D3D12TextureContainer *container,
  3266. Uint32 layer,
  3267. Uint32 level,
  3268. bool cycle,
  3269. D3D12_RESOURCE_STATES destinationUsageMode)
  3270. {
  3271. D3D12TextureSubresource *subresource = D3D12_INTERNAL_FetchTextureSubresource(
  3272. container,
  3273. layer,
  3274. level);
  3275. if (
  3276. container->canBeCycled &&
  3277. cycle &&
  3278. SDL_GetAtomicInt(&subresource->parent->referenceCount) > 0) {
  3279. D3D12_INTERNAL_CycleActiveTexture(
  3280. commandBuffer->renderer,
  3281. container);
  3282. subresource = D3D12_INTERNAL_FetchTextureSubresource(
  3283. container,
  3284. layer,
  3285. level);
  3286. }
  3287. D3D12_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  3288. commandBuffer,
  3289. destinationUsageMode,
  3290. subresource);
  3291. return subresource;
  3292. }
  3293. static void D3D12_INTERNAL_CycleActiveBuffer(
  3294. D3D12Renderer *renderer,
  3295. D3D12BufferContainer *container)
  3296. {
  3297. // If a previously-cycled buffer is available, we can use that.
  3298. for (Uint32 i = 0; i < container->bufferCount; i += 1) {
  3299. D3D12Buffer *buffer = container->buffers[i];
  3300. if (SDL_GetAtomicInt(&buffer->referenceCount) == 0) {
  3301. container->activeBuffer = buffer;
  3302. return;
  3303. }
  3304. }
  3305. // No buffer handle is available, create a new one.
  3306. D3D12Buffer *buffer = D3D12_INTERNAL_CreateBuffer(
  3307. renderer,
  3308. container->usage,
  3309. container->size,
  3310. container->type);
  3311. if (!buffer) {
  3312. return;
  3313. }
  3314. EXPAND_ARRAY_IF_NEEDED(
  3315. container->buffers,
  3316. D3D12Buffer *,
  3317. container->bufferCount + 1,
  3318. container->bufferCapacity,
  3319. container->bufferCapacity * 2);
  3320. container->buffers[container->bufferCount] = buffer;
  3321. buffer->container = container;
  3322. buffer->containerIndex = container->bufferCount;
  3323. container->bufferCount += 1;
  3324. container->activeBuffer = buffer;
  3325. if (renderer->debug_mode && container->debugName != NULL) {
  3326. D3D12_INTERNAL_SetResourceName(
  3327. renderer,
  3328. container->activeBuffer->handle,
  3329. container->debugName);
  3330. }
  3331. }
  3332. static D3D12Buffer *D3D12_INTERNAL_PrepareBufferForWrite(
  3333. D3D12CommandBuffer *commandBuffer,
  3334. D3D12BufferContainer *container,
  3335. bool cycle,
  3336. D3D12_RESOURCE_STATES destinationState)
  3337. {
  3338. if (
  3339. cycle &&
  3340. SDL_GetAtomicInt(&container->activeBuffer->referenceCount) > 0) {
  3341. D3D12_INTERNAL_CycleActiveBuffer(
  3342. commandBuffer->renderer,
  3343. container);
  3344. }
  3345. D3D12_INTERNAL_BufferTransitionFromDefaultUsage(
  3346. commandBuffer,
  3347. destinationState,
  3348. container->activeBuffer);
  3349. return container->activeBuffer;
  3350. }
  3351. static void D3D12_BeginRenderPass(
  3352. SDL_GPUCommandBuffer *commandBuffer,
  3353. const SDL_GPUColorTargetInfo *colorTargetInfos,
  3354. Uint32 numColorTargets,
  3355. const SDL_GPUDepthStencilTargetInfo *depthStencilTargetInfo)
  3356. {
  3357. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3358. Uint32 framebufferWidth = SDL_MAX_UINT32;
  3359. Uint32 framebufferHeight = SDL_MAX_UINT32;
  3360. for (Uint32 i = 0; i < numColorTargets; i += 1) {
  3361. D3D12TextureContainer *container = (D3D12TextureContainer *)colorTargetInfos[i].texture;
  3362. Uint32 h = container->header.info.height >> colorTargetInfos[i].mip_level;
  3363. Uint32 w = container->header.info.width >> colorTargetInfos[i].mip_level;
  3364. // The framebuffer cannot be larger than the smallest target.
  3365. if (w < framebufferWidth) {
  3366. framebufferWidth = w;
  3367. }
  3368. if (h < framebufferHeight) {
  3369. framebufferHeight = h;
  3370. }
  3371. }
  3372. if (depthStencilTargetInfo != NULL) {
  3373. D3D12TextureContainer *container = (D3D12TextureContainer *)depthStencilTargetInfo->texture;
  3374. Uint32 h = container->header.info.height;
  3375. Uint32 w = container->header.info.width;
  3376. // The framebuffer cannot be larger than the smallest target.
  3377. if (w < framebufferWidth) {
  3378. framebufferWidth = w;
  3379. }
  3380. if (h < framebufferHeight) {
  3381. framebufferHeight = h;
  3382. }
  3383. }
  3384. D3D12_CPU_DESCRIPTOR_HANDLE rtvs[MAX_COLOR_TARGET_BINDINGS];
  3385. for (Uint32 i = 0; i < numColorTargets; i += 1) {
  3386. D3D12TextureContainer *container = (D3D12TextureContainer *)colorTargetInfos[i].texture;
  3387. D3D12TextureSubresource *subresource = D3D12_INTERNAL_PrepareTextureSubresourceForWrite(
  3388. d3d12CommandBuffer,
  3389. container,
  3390. container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? 0 : colorTargetInfos[i].layer_or_depth_plane,
  3391. colorTargetInfos[i].mip_level,
  3392. colorTargetInfos[i].cycle,
  3393. D3D12_RESOURCE_STATE_RENDER_TARGET);
  3394. Uint32 rtvIndex = container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? colorTargetInfos[i].layer_or_depth_plane : 0;
  3395. D3D12_CPU_DESCRIPTOR_HANDLE rtv = subresource->rtvHandles[rtvIndex].cpuHandle;
  3396. if (colorTargetInfos[i].load_op == SDL_GPU_LOADOP_CLEAR) {
  3397. float clearColor[4];
  3398. clearColor[0] = colorTargetInfos[i].clear_color.r;
  3399. clearColor[1] = colorTargetInfos[i].clear_color.g;
  3400. clearColor[2] = colorTargetInfos[i].clear_color.b;
  3401. clearColor[3] = colorTargetInfos[i].clear_color.a;
  3402. ID3D12GraphicsCommandList_ClearRenderTargetView(
  3403. d3d12CommandBuffer->graphicsCommandList,
  3404. rtv,
  3405. clearColor,
  3406. 0,
  3407. NULL);
  3408. }
  3409. rtvs[i] = rtv;
  3410. d3d12CommandBuffer->colorTargetSubresources[i] = subresource;
  3411. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, subresource->parent);
  3412. if (colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE || colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE_AND_STORE) {
  3413. D3D12TextureContainer *resolveContainer = (D3D12TextureContainer *)colorTargetInfos[i].resolve_texture;
  3414. D3D12TextureSubresource *resolveSubresource = D3D12_INTERNAL_PrepareTextureSubresourceForWrite(
  3415. d3d12CommandBuffer,
  3416. resolveContainer,
  3417. colorTargetInfos[i].resolve_layer,
  3418. colorTargetInfos[i].resolve_mip_level,
  3419. colorTargetInfos[i].cycle_resolve_texture,
  3420. D3D12_RESOURCE_STATE_RESOLVE_DEST);
  3421. d3d12CommandBuffer->colorResolveSubresources[i] = resolveSubresource;
  3422. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, resolveSubresource->parent);
  3423. }
  3424. }
  3425. D3D12_CPU_DESCRIPTOR_HANDLE dsv;
  3426. if (depthStencilTargetInfo != NULL) {
  3427. D3D12TextureContainer *container = (D3D12TextureContainer *)depthStencilTargetInfo->texture;
  3428. D3D12TextureSubresource *subresource = D3D12_INTERNAL_PrepareTextureSubresourceForWrite(
  3429. d3d12CommandBuffer,
  3430. container,
  3431. 0,
  3432. 0,
  3433. depthStencilTargetInfo->cycle,
  3434. D3D12_RESOURCE_STATE_DEPTH_WRITE);
  3435. if (
  3436. depthStencilTargetInfo->load_op == SDL_GPU_LOADOP_CLEAR ||
  3437. depthStencilTargetInfo->stencil_load_op == SDL_GPU_LOADOP_CLEAR) {
  3438. D3D12_CLEAR_FLAGS clearFlags = (D3D12_CLEAR_FLAGS)0;
  3439. if (depthStencilTargetInfo->load_op == SDL_GPU_LOADOP_CLEAR) {
  3440. clearFlags |= D3D12_CLEAR_FLAG_DEPTH;
  3441. }
  3442. if (depthStencilTargetInfo->stencil_load_op == SDL_GPU_LOADOP_CLEAR) {
  3443. clearFlags |= D3D12_CLEAR_FLAG_STENCIL;
  3444. }
  3445. ID3D12GraphicsCommandList_ClearDepthStencilView(
  3446. d3d12CommandBuffer->graphicsCommandList,
  3447. subresource->dsvHandle.cpuHandle,
  3448. clearFlags,
  3449. depthStencilTargetInfo->clear_depth,
  3450. depthStencilTargetInfo->clear_stencil,
  3451. 0,
  3452. NULL);
  3453. }
  3454. dsv = subresource->dsvHandle.cpuHandle;
  3455. d3d12CommandBuffer->depthStencilTextureSubresource = subresource;
  3456. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, subresource->parent);
  3457. }
  3458. ID3D12GraphicsCommandList_OMSetRenderTargets(
  3459. d3d12CommandBuffer->graphicsCommandList,
  3460. numColorTargets,
  3461. rtvs,
  3462. false,
  3463. (depthStencilTargetInfo == NULL) ? NULL : &dsv);
  3464. // Set sensible default states
  3465. SDL_GPUViewport defaultViewport;
  3466. defaultViewport.x = 0;
  3467. defaultViewport.y = 0;
  3468. defaultViewport.w = (float)framebufferWidth;
  3469. defaultViewport.h = (float)framebufferHeight;
  3470. defaultViewport.min_depth = 0;
  3471. defaultViewport.max_depth = 1;
  3472. D3D12_SetViewport(
  3473. commandBuffer,
  3474. &defaultViewport);
  3475. SDL_Rect defaultScissor;
  3476. defaultScissor.x = 0;
  3477. defaultScissor.y = 0;
  3478. defaultScissor.w = (Sint32)framebufferWidth;
  3479. defaultScissor.h = (Sint32)framebufferHeight;
  3480. D3D12_SetScissor(
  3481. commandBuffer,
  3482. &defaultScissor);
  3483. D3D12_SetStencilReference(
  3484. commandBuffer,
  3485. 0);
  3486. SDL_FColor blendConstants;
  3487. blendConstants.r = 1.0f;
  3488. blendConstants.g = 1.0f;
  3489. blendConstants.b = 1.0f;
  3490. blendConstants.a = 1.0f;
  3491. D3D12_SetBlendConstants(
  3492. commandBuffer,
  3493. blendConstants);
  3494. }
  3495. static void D3D12_INTERNAL_TrackUniformBuffer(
  3496. D3D12CommandBuffer *commandBuffer,
  3497. D3D12UniformBuffer *uniformBuffer)
  3498. {
  3499. Uint32 i;
  3500. for (i = 0; i < commandBuffer->usedUniformBufferCount; i += 1) {
  3501. if (commandBuffer->usedUniformBuffers[i] == uniformBuffer) {
  3502. return;
  3503. }
  3504. }
  3505. if (commandBuffer->usedUniformBufferCount == commandBuffer->usedUniformBufferCapacity) {
  3506. commandBuffer->usedUniformBufferCapacity += 1;
  3507. commandBuffer->usedUniformBuffers = (D3D12UniformBuffer **)SDL_realloc(
  3508. commandBuffer->usedUniformBuffers,
  3509. commandBuffer->usedUniformBufferCapacity * sizeof(D3D12UniformBuffer *));
  3510. }
  3511. commandBuffer->usedUniformBuffers[commandBuffer->usedUniformBufferCount] = uniformBuffer;
  3512. commandBuffer->usedUniformBufferCount += 1;
  3513. D3D12_INTERNAL_TrackBuffer(
  3514. commandBuffer,
  3515. uniformBuffer->buffer);
  3516. }
  3517. static D3D12UniformBuffer *D3D12_INTERNAL_AcquireUniformBufferFromPool(
  3518. D3D12CommandBuffer *commandBuffer)
  3519. {
  3520. D3D12Renderer *renderer = commandBuffer->renderer;
  3521. D3D12UniformBuffer *uniformBuffer;
  3522. SDL_LockMutex(renderer->acquireUniformBufferLock);
  3523. if (renderer->uniformBufferPoolCount > 0) {
  3524. uniformBuffer = renderer->uniformBufferPool[renderer->uniformBufferPoolCount - 1];
  3525. renderer->uniformBufferPoolCount -= 1;
  3526. } else {
  3527. uniformBuffer = (D3D12UniformBuffer *)SDL_calloc(1, sizeof(D3D12UniformBuffer));
  3528. if (!uniformBuffer) {
  3529. SDL_UnlockMutex(renderer->acquireUniformBufferLock);
  3530. return NULL;
  3531. }
  3532. uniformBuffer->buffer = D3D12_INTERNAL_CreateBuffer(
  3533. renderer,
  3534. 0,
  3535. UNIFORM_BUFFER_SIZE,
  3536. D3D12_BUFFER_TYPE_UNIFORM);
  3537. if (!uniformBuffer->buffer) {
  3538. SDL_UnlockMutex(renderer->acquireUniformBufferLock);
  3539. return NULL;
  3540. }
  3541. }
  3542. SDL_UnlockMutex(renderer->acquireUniformBufferLock);
  3543. uniformBuffer->currentBlockSize = 0;
  3544. uniformBuffer->drawOffset = 0;
  3545. uniformBuffer->writeOffset = 0;
  3546. HRESULT res = ID3D12Resource_Map(
  3547. uniformBuffer->buffer->handle,
  3548. 0,
  3549. NULL,
  3550. (void **)&uniformBuffer->buffer->mapPointer);
  3551. CHECK_D3D12_ERROR_AND_RETURN("Failed to map buffer pool!", NULL);
  3552. D3D12_INTERNAL_TrackUniformBuffer(commandBuffer, uniformBuffer);
  3553. return uniformBuffer;
  3554. }
  3555. static void D3D12_INTERNAL_ReturnUniformBufferToPool(
  3556. D3D12Renderer *renderer,
  3557. D3D12UniformBuffer *uniformBuffer)
  3558. {
  3559. if (renderer->uniformBufferPoolCount >= renderer->uniformBufferPoolCapacity) {
  3560. renderer->uniformBufferPoolCapacity *= 2;
  3561. renderer->uniformBufferPool = (D3D12UniformBuffer **)SDL_realloc(
  3562. renderer->uniformBufferPool,
  3563. renderer->uniformBufferPoolCapacity * sizeof(D3D12UniformBuffer *));
  3564. }
  3565. renderer->uniformBufferPool[renderer->uniformBufferPoolCount] = uniformBuffer;
  3566. renderer->uniformBufferPoolCount += 1;
  3567. }
  3568. static void D3D12_INTERNAL_PushUniformData(
  3569. D3D12CommandBuffer *commandBuffer,
  3570. SDL_GPUShaderStage shaderStage,
  3571. Uint32 slotIndex,
  3572. const void *data,
  3573. Uint32 length)
  3574. {
  3575. D3D12UniformBuffer *uniformBuffer;
  3576. if (shaderStage == SDL_GPU_SHADERSTAGE_VERTEX) {
  3577. if (commandBuffer->vertexUniformBuffers[slotIndex] == NULL) {
  3578. commandBuffer->vertexUniformBuffers[slotIndex] = D3D12_INTERNAL_AcquireUniformBufferFromPool(
  3579. commandBuffer);
  3580. }
  3581. uniformBuffer = commandBuffer->vertexUniformBuffers[slotIndex];
  3582. } else if (shaderStage == SDL_GPU_SHADERSTAGE_FRAGMENT) {
  3583. if (commandBuffer->fragmentUniformBuffers[slotIndex] == NULL) {
  3584. commandBuffer->fragmentUniformBuffers[slotIndex] = D3D12_INTERNAL_AcquireUniformBufferFromPool(
  3585. commandBuffer);
  3586. }
  3587. uniformBuffer = commandBuffer->fragmentUniformBuffers[slotIndex];
  3588. } else if (shaderStage == SDL_GPU_SHADERSTAGE_COMPUTE) {
  3589. if (commandBuffer->computeUniformBuffers[slotIndex] == NULL) {
  3590. commandBuffer->computeUniformBuffers[slotIndex] = D3D12_INTERNAL_AcquireUniformBufferFromPool(
  3591. commandBuffer);
  3592. }
  3593. uniformBuffer = commandBuffer->computeUniformBuffers[slotIndex];
  3594. } else {
  3595. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized shader stage!");
  3596. return;
  3597. }
  3598. uniformBuffer->currentBlockSize =
  3599. D3D12_INTERNAL_Align(
  3600. length,
  3601. 256);
  3602. // If there is no more room, acquire a new uniform buffer
  3603. if (uniformBuffer->writeOffset + uniformBuffer->currentBlockSize >= UNIFORM_BUFFER_SIZE) {
  3604. ID3D12Resource_Unmap(
  3605. uniformBuffer->buffer->handle,
  3606. 0,
  3607. NULL);
  3608. uniformBuffer->buffer->mapPointer = NULL;
  3609. uniformBuffer = D3D12_INTERNAL_AcquireUniformBufferFromPool(commandBuffer);
  3610. uniformBuffer->drawOffset = 0;
  3611. uniformBuffer->writeOffset = 0;
  3612. if (shaderStage == SDL_GPU_SHADERSTAGE_VERTEX) {
  3613. commandBuffer->vertexUniformBuffers[slotIndex] = uniformBuffer;
  3614. } else if (shaderStage == SDL_GPU_SHADERSTAGE_FRAGMENT) {
  3615. commandBuffer->fragmentUniformBuffers[slotIndex] = uniformBuffer;
  3616. } else if (shaderStage == SDL_GPU_SHADERSTAGE_COMPUTE) {
  3617. commandBuffer->computeUniformBuffers[slotIndex] = uniformBuffer;
  3618. } else {
  3619. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized shader stage!");
  3620. }
  3621. }
  3622. uniformBuffer->drawOffset = uniformBuffer->writeOffset;
  3623. SDL_memcpy(
  3624. (Uint8 *)uniformBuffer->buffer->mapPointer + uniformBuffer->writeOffset,
  3625. data,
  3626. length);
  3627. uniformBuffer->writeOffset += uniformBuffer->currentBlockSize;
  3628. if (shaderStage == SDL_GPU_SHADERSTAGE_VERTEX) {
  3629. commandBuffer->needVertexUniformBufferBind[slotIndex] = true;
  3630. } else if (shaderStage == SDL_GPU_SHADERSTAGE_FRAGMENT) {
  3631. commandBuffer->needFragmentUniformBufferBind[slotIndex] = true;
  3632. } else if (shaderStage == SDL_GPU_SHADERSTAGE_COMPUTE) {
  3633. commandBuffer->needComputeUniformBufferBind[slotIndex] = true;
  3634. } else {
  3635. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized shader stage!");
  3636. }
  3637. }
  3638. static void D3D12_BindGraphicsPipeline(
  3639. SDL_GPUCommandBuffer *commandBuffer,
  3640. SDL_GPUGraphicsPipeline *graphicsPipeline)
  3641. {
  3642. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3643. D3D12GraphicsPipeline *pipeline = (D3D12GraphicsPipeline *)graphicsPipeline;
  3644. Uint32 i;
  3645. d3d12CommandBuffer->currentGraphicsPipeline = pipeline;
  3646. // Set the pipeline state
  3647. ID3D12GraphicsCommandList_SetPipelineState(d3d12CommandBuffer->graphicsCommandList, pipeline->pipelineState);
  3648. ID3D12GraphicsCommandList_SetGraphicsRootSignature(d3d12CommandBuffer->graphicsCommandList, pipeline->rootSignature->handle);
  3649. ID3D12GraphicsCommandList_IASetPrimitiveTopology(d3d12CommandBuffer->graphicsCommandList, SDLToD3D12_PrimitiveType[pipeline->primitiveType]);
  3650. // Mark that bindings are needed
  3651. d3d12CommandBuffer->needVertexSamplerBind = true;
  3652. d3d12CommandBuffer->needVertexStorageTextureBind = true;
  3653. d3d12CommandBuffer->needVertexStorageBufferBind = true;
  3654. d3d12CommandBuffer->needFragmentSamplerBind = true;
  3655. d3d12CommandBuffer->needFragmentStorageTextureBind = true;
  3656. d3d12CommandBuffer->needFragmentStorageBufferBind = true;
  3657. for (i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  3658. d3d12CommandBuffer->needVertexUniformBufferBind[i] = true;
  3659. d3d12CommandBuffer->needFragmentUniformBufferBind[i] = true;
  3660. }
  3661. for (i = 0; i < pipeline->vertexUniformBufferCount; i += 1) {
  3662. if (d3d12CommandBuffer->vertexUniformBuffers[i] == NULL) {
  3663. d3d12CommandBuffer->vertexUniformBuffers[i] = D3D12_INTERNAL_AcquireUniformBufferFromPool(
  3664. d3d12CommandBuffer);
  3665. }
  3666. }
  3667. for (i = 0; i < pipeline->fragmentUniformBufferCount; i += 1) {
  3668. if (d3d12CommandBuffer->fragmentUniformBuffers[i] == NULL) {
  3669. d3d12CommandBuffer->fragmentUniformBuffers[i] = D3D12_INTERNAL_AcquireUniformBufferFromPool(
  3670. d3d12CommandBuffer);
  3671. }
  3672. }
  3673. D3D12_INTERNAL_TrackGraphicsPipeline(d3d12CommandBuffer, pipeline);
  3674. }
  3675. static void D3D12_BindVertexBuffers(
  3676. SDL_GPUCommandBuffer *commandBuffer,
  3677. Uint32 firstSlot,
  3678. const SDL_GPUBufferBinding *bindings,
  3679. Uint32 numBindings)
  3680. {
  3681. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3682. for (Uint32 i = 0; i < numBindings; i += 1) {
  3683. D3D12Buffer *currentBuffer = ((D3D12BufferContainer *)bindings[i].buffer)->activeBuffer;
  3684. d3d12CommandBuffer->vertexBuffers[firstSlot + i] = currentBuffer;
  3685. d3d12CommandBuffer->vertexBufferOffsets[firstSlot + i] = bindings[i].offset;
  3686. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, currentBuffer);
  3687. }
  3688. d3d12CommandBuffer->vertexBufferCount =
  3689. SDL_max(d3d12CommandBuffer->vertexBufferCount, firstSlot + numBindings);
  3690. d3d12CommandBuffer->needVertexBufferBind = true;
  3691. }
  3692. static void D3D12_BindIndexBuffer(
  3693. SDL_GPUCommandBuffer *commandBuffer,
  3694. const SDL_GPUBufferBinding *binding,
  3695. SDL_GPUIndexElementSize indexElementSize)
  3696. {
  3697. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3698. D3D12Buffer *buffer = ((D3D12BufferContainer *)binding->buffer)->activeBuffer;
  3699. D3D12_INDEX_BUFFER_VIEW view;
  3700. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, buffer);
  3701. view.BufferLocation = buffer->virtualAddress + binding->offset;
  3702. view.SizeInBytes = buffer->container->size - binding->offset;
  3703. view.Format =
  3704. indexElementSize == SDL_GPU_INDEXELEMENTSIZE_16BIT ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
  3705. ID3D12GraphicsCommandList_IASetIndexBuffer(
  3706. d3d12CommandBuffer->graphicsCommandList,
  3707. &view);
  3708. }
  3709. static void D3D12_BindVertexSamplers(
  3710. SDL_GPUCommandBuffer *commandBuffer,
  3711. Uint32 firstSlot,
  3712. const SDL_GPUTextureSamplerBinding *textureSamplerBindings,
  3713. Uint32 numBindings)
  3714. {
  3715. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3716. for (Uint32 i = 0; i < numBindings; i += 1) {
  3717. D3D12TextureContainer *container = (D3D12TextureContainer *)textureSamplerBindings[i].texture;
  3718. D3D12Sampler *sampler = (D3D12Sampler *)textureSamplerBindings[i].sampler;
  3719. D3D12_INTERNAL_TrackTexture(
  3720. d3d12CommandBuffer,
  3721. container->activeTexture);
  3722. D3D12_INTERNAL_TrackSampler(
  3723. d3d12CommandBuffer,
  3724. sampler);
  3725. d3d12CommandBuffer->vertexSamplers[firstSlot + i] = sampler;
  3726. d3d12CommandBuffer->vertexSamplerTextures[firstSlot + i] = container->activeTexture;
  3727. }
  3728. d3d12CommandBuffer->needVertexSamplerBind = true;
  3729. }
  3730. static void D3D12_BindVertexStorageTextures(
  3731. SDL_GPUCommandBuffer *commandBuffer,
  3732. Uint32 firstSlot,
  3733. SDL_GPUTexture *const *storageTextures,
  3734. Uint32 numBindings)
  3735. {
  3736. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3737. for (Uint32 i = 0; i < numBindings; i += 1) {
  3738. D3D12TextureContainer *container = (D3D12TextureContainer *)storageTextures[i];
  3739. D3D12Texture *texture = container->activeTexture;
  3740. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, texture);
  3741. d3d12CommandBuffer->vertexStorageTextures[firstSlot + i] = texture;
  3742. }
  3743. d3d12CommandBuffer->needVertexStorageTextureBind = true;
  3744. }
  3745. static void D3D12_BindVertexStorageBuffers(
  3746. SDL_GPUCommandBuffer *commandBuffer,
  3747. Uint32 firstSlot,
  3748. SDL_GPUBuffer *const *storageBuffers,
  3749. Uint32 numBindings)
  3750. {
  3751. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3752. for (Uint32 i = 0; i < numBindings; i += 1) {
  3753. D3D12BufferContainer *container = (D3D12BufferContainer *)storageBuffers[i];
  3754. D3D12_INTERNAL_TrackBuffer(
  3755. d3d12CommandBuffer,
  3756. container->activeBuffer);
  3757. d3d12CommandBuffer->vertexStorageBuffers[firstSlot + i] = container->activeBuffer;
  3758. }
  3759. d3d12CommandBuffer->needVertexStorageBufferBind = true;
  3760. }
  3761. static void D3D12_BindFragmentSamplers(
  3762. SDL_GPUCommandBuffer *commandBuffer,
  3763. Uint32 firstSlot,
  3764. const SDL_GPUTextureSamplerBinding *textureSamplerBindings,
  3765. Uint32 numBindings)
  3766. {
  3767. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3768. for (Uint32 i = 0; i < numBindings; i += 1) {
  3769. D3D12TextureContainer *container = (D3D12TextureContainer *)textureSamplerBindings[i].texture;
  3770. D3D12Sampler *sampler = (D3D12Sampler *)textureSamplerBindings[i].sampler;
  3771. D3D12_INTERNAL_TrackTexture(
  3772. d3d12CommandBuffer,
  3773. container->activeTexture);
  3774. D3D12_INTERNAL_TrackSampler(
  3775. d3d12CommandBuffer,
  3776. sampler);
  3777. d3d12CommandBuffer->fragmentSamplers[firstSlot + i] = sampler;
  3778. d3d12CommandBuffer->fragmentSamplerTextures[firstSlot + i] = container->activeTexture;
  3779. }
  3780. d3d12CommandBuffer->needFragmentSamplerBind = true;
  3781. }
  3782. static void D3D12_BindFragmentStorageTextures(
  3783. SDL_GPUCommandBuffer *commandBuffer,
  3784. Uint32 firstSlot,
  3785. SDL_GPUTexture *const *storageTextures,
  3786. Uint32 numBindings)
  3787. {
  3788. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3789. for (Uint32 i = 0; i < numBindings; i += 1) {
  3790. D3D12TextureContainer *container = (D3D12TextureContainer *)storageTextures[i];
  3791. D3D12Texture *texture = container->activeTexture;
  3792. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, texture);
  3793. d3d12CommandBuffer->fragmentStorageTextures[firstSlot + i] = texture;
  3794. }
  3795. d3d12CommandBuffer->needFragmentStorageTextureBind = true;
  3796. }
  3797. static void D3D12_BindFragmentStorageBuffers(
  3798. SDL_GPUCommandBuffer *commandBuffer,
  3799. Uint32 firstSlot,
  3800. SDL_GPUBuffer *const *storageBuffers,
  3801. Uint32 numBindings)
  3802. {
  3803. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3804. for (Uint32 i = 0; i < numBindings; i += 1) {
  3805. D3D12BufferContainer *container = (D3D12BufferContainer *)storageBuffers[i];
  3806. D3D12_INTERNAL_TrackBuffer(
  3807. d3d12CommandBuffer,
  3808. container->activeBuffer);
  3809. d3d12CommandBuffer->fragmentStorageBuffers[firstSlot + i] = container->activeBuffer;
  3810. }
  3811. d3d12CommandBuffer->needFragmentStorageBufferBind = true;
  3812. }
  3813. static void D3D12_PushVertexUniformData(
  3814. SDL_GPUCommandBuffer *commandBuffer,
  3815. Uint32 slotIndex,
  3816. const void *data,
  3817. Uint32 length)
  3818. {
  3819. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3820. D3D12_INTERNAL_PushUniformData(
  3821. d3d12CommandBuffer,
  3822. SDL_GPU_SHADERSTAGE_VERTEX,
  3823. slotIndex,
  3824. data,
  3825. length);
  3826. }
  3827. static void D3D12_PushFragmentUniformData(
  3828. SDL_GPUCommandBuffer *commandBuffer,
  3829. Uint32 slotIndex,
  3830. const void *data,
  3831. Uint32 length)
  3832. {
  3833. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  3834. D3D12_INTERNAL_PushUniformData(
  3835. d3d12CommandBuffer,
  3836. SDL_GPU_SHADERSTAGE_FRAGMENT,
  3837. slotIndex,
  3838. data,
  3839. length);
  3840. }
  3841. static void D3D12_INTERNAL_WriteGPUDescriptors(
  3842. D3D12CommandBuffer *commandBuffer,
  3843. D3D12_DESCRIPTOR_HEAP_TYPE heapType,
  3844. D3D12_CPU_DESCRIPTOR_HANDLE *resourceDescriptorHandles,
  3845. Uint32 resourceHandleCount,
  3846. D3D12_GPU_DESCRIPTOR_HANDLE *gpuBaseDescriptor)
  3847. {
  3848. D3D12DescriptorHeap *heap = commandBuffer->gpuDescriptorHeaps[heapType];
  3849. D3D12_CPU_DESCRIPTOR_HANDLE gpuHeapCpuHandle;
  3850. // FIXME: need to error on overflow
  3851. gpuHeapCpuHandle.ptr = heap->descriptorHeapCPUStart.ptr + (heap->currentDescriptorIndex * heap->descriptorSize);
  3852. gpuBaseDescriptor->ptr = heap->descriptorHeapGPUStart.ptr + (heap->currentDescriptorIndex * heap->descriptorSize);
  3853. for (Uint32 i = 0; i < resourceHandleCount; i += 1) {
  3854. ID3D12Device_CopyDescriptorsSimple(
  3855. commandBuffer->renderer->device,
  3856. 1,
  3857. gpuHeapCpuHandle,
  3858. resourceDescriptorHandles[i],
  3859. heapType);
  3860. heap->currentDescriptorIndex += 1;
  3861. gpuHeapCpuHandle.ptr += heap->descriptorSize;
  3862. }
  3863. }
  3864. static void D3D12_INTERNAL_BindGraphicsResources(
  3865. D3D12CommandBuffer *commandBuffer)
  3866. {
  3867. D3D12GraphicsPipeline *graphicsPipeline = commandBuffer->currentGraphicsPipeline;
  3868. D3D12_CPU_DESCRIPTOR_HANDLE cpuHandles[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  3869. D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptorHandle;
  3870. D3D12_VERTEX_BUFFER_VIEW vertexBufferViews[MAX_VERTEX_BUFFERS];
  3871. if (commandBuffer->needVertexBufferBind) {
  3872. for (Uint32 i = 0; i < commandBuffer->vertexBufferCount; i += 1) {
  3873. vertexBufferViews[i].BufferLocation = commandBuffer->vertexBuffers[i]->virtualAddress + commandBuffer->vertexBufferOffsets[i];
  3874. vertexBufferViews[i].SizeInBytes = commandBuffer->vertexBuffers[i]->container->size - commandBuffer->vertexBufferOffsets[i];
  3875. vertexBufferViews[i].StrideInBytes = graphicsPipeline->vertexStrides[i];
  3876. }
  3877. ID3D12GraphicsCommandList_IASetVertexBuffers(
  3878. commandBuffer->graphicsCommandList,
  3879. 0,
  3880. commandBuffer->vertexBufferCount,
  3881. vertexBufferViews);
  3882. }
  3883. if (commandBuffer->needVertexSamplerBind) {
  3884. if (graphicsPipeline->vertexSamplerCount > 0) {
  3885. for (Uint32 i = 0; i < graphicsPipeline->vertexSamplerCount; i += 1) {
  3886. cpuHandles[i] = commandBuffer->vertexSamplers[i]->handle.cpuHandle;
  3887. }
  3888. D3D12_INTERNAL_WriteGPUDescriptors(
  3889. commandBuffer,
  3890. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
  3891. cpuHandles,
  3892. graphicsPipeline->vertexSamplerCount,
  3893. &gpuDescriptorHandle);
  3894. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  3895. commandBuffer->graphicsCommandList,
  3896. graphicsPipeline->rootSignature->vertexSamplerRootIndex,
  3897. gpuDescriptorHandle);
  3898. for (Uint32 i = 0; i < graphicsPipeline->vertexSamplerCount; i += 1) {
  3899. cpuHandles[i] = commandBuffer->vertexSamplerTextures[i]->srvHandle.cpuHandle;
  3900. }
  3901. D3D12_INTERNAL_WriteGPUDescriptors(
  3902. commandBuffer,
  3903. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  3904. cpuHandles,
  3905. graphicsPipeline->vertexSamplerCount,
  3906. &gpuDescriptorHandle);
  3907. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  3908. commandBuffer->graphicsCommandList,
  3909. graphicsPipeline->rootSignature->vertexSamplerTextureRootIndex,
  3910. gpuDescriptorHandle);
  3911. }
  3912. commandBuffer->needVertexSamplerBind = false;
  3913. }
  3914. if (commandBuffer->needVertexStorageTextureBind) {
  3915. if (graphicsPipeline->vertexStorageTextureCount > 0) {
  3916. for (Uint32 i = 0; i < graphicsPipeline->vertexStorageTextureCount; i += 1) {
  3917. cpuHandles[i] = commandBuffer->vertexStorageTextures[i]->srvHandle.cpuHandle;
  3918. }
  3919. D3D12_INTERNAL_WriteGPUDescriptors(
  3920. commandBuffer,
  3921. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  3922. cpuHandles,
  3923. graphicsPipeline->vertexStorageTextureCount,
  3924. &gpuDescriptorHandle);
  3925. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  3926. commandBuffer->graphicsCommandList,
  3927. graphicsPipeline->rootSignature->vertexStorageTextureRootIndex,
  3928. gpuDescriptorHandle);
  3929. }
  3930. commandBuffer->needVertexStorageTextureBind = false;
  3931. }
  3932. if (commandBuffer->needVertexStorageBufferBind) {
  3933. if (graphicsPipeline->vertexStorageBufferCount > 0) {
  3934. for (Uint32 i = 0; i < graphicsPipeline->vertexStorageBufferCount; i += 1) {
  3935. cpuHandles[i] = commandBuffer->vertexStorageBuffers[i]->srvDescriptor.cpuHandle;
  3936. }
  3937. D3D12_INTERNAL_WriteGPUDescriptors(
  3938. commandBuffer,
  3939. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  3940. cpuHandles,
  3941. graphicsPipeline->vertexStorageBufferCount,
  3942. &gpuDescriptorHandle);
  3943. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  3944. commandBuffer->graphicsCommandList,
  3945. graphicsPipeline->rootSignature->vertexStorageBufferRootIndex,
  3946. gpuDescriptorHandle);
  3947. }
  3948. commandBuffer->needVertexStorageBufferBind = false;
  3949. }
  3950. for (Uint32 i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  3951. if (commandBuffer->needVertexUniformBufferBind[i]) {
  3952. if (graphicsPipeline->vertexUniformBufferCount > i) {
  3953. ID3D12GraphicsCommandList_SetGraphicsRootConstantBufferView(
  3954. commandBuffer->graphicsCommandList,
  3955. graphicsPipeline->rootSignature->vertexUniformBufferRootIndex[i],
  3956. commandBuffer->vertexUniformBuffers[i]->buffer->virtualAddress + commandBuffer->vertexUniformBuffers[i]->drawOffset);
  3957. }
  3958. commandBuffer->needVertexUniformBufferBind[i] = false;
  3959. }
  3960. }
  3961. if (commandBuffer->needFragmentSamplerBind) {
  3962. if (graphicsPipeline->fragmentSamplerCount > 0) {
  3963. for (Uint32 i = 0; i < graphicsPipeline->fragmentSamplerCount; i += 1) {
  3964. cpuHandles[i] = commandBuffer->fragmentSamplers[i]->handle.cpuHandle;
  3965. }
  3966. D3D12_INTERNAL_WriteGPUDescriptors(
  3967. commandBuffer,
  3968. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
  3969. cpuHandles,
  3970. graphicsPipeline->fragmentSamplerCount,
  3971. &gpuDescriptorHandle);
  3972. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  3973. commandBuffer->graphicsCommandList,
  3974. graphicsPipeline->rootSignature->fragmentSamplerRootIndex,
  3975. gpuDescriptorHandle);
  3976. for (Uint32 i = 0; i < graphicsPipeline->fragmentSamplerCount; i += 1) {
  3977. cpuHandles[i] = commandBuffer->fragmentSamplerTextures[i]->srvHandle.cpuHandle;
  3978. }
  3979. D3D12_INTERNAL_WriteGPUDescriptors(
  3980. commandBuffer,
  3981. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  3982. cpuHandles,
  3983. graphicsPipeline->fragmentSamplerCount,
  3984. &gpuDescriptorHandle);
  3985. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  3986. commandBuffer->graphicsCommandList,
  3987. graphicsPipeline->rootSignature->fragmentSamplerTextureRootIndex,
  3988. gpuDescriptorHandle);
  3989. }
  3990. commandBuffer->needFragmentSamplerBind = false;
  3991. }
  3992. if (commandBuffer->needFragmentStorageTextureBind) {
  3993. if (graphicsPipeline->fragmentStorageTextureCount > 0) {
  3994. for (Uint32 i = 0; i < graphicsPipeline->fragmentStorageTextureCount; i += 1) {
  3995. cpuHandles[i] = commandBuffer->fragmentStorageTextures[i]->srvHandle.cpuHandle;
  3996. }
  3997. D3D12_INTERNAL_WriteGPUDescriptors(
  3998. commandBuffer,
  3999. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4000. cpuHandles,
  4001. graphicsPipeline->fragmentStorageTextureCount,
  4002. &gpuDescriptorHandle);
  4003. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  4004. commandBuffer->graphicsCommandList,
  4005. graphicsPipeline->rootSignature->fragmentStorageTextureRootIndex,
  4006. gpuDescriptorHandle);
  4007. }
  4008. commandBuffer->needFragmentStorageTextureBind = false;
  4009. }
  4010. if (commandBuffer->needFragmentStorageBufferBind) {
  4011. if (graphicsPipeline->fragmentStorageBufferCount > 0) {
  4012. for (Uint32 i = 0; i < graphicsPipeline->fragmentStorageBufferCount; i += 1) {
  4013. cpuHandles[i] = commandBuffer->fragmentStorageBuffers[i]->srvDescriptor.cpuHandle;
  4014. }
  4015. D3D12_INTERNAL_WriteGPUDescriptors(
  4016. commandBuffer,
  4017. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4018. cpuHandles,
  4019. graphicsPipeline->fragmentStorageBufferCount,
  4020. &gpuDescriptorHandle);
  4021. ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(
  4022. commandBuffer->graphicsCommandList,
  4023. graphicsPipeline->rootSignature->fragmentStorageBufferRootIndex,
  4024. gpuDescriptorHandle);
  4025. }
  4026. commandBuffer->needFragmentStorageBufferBind = false;
  4027. }
  4028. for (Uint32 i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  4029. if (commandBuffer->needFragmentUniformBufferBind[i]) {
  4030. if (graphicsPipeline->fragmentUniformBufferCount > i) {
  4031. ID3D12GraphicsCommandList_SetGraphicsRootConstantBufferView(
  4032. commandBuffer->graphicsCommandList,
  4033. graphicsPipeline->rootSignature->fragmentUniformBufferRootIndex[i],
  4034. commandBuffer->fragmentUniformBuffers[i]->buffer->virtualAddress + commandBuffer->fragmentUniformBuffers[i]->drawOffset);
  4035. }
  4036. commandBuffer->needFragmentUniformBufferBind[i] = false;
  4037. }
  4038. }
  4039. }
  4040. static void D3D12_DrawIndexedPrimitives(
  4041. SDL_GPUCommandBuffer *commandBuffer,
  4042. Uint32 numIndices,
  4043. Uint32 numInstances,
  4044. Uint32 firstIndex,
  4045. Sint32 vertexOffset,
  4046. Uint32 firstInstance)
  4047. {
  4048. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4049. D3D12_INTERNAL_BindGraphicsResources(d3d12CommandBuffer);
  4050. ID3D12GraphicsCommandList_DrawIndexedInstanced(
  4051. d3d12CommandBuffer->graphicsCommandList,
  4052. numIndices,
  4053. numInstances,
  4054. firstIndex,
  4055. vertexOffset,
  4056. firstInstance);
  4057. }
  4058. static void D3D12_DrawPrimitives(
  4059. SDL_GPUCommandBuffer *commandBuffer,
  4060. Uint32 numVertices,
  4061. Uint32 numInstances,
  4062. Uint32 firstVertex,
  4063. Uint32 firstInstance)
  4064. {
  4065. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4066. D3D12_INTERNAL_BindGraphicsResources(d3d12CommandBuffer);
  4067. ID3D12GraphicsCommandList_DrawInstanced(
  4068. d3d12CommandBuffer->graphicsCommandList,
  4069. numVertices,
  4070. numInstances,
  4071. firstVertex,
  4072. firstInstance);
  4073. }
  4074. static void D3D12_DrawPrimitivesIndirect(
  4075. SDL_GPUCommandBuffer *commandBuffer,
  4076. SDL_GPUBuffer *buffer,
  4077. Uint32 offset,
  4078. Uint32 drawCount)
  4079. {
  4080. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4081. D3D12Buffer *d3d12Buffer = ((D3D12BufferContainer *)buffer)->activeBuffer;
  4082. D3D12_INTERNAL_BindGraphicsResources(d3d12CommandBuffer);
  4083. ID3D12GraphicsCommandList_ExecuteIndirect(
  4084. d3d12CommandBuffer->graphicsCommandList,
  4085. d3d12CommandBuffer->renderer->indirectDrawCommandSignature,
  4086. drawCount,
  4087. d3d12Buffer->handle,
  4088. offset,
  4089. NULL,
  4090. 0);
  4091. }
  4092. static void D3D12_DrawIndexedPrimitivesIndirect(
  4093. SDL_GPUCommandBuffer *commandBuffer,
  4094. SDL_GPUBuffer *buffer,
  4095. Uint32 offset,
  4096. Uint32 drawCount)
  4097. {
  4098. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4099. D3D12Buffer *d3d12Buffer = ((D3D12BufferContainer *)buffer)->activeBuffer;
  4100. D3D12_INTERNAL_BindGraphicsResources(d3d12CommandBuffer);
  4101. ID3D12GraphicsCommandList_ExecuteIndirect(
  4102. d3d12CommandBuffer->graphicsCommandList,
  4103. d3d12CommandBuffer->renderer->indirectIndexedDrawCommandSignature,
  4104. drawCount,
  4105. d3d12Buffer->handle,
  4106. offset,
  4107. NULL,
  4108. 0);
  4109. }
  4110. static void D3D12_EndRenderPass(
  4111. SDL_GPUCommandBuffer *commandBuffer)
  4112. {
  4113. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4114. Uint32 i;
  4115. for (i = 0; i < MAX_COLOR_TARGET_BINDINGS; i += 1) {
  4116. if (d3d12CommandBuffer->colorTargetSubresources[i] != NULL) {
  4117. if (d3d12CommandBuffer->colorResolveSubresources[i] != NULL) {
  4118. // Resolving requires some extra barriers
  4119. D3D12_INTERNAL_TextureSubresourceBarrier(
  4120. d3d12CommandBuffer,
  4121. D3D12_RESOURCE_STATE_RENDER_TARGET,
  4122. D3D12_RESOURCE_STATE_RESOLVE_SOURCE,
  4123. d3d12CommandBuffer->colorTargetSubresources[i]
  4124. );
  4125. ID3D12GraphicsCommandList_ResolveSubresource(
  4126. d3d12CommandBuffer->graphicsCommandList,
  4127. d3d12CommandBuffer->colorResolveSubresources[i]->parent->resource,
  4128. d3d12CommandBuffer->colorResolveSubresources[i]->index,
  4129. d3d12CommandBuffer->colorTargetSubresources[i]->parent->resource,
  4130. d3d12CommandBuffer->colorTargetSubresources[i]->index,
  4131. SDLToD3D12_TextureFormat[d3d12CommandBuffer->colorTargetSubresources[i]->parent->container->header.info.format]);
  4132. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  4133. d3d12CommandBuffer,
  4134. D3D12_RESOURCE_STATE_RESOLVE_SOURCE,
  4135. d3d12CommandBuffer->colorTargetSubresources[i]);
  4136. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  4137. d3d12CommandBuffer,
  4138. D3D12_RESOURCE_STATE_RESOLVE_DEST,
  4139. d3d12CommandBuffer->colorResolveSubresources[i]);
  4140. } else {
  4141. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  4142. d3d12CommandBuffer,
  4143. D3D12_RESOURCE_STATE_RENDER_TARGET,
  4144. d3d12CommandBuffer->colorTargetSubresources[i]);
  4145. }
  4146. }
  4147. }
  4148. if (d3d12CommandBuffer->depthStencilTextureSubresource != NULL) {
  4149. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  4150. d3d12CommandBuffer,
  4151. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  4152. d3d12CommandBuffer->depthStencilTextureSubresource);
  4153. d3d12CommandBuffer->depthStencilTextureSubresource = NULL;
  4154. }
  4155. d3d12CommandBuffer->currentGraphicsPipeline = NULL;
  4156. ID3D12GraphicsCommandList_OMSetRenderTargets(
  4157. d3d12CommandBuffer->graphicsCommandList,
  4158. 0,
  4159. NULL,
  4160. false,
  4161. NULL);
  4162. // Reset bind state
  4163. SDL_zeroa(d3d12CommandBuffer->colorTargetSubresources);
  4164. SDL_zeroa(d3d12CommandBuffer->colorResolveSubresources);
  4165. d3d12CommandBuffer->depthStencilTextureSubresource = NULL;
  4166. SDL_zeroa(d3d12CommandBuffer->vertexBuffers);
  4167. SDL_zeroa(d3d12CommandBuffer->vertexBufferOffsets);
  4168. d3d12CommandBuffer->vertexBufferCount = 0;
  4169. SDL_zeroa(d3d12CommandBuffer->vertexSamplerTextures);
  4170. SDL_zeroa(d3d12CommandBuffer->vertexSamplers);
  4171. SDL_zeroa(d3d12CommandBuffer->vertexStorageTextures);
  4172. SDL_zeroa(d3d12CommandBuffer->vertexStorageBuffers);
  4173. SDL_zeroa(d3d12CommandBuffer->fragmentSamplerTextures);
  4174. SDL_zeroa(d3d12CommandBuffer->fragmentSamplers);
  4175. SDL_zeroa(d3d12CommandBuffer->fragmentStorageTextures);
  4176. SDL_zeroa(d3d12CommandBuffer->fragmentStorageBuffers);
  4177. }
  4178. // Compute Pass
  4179. static void D3D12_BeginComputePass(
  4180. SDL_GPUCommandBuffer *commandBuffer,
  4181. const SDL_GPUStorageTextureReadWriteBinding *storageTextureBindings,
  4182. Uint32 numStorageTextureBindings,
  4183. const SDL_GPUStorageBufferReadWriteBinding *storageBufferBindings,
  4184. Uint32 numStorageBufferBindings)
  4185. {
  4186. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4187. d3d12CommandBuffer->computeReadWriteStorageTextureSubresourceCount = numStorageTextureBindings;
  4188. d3d12CommandBuffer->computeReadWriteStorageBufferCount = numStorageBufferBindings;
  4189. /* Read-write resources will be actually bound in BindComputePipeline
  4190. * after the root signature is set.
  4191. * We also have to scan to see which barriers we actually need because depth slices aren't separate subresources
  4192. */
  4193. if (numStorageTextureBindings > 0) {
  4194. for (Uint32 i = 0; i < numStorageTextureBindings; i += 1) {
  4195. D3D12TextureContainer *container = (D3D12TextureContainer *)storageTextureBindings[i].texture;
  4196. D3D12TextureSubresource *subresource = D3D12_INTERNAL_PrepareTextureSubresourceForWrite(
  4197. d3d12CommandBuffer,
  4198. container,
  4199. storageTextureBindings[i].layer,
  4200. storageTextureBindings[i].mip_level,
  4201. storageTextureBindings[i].cycle,
  4202. D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  4203. d3d12CommandBuffer->computeReadWriteStorageTextureSubresources[i] = subresource;
  4204. D3D12_INTERNAL_TrackTexture(
  4205. d3d12CommandBuffer,
  4206. subresource->parent);
  4207. }
  4208. }
  4209. if (numStorageBufferBindings > 0) {
  4210. for (Uint32 i = 0; i < numStorageBufferBindings; i += 1) {
  4211. D3D12BufferContainer *container = (D3D12BufferContainer *)storageBufferBindings[i].buffer;
  4212. D3D12Buffer *buffer = D3D12_INTERNAL_PrepareBufferForWrite(
  4213. d3d12CommandBuffer,
  4214. container,
  4215. storageBufferBindings[i].cycle,
  4216. D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  4217. d3d12CommandBuffer->computeReadWriteStorageBuffers[i] = buffer;
  4218. D3D12_INTERNAL_TrackBuffer(
  4219. d3d12CommandBuffer,
  4220. buffer);
  4221. }
  4222. }
  4223. }
  4224. static void D3D12_BindComputePipeline(
  4225. SDL_GPUCommandBuffer *commandBuffer,
  4226. SDL_GPUComputePipeline *computePipeline)
  4227. {
  4228. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4229. D3D12ComputePipeline *pipeline = (D3D12ComputePipeline *)computePipeline;
  4230. D3D12_CPU_DESCRIPTOR_HANDLE cpuHandles[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  4231. D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptorHandle;
  4232. ID3D12GraphicsCommandList_SetPipelineState(
  4233. d3d12CommandBuffer->graphicsCommandList,
  4234. pipeline->pipelineState);
  4235. ID3D12GraphicsCommandList_SetComputeRootSignature(
  4236. d3d12CommandBuffer->graphicsCommandList,
  4237. pipeline->rootSignature->handle);
  4238. d3d12CommandBuffer->currentComputePipeline = pipeline;
  4239. d3d12CommandBuffer->needComputeSamplerBind = true;
  4240. d3d12CommandBuffer->needComputeReadOnlyStorageTextureBind = true;
  4241. d3d12CommandBuffer->needComputeReadOnlyStorageBufferBind = true;
  4242. for (Uint32 i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  4243. d3d12CommandBuffer->needComputeUniformBufferBind[i] = true;
  4244. }
  4245. for (Uint32 i = 0; i < pipeline->numUniformBuffers; i += 1) {
  4246. if (d3d12CommandBuffer->computeUniformBuffers[i] == NULL) {
  4247. d3d12CommandBuffer->computeUniformBuffers[i] = D3D12_INTERNAL_AcquireUniformBufferFromPool(
  4248. d3d12CommandBuffer);
  4249. }
  4250. }
  4251. D3D12_INTERNAL_TrackComputePipeline(d3d12CommandBuffer, pipeline);
  4252. // Bind write-only resources after setting root signature
  4253. if (pipeline->numReadWriteStorageTextures > 0) {
  4254. for (Uint32 i = 0; i < pipeline->numReadWriteStorageTextures; i += 1) {
  4255. cpuHandles[i] = d3d12CommandBuffer->computeReadWriteStorageTextureSubresources[i]->uavHandle.cpuHandle;
  4256. }
  4257. D3D12_INTERNAL_WriteGPUDescriptors(
  4258. d3d12CommandBuffer,
  4259. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4260. cpuHandles,
  4261. d3d12CommandBuffer->computeReadWriteStorageTextureSubresourceCount,
  4262. &gpuDescriptorHandle);
  4263. ID3D12GraphicsCommandList_SetComputeRootDescriptorTable(
  4264. d3d12CommandBuffer->graphicsCommandList,
  4265. d3d12CommandBuffer->currentComputePipeline->rootSignature->readWriteStorageTextureRootIndex,
  4266. gpuDescriptorHandle);
  4267. }
  4268. if (pipeline->numReadWriteStorageBuffers > 0) {
  4269. for (Uint32 i = 0; i < pipeline->numReadWriteStorageBuffers; i += 1) {
  4270. cpuHandles[i] = d3d12CommandBuffer->computeReadWriteStorageBuffers[i]->uavDescriptor.cpuHandle;
  4271. }
  4272. D3D12_INTERNAL_WriteGPUDescriptors(
  4273. d3d12CommandBuffer,
  4274. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4275. cpuHandles,
  4276. d3d12CommandBuffer->computeReadWriteStorageBufferCount,
  4277. &gpuDescriptorHandle);
  4278. ID3D12GraphicsCommandList_SetComputeRootDescriptorTable(
  4279. d3d12CommandBuffer->graphicsCommandList,
  4280. d3d12CommandBuffer->currentComputePipeline->rootSignature->readWriteStorageBufferRootIndex,
  4281. gpuDescriptorHandle);
  4282. }
  4283. }
  4284. static void D3D12_BindComputeSamplers(
  4285. SDL_GPUCommandBuffer *commandBuffer,
  4286. Uint32 firstSlot,
  4287. const SDL_GPUTextureSamplerBinding *textureSamplerBindings,
  4288. Uint32 numBindings)
  4289. {
  4290. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4291. for (Uint32 i = 0; i < numBindings; i += 1) {
  4292. D3D12TextureContainer *container = (D3D12TextureContainer *)textureSamplerBindings[i].texture;
  4293. D3D12_INTERNAL_TrackSampler(
  4294. d3d12CommandBuffer,
  4295. (D3D12Sampler *)textureSamplerBindings[i].sampler);
  4296. D3D12_INTERNAL_TrackTexture(
  4297. d3d12CommandBuffer,
  4298. container->activeTexture);
  4299. d3d12CommandBuffer->computeSamplerTextures[firstSlot + i] = container->activeTexture;
  4300. d3d12CommandBuffer->computeSamplers[firstSlot + i] = (D3D12Sampler *)textureSamplerBindings[i].sampler;
  4301. }
  4302. d3d12CommandBuffer->needComputeSamplerBind = true;
  4303. }
  4304. static void D3D12_BindComputeStorageTextures(
  4305. SDL_GPUCommandBuffer *commandBuffer,
  4306. Uint32 firstSlot,
  4307. SDL_GPUTexture *const *storageTextures,
  4308. Uint32 numBindings)
  4309. {
  4310. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4311. for (Uint32 i = 0; i < numBindings; i += 1) {
  4312. if (d3d12CommandBuffer->computeReadOnlyStorageTextures[firstSlot + i] != NULL) {
  4313. D3D12_INTERNAL_TextureTransitionToDefaultUsage(
  4314. d3d12CommandBuffer,
  4315. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  4316. d3d12CommandBuffer->computeReadOnlyStorageTextures[firstSlot + i]);
  4317. }
  4318. D3D12TextureContainer *container = (D3D12TextureContainer *)storageTextures[i];
  4319. d3d12CommandBuffer->computeReadOnlyStorageTextures[firstSlot + i] = container->activeTexture;
  4320. D3D12_INTERNAL_TextureTransitionFromDefaultUsage(
  4321. d3d12CommandBuffer,
  4322. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  4323. container->activeTexture);
  4324. D3D12_INTERNAL_TrackTexture(
  4325. d3d12CommandBuffer,
  4326. container->activeTexture);
  4327. }
  4328. d3d12CommandBuffer->needComputeReadOnlyStorageTextureBind = true;
  4329. }
  4330. static void D3D12_BindComputeStorageBuffers(
  4331. SDL_GPUCommandBuffer *commandBuffer,
  4332. Uint32 firstSlot,
  4333. SDL_GPUBuffer *const *storageBuffers,
  4334. Uint32 numBindings)
  4335. {
  4336. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4337. for (Uint32 i = 0; i < numBindings; i += 1) {
  4338. if (d3d12CommandBuffer->computeReadOnlyStorageBuffers[firstSlot + i] != NULL) {
  4339. D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  4340. d3d12CommandBuffer,
  4341. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  4342. d3d12CommandBuffer->computeReadOnlyStorageBuffers[firstSlot + i]);
  4343. }
  4344. D3D12BufferContainer *container = (D3D12BufferContainer *)storageBuffers[i];
  4345. D3D12Buffer *buffer = container->activeBuffer;
  4346. d3d12CommandBuffer->computeReadOnlyStorageBuffers[firstSlot + i] = buffer;
  4347. D3D12_INTERNAL_BufferTransitionFromDefaultUsage(
  4348. d3d12CommandBuffer,
  4349. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  4350. buffer);
  4351. D3D12_INTERNAL_TrackBuffer(
  4352. d3d12CommandBuffer,
  4353. buffer);
  4354. }
  4355. d3d12CommandBuffer->needComputeReadOnlyStorageBufferBind = true;
  4356. }
  4357. static void D3D12_PushComputeUniformData(
  4358. SDL_GPUCommandBuffer *commandBuffer,
  4359. Uint32 slotIndex,
  4360. const void *data,
  4361. Uint32 length)
  4362. {
  4363. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4364. D3D12_INTERNAL_PushUniformData(
  4365. d3d12CommandBuffer,
  4366. SDL_GPU_SHADERSTAGE_COMPUTE,
  4367. slotIndex,
  4368. data,
  4369. length);
  4370. }
  4371. static void D3D12_INTERNAL_BindComputeResources(
  4372. D3D12CommandBuffer *commandBuffer)
  4373. {
  4374. D3D12ComputePipeline *computePipeline = commandBuffer->currentComputePipeline;
  4375. D3D12_CPU_DESCRIPTOR_HANDLE cpuHandles[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  4376. D3D12_GPU_DESCRIPTOR_HANDLE gpuDescriptorHandle;
  4377. if (commandBuffer->needComputeSamplerBind) {
  4378. if (computePipeline->numSamplers > 0) {
  4379. for (Uint32 i = 0; i < computePipeline->numSamplers; i += 1) {
  4380. cpuHandles[i] = commandBuffer->computeSamplers[i]->handle.cpuHandle;
  4381. }
  4382. D3D12_INTERNAL_WriteGPUDescriptors(
  4383. commandBuffer,
  4384. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
  4385. cpuHandles,
  4386. computePipeline->numSamplers,
  4387. &gpuDescriptorHandle);
  4388. ID3D12GraphicsCommandList_SetComputeRootDescriptorTable(
  4389. commandBuffer->graphicsCommandList,
  4390. computePipeline->rootSignature->samplerRootIndex,
  4391. gpuDescriptorHandle);
  4392. for (Uint32 i = 0; i < computePipeline->numSamplers; i += 1) {
  4393. cpuHandles[i] = commandBuffer->computeSamplerTextures[i]->srvHandle.cpuHandle;
  4394. }
  4395. D3D12_INTERNAL_WriteGPUDescriptors(
  4396. commandBuffer,
  4397. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4398. cpuHandles,
  4399. computePipeline->numSamplers,
  4400. &gpuDescriptorHandle);
  4401. ID3D12GraphicsCommandList_SetComputeRootDescriptorTable(
  4402. commandBuffer->graphicsCommandList,
  4403. computePipeline->rootSignature->samplerTextureRootIndex,
  4404. gpuDescriptorHandle);
  4405. }
  4406. commandBuffer->needComputeSamplerBind = false;
  4407. }
  4408. if (commandBuffer->needComputeReadOnlyStorageTextureBind) {
  4409. if (computePipeline->numReadOnlyStorageTextures > 0) {
  4410. for (Uint32 i = 0; i < computePipeline->numReadOnlyStorageTextures; i += 1) {
  4411. cpuHandles[i] = commandBuffer->computeReadOnlyStorageTextures[i]->srvHandle.cpuHandle;
  4412. }
  4413. D3D12_INTERNAL_WriteGPUDescriptors(
  4414. commandBuffer,
  4415. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4416. cpuHandles,
  4417. computePipeline->numReadOnlyStorageTextures,
  4418. &gpuDescriptorHandle);
  4419. ID3D12GraphicsCommandList_SetComputeRootDescriptorTable(
  4420. commandBuffer->graphicsCommandList,
  4421. computePipeline->rootSignature->readOnlyStorageTextureRootIndex,
  4422. gpuDescriptorHandle);
  4423. }
  4424. commandBuffer->needComputeReadOnlyStorageTextureBind = false;
  4425. }
  4426. if (commandBuffer->needComputeReadOnlyStorageBufferBind) {
  4427. if (computePipeline->numReadOnlyStorageBuffers > 0) {
  4428. for (Uint32 i = 0; i < computePipeline->numReadOnlyStorageBuffers; i += 1) {
  4429. cpuHandles[i] = commandBuffer->computeReadOnlyStorageBuffers[i]->srvDescriptor.cpuHandle;
  4430. }
  4431. D3D12_INTERNAL_WriteGPUDescriptors(
  4432. commandBuffer,
  4433. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  4434. cpuHandles,
  4435. computePipeline->numReadOnlyStorageBuffers,
  4436. &gpuDescriptorHandle);
  4437. ID3D12GraphicsCommandList_SetComputeRootDescriptorTable(
  4438. commandBuffer->graphicsCommandList,
  4439. computePipeline->rootSignature->readOnlyStorageBufferRootIndex,
  4440. gpuDescriptorHandle);
  4441. }
  4442. commandBuffer->needComputeReadOnlyStorageBufferBind = false;
  4443. }
  4444. for (Uint32 i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  4445. if (commandBuffer->needComputeUniformBufferBind[i]) {
  4446. if (computePipeline->numUniformBuffers > i) {
  4447. ID3D12GraphicsCommandList_SetComputeRootConstantBufferView(
  4448. commandBuffer->graphicsCommandList,
  4449. computePipeline->rootSignature->uniformBufferRootIndex[i],
  4450. commandBuffer->computeUniformBuffers[i]->buffer->virtualAddress + commandBuffer->computeUniformBuffers[i]->drawOffset);
  4451. }
  4452. }
  4453. commandBuffer->needComputeUniformBufferBind[i] = false;
  4454. }
  4455. }
  4456. static void D3D12_DispatchCompute(
  4457. SDL_GPUCommandBuffer *commandBuffer,
  4458. Uint32 groupcountX,
  4459. Uint32 groupcountY,
  4460. Uint32 groupcountZ)
  4461. {
  4462. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4463. D3D12_INTERNAL_BindComputeResources(d3d12CommandBuffer);
  4464. ID3D12GraphicsCommandList_Dispatch(
  4465. d3d12CommandBuffer->graphicsCommandList,
  4466. groupcountX,
  4467. groupcountY,
  4468. groupcountZ);
  4469. }
  4470. static void D3D12_DispatchComputeIndirect(
  4471. SDL_GPUCommandBuffer *commandBuffer,
  4472. SDL_GPUBuffer *buffer,
  4473. Uint32 offset)
  4474. {
  4475. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4476. D3D12Buffer *d3d12Buffer = ((D3D12BufferContainer *)buffer)->activeBuffer;
  4477. D3D12_INTERNAL_BindComputeResources(d3d12CommandBuffer);
  4478. ID3D12GraphicsCommandList_ExecuteIndirect(
  4479. d3d12CommandBuffer->graphicsCommandList,
  4480. d3d12CommandBuffer->renderer->indirectDispatchCommandSignature,
  4481. 1,
  4482. d3d12Buffer->handle,
  4483. offset,
  4484. NULL,
  4485. 0);
  4486. }
  4487. static void D3D12_EndComputePass(
  4488. SDL_GPUCommandBuffer *commandBuffer)
  4489. {
  4490. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4491. for (Uint32 i = 0; i < d3d12CommandBuffer->computeReadWriteStorageTextureSubresourceCount; i += 1) {
  4492. if (d3d12CommandBuffer->computeReadWriteStorageTextureSubresources[i]) {
  4493. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  4494. d3d12CommandBuffer,
  4495. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  4496. d3d12CommandBuffer->computeReadWriteStorageTextureSubresources[i]);
  4497. d3d12CommandBuffer->computeReadWriteStorageTextureSubresources[i] = NULL;
  4498. }
  4499. }
  4500. d3d12CommandBuffer->computeReadWriteStorageTextureSubresourceCount = 0;
  4501. for (Uint32 i = 0; i < d3d12CommandBuffer->computeReadWriteStorageBufferCount; i += 1) {
  4502. if (d3d12CommandBuffer->computeReadWriteStorageBuffers[i]) {
  4503. D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  4504. d3d12CommandBuffer,
  4505. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  4506. d3d12CommandBuffer->computeReadWriteStorageBuffers[i]);
  4507. d3d12CommandBuffer->computeReadWriteStorageBuffers[i] = NULL;
  4508. }
  4509. }
  4510. d3d12CommandBuffer->computeReadWriteStorageBufferCount = 0;
  4511. for (Uint32 i = 0; i < MAX_STORAGE_TEXTURES_PER_STAGE; i += 1) {
  4512. if (d3d12CommandBuffer->computeReadOnlyStorageTextures[i]) {
  4513. D3D12_INTERNAL_TextureTransitionToDefaultUsage(
  4514. d3d12CommandBuffer,
  4515. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  4516. d3d12CommandBuffer->computeReadOnlyStorageTextures[i]);
  4517. d3d12CommandBuffer->computeReadOnlyStorageTextures[i] = NULL;
  4518. }
  4519. }
  4520. for (Uint32 i = 0; i < MAX_STORAGE_BUFFERS_PER_STAGE; i += 1) {
  4521. if (d3d12CommandBuffer->computeReadOnlyStorageBuffers[i]) {
  4522. D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  4523. d3d12CommandBuffer,
  4524. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  4525. d3d12CommandBuffer->computeReadOnlyStorageBuffers[i]);
  4526. d3d12CommandBuffer->computeReadOnlyStorageBuffers[i] = NULL;
  4527. }
  4528. }
  4529. SDL_zeroa(d3d12CommandBuffer->computeSamplerTextures);
  4530. SDL_zeroa(d3d12CommandBuffer->computeSamplers);
  4531. d3d12CommandBuffer->currentComputePipeline = NULL;
  4532. }
  4533. // TransferBuffer Data
  4534. static void *D3D12_MapTransferBuffer(
  4535. SDL_GPURenderer *driverData,
  4536. SDL_GPUTransferBuffer *transferBuffer,
  4537. bool cycle)
  4538. {
  4539. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  4540. D3D12BufferContainer *container = (D3D12BufferContainer *)transferBuffer;
  4541. void *dataPointer;
  4542. if (
  4543. cycle &&
  4544. SDL_GetAtomicInt(&container->activeBuffer->referenceCount) > 0) {
  4545. D3D12_INTERNAL_CycleActiveBuffer(
  4546. renderer,
  4547. container);
  4548. }
  4549. // Upload buffers are persistently mapped, download buffers are not
  4550. if (container->type == D3D12_BUFFER_TYPE_UPLOAD) {
  4551. dataPointer = container->activeBuffer->mapPointer;
  4552. } else {
  4553. ID3D12Resource_Map(
  4554. container->activeBuffer->handle,
  4555. 0,
  4556. NULL,
  4557. (void **)&dataPointer);
  4558. }
  4559. return dataPointer;
  4560. }
  4561. static void D3D12_UnmapTransferBuffer(
  4562. SDL_GPURenderer *driverData,
  4563. SDL_GPUTransferBuffer *transferBuffer)
  4564. {
  4565. (void)driverData;
  4566. D3D12BufferContainer *container = (D3D12BufferContainer *)transferBuffer;
  4567. // Upload buffers are persistently mapped, download buffers are not
  4568. if (container->type == D3D12_BUFFER_TYPE_DOWNLOAD) {
  4569. ID3D12Resource_Unmap(
  4570. container->activeBuffer->handle,
  4571. 0,
  4572. NULL);
  4573. }
  4574. }
  4575. // Copy Pass
  4576. static void D3D12_BeginCopyPass(
  4577. SDL_GPUCommandBuffer *commandBuffer)
  4578. {
  4579. // no-op
  4580. (void)commandBuffer;
  4581. }
  4582. static void D3D12_UploadToTexture(
  4583. SDL_GPUCommandBuffer *commandBuffer,
  4584. const SDL_GPUTextureTransferInfo *source,
  4585. const SDL_GPUTextureRegion *destination,
  4586. bool cycle)
  4587. {
  4588. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4589. D3D12BufferContainer *transferBufferContainer = (D3D12BufferContainer *)source->transfer_buffer;
  4590. D3D12Buffer *temporaryBuffer = NULL;
  4591. D3D12_TEXTURE_COPY_LOCATION sourceLocation;
  4592. D3D12_TEXTURE_COPY_LOCATION destinationLocation;
  4593. Uint32 pixelsPerRow = source->pixels_per_row;
  4594. Uint32 rowPitch;
  4595. Uint32 alignedRowPitch;
  4596. Uint32 rowsPerSlice = source->rows_per_layer;
  4597. Uint32 bytesPerSlice;
  4598. bool needsRealignment;
  4599. bool needsPlacementCopy;
  4600. // Note that the transfer buffer does not need a barrier, as it is synced by the client.
  4601. D3D12TextureContainer *textureContainer = (D3D12TextureContainer *)destination->texture;
  4602. D3D12TextureSubresource *textureSubresource = D3D12_INTERNAL_PrepareTextureSubresourceForWrite(
  4603. d3d12CommandBuffer,
  4604. textureContainer,
  4605. destination->layer,
  4606. destination->mip_level,
  4607. cycle,
  4608. D3D12_RESOURCE_STATE_COPY_DEST);
  4609. /* D3D12 requires texture data row pitch to be 256 byte aligned, which is obviously insane.
  4610. * Instead of exposing that restriction to the client, which is a huge rake to step on,
  4611. * and a restriction that no other backend requires, we're going to copy data to a temporary buffer,
  4612. * copy THAT data to the texture, and then get rid of the temporary buffer ASAP.
  4613. * If we're lucky and the row pitch and depth pitch are already aligned, we can skip all of that.
  4614. *
  4615. * D3D12 also requires offsets to be 512 byte aligned. We'll fix that for the client and warn them as well.
  4616. *
  4617. * And just for some extra fun, D3D12 doesn't actually support depth pitch, so we have to realign that too!
  4618. */
  4619. if (pixelsPerRow == 0) {
  4620. pixelsPerRow = destination->w;
  4621. }
  4622. rowPitch = BytesPerRow(pixelsPerRow, textureContainer->header.info.format);
  4623. if (rowsPerSlice == 0) {
  4624. rowsPerSlice = destination->h;
  4625. }
  4626. bytesPerSlice = rowsPerSlice * rowPitch;
  4627. alignedRowPitch = D3D12_INTERNAL_Align(rowPitch, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  4628. needsRealignment = rowsPerSlice != destination->h || rowPitch != alignedRowPitch;
  4629. needsPlacementCopy = source->offset % D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT != 0;
  4630. sourceLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  4631. sourceLocation.PlacedFootprint.Footprint.Format = SDLToD3D12_TextureFormat[textureContainer->header.info.format];
  4632. sourceLocation.PlacedFootprint.Footprint.RowPitch = alignedRowPitch;
  4633. destinationLocation.pResource = textureContainer->activeTexture->resource;
  4634. destinationLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  4635. destinationLocation.SubresourceIndex = textureSubresource->index;
  4636. if (needsRealignment) {
  4637. temporaryBuffer = D3D12_INTERNAL_CreateBuffer(
  4638. d3d12CommandBuffer->renderer,
  4639. 0,
  4640. alignedRowPitch * destination->h * destination->d,
  4641. D3D12_BUFFER_TYPE_UPLOAD);
  4642. if (!temporaryBuffer) {
  4643. return;
  4644. }
  4645. sourceLocation.pResource = temporaryBuffer->handle;
  4646. for (Uint32 sliceIndex = 0; sliceIndex < destination->d; sliceIndex += 1) {
  4647. // copy row count minus one to avoid overread
  4648. for (Uint32 rowIndex = 0; rowIndex < rowsPerSlice - 1; rowIndex += 1) {
  4649. SDL_memcpy(
  4650. temporaryBuffer->mapPointer + (sliceIndex * rowsPerSlice) + (rowIndex * alignedRowPitch),
  4651. transferBufferContainer->activeBuffer->mapPointer + source->offset + (sliceIndex * bytesPerSlice) + (rowIndex * rowPitch),
  4652. alignedRowPitch);
  4653. }
  4654. Uint32 offset = source->offset + (sliceIndex * bytesPerSlice) + ((rowsPerSlice - 1) * rowPitch);
  4655. SDL_memcpy(
  4656. temporaryBuffer->mapPointer + (sliceIndex * rowsPerSlice) + ((rowsPerSlice - 1) * alignedRowPitch),
  4657. transferBufferContainer->activeBuffer->mapPointer + offset,
  4658. SDL_min(alignedRowPitch, transferBufferContainer->size - offset));
  4659. sourceLocation.PlacedFootprint.Footprint.Width = destination->w;
  4660. sourceLocation.PlacedFootprint.Footprint.Height = rowsPerSlice;
  4661. sourceLocation.PlacedFootprint.Footprint.Depth = 1;
  4662. sourceLocation.PlacedFootprint.Offset = (sliceIndex * bytesPerSlice);
  4663. ID3D12GraphicsCommandList_CopyTextureRegion(
  4664. d3d12CommandBuffer->graphicsCommandList,
  4665. &destinationLocation,
  4666. destination->x,
  4667. destination->y,
  4668. sliceIndex,
  4669. &sourceLocation,
  4670. NULL);
  4671. }
  4672. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, temporaryBuffer);
  4673. D3D12_INTERNAL_ReleaseBuffer(
  4674. d3d12CommandBuffer->renderer,
  4675. temporaryBuffer);
  4676. } else if (needsPlacementCopy) {
  4677. temporaryBuffer = D3D12_INTERNAL_CreateBuffer(
  4678. d3d12CommandBuffer->renderer,
  4679. 0,
  4680. alignedRowPitch * destination->h * destination->d,
  4681. D3D12_BUFFER_TYPE_UPLOAD);
  4682. if (!temporaryBuffer) {
  4683. return;
  4684. }
  4685. SDL_memcpy(
  4686. temporaryBuffer->mapPointer,
  4687. transferBufferContainer->activeBuffer->mapPointer + source->offset,
  4688. alignedRowPitch * destination->h * destination->d);
  4689. sourceLocation.pResource = temporaryBuffer->handle;
  4690. sourceLocation.PlacedFootprint.Offset = 0;
  4691. sourceLocation.PlacedFootprint.Footprint.Width = destination->w;
  4692. sourceLocation.PlacedFootprint.Footprint.Height = destination->h;
  4693. sourceLocation.PlacedFootprint.Footprint.Depth = 1;
  4694. ID3D12GraphicsCommandList_CopyTextureRegion(
  4695. d3d12CommandBuffer->graphicsCommandList,
  4696. &destinationLocation,
  4697. destination->x,
  4698. destination->y,
  4699. destination->z,
  4700. &sourceLocation,
  4701. NULL);
  4702. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, temporaryBuffer);
  4703. D3D12_INTERNAL_ReleaseBuffer(
  4704. d3d12CommandBuffer->renderer,
  4705. temporaryBuffer);
  4706. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Texture upload offset not aligned to 512 bytes! This is suboptimal on D3D12!");
  4707. } else {
  4708. sourceLocation.pResource = transferBufferContainer->activeBuffer->handle;
  4709. sourceLocation.PlacedFootprint.Offset = source->offset;
  4710. sourceLocation.PlacedFootprint.Footprint.Width = destination->w;
  4711. sourceLocation.PlacedFootprint.Footprint.Height = destination->h;
  4712. sourceLocation.PlacedFootprint.Footprint.Depth = destination->d;
  4713. ID3D12GraphicsCommandList_CopyTextureRegion(
  4714. d3d12CommandBuffer->graphicsCommandList,
  4715. &destinationLocation,
  4716. destination->x,
  4717. destination->y,
  4718. destination->z,
  4719. &sourceLocation,
  4720. NULL);
  4721. }
  4722. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  4723. d3d12CommandBuffer,
  4724. D3D12_RESOURCE_STATE_COPY_DEST,
  4725. textureSubresource);
  4726. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, transferBufferContainer->activeBuffer);
  4727. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, textureSubresource->parent);
  4728. }
  4729. static void D3D12_UploadToBuffer(
  4730. SDL_GPUCommandBuffer *commandBuffer,
  4731. const SDL_GPUTransferBufferLocation *source,
  4732. const SDL_GPUBufferRegion *destination,
  4733. bool cycle)
  4734. {
  4735. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4736. D3D12BufferContainer *transferBufferContainer = (D3D12BufferContainer *)source->transfer_buffer;
  4737. D3D12BufferContainer *bufferContainer = (D3D12BufferContainer *)destination->buffer;
  4738. // The transfer buffer does not need a barrier, it is synced by the client.
  4739. D3D12Buffer *buffer = D3D12_INTERNAL_PrepareBufferForWrite(
  4740. d3d12CommandBuffer,
  4741. bufferContainer,
  4742. cycle,
  4743. D3D12_RESOURCE_STATE_COPY_DEST);
  4744. ID3D12GraphicsCommandList_CopyBufferRegion(
  4745. d3d12CommandBuffer->graphicsCommandList,
  4746. buffer->handle,
  4747. destination->offset,
  4748. transferBufferContainer->activeBuffer->handle,
  4749. source->offset,
  4750. destination->size);
  4751. D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  4752. d3d12CommandBuffer,
  4753. D3D12_RESOURCE_STATE_COPY_DEST,
  4754. buffer);
  4755. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, transferBufferContainer->activeBuffer);
  4756. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, buffer);
  4757. }
  4758. static void D3D12_CopyTextureToTexture(
  4759. SDL_GPUCommandBuffer *commandBuffer,
  4760. const SDL_GPUTextureLocation *source,
  4761. const SDL_GPUTextureLocation *destination,
  4762. Uint32 w,
  4763. Uint32 h,
  4764. Uint32 d,
  4765. bool cycle)
  4766. {
  4767. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4768. D3D12_TEXTURE_COPY_LOCATION sourceLocation;
  4769. D3D12_TEXTURE_COPY_LOCATION destinationLocation;
  4770. D3D12TextureSubresource *sourceSubresource = D3D12_INTERNAL_FetchTextureSubresource(
  4771. (D3D12TextureContainer *)source->texture,
  4772. source->layer,
  4773. source->mip_level);
  4774. D3D12TextureSubresource *destinationSubresource = D3D12_INTERNAL_PrepareTextureSubresourceForWrite(
  4775. d3d12CommandBuffer,
  4776. (D3D12TextureContainer *)destination->texture,
  4777. destination->layer,
  4778. destination->mip_level,
  4779. cycle,
  4780. D3D12_RESOURCE_STATE_COPY_DEST);
  4781. D3D12_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  4782. d3d12CommandBuffer,
  4783. D3D12_RESOURCE_STATE_COPY_SOURCE,
  4784. sourceSubresource);
  4785. sourceLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  4786. sourceLocation.SubresourceIndex = sourceSubresource->index;
  4787. sourceLocation.pResource = sourceSubresource->parent->resource;
  4788. destinationLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  4789. destinationLocation.SubresourceIndex = destinationSubresource->index;
  4790. destinationLocation.pResource = destinationSubresource->parent->resource;
  4791. D3D12_BOX sourceBox = { source->x, source->y, source->z, source->x + w, source->y + h, source->z + d };
  4792. ID3D12GraphicsCommandList_CopyTextureRegion(
  4793. d3d12CommandBuffer->graphicsCommandList,
  4794. &destinationLocation,
  4795. destination->x,
  4796. destination->y,
  4797. destination->z,
  4798. &sourceLocation,
  4799. &sourceBox);
  4800. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  4801. d3d12CommandBuffer,
  4802. D3D12_RESOURCE_STATE_COPY_SOURCE,
  4803. sourceSubresource);
  4804. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  4805. d3d12CommandBuffer,
  4806. D3D12_RESOURCE_STATE_COPY_DEST,
  4807. destinationSubresource);
  4808. D3D12_INTERNAL_TrackTexture(
  4809. d3d12CommandBuffer,
  4810. sourceSubresource->parent);
  4811. D3D12_INTERNAL_TrackTexture(
  4812. d3d12CommandBuffer,
  4813. destinationSubresource->parent);
  4814. }
  4815. static void D3D12_CopyBufferToBuffer(
  4816. SDL_GPUCommandBuffer *commandBuffer,
  4817. const SDL_GPUBufferLocation *source,
  4818. const SDL_GPUBufferLocation *destination,
  4819. Uint32 size,
  4820. bool cycle)
  4821. {
  4822. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4823. D3D12BufferContainer *sourceContainer = (D3D12BufferContainer *)source->buffer;
  4824. D3D12BufferContainer *destinationContainer = (D3D12BufferContainer *)destination->buffer;
  4825. D3D12Buffer *sourceBuffer = sourceContainer->activeBuffer;
  4826. D3D12Buffer *destinationBuffer = D3D12_INTERNAL_PrepareBufferForWrite(
  4827. d3d12CommandBuffer,
  4828. destinationContainer,
  4829. cycle,
  4830. D3D12_RESOURCE_STATE_COPY_DEST);
  4831. D3D12_INTERNAL_BufferTransitionFromDefaultUsage(
  4832. d3d12CommandBuffer,
  4833. D3D12_RESOURCE_STATE_COPY_SOURCE,
  4834. sourceBuffer);
  4835. ID3D12GraphicsCommandList_CopyBufferRegion(
  4836. d3d12CommandBuffer->graphicsCommandList,
  4837. destinationBuffer->handle,
  4838. destination->offset,
  4839. sourceBuffer->handle,
  4840. source->offset,
  4841. size);
  4842. D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  4843. d3d12CommandBuffer,
  4844. D3D12_RESOURCE_STATE_COPY_SOURCE,
  4845. sourceBuffer);
  4846. D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  4847. d3d12CommandBuffer,
  4848. D3D12_RESOURCE_STATE_COPY_DEST,
  4849. destinationBuffer);
  4850. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, sourceBuffer);
  4851. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, destinationBuffer);
  4852. }
  4853. static void D3D12_DownloadFromTexture(
  4854. SDL_GPUCommandBuffer *commandBuffer,
  4855. const SDL_GPUTextureRegion *source,
  4856. const SDL_GPUTextureTransferInfo *destination)
  4857. {
  4858. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4859. D3D12_TEXTURE_COPY_LOCATION sourceLocation;
  4860. D3D12_TEXTURE_COPY_LOCATION destinationLocation;
  4861. Uint32 pixelsPerRow = destination->pixels_per_row;
  4862. Uint32 rowPitch;
  4863. Uint32 alignedRowPitch;
  4864. Uint32 rowsPerSlice = destination->rows_per_layer;
  4865. bool needsRealignment;
  4866. bool needsPlacementCopy;
  4867. D3D12TextureDownload *textureDownload = NULL;
  4868. D3D12TextureContainer *sourceContainer = (D3D12TextureContainer *)source->texture;
  4869. D3D12TextureSubresource *sourceSubresource = D3D12_INTERNAL_FetchTextureSubresource(
  4870. sourceContainer,
  4871. source->layer,
  4872. source->mip_level);
  4873. D3D12BufferContainer *destinationContainer = (D3D12BufferContainer *)destination->transfer_buffer;
  4874. D3D12Buffer *destinationBuffer = destinationContainer->activeBuffer;
  4875. /* D3D12 requires texture data row pitch to be 256 byte aligned, which is obviously insane.
  4876. * Instead of exposing that restriction to the client, which is a huge rake to step on,
  4877. * and a restriction that no other backend requires, we're going to copy data to a temporary buffer,
  4878. * copy THAT data to the texture, and then get rid of the temporary buffer ASAP.
  4879. * If we're lucky and the row pitch and depth pitch are already aligned, we can skip all of that.
  4880. *
  4881. * D3D12 also requires offsets to be 512 byte aligned. We'll fix that for the client and warn them as well.
  4882. *
  4883. * And just for some extra fun, D3D12 doesn't actually support depth pitch, so we have to realign that too!
  4884. *
  4885. * Since this is an async download we have to do all these fixups after the command is finished,
  4886. * so we'll cache the metadata similar to D3D11 and map and copy it when the command buffer is cleaned.
  4887. */
  4888. if (pixelsPerRow == 0) {
  4889. pixelsPerRow = source->w;
  4890. }
  4891. rowPitch = BytesPerRow(pixelsPerRow, sourceContainer->header.info.format);
  4892. if (rowsPerSlice == 0) {
  4893. rowsPerSlice = source->h;
  4894. }
  4895. alignedRowPitch = D3D12_INTERNAL_Align(rowPitch, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  4896. needsRealignment = rowsPerSlice != source->h || rowPitch != alignedRowPitch;
  4897. needsPlacementCopy = destination->offset % D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT != 0;
  4898. sourceLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
  4899. sourceLocation.SubresourceIndex = sourceSubresource->index;
  4900. sourceLocation.pResource = sourceSubresource->parent->resource;
  4901. D3D12_BOX sourceBox = { source->x, source->y, source->z, source->x + source->w, source->y + rowsPerSlice, source->z + source->d };
  4902. destinationLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
  4903. destinationLocation.PlacedFootprint.Footprint.Format = SDLToD3D12_TextureFormat[sourceContainer->header.info.format];
  4904. destinationLocation.PlacedFootprint.Footprint.Width = source->w;
  4905. destinationLocation.PlacedFootprint.Footprint.Height = rowsPerSlice;
  4906. destinationLocation.PlacedFootprint.Footprint.Depth = source->d;
  4907. destinationLocation.PlacedFootprint.Footprint.RowPitch = alignedRowPitch;
  4908. if (needsRealignment || needsPlacementCopy) {
  4909. textureDownload = (D3D12TextureDownload *)SDL_malloc(sizeof(D3D12TextureDownload));
  4910. if (!textureDownload) {
  4911. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create texture download structure!");
  4912. return;
  4913. }
  4914. textureDownload->temporaryBuffer = D3D12_INTERNAL_CreateBuffer(
  4915. d3d12CommandBuffer->renderer,
  4916. 0,
  4917. alignedRowPitch * rowsPerSlice * source->d,
  4918. D3D12_BUFFER_TYPE_DOWNLOAD);
  4919. if (!textureDownload->temporaryBuffer) {
  4920. SDL_free(textureDownload);
  4921. return;
  4922. }
  4923. textureDownload->destinationBuffer = destinationBuffer;
  4924. textureDownload->bufferOffset = destination->offset;
  4925. textureDownload->width = source->w;
  4926. textureDownload->height = rowsPerSlice;
  4927. textureDownload->depth = source->d;
  4928. textureDownload->bytesPerRow = rowPitch;
  4929. textureDownload->bytesPerDepthSlice = rowPitch * rowsPerSlice;
  4930. textureDownload->alignedBytesPerRow = alignedRowPitch;
  4931. destinationLocation.pResource = textureDownload->temporaryBuffer->handle;
  4932. destinationLocation.PlacedFootprint.Offset = 0;
  4933. } else {
  4934. destinationLocation.pResource = destinationBuffer->handle;
  4935. destinationLocation.PlacedFootprint.Offset = destination->offset;
  4936. }
  4937. D3D12_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  4938. d3d12CommandBuffer,
  4939. D3D12_RESOURCE_STATE_COPY_SOURCE,
  4940. sourceSubresource);
  4941. ID3D12GraphicsCommandList_CopyTextureRegion(
  4942. d3d12CommandBuffer->graphicsCommandList,
  4943. &destinationLocation,
  4944. 0,
  4945. 0,
  4946. 0,
  4947. &sourceLocation,
  4948. &sourceBox);
  4949. D3D12_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  4950. d3d12CommandBuffer,
  4951. D3D12_RESOURCE_STATE_COPY_SOURCE,
  4952. sourceSubresource);
  4953. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, destinationBuffer);
  4954. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, sourceSubresource->parent);
  4955. if (textureDownload != NULL) {
  4956. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, textureDownload->temporaryBuffer);
  4957. if (d3d12CommandBuffer->textureDownloadCount >= d3d12CommandBuffer->textureDownloadCapacity) {
  4958. d3d12CommandBuffer->textureDownloadCapacity *= 2;
  4959. d3d12CommandBuffer->textureDownloads = (D3D12TextureDownload **)SDL_realloc(
  4960. d3d12CommandBuffer->textureDownloads,
  4961. d3d12CommandBuffer->textureDownloadCapacity * sizeof(D3D12TextureDownload *));
  4962. }
  4963. d3d12CommandBuffer->textureDownloads[d3d12CommandBuffer->textureDownloadCount] = textureDownload;
  4964. d3d12CommandBuffer->textureDownloadCount += 1;
  4965. D3D12_INTERNAL_ReleaseBuffer(d3d12CommandBuffer->renderer, textureDownload->temporaryBuffer);
  4966. }
  4967. }
  4968. static void D3D12_DownloadFromBuffer(
  4969. SDL_GPUCommandBuffer *commandBuffer,
  4970. const SDL_GPUBufferRegion *source,
  4971. const SDL_GPUTransferBufferLocation *destination)
  4972. {
  4973. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  4974. D3D12BufferContainer *sourceContainer = (D3D12BufferContainer *)source->buffer;
  4975. D3D12BufferContainer *destinationContainer = (D3D12BufferContainer *)destination->transfer_buffer;
  4976. D3D12Buffer *sourceBuffer = sourceContainer->activeBuffer;
  4977. D3D12_INTERNAL_BufferTransitionFromDefaultUsage(
  4978. d3d12CommandBuffer,
  4979. D3D12_RESOURCE_STATE_COPY_SOURCE,
  4980. sourceBuffer);
  4981. D3D12Buffer *destinationBuffer = destinationContainer->activeBuffer;
  4982. ID3D12GraphicsCommandList_CopyBufferRegion(
  4983. d3d12CommandBuffer->graphicsCommandList,
  4984. destinationBuffer->handle,
  4985. destination->offset,
  4986. sourceBuffer->handle,
  4987. source->offset,
  4988. source->size);
  4989. D3D12_INTERNAL_BufferTransitionToDefaultUsage(
  4990. d3d12CommandBuffer,
  4991. D3D12_RESOURCE_STATE_COPY_SOURCE,
  4992. sourceBuffer);
  4993. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, sourceBuffer);
  4994. D3D12_INTERNAL_TrackBuffer(d3d12CommandBuffer, destinationBuffer);
  4995. }
  4996. static void D3D12_EndCopyPass(
  4997. SDL_GPUCommandBuffer *commandBuffer)
  4998. {
  4999. // no-op
  5000. (void)commandBuffer;
  5001. }
  5002. static void D3D12_GenerateMipmaps(
  5003. SDL_GPUCommandBuffer *commandBuffer,
  5004. SDL_GPUTexture *texture)
  5005. {
  5006. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  5007. D3D12Renderer *renderer = d3d12CommandBuffer->renderer;
  5008. D3D12TextureContainer *container = (D3D12TextureContainer *)texture;
  5009. SDL_GPUGraphicsPipeline *blitPipeline;
  5010. blitPipeline = SDL_GPU_FetchBlitPipeline(
  5011. renderer->sdlGPUDevice,
  5012. container->header.info.type,
  5013. container->header.info.format,
  5014. renderer->blitVertexShader,
  5015. renderer->blitFrom2DShader,
  5016. renderer->blitFrom2DArrayShader,
  5017. renderer->blitFrom3DShader,
  5018. renderer->blitFromCubeShader,
  5019. renderer->blitFromCubeArrayShader,
  5020. &renderer->blitPipelines,
  5021. &renderer->blitPipelineCount,
  5022. &renderer->blitPipelineCapacity);
  5023. if (blitPipeline == NULL) {
  5024. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Could not fetch blit pipeline");
  5025. return;
  5026. }
  5027. // We have to do this one subresource at a time
  5028. for (Uint32 layerOrDepthIndex = 0; layerOrDepthIndex < container->header.info.layer_count_or_depth; layerOrDepthIndex += 1) {
  5029. for (Uint32 levelIndex = 1; levelIndex < container->header.info.num_levels; levelIndex += 1) {
  5030. SDL_GPUBlitInfo blitInfo;
  5031. SDL_zero(blitInfo);
  5032. blitInfo.source.texture = texture;
  5033. blitInfo.source.mip_level = levelIndex - 1;
  5034. blitInfo.source.layer_or_depth_plane = layerOrDepthIndex;
  5035. blitInfo.source.x = 0;
  5036. blitInfo.source.y = 0;
  5037. blitInfo.source.w = container->header.info.width >> (levelIndex - 1);
  5038. blitInfo.source.h = container->header.info.height >> (levelIndex - 1);
  5039. blitInfo.destination.texture = texture;
  5040. blitInfo.destination.mip_level = levelIndex;
  5041. blitInfo.destination.layer_or_depth_plane = layerOrDepthIndex;
  5042. blitInfo.destination.x = 0;
  5043. blitInfo.destination.y = 0;
  5044. blitInfo.destination.w = container->header.info.width >> levelIndex;
  5045. blitInfo.destination.h = container->header.info.height >> levelIndex;
  5046. blitInfo.load_op = SDL_GPU_LOADOP_DONT_CARE;
  5047. blitInfo.filter = SDL_GPU_FILTER_LINEAR;
  5048. SDL_BlitGPUTexture(
  5049. commandBuffer,
  5050. &blitInfo);
  5051. }
  5052. }
  5053. D3D12_INTERNAL_TrackTexture(d3d12CommandBuffer, container->activeTexture);
  5054. }
  5055. static void D3D12_Blit(
  5056. SDL_GPUCommandBuffer *commandBuffer,
  5057. const SDL_GPUBlitInfo *info)
  5058. {
  5059. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  5060. D3D12Renderer *renderer = (D3D12Renderer *)d3d12CommandBuffer->renderer;
  5061. SDL_GPU_BlitCommon(
  5062. commandBuffer,
  5063. info,
  5064. renderer->blitLinearSampler,
  5065. renderer->blitNearestSampler,
  5066. renderer->blitVertexShader,
  5067. renderer->blitFrom2DShader,
  5068. renderer->blitFrom2DArrayShader,
  5069. renderer->blitFrom3DShader,
  5070. renderer->blitFromCubeShader,
  5071. renderer->blitFromCubeArrayShader,
  5072. &renderer->blitPipelines,
  5073. &renderer->blitPipelineCount,
  5074. &renderer->blitPipelineCapacity);
  5075. }
  5076. // Submission/Presentation
  5077. static D3D12WindowData *D3D12_INTERNAL_FetchWindowData(
  5078. SDL_Window *window)
  5079. {
  5080. SDL_PropertiesID properties = SDL_GetWindowProperties(window);
  5081. return (D3D12WindowData *)SDL_GetPointerProperty(properties, WINDOW_PROPERTY_DATA, NULL);
  5082. }
  5083. static bool D3D12_INTERNAL_OnWindowResize(void *userdata, SDL_Event *e)
  5084. {
  5085. SDL_Window *w = (SDL_Window *)userdata;
  5086. D3D12WindowData *data;
  5087. if (e->type == SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED && e->window.windowID == SDL_GetWindowID(w)) {
  5088. data = D3D12_INTERNAL_FetchWindowData(w);
  5089. data->needsSwapchainRecreate = true;
  5090. }
  5091. return true;
  5092. }
  5093. static bool D3D12_SupportsSwapchainComposition(
  5094. SDL_GPURenderer *driverData,
  5095. SDL_Window *window,
  5096. SDL_GPUSwapchainComposition swapchainComposition)
  5097. {
  5098. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  5099. // FIXME: HDR support would be nice to add, but it seems complicated...
  5100. return swapchainComposition == SDL_GPU_SWAPCHAINCOMPOSITION_SDR ||
  5101. swapchainComposition == SDL_GPU_SWAPCHAINCOMPOSITION_SDR_LINEAR;
  5102. #else
  5103. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  5104. DXGI_FORMAT format;
  5105. D3D12_FEATURE_DATA_FORMAT_SUPPORT formatSupport;
  5106. Uint32 colorSpaceSupport;
  5107. HRESULT res;
  5108. format = SwapchainCompositionToTextureFormat[swapchainComposition];
  5109. formatSupport.Format = format;
  5110. res = ID3D12Device_CheckFeatureSupport(
  5111. renderer->device,
  5112. D3D12_FEATURE_FORMAT_SUPPORT,
  5113. &formatSupport,
  5114. sizeof(formatSupport));
  5115. if (FAILED(res)) {
  5116. // Format is apparently unknown
  5117. return false;
  5118. }
  5119. if (!(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_DISPLAY)) {
  5120. return false;
  5121. }
  5122. D3D12WindowData *windowData = D3D12_INTERNAL_FetchWindowData(window);
  5123. if (windowData == NULL) {
  5124. SET_STRING_ERROR_AND_RETURN("Must claim window before querying swapchain composition support!", false)
  5125. }
  5126. // Check the color space support if necessary
  5127. if (swapchainComposition != SDL_GPU_SWAPCHAINCOMPOSITION_SDR) {
  5128. IDXGISwapChain3_CheckColorSpaceSupport(
  5129. windowData->swapchain,
  5130. SwapchainCompositionToColorSpace[swapchainComposition],
  5131. &colorSpaceSupport);
  5132. if (!(colorSpaceSupport & DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT)) {
  5133. return false;
  5134. }
  5135. }
  5136. #endif
  5137. return true;
  5138. }
  5139. static bool D3D12_SupportsPresentMode(
  5140. SDL_GPURenderer *driverData,
  5141. SDL_Window *window,
  5142. SDL_GPUPresentMode presentMode)
  5143. {
  5144. (void)driverData;
  5145. (void)window;
  5146. switch (presentMode) {
  5147. case SDL_GPU_PRESENTMODE_IMMEDIATE:
  5148. case SDL_GPU_PRESENTMODE_VSYNC:
  5149. return true;
  5150. case SDL_GPU_PRESENTMODE_MAILBOX:
  5151. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  5152. return false;
  5153. #else
  5154. return true;
  5155. #endif
  5156. default:
  5157. SDL_assert(!"Unrecognized present mode");
  5158. return false;
  5159. }
  5160. }
  5161. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  5162. static bool D3D12_INTERNAL_CreateSwapchain(
  5163. D3D12Renderer *renderer,
  5164. D3D12WindowData *windowData,
  5165. SDL_GPUSwapchainComposition swapchain_composition,
  5166. SDL_GPUPresentMode present_mode)
  5167. {
  5168. int width, height;
  5169. SDL_GPUTextureCreateInfo createInfo;
  5170. D3D12Texture *texture;
  5171. // Get the swapchain size
  5172. SDL_SyncWindow(windowData->window);
  5173. SDL_GetWindowSizeInPixels(windowData->window, &width, &height);
  5174. // Create the swapchain textures
  5175. SDL_zero(createInfo);
  5176. createInfo.type = SDL_GPU_TEXTURETYPE_2D;
  5177. createInfo.width = width;
  5178. createInfo.height = height;
  5179. createInfo.format = SwapchainCompositionToSDLTextureFormat[swapchain_composition];
  5180. createInfo.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
  5181. createInfo.layer_count_or_depth = 1;
  5182. createInfo.num_levels = 1;
  5183. for (Uint32 i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  5184. texture = D3D12_INTERNAL_CreateTexture(renderer, &createInfo, true);
  5185. texture->container = &windowData->textureContainers[i];
  5186. windowData->textureContainers[i].activeTexture = texture;
  5187. windowData->textureContainers[i].canBeCycled = false;
  5188. windowData->textureContainers[i].header.info = createInfo;
  5189. windowData->textureContainers[i].textureCapacity = 1;
  5190. windowData->textureContainers[i].textureCount = 1;
  5191. windowData->textureContainers[i].textures = &windowData->textureContainers[i].activeTexture;
  5192. }
  5193. // Initialize the swapchain data
  5194. windowData->present_mode = present_mode;
  5195. windowData->swapchainComposition = swapchain_composition;
  5196. windowData->swapchainColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
  5197. windowData->frameCounter = 0;
  5198. // Precache blit pipelines for the swapchain format
  5199. for (Uint32 i = 0; i < 5; i += 1) {
  5200. SDL_GPU_FetchBlitPipeline(
  5201. renderer->sdlGPUDevice,
  5202. (SDL_GPUTextureType)i,
  5203. createInfo.format,
  5204. renderer->blitVertexShader,
  5205. renderer->blitFrom2DShader,
  5206. renderer->blitFrom2DArrayShader,
  5207. renderer->blitFrom3DShader,
  5208. renderer->blitFromCubeShader,
  5209. renderer->blitFromCubeArrayShader,
  5210. &renderer->blitPipelines,
  5211. &renderer->blitPipelineCount,
  5212. &renderer->blitPipelineCapacity);
  5213. }
  5214. return true;
  5215. }
  5216. static void D3D12_INTERNAL_DestroySwapchain(
  5217. D3D12Renderer *renderer,
  5218. D3D12WindowData *windowData)
  5219. {
  5220. renderer->commandQueue->PresentX(0, NULL, NULL);
  5221. for (Uint32 i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  5222. D3D12_INTERNAL_DestroyTexture(
  5223. renderer,
  5224. windowData->textureContainers[i].activeTexture);
  5225. }
  5226. }
  5227. static bool D3D12_INTERNAL_ResizeSwapchain(
  5228. D3D12Renderer *renderer,
  5229. D3D12WindowData *windowData)
  5230. {
  5231. // Wait so we don't release in-flight views
  5232. D3D12_Wait((SDL_GPURenderer *)renderer);
  5233. // Present a black screen
  5234. renderer->commandQueue->PresentX(0, NULL, NULL);
  5235. // Clean up the previous swapchain textures
  5236. for (Uint32 i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  5237. D3D12_INTERNAL_DestroyTexture(
  5238. renderer,
  5239. windowData->textureContainers[i].activeTexture);
  5240. }
  5241. // Create a new swapchain
  5242. D3D12_INTERNAL_CreateSwapchain(
  5243. renderer,
  5244. windowData,
  5245. windowData->swapchainComposition,
  5246. windowData->present_mode);
  5247. windowData->needsSwapchainRecreate = false;
  5248. return true;
  5249. }
  5250. #else
  5251. static bool D3D12_INTERNAL_InitializeSwapchainTexture(
  5252. D3D12Renderer *renderer,
  5253. IDXGISwapChain3 *swapchain,
  5254. SDL_GPUSwapchainComposition composition,
  5255. Uint32 index,
  5256. D3D12TextureContainer *pTextureContainer)
  5257. {
  5258. D3D12Texture *pTexture;
  5259. ID3D12Resource *swapchainTexture;
  5260. D3D12_RESOURCE_DESC textureDesc;
  5261. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
  5262. D3D12_RENDER_TARGET_VIEW_DESC rtvDesc;
  5263. DXGI_FORMAT swapchainFormat = SwapchainCompositionToTextureFormat[composition];
  5264. HRESULT res;
  5265. res = IDXGISwapChain_GetBuffer(
  5266. swapchain,
  5267. index,
  5268. D3D_GUID(D3D_IID_ID3D12Resource),
  5269. (void **)&swapchainTexture);
  5270. CHECK_D3D12_ERROR_AND_RETURN("Could not get buffer from swapchain!", false);
  5271. pTexture = (D3D12Texture *)SDL_calloc(1, sizeof(D3D12Texture));
  5272. if (!pTexture) {
  5273. ID3D12Resource_Release(swapchainTexture);
  5274. return false;
  5275. }
  5276. pTexture->resource = NULL; // This will be set in AcquireSwapchainTexture
  5277. SDL_SetAtomicInt(&pTexture->referenceCount, 0);
  5278. pTexture->subresourceCount = 1;
  5279. pTexture->subresources = (D3D12TextureSubresource *)SDL_calloc(1, sizeof(D3D12TextureSubresource));
  5280. if (!pTexture->subresources) {
  5281. SDL_free(pTexture);
  5282. ID3D12Resource_Release(swapchainTexture);
  5283. return false;
  5284. }
  5285. pTexture->subresources[0].rtvHandles = SDL_calloc(1, sizeof(D3D12CPUDescriptor));
  5286. pTexture->subresources[0].uavHandle.heap = NULL;
  5287. pTexture->subresources[0].dsvHandle.heap = NULL;
  5288. pTexture->subresources[0].parent = pTexture;
  5289. pTexture->subresources[0].index = 0;
  5290. pTexture->subresources[0].layer = 0;
  5291. pTexture->subresources[0].depth = 1;
  5292. pTexture->subresources[0].level = 0;
  5293. ID3D12Resource_GetDesc(swapchainTexture, &textureDesc);
  5294. pTextureContainer->header.info.width = (Uint32)textureDesc.Width;
  5295. pTextureContainer->header.info.height = (Uint32)textureDesc.Height;
  5296. pTextureContainer->header.info.layer_count_or_depth = 1;
  5297. pTextureContainer->header.info.num_levels = 1;
  5298. pTextureContainer->header.info.type = SDL_GPU_TEXTURETYPE_2D;
  5299. pTextureContainer->header.info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
  5300. pTextureContainer->header.info.sample_count = SDL_GPU_SAMPLECOUNT_1;
  5301. pTextureContainer->header.info.format = SwapchainCompositionToSDLTextureFormat[composition];
  5302. pTextureContainer->debugName = NULL;
  5303. pTextureContainer->textures = (D3D12Texture **)SDL_calloc(1, sizeof(D3D12Texture *));
  5304. if (!pTextureContainer->textures) {
  5305. SDL_free(pTexture->subresources);
  5306. SDL_free(pTexture);
  5307. ID3D12Resource_Release(swapchainTexture);
  5308. return false;
  5309. }
  5310. pTextureContainer->textureCapacity = 1;
  5311. pTextureContainer->textureCount = 1;
  5312. pTextureContainer->textures[0] = pTexture;
  5313. pTextureContainer->activeTexture = pTexture;
  5314. pTextureContainer->canBeCycled = false;
  5315. pTexture->container = pTextureContainer;
  5316. pTexture->containerIndex = 0;
  5317. // Create the SRV for the swapchain
  5318. D3D12_INTERNAL_AssignCpuDescriptorHandle(
  5319. renderer,
  5320. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  5321. &pTexture->srvHandle);
  5322. srvDesc.Format = SwapchainCompositionToTextureFormat[composition];
  5323. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  5324. srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  5325. srvDesc.Texture2D.MipLevels = 1;
  5326. srvDesc.Texture2D.MostDetailedMip = 0;
  5327. srvDesc.Texture2D.ResourceMinLODClamp = 0;
  5328. srvDesc.Texture2D.PlaneSlice = 0;
  5329. ID3D12Device_CreateShaderResourceView(
  5330. renderer->device,
  5331. swapchainTexture,
  5332. &srvDesc,
  5333. pTexture->srvHandle.cpuHandle);
  5334. // Create the RTV for the swapchain
  5335. D3D12_INTERNAL_AssignCpuDescriptorHandle(
  5336. renderer,
  5337. D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  5338. &pTexture->subresources[0].rtvHandles[0]);
  5339. rtvDesc.Format = (composition == SDL_GPU_SWAPCHAINCOMPOSITION_SDR_LINEAR) ? DXGI_FORMAT_B8G8R8A8_UNORM_SRGB : swapchainFormat;
  5340. rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
  5341. rtvDesc.Texture2D.MipSlice = 0;
  5342. rtvDesc.Texture2D.PlaneSlice = 0;
  5343. ID3D12Device_CreateRenderTargetView(
  5344. renderer->device,
  5345. swapchainTexture,
  5346. &rtvDesc,
  5347. pTexture->subresources[0].rtvHandles[0].cpuHandle);
  5348. ID3D12Resource_Release(swapchainTexture);
  5349. return true;
  5350. }
  5351. static bool D3D12_INTERNAL_ResizeSwapchain(
  5352. D3D12Renderer *renderer,
  5353. D3D12WindowData *windowData)
  5354. {
  5355. // Wait so we don't release in-flight views
  5356. D3D12_Wait((SDL_GPURenderer *)renderer);
  5357. // Release views and clean up
  5358. for (Uint32 i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  5359. D3D12_INTERNAL_ReleaseCpuDescriptorHandle(
  5360. renderer,
  5361. &windowData->textureContainers[i].activeTexture->srvHandle);
  5362. D3D12_INTERNAL_ReleaseCpuDescriptorHandle(
  5363. renderer,
  5364. &windowData->textureContainers[i].activeTexture->subresources[0].rtvHandles[0]);
  5365. SDL_free(windowData->textureContainers[i].activeTexture->subresources[0].rtvHandles);
  5366. SDL_free(windowData->textureContainers[i].activeTexture->subresources);
  5367. SDL_free(windowData->textureContainers[i].activeTexture);
  5368. SDL_free(windowData->textureContainers[i].textures);
  5369. }
  5370. int w, h;
  5371. SDL_SyncWindow(windowData->window);
  5372. SDL_GetWindowSizeInPixels(
  5373. windowData->window,
  5374. &w,
  5375. &h);
  5376. // Resize the swapchain
  5377. HRESULT res = IDXGISwapChain_ResizeBuffers(
  5378. windowData->swapchain,
  5379. 0, // Keep buffer count the same
  5380. w,
  5381. h,
  5382. DXGI_FORMAT_UNKNOWN, // Keep the old format
  5383. renderer->supportsTearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0);
  5384. CHECK_D3D12_ERROR_AND_RETURN("Could not resize swapchain buffers", false)
  5385. // Create texture object for the swapchain
  5386. for (Uint32 i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  5387. if (!D3D12_INTERNAL_InitializeSwapchainTexture(
  5388. renderer,
  5389. windowData->swapchain,
  5390. windowData->swapchainComposition,
  5391. i,
  5392. &windowData->textureContainers[i])) {
  5393. return false;
  5394. }
  5395. }
  5396. windowData->needsSwapchainRecreate = false;
  5397. return true;
  5398. }
  5399. static void D3D12_INTERNAL_DestroySwapchain(
  5400. D3D12Renderer *renderer,
  5401. D3D12WindowData *windowData)
  5402. {
  5403. // Release views and clean up
  5404. for (Uint32 i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  5405. D3D12_INTERNAL_ReleaseCpuDescriptorHandle(
  5406. renderer,
  5407. &windowData->textureContainers[i].activeTexture->srvHandle);
  5408. D3D12_INTERNAL_ReleaseCpuDescriptorHandle(
  5409. renderer,
  5410. &windowData->textureContainers[i].activeTexture->subresources[0].rtvHandles[0]);
  5411. SDL_free(windowData->textureContainers[i].activeTexture->subresources[0].rtvHandles);
  5412. SDL_free(windowData->textureContainers[i].activeTexture->subresources);
  5413. SDL_free(windowData->textureContainers[i].activeTexture);
  5414. SDL_free(windowData->textureContainers[i].textures);
  5415. }
  5416. IDXGISwapChain_Release(windowData->swapchain);
  5417. windowData->swapchain = NULL;
  5418. }
  5419. static bool D3D12_INTERNAL_CreateSwapchain(
  5420. D3D12Renderer *renderer,
  5421. D3D12WindowData *windowData,
  5422. SDL_GPUSwapchainComposition swapchainComposition,
  5423. SDL_GPUPresentMode presentMode)
  5424. {
  5425. HWND dxgiHandle;
  5426. DXGI_SWAP_CHAIN_DESC1 swapchainDesc;
  5427. DXGI_SWAP_CHAIN_FULLSCREEN_DESC fullscreenDesc;
  5428. DXGI_FORMAT swapchainFormat;
  5429. IDXGIFactory1 *pParent;
  5430. IDXGISwapChain1 *swapchain;
  5431. IDXGISwapChain3 *swapchain3;
  5432. HRESULT res;
  5433. // Get the DXGI handle
  5434. #ifdef _WIN32
  5435. dxgiHandle = (HWND)SDL_GetPointerProperty(SDL_GetWindowProperties(windowData->window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, NULL);
  5436. #else
  5437. dxgiHandle = (HWND)windowData->window;
  5438. #endif
  5439. swapchainFormat = SwapchainCompositionToTextureFormat[swapchainComposition];
  5440. // Initialize the swapchain buffer descriptor
  5441. swapchainDesc.Width = 0;
  5442. swapchainDesc.Height = 0;
  5443. swapchainDesc.Format = swapchainFormat;
  5444. swapchainDesc.SampleDesc.Count = 1;
  5445. swapchainDesc.SampleDesc.Quality = 0;
  5446. swapchainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  5447. swapchainDesc.BufferCount = MAX_FRAMES_IN_FLIGHT;
  5448. swapchainDesc.Scaling = DXGI_SCALING_STRETCH;
  5449. swapchainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
  5450. swapchainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
  5451. swapchainDesc.Flags = 0;
  5452. swapchainDesc.Stereo = 0;
  5453. // Initialize the fullscreen descriptor (if needed)
  5454. fullscreenDesc.RefreshRate.Numerator = 0;
  5455. fullscreenDesc.RefreshRate.Denominator = 0;
  5456. fullscreenDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
  5457. fullscreenDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
  5458. fullscreenDesc.Windowed = true;
  5459. if (renderer->supportsTearing) {
  5460. swapchainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
  5461. } else {
  5462. swapchainDesc.Flags = 0;
  5463. }
  5464. if (!IsWindow(dxgiHandle)) {
  5465. return false;
  5466. }
  5467. // Create the swapchain!
  5468. res = IDXGIFactory4_CreateSwapChainForHwnd(
  5469. renderer->factory,
  5470. (IUnknown *)renderer->commandQueue,
  5471. dxgiHandle,
  5472. &swapchainDesc,
  5473. &fullscreenDesc,
  5474. NULL,
  5475. &swapchain);
  5476. CHECK_D3D12_ERROR_AND_RETURN("Could not create swapchain", false);
  5477. res = IDXGISwapChain1_QueryInterface(
  5478. swapchain,
  5479. D3D_GUID(D3D_IID_IDXGISwapChain3),
  5480. (void **)&swapchain3);
  5481. IDXGISwapChain1_Release(swapchain);
  5482. CHECK_D3D12_ERROR_AND_RETURN("Could not create IDXGISwapChain3", false);
  5483. if (swapchainComposition != SDL_GPU_SWAPCHAINCOMPOSITION_SDR) {
  5484. // Support already verified if we hit this block
  5485. IDXGISwapChain3_SetColorSpace1(
  5486. swapchain3,
  5487. SwapchainCompositionToColorSpace[swapchainComposition]);
  5488. }
  5489. /*
  5490. * The swapchain's parent is a separate factory from the factory that
  5491. * we used to create the swapchain, and only that parent can be used to
  5492. * set the window association. Trying to set an association on our factory
  5493. * will silently fail and doesn't even verify arguments or return errors.
  5494. * See https://gamedev.net/forums/topic/634235-dxgidisabling-altenter/4999955/
  5495. */
  5496. res = IDXGISwapChain3_GetParent(
  5497. swapchain3,
  5498. D3D_GUID(D3D_IID_IDXGIFactory1),
  5499. (void **)&pParent);
  5500. if (FAILED(res)) {
  5501. SDL_LogWarn(
  5502. SDL_LOG_CATEGORY_APPLICATION,
  5503. "Could not get swapchain parent! Error Code: " HRESULT_FMT,
  5504. res);
  5505. } else {
  5506. // Disable DXGI window crap
  5507. res = IDXGIFactory1_MakeWindowAssociation(
  5508. pParent,
  5509. dxgiHandle,
  5510. DXGI_MWA_NO_WINDOW_CHANGES);
  5511. if (FAILED(res)) {
  5512. SDL_LogWarn(
  5513. SDL_LOG_CATEGORY_APPLICATION,
  5514. "MakeWindowAssociation failed! Error Code: " HRESULT_FMT,
  5515. res);
  5516. }
  5517. // We're done with the parent now
  5518. IDXGIFactory1_Release(pParent);
  5519. }
  5520. // Initialize the swapchain data
  5521. windowData->swapchain = swapchain3;
  5522. windowData->present_mode = presentMode;
  5523. windowData->swapchainComposition = swapchainComposition;
  5524. windowData->swapchainColorSpace = SwapchainCompositionToColorSpace[swapchainComposition];
  5525. windowData->frameCounter = 0;
  5526. // Precache blit pipelines for the swapchain format
  5527. for (Uint32 i = 0; i < 5; i += 1) {
  5528. SDL_GPU_FetchBlitPipeline(
  5529. renderer->sdlGPUDevice,
  5530. (SDL_GPUTextureType)i,
  5531. SwapchainCompositionToSDLTextureFormat[swapchainComposition],
  5532. renderer->blitVertexShader,
  5533. renderer->blitFrom2DShader,
  5534. renderer->blitFrom2DArrayShader,
  5535. renderer->blitFrom3DShader,
  5536. renderer->blitFromCubeShader,
  5537. renderer->blitFromCubeArrayShader,
  5538. &renderer->blitPipelines,
  5539. &renderer->blitPipelineCount,
  5540. &renderer->blitPipelineCapacity);
  5541. }
  5542. /* If a you are using a FLIP model format you can't create the swapchain as DXGI_FORMAT_B8G8R8A8_UNORM_SRGB.
  5543. * 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
  5544. */
  5545. for (Uint32 i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  5546. if (!D3D12_INTERNAL_InitializeSwapchainTexture(
  5547. renderer,
  5548. swapchain3,
  5549. swapchainComposition,
  5550. i,
  5551. &windowData->textureContainers[i])) {
  5552. IDXGISwapChain3_Release(swapchain3);
  5553. return false;
  5554. }
  5555. }
  5556. return true;
  5557. }
  5558. #endif
  5559. static bool D3D12_ClaimWindow(
  5560. SDL_GPURenderer *driverData,
  5561. SDL_Window *window)
  5562. {
  5563. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  5564. D3D12WindowData *windowData = D3D12_INTERNAL_FetchWindowData(window);
  5565. if (windowData == NULL) {
  5566. windowData = (D3D12WindowData *)SDL_calloc(1, sizeof(D3D12WindowData));
  5567. if (!windowData) {
  5568. return false;
  5569. }
  5570. windowData->window = window;
  5571. if (D3D12_INTERNAL_CreateSwapchain(renderer, windowData, SDL_GPU_SWAPCHAINCOMPOSITION_SDR, SDL_GPU_PRESENTMODE_VSYNC)) {
  5572. SDL_SetPointerProperty(SDL_GetWindowProperties(window), WINDOW_PROPERTY_DATA, windowData);
  5573. SDL_LockMutex(renderer->windowLock);
  5574. if (renderer->claimedWindowCount >= renderer->claimedWindowCapacity) {
  5575. renderer->claimedWindowCapacity *= 2;
  5576. renderer->claimedWindows = (D3D12WindowData **)SDL_realloc(
  5577. renderer->claimedWindows,
  5578. renderer->claimedWindowCapacity * sizeof(D3D12WindowData *));
  5579. }
  5580. renderer->claimedWindows[renderer->claimedWindowCount] = windowData;
  5581. renderer->claimedWindowCount += 1;
  5582. SDL_UnlockMutex(renderer->windowLock);
  5583. SDL_AddEventWatch(D3D12_INTERNAL_OnWindowResize, window);
  5584. return true;
  5585. } else {
  5586. SDL_free(windowData);
  5587. SET_STRING_ERROR_AND_RETURN("Could not create swapchain, failed to claim window!", false)
  5588. }
  5589. } else {
  5590. SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Window already claimed!");
  5591. return false;
  5592. }
  5593. }
  5594. static void D3D12_ReleaseWindow(
  5595. SDL_GPURenderer *driverData,
  5596. SDL_Window *window)
  5597. {
  5598. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  5599. D3D12WindowData *windowData = D3D12_INTERNAL_FetchWindowData(window);
  5600. if (windowData == NULL) {
  5601. SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Window already unclaimed!");
  5602. return;
  5603. }
  5604. D3D12_Wait(driverData);
  5605. for (Uint32 i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  5606. if (windowData->inFlightFences[i] != NULL) {
  5607. D3D12_ReleaseFence(
  5608. driverData,
  5609. windowData->inFlightFences[i]);
  5610. windowData->inFlightFences[i] = NULL;
  5611. }
  5612. }
  5613. D3D12_INTERNAL_DestroySwapchain(renderer, windowData);
  5614. SDL_LockMutex(renderer->windowLock);
  5615. for (Uint32 i = 0; i < renderer->claimedWindowCount; i += 1) {
  5616. if (renderer->claimedWindows[i]->window == window) {
  5617. renderer->claimedWindows[i] = renderer->claimedWindows[renderer->claimedWindowCount - 1];
  5618. renderer->claimedWindowCount -= 1;
  5619. break;
  5620. }
  5621. }
  5622. SDL_UnlockMutex(renderer->windowLock);
  5623. SDL_free(windowData);
  5624. SDL_ClearProperty(SDL_GetWindowProperties(window), WINDOW_PROPERTY_DATA);
  5625. SDL_RemoveEventWatch(D3D12_INTERNAL_OnWindowResize, window);
  5626. }
  5627. static bool D3D12_SetSwapchainParameters(
  5628. SDL_GPURenderer *driverData,
  5629. SDL_Window *window,
  5630. SDL_GPUSwapchainComposition swapchainComposition,
  5631. SDL_GPUPresentMode presentMode)
  5632. {
  5633. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  5634. D3D12WindowData *windowData = D3D12_INTERNAL_FetchWindowData(window);
  5635. if (windowData == NULL) {
  5636. SET_STRING_ERROR_AND_RETURN("Cannot set swapchain parameters on unclaimed window!", false)
  5637. }
  5638. if (!D3D12_SupportsSwapchainComposition(driverData, window, swapchainComposition)) {
  5639. SET_STRING_ERROR_AND_RETURN("Swapchain composition not supported!", false)
  5640. }
  5641. if (!D3D12_SupportsPresentMode(driverData, window, presentMode)) {
  5642. SET_STRING_ERROR_AND_RETURN("Present mode not supported!", false)
  5643. }
  5644. if (
  5645. swapchainComposition != windowData->swapchainComposition ||
  5646. presentMode != windowData->present_mode) {
  5647. D3D12_Wait(driverData);
  5648. // Recreate the swapchain
  5649. D3D12_INTERNAL_DestroySwapchain(
  5650. renderer,
  5651. windowData);
  5652. return D3D12_INTERNAL_CreateSwapchain(
  5653. renderer,
  5654. windowData,
  5655. swapchainComposition,
  5656. presentMode);
  5657. }
  5658. return true;
  5659. }
  5660. static SDL_GPUTextureFormat D3D12_GetSwapchainTextureFormat(
  5661. SDL_GPURenderer *driverData,
  5662. SDL_Window *window)
  5663. {
  5664. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  5665. D3D12WindowData *windowData = D3D12_INTERNAL_FetchWindowData(window);
  5666. if (windowData == NULL) {
  5667. SET_STRING_ERROR_AND_RETURN("Cannot get swapchain format, window has not been claimed!", SDL_GPU_TEXTUREFORMAT_INVALID)
  5668. }
  5669. return windowData->textureContainers[windowData->frameCounter].header.info.format;
  5670. }
  5671. static D3D12Fence *D3D12_INTERNAL_AcquireFence(
  5672. D3D12Renderer *renderer)
  5673. {
  5674. D3D12Fence *fence;
  5675. ID3D12Fence *handle;
  5676. HRESULT res;
  5677. SDL_LockMutex(renderer->fenceLock);
  5678. if (renderer->availableFenceCount == 0) {
  5679. res = ID3D12Device_CreateFence(
  5680. renderer->device,
  5681. D3D12_FENCE_UNSIGNALED_VALUE,
  5682. D3D12_FENCE_FLAG_NONE,
  5683. D3D_GUID(D3D_IID_ID3D12Fence),
  5684. (void **)&handle);
  5685. if (FAILED(res)) {
  5686. D3D12_INTERNAL_SetError(renderer, "Failed to create fence!", res);
  5687. SDL_UnlockMutex(renderer->fenceLock);
  5688. return NULL;
  5689. }
  5690. fence = (D3D12Fence *)SDL_calloc(1, sizeof(D3D12Fence));
  5691. if (!fence) {
  5692. ID3D12Fence_Release(handle);
  5693. SDL_UnlockMutex(renderer->fenceLock);
  5694. return NULL;
  5695. }
  5696. fence->handle = handle;
  5697. fence->event = CreateEventEx(NULL, 0, 0, EVENT_ALL_ACCESS);
  5698. SDL_SetAtomicInt(&fence->referenceCount, 0);
  5699. } else {
  5700. fence = renderer->availableFences[renderer->availableFenceCount - 1];
  5701. renderer->availableFenceCount -= 1;
  5702. ID3D12Fence_Signal(fence->handle, D3D12_FENCE_UNSIGNALED_VALUE);
  5703. }
  5704. SDL_UnlockMutex(renderer->fenceLock);
  5705. (void)SDL_AtomicIncRef(&fence->referenceCount);
  5706. return fence;
  5707. }
  5708. static bool D3D12_INTERNAL_AllocateCommandBuffer(
  5709. D3D12Renderer *renderer)
  5710. {
  5711. D3D12CommandBuffer *commandBuffer;
  5712. HRESULT res;
  5713. ID3D12CommandAllocator *commandAllocator;
  5714. ID3D12GraphicsCommandList *commandList;
  5715. commandBuffer = (D3D12CommandBuffer *)SDL_calloc(1, sizeof(D3D12CommandBuffer));
  5716. if (!commandBuffer) {
  5717. SET_STRING_ERROR_AND_RETURN("Failed to create ID3D12CommandList. Out of Memory", false)
  5718. }
  5719. res = ID3D12Device_CreateCommandAllocator(
  5720. renderer->device,
  5721. D3D12_COMMAND_LIST_TYPE_DIRECT,
  5722. D3D_GUID(D3D_IID_ID3D12CommandAllocator),
  5723. (void **)&commandAllocator);
  5724. if (FAILED(res)) {
  5725. D3D12_INTERNAL_SetError(renderer, "Failed to create ID3D12CommandAllocator", res);
  5726. D3D12_INTERNAL_DestroyCommandBuffer(commandBuffer);
  5727. return false;
  5728. }
  5729. commandBuffer->commandAllocator = commandAllocator;
  5730. res = ID3D12Device_CreateCommandList(
  5731. renderer->device,
  5732. 0,
  5733. D3D12_COMMAND_LIST_TYPE_DIRECT,
  5734. commandAllocator,
  5735. NULL,
  5736. D3D_GUID(D3D_IID_ID3D12GraphicsCommandList),
  5737. (void **)&commandList);
  5738. if (FAILED(res)) {
  5739. D3D12_INTERNAL_SetError(renderer, "Failed to create ID3D12CommandList", res);
  5740. D3D12_INTERNAL_DestroyCommandBuffer(commandBuffer);
  5741. return false;
  5742. }
  5743. commandBuffer->graphicsCommandList = commandList;
  5744. commandBuffer->renderer = renderer;
  5745. commandBuffer->inFlightFence = NULL;
  5746. // Window handling
  5747. commandBuffer->presentDataCapacity = 1;
  5748. commandBuffer->presentDataCount = 0;
  5749. commandBuffer->presentDatas = (D3D12PresentData *)SDL_calloc(
  5750. commandBuffer->presentDataCapacity, sizeof(D3D12PresentData));
  5751. // Resource tracking
  5752. commandBuffer->usedTextureCapacity = 4;
  5753. commandBuffer->usedTextureCount = 0;
  5754. commandBuffer->usedTextures = (D3D12Texture **)SDL_calloc(
  5755. commandBuffer->usedTextureCapacity, sizeof(D3D12Texture *));
  5756. commandBuffer->usedBufferCapacity = 4;
  5757. commandBuffer->usedBufferCount = 0;
  5758. commandBuffer->usedBuffers = (D3D12Buffer **)SDL_calloc(
  5759. commandBuffer->usedBufferCapacity, sizeof(D3D12Buffer *));
  5760. commandBuffer->usedSamplerCapacity = 4;
  5761. commandBuffer->usedSamplerCount = 0;
  5762. commandBuffer->usedSamplers = (D3D12Sampler **)SDL_calloc(
  5763. commandBuffer->usedSamplerCapacity, sizeof(D3D12Sampler *));
  5764. commandBuffer->usedGraphicsPipelineCapacity = 4;
  5765. commandBuffer->usedGraphicsPipelineCount = 0;
  5766. commandBuffer->usedGraphicsPipelines = (D3D12GraphicsPipeline **)SDL_calloc(
  5767. commandBuffer->usedGraphicsPipelineCapacity, sizeof(D3D12GraphicsPipeline *));
  5768. commandBuffer->usedComputePipelineCapacity = 4;
  5769. commandBuffer->usedComputePipelineCount = 0;
  5770. commandBuffer->usedComputePipelines = (D3D12ComputePipeline **)SDL_calloc(
  5771. commandBuffer->usedComputePipelineCapacity, sizeof(D3D12ComputePipeline *));
  5772. commandBuffer->usedUniformBufferCapacity = 4;
  5773. commandBuffer->usedUniformBufferCount = 0;
  5774. commandBuffer->usedUniformBuffers = (D3D12UniformBuffer **)SDL_calloc(
  5775. commandBuffer->usedUniformBufferCapacity, sizeof(D3D12UniformBuffer *));
  5776. commandBuffer->textureDownloadCapacity = 4;
  5777. commandBuffer->textureDownloadCount = 0;
  5778. commandBuffer->textureDownloads = (D3D12TextureDownload **)SDL_calloc(
  5779. commandBuffer->textureDownloadCapacity, sizeof(D3D12TextureDownload *));
  5780. if (
  5781. (!commandBuffer->presentDatas) ||
  5782. (!commandBuffer->usedTextures) ||
  5783. (!commandBuffer->usedBuffers) ||
  5784. (!commandBuffer->usedSamplers) ||
  5785. (!commandBuffer->usedGraphicsPipelines) ||
  5786. (!commandBuffer->usedComputePipelines) ||
  5787. (!commandBuffer->usedUniformBuffers) ||
  5788. (!commandBuffer->textureDownloads)) {
  5789. D3D12_INTERNAL_DestroyCommandBuffer(commandBuffer);
  5790. SET_STRING_ERROR_AND_RETURN("Failed to create ID3D12CommandList. Out of Memory", false)
  5791. }
  5792. D3D12CommandBuffer **resizedAvailableCommandBuffers = (D3D12CommandBuffer **)SDL_realloc(
  5793. renderer->availableCommandBuffers,
  5794. sizeof(D3D12CommandBuffer *) * (renderer->availableCommandBufferCapacity + 1));
  5795. if (!resizedAvailableCommandBuffers) {
  5796. D3D12_INTERNAL_DestroyCommandBuffer(commandBuffer);
  5797. SET_STRING_ERROR_AND_RETURN("Failed to create ID3D12CommandList. Out of Memory", false)
  5798. }
  5799. // Add to inactive command buffer array
  5800. renderer->availableCommandBufferCapacity += 1;
  5801. renderer->availableCommandBuffers = resizedAvailableCommandBuffers;
  5802. renderer->availableCommandBuffers[renderer->availableCommandBufferCount] = commandBuffer;
  5803. renderer->availableCommandBufferCount += 1;
  5804. return true;
  5805. }
  5806. static D3D12CommandBuffer *D3D12_INTERNAL_AcquireCommandBufferFromPool(
  5807. D3D12Renderer *renderer)
  5808. {
  5809. D3D12CommandBuffer *commandBuffer;
  5810. if (renderer->availableCommandBufferCount == 0) {
  5811. if (!D3D12_INTERNAL_AllocateCommandBuffer(renderer)) {
  5812. return NULL;
  5813. }
  5814. }
  5815. commandBuffer = renderer->availableCommandBuffers[renderer->availableCommandBufferCount - 1];
  5816. renderer->availableCommandBufferCount -= 1;
  5817. return commandBuffer;
  5818. }
  5819. static SDL_GPUCommandBuffer *D3D12_AcquireCommandBuffer(
  5820. SDL_GPURenderer *driverData)
  5821. {
  5822. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  5823. D3D12CommandBuffer *commandBuffer;
  5824. ID3D12DescriptorHeap *heaps[2];
  5825. SDL_zeroa(heaps);
  5826. SDL_LockMutex(renderer->acquireCommandBufferLock);
  5827. commandBuffer = D3D12_INTERNAL_AcquireCommandBufferFromPool(renderer);
  5828. SDL_UnlockMutex(renderer->acquireCommandBufferLock);
  5829. if (commandBuffer == NULL) {
  5830. return NULL;
  5831. }
  5832. // Set the descriptor heaps!
  5833. commandBuffer->gpuDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV] =
  5834. D3D12_INTERNAL_AcquireDescriptorHeapFromPool(commandBuffer, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  5835. if (!commandBuffer->gpuDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV]) {
  5836. D3D12_INTERNAL_DestroyCommandBuffer(commandBuffer);
  5837. return NULL;
  5838. }
  5839. commandBuffer->gpuDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER] =
  5840. D3D12_INTERNAL_AcquireDescriptorHeapFromPool(commandBuffer, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
  5841. if (!commandBuffer->gpuDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER]) {
  5842. D3D12_INTERNAL_DestroyCommandBuffer(commandBuffer);
  5843. return NULL;
  5844. }
  5845. heaps[0] = commandBuffer->gpuDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV]->handle;
  5846. heaps[1] = commandBuffer->gpuDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER]->handle;
  5847. ID3D12GraphicsCommandList_SetDescriptorHeaps(
  5848. commandBuffer->graphicsCommandList,
  5849. 2,
  5850. heaps);
  5851. // Set the bind state
  5852. commandBuffer->currentGraphicsPipeline = NULL;
  5853. SDL_zeroa(commandBuffer->colorTargetSubresources);
  5854. SDL_zeroa(commandBuffer->colorResolveSubresources);
  5855. commandBuffer->depthStencilTextureSubresource = NULL;
  5856. SDL_zeroa(commandBuffer->vertexBuffers);
  5857. SDL_zeroa(commandBuffer->vertexBufferOffsets);
  5858. commandBuffer->vertexBufferCount = 0;
  5859. SDL_zeroa(commandBuffer->vertexSamplerTextures);
  5860. SDL_zeroa(commandBuffer->vertexSamplers);
  5861. SDL_zeroa(commandBuffer->vertexStorageTextures);
  5862. SDL_zeroa(commandBuffer->vertexStorageBuffers);
  5863. SDL_zeroa(commandBuffer->vertexUniformBuffers);
  5864. SDL_zeroa(commandBuffer->fragmentSamplerTextures);
  5865. SDL_zeroa(commandBuffer->fragmentSamplers);
  5866. SDL_zeroa(commandBuffer->fragmentStorageTextures);
  5867. SDL_zeroa(commandBuffer->fragmentStorageBuffers);
  5868. SDL_zeroa(commandBuffer->fragmentUniformBuffers);
  5869. SDL_zeroa(commandBuffer->computeSamplerTextures);
  5870. SDL_zeroa(commandBuffer->computeSamplers);
  5871. SDL_zeroa(commandBuffer->computeReadOnlyStorageTextures);
  5872. SDL_zeroa(commandBuffer->computeReadOnlyStorageBuffers);
  5873. SDL_zeroa(commandBuffer->computeReadWriteStorageTextureSubresources);
  5874. SDL_zeroa(commandBuffer->computeReadWriteStorageBuffers);
  5875. SDL_zeroa(commandBuffer->computeUniformBuffers);
  5876. commandBuffer->autoReleaseFence = true;
  5877. return (SDL_GPUCommandBuffer *)commandBuffer;
  5878. }
  5879. static bool D3D12_AcquireSwapchainTexture(
  5880. SDL_GPUCommandBuffer *commandBuffer,
  5881. SDL_Window *window,
  5882. SDL_GPUTexture **swapchainTexture)
  5883. {
  5884. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  5885. D3D12Renderer *renderer = d3d12CommandBuffer->renderer;
  5886. D3D12WindowData *windowData;
  5887. Uint32 swapchainIndex;
  5888. HRESULT res;
  5889. *swapchainTexture = NULL;
  5890. windowData = D3D12_INTERNAL_FetchWindowData(window);
  5891. if (windowData == NULL) {
  5892. SET_STRING_ERROR_AND_RETURN("Cannot acquire swapchain texture from an unclaimed window!", false)
  5893. }
  5894. if (windowData->needsSwapchainRecreate) {
  5895. if (!D3D12_INTERNAL_ResizeSwapchain(renderer, windowData)) {
  5896. return false;
  5897. }
  5898. }
  5899. if (windowData->inFlightFences[windowData->frameCounter] != NULL) {
  5900. if (windowData->present_mode == SDL_GPU_PRESENTMODE_VSYNC) {
  5901. // In VSYNC mode, block until the least recent presented frame is done
  5902. if (!D3D12_WaitForFences(
  5903. (SDL_GPURenderer *)renderer,
  5904. true,
  5905. &windowData->inFlightFences[windowData->frameCounter],
  5906. 1)) {
  5907. return false;
  5908. }
  5909. } else {
  5910. if (!D3D12_QueryFence(
  5911. (SDL_GPURenderer *)renderer,
  5912. windowData->inFlightFences[windowData->frameCounter])) {
  5913. /*
  5914. * In MAILBOX or IMMEDIATE mode, if the least recent fence is not signaled,
  5915. * return true to indicate that there is no error but rendering should be skipped
  5916. */
  5917. return true;
  5918. }
  5919. }
  5920. D3D12_ReleaseFence(
  5921. (SDL_GPURenderer *)renderer,
  5922. windowData->inFlightFences[windowData->frameCounter]);
  5923. windowData->inFlightFences[windowData->frameCounter] = NULL;
  5924. }
  5925. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  5926. // FIXME: Should this happen before the inFlightFences stuff above?
  5927. windowData->frameToken = D3D12XBOX_FRAME_PIPELINE_TOKEN_NULL;
  5928. renderer->device->WaitFrameEventX(D3D12XBOX_FRAME_EVENT_ORIGIN, INFINITE, NULL, D3D12XBOX_WAIT_FRAME_EVENT_FLAG_NONE, &windowData->frameToken);
  5929. swapchainIndex = windowData->frameCounter;
  5930. #else
  5931. swapchainIndex = IDXGISwapChain3_GetCurrentBackBufferIndex(windowData->swapchain);
  5932. // Set the handle on the windowData texture data.
  5933. res = IDXGISwapChain_GetBuffer(
  5934. windowData->swapchain,
  5935. swapchainIndex,
  5936. D3D_GUID(D3D_IID_ID3D12Resource),
  5937. (void **)&windowData->textureContainers[swapchainIndex].activeTexture->resource);
  5938. CHECK_D3D12_ERROR_AND_RETURN("Could not acquire swapchain!", false);
  5939. #endif
  5940. // Set up presentation
  5941. if (d3d12CommandBuffer->presentDataCount == d3d12CommandBuffer->presentDataCapacity) {
  5942. d3d12CommandBuffer->presentDataCapacity += 1;
  5943. d3d12CommandBuffer->presentDatas = (D3D12PresentData *)SDL_realloc(
  5944. d3d12CommandBuffer->presentDatas,
  5945. d3d12CommandBuffer->presentDataCapacity * sizeof(D3D12PresentData));
  5946. }
  5947. d3d12CommandBuffer->presentDatas[d3d12CommandBuffer->presentDataCount].windowData = windowData;
  5948. d3d12CommandBuffer->presentDatas[d3d12CommandBuffer->presentDataCount].swapchainImageIndex = swapchainIndex;
  5949. d3d12CommandBuffer->presentDataCount += 1;
  5950. // Set up resource barrier
  5951. D3D12_RESOURCE_BARRIER barrierDesc;
  5952. barrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  5953. barrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  5954. barrierDesc.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
  5955. barrierDesc.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
  5956. barrierDesc.Transition.pResource = windowData->textureContainers[swapchainIndex].activeTexture->resource;
  5957. barrierDesc.Transition.Subresource = 0;
  5958. ID3D12GraphicsCommandList_ResourceBarrier(
  5959. d3d12CommandBuffer->graphicsCommandList,
  5960. 1,
  5961. &barrierDesc);
  5962. *swapchainTexture = (SDL_GPUTexture*)&windowData->textureContainers[swapchainIndex];
  5963. return true;
  5964. }
  5965. static void D3D12_INTERNAL_PerformPendingDestroys(D3D12Renderer *renderer)
  5966. {
  5967. SDL_LockMutex(renderer->disposeLock);
  5968. for (Sint32 i = renderer->buffersToDestroyCount - 1; i >= 0; i -= 1) {
  5969. if (SDL_GetAtomicInt(&renderer->buffersToDestroy[i]->referenceCount) == 0) {
  5970. D3D12_INTERNAL_DestroyBuffer(
  5971. renderer,
  5972. renderer->buffersToDestroy[i]);
  5973. renderer->buffersToDestroy[i] = renderer->buffersToDestroy[renderer->buffersToDestroyCount - 1];
  5974. renderer->buffersToDestroyCount -= 1;
  5975. }
  5976. }
  5977. for (Sint32 i = renderer->texturesToDestroyCount - 1; i >= 0; i -= 1) {
  5978. if (SDL_GetAtomicInt(&renderer->texturesToDestroy[i]->referenceCount) == 0) {
  5979. D3D12_INTERNAL_DestroyTexture(
  5980. renderer,
  5981. renderer->texturesToDestroy[i]);
  5982. renderer->texturesToDestroy[i] = renderer->texturesToDestroy[renderer->texturesToDestroyCount - 1];
  5983. renderer->texturesToDestroyCount -= 1;
  5984. }
  5985. }
  5986. for (Sint32 i = renderer->samplersToDestroyCount - 1; i >= 0; i -= 1) {
  5987. if (SDL_GetAtomicInt(&renderer->samplersToDestroy[i]->referenceCount) == 0) {
  5988. D3D12_INTERNAL_DestroySampler(
  5989. renderer,
  5990. renderer->samplersToDestroy[i]);
  5991. renderer->samplersToDestroy[i] = renderer->samplersToDestroy[renderer->samplersToDestroyCount - 1];
  5992. renderer->samplersToDestroyCount -= 1;
  5993. }
  5994. }
  5995. for (Sint32 i = renderer->graphicsPipelinesToDestroyCount - 1; i >= 0; i -= 1) {
  5996. if (SDL_GetAtomicInt(&renderer->graphicsPipelinesToDestroy[i]->referenceCount) == 0) {
  5997. D3D12_INTERNAL_DestroyGraphicsPipeline(
  5998. renderer->graphicsPipelinesToDestroy[i]);
  5999. renderer->graphicsPipelinesToDestroy[i] = renderer->graphicsPipelinesToDestroy[renderer->graphicsPipelinesToDestroyCount - 1];
  6000. renderer->graphicsPipelinesToDestroyCount -= 1;
  6001. }
  6002. }
  6003. for (Sint32 i = renderer->computePipelinesToDestroyCount - 1; i >= 0; i -= 1) {
  6004. if (SDL_GetAtomicInt(&renderer->computePipelinesToDestroy[i]->referenceCount) == 0) {
  6005. D3D12_INTERNAL_DestroyComputePipeline(
  6006. renderer->computePipelinesToDestroy[i]);
  6007. renderer->computePipelinesToDestroy[i] = renderer->computePipelinesToDestroy[renderer->computePipelinesToDestroyCount - 1];
  6008. renderer->computePipelinesToDestroyCount -= 1;
  6009. }
  6010. }
  6011. SDL_UnlockMutex(renderer->disposeLock);
  6012. }
  6013. static bool D3D12_INTERNAL_CopyTextureDownload(
  6014. D3D12CommandBuffer *commandBuffer,
  6015. D3D12TextureDownload *download)
  6016. {
  6017. D3D12Renderer *renderer = commandBuffer->renderer;
  6018. Uint8 *sourcePtr;
  6019. Uint8 *destPtr;
  6020. HRESULT res;
  6021. res = ID3D12Resource_Map(
  6022. download->temporaryBuffer->handle,
  6023. 0,
  6024. NULL,
  6025. (void **)&sourcePtr);
  6026. CHECK_D3D12_ERROR_AND_RETURN("Failed to map temporary buffer", false)
  6027. res = ID3D12Resource_Map(
  6028. download->destinationBuffer->handle,
  6029. 0,
  6030. NULL,
  6031. (void **)&destPtr);
  6032. CHECK_D3D12_ERROR_AND_RETURN("Failed to map destination buffer", false)
  6033. for (Uint32 sliceIndex = 0; sliceIndex < download->depth; sliceIndex += 1) {
  6034. for (Uint32 rowIndex = 0; rowIndex < download->height; rowIndex += 1) {
  6035. SDL_memcpy(
  6036. destPtr + download->bufferOffset + (sliceIndex * download->bytesPerDepthSlice) + (rowIndex * download->bytesPerRow),
  6037. sourcePtr + (sliceIndex * download->height) + (rowIndex * download->alignedBytesPerRow),
  6038. download->bytesPerRow);
  6039. }
  6040. }
  6041. ID3D12Resource_Unmap(
  6042. download->temporaryBuffer->handle,
  6043. 0,
  6044. NULL);
  6045. ID3D12Resource_Unmap(
  6046. download->destinationBuffer->handle,
  6047. 0,
  6048. NULL);
  6049. return true;
  6050. }
  6051. static bool D3D12_INTERNAL_CleanCommandBuffer(
  6052. D3D12Renderer *renderer,
  6053. D3D12CommandBuffer *commandBuffer)
  6054. {
  6055. Uint32 i;
  6056. HRESULT res;
  6057. bool result = true;
  6058. // Perform deferred texture data copies
  6059. for (i = 0; i < commandBuffer->textureDownloadCount; i += 1) {
  6060. result &= D3D12_INTERNAL_CopyTextureDownload(
  6061. commandBuffer,
  6062. commandBuffer->textureDownloads[i]);
  6063. SDL_free(commandBuffer->textureDownloads[i]);
  6064. }
  6065. commandBuffer->textureDownloadCount = 0;
  6066. if (!result) {
  6067. return false;
  6068. }
  6069. res = ID3D12CommandAllocator_Reset(commandBuffer->commandAllocator);
  6070. CHECK_D3D12_ERROR_AND_RETURN("Could not reset command allocator", false)
  6071. res = ID3D12GraphicsCommandList_Reset(
  6072. commandBuffer->graphicsCommandList,
  6073. commandBuffer->commandAllocator,
  6074. NULL);
  6075. CHECK_D3D12_ERROR_AND_RETURN("Could not reset command list", false)
  6076. // Return descriptor heaps to pool
  6077. D3D12_INTERNAL_ReturnDescriptorHeapToPool(
  6078. renderer,
  6079. commandBuffer->gpuDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV]);
  6080. D3D12_INTERNAL_ReturnDescriptorHeapToPool(
  6081. renderer,
  6082. commandBuffer->gpuDescriptorHeaps[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER]);
  6083. // Uniform buffers are now available
  6084. SDL_LockMutex(renderer->acquireUniformBufferLock);
  6085. for (i = 0; i < commandBuffer->usedUniformBufferCount; i += 1) {
  6086. D3D12_INTERNAL_ReturnUniformBufferToPool(
  6087. renderer,
  6088. commandBuffer->usedUniformBuffers[i]);
  6089. }
  6090. commandBuffer->usedUniformBufferCount = 0;
  6091. SDL_UnlockMutex(renderer->acquireUniformBufferLock);
  6092. // TODO: More reference counting
  6093. for (i = 0; i < commandBuffer->usedTextureCount; i += 1) {
  6094. (void)SDL_AtomicDecRef(&commandBuffer->usedTextures[i]->referenceCount);
  6095. }
  6096. commandBuffer->usedTextureCount = 0;
  6097. for (i = 0; i < commandBuffer->usedBufferCount; i += 1) {
  6098. (void)SDL_AtomicDecRef(&commandBuffer->usedBuffers[i]->referenceCount);
  6099. }
  6100. commandBuffer->usedBufferCount = 0;
  6101. for (i = 0; i < commandBuffer->usedSamplerCount; i += 1) {
  6102. (void)SDL_AtomicDecRef(&commandBuffer->usedSamplers[i]->referenceCount);
  6103. }
  6104. commandBuffer->usedSamplerCount = 0;
  6105. for (i = 0; i < commandBuffer->usedGraphicsPipelineCount; i += 1) {
  6106. (void)SDL_AtomicDecRef(&commandBuffer->usedGraphicsPipelines[i]->referenceCount);
  6107. }
  6108. commandBuffer->usedGraphicsPipelineCount = 0;
  6109. for (i = 0; i < commandBuffer->usedComputePipelineCount; i += 1) {
  6110. (void)SDL_AtomicDecRef(&commandBuffer->usedComputePipelines[i]->referenceCount);
  6111. }
  6112. commandBuffer->usedComputePipelineCount = 0;
  6113. // Reset presentation
  6114. commandBuffer->presentDataCount = 0;
  6115. // The fence is now available (unless SubmitAndAcquireFence was called)
  6116. if (commandBuffer->autoReleaseFence) {
  6117. D3D12_ReleaseFence(
  6118. (SDL_GPURenderer *)renderer,
  6119. (SDL_GPUFence *)commandBuffer->inFlightFence);
  6120. commandBuffer->inFlightFence = NULL;
  6121. }
  6122. // Return command buffer to pool
  6123. SDL_LockMutex(renderer->acquireCommandBufferLock);
  6124. if (renderer->availableCommandBufferCount == renderer->availableCommandBufferCapacity) {
  6125. renderer->availableCommandBufferCapacity += 1;
  6126. renderer->availableCommandBuffers = (D3D12CommandBuffer **)SDL_realloc(
  6127. renderer->availableCommandBuffers,
  6128. renderer->availableCommandBufferCapacity * sizeof(D3D12CommandBuffer *));
  6129. }
  6130. renderer->availableCommandBuffers[renderer->availableCommandBufferCount] = commandBuffer;
  6131. renderer->availableCommandBufferCount += 1;
  6132. SDL_UnlockMutex(renderer->acquireCommandBufferLock);
  6133. // Remove this command buffer from the submitted list
  6134. for (i = 0; i < renderer->submittedCommandBufferCount; i += 1) {
  6135. if (renderer->submittedCommandBuffers[i] == commandBuffer) {
  6136. renderer->submittedCommandBuffers[i] = renderer->submittedCommandBuffers[renderer->submittedCommandBufferCount - 1];
  6137. renderer->submittedCommandBufferCount -= 1;
  6138. }
  6139. }
  6140. return true;
  6141. }
  6142. static bool D3D12_Submit(
  6143. SDL_GPUCommandBuffer *commandBuffer)
  6144. {
  6145. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  6146. D3D12Renderer *renderer = d3d12CommandBuffer->renderer;
  6147. ID3D12CommandList *commandLists[1];
  6148. HRESULT res;
  6149. SDL_LockMutex(renderer->submitLock);
  6150. // Unmap uniform buffers
  6151. for (Uint32 i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  6152. if (d3d12CommandBuffer->vertexUniformBuffers[i] != NULL) {
  6153. ID3D12Resource_Unmap(
  6154. d3d12CommandBuffer->vertexUniformBuffers[i]->buffer->handle,
  6155. 0,
  6156. NULL);
  6157. d3d12CommandBuffer->vertexUniformBuffers[i]->buffer->mapPointer = NULL;
  6158. }
  6159. if (d3d12CommandBuffer->fragmentUniformBuffers[i] != NULL) {
  6160. ID3D12Resource_Unmap(
  6161. d3d12CommandBuffer->fragmentUniformBuffers[i]->buffer->handle,
  6162. 0,
  6163. NULL);
  6164. d3d12CommandBuffer->fragmentUniformBuffers[i]->buffer->mapPointer = NULL;
  6165. }
  6166. // TODO: compute uniforms
  6167. }
  6168. // Transition present textures to present mode
  6169. for (Uint32 i = 0; i < d3d12CommandBuffer->presentDataCount; i += 1) {
  6170. Uint32 swapchainIndex = d3d12CommandBuffer->presentDatas[i].swapchainImageIndex;
  6171. D3D12TextureContainer *container = &d3d12CommandBuffer->presentDatas[i].windowData->textureContainers[swapchainIndex];
  6172. D3D12TextureSubresource *subresource = D3D12_INTERNAL_FetchTextureSubresource(container, 0, 0);
  6173. D3D12_RESOURCE_BARRIER barrierDesc;
  6174. barrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  6175. barrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  6176. barrierDesc.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
  6177. barrierDesc.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
  6178. barrierDesc.Transition.pResource = subresource->parent->resource;
  6179. barrierDesc.Transition.Subresource = subresource->index;
  6180. ID3D12GraphicsCommandList_ResourceBarrier(
  6181. d3d12CommandBuffer->graphicsCommandList,
  6182. 1,
  6183. &barrierDesc);
  6184. }
  6185. // Notify the command buffer that we have completed recording
  6186. res = ID3D12GraphicsCommandList_Close(d3d12CommandBuffer->graphicsCommandList);
  6187. CHECK_D3D12_ERROR_AND_RETURN("Failed to close command list!", false);
  6188. res = ID3D12GraphicsCommandList_QueryInterface(
  6189. d3d12CommandBuffer->graphicsCommandList,
  6190. D3D_GUID(D3D_IID_ID3D12CommandList),
  6191. (void **)&commandLists[0]);
  6192. if (FAILED(res)) {
  6193. SDL_UnlockMutex(renderer->submitLock);
  6194. CHECK_D3D12_ERROR_AND_RETURN("Failed to convert command list!", false)
  6195. }
  6196. // Submit the command list to the queue
  6197. ID3D12CommandQueue_ExecuteCommandLists(
  6198. renderer->commandQueue,
  6199. 1,
  6200. commandLists);
  6201. ID3D12CommandList_Release(commandLists[0]);
  6202. // Acquire a fence and set it to the in-flight fence
  6203. d3d12CommandBuffer->inFlightFence = D3D12_INTERNAL_AcquireFence(renderer);
  6204. if (!d3d12CommandBuffer->inFlightFence) {
  6205. SDL_UnlockMutex(renderer->submitLock);
  6206. return false;
  6207. }
  6208. // Mark that a fence should be signaled after command list execution
  6209. res = ID3D12CommandQueue_Signal(
  6210. renderer->commandQueue,
  6211. d3d12CommandBuffer->inFlightFence->handle,
  6212. D3D12_FENCE_SIGNAL_VALUE);
  6213. if (FAILED(res)) {
  6214. SDL_UnlockMutex(renderer->submitLock);
  6215. CHECK_D3D12_ERROR_AND_RETURN("Failed to enqueue fence signal!", false);
  6216. }
  6217. // Mark the command buffer as submitted
  6218. if (renderer->submittedCommandBufferCount + 1 >= renderer->submittedCommandBufferCapacity) {
  6219. renderer->submittedCommandBufferCapacity = renderer->submittedCommandBufferCount + 1;
  6220. renderer->submittedCommandBuffers = (D3D12CommandBuffer **)SDL_realloc(
  6221. renderer->submittedCommandBuffers,
  6222. sizeof(D3D12CommandBuffer *) * renderer->submittedCommandBufferCapacity);
  6223. }
  6224. renderer->submittedCommandBuffers[renderer->submittedCommandBufferCount] = d3d12CommandBuffer;
  6225. renderer->submittedCommandBufferCount += 1;
  6226. bool result = true;
  6227. // Present, if applicable
  6228. for (Uint32 i = 0; i < d3d12CommandBuffer->presentDataCount; i += 1) {
  6229. D3D12PresentData *presentData = &d3d12CommandBuffer->presentDatas[i];
  6230. D3D12WindowData *windowData = presentData->windowData;
  6231. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  6232. D3D12XBOX_PRESENT_PLANE_PARAMETERS planeParams;
  6233. SDL_zero(planeParams);
  6234. planeParams.Token = windowData->frameToken;
  6235. planeParams.ResourceCount = 1;
  6236. planeParams.ppResources = &windowData->textureContainers[windowData->frameCounter].activeTexture->resource;
  6237. planeParams.ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; // FIXME
  6238. D3D12XBOX_PRESENT_PARAMETERS presentParams;
  6239. SDL_zero(presentParams);
  6240. presentParams.Flags = (windowData->present_mode == SDL_GPU_PRESENTMODE_IMMEDIATE) ? D3D12XBOX_PRESENT_FLAG_IMMEDIATE : D3D12XBOX_PRESENT_FLAG_NONE;
  6241. renderer->commandQueue->PresentX(1, &planeParams, &presentParams);
  6242. if (FAILED(res)) {
  6243. result = false;
  6244. }
  6245. #else
  6246. // NOTE: flip discard always supported since DXGI 1.4 is required
  6247. Uint32 syncInterval = 1;
  6248. if (windowData->present_mode == SDL_GPU_PRESENTMODE_IMMEDIATE ||
  6249. windowData->present_mode == SDL_GPU_PRESENTMODE_MAILBOX) {
  6250. syncInterval = 0;
  6251. }
  6252. Uint32 presentFlags = 0;
  6253. if (renderer->supportsTearing &&
  6254. windowData->present_mode == SDL_GPU_PRESENTMODE_IMMEDIATE) {
  6255. presentFlags = DXGI_PRESENT_ALLOW_TEARING;
  6256. }
  6257. res = IDXGISwapChain_Present(
  6258. windowData->swapchain,
  6259. syncInterval,
  6260. presentFlags);
  6261. if (FAILED(res)) {
  6262. result = false;
  6263. }
  6264. ID3D12Resource_Release(windowData->textureContainers[presentData->swapchainImageIndex].activeTexture->resource);
  6265. #endif
  6266. windowData->inFlightFences[windowData->frameCounter] = (SDL_GPUFence*)d3d12CommandBuffer->inFlightFence;
  6267. (void)SDL_AtomicIncRef(&d3d12CommandBuffer->inFlightFence->referenceCount);
  6268. windowData->frameCounter = (windowData->frameCounter + 1) % MAX_FRAMES_IN_FLIGHT;
  6269. }
  6270. // Check for cleanups
  6271. for (Sint32 i = renderer->submittedCommandBufferCount - 1; i >= 0; i -= 1) {
  6272. Uint64 fenceValue = ID3D12Fence_GetCompletedValue(
  6273. renderer->submittedCommandBuffers[i]->inFlightFence->handle);
  6274. if (fenceValue == D3D12_FENCE_SIGNAL_VALUE) {
  6275. result &= D3D12_INTERNAL_CleanCommandBuffer(
  6276. renderer,
  6277. renderer->submittedCommandBuffers[i]);
  6278. }
  6279. }
  6280. D3D12_INTERNAL_PerformPendingDestroys(renderer);
  6281. SDL_UnlockMutex(renderer->submitLock);
  6282. return result;
  6283. }
  6284. static SDL_GPUFence *D3D12_SubmitAndAcquireFence(
  6285. SDL_GPUCommandBuffer *commandBuffer)
  6286. {
  6287. D3D12CommandBuffer *d3d12CommandBuffer = (D3D12CommandBuffer *)commandBuffer;
  6288. d3d12CommandBuffer->autoReleaseFence = false;
  6289. D3D12_Submit(commandBuffer);
  6290. return (SDL_GPUFence *)d3d12CommandBuffer->inFlightFence;
  6291. }
  6292. static bool D3D12_Wait(
  6293. SDL_GPURenderer *driverData)
  6294. {
  6295. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  6296. D3D12Fence *fence = D3D12_INTERNAL_AcquireFence(renderer);
  6297. if (!fence) {
  6298. return false;
  6299. }
  6300. HRESULT res;
  6301. SDL_LockMutex(renderer->submitLock);
  6302. if (renderer->commandQueue) {
  6303. // Insert a signal into the end of the command queue...
  6304. ID3D12CommandQueue_Signal(
  6305. renderer->commandQueue,
  6306. fence->handle,
  6307. D3D12_FENCE_SIGNAL_VALUE);
  6308. // ...and then block on it.
  6309. if (ID3D12Fence_GetCompletedValue(fence->handle) != D3D12_FENCE_SIGNAL_VALUE) {
  6310. res = ID3D12Fence_SetEventOnCompletion(
  6311. fence->handle,
  6312. D3D12_FENCE_SIGNAL_VALUE,
  6313. fence->event);
  6314. CHECK_D3D12_ERROR_AND_RETURN("Setting fence event failed", false)
  6315. DWORD waitResult = WaitForSingleObject(fence->event, INFINITE);
  6316. if (waitResult == WAIT_FAILED) {
  6317. SDL_UnlockMutex(renderer->submitLock);
  6318. SET_STRING_ERROR_AND_RETURN("Wait failed", false) // TODO: is there a better way to report this?
  6319. }
  6320. }
  6321. }
  6322. D3D12_ReleaseFence(
  6323. (SDL_GPURenderer *)renderer,
  6324. (SDL_GPUFence *)fence);
  6325. bool result = true;
  6326. // Clean up
  6327. for (Sint32 i = renderer->submittedCommandBufferCount - 1; i >= 0; i -= 1) {
  6328. result &= D3D12_INTERNAL_CleanCommandBuffer(renderer, renderer->submittedCommandBuffers[i]);
  6329. }
  6330. D3D12_INTERNAL_PerformPendingDestroys(renderer);
  6331. SDL_UnlockMutex(renderer->submitLock);
  6332. return result;
  6333. }
  6334. static bool D3D12_WaitForFences(
  6335. SDL_GPURenderer *driverData,
  6336. bool waitAll,
  6337. SDL_GPUFence *const *fences,
  6338. Uint32 numFences)
  6339. {
  6340. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  6341. D3D12Fence *fence;
  6342. HANDLE *events = SDL_stack_alloc(HANDLE, numFences);
  6343. HRESULT res;
  6344. SDL_LockMutex(renderer->submitLock);
  6345. for (Uint32 i = 0; i < numFences; i += 1) {
  6346. fence = (D3D12Fence *)fences[i];
  6347. res = ID3D12Fence_SetEventOnCompletion(
  6348. fence->handle,
  6349. D3D12_FENCE_SIGNAL_VALUE,
  6350. fence->event);
  6351. CHECK_D3D12_ERROR_AND_RETURN("Setting fence event failed", false)
  6352. events[i] = fence->event;
  6353. }
  6354. DWORD waitResult = WaitForMultipleObjects(
  6355. numFences,
  6356. events,
  6357. waitAll,
  6358. INFINITE);
  6359. if (waitResult == WAIT_FAILED) {
  6360. SDL_UnlockMutex(renderer->submitLock);
  6361. SET_STRING_ERROR_AND_RETURN("Wait failed", false) // TODO: is there a better way to report this?
  6362. }
  6363. bool result = true;
  6364. // Check for cleanups
  6365. for (Sint32 i = renderer->submittedCommandBufferCount - 1; i >= 0; i -= 1) {
  6366. Uint64 fenceValue = ID3D12Fence_GetCompletedValue(
  6367. renderer->submittedCommandBuffers[i]->inFlightFence->handle);
  6368. if (fenceValue == D3D12_FENCE_SIGNAL_VALUE) {
  6369. result &= D3D12_INTERNAL_CleanCommandBuffer(
  6370. renderer,
  6371. renderer->submittedCommandBuffers[i]);
  6372. }
  6373. }
  6374. D3D12_INTERNAL_PerformPendingDestroys(renderer);
  6375. SDL_stack_free(events);
  6376. SDL_UnlockMutex(renderer->submitLock);
  6377. return result;
  6378. }
  6379. // Feature Queries
  6380. static bool D3D12_SupportsTextureFormat(
  6381. SDL_GPURenderer *driverData,
  6382. SDL_GPUTextureFormat format,
  6383. SDL_GPUTextureType type,
  6384. SDL_GPUTextureUsageFlags usage)
  6385. {
  6386. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  6387. DXGI_FORMAT dxgiFormat = SDLToD3D12_TextureFormat[format];
  6388. D3D12_FEATURE_DATA_FORMAT_SUPPORT formatSupport = { dxgiFormat, D3D12_FORMAT_SUPPORT1_NONE, D3D12_FORMAT_SUPPORT2_NONE };
  6389. HRESULT res;
  6390. res = ID3D12Device_CheckFeatureSupport(
  6391. renderer->device,
  6392. D3D12_FEATURE_FORMAT_SUPPORT,
  6393. &formatSupport,
  6394. sizeof(formatSupport));
  6395. if (FAILED(res)) {
  6396. // Format is apparently unknown
  6397. return false;
  6398. }
  6399. // Is the texture type supported?
  6400. if (type == SDL_GPU_TEXTURETYPE_2D && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D)) {
  6401. return false;
  6402. }
  6403. if (type == SDL_GPU_TEXTURETYPE_2D_ARRAY && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D)) {
  6404. return false;
  6405. }
  6406. if (type == SDL_GPU_TEXTURETYPE_3D && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE3D)) {
  6407. return false;
  6408. }
  6409. if (type == SDL_GPU_TEXTURETYPE_CUBE && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURECUBE)) {
  6410. return false;
  6411. }
  6412. if (type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURECUBE)) {
  6413. return false;
  6414. }
  6415. // Are the usage flags supported?
  6416. if ((usage & SDL_GPU_TEXTUREUSAGE_SAMPLER) && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE)) {
  6417. return false;
  6418. }
  6419. if ((usage & (SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ)) && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_LOAD)) {
  6420. return false;
  6421. }
  6422. if ((usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE) && !(formatSupport.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE)) {
  6423. return false;
  6424. }
  6425. if ((usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE) && !(formatSupport.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD)) {
  6426. return false;
  6427. }
  6428. if ((usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET)) {
  6429. return false;
  6430. }
  6431. if ((usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) && !(formatSupport.Support1 & D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL)) {
  6432. return false;
  6433. }
  6434. return true;
  6435. }
  6436. static bool D3D12_SupportsSampleCount(
  6437. SDL_GPURenderer *driverData,
  6438. SDL_GPUTextureFormat format,
  6439. SDL_GPUSampleCount sampleCount)
  6440. {
  6441. D3D12Renderer *renderer = (D3D12Renderer *)driverData;
  6442. D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS featureData;
  6443. HRESULT res;
  6444. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  6445. featureData.Flags = (D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG)0;
  6446. #else
  6447. featureData.Flags = (D3D12_MULTISAMPLE_QUALITY_LEVEL_FLAGS)0;
  6448. #endif
  6449. featureData.Format = SDLToD3D12_TextureFormat[format];
  6450. featureData.SampleCount = SDLToD3D12_SampleCount[sampleCount];
  6451. res = ID3D12Device_CheckFeatureSupport(
  6452. renderer->device,
  6453. D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS,
  6454. &featureData,
  6455. sizeof(featureData));
  6456. return SUCCEEDED(res) && featureData.NumQualityLevels > 0;
  6457. }
  6458. static void D3D12_INTERNAL_InitBlitResources(
  6459. D3D12Renderer *renderer)
  6460. {
  6461. SDL_GPUShaderCreateInfo shaderCreateInfo;
  6462. SDL_GPUSamplerCreateInfo samplerCreateInfo;
  6463. renderer->blitPipelineCapacity = 2;
  6464. renderer->blitPipelineCount = 0;
  6465. renderer->blitPipelines = (BlitPipelineCacheEntry *)SDL_malloc(
  6466. renderer->blitPipelineCapacity * sizeof(BlitPipelineCacheEntry));
  6467. // Fullscreen vertex shader
  6468. SDL_zero(shaderCreateInfo);
  6469. shaderCreateInfo.code = (Uint8 *)D3D12_FullscreenVert;
  6470. shaderCreateInfo.code_size = sizeof(D3D12_FullscreenVert);
  6471. shaderCreateInfo.stage = SDL_GPU_SHADERSTAGE_VERTEX;
  6472. shaderCreateInfo.format = SDL_GPU_SHADERFORMAT_DXBC;
  6473. shaderCreateInfo.entrypoint = "main";
  6474. renderer->blitVertexShader = D3D12_CreateShader(
  6475. (SDL_GPURenderer *)renderer,
  6476. &shaderCreateInfo);
  6477. if (renderer->blitVertexShader == NULL) {
  6478. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile vertex shader for blit!");
  6479. }
  6480. // BlitFrom2D pixel shader
  6481. shaderCreateInfo.code = (Uint8 *)D3D12_BlitFrom2D;
  6482. shaderCreateInfo.code_size = sizeof(D3D12_BlitFrom2D);
  6483. shaderCreateInfo.stage = SDL_GPU_SHADERSTAGE_FRAGMENT;
  6484. shaderCreateInfo.num_samplers = 1;
  6485. shaderCreateInfo.num_uniform_buffers = 1;
  6486. renderer->blitFrom2DShader = D3D12_CreateShader(
  6487. (SDL_GPURenderer *)renderer,
  6488. &shaderCreateInfo);
  6489. if (renderer->blitFrom2DShader == NULL) {
  6490. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile BlitFrom2D pixel shader!");
  6491. }
  6492. // BlitFrom2DArray pixel shader
  6493. shaderCreateInfo.code = (Uint8 *)D3D12_BlitFrom2DArray;
  6494. shaderCreateInfo.code_size = sizeof(D3D12_BlitFrom2DArray);
  6495. renderer->blitFrom2DArrayShader = D3D12_CreateShader(
  6496. (SDL_GPURenderer *)renderer,
  6497. &shaderCreateInfo);
  6498. if (renderer->blitFrom2DArrayShader == NULL) {
  6499. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile BlitFrom2DArray pixel shader!");
  6500. }
  6501. // BlitFrom3D pixel shader
  6502. shaderCreateInfo.code = (Uint8 *)D3D12_BlitFrom3D;
  6503. shaderCreateInfo.code_size = sizeof(D3D12_BlitFrom3D);
  6504. renderer->blitFrom3DShader = D3D12_CreateShader(
  6505. (SDL_GPURenderer *)renderer,
  6506. &shaderCreateInfo);
  6507. if (renderer->blitFrom3DShader == NULL) {
  6508. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile BlitFrom3D pixel shader!");
  6509. }
  6510. // BlitFromCube pixel shader
  6511. shaderCreateInfo.code = (Uint8 *)D3D12_BlitFromCube;
  6512. shaderCreateInfo.code_size = sizeof(D3D12_BlitFromCube);
  6513. renderer->blitFromCubeShader = D3D12_CreateShader(
  6514. (SDL_GPURenderer *)renderer,
  6515. &shaderCreateInfo);
  6516. if (renderer->blitFromCubeShader == NULL) {
  6517. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile BlitFromCube pixel shader!");
  6518. }
  6519. // BlitFromCubeArray pixel shader
  6520. shaderCreateInfo.code = (Uint8 *)D3D12_BlitFromCubeArray;
  6521. shaderCreateInfo.code_size = sizeof(D3D12_BlitFromCubeArray);
  6522. renderer->blitFromCubeArrayShader = D3D12_CreateShader(
  6523. (SDL_GPURenderer *)renderer,
  6524. &shaderCreateInfo);
  6525. if (renderer->blitFromCubeArrayShader == NULL) {
  6526. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to compile BlitFromCubeArray pixel shader!");
  6527. }
  6528. // Create samplers
  6529. samplerCreateInfo.address_mode_u = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
  6530. samplerCreateInfo.address_mode_v = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
  6531. samplerCreateInfo.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
  6532. samplerCreateInfo.enable_anisotropy = 0;
  6533. samplerCreateInfo.enable_compare = 0;
  6534. samplerCreateInfo.mag_filter = SDL_GPU_FILTER_NEAREST;
  6535. samplerCreateInfo.min_filter = SDL_GPU_FILTER_NEAREST;
  6536. samplerCreateInfo.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
  6537. samplerCreateInfo.mip_lod_bias = 0.0f;
  6538. samplerCreateInfo.min_lod = 0;
  6539. samplerCreateInfo.max_lod = 1000;
  6540. samplerCreateInfo.max_anisotropy = 1.0f;
  6541. samplerCreateInfo.compare_op = SDL_GPU_COMPAREOP_ALWAYS;
  6542. renderer->blitNearestSampler = D3D12_CreateSampler(
  6543. (SDL_GPURenderer *)renderer,
  6544. &samplerCreateInfo);
  6545. if (renderer->blitNearestSampler == NULL) {
  6546. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create blit nearest sampler!");
  6547. }
  6548. samplerCreateInfo.mag_filter = SDL_GPU_FILTER_LINEAR;
  6549. samplerCreateInfo.min_filter = SDL_GPU_FILTER_LINEAR;
  6550. samplerCreateInfo.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_LINEAR;
  6551. renderer->blitLinearSampler = D3D12_CreateSampler(
  6552. (SDL_GPURenderer *)renderer,
  6553. &samplerCreateInfo);
  6554. if (renderer->blitLinearSampler == NULL) {
  6555. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Failed to create blit linear sampler!");
  6556. }
  6557. }
  6558. static bool D3D12_PrepareDriver(SDL_VideoDevice *_this)
  6559. {
  6560. #if defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)
  6561. return true;
  6562. #else
  6563. void *d3d12Dll;
  6564. void *dxgiDll;
  6565. PFN_D3D12_CREATE_DEVICE D3D12CreateDeviceFunc;
  6566. PFN_CREATE_DXGI_FACTORY1 CreateDXGIFactoryFunc;
  6567. HRESULT res;
  6568. ID3D12Device *device;
  6569. IDXGIFactory1 *factory;
  6570. IDXGIFactory4 *factory4;
  6571. IDXGIFactory6 *factory6;
  6572. IDXGIAdapter1 *adapter;
  6573. // Can we load D3D12?
  6574. d3d12Dll = SDL_LoadObject(D3D12_DLL);
  6575. if (d3d12Dll == NULL) {
  6576. SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "D3D12: Could not find " D3D12_DLL);
  6577. return false;
  6578. }
  6579. D3D12CreateDeviceFunc = (PFN_D3D12_CREATE_DEVICE)SDL_LoadFunction(
  6580. d3d12Dll,
  6581. D3D12_CREATE_DEVICE_FUNC);
  6582. if (D3D12CreateDeviceFunc == NULL) {
  6583. SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "D3D12: Could not find function " D3D12_CREATE_DEVICE_FUNC " in " D3D12_DLL);
  6584. SDL_UnloadObject(d3d12Dll);
  6585. return false;
  6586. }
  6587. // Can we load DXGI?
  6588. dxgiDll = SDL_LoadObject(DXGI_DLL);
  6589. if (dxgiDll == NULL) {
  6590. SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "D3D12: Could not find " DXGI_DLL);
  6591. return false;
  6592. }
  6593. CreateDXGIFactoryFunc = (PFN_CREATE_DXGI_FACTORY1)SDL_LoadFunction(
  6594. dxgiDll,
  6595. CREATE_DXGI_FACTORY1_FUNC);
  6596. if (CreateDXGIFactoryFunc == NULL) {
  6597. SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "D3D12: Could not find function " CREATE_DXGI_FACTORY1_FUNC " in " DXGI_DLL);
  6598. SDL_UnloadObject(dxgiDll);
  6599. return false;
  6600. }
  6601. // Can we create a device?
  6602. // Create the DXGI factory
  6603. res = CreateDXGIFactoryFunc(
  6604. &D3D_IID_IDXGIFactory1,
  6605. (void **)&factory);
  6606. if (FAILED(res)) {
  6607. SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "D3D12: Could not create DXGIFactory");
  6608. SDL_UnloadObject(d3d12Dll);
  6609. SDL_UnloadObject(dxgiDll);
  6610. return false;
  6611. }
  6612. // Check for DXGI 1.4 support
  6613. res = IDXGIFactory1_QueryInterface(
  6614. factory,
  6615. D3D_GUID(D3D_IID_IDXGIFactory4),
  6616. (void **)&factory4);
  6617. if (FAILED(res)) {
  6618. IDXGIFactory1_Release(factory);
  6619. SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "D3D12: Failed to find DXGI1.4 support, required for DX12");
  6620. SDL_UnloadObject(d3d12Dll);
  6621. SDL_UnloadObject(dxgiDll);
  6622. return false;
  6623. }
  6624. IDXGIFactory4_Release(factory4);
  6625. res = IDXGIFactory1_QueryInterface(
  6626. factory,
  6627. D3D_GUID(D3D_IID_IDXGIFactory6),
  6628. (void **)&factory6);
  6629. if (SUCCEEDED(res)) {
  6630. res = IDXGIFactory6_EnumAdapterByGpuPreference(
  6631. factory6,
  6632. 0,
  6633. DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE,
  6634. D3D_GUID(D3D_IID_IDXGIAdapter1),
  6635. (void **)&adapter);
  6636. IDXGIFactory6_Release(factory6);
  6637. } else {
  6638. res = IDXGIFactory1_EnumAdapters1(
  6639. factory,
  6640. 0,
  6641. &adapter);
  6642. }
  6643. if (FAILED(res)) {
  6644. SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "D3D12: Failed to find adapter for D3D12Device");
  6645. IDXGIFactory1_Release(factory);
  6646. SDL_UnloadObject(d3d12Dll);
  6647. SDL_UnloadObject(dxgiDll);
  6648. return false;
  6649. }
  6650. res = D3D12CreateDeviceFunc(
  6651. (IUnknown *)adapter,
  6652. D3D_FEATURE_LEVEL_CHOICE,
  6653. D3D_GUID(D3D_IID_ID3D12Device),
  6654. (void **)&device);
  6655. if (SUCCEEDED(res)) {
  6656. ID3D12Device_Release(device);
  6657. }
  6658. IDXGIAdapter1_Release(adapter);
  6659. IDXGIFactory1_Release(factory);
  6660. SDL_UnloadObject(d3d12Dll);
  6661. SDL_UnloadObject(dxgiDll);
  6662. if (FAILED(res)) {
  6663. SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "D3D12: Could not create D3D12Device with feature level " D3D_FEATURE_LEVEL_CHOICE_STR);
  6664. return false;
  6665. }
  6666. return true;
  6667. #endif
  6668. }
  6669. #if !(defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES)) && defined(HAVE_IDXGIINFOQUEUE)
  6670. static void D3D12_INTERNAL_TryInitializeDXGIDebug(D3D12Renderer *renderer)
  6671. {
  6672. PFN_DXGI_GET_DEBUG_INTERFACE DXGIGetDebugInterfaceFunc;
  6673. HRESULT res;
  6674. renderer->dxgidebug_dll = SDL_LoadObject(DXGIDEBUG_DLL);
  6675. if (renderer->dxgidebug_dll == NULL) {
  6676. SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Could not find " DXGIDEBUG_DLL);
  6677. return;
  6678. }
  6679. DXGIGetDebugInterfaceFunc = (PFN_DXGI_GET_DEBUG_INTERFACE)SDL_LoadFunction(
  6680. renderer->dxgidebug_dll,
  6681. DXGI_GET_DEBUG_INTERFACE_FUNC);
  6682. if (DXGIGetDebugInterfaceFunc == NULL) {
  6683. SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Could not load function: " DXGI_GET_DEBUG_INTERFACE_FUNC);
  6684. return;
  6685. }
  6686. res = DXGIGetDebugInterfaceFunc(&D3D_IID_IDXGIDebug, (void **)&renderer->dxgiDebug);
  6687. if (FAILED(res)) {
  6688. SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Could not get IDXGIDebug interface");
  6689. }
  6690. res = DXGIGetDebugInterfaceFunc(&D3D_IID_IDXGIInfoQueue, (void **)&renderer->dxgiInfoQueue);
  6691. if (FAILED(res)) {
  6692. SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Could not get IDXGIInfoQueue interface");
  6693. }
  6694. }
  6695. #endif
  6696. static void D3D12_INTERNAL_TryInitializeD3D12Debug(D3D12Renderer *renderer)
  6697. {
  6698. PFN_D3D12_GET_DEBUG_INTERFACE D3D12GetDebugInterfaceFunc;
  6699. HRESULT res;
  6700. D3D12GetDebugInterfaceFunc = (PFN_D3D12_GET_DEBUG_INTERFACE)SDL_LoadFunction(
  6701. renderer->d3d12_dll,
  6702. D3D12_GET_DEBUG_INTERFACE_FUNC);
  6703. if (D3D12GetDebugInterfaceFunc == NULL) {
  6704. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Could not load function: " D3D12_GET_DEBUG_INTERFACE_FUNC);
  6705. return;
  6706. }
  6707. res = D3D12GetDebugInterfaceFunc(D3D_GUID(D3D_IID_ID3D12Debug), (void **)&renderer->d3d12Debug);
  6708. if (FAILED(res)) {
  6709. SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Could not get ID3D12Debug interface");
  6710. return;
  6711. }
  6712. ID3D12Debug_EnableDebugLayer(renderer->d3d12Debug);
  6713. }
  6714. #if !(defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  6715. static bool D3D12_INTERNAL_TryInitializeD3D12DebugInfoQueue(D3D12Renderer *renderer)
  6716. {
  6717. ID3D12InfoQueue *infoQueue = NULL;
  6718. D3D12_MESSAGE_SEVERITY severities[] = { D3D12_MESSAGE_SEVERITY_INFO };
  6719. D3D12_INFO_QUEUE_FILTER filter;
  6720. HRESULT res;
  6721. res = ID3D12Device_QueryInterface(
  6722. renderer->device,
  6723. D3D_GUID(D3D_IID_ID3D12InfoQueue),
  6724. (void **)&infoQueue);
  6725. if (FAILED(res)) {
  6726. CHECK_D3D12_ERROR_AND_RETURN("Failed to convert ID3D12Device to ID3D12InfoQueue", false);
  6727. }
  6728. SDL_zero(filter);
  6729. filter.DenyList.NumSeverities = 1;
  6730. filter.DenyList.pSeverityList = severities;
  6731. ID3D12InfoQueue_PushStorageFilter(
  6732. infoQueue,
  6733. &filter);
  6734. ID3D12InfoQueue_SetBreakOnSeverity(
  6735. infoQueue,
  6736. D3D12_MESSAGE_SEVERITY_ERROR,
  6737. true);
  6738. ID3D12InfoQueue_SetBreakOnSeverity(
  6739. infoQueue,
  6740. D3D12_MESSAGE_SEVERITY_CORRUPTION,
  6741. true);
  6742. ID3D12InfoQueue_Release(infoQueue);
  6743. return true;
  6744. }
  6745. #endif
  6746. static SDL_GPUDevice *D3D12_CreateDevice(bool debugMode, bool preferLowPower, SDL_PropertiesID props)
  6747. {
  6748. SDL_GPUDevice *result;
  6749. D3D12Renderer *renderer;
  6750. HRESULT res;
  6751. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  6752. PFN_D3D12_XBOX_CREATE_DEVICE D3D12XboxCreateDeviceFunc;
  6753. D3D12XBOX_CREATE_DEVICE_PARAMETERS createDeviceParams;
  6754. #else
  6755. PFN_CREATE_DXGI_FACTORY1 CreateDXGIFactoryFunc;
  6756. IDXGIFactory1 *factory1;
  6757. IDXGIFactory5 *factory5;
  6758. IDXGIFactory6 *factory6;
  6759. DXGI_ADAPTER_DESC1 adapterDesc;
  6760. PFN_D3D12_CREATE_DEVICE D3D12CreateDeviceFunc;
  6761. #endif
  6762. D3D12_FEATURE_DATA_ARCHITECTURE architecture;
  6763. D3D12_COMMAND_QUEUE_DESC queueDesc;
  6764. renderer = (D3D12Renderer *)SDL_calloc(1, sizeof(D3D12Renderer));
  6765. #if !(defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  6766. // Load the DXGI library
  6767. renderer->dxgi_dll = SDL_LoadObject(DXGI_DLL);
  6768. if (renderer->dxgi_dll == NULL) {
  6769. D3D12_INTERNAL_DestroyRenderer(renderer);
  6770. SET_STRING_ERROR_AND_RETURN("Could not find " DXGI_DLL, NULL);
  6771. }
  6772. #ifdef HAVE_IDXGIINFOQUEUE
  6773. // Initialize the DXGI debug layer, if applicable
  6774. if (debugMode) {
  6775. D3D12_INTERNAL_TryInitializeDXGIDebug(renderer);
  6776. }
  6777. #endif
  6778. // Load the CreateDXGIFactory1 function
  6779. CreateDXGIFactoryFunc = (PFN_CREATE_DXGI_FACTORY1)SDL_LoadFunction(
  6780. renderer->dxgi_dll,
  6781. CREATE_DXGI_FACTORY1_FUNC);
  6782. if (CreateDXGIFactoryFunc == NULL) {
  6783. D3D12_INTERNAL_DestroyRenderer(renderer);
  6784. SET_STRING_ERROR_AND_RETURN("Could not load function: " CREATE_DXGI_FACTORY1_FUNC, NULL)
  6785. }
  6786. // Create the DXGI factory
  6787. res = CreateDXGIFactoryFunc(
  6788. &D3D_IID_IDXGIFactory1,
  6789. (void **)&factory1);
  6790. if (FAILED(res)) {
  6791. D3D12_INTERNAL_DestroyRenderer(renderer);
  6792. CHECK_D3D12_ERROR_AND_RETURN("Could not create DXGIFactory", NULL);
  6793. }
  6794. // Check for DXGI 1.4 support
  6795. res = IDXGIFactory1_QueryInterface(
  6796. factory1,
  6797. D3D_GUID(D3D_IID_IDXGIFactory4),
  6798. (void **)&renderer->factory);
  6799. if (FAILED(res)) {
  6800. D3D12_INTERNAL_DestroyRenderer(renderer);
  6801. CHECK_D3D12_ERROR_AND_RETURN("DXGI1.4 support not found, required for DX12", NULL);
  6802. }
  6803. IDXGIFactory1_Release(factory1);
  6804. // Check for explicit tearing support
  6805. res = IDXGIFactory4_QueryInterface(
  6806. renderer->factory,
  6807. D3D_GUID(D3D_IID_IDXGIFactory5),
  6808. (void **)&factory5);
  6809. if (SUCCEEDED(res)) {
  6810. res = IDXGIFactory5_CheckFeatureSupport(
  6811. factory5,
  6812. DXGI_FEATURE_PRESENT_ALLOW_TEARING,
  6813. &renderer->supportsTearing,
  6814. sizeof(renderer->supportsTearing));
  6815. if (FAILED(res)) {
  6816. renderer->supportsTearing = false;
  6817. }
  6818. IDXGIFactory5_Release(factory5);
  6819. }
  6820. // Select the appropriate device for rendering
  6821. res = IDXGIFactory4_QueryInterface(
  6822. renderer->factory,
  6823. D3D_GUID(D3D_IID_IDXGIFactory6),
  6824. (void **)&factory6);
  6825. if (SUCCEEDED(res)) {
  6826. res = IDXGIFactory6_EnumAdapterByGpuPreference(
  6827. factory6,
  6828. 0,
  6829. preferLowPower ? DXGI_GPU_PREFERENCE_MINIMUM_POWER : DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE,
  6830. D3D_GUID(D3D_IID_IDXGIAdapter1),
  6831. (void **)&renderer->adapter);
  6832. IDXGIFactory6_Release(factory6);
  6833. } else {
  6834. res = IDXGIFactory4_EnumAdapters1(
  6835. renderer->factory,
  6836. 0,
  6837. &renderer->adapter);
  6838. }
  6839. if (FAILED(res)) {
  6840. D3D12_INTERNAL_DestroyRenderer(renderer);
  6841. CHECK_D3D12_ERROR_AND_RETURN("Could not find adapter for D3D12Device", NULL);
  6842. }
  6843. // Get information about the selected adapter. Used for logging info.
  6844. res = IDXGIAdapter1_GetDesc1(renderer->adapter, &adapterDesc);
  6845. if (FAILED(res)) {
  6846. D3D12_INTERNAL_DestroyRenderer(renderer);
  6847. CHECK_D3D12_ERROR_AND_RETURN("Could not get adapter description", NULL);
  6848. }
  6849. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "SDL_GPU Driver: D3D12");
  6850. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "D3D12 Adapter: %S", adapterDesc.Description);
  6851. #endif
  6852. // Load the D3D library
  6853. renderer->d3d12_dll = SDL_LoadObject(D3D12_DLL);
  6854. if (renderer->d3d12_dll == NULL) {
  6855. D3D12_INTERNAL_DestroyRenderer(renderer);
  6856. SET_STRING_ERROR_AND_RETURN("Could not find " D3D12_DLL, NULL);
  6857. }
  6858. // Load the CreateDevice function
  6859. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  6860. D3D12XboxCreateDeviceFunc = (PFN_D3D12_XBOX_CREATE_DEVICE)SDL_LoadFunction(
  6861. renderer->d3d12_dll,
  6862. "D3D12XboxCreateDevice");
  6863. if (D3D12XboxCreateDeviceFunc == NULL) {
  6864. D3D12_INTERNAL_DestroyRenderer(renderer);
  6865. SET_STRING_ERROR_AND_RETURN("Could not load function: D3D12XboxCreateDevice", NULL)
  6866. }
  6867. #else
  6868. D3D12CreateDeviceFunc = (PFN_D3D12_CREATE_DEVICE)SDL_LoadFunction(
  6869. renderer->d3d12_dll,
  6870. D3D12_CREATE_DEVICE_FUNC);
  6871. if (D3D12CreateDeviceFunc == NULL) {
  6872. D3D12_INTERNAL_DestroyRenderer(renderer);
  6873. SET_STRING_ERROR_AND_RETURN("Could not load function: " D3D12_CREATE_DEVICE_FUNC, NULL)
  6874. }
  6875. #endif
  6876. renderer->D3D12SerializeRootSignature_func = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)SDL_LoadFunction(
  6877. renderer->d3d12_dll,
  6878. D3D12_SERIALIZE_ROOT_SIGNATURE_FUNC);
  6879. if (renderer->D3D12SerializeRootSignature_func == NULL) {
  6880. D3D12_INTERNAL_DestroyRenderer(renderer);
  6881. SET_STRING_ERROR_AND_RETURN("Could not load function: " D3D12_SERIALIZE_ROOT_SIGNATURE_FUNC, NULL)
  6882. }
  6883. // Initialize the D3D12 debug layer, if applicable
  6884. if (debugMode) {
  6885. D3D12_INTERNAL_TryInitializeD3D12Debug(renderer);
  6886. }
  6887. // Create the D3D12Device
  6888. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  6889. if (s_Device != NULL) {
  6890. renderer->device = s_Device;
  6891. } else {
  6892. SDL_zero(createDeviceParams);
  6893. createDeviceParams.Version = D3D12_SDK_VERSION;
  6894. createDeviceParams.GraphicsCommandQueueRingSizeBytes = D3D12XBOX_DEFAULT_SIZE_BYTES;
  6895. createDeviceParams.GraphicsScratchMemorySizeBytes = D3D12XBOX_DEFAULT_SIZE_BYTES;
  6896. createDeviceParams.ComputeScratchMemorySizeBytes = D3D12XBOX_DEFAULT_SIZE_BYTES;
  6897. createDeviceParams.DisableGeometryShaderAllocations = TRUE;
  6898. createDeviceParams.DisableTessellationShaderAllocations = TRUE;
  6899. #if defined(SDL_PLATFORM_XBOXSERIES)
  6900. createDeviceParams.DisableDXR = TRUE;
  6901. #endif
  6902. if (debugMode) {
  6903. createDeviceParams.ProcessDebugFlags = D3D12XBOX_PROCESS_DEBUG_FLAG_DEBUG;
  6904. }
  6905. res = D3D12XboxCreateDeviceFunc(
  6906. NULL,
  6907. &createDeviceParams,
  6908. IID_GRAPHICS_PPV_ARGS(&renderer->device));
  6909. if (FAILED(res)) {
  6910. D3D12_INTERNAL_DestroyRenderer(renderer);
  6911. CHECK_D3D12_ERROR_AND_RETURN("Could not create D3D12Device", NULL);
  6912. }
  6913. res = renderer->device->SetFrameIntervalX(
  6914. NULL,
  6915. D3D12XBOX_FRAME_INTERVAL_60_HZ,
  6916. MAX_FRAMES_IN_FLIGHT - 1,
  6917. D3D12XBOX_FRAME_INTERVAL_FLAG_NONE);
  6918. if (FAILED(res)) {
  6919. D3D12_INTERNAL_DestroyRenderer(renderer);
  6920. CHECK_D3D12_ERROR_AND_RETURN("Could not get set frame interval", NULL);
  6921. }
  6922. res = renderer->device->ScheduleFrameEventX(
  6923. D3D12XBOX_FRAME_EVENT_ORIGIN,
  6924. 0,
  6925. NULL,
  6926. D3D12XBOX_SCHEDULE_FRAME_EVENT_FLAG_NONE);
  6927. if (FAILED(res)) {
  6928. D3D12_INTERNAL_DestroyRenderer(renderer);
  6929. CHECK_D3D12_ERROR_AND_RETURN("Could not schedule frame events", NULL);
  6930. }
  6931. s_Device = renderer->device;
  6932. }
  6933. #else
  6934. res = D3D12CreateDeviceFunc(
  6935. (IUnknown *)renderer->adapter,
  6936. D3D_FEATURE_LEVEL_CHOICE,
  6937. D3D_GUID(D3D_IID_ID3D12Device),
  6938. (void **)&renderer->device);
  6939. if (FAILED(res)) {
  6940. D3D12_INTERNAL_DestroyRenderer(renderer);
  6941. CHECK_D3D12_ERROR_AND_RETURN("Could not create D3D12Device", NULL);
  6942. }
  6943. // Initialize the D3D12 debug info queue, if applicable
  6944. if (debugMode) {
  6945. if (!D3D12_INTERNAL_TryInitializeD3D12DebugInfoQueue(renderer)) {
  6946. return NULL;
  6947. }
  6948. }
  6949. #endif
  6950. // Check UMA
  6951. architecture.NodeIndex = 0;
  6952. res = ID3D12Device_CheckFeatureSupport(
  6953. renderer->device,
  6954. D3D12_FEATURE_ARCHITECTURE,
  6955. &architecture,
  6956. sizeof(D3D12_FEATURE_DATA_ARCHITECTURE));
  6957. if (FAILED(res)) {
  6958. D3D12_INTERNAL_DestroyRenderer(renderer);
  6959. CHECK_D3D12_ERROR_AND_RETURN("Could not get device architecture", NULL);
  6960. }
  6961. renderer->UMA = (bool)architecture.UMA;
  6962. renderer->UMACacheCoherent = (bool)architecture.CacheCoherentUMA;
  6963. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  6964. renderer->GPUUploadHeapSupported = false;
  6965. #else
  6966. // Check "GPU Upload Heap" support (for fast uniform buffers)
  6967. D3D12_FEATURE_DATA_D3D12_OPTIONS16 options16; // 15 wasn't enough, huh?
  6968. renderer->GPUUploadHeapSupported = false;
  6969. res = ID3D12Device_CheckFeatureSupport(
  6970. renderer->device,
  6971. D3D12_FEATURE_D3D12_OPTIONS16,
  6972. &options16,
  6973. sizeof(options16));
  6974. if (SUCCEEDED(res)) {
  6975. renderer->GPUUploadHeapSupported = options16.GPUUploadHeapSupported;
  6976. }
  6977. #endif
  6978. // Create command queue
  6979. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  6980. if (s_CommandQueue != NULL) {
  6981. renderer->commandQueue = s_CommandQueue;
  6982. } else {
  6983. #endif
  6984. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  6985. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  6986. queueDesc.NodeMask = 0;
  6987. queueDesc.Priority = 0;
  6988. res = ID3D12Device_CreateCommandQueue(
  6989. renderer->device,
  6990. &queueDesc,
  6991. D3D_GUID(D3D_IID_ID3D12CommandQueue),
  6992. (void **)&renderer->commandQueue);
  6993. if (FAILED(res)) {
  6994. D3D12_INTERNAL_DestroyRenderer(renderer);
  6995. CHECK_D3D12_ERROR_AND_RETURN("Could not create D3D12CommandQueue", NULL);
  6996. }
  6997. #if (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  6998. s_CommandQueue = renderer->commandQueue;
  6999. }
  7000. #endif
  7001. // Create indirect command signatures
  7002. D3D12_COMMAND_SIGNATURE_DESC commandSignatureDesc;
  7003. D3D12_INDIRECT_ARGUMENT_DESC indirectArgumentDesc;
  7004. SDL_zero(indirectArgumentDesc);
  7005. indirectArgumentDesc.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW;
  7006. commandSignatureDesc.NodeMask = 0;
  7007. commandSignatureDesc.ByteStride = sizeof(SDL_GPUIndirectDrawCommand);
  7008. commandSignatureDesc.NumArgumentDescs = 1;
  7009. commandSignatureDesc.pArgumentDescs = &indirectArgumentDesc;
  7010. res = ID3D12Device_CreateCommandSignature(
  7011. renderer->device,
  7012. &commandSignatureDesc,
  7013. NULL,
  7014. D3D_GUID(D3D_IID_ID3D12CommandSignature),
  7015. (void **)&renderer->indirectDrawCommandSignature);
  7016. if (FAILED(res)) {
  7017. D3D12_INTERNAL_DestroyRenderer(renderer);
  7018. CHECK_D3D12_ERROR_AND_RETURN("Could not create indirect draw command signature", NULL)
  7019. }
  7020. indirectArgumentDesc.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED;
  7021. commandSignatureDesc.ByteStride = sizeof(SDL_GPUIndexedIndirectDrawCommand);
  7022. commandSignatureDesc.pArgumentDescs = &indirectArgumentDesc;
  7023. res = ID3D12Device_CreateCommandSignature(
  7024. renderer->device,
  7025. &commandSignatureDesc,
  7026. NULL,
  7027. D3D_GUID(D3D_IID_ID3D12CommandSignature),
  7028. (void **)&renderer->indirectIndexedDrawCommandSignature);
  7029. if (FAILED(res)) {
  7030. D3D12_INTERNAL_DestroyRenderer(renderer);
  7031. CHECK_D3D12_ERROR_AND_RETURN("Could not create indirect indexed draw command signature", NULL)
  7032. }
  7033. indirectArgumentDesc.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH;
  7034. commandSignatureDesc.ByteStride = sizeof(SDL_GPUIndirectDispatchCommand);
  7035. commandSignatureDesc.pArgumentDescs = &indirectArgumentDesc;
  7036. res = ID3D12Device_CreateCommandSignature(
  7037. renderer->device,
  7038. &commandSignatureDesc,
  7039. NULL,
  7040. D3D_GUID(D3D_IID_ID3D12CommandSignature),
  7041. (void **)&renderer->indirectDispatchCommandSignature);
  7042. if (FAILED(res)) {
  7043. D3D12_INTERNAL_DestroyRenderer(renderer);
  7044. CHECK_D3D12_ERROR_AND_RETURN("Could not create indirect dispatch command signature", NULL)
  7045. }
  7046. // Initialize pools
  7047. renderer->submittedCommandBufferCapacity = 4;
  7048. renderer->submittedCommandBufferCount = 0;
  7049. renderer->submittedCommandBuffers = (D3D12CommandBuffer **)SDL_calloc(
  7050. renderer->submittedCommandBufferCapacity, sizeof(D3D12CommandBuffer *));
  7051. if (!renderer->submittedCommandBuffers) {
  7052. D3D12_INTERNAL_DestroyRenderer(renderer);
  7053. return NULL;
  7054. }
  7055. renderer->uniformBufferPoolCapacity = 4;
  7056. renderer->uniformBufferPoolCount = 0;
  7057. renderer->uniformBufferPool = (D3D12UniformBuffer **)SDL_calloc(
  7058. renderer->uniformBufferPoolCapacity, sizeof(D3D12UniformBuffer *));
  7059. if (!renderer->uniformBufferPool) {
  7060. D3D12_INTERNAL_DestroyRenderer(renderer);
  7061. return NULL;
  7062. }
  7063. renderer->claimedWindowCapacity = 4;
  7064. renderer->claimedWindowCount = 0;
  7065. renderer->claimedWindows = (D3D12WindowData **)SDL_calloc(
  7066. renderer->claimedWindowCapacity, sizeof(D3D12WindowData *));
  7067. if (!renderer->claimedWindows) {
  7068. D3D12_INTERNAL_DestroyRenderer(renderer);
  7069. return NULL;
  7070. }
  7071. renderer->availableFenceCapacity = 4;
  7072. renderer->availableFenceCount = 0;
  7073. renderer->availableFences = (D3D12Fence **)SDL_calloc(
  7074. renderer->availableFenceCapacity, sizeof(D3D12Fence *));
  7075. if (!renderer->availableFences) {
  7076. D3D12_INTERNAL_DestroyRenderer(renderer);
  7077. return NULL;
  7078. }
  7079. // Initialize CPU descriptor heaps
  7080. for (Uint32 i = 0; i < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; i += 1) {
  7081. renderer->stagingDescriptorHeaps[i] = D3D12_INTERNAL_CreateDescriptorHeap(
  7082. renderer,
  7083. (D3D12_DESCRIPTOR_HEAP_TYPE)i,
  7084. (i <= D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) ? VIEW_SAMPLER_STAGING_DESCRIPTOR_COUNT : TARGET_STAGING_DESCRIPTOR_COUNT,
  7085. true);
  7086. if (renderer->stagingDescriptorHeaps[i] == NULL) {
  7087. D3D12_INTERNAL_DestroyRenderer(renderer);
  7088. return NULL;
  7089. }
  7090. }
  7091. // Initialize GPU descriptor heaps
  7092. for (Uint32 i = 0; i < 2; i += 1) {
  7093. renderer->descriptorHeapPools[i].lock = SDL_CreateMutex();
  7094. renderer->descriptorHeapPools[i].capacity = 4;
  7095. renderer->descriptorHeapPools[i].count = 4;
  7096. renderer->descriptorHeapPools[i].heaps = (D3D12DescriptorHeap **)SDL_calloc(
  7097. renderer->descriptorHeapPools[i].capacity, sizeof(D3D12DescriptorHeap *));
  7098. for (Uint32 j = 0; j < renderer->descriptorHeapPools[i].capacity; j += 1) {
  7099. renderer->descriptorHeapPools[i].heaps[j] = D3D12_INTERNAL_CreateDescriptorHeap(
  7100. renderer,
  7101. (D3D12_DESCRIPTOR_HEAP_TYPE)i,
  7102. i == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ? VIEW_GPU_DESCRIPTOR_COUNT : SAMPLER_GPU_DESCRIPTOR_COUNT,
  7103. false);
  7104. if (renderer->descriptorHeapPools[i].heaps[j] == NULL) {
  7105. D3D12_INTERNAL_DestroyRenderer(renderer);
  7106. return NULL;
  7107. }
  7108. }
  7109. }
  7110. // Deferred resource releasing
  7111. renderer->buffersToDestroyCapacity = 4;
  7112. renderer->buffersToDestroyCount = 0;
  7113. renderer->buffersToDestroy = (D3D12Buffer **)SDL_calloc(
  7114. renderer->buffersToDestroyCapacity, sizeof(D3D12Buffer *));
  7115. if (!renderer->buffersToDestroy) {
  7116. D3D12_INTERNAL_DestroyRenderer(renderer);
  7117. return NULL;
  7118. }
  7119. renderer->texturesToDestroyCapacity = 4;
  7120. renderer->texturesToDestroyCount = 0;
  7121. renderer->texturesToDestroy = (D3D12Texture **)SDL_calloc(
  7122. renderer->texturesToDestroyCapacity, sizeof(D3D12Texture *));
  7123. if (!renderer->texturesToDestroy) {
  7124. D3D12_INTERNAL_DestroyRenderer(renderer);
  7125. return NULL;
  7126. }
  7127. renderer->samplersToDestroyCapacity = 4;
  7128. renderer->samplersToDestroyCount = 0;
  7129. renderer->samplersToDestroy = (D3D12Sampler **)SDL_calloc(
  7130. renderer->samplersToDestroyCapacity, sizeof(D3D12Sampler *));
  7131. if (!renderer->samplersToDestroy) {
  7132. D3D12_INTERNAL_DestroyRenderer(renderer);
  7133. return NULL;
  7134. }
  7135. renderer->graphicsPipelinesToDestroyCapacity = 4;
  7136. renderer->graphicsPipelinesToDestroyCount = 0;
  7137. renderer->graphicsPipelinesToDestroy = (D3D12GraphicsPipeline **)SDL_calloc(
  7138. renderer->graphicsPipelinesToDestroyCapacity, sizeof(D3D12GraphicsPipeline *));
  7139. if (!renderer->graphicsPipelinesToDestroy) {
  7140. D3D12_INTERNAL_DestroyRenderer(renderer);
  7141. return NULL;
  7142. }
  7143. renderer->computePipelinesToDestroyCapacity = 4;
  7144. renderer->computePipelinesToDestroyCount = 0;
  7145. renderer->computePipelinesToDestroy = (D3D12ComputePipeline **)SDL_calloc(
  7146. renderer->computePipelinesToDestroyCapacity, sizeof(D3D12ComputePipeline *));
  7147. if (!renderer->computePipelinesToDestroy) {
  7148. D3D12_INTERNAL_DestroyRenderer(renderer);
  7149. return NULL;
  7150. }
  7151. // Locks
  7152. renderer->stagingDescriptorHeapLock = SDL_CreateMutex();
  7153. renderer->acquireCommandBufferLock = SDL_CreateMutex();
  7154. renderer->acquireUniformBufferLock = SDL_CreateMutex();
  7155. renderer->submitLock = SDL_CreateMutex();
  7156. renderer->windowLock = SDL_CreateMutex();
  7157. renderer->fenceLock = SDL_CreateMutex();
  7158. renderer->disposeLock = SDL_CreateMutex();
  7159. renderer->debug_mode = debugMode;
  7160. renderer->semantic = SDL_GetStringProperty(props, SDL_PROP_GPU_DEVICE_CREATE_D3D12_SEMANTIC_NAME_STRING, "TEXCOORD");
  7161. // Blit resources
  7162. D3D12_INTERNAL_InitBlitResources(renderer);
  7163. // Create the SDL_GPU Device
  7164. result = (SDL_GPUDevice *)SDL_calloc(1, sizeof(SDL_GPUDevice));
  7165. if (!result) {
  7166. D3D12_INTERNAL_DestroyRenderer(renderer);
  7167. return NULL;
  7168. }
  7169. ASSIGN_DRIVER(D3D12)
  7170. result->driverData = (SDL_GPURenderer *)renderer;
  7171. result->debug_mode = debugMode;
  7172. renderer->sdlGPUDevice = result;
  7173. return result;
  7174. }
  7175. SDL_GPUBootstrap D3D12Driver = {
  7176. "direct3d12",
  7177. SDL_GPU_SHADERFORMAT_DXIL,
  7178. D3D12_PrepareDriver,
  7179. D3D12_CreateDevice
  7180. };
  7181. #endif // SDL_GPU_D3D12
  7182. // GDK-specific APIs
  7183. #ifdef SDL_PLATFORM_GDK
  7184. void SDL_GDKSuspendGPU(SDL_GPUDevice *device)
  7185. {
  7186. #if defined(SDL_GPU_D3D12) && (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  7187. D3D12Renderer *renderer = (D3D12Renderer *)device->driverData;
  7188. HRESULT res;
  7189. if (device == NULL) {
  7190. SET_STRING_ERROR_AND_RETURN("Invalid GPU device", );
  7191. }
  7192. SDL_LockMutex(renderer->submitLock);
  7193. res = renderer->commandQueue->SuspendX(0);
  7194. if (FAILED(res)) {
  7195. SDL_LogError(SDL_LOG_CATEGORY_GPU, "SuspendX failed: %X", res);
  7196. }
  7197. SDL_UnlockMutex(renderer->submitLock);
  7198. #endif
  7199. }
  7200. void SDL_GDKResumeGPU(SDL_GPUDevice *device)
  7201. {
  7202. #if defined(SDL_GPU_D3D12) && (defined(SDL_PLATFORM_XBOXONE) || defined(SDL_PLATFORM_XBOXSERIES))
  7203. D3D12Renderer *renderer = (D3D12Renderer *)device->driverData;
  7204. HRESULT res;
  7205. if (device == NULL) {
  7206. SET_STRING_ERROR_AND_RETURN("Invalid GPU device", );
  7207. }
  7208. SDL_LockMutex(renderer->submitLock);
  7209. res = renderer->commandQueue->ResumeX();
  7210. if (FAILED(res)) {
  7211. SDL_LogError(SDL_LOG_CATEGORY_GPU, "ResumeX failed: %X", res);
  7212. }
  7213. SDL_UnlockMutex(renderer->submitLock);
  7214. res = renderer->device->SetFrameIntervalX(
  7215. NULL,
  7216. D3D12XBOX_FRAME_INTERVAL_60_HZ,
  7217. MAX_FRAMES_IN_FLIGHT - 1,
  7218. D3D12XBOX_FRAME_INTERVAL_FLAG_NONE);
  7219. if (FAILED(res)) {
  7220. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Could not set frame interval: %X", res);
  7221. }
  7222. res = renderer->device->ScheduleFrameEventX(
  7223. D3D12XBOX_FRAME_EVENT_ORIGIN,
  7224. 0,
  7225. NULL,
  7226. D3D12XBOX_SCHEDULE_FRAME_EVENT_FLAG_NONE);
  7227. if (FAILED(res)) {
  7228. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Could not schedule frame events: %X", res);
  7229. }
  7230. #endif
  7231. }
  7232. #endif // SDL_PLATFORM_GDK