SDL_gpu_d3d12.c 325 KB

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