rendering_device_driver_d3d12.cpp 288 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667
  1. /**************************************************************************/
  2. /* rendering_device_driver_d3d12.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "rendering_device_driver_d3d12.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/marshalls.h"
  33. #include "servers/rendering/rendering_device.h"
  34. #include "thirdparty/zlib/zlib.h"
  35. #include "d3d12_godot_nir_bridge.h"
  36. #include "dxil_hash.h"
  37. #include "rendering_context_driver_d3d12.h"
  38. // No point in fighting warnings in Mesa.
  39. #if defined(_MSC_VER)
  40. #pragma warning(push)
  41. #pragma warning(disable : 4200) // "nonstandard extension used: zero-sized array in struct/union".
  42. #pragma warning(disable : 4806) // "'&': unsafe operation: no value of type 'bool' promoted to type 'uint32_t' can equal the given constant".
  43. #endif
  44. #if defined(__GNUC__) && !defined(__clang__)
  45. #pragma GCC diagnostic push
  46. #pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
  47. #pragma GCC diagnostic ignored "-Wshadow"
  48. #pragma GCC diagnostic ignored "-Wswitch"
  49. #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  50. #elif defined(__clang__)
  51. #pragma clang diagnostic push
  52. #pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  53. #pragma clang diagnostic ignored "-Wstring-plus-int"
  54. #pragma clang diagnostic ignored "-Wswitch"
  55. #pragma clang diagnostic ignored "-Wmissing-field-initializers"
  56. #endif
  57. #include "nir_spirv.h"
  58. #include "nir_to_dxil.h"
  59. #include "spirv_to_dxil.h"
  60. extern "C" {
  61. #include "dxil_spirv_nir.h"
  62. }
  63. #if defined(__GNUC__) && !defined(__clang__)
  64. #pragma GCC diagnostic pop
  65. #elif defined(__clang__)
  66. #pragma clang diagnostic pop
  67. #endif
  68. #if defined(_MSC_VER)
  69. #pragma warning(pop)
  70. #endif
  71. #if !defined(_MSC_VER)
  72. #include <guiddef.h>
  73. #include <dxguids.h>
  74. #endif
  75. // Mesa may define this.
  76. #ifdef UNUSED
  77. #undef UNUSED
  78. #endif
  79. #ifdef PIX_ENABLED
  80. #if defined(__GNUC__)
  81. #define _MSC_VER 1800
  82. #endif
  83. #define USE_PIX
  84. #include "WinPixEventRuntime/pix3.h"
  85. #if defined(__GNUC__)
  86. #undef _MSC_VER
  87. #endif
  88. #endif
  89. static const D3D12_RANGE VOID_RANGE = {};
  90. static const uint32_t ROOT_CONSTANT_REGISTER = GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER * (RDD::MAX_UNIFORM_SETS + 1);
  91. static const uint32_t RUNTIME_DATA_REGISTER = GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER * (RDD::MAX_UNIFORM_SETS + 2);
  92. /*****************/
  93. /**** GENERIC ****/
  94. /*****************/
  95. // NOTE: RD's packed format names are reversed in relation to DXGI's; e.g.:.
  96. // - DATA_FORMAT_A8B8G8R8_UNORM_PACK32 -> DXGI_FORMAT_R8G8B8A8_UNORM (packed; note ABGR vs. RGBA).
  97. // - DATA_FORMAT_B8G8R8A8_UNORM -> DXGI_FORMAT_B8G8R8A8_UNORM (not packed; note BGRA order matches).
  98. // TODO: Add YUV formats properly, which would require better support for planes in the RD API.
  99. const RenderingDeviceDriverD3D12::D3D12Format RenderingDeviceDriverD3D12::RD_TO_D3D12_FORMAT[RDD::DATA_FORMAT_MAX] = {
  100. /* DATA_FORMAT_R4G4_UNORM_PACK8 */ {},
  101. /* DATA_FORMAT_R4G4B4A4_UNORM_PACK16 */ { DXGI_FORMAT_B4G4R4A4_UNORM, DXGI_FORMAT_B4G4R4A4_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(1, 2, 3, 0) },
  102. /* DATA_FORMAT_B4G4R4A4_UNORM_PACK16 */ { DXGI_FORMAT_B4G4R4A4_UNORM, DXGI_FORMAT_B4G4R4A4_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(3, 2, 1, 0) },
  103. /* DATA_FORMAT_R5G6B5_UNORM_PACK16 */ { DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G6R5_UNORM },
  104. /* DATA_FORMAT_B5G6R5_UNORM_PACK16 */ { DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G6R5_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(2, 1, 0, 3) },
  105. /* DATA_FORMAT_R5G5B5A1_UNORM_PACK16 */ { DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(1, 2, 3, 0) },
  106. /* DATA_FORMAT_B5G5R5A1_UNORM_PACK16 */ { DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(3, 2, 1, 0) },
  107. /* DATA_FORMAT_A1R5G5B5_UNORM_PACK16 */ { DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM },
  108. /* DATA_FORMAT_R8_UNORM */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_UNORM },
  109. /* DATA_FORMAT_R8_SNORM */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_SNORM },
  110. /* DATA_FORMAT_R8_USCALED */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_UINT },
  111. /* DATA_FORMAT_R8_SSCALED */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_SINT },
  112. /* DATA_FORMAT_R8_UINT */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_UINT },
  113. /* DATA_FORMAT_R8_SINT */ { DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_SINT },
  114. /* DATA_FORMAT_R8_SRGB */ {},
  115. /* DATA_FORMAT_R8G8_UNORM */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UNORM },
  116. /* DATA_FORMAT_R8G8_SNORM */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_SNORM },
  117. /* DATA_FORMAT_R8G8_USCALED */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UINT },
  118. /* DATA_FORMAT_R8G8_SSCALED */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_SINT },
  119. /* DATA_FORMAT_R8G8_UINT */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UINT },
  120. /* DATA_FORMAT_R8G8_SINT */ { DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_SINT },
  121. /* DATA_FORMAT_R8G8_SRGB */ {},
  122. /* DATA_FORMAT_R8G8B8_UNORM */ {},
  123. /* DATA_FORMAT_R8G8B8_SNORM */ {},
  124. /* DATA_FORMAT_R8G8B8_USCALED */ {},
  125. /* DATA_FORMAT_R8G8B8_SSCALED */ {},
  126. /* DATA_FORMAT_R8G8B8_UINT */ {},
  127. /* DATA_FORMAT_R8G8B8_SINT */ {},
  128. /* DATA_FORMAT_R8G8B8_SRGB */ {},
  129. /* DATA_FORMAT_B8G8R8_UNORM */ {},
  130. /* DATA_FORMAT_B8G8R8_SNORM */ {},
  131. /* DATA_FORMAT_B8G8R8_USCALED */ {},
  132. /* DATA_FORMAT_B8G8R8_SSCALED */ {},
  133. /* DATA_FORMAT_B8G8R8_UINT */ {},
  134. /* DATA_FORMAT_B8G8R8_SINT */ {},
  135. /* DATA_FORMAT_B8G8R8_SRGB */ {},
  136. /* DATA_FORMAT_R8G8B8A8_UNORM */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM },
  137. /* DATA_FORMAT_R8G8B8A8_SNORM */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SNORM },
  138. /* DATA_FORMAT_R8G8B8A8_USCALED */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT },
  139. /* DATA_FORMAT_R8G8B8A8_SSCALED */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT },
  140. /* DATA_FORMAT_R8G8B8A8_UINT */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT },
  141. /* DATA_FORMAT_R8G8B8A8_SINT */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT },
  142. /* DATA_FORMAT_R8G8B8A8_SRGB */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB },
  143. /* DATA_FORMAT_B8G8R8A8_UNORM */ { DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_UNORM },
  144. /* DATA_FORMAT_B8G8R8A8_SNORM */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SNORM },
  145. /* DATA_FORMAT_B8G8R8A8_USCALED */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT },
  146. /* DATA_FORMAT_B8G8R8A8_SSCALED */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT },
  147. /* DATA_FORMAT_B8G8R8A8_UINT */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT },
  148. /* DATA_FORMAT_B8G8R8A8_SINT */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT },
  149. /* DATA_FORMAT_B8G8R8A8_SRGB */ { DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB },
  150. /* DATA_FORMAT_A8B8G8R8_UNORM_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM },
  151. /* DATA_FORMAT_A8B8G8R8_SNORM_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SNORM },
  152. /* DATA_FORMAT_A8B8G8R8_USCALED_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT },
  153. /* DATA_FORMAT_A8B8G8R8_SSCALED_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT },
  154. /* DATA_FORMAT_A8B8G8R8_UINT_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UINT },
  155. /* DATA_FORMAT_A8B8G8R8_SINT_PACK32 */ { DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_SINT },
  156. /* DATA_FORMAT_A8B8G8R8_SRGB_PACK32 */ { DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB },
  157. /* DATA_FORMAT_A2R10G10B10_UNORM_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(2, 1, 0, 3) },
  158. /* DATA_FORMAT_A2R10G10B10_SNORM_PACK32 */ {},
  159. /* DATA_FORMAT_A2R10G10B10_USCALED_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UINT, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(2, 1, 0, 3) },
  160. /* DATA_FORMAT_A2R10G10B10_SSCALED_PACK32 */ {},
  161. /* DATA_FORMAT_A2R10G10B10_UINT_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UINT, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(2, 1, 0, 3) },
  162. /* DATA_FORMAT_A2R10G10B10_SINT_PACK32 */ {},
  163. /* DATA_FORMAT_A2B10G10R10_UNORM_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UNORM },
  164. /* DATA_FORMAT_A2B10G10R10_SNORM_PACK32 */ {},
  165. /* DATA_FORMAT_A2B10G10R10_USCALED_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UINT },
  166. /* DATA_FORMAT_A2B10G10R10_SSCALED_PACK32 */ {},
  167. /* DATA_FORMAT_A2B10G10R10_UINT_PACK32 */ { DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UINT },
  168. /* DATA_FORMAT_A2B10G10R10_SINT_PACK32 */ {},
  169. /* DATA_FORMAT_R16_UNORM */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UNORM },
  170. /* DATA_FORMAT_R16_SNORM */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_SNORM },
  171. /* DATA_FORMAT_R16_USCALED */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UINT },
  172. /* DATA_FORMAT_R16_SSCALED */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_SINT },
  173. /* DATA_FORMAT_R16_UINT */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UINT },
  174. /* DATA_FORMAT_R16_SINT */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_SINT },
  175. /* DATA_FORMAT_R16_SFLOAT */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_FLOAT },
  176. /* DATA_FORMAT_R16G16_UNORM */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_UNORM },
  177. /* DATA_FORMAT_R16G16_SNORM */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_SNORM },
  178. /* DATA_FORMAT_R16G16_USCALED */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_UINT },
  179. /* DATA_FORMAT_R16G16_SSCALED */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_SINT },
  180. /* DATA_FORMAT_R16G16_UINT */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_UINT },
  181. /* DATA_FORMAT_R16G16_SINT */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_SINT },
  182. /* DATA_FORMAT_R16G16_SFLOAT */ { DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_FLOAT },
  183. /* DATA_FORMAT_R16G16B16_UNORM */ {},
  184. /* DATA_FORMAT_R16G16B16_SNORM */ {},
  185. /* DATA_FORMAT_R16G16B16_USCALED */ {},
  186. /* DATA_FORMAT_R16G16B16_SSCALED */ {},
  187. /* DATA_FORMAT_R16G16B16_UINT */ {},
  188. /* DATA_FORMAT_R16G16B16_SINT */ {},
  189. /* DATA_FORMAT_R16G16B16_SFLOAT */ {},
  190. /* DATA_FORMAT_R16G16B16A16_UNORM */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UNORM },
  191. /* DATA_FORMAT_R16G16B16A16_SNORM */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_SNORM },
  192. /* DATA_FORMAT_R16G16B16A16_USCALED */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UINT },
  193. /* DATA_FORMAT_R16G16B16A16_SSCALED */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_SINT },
  194. /* DATA_FORMAT_R16G16B16A16_UINT */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UINT },
  195. /* DATA_FORMAT_R16G16B16A16_SINT */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_SINT },
  196. /* DATA_FORMAT_R16G16B16A16_SFLOAT */ { DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_FLOAT },
  197. /* DATA_FORMAT_R32_UINT */ { DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_UINT },
  198. /* DATA_FORMAT_R32_SINT */ { DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_SINT },
  199. /* DATA_FORMAT_R32_SFLOAT */ { DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_FLOAT },
  200. /* DATA_FORMAT_R32G32_UINT */ { DXGI_FORMAT_R32G32_TYPELESS, DXGI_FORMAT_R32G32_UINT },
  201. /* DATA_FORMAT_R32G32_SINT */ { DXGI_FORMAT_R32G32_TYPELESS, DXGI_FORMAT_R32G32_SINT },
  202. /* DATA_FORMAT_R32G32_SFLOAT */ { DXGI_FORMAT_R32G32_TYPELESS, DXGI_FORMAT_R32G32_FLOAT },
  203. /* DATA_FORMAT_R32G32B32_UINT */ { DXGI_FORMAT_R32G32B32_TYPELESS, DXGI_FORMAT_R32G32B32_UINT },
  204. /* DATA_FORMAT_R32G32B32_SINT */ { DXGI_FORMAT_R32G32B32_TYPELESS, DXGI_FORMAT_R32G32B32_SINT },
  205. /* DATA_FORMAT_R32G32B32_SFLOAT */ { DXGI_FORMAT_R32G32B32_TYPELESS, DXGI_FORMAT_R32G32B32_FLOAT },
  206. /* DATA_FORMAT_R32G32B32A32_UINT */ { DXGI_FORMAT_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32A32_UINT },
  207. /* DATA_FORMAT_R32G32B32A32_SINT */ { DXGI_FORMAT_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32A32_SINT },
  208. /* DATA_FORMAT_R32G32B32A32_SFLOAT */ { DXGI_FORMAT_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32A32_FLOAT },
  209. /* DATA_FORMAT_R64_UINT */ {},
  210. /* DATA_FORMAT_R64_SINT */ {},
  211. /* DATA_FORMAT_R64_SFLOAT */ {},
  212. /* DATA_FORMAT_R64G64_UINT */ {},
  213. /* DATA_FORMAT_R64G64_SINT */ {},
  214. /* DATA_FORMAT_R64G64_SFLOAT */ {},
  215. /* DATA_FORMAT_R64G64B64_UINT */ {},
  216. /* DATA_FORMAT_R64G64B64_SINT */ {},
  217. /* DATA_FORMAT_R64G64B64_SFLOAT */ {},
  218. /* DATA_FORMAT_R64G64B64A64_UINT */ {},
  219. /* DATA_FORMAT_R64G64B64A64_SINT */ {},
  220. /* DATA_FORMAT_R64G64B64A64_SFLOAT */ {},
  221. /* DATA_FORMAT_B10G11R11_UFLOAT_PACK32 */ { DXGI_FORMAT_R11G11B10_FLOAT, DXGI_FORMAT_R11G11B10_FLOAT },
  222. /* DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32 */ { DXGI_FORMAT_R9G9B9E5_SHAREDEXP, DXGI_FORMAT_R9G9B9E5_SHAREDEXP },
  223. /* DATA_FORMAT_D16_UNORM */ { DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UNORM, 0, DXGI_FORMAT_D16_UNORM },
  224. /* DATA_FORMAT_X8_D24_UNORM_PACK32 */ { DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_UNKNOWN, 0, DXGI_FORMAT_D24_UNORM_S8_UINT },
  225. /* DATA_FORMAT_D32_SFLOAT */ { DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_FLOAT, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, DXGI_FORMAT_D32_FLOAT },
  226. /* DATA_FORMAT_S8_UINT */ {},
  227. /* DATA_FORMAT_D16_UNORM_S8_UINT */ {},
  228. /* DATA_FORMAT_D24_UNORM_S8_UINT */ { DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_UNKNOWN, 0, DXGI_FORMAT_D24_UNORM_S8_UINT },
  229. /* DATA_FORMAT_D32_SFLOAT_S8_UINT */ { DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, DXGI_FORMAT_D32_FLOAT_S8X24_UINT },
  230. /* DATA_FORMAT_BC1_RGB_UNORM_BLOCK */ { DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 1, 2, D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1) },
  231. /* DATA_FORMAT_BC1_RGB_SRGB_BLOCK */ { DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM_SRGB, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 1, 2, D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1) },
  232. /* DATA_FORMAT_BC1_RGBA_UNORM_BLOCK */ { DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM },
  233. /* DATA_FORMAT_BC1_RGBA_SRGB_BLOCK */ { DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM_SRGB },
  234. /* DATA_FORMAT_BC2_UNORM_BLOCK */ { DXGI_FORMAT_BC2_TYPELESS, DXGI_FORMAT_BC2_UNORM },
  235. /* DATA_FORMAT_BC2_SRGB_BLOCK */ { DXGI_FORMAT_BC2_TYPELESS, DXGI_FORMAT_BC2_UNORM_SRGB },
  236. /* DATA_FORMAT_BC3_UNORM_BLOCK */ { DXGI_FORMAT_BC3_TYPELESS, DXGI_FORMAT_BC3_UNORM },
  237. /* DATA_FORMAT_BC3_SRGB_BLOCK */ { DXGI_FORMAT_BC3_TYPELESS, DXGI_FORMAT_BC3_UNORM_SRGB },
  238. /* DATA_FORMAT_BC4_UNORM_BLOCK */ { DXGI_FORMAT_BC4_TYPELESS, DXGI_FORMAT_BC4_UNORM },
  239. /* DATA_FORMAT_BC4_SNORM_BLOCK */ { DXGI_FORMAT_BC4_TYPELESS, DXGI_FORMAT_BC4_SNORM },
  240. /* DATA_FORMAT_BC5_UNORM_BLOCK */ { DXGI_FORMAT_BC5_TYPELESS, DXGI_FORMAT_BC5_UNORM },
  241. /* DATA_FORMAT_BC5_SNORM_BLOCK */ { DXGI_FORMAT_BC5_TYPELESS, DXGI_FORMAT_BC5_SNORM },
  242. /* DATA_FORMAT_BC6H_UFLOAT_BLOCK */ { DXGI_FORMAT_BC6H_TYPELESS, DXGI_FORMAT_BC6H_UF16 },
  243. /* DATA_FORMAT_BC6H_SFLOAT_BLOCK */ { DXGI_FORMAT_BC6H_TYPELESS, DXGI_FORMAT_BC6H_SF16 },
  244. /* DATA_FORMAT_BC7_UNORM_BLOCK */ { DXGI_FORMAT_BC7_TYPELESS, DXGI_FORMAT_BC7_UNORM },
  245. /* DATA_FORMAT_BC7_SRGB_BLOCK */ { DXGI_FORMAT_BC7_TYPELESS, DXGI_FORMAT_BC7_UNORM_SRGB },
  246. /* DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK */ {},
  247. /* DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK */ {},
  248. /* DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK */ {},
  249. /* DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK */ {},
  250. /* DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK */ {},
  251. /* DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK */ {},
  252. /* DATA_FORMAT_EAC_R11_UNORM_BLOCK */ {},
  253. /* DATA_FORMAT_EAC_R11_SNORM_BLOCK */ {},
  254. /* DATA_FORMAT_EAC_R11G11_UNORM_BLOCK */ {},
  255. /* DATA_FORMAT_EAC_R11G11_SNORM_BLOCK */ {},
  256. /* DATA_FORMAT_ASTC_4x4_UNORM_BLOCK */ {},
  257. /* DATA_FORMAT_ASTC_4x4_SRGB_BLOCK */ {},
  258. /* DATA_FORMAT_ASTC_5x4_UNORM_BLOCK */ {},
  259. /* DATA_FORMAT_ASTC_5x4_SRGB_BLOCK */ {},
  260. /* DATA_FORMAT_ASTC_5x5_UNORM_BLOCK */ {},
  261. /* DATA_FORMAT_ASTC_5x5_SRGB_BLOCK */ {},
  262. /* DATA_FORMAT_ASTC_6x5_UNORM_BLOCK */ {},
  263. /* DATA_FORMAT_ASTC_6x5_SRGB_BLOCK */ {},
  264. /* DATA_FORMAT_ASTC_6x6_UNORM_BLOCK */ {},
  265. /* DATA_FORMAT_ASTC_6x6_SRGB_BLOCK */ {},
  266. /* DATA_FORMAT_ASTC_8x5_UNORM_BLOCK */ {},
  267. /* DATA_FORMAT_ASTC_8x5_SRGB_BLOCK */ {},
  268. /* DATA_FORMAT_ASTC_8x6_UNORM_BLOCK */ {},
  269. /* DATA_FORMAT_ASTC_8x6_SRGB_BLOCK */ {},
  270. /* DATA_FORMAT_ASTC_8x8_UNORM_BLOCK */ {},
  271. /* DATA_FORMAT_ASTC_8x8_SRGB_BLOCK */ {},
  272. /* DATA_FORMAT_ASTC_10x5_UNORM_BLOCK */ {},
  273. /* DATA_FORMAT_ASTC_10x5_SRGB_BLOCK */ {},
  274. /* DATA_FORMAT_ASTC_10x6_UNORM_BLOCK */ {},
  275. /* DATA_FORMAT_ASTC_10x6_SRGB_BLOCK */ {},
  276. /* DATA_FORMAT_ASTC_10x8_UNORM_BLOCK */ {},
  277. /* DATA_FORMAT_ASTC_10x8_SRGB_BLOCK */ {},
  278. /* DATA_FORMAT_ASTC_10x10_UNORM_BLOCK */ {},
  279. /* DATA_FORMAT_ASTC_10x10_SRGB_BLOCK */ {},
  280. /* DATA_FORMAT_ASTC_12x10_UNORM_BLOCK */ {},
  281. /* DATA_FORMAT_ASTC_12x10_SRGB_BLOCK */ {},
  282. /* DATA_FORMAT_ASTC_12x12_UNORM_BLOCK */ {},
  283. /* DATA_FORMAT_ASTC_12x12_SRGB_BLOCK */ {},
  284. /* DATA_FORMAT_G8B8G8R8_422_UNORM */ {},
  285. /* DATA_FORMAT_B8G8R8G8_422_UNORM */ {},
  286. /* DATA_FORMAT_G8_B8_R8_3PLANE_420_UNORM */ {},
  287. /* DATA_FORMAT_G8_B8R8_2PLANE_420_UNORM */ {},
  288. /* DATA_FORMAT_G8_B8_R8_3PLANE_422_UNORM */ {},
  289. /* DATA_FORMAT_G8_B8R8_2PLANE_422_UNORM */ {},
  290. /* DATA_FORMAT_G8_B8_R8_3PLANE_444_UNORM */ {},
  291. /* DATA_FORMAT_R10X6_UNORM_PACK16 */ {},
  292. /* DATA_FORMAT_R10X6G10X6_UNORM_2PACK16 */ {},
  293. /* DATA_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16 */ {},
  294. /* DATA_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16 */ {},
  295. /* DATA_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16 */ {},
  296. /* DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16 */ {},
  297. /* DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16 */ {},
  298. /* DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16 */ {},
  299. /* DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16 */ {},
  300. /* DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16 */ {},
  301. /* DATA_FORMAT_R12X4_UNORM_PACK16 */ {},
  302. /* DATA_FORMAT_R12X4G12X4_UNORM_2PACK16 */ {},
  303. /* DATA_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16 */ {},
  304. /* DATA_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16 */ {},
  305. /* DATA_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16 */ {},
  306. /* DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16 */ {},
  307. /* DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16 */ {},
  308. /* DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16 */ {},
  309. /* DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16 */ {},
  310. /* DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16 */ {},
  311. /* DATA_FORMAT_G16B16G16R16_422_UNORM */ {},
  312. /* DATA_FORMAT_B16G16R16G16_422_UNORM */ {},
  313. /* DATA_FORMAT_G16_B16_R16_3PLANE_420_UNORM */ {},
  314. /* DATA_FORMAT_G16_B16R16_2PLANE_420_UNORM */ {},
  315. /* DATA_FORMAT_G16_B16_R16_3PLANE_422_UNORM */ {},
  316. /* DATA_FORMAT_G16_B16R16_2PLANE_422_UNORM */ {},
  317. /* DATA_FORMAT_G16_B16_R16_3PLANE_444_UNORM */ {},
  318. };
  319. Error RenderingDeviceDriverD3D12::DescriptorsHeap::allocate(ID3D12Device *p_device, D3D12_DESCRIPTOR_HEAP_TYPE p_type, uint32_t p_descriptor_count, bool p_for_gpu) {
  320. ERR_FAIL_COND_V(heap, ERR_ALREADY_EXISTS);
  321. ERR_FAIL_COND_V(p_descriptor_count == 0, ERR_INVALID_PARAMETER);
  322. handle_size = p_device->GetDescriptorHandleIncrementSize(p_type);
  323. desc.Type = p_type;
  324. desc.NumDescriptors = p_descriptor_count;
  325. desc.Flags = p_for_gpu ? D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE : D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
  326. HRESULT res = p_device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(heap.GetAddressOf()));
  327. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ERR_CANT_CREATE, "CreateDescriptorHeap failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  328. return OK;
  329. }
  330. RenderingDeviceDriverD3D12::DescriptorsHeap::Walker RenderingDeviceDriverD3D12::DescriptorsHeap::make_walker() const {
  331. Walker walker;
  332. walker.handle_size = handle_size;
  333. walker.handle_count = desc.NumDescriptors;
  334. if (heap) {
  335. #if defined(_MSC_VER) || !defined(_WIN32)
  336. walker.first_cpu_handle = heap->GetCPUDescriptorHandleForHeapStart();
  337. if ((desc.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) {
  338. walker.first_gpu_handle = heap->GetGPUDescriptorHandleForHeapStart();
  339. }
  340. #else
  341. heap->GetCPUDescriptorHandleForHeapStart(&walker.first_cpu_handle);
  342. if ((desc.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) {
  343. heap->GetGPUDescriptorHandleForHeapStart(&walker.first_gpu_handle);
  344. }
  345. #endif
  346. }
  347. return walker;
  348. }
  349. void RenderingDeviceDriverD3D12::DescriptorsHeap::Walker::advance(uint32_t p_count) {
  350. ERR_FAIL_COND_MSG(handle_index + p_count > handle_count, "Would advance past EOF.");
  351. handle_index += p_count;
  352. }
  353. D3D12_CPU_DESCRIPTOR_HANDLE RenderingDeviceDriverD3D12::DescriptorsHeap::Walker::get_curr_cpu_handle() {
  354. ERR_FAIL_COND_V_MSG(is_at_eof(), D3D12_CPU_DESCRIPTOR_HANDLE(), "Heap walker is at EOF.");
  355. return D3D12_CPU_DESCRIPTOR_HANDLE{ first_cpu_handle.ptr + handle_index * handle_size };
  356. }
  357. D3D12_GPU_DESCRIPTOR_HANDLE RenderingDeviceDriverD3D12::DescriptorsHeap::Walker::get_curr_gpu_handle() {
  358. ERR_FAIL_COND_V_MSG(!first_gpu_handle.ptr, D3D12_GPU_DESCRIPTOR_HANDLE(), "Can't provide a GPU handle from a non-GPU descriptors heap.");
  359. ERR_FAIL_COND_V_MSG(is_at_eof(), D3D12_GPU_DESCRIPTOR_HANDLE(), "Heap walker is at EOF.");
  360. return D3D12_GPU_DESCRIPTOR_HANDLE{ first_gpu_handle.ptr + handle_index * handle_size };
  361. }
  362. static const D3D12_COMPARISON_FUNC RD_TO_D3D12_COMPARE_OP[RD::COMPARE_OP_MAX] = {
  363. D3D12_COMPARISON_FUNC_NEVER,
  364. D3D12_COMPARISON_FUNC_LESS,
  365. D3D12_COMPARISON_FUNC_EQUAL,
  366. D3D12_COMPARISON_FUNC_LESS_EQUAL,
  367. D3D12_COMPARISON_FUNC_GREATER,
  368. D3D12_COMPARISON_FUNC_NOT_EQUAL,
  369. D3D12_COMPARISON_FUNC_GREATER_EQUAL,
  370. D3D12_COMPARISON_FUNC_ALWAYS,
  371. };
  372. uint32_t RenderingDeviceDriverD3D12::SubgroupCapabilities::supported_stages_flags_rd() const {
  373. // If there's a way to check exactly which are supported, I have yet to find it.
  374. return (
  375. RenderingDevice::ShaderStage::SHADER_STAGE_FRAGMENT_BIT |
  376. RenderingDevice::ShaderStage::SHADER_STAGE_COMPUTE_BIT);
  377. }
  378. uint32_t RenderingDeviceDriverD3D12::SubgroupCapabilities::supported_operations_flags_rd() const {
  379. if (!wave_ops_supported) {
  380. return 0;
  381. } else {
  382. return (
  383. RenderingDevice::SubgroupOperations::SUBGROUP_BASIC_BIT |
  384. RenderingDevice::SubgroupOperations::SUBGROUP_BALLOT_BIT |
  385. RenderingDevice::SubgroupOperations::SUBGROUP_VOTE_BIT |
  386. RenderingDevice::SubgroupOperations::SUBGROUP_SHUFFLE_BIT |
  387. RenderingDevice::SubgroupOperations::SUBGROUP_SHUFFLE_RELATIVE_BIT |
  388. RenderingDevice::SubgroupOperations::SUBGROUP_QUAD_BIT |
  389. RenderingDevice::SubgroupOperations::SUBGROUP_ARITHMETIC_BIT |
  390. RenderingDevice::SubgroupOperations::SUBGROUP_CLUSTERED_BIT);
  391. }
  392. }
  393. void RenderingDeviceDriverD3D12::_debug_message_func(D3D12_MESSAGE_CATEGORY p_category, D3D12_MESSAGE_SEVERITY p_severity, D3D12_MESSAGE_ID p_id, LPCSTR p_description, void *p_context) {
  394. String type_string;
  395. switch (p_category) {
  396. case D3D12_MESSAGE_CATEGORY_APPLICATION_DEFINED:
  397. type_string = "APPLICATION_DEFINED";
  398. break;
  399. case D3D12_MESSAGE_CATEGORY_MISCELLANEOUS:
  400. type_string = "MISCELLANEOUS";
  401. break;
  402. case D3D12_MESSAGE_CATEGORY_INITIALIZATION:
  403. type_string = "INITIALIZATION";
  404. break;
  405. case D3D12_MESSAGE_CATEGORY_CLEANUP:
  406. type_string = "CLEANUP";
  407. break;
  408. case D3D12_MESSAGE_CATEGORY_COMPILATION:
  409. type_string = "COMPILATION";
  410. break;
  411. case D3D12_MESSAGE_CATEGORY_STATE_CREATION:
  412. type_string = "STATE_CREATION";
  413. break;
  414. case D3D12_MESSAGE_CATEGORY_STATE_SETTING:
  415. type_string = "STATE_SETTING";
  416. break;
  417. case D3D12_MESSAGE_CATEGORY_STATE_GETTING:
  418. type_string = "STATE_GETTING";
  419. break;
  420. case D3D12_MESSAGE_CATEGORY_RESOURCE_MANIPULATION:
  421. type_string = "RESOURCE_MANIPULATION";
  422. break;
  423. case D3D12_MESSAGE_CATEGORY_EXECUTION:
  424. type_string = "EXECUTION";
  425. break;
  426. case D3D12_MESSAGE_CATEGORY_SHADER:
  427. type_string = "SHADER";
  428. break;
  429. }
  430. String error_message(type_string +
  431. " - Message Id Number: " + String::num_int64(p_id) +
  432. "\n\t" + p_description);
  433. // Convert D3D12 severity to our own log macros.
  434. switch (p_severity) {
  435. case D3D12_MESSAGE_SEVERITY_MESSAGE:
  436. print_verbose(error_message);
  437. break;
  438. case D3D12_MESSAGE_SEVERITY_INFO:
  439. print_line(error_message);
  440. break;
  441. case D3D12_MESSAGE_SEVERITY_WARNING:
  442. WARN_PRINT(error_message);
  443. break;
  444. case D3D12_MESSAGE_SEVERITY_ERROR:
  445. case D3D12_MESSAGE_SEVERITY_CORRUPTION:
  446. ERR_PRINT(error_message);
  447. CRASH_COND_MSG(Engine::get_singleton()->is_abort_on_gpu_errors_enabled(),
  448. "Crashing, because abort on GPU errors is enabled.");
  449. break;
  450. }
  451. }
  452. /******************/
  453. /**** RESOURCE ****/
  454. /******************/
  455. static const D3D12_RESOURCE_DIMENSION RD_TEXTURE_TYPE_TO_D3D12_RESOURCE_DIMENSION[RD::TEXTURE_TYPE_MAX] = {
  456. D3D12_RESOURCE_DIMENSION_TEXTURE1D,
  457. D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  458. D3D12_RESOURCE_DIMENSION_TEXTURE3D,
  459. D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  460. D3D12_RESOURCE_DIMENSION_TEXTURE1D,
  461. D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  462. D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  463. };
  464. void RenderingDeviceDriverD3D12::_resource_transition_batch(CommandBufferInfo *p_command_buffer, ResourceInfo *p_resource, uint32_t p_subresource, uint32_t p_num_planes, D3D12_RESOURCE_STATES p_new_state) {
  465. DEV_ASSERT(p_subresource != UINT32_MAX); // We don't support an "all-resources" command here.
  466. ResourceInfo::States *res_states = p_resource->states_ptr;
  467. D3D12_RESOURCE_STATES *curr_state = &res_states->subresource_states[p_subresource];
  468. // Transitions can be considered redundant if the current state has all the bits of the new state.
  469. // This check does not apply to the common state however, which must resort to checking if the state is the same (0).
  470. bool any_state_is_common = *curr_state == D3D12_RESOURCE_STATE_COMMON || p_new_state == D3D12_RESOURCE_STATE_COMMON;
  471. bool redundant_transition = any_state_is_common ? *curr_state == p_new_state : ((*curr_state) & p_new_state) == p_new_state;
  472. if (redundant_transition) {
  473. bool just_written = *curr_state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  474. bool needs_uav_barrier = just_written && res_states->last_batch_with_uav_barrier != p_command_buffer->res_barriers_batch;
  475. if (needs_uav_barrier) {
  476. if (p_command_buffer->res_barriers.size() < p_command_buffer->res_barriers_count + 1) {
  477. p_command_buffer->res_barriers.resize(p_command_buffer->res_barriers_count + 1);
  478. }
  479. p_command_buffer->res_barriers[p_command_buffer->res_barriers_count] = CD3DX12_RESOURCE_BARRIER::UAV(p_resource->resource);
  480. p_command_buffer->res_barriers_count++;
  481. res_states->last_batch_with_uav_barrier = p_command_buffer->res_barriers_batch;
  482. }
  483. } else {
  484. uint64_t subres_mask_piece = ((uint64_t)1 << (p_subresource & 0b111111));
  485. uint8_t subres_qword = p_subresource >> 6;
  486. if (p_command_buffer->res_barriers_requests.has(res_states)) {
  487. BarrierRequest &br = p_command_buffer->res_barriers_requests.get(res_states);
  488. DEV_ASSERT(br.dx_resource == p_resource->resource);
  489. DEV_ASSERT(br.subres_mask_qwords == STEPIFY(res_states->subresource_states.size(), 64) / 64);
  490. DEV_ASSERT(br.planes == p_num_planes);
  491. // First, find if the subresource already has a barrier scheduled.
  492. uint8_t curr_group_idx = 0;
  493. bool same_transition_scheduled = false;
  494. for (curr_group_idx = 0; curr_group_idx < br.groups_count; curr_group_idx++) {
  495. if (unlikely(br.groups[curr_group_idx].states == BarrierRequest::DELETED_GROUP)) {
  496. continue;
  497. }
  498. if ((br.groups[curr_group_idx].subres_mask[subres_qword] & subres_mask_piece)) {
  499. uint32_t state_mask = br.groups[curr_group_idx].states;
  500. same_transition_scheduled = (state_mask & (uint32_t)p_new_state) == (uint32_t)p_new_state;
  501. break;
  502. }
  503. }
  504. if (!same_transition_scheduled) {
  505. bool subres_already_there = curr_group_idx != br.groups_count;
  506. D3D12_RESOURCE_STATES final_states = {};
  507. if (subres_already_there) {
  508. final_states = br.groups[curr_group_idx].states;
  509. final_states |= p_new_state;
  510. bool subres_alone = true;
  511. for (uint8_t i = 0; i < br.subres_mask_qwords; i++) {
  512. if (i == subres_qword) {
  513. if (br.groups[curr_group_idx].subres_mask[i] != subres_mask_piece) {
  514. subres_alone = false;
  515. break;
  516. }
  517. } else {
  518. if (br.groups[curr_group_idx].subres_mask[i] != 0) {
  519. subres_alone = false;
  520. break;
  521. }
  522. }
  523. }
  524. bool relocated = false;
  525. if (subres_alone) {
  526. // Subresource is there by itself.
  527. for (uint8_t i = 0; i < br.groups_count; i++) {
  528. if (unlikely(i == curr_group_idx)) {
  529. continue;
  530. }
  531. if (unlikely(br.groups[i].states == BarrierRequest::DELETED_GROUP)) {
  532. continue;
  533. }
  534. // There's another group with the final states; relocate to it.
  535. if (br.groups[i].states == final_states) {
  536. br.groups[curr_group_idx].subres_mask[subres_qword] &= ~subres_mask_piece;
  537. relocated = true;
  538. break;
  539. }
  540. }
  541. if (relocated) {
  542. // Let's delete the group where it used to be by itself.
  543. if (curr_group_idx == br.groups_count - 1) {
  544. br.groups_count--;
  545. } else {
  546. br.groups[curr_group_idx].states = BarrierRequest::DELETED_GROUP;
  547. }
  548. } else {
  549. // Its current group, where it's alone, can extend its states.
  550. br.groups[curr_group_idx].states = final_states;
  551. }
  552. } else {
  553. // Already there, but not by itself and the state mask is different, so it now belongs to a different group.
  554. br.groups[curr_group_idx].subres_mask[subres_qword] &= ~subres_mask_piece;
  555. subres_already_there = false;
  556. }
  557. } else {
  558. final_states = p_new_state;
  559. }
  560. if (!subres_already_there) {
  561. // See if it fits exactly the states of some of the groups to fit it there.
  562. for (uint8_t i = 0; i < br.groups_count; i++) {
  563. if (unlikely(i == curr_group_idx)) {
  564. continue;
  565. }
  566. if (unlikely(br.groups[i].states == BarrierRequest::DELETED_GROUP)) {
  567. continue;
  568. }
  569. if (br.groups[i].states == final_states) {
  570. br.groups[i].subres_mask[subres_qword] |= subres_mask_piece;
  571. subres_already_there = true;
  572. break;
  573. }
  574. }
  575. if (!subres_already_there) {
  576. // Add a new group to accommodate this subresource.
  577. uint8_t group_to_fill = 0;
  578. if (br.groups_count < BarrierRequest::MAX_GROUPS) {
  579. // There are still free groups.
  580. group_to_fill = br.groups_count;
  581. br.groups_count++;
  582. } else {
  583. // Let's try to take over a deleted one.
  584. for (; group_to_fill < br.groups_count; group_to_fill++) {
  585. if (unlikely(br.groups[group_to_fill].states == BarrierRequest::DELETED_GROUP)) {
  586. break;
  587. }
  588. }
  589. CRASH_COND(group_to_fill == br.groups_count);
  590. }
  591. br.groups[group_to_fill].states = final_states;
  592. for (uint8_t i = 0; i < br.subres_mask_qwords; i++) {
  593. if (unlikely(i == subres_qword)) {
  594. br.groups[group_to_fill].subres_mask[i] = subres_mask_piece;
  595. } else {
  596. br.groups[group_to_fill].subres_mask[i] = 0;
  597. }
  598. }
  599. }
  600. }
  601. }
  602. } else {
  603. BarrierRequest &br = p_command_buffer->res_barriers_requests[res_states];
  604. br.dx_resource = p_resource->resource;
  605. br.subres_mask_qwords = STEPIFY(p_resource->states_ptr->subresource_states.size(), 64) / 64;
  606. CRASH_COND(p_resource->states_ptr->subresource_states.size() > BarrierRequest::MAX_SUBRESOURCES);
  607. br.planes = p_num_planes;
  608. br.groups[0].states = p_new_state;
  609. for (uint8_t i = 0; i < br.subres_mask_qwords; i++) {
  610. if (unlikely(i == subres_qword)) {
  611. br.groups[0].subres_mask[i] = subres_mask_piece;
  612. } else {
  613. br.groups[0].subres_mask[i] = 0;
  614. }
  615. }
  616. br.groups_count = 1;
  617. }
  618. }
  619. }
  620. void RenderingDeviceDriverD3D12::_resource_transitions_flush(CommandBufferInfo *p_command_buffer) {
  621. for (const KeyValue<ResourceInfo::States *, BarrierRequest> &E : p_command_buffer->res_barriers_requests) {
  622. ResourceInfo::States *res_states = E.key;
  623. const BarrierRequest &br = E.value;
  624. uint32_t num_subresources = res_states->subresource_states.size();
  625. // When there's not a lot of subresources, the empirical finding is that it's better
  626. // to avoid attempting the single-barrier optimization.
  627. static const uint32_t SINGLE_BARRIER_ATTEMPT_MAX_NUM_SUBRESOURCES = 48;
  628. bool may_do_single_barrier = br.groups_count == 1 && num_subresources * br.planes >= SINGLE_BARRIER_ATTEMPT_MAX_NUM_SUBRESOURCES;
  629. if (may_do_single_barrier) {
  630. // A single group means we may be able to do a single all-subresources barrier.
  631. {
  632. // First requisite is that all subresources are involved.
  633. uint8_t subres_mask_full_qwords = num_subresources / 64;
  634. for (uint32_t i = 0; i < subres_mask_full_qwords; i++) {
  635. if (br.groups[0].subres_mask[i] != UINT64_MAX) {
  636. may_do_single_barrier = false;
  637. break;
  638. }
  639. }
  640. if (may_do_single_barrier) {
  641. if (num_subresources % 64) {
  642. DEV_ASSERT(br.subres_mask_qwords == subres_mask_full_qwords + 1);
  643. uint64_t mask_tail_qword = 0;
  644. for (uint8_t i = 0; i < num_subresources % 64; i++) {
  645. mask_tail_qword |= ((uint64_t)1 << i);
  646. }
  647. if ((br.groups[0].subres_mask[subres_mask_full_qwords] & mask_tail_qword) != mask_tail_qword) {
  648. may_do_single_barrier = false;
  649. }
  650. }
  651. }
  652. }
  653. if (may_do_single_barrier) {
  654. // Second requisite is that the source state is the same for all.
  655. for (uint32_t i = 1; i < num_subresources; i++) {
  656. if (res_states->subresource_states[i] != res_states->subresource_states[0]) {
  657. may_do_single_barrier = false;
  658. break;
  659. }
  660. }
  661. if (may_do_single_barrier) {
  662. // Hurray!, we can do a single barrier (plus maybe a UAV one, too).
  663. bool just_written = res_states->subresource_states[0] == D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  664. bool needs_uav_barrier = just_written && res_states->last_batch_with_uav_barrier != p_command_buffer->res_barriers_batch;
  665. uint32_t needed_barriers = (needs_uav_barrier ? 1 : 0) + 1;
  666. if (p_command_buffer->res_barriers.size() < p_command_buffer->res_barriers_count + needed_barriers) {
  667. p_command_buffer->res_barriers.resize(p_command_buffer->res_barriers_count + needed_barriers);
  668. }
  669. if (needs_uav_barrier) {
  670. p_command_buffer->res_barriers[p_command_buffer->res_barriers_count] = CD3DX12_RESOURCE_BARRIER::UAV(br.dx_resource);
  671. p_command_buffer->res_barriers_count++;
  672. res_states->last_batch_with_uav_barrier = p_command_buffer->res_barriers_batch;
  673. }
  674. if (res_states->subresource_states[0] != br.groups[0].states) {
  675. p_command_buffer->res_barriers[p_command_buffer->res_barriers_count] = CD3DX12_RESOURCE_BARRIER::Transition(br.dx_resource, res_states->subresource_states[0], br.groups[0].states, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES);
  676. p_command_buffer->res_barriers_count++;
  677. }
  678. for (uint32_t i = 0; i < num_subresources; i++) {
  679. res_states->subresource_states[i] = br.groups[0].states;
  680. }
  681. }
  682. }
  683. }
  684. if (!may_do_single_barrier) {
  685. for (uint8_t i = 0; i < br.groups_count; i++) {
  686. const BarrierRequest::Group &g = E.value.groups[i];
  687. if (unlikely(g.states == BarrierRequest::DELETED_GROUP)) {
  688. continue;
  689. }
  690. uint32_t subresource = 0;
  691. do {
  692. uint64_t subres_mask_piece = ((uint64_t)1 << (subresource % 64));
  693. uint8_t subres_qword = subresource / 64;
  694. if (likely(g.subres_mask[subres_qword] == 0)) {
  695. subresource += 64;
  696. continue;
  697. }
  698. if (likely(!(g.subres_mask[subres_qword] & subres_mask_piece))) {
  699. subresource++;
  700. continue;
  701. }
  702. D3D12_RESOURCE_STATES *curr_state = &res_states->subresource_states[subresource];
  703. bool just_written = *curr_state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  704. bool needs_uav_barrier = just_written && res_states->last_batch_with_uav_barrier != p_command_buffer->res_barriers_batch;
  705. uint32_t needed_barriers = (needs_uav_barrier ? 1 : 0) + br.planes;
  706. if (p_command_buffer->res_barriers.size() < p_command_buffer->res_barriers_count + needed_barriers) {
  707. p_command_buffer->res_barriers.resize(p_command_buffer->res_barriers_count + needed_barriers);
  708. }
  709. if (needs_uav_barrier) {
  710. p_command_buffer->res_barriers[p_command_buffer->res_barriers_count] = CD3DX12_RESOURCE_BARRIER::UAV(br.dx_resource);
  711. p_command_buffer->res_barriers_count++;
  712. res_states->last_batch_with_uav_barrier = p_command_buffer->res_barriers_batch;
  713. }
  714. if (*curr_state != g.states) {
  715. for (uint8_t k = 0; k < br.planes; k++) {
  716. p_command_buffer->res_barriers[p_command_buffer->res_barriers_count] = CD3DX12_RESOURCE_BARRIER::Transition(br.dx_resource, *curr_state, g.states, subresource + k * num_subresources);
  717. p_command_buffer->res_barriers_count++;
  718. }
  719. }
  720. *curr_state = g.states;
  721. subresource++;
  722. } while (subresource < num_subresources);
  723. }
  724. }
  725. }
  726. if (p_command_buffer->res_barriers_count) {
  727. p_command_buffer->cmd_list->ResourceBarrier(p_command_buffer->res_barriers_count, p_command_buffer->res_barriers.ptr());
  728. p_command_buffer->res_barriers_requests.clear();
  729. }
  730. p_command_buffer->res_barriers_count = 0;
  731. p_command_buffer->res_barriers_batch++;
  732. }
  733. /*****************/
  734. /**** BUFFERS ****/
  735. /*****************/
  736. RDD::BufferID RenderingDeviceDriverD3D12::buffer_create(uint64_t p_size, BitField<BufferUsageBits> p_usage, MemoryAllocationType p_allocation_type) {
  737. // D3D12 debug layers complain at CBV creation time if the size is not multiple of the value per the spec
  738. // but also if you give a rounded size at that point because it will extend beyond the
  739. // memory of the resource. Therefore, it seems the only way is to create it with a
  740. // rounded size.
  741. CD3DX12_RESOURCE_DESC1 resource_desc = CD3DX12_RESOURCE_DESC1::Buffer(STEPIFY(p_size, D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT));
  742. if (p_usage.has_flag(RDD::BUFFER_USAGE_STORAGE_BIT)) {
  743. resource_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
  744. } else {
  745. resource_desc.Flags |= D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE;
  746. }
  747. D3D12MA::ALLOCATION_DESC allocation_desc = {};
  748. allocation_desc.HeapType = D3D12_HEAP_TYPE_DEFAULT;
  749. D3D12_RESOURCE_STATES initial_state = D3D12_RESOURCE_STATE_COMMON;
  750. switch (p_allocation_type) {
  751. case MEMORY_ALLOCATION_TYPE_CPU: {
  752. bool is_src = p_usage.has_flag(BUFFER_USAGE_TRANSFER_FROM_BIT);
  753. bool is_dst = p_usage.has_flag(BUFFER_USAGE_TRANSFER_TO_BIT);
  754. if (is_src && !is_dst) {
  755. // Looks like a staging buffer: CPU maps, writes sequentially, then GPU copies to VRAM.
  756. allocation_desc.HeapType = D3D12_HEAP_TYPE_UPLOAD;
  757. initial_state = D3D12_RESOURCE_STATE_GENERIC_READ;
  758. }
  759. if (is_dst && !is_src) {
  760. // Looks like a readback buffer: GPU copies from VRAM, then CPU maps and reads.
  761. allocation_desc.HeapType = D3D12_HEAP_TYPE_READBACK;
  762. initial_state = D3D12_RESOURCE_STATE_COPY_DEST;
  763. }
  764. } break;
  765. case MEMORY_ALLOCATION_TYPE_GPU: {
  766. // Use default parameters.
  767. } break;
  768. }
  769. ComPtr<ID3D12Resource> buffer;
  770. ComPtr<D3D12MA::Allocation> allocation;
  771. HRESULT res;
  772. if (barrier_capabilities.enhanced_barriers_supported) {
  773. res = allocator->CreateResource3(
  774. &allocation_desc,
  775. &resource_desc,
  776. D3D12_BARRIER_LAYOUT_UNDEFINED,
  777. nullptr,
  778. 0,
  779. nullptr,
  780. allocation.GetAddressOf(),
  781. IID_PPV_ARGS(buffer.GetAddressOf()));
  782. } else {
  783. res = allocator->CreateResource(
  784. &allocation_desc,
  785. reinterpret_cast<const D3D12_RESOURCE_DESC *>(&resource_desc),
  786. initial_state,
  787. nullptr,
  788. allocation.GetAddressOf(),
  789. IID_PPV_ARGS(buffer.GetAddressOf()));
  790. }
  791. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), BufferID(), "Can't create buffer of size: " + itos(p_size) + ", error " + vformat("0x%08ux", (uint64_t)res) + ".");
  792. // Bookkeep.
  793. BufferInfo *buf_info = VersatileResource::allocate<BufferInfo>(resources_allocator);
  794. buf_info->resource = buffer.Get();
  795. buf_info->owner_info.resource = buffer;
  796. buf_info->owner_info.allocation = allocation;
  797. buf_info->owner_info.states.subresource_states.push_back(initial_state);
  798. buf_info->states_ptr = &buf_info->owner_info.states;
  799. buf_info->size = p_size;
  800. buf_info->flags.usable_as_uav = (resource_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
  801. return BufferID(buf_info);
  802. }
  803. bool RenderingDeviceDriverD3D12::buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) {
  804. BufferInfo *buf_info = (BufferInfo *)p_buffer.id;
  805. buf_info->texel_format = p_format;
  806. return true;
  807. }
  808. void RenderingDeviceDriverD3D12::buffer_free(BufferID p_buffer) {
  809. BufferInfo *buf_info = (BufferInfo *)p_buffer.id;
  810. VersatileResource::free(resources_allocator, buf_info);
  811. }
  812. uint64_t RenderingDeviceDriverD3D12::buffer_get_allocation_size(BufferID p_buffer) {
  813. const BufferInfo *buf_info = (const BufferInfo *)p_buffer.id;
  814. return buf_info->owner_info.allocation ? buf_info->owner_info.allocation->GetSize() : 0;
  815. }
  816. uint8_t *RenderingDeviceDriverD3D12::buffer_map(BufferID p_buffer) {
  817. const BufferInfo *buf_info = (const BufferInfo *)p_buffer.id;
  818. void *data_ptr = nullptr;
  819. HRESULT res = buf_info->resource->Map(0, &VOID_RANGE, &data_ptr);
  820. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), nullptr, "Map failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  821. return (uint8_t *)data_ptr;
  822. }
  823. void RenderingDeviceDriverD3D12::buffer_unmap(BufferID p_buffer) {
  824. const BufferInfo *buf_info = (const BufferInfo *)p_buffer.id;
  825. buf_info->resource->Unmap(0, &VOID_RANGE);
  826. }
  827. /*****************/
  828. /**** TEXTURE ****/
  829. /*****************/
  830. static const D3D12_SRV_DIMENSION RD_TEXTURE_TYPE_TO_D3D12_VIEW_DIMENSION_FOR_SRV[RD::TEXTURE_TYPE_MAX] = {
  831. D3D12_SRV_DIMENSION_TEXTURE1D,
  832. D3D12_SRV_DIMENSION_TEXTURE2D,
  833. D3D12_SRV_DIMENSION_TEXTURE3D,
  834. D3D12_SRV_DIMENSION_TEXTURECUBE,
  835. D3D12_SRV_DIMENSION_TEXTURE1DARRAY,
  836. D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  837. D3D12_SRV_DIMENSION_TEXTURECUBEARRAY,
  838. };
  839. static const D3D12_SRV_DIMENSION RD_TEXTURE_TYPE_TO_D3D12_VIEW_DIMENSION_FOR_SRV_MS[RD::TEXTURE_TYPE_MAX] = {
  840. D3D12_SRV_DIMENSION_UNKNOWN,
  841. D3D12_SRV_DIMENSION_TEXTURE2DMS,
  842. D3D12_SRV_DIMENSION_UNKNOWN,
  843. D3D12_SRV_DIMENSION_UNKNOWN,
  844. D3D12_SRV_DIMENSION_UNKNOWN,
  845. D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY,
  846. D3D12_SRV_DIMENSION_UNKNOWN,
  847. };
  848. static const D3D12_UAV_DIMENSION RD_TEXTURE_TYPE_TO_D3D12_VIEW_DIMENSION_FOR_UAV[RD::TEXTURE_TYPE_MAX] = {
  849. D3D12_UAV_DIMENSION_TEXTURE1D,
  850. D3D12_UAV_DIMENSION_TEXTURE2D,
  851. D3D12_UAV_DIMENSION_TEXTURE3D,
  852. D3D12_UAV_DIMENSION_TEXTURE2DARRAY,
  853. D3D12_UAV_DIMENSION_TEXTURE1DARRAY,
  854. D3D12_UAV_DIMENSION_TEXTURE2DARRAY,
  855. D3D12_UAV_DIMENSION_TEXTURE2DARRAY,
  856. };
  857. uint32_t RenderingDeviceDriverD3D12::_find_max_common_supported_sample_count(VectorView<DXGI_FORMAT> p_formats) {
  858. uint32_t common = UINT32_MAX;
  859. MutexLock lock(format_sample_counts_mask_cache_mutex);
  860. for (uint32_t i = 0; i < p_formats.size(); i++) {
  861. if (format_sample_counts_mask_cache.has(p_formats[i])) {
  862. common &= format_sample_counts_mask_cache[p_formats[i]];
  863. } else {
  864. D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS msql = {};
  865. msql.Format = p_formats[i];
  866. uint32_t mask = 0;
  867. for (int samples = 1 << (TEXTURE_SAMPLES_MAX - 1); samples >= 1; samples /= 2) {
  868. msql.SampleCount = (UINT)samples;
  869. HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &msql, sizeof(msql));
  870. if (SUCCEEDED(res) && msql.NumQualityLevels) {
  871. int bit = get_shift_from_power_of_2(samples);
  872. ERR_FAIL_COND_V(bit == -1, 1);
  873. mask |= (uint32_t)(1 << bit);
  874. }
  875. }
  876. format_sample_counts_mask_cache.insert(p_formats[i], mask);
  877. common &= mask;
  878. }
  879. }
  880. if (common == UINT32_MAX) {
  881. return 1;
  882. } else {
  883. return ((uint32_t)1 << nearest_shift(common));
  884. }
  885. }
  886. UINT RenderingDeviceDriverD3D12::_compute_component_mapping(const RDD::TextureView &p_view) {
  887. UINT base_swizzle = RD_TO_D3D12_FORMAT[p_view.format].swizzle;
  888. D3D12_SHADER_COMPONENT_MAPPING component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  889. D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0, // Unused.
  890. D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0,
  891. D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1,
  892. // These will be D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_*.
  893. D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(0, base_swizzle),
  894. D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(1, base_swizzle),
  895. D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(2, base_swizzle),
  896. D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(3, base_swizzle),
  897. };
  898. return D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(
  899. p_view.swizzle_r == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_R] : component_swizzles[p_view.swizzle_r],
  900. p_view.swizzle_g == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_G] : component_swizzles[p_view.swizzle_g],
  901. p_view.swizzle_b == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_B] : component_swizzles[p_view.swizzle_b],
  902. p_view.swizzle_a == TEXTURE_SWIZZLE_IDENTITY ? component_swizzles[TEXTURE_SWIZZLE_A] : component_swizzles[p_view.swizzle_a]);
  903. }
  904. UINT RenderingDeviceDriverD3D12::_compute_plane_slice(DataFormat p_format, BitField<TextureAspectBits> p_aspect_bits) {
  905. TextureAspect aspect = TEXTURE_ASPECT_MAX;
  906. if (p_aspect_bits.has_flag(TEXTURE_ASPECT_COLOR_BIT)) {
  907. DEV_ASSERT(aspect == TEXTURE_ASPECT_MAX);
  908. aspect = TEXTURE_ASPECT_COLOR;
  909. }
  910. if (p_aspect_bits.has_flag(TEXTURE_ASPECT_DEPTH_BIT)) {
  911. DEV_ASSERT(aspect == TEXTURE_ASPECT_MAX);
  912. aspect = TEXTURE_ASPECT_DEPTH;
  913. } else if (p_aspect_bits.has_flag(TEXTURE_ASPECT_STENCIL_BIT)) {
  914. DEV_ASSERT(aspect == TEXTURE_ASPECT_MAX);
  915. aspect = TEXTURE_ASPECT_STENCIL;
  916. }
  917. DEV_ASSERT(aspect != TEXTURE_ASPECT_MAX);
  918. return _compute_plane_slice(p_format, aspect);
  919. }
  920. UINT RenderingDeviceDriverD3D12::_compute_plane_slice(DataFormat p_format, TextureAspect p_aspect) {
  921. switch (p_aspect) {
  922. case TEXTURE_ASPECT_COLOR:
  923. // The plane must be 0 for the color aspect (assuming the format is a regular color one, which must be the case).
  924. return 0;
  925. case TEXTURE_ASPECT_DEPTH:
  926. // The plane must be 0 for the color or depth aspect
  927. return 0;
  928. case TEXTURE_ASPECT_STENCIL:
  929. // The plane may be 0 for the stencil aspect (if the format is stencil-only), or 1 (if the format is depth-stencil; other cases are ill).
  930. return format_get_plane_count(p_format) == 2 ? 1 : 0;
  931. default:
  932. DEV_ASSERT(false);
  933. return 0;
  934. }
  935. }
  936. UINT RenderingDeviceDriverD3D12::_compute_subresource_from_layers(TextureInfo *p_texture, const TextureSubresourceLayers &p_layers, uint32_t p_layer_offset) {
  937. return D3D12CalcSubresource(p_layers.mipmap, p_layers.base_layer + p_layer_offset, _compute_plane_slice(p_texture->format, p_layers.aspect), p_texture->desc.MipLevels, p_texture->desc.ArraySize());
  938. }
  939. void RenderingDeviceDriverD3D12::_discard_texture_subresources(const TextureInfo *p_tex_info, const CommandBufferInfo *p_cmd_buf_info) {
  940. uint32_t planes = 1;
  941. if ((p_tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
  942. planes = format_get_plane_count(p_tex_info->format);
  943. }
  944. D3D12_DISCARD_REGION dr = {};
  945. dr.NumRects = p_cmd_buf_info->render_pass_state.region_is_all ? 0 : 1;
  946. dr.pRects = p_cmd_buf_info->render_pass_state.region_is_all ? nullptr : &p_cmd_buf_info->render_pass_state.region_rect;
  947. dr.FirstSubresource = UINT_MAX;
  948. dr.NumSubresources = 0;
  949. for (uint32_t u = 0; u < planes; u++) {
  950. for (uint32_t v = 0; v < p_tex_info->layers; v++) {
  951. for (uint32_t w = 0; w < p_tex_info->mipmaps; w++) {
  952. UINT subresource = D3D12CalcSubresource(
  953. p_tex_info->base_mip + w,
  954. p_tex_info->base_layer + v,
  955. u,
  956. p_tex_info->desc.MipLevels,
  957. p_tex_info->desc.ArraySize());
  958. if (dr.NumSubresources == 0) {
  959. dr.FirstSubresource = subresource;
  960. dr.NumSubresources = 1;
  961. } else if (dr.FirstSubresource + dr.NumSubresources == subresource) {
  962. dr.NumSubresources++;
  963. } else {
  964. p_cmd_buf_info->cmd_list->DiscardResource(p_tex_info->resource, &dr);
  965. dr.FirstSubresource = subresource;
  966. dr.NumSubresources = 1;
  967. }
  968. }
  969. }
  970. }
  971. if (dr.NumSubresources) {
  972. p_cmd_buf_info->cmd_list->DiscardResource(p_tex_info->resource, &dr);
  973. }
  974. }
  975. bool RenderingDeviceDriverD3D12::_unordered_access_supported_by_format(DataFormat p_format) {
  976. switch (p_format) {
  977. case DATA_FORMAT_R4G4_UNORM_PACK8:
  978. case DATA_FORMAT_R4G4B4A4_UNORM_PACK16:
  979. case DATA_FORMAT_B4G4R4A4_UNORM_PACK16:
  980. case DATA_FORMAT_R5G6B5_UNORM_PACK16:
  981. case DATA_FORMAT_B5G6R5_UNORM_PACK16:
  982. case DATA_FORMAT_R5G5B5A1_UNORM_PACK16:
  983. case DATA_FORMAT_B5G5R5A1_UNORM_PACK16:
  984. case DATA_FORMAT_A1R5G5B5_UNORM_PACK16:
  985. case DATA_FORMAT_A8B8G8R8_UNORM_PACK32:
  986. case DATA_FORMAT_A8B8G8R8_SNORM_PACK32:
  987. case DATA_FORMAT_A8B8G8R8_USCALED_PACK32:
  988. case DATA_FORMAT_A8B8G8R8_SSCALED_PACK32:
  989. case DATA_FORMAT_A8B8G8R8_UINT_PACK32:
  990. case DATA_FORMAT_A8B8G8R8_SINT_PACK32:
  991. case DATA_FORMAT_A8B8G8R8_SRGB_PACK32:
  992. case DATA_FORMAT_A2R10G10B10_UNORM_PACK32:
  993. case DATA_FORMAT_A2R10G10B10_SNORM_PACK32:
  994. case DATA_FORMAT_A2R10G10B10_USCALED_PACK32:
  995. case DATA_FORMAT_A2R10G10B10_SSCALED_PACK32:
  996. case DATA_FORMAT_A2R10G10B10_UINT_PACK32:
  997. case DATA_FORMAT_A2R10G10B10_SINT_PACK32:
  998. case DATA_FORMAT_A2B10G10R10_UNORM_PACK32:
  999. case DATA_FORMAT_A2B10G10R10_SNORM_PACK32:
  1000. case DATA_FORMAT_A2B10G10R10_USCALED_PACK32:
  1001. case DATA_FORMAT_A2B10G10R10_SSCALED_PACK32:
  1002. case DATA_FORMAT_A2B10G10R10_UINT_PACK32:
  1003. case DATA_FORMAT_A2B10G10R10_SINT_PACK32:
  1004. case DATA_FORMAT_B10G11R11_UFLOAT_PACK32:
  1005. case DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32:
  1006. case DATA_FORMAT_X8_D24_UNORM_PACK32:
  1007. case DATA_FORMAT_R10X6_UNORM_PACK16:
  1008. case DATA_FORMAT_R10X6G10X6_UNORM_2PACK16:
  1009. case DATA_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
  1010. case DATA_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16:
  1011. case DATA_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16:
  1012. case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16:
  1013. case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16:
  1014. case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16:
  1015. case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16:
  1016. case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16:
  1017. case DATA_FORMAT_R12X4_UNORM_PACK16:
  1018. case DATA_FORMAT_R12X4G12X4_UNORM_2PACK16:
  1019. case DATA_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16:
  1020. case DATA_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16:
  1021. case DATA_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16:
  1022. case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16:
  1023. case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16:
  1024. case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16:
  1025. case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16:
  1026. case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16:
  1027. return false;
  1028. default:
  1029. return true;
  1030. }
  1031. }
  1032. RDD::TextureID RenderingDeviceDriverD3D12::texture_create(const TextureFormat &p_format, const TextureView &p_view) {
  1033. // Using D3D12_RESOURCE_DESC1. Thanks to the layout, it's sliceable down to D3D12_RESOURCE_DESC if needed.
  1034. CD3DX12_RESOURCE_DESC1 resource_desc = {};
  1035. resource_desc.Dimension = RD_TEXTURE_TYPE_TO_D3D12_RESOURCE_DIMENSION[p_format.texture_type];
  1036. resource_desc.Alignment = 0; // D3D12MA will override this to use a smaller alignment than the default if possible.
  1037. resource_desc.Width = p_format.width;
  1038. resource_desc.Height = p_format.height;
  1039. resource_desc.DepthOrArraySize = p_format.depth * p_format.array_layers;
  1040. resource_desc.MipLevels = p_format.mipmaps;
  1041. // Format.
  1042. bool cross_family_sharing = false;
  1043. bool relaxed_casting_available = false;
  1044. DXGI_FORMAT *relaxed_casting_formats = nullptr;
  1045. uint32_t relaxed_casting_format_count = 0;
  1046. {
  1047. resource_desc.Format = RD_TO_D3D12_FORMAT[p_format.format].family;
  1048. // If views of different families are wanted, special setup is needed for proper sharing among them.
  1049. // If the driver reports relaxed casting is, leverage its new extended resource creation API (via D3D12MA).
  1050. if (p_format.shareable_formats.size() && format_capabilities.relaxed_casting_supported) {
  1051. relaxed_casting_available = true;
  1052. relaxed_casting_formats = ALLOCA_ARRAY(DXGI_FORMAT, p_format.shareable_formats.size() + 1);
  1053. relaxed_casting_formats[0] = RD_TO_D3D12_FORMAT[p_format.format].general_format;
  1054. relaxed_casting_format_count++;
  1055. }
  1056. HashMap<DataFormat, D3D12_RESOURCE_FLAGS> aliases_forbidden_flags;
  1057. for (int i = 0; i < p_format.shareable_formats.size(); i++) {
  1058. DataFormat curr_format = p_format.shareable_formats[i];
  1059. String format_text = "'" + String(FORMAT_NAMES[p_format.format]) + "'";
  1060. ERR_FAIL_COND_V_MSG(RD_TO_D3D12_FORMAT[curr_format].family == DXGI_FORMAT_UNKNOWN, TextureID(), "Format " + format_text + " is not supported.");
  1061. if (RD_TO_D3D12_FORMAT[curr_format].family != RD_TO_D3D12_FORMAT[p_format.format].family) {
  1062. cross_family_sharing = true;
  1063. }
  1064. if (relaxed_casting_available) {
  1065. relaxed_casting_formats[relaxed_casting_format_count] = RD_TO_D3D12_FORMAT[curr_format].general_format;
  1066. relaxed_casting_format_count++;
  1067. }
  1068. }
  1069. if (cross_family_sharing && !relaxed_casting_available) {
  1070. // Per https://docs.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_texture_layout.
  1071. if (p_format.texture_type == TEXTURE_TYPE_1D) {
  1072. ERR_FAIL_V_MSG(TextureID(), "This texture's views require aliasing, but that's not supported for a 1D texture.");
  1073. }
  1074. if (p_format.samples != TEXTURE_SAMPLES_1) {
  1075. ERR_FAIL_V_MSG(TextureID(), "This texture's views require aliasing, but that's not supported for a multi-sample texture.");
  1076. }
  1077. if ((p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  1078. ERR_FAIL_V_MSG(TextureID(), "This texture's views require aliasing, but that's not supported for a depth-stencil texture.");
  1079. }
  1080. if (RD_TO_D3D12_FORMAT[p_format.format].family == DXGI_FORMAT_R32G32B32_TYPELESS) {
  1081. ERR_FAIL_V_MSG(TextureID(), "This texture's views require aliasing, but that's not supported for an R32G32B32 texture.");
  1082. }
  1083. }
  1084. }
  1085. // Usage.
  1086. if ((p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) {
  1087. resource_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
  1088. } else {
  1089. if ((p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_TO_BIT) && _unordered_access_supported_by_format(p_format.format)) {
  1090. resource_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; // For clearing via UAV.
  1091. }
  1092. }
  1093. if ((p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  1094. resource_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
  1095. }
  1096. if ((p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT)) {
  1097. resource_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
  1098. }
  1099. if ((p_format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT)) {
  1100. // For VRS images we can't use the typeless format.
  1101. resource_desc.Format = DXGI_FORMAT_R8_UINT;
  1102. }
  1103. resource_desc.SampleDesc = {};
  1104. DXGI_FORMAT format_to_test = (resource_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) ? RD_TO_D3D12_FORMAT[p_format.format].dsv_format : RD_TO_D3D12_FORMAT[p_format.format].general_format;
  1105. if (!(resource_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) {
  1106. resource_desc.SampleDesc.Count = MIN(
  1107. _find_max_common_supported_sample_count(format_to_test),
  1108. TEXTURE_SAMPLES_COUNT[p_format.samples]);
  1109. } else {
  1110. // No MSAA in D3D12 if storage. May have become possible recently where supported, though.
  1111. resource_desc.SampleDesc.Count = 1;
  1112. }
  1113. resource_desc.SampleDesc.Quality = resource_desc.SampleDesc.Count == 1 ? 0 : DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN;
  1114. // Create.
  1115. D3D12MA::ALLOCATION_DESC allocation_desc = {};
  1116. allocation_desc.HeapType = (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) ? D3D12_HEAP_TYPE_READBACK : D3D12_HEAP_TYPE_DEFAULT;
  1117. if ((resource_desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL))) {
  1118. allocation_desc.ExtraHeapFlags = D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES;
  1119. } else {
  1120. allocation_desc.ExtraHeapFlags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES;
  1121. }
  1122. if ((resource_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) {
  1123. allocation_desc.ExtraHeapFlags |= D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS;
  1124. }
  1125. D3D12_RESOURCE_STATES initial_state = {};
  1126. ID3D12Resource *texture = nullptr;
  1127. ComPtr<ID3D12Resource> main_texture;
  1128. ComPtr<D3D12MA::Allocation> allocation;
  1129. static const FLOAT black[4] = {};
  1130. D3D12_CLEAR_VALUE clear_value = CD3DX12_CLEAR_VALUE(RD_TO_D3D12_FORMAT[p_format.format].general_format, black);
  1131. D3D12_CLEAR_VALUE *clear_value_ptr = (resource_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) ? &clear_value : nullptr;
  1132. {
  1133. HRESULT res = E_FAIL;
  1134. if (barrier_capabilities.enhanced_barriers_supported || (cross_family_sharing && relaxed_casting_available)) {
  1135. // Create with undefined layout if enhanced barriers are supported. Leave as common otherwise for interop with legacy barriers.
  1136. D3D12_BARRIER_LAYOUT initial_layout = barrier_capabilities.enhanced_barriers_supported ? D3D12_BARRIER_LAYOUT_UNDEFINED : D3D12_BARRIER_LAYOUT_COMMON;
  1137. res = allocator->CreateResource3(
  1138. &allocation_desc,
  1139. &resource_desc,
  1140. initial_layout,
  1141. clear_value_ptr,
  1142. relaxed_casting_format_count,
  1143. relaxed_casting_formats,
  1144. allocation.GetAddressOf(),
  1145. IID_PPV_ARGS(main_texture.GetAddressOf()));
  1146. initial_state = D3D12_RESOURCE_STATE_COMMON;
  1147. } else {
  1148. res = allocator->CreateResource(
  1149. &allocation_desc,
  1150. (D3D12_RESOURCE_DESC *)&resource_desc,
  1151. D3D12_RESOURCE_STATE_COPY_DEST,
  1152. clear_value_ptr,
  1153. allocation.GetAddressOf(),
  1154. IID_PPV_ARGS(main_texture.GetAddressOf()));
  1155. initial_state = D3D12_RESOURCE_STATE_COPY_DEST;
  1156. }
  1157. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), TextureID(), "CreateResource failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  1158. texture = main_texture.Get();
  1159. }
  1160. // Describe views.
  1161. D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc = {};
  1162. {
  1163. srv_desc.Format = RD_TO_D3D12_FORMAT[p_view.format].general_format;
  1164. srv_desc.ViewDimension = p_format.samples == TEXTURE_SAMPLES_1 ? RD_TEXTURE_TYPE_TO_D3D12_VIEW_DIMENSION_FOR_SRV[p_format.texture_type] : RD_TEXTURE_TYPE_TO_D3D12_VIEW_DIMENSION_FOR_SRV_MS[p_format.texture_type];
  1165. srv_desc.Shader4ComponentMapping = _compute_component_mapping(p_view);
  1166. switch (srv_desc.ViewDimension) {
  1167. case D3D12_SRV_DIMENSION_TEXTURE1D: {
  1168. srv_desc.Texture1D.MipLevels = p_format.mipmaps;
  1169. } break;
  1170. case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: {
  1171. srv_desc.Texture1DArray.MipLevels = p_format.mipmaps;
  1172. srv_desc.Texture1DArray.ArraySize = p_format.array_layers;
  1173. } break;
  1174. case D3D12_SRV_DIMENSION_TEXTURE2D: {
  1175. srv_desc.Texture2D.MipLevels = p_format.mipmaps;
  1176. } break;
  1177. case D3D12_SRV_DIMENSION_TEXTURE2DMS: {
  1178. } break;
  1179. case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: {
  1180. srv_desc.Texture2DArray.MipLevels = p_format.mipmaps;
  1181. srv_desc.Texture2DArray.ArraySize = p_format.array_layers;
  1182. } break;
  1183. case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: {
  1184. srv_desc.Texture2DMSArray.ArraySize = p_format.array_layers;
  1185. } break;
  1186. case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: {
  1187. srv_desc.TextureCubeArray.MipLevels = p_format.mipmaps;
  1188. srv_desc.TextureCubeArray.NumCubes = p_format.array_layers / 6;
  1189. } break;
  1190. case D3D12_SRV_DIMENSION_TEXTURE3D: {
  1191. srv_desc.Texture3D.MipLevels = p_format.mipmaps;
  1192. } break;
  1193. case D3D12_SRV_DIMENSION_TEXTURECUBE: {
  1194. srv_desc.TextureCube.MipLevels = p_format.mipmaps;
  1195. } break;
  1196. default: {
  1197. }
  1198. }
  1199. }
  1200. D3D12_UNORDERED_ACCESS_VIEW_DESC main_uav_desc = {};
  1201. {
  1202. main_uav_desc.Format = RD_TO_D3D12_FORMAT[p_format.format].general_format;
  1203. main_uav_desc.ViewDimension = p_format.samples == TEXTURE_SAMPLES_1 ? RD_TEXTURE_TYPE_TO_D3D12_VIEW_DIMENSION_FOR_UAV[p_format.texture_type] : D3D12_UAV_DIMENSION_UNKNOWN;
  1204. switch (main_uav_desc.ViewDimension) {
  1205. case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: {
  1206. main_uav_desc.Texture1DArray.ArraySize = p_format.array_layers;
  1207. } break;
  1208. case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: {
  1209. // Either for an actual 2D texture array, cubemap or cubemap array.
  1210. main_uav_desc.Texture2DArray.ArraySize = p_format.array_layers;
  1211. } break;
  1212. case D3D12_UAV_DIMENSION_TEXTURE3D: {
  1213. main_uav_desc.Texture3D.WSize = p_format.depth;
  1214. } break;
  1215. default: {
  1216. }
  1217. }
  1218. }
  1219. D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc = main_uav_desc;
  1220. uav_desc.Format = RD_TO_D3D12_FORMAT[p_view.format].general_format;
  1221. // Bookkeep.
  1222. TextureInfo *tex_info = VersatileResource::allocate<TextureInfo>(resources_allocator);
  1223. tex_info->resource = texture;
  1224. tex_info->owner_info.resource = main_texture;
  1225. tex_info->owner_info.allocation = allocation;
  1226. tex_info->owner_info.states.subresource_states.resize(p_format.mipmaps * p_format.array_layers);
  1227. for (uint32_t i = 0; i < tex_info->owner_info.states.subresource_states.size(); i++) {
  1228. tex_info->owner_info.states.subresource_states[i] = initial_state;
  1229. }
  1230. tex_info->states_ptr = &tex_info->owner_info.states;
  1231. tex_info->format = p_format.format;
  1232. #if defined(__GNUC__) && !defined(__clang__)
  1233. #pragma GCC diagnostic push
  1234. #pragma GCC diagnostic ignored "-Wstrict-aliasing"
  1235. #endif
  1236. tex_info->desc = *(CD3DX12_RESOURCE_DESC *)&resource_desc;
  1237. #if defined(__GNUC__) && !defined(__clang__)
  1238. #pragma GCC diagnostic pop
  1239. #endif
  1240. tex_info->base_layer = 0;
  1241. tex_info->layers = resource_desc.ArraySize();
  1242. tex_info->base_mip = 0;
  1243. tex_info->mipmaps = resource_desc.MipLevels;
  1244. tex_info->view_descs.srv = srv_desc;
  1245. tex_info->view_descs.uav = uav_desc;
  1246. if (!barrier_capabilities.enhanced_barriers_supported && (p_format.usage_bits & (TEXTURE_USAGE_STORAGE_BIT | TEXTURE_USAGE_COLOR_ATTACHMENT_BIT))) {
  1247. // Fallback to clear resources when they're first used in a uniform set. Not necessary if enhanced barriers
  1248. // are supported, as the discard flag will be used instead when transitioning from an undefined layout.
  1249. textures_pending_clear.add(&tex_info->pending_clear);
  1250. }
  1251. return TextureID(tex_info);
  1252. }
  1253. RDD::TextureID RenderingDeviceDriverD3D12::texture_create_from_extension(uint64_t p_native_texture, TextureType p_type, DataFormat p_format, uint32_t p_array_layers, bool p_depth_stencil) {
  1254. ERR_FAIL_V_MSG(TextureID(), "Unimplemented!");
  1255. }
  1256. RDD::TextureID RenderingDeviceDriverD3D12::texture_create_shared(TextureID p_original_texture, const TextureView &p_view) {
  1257. return _texture_create_shared_from_slice(p_original_texture, p_view, (TextureSliceType)-1, 0, 0, 0, 0);
  1258. }
  1259. RDD::TextureID RenderingDeviceDriverD3D12::texture_create_shared_from_slice(TextureID p_original_texture, const TextureView &p_view, TextureSliceType p_slice_type, uint32_t p_layer, uint32_t p_layers, uint32_t p_mipmap, uint32_t p_mipmaps) {
  1260. return _texture_create_shared_from_slice(p_original_texture, p_view, p_slice_type, p_layer, p_layers, p_mipmap, p_mipmaps);
  1261. }
  1262. RDD::TextureID RenderingDeviceDriverD3D12::_texture_create_shared_from_slice(TextureID p_original_texture, const TextureView &p_view, TextureSliceType p_slice_type, uint32_t p_layer, uint32_t p_layers, uint32_t p_mipmap, uint32_t p_mipmaps) {
  1263. TextureInfo *owner_tex_info = (TextureInfo *)p_original_texture.id;
  1264. #ifdef DEBUG_ENABLED
  1265. ERR_FAIL_COND_V(!owner_tex_info->owner_info.allocation, TextureID());
  1266. #endif
  1267. ComPtr<ID3D12Resource> new_texture;
  1268. ComPtr<D3D12MA::Allocation> new_allocation;
  1269. ID3D12Resource *resource = owner_tex_info->resource;
  1270. CD3DX12_RESOURCE_DESC new_tex_resource_desc = owner_tex_info->desc;
  1271. // Describe views.
  1272. D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc = owner_tex_info->view_descs.srv;
  1273. {
  1274. srv_desc.Format = RD_TO_D3D12_FORMAT[p_view.format].general_format;
  1275. srv_desc.Shader4ComponentMapping = _compute_component_mapping(p_view);
  1276. }
  1277. D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc = owner_tex_info->view_descs.uav;
  1278. {
  1279. uav_desc.Format = RD_TO_D3D12_FORMAT[p_view.format].general_format;
  1280. }
  1281. if (p_slice_type != (TextureSliceType)-1) {
  1282. // Complete description with slicing.
  1283. switch (p_slice_type) {
  1284. case TEXTURE_SLICE_2D: {
  1285. if (srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D && p_layer == 0) {
  1286. srv_desc.Texture2D.MostDetailedMip = p_mipmap;
  1287. srv_desc.Texture2D.MipLevels = p_mipmaps;
  1288. DEV_ASSERT(uav_desc.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2D);
  1289. uav_desc.Texture1D.MipSlice = p_mipmap;
  1290. } else if (srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DMS && p_layer == 0) {
  1291. DEV_ASSERT(uav_desc.ViewDimension == D3D12_UAV_DIMENSION_UNKNOWN);
  1292. } else if ((srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY || (srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D && p_layer)) || srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBE || srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBEARRAY) {
  1293. srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
  1294. srv_desc.Texture2DArray.MostDetailedMip = p_mipmap;
  1295. srv_desc.Texture2DArray.MipLevels = p_mipmaps;
  1296. srv_desc.Texture2DArray.FirstArraySlice = p_layer;
  1297. srv_desc.Texture2DArray.ArraySize = 1;
  1298. srv_desc.Texture2DArray.PlaneSlice = 0;
  1299. srv_desc.Texture2DArray.ResourceMinLODClamp = 0.0f;
  1300. uav_desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
  1301. uav_desc.Texture2DArray.MipSlice = p_mipmap;
  1302. uav_desc.Texture2DArray.FirstArraySlice = p_layer;
  1303. uav_desc.Texture2DArray.ArraySize = 1;
  1304. uav_desc.Texture2DArray.PlaneSlice = 0;
  1305. } else if ((srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY || (srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DMS && p_layer))) {
  1306. srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
  1307. srv_desc.Texture2DMSArray.FirstArraySlice = p_layer;
  1308. srv_desc.Texture2DMSArray.ArraySize = 1;
  1309. uav_desc.ViewDimension = D3D12_UAV_DIMENSION_UNKNOWN;
  1310. } else {
  1311. DEV_ASSERT(false);
  1312. }
  1313. } break;
  1314. case TEXTURE_SLICE_CUBEMAP: {
  1315. if (srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBE || p_layer == 0) {
  1316. srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE;
  1317. srv_desc.TextureCube.MostDetailedMip = p_mipmap;
  1318. srv_desc.TextureCube.MipLevels = p_mipmaps;
  1319. DEV_ASSERT(uav_desc.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY);
  1320. uav_desc.Texture2DArray.MipSlice = p_mipmap;
  1321. uav_desc.Texture2DArray.FirstArraySlice = p_layer;
  1322. uav_desc.Texture2DArray.ArraySize = 6;
  1323. uav_desc.Texture2DArray.PlaneSlice = 0;
  1324. } else if (srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBEARRAY || p_layer != 0) {
  1325. srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBEARRAY;
  1326. srv_desc.TextureCubeArray.MostDetailedMip = p_mipmap;
  1327. srv_desc.TextureCubeArray.MipLevels = p_mipmaps;
  1328. srv_desc.TextureCubeArray.First2DArrayFace = p_layer;
  1329. srv_desc.TextureCubeArray.NumCubes = 1;
  1330. srv_desc.TextureCubeArray.ResourceMinLODClamp = 0.0f;
  1331. DEV_ASSERT(uav_desc.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY);
  1332. uav_desc.Texture2DArray.MipSlice = p_mipmap;
  1333. uav_desc.Texture2DArray.FirstArraySlice = p_layer;
  1334. uav_desc.Texture2DArray.ArraySize = 6;
  1335. uav_desc.Texture2DArray.PlaneSlice = 0;
  1336. } else {
  1337. DEV_ASSERT(false);
  1338. }
  1339. } break;
  1340. case TEXTURE_SLICE_3D: {
  1341. DEV_ASSERT(srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE3D);
  1342. srv_desc.Texture3D.MostDetailedMip = p_mipmap;
  1343. srv_desc.Texture3D.MipLevels = p_mipmaps;
  1344. DEV_ASSERT(uav_desc.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE3D);
  1345. uav_desc.Texture3D.MipSlice = p_mipmap;
  1346. uav_desc.Texture3D.WSize = -1;
  1347. } break;
  1348. case TEXTURE_SLICE_2D_ARRAY: {
  1349. DEV_ASSERT(srv_desc.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY);
  1350. srv_desc.Texture2DArray.MostDetailedMip = p_mipmap;
  1351. srv_desc.Texture2DArray.MipLevels = p_mipmaps;
  1352. srv_desc.Texture2DArray.FirstArraySlice = p_layer;
  1353. srv_desc.Texture2DArray.ArraySize = p_layers;
  1354. DEV_ASSERT(uav_desc.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY);
  1355. uav_desc.Texture2DArray.MipSlice = p_mipmap;
  1356. uav_desc.Texture2DArray.FirstArraySlice = p_layer;
  1357. uav_desc.Texture2DArray.ArraySize = p_layers;
  1358. } break;
  1359. default:
  1360. break;
  1361. }
  1362. }
  1363. // Bookkeep.
  1364. TextureInfo *tex_info = VersatileResource::allocate<TextureInfo>(resources_allocator);
  1365. tex_info->resource = resource;
  1366. tex_info->states_ptr = owner_tex_info->states_ptr;
  1367. tex_info->format = p_view.format;
  1368. tex_info->desc = new_tex_resource_desc;
  1369. if (p_slice_type == (TextureSliceType)-1) {
  1370. tex_info->base_layer = owner_tex_info->base_layer;
  1371. tex_info->layers = owner_tex_info->layers;
  1372. tex_info->base_mip = owner_tex_info->base_mip;
  1373. tex_info->mipmaps = owner_tex_info->mipmaps;
  1374. } else {
  1375. tex_info->base_layer = p_layer;
  1376. tex_info->layers = p_layers;
  1377. tex_info->base_mip = p_mipmap;
  1378. tex_info->mipmaps = p_mipmaps;
  1379. }
  1380. tex_info->view_descs.srv = srv_desc;
  1381. tex_info->view_descs.uav = uav_desc;
  1382. tex_info->main_texture = owner_tex_info;
  1383. return TextureID(tex_info);
  1384. }
  1385. void RenderingDeviceDriverD3D12::texture_free(TextureID p_texture) {
  1386. TextureInfo *tex_info = (TextureInfo *)p_texture.id;
  1387. VersatileResource::free(resources_allocator, tex_info);
  1388. }
  1389. uint64_t RenderingDeviceDriverD3D12::texture_get_allocation_size(TextureID p_texture) {
  1390. const TextureInfo *tex_info = (const TextureInfo *)p_texture.id;
  1391. return tex_info->owner_info.allocation ? tex_info->owner_info.allocation->GetSize() : 0;
  1392. }
  1393. void RenderingDeviceDriverD3D12::texture_get_copyable_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) {
  1394. TextureInfo *tex_info = (TextureInfo *)p_texture.id;
  1395. UINT subresource = tex_info->desc.CalcSubresource(p_subresource.mipmap, p_subresource.layer, 0);
  1396. D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint = {};
  1397. UINT64 subresource_total_size = 0;
  1398. device->GetCopyableFootprints(
  1399. &tex_info->desc,
  1400. subresource,
  1401. 1,
  1402. 0,
  1403. &footprint,
  1404. nullptr,
  1405. nullptr,
  1406. &subresource_total_size);
  1407. *r_layout = {};
  1408. r_layout->offset = footprint.Offset;
  1409. r_layout->size = subresource_total_size;
  1410. r_layout->row_pitch = footprint.Footprint.RowPitch;
  1411. r_layout->depth_pitch = subresource_total_size / tex_info->desc.Depth();
  1412. r_layout->layer_pitch = subresource_total_size / tex_info->desc.ArraySize();
  1413. }
  1414. uint8_t *RenderingDeviceDriverD3D12::texture_map(TextureID p_texture, const TextureSubresource &p_subresource) {
  1415. TextureInfo *tex_info = (TextureInfo *)p_texture.id;
  1416. #ifdef DEBUG_ENABLED
  1417. ERR_FAIL_COND_V(tex_info->mapped_subresource != UINT_MAX, nullptr);
  1418. #endif
  1419. UINT plane = _compute_plane_slice(tex_info->format, p_subresource.aspect);
  1420. UINT subresource = tex_info->desc.CalcSubresource(p_subresource.mipmap, p_subresource.layer, plane);
  1421. void *data_ptr = nullptr;
  1422. HRESULT res = tex_info->resource->Map(subresource, &VOID_RANGE, &data_ptr);
  1423. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), nullptr, "Map failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  1424. tex_info->mapped_subresource = subresource;
  1425. return (uint8_t *)data_ptr;
  1426. }
  1427. void RenderingDeviceDriverD3D12::texture_unmap(TextureID p_texture) {
  1428. TextureInfo *tex_info = (TextureInfo *)p_texture.id;
  1429. #ifdef DEBUG_ENABLED
  1430. ERR_FAIL_COND(tex_info->mapped_subresource == UINT_MAX);
  1431. #endif
  1432. tex_info->resource->Unmap(tex_info->mapped_subresource, &VOID_RANGE);
  1433. tex_info->mapped_subresource = UINT_MAX;
  1434. }
  1435. BitField<RDD::TextureUsageBits> RenderingDeviceDriverD3D12::texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) {
  1436. D3D12_FEATURE_DATA_FORMAT_SUPPORT srv_rtv_support = {};
  1437. srv_rtv_support.Format = RD_TO_D3D12_FORMAT[p_format].general_format;
  1438. if (srv_rtv_support.Format != DXGI_FORMAT_UNKNOWN) { // Some implementations (i.e., vkd3d-proton) error out instead of returning empty.
  1439. HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &srv_rtv_support, sizeof(srv_rtv_support));
  1440. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), false, "CheckFeatureSupport failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  1441. }
  1442. D3D12_FEATURE_DATA_FORMAT_SUPPORT &uav_support = srv_rtv_support; // Fine for now.
  1443. D3D12_FEATURE_DATA_FORMAT_SUPPORT dsv_support = {};
  1444. dsv_support.Format = RD_TO_D3D12_FORMAT[p_format].dsv_format;
  1445. if (dsv_support.Format != DXGI_FORMAT_UNKNOWN) { // See above.
  1446. HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &dsv_support, sizeof(dsv_support));
  1447. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), false, "CheckFeatureSupport failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  1448. }
  1449. // Everything supported by default makes an all-or-nothing check easier for the caller.
  1450. BitField<RDD::TextureUsageBits> supported = INT64_MAX;
  1451. // Per https://docs.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_format_support1,
  1452. // as long as the resource can be used as a texture, Sample() will work with point filter at least.
  1453. // However, we've empirically found that checking for at least D3D12_FORMAT_SUPPORT1_SHADER_LOAD is needed.
  1454. // That's almost good for integer formats. The problem is that theoretically there may be
  1455. // float formats that support LOAD but not SAMPLE fully, so this check will not detect
  1456. // such a flaw in the format. Linearly interpolated sampling would just not work on them.
  1457. if (!(srv_rtv_support.Support1 & (D3D12_FORMAT_SUPPORT1_SHADER_LOAD | D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE)) ||
  1458. RD_TO_D3D12_FORMAT[p_format].general_format == DXGI_FORMAT_UNKNOWN) {
  1459. supported.clear_flag(TEXTURE_USAGE_SAMPLING_BIT);
  1460. }
  1461. if (!(srv_rtv_support.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET)) {
  1462. supported.clear_flag(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT);
  1463. }
  1464. if (!(dsv_support.Support1 & D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL)) {
  1465. supported.clear_flag(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
  1466. }
  1467. if (!(uav_support.Support1 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW)) { // Maybe check LOAD/STORE, too?
  1468. supported.clear_flag(TEXTURE_USAGE_STORAGE_BIT);
  1469. }
  1470. if (!(uav_support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_ADD)) { // Check a basic atomic at least.
  1471. supported.clear_flag(TEXTURE_USAGE_STORAGE_ATOMIC_BIT);
  1472. }
  1473. if (RD_TO_D3D12_FORMAT[p_format].general_format != DXGI_FORMAT_R8_UINT) {
  1474. supported.clear_flag(TEXTURE_USAGE_VRS_ATTACHMENT_BIT);
  1475. }
  1476. return supported;
  1477. }
  1478. bool RenderingDeviceDriverD3D12::texture_can_make_shared_with_format(TextureID p_texture, DataFormat p_format, bool &r_raw_reinterpretation) {
  1479. r_raw_reinterpretation = false;
  1480. if (format_capabilities.relaxed_casting_supported) {
  1481. // Relaxed casting is supported, there should be no need to check for format family compatibility.
  1482. return true;
  1483. } else {
  1484. TextureInfo *tex_info = (TextureInfo *)p_texture.id;
  1485. if (tex_info->format == DATA_FORMAT_R16_UINT && p_format == DATA_FORMAT_R4G4B4A4_UNORM_PACK16) {
  1486. // Specific cases that require buffer reinterpretation.
  1487. r_raw_reinterpretation = true;
  1488. return false;
  1489. } else if (RD_TO_D3D12_FORMAT[tex_info->format].family != RD_TO_D3D12_FORMAT[p_format].family) {
  1490. // Format family is different but copying resources directly is possible.
  1491. return false;
  1492. } else {
  1493. // Format family is the same and the view can just cast the format.
  1494. return true;
  1495. }
  1496. }
  1497. }
  1498. /*****************/
  1499. /**** SAMPLER ****/
  1500. /*****************/
  1501. static const D3D12_TEXTURE_ADDRESS_MODE RD_REPEAT_MODE_TO_D3D12_ADDRES_MODE[RDD::SAMPLER_REPEAT_MODE_MAX] = {
  1502. D3D12_TEXTURE_ADDRESS_MODE_WRAP,
  1503. D3D12_TEXTURE_ADDRESS_MODE_MIRROR,
  1504. D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  1505. D3D12_TEXTURE_ADDRESS_MODE_BORDER,
  1506. D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE,
  1507. };
  1508. static const FLOAT RD_TO_D3D12_SAMPLER_BORDER_COLOR[RDD::SAMPLER_BORDER_COLOR_MAX][4] = {
  1509. { 0, 0, 0, 0 },
  1510. { 0, 0, 0, 0 },
  1511. { 0, 0, 0, 1 },
  1512. { 0, 0, 0, 1 },
  1513. { 1, 1, 1, 1 },
  1514. { 1, 1, 1, 1 },
  1515. };
  1516. RDD::SamplerID RenderingDeviceDriverD3D12::sampler_create(const SamplerState &p_state) {
  1517. uint32_t slot = UINT32_MAX;
  1518. if (samplers.is_empty()) {
  1519. // Adding a seemigly busy slot 0 makes things easier elsewhere.
  1520. samplers.push_back({});
  1521. samplers.push_back({});
  1522. slot = 1;
  1523. } else {
  1524. for (uint32_t i = 1; i < samplers.size(); i++) {
  1525. if ((int)samplers[i].Filter == INT_MAX) {
  1526. slot = i;
  1527. break;
  1528. }
  1529. }
  1530. if (slot == UINT32_MAX) {
  1531. slot = samplers.size();
  1532. samplers.push_back({});
  1533. }
  1534. }
  1535. D3D12_SAMPLER_DESC &sampler_desc = samplers[slot];
  1536. if (p_state.use_anisotropy) {
  1537. sampler_desc.Filter = D3D12_ENCODE_ANISOTROPIC_FILTER(D3D12_FILTER_REDUCTION_TYPE_STANDARD);
  1538. sampler_desc.MaxAnisotropy = p_state.anisotropy_max;
  1539. } else {
  1540. static const D3D12_FILTER_TYPE RD_FILTER_TYPE_TO_D3D12[] = {
  1541. D3D12_FILTER_TYPE_POINT, // SAMPLER_FILTER_NEAREST.
  1542. D3D12_FILTER_TYPE_LINEAR, // SAMPLER_FILTER_LINEAR.
  1543. };
  1544. sampler_desc.Filter = D3D12_ENCODE_BASIC_FILTER(
  1545. RD_FILTER_TYPE_TO_D3D12[p_state.min_filter],
  1546. RD_FILTER_TYPE_TO_D3D12[p_state.mag_filter],
  1547. RD_FILTER_TYPE_TO_D3D12[p_state.mip_filter],
  1548. p_state.enable_compare ? D3D12_FILTER_REDUCTION_TYPE_COMPARISON : D3D12_FILTER_REDUCTION_TYPE_STANDARD);
  1549. }
  1550. sampler_desc.AddressU = RD_REPEAT_MODE_TO_D3D12_ADDRES_MODE[p_state.repeat_u];
  1551. sampler_desc.AddressV = RD_REPEAT_MODE_TO_D3D12_ADDRES_MODE[p_state.repeat_v];
  1552. sampler_desc.AddressW = RD_REPEAT_MODE_TO_D3D12_ADDRES_MODE[p_state.repeat_w];
  1553. for (int i = 0; i < 4; i++) {
  1554. sampler_desc.BorderColor[i] = RD_TO_D3D12_SAMPLER_BORDER_COLOR[p_state.border_color][i];
  1555. }
  1556. sampler_desc.MinLOD = p_state.min_lod;
  1557. sampler_desc.MaxLOD = p_state.max_lod;
  1558. sampler_desc.MipLODBias = p_state.lod_bias;
  1559. sampler_desc.ComparisonFunc = p_state.enable_compare ? RD_TO_D3D12_COMPARE_OP[p_state.compare_op] : D3D12_COMPARISON_FUNC_NEVER;
  1560. // TODO: Emulate somehow?
  1561. if (p_state.unnormalized_uvw) {
  1562. WARN_PRINT("Creating a sampler with unnormalized UVW, which is not supported.");
  1563. }
  1564. return SamplerID(slot);
  1565. }
  1566. void RenderingDeviceDriverD3D12::sampler_free(SamplerID p_sampler) {
  1567. samplers[p_sampler.id].Filter = (D3D12_FILTER)INT_MAX;
  1568. }
  1569. bool RenderingDeviceDriverD3D12::sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) {
  1570. D3D12_FEATURE_DATA_FORMAT_SUPPORT srv_rtv_support = {};
  1571. srv_rtv_support.Format = RD_TO_D3D12_FORMAT[p_format].general_format;
  1572. HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &srv_rtv_support, sizeof(srv_rtv_support));
  1573. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), false, "CheckFeatureSupport failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  1574. return (srv_rtv_support.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE);
  1575. }
  1576. /**********************/
  1577. /**** VERTEX ARRAY ****/
  1578. /**********************/
  1579. RDD::VertexFormatID RenderingDeviceDriverD3D12::vertex_format_create(VectorView<VertexAttribute> p_vertex_attribs) {
  1580. VertexFormatInfo *vf_info = VersatileResource::allocate<VertexFormatInfo>(resources_allocator);
  1581. vf_info->input_elem_descs.resize(p_vertex_attribs.size());
  1582. vf_info->vertex_buffer_strides.resize(p_vertex_attribs.size());
  1583. for (uint32_t i = 0; i < p_vertex_attribs.size(); i++) {
  1584. vf_info->input_elem_descs[i] = {};
  1585. vf_info->input_elem_descs[i].SemanticName = "TEXCOORD";
  1586. vf_info->input_elem_descs[i].SemanticIndex = p_vertex_attribs[i].location;
  1587. vf_info->input_elem_descs[i].Format = RD_TO_D3D12_FORMAT[p_vertex_attribs[i].format].general_format;
  1588. vf_info->input_elem_descs[i].InputSlot = i; // TODO: Can the same slot be used if data comes from the same buffer (regardless format)?
  1589. vf_info->input_elem_descs[i].AlignedByteOffset = p_vertex_attribs[i].offset;
  1590. if (p_vertex_attribs[i].frequency == VERTEX_FREQUENCY_INSTANCE) {
  1591. vf_info->input_elem_descs[i].InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA;
  1592. vf_info->input_elem_descs[i].InstanceDataStepRate = 1;
  1593. } else {
  1594. vf_info->input_elem_descs[i].InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
  1595. vf_info->input_elem_descs[i].InstanceDataStepRate = 0;
  1596. }
  1597. vf_info->vertex_buffer_strides[i] = p_vertex_attribs[i].stride;
  1598. }
  1599. return VertexFormatID(vf_info);
  1600. }
  1601. void RenderingDeviceDriverD3D12::vertex_format_free(VertexFormatID p_vertex_format) {
  1602. VertexFormatInfo *vf_info = (VertexFormatInfo *)p_vertex_format.id;
  1603. VersatileResource::free(resources_allocator, vf_info);
  1604. }
  1605. /******************/
  1606. /**** BARRIERS ****/
  1607. /******************/
  1608. static D3D12_BARRIER_ACCESS _rd_texture_layout_access_mask(RDD::TextureLayout p_texture_layout) {
  1609. switch (p_texture_layout) {
  1610. case RDD::TEXTURE_LAYOUT_STORAGE_OPTIMAL:
  1611. return D3D12_BARRIER_ACCESS_UNORDERED_ACCESS;
  1612. case RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
  1613. return D3D12_BARRIER_ACCESS_RENDER_TARGET;
  1614. case RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
  1615. return D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ | D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE;
  1616. case RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
  1617. return D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ;
  1618. case RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
  1619. return D3D12_BARRIER_ACCESS_SHADER_RESOURCE;
  1620. case RDD::TEXTURE_LAYOUT_COPY_SRC_OPTIMAL:
  1621. return D3D12_BARRIER_ACCESS_COPY_SOURCE;
  1622. case RDD::TEXTURE_LAYOUT_COPY_DST_OPTIMAL:
  1623. return D3D12_BARRIER_ACCESS_COPY_DEST;
  1624. case RDD::TEXTURE_LAYOUT_RESOLVE_SRC_OPTIMAL:
  1625. return D3D12_BARRIER_ACCESS_RESOLVE_SOURCE;
  1626. case RDD::TEXTURE_LAYOUT_RESOLVE_DST_OPTIMAL:
  1627. return D3D12_BARRIER_ACCESS_RESOLVE_DEST;
  1628. case RDD::TEXTURE_LAYOUT_VRS_ATTACHMENT_OPTIMAL:
  1629. return D3D12_BARRIER_ACCESS_SHADING_RATE_SOURCE;
  1630. default:
  1631. return D3D12_BARRIER_ACCESS_NO_ACCESS;
  1632. }
  1633. }
  1634. static void _rd_access_to_d3d12_and_mask(BitField<RDD::BarrierAccessBits> p_access, RDD::TextureLayout p_texture_layout, D3D12_BARRIER_ACCESS &r_access, D3D12_BARRIER_SYNC &r_sync_mask) {
  1635. r_access = D3D12_BARRIER_ACCESS_COMMON;
  1636. r_sync_mask = D3D12_BARRIER_SYNC_NONE;
  1637. if (p_access.has_flag(RDD::BARRIER_ACCESS_INDIRECT_COMMAND_READ_BIT)) {
  1638. r_access |= D3D12_BARRIER_ACCESS_INDIRECT_ARGUMENT;
  1639. r_sync_mask |= D3D12_BARRIER_SYNC_EXECUTE_INDIRECT;
  1640. }
  1641. if (p_access.has_flag(RDD::BARRIER_ACCESS_INDEX_READ_BIT)) {
  1642. r_access |= D3D12_BARRIER_ACCESS_INDEX_BUFFER;
  1643. r_sync_mask |= D3D12_BARRIER_SYNC_INDEX_INPUT | D3D12_BARRIER_SYNC_DRAW;
  1644. }
  1645. if (p_access.has_flag(RDD::BARRIER_ACCESS_VERTEX_ATTRIBUTE_READ_BIT)) {
  1646. r_access |= D3D12_BARRIER_ACCESS_VERTEX_BUFFER;
  1647. r_sync_mask |= D3D12_BARRIER_SYNC_VERTEX_SHADING | D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_ALL_SHADING;
  1648. }
  1649. if (p_access.has_flag(RDD::BARRIER_ACCESS_UNIFORM_READ_BIT)) {
  1650. r_access |= D3D12_BARRIER_ACCESS_CONSTANT_BUFFER;
  1651. r_sync_mask |= D3D12_BARRIER_SYNC_VERTEX_SHADING | D3D12_BARRIER_SYNC_PIXEL_SHADING | D3D12_BARRIER_SYNC_COMPUTE_SHADING |
  1652. D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_ALL_SHADING;
  1653. }
  1654. if (p_access.has_flag(RDD::BARRIER_ACCESS_INPUT_ATTACHMENT_READ_BIT)) {
  1655. r_access |= D3D12_BARRIER_ACCESS_RENDER_TARGET;
  1656. r_sync_mask |= D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_RENDER_TARGET;
  1657. }
  1658. if (p_access.has_flag(RDD::BARRIER_ACCESS_COPY_READ_BIT)) {
  1659. r_access |= D3D12_BARRIER_ACCESS_COPY_SOURCE;
  1660. r_sync_mask |= D3D12_BARRIER_SYNC_COPY;
  1661. }
  1662. if (p_access.has_flag(RDD::BARRIER_ACCESS_COPY_WRITE_BIT)) {
  1663. r_access |= D3D12_BARRIER_ACCESS_COPY_DEST;
  1664. r_sync_mask |= D3D12_BARRIER_SYNC_COPY;
  1665. }
  1666. if (p_access.has_flag(RDD::BARRIER_ACCESS_RESOLVE_READ_BIT)) {
  1667. r_access |= D3D12_BARRIER_ACCESS_RESOLVE_SOURCE;
  1668. r_sync_mask |= D3D12_BARRIER_SYNC_RESOLVE;
  1669. }
  1670. if (p_access.has_flag(RDD::BARRIER_ACCESS_RESOLVE_WRITE_BIT)) {
  1671. r_access |= D3D12_BARRIER_ACCESS_RESOLVE_DEST;
  1672. r_sync_mask |= D3D12_BARRIER_SYNC_RESOLVE;
  1673. }
  1674. if (p_access.has_flag(RDD::BARRIER_ACCESS_FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT)) {
  1675. r_access |= D3D12_BARRIER_ACCESS_SHADING_RATE_SOURCE;
  1676. r_sync_mask |= D3D12_BARRIER_SYNC_PIXEL_SHADING | D3D12_BARRIER_SYNC_ALL_SHADING;
  1677. }
  1678. const D3D12_BARRIER_SYNC unordered_access_mask = D3D12_BARRIER_SYNC_VERTEX_SHADING | D3D12_BARRIER_SYNC_PIXEL_SHADING | D3D12_BARRIER_SYNC_COMPUTE_SHADING |
  1679. D3D12_BARRIER_SYNC_VERTEX_SHADING | D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_ALL_SHADING | D3D12_BARRIER_SYNC_CLEAR_UNORDERED_ACCESS_VIEW;
  1680. if (p_access.has_flag(RDD::BARRIER_ACCESS_STORAGE_CLEAR_BIT)) {
  1681. r_access |= D3D12_BARRIER_ACCESS_UNORDERED_ACCESS;
  1682. r_sync_mask |= unordered_access_mask;
  1683. }
  1684. // These access bits only have compatibility with certain layouts unlike in Vulkan where they imply specific operations in the same layout.
  1685. if (p_access.has_flag(RDD::BARRIER_ACCESS_SHADER_WRITE_BIT)) {
  1686. r_access |= D3D12_BARRIER_ACCESS_UNORDERED_ACCESS;
  1687. r_sync_mask |= unordered_access_mask;
  1688. } else if (p_access.has_flag(RDD::BARRIER_ACCESS_SHADER_READ_BIT)) {
  1689. if (p_texture_layout == RDD::TEXTURE_LAYOUT_STORAGE_OPTIMAL) {
  1690. // Unordered access must be enforced if the texture is using the storage layout.
  1691. r_access |= D3D12_BARRIER_ACCESS_UNORDERED_ACCESS;
  1692. r_sync_mask |= unordered_access_mask;
  1693. } else {
  1694. r_access |= D3D12_BARRIER_ACCESS_SHADER_RESOURCE;
  1695. r_sync_mask |= D3D12_BARRIER_SYNC_VERTEX_SHADING | D3D12_BARRIER_SYNC_PIXEL_SHADING | D3D12_BARRIER_SYNC_COMPUTE_SHADING | D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_ALL_SHADING;
  1696. }
  1697. }
  1698. if (p_access.has_flag(RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT) || p_access.has_flag(RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_READ_BIT)) {
  1699. r_access |= D3D12_BARRIER_ACCESS_RENDER_TARGET;
  1700. r_sync_mask |= D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_RENDER_TARGET;
  1701. }
  1702. if (p_access.has_flag(RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT)) {
  1703. r_access |= D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE;
  1704. r_sync_mask |= D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_DEPTH_STENCIL;
  1705. } else if (p_access.has_flag(RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT)) {
  1706. r_access |= D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ;
  1707. r_sync_mask |= D3D12_BARRIER_SYNC_DRAW | D3D12_BARRIER_SYNC_DEPTH_STENCIL;
  1708. }
  1709. }
  1710. static void _rd_stages_to_d3d12(BitField<RDD::PipelineStageBits> p_stages, D3D12_BARRIER_SYNC &r_sync) {
  1711. if (p_stages.has_flag(RDD::PIPELINE_STAGE_ALL_COMMANDS_BIT)) {
  1712. r_sync = D3D12_BARRIER_SYNC_ALL;
  1713. } else {
  1714. if (p_stages.has_flag(RDD::PIPELINE_STAGE_DRAW_INDIRECT_BIT)) {
  1715. r_sync |= D3D12_BARRIER_SYNC_EXECUTE_INDIRECT;
  1716. }
  1717. if (p_stages.has_flag(RDD::PIPELINE_STAGE_VERTEX_INPUT_BIT)) {
  1718. r_sync |= D3D12_BARRIER_SYNC_INDEX_INPUT;
  1719. }
  1720. if (p_stages.has_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT)) {
  1721. r_sync |= D3D12_BARRIER_SYNC_VERTEX_SHADING;
  1722. }
  1723. if (p_stages.has_flag(RDD::PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT) || p_stages.has_flag(RDD::PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT) || p_stages.has_flag(RDD::PIPELINE_STAGE_GEOMETRY_SHADER_BIT)) {
  1724. // There's no granularity for tessellation or geometry stages. The specification defines it as part of vertex shading.
  1725. r_sync |= D3D12_BARRIER_SYNC_VERTEX_SHADING;
  1726. }
  1727. if (p_stages.has_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT)) {
  1728. r_sync |= D3D12_BARRIER_SYNC_PIXEL_SHADING;
  1729. }
  1730. if (p_stages.has_flag(RDD::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT) || p_stages.has_flag(RDD::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT)) {
  1731. // Covers both read and write operations for depth stencil.
  1732. r_sync |= D3D12_BARRIER_SYNC_DEPTH_STENCIL;
  1733. }
  1734. if (p_stages.has_flag(RDD::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT)) {
  1735. r_sync |= D3D12_BARRIER_SYNC_RENDER_TARGET;
  1736. }
  1737. if (p_stages.has_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT)) {
  1738. r_sync |= D3D12_BARRIER_SYNC_COMPUTE_SHADING;
  1739. }
  1740. if (p_stages.has_flag(RDD::PIPELINE_STAGE_COPY_BIT)) {
  1741. r_sync |= D3D12_BARRIER_SYNC_COPY;
  1742. }
  1743. if (p_stages.has_flag(RDD::PIPELINE_STAGE_RESOLVE_BIT)) {
  1744. r_sync |= D3D12_BARRIER_SYNC_RESOLVE;
  1745. }
  1746. if (p_stages.has_flag(RDD::PIPELINE_STAGE_CLEAR_STORAGE_BIT)) {
  1747. r_sync |= D3D12_BARRIER_SYNC_CLEAR_UNORDERED_ACCESS_VIEW;
  1748. }
  1749. if (p_stages.has_flag(RDD::PIPELINE_STAGE_ALL_GRAPHICS_BIT)) {
  1750. r_sync |= D3D12_BARRIER_SYNC_DRAW;
  1751. }
  1752. }
  1753. }
  1754. static void _rd_stages_and_access_to_d3d12(BitField<RDD::PipelineStageBits> p_stages, RDD::TextureLayout p_texture_layout, BitField<RDD::BarrierAccessBits> p_access, D3D12_BARRIER_SYNC &r_sync, D3D12_BARRIER_ACCESS &r_access) {
  1755. D3D12_BARRIER_SYNC sync_mask;
  1756. r_sync = D3D12_BARRIER_SYNC_NONE;
  1757. if (p_texture_layout == RDD::TEXTURE_LAYOUT_UNDEFINED) {
  1758. // Undefined texture layouts are a special case where no access bits or synchronization scopes are allowed.
  1759. r_access = D3D12_BARRIER_ACCESS_NO_ACCESS;
  1760. return;
  1761. }
  1762. // Convert access bits to the D3D12 barrier access bits.
  1763. _rd_access_to_d3d12_and_mask(p_access, p_texture_layout, r_access, sync_mask);
  1764. if (p_texture_layout != RDD::TEXTURE_LAYOUT_MAX) {
  1765. // Only allow the access bits compatible with the texture layout.
  1766. r_access &= _rd_texture_layout_access_mask(p_texture_layout);
  1767. }
  1768. // Convert stage bits to the D3D12 synchronization scope bits.
  1769. _rd_stages_to_d3d12(p_stages, r_sync);
  1770. // Only enable synchronization stages compatible with the access bits that were used.
  1771. r_sync &= sync_mask;
  1772. if (r_sync == D3D12_BARRIER_SYNC_NONE) {
  1773. if (p_access.is_empty()) {
  1774. // No valid synchronization scope was defined and no access in particular is required.
  1775. r_access = D3D12_BARRIER_ACCESS_NO_ACCESS;
  1776. } else {
  1777. // Access is required but the synchronization scope wasn't compatible. We fall back to the global synchronization scope and access.
  1778. r_sync = D3D12_BARRIER_SYNC_ALL;
  1779. r_access = D3D12_BARRIER_ACCESS_COMMON;
  1780. }
  1781. }
  1782. }
  1783. static D3D12_BARRIER_LAYOUT _rd_texture_layout_to_d3d12_barrier_layout(RDD::TextureLayout p_texture_layout) {
  1784. switch (p_texture_layout) {
  1785. case RDD::TEXTURE_LAYOUT_UNDEFINED:
  1786. return D3D12_BARRIER_LAYOUT_UNDEFINED;
  1787. case RDD::TEXTURE_LAYOUT_GENERAL:
  1788. return D3D12_BARRIER_LAYOUT_COMMON;
  1789. case RDD::TEXTURE_LAYOUT_STORAGE_OPTIMAL:
  1790. return D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS;
  1791. case RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
  1792. return D3D12_BARRIER_LAYOUT_RENDER_TARGET;
  1793. case RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
  1794. return D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE;
  1795. case RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
  1796. return D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ;
  1797. case RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
  1798. return D3D12_BARRIER_LAYOUT_SHADER_RESOURCE;
  1799. case RDD::TEXTURE_LAYOUT_COPY_SRC_OPTIMAL:
  1800. return D3D12_BARRIER_LAYOUT_COPY_SOURCE;
  1801. case RDD::TEXTURE_LAYOUT_COPY_DST_OPTIMAL:
  1802. return D3D12_BARRIER_LAYOUT_COPY_DEST;
  1803. case RDD::TEXTURE_LAYOUT_RESOLVE_SRC_OPTIMAL:
  1804. return D3D12_BARRIER_LAYOUT_RESOLVE_SOURCE;
  1805. case RDD::TEXTURE_LAYOUT_RESOLVE_DST_OPTIMAL:
  1806. return D3D12_BARRIER_LAYOUT_RESOLVE_DEST;
  1807. case RDD::TEXTURE_LAYOUT_VRS_ATTACHMENT_OPTIMAL:
  1808. return D3D12_BARRIER_LAYOUT_SHADING_RATE_SOURCE;
  1809. default:
  1810. DEV_ASSERT(false && "Unknown texture layout.");
  1811. return D3D12_BARRIER_LAYOUT_UNDEFINED;
  1812. }
  1813. }
  1814. void RenderingDeviceDriverD3D12::command_pipeline_barrier(CommandBufferID p_cmd_buffer,
  1815. BitField<PipelineStageBits> p_src_stages,
  1816. BitField<PipelineStageBits> p_dst_stages,
  1817. VectorView<RDD::MemoryBarrier> p_memory_barriers,
  1818. VectorView<RDD::BufferBarrier> p_buffer_barriers,
  1819. VectorView<RDD::TextureBarrier> p_texture_barriers) {
  1820. if (!barrier_capabilities.enhanced_barriers_supported) {
  1821. // Enhanced barriers are a requirement for this function.
  1822. return;
  1823. }
  1824. if (p_memory_barriers.size() == 0 && p_buffer_barriers.size() == 0 && p_texture_barriers.size() == 0) {
  1825. // At least one barrier must be present in the arguments.
  1826. return;
  1827. }
  1828. // The command list must support the required interface.
  1829. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)(p_cmd_buffer.id);
  1830. ID3D12GraphicsCommandList7 *cmd_list_7 = nullptr;
  1831. HRESULT res = cmd_buf_info->cmd_list->QueryInterface(IID_PPV_ARGS(&cmd_list_7));
  1832. ERR_FAIL_COND(FAILED(res));
  1833. // Convert the RDD barriers to D3D12 enhanced barriers.
  1834. thread_local LocalVector<D3D12_GLOBAL_BARRIER> global_barriers;
  1835. thread_local LocalVector<D3D12_BUFFER_BARRIER> buffer_barriers;
  1836. thread_local LocalVector<D3D12_TEXTURE_BARRIER> texture_barriers;
  1837. global_barriers.clear();
  1838. buffer_barriers.clear();
  1839. texture_barriers.clear();
  1840. D3D12_GLOBAL_BARRIER global_barrier = {};
  1841. for (uint32_t i = 0; i < p_memory_barriers.size(); i++) {
  1842. const MemoryBarrier &memory_barrier = p_memory_barriers[i];
  1843. _rd_stages_and_access_to_d3d12(p_src_stages, RDD::TEXTURE_LAYOUT_MAX, memory_barrier.src_access, global_barrier.SyncBefore, global_barrier.AccessBefore);
  1844. _rd_stages_and_access_to_d3d12(p_dst_stages, RDD::TEXTURE_LAYOUT_MAX, memory_barrier.dst_access, global_barrier.SyncAfter, global_barrier.AccessAfter);
  1845. global_barriers.push_back(global_barrier);
  1846. }
  1847. D3D12_BUFFER_BARRIER buffer_barrier_d3d12 = {};
  1848. buffer_barrier_d3d12.Offset = 0;
  1849. buffer_barrier_d3d12.Size = UINT64_MAX; // The specification says this must be the size of the buffer barrier.
  1850. for (uint32_t i = 0; i < p_buffer_barriers.size(); i++) {
  1851. const BufferBarrier &buffer_barrier_rd = p_buffer_barriers[i];
  1852. const BufferInfo *buffer_info = (const BufferInfo *)(buffer_barrier_rd.buffer.id);
  1853. _rd_stages_and_access_to_d3d12(p_src_stages, RDD::TEXTURE_LAYOUT_MAX, buffer_barrier_rd.src_access, buffer_barrier_d3d12.SyncBefore, buffer_barrier_d3d12.AccessBefore);
  1854. _rd_stages_and_access_to_d3d12(p_dst_stages, RDD::TEXTURE_LAYOUT_MAX, buffer_barrier_rd.dst_access, buffer_barrier_d3d12.SyncAfter, buffer_barrier_d3d12.AccessAfter);
  1855. buffer_barrier_d3d12.pResource = buffer_info->resource;
  1856. buffer_barriers.push_back(buffer_barrier_d3d12);
  1857. }
  1858. D3D12_TEXTURE_BARRIER texture_barrier_d3d12 = {};
  1859. for (uint32_t i = 0; i < p_texture_barriers.size(); i++) {
  1860. const TextureBarrier &texture_barrier_rd = p_texture_barriers[i];
  1861. const TextureInfo *texture_info = (const TextureInfo *)(texture_barrier_rd.texture.id);
  1862. if (texture_info->main_texture) {
  1863. texture_info = texture_info->main_texture;
  1864. }
  1865. _rd_stages_and_access_to_d3d12(p_src_stages, texture_barrier_rd.prev_layout, texture_barrier_rd.src_access, texture_barrier_d3d12.SyncBefore, texture_barrier_d3d12.AccessBefore);
  1866. _rd_stages_and_access_to_d3d12(p_dst_stages, texture_barrier_rd.next_layout, texture_barrier_rd.dst_access, texture_barrier_d3d12.SyncAfter, texture_barrier_d3d12.AccessAfter);
  1867. texture_barrier_d3d12.LayoutBefore = _rd_texture_layout_to_d3d12_barrier_layout(texture_barrier_rd.prev_layout);
  1868. texture_barrier_d3d12.LayoutAfter = _rd_texture_layout_to_d3d12_barrier_layout(texture_barrier_rd.next_layout);
  1869. texture_barrier_d3d12.pResource = texture_info->resource;
  1870. if (texture_barrier_rd.subresources.mipmap_count == texture_info->mipmaps && texture_barrier_rd.subresources.layer_count == texture_info->layers) {
  1871. // So, all resources. Then, let's be explicit about it so D3D12 doesn't think
  1872. // we are dealing with a subset of subresources.
  1873. texture_barrier_d3d12.Subresources.IndexOrFirstMipLevel = 0xffffffff;
  1874. texture_barrier_d3d12.Subresources.NumMipLevels = 0;
  1875. // Because NumMipLevels == 0, all the other fields are ignored by D3D12.
  1876. } else {
  1877. texture_barrier_d3d12.Subresources.IndexOrFirstMipLevel = texture_barrier_rd.subresources.base_mipmap;
  1878. texture_barrier_d3d12.Subresources.NumMipLevels = texture_barrier_rd.subresources.mipmap_count;
  1879. texture_barrier_d3d12.Subresources.FirstArraySlice = texture_barrier_rd.subresources.base_layer;
  1880. texture_barrier_d3d12.Subresources.NumArraySlices = texture_barrier_rd.subresources.layer_count;
  1881. texture_barrier_d3d12.Subresources.FirstPlane = _compute_plane_slice(texture_info->format, texture_barrier_rd.subresources.aspect);
  1882. texture_barrier_d3d12.Subresources.NumPlanes = format_get_plane_count(texture_info->format);
  1883. }
  1884. texture_barrier_d3d12.Flags = (texture_barrier_rd.prev_layout == RDD::TEXTURE_LAYOUT_UNDEFINED) ? D3D12_TEXTURE_BARRIER_FLAG_DISCARD : D3D12_TEXTURE_BARRIER_FLAG_NONE;
  1885. texture_barriers.push_back(texture_barrier_d3d12);
  1886. }
  1887. // Define the barrier groups and execute.
  1888. D3D12_BARRIER_GROUP barrier_groups[3] = {};
  1889. uint32_t barrier_groups_count = 0;
  1890. if (!global_barriers.is_empty()) {
  1891. D3D12_BARRIER_GROUP &barrier_group = barrier_groups[barrier_groups_count++];
  1892. barrier_group.Type = D3D12_BARRIER_TYPE_GLOBAL;
  1893. barrier_group.NumBarriers = global_barriers.size();
  1894. barrier_group.pGlobalBarriers = global_barriers.ptr();
  1895. }
  1896. if (!buffer_barriers.is_empty()) {
  1897. D3D12_BARRIER_GROUP &barrier_group = barrier_groups[barrier_groups_count++];
  1898. barrier_group.Type = D3D12_BARRIER_TYPE_BUFFER;
  1899. barrier_group.NumBarriers = buffer_barriers.size();
  1900. barrier_group.pBufferBarriers = buffer_barriers.ptr();
  1901. }
  1902. if (!texture_barriers.is_empty()) {
  1903. D3D12_BARRIER_GROUP &barrier_group = barrier_groups[barrier_groups_count++];
  1904. barrier_group.Type = D3D12_BARRIER_TYPE_TEXTURE;
  1905. barrier_group.NumBarriers = texture_barriers.size();
  1906. barrier_group.pTextureBarriers = texture_barriers.ptr();
  1907. }
  1908. cmd_list_7->Barrier(barrier_groups_count, barrier_groups);
  1909. }
  1910. /****************/
  1911. /**** FENCES ****/
  1912. /****************/
  1913. RDD::FenceID RenderingDeviceDriverD3D12::fence_create() {
  1914. ComPtr<ID3D12Fence> d3d_fence;
  1915. HRESULT res = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(d3d_fence.GetAddressOf()));
  1916. ERR_FAIL_COND_V(!SUCCEEDED(res), FenceID());
  1917. HANDLE event_handle = CreateEvent(nullptr, FALSE, FALSE, nullptr);
  1918. ERR_FAIL_NULL_V(event_handle, FenceID());
  1919. FenceInfo *fence = memnew(FenceInfo);
  1920. fence->d3d_fence = d3d_fence;
  1921. fence->event_handle = event_handle;
  1922. return FenceID(fence);
  1923. }
  1924. Error RenderingDeviceDriverD3D12::fence_wait(FenceID p_fence) {
  1925. FenceInfo *fence = (FenceInfo *)(p_fence.id);
  1926. DWORD res = WaitForSingleObjectEx(fence->event_handle, INFINITE, FALSE);
  1927. #ifdef PIX_ENABLED
  1928. PIXNotifyWakeFromFenceSignal(fence->event_handle);
  1929. #endif
  1930. return (res == WAIT_FAILED) ? FAILED : OK;
  1931. }
  1932. void RenderingDeviceDriverD3D12::fence_free(FenceID p_fence) {
  1933. FenceInfo *fence = (FenceInfo *)(p_fence.id);
  1934. CloseHandle(fence->event_handle);
  1935. memdelete(fence);
  1936. }
  1937. /********************/
  1938. /**** SEMAPHORES ****/
  1939. /********************/
  1940. RDD::SemaphoreID RenderingDeviceDriverD3D12::semaphore_create() {
  1941. ComPtr<ID3D12Fence> d3d_fence;
  1942. HRESULT res = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(d3d_fence.GetAddressOf()));
  1943. ERR_FAIL_COND_V(!SUCCEEDED(res), SemaphoreID());
  1944. SemaphoreInfo *semaphore = memnew(SemaphoreInfo);
  1945. semaphore->d3d_fence = d3d_fence;
  1946. return SemaphoreID(semaphore);
  1947. }
  1948. void RenderingDeviceDriverD3D12::semaphore_free(SemaphoreID p_semaphore) {
  1949. SemaphoreInfo *semaphore = (SemaphoreInfo *)(p_semaphore.id);
  1950. memdelete(semaphore);
  1951. }
  1952. /******************/
  1953. /**** COMMANDS ****/
  1954. /******************/
  1955. // ----- QUEUE FAMILY -----
  1956. RDD::CommandQueueFamilyID RenderingDeviceDriverD3D12::command_queue_family_get(BitField<CommandQueueFamilyBits> p_cmd_queue_family_bits, RenderingContextDriver::SurfaceID p_surface) {
  1957. // Return the command list type encoded plus one so zero is an invalid value.
  1958. // The only ones that support presenting to a surface are direct queues.
  1959. if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_GRAPHICS_BIT) || (p_surface != 0)) {
  1960. return CommandQueueFamilyID(D3D12_COMMAND_LIST_TYPE_DIRECT + 1);
  1961. } else if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_COMPUTE_BIT)) {
  1962. return CommandQueueFamilyID(D3D12_COMMAND_LIST_TYPE_COMPUTE + 1);
  1963. } else if (p_cmd_queue_family_bits.has_flag(COMMAND_QUEUE_FAMILY_TRANSFER_BIT)) {
  1964. return CommandQueueFamilyID(D3D12_COMMAND_LIST_TYPE_COPY + 1);
  1965. } else {
  1966. return CommandQueueFamilyID();
  1967. }
  1968. }
  1969. // ----- QUEUE -----
  1970. RDD::CommandQueueID RenderingDeviceDriverD3D12::command_queue_create(CommandQueueFamilyID p_cmd_queue_family, bool p_identify_as_main_queue) {
  1971. ComPtr<ID3D12CommandQueue> d3d_queue;
  1972. D3D12_COMMAND_QUEUE_DESC queue_desc = {};
  1973. queue_desc.Type = (D3D12_COMMAND_LIST_TYPE)(p_cmd_queue_family.id - 1);
  1974. HRESULT res = device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(d3d_queue.GetAddressOf()));
  1975. ERR_FAIL_COND_V(!SUCCEEDED(res), CommandQueueID());
  1976. CommandQueueInfo *command_queue = memnew(CommandQueueInfo);
  1977. command_queue->d3d_queue = d3d_queue;
  1978. return CommandQueueID(command_queue);
  1979. }
  1980. Error RenderingDeviceDriverD3D12::command_queue_execute_and_present(CommandQueueID p_cmd_queue, VectorView<SemaphoreID> p_wait_semaphores, VectorView<CommandBufferID> p_cmd_buffers, VectorView<SemaphoreID> p_cmd_semaphores, FenceID p_cmd_fence, VectorView<SwapChainID> p_swap_chains) {
  1981. CommandQueueInfo *command_queue = (CommandQueueInfo *)(p_cmd_queue.id);
  1982. for (uint32_t i = 0; i < p_wait_semaphores.size(); i++) {
  1983. const SemaphoreInfo *semaphore = (const SemaphoreInfo *)(p_wait_semaphores[i].id);
  1984. command_queue->d3d_queue->Wait(semaphore->d3d_fence.Get(), semaphore->fence_value);
  1985. }
  1986. if (p_cmd_buffers.size() > 0) {
  1987. thread_local LocalVector<ID3D12CommandList *> command_lists;
  1988. command_lists.resize(p_cmd_buffers.size());
  1989. for (uint32_t i = 0; i < p_cmd_buffers.size(); i++) {
  1990. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)(p_cmd_buffers[i].id);
  1991. command_lists[i] = cmd_buf_info->cmd_list.Get();
  1992. }
  1993. command_queue->d3d_queue->ExecuteCommandLists(command_lists.size(), command_lists.ptr());
  1994. for (uint32_t i = 0; i < p_cmd_semaphores.size(); i++) {
  1995. SemaphoreInfo *semaphore = (SemaphoreInfo *)(p_cmd_semaphores[i].id);
  1996. semaphore->fence_value++;
  1997. command_queue->d3d_queue->Signal(semaphore->d3d_fence.Get(), semaphore->fence_value);
  1998. }
  1999. if (p_cmd_fence) {
  2000. FenceInfo *fence = (FenceInfo *)(p_cmd_fence.id);
  2001. fence->fence_value++;
  2002. command_queue->d3d_queue->Signal(fence->d3d_fence.Get(), fence->fence_value);
  2003. fence->d3d_fence->SetEventOnCompletion(fence->fence_value, fence->event_handle);
  2004. }
  2005. }
  2006. HRESULT res;
  2007. bool any_present_failed = false;
  2008. for (uint32_t i = 0; i < p_swap_chains.size(); i++) {
  2009. SwapChain *swap_chain = (SwapChain *)(p_swap_chains[i].id);
  2010. res = swap_chain->d3d_swap_chain->Present(swap_chain->sync_interval, swap_chain->present_flags);
  2011. if (!SUCCEEDED(res)) {
  2012. print_verbose(vformat("D3D12: Presenting swapchain failed with error 0x%08ux.", (uint64_t)res));
  2013. any_present_failed = true;
  2014. }
  2015. }
  2016. return any_present_failed ? FAILED : OK;
  2017. }
  2018. void RenderingDeviceDriverD3D12::command_queue_free(CommandQueueID p_cmd_queue) {
  2019. CommandQueueInfo *command_queue = (CommandQueueInfo *)(p_cmd_queue.id);
  2020. memdelete(command_queue);
  2021. }
  2022. // ----- POOL -----
  2023. RDD::CommandPoolID RenderingDeviceDriverD3D12::command_pool_create(CommandQueueFamilyID p_cmd_queue_family, CommandBufferType p_cmd_buffer_type) {
  2024. CommandPoolInfo *command_pool = memnew(CommandPoolInfo);
  2025. command_pool->queue_family = p_cmd_queue_family;
  2026. command_pool->buffer_type = p_cmd_buffer_type;
  2027. return CommandPoolID(command_pool);
  2028. }
  2029. void RenderingDeviceDriverD3D12::command_pool_free(CommandPoolID p_cmd_pool) {
  2030. CommandPoolInfo *command_pool = (CommandPoolInfo *)(p_cmd_pool.id);
  2031. memdelete(command_pool);
  2032. }
  2033. // ----- BUFFER -----
  2034. RDD::CommandBufferID RenderingDeviceDriverD3D12::command_buffer_create(CommandPoolID p_cmd_pool) {
  2035. DEV_ASSERT(p_cmd_pool);
  2036. const CommandPoolInfo *command_pool = (CommandPoolInfo *)(p_cmd_pool.id);
  2037. D3D12_COMMAND_LIST_TYPE list_type;
  2038. if (command_pool->buffer_type == COMMAND_BUFFER_TYPE_SECONDARY) {
  2039. list_type = D3D12_COMMAND_LIST_TYPE_BUNDLE;
  2040. } else {
  2041. list_type = D3D12_COMMAND_LIST_TYPE(command_pool->queue_family.id - 1);
  2042. }
  2043. ID3D12CommandAllocator *cmd_allocator = nullptr;
  2044. {
  2045. HRESULT res = device->CreateCommandAllocator(list_type, IID_PPV_ARGS(&cmd_allocator));
  2046. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), CommandBufferID(), "CreateCommandAllocator failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  2047. }
  2048. ID3D12GraphicsCommandList *cmd_list = nullptr;
  2049. {
  2050. ComPtr<ID3D12Device4> device_4;
  2051. device->QueryInterface(device_4.GetAddressOf());
  2052. HRESULT res = E_FAIL;
  2053. if (device_4) {
  2054. res = device_4->CreateCommandList1(0, list_type, D3D12_COMMAND_LIST_FLAG_NONE, IID_PPV_ARGS(&cmd_list));
  2055. } else {
  2056. res = device->CreateCommandList(0, list_type, cmd_allocator, nullptr, IID_PPV_ARGS(&cmd_list));
  2057. }
  2058. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), CommandBufferID(), "CreateCommandList failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  2059. if (!device_4) {
  2060. cmd_list->Close();
  2061. }
  2062. }
  2063. // Bookkeep
  2064. CommandBufferInfo *cmd_buf_info = VersatileResource::allocate<CommandBufferInfo>(resources_allocator);
  2065. cmd_buf_info->cmd_allocator = cmd_allocator;
  2066. cmd_buf_info->cmd_list = cmd_list;
  2067. return CommandBufferID(cmd_buf_info);
  2068. }
  2069. bool RenderingDeviceDriverD3D12::command_buffer_begin(CommandBufferID p_cmd_buffer) {
  2070. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  2071. HRESULT res = cmd_buf_info->cmd_allocator->Reset();
  2072. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), false, "Reset failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  2073. res = cmd_buf_info->cmd_list->Reset(cmd_buf_info->cmd_allocator.Get(), nullptr);
  2074. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), false, "Reset failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  2075. return true;
  2076. }
  2077. bool RenderingDeviceDriverD3D12::command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) {
  2078. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  2079. HRESULT res = cmd_buf_info->cmd_allocator->Reset();
  2080. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), false, "Reset failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  2081. res = cmd_buf_info->cmd_list->Reset(cmd_buf_info->cmd_allocator.Get(), nullptr);
  2082. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), false, "Reset failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  2083. return true;
  2084. }
  2085. void RenderingDeviceDriverD3D12::command_buffer_end(CommandBufferID p_cmd_buffer) {
  2086. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  2087. HRESULT res = cmd_buf_info->cmd_list->Close();
  2088. ERR_FAIL_COND_MSG(!SUCCEEDED(res), "Close failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  2089. cmd_buf_info->graphics_pso = nullptr;
  2090. cmd_buf_info->graphics_root_signature_crc = 0;
  2091. cmd_buf_info->compute_pso = nullptr;
  2092. cmd_buf_info->compute_root_signature_crc = 0;
  2093. cmd_buf_info->descriptor_heaps_set = false;
  2094. }
  2095. void RenderingDeviceDriverD3D12::command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView<CommandBufferID> p_secondary_cmd_buffers) {
  2096. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  2097. for (uint32_t i = 0; i < p_secondary_cmd_buffers.size(); i++) {
  2098. const CommandBufferInfo *secondary_cb_info = (const CommandBufferInfo *)p_secondary_cmd_buffers[i].id;
  2099. cmd_buf_info->cmd_list->ExecuteBundle(secondary_cb_info->cmd_list.Get());
  2100. }
  2101. }
  2102. /********************/
  2103. /**** SWAP CHAIN ****/
  2104. /********************/
  2105. void RenderingDeviceDriverD3D12::_swap_chain_release(SwapChain *p_swap_chain) {
  2106. _swap_chain_release_buffers(p_swap_chain);
  2107. p_swap_chain->d3d_swap_chain.Reset();
  2108. }
  2109. void RenderingDeviceDriverD3D12::_swap_chain_release_buffers(SwapChain *p_swap_chain) {
  2110. for (ID3D12Resource *render_target : p_swap_chain->render_targets) {
  2111. render_target->Release();
  2112. }
  2113. p_swap_chain->render_targets.clear();
  2114. p_swap_chain->render_targets_info.clear();
  2115. for (RDD::FramebufferID framebuffer : p_swap_chain->framebuffers) {
  2116. framebuffer_free(framebuffer);
  2117. }
  2118. p_swap_chain->framebuffers.clear();
  2119. }
  2120. RDD::SwapChainID RenderingDeviceDriverD3D12::swap_chain_create(RenderingContextDriver::SurfaceID p_surface) {
  2121. // Create the render pass that will be used to draw to the swap chain's framebuffers.
  2122. RDD::Attachment attachment;
  2123. attachment.format = DATA_FORMAT_R8G8B8A8_UNORM;
  2124. attachment.samples = RDD::TEXTURE_SAMPLES_1;
  2125. attachment.load_op = RDD::ATTACHMENT_LOAD_OP_CLEAR;
  2126. attachment.store_op = RDD::ATTACHMENT_STORE_OP_STORE;
  2127. RDD::Subpass subpass;
  2128. RDD::AttachmentReference color_ref;
  2129. color_ref.attachment = 0;
  2130. color_ref.aspect.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT);
  2131. subpass.color_references.push_back(color_ref);
  2132. RenderPassID render_pass = render_pass_create(attachment, subpass, {}, 1);
  2133. ERR_FAIL_COND_V(!render_pass, SwapChainID());
  2134. // Create the empty swap chain until it is resized.
  2135. SwapChain *swap_chain = memnew(SwapChain);
  2136. swap_chain->surface = p_surface;
  2137. swap_chain->data_format = attachment.format;
  2138. swap_chain->render_pass = render_pass;
  2139. return SwapChainID(swap_chain);
  2140. }
  2141. Error RenderingDeviceDriverD3D12::swap_chain_resize(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, uint32_t p_desired_framebuffer_count) {
  2142. DEV_ASSERT(p_cmd_queue.id != 0);
  2143. DEV_ASSERT(p_swap_chain.id != 0);
  2144. CommandQueueInfo *command_queue = (CommandQueueInfo *)(p_cmd_queue.id);
  2145. SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
  2146. RenderingContextDriverD3D12::Surface *surface = (RenderingContextDriverD3D12::Surface *)(swap_chain->surface);
  2147. if (surface->width == 0 || surface->height == 0) {
  2148. // Very likely the window is minimized, don't create a swap chain.
  2149. return ERR_SKIP;
  2150. }
  2151. HRESULT res;
  2152. const bool is_tearing_supported = context_driver->get_tearing_supported();
  2153. UINT sync_interval = 0;
  2154. UINT present_flags = 0;
  2155. UINT creation_flags = 0;
  2156. switch (surface->vsync_mode) {
  2157. case DisplayServer::VSYNC_MAILBOX: {
  2158. sync_interval = 1;
  2159. present_flags = DXGI_PRESENT_RESTART;
  2160. } break;
  2161. case DisplayServer::VSYNC_ENABLED: {
  2162. sync_interval = 1;
  2163. present_flags = 0;
  2164. } break;
  2165. case DisplayServer::VSYNC_DISABLED: {
  2166. sync_interval = 0;
  2167. present_flags = is_tearing_supported ? DXGI_PRESENT_ALLOW_TEARING : 0;
  2168. creation_flags = is_tearing_supported ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;
  2169. } break;
  2170. case DisplayServer::VSYNC_ADAPTIVE: // Unsupported.
  2171. default:
  2172. sync_interval = 1;
  2173. present_flags = 0;
  2174. break;
  2175. }
  2176. print_verbose("Using swap chain flags: " + itos(creation_flags) + ", sync interval: " + itos(sync_interval) + ", present flags: " + itos(present_flags));
  2177. if (swap_chain->d3d_swap_chain != nullptr && creation_flags != swap_chain->creation_flags) {
  2178. // The swap chain must be recreated if the creation flags are different.
  2179. _swap_chain_release(swap_chain);
  2180. }
  2181. DXGI_SWAP_CHAIN_DESC1 swap_chain_desc = {};
  2182. if (swap_chain->d3d_swap_chain != nullptr) {
  2183. _swap_chain_release_buffers(swap_chain);
  2184. res = swap_chain->d3d_swap_chain->ResizeBuffers(p_desired_framebuffer_count, 0, 0, DXGI_FORMAT_UNKNOWN, creation_flags);
  2185. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_UNAVAILABLE);
  2186. } else {
  2187. swap_chain_desc.BufferCount = p_desired_framebuffer_count;
  2188. swap_chain_desc.Format = RD_TO_D3D12_FORMAT[swap_chain->data_format].general_format;
  2189. swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  2190. swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
  2191. swap_chain_desc.SampleDesc.Count = 1;
  2192. swap_chain_desc.Flags = creation_flags;
  2193. swap_chain_desc.Scaling = DXGI_SCALING_NONE;
  2194. if (OS::get_singleton()->is_layered_allowed()) {
  2195. swap_chain_desc.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
  2196. has_comp_alpha[(uint64_t)p_cmd_queue.id] = true;
  2197. } else {
  2198. swap_chain_desc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
  2199. has_comp_alpha[(uint64_t)p_cmd_queue.id] = false;
  2200. }
  2201. ComPtr<IDXGISwapChain1> swap_chain_1;
  2202. res = context_driver->dxgi_factory_get()->CreateSwapChainForHwnd(command_queue->d3d_queue.Get(), surface->hwnd, &swap_chain_desc, nullptr, nullptr, swap_chain_1.GetAddressOf());
  2203. if (!SUCCEEDED(res) && swap_chain_desc.AlphaMode != DXGI_ALPHA_MODE_IGNORE) {
  2204. swap_chain_desc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
  2205. has_comp_alpha[(uint64_t)p_cmd_queue.id] = false;
  2206. res = context_driver->dxgi_factory_get()->CreateSwapChainForHwnd(command_queue->d3d_queue.Get(), surface->hwnd, &swap_chain_desc, nullptr, nullptr, swap_chain_1.GetAddressOf());
  2207. }
  2208. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  2209. swap_chain_1.As(&swap_chain->d3d_swap_chain);
  2210. ERR_FAIL_NULL_V(swap_chain->d3d_swap_chain, ERR_CANT_CREATE);
  2211. res = context_driver->dxgi_factory_get()->MakeWindowAssociation(surface->hwnd, DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_WINDOW_CHANGES);
  2212. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  2213. }
  2214. res = swap_chain->d3d_swap_chain->GetDesc1(&swap_chain_desc);
  2215. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  2216. ERR_FAIL_COND_V(swap_chain_desc.BufferCount == 0, ERR_CANT_CREATE);
  2217. surface->width = swap_chain_desc.Width;
  2218. surface->height = swap_chain_desc.Height;
  2219. swap_chain->creation_flags = creation_flags;
  2220. swap_chain->sync_interval = sync_interval;
  2221. swap_chain->present_flags = present_flags;
  2222. // Retrieve the render targets associated to the swap chain and recreate the framebuffers. The following code
  2223. // relies on the address of the elements remaining static when new elements are inserted, so the container must
  2224. // follow this restriction when reserving the right amount of elements beforehand.
  2225. swap_chain->render_targets.reserve(swap_chain_desc.BufferCount);
  2226. swap_chain->render_targets_info.reserve(swap_chain_desc.BufferCount);
  2227. swap_chain->framebuffers.reserve(swap_chain_desc.BufferCount);
  2228. for (uint32_t i = 0; i < swap_chain_desc.BufferCount; i++) {
  2229. // Retrieve the resource corresponding to the swap chain's buffer.
  2230. ID3D12Resource *render_target = nullptr;
  2231. res = swap_chain->d3d_swap_chain->GetBuffer(i, IID_PPV_ARGS(&render_target));
  2232. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  2233. swap_chain->render_targets.push_back(render_target);
  2234. // Create texture information for the framebuffer to reference the resource. Since the states pointer must
  2235. // reference an address of the element itself, we must insert it first and then modify it.
  2236. swap_chain->render_targets_info.push_back(TextureInfo());
  2237. TextureInfo &texture_info = swap_chain->render_targets_info[i];
  2238. texture_info.owner_info.states.subresource_states.push_back(D3D12_RESOURCE_STATE_PRESENT);
  2239. texture_info.states_ptr = &texture_info.owner_info.states;
  2240. texture_info.format = swap_chain->data_format;
  2241. #if defined(_MSC_VER) || !defined(_WIN32)
  2242. texture_info.desc = CD3DX12_RESOURCE_DESC(render_target->GetDesc());
  2243. #else
  2244. render_target->GetDesc(&texture_info.desc);
  2245. #endif
  2246. texture_info.layers = 1;
  2247. texture_info.mipmaps = 1;
  2248. texture_info.resource = render_target;
  2249. texture_info.view_descs.srv.Format = texture_info.desc.Format;
  2250. texture_info.view_descs.srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
  2251. // Create the framebuffer for this buffer.
  2252. FramebufferID framebuffer = _framebuffer_create(swap_chain->render_pass, TextureID(&swap_chain->render_targets_info[i]), swap_chain_desc.Width, swap_chain_desc.Height, true);
  2253. ERR_FAIL_COND_V(!framebuffer, ERR_CANT_CREATE);
  2254. swap_chain->framebuffers.push_back(framebuffer);
  2255. }
  2256. // Once everything's been created correctly, indicate the surface no longer needs to be resized.
  2257. context_driver->surface_set_needs_resize(swap_chain->surface, false);
  2258. return OK;
  2259. }
  2260. RDD::FramebufferID RenderingDeviceDriverD3D12::swap_chain_acquire_framebuffer(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, bool &r_resize_required) {
  2261. DEV_ASSERT(p_swap_chain.id != 0);
  2262. const SwapChain *swap_chain = (const SwapChain *)(p_swap_chain.id);
  2263. if (context_driver->surface_get_needs_resize(swap_chain->surface)) {
  2264. r_resize_required = true;
  2265. return FramebufferID();
  2266. }
  2267. const uint32_t buffer_index = swap_chain->d3d_swap_chain->GetCurrentBackBufferIndex();
  2268. DEV_ASSERT(buffer_index < swap_chain->framebuffers.size());
  2269. return swap_chain->framebuffers[buffer_index];
  2270. }
  2271. RDD::RenderPassID RenderingDeviceDriverD3D12::swap_chain_get_render_pass(SwapChainID p_swap_chain) {
  2272. const SwapChain *swap_chain = (const SwapChain *)(p_swap_chain.id);
  2273. return swap_chain->render_pass;
  2274. }
  2275. RDD::DataFormat RenderingDeviceDriverD3D12::swap_chain_get_format(SwapChainID p_swap_chain) {
  2276. const SwapChain *swap_chain = (const SwapChain *)(p_swap_chain.id);
  2277. return swap_chain->data_format;
  2278. }
  2279. void RenderingDeviceDriverD3D12::swap_chain_free(SwapChainID p_swap_chain) {
  2280. SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
  2281. _swap_chain_release(swap_chain);
  2282. render_pass_free(swap_chain->render_pass);
  2283. memdelete(swap_chain);
  2284. }
  2285. /*********************/
  2286. /**** FRAMEBUFFER ****/
  2287. /*********************/
  2288. D3D12_RENDER_TARGET_VIEW_DESC RenderingDeviceDriverD3D12::_make_rtv_for_texture(const TextureInfo *p_texture_info, uint32_t p_mipmap_offset, uint32_t p_layer_offset, uint32_t p_layers, bool p_add_bases) {
  2289. D3D12_RENDER_TARGET_VIEW_DESC rtv_desc = {};
  2290. rtv_desc.Format = p_texture_info->view_descs.srv.Format;
  2291. switch (p_texture_info->view_descs.srv.ViewDimension) {
  2292. case D3D12_SRV_DIMENSION_TEXTURE1D: {
  2293. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1D;
  2294. rtv_desc.Texture1D.MipSlice = p_texture_info->base_mip + p_mipmap_offset;
  2295. } break;
  2296. case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: {
  2297. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1DARRAY;
  2298. rtv_desc.Texture1DArray.MipSlice = (p_add_bases ? p_texture_info->base_mip : 0) + p_mipmap_offset;
  2299. rtv_desc.Texture1DArray.FirstArraySlice = (p_add_bases ? p_texture_info->base_layer : 0) + p_layer_offset;
  2300. rtv_desc.Texture1DArray.ArraySize = p_layers == UINT32_MAX ? p_texture_info->view_descs.srv.Texture1DArray.ArraySize : p_layers;
  2301. } break;
  2302. case D3D12_SRV_DIMENSION_TEXTURE2D: {
  2303. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
  2304. rtv_desc.Texture2D.MipSlice = (p_add_bases ? p_texture_info->base_mip : 0) + p_mipmap_offset;
  2305. rtv_desc.Texture2D.PlaneSlice = p_texture_info->view_descs.srv.Texture2D.PlaneSlice;
  2306. } break;
  2307. case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: {
  2308. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
  2309. rtv_desc.Texture2DArray.MipSlice = (p_add_bases ? p_texture_info->base_mip : 0) + p_mipmap_offset;
  2310. rtv_desc.Texture2DArray.FirstArraySlice = (p_add_bases ? p_texture_info->base_layer : 0) + p_layer_offset;
  2311. rtv_desc.Texture2DArray.ArraySize = p_layers == UINT32_MAX ? p_texture_info->view_descs.srv.Texture2DArray.ArraySize : p_layers;
  2312. rtv_desc.Texture2DArray.PlaneSlice = p_texture_info->view_descs.srv.Texture2DArray.PlaneSlice;
  2313. } break;
  2314. case D3D12_SRV_DIMENSION_TEXTURE2DMS: {
  2315. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS;
  2316. } break;
  2317. case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: {
  2318. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY;
  2319. rtv_desc.Texture2DMSArray.FirstArraySlice = (p_add_bases ? p_texture_info->base_layer : 0) + p_layer_offset;
  2320. rtv_desc.Texture2DMSArray.ArraySize = p_layers == UINT32_MAX ? p_texture_info->view_descs.srv.Texture2DMSArray.ArraySize : p_layers;
  2321. } break;
  2322. case D3D12_SRV_DIMENSION_TEXTURE3D: {
  2323. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D;
  2324. rtv_desc.Texture3D.MipSlice = p_texture_info->view_descs.srv.Texture3D.MostDetailedMip + p_mipmap_offset;
  2325. rtv_desc.Texture3D.FirstWSlice = 0;
  2326. rtv_desc.Texture3D.WSize = -1;
  2327. } break;
  2328. case D3D12_SRV_DIMENSION_TEXTURECUBE:
  2329. case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: {
  2330. rtv_desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
  2331. rtv_desc.Texture2DArray.MipSlice = (p_add_bases ? p_texture_info->base_mip : 0) + p_mipmap_offset;
  2332. rtv_desc.Texture2DArray.FirstArraySlice = (p_add_bases ? p_texture_info->base_layer : 0) + p_layer_offset;
  2333. rtv_desc.Texture2DArray.ArraySize = p_layers == UINT32_MAX ? p_texture_info->layers : p_layers;
  2334. rtv_desc.Texture2DArray.PlaneSlice = 0;
  2335. } break;
  2336. default: {
  2337. DEV_ASSERT(false);
  2338. }
  2339. }
  2340. return rtv_desc;
  2341. }
  2342. D3D12_UNORDERED_ACCESS_VIEW_DESC RenderingDeviceDriverD3D12::_make_ranged_uav_for_texture(const TextureInfo *p_texture_info, uint32_t p_mipmap_offset, uint32_t p_layer_offset, uint32_t p_layers, bool p_add_bases) {
  2343. D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc = p_texture_info->view_descs.uav;
  2344. uint32_t mip = (p_add_bases ? p_texture_info->base_mip : 0) + p_mipmap_offset;
  2345. switch (p_texture_info->view_descs.uav.ViewDimension) {
  2346. case D3D12_UAV_DIMENSION_TEXTURE1D: {
  2347. uav_desc.Texture1DArray.MipSlice = mip;
  2348. } break;
  2349. case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: {
  2350. uav_desc.Texture1DArray.MipSlice = mip;
  2351. uav_desc.Texture1DArray.FirstArraySlice = mip;
  2352. uav_desc.Texture1DArray.ArraySize = p_layers;
  2353. } break;
  2354. case D3D12_UAV_DIMENSION_TEXTURE2D: {
  2355. uav_desc.Texture2D.MipSlice = mip;
  2356. } break;
  2357. case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: {
  2358. uav_desc.Texture2DArray.MipSlice = mip;
  2359. uav_desc.Texture2DArray.FirstArraySlice = (p_add_bases ? p_texture_info->base_layer : 0) + p_layer_offset;
  2360. uav_desc.Texture2DArray.ArraySize = p_layers;
  2361. } break;
  2362. case D3D12_UAV_DIMENSION_TEXTURE3D: {
  2363. uav_desc.Texture3D.MipSlice = mip;
  2364. uav_desc.Texture3D.WSize >>= p_mipmap_offset;
  2365. } break;
  2366. default:
  2367. break;
  2368. }
  2369. return uav_desc;
  2370. }
  2371. D3D12_DEPTH_STENCIL_VIEW_DESC RenderingDeviceDriverD3D12::_make_dsv_for_texture(const TextureInfo *p_texture_info) {
  2372. D3D12_DEPTH_STENCIL_VIEW_DESC dsv_desc = {};
  2373. dsv_desc.Format = RD_TO_D3D12_FORMAT[p_texture_info->format].dsv_format;
  2374. dsv_desc.Flags = D3D12_DSV_FLAG_NONE;
  2375. switch (p_texture_info->view_descs.srv.ViewDimension) {
  2376. case D3D12_SRV_DIMENSION_TEXTURE1D: {
  2377. dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1D;
  2378. dsv_desc.Texture1D.MipSlice = p_texture_info->base_mip;
  2379. } break;
  2380. case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: {
  2381. dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1DARRAY;
  2382. dsv_desc.Texture1DArray.MipSlice = p_texture_info->base_mip;
  2383. dsv_desc.Texture1DArray.FirstArraySlice = p_texture_info->base_layer;
  2384. dsv_desc.Texture1DArray.ArraySize = p_texture_info->view_descs.srv.Texture1DArray.ArraySize;
  2385. } break;
  2386. case D3D12_SRV_DIMENSION_TEXTURE2D: {
  2387. dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
  2388. dsv_desc.Texture2D.MipSlice = p_texture_info->view_descs.srv.Texture2D.MostDetailedMip;
  2389. } break;
  2390. case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: {
  2391. dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY;
  2392. dsv_desc.Texture2DArray.MipSlice = p_texture_info->base_mip;
  2393. dsv_desc.Texture2DArray.FirstArraySlice = p_texture_info->base_layer;
  2394. dsv_desc.Texture2DArray.ArraySize = p_texture_info->view_descs.srv.Texture2DArray.ArraySize;
  2395. } break;
  2396. case D3D12_SRV_DIMENSION_TEXTURE2DMS: {
  2397. dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMS;
  2398. dsv_desc.Texture2DMS.UnusedField_NothingToDefine = p_texture_info->view_descs.srv.Texture2DMS.UnusedField_NothingToDefine;
  2399. } break;
  2400. case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: {
  2401. dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY;
  2402. dsv_desc.Texture2DMSArray.FirstArraySlice = p_texture_info->base_layer;
  2403. dsv_desc.Texture2DMSArray.ArraySize = p_texture_info->view_descs.srv.Texture2DMSArray.ArraySize;
  2404. } break;
  2405. default: {
  2406. DEV_ASSERT(false);
  2407. }
  2408. }
  2409. return dsv_desc;
  2410. }
  2411. RDD::FramebufferID RenderingDeviceDriverD3D12::_framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height, bool p_is_screen) {
  2412. // Pre-bookkeep.
  2413. FramebufferInfo *fb_info = VersatileResource::allocate<FramebufferInfo>(resources_allocator);
  2414. fb_info->is_screen = p_is_screen;
  2415. const RenderPassInfo *pass_info = (const RenderPassInfo *)p_render_pass.id;
  2416. uint32_t num_color = 0;
  2417. uint32_t num_depth_stencil = 0;
  2418. for (uint32_t i = 0; i < p_attachments.size(); i++) {
  2419. const TextureInfo *tex_info = (const TextureInfo *)p_attachments[i].id;
  2420. if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) {
  2421. num_color++;
  2422. } else if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
  2423. num_depth_stencil++;
  2424. }
  2425. }
  2426. uint32_t vrs_index = UINT32_MAX;
  2427. for (const Subpass &E : pass_info->subpasses) {
  2428. if (E.vrs_reference.attachment != AttachmentReference::UNUSED) {
  2429. vrs_index = E.vrs_reference.attachment;
  2430. }
  2431. }
  2432. if (num_color) {
  2433. Error err = fb_info->rtv_heap.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_RTV, num_color, false);
  2434. if (err) {
  2435. VersatileResource::free(resources_allocator, fb_info);
  2436. ERR_FAIL_V(FramebufferID());
  2437. }
  2438. }
  2439. DescriptorsHeap::Walker rtv_heap_walker = fb_info->rtv_heap.make_walker();
  2440. if (num_depth_stencil) {
  2441. Error err = fb_info->dsv_heap.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_DSV, num_depth_stencil, false);
  2442. if (err) {
  2443. VersatileResource::free(resources_allocator, fb_info);
  2444. ERR_FAIL_V(FramebufferID());
  2445. }
  2446. }
  2447. DescriptorsHeap::Walker dsv_heap_walker = fb_info->dsv_heap.make_walker();
  2448. fb_info->attachments_handle_inds.resize(p_attachments.size());
  2449. fb_info->attachments.reserve(num_color + num_depth_stencil);
  2450. uint32_t color_idx = 0;
  2451. uint32_t depth_stencil_idx = 0;
  2452. for (uint32_t i = 0; i < p_attachments.size(); i++) {
  2453. const TextureInfo *tex_info = (const TextureInfo *)p_attachments[i].id;
  2454. if (fb_info->size.x == 0) {
  2455. fb_info->size = Size2i(tex_info->desc.Width, tex_info->desc.Height);
  2456. }
  2457. if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) {
  2458. D3D12_RENDER_TARGET_VIEW_DESC rtv_desc = _make_rtv_for_texture(tex_info, 0, 0, UINT32_MAX);
  2459. device->CreateRenderTargetView(tex_info->resource, &rtv_desc, rtv_heap_walker.get_curr_cpu_handle());
  2460. rtv_heap_walker.advance();
  2461. fb_info->attachments_handle_inds[i] = color_idx;
  2462. fb_info->attachments.push_back(p_attachments[i]);
  2463. color_idx++;
  2464. } else if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
  2465. D3D12_DEPTH_STENCIL_VIEW_DESC dsv_desc = _make_dsv_for_texture(tex_info);
  2466. device->CreateDepthStencilView(tex_info->resource, &dsv_desc, dsv_heap_walker.get_curr_cpu_handle());
  2467. dsv_heap_walker.advance();
  2468. fb_info->attachments_handle_inds[i] = depth_stencil_idx;
  2469. fb_info->attachments.push_back(p_attachments[i]);
  2470. depth_stencil_idx++;
  2471. } else if (i == vrs_index) {
  2472. fb_info->vrs_attachment = p_attachments[i];
  2473. } else {
  2474. DEV_ASSERT(false);
  2475. }
  2476. }
  2477. DEV_ASSERT(fb_info->attachments.size() == color_idx + depth_stencil_idx);
  2478. DEV_ASSERT((fb_info->vrs_attachment.id != 0) == (vrs_index != UINT32_MAX));
  2479. DEV_ASSERT(rtv_heap_walker.is_at_eof());
  2480. DEV_ASSERT(dsv_heap_walker.is_at_eof());
  2481. return FramebufferID(fb_info);
  2482. }
  2483. RDD::FramebufferID RenderingDeviceDriverD3D12::framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height) {
  2484. return _framebuffer_create(p_render_pass, p_attachments, p_width, p_height, false);
  2485. }
  2486. void RenderingDeviceDriverD3D12::framebuffer_free(FramebufferID p_framebuffer) {
  2487. FramebufferInfo *fb_info = (FramebufferInfo *)p_framebuffer.id;
  2488. VersatileResource::free(resources_allocator, fb_info);
  2489. }
  2490. /****************/
  2491. /**** SHADER ****/
  2492. /****************/
  2493. static uint32_t SHADER_STAGES_BIT_OFFSET_INDICES[RenderingDevice::SHADER_STAGE_MAX] = {
  2494. /* SHADER_STAGE_VERTEX */ 0,
  2495. /* SHADER_STAGE_FRAGMENT */ 1,
  2496. /* SHADER_STAGE_TESSELATION_CONTROL */ UINT32_MAX,
  2497. /* SHADER_STAGE_TESSELATION_EVALUATION */ UINT32_MAX,
  2498. /* SHADER_STAGE_COMPUTE */ 2,
  2499. };
  2500. uint32_t RenderingDeviceDriverD3D12::_shader_patch_dxil_specialization_constant(
  2501. PipelineSpecializationConstantType p_type,
  2502. const void *p_value,
  2503. const uint64_t (&p_stages_bit_offsets)[D3D12_BITCODE_OFFSETS_NUM_STAGES],
  2504. HashMap<ShaderStage, Vector<uint8_t>> &r_stages_bytecodes,
  2505. bool p_is_first_patch) {
  2506. uint32_t patch_val = 0;
  2507. switch (p_type) {
  2508. case PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT: {
  2509. uint32_t int_value = *((const int *)p_value);
  2510. ERR_FAIL_COND_V(int_value & (1 << 31), 0);
  2511. patch_val = int_value;
  2512. } break;
  2513. case PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL: {
  2514. bool bool_value = *((const bool *)p_value);
  2515. patch_val = (uint32_t)bool_value;
  2516. } break;
  2517. case PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT: {
  2518. uint32_t int_value = *((const int *)p_value);
  2519. ERR_FAIL_COND_V(int_value & (1 << 31), 0);
  2520. patch_val = (int_value >> 1);
  2521. } break;
  2522. }
  2523. // For VBR encoding to encode the number of bits we expect (32), we need to set the MSB unconditionally.
  2524. // However, signed VBR moves the MSB to the LSB, so setting the MSB to 1 wouldn't help. Therefore,
  2525. // the bit we set to 1 is the one at index 30.
  2526. patch_val |= (1 << 30);
  2527. patch_val <<= 1; // What signed VBR does.
  2528. auto tamper_bits = [](uint8_t *p_start, uint64_t p_bit_offset, uint64_t p_tb_value) -> uint64_t {
  2529. uint64_t original = 0;
  2530. uint32_t curr_input_byte = p_bit_offset / 8;
  2531. uint8_t curr_input_bit = p_bit_offset % 8;
  2532. auto get_curr_input_bit = [&]() -> bool {
  2533. return ((p_start[curr_input_byte] >> curr_input_bit) & 1);
  2534. };
  2535. auto move_to_next_input_bit = [&]() {
  2536. if (curr_input_bit == 7) {
  2537. curr_input_bit = 0;
  2538. curr_input_byte++;
  2539. } else {
  2540. curr_input_bit++;
  2541. }
  2542. };
  2543. auto tamper_input_bit = [&](bool p_new_bit) {
  2544. p_start[curr_input_byte] &= ~((uint8_t)1 << curr_input_bit);
  2545. if (p_new_bit) {
  2546. p_start[curr_input_byte] |= (uint8_t)1 << curr_input_bit;
  2547. }
  2548. };
  2549. uint8_t value_bit_idx = 0;
  2550. for (uint32_t i = 0; i < 5; i++) { // 32 bits take 5 full bytes in VBR.
  2551. for (uint32_t j = 0; j < 7; j++) {
  2552. bool input_bit = get_curr_input_bit();
  2553. original |= (uint64_t)(input_bit ? 1 : 0) << value_bit_idx;
  2554. tamper_input_bit((p_tb_value >> value_bit_idx) & 1);
  2555. move_to_next_input_bit();
  2556. value_bit_idx++;
  2557. }
  2558. #ifdef DEV_ENABLED
  2559. bool input_bit = get_curr_input_bit();
  2560. DEV_ASSERT((i < 4 && input_bit) || (i == 4 && !input_bit));
  2561. #endif
  2562. move_to_next_input_bit();
  2563. }
  2564. return original;
  2565. };
  2566. uint32_t stages_patched_mask = 0;
  2567. for (int stage = 0; stage < SHADER_STAGE_MAX; stage++) {
  2568. if (!r_stages_bytecodes.has((ShaderStage)stage)) {
  2569. continue;
  2570. }
  2571. uint64_t offset = p_stages_bit_offsets[SHADER_STAGES_BIT_OFFSET_INDICES[stage]];
  2572. if (offset == 0) {
  2573. // This constant does not appear at this stage.
  2574. continue;
  2575. }
  2576. Vector<uint8_t> &bytecode = r_stages_bytecodes[(ShaderStage)stage];
  2577. #ifdef DEV_ENABLED
  2578. uint64_t orig_patch_val = tamper_bits(bytecode.ptrw(), offset, patch_val);
  2579. // Checking against the value the NIR patch should have set.
  2580. DEV_ASSERT(!p_is_first_patch || ((orig_patch_val >> 1) & GODOT_NIR_SC_SENTINEL_MAGIC_MASK) == GODOT_NIR_SC_SENTINEL_MAGIC);
  2581. uint64_t readback_patch_val = tamper_bits(bytecode.ptrw(), offset, patch_val);
  2582. DEV_ASSERT(readback_patch_val == patch_val);
  2583. #else
  2584. tamper_bits(bytecode.ptrw(), offset, patch_val);
  2585. #endif
  2586. stages_patched_mask |= (1 << stage);
  2587. }
  2588. return stages_patched_mask;
  2589. }
  2590. bool RenderingDeviceDriverD3D12::_shader_apply_specialization_constants(
  2591. const ShaderInfo *p_shader_info,
  2592. VectorView<PipelineSpecializationConstant> p_specialization_constants,
  2593. HashMap<ShaderStage, Vector<uint8_t>> &r_final_stages_bytecode) {
  2594. // If something needs to be patched, COW will do the trick.
  2595. r_final_stages_bytecode = p_shader_info->stages_bytecode;
  2596. uint32_t stages_re_sign_mask = 0;
  2597. for (uint32_t i = 0; i < p_specialization_constants.size(); i++) {
  2598. const PipelineSpecializationConstant &psc = p_specialization_constants[i];
  2599. if (!(p_shader_info->spirv_specialization_constants_ids_mask & (1 << psc.constant_id))) {
  2600. // This SC wasn't even in the original SPIR-V shader.
  2601. continue;
  2602. }
  2603. for (const ShaderInfo::SpecializationConstant &sc : p_shader_info->specialization_constants) {
  2604. if (psc.constant_id == sc.constant_id) {
  2605. if (psc.int_value != sc.int_value) {
  2606. stages_re_sign_mask |= _shader_patch_dxil_specialization_constant(psc.type, &psc.int_value, sc.stages_bit_offsets, r_final_stages_bytecode, false);
  2607. }
  2608. break;
  2609. }
  2610. }
  2611. }
  2612. // Re-sign patched stages.
  2613. for (KeyValue<ShaderStage, Vector<uint8_t>> &E : r_final_stages_bytecode) {
  2614. ShaderStage stage = E.key;
  2615. if ((stages_re_sign_mask & (1 << stage))) {
  2616. Vector<uint8_t> &bytecode = E.value;
  2617. _shader_sign_dxil_bytecode(stage, bytecode);
  2618. }
  2619. }
  2620. return true;
  2621. }
  2622. void RenderingDeviceDriverD3D12::_shader_sign_dxil_bytecode(ShaderStage p_stage, Vector<uint8_t> &r_dxil_blob) {
  2623. uint8_t *w = r_dxil_blob.ptrw();
  2624. compute_dxil_hash(w + 20, r_dxil_blob.size() - 20, w + 4);
  2625. }
  2626. String RenderingDeviceDriverD3D12::shader_get_binary_cache_key() {
  2627. return "D3D12-SV" + uitos(ShaderBinary::VERSION) + "-" + itos(shader_capabilities.shader_model);
  2628. }
  2629. Vector<uint8_t> RenderingDeviceDriverD3D12::shader_compile_binary_from_spirv(VectorView<ShaderStageSPIRVData> p_spirv, const String &p_shader_name) {
  2630. ShaderReflection shader_refl;
  2631. if (_reflect_spirv(p_spirv, shader_refl) != OK) {
  2632. return Vector<uint8_t>();
  2633. }
  2634. // Collect reflection data into binary data.
  2635. ShaderBinary::Data binary_data;
  2636. Vector<Vector<ShaderBinary::DataBinding>> sets_bindings;
  2637. Vector<ShaderBinary::SpecializationConstant> specialization_constants;
  2638. {
  2639. binary_data.vertex_input_mask = shader_refl.vertex_input_mask;
  2640. binary_data.fragment_output_mask = shader_refl.fragment_output_mask;
  2641. binary_data.specialization_constants_count = shader_refl.specialization_constants.size();
  2642. binary_data.is_compute = shader_refl.is_compute;
  2643. binary_data.compute_local_size[0] = shader_refl.compute_local_size[0];
  2644. binary_data.compute_local_size[1] = shader_refl.compute_local_size[1];
  2645. binary_data.compute_local_size[2] = shader_refl.compute_local_size[2];
  2646. binary_data.set_count = shader_refl.uniform_sets.size();
  2647. binary_data.push_constant_size = shader_refl.push_constant_size;
  2648. binary_data.nir_runtime_data_root_param_idx = UINT32_MAX;
  2649. binary_data.stage_count = p_spirv.size();
  2650. for (const Vector<ShaderUniform> &spirv_set : shader_refl.uniform_sets) {
  2651. Vector<ShaderBinary::DataBinding> bindings;
  2652. for (const ShaderUniform &spirv_uniform : spirv_set) {
  2653. ShaderBinary::DataBinding binding;
  2654. binding.type = (uint32_t)spirv_uniform.type;
  2655. binding.binding = spirv_uniform.binding;
  2656. binding.stages = (uint32_t)spirv_uniform.stages;
  2657. binding.length = spirv_uniform.length;
  2658. binding.writable = (uint32_t)spirv_uniform.writable;
  2659. bindings.push_back(binding);
  2660. }
  2661. sets_bindings.push_back(bindings);
  2662. }
  2663. for (const ShaderSpecializationConstant &spirv_sc : shader_refl.specialization_constants) {
  2664. ShaderBinary::SpecializationConstant spec_constant;
  2665. spec_constant.type = (uint32_t)spirv_sc.type;
  2666. spec_constant.constant_id = spirv_sc.constant_id;
  2667. spec_constant.int_value = spirv_sc.int_value;
  2668. spec_constant.stage_flags = spirv_sc.stages;
  2669. specialization_constants.push_back(spec_constant);
  2670. binary_data.spirv_specialization_constants_ids_mask |= (1 << spirv_sc.constant_id);
  2671. }
  2672. }
  2673. // Translate SPIR-V shaders to DXIL, and collect shader info from the new representation.
  2674. HashMap<ShaderStage, Vector<uint8_t>> dxil_blobs;
  2675. BitField<ShaderStage> stages_processed;
  2676. {
  2677. HashMap<int, nir_shader *> stages_nir_shaders;
  2678. auto free_nir_shaders = [&]() {
  2679. for (KeyValue<int, nir_shader *> &E : stages_nir_shaders) {
  2680. ralloc_free(E.value);
  2681. }
  2682. stages_nir_shaders.clear();
  2683. };
  2684. // This is based on spirv2dxil.c. May need updates when it changes.
  2685. // Also, this has to stay around until after linking.
  2686. nir_shader_compiler_options nir_options = *dxil_get_nir_compiler_options();
  2687. nir_options.lower_base_vertex = false;
  2688. dxil_spirv_runtime_conf dxil_runtime_conf = {};
  2689. dxil_runtime_conf.runtime_data_cbv.base_shader_register = RUNTIME_DATA_REGISTER;
  2690. dxil_runtime_conf.push_constant_cbv.base_shader_register = ROOT_CONSTANT_REGISTER;
  2691. dxil_runtime_conf.zero_based_vertex_instance_id = true;
  2692. dxil_runtime_conf.zero_based_compute_workgroup_id = true;
  2693. dxil_runtime_conf.declared_read_only_images_as_srvs = true;
  2694. // Making this explicit to let maintainers know that in practice this didn't improve performance,
  2695. // probably because data generated by one shader and consumed by another one forces the resource
  2696. // to transition from UAV to SRV, and back, instead of being an UAV all the time.
  2697. // In case someone wants to try, care must be taken so in case of incompatible bindings across stages
  2698. // happen as a result, all the stages are re-translated. That can happen if, for instance, a stage only
  2699. // uses an allegedly writable resource only for reading but the next stage doesn't.
  2700. dxil_runtime_conf.inferred_read_only_images_as_srvs = false;
  2701. // - Translate SPIR-V to NIR.
  2702. for (uint32_t i = 0; i < p_spirv.size(); i++) {
  2703. ShaderStage stage = (ShaderStage)p_spirv[i].shader_stage;
  2704. ShaderStage stage_flag = (ShaderStage)(1 << p_spirv[i].shader_stage);
  2705. stages_processed.set_flag(stage_flag);
  2706. {
  2707. const char *entry_point = "main";
  2708. static const gl_shader_stage SPIRV_TO_MESA_STAGES[SHADER_STAGE_MAX] = {
  2709. /* SHADER_STAGE_VERTEX */ MESA_SHADER_VERTEX,
  2710. /* SHADER_STAGE_FRAGMENT */ MESA_SHADER_FRAGMENT,
  2711. /* SHADER_STAGE_TESSELATION_CONTROL */ MESA_SHADER_TESS_CTRL,
  2712. /* SHADER_STAGE_TESSELATION_EVALUATION */ MESA_SHADER_TESS_EVAL,
  2713. /* SHADER_STAGE_COMPUTE */ MESA_SHADER_COMPUTE,
  2714. };
  2715. nir_shader *shader = spirv_to_nir(
  2716. (const uint32_t *)p_spirv[i].spirv.ptr(),
  2717. p_spirv[i].spirv.size() / sizeof(uint32_t),
  2718. nullptr,
  2719. 0,
  2720. SPIRV_TO_MESA_STAGES[stage],
  2721. entry_point,
  2722. dxil_spirv_nir_get_spirv_options(), &nir_options);
  2723. if (!shader) {
  2724. free_nir_shaders();
  2725. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Shader translation (step 1) at stage " + String(SHADER_STAGE_NAMES[stage]) + " failed.");
  2726. }
  2727. #ifdef DEV_ENABLED
  2728. nir_validate_shader(shader, "Validate before feeding NIR to the DXIL compiler");
  2729. #endif
  2730. if (stage == SHADER_STAGE_VERTEX) {
  2731. dxil_runtime_conf.yz_flip.y_mask = 0xffff;
  2732. dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_Y_FLIP_UNCONDITIONAL;
  2733. } else {
  2734. dxil_runtime_conf.yz_flip.y_mask = 0;
  2735. dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_YZ_FLIP_NONE;
  2736. }
  2737. // This is based on spirv2dxil.c. May need updates when it changes.
  2738. dxil_spirv_nir_prep(shader);
  2739. bool requires_runtime_data = {};
  2740. dxil_spirv_nir_passes(shader, &dxil_runtime_conf, &requires_runtime_data);
  2741. stages_nir_shaders[stage] = shader;
  2742. }
  2743. }
  2744. // - Link NIR shaders.
  2745. for (int i = SHADER_STAGE_MAX - 1; i >= 0; i--) {
  2746. if (!stages_nir_shaders.has(i)) {
  2747. continue;
  2748. }
  2749. nir_shader *shader = stages_nir_shaders[i];
  2750. nir_shader *prev_shader = nullptr;
  2751. for (int j = i - 1; j >= 0; j--) {
  2752. if (stages_nir_shaders.has(j)) {
  2753. prev_shader = stages_nir_shaders[j];
  2754. break;
  2755. }
  2756. }
  2757. if (prev_shader) {
  2758. bool requires_runtime_data = {};
  2759. dxil_spirv_nir_link(shader, prev_shader, &dxil_runtime_conf, &requires_runtime_data);
  2760. }
  2761. }
  2762. // - Translate NIR to DXIL.
  2763. for (uint32_t i = 0; i < p_spirv.size(); i++) {
  2764. ShaderStage stage = (ShaderStage)p_spirv[i].shader_stage;
  2765. struct ShaderData {
  2766. ShaderStage stage;
  2767. ShaderBinary::Data &binary_data;
  2768. Vector<Vector<ShaderBinary::DataBinding>> &sets_bindings;
  2769. Vector<ShaderBinary::SpecializationConstant> &specialization_constants;
  2770. } shader_data{ stage, binary_data, sets_bindings, specialization_constants };
  2771. GodotNirCallbacks godot_nir_callbacks = {};
  2772. godot_nir_callbacks.data = &shader_data;
  2773. godot_nir_callbacks.report_resource = [](uint32_t p_register, uint32_t p_space, uint32_t p_dxil_type, void *p_data) {
  2774. ShaderData &shader_data_in = *(ShaderData *)p_data;
  2775. // Types based on Mesa's dxil_container.h.
  2776. static const uint32_t DXIL_RES_SAMPLER = 1;
  2777. static const ResourceClass DXIL_TYPE_TO_CLASS[] = {
  2778. /* DXIL_RES_INVALID */ RES_CLASS_INVALID,
  2779. /* DXIL_RES_SAMPLER */ RES_CLASS_INVALID, // Handling sampler as a flag.
  2780. /* DXIL_RES_CBV */ RES_CLASS_CBV,
  2781. /* DXIL_RES_SRV_TYPED */ RES_CLASS_SRV,
  2782. /* DXIL_RES_SRV_RAW */ RES_CLASS_SRV,
  2783. /* DXIL_RES_SRV_STRUCTURED */ RES_CLASS_SRV,
  2784. /* DXIL_RES_UAV_TYPED */ RES_CLASS_UAV,
  2785. /* DXIL_RES_UAV_RAW */ RES_CLASS_UAV,
  2786. /* DXIL_RES_UAV_STRUCTURED */ RES_CLASS_UAV,
  2787. /* DXIL_RES_UAV_STRUCTURED_WITH_COUNTER */ RES_CLASS_INVALID,
  2788. };
  2789. DEV_ASSERT(p_dxil_type < ARRAY_SIZE(DXIL_TYPE_TO_CLASS));
  2790. ResourceClass res_class = DXIL_TYPE_TO_CLASS[p_dxil_type];
  2791. if (p_register == ROOT_CONSTANT_REGISTER && p_space == 0) {
  2792. DEV_ASSERT(res_class == RES_CLASS_CBV);
  2793. shader_data_in.binary_data.dxil_push_constant_stages |= (1 << shader_data_in.stage);
  2794. } else if (p_register == RUNTIME_DATA_REGISTER && p_space == 0) {
  2795. DEV_ASSERT(res_class == RES_CLASS_CBV);
  2796. shader_data_in.binary_data.nir_runtime_data_root_param_idx = 1; // Temporary, to be determined later.
  2797. } else {
  2798. DEV_ASSERT(p_space == 0);
  2799. uint32_t set = p_register / GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER;
  2800. uint32_t binding = (p_register % GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER) / GODOT_NIR_BINDING_MULTIPLIER;
  2801. DEV_ASSERT(set < (uint32_t)shader_data_in.sets_bindings.size());
  2802. [[maybe_unused]] bool found = false;
  2803. for (int j = 0; j < shader_data_in.sets_bindings[set].size(); j++) {
  2804. if (shader_data_in.sets_bindings[set][j].binding != binding) {
  2805. continue;
  2806. }
  2807. ShaderBinary::DataBinding &binding_info = shader_data_in.sets_bindings.write[set].write[j];
  2808. binding_info.dxil_stages |= (1 << shader_data_in.stage);
  2809. if (res_class != RES_CLASS_INVALID) {
  2810. DEV_ASSERT(binding_info.res_class == (uint32_t)RES_CLASS_INVALID || binding_info.res_class == (uint32_t)res_class);
  2811. binding_info.res_class = res_class;
  2812. } else if (p_dxil_type == DXIL_RES_SAMPLER) {
  2813. binding_info.has_sampler = (uint32_t)true;
  2814. } else {
  2815. CRASH_NOW();
  2816. }
  2817. found = true;
  2818. break;
  2819. }
  2820. DEV_ASSERT(found);
  2821. }
  2822. };
  2823. godot_nir_callbacks.report_sc_bit_offset_fn = [](uint32_t p_sc_id, uint64_t p_bit_offset, void *p_data) {
  2824. ShaderData &shader_data_in = *(ShaderData *)p_data;
  2825. [[maybe_unused]] bool found = false;
  2826. for (int j = 0; j < shader_data_in.specialization_constants.size(); j++) {
  2827. if (shader_data_in.specialization_constants[j].constant_id != p_sc_id) {
  2828. continue;
  2829. }
  2830. uint32_t offset_idx = SHADER_STAGES_BIT_OFFSET_INDICES[shader_data_in.stage];
  2831. DEV_ASSERT(shader_data_in.specialization_constants.write[j].stages_bit_offsets[offset_idx] == 0);
  2832. shader_data_in.specialization_constants.write[j].stages_bit_offsets[offset_idx] = p_bit_offset;
  2833. found = true;
  2834. break;
  2835. }
  2836. DEV_ASSERT(found);
  2837. };
  2838. godot_nir_callbacks.report_bitcode_bit_offset_fn = [](uint64_t p_bit_offset, void *p_data) {
  2839. DEV_ASSERT(p_bit_offset % 8 == 0);
  2840. ShaderData &shader_data_in = *(ShaderData *)p_data;
  2841. uint32_t offset_idx = SHADER_STAGES_BIT_OFFSET_INDICES[shader_data_in.stage];
  2842. for (int j = 0; j < shader_data_in.specialization_constants.size(); j++) {
  2843. if (shader_data_in.specialization_constants.write[j].stages_bit_offsets[offset_idx] == 0) {
  2844. // This SC has been optimized out from this stage.
  2845. continue;
  2846. }
  2847. shader_data_in.specialization_constants.write[j].stages_bit_offsets[offset_idx] += p_bit_offset;
  2848. }
  2849. };
  2850. auto shader_model_d3d_to_dxil = [](D3D_SHADER_MODEL p_d3d_shader_model) -> dxil_shader_model {
  2851. static_assert(SHADER_MODEL_6_0 == 0x60000);
  2852. static_assert(SHADER_MODEL_6_3 == 0x60003);
  2853. static_assert(D3D_SHADER_MODEL_6_0 == 0x60);
  2854. static_assert(D3D_SHADER_MODEL_6_3 == 0x63);
  2855. return (dxil_shader_model)((p_d3d_shader_model >> 4) * 0x10000 + (p_d3d_shader_model & 0xf));
  2856. };
  2857. nir_to_dxil_options nir_to_dxil_options = {};
  2858. nir_to_dxil_options.environment = DXIL_ENVIRONMENT_VULKAN;
  2859. nir_to_dxil_options.shader_model_max = shader_model_d3d_to_dxil(shader_capabilities.shader_model);
  2860. nir_to_dxil_options.validator_version_max = NO_DXIL_VALIDATION;
  2861. nir_to_dxil_options.godot_nir_callbacks = &godot_nir_callbacks;
  2862. dxil_logger logger = {};
  2863. logger.log = [](void *p_priv, const char *p_msg) {
  2864. #ifdef DEBUG_ENABLED
  2865. print_verbose(p_msg);
  2866. #endif
  2867. };
  2868. blob dxil_blob = {};
  2869. bool ok = nir_to_dxil(stages_nir_shaders[stage], &nir_to_dxil_options, &logger, &dxil_blob);
  2870. ralloc_free(stages_nir_shaders[stage]);
  2871. stages_nir_shaders.erase(stage);
  2872. if (!ok) {
  2873. free_nir_shaders();
  2874. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Shader translation at stage " + String(SHADER_STAGE_NAMES[stage]) + " failed.");
  2875. }
  2876. Vector<uint8_t> blob_copy;
  2877. blob_copy.resize(dxil_blob.size);
  2878. memcpy(blob_copy.ptrw(), dxil_blob.data, dxil_blob.size);
  2879. blob_finish(&dxil_blob);
  2880. dxil_blobs.insert(stage, blob_copy);
  2881. }
  2882. }
  2883. #if 0
  2884. if (dxil_blobs.has(SHADER_STAGE_FRAGMENT)) {
  2885. Ref<FileAccess> f = FileAccess::open("res://1.dxil", FileAccess::WRITE);
  2886. f->store_buffer(dxil_blobs[SHADER_STAGE_FRAGMENT].ptr(), dxil_blobs[SHADER_STAGE_FRAGMENT].size());
  2887. }
  2888. #endif
  2889. // Patch with default values of specialization constants.
  2890. if (specialization_constants.size()) {
  2891. for (const ShaderBinary::SpecializationConstant &sc : specialization_constants) {
  2892. _shader_patch_dxil_specialization_constant((PipelineSpecializationConstantType)sc.type, &sc.int_value, sc.stages_bit_offsets, dxil_blobs, true);
  2893. }
  2894. #if 0
  2895. if (dxil_blobs.has(SHADER_STAGE_FRAGMENT)) {
  2896. Ref<FileAccess> f = FileAccess::open("res://2.dxil", FileAccess::WRITE);
  2897. f->store_buffer(dxil_blobs[SHADER_STAGE_FRAGMENT].ptr(), dxil_blobs[SHADER_STAGE_FRAGMENT].size());
  2898. }
  2899. #endif
  2900. }
  2901. // Sign.
  2902. for (KeyValue<ShaderStage, Vector<uint8_t>> &E : dxil_blobs) {
  2903. ShaderStage stage = E.key;
  2904. Vector<uint8_t> &dxil_blob = E.value;
  2905. _shader_sign_dxil_bytecode(stage, dxil_blob);
  2906. }
  2907. // Build the root signature.
  2908. ComPtr<ID3DBlob> root_sig_blob;
  2909. {
  2910. auto stages_to_d3d12_visibility = [](uint32_t p_stages_mask) -> D3D12_SHADER_VISIBILITY {
  2911. switch (p_stages_mask) {
  2912. case SHADER_STAGE_VERTEX_BIT: {
  2913. return D3D12_SHADER_VISIBILITY_VERTEX;
  2914. }
  2915. case SHADER_STAGE_FRAGMENT_BIT: {
  2916. return D3D12_SHADER_VISIBILITY_PIXEL;
  2917. }
  2918. default: {
  2919. return D3D12_SHADER_VISIBILITY_ALL;
  2920. }
  2921. }
  2922. };
  2923. LocalVector<D3D12_ROOT_PARAMETER1> root_params;
  2924. // Root (push) constants.
  2925. if (binary_data.dxil_push_constant_stages) {
  2926. CD3DX12_ROOT_PARAMETER1 push_constant;
  2927. push_constant.InitAsConstants(
  2928. binary_data.push_constant_size / sizeof(uint32_t),
  2929. ROOT_CONSTANT_REGISTER,
  2930. 0,
  2931. stages_to_d3d12_visibility(binary_data.dxil_push_constant_stages));
  2932. root_params.push_back(push_constant);
  2933. }
  2934. // NIR-DXIL runtime data.
  2935. if (binary_data.nir_runtime_data_root_param_idx == 1) { // Set above to 1 when discovering runtime data is needed.
  2936. DEV_ASSERT(!binary_data.is_compute); // Could be supported if needed, but it's pointless as of now.
  2937. binary_data.nir_runtime_data_root_param_idx = root_params.size();
  2938. CD3DX12_ROOT_PARAMETER1 nir_runtime_data;
  2939. nir_runtime_data.InitAsConstants(
  2940. sizeof(dxil_spirv_vertex_runtime_data) / sizeof(uint32_t),
  2941. RUNTIME_DATA_REGISTER,
  2942. 0,
  2943. D3D12_SHADER_VISIBILITY_VERTEX);
  2944. root_params.push_back(nir_runtime_data);
  2945. }
  2946. // Descriptor tables (up to two per uniform set, for resources and/or samplers).
  2947. // These have to stay around until serialization!
  2948. struct TraceableDescriptorTable {
  2949. uint32_t stages_mask = {};
  2950. Vector<D3D12_DESCRIPTOR_RANGE1> ranges;
  2951. Vector<ShaderBinary::DataBinding::RootSignatureLocation *> root_sig_locations;
  2952. };
  2953. Vector<TraceableDescriptorTable> resource_tables_maps;
  2954. Vector<TraceableDescriptorTable> sampler_tables_maps;
  2955. for (int set = 0; set < sets_bindings.size(); set++) {
  2956. bool first_resource_in_set = true;
  2957. bool first_sampler_in_set = true;
  2958. sets_bindings.write[set].sort();
  2959. for (int i = 0; i < sets_bindings[set].size(); i++) {
  2960. const ShaderBinary::DataBinding &binding = sets_bindings[set][i];
  2961. bool really_used = binding.dxil_stages != 0;
  2962. #ifdef DEV_ENABLED
  2963. bool anybody_home = (ResourceClass)binding.res_class != RES_CLASS_INVALID || binding.has_sampler;
  2964. DEV_ASSERT(anybody_home == really_used);
  2965. #endif
  2966. if (!really_used) {
  2967. continue; // Existed in SPIR-V; went away in DXIL.
  2968. }
  2969. auto insert_range = [](D3D12_DESCRIPTOR_RANGE_TYPE p_range_type,
  2970. uint32_t p_num_descriptors,
  2971. uint32_t p_dxil_register,
  2972. uint32_t p_dxil_stages_mask,
  2973. ShaderBinary::DataBinding::RootSignatureLocation(&p_root_sig_locations),
  2974. Vector<TraceableDescriptorTable> &r_tables,
  2975. bool &r_first_in_set) {
  2976. if (r_first_in_set) {
  2977. r_tables.resize(r_tables.size() + 1);
  2978. r_first_in_set = false;
  2979. }
  2980. TraceableDescriptorTable &table = r_tables.write[r_tables.size() - 1];
  2981. table.stages_mask |= p_dxil_stages_mask;
  2982. CD3DX12_DESCRIPTOR_RANGE1 range;
  2983. // Due to the aliasing hack for SRV-UAV of different families,
  2984. // we can be causing an unintended change of data (sometimes the validation layers catch it).
  2985. D3D12_DESCRIPTOR_RANGE_FLAGS flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE;
  2986. if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_SRV || p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_UAV) {
  2987. flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE;
  2988. } else if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_CBV) {
  2989. flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE;
  2990. }
  2991. range.Init(p_range_type, p_num_descriptors, p_dxil_register, 0, flags);
  2992. table.ranges.push_back(range);
  2993. table.root_sig_locations.push_back(&p_root_sig_locations);
  2994. };
  2995. uint32_t num_descriptors = 1;
  2996. D3D12_DESCRIPTOR_RANGE_TYPE resource_range_type = {};
  2997. switch ((ResourceClass)binding.res_class) {
  2998. case RES_CLASS_INVALID: {
  2999. num_descriptors = binding.length;
  3000. DEV_ASSERT(binding.has_sampler);
  3001. } break;
  3002. case RES_CLASS_CBV: {
  3003. resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
  3004. DEV_ASSERT(!binding.has_sampler);
  3005. } break;
  3006. case RES_CLASS_SRV: {
  3007. resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  3008. num_descriptors = MAX(1u, binding.length); // An unbound R/O buffer is reflected as zero-size.
  3009. } break;
  3010. case RES_CLASS_UAV: {
  3011. resource_range_type = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
  3012. num_descriptors = MAX(1u, binding.length); // An unbound R/W buffer is reflected as zero-size.
  3013. DEV_ASSERT(!binding.has_sampler);
  3014. } break;
  3015. }
  3016. uint32_t dxil_register = set * GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER + binding.binding * GODOT_NIR_BINDING_MULTIPLIER;
  3017. if (binding.res_class != RES_CLASS_INVALID) {
  3018. insert_range(
  3019. resource_range_type,
  3020. num_descriptors,
  3021. dxil_register,
  3022. sets_bindings[set][i].dxil_stages,
  3023. sets_bindings.write[set].write[i].root_sig_locations[RS_LOC_TYPE_RESOURCE],
  3024. resource_tables_maps,
  3025. first_resource_in_set);
  3026. }
  3027. if (binding.has_sampler) {
  3028. insert_range(
  3029. D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,
  3030. num_descriptors,
  3031. dxil_register,
  3032. sets_bindings[set][i].dxil_stages,
  3033. sets_bindings.write[set].write[i].root_sig_locations[RS_LOC_TYPE_SAMPLER],
  3034. sampler_tables_maps,
  3035. first_sampler_in_set);
  3036. }
  3037. }
  3038. }
  3039. auto make_descriptor_tables = [&root_params, &stages_to_d3d12_visibility](const Vector<TraceableDescriptorTable> &p_tables) {
  3040. for (const TraceableDescriptorTable &table : p_tables) {
  3041. D3D12_SHADER_VISIBILITY visibility = stages_to_d3d12_visibility(table.stages_mask);
  3042. DEV_ASSERT(table.ranges.size() == table.root_sig_locations.size());
  3043. for (int i = 0; i < table.ranges.size(); i++) {
  3044. // By now we know very well which root signature location corresponds to the pointed uniform.
  3045. table.root_sig_locations[i]->root_param_idx = root_params.size();
  3046. table.root_sig_locations[i]->range_idx = i;
  3047. }
  3048. CD3DX12_ROOT_PARAMETER1 root_table;
  3049. root_table.InitAsDescriptorTable(table.ranges.size(), table.ranges.ptr(), visibility);
  3050. root_params.push_back(root_table);
  3051. }
  3052. };
  3053. make_descriptor_tables(resource_tables_maps);
  3054. make_descriptor_tables(sampler_tables_maps);
  3055. CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC root_sig_desc = {};
  3056. D3D12_ROOT_SIGNATURE_FLAGS root_sig_flags =
  3057. D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
  3058. D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
  3059. D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS |
  3060. D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS |
  3061. D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS;
  3062. if (!stages_processed.has_flag(SHADER_STAGE_VERTEX_BIT)) {
  3063. root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS;
  3064. }
  3065. if (!stages_processed.has_flag(SHADER_STAGE_FRAGMENT_BIT)) {
  3066. root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS;
  3067. }
  3068. if (binary_data.vertex_input_mask) {
  3069. root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
  3070. }
  3071. root_sig_desc.Init_1_1(root_params.size(), root_params.ptr(), 0, nullptr, root_sig_flags);
  3072. ComPtr<ID3DBlob> error_blob;
  3073. HRESULT res = D3DX12SerializeVersionedRootSignature(context_driver->lib_d3d12, &root_sig_desc, D3D_ROOT_SIGNATURE_VERSION_1_1, root_sig_blob.GetAddressOf(), error_blob.GetAddressOf());
  3074. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), Vector<uint8_t>(),
  3075. "Serialization of root signature failed with error " + vformat("0x%08ux", (uint64_t)res) + " and the following message:\n" + String((char *)error_blob->GetBufferPointer(), error_blob->GetBufferSize()));
  3076. binary_data.root_signature_crc = crc32(0, nullptr, 0);
  3077. binary_data.root_signature_crc = crc32(binary_data.root_signature_crc, (const Bytef *)root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize());
  3078. }
  3079. Vector<Vector<uint8_t>> compressed_stages;
  3080. Vector<uint32_t> zstd_size;
  3081. uint32_t stages_binary_size = 0;
  3082. for (uint32_t i = 0; i < p_spirv.size(); i++) {
  3083. Vector<uint8_t> zstd;
  3084. Vector<uint8_t> &dxil_blob = dxil_blobs[p_spirv[i].shader_stage];
  3085. zstd.resize(Compression::get_max_compressed_buffer_size(dxil_blob.size(), Compression::MODE_ZSTD));
  3086. int dst_size = Compression::compress(zstd.ptrw(), dxil_blob.ptr(), dxil_blob.size(), Compression::MODE_ZSTD);
  3087. zstd_size.push_back(dst_size);
  3088. zstd.resize(dst_size);
  3089. compressed_stages.push_back(zstd);
  3090. uint32_t s = compressed_stages[i].size();
  3091. stages_binary_size += STEPIFY(s, 4);
  3092. }
  3093. CharString shader_name_utf = p_shader_name.utf8();
  3094. binary_data.shader_name_len = shader_name_utf.length();
  3095. uint32_t total_size = sizeof(uint32_t) * 3; // Header + version + main datasize;.
  3096. total_size += sizeof(ShaderBinary::Data);
  3097. total_size += STEPIFY(binary_data.shader_name_len, 4);
  3098. for (int i = 0; i < sets_bindings.size(); i++) {
  3099. total_size += sizeof(uint32_t);
  3100. total_size += sets_bindings[i].size() * sizeof(ShaderBinary::DataBinding);
  3101. }
  3102. total_size += sizeof(ShaderBinary::SpecializationConstant) * specialization_constants.size();
  3103. total_size += compressed_stages.size() * sizeof(uint32_t) * 3; // Sizes.
  3104. total_size += stages_binary_size;
  3105. binary_data.root_signature_len = root_sig_blob->GetBufferSize();
  3106. total_size += binary_data.root_signature_len;
  3107. Vector<uint8_t> ret;
  3108. ret.resize(total_size);
  3109. {
  3110. uint32_t offset = 0;
  3111. uint8_t *binptr = ret.ptrw();
  3112. binptr[0] = 'G';
  3113. binptr[1] = 'S';
  3114. binptr[2] = 'B';
  3115. binptr[3] = 'D'; // Godot shader binary data.
  3116. offset += 4;
  3117. encode_uint32(ShaderBinary::VERSION, binptr + offset);
  3118. offset += sizeof(uint32_t);
  3119. encode_uint32(sizeof(ShaderBinary::Data), binptr + offset);
  3120. offset += sizeof(uint32_t);
  3121. memcpy(binptr + offset, &binary_data, sizeof(ShaderBinary::Data));
  3122. offset += sizeof(ShaderBinary::Data);
  3123. #define ADVANCE_OFFSET_WITH_ALIGNMENT(m_bytes) \
  3124. { \
  3125. offset += m_bytes; \
  3126. uint32_t padding = STEPIFY(m_bytes, 4) - m_bytes; \
  3127. memset(binptr + offset, 0, padding); /* Avoid garbage data. */ \
  3128. offset += padding; \
  3129. }
  3130. if (binary_data.shader_name_len > 0) {
  3131. memcpy(binptr + offset, shader_name_utf.ptr(), binary_data.shader_name_len);
  3132. ADVANCE_OFFSET_WITH_ALIGNMENT(binary_data.shader_name_len);
  3133. }
  3134. for (int i = 0; i < sets_bindings.size(); i++) {
  3135. int count = sets_bindings[i].size();
  3136. encode_uint32(count, binptr + offset);
  3137. offset += sizeof(uint32_t);
  3138. if (count > 0) {
  3139. memcpy(binptr + offset, sets_bindings[i].ptr(), sizeof(ShaderBinary::DataBinding) * count);
  3140. offset += sizeof(ShaderBinary::DataBinding) * count;
  3141. }
  3142. }
  3143. if (specialization_constants.size()) {
  3144. memcpy(binptr + offset, specialization_constants.ptr(), sizeof(ShaderBinary::SpecializationConstant) * specialization_constants.size());
  3145. offset += sizeof(ShaderBinary::SpecializationConstant) * specialization_constants.size();
  3146. }
  3147. for (int i = 0; i < compressed_stages.size(); i++) {
  3148. encode_uint32(p_spirv[i].shader_stage, binptr + offset);
  3149. offset += sizeof(uint32_t);
  3150. encode_uint32(dxil_blobs[p_spirv[i].shader_stage].size(), binptr + offset);
  3151. offset += sizeof(uint32_t);
  3152. encode_uint32(zstd_size[i], binptr + offset);
  3153. offset += sizeof(uint32_t);
  3154. memcpy(binptr + offset, compressed_stages[i].ptr(), compressed_stages[i].size());
  3155. ADVANCE_OFFSET_WITH_ALIGNMENT(compressed_stages[i].size());
  3156. }
  3157. memcpy(binptr + offset, root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize());
  3158. offset += root_sig_blob->GetBufferSize();
  3159. ERR_FAIL_COND_V(offset != (uint32_t)ret.size(), Vector<uint8_t>());
  3160. }
  3161. return ret;
  3162. }
  3163. RDD::ShaderID RenderingDeviceDriverD3D12::shader_create_from_bytecode(const Vector<uint8_t> &p_shader_binary, ShaderDescription &r_shader_desc, String &r_name) {
  3164. r_shader_desc = {}; // Driver-agnostic.
  3165. ShaderInfo shader_info_in; // Driver-specific.
  3166. const uint8_t *binptr = p_shader_binary.ptr();
  3167. uint32_t binsize = p_shader_binary.size();
  3168. uint32_t read_offset = 0;
  3169. // Consistency check.
  3170. ERR_FAIL_COND_V(binsize < sizeof(uint32_t) * 3 + sizeof(ShaderBinary::Data), ShaderID());
  3171. ERR_FAIL_COND_V(binptr[0] != 'G' || binptr[1] != 'S' || binptr[2] != 'B' || binptr[3] != 'D', ShaderID());
  3172. uint32_t bin_version = decode_uint32(binptr + 4);
  3173. ERR_FAIL_COND_V(bin_version != ShaderBinary::VERSION, ShaderID());
  3174. uint32_t bin_data_size = decode_uint32(binptr + 8);
  3175. const ShaderBinary::Data &binary_data = *(reinterpret_cast<const ShaderBinary::Data *>(binptr + 12));
  3176. r_shader_desc.push_constant_size = binary_data.push_constant_size;
  3177. shader_info_in.dxil_push_constant_size = binary_data.dxil_push_constant_stages ? binary_data.push_constant_size : 0;
  3178. shader_info_in.nir_runtime_data_root_param_idx = binary_data.nir_runtime_data_root_param_idx;
  3179. r_shader_desc.vertex_input_mask = binary_data.vertex_input_mask;
  3180. r_shader_desc.fragment_output_mask = binary_data.fragment_output_mask;
  3181. r_shader_desc.is_compute = binary_data.is_compute;
  3182. shader_info_in.is_compute = binary_data.is_compute;
  3183. r_shader_desc.compute_local_size[0] = binary_data.compute_local_size[0];
  3184. r_shader_desc.compute_local_size[1] = binary_data.compute_local_size[1];
  3185. r_shader_desc.compute_local_size[2] = binary_data.compute_local_size[2];
  3186. read_offset += sizeof(uint32_t) * 3 + bin_data_size;
  3187. if (binary_data.shader_name_len) {
  3188. r_name.parse_utf8((const char *)(binptr + read_offset), binary_data.shader_name_len);
  3189. read_offset += STEPIFY(binary_data.shader_name_len, 4);
  3190. }
  3191. r_shader_desc.uniform_sets.resize(binary_data.set_count);
  3192. shader_info_in.sets.resize(binary_data.set_count);
  3193. for (uint32_t i = 0; i < binary_data.set_count; i++) {
  3194. ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) >= binsize, ShaderID());
  3195. uint32_t set_count = decode_uint32(binptr + read_offset);
  3196. read_offset += sizeof(uint32_t);
  3197. const ShaderBinary::DataBinding *set_ptr = reinterpret_cast<const ShaderBinary::DataBinding *>(binptr + read_offset);
  3198. uint32_t set_size = set_count * sizeof(ShaderBinary::DataBinding);
  3199. ERR_FAIL_COND_V(read_offset + set_size >= binsize, ShaderID());
  3200. shader_info_in.sets[i].bindings.reserve(set_count);
  3201. for (uint32_t j = 0; j < set_count; j++) {
  3202. ShaderUniform info;
  3203. info.type = UniformType(set_ptr[j].type);
  3204. info.writable = set_ptr[j].writable;
  3205. info.length = set_ptr[j].length;
  3206. info.binding = set_ptr[j].binding;
  3207. ShaderInfo::UniformBindingInfo binding;
  3208. binding.stages = set_ptr[j].dxil_stages;
  3209. binding.res_class = (ResourceClass)set_ptr[j].res_class;
  3210. binding.type = info.type;
  3211. binding.length = info.length;
  3212. #ifdef DEV_ENABLED
  3213. binding.writable = set_ptr[j].writable;
  3214. #endif
  3215. static_assert(sizeof(ShaderInfo::UniformBindingInfo::root_sig_locations) == sizeof(ShaderBinary::DataBinding::root_sig_locations));
  3216. memcpy((void *)&binding.root_sig_locations, (void *)&set_ptr[j].root_sig_locations, sizeof(ShaderInfo::UniformBindingInfo::root_sig_locations));
  3217. if (binding.root_sig_locations.resource.root_param_idx != UINT32_MAX) {
  3218. shader_info_in.sets[i].num_root_params.resources++;
  3219. }
  3220. if (binding.root_sig_locations.sampler.root_param_idx != UINT32_MAX) {
  3221. shader_info_in.sets[i].num_root_params.samplers++;
  3222. }
  3223. r_shader_desc.uniform_sets.write[i].push_back(info);
  3224. shader_info_in.sets[i].bindings.push_back(binding);
  3225. }
  3226. read_offset += set_size;
  3227. }
  3228. ERR_FAIL_COND_V(read_offset + binary_data.specialization_constants_count * sizeof(ShaderBinary::SpecializationConstant) >= binsize, ShaderID());
  3229. r_shader_desc.specialization_constants.resize(binary_data.specialization_constants_count);
  3230. shader_info_in.specialization_constants.resize(binary_data.specialization_constants_count);
  3231. for (uint32_t i = 0; i < binary_data.specialization_constants_count; i++) {
  3232. const ShaderBinary::SpecializationConstant &src_sc = *(reinterpret_cast<const ShaderBinary::SpecializationConstant *>(binptr + read_offset));
  3233. ShaderSpecializationConstant sc;
  3234. sc.type = PipelineSpecializationConstantType(src_sc.type);
  3235. sc.constant_id = src_sc.constant_id;
  3236. sc.int_value = src_sc.int_value;
  3237. sc.stages = src_sc.stage_flags;
  3238. r_shader_desc.specialization_constants.write[i] = sc;
  3239. ShaderInfo::SpecializationConstant ssc;
  3240. ssc.constant_id = src_sc.constant_id;
  3241. ssc.int_value = src_sc.int_value;
  3242. memcpy(ssc.stages_bit_offsets, src_sc.stages_bit_offsets, sizeof(ssc.stages_bit_offsets));
  3243. shader_info_in.specialization_constants[i] = ssc;
  3244. read_offset += sizeof(ShaderBinary::SpecializationConstant);
  3245. }
  3246. shader_info_in.spirv_specialization_constants_ids_mask = binary_data.spirv_specialization_constants_ids_mask;
  3247. for (uint32_t i = 0; i < binary_data.stage_count; i++) {
  3248. ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) * 3 >= binsize, ShaderID());
  3249. uint32_t stage = decode_uint32(binptr + read_offset);
  3250. read_offset += sizeof(uint32_t);
  3251. uint32_t dxil_size = decode_uint32(binptr + read_offset);
  3252. read_offset += sizeof(uint32_t);
  3253. uint32_t zstd_size = decode_uint32(binptr + read_offset);
  3254. read_offset += sizeof(uint32_t);
  3255. // Decompress.
  3256. Vector<uint8_t> dxil;
  3257. dxil.resize(dxil_size);
  3258. int dec_dxil_size = Compression::decompress(dxil.ptrw(), dxil.size(), binptr + read_offset, zstd_size, Compression::MODE_ZSTD);
  3259. ERR_FAIL_COND_V(dec_dxil_size != (int32_t)dxil_size, ShaderID());
  3260. shader_info_in.stages_bytecode[ShaderStage(stage)] = dxil;
  3261. zstd_size = STEPIFY(zstd_size, 4);
  3262. read_offset += zstd_size;
  3263. ERR_FAIL_COND_V(read_offset > binsize, ShaderID());
  3264. r_shader_desc.stages.push_back(ShaderStage(stage));
  3265. }
  3266. const uint8_t *root_sig_data_ptr = binptr + read_offset;
  3267. PFN_D3D12_CREATE_ROOT_SIGNATURE_DESERIALIZER d3d_D3D12CreateRootSignatureDeserializer = (PFN_D3D12_CREATE_ROOT_SIGNATURE_DESERIALIZER)(void *)GetProcAddress(context_driver->lib_d3d12, "D3D12CreateRootSignatureDeserializer");
  3268. ERR_FAIL_NULL_V(d3d_D3D12CreateRootSignatureDeserializer, ShaderID());
  3269. HRESULT res = d3d_D3D12CreateRootSignatureDeserializer(root_sig_data_ptr, binary_data.root_signature_len, IID_PPV_ARGS(shader_info_in.root_signature_deserializer.GetAddressOf()));
  3270. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ShaderID(), "D3D12CreateRootSignatureDeserializer failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  3271. read_offset += binary_data.root_signature_len;
  3272. ERR_FAIL_COND_V(read_offset != binsize, ShaderID());
  3273. ComPtr<ID3D12RootSignature> root_signature;
  3274. res = device->CreateRootSignature(0, root_sig_data_ptr, binary_data.root_signature_len, IID_PPV_ARGS(shader_info_in.root_signature.GetAddressOf()));
  3275. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ShaderID(), "CreateRootSignature failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  3276. shader_info_in.root_signature_desc = shader_info_in.root_signature_deserializer->GetRootSignatureDesc();
  3277. shader_info_in.root_signature_crc = binary_data.root_signature_crc;
  3278. // Bookkeep.
  3279. ShaderInfo *shader_info_ptr = VersatileResource::allocate<ShaderInfo>(resources_allocator);
  3280. *shader_info_ptr = shader_info_in;
  3281. return ShaderID(shader_info_ptr);
  3282. }
  3283. uint32_t RenderingDeviceDriverD3D12::shader_get_layout_hash(ShaderID p_shader) {
  3284. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_shader.id;
  3285. return shader_info_in->root_signature_crc;
  3286. }
  3287. void RenderingDeviceDriverD3D12::shader_free(ShaderID p_shader) {
  3288. ShaderInfo *shader_info_in = (ShaderInfo *)p_shader.id;
  3289. VersatileResource::free(resources_allocator, shader_info_in);
  3290. }
  3291. void RenderingDeviceDriverD3D12::shader_destroy_modules(ShaderID p_shader) {
  3292. ShaderInfo *shader_info_in = (ShaderInfo *)p_shader.id;
  3293. shader_info_in->stages_bytecode.clear();
  3294. }
  3295. /*********************/
  3296. /**** UNIFORM SET ****/
  3297. /*********************/
  3298. static void _add_descriptor_count_for_uniform(RenderingDevice::UniformType p_type, uint32_t p_binding_length, bool p_dobule_srv_uav_ambiguous, uint32_t &r_num_resources, uint32_t &r_num_samplers, bool &r_srv_uav_ambiguity) {
  3299. r_srv_uav_ambiguity = false;
  3300. // Some resource types can be SRV or UAV, depending on what NIR-DXIL decided for a specific shader variant.
  3301. // The goal is to generate both SRV and UAV for the descriptor sets' heaps and copy only the relevant one
  3302. // to the frame descriptor heap at binding time.
  3303. // [[SRV_UAV_AMBIGUITY]]
  3304. switch (p_type) {
  3305. case RenderingDevice::UNIFORM_TYPE_SAMPLER: {
  3306. r_num_samplers += p_binding_length;
  3307. } break;
  3308. case RenderingDevice::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE:
  3309. case RenderingDevice::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: {
  3310. r_num_resources += p_binding_length;
  3311. r_num_samplers += p_binding_length;
  3312. } break;
  3313. case RenderingDevice::UNIFORM_TYPE_UNIFORM_BUFFER: {
  3314. r_num_resources += 1;
  3315. } break;
  3316. case RenderingDevice::UNIFORM_TYPE_STORAGE_BUFFER: {
  3317. r_num_resources += p_dobule_srv_uav_ambiguous ? 2 : 1;
  3318. r_srv_uav_ambiguity = true;
  3319. } break;
  3320. case RenderingDevice::UNIFORM_TYPE_IMAGE: {
  3321. r_num_resources += p_binding_length * (p_dobule_srv_uav_ambiguous ? 2 : 1);
  3322. r_srv_uav_ambiguity = true;
  3323. } break;
  3324. default: {
  3325. r_num_resources += p_binding_length;
  3326. }
  3327. }
  3328. }
  3329. RDD::UniformSetID RenderingDeviceDriverD3D12::uniform_set_create(VectorView<BoundUniform> p_uniforms, ShaderID p_shader, uint32_t p_set_index) {
  3330. // Pre-bookkeep.
  3331. UniformSetInfo *uniform_set_info = VersatileResource::allocate<UniformSetInfo>(resources_allocator);
  3332. // Do a first pass to count resources and samplers.
  3333. uint32_t num_resource_descs = 0;
  3334. uint32_t num_sampler_descs = 0;
  3335. for (uint32_t i = 0; i < p_uniforms.size(); i++) {
  3336. const BoundUniform &uniform = p_uniforms[i];
  3337. // Since the uniform set may be created for a shader different than the one that will be actually bound,
  3338. // which may have a different set of uniforms optimized out, the stages mask we can check now is not reliable.
  3339. // Therefore, we can't make any assumptions here about descriptors that we may not need to create,
  3340. // pixel or vertex-only shader resource states, etc.
  3341. bool srv_uav_ambiguity = false;
  3342. uint32_t binding_length = uniform.ids.size();
  3343. if (uniform.type == UNIFORM_TYPE_SAMPLER_WITH_TEXTURE || uniform.type == UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER) {
  3344. binding_length /= 2;
  3345. }
  3346. _add_descriptor_count_for_uniform(uniform.type, binding_length, true, num_resource_descs, num_sampler_descs, srv_uav_ambiguity);
  3347. }
  3348. #ifdef DEV_ENABLED
  3349. uniform_set_info->resources_desc_info.reserve(num_resource_descs);
  3350. #endif
  3351. if (num_resource_descs) {
  3352. Error err = uniform_set_info->desc_heaps.resources.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, num_resource_descs, false);
  3353. if (err) {
  3354. VersatileResource::free(resources_allocator, uniform_set_info);
  3355. ERR_FAIL_V(UniformSetID());
  3356. }
  3357. }
  3358. if (num_sampler_descs) {
  3359. Error err = uniform_set_info->desc_heaps.samplers.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, num_sampler_descs, false);
  3360. if (err) {
  3361. VersatileResource::free(resources_allocator, uniform_set_info);
  3362. ERR_FAIL_V(UniformSetID());
  3363. }
  3364. }
  3365. struct {
  3366. DescriptorsHeap::Walker resources;
  3367. DescriptorsHeap::Walker samplers;
  3368. } desc_heap_walkers;
  3369. desc_heap_walkers.resources = uniform_set_info->desc_heaps.resources.make_walker();
  3370. desc_heap_walkers.samplers = uniform_set_info->desc_heaps.samplers.make_walker();
  3371. struct NeededState {
  3372. bool is_buffer = false;
  3373. uint64_t shader_uniform_idx_mask = 0;
  3374. D3D12_RESOURCE_STATES states = {};
  3375. };
  3376. HashMap<ResourceInfo *, NeededState> resource_states;
  3377. for (uint32_t i = 0; i < p_uniforms.size(); i++) {
  3378. const BoundUniform &uniform = p_uniforms[i];
  3379. #ifdef DEV_ENABLED
  3380. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_shader.id;
  3381. const ShaderInfo::UniformBindingInfo &shader_uniform = shader_info_in->sets[p_set_index].bindings[i];
  3382. bool is_compute = shader_info_in->stages_bytecode.has(SHADER_STAGE_COMPUTE);
  3383. DEV_ASSERT(!(is_compute && (shader_uniform.stages & (SHADER_STAGE_VERTEX_BIT | SHADER_STAGE_FRAGMENT_BIT))));
  3384. DEV_ASSERT(!(!is_compute && (shader_uniform.stages & SHADER_STAGE_COMPUTE_BIT)));
  3385. #endif
  3386. switch (uniform.type) {
  3387. case UNIFORM_TYPE_SAMPLER: {
  3388. for (uint32_t j = 0; j < uniform.ids.size(); j++) {
  3389. const D3D12_SAMPLER_DESC &sampler_desc = samplers[uniform.ids[j].id];
  3390. device->CreateSampler(&sampler_desc, desc_heap_walkers.samplers.get_curr_cpu_handle());
  3391. desc_heap_walkers.samplers.advance();
  3392. }
  3393. } break;
  3394. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {
  3395. for (uint32_t j = 0; j < uniform.ids.size(); j += 2) {
  3396. const D3D12_SAMPLER_DESC &sampler_desc = samplers[uniform.ids[j].id];
  3397. TextureInfo *texture_info = (TextureInfo *)uniform.ids[j + 1].id;
  3398. device->CreateSampler(&sampler_desc, desc_heap_walkers.samplers.get_curr_cpu_handle());
  3399. desc_heap_walkers.samplers.advance();
  3400. device->CreateShaderResourceView(texture_info->resource, &texture_info->view_descs.srv, desc_heap_walkers.resources.get_curr_cpu_handle());
  3401. #ifdef DEV_ENABLED
  3402. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_SRV, texture_info->view_descs.srv.ViewDimension });
  3403. #endif
  3404. desc_heap_walkers.resources.advance();
  3405. NeededState &ns = resource_states[texture_info];
  3406. ns.shader_uniform_idx_mask |= ((uint64_t)1 << i);
  3407. ns.states |= D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE;
  3408. }
  3409. } break;
  3410. case UNIFORM_TYPE_TEXTURE: {
  3411. for (uint32_t j = 0; j < uniform.ids.size(); j++) {
  3412. TextureInfo *texture_info = (TextureInfo *)uniform.ids[j].id;
  3413. device->CreateShaderResourceView(texture_info->resource, &texture_info->view_descs.srv, desc_heap_walkers.resources.get_curr_cpu_handle());
  3414. #ifdef DEV_ENABLED
  3415. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_SRV, texture_info->view_descs.srv.ViewDimension });
  3416. #endif
  3417. desc_heap_walkers.resources.advance();
  3418. NeededState &ns = resource_states[texture_info];
  3419. ns.shader_uniform_idx_mask |= ((uint64_t)1 << i);
  3420. ns.states |= D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE;
  3421. }
  3422. } break;
  3423. case UNIFORM_TYPE_IMAGE: {
  3424. for (uint32_t j = 0; j < uniform.ids.size(); j++) {
  3425. TextureInfo *texture_info = (TextureInfo *)uniform.ids[j].id;
  3426. NeededState &ns = resource_states[texture_info];
  3427. ns.shader_uniform_idx_mask |= ((uint64_t)1 << i);
  3428. ns.states |= (D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  3429. }
  3430. // SRVs first. [[SRV_UAV_AMBIGUITY]]
  3431. for (uint32_t j = 0; j < uniform.ids.size(); j++) {
  3432. TextureInfo *texture_info = (TextureInfo *)uniform.ids[j].id;
  3433. device->CreateShaderResourceView(texture_info->resource, &texture_info->view_descs.srv, desc_heap_walkers.resources.get_curr_cpu_handle());
  3434. #ifdef DEV_ENABLED
  3435. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_SRV, texture_info->view_descs.srv.ViewDimension });
  3436. #endif
  3437. desc_heap_walkers.resources.advance();
  3438. }
  3439. // UAVs then. [[SRV_UAV_AMBIGUITY]]
  3440. for (uint32_t j = 0; j < uniform.ids.size(); j++) {
  3441. TextureInfo *texture_info = (TextureInfo *)uniform.ids[j].id;
  3442. device->CreateUnorderedAccessView(texture_info->resource, nullptr, &texture_info->view_descs.uav, desc_heap_walkers.resources.get_curr_cpu_handle());
  3443. #ifdef DEV_ENABLED
  3444. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_UAV, {} });
  3445. #endif
  3446. desc_heap_walkers.resources.advance();
  3447. }
  3448. } break;
  3449. case UNIFORM_TYPE_TEXTURE_BUFFER:
  3450. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: {
  3451. CRASH_NOW_MSG("Unimplemented!");
  3452. } break;
  3453. case UNIFORM_TYPE_IMAGE_BUFFER: {
  3454. CRASH_NOW_MSG("Unimplemented!");
  3455. } break;
  3456. case UNIFORM_TYPE_UNIFORM_BUFFER: {
  3457. BufferInfo *buf_info = (BufferInfo *)uniform.ids[0].id;
  3458. D3D12_CONSTANT_BUFFER_VIEW_DESC cbv_desc = {};
  3459. cbv_desc.BufferLocation = buf_info->resource->GetGPUVirtualAddress();
  3460. cbv_desc.SizeInBytes = STEPIFY(buf_info->size, 256);
  3461. device->CreateConstantBufferView(&cbv_desc, desc_heap_walkers.resources.get_curr_cpu_handle());
  3462. desc_heap_walkers.resources.advance();
  3463. #ifdef DEV_ENABLED
  3464. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_CBV, {} });
  3465. #endif
  3466. NeededState &ns = resource_states[buf_info];
  3467. ns.is_buffer = true;
  3468. ns.shader_uniform_idx_mask |= ((uint64_t)1 << i);
  3469. ns.states |= D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
  3470. } break;
  3471. case UNIFORM_TYPE_STORAGE_BUFFER: {
  3472. BufferInfo *buf_info = (BufferInfo *)uniform.ids[0].id;
  3473. // SRV first. [[SRV_UAV_AMBIGUITY]]
  3474. {
  3475. D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc = {};
  3476. srv_desc.Format = DXGI_FORMAT_R32_TYPELESS;
  3477. srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
  3478. srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  3479. srv_desc.Buffer.FirstElement = 0;
  3480. srv_desc.Buffer.NumElements = (buf_info->size + 3) / 4;
  3481. srv_desc.Buffer.StructureByteStride = 0;
  3482. srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW;
  3483. device->CreateShaderResourceView(buf_info->resource, &srv_desc, desc_heap_walkers.resources.get_curr_cpu_handle());
  3484. #ifdef DEV_ENABLED
  3485. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srv_desc.ViewDimension });
  3486. #endif
  3487. desc_heap_walkers.resources.advance();
  3488. }
  3489. // UAV then. [[SRV_UAV_AMBIGUITY]]
  3490. {
  3491. if (buf_info->flags.usable_as_uav) {
  3492. D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc = {};
  3493. uav_desc.Format = DXGI_FORMAT_R32_TYPELESS;
  3494. uav_desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  3495. uav_desc.Buffer.FirstElement = 0;
  3496. uav_desc.Buffer.NumElements = (buf_info->size + 3) / 4;
  3497. uav_desc.Buffer.StructureByteStride = 0;
  3498. uav_desc.Buffer.CounterOffsetInBytes = 0;
  3499. uav_desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  3500. device->CreateUnorderedAccessView(buf_info->resource, nullptr, &uav_desc, desc_heap_walkers.resources.get_curr_cpu_handle());
  3501. #ifdef DEV_ENABLED
  3502. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_UAV, {} });
  3503. #endif
  3504. } else {
  3505. // If can't transition to UAV, leave this one empty since it won't be
  3506. // used, and trying to create an UAV view would trigger a validation error.
  3507. }
  3508. desc_heap_walkers.resources.advance();
  3509. }
  3510. NeededState &ns = resource_states[buf_info];
  3511. ns.shader_uniform_idx_mask |= ((uint64_t)1 << i);
  3512. ns.is_buffer = true;
  3513. ns.states |= (D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  3514. } break;
  3515. case UNIFORM_TYPE_INPUT_ATTACHMENT: {
  3516. for (uint32_t j = 0; j < uniform.ids.size(); j++) {
  3517. TextureInfo *texture_info = (TextureInfo *)uniform.ids[j].id;
  3518. device->CreateShaderResourceView(texture_info->resource, &texture_info->view_descs.srv, desc_heap_walkers.resources.get_curr_cpu_handle());
  3519. #ifdef DEV_ENABLED
  3520. uniform_set_info->resources_desc_info.push_back({ D3D12_DESCRIPTOR_RANGE_TYPE_SRV, texture_info->view_descs.srv.ViewDimension });
  3521. #endif
  3522. desc_heap_walkers.resources.advance();
  3523. NeededState &ns = resource_states[texture_info];
  3524. ns.shader_uniform_idx_mask |= ((uint64_t)1 << i);
  3525. ns.states |= D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  3526. }
  3527. } break;
  3528. default: {
  3529. DEV_ASSERT(false);
  3530. }
  3531. }
  3532. }
  3533. DEV_ASSERT(desc_heap_walkers.resources.is_at_eof());
  3534. DEV_ASSERT(desc_heap_walkers.samplers.is_at_eof());
  3535. {
  3536. uniform_set_info->resource_states.reserve(resource_states.size());
  3537. for (const KeyValue<ResourceInfo *, NeededState> &E : resource_states) {
  3538. UniformSetInfo::StateRequirement sr;
  3539. sr.resource = E.key;
  3540. sr.is_buffer = E.value.is_buffer;
  3541. sr.states = E.value.states;
  3542. sr.shader_uniform_idx_mask = E.value.shader_uniform_idx_mask;
  3543. uniform_set_info->resource_states.push_back(sr);
  3544. }
  3545. }
  3546. return UniformSetID(uniform_set_info);
  3547. }
  3548. void RenderingDeviceDriverD3D12::uniform_set_free(UniformSetID p_uniform_set) {
  3549. UniformSetInfo *uniform_set_info = (UniformSetInfo *)p_uniform_set.id;
  3550. VersatileResource::free(resources_allocator, uniform_set_info);
  3551. }
  3552. // ----- COMMANDS -----
  3553. void RenderingDeviceDriverD3D12::command_uniform_set_prepare_for_use(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
  3554. if (barrier_capabilities.enhanced_barriers_supported) {
  3555. return;
  3556. }
  3557. // Perform pending blackouts.
  3558. {
  3559. SelfList<TextureInfo> *E = textures_pending_clear.first();
  3560. while (E) {
  3561. TextureSubresourceRange subresources;
  3562. subresources.layer_count = E->self()->layers;
  3563. subresources.mipmap_count = E->self()->mipmaps;
  3564. command_clear_color_texture(p_cmd_buffer, TextureID(E->self()), TEXTURE_LAYOUT_UNDEFINED, Color(), subresources);
  3565. SelfList<TextureInfo> *next = E->next();
  3566. E->remove_from_list();
  3567. E = next;
  3568. }
  3569. }
  3570. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  3571. const UniformSetInfo *uniform_set_info = (const UniformSetInfo *)p_uniform_set.id;
  3572. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_shader.id;
  3573. const ShaderInfo::UniformSet &shader_set = shader_info_in->sets[p_set_index];
  3574. for (const UniformSetInfo::StateRequirement &sr : uniform_set_info->resource_states) {
  3575. #ifdef DEV_ENABLED
  3576. {
  3577. uint32_t stages = 0;
  3578. D3D12_RESOURCE_STATES wanted_state = {};
  3579. bool writable = false;
  3580. // Doing the full loop for debugging since the real one below may break early,
  3581. // but we want an exhaustive check
  3582. uint64_t inv_uniforms_mask = ~sr.shader_uniform_idx_mask; // Inverting the mask saves operations.
  3583. for (uint8_t bit = 0; inv_uniforms_mask != UINT64_MAX; bit++) {
  3584. uint64_t bit_mask = ((uint64_t)1 << bit);
  3585. if (likely((inv_uniforms_mask & bit_mask))) {
  3586. continue;
  3587. }
  3588. inv_uniforms_mask |= bit_mask;
  3589. const ShaderInfo::UniformBindingInfo &binding = shader_set.bindings[bit];
  3590. if (unlikely(!binding.stages)) {
  3591. continue;
  3592. }
  3593. D3D12_RESOURCE_STATES required_states = sr.states;
  3594. // Resolve a case of SRV/UAV ambiguity now. [[SRV_UAV_AMBIGUITY]]
  3595. if ((required_states & D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE) && (required_states & D3D12_RESOURCE_STATE_UNORDERED_ACCESS)) {
  3596. if (binding.res_class == RES_CLASS_SRV) {
  3597. required_states &= ~D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  3598. } else {
  3599. required_states = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  3600. }
  3601. }
  3602. if (stages) { // Second occurrence at least?
  3603. CRASH_COND_MSG(binding.writable != writable, "A resource is used in the same uniform set both as R/O and R/W. That's not supported and shouldn't happen.");
  3604. CRASH_COND_MSG(required_states != wanted_state, "A resource is used in the same uniform set with different resource states. The code needs to be enhanced to support that.");
  3605. } else {
  3606. wanted_state = required_states;
  3607. stages |= binding.stages;
  3608. writable = binding.writable;
  3609. }
  3610. DEV_ASSERT((wanted_state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS) == (bool)(wanted_state & D3D12_RESOURCE_STATE_UNORDERED_ACCESS));
  3611. }
  3612. }
  3613. #endif
  3614. // We may have assumed D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE for a resource,
  3615. // because at uniform set creation time we couldn't know for sure which stages
  3616. // it would be used in (due to the fact that a set can be created against a different,
  3617. // albeit compatible, shader, which may make a different usage in the end).
  3618. // However, now we know and can exclude up to one unneeded states.
  3619. // TODO: If subresources involved already in the needed states, or scheduled for it,
  3620. // maybe it's more optimal not to do anything here
  3621. uint32_t stages = 0;
  3622. D3D12_RESOURCE_STATES wanted_state = {};
  3623. uint64_t inv_uniforms_mask = ~sr.shader_uniform_idx_mask; // Inverting the mask saves operations.
  3624. for (uint8_t bit = 0; inv_uniforms_mask != UINT64_MAX; bit++) {
  3625. uint64_t bit_mask = ((uint64_t)1 << bit);
  3626. if (likely((inv_uniforms_mask & bit_mask))) {
  3627. continue;
  3628. }
  3629. inv_uniforms_mask |= bit_mask;
  3630. const ShaderInfo::UniformBindingInfo &binding = shader_set.bindings[bit];
  3631. if (unlikely(!binding.stages)) {
  3632. continue;
  3633. }
  3634. if (!stages) {
  3635. D3D12_RESOURCE_STATES required_states = sr.states;
  3636. // Resolve a case of SRV/UAV ambiguity now. [[SRV_UAV_AMBIGUITY]]
  3637. if ((required_states & D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE) && (required_states & D3D12_RESOURCE_STATE_UNORDERED_ACCESS)) {
  3638. if (binding.res_class == RES_CLASS_SRV) {
  3639. required_states &= ~D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  3640. } else {
  3641. required_states = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  3642. }
  3643. }
  3644. wanted_state = required_states;
  3645. if (!(wanted_state & D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE)) {
  3646. // By now, we already know the resource is used, and with no PS/NON_PS disjuntive; no need to check further.
  3647. break;
  3648. }
  3649. }
  3650. stages |= binding.stages;
  3651. if (stages == (SHADER_STAGE_VERTEX_BIT | SHADER_STAGE_FRAGMENT_BIT) || stages == SHADER_STAGE_COMPUTE_BIT) {
  3652. // By now, we already know the resource is used, and as both PS/NON_PS; no need to check further.
  3653. break;
  3654. }
  3655. }
  3656. if (likely(wanted_state)) {
  3657. if ((wanted_state & D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE)) {
  3658. if (stages == SHADER_STAGE_VERTEX_BIT || stages == SHADER_STAGE_COMPUTE_BIT) {
  3659. D3D12_RESOURCE_STATES unneeded_states = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  3660. wanted_state &= ~unneeded_states;
  3661. } else if (stages == SHADER_STAGE_FRAGMENT_BIT) {
  3662. D3D12_RESOURCE_STATES unneeded_states = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
  3663. wanted_state &= ~unneeded_states;
  3664. }
  3665. }
  3666. if (likely(wanted_state)) {
  3667. if (sr.is_buffer) {
  3668. _resource_transition_batch(cmd_buf_info, sr.resource, 0, 1, wanted_state);
  3669. } else {
  3670. TextureInfo *tex_info = (TextureInfo *)sr.resource;
  3671. uint32_t planes = 1;
  3672. if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
  3673. planes = format_get_plane_count(tex_info->format);
  3674. }
  3675. for (uint32_t i = 0; i < tex_info->layers; i++) {
  3676. for (uint32_t j = 0; j < tex_info->mipmaps; j++) {
  3677. uint32_t subresource = D3D12CalcSubresource(tex_info->base_mip + j, tex_info->base_layer + i, 0, tex_info->desc.MipLevels, tex_info->desc.ArraySize());
  3678. _resource_transition_batch(cmd_buf_info, tex_info, subresource, planes, wanted_state);
  3679. }
  3680. }
  3681. }
  3682. }
  3683. }
  3684. }
  3685. if (p_set_index == shader_info_in->sets.size() - 1) {
  3686. _resource_transitions_flush(cmd_buf_info);
  3687. }
  3688. }
  3689. void RenderingDeviceDriverD3D12::_command_check_descriptor_sets(CommandBufferID p_cmd_buffer) {
  3690. DEV_ASSERT(segment_begun && "Unable to use commands that rely on descriptors because a segment was never begun.");
  3691. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  3692. if (!cmd_buf_info->descriptor_heaps_set) {
  3693. // Set descriptor heaps for the command buffer if they haven't been set yet.
  3694. ID3D12DescriptorHeap *heaps[] = {
  3695. frames[frame_idx].desc_heaps.resources.get_heap(),
  3696. frames[frame_idx].desc_heaps.samplers.get_heap(),
  3697. };
  3698. cmd_buf_info->cmd_list->SetDescriptorHeaps(2, heaps);
  3699. cmd_buf_info->descriptor_heaps_set = true;
  3700. }
  3701. }
  3702. void RenderingDeviceDriverD3D12::_command_bind_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index, bool p_for_compute) {
  3703. _command_check_descriptor_sets(p_cmd_buffer);
  3704. UniformSetInfo *uniform_set_info = (UniformSetInfo *)p_uniform_set.id;
  3705. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_shader.id;
  3706. const ShaderInfo::UniformSet &shader_set = shader_info_in->sets[p_set_index];
  3707. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  3708. using SetRootDescriptorTableFn = void (STDMETHODCALLTYPE ID3D12GraphicsCommandList::*)(UINT, D3D12_GPU_DESCRIPTOR_HANDLE);
  3709. SetRootDescriptorTableFn set_root_desc_table_fn = p_for_compute ? &ID3D12GraphicsCommandList::SetComputeRootDescriptorTable : &ID3D12GraphicsCommandList1::SetGraphicsRootDescriptorTable;
  3710. // If this set's descriptors have already been set for the current execution and a compatible root signature, reuse!
  3711. uint32_t root_sig_crc = p_for_compute ? cmd_buf_info->compute_root_signature_crc : cmd_buf_info->graphics_root_signature_crc;
  3712. UniformSetInfo::RecentBind *last_bind = nullptr;
  3713. for (int i = 0; i < (int)ARRAY_SIZE(uniform_set_info->recent_binds); i++) {
  3714. if (uniform_set_info->recent_binds[i].segment_serial == frames[frame_idx].segment_serial) {
  3715. if (uniform_set_info->recent_binds[i].root_signature_crc == root_sig_crc) {
  3716. for (const RootDescriptorTable &table : uniform_set_info->recent_binds[i].root_tables.resources) {
  3717. (cmd_buf_info->cmd_list.Get()->*set_root_desc_table_fn)(table.root_param_idx, table.start_gpu_handle);
  3718. }
  3719. for (const RootDescriptorTable &table : uniform_set_info->recent_binds[i].root_tables.samplers) {
  3720. (cmd_buf_info->cmd_list.Get()->*set_root_desc_table_fn)(table.root_param_idx, table.start_gpu_handle);
  3721. }
  3722. #ifdef DEV_ENABLED
  3723. uniform_set_info->recent_binds[i].uses++;
  3724. frames[frame_idx].uniform_set_reused++;
  3725. #endif
  3726. return;
  3727. } else {
  3728. if (!last_bind || uniform_set_info->recent_binds[i].uses < last_bind->uses) {
  3729. // Prefer this one since it's been used less or we still haven't a better option.
  3730. last_bind = &uniform_set_info->recent_binds[i];
  3731. }
  3732. }
  3733. } else {
  3734. // Prefer this one since it's unused.
  3735. last_bind = &uniform_set_info->recent_binds[i];
  3736. last_bind->uses = 0;
  3737. }
  3738. }
  3739. struct {
  3740. DescriptorsHeap::Walker *resources = nullptr;
  3741. DescriptorsHeap::Walker *samplers = nullptr;
  3742. } frame_heap_walkers;
  3743. frame_heap_walkers.resources = &frames[frame_idx].desc_heap_walkers.resources;
  3744. frame_heap_walkers.samplers = &frames[frame_idx].desc_heap_walkers.samplers;
  3745. struct {
  3746. DescriptorsHeap::Walker resources;
  3747. DescriptorsHeap::Walker samplers;
  3748. } set_heap_walkers;
  3749. set_heap_walkers.resources = uniform_set_info->desc_heaps.resources.make_walker();
  3750. set_heap_walkers.samplers = uniform_set_info->desc_heaps.samplers.make_walker();
  3751. #ifdef DEV_ENABLED
  3752. // Whether we have stages where the uniform is actually used should match
  3753. // whether we have any root signature locations for it.
  3754. for (uint32_t i = 0; i < shader_set.bindings.size(); i++) {
  3755. bool has_rs_locations = false;
  3756. if (shader_set.bindings[i].root_sig_locations.resource.root_param_idx != UINT32_MAX ||
  3757. shader_set.bindings[i].root_sig_locations.sampler.root_param_idx != UINT32_MAX) {
  3758. has_rs_locations = true;
  3759. break;
  3760. }
  3761. bool has_stages = shader_set.bindings[i].stages;
  3762. DEV_ASSERT(has_rs_locations == has_stages);
  3763. }
  3764. #endif
  3765. last_bind->root_tables.resources.reserve(shader_set.num_root_params.resources);
  3766. last_bind->root_tables.resources.clear();
  3767. last_bind->root_tables.samplers.reserve(shader_set.num_root_params.samplers);
  3768. last_bind->root_tables.samplers.clear();
  3769. last_bind->uses++;
  3770. struct {
  3771. RootDescriptorTable *resources = nullptr;
  3772. RootDescriptorTable *samplers = nullptr;
  3773. } tables;
  3774. for (uint32_t i = 0; i < shader_set.bindings.size(); i++) {
  3775. const ShaderInfo::UniformBindingInfo &binding = shader_set.bindings[i];
  3776. uint32_t num_resource_descs = 0;
  3777. uint32_t num_sampler_descs = 0;
  3778. bool srv_uav_ambiguity = false;
  3779. _add_descriptor_count_for_uniform(binding.type, binding.length, false, num_resource_descs, num_sampler_descs, srv_uav_ambiguity);
  3780. bool resource_used = false;
  3781. if (shader_set.bindings[i].stages) {
  3782. {
  3783. const ShaderInfo::UniformBindingInfo::RootSignatureLocation &rs_loc_resource = shader_set.bindings[i].root_sig_locations.resource;
  3784. if (rs_loc_resource.root_param_idx != UINT32_MAX) { // Location used?
  3785. DEV_ASSERT(num_resource_descs);
  3786. DEV_ASSERT(!(srv_uav_ambiguity && (shader_set.bindings[i].res_class != RES_CLASS_SRV && shader_set.bindings[i].res_class != RES_CLASS_UAV))); // [[SRV_UAV_AMBIGUITY]]
  3787. bool must_flush_table = tables.resources && rs_loc_resource.root_param_idx != tables.resources->root_param_idx;
  3788. if (must_flush_table) {
  3789. // Check the root signature data has been filled ordered.
  3790. DEV_ASSERT(rs_loc_resource.root_param_idx > tables.resources->root_param_idx);
  3791. (cmd_buf_info->cmd_list.Get()->*set_root_desc_table_fn)(tables.resources->root_param_idx, tables.resources->start_gpu_handle);
  3792. tables.resources = nullptr;
  3793. }
  3794. if (unlikely(frame_heap_walkers.resources->get_free_handles() < num_resource_descs)) {
  3795. if (!frames[frame_idx].desc_heaps_exhausted_reported.resources) {
  3796. frames[frame_idx].desc_heaps_exhausted_reported.resources = true;
  3797. ERR_FAIL_MSG("Cannot bind uniform set because there's no enough room in current frame's RESOURCES descriptor heap.\n"
  3798. "Please increase the value of the rendering/rendering_device/d3d12/max_resource_descriptors_per_frame project setting.");
  3799. } else {
  3800. return;
  3801. }
  3802. }
  3803. if (!tables.resources) {
  3804. DEV_ASSERT(last_bind->root_tables.resources.size() < last_bind->root_tables.resources.get_capacity());
  3805. last_bind->root_tables.resources.resize(last_bind->root_tables.resources.size() + 1);
  3806. tables.resources = &last_bind->root_tables.resources[last_bind->root_tables.resources.size() - 1];
  3807. tables.resources->root_param_idx = rs_loc_resource.root_param_idx;
  3808. tables.resources->start_gpu_handle = frame_heap_walkers.resources->get_curr_gpu_handle();
  3809. }
  3810. // If there is ambiguity and it didn't clarify as SRVs, skip them, which come first. [[SRV_UAV_AMBIGUITY]]
  3811. if (srv_uav_ambiguity && shader_set.bindings[i].res_class != RES_CLASS_SRV) {
  3812. set_heap_walkers.resources.advance(num_resource_descs);
  3813. }
  3814. // TODO: Batch to avoid multiple calls where possible (in any case, flush before setting root descriptor tables, or even batch that as well).
  3815. device->CopyDescriptorsSimple(
  3816. num_resource_descs,
  3817. frame_heap_walkers.resources->get_curr_cpu_handle(),
  3818. set_heap_walkers.resources.get_curr_cpu_handle(),
  3819. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  3820. frame_heap_walkers.resources->advance(num_resource_descs);
  3821. // If there is ambiguity and it didn't clarify as UAVs, skip them, which come later. [[SRV_UAV_AMBIGUITY]]
  3822. if (srv_uav_ambiguity && shader_set.bindings[i].res_class != RES_CLASS_UAV) {
  3823. set_heap_walkers.resources.advance(num_resource_descs);
  3824. }
  3825. resource_used = true;
  3826. }
  3827. }
  3828. {
  3829. const ShaderInfo::UniformBindingInfo::RootSignatureLocation &rs_loc_sampler = shader_set.bindings[i].root_sig_locations.sampler;
  3830. if (rs_loc_sampler.root_param_idx != UINT32_MAX) { // Location used?
  3831. DEV_ASSERT(num_sampler_descs);
  3832. DEV_ASSERT(!srv_uav_ambiguity); // [[SRV_UAV_AMBIGUITY]]
  3833. bool must_flush_table = tables.samplers && rs_loc_sampler.root_param_idx != tables.samplers->root_param_idx;
  3834. if (must_flush_table) {
  3835. // Check the root signature data has been filled ordered.
  3836. DEV_ASSERT(rs_loc_sampler.root_param_idx > tables.samplers->root_param_idx);
  3837. (cmd_buf_info->cmd_list.Get()->*set_root_desc_table_fn)(tables.samplers->root_param_idx, tables.samplers->start_gpu_handle);
  3838. tables.samplers = nullptr;
  3839. }
  3840. if (unlikely(frame_heap_walkers.samplers->get_free_handles() < num_sampler_descs)) {
  3841. if (!frames[frame_idx].desc_heaps_exhausted_reported.samplers) {
  3842. frames[frame_idx].desc_heaps_exhausted_reported.samplers = true;
  3843. ERR_FAIL_MSG("Cannot bind uniform set because there's no enough room in current frame's SAMPLERS descriptors heap.\n"
  3844. "Please increase the value of the rendering/rendering_device/d3d12/max_sampler_descriptors_per_frame project setting.");
  3845. } else {
  3846. return;
  3847. }
  3848. }
  3849. if (!tables.samplers) {
  3850. DEV_ASSERT(last_bind->root_tables.samplers.size() < last_bind->root_tables.samplers.get_capacity());
  3851. last_bind->root_tables.samplers.resize(last_bind->root_tables.samplers.size() + 1);
  3852. tables.samplers = &last_bind->root_tables.samplers[last_bind->root_tables.samplers.size() - 1];
  3853. tables.samplers->root_param_idx = rs_loc_sampler.root_param_idx;
  3854. tables.samplers->start_gpu_handle = frame_heap_walkers.samplers->get_curr_gpu_handle();
  3855. }
  3856. // TODO: Batch to avoid multiple calls where possible (in any case, flush before setting root descriptor tables, or even batch that as well).
  3857. device->CopyDescriptorsSimple(
  3858. num_sampler_descs,
  3859. frame_heap_walkers.samplers->get_curr_cpu_handle(),
  3860. set_heap_walkers.samplers.get_curr_cpu_handle(),
  3861. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
  3862. frame_heap_walkers.samplers->advance(num_sampler_descs);
  3863. }
  3864. }
  3865. }
  3866. // Uniform set descriptor heaps are always full (descriptors are created for every uniform in them) despite
  3867. // the shader variant a given set is created upon may not need all of them due to DXC optimizations.
  3868. // Therefore, at this point we have to advance through the descriptor set descriptor's heap unconditionally.
  3869. set_heap_walkers.resources.advance(num_resource_descs);
  3870. if (srv_uav_ambiguity) {
  3871. DEV_ASSERT(num_resource_descs);
  3872. if (!resource_used) {
  3873. set_heap_walkers.resources.advance(num_resource_descs); // Additional skip, since both SRVs and UAVs have to be bypassed.
  3874. }
  3875. }
  3876. set_heap_walkers.samplers.advance(num_sampler_descs);
  3877. }
  3878. DEV_ASSERT(set_heap_walkers.resources.is_at_eof());
  3879. DEV_ASSERT(set_heap_walkers.samplers.is_at_eof());
  3880. {
  3881. bool must_flush_table = tables.resources;
  3882. if (must_flush_table) {
  3883. (cmd_buf_info->cmd_list.Get()->*set_root_desc_table_fn)(tables.resources->root_param_idx, tables.resources->start_gpu_handle);
  3884. }
  3885. }
  3886. {
  3887. bool must_flush_table = tables.samplers;
  3888. if (must_flush_table) {
  3889. (cmd_buf_info->cmd_list.Get()->*set_root_desc_table_fn)(tables.samplers->root_param_idx, tables.samplers->start_gpu_handle);
  3890. }
  3891. }
  3892. last_bind->root_signature_crc = root_sig_crc;
  3893. last_bind->segment_serial = frames[frame_idx].segment_serial;
  3894. }
  3895. /******************/
  3896. /**** TRANSFER ****/
  3897. /******************/
  3898. void RenderingDeviceDriverD3D12::command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) {
  3899. _command_check_descriptor_sets(p_cmd_buffer);
  3900. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  3901. BufferInfo *buf_info = (BufferInfo *)p_buffer.id;
  3902. if (frames[frame_idx].desc_heap_walkers.resources.is_at_eof()) {
  3903. if (!frames[frame_idx].desc_heaps_exhausted_reported.resources) {
  3904. frames[frame_idx].desc_heaps_exhausted_reported.resources = true;
  3905. ERR_FAIL_MSG(
  3906. "Cannot clear buffer because there's no enough room in current frame's RESOURCE descriptors heap.\n"
  3907. "Please increase the value of the rendering/rendering_device/d3d12/max_resource_descriptors_per_frame project setting.");
  3908. } else {
  3909. return;
  3910. }
  3911. }
  3912. if (frames[frame_idx].desc_heap_walkers.aux.is_at_eof()) {
  3913. if (!frames[frame_idx].desc_heaps_exhausted_reported.aux) {
  3914. frames[frame_idx].desc_heaps_exhausted_reported.aux = true;
  3915. ERR_FAIL_MSG(
  3916. "Cannot clear buffer because there's no enough room in current frame's AUX descriptors heap.\n"
  3917. "Please increase the value of the rendering/rendering_device/d3d12/max_misc_descriptors_per_frame project setting.");
  3918. } else {
  3919. return;
  3920. }
  3921. }
  3922. if (!barrier_capabilities.enhanced_barriers_supported) {
  3923. _resource_transition_batch(cmd_buf_info, buf_info, 0, 1, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  3924. _resource_transitions_flush(cmd_buf_info);
  3925. }
  3926. D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc = {};
  3927. uav_desc.Format = DXGI_FORMAT_R32_TYPELESS;
  3928. uav_desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  3929. uav_desc.Buffer.FirstElement = 0;
  3930. uav_desc.Buffer.NumElements = (buf_info->size + 3) / 4;
  3931. uav_desc.Buffer.StructureByteStride = 0;
  3932. uav_desc.Buffer.CounterOffsetInBytes = 0;
  3933. uav_desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  3934. device->CreateUnorderedAccessView(
  3935. buf_info->resource,
  3936. nullptr,
  3937. &uav_desc,
  3938. frames[frame_idx].desc_heap_walkers.aux.get_curr_cpu_handle());
  3939. device->CopyDescriptorsSimple(
  3940. 1,
  3941. frames[frame_idx].desc_heap_walkers.resources.get_curr_cpu_handle(),
  3942. frames[frame_idx].desc_heap_walkers.aux.get_curr_cpu_handle(),
  3943. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  3944. static const UINT values[4] = {};
  3945. cmd_buf_info->cmd_list->ClearUnorderedAccessViewUint(
  3946. frames[frame_idx].desc_heap_walkers.resources.get_curr_gpu_handle(),
  3947. frames[frame_idx].desc_heap_walkers.aux.get_curr_cpu_handle(),
  3948. buf_info->resource,
  3949. values,
  3950. 0,
  3951. nullptr);
  3952. frames[frame_idx].desc_heap_walkers.resources.advance();
  3953. frames[frame_idx].desc_heap_walkers.aux.advance();
  3954. }
  3955. void RenderingDeviceDriverD3D12::command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_buf_locfer, VectorView<BufferCopyRegion> p_regions) {
  3956. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  3957. BufferInfo *src_buf_info = (BufferInfo *)p_src_buffer.id;
  3958. BufferInfo *buf_loc_info = (BufferInfo *)p_buf_locfer.id;
  3959. if (!barrier_capabilities.enhanced_barriers_supported) {
  3960. _resource_transition_batch(cmd_buf_info, src_buf_info, 0, 1, D3D12_RESOURCE_STATE_COPY_SOURCE);
  3961. _resource_transition_batch(cmd_buf_info, buf_loc_info, 0, 1, D3D12_RESOURCE_STATE_COPY_DEST);
  3962. _resource_transitions_flush(cmd_buf_info);
  3963. }
  3964. for (uint32_t i = 0; i < p_regions.size(); i++) {
  3965. cmd_buf_info->cmd_list->CopyBufferRegion(buf_loc_info->resource, p_regions[i].dst_offset, src_buf_info->resource, p_regions[i].src_offset, p_regions[i].size);
  3966. }
  3967. }
  3968. void RenderingDeviceDriverD3D12::command_copy_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView<TextureCopyRegion> p_regions) {
  3969. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  3970. TextureInfo *src_tex_info = (TextureInfo *)p_src_texture.id;
  3971. TextureInfo *dst_tex_info = (TextureInfo *)p_dst_texture.id;
  3972. if (!barrier_capabilities.enhanced_barriers_supported) {
  3973. // Batch all barrier transitions for the textures before performing the copies.
  3974. for (uint32_t i = 0; i < p_regions.size(); i++) {
  3975. uint32_t layer_count = MIN(p_regions[i].src_subresources.layer_count, p_regions[i].dst_subresources.layer_count);
  3976. for (uint32_t j = 0; j < layer_count; j++) {
  3977. UINT src_subresource = _compute_subresource_from_layers(src_tex_info, p_regions[i].src_subresources, j);
  3978. UINT dst_subresource = _compute_subresource_from_layers(dst_tex_info, p_regions[i].dst_subresources, j);
  3979. _resource_transition_batch(cmd_buf_info, src_tex_info, src_subresource, 1, D3D12_RESOURCE_STATE_COPY_SOURCE);
  3980. _resource_transition_batch(cmd_buf_info, dst_tex_info, dst_subresource, 1, D3D12_RESOURCE_STATE_COPY_DEST);
  3981. }
  3982. }
  3983. _resource_transitions_flush(cmd_buf_info);
  3984. }
  3985. CD3DX12_BOX src_box;
  3986. for (uint32_t i = 0; i < p_regions.size(); i++) {
  3987. uint32_t layer_count = MIN(p_regions[i].src_subresources.layer_count, p_regions[i].dst_subresources.layer_count);
  3988. for (uint32_t j = 0; j < layer_count; j++) {
  3989. UINT src_subresource = _compute_subresource_from_layers(src_tex_info, p_regions[i].src_subresources, j);
  3990. UINT dst_subresource = _compute_subresource_from_layers(dst_tex_info, p_regions[i].dst_subresources, j);
  3991. CD3DX12_TEXTURE_COPY_LOCATION src_location(src_tex_info->resource, src_subresource);
  3992. CD3DX12_TEXTURE_COPY_LOCATION dst_location(dst_tex_info->resource, dst_subresource);
  3993. src_box.left = p_regions[i].src_offset.x;
  3994. src_box.top = p_regions[i].src_offset.y;
  3995. src_box.front = p_regions[i].src_offset.z;
  3996. src_box.right = p_regions[i].src_offset.x + p_regions[i].size.x;
  3997. src_box.bottom = p_regions[i].src_offset.y + p_regions[i].size.y;
  3998. src_box.back = p_regions[i].src_offset.z + p_regions[i].size.z;
  3999. cmd_buf_info->cmd_list->CopyTextureRegion(&dst_location, p_regions[i].dst_offset.x, p_regions[i].dst_offset.y, p_regions[i].dst_offset.z, &src_location, &src_box);
  4000. }
  4001. }
  4002. }
  4003. void RenderingDeviceDriverD3D12::command_resolve_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, uint32_t p_src_layer, uint32_t p_src_mipmap, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, uint32_t p_dst_layer, uint32_t p_dst_mipmap) {
  4004. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4005. TextureInfo *src_tex_info = (TextureInfo *)p_src_texture.id;
  4006. TextureInfo *dst_tex_info = (TextureInfo *)p_dst_texture.id;
  4007. UINT src_subresource = D3D12CalcSubresource(p_src_mipmap, p_src_layer, 0, src_tex_info->desc.MipLevels, src_tex_info->desc.ArraySize());
  4008. UINT dst_subresource = D3D12CalcSubresource(p_dst_mipmap, p_dst_layer, 0, dst_tex_info->desc.MipLevels, dst_tex_info->desc.ArraySize());
  4009. if (!barrier_capabilities.enhanced_barriers_supported) {
  4010. _resource_transition_batch(cmd_buf_info, src_tex_info, src_subresource, 1, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
  4011. _resource_transition_batch(cmd_buf_info, dst_tex_info, dst_subresource, 1, D3D12_RESOURCE_STATE_RESOLVE_DEST);
  4012. _resource_transitions_flush(cmd_buf_info);
  4013. }
  4014. cmd_buf_info->cmd_list->ResolveSubresource(dst_tex_info->resource, dst_subresource, src_tex_info->resource, src_subresource, RD_TO_D3D12_FORMAT[src_tex_info->format].general_format);
  4015. }
  4016. void RenderingDeviceDriverD3D12::command_clear_color_texture(CommandBufferID p_cmd_buffer, TextureID p_texture, TextureLayout p_texture_layout, const Color &p_color, const TextureSubresourceRange &p_subresources) {
  4017. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4018. TextureInfo *tex_info = (TextureInfo *)p_texture.id;
  4019. if (tex_info->main_texture) {
  4020. tex_info = tex_info->main_texture;
  4021. }
  4022. auto _transition_subresources = [&](D3D12_RESOURCE_STATES p_new_state) {
  4023. for (uint32_t i = 0; i < p_subresources.layer_count; i++) {
  4024. for (uint32_t j = 0; j < p_subresources.mipmap_count; j++) {
  4025. UINT subresource = D3D12CalcSubresource(
  4026. p_subresources.base_mipmap + j,
  4027. p_subresources.base_layer + i,
  4028. 0,
  4029. tex_info->desc.MipLevels,
  4030. tex_info->desc.ArraySize());
  4031. _resource_transition_batch(cmd_buf_info, tex_info, subresource, 1, p_new_state);
  4032. }
  4033. }
  4034. _resource_transitions_flush(cmd_buf_info);
  4035. };
  4036. if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) {
  4037. // Clear via RTV.
  4038. if (frames[frame_idx].desc_heap_walkers.rtv.get_free_handles() < p_subresources.mipmap_count) {
  4039. if (!frames[frame_idx].desc_heaps_exhausted_reported.rtv) {
  4040. frames[frame_idx].desc_heaps_exhausted_reported.rtv = true;
  4041. ERR_FAIL_MSG(
  4042. "Cannot clear texture because there's no enough room in current frame's RENDER TARGET descriptors heap.\n"
  4043. "Please increase the value of the rendering/rendering_device/d3d12/max_misc_descriptors_per_frame project setting.");
  4044. } else {
  4045. return;
  4046. }
  4047. }
  4048. if (!barrier_capabilities.enhanced_barriers_supported) {
  4049. _transition_subresources(D3D12_RESOURCE_STATE_RENDER_TARGET);
  4050. }
  4051. for (uint32_t i = 0; i < p_subresources.mipmap_count; i++) {
  4052. D3D12_RENDER_TARGET_VIEW_DESC rtv_desc = _make_rtv_for_texture(tex_info, p_subresources.base_mipmap + i, p_subresources.base_layer, p_subresources.layer_count, false);
  4053. rtv_desc.Format = tex_info->view_descs.uav.Format;
  4054. device->CreateRenderTargetView(
  4055. tex_info->resource,
  4056. &rtv_desc,
  4057. frames[frame_idx].desc_heap_walkers.rtv.get_curr_cpu_handle());
  4058. cmd_buf_info->cmd_list->ClearRenderTargetView(
  4059. frames[frame_idx].desc_heap_walkers.rtv.get_curr_cpu_handle(),
  4060. p_color.components,
  4061. 0,
  4062. nullptr);
  4063. frames[frame_idx].desc_heap_walkers.rtv.advance();
  4064. }
  4065. } else if (tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) {
  4066. // Clear via UAV.
  4067. _command_check_descriptor_sets(p_cmd_buffer);
  4068. if (frames[frame_idx].desc_heap_walkers.resources.get_free_handles() < p_subresources.mipmap_count) {
  4069. if (!frames[frame_idx].desc_heaps_exhausted_reported.resources) {
  4070. frames[frame_idx].desc_heaps_exhausted_reported.resources = true;
  4071. ERR_FAIL_MSG(
  4072. "Cannot clear texture because there's no enough room in current frame's RESOURCE descriptors heap.\n"
  4073. "Please increase the value of the rendering/rendering_device/d3d12/max_resource_descriptors_per_frame project setting.");
  4074. } else {
  4075. return;
  4076. }
  4077. }
  4078. if (frames[frame_idx].desc_heap_walkers.aux.get_free_handles() < p_subresources.mipmap_count) {
  4079. if (!frames[frame_idx].desc_heaps_exhausted_reported.aux) {
  4080. frames[frame_idx].desc_heaps_exhausted_reported.aux = true;
  4081. ERR_FAIL_MSG(
  4082. "Cannot clear texture because there's no enough room in current frame's AUX descriptors heap.\n"
  4083. "Please increase the value of the rendering/rendering_device/d3d12/max_misc_descriptors_per_frame project setting.");
  4084. } else {
  4085. return;
  4086. }
  4087. }
  4088. if (!barrier_capabilities.enhanced_barriers_supported) {
  4089. _transition_subresources(D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  4090. }
  4091. for (uint32_t i = 0; i < p_subresources.mipmap_count; i++) {
  4092. D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc = _make_ranged_uav_for_texture(tex_info, p_subresources.base_mipmap + i, p_subresources.base_layer, p_subresources.layer_count, false);
  4093. device->CreateUnorderedAccessView(
  4094. tex_info->resource,
  4095. nullptr,
  4096. &uav_desc,
  4097. frames[frame_idx].desc_heap_walkers.aux.get_curr_cpu_handle());
  4098. device->CopyDescriptorsSimple(
  4099. 1,
  4100. frames[frame_idx].desc_heap_walkers.resources.get_curr_cpu_handle(),
  4101. frames[frame_idx].desc_heap_walkers.aux.get_curr_cpu_handle(),
  4102. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  4103. UINT values[4] = {
  4104. (UINT)p_color.get_r8(),
  4105. (UINT)p_color.get_g8(),
  4106. (UINT)p_color.get_b8(),
  4107. (UINT)p_color.get_a8(),
  4108. };
  4109. cmd_buf_info->cmd_list->ClearUnorderedAccessViewUint(
  4110. frames[frame_idx].desc_heap_walkers.resources.get_curr_gpu_handle(),
  4111. frames[frame_idx].desc_heap_walkers.aux.get_curr_cpu_handle(),
  4112. tex_info->resource,
  4113. values,
  4114. 0,
  4115. nullptr);
  4116. frames[frame_idx].desc_heap_walkers.resources.advance();
  4117. frames[frame_idx].desc_heap_walkers.aux.advance();
  4118. }
  4119. } else {
  4120. ERR_FAIL_MSG("Cannot clear texture because its format does not support UAV writes. You'll need to update its contents through another method.");
  4121. }
  4122. }
  4123. void RenderingDeviceDriverD3D12::command_copy_buffer_to_texture(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView<BufferTextureCopyRegion> p_regions) {
  4124. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4125. BufferInfo *buf_info = (BufferInfo *)p_src_buffer.id;
  4126. TextureInfo *tex_info = (TextureInfo *)p_dst_texture.id;
  4127. if (!barrier_capabilities.enhanced_barriers_supported) {
  4128. _resource_transition_batch(cmd_buf_info, buf_info, 0, 1, D3D12_RESOURCE_STATE_COPY_SOURCE);
  4129. }
  4130. uint32_t pixel_size = get_image_format_pixel_size(tex_info->format);
  4131. uint32_t block_w = 0, block_h = 0;
  4132. get_compressed_image_format_block_dimensions(tex_info->format, block_w, block_h);
  4133. for (uint32_t i = 0; i < p_regions.size(); i++) {
  4134. uint32_t region_pitch = (p_regions[i].texture_region_size.x * pixel_size * block_w) >> get_compressed_image_format_pixel_rshift(tex_info->format);
  4135. region_pitch = STEPIFY(region_pitch, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  4136. D3D12_PLACED_SUBRESOURCE_FOOTPRINT src_footprint = {};
  4137. src_footprint.Offset = p_regions[i].buffer_offset;
  4138. src_footprint.Footprint = CD3DX12_SUBRESOURCE_FOOTPRINT(
  4139. RD_TO_D3D12_FORMAT[tex_info->format].family,
  4140. STEPIFY(p_regions[i].texture_region_size.x, block_w),
  4141. STEPIFY(p_regions[i].texture_region_size.y, block_h),
  4142. p_regions[i].texture_region_size.z,
  4143. region_pitch);
  4144. CD3DX12_TEXTURE_COPY_LOCATION copy_src(buf_info->resource, src_footprint);
  4145. CD3DX12_BOX src_box(
  4146. 0, 0, 0,
  4147. STEPIFY(p_regions[i].texture_region_size.x, block_w),
  4148. STEPIFY(p_regions[i].texture_region_size.y, block_h),
  4149. p_regions[i].texture_region_size.z);
  4150. if (!barrier_capabilities.enhanced_barriers_supported) {
  4151. for (uint32_t j = 0; j < p_regions[i].texture_subresources.layer_count; j++) {
  4152. UINT dst_subresource = D3D12CalcSubresource(
  4153. p_regions[i].texture_subresources.mipmap,
  4154. p_regions[i].texture_subresources.base_layer + j,
  4155. _compute_plane_slice(tex_info->format, p_regions[i].texture_subresources.aspect),
  4156. tex_info->desc.MipLevels,
  4157. tex_info->desc.ArraySize());
  4158. CD3DX12_TEXTURE_COPY_LOCATION copy_dst(tex_info->resource, dst_subresource);
  4159. _resource_transition_batch(cmd_buf_info, tex_info, dst_subresource, 1, D3D12_RESOURCE_STATE_COPY_DEST);
  4160. }
  4161. _resource_transitions_flush(cmd_buf_info);
  4162. }
  4163. for (uint32_t j = 0; j < p_regions[i].texture_subresources.layer_count; j++) {
  4164. UINT dst_subresource = D3D12CalcSubresource(
  4165. p_regions[i].texture_subresources.mipmap,
  4166. p_regions[i].texture_subresources.base_layer + j,
  4167. _compute_plane_slice(tex_info->format, p_regions[i].texture_subresources.aspect),
  4168. tex_info->desc.MipLevels,
  4169. tex_info->desc.ArraySize());
  4170. CD3DX12_TEXTURE_COPY_LOCATION copy_dst(tex_info->resource, dst_subresource);
  4171. cmd_buf_info->cmd_list->CopyTextureRegion(
  4172. &copy_dst,
  4173. p_regions[i].texture_offset.x,
  4174. p_regions[i].texture_offset.y,
  4175. p_regions[i].texture_offset.z,
  4176. &copy_src,
  4177. &src_box);
  4178. }
  4179. }
  4180. }
  4181. void RenderingDeviceDriverD3D12::command_copy_texture_to_buffer(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, BufferID p_buf_locfer, VectorView<BufferTextureCopyRegion> p_regions) {
  4182. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4183. TextureInfo *tex_info = (TextureInfo *)p_src_texture.id;
  4184. BufferInfo *buf_info = (BufferInfo *)p_buf_locfer.id;
  4185. if (!barrier_capabilities.enhanced_barriers_supported) {
  4186. _resource_transition_batch(cmd_buf_info, buf_info, 0, 1, D3D12_RESOURCE_STATE_COPY_DEST);
  4187. }
  4188. uint32_t block_w = 0, block_h = 0;
  4189. get_compressed_image_format_block_dimensions(tex_info->format, block_w, block_h);
  4190. for (uint32_t i = 0; i < p_regions.size(); i++) {
  4191. if (!barrier_capabilities.enhanced_barriers_supported) {
  4192. for (uint32_t j = 0; j < p_regions[i].texture_subresources.layer_count; j++) {
  4193. UINT src_subresource = D3D12CalcSubresource(
  4194. p_regions[i].texture_subresources.mipmap,
  4195. p_regions[i].texture_subresources.base_layer + j,
  4196. _compute_plane_slice(tex_info->format, p_regions[i].texture_subresources.aspect),
  4197. tex_info->desc.MipLevels,
  4198. tex_info->desc.ArraySize());
  4199. _resource_transition_batch(cmd_buf_info, tex_info, src_subresource, 1, D3D12_RESOURCE_STATE_COPY_SOURCE);
  4200. }
  4201. _resource_transitions_flush(cmd_buf_info);
  4202. }
  4203. for (uint32_t j = 0; j < p_regions[i].texture_subresources.layer_count; j++) {
  4204. UINT src_subresource = D3D12CalcSubresource(
  4205. p_regions[i].texture_subresources.mipmap,
  4206. p_regions[i].texture_subresources.base_layer + j,
  4207. _compute_plane_slice(tex_info->format, p_regions[i].texture_subresources.aspect),
  4208. tex_info->desc.MipLevels,
  4209. tex_info->desc.ArraySize());
  4210. CD3DX12_TEXTURE_COPY_LOCATION copy_src(tex_info->resource, src_subresource);
  4211. uint32_t computed_d = MAX(1, tex_info->desc.DepthOrArraySize >> p_regions[i].texture_subresources.mipmap);
  4212. uint32_t image_size = get_image_format_required_size(
  4213. tex_info->format,
  4214. MAX(1u, tex_info->desc.Width >> p_regions[i].texture_subresources.mipmap),
  4215. MAX(1u, tex_info->desc.Height >> p_regions[i].texture_subresources.mipmap),
  4216. computed_d,
  4217. 1);
  4218. uint32_t row_pitch = image_size / (p_regions[i].texture_region_size.y * computed_d) * block_h;
  4219. row_pitch = STEPIFY(row_pitch, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  4220. D3D12_PLACED_SUBRESOURCE_FOOTPRINT dst_footprint = {};
  4221. dst_footprint.Offset = p_regions[i].buffer_offset;
  4222. dst_footprint.Footprint.Width = STEPIFY(p_regions[i].texture_region_size.x, block_w);
  4223. dst_footprint.Footprint.Height = STEPIFY(p_regions[i].texture_region_size.y, block_h);
  4224. dst_footprint.Footprint.Depth = p_regions[i].texture_region_size.z;
  4225. dst_footprint.Footprint.RowPitch = row_pitch;
  4226. dst_footprint.Footprint.Format = RD_TO_D3D12_FORMAT[tex_info->format].family;
  4227. CD3DX12_TEXTURE_COPY_LOCATION copy_dst(buf_info->resource, dst_footprint);
  4228. cmd_buf_info->cmd_list->CopyTextureRegion(&copy_dst, 0, 0, 0, &copy_src, nullptr);
  4229. }
  4230. }
  4231. }
  4232. /******************/
  4233. /**** PIPELINE ****/
  4234. /******************/
  4235. void RenderingDeviceDriverD3D12::pipeline_free(PipelineID p_pipeline) {
  4236. PipelineInfo *pipeline_info = (PipelineInfo *)(p_pipeline.id);
  4237. pipeline_info->pso->Release();
  4238. memdelete(pipeline_info);
  4239. }
  4240. // ----- BINDING -----
  4241. void RenderingDeviceDriverD3D12::command_bind_push_constants(CommandBufferID p_cmd_buffer, ShaderID p_shader, uint32_t p_dst_first_index, VectorView<uint32_t> p_data) {
  4242. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  4243. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_shader.id;
  4244. if (!shader_info_in->dxil_push_constant_size) {
  4245. return;
  4246. }
  4247. if (shader_info_in->is_compute) {
  4248. cmd_buf_info->cmd_list->SetComputeRoot32BitConstants(0, p_data.size(), p_data.ptr(), p_dst_first_index);
  4249. } else {
  4250. cmd_buf_info->cmd_list->SetGraphicsRoot32BitConstants(0, p_data.size(), p_data.ptr(), p_dst_first_index);
  4251. }
  4252. }
  4253. // ----- CACHE -----
  4254. bool RenderingDeviceDriverD3D12::pipeline_cache_create(const Vector<uint8_t> &p_data) {
  4255. WARN_PRINT("PSO caching is not implemented yet in the Direct3D 12 driver.");
  4256. return false;
  4257. }
  4258. void RenderingDeviceDriverD3D12::pipeline_cache_free() {
  4259. ERR_FAIL_MSG("Not implemented.");
  4260. }
  4261. size_t RenderingDeviceDriverD3D12::pipeline_cache_query_size() {
  4262. ERR_FAIL_V_MSG(0, "Not implemented.");
  4263. }
  4264. Vector<uint8_t> RenderingDeviceDriverD3D12::pipeline_cache_serialize() {
  4265. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Not implemented.");
  4266. }
  4267. /*******************/
  4268. /**** RENDERING ****/
  4269. /*******************/
  4270. // ----- SUBPASS -----
  4271. RDD::RenderPassID RenderingDeviceDriverD3D12::render_pass_create(VectorView<Attachment> p_attachments, VectorView<Subpass> p_subpasses, VectorView<SubpassDependency> p_subpass_dependencies, uint32_t p_view_count) {
  4272. // Pre-bookkeep.
  4273. RenderPassInfo *pass_info = VersatileResource::allocate<RenderPassInfo>(resources_allocator);
  4274. pass_info->attachments.resize(p_attachments.size());
  4275. for (uint32_t i = 0; i < p_attachments.size(); i++) {
  4276. pass_info->attachments[i] = p_attachments[i];
  4277. }
  4278. pass_info->subpasses.resize(p_subpasses.size());
  4279. for (uint32_t i = 0; i < p_subpasses.size(); i++) {
  4280. pass_info->subpasses[i] = p_subpasses[i];
  4281. }
  4282. pass_info->view_count = p_view_count;
  4283. DXGI_FORMAT *formats = ALLOCA_ARRAY(DXGI_FORMAT, p_attachments.size());
  4284. for (uint32_t i = 0; i < p_attachments.size(); i++) {
  4285. const D3D12Format &format = RD_TO_D3D12_FORMAT[p_attachments[i].format];
  4286. if (format.dsv_format != DXGI_FORMAT_UNKNOWN) {
  4287. formats[i] = format.dsv_format;
  4288. } else {
  4289. formats[i] = format.general_format;
  4290. }
  4291. }
  4292. pass_info->max_supported_sample_count = _find_max_common_supported_sample_count(VectorView(formats, p_attachments.size()));
  4293. return RenderPassID(pass_info);
  4294. }
  4295. void RenderingDeviceDriverD3D12::render_pass_free(RenderPassID p_render_pass) {
  4296. RenderPassInfo *pass_info = (RenderPassInfo *)p_render_pass.id;
  4297. VersatileResource::free(resources_allocator, pass_info);
  4298. }
  4299. // ----- COMMANDS -----
  4300. void RenderingDeviceDriverD3D12::command_begin_render_pass(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, FramebufferID p_framebuffer, CommandBufferType p_cmd_buffer_type, const Rect2i &p_rect, VectorView<RenderPassClearValue> p_attachment_clears) {
  4301. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4302. const RenderPassInfo *pass_info = (const RenderPassInfo *)p_render_pass.id;
  4303. const FramebufferInfo *fb_info = (const FramebufferInfo *)p_framebuffer.id;
  4304. DEV_ASSERT(cmd_buf_info->render_pass_state.current_subpass == UINT32_MAX);
  4305. auto _transition_subresources = [&](TextureInfo *p_texture_info, D3D12_RESOURCE_STATES p_states) {
  4306. uint32_t planes = 1;
  4307. if ((p_texture_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
  4308. planes = format_get_plane_count(p_texture_info->format);
  4309. }
  4310. for (uint32_t i = 0; i < p_texture_info->layers; i++) {
  4311. for (uint32_t j = 0; j < p_texture_info->mipmaps; j++) {
  4312. uint32_t subresource = D3D12CalcSubresource(
  4313. p_texture_info->base_mip + j,
  4314. p_texture_info->base_layer + i,
  4315. 0,
  4316. p_texture_info->desc.MipLevels,
  4317. p_texture_info->desc.ArraySize());
  4318. _resource_transition_batch(cmd_buf_info, p_texture_info, subresource, planes, p_states);
  4319. }
  4320. }
  4321. };
  4322. if (fb_info->is_screen || !barrier_capabilities.enhanced_barriers_supported) {
  4323. // Screen framebuffers must perform this transition even if enhanced barriers are supported.
  4324. for (uint32_t i = 0; i < fb_info->attachments.size(); i++) {
  4325. TextureInfo *tex_info = (TextureInfo *)fb_info->attachments[i].id;
  4326. if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) {
  4327. _transition_subresources(tex_info, D3D12_RESOURCE_STATE_RENDER_TARGET);
  4328. } else if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
  4329. _transition_subresources(tex_info, D3D12_RESOURCE_STATE_DEPTH_WRITE);
  4330. } else {
  4331. DEV_ASSERT(false);
  4332. }
  4333. }
  4334. if (fb_info->vrs_attachment) {
  4335. TextureInfo *tex_info = (TextureInfo *)fb_info->vrs_attachment.id;
  4336. _transition_subresources(tex_info, D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE);
  4337. }
  4338. _resource_transitions_flush(cmd_buf_info);
  4339. }
  4340. cmd_buf_info->render_pass_state.region_rect = CD3DX12_RECT(
  4341. p_rect.position.x,
  4342. p_rect.position.y,
  4343. p_rect.position.x + p_rect.size.x,
  4344. p_rect.position.y + p_rect.size.y);
  4345. cmd_buf_info->render_pass_state.region_is_all = !(
  4346. cmd_buf_info->render_pass_state.region_rect.left == 0 &&
  4347. cmd_buf_info->render_pass_state.region_rect.top == 0 &&
  4348. cmd_buf_info->render_pass_state.region_rect.right == fb_info->size.x &&
  4349. cmd_buf_info->render_pass_state.region_rect.bottom == fb_info->size.y);
  4350. for (uint32_t i = 0; i < pass_info->attachments.size(); i++) {
  4351. if (pass_info->attachments[i].load_op == ATTACHMENT_LOAD_OP_DONT_CARE) {
  4352. const TextureInfo *tex_info = (const TextureInfo *)fb_info->attachments[i].id;
  4353. _discard_texture_subresources(tex_info, cmd_buf_info);
  4354. }
  4355. }
  4356. if (fb_info->vrs_attachment && vrs_capabilities.ss_image_supported) {
  4357. ComPtr<ID3D12GraphicsCommandList5> cmd_list_5;
  4358. cmd_buf_info->cmd_list->QueryInterface(cmd_list_5.GetAddressOf());
  4359. if (cmd_list_5) {
  4360. static const D3D12_SHADING_RATE_COMBINER COMBINERS[D3D12_RS_SET_SHADING_RATE_COMBINER_COUNT] = {
  4361. D3D12_SHADING_RATE_COMBINER_PASSTHROUGH,
  4362. D3D12_SHADING_RATE_COMBINER_OVERRIDE,
  4363. };
  4364. cmd_list_5->RSSetShadingRate(D3D12_SHADING_RATE_1X1, COMBINERS);
  4365. }
  4366. }
  4367. cmd_buf_info->render_pass_state.current_subpass = UINT32_MAX;
  4368. cmd_buf_info->render_pass_state.fb_info = fb_info;
  4369. cmd_buf_info->render_pass_state.pass_info = pass_info;
  4370. command_next_render_subpass(p_cmd_buffer, p_cmd_buffer_type);
  4371. AttachmentClear *clears = ALLOCA_ARRAY(AttachmentClear, pass_info->attachments.size());
  4372. Rect2i *clear_rects = ALLOCA_ARRAY(Rect2i, pass_info->attachments.size());
  4373. uint32_t num_clears = 0;
  4374. for (uint32_t i = 0; i < pass_info->attachments.size(); i++) {
  4375. TextureInfo *tex_info = (TextureInfo *)fb_info->attachments[i].id;
  4376. if (!tex_info) {
  4377. continue;
  4378. }
  4379. AttachmentClear clear;
  4380. if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) {
  4381. if (pass_info->attachments[i].load_op == ATTACHMENT_LOAD_OP_CLEAR) {
  4382. clear.aspect.set_flag(TEXTURE_ASPECT_COLOR_BIT);
  4383. clear.color_attachment = i;
  4384. tex_info->pending_clear.remove_from_list();
  4385. }
  4386. } else if ((tex_info->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
  4387. if (pass_info->attachments[i].stencil_load_op == ATTACHMENT_LOAD_OP_CLEAR) {
  4388. clear.aspect.set_flag(TEXTURE_ASPECT_DEPTH_BIT);
  4389. }
  4390. }
  4391. if (!clear.aspect.is_empty()) {
  4392. clear.value = p_attachment_clears[i];
  4393. clears[num_clears] = clear;
  4394. clear_rects[num_clears] = p_rect;
  4395. num_clears++;
  4396. }
  4397. }
  4398. if (num_clears) {
  4399. command_render_clear_attachments(p_cmd_buffer, VectorView(clears, num_clears), VectorView(clear_rects, num_clears));
  4400. }
  4401. }
  4402. void RenderingDeviceDriverD3D12::_end_render_pass(CommandBufferID p_cmd_buffer) {
  4403. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4404. DEV_ASSERT(cmd_buf_info->render_pass_state.current_subpass != UINT32_MAX);
  4405. const FramebufferInfo *fb_info = cmd_buf_info->render_pass_state.fb_info;
  4406. const RenderPassInfo *pass_info = cmd_buf_info->render_pass_state.pass_info;
  4407. const Subpass &subpass = pass_info->subpasses[cmd_buf_info->render_pass_state.current_subpass];
  4408. if (fb_info->is_screen) {
  4409. // Screen framebuffers must transition back to present state when the render pass is finished.
  4410. for (uint32_t i = 0; i < fb_info->attachments.size(); i++) {
  4411. TextureInfo *src_tex_info = (TextureInfo *)(fb_info->attachments[i].id);
  4412. uint32_t src_subresource = D3D12CalcSubresource(src_tex_info->base_mip, src_tex_info->base_layer, 0, src_tex_info->desc.MipLevels, src_tex_info->desc.ArraySize());
  4413. _resource_transition_batch(cmd_buf_info, src_tex_info, src_subresource, 1, D3D12_RESOURCE_STATE_PRESENT);
  4414. }
  4415. }
  4416. struct Resolve {
  4417. ID3D12Resource *src_res = nullptr;
  4418. uint32_t src_subres = 0;
  4419. ID3D12Resource *dst_res = nullptr;
  4420. uint32_t dst_subres = 0;
  4421. DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
  4422. };
  4423. Resolve *resolves = ALLOCA_ARRAY(Resolve, subpass.resolve_references.size());
  4424. uint32_t num_resolves = 0;
  4425. for (uint32_t i = 0; i < subpass.resolve_references.size(); i++) {
  4426. uint32_t color_index = subpass.color_references[i].attachment;
  4427. uint32_t resolve_index = subpass.resolve_references[i].attachment;
  4428. DEV_ASSERT((color_index == AttachmentReference::UNUSED) == (resolve_index == AttachmentReference::UNUSED));
  4429. if (color_index == AttachmentReference::UNUSED || !fb_info->attachments[color_index]) {
  4430. continue;
  4431. }
  4432. TextureInfo *src_tex_info = (TextureInfo *)fb_info->attachments[color_index].id;
  4433. uint32_t src_subresource = D3D12CalcSubresource(src_tex_info->base_mip, src_tex_info->base_layer, 0, src_tex_info->desc.MipLevels, src_tex_info->desc.ArraySize());
  4434. _resource_transition_batch(cmd_buf_info, src_tex_info, src_subresource, 1, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
  4435. TextureInfo *dst_tex_info = (TextureInfo *)fb_info->attachments[resolve_index].id;
  4436. uint32_t dst_subresource = D3D12CalcSubresource(dst_tex_info->base_mip, dst_tex_info->base_layer, 0, dst_tex_info->desc.MipLevels, dst_tex_info->desc.ArraySize());
  4437. _resource_transition_batch(cmd_buf_info, dst_tex_info, dst_subresource, 1, D3D12_RESOURCE_STATE_RESOLVE_DEST);
  4438. resolves[num_resolves].src_res = src_tex_info->resource;
  4439. resolves[num_resolves].src_subres = src_subresource;
  4440. resolves[num_resolves].dst_res = dst_tex_info->resource;
  4441. resolves[num_resolves].dst_subres = dst_subresource;
  4442. resolves[num_resolves].format = RD_TO_D3D12_FORMAT[src_tex_info->format].general_format;
  4443. num_resolves++;
  4444. }
  4445. _resource_transitions_flush(cmd_buf_info);
  4446. for (uint32_t i = 0; i < num_resolves; i++) {
  4447. cmd_buf_info->cmd_list->ResolveSubresource(resolves[i].dst_res, resolves[i].dst_subres, resolves[i].src_res, resolves[i].src_subres, resolves[i].format);
  4448. }
  4449. }
  4450. void RenderingDeviceDriverD3D12::command_end_render_pass(CommandBufferID p_cmd_buffer) {
  4451. _end_render_pass(p_cmd_buffer);
  4452. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4453. DEV_ASSERT(cmd_buf_info->render_pass_state.current_subpass != UINT32_MAX);
  4454. const FramebufferInfo *fb_info = cmd_buf_info->render_pass_state.fb_info;
  4455. const RenderPassInfo *pass_info = cmd_buf_info->render_pass_state.pass_info;
  4456. if (vrs_capabilities.ss_image_supported) {
  4457. ComPtr<ID3D12GraphicsCommandList5> cmd_list_5;
  4458. cmd_buf_info->cmd_list->QueryInterface(cmd_list_5.GetAddressOf());
  4459. if (cmd_list_5) {
  4460. cmd_list_5->RSSetShadingRateImage(nullptr);
  4461. }
  4462. }
  4463. for (uint32_t i = 0; i < pass_info->attachments.size(); i++) {
  4464. if (pass_info->attachments[i].store_op == ATTACHMENT_STORE_OP_DONT_CARE) {
  4465. const TextureInfo *tex_info = (const TextureInfo *)fb_info->attachments[i].id;
  4466. _discard_texture_subresources(tex_info, cmd_buf_info);
  4467. }
  4468. }
  4469. cmd_buf_info->render_pass_state.current_subpass = UINT32_MAX;
  4470. }
  4471. void RenderingDeviceDriverD3D12::command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) {
  4472. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4473. if (cmd_buf_info->render_pass_state.current_subpass == UINT32_MAX) {
  4474. cmd_buf_info->render_pass_state.current_subpass = 0;
  4475. } else {
  4476. _end_render_pass(p_cmd_buffer);
  4477. cmd_buf_info->render_pass_state.current_subpass++;
  4478. }
  4479. const FramebufferInfo *fb_info = cmd_buf_info->render_pass_state.fb_info;
  4480. const RenderPassInfo *pass_info = cmd_buf_info->render_pass_state.pass_info;
  4481. const Subpass &subpass = pass_info->subpasses[cmd_buf_info->render_pass_state.current_subpass];
  4482. D3D12_CPU_DESCRIPTOR_HANDLE *rtv_handles = ALLOCA_ARRAY(D3D12_CPU_DESCRIPTOR_HANDLE, subpass.color_references.size());
  4483. DescriptorsHeap::Walker rtv_heap_walker = fb_info->rtv_heap.make_walker();
  4484. for (uint32_t i = 0; i < subpass.color_references.size(); i++) {
  4485. uint32_t attachment = subpass.color_references[i].attachment;
  4486. if (attachment == AttachmentReference::UNUSED) {
  4487. if (!frames[frame_idx].null_rtv_handle.ptr) {
  4488. // No null descriptor-handle created for this frame yet.
  4489. if (frames[frame_idx].desc_heap_walkers.rtv.is_at_eof()) {
  4490. if (!frames[frame_idx].desc_heaps_exhausted_reported.rtv) {
  4491. frames[frame_idx].desc_heaps_exhausted_reported.rtv = true;
  4492. ERR_FAIL_MSG("Cannot begin subpass because there's no enough room in current frame's RENDER TARGET descriptors heap.\n"
  4493. "Please increase the value of the rendering/rendering_device/d3d12/max_misc_descriptors_per_frame project setting.");
  4494. } else {
  4495. return;
  4496. }
  4497. }
  4498. D3D12_RENDER_TARGET_VIEW_DESC rtv_desc_null = {};
  4499. rtv_desc_null.Format = DXGI_FORMAT_R8_UINT;
  4500. rtv_desc_null.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
  4501. frames[frame_idx].null_rtv_handle = frames[frame_idx].desc_heap_walkers.rtv.get_curr_cpu_handle();
  4502. device->CreateRenderTargetView(nullptr, &rtv_desc_null, frames[frame_idx].null_rtv_handle);
  4503. frames[frame_idx].desc_heap_walkers.rtv.advance();
  4504. }
  4505. rtv_handles[i] = frames[frame_idx].null_rtv_handle;
  4506. } else {
  4507. uint32_t rt_index = fb_info->attachments_handle_inds[attachment];
  4508. rtv_heap_walker.rewind();
  4509. rtv_heap_walker.advance(rt_index);
  4510. rtv_handles[i] = rtv_heap_walker.get_curr_cpu_handle();
  4511. }
  4512. }
  4513. D3D12_CPU_DESCRIPTOR_HANDLE dsv_handle = {};
  4514. {
  4515. DescriptorsHeap::Walker dsv_heap_walker = fb_info->dsv_heap.make_walker();
  4516. if (subpass.depth_stencil_reference.attachment != AttachmentReference::UNUSED) {
  4517. uint32_t ds_index = fb_info->attachments_handle_inds[subpass.depth_stencil_reference.attachment];
  4518. dsv_heap_walker.rewind();
  4519. dsv_heap_walker.advance(ds_index);
  4520. dsv_handle = dsv_heap_walker.get_curr_cpu_handle();
  4521. }
  4522. }
  4523. cmd_buf_info->cmd_list->OMSetRenderTargets(subpass.color_references.size(), rtv_handles, false, dsv_handle.ptr ? &dsv_handle : nullptr);
  4524. }
  4525. void RenderingDeviceDriverD3D12::command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_viewports) {
  4526. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  4527. D3D12_VIEWPORT *d3d12_viewports = ALLOCA_ARRAY(D3D12_VIEWPORT, p_viewports.size());
  4528. for (uint32_t i = 0; i < p_viewports.size(); i++) {
  4529. d3d12_viewports[i] = CD3DX12_VIEWPORT(
  4530. p_viewports[i].position.x,
  4531. p_viewports[i].position.y,
  4532. p_viewports[i].size.x,
  4533. p_viewports[i].size.y);
  4534. }
  4535. cmd_buf_info->cmd_list->RSSetViewports(p_viewports.size(), d3d12_viewports);
  4536. }
  4537. void RenderingDeviceDriverD3D12::command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_scissors) {
  4538. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  4539. D3D12_RECT *d3d12_scissors = ALLOCA_ARRAY(D3D12_RECT, p_scissors.size());
  4540. for (uint32_t i = 0; i < p_scissors.size(); i++) {
  4541. d3d12_scissors[i] = CD3DX12_RECT(
  4542. p_scissors[i].position.x,
  4543. p_scissors[i].position.y,
  4544. p_scissors[i].position.x + p_scissors[i].size.x,
  4545. p_scissors[i].position.y + p_scissors[i].size.y);
  4546. }
  4547. cmd_buf_info->cmd_list->RSSetScissorRects(p_scissors.size(), d3d12_scissors);
  4548. }
  4549. void RenderingDeviceDriverD3D12::command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView<AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects) {
  4550. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  4551. DEV_ASSERT(cmd_buf_info->render_pass_state.current_subpass != UINT32_MAX);
  4552. const FramebufferInfo *fb_info = cmd_buf_info->render_pass_state.fb_info;
  4553. const RenderPassInfo *pass_info = cmd_buf_info->render_pass_state.pass_info;
  4554. DescriptorsHeap::Walker rtv_heap_walker = fb_info->rtv_heap.make_walker();
  4555. DescriptorsHeap::Walker dsv_heap_walker = fb_info->dsv_heap.make_walker();
  4556. for (uint32_t i = 0; i < p_attachment_clears.size(); i++) {
  4557. uint32_t attachment = UINT32_MAX;
  4558. bool is_render_target = false;
  4559. if (p_attachment_clears[i].aspect.has_flag(TEXTURE_ASPECT_COLOR_BIT)) {
  4560. attachment = p_attachment_clears[i].color_attachment;
  4561. is_render_target = true;
  4562. } else {
  4563. attachment = pass_info->subpasses[cmd_buf_info->render_pass_state.current_subpass].depth_stencil_reference.attachment;
  4564. }
  4565. for (uint32_t j = 0; j < p_rects.size(); j++) {
  4566. D3D12_RECT rect = CD3DX12_RECT(
  4567. p_rects[j].position.x,
  4568. p_rects[j].position.y,
  4569. p_rects[j].position.x + p_rects[j].size.x,
  4570. p_rects[j].position.y + p_rects[j].size.y);
  4571. const D3D12_RECT *rect_ptr = cmd_buf_info->render_pass_state.region_is_all ? nullptr : &rect;
  4572. if (is_render_target) {
  4573. uint32_t color_idx = fb_info->attachments_handle_inds[attachment];
  4574. rtv_heap_walker.rewind();
  4575. rtv_heap_walker.advance(color_idx);
  4576. cmd_buf_info->cmd_list->ClearRenderTargetView(
  4577. rtv_heap_walker.get_curr_cpu_handle(),
  4578. p_attachment_clears[i].value.color.components,
  4579. rect_ptr ? 1 : 0,
  4580. rect_ptr);
  4581. } else {
  4582. uint32_t depth_stencil_idx = fb_info->attachments_handle_inds[attachment];
  4583. dsv_heap_walker.rewind();
  4584. dsv_heap_walker.advance(depth_stencil_idx);
  4585. D3D12_CLEAR_FLAGS flags = {};
  4586. if (p_attachment_clears[i].aspect.has_flag(TEXTURE_ASPECT_DEPTH_BIT)) {
  4587. flags |= D3D12_CLEAR_FLAG_DEPTH;
  4588. }
  4589. if (p_attachment_clears[i].aspect.has_flag(TEXTURE_ASPECT_STENCIL_BIT)) {
  4590. flags |= D3D12_CLEAR_FLAG_STENCIL;
  4591. }
  4592. cmd_buf_info->cmd_list->ClearDepthStencilView(
  4593. dsv_heap_walker.get_curr_cpu_handle(),
  4594. flags,
  4595. p_attachment_clears[i].value.depth,
  4596. p_attachment_clears[i].value.stencil,
  4597. rect_ptr ? 1 : 0,
  4598. rect_ptr);
  4599. }
  4600. }
  4601. }
  4602. }
  4603. void RenderingDeviceDriverD3D12::command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) {
  4604. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4605. const PipelineInfo *pipeline_info = (const PipelineInfo *)p_pipeline.id;
  4606. if (cmd_buf_info->graphics_pso == pipeline_info->pso) {
  4607. return;
  4608. }
  4609. const ShaderInfo *shader_info_in = pipeline_info->shader_info;
  4610. const RenderPipelineInfo &render_info = pipeline_info->render_info;
  4611. cmd_buf_info->cmd_list->SetPipelineState(pipeline_info->pso);
  4612. if (cmd_buf_info->graphics_root_signature_crc != shader_info_in->root_signature_crc) {
  4613. cmd_buf_info->cmd_list->SetGraphicsRootSignature(shader_info_in->root_signature.Get());
  4614. cmd_buf_info->graphics_root_signature_crc = shader_info_in->root_signature_crc;
  4615. }
  4616. cmd_buf_info->cmd_list->IASetPrimitiveTopology(render_info.dyn_params.primitive_topology);
  4617. cmd_buf_info->cmd_list->OMSetBlendFactor(render_info.dyn_params.blend_constant.components);
  4618. cmd_buf_info->cmd_list->OMSetStencilRef(render_info.dyn_params.stencil_reference);
  4619. if (misc_features_support.depth_bounds_supported) {
  4620. ComPtr<ID3D12GraphicsCommandList1> command_list_1;
  4621. cmd_buf_info->cmd_list->QueryInterface(command_list_1.GetAddressOf());
  4622. if (command_list_1) {
  4623. command_list_1->OMSetDepthBounds(render_info.dyn_params.depth_bounds_min, render_info.dyn_params.depth_bounds_max);
  4624. }
  4625. }
  4626. cmd_buf_info->render_pass_state.vf_info = render_info.vf_info;
  4627. cmd_buf_info->graphics_pso = pipeline_info->pso;
  4628. cmd_buf_info->compute_pso = nullptr;
  4629. }
  4630. void RenderingDeviceDriverD3D12::command_bind_render_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
  4631. _command_bind_uniform_set(p_cmd_buffer, p_uniform_set, p_shader, p_set_index, false);
  4632. }
  4633. void RenderingDeviceDriverD3D12::command_render_draw(CommandBufferID p_cmd_buffer, uint32_t p_vertex_count, uint32_t p_instance_count, uint32_t p_base_vertex, uint32_t p_first_instance) {
  4634. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4635. _bind_vertex_buffers(cmd_buf_info);
  4636. cmd_buf_info->cmd_list->DrawInstanced(p_vertex_count, p_instance_count, p_base_vertex, p_first_instance);
  4637. }
  4638. void RenderingDeviceDriverD3D12::command_render_draw_indexed(CommandBufferID p_cmd_buffer, uint32_t p_index_count, uint32_t p_instance_count, uint32_t p_first_index, int32_t p_vertex_offset, uint32_t p_first_instance) {
  4639. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4640. _bind_vertex_buffers(cmd_buf_info);
  4641. cmd_buf_info->cmd_list->DrawIndexedInstanced(p_index_count, p_instance_count, p_first_index, p_vertex_offset, p_first_instance);
  4642. }
  4643. void RenderingDeviceDriverD3D12::command_render_draw_indexed_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) {
  4644. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4645. _bind_vertex_buffers(cmd_buf_info);
  4646. BufferInfo *indirect_buf_info = (BufferInfo *)p_indirect_buffer.id;
  4647. if (!barrier_capabilities.enhanced_barriers_supported) {
  4648. _resource_transition_batch(cmd_buf_info, indirect_buf_info, 0, 1, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  4649. _resource_transitions_flush(cmd_buf_info);
  4650. }
  4651. cmd_buf_info->cmd_list->ExecuteIndirect(indirect_cmd_signatures.draw_indexed.Get(), p_draw_count, indirect_buf_info->resource, p_offset, nullptr, 0);
  4652. }
  4653. void RenderingDeviceDriverD3D12::command_render_draw_indexed_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) {
  4654. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4655. _bind_vertex_buffers(cmd_buf_info);
  4656. BufferInfo *indirect_buf_info = (BufferInfo *)p_indirect_buffer.id;
  4657. BufferInfo *count_buf_info = (BufferInfo *)p_count_buffer.id;
  4658. if (!barrier_capabilities.enhanced_barriers_supported) {
  4659. _resource_transition_batch(cmd_buf_info, indirect_buf_info, 0, 1, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  4660. _resource_transition_batch(cmd_buf_info, count_buf_info, 0, 1, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  4661. _resource_transitions_flush(cmd_buf_info);
  4662. }
  4663. cmd_buf_info->cmd_list->ExecuteIndirect(indirect_cmd_signatures.draw_indexed.Get(), p_max_draw_count, indirect_buf_info->resource, p_offset, count_buf_info->resource, p_count_buffer_offset);
  4664. }
  4665. void RenderingDeviceDriverD3D12::command_render_draw_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) {
  4666. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4667. _bind_vertex_buffers(cmd_buf_info);
  4668. BufferInfo *indirect_buf_info = (BufferInfo *)p_indirect_buffer.id;
  4669. if (!barrier_capabilities.enhanced_barriers_supported) {
  4670. _resource_transition_batch(cmd_buf_info, indirect_buf_info, 0, 1, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  4671. _resource_transitions_flush(cmd_buf_info);
  4672. }
  4673. cmd_buf_info->cmd_list->ExecuteIndirect(indirect_cmd_signatures.draw.Get(), p_draw_count, indirect_buf_info->resource, p_offset, nullptr, 0);
  4674. }
  4675. void RenderingDeviceDriverD3D12::command_render_draw_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) {
  4676. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4677. _bind_vertex_buffers(cmd_buf_info);
  4678. BufferInfo *indirect_buf_info = (BufferInfo *)p_indirect_buffer.id;
  4679. BufferInfo *count_buf_info = (BufferInfo *)p_count_buffer.id;
  4680. if (!barrier_capabilities.enhanced_barriers_supported) {
  4681. _resource_transition_batch(cmd_buf_info, indirect_buf_info, 0, 1, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  4682. _resource_transition_batch(cmd_buf_info, count_buf_info, 0, 1, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  4683. _resource_transitions_flush(cmd_buf_info);
  4684. }
  4685. cmd_buf_info->cmd_list->ExecuteIndirect(indirect_cmd_signatures.draw.Get(), p_max_draw_count, indirect_buf_info->resource, p_offset, count_buf_info->resource, p_count_buffer_offset);
  4686. }
  4687. void RenderingDeviceDriverD3D12::command_render_bind_vertex_buffers(CommandBufferID p_cmd_buffer, uint32_t p_binding_count, const BufferID *p_buffers, const uint64_t *p_offsets) {
  4688. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4689. DEV_ASSERT(cmd_buf_info->render_pass_state.current_subpass != UINT32_MAX);
  4690. // Vertex buffer views are set deferredly, to be sure we already know the strides by then,
  4691. // which is only true once the pipeline has been bound. Otherwise, we'd need that the pipeline
  4692. // is always bound first, which would be not kind of us. [[DEFERRED_VERTEX_BUFFERS]]
  4693. DEV_ASSERT(p_binding_count <= ARRAY_SIZE(cmd_buf_info->render_pass_state.vertex_buffer_views));
  4694. for (uint32_t i = 0; i < p_binding_count; i++) {
  4695. BufferInfo *buffer_info = (BufferInfo *)p_buffers[i].id;
  4696. cmd_buf_info->render_pass_state.vertex_buffer_views[i] = {};
  4697. cmd_buf_info->render_pass_state.vertex_buffer_views[i].BufferLocation = buffer_info->resource->GetGPUVirtualAddress() + p_offsets[i];
  4698. cmd_buf_info->render_pass_state.vertex_buffer_views[i].SizeInBytes = buffer_info->size - p_offsets[i];
  4699. if (!barrier_capabilities.enhanced_barriers_supported) {
  4700. _resource_transition_batch(cmd_buf_info, buffer_info, 0, 1, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
  4701. }
  4702. }
  4703. if (!barrier_capabilities.enhanced_barriers_supported) {
  4704. _resource_transitions_flush(cmd_buf_info);
  4705. }
  4706. cmd_buf_info->render_pass_state.vertex_buffer_count = p_binding_count;
  4707. }
  4708. void RenderingDeviceDriverD3D12::command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) {
  4709. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  4710. BufferInfo *buffer_info = (BufferInfo *)p_buffer.id;
  4711. D3D12_INDEX_BUFFER_VIEW d3d12_ib_view = {};
  4712. d3d12_ib_view.BufferLocation = buffer_info->resource->GetGPUVirtualAddress() + p_offset;
  4713. d3d12_ib_view.SizeInBytes = buffer_info->size - p_offset;
  4714. d3d12_ib_view.Format = p_format == INDEX_BUFFER_FORMAT_UINT16 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
  4715. if (!barrier_capabilities.enhanced_barriers_supported) {
  4716. _resource_transition_batch(cmd_buf_info, buffer_info, 0, 1, D3D12_RESOURCE_STATE_INDEX_BUFFER);
  4717. _resource_transitions_flush(cmd_buf_info);
  4718. }
  4719. cmd_buf_info->cmd_list->IASetIndexBuffer(&d3d12_ib_view);
  4720. }
  4721. // [[DEFERRED_VERTEX_BUFFERS]]
  4722. void RenderingDeviceDriverD3D12::_bind_vertex_buffers(CommandBufferInfo *p_cmd_buf_info) {
  4723. RenderPassState &render_pass_state = p_cmd_buf_info->render_pass_state;
  4724. if (render_pass_state.vertex_buffer_count && render_pass_state.vf_info) {
  4725. for (uint32_t i = 0; i < render_pass_state.vertex_buffer_count; i++) {
  4726. render_pass_state.vertex_buffer_views[i].StrideInBytes = render_pass_state.vf_info->vertex_buffer_strides[i];
  4727. }
  4728. p_cmd_buf_info->cmd_list->IASetVertexBuffers(0, render_pass_state.vertex_buffer_count, render_pass_state.vertex_buffer_views);
  4729. render_pass_state.vertex_buffer_count = 0;
  4730. }
  4731. }
  4732. void RenderingDeviceDriverD3D12::command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) {
  4733. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  4734. cmd_buf_info->cmd_list->OMSetBlendFactor(p_constants.components);
  4735. }
  4736. void RenderingDeviceDriverD3D12::command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) {
  4737. if (!Math::is_equal_approx(p_width, 1.0f)) {
  4738. ERR_FAIL_MSG("Setting line widths other than 1.0 is not supported by the Direct3D 12 rendering driver.");
  4739. }
  4740. }
  4741. // ----- PIPELINE -----
  4742. static const D3D12_PRIMITIVE_TOPOLOGY_TYPE RD_PRIMITIVE_TO_D3D12_TOPOLOGY_TYPE[RDD::RENDER_PRIMITIVE_MAX] = {
  4743. D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT,
  4744. D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE,
  4745. D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE,
  4746. D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE,
  4747. D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE,
  4748. D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  4749. D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  4750. D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  4751. D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  4752. D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  4753. D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH,
  4754. };
  4755. static const D3D12_PRIMITIVE_TOPOLOGY RD_PRIMITIVE_TO_D3D12_TOPOLOGY[RDD::RENDER_PRIMITIVE_MAX] = {
  4756. D3D_PRIMITIVE_TOPOLOGY_POINTLIST,
  4757. D3D_PRIMITIVE_TOPOLOGY_LINELIST,
  4758. D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ,
  4759. D3D_PRIMITIVE_TOPOLOGY_LINESTRIP,
  4760. D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ,
  4761. D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
  4762. D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ,
  4763. D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,
  4764. D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ,
  4765. D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,
  4766. D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST,
  4767. };
  4768. static const D3D12_CULL_MODE RD_POLYGON_CULL_TO_D3D12_CULL_MODE[RDD::POLYGON_CULL_MAX] = {
  4769. D3D12_CULL_MODE_NONE,
  4770. D3D12_CULL_MODE_FRONT,
  4771. D3D12_CULL_MODE_BACK,
  4772. };
  4773. static const D3D12_STENCIL_OP RD_TO_D3D12_STENCIL_OP[RDD::STENCIL_OP_MAX] = {
  4774. D3D12_STENCIL_OP_KEEP,
  4775. D3D12_STENCIL_OP_ZERO,
  4776. D3D12_STENCIL_OP_REPLACE,
  4777. D3D12_STENCIL_OP_INCR_SAT,
  4778. D3D12_STENCIL_OP_DECR_SAT,
  4779. D3D12_STENCIL_OP_INVERT,
  4780. D3D12_STENCIL_OP_INCR,
  4781. D3D12_STENCIL_OP_DECR,
  4782. };
  4783. static const D3D12_LOGIC_OP RD_TO_D3D12_LOGIC_OP[RDD::LOGIC_OP_MAX] = {
  4784. D3D12_LOGIC_OP_CLEAR,
  4785. D3D12_LOGIC_OP_AND,
  4786. D3D12_LOGIC_OP_AND_REVERSE,
  4787. D3D12_LOGIC_OP_COPY,
  4788. D3D12_LOGIC_OP_AND_INVERTED,
  4789. D3D12_LOGIC_OP_NOOP,
  4790. D3D12_LOGIC_OP_XOR,
  4791. D3D12_LOGIC_OP_OR,
  4792. D3D12_LOGIC_OP_NOR,
  4793. D3D12_LOGIC_OP_EQUIV,
  4794. D3D12_LOGIC_OP_INVERT,
  4795. D3D12_LOGIC_OP_OR_REVERSE,
  4796. D3D12_LOGIC_OP_COPY_INVERTED,
  4797. D3D12_LOGIC_OP_OR_INVERTED,
  4798. D3D12_LOGIC_OP_NAND,
  4799. D3D12_LOGIC_OP_SET,
  4800. };
  4801. static const D3D12_BLEND RD_TO_D3D12_BLEND_FACTOR[RDD::BLEND_FACTOR_MAX] = {
  4802. D3D12_BLEND_ZERO,
  4803. D3D12_BLEND_ONE,
  4804. D3D12_BLEND_SRC_COLOR,
  4805. D3D12_BLEND_INV_SRC_COLOR,
  4806. D3D12_BLEND_DEST_COLOR,
  4807. D3D12_BLEND_INV_DEST_COLOR,
  4808. D3D12_BLEND_SRC_ALPHA,
  4809. D3D12_BLEND_INV_SRC_ALPHA,
  4810. D3D12_BLEND_DEST_ALPHA,
  4811. D3D12_BLEND_INV_DEST_ALPHA,
  4812. D3D12_BLEND_BLEND_FACTOR,
  4813. D3D12_BLEND_INV_BLEND_FACTOR,
  4814. D3D12_BLEND_BLEND_FACTOR,
  4815. D3D12_BLEND_INV_BLEND_FACTOR,
  4816. D3D12_BLEND_SRC_ALPHA_SAT,
  4817. D3D12_BLEND_SRC1_COLOR,
  4818. D3D12_BLEND_INV_SRC1_COLOR,
  4819. D3D12_BLEND_SRC1_ALPHA,
  4820. D3D12_BLEND_INV_SRC1_ALPHA,
  4821. };
  4822. static const D3D12_BLEND_OP RD_TO_D3D12_BLEND_OP[RDD::BLEND_OP_MAX] = {
  4823. D3D12_BLEND_OP_ADD,
  4824. D3D12_BLEND_OP_SUBTRACT,
  4825. D3D12_BLEND_OP_REV_SUBTRACT,
  4826. D3D12_BLEND_OP_MIN,
  4827. D3D12_BLEND_OP_MAX,
  4828. };
  4829. RDD::PipelineID RenderingDeviceDriverD3D12::render_pipeline_create(
  4830. ShaderID p_shader,
  4831. VertexFormatID p_vertex_format,
  4832. RenderPrimitive p_render_primitive,
  4833. PipelineRasterizationState p_rasterization_state,
  4834. PipelineMultisampleState p_multisample_state,
  4835. PipelineDepthStencilState p_depth_stencil_state,
  4836. PipelineColorBlendState p_blend_state,
  4837. VectorView<int32_t> p_color_attachments,
  4838. BitField<PipelineDynamicStateFlags> p_dynamic_state,
  4839. RenderPassID p_render_pass,
  4840. uint32_t p_render_subpass,
  4841. VectorView<PipelineSpecializationConstant> p_specialization_constants) {
  4842. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_shader.id;
  4843. CD3DX12_PIPELINE_STATE_STREAM pipeline_desc = {};
  4844. const RenderPassInfo *pass_info = (const RenderPassInfo *)p_render_pass.id;
  4845. RenderPipelineInfo render_info;
  4846. // Attachments.
  4847. LocalVector<uint32_t> color_attachments;
  4848. {
  4849. const Subpass &subpass = pass_info->subpasses[p_render_subpass];
  4850. for (uint32_t i = 0; i < ARRAY_SIZE((&pipeline_desc.RTVFormats)->RTFormats); i++) {
  4851. (&pipeline_desc.RTVFormats)->RTFormats[i] = DXGI_FORMAT_UNKNOWN;
  4852. }
  4853. for (uint32_t i = 0; i < subpass.color_references.size(); i++) {
  4854. const AttachmentReference &ref = subpass.color_references[i];
  4855. if (ref.attachment != AttachmentReference::UNUSED) {
  4856. const Attachment &attachment = pass_info->attachments[ref.attachment];
  4857. DEV_ASSERT((&pipeline_desc.RTVFormats)->RTFormats[i] == DXGI_FORMAT_UNKNOWN);
  4858. (&pipeline_desc.RTVFormats)->RTFormats[i] = RD_TO_D3D12_FORMAT[attachment.format].general_format;
  4859. }
  4860. }
  4861. (&pipeline_desc.RTVFormats)->NumRenderTargets = p_color_attachments.size();
  4862. if (subpass.depth_stencil_reference.attachment != AttachmentReference::UNUSED) {
  4863. const Attachment &attachment = pass_info->attachments[subpass.depth_stencil_reference.attachment];
  4864. pipeline_desc.DSVFormat = RD_TO_D3D12_FORMAT[attachment.format].dsv_format;
  4865. } else {
  4866. pipeline_desc.DSVFormat = DXGI_FORMAT_UNKNOWN;
  4867. }
  4868. }
  4869. // Vertex.
  4870. if (p_vertex_format) {
  4871. const VertexFormatInfo *vf_info = (const VertexFormatInfo *)p_vertex_format.id;
  4872. (&pipeline_desc.InputLayout)->pInputElementDescs = vf_info->input_elem_descs.ptr();
  4873. (&pipeline_desc.InputLayout)->NumElements = vf_info->input_elem_descs.size();
  4874. render_info.vf_info = vf_info;
  4875. }
  4876. // Input assembly & tessellation.
  4877. pipeline_desc.PrimitiveTopologyType = RD_PRIMITIVE_TO_D3D12_TOPOLOGY_TYPE[p_render_primitive];
  4878. if (p_render_primitive == RENDER_PRIMITIVE_TESSELATION_PATCH) {
  4879. // Is there any way to get the true point count limit?
  4880. ERR_FAIL_COND_V(p_rasterization_state.patch_control_points < 1 || p_rasterization_state.patch_control_points > 32, PipelineID());
  4881. render_info.dyn_params.primitive_topology = (D3D12_PRIMITIVE_TOPOLOGY)((int)D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST + p_rasterization_state.patch_control_points);
  4882. } else {
  4883. render_info.dyn_params.primitive_topology = RD_PRIMITIVE_TO_D3D12_TOPOLOGY[p_render_primitive];
  4884. }
  4885. if (p_render_primitive == RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX) {
  4886. // TODO: This is right for 16-bit indices; for 32-bit there's a different enum value to set, but we don't know at this point.
  4887. pipeline_desc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF;
  4888. } else {
  4889. pipeline_desc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED;
  4890. }
  4891. // Rasterization.
  4892. (&pipeline_desc.RasterizerState)->DepthClipEnable = !p_rasterization_state.enable_depth_clamp;
  4893. // In D3D12, discard can be supported with some extra effort (empty pixel shader + disable depth/stencil test); that said, unsupported by now.
  4894. ERR_FAIL_COND_V(p_rasterization_state.discard_primitives, PipelineID());
  4895. (&pipeline_desc.RasterizerState)->FillMode = p_rasterization_state.wireframe ? D3D12_FILL_MODE_WIREFRAME : D3D12_FILL_MODE_SOLID;
  4896. (&pipeline_desc.RasterizerState)->CullMode = RD_POLYGON_CULL_TO_D3D12_CULL_MODE[p_rasterization_state.cull_mode];
  4897. (&pipeline_desc.RasterizerState)->FrontCounterClockwise = p_rasterization_state.front_face == POLYGON_FRONT_FACE_COUNTER_CLOCKWISE;
  4898. // In D3D12, there's still a point in setting up depth bias with no depth buffer, but just zeroing (disabling) it all in such case is closer to Vulkan.
  4899. if (p_rasterization_state.depth_bias_enabled && pipeline_desc.DSVFormat != DXGI_FORMAT_UNKNOWN) {
  4900. (&pipeline_desc.RasterizerState)->DepthBias = p_rasterization_state.depth_bias_constant_factor;
  4901. (&pipeline_desc.RasterizerState)->DepthBiasClamp = p_rasterization_state.depth_bias_clamp;
  4902. (&pipeline_desc.RasterizerState)->SlopeScaledDepthBias = p_rasterization_state.depth_bias_slope_factor;
  4903. (&pipeline_desc.RasterizerState)->DepthBias = 0;
  4904. (&pipeline_desc.RasterizerState)->DepthBiasClamp = 0.0f;
  4905. (&pipeline_desc.RasterizerState)->SlopeScaledDepthBias = 0.0f;
  4906. }
  4907. (&pipeline_desc.RasterizerState)->ForcedSampleCount = 0;
  4908. (&pipeline_desc.RasterizerState)->ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
  4909. (&pipeline_desc.RasterizerState)->MultisampleEnable = TEXTURE_SAMPLES_COUNT[p_multisample_state.sample_count] != 1;
  4910. (&pipeline_desc.RasterizerState)->AntialiasedLineEnable = true;
  4911. // In D3D12, there's no line width.
  4912. ERR_FAIL_COND_V(!Math::is_equal_approx(p_rasterization_state.line_width, 1.0f), PipelineID());
  4913. // Multisample.
  4914. ERR_FAIL_COND_V(p_multisample_state.enable_sample_shading, PipelineID()); // How one enables this in D3D12?
  4915. if ((&pipeline_desc.RTVFormats)->NumRenderTargets || pipeline_desc.DSVFormat != DXGI_FORMAT_UNKNOWN) {
  4916. uint32_t sample_count = MIN(
  4917. pass_info->max_supported_sample_count,
  4918. TEXTURE_SAMPLES_COUNT[p_multisample_state.sample_count]);
  4919. (&pipeline_desc.SampleDesc)->Count = sample_count;
  4920. } else {
  4921. (&pipeline_desc.SampleDesc)->Count = 1;
  4922. }
  4923. if ((&pipeline_desc.SampleDesc)->Count > 1) {
  4924. (&pipeline_desc.SampleDesc)->Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN;
  4925. } else {
  4926. (&pipeline_desc.SampleDesc)->Quality = 0;
  4927. }
  4928. if (p_multisample_state.sample_mask.size()) {
  4929. for (int i = 1; i < p_multisample_state.sample_mask.size(); i++) {
  4930. // In D3D12 there's a single sample mask for every pixel.
  4931. ERR_FAIL_COND_V(p_multisample_state.sample_mask[i] != p_multisample_state.sample_mask[0], PipelineID());
  4932. }
  4933. pipeline_desc.SampleMask = p_multisample_state.sample_mask[0];
  4934. } else {
  4935. pipeline_desc.SampleMask = 0xffffffff;
  4936. }
  4937. // Depth stencil.
  4938. if (pipeline_desc.DSVFormat == DXGI_FORMAT_UNKNOWN) {
  4939. (&pipeline_desc.DepthStencilState)->DepthEnable = false;
  4940. (&pipeline_desc.DepthStencilState)->StencilEnable = false;
  4941. } else {
  4942. (&pipeline_desc.DepthStencilState)->DepthEnable = p_depth_stencil_state.enable_depth_test;
  4943. (&pipeline_desc.DepthStencilState)->DepthWriteMask = p_depth_stencil_state.enable_depth_write ? D3D12_DEPTH_WRITE_MASK_ALL : D3D12_DEPTH_WRITE_MASK_ZERO;
  4944. (&pipeline_desc.DepthStencilState)->DepthFunc = RD_TO_D3D12_COMPARE_OP[p_depth_stencil_state.depth_compare_operator];
  4945. (&pipeline_desc.DepthStencilState)->DepthBoundsTestEnable = p_depth_stencil_state.enable_depth_range;
  4946. (&pipeline_desc.DepthStencilState)->StencilEnable = p_depth_stencil_state.enable_stencil;
  4947. // In D3D12 some elements can't be different across front and back.
  4948. ERR_FAIL_COND_V(p_depth_stencil_state.front_op.compare_mask != p_depth_stencil_state.back_op.compare_mask, PipelineID());
  4949. ERR_FAIL_COND_V(p_depth_stencil_state.front_op.write_mask != p_depth_stencil_state.back_op.write_mask, PipelineID());
  4950. ERR_FAIL_COND_V(p_depth_stencil_state.front_op.reference != p_depth_stencil_state.back_op.reference, PipelineID());
  4951. (&pipeline_desc.DepthStencilState)->StencilReadMask = p_depth_stencil_state.front_op.compare_mask;
  4952. (&pipeline_desc.DepthStencilState)->StencilWriteMask = p_depth_stencil_state.front_op.write_mask;
  4953. (&pipeline_desc.DepthStencilState)->FrontFace.StencilFailOp = RD_TO_D3D12_STENCIL_OP[p_depth_stencil_state.front_op.fail];
  4954. (&pipeline_desc.DepthStencilState)->FrontFace.StencilPassOp = RD_TO_D3D12_STENCIL_OP[p_depth_stencil_state.front_op.pass];
  4955. (&pipeline_desc.DepthStencilState)->FrontFace.StencilDepthFailOp = RD_TO_D3D12_STENCIL_OP[p_depth_stencil_state.front_op.depth_fail];
  4956. (&pipeline_desc.DepthStencilState)->FrontFace.StencilFunc = RD_TO_D3D12_COMPARE_OP[p_depth_stencil_state.front_op.compare];
  4957. (&pipeline_desc.DepthStencilState)->BackFace.StencilFailOp = RD_TO_D3D12_STENCIL_OP[p_depth_stencil_state.back_op.fail];
  4958. (&pipeline_desc.DepthStencilState)->BackFace.StencilPassOp = RD_TO_D3D12_STENCIL_OP[p_depth_stencil_state.back_op.pass];
  4959. (&pipeline_desc.DepthStencilState)->BackFace.StencilDepthFailOp = RD_TO_D3D12_STENCIL_OP[p_depth_stencil_state.back_op.depth_fail];
  4960. (&pipeline_desc.DepthStencilState)->BackFace.StencilFunc = RD_TO_D3D12_COMPARE_OP[p_depth_stencil_state.back_op.compare];
  4961. if (misc_features_support.depth_bounds_supported) {
  4962. render_info.dyn_params.depth_bounds_min = p_depth_stencil_state.enable_depth_range ? p_depth_stencil_state.depth_range_min : 0.0f;
  4963. render_info.dyn_params.depth_bounds_max = p_depth_stencil_state.enable_depth_range ? p_depth_stencil_state.depth_range_max : 1.0f;
  4964. } else {
  4965. if (p_depth_stencil_state.enable_depth_range) {
  4966. WARN_PRINT_ONCE("Depth bounds test is not supported by the GPU driver.");
  4967. }
  4968. }
  4969. render_info.dyn_params.stencil_reference = p_depth_stencil_state.front_op.reference;
  4970. }
  4971. // Blend states.
  4972. (&pipeline_desc.BlendState)->AlphaToCoverageEnable = p_multisample_state.enable_alpha_to_coverage;
  4973. {
  4974. bool all_attachments_same_blend = true;
  4975. for (int i = 0; i < p_blend_state.attachments.size(); i++) {
  4976. const PipelineColorBlendState::Attachment &bs = p_blend_state.attachments[i];
  4977. D3D12_RENDER_TARGET_BLEND_DESC &bd = (&pipeline_desc.BlendState)->RenderTarget[i];
  4978. bd.BlendEnable = bs.enable_blend;
  4979. bd.LogicOpEnable = p_blend_state.enable_logic_op;
  4980. bd.LogicOp = RD_TO_D3D12_LOGIC_OP[p_blend_state.logic_op];
  4981. bd.SrcBlend = RD_TO_D3D12_BLEND_FACTOR[bs.src_color_blend_factor];
  4982. bd.DestBlend = RD_TO_D3D12_BLEND_FACTOR[bs.dst_color_blend_factor];
  4983. bd.BlendOp = RD_TO_D3D12_BLEND_OP[bs.color_blend_op];
  4984. bd.SrcBlendAlpha = RD_TO_D3D12_BLEND_FACTOR[bs.src_alpha_blend_factor];
  4985. bd.DestBlendAlpha = RD_TO_D3D12_BLEND_FACTOR[bs.dst_alpha_blend_factor];
  4986. bd.BlendOpAlpha = RD_TO_D3D12_BLEND_OP[bs.alpha_blend_op];
  4987. if (bs.write_r) {
  4988. bd.RenderTargetWriteMask |= D3D12_COLOR_WRITE_ENABLE_RED;
  4989. }
  4990. if (bs.write_g) {
  4991. bd.RenderTargetWriteMask |= D3D12_COLOR_WRITE_ENABLE_GREEN;
  4992. }
  4993. if (bs.write_b) {
  4994. bd.RenderTargetWriteMask |= D3D12_COLOR_WRITE_ENABLE_BLUE;
  4995. }
  4996. if (bs.write_a) {
  4997. bd.RenderTargetWriteMask |= D3D12_COLOR_WRITE_ENABLE_ALPHA;
  4998. }
  4999. if (i > 0 && all_attachments_same_blend) {
  5000. all_attachments_same_blend = &(&pipeline_desc.BlendState)->RenderTarget[i] == &(&pipeline_desc.BlendState)->RenderTarget[0];
  5001. }
  5002. }
  5003. // Per D3D12 docs, if logic op used, independent blending is not supported.
  5004. ERR_FAIL_COND_V(p_blend_state.enable_logic_op && !all_attachments_same_blend, PipelineID());
  5005. (&pipeline_desc.BlendState)->IndependentBlendEnable = !all_attachments_same_blend;
  5006. }
  5007. render_info.dyn_params.blend_constant = p_blend_state.blend_constant;
  5008. // Stages bytecodes + specialization constants.
  5009. pipeline_desc.pRootSignature = shader_info_in->root_signature.Get();
  5010. HashMap<ShaderStage, Vector<uint8_t>> final_stages_bytecode;
  5011. bool ok = _shader_apply_specialization_constants(shader_info_in, p_specialization_constants, final_stages_bytecode);
  5012. ERR_FAIL_COND_V(!ok, PipelineID());
  5013. pipeline_desc.VS = D3D12_SHADER_BYTECODE{
  5014. final_stages_bytecode[SHADER_STAGE_VERTEX].ptr(),
  5015. (SIZE_T)final_stages_bytecode[SHADER_STAGE_VERTEX].size()
  5016. };
  5017. pipeline_desc.PS = D3D12_SHADER_BYTECODE{
  5018. final_stages_bytecode[SHADER_STAGE_FRAGMENT].ptr(),
  5019. (SIZE_T)final_stages_bytecode[SHADER_STAGE_FRAGMENT].size()
  5020. };
  5021. ComPtr<ID3D12Device2> device_2;
  5022. device->QueryInterface(device_2.GetAddressOf());
  5023. ID3D12PipelineState *pso = nullptr;
  5024. HRESULT res = E_FAIL;
  5025. if (device_2) {
  5026. D3D12_PIPELINE_STATE_STREAM_DESC pssd = {};
  5027. pssd.pPipelineStateSubobjectStream = &pipeline_desc;
  5028. pssd.SizeInBytes = sizeof(pipeline_desc);
  5029. res = device_2->CreatePipelineState(&pssd, IID_PPV_ARGS(&pso));
  5030. } else {
  5031. D3D12_GRAPHICS_PIPELINE_STATE_DESC desc = pipeline_desc.GraphicsDescV0();
  5032. res = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso));
  5033. }
  5034. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), PipelineID(), "Create(Graphics)PipelineState failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5035. PipelineInfo *pipeline_info = memnew(PipelineInfo);
  5036. pipeline_info->pso = pso;
  5037. pipeline_info->shader_info = shader_info_in;
  5038. pipeline_info->render_info = render_info;
  5039. return PipelineID(pipeline_info);
  5040. }
  5041. /*****************/
  5042. /**** COMPUTE ****/
  5043. /*****************/
  5044. // ----- COMMANDS -----
  5045. void RenderingDeviceDriverD3D12::command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) {
  5046. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  5047. const PipelineInfo *pipeline_info = (const PipelineInfo *)p_pipeline.id;
  5048. if (cmd_buf_info->compute_pso == pipeline_info->pso) {
  5049. return;
  5050. }
  5051. const ShaderInfo *shader_info_in = pipeline_info->shader_info;
  5052. cmd_buf_info->cmd_list->SetPipelineState(pipeline_info->pso);
  5053. if (cmd_buf_info->compute_root_signature_crc != shader_info_in->root_signature_crc) {
  5054. cmd_buf_info->cmd_list->SetComputeRootSignature(shader_info_in->root_signature.Get());
  5055. cmd_buf_info->compute_root_signature_crc = shader_info_in->root_signature_crc;
  5056. }
  5057. cmd_buf_info->compute_pso = pipeline_info->pso;
  5058. cmd_buf_info->graphics_pso = nullptr;
  5059. }
  5060. void RenderingDeviceDriverD3D12::command_bind_compute_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) {
  5061. _command_bind_uniform_set(p_cmd_buffer, p_uniform_set, p_shader, p_set_index, true);
  5062. }
  5063. void RenderingDeviceDriverD3D12::command_compute_dispatch(CommandBufferID p_cmd_buffer, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) {
  5064. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  5065. if (!barrier_capabilities.enhanced_barriers_supported) {
  5066. _resource_transitions_flush(cmd_buf_info);
  5067. }
  5068. cmd_buf_info->cmd_list->Dispatch(p_x_groups, p_y_groups, p_z_groups);
  5069. }
  5070. void RenderingDeviceDriverD3D12::command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) {
  5071. CommandBufferInfo *cmd_buf_info = (CommandBufferInfo *)p_cmd_buffer.id;
  5072. BufferInfo *indirect_buf_info = (BufferInfo *)p_indirect_buffer.id;
  5073. if (!barrier_capabilities.enhanced_barriers_supported) {
  5074. _resource_transition_batch(cmd_buf_info, indirect_buf_info, 0, 1, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  5075. _resource_transitions_flush(cmd_buf_info);
  5076. }
  5077. cmd_buf_info->cmd_list->ExecuteIndirect(indirect_cmd_signatures.dispatch.Get(), 1, indirect_buf_info->resource, p_offset, nullptr, 0);
  5078. }
  5079. // ----- PIPELINE -----
  5080. RDD::PipelineID RenderingDeviceDriverD3D12::compute_pipeline_create(ShaderID p_shader, VectorView<PipelineSpecializationConstant> p_specialization_constants) {
  5081. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_shader.id;
  5082. CD3DX12_PIPELINE_STATE_STREAM pipeline_desc = {};
  5083. // Stages bytecodes + specialization constants.
  5084. pipeline_desc.pRootSignature = shader_info_in->root_signature.Get();
  5085. HashMap<ShaderStage, Vector<uint8_t>> final_stages_bytecode;
  5086. bool ok = _shader_apply_specialization_constants(shader_info_in, p_specialization_constants, final_stages_bytecode);
  5087. ERR_FAIL_COND_V(!ok, PipelineID());
  5088. pipeline_desc.CS = D3D12_SHADER_BYTECODE{
  5089. final_stages_bytecode[SHADER_STAGE_COMPUTE].ptr(),
  5090. (SIZE_T)final_stages_bytecode[SHADER_STAGE_COMPUTE].size()
  5091. };
  5092. ComPtr<ID3D12Device2> device_2;
  5093. device->QueryInterface(device_2.GetAddressOf());
  5094. ID3D12PipelineState *pso = nullptr;
  5095. HRESULT res = E_FAIL;
  5096. if (device_2) {
  5097. D3D12_PIPELINE_STATE_STREAM_DESC pssd = {};
  5098. pssd.pPipelineStateSubobjectStream = &pipeline_desc;
  5099. pssd.SizeInBytes = sizeof(pipeline_desc);
  5100. res = device_2->CreatePipelineState(&pssd, IID_PPV_ARGS(&pso));
  5101. } else {
  5102. D3D12_COMPUTE_PIPELINE_STATE_DESC desc = pipeline_desc.ComputeDescV0();
  5103. res = device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso));
  5104. }
  5105. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), PipelineID(), "Create(Compute)PipelineState failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5106. PipelineInfo *pipeline_info = memnew(PipelineInfo);
  5107. pipeline_info->pso = pso;
  5108. pipeline_info->shader_info = shader_info_in;
  5109. return PipelineID(pipeline_info);
  5110. }
  5111. /*****************/
  5112. /**** QUERIES ****/
  5113. /*****************/
  5114. // ----- TIMESTAMP -----
  5115. RDD::QueryPoolID RenderingDeviceDriverD3D12::timestamp_query_pool_create(uint32_t p_query_count) {
  5116. ComPtr<ID3D12QueryHeap> query_heap;
  5117. {
  5118. D3D12_QUERY_HEAP_DESC qh_desc = {};
  5119. qh_desc.Type = D3D12_QUERY_HEAP_TYPE_TIMESTAMP;
  5120. qh_desc.Count = p_query_count;
  5121. qh_desc.NodeMask = 0;
  5122. HRESULT res = device->CreateQueryHeap(&qh_desc, IID_PPV_ARGS(query_heap.GetAddressOf()));
  5123. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), QueryPoolID(), "CreateQueryHeap failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5124. }
  5125. ComPtr<D3D12MA::Allocation> results_buffer_allocation;
  5126. {
  5127. D3D12MA::ALLOCATION_DESC allocation_desc = {};
  5128. allocation_desc.HeapType = D3D12_HEAP_TYPE_READBACK;
  5129. CD3DX12_RESOURCE_DESC resource_desc = CD3DX12_RESOURCE_DESC::Buffer(sizeof(uint64_t) * p_query_count);
  5130. ComPtr<ID3D12Resource> results_buffer;
  5131. HRESULT res = allocator->CreateResource(
  5132. &allocation_desc,
  5133. &resource_desc,
  5134. D3D12_RESOURCE_STATE_COPY_DEST,
  5135. nullptr,
  5136. results_buffer_allocation.GetAddressOf(),
  5137. IID_PPV_ARGS(results_buffer.GetAddressOf()));
  5138. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), QueryPoolID(), "D3D12MA::CreateResource failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5139. }
  5140. // Bookkeep.
  5141. TimestampQueryPoolInfo *tqp_info = VersatileResource::allocate<TimestampQueryPoolInfo>(resources_allocator);
  5142. tqp_info->query_heap = query_heap;
  5143. tqp_info->query_count = p_query_count;
  5144. tqp_info->results_buffer_allocation = results_buffer_allocation;
  5145. return RDD::QueryPoolID(tqp_info);
  5146. }
  5147. void RenderingDeviceDriverD3D12::timestamp_query_pool_free(QueryPoolID p_pool_id) {
  5148. TimestampQueryPoolInfo *tqp_info = (TimestampQueryPoolInfo *)p_pool_id.id;
  5149. VersatileResource::free(resources_allocator, tqp_info);
  5150. }
  5151. void RenderingDeviceDriverD3D12::timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) {
  5152. TimestampQueryPoolInfo *tqp_info = (TimestampQueryPoolInfo *)p_pool_id.id;
  5153. ID3D12Resource *results_buffer = tqp_info->results_buffer_allocation->GetResource();
  5154. void *results_buffer_data = nullptr;
  5155. results_buffer->Map(0, &VOID_RANGE, &results_buffer_data);
  5156. memcpy(r_results, results_buffer_data, sizeof(uint64_t) * p_query_count);
  5157. results_buffer->Unmap(0, &VOID_RANGE);
  5158. }
  5159. uint64_t RenderingDeviceDriverD3D12::timestamp_query_result_to_time(uint64_t p_result) {
  5160. return p_result / (double)device_limits.timestamp_frequency * 1000000000.0;
  5161. }
  5162. void RenderingDeviceDriverD3D12::command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) {
  5163. }
  5164. void RenderingDeviceDriverD3D12::command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) {
  5165. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  5166. TimestampQueryPoolInfo *tqp_info = (TimestampQueryPoolInfo *)p_pool_id.id;
  5167. ID3D12Resource *results_buffer = tqp_info->results_buffer_allocation->GetResource();
  5168. cmd_buf_info->cmd_list->EndQuery(tqp_info->query_heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, p_index);
  5169. cmd_buf_info->cmd_list->ResolveQueryData(tqp_info->query_heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, p_index, 1, results_buffer, p_index * sizeof(uint64_t));
  5170. }
  5171. void RenderingDeviceDriverD3D12::command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) {
  5172. #ifdef PIX_ENABLED
  5173. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  5174. PIXBeginEvent(cmd_buf_info->cmd_list.Get(), p_color.to_argb32(), p_label_name);
  5175. #endif
  5176. }
  5177. void RenderingDeviceDriverD3D12::command_end_label(CommandBufferID p_cmd_buffer) {
  5178. #ifdef PIX_ENABLED
  5179. const CommandBufferInfo *cmd_buf_info = (const CommandBufferInfo *)p_cmd_buffer.id;
  5180. PIXEndEvent(cmd_buf_info->cmd_list.Get());
  5181. #endif
  5182. }
  5183. void RenderingDeviceDriverD3D12::command_insert_breadcrumb(CommandBufferID p_cmd_buffer, uint32_t p_data) {
  5184. // TODO: Implement via DRED.
  5185. }
  5186. /********************/
  5187. /**** SUBMISSION ****/
  5188. /********************/
  5189. void RenderingDeviceDriverD3D12::begin_segment(uint32_t p_frame_index, uint32_t p_frames_drawn) {
  5190. frame_idx = p_frame_index;
  5191. frames_drawn = p_frames_drawn;
  5192. allocator->SetCurrentFrameIndex(p_frames_drawn);
  5193. frames[frame_idx].desc_heap_walkers.resources.rewind();
  5194. frames[frame_idx].desc_heap_walkers.samplers.rewind();
  5195. frames[frame_idx].desc_heap_walkers.aux.rewind();
  5196. frames[frame_idx].desc_heap_walkers.rtv.rewind();
  5197. frames[frame_idx].desc_heaps_exhausted_reported = {};
  5198. frames[frame_idx].null_rtv_handle = CD3DX12_CPU_DESCRIPTOR_HANDLE{};
  5199. frames[frame_idx].segment_serial = segment_serial;
  5200. segment_begun = true;
  5201. }
  5202. void RenderingDeviceDriverD3D12::end_segment() {
  5203. segment_serial++;
  5204. segment_begun = false;
  5205. }
  5206. /**************/
  5207. /**** MISC ****/
  5208. /**************/
  5209. void RenderingDeviceDriverD3D12::_set_object_name(ID3D12Object *p_object, String p_object_name) {
  5210. ERR_FAIL_NULL(p_object);
  5211. int name_len = p_object_name.size();
  5212. WCHAR *name_w = (WCHAR *)alloca(sizeof(WCHAR) * (name_len + 1));
  5213. MultiByteToWideChar(CP_UTF8, 0, p_object_name.utf8().get_data(), -1, name_w, name_len);
  5214. p_object->SetName(name_w);
  5215. }
  5216. void RenderingDeviceDriverD3D12::set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) {
  5217. switch (p_type) {
  5218. case OBJECT_TYPE_TEXTURE: {
  5219. const TextureInfo *tex_info = (const TextureInfo *)p_driver_id.id;
  5220. if (tex_info->owner_info.allocation) {
  5221. _set_object_name(tex_info->resource, p_name);
  5222. }
  5223. } break;
  5224. case OBJECT_TYPE_SAMPLER: {
  5225. } break;
  5226. case OBJECT_TYPE_BUFFER: {
  5227. const BufferInfo *buf_info = (const BufferInfo *)p_driver_id.id;
  5228. _set_object_name(buf_info->resource, p_name);
  5229. } break;
  5230. case OBJECT_TYPE_SHADER: {
  5231. const ShaderInfo *shader_info_in = (const ShaderInfo *)p_driver_id.id;
  5232. _set_object_name(shader_info_in->root_signature.Get(), p_name);
  5233. } break;
  5234. case OBJECT_TYPE_UNIFORM_SET: {
  5235. const UniformSetInfo *uniform_set_info = (const UniformSetInfo *)p_driver_id.id;
  5236. if (uniform_set_info->desc_heaps.resources.get_heap()) {
  5237. _set_object_name(uniform_set_info->desc_heaps.resources.get_heap(), p_name + " resources heap");
  5238. }
  5239. if (uniform_set_info->desc_heaps.samplers.get_heap()) {
  5240. _set_object_name(uniform_set_info->desc_heaps.samplers.get_heap(), p_name + " samplers heap");
  5241. }
  5242. } break;
  5243. case OBJECT_TYPE_PIPELINE: {
  5244. const PipelineInfo *pipeline_info = (const PipelineInfo *)p_driver_id.id;
  5245. _set_object_name(pipeline_info->pso, p_name);
  5246. } break;
  5247. default: {
  5248. DEV_ASSERT(false);
  5249. }
  5250. }
  5251. }
  5252. uint64_t RenderingDeviceDriverD3D12::get_resource_native_handle(DriverResource p_type, ID p_driver_id) {
  5253. switch (p_type) {
  5254. case DRIVER_RESOURCE_LOGICAL_DEVICE: {
  5255. return (uint64_t)device.Get();
  5256. }
  5257. case DRIVER_RESOURCE_PHYSICAL_DEVICE: {
  5258. return (uint64_t)adapter.Get();
  5259. }
  5260. case DRIVER_RESOURCE_TOPMOST_OBJECT: {
  5261. return 0;
  5262. }
  5263. case DRIVER_RESOURCE_COMMAND_QUEUE: {
  5264. return (uint64_t)p_driver_id.id;
  5265. }
  5266. case DRIVER_RESOURCE_QUEUE_FAMILY: {
  5267. return 0;
  5268. }
  5269. case DRIVER_RESOURCE_TEXTURE: {
  5270. const TextureInfo *tex_info = (const TextureInfo *)p_driver_id.id;
  5271. return (uint64_t)tex_info->main_texture;
  5272. } break;
  5273. case DRIVER_RESOURCE_TEXTURE_VIEW: {
  5274. const TextureInfo *tex_info = (const TextureInfo *)p_driver_id.id;
  5275. return (uint64_t)tex_info->resource;
  5276. }
  5277. case DRIVER_RESOURCE_TEXTURE_DATA_FORMAT: {
  5278. const TextureInfo *tex_info = (const TextureInfo *)p_driver_id.id;
  5279. return (uint64_t)tex_info->desc.Format;
  5280. }
  5281. case DRIVER_RESOURCE_SAMPLER:
  5282. case DRIVER_RESOURCE_UNIFORM_SET:
  5283. return 0;
  5284. case DRIVER_RESOURCE_BUFFER: {
  5285. const TextureInfo *tex_info = (const TextureInfo *)p_driver_id.id;
  5286. return (uint64_t)tex_info->resource;
  5287. } break;
  5288. case DRIVER_RESOURCE_COMPUTE_PIPELINE:
  5289. case DRIVER_RESOURCE_RENDER_PIPELINE: {
  5290. return p_driver_id.id;
  5291. }
  5292. default: {
  5293. return 0;
  5294. }
  5295. }
  5296. }
  5297. uint64_t RenderingDeviceDriverD3D12::get_total_memory_used() {
  5298. D3D12MA::TotalStatistics stats;
  5299. allocator->CalculateStatistics(&stats);
  5300. return stats.Total.Stats.BlockBytes;
  5301. }
  5302. uint64_t RenderingDeviceDriverD3D12::limit_get(Limit p_limit) {
  5303. uint64_t safe_unbounded = ((uint64_t)1 << 30);
  5304. switch (p_limit) {
  5305. case LIMIT_MAX_BOUND_UNIFORM_SETS:
  5306. return safe_unbounded;
  5307. case LIMIT_MAX_TEXTURES_PER_SHADER_STAGE:
  5308. return device_limits.max_srvs_per_shader_stage;
  5309. case LIMIT_MAX_UNIFORM_BUFFER_SIZE:
  5310. return 65536;
  5311. case LIMIT_MAX_VIEWPORT_DIMENSIONS_X:
  5312. case LIMIT_MAX_VIEWPORT_DIMENSIONS_Y:
  5313. return 16384; // Based on max. texture size. Maybe not correct.
  5314. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X:
  5315. return D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  5316. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y:
  5317. return D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  5318. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z:
  5319. return D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  5320. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X:
  5321. return D3D12_CS_THREAD_GROUP_MAX_X;
  5322. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y:
  5323. return D3D12_CS_THREAD_GROUP_MAX_Y;
  5324. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z:
  5325. return D3D12_CS_THREAD_GROUP_MAX_Z;
  5326. case LIMIT_SUBGROUP_SIZE:
  5327. // Note in min/max. Shader model 6.6 supports it (see https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_WaveSize.html),
  5328. // but at this time I don't know the implications on the transpilation to DXIL, etc.
  5329. case LIMIT_SUBGROUP_MIN_SIZE:
  5330. case LIMIT_SUBGROUP_MAX_SIZE:
  5331. return subgroup_capabilities.size;
  5332. case LIMIT_SUBGROUP_IN_SHADERS:
  5333. return subgroup_capabilities.supported_stages_flags_rd();
  5334. case LIMIT_SUBGROUP_OPERATIONS:
  5335. return subgroup_capabilities.supported_operations_flags_rd();
  5336. case LIMIT_VRS_TEXEL_WIDTH:
  5337. case LIMIT_VRS_TEXEL_HEIGHT:
  5338. return vrs_capabilities.ss_image_tile_size;
  5339. case LIMIT_VRS_MAX_FRAGMENT_WIDTH:
  5340. case LIMIT_VRS_MAX_FRAGMENT_HEIGHT:
  5341. return vrs_capabilities.ss_max_fragment_size;
  5342. default: {
  5343. #ifdef DEV_ENABLED
  5344. WARN_PRINT("Returning maximum value for unknown limit " + itos(p_limit) + ".");
  5345. #endif
  5346. return safe_unbounded;
  5347. }
  5348. }
  5349. }
  5350. uint64_t RenderingDeviceDriverD3D12::api_trait_get(ApiTrait p_trait) {
  5351. switch (p_trait) {
  5352. case API_TRAIT_HONORS_PIPELINE_BARRIERS:
  5353. return barrier_capabilities.enhanced_barriers_supported;
  5354. case API_TRAIT_SHADER_CHANGE_INVALIDATION:
  5355. return (uint64_t)SHADER_CHANGE_INVALIDATION_ALL_OR_NONE_ACCORDING_TO_LAYOUT_HASH;
  5356. case API_TRAIT_TEXTURE_TRANSFER_ALIGNMENT:
  5357. return D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT;
  5358. case API_TRAIT_TEXTURE_DATA_ROW_PITCH_STEP:
  5359. return D3D12_TEXTURE_DATA_PITCH_ALIGNMENT;
  5360. case API_TRAIT_SECONDARY_VIEWPORT_SCISSOR:
  5361. return false;
  5362. case API_TRAIT_CLEARS_WITH_COPY_ENGINE:
  5363. return false;
  5364. case API_TRAIT_USE_GENERAL_IN_COPY_QUEUES:
  5365. return true;
  5366. default:
  5367. return RenderingDeviceDriver::api_trait_get(p_trait);
  5368. }
  5369. }
  5370. bool RenderingDeviceDriverD3D12::has_feature(Features p_feature) {
  5371. switch (p_feature) {
  5372. case SUPPORTS_MULTIVIEW:
  5373. return multiview_capabilities.is_supported && multiview_capabilities.max_view_count > 1;
  5374. case SUPPORTS_FSR_HALF_FLOAT:
  5375. return shader_capabilities.native_16bit_ops && storage_buffer_capabilities.storage_buffer_16_bit_access_is_supported;
  5376. case SUPPORTS_ATTACHMENT_VRS:
  5377. return vrs_capabilities.ss_image_supported;
  5378. case SUPPORTS_FRAGMENT_SHADER_WITH_ONLY_SIDE_EFFECTS:
  5379. return true;
  5380. default:
  5381. return false;
  5382. }
  5383. }
  5384. const RDD::MultiviewCapabilities &RenderingDeviceDriverD3D12::get_multiview_capabilities() {
  5385. return multiview_capabilities;
  5386. }
  5387. String RenderingDeviceDriverD3D12::get_api_name() const {
  5388. return "D3D12";
  5389. }
  5390. String RenderingDeviceDriverD3D12::get_api_version() const {
  5391. return vformat("%d_%d", feature_level / 10, feature_level % 10);
  5392. }
  5393. String RenderingDeviceDriverD3D12::get_pipeline_cache_uuid() const {
  5394. return pipeline_cache_id;
  5395. }
  5396. const RDD::Capabilities &RenderingDeviceDriverD3D12::get_capabilities() const {
  5397. return device_capabilities;
  5398. }
  5399. bool RenderingDeviceDriverD3D12::is_composite_alpha_supported(CommandQueueID p_queue) const {
  5400. if (has_comp_alpha.has((uint64_t)p_queue.id)) {
  5401. return has_comp_alpha[(uint64_t)p_queue.id];
  5402. }
  5403. return false;
  5404. }
  5405. /******************/
  5406. RenderingDeviceDriverD3D12::RenderingDeviceDriverD3D12(RenderingContextDriverD3D12 *p_context_driver) {
  5407. DEV_ASSERT(p_context_driver != nullptr);
  5408. this->context_driver = p_context_driver;
  5409. }
  5410. RenderingDeviceDriverD3D12::~RenderingDeviceDriverD3D12() {
  5411. glsl_type_singleton_decref();
  5412. }
  5413. bool RenderingDeviceDriverD3D12::is_in_developer_mode() {
  5414. HKEY hkey = nullptr;
  5415. LSTATUS result = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\AppModelUnlock", 0, KEY_READ, &hkey);
  5416. if (result != ERROR_SUCCESS) {
  5417. return false;
  5418. }
  5419. DWORD value = 0;
  5420. DWORD dword_size = sizeof(DWORD);
  5421. result = RegQueryValueExW(hkey, L"AllowDevelopmentWithoutDevLicense", nullptr, nullptr, (PBYTE)&value, &dword_size);
  5422. RegCloseKey(hkey);
  5423. if (result != ERROR_SUCCESS) {
  5424. return false;
  5425. }
  5426. return (value != 0);
  5427. }
  5428. Error RenderingDeviceDriverD3D12::_initialize_device() {
  5429. HRESULT res;
  5430. if (is_in_developer_mode()) {
  5431. typedef HRESULT(WINAPI * PFN_D3D12_ENABLE_EXPERIMENTAL_FEATURES)(_In_ UINT, _In_count_(NumFeatures) const IID *, _In_opt_count_(NumFeatures) void *, _In_opt_count_(NumFeatures) UINT *);
  5432. PFN_D3D12_ENABLE_EXPERIMENTAL_FEATURES d3d_D3D12EnableExperimentalFeatures = (PFN_D3D12_ENABLE_EXPERIMENTAL_FEATURES)(void *)GetProcAddress(context_driver->lib_d3d12, "D3D12EnableExperimentalFeatures");
  5433. ERR_FAIL_NULL_V(d3d_D3D12EnableExperimentalFeatures, ERR_CANT_CREATE);
  5434. UUID experimental_features[] = { D3D12ExperimentalShaderModels };
  5435. d3d_D3D12EnableExperimentalFeatures(1, experimental_features, nullptr, nullptr);
  5436. }
  5437. ID3D12DeviceFactory *device_factory = context_driver->device_factory_get();
  5438. if (device_factory != nullptr) {
  5439. res = device_factory->CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(device.GetAddressOf()));
  5440. } else {
  5441. PFN_D3D12_CREATE_DEVICE d3d_D3D12CreateDevice = (PFN_D3D12_CREATE_DEVICE)(void *)GetProcAddress(context_driver->lib_d3d12, "D3D12CreateDevice");
  5442. ERR_FAIL_NULL_V(d3d_D3D12CreateDevice, ERR_CANT_CREATE);
  5443. res = d3d_D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(device.GetAddressOf()));
  5444. }
  5445. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ERR_CANT_CREATE, "D3D12CreateDevice failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5446. if (context_driver->use_validation_layers()) {
  5447. ComPtr<ID3D12InfoQueue> info_queue;
  5448. res = device.As(&info_queue);
  5449. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5450. #if CUSTOM_INFO_QUEUE_ENABLED
  5451. ComPtr<ID3D12InfoQueue1> info_queue_1;
  5452. device.As(&info_queue_1);
  5453. if (info_queue_1) {
  5454. // Custom printing supported (added in Windows 10 Release Preview build 20236). Even if the callback cookie is unused, it seems the
  5455. // argument is not optional and the function will fail if it's not specified.
  5456. DWORD callback_cookie;
  5457. info_queue_1->SetMuteDebugOutput(TRUE);
  5458. res = info_queue_1->RegisterMessageCallback(&_debug_message_func, D3D12_MESSAGE_CALLBACK_IGNORE_FILTERS, nullptr, &callback_cookie);
  5459. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5460. } else
  5461. #endif
  5462. {
  5463. // Rely on D3D12's own debug printing.
  5464. if (Engine::get_singleton()->is_abort_on_gpu_errors_enabled()) {
  5465. res = info_queue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, TRUE);
  5466. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5467. res = info_queue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, TRUE);
  5468. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5469. res = info_queue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, TRUE);
  5470. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5471. }
  5472. }
  5473. D3D12_MESSAGE_SEVERITY severities_to_mute[] = {
  5474. D3D12_MESSAGE_SEVERITY_INFO,
  5475. };
  5476. D3D12_MESSAGE_ID messages_to_mute[] = {
  5477. D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE,
  5478. D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_MISMATCHINGCLEARVALUE,
  5479. // These happen due to how D3D12MA manages buffers; seems benign.
  5480. D3D12_MESSAGE_ID_HEAP_ADDRESS_RANGE_HAS_NO_RESOURCE,
  5481. D3D12_MESSAGE_ID_HEAP_ADDRESS_RANGE_INTERSECTS_MULTIPLE_BUFFERS,
  5482. // Seemingly a false positive.
  5483. D3D12_MESSAGE_ID_DATA_STATIC_WHILE_SET_AT_EXECUTE_DESCRIPTOR_INVALID_DATA_CHANGE,
  5484. };
  5485. D3D12_INFO_QUEUE_FILTER filter = {};
  5486. filter.DenyList.NumSeverities = ARRAY_SIZE(severities_to_mute);
  5487. filter.DenyList.pSeverityList = severities_to_mute;
  5488. filter.DenyList.NumIDs = ARRAY_SIZE(messages_to_mute);
  5489. filter.DenyList.pIDList = messages_to_mute;
  5490. res = info_queue->PushStorageFilter(&filter);
  5491. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5492. }
  5493. return OK;
  5494. }
  5495. Error RenderingDeviceDriverD3D12::_check_capabilities() {
  5496. // Check feature levels.
  5497. const D3D_FEATURE_LEVEL FEATURE_LEVELS[] = {
  5498. D3D_FEATURE_LEVEL_11_0,
  5499. D3D_FEATURE_LEVEL_11_1,
  5500. D3D_FEATURE_LEVEL_12_0,
  5501. D3D_FEATURE_LEVEL_12_1,
  5502. D3D_FEATURE_LEVEL_12_2,
  5503. };
  5504. D3D12_FEATURE_DATA_FEATURE_LEVELS feat_levels = {};
  5505. feat_levels.NumFeatureLevels = ARRAY_SIZE(FEATURE_LEVELS);
  5506. feat_levels.pFeatureLevelsRequested = FEATURE_LEVELS;
  5507. HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_FEATURE_LEVELS, &feat_levels, sizeof(feat_levels));
  5508. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ERR_UNAVAILABLE, "CheckFeatureSupport failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5509. // Example: D3D_FEATURE_LEVEL_12_1 = 0xc100.
  5510. uint32_t feat_level_major = feat_levels.MaxSupportedFeatureLevel >> 12;
  5511. uint32_t feat_level_minor = (feat_levels.MaxSupportedFeatureLevel >> 16) & 0xff;
  5512. feature_level = feat_level_major * 10 + feat_level_minor;
  5513. // Fill device capabilities.
  5514. device_capabilities.device_family = DEVICE_DIRECTX;
  5515. device_capabilities.version_major = feature_level / 10;
  5516. device_capabilities.version_minor = feature_level % 10;
  5517. // Assume not supported until proven otherwise.
  5518. vrs_capabilities.draw_call_supported = false;
  5519. vrs_capabilities.primitive_supported = false;
  5520. vrs_capabilities.primitive_in_multiviewport = false;
  5521. vrs_capabilities.ss_image_supported = false;
  5522. vrs_capabilities.ss_image_tile_size = 1;
  5523. vrs_capabilities.additional_rates_supported = false;
  5524. multiview_capabilities.is_supported = false;
  5525. multiview_capabilities.geometry_shader_is_supported = false;
  5526. multiview_capabilities.tessellation_shader_is_supported = false;
  5527. multiview_capabilities.max_view_count = 0;
  5528. multiview_capabilities.max_instance_count = 0;
  5529. multiview_capabilities.is_supported = false;
  5530. subgroup_capabilities.size = 0;
  5531. subgroup_capabilities.wave_ops_supported = false;
  5532. shader_capabilities.shader_model = (D3D_SHADER_MODEL)0;
  5533. shader_capabilities.native_16bit_ops = false;
  5534. storage_buffer_capabilities.storage_buffer_16_bit_access_is_supported = false;
  5535. format_capabilities.relaxed_casting_supported = false;
  5536. {
  5537. static const D3D_SHADER_MODEL SMS_TO_CHECK[] = {
  5538. D3D_SHADER_MODEL_6_6,
  5539. D3D_SHADER_MODEL_6_5,
  5540. D3D_SHADER_MODEL_6_4,
  5541. D3D_SHADER_MODEL_6_3,
  5542. D3D_SHADER_MODEL_6_2,
  5543. D3D_SHADER_MODEL_6_1,
  5544. D3D_SHADER_MODEL_6_0, // Determined by NIR (dxil_min_shader_model).
  5545. };
  5546. D3D12_FEATURE_DATA_SHADER_MODEL shader_model = {};
  5547. for (uint32_t i = 0; i < ARRAY_SIZE(SMS_TO_CHECK); i++) {
  5548. shader_model.HighestShaderModel = SMS_TO_CHECK[i];
  5549. res = device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &shader_model, sizeof(shader_model));
  5550. if (SUCCEEDED(res)) {
  5551. shader_capabilities.shader_model = shader_model.HighestShaderModel;
  5552. break;
  5553. }
  5554. if (res == E_INVALIDARG) {
  5555. continue; // Must assume the device doesn't know about the SM just checked.
  5556. }
  5557. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ERR_CANT_CREATE, "CheckFeatureSupport failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5558. }
  5559. #define D3D_SHADER_MODEL_TO_STRING(m_sm) vformat("%d.%d", (m_sm >> 4), (m_sm & 0xf))
  5560. ERR_FAIL_COND_V_MSG(!shader_capabilities.shader_model, ERR_UNAVAILABLE,
  5561. vformat("No support for any of the suitable shader models (%s-%s) has been found.", D3D_SHADER_MODEL_TO_STRING(SMS_TO_CHECK[ARRAY_SIZE(SMS_TO_CHECK) - 1]), D3D_SHADER_MODEL_TO_STRING(SMS_TO_CHECK[0])));
  5562. print_verbose("- Shader:");
  5563. print_verbose(" model: " + D3D_SHADER_MODEL_TO_STRING(shader_capabilities.shader_model));
  5564. }
  5565. D3D12_FEATURE_DATA_D3D12_OPTIONS options = {};
  5566. res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options));
  5567. if (SUCCEEDED(res)) {
  5568. storage_buffer_capabilities.storage_buffer_16_bit_access_is_supported = options.TypedUAVLoadAdditionalFormats;
  5569. }
  5570. D3D12_FEATURE_DATA_D3D12_OPTIONS1 options1 = {};
  5571. res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &options1, sizeof(options1));
  5572. if (SUCCEEDED(res)) {
  5573. subgroup_capabilities.size = options1.WaveLaneCountMin;
  5574. subgroup_capabilities.wave_ops_supported = options1.WaveOps;
  5575. }
  5576. D3D12_FEATURE_DATA_D3D12_OPTIONS2 options2 = {};
  5577. res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS2, &options2, sizeof(options2));
  5578. if (SUCCEEDED(res)) {
  5579. misc_features_support.depth_bounds_supported = options2.DepthBoundsTestSupported;
  5580. }
  5581. D3D12_FEATURE_DATA_D3D12_OPTIONS3 options3 = {};
  5582. res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS3, &options3, sizeof(options3));
  5583. if (SUCCEEDED(res)) {
  5584. // https://docs.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_view_instancing_tier
  5585. // https://microsoft.github.io/DirectX-Specs/d3d/ViewInstancing.html#sv_viewid
  5586. if (options3.ViewInstancingTier >= D3D12_VIEW_INSTANCING_TIER_1) {
  5587. multiview_capabilities.is_supported = true;
  5588. multiview_capabilities.geometry_shader_is_supported = options3.ViewInstancingTier >= D3D12_VIEW_INSTANCING_TIER_3;
  5589. multiview_capabilities.tessellation_shader_is_supported = options3.ViewInstancingTier >= D3D12_VIEW_INSTANCING_TIER_3;
  5590. multiview_capabilities.max_view_count = D3D12_MAX_VIEW_INSTANCE_COUNT;
  5591. multiview_capabilities.max_instance_count = UINT32_MAX;
  5592. }
  5593. }
  5594. D3D12_FEATURE_DATA_D3D12_OPTIONS4 options4 = {};
  5595. res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS4, &options4, sizeof(options4));
  5596. if (SUCCEEDED(res)) {
  5597. shader_capabilities.native_16bit_ops = options4.Native16BitShaderOpsSupported;
  5598. }
  5599. D3D12_FEATURE_DATA_D3D12_OPTIONS6 options6 = {};
  5600. res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS6, &options6, sizeof(options6));
  5601. if (SUCCEEDED(res)) {
  5602. if (options6.VariableShadingRateTier >= D3D12_VARIABLE_SHADING_RATE_TIER_1) {
  5603. vrs_capabilities.draw_call_supported = true;
  5604. if (options6.VariableShadingRateTier >= D3D12_VARIABLE_SHADING_RATE_TIER_2) {
  5605. vrs_capabilities.primitive_supported = true;
  5606. vrs_capabilities.primitive_in_multiviewport = options6.PerPrimitiveShadingRateSupportedWithViewportIndexing;
  5607. vrs_capabilities.ss_image_supported = true;
  5608. vrs_capabilities.ss_image_tile_size = options6.ShadingRateImageTileSize;
  5609. vrs_capabilities.ss_max_fragment_size = 8; // TODO figure out if this is supplied and/or needed
  5610. vrs_capabilities.additional_rates_supported = options6.AdditionalShadingRatesSupported;
  5611. }
  5612. }
  5613. }
  5614. D3D12_FEATURE_DATA_D3D12_OPTIONS12 options12 = {};
  5615. res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, &options12, sizeof(options12));
  5616. if (SUCCEEDED(res)) {
  5617. format_capabilities.relaxed_casting_supported = options12.RelaxedFormatCastingSupported;
  5618. barrier_capabilities.enhanced_barriers_supported = options12.EnhancedBarriersSupported;
  5619. }
  5620. if (vrs_capabilities.draw_call_supported || vrs_capabilities.primitive_supported || vrs_capabilities.ss_image_supported) {
  5621. print_verbose("- D3D12 Variable Rate Shading supported:");
  5622. if (vrs_capabilities.draw_call_supported) {
  5623. print_verbose(" Draw call");
  5624. }
  5625. if (vrs_capabilities.primitive_supported) {
  5626. print_verbose(String(" Per-primitive (multi-viewport: ") + (vrs_capabilities.primitive_in_multiviewport ? "yes" : "no") + ")");
  5627. }
  5628. if (vrs_capabilities.ss_image_supported) {
  5629. print_verbose(String(" Screen-space image (tile size: ") + itos(vrs_capabilities.ss_image_tile_size) + ")");
  5630. }
  5631. if (vrs_capabilities.additional_rates_supported) {
  5632. print_verbose(String(" Additional rates: ") + (vrs_capabilities.additional_rates_supported ? "yes" : "no"));
  5633. }
  5634. } else {
  5635. print_verbose("- D3D12 Variable Rate Shading not supported");
  5636. }
  5637. if (multiview_capabilities.is_supported) {
  5638. print_verbose("- D3D12 multiview supported:");
  5639. print_verbose(" max view count: " + itos(multiview_capabilities.max_view_count));
  5640. //print_verbose(" max instances: " + itos(multiview_capabilities.max_instance_count)); // Hardcoded; not very useful at the moment.
  5641. } else {
  5642. print_verbose("- D3D12 multiview not supported");
  5643. }
  5644. if (format_capabilities.relaxed_casting_supported) {
  5645. #if 0
  5646. print_verbose("- Relaxed casting supported");
  5647. #else
  5648. // Certain configurations (Windows 11 with an updated NVIDIA driver) crash when using relaxed casting.
  5649. // Therefore, we disable it temporarily until we can assure that it's reliable.
  5650. // There are fallbacks in place that work in every case, if less efficient.
  5651. format_capabilities.relaxed_casting_supported = false;
  5652. print_verbose("- Relaxed casting supported (but disabled for now)");
  5653. #endif
  5654. } else {
  5655. print_verbose("- Relaxed casting not supported");
  5656. }
  5657. print_verbose(String("- D3D12 16-bit ops supported: ") + (shader_capabilities.native_16bit_ops ? "yes" : "no"));
  5658. if (misc_features_support.depth_bounds_supported) {
  5659. print_verbose("- Depth bounds test supported");
  5660. } else {
  5661. print_verbose("- Depth bounds test not supported");
  5662. }
  5663. return OK;
  5664. }
  5665. Error RenderingDeviceDriverD3D12::_get_device_limits() {
  5666. D3D12_FEATURE_DATA_D3D12_OPTIONS options = {};
  5667. HRESULT res = device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options));
  5668. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ERR_UNAVAILABLE, "CheckFeatureSupport failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5669. // https://docs.microsoft.com/en-us/windows/win32/direct3d12/hardware-support
  5670. device_limits.max_srvs_per_shader_stage = options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_1 ? 128 : UINT64_MAX;
  5671. device_limits.max_cbvs_per_shader_stage = options.ResourceBindingTier <= D3D12_RESOURCE_BINDING_TIER_2 ? 14 : UINT64_MAX;
  5672. device_limits.max_samplers_across_all_stages = options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_1 ? 16 : 2048;
  5673. if (options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_1) {
  5674. device_limits.max_uavs_across_all_stages = feature_level <= 110 ? 8 : 64;
  5675. } else if (options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_2) {
  5676. device_limits.max_uavs_across_all_stages = 64;
  5677. } else {
  5678. device_limits.max_uavs_across_all_stages = UINT64_MAX;
  5679. }
  5680. // Retrieving the timestamp frequency requires creating a command queue that will be discarded immediately.
  5681. ComPtr<ID3D12CommandQueue> unused_command_queue;
  5682. D3D12_COMMAND_QUEUE_DESC queue_desc = {};
  5683. queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  5684. res = device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(unused_command_queue.GetAddressOf()));
  5685. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5686. res = unused_command_queue->GetTimestampFrequency(&device_limits.timestamp_frequency);
  5687. if (!SUCCEEDED(res)) {
  5688. print_verbose("D3D12: GetTimestampFrequency failed with error " + vformat("0x%08ux", (uint64_t)res) + ". Timestamps will be inaccurate.");
  5689. }
  5690. return OK;
  5691. }
  5692. Error RenderingDeviceDriverD3D12::_initialize_allocator() {
  5693. D3D12MA::ALLOCATOR_DESC allocator_desc = {};
  5694. allocator_desc.pDevice = device.Get();
  5695. allocator_desc.pAdapter = adapter.Get();
  5696. allocator_desc.Flags = D3D12MA::ALLOCATOR_FLAG_DEFAULT_POOLS_NOT_ZEROED;
  5697. HRESULT res = D3D12MA::CreateAllocator(&allocator_desc, &allocator);
  5698. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ERR_CANT_CREATE, "D3D12MA::CreateAllocator failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5699. return OK;
  5700. }
  5701. static Error create_command_signature(ID3D12Device *device, D3D12_INDIRECT_ARGUMENT_TYPE p_type, uint32_t p_stride, ComPtr<ID3D12CommandSignature> *r_cmd_sig) {
  5702. D3D12_INDIRECT_ARGUMENT_DESC iarg_desc = {};
  5703. iarg_desc.Type = p_type;
  5704. D3D12_COMMAND_SIGNATURE_DESC cs_desc = {};
  5705. cs_desc.ByteStride = p_stride;
  5706. cs_desc.NumArgumentDescs = 1;
  5707. cs_desc.pArgumentDescs = &iarg_desc;
  5708. cs_desc.NodeMask = 0;
  5709. HRESULT res = device->CreateCommandSignature(&cs_desc, nullptr, IID_PPV_ARGS(r_cmd_sig->GetAddressOf()));
  5710. ERR_FAIL_COND_V_MSG(!SUCCEEDED(res), ERR_CANT_CREATE, "CreateCommandSignature failed with error " + vformat("0x%08ux", (uint64_t)res) + ".");
  5711. return OK;
  5712. };
  5713. Error RenderingDeviceDriverD3D12::_initialize_frames(uint32_t p_frame_count) {
  5714. Error err;
  5715. //CD3DX12_RESOURCE_DESC resource_desc = CD3DX12_RESOURCE_DESC::Buffer(D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT);
  5716. uint32_t resource_descriptors_per_frame = GLOBAL_GET("rendering/rendering_device/d3d12/max_resource_descriptors_per_frame");
  5717. uint32_t sampler_descriptors_per_frame = GLOBAL_GET("rendering/rendering_device/d3d12/max_sampler_descriptors_per_frame");
  5718. uint32_t misc_descriptors_per_frame = GLOBAL_GET("rendering/rendering_device/d3d12/max_misc_descriptors_per_frame");
  5719. frames.resize(p_frame_count);
  5720. for (uint32_t i = 0; i < frames.size(); i++) {
  5721. err = frames[i].desc_heaps.resources.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, resource_descriptors_per_frame, true);
  5722. ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_CREATE, "Creating the frame's RESOURCE descriptors heap failed.");
  5723. err = frames[i].desc_heaps.samplers.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, sampler_descriptors_per_frame, true);
  5724. ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_CREATE, "Creating the frame's SAMPLER descriptors heap failed.");
  5725. err = frames[i].desc_heaps.aux.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, misc_descriptors_per_frame, false);
  5726. ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_CREATE, "Creating the frame's AUX descriptors heap failed.");
  5727. err = frames[i].desc_heaps.rtv.allocate(device.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_RTV, misc_descriptors_per_frame, false);
  5728. ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_CREATE, "Creating the frame's RENDER TARGET descriptors heap failed.");
  5729. frames[i].desc_heap_walkers.resources = frames[i].desc_heaps.resources.make_walker();
  5730. frames[i].desc_heap_walkers.samplers = frames[i].desc_heaps.samplers.make_walker();
  5731. frames[i].desc_heap_walkers.aux = frames[i].desc_heaps.aux.make_walker();
  5732. frames[i].desc_heap_walkers.rtv = frames[i].desc_heaps.rtv.make_walker();
  5733. }
  5734. return OK;
  5735. }
  5736. Error RenderingDeviceDriverD3D12::_initialize_command_signatures() {
  5737. Error err = create_command_signature(device.Get(), D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, sizeof(D3D12_DRAW_ARGUMENTS), &indirect_cmd_signatures.draw);
  5738. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5739. err = create_command_signature(device.Get(), D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED, sizeof(D3D12_DRAW_INDEXED_ARGUMENTS), &indirect_cmd_signatures.draw_indexed);
  5740. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5741. err = create_command_signature(device.Get(), D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, sizeof(D3D12_DISPATCH_ARGUMENTS), &indirect_cmd_signatures.dispatch);
  5742. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5743. return OK;
  5744. }
  5745. Error RenderingDeviceDriverD3D12::initialize(uint32_t p_device_index, uint32_t p_frame_count) {
  5746. context_device = context_driver->device_get(p_device_index);
  5747. adapter = context_driver->create_adapter(p_device_index);
  5748. ERR_FAIL_NULL_V(adapter, ERR_CANT_CREATE);
  5749. HRESULT res = adapter->GetDesc(&adapter_desc);
  5750. ERR_FAIL_COND_V(!SUCCEEDED(res), ERR_CANT_CREATE);
  5751. // Set the pipeline cache ID based on the adapter information.
  5752. pipeline_cache_id = String::hex_encode_buffer((uint8_t *)&adapter_desc.AdapterLuid, sizeof(LUID));
  5753. pipeline_cache_id += "-driver-" + itos(adapter_desc.Revision);
  5754. Error err = _initialize_device();
  5755. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5756. err = _check_capabilities();
  5757. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5758. err = _get_device_limits();
  5759. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5760. err = _initialize_allocator();
  5761. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5762. err = _initialize_frames(p_frame_count);
  5763. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5764. err = _initialize_command_signatures();
  5765. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  5766. glsl_type_singleton_init_or_ref();
  5767. return OK;
  5768. }