SDL_gpu_d3d12.c 331 KB

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