rendering_device_vulkan.cpp 399 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853
  1. /*************************************************************************/
  2. /* rendering_device_vulkan.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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_vulkan.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/compression.h"
  33. #include "core/io/file_access.h"
  34. #include "core/io/marshalls.h"
  35. #include "core/os/os.h"
  36. #include "core/templates/hashfuncs.h"
  37. #include "core/version.h"
  38. #include "drivers/vulkan/vulkan_context.h"
  39. #include "thirdparty/misc/smolv.h"
  40. #include "thirdparty/spirv-reflect/spirv_reflect.h"
  41. //#define FORCE_FULL_BARRIER
  42. static const uint32_t SMALL_ALLOCATION_MAX_SIZE = 4096;
  43. // Get the Vulkan object information and possible stage access types (bitwise OR'd with incoming values).
  44. RenderingDeviceVulkan::Buffer *RenderingDeviceVulkan::_get_buffer_from_owner(RID p_buffer, VkPipelineStageFlags &r_stage_mask, VkAccessFlags &r_access_mask, uint32_t p_post_barrier) {
  45. Buffer *buffer = nullptr;
  46. if (vertex_buffer_owner.owns(p_buffer)) {
  47. buffer = vertex_buffer_owner.get_or_null(p_buffer);
  48. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  49. r_access_mask |= VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
  50. if (buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) {
  51. if (p_post_barrier & BARRIER_MASK_RASTER) {
  52. r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  53. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  54. }
  55. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  56. r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  57. r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  58. }
  59. }
  60. } else if (index_buffer_owner.owns(p_buffer)) {
  61. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  62. r_access_mask |= VK_ACCESS_INDEX_READ_BIT;
  63. buffer = index_buffer_owner.get_or_null(p_buffer);
  64. } else if (uniform_buffer_owner.owns(p_buffer)) {
  65. if (p_post_barrier & BARRIER_MASK_RASTER) {
  66. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  67. }
  68. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  69. r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  70. }
  71. r_access_mask |= VK_ACCESS_UNIFORM_READ_BIT;
  72. buffer = uniform_buffer_owner.get_or_null(p_buffer);
  73. } else if (texture_buffer_owner.owns(p_buffer)) {
  74. if (p_post_barrier & BARRIER_MASK_RASTER) {
  75. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  76. r_access_mask |= VK_ACCESS_SHADER_READ_BIT;
  77. }
  78. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  79. r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  80. r_access_mask |= VK_ACCESS_SHADER_READ_BIT;
  81. }
  82. buffer = &texture_buffer_owner.get_or_null(p_buffer)->buffer;
  83. } else if (storage_buffer_owner.owns(p_buffer)) {
  84. buffer = storage_buffer_owner.get_or_null(p_buffer);
  85. if (p_post_barrier & BARRIER_MASK_RASTER) {
  86. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  87. r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  88. }
  89. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  90. r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  91. r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  92. }
  93. if (buffer->usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) {
  94. r_stage_mask |= VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
  95. r_access_mask |= VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
  96. }
  97. }
  98. return buffer;
  99. }
  100. static void update_external_dependency_for_store(VkSubpassDependency2KHR &dependency, bool is_sampled, bool is_storage, bool is_depth) {
  101. // Transitioning from write to read, protect the shaders that may use this next.
  102. // Allow for copies/image layout transitions.
  103. dependency.dstStageMask |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  104. dependency.dstAccessMask |= VK_ACCESS_TRANSFER_READ_BIT;
  105. if (is_sampled) {
  106. dependency.dstStageMask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  107. dependency.dstAccessMask |= VK_ACCESS_SHADER_READ_BIT;
  108. } else if (is_storage) {
  109. dependency.dstStageMask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  110. dependency.dstAccessMask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  111. } else {
  112. dependency.dstStageMask |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  113. dependency.dstAccessMask |= VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  114. }
  115. if (is_depth) {
  116. // Depth resources have additional stages that may be interested in them.
  117. dependency.dstStageMask |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  118. dependency.dstAccessMask |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  119. }
  120. }
  121. void RenderingDeviceVulkan::_add_dependency(RID p_id, RID p_depends_on) {
  122. if (!dependency_map.has(p_depends_on)) {
  123. dependency_map[p_depends_on] = HashSet<RID>();
  124. }
  125. dependency_map[p_depends_on].insert(p_id);
  126. if (!reverse_dependency_map.has(p_id)) {
  127. reverse_dependency_map[p_id] = HashSet<RID>();
  128. }
  129. reverse_dependency_map[p_id].insert(p_depends_on);
  130. }
  131. void RenderingDeviceVulkan::_free_dependencies(RID p_id) {
  132. // Direct dependencies must be freed.
  133. HashMap<RID, HashSet<RID>>::Iterator E = dependency_map.find(p_id);
  134. if (E) {
  135. while (E->value.size()) {
  136. free(*E->value.begin());
  137. }
  138. dependency_map.remove(E);
  139. }
  140. // Reverse dependencies must be unreferenced.
  141. E = reverse_dependency_map.find(p_id);
  142. if (E) {
  143. for (const RID &F : E->value) {
  144. HashMap<RID, HashSet<RID>>::Iterator G = dependency_map.find(F);
  145. ERR_CONTINUE(!G);
  146. ERR_CONTINUE(!G->value.has(p_id));
  147. G->value.erase(p_id);
  148. }
  149. reverse_dependency_map.remove(E);
  150. }
  151. }
  152. const VkFormat RenderingDeviceVulkan::vulkan_formats[RenderingDevice::DATA_FORMAT_MAX] = {
  153. VK_FORMAT_R4G4_UNORM_PACK8,
  154. VK_FORMAT_R4G4B4A4_UNORM_PACK16,
  155. VK_FORMAT_B4G4R4A4_UNORM_PACK16,
  156. VK_FORMAT_R5G6B5_UNORM_PACK16,
  157. VK_FORMAT_B5G6R5_UNORM_PACK16,
  158. VK_FORMAT_R5G5B5A1_UNORM_PACK16,
  159. VK_FORMAT_B5G5R5A1_UNORM_PACK16,
  160. VK_FORMAT_A1R5G5B5_UNORM_PACK16,
  161. VK_FORMAT_R8_UNORM,
  162. VK_FORMAT_R8_SNORM,
  163. VK_FORMAT_R8_USCALED,
  164. VK_FORMAT_R8_SSCALED,
  165. VK_FORMAT_R8_UINT,
  166. VK_FORMAT_R8_SINT,
  167. VK_FORMAT_R8_SRGB,
  168. VK_FORMAT_R8G8_UNORM,
  169. VK_FORMAT_R8G8_SNORM,
  170. VK_FORMAT_R8G8_USCALED,
  171. VK_FORMAT_R8G8_SSCALED,
  172. VK_FORMAT_R8G8_UINT,
  173. VK_FORMAT_R8G8_SINT,
  174. VK_FORMAT_R8G8_SRGB,
  175. VK_FORMAT_R8G8B8_UNORM,
  176. VK_FORMAT_R8G8B8_SNORM,
  177. VK_FORMAT_R8G8B8_USCALED,
  178. VK_FORMAT_R8G8B8_SSCALED,
  179. VK_FORMAT_R8G8B8_UINT,
  180. VK_FORMAT_R8G8B8_SINT,
  181. VK_FORMAT_R8G8B8_SRGB,
  182. VK_FORMAT_B8G8R8_UNORM,
  183. VK_FORMAT_B8G8R8_SNORM,
  184. VK_FORMAT_B8G8R8_USCALED,
  185. VK_FORMAT_B8G8R8_SSCALED,
  186. VK_FORMAT_B8G8R8_UINT,
  187. VK_FORMAT_B8G8R8_SINT,
  188. VK_FORMAT_B8G8R8_SRGB,
  189. VK_FORMAT_R8G8B8A8_UNORM,
  190. VK_FORMAT_R8G8B8A8_SNORM,
  191. VK_FORMAT_R8G8B8A8_USCALED,
  192. VK_FORMAT_R8G8B8A8_SSCALED,
  193. VK_FORMAT_R8G8B8A8_UINT,
  194. VK_FORMAT_R8G8B8A8_SINT,
  195. VK_FORMAT_R8G8B8A8_SRGB,
  196. VK_FORMAT_B8G8R8A8_UNORM,
  197. VK_FORMAT_B8G8R8A8_SNORM,
  198. VK_FORMAT_B8G8R8A8_USCALED,
  199. VK_FORMAT_B8G8R8A8_SSCALED,
  200. VK_FORMAT_B8G8R8A8_UINT,
  201. VK_FORMAT_B8G8R8A8_SINT,
  202. VK_FORMAT_B8G8R8A8_SRGB,
  203. VK_FORMAT_A8B8G8R8_UNORM_PACK32,
  204. VK_FORMAT_A8B8G8R8_SNORM_PACK32,
  205. VK_FORMAT_A8B8G8R8_USCALED_PACK32,
  206. VK_FORMAT_A8B8G8R8_SSCALED_PACK32,
  207. VK_FORMAT_A8B8G8R8_UINT_PACK32,
  208. VK_FORMAT_A8B8G8R8_SINT_PACK32,
  209. VK_FORMAT_A8B8G8R8_SRGB_PACK32,
  210. VK_FORMAT_A2R10G10B10_UNORM_PACK32,
  211. VK_FORMAT_A2R10G10B10_SNORM_PACK32,
  212. VK_FORMAT_A2R10G10B10_USCALED_PACK32,
  213. VK_FORMAT_A2R10G10B10_SSCALED_PACK32,
  214. VK_FORMAT_A2R10G10B10_UINT_PACK32,
  215. VK_FORMAT_A2R10G10B10_SINT_PACK32,
  216. VK_FORMAT_A2B10G10R10_UNORM_PACK32,
  217. VK_FORMAT_A2B10G10R10_SNORM_PACK32,
  218. VK_FORMAT_A2B10G10R10_USCALED_PACK32,
  219. VK_FORMAT_A2B10G10R10_SSCALED_PACK32,
  220. VK_FORMAT_A2B10G10R10_UINT_PACK32,
  221. VK_FORMAT_A2B10G10R10_SINT_PACK32,
  222. VK_FORMAT_R16_UNORM,
  223. VK_FORMAT_R16_SNORM,
  224. VK_FORMAT_R16_USCALED,
  225. VK_FORMAT_R16_SSCALED,
  226. VK_FORMAT_R16_UINT,
  227. VK_FORMAT_R16_SINT,
  228. VK_FORMAT_R16_SFLOAT,
  229. VK_FORMAT_R16G16_UNORM,
  230. VK_FORMAT_R16G16_SNORM,
  231. VK_FORMAT_R16G16_USCALED,
  232. VK_FORMAT_R16G16_SSCALED,
  233. VK_FORMAT_R16G16_UINT,
  234. VK_FORMAT_R16G16_SINT,
  235. VK_FORMAT_R16G16_SFLOAT,
  236. VK_FORMAT_R16G16B16_UNORM,
  237. VK_FORMAT_R16G16B16_SNORM,
  238. VK_FORMAT_R16G16B16_USCALED,
  239. VK_FORMAT_R16G16B16_SSCALED,
  240. VK_FORMAT_R16G16B16_UINT,
  241. VK_FORMAT_R16G16B16_SINT,
  242. VK_FORMAT_R16G16B16_SFLOAT,
  243. VK_FORMAT_R16G16B16A16_UNORM,
  244. VK_FORMAT_R16G16B16A16_SNORM,
  245. VK_FORMAT_R16G16B16A16_USCALED,
  246. VK_FORMAT_R16G16B16A16_SSCALED,
  247. VK_FORMAT_R16G16B16A16_UINT,
  248. VK_FORMAT_R16G16B16A16_SINT,
  249. VK_FORMAT_R16G16B16A16_SFLOAT,
  250. VK_FORMAT_R32_UINT,
  251. VK_FORMAT_R32_SINT,
  252. VK_FORMAT_R32_SFLOAT,
  253. VK_FORMAT_R32G32_UINT,
  254. VK_FORMAT_R32G32_SINT,
  255. VK_FORMAT_R32G32_SFLOAT,
  256. VK_FORMAT_R32G32B32_UINT,
  257. VK_FORMAT_R32G32B32_SINT,
  258. VK_FORMAT_R32G32B32_SFLOAT,
  259. VK_FORMAT_R32G32B32A32_UINT,
  260. VK_FORMAT_R32G32B32A32_SINT,
  261. VK_FORMAT_R32G32B32A32_SFLOAT,
  262. VK_FORMAT_R64_UINT,
  263. VK_FORMAT_R64_SINT,
  264. VK_FORMAT_R64_SFLOAT,
  265. VK_FORMAT_R64G64_UINT,
  266. VK_FORMAT_R64G64_SINT,
  267. VK_FORMAT_R64G64_SFLOAT,
  268. VK_FORMAT_R64G64B64_UINT,
  269. VK_FORMAT_R64G64B64_SINT,
  270. VK_FORMAT_R64G64B64_SFLOAT,
  271. VK_FORMAT_R64G64B64A64_UINT,
  272. VK_FORMAT_R64G64B64A64_SINT,
  273. VK_FORMAT_R64G64B64A64_SFLOAT,
  274. VK_FORMAT_B10G11R11_UFLOAT_PACK32,
  275. VK_FORMAT_E5B9G9R9_UFLOAT_PACK32,
  276. VK_FORMAT_D16_UNORM,
  277. VK_FORMAT_X8_D24_UNORM_PACK32,
  278. VK_FORMAT_D32_SFLOAT,
  279. VK_FORMAT_S8_UINT,
  280. VK_FORMAT_D16_UNORM_S8_UINT,
  281. VK_FORMAT_D24_UNORM_S8_UINT,
  282. VK_FORMAT_D32_SFLOAT_S8_UINT,
  283. VK_FORMAT_BC1_RGB_UNORM_BLOCK,
  284. VK_FORMAT_BC1_RGB_SRGB_BLOCK,
  285. VK_FORMAT_BC1_RGBA_UNORM_BLOCK,
  286. VK_FORMAT_BC1_RGBA_SRGB_BLOCK,
  287. VK_FORMAT_BC2_UNORM_BLOCK,
  288. VK_FORMAT_BC2_SRGB_BLOCK,
  289. VK_FORMAT_BC3_UNORM_BLOCK,
  290. VK_FORMAT_BC3_SRGB_BLOCK,
  291. VK_FORMAT_BC4_UNORM_BLOCK,
  292. VK_FORMAT_BC4_SNORM_BLOCK,
  293. VK_FORMAT_BC5_UNORM_BLOCK,
  294. VK_FORMAT_BC5_SNORM_BLOCK,
  295. VK_FORMAT_BC6H_UFLOAT_BLOCK,
  296. VK_FORMAT_BC6H_SFLOAT_BLOCK,
  297. VK_FORMAT_BC7_UNORM_BLOCK,
  298. VK_FORMAT_BC7_SRGB_BLOCK,
  299. VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK,
  300. VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK,
  301. VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK,
  302. VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK,
  303. VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK,
  304. VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK,
  305. VK_FORMAT_EAC_R11_UNORM_BLOCK,
  306. VK_FORMAT_EAC_R11_SNORM_BLOCK,
  307. VK_FORMAT_EAC_R11G11_UNORM_BLOCK,
  308. VK_FORMAT_EAC_R11G11_SNORM_BLOCK,
  309. VK_FORMAT_ASTC_4x4_UNORM_BLOCK,
  310. VK_FORMAT_ASTC_4x4_SRGB_BLOCK,
  311. VK_FORMAT_ASTC_5x4_UNORM_BLOCK,
  312. VK_FORMAT_ASTC_5x4_SRGB_BLOCK,
  313. VK_FORMAT_ASTC_5x5_UNORM_BLOCK,
  314. VK_FORMAT_ASTC_5x5_SRGB_BLOCK,
  315. VK_FORMAT_ASTC_6x5_UNORM_BLOCK,
  316. VK_FORMAT_ASTC_6x5_SRGB_BLOCK,
  317. VK_FORMAT_ASTC_6x6_UNORM_BLOCK,
  318. VK_FORMAT_ASTC_6x6_SRGB_BLOCK,
  319. VK_FORMAT_ASTC_8x5_UNORM_BLOCK,
  320. VK_FORMAT_ASTC_8x5_SRGB_BLOCK,
  321. VK_FORMAT_ASTC_8x6_UNORM_BLOCK,
  322. VK_FORMAT_ASTC_8x6_SRGB_BLOCK,
  323. VK_FORMAT_ASTC_8x8_UNORM_BLOCK,
  324. VK_FORMAT_ASTC_8x8_SRGB_BLOCK,
  325. VK_FORMAT_ASTC_10x5_UNORM_BLOCK,
  326. VK_FORMAT_ASTC_10x5_SRGB_BLOCK,
  327. VK_FORMAT_ASTC_10x6_UNORM_BLOCK,
  328. VK_FORMAT_ASTC_10x6_SRGB_BLOCK,
  329. VK_FORMAT_ASTC_10x8_UNORM_BLOCK,
  330. VK_FORMAT_ASTC_10x8_SRGB_BLOCK,
  331. VK_FORMAT_ASTC_10x10_UNORM_BLOCK,
  332. VK_FORMAT_ASTC_10x10_SRGB_BLOCK,
  333. VK_FORMAT_ASTC_12x10_UNORM_BLOCK,
  334. VK_FORMAT_ASTC_12x10_SRGB_BLOCK,
  335. VK_FORMAT_ASTC_12x12_UNORM_BLOCK,
  336. VK_FORMAT_ASTC_12x12_SRGB_BLOCK,
  337. VK_FORMAT_G8B8G8R8_422_UNORM,
  338. VK_FORMAT_B8G8R8G8_422_UNORM,
  339. VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM,
  340. VK_FORMAT_G8_B8R8_2PLANE_420_UNORM,
  341. VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM,
  342. VK_FORMAT_G8_B8R8_2PLANE_422_UNORM,
  343. VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM,
  344. VK_FORMAT_R10X6_UNORM_PACK16,
  345. VK_FORMAT_R10X6G10X6_UNORM_2PACK16,
  346. VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
  347. VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16,
  348. VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16,
  349. VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16,
  350. VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16,
  351. VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16,
  352. VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16,
  353. VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16,
  354. VK_FORMAT_R12X4_UNORM_PACK16,
  355. VK_FORMAT_R12X4G12X4_UNORM_2PACK16,
  356. VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16,
  357. VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16,
  358. VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16,
  359. VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16,
  360. VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16,
  361. VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16,
  362. VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16,
  363. VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16,
  364. VK_FORMAT_G16B16G16R16_422_UNORM,
  365. VK_FORMAT_B16G16R16G16_422_UNORM,
  366. VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM,
  367. VK_FORMAT_G16_B16R16_2PLANE_420_UNORM,
  368. VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM,
  369. VK_FORMAT_G16_B16R16_2PLANE_422_UNORM,
  370. VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM,
  371. };
  372. const char *RenderingDeviceVulkan::named_formats[RenderingDevice::DATA_FORMAT_MAX] = {
  373. "R4G4_Unorm_Pack8",
  374. "R4G4B4A4_Unorm_Pack16",
  375. "B4G4R4A4_Unorm_Pack16",
  376. "R5G6B5_Unorm_Pack16",
  377. "B5G6R5_Unorm_Pack16",
  378. "R5G5B5A1_Unorm_Pack16",
  379. "B5G5R5A1_Unorm_Pack16",
  380. "A1R5G5B5_Unorm_Pack16",
  381. "R8_Unorm",
  382. "R8_Snorm",
  383. "R8_Uscaled",
  384. "R8_Sscaled",
  385. "R8_Uint",
  386. "R8_Sint",
  387. "R8_Srgb",
  388. "R8G8_Unorm",
  389. "R8G8_Snorm",
  390. "R8G8_Uscaled",
  391. "R8G8_Sscaled",
  392. "R8G8_Uint",
  393. "R8G8_Sint",
  394. "R8G8_Srgb",
  395. "R8G8B8_Unorm",
  396. "R8G8B8_Snorm",
  397. "R8G8B8_Uscaled",
  398. "R8G8B8_Sscaled",
  399. "R8G8B8_Uint",
  400. "R8G8B8_Sint",
  401. "R8G8B8_Srgb",
  402. "B8G8R8_Unorm",
  403. "B8G8R8_Snorm",
  404. "B8G8R8_Uscaled",
  405. "B8G8R8_Sscaled",
  406. "B8G8R8_Uint",
  407. "B8G8R8_Sint",
  408. "B8G8R8_Srgb",
  409. "R8G8B8A8_Unorm",
  410. "R8G8B8A8_Snorm",
  411. "R8G8B8A8_Uscaled",
  412. "R8G8B8A8_Sscaled",
  413. "R8G8B8A8_Uint",
  414. "R8G8B8A8_Sint",
  415. "R8G8B8A8_Srgb",
  416. "B8G8R8A8_Unorm",
  417. "B8G8R8A8_Snorm",
  418. "B8G8R8A8_Uscaled",
  419. "B8G8R8A8_Sscaled",
  420. "B8G8R8A8_Uint",
  421. "B8G8R8A8_Sint",
  422. "B8G8R8A8_Srgb",
  423. "A8B8G8R8_Unorm_Pack32",
  424. "A8B8G8R8_Snorm_Pack32",
  425. "A8B8G8R8_Uscaled_Pack32",
  426. "A8B8G8R8_Sscaled_Pack32",
  427. "A8B8G8R8_Uint_Pack32",
  428. "A8B8G8R8_Sint_Pack32",
  429. "A8B8G8R8_Srgb_Pack32",
  430. "A2R10G10B10_Unorm_Pack32",
  431. "A2R10G10B10_Snorm_Pack32",
  432. "A2R10G10B10_Uscaled_Pack32",
  433. "A2R10G10B10_Sscaled_Pack32",
  434. "A2R10G10B10_Uint_Pack32",
  435. "A2R10G10B10_Sint_Pack32",
  436. "A2B10G10R10_Unorm_Pack32",
  437. "A2B10G10R10_Snorm_Pack32",
  438. "A2B10G10R10_Uscaled_Pack32",
  439. "A2B10G10R10_Sscaled_Pack32",
  440. "A2B10G10R10_Uint_Pack32",
  441. "A2B10G10R10_Sint_Pack32",
  442. "R16_Unorm",
  443. "R16_Snorm",
  444. "R16_Uscaled",
  445. "R16_Sscaled",
  446. "R16_Uint",
  447. "R16_Sint",
  448. "R16_Sfloat",
  449. "R16G16_Unorm",
  450. "R16G16_Snorm",
  451. "R16G16_Uscaled",
  452. "R16G16_Sscaled",
  453. "R16G16_Uint",
  454. "R16G16_Sint",
  455. "R16G16_Sfloat",
  456. "R16G16B16_Unorm",
  457. "R16G16B16_Snorm",
  458. "R16G16B16_Uscaled",
  459. "R16G16B16_Sscaled",
  460. "R16G16B16_Uint",
  461. "R16G16B16_Sint",
  462. "R16G16B16_Sfloat",
  463. "R16G16B16A16_Unorm",
  464. "R16G16B16A16_Snorm",
  465. "R16G16B16A16_Uscaled",
  466. "R16G16B16A16_Sscaled",
  467. "R16G16B16A16_Uint",
  468. "R16G16B16A16_Sint",
  469. "R16G16B16A16_Sfloat",
  470. "R32_Uint",
  471. "R32_Sint",
  472. "R32_Sfloat",
  473. "R32G32_Uint",
  474. "R32G32_Sint",
  475. "R32G32_Sfloat",
  476. "R32G32B32_Uint",
  477. "R32G32B32_Sint",
  478. "R32G32B32_Sfloat",
  479. "R32G32B32A32_Uint",
  480. "R32G32B32A32_Sint",
  481. "R32G32B32A32_Sfloat",
  482. "R64_Uint",
  483. "R64_Sint",
  484. "R64_Sfloat",
  485. "R64G64_Uint",
  486. "R64G64_Sint",
  487. "R64G64_Sfloat",
  488. "R64G64B64_Uint",
  489. "R64G64B64_Sint",
  490. "R64G64B64_Sfloat",
  491. "R64G64B64A64_Uint",
  492. "R64G64B64A64_Sint",
  493. "R64G64B64A64_Sfloat",
  494. "B10G11R11_Ufloat_Pack32",
  495. "E5B9G9R9_Ufloat_Pack32",
  496. "D16_Unorm",
  497. "X8_D24_Unorm_Pack32",
  498. "D32_Sfloat",
  499. "S8_Uint",
  500. "D16_Unorm_S8_Uint",
  501. "D24_Unorm_S8_Uint",
  502. "D32_Sfloat_S8_Uint",
  503. "Bc1_Rgb_Unorm_Block",
  504. "Bc1_Rgb_Srgb_Block",
  505. "Bc1_Rgba_Unorm_Block",
  506. "Bc1_Rgba_Srgb_Block",
  507. "Bc2_Unorm_Block",
  508. "Bc2_Srgb_Block",
  509. "Bc3_Unorm_Block",
  510. "Bc3_Srgb_Block",
  511. "Bc4_Unorm_Block",
  512. "Bc4_Snorm_Block",
  513. "Bc5_Unorm_Block",
  514. "Bc5_Snorm_Block",
  515. "Bc6H_Ufloat_Block",
  516. "Bc6H_Sfloat_Block",
  517. "Bc7_Unorm_Block",
  518. "Bc7_Srgb_Block",
  519. "Etc2_R8G8B8_Unorm_Block",
  520. "Etc2_R8G8B8_Srgb_Block",
  521. "Etc2_R8G8B8A1_Unorm_Block",
  522. "Etc2_R8G8B8A1_Srgb_Block",
  523. "Etc2_R8G8B8A8_Unorm_Block",
  524. "Etc2_R8G8B8A8_Srgb_Block",
  525. "Eac_R11_Unorm_Block",
  526. "Eac_R11_Snorm_Block",
  527. "Eac_R11G11_Unorm_Block",
  528. "Eac_R11G11_Snorm_Block",
  529. "Astc_4X4_Unorm_Block",
  530. "Astc_4X4_Srgb_Block",
  531. "Astc_5X4_Unorm_Block",
  532. "Astc_5X4_Srgb_Block",
  533. "Astc_5X5_Unorm_Block",
  534. "Astc_5X5_Srgb_Block",
  535. "Astc_6X5_Unorm_Block",
  536. "Astc_6X5_Srgb_Block",
  537. "Astc_6X6_Unorm_Block",
  538. "Astc_6X6_Srgb_Block",
  539. "Astc_8X5_Unorm_Block",
  540. "Astc_8X5_Srgb_Block",
  541. "Astc_8X6_Unorm_Block",
  542. "Astc_8X6_Srgb_Block",
  543. "Astc_8X8_Unorm_Block",
  544. "Astc_8X8_Srgb_Block",
  545. "Astc_10X5_Unorm_Block",
  546. "Astc_10X5_Srgb_Block",
  547. "Astc_10X6_Unorm_Block",
  548. "Astc_10X6_Srgb_Block",
  549. "Astc_10X8_Unorm_Block",
  550. "Astc_10X8_Srgb_Block",
  551. "Astc_10X10_Unorm_Block",
  552. "Astc_10X10_Srgb_Block",
  553. "Astc_12X10_Unorm_Block",
  554. "Astc_12X10_Srgb_Block",
  555. "Astc_12X12_Unorm_Block",
  556. "Astc_12X12_Srgb_Block",
  557. "G8B8G8R8_422_Unorm",
  558. "B8G8R8G8_422_Unorm",
  559. "G8_B8_R8_3Plane_420_Unorm",
  560. "G8_B8R8_2Plane_420_Unorm",
  561. "G8_B8_R8_3Plane_422_Unorm",
  562. "G8_B8R8_2Plane_422_Unorm",
  563. "G8_B8_R8_3Plane_444_Unorm",
  564. "R10X6_Unorm_Pack16",
  565. "R10X6G10X6_Unorm_2Pack16",
  566. "R10X6G10X6B10X6A10X6_Unorm_4Pack16",
  567. "G10X6B10X6G10X6R10X6_422_Unorm_4Pack16",
  568. "B10X6G10X6R10X6G10X6_422_Unorm_4Pack16",
  569. "G10X6_B10X6_R10X6_3Plane_420_Unorm_3Pack16",
  570. "G10X6_B10X6R10X6_2Plane_420_Unorm_3Pack16",
  571. "G10X6_B10X6_R10X6_3Plane_422_Unorm_3Pack16",
  572. "G10X6_B10X6R10X6_2Plane_422_Unorm_3Pack16",
  573. "G10X6_B10X6_R10X6_3Plane_444_Unorm_3Pack16",
  574. "R12X4_Unorm_Pack16",
  575. "R12X4G12X4_Unorm_2Pack16",
  576. "R12X4G12X4B12X4A12X4_Unorm_4Pack16",
  577. "G12X4B12X4G12X4R12X4_422_Unorm_4Pack16",
  578. "B12X4G12X4R12X4G12X4_422_Unorm_4Pack16",
  579. "G12X4_B12X4_R12X4_3Plane_420_Unorm_3Pack16",
  580. "G12X4_B12X4R12X4_2Plane_420_Unorm_3Pack16",
  581. "G12X4_B12X4_R12X4_3Plane_422_Unorm_3Pack16",
  582. "G12X4_B12X4R12X4_2Plane_422_Unorm_3Pack16",
  583. "G12X4_B12X4_R12X4_3Plane_444_Unorm_3Pack16",
  584. "G16B16G16R16_422_Unorm",
  585. "B16G16R16G16_422_Unorm",
  586. "G16_B16_R16_3Plane_420_Unorm",
  587. "G16_B16R16_2Plane_420_Unorm",
  588. "G16_B16_R16_3Plane_422_Unorm",
  589. "G16_B16R16_2Plane_422_Unorm",
  590. "G16_B16_R16_3Plane_444_Unorm",
  591. };
  592. int RenderingDeviceVulkan::get_format_vertex_size(DataFormat p_format) {
  593. switch (p_format) {
  594. case DATA_FORMAT_R8_UNORM:
  595. case DATA_FORMAT_R8_SNORM:
  596. case DATA_FORMAT_R8_UINT:
  597. case DATA_FORMAT_R8_SINT:
  598. case DATA_FORMAT_R8G8_UNORM:
  599. case DATA_FORMAT_R8G8_SNORM:
  600. case DATA_FORMAT_R8G8_UINT:
  601. case DATA_FORMAT_R8G8_SINT:
  602. case DATA_FORMAT_R8G8B8_UNORM:
  603. case DATA_FORMAT_R8G8B8_SNORM:
  604. case DATA_FORMAT_R8G8B8_UINT:
  605. case DATA_FORMAT_R8G8B8_SINT:
  606. case DATA_FORMAT_B8G8R8_UNORM:
  607. case DATA_FORMAT_B8G8R8_SNORM:
  608. case DATA_FORMAT_B8G8R8_UINT:
  609. case DATA_FORMAT_B8G8R8_SINT:
  610. case DATA_FORMAT_R8G8B8A8_UNORM:
  611. case DATA_FORMAT_R8G8B8A8_SNORM:
  612. case DATA_FORMAT_R8G8B8A8_UINT:
  613. case DATA_FORMAT_R8G8B8A8_SINT:
  614. case DATA_FORMAT_B8G8R8A8_UNORM:
  615. case DATA_FORMAT_B8G8R8A8_SNORM:
  616. case DATA_FORMAT_B8G8R8A8_UINT:
  617. case DATA_FORMAT_B8G8R8A8_SINT:
  618. case DATA_FORMAT_A2B10G10R10_UNORM_PACK32:
  619. return 4;
  620. case DATA_FORMAT_R16_UNORM:
  621. case DATA_FORMAT_R16_SNORM:
  622. case DATA_FORMAT_R16_UINT:
  623. case DATA_FORMAT_R16_SINT:
  624. case DATA_FORMAT_R16_SFLOAT:
  625. return 4;
  626. case DATA_FORMAT_R16G16_UNORM:
  627. case DATA_FORMAT_R16G16_SNORM:
  628. case DATA_FORMAT_R16G16_UINT:
  629. case DATA_FORMAT_R16G16_SINT:
  630. case DATA_FORMAT_R16G16_SFLOAT:
  631. return 4;
  632. case DATA_FORMAT_R16G16B16_UNORM:
  633. case DATA_FORMAT_R16G16B16_SNORM:
  634. case DATA_FORMAT_R16G16B16_UINT:
  635. case DATA_FORMAT_R16G16B16_SINT:
  636. case DATA_FORMAT_R16G16B16_SFLOAT:
  637. return 8;
  638. case DATA_FORMAT_R16G16B16A16_UNORM:
  639. case DATA_FORMAT_R16G16B16A16_SNORM:
  640. case DATA_FORMAT_R16G16B16A16_UINT:
  641. case DATA_FORMAT_R16G16B16A16_SINT:
  642. case DATA_FORMAT_R16G16B16A16_SFLOAT:
  643. return 8;
  644. case DATA_FORMAT_R32_UINT:
  645. case DATA_FORMAT_R32_SINT:
  646. case DATA_FORMAT_R32_SFLOAT:
  647. return 4;
  648. case DATA_FORMAT_R32G32_UINT:
  649. case DATA_FORMAT_R32G32_SINT:
  650. case DATA_FORMAT_R32G32_SFLOAT:
  651. return 8;
  652. case DATA_FORMAT_R32G32B32_UINT:
  653. case DATA_FORMAT_R32G32B32_SINT:
  654. case DATA_FORMAT_R32G32B32_SFLOAT:
  655. return 12;
  656. case DATA_FORMAT_R32G32B32A32_UINT:
  657. case DATA_FORMAT_R32G32B32A32_SINT:
  658. case DATA_FORMAT_R32G32B32A32_SFLOAT:
  659. return 16;
  660. case DATA_FORMAT_R64_UINT:
  661. case DATA_FORMAT_R64_SINT:
  662. case DATA_FORMAT_R64_SFLOAT:
  663. return 8;
  664. case DATA_FORMAT_R64G64_UINT:
  665. case DATA_FORMAT_R64G64_SINT:
  666. case DATA_FORMAT_R64G64_SFLOAT:
  667. return 16;
  668. case DATA_FORMAT_R64G64B64_UINT:
  669. case DATA_FORMAT_R64G64B64_SINT:
  670. case DATA_FORMAT_R64G64B64_SFLOAT:
  671. return 24;
  672. case DATA_FORMAT_R64G64B64A64_UINT:
  673. case DATA_FORMAT_R64G64B64A64_SINT:
  674. case DATA_FORMAT_R64G64B64A64_SFLOAT:
  675. return 32;
  676. default:
  677. return 0;
  678. }
  679. }
  680. uint32_t RenderingDeviceVulkan::get_image_format_pixel_size(DataFormat p_format) {
  681. switch (p_format) {
  682. case DATA_FORMAT_R4G4_UNORM_PACK8:
  683. return 1;
  684. case DATA_FORMAT_R4G4B4A4_UNORM_PACK16:
  685. case DATA_FORMAT_B4G4R4A4_UNORM_PACK16:
  686. case DATA_FORMAT_R5G6B5_UNORM_PACK16:
  687. case DATA_FORMAT_B5G6R5_UNORM_PACK16:
  688. case DATA_FORMAT_R5G5B5A1_UNORM_PACK16:
  689. case DATA_FORMAT_B5G5R5A1_UNORM_PACK16:
  690. case DATA_FORMAT_A1R5G5B5_UNORM_PACK16:
  691. return 2;
  692. case DATA_FORMAT_R8_UNORM:
  693. case DATA_FORMAT_R8_SNORM:
  694. case DATA_FORMAT_R8_USCALED:
  695. case DATA_FORMAT_R8_SSCALED:
  696. case DATA_FORMAT_R8_UINT:
  697. case DATA_FORMAT_R8_SINT:
  698. case DATA_FORMAT_R8_SRGB:
  699. return 1;
  700. case DATA_FORMAT_R8G8_UNORM:
  701. case DATA_FORMAT_R8G8_SNORM:
  702. case DATA_FORMAT_R8G8_USCALED:
  703. case DATA_FORMAT_R8G8_SSCALED:
  704. case DATA_FORMAT_R8G8_UINT:
  705. case DATA_FORMAT_R8G8_SINT:
  706. case DATA_FORMAT_R8G8_SRGB:
  707. return 2;
  708. case DATA_FORMAT_R8G8B8_UNORM:
  709. case DATA_FORMAT_R8G8B8_SNORM:
  710. case DATA_FORMAT_R8G8B8_USCALED:
  711. case DATA_FORMAT_R8G8B8_SSCALED:
  712. case DATA_FORMAT_R8G8B8_UINT:
  713. case DATA_FORMAT_R8G8B8_SINT:
  714. case DATA_FORMAT_R8G8B8_SRGB:
  715. case DATA_FORMAT_B8G8R8_UNORM:
  716. case DATA_FORMAT_B8G8R8_SNORM:
  717. case DATA_FORMAT_B8G8R8_USCALED:
  718. case DATA_FORMAT_B8G8R8_SSCALED:
  719. case DATA_FORMAT_B8G8R8_UINT:
  720. case DATA_FORMAT_B8G8R8_SINT:
  721. case DATA_FORMAT_B8G8R8_SRGB:
  722. return 3;
  723. case DATA_FORMAT_R8G8B8A8_UNORM:
  724. case DATA_FORMAT_R8G8B8A8_SNORM:
  725. case DATA_FORMAT_R8G8B8A8_USCALED:
  726. case DATA_FORMAT_R8G8B8A8_SSCALED:
  727. case DATA_FORMAT_R8G8B8A8_UINT:
  728. case DATA_FORMAT_R8G8B8A8_SINT:
  729. case DATA_FORMAT_R8G8B8A8_SRGB:
  730. case DATA_FORMAT_B8G8R8A8_UNORM:
  731. case DATA_FORMAT_B8G8R8A8_SNORM:
  732. case DATA_FORMAT_B8G8R8A8_USCALED:
  733. case DATA_FORMAT_B8G8R8A8_SSCALED:
  734. case DATA_FORMAT_B8G8R8A8_UINT:
  735. case DATA_FORMAT_B8G8R8A8_SINT:
  736. case DATA_FORMAT_B8G8R8A8_SRGB:
  737. return 4;
  738. case DATA_FORMAT_A8B8G8R8_UNORM_PACK32:
  739. case DATA_FORMAT_A8B8G8R8_SNORM_PACK32:
  740. case DATA_FORMAT_A8B8G8R8_USCALED_PACK32:
  741. case DATA_FORMAT_A8B8G8R8_SSCALED_PACK32:
  742. case DATA_FORMAT_A8B8G8R8_UINT_PACK32:
  743. case DATA_FORMAT_A8B8G8R8_SINT_PACK32:
  744. case DATA_FORMAT_A8B8G8R8_SRGB_PACK32:
  745. case DATA_FORMAT_A2R10G10B10_UNORM_PACK32:
  746. case DATA_FORMAT_A2R10G10B10_SNORM_PACK32:
  747. case DATA_FORMAT_A2R10G10B10_USCALED_PACK32:
  748. case DATA_FORMAT_A2R10G10B10_SSCALED_PACK32:
  749. case DATA_FORMAT_A2R10G10B10_UINT_PACK32:
  750. case DATA_FORMAT_A2R10G10B10_SINT_PACK32:
  751. case DATA_FORMAT_A2B10G10R10_UNORM_PACK32:
  752. case DATA_FORMAT_A2B10G10R10_SNORM_PACK32:
  753. case DATA_FORMAT_A2B10G10R10_USCALED_PACK32:
  754. case DATA_FORMAT_A2B10G10R10_SSCALED_PACK32:
  755. case DATA_FORMAT_A2B10G10R10_UINT_PACK32:
  756. case DATA_FORMAT_A2B10G10R10_SINT_PACK32:
  757. return 4;
  758. case DATA_FORMAT_R16_UNORM:
  759. case DATA_FORMAT_R16_SNORM:
  760. case DATA_FORMAT_R16_USCALED:
  761. case DATA_FORMAT_R16_SSCALED:
  762. case DATA_FORMAT_R16_UINT:
  763. case DATA_FORMAT_R16_SINT:
  764. case DATA_FORMAT_R16_SFLOAT:
  765. return 2;
  766. case DATA_FORMAT_R16G16_UNORM:
  767. case DATA_FORMAT_R16G16_SNORM:
  768. case DATA_FORMAT_R16G16_USCALED:
  769. case DATA_FORMAT_R16G16_SSCALED:
  770. case DATA_FORMAT_R16G16_UINT:
  771. case DATA_FORMAT_R16G16_SINT:
  772. case DATA_FORMAT_R16G16_SFLOAT:
  773. return 4;
  774. case DATA_FORMAT_R16G16B16_UNORM:
  775. case DATA_FORMAT_R16G16B16_SNORM:
  776. case DATA_FORMAT_R16G16B16_USCALED:
  777. case DATA_FORMAT_R16G16B16_SSCALED:
  778. case DATA_FORMAT_R16G16B16_UINT:
  779. case DATA_FORMAT_R16G16B16_SINT:
  780. case DATA_FORMAT_R16G16B16_SFLOAT:
  781. return 6;
  782. case DATA_FORMAT_R16G16B16A16_UNORM:
  783. case DATA_FORMAT_R16G16B16A16_SNORM:
  784. case DATA_FORMAT_R16G16B16A16_USCALED:
  785. case DATA_FORMAT_R16G16B16A16_SSCALED:
  786. case DATA_FORMAT_R16G16B16A16_UINT:
  787. case DATA_FORMAT_R16G16B16A16_SINT:
  788. case DATA_FORMAT_R16G16B16A16_SFLOAT:
  789. return 8;
  790. case DATA_FORMAT_R32_UINT:
  791. case DATA_FORMAT_R32_SINT:
  792. case DATA_FORMAT_R32_SFLOAT:
  793. return 4;
  794. case DATA_FORMAT_R32G32_UINT:
  795. case DATA_FORMAT_R32G32_SINT:
  796. case DATA_FORMAT_R32G32_SFLOAT:
  797. return 8;
  798. case DATA_FORMAT_R32G32B32_UINT:
  799. case DATA_FORMAT_R32G32B32_SINT:
  800. case DATA_FORMAT_R32G32B32_SFLOAT:
  801. return 12;
  802. case DATA_FORMAT_R32G32B32A32_UINT:
  803. case DATA_FORMAT_R32G32B32A32_SINT:
  804. case DATA_FORMAT_R32G32B32A32_SFLOAT:
  805. return 16;
  806. case DATA_FORMAT_R64_UINT:
  807. case DATA_FORMAT_R64_SINT:
  808. case DATA_FORMAT_R64_SFLOAT:
  809. return 8;
  810. case DATA_FORMAT_R64G64_UINT:
  811. case DATA_FORMAT_R64G64_SINT:
  812. case DATA_FORMAT_R64G64_SFLOAT:
  813. return 16;
  814. case DATA_FORMAT_R64G64B64_UINT:
  815. case DATA_FORMAT_R64G64B64_SINT:
  816. case DATA_FORMAT_R64G64B64_SFLOAT:
  817. return 24;
  818. case DATA_FORMAT_R64G64B64A64_UINT:
  819. case DATA_FORMAT_R64G64B64A64_SINT:
  820. case DATA_FORMAT_R64G64B64A64_SFLOAT:
  821. return 32;
  822. case DATA_FORMAT_B10G11R11_UFLOAT_PACK32:
  823. case DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32:
  824. return 4;
  825. case DATA_FORMAT_D16_UNORM:
  826. return 2;
  827. case DATA_FORMAT_X8_D24_UNORM_PACK32:
  828. return 4;
  829. case DATA_FORMAT_D32_SFLOAT:
  830. return 4;
  831. case DATA_FORMAT_S8_UINT:
  832. return 1;
  833. case DATA_FORMAT_D16_UNORM_S8_UINT:
  834. return 4;
  835. case DATA_FORMAT_D24_UNORM_S8_UINT:
  836. return 4;
  837. case DATA_FORMAT_D32_SFLOAT_S8_UINT:
  838. return 5; // ?
  839. case DATA_FORMAT_BC1_RGB_UNORM_BLOCK:
  840. case DATA_FORMAT_BC1_RGB_SRGB_BLOCK:
  841. case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK:
  842. case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK:
  843. case DATA_FORMAT_BC2_UNORM_BLOCK:
  844. case DATA_FORMAT_BC2_SRGB_BLOCK:
  845. case DATA_FORMAT_BC3_UNORM_BLOCK:
  846. case DATA_FORMAT_BC3_SRGB_BLOCK:
  847. case DATA_FORMAT_BC4_UNORM_BLOCK:
  848. case DATA_FORMAT_BC4_SNORM_BLOCK:
  849. case DATA_FORMAT_BC5_UNORM_BLOCK:
  850. case DATA_FORMAT_BC5_SNORM_BLOCK:
  851. case DATA_FORMAT_BC6H_UFLOAT_BLOCK:
  852. case DATA_FORMAT_BC6H_SFLOAT_BLOCK:
  853. case DATA_FORMAT_BC7_UNORM_BLOCK:
  854. case DATA_FORMAT_BC7_SRGB_BLOCK:
  855. return 1;
  856. case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK:
  857. case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK:
  858. case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK:
  859. case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK:
  860. case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK:
  861. case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK:
  862. return 1;
  863. case DATA_FORMAT_EAC_R11_UNORM_BLOCK:
  864. case DATA_FORMAT_EAC_R11_SNORM_BLOCK:
  865. case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK:
  866. case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK:
  867. return 1;
  868. case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK:
  869. case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK:
  870. case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK:
  871. case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK:
  872. case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK:
  873. case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK:
  874. case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK:
  875. case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK:
  876. case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK:
  877. case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK:
  878. case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK:
  879. case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK:
  880. case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK:
  881. case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK:
  882. case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK:
  883. case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK:
  884. case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK:
  885. case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK:
  886. case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK:
  887. case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK:
  888. case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK:
  889. case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK:
  890. case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK:
  891. case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK:
  892. case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK:
  893. case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK:
  894. case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK:
  895. case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK:
  896. return 1;
  897. case DATA_FORMAT_G8B8G8R8_422_UNORM:
  898. case DATA_FORMAT_B8G8R8G8_422_UNORM:
  899. return 4;
  900. case DATA_FORMAT_G8_B8_R8_3PLANE_420_UNORM:
  901. case DATA_FORMAT_G8_B8R8_2PLANE_420_UNORM:
  902. case DATA_FORMAT_G8_B8_R8_3PLANE_422_UNORM:
  903. case DATA_FORMAT_G8_B8R8_2PLANE_422_UNORM:
  904. case DATA_FORMAT_G8_B8_R8_3PLANE_444_UNORM:
  905. return 4;
  906. case DATA_FORMAT_R10X6_UNORM_PACK16:
  907. case DATA_FORMAT_R10X6G10X6_UNORM_2PACK16:
  908. case DATA_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
  909. case DATA_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16:
  910. case DATA_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16:
  911. case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16:
  912. case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16:
  913. case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16:
  914. case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16:
  915. case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16:
  916. case DATA_FORMAT_R12X4_UNORM_PACK16:
  917. case DATA_FORMAT_R12X4G12X4_UNORM_2PACK16:
  918. case DATA_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16:
  919. case DATA_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16:
  920. case DATA_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16:
  921. case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16:
  922. case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16:
  923. case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16:
  924. case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16:
  925. case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16:
  926. return 2;
  927. case DATA_FORMAT_G16B16G16R16_422_UNORM:
  928. case DATA_FORMAT_B16G16R16G16_422_UNORM:
  929. case DATA_FORMAT_G16_B16_R16_3PLANE_420_UNORM:
  930. case DATA_FORMAT_G16_B16R16_2PLANE_420_UNORM:
  931. case DATA_FORMAT_G16_B16_R16_3PLANE_422_UNORM:
  932. case DATA_FORMAT_G16_B16R16_2PLANE_422_UNORM:
  933. case DATA_FORMAT_G16_B16_R16_3PLANE_444_UNORM:
  934. return 8;
  935. default: {
  936. ERR_PRINT("Format not handled, bug");
  937. }
  938. }
  939. return 1;
  940. }
  941. // https://www.khronos.org/registry/DataFormat/specs/1.1/dataformat.1.1.pdf
  942. void RenderingDeviceVulkan::get_compressed_image_format_block_dimensions(DataFormat p_format, uint32_t &r_w, uint32_t &r_h) {
  943. switch (p_format) {
  944. case DATA_FORMAT_BC1_RGB_UNORM_BLOCK:
  945. case DATA_FORMAT_BC1_RGB_SRGB_BLOCK:
  946. case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK:
  947. case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK:
  948. case DATA_FORMAT_BC2_UNORM_BLOCK:
  949. case DATA_FORMAT_BC2_SRGB_BLOCK:
  950. case DATA_FORMAT_BC3_UNORM_BLOCK:
  951. case DATA_FORMAT_BC3_SRGB_BLOCK:
  952. case DATA_FORMAT_BC4_UNORM_BLOCK:
  953. case DATA_FORMAT_BC4_SNORM_BLOCK:
  954. case DATA_FORMAT_BC5_UNORM_BLOCK:
  955. case DATA_FORMAT_BC5_SNORM_BLOCK:
  956. case DATA_FORMAT_BC6H_UFLOAT_BLOCK:
  957. case DATA_FORMAT_BC6H_SFLOAT_BLOCK:
  958. case DATA_FORMAT_BC7_UNORM_BLOCK:
  959. case DATA_FORMAT_BC7_SRGB_BLOCK:
  960. case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK:
  961. case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK:
  962. case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK:
  963. case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK:
  964. case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK:
  965. case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK:
  966. case DATA_FORMAT_EAC_R11_UNORM_BLOCK:
  967. case DATA_FORMAT_EAC_R11_SNORM_BLOCK:
  968. case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK:
  969. case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK:
  970. case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK: // Again, not sure about astc.
  971. case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK: {
  972. r_w = 4;
  973. r_h = 4;
  974. } break;
  975. case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK: // Unsupported
  976. case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK:
  977. case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK:
  978. case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK:
  979. case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK:
  980. case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK:
  981. case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK:
  982. case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK:
  983. case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK:
  984. case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK:
  985. case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK:
  986. case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK: {
  987. r_w = 4;
  988. r_h = 4;
  989. } break;
  990. case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK:
  991. case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK: {
  992. r_w = 8;
  993. r_h = 8;
  994. } break;
  995. case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK: // Unsupported
  996. case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK:
  997. case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK:
  998. case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK:
  999. case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK:
  1000. case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK:
  1001. case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK:
  1002. case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK:
  1003. case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK:
  1004. case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK:
  1005. case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK:
  1006. case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK:
  1007. r_w = 4;
  1008. r_h = 4;
  1009. return;
  1010. default: {
  1011. r_w = 1;
  1012. r_h = 1;
  1013. }
  1014. }
  1015. }
  1016. uint32_t RenderingDeviceVulkan::get_compressed_image_format_block_byte_size(DataFormat p_format) {
  1017. switch (p_format) {
  1018. case DATA_FORMAT_BC1_RGB_UNORM_BLOCK:
  1019. case DATA_FORMAT_BC1_RGB_SRGB_BLOCK:
  1020. case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK:
  1021. case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK:
  1022. return 8;
  1023. case DATA_FORMAT_BC2_UNORM_BLOCK:
  1024. case DATA_FORMAT_BC2_SRGB_BLOCK:
  1025. return 16;
  1026. case DATA_FORMAT_BC3_UNORM_BLOCK:
  1027. case DATA_FORMAT_BC3_SRGB_BLOCK:
  1028. return 16;
  1029. case DATA_FORMAT_BC4_UNORM_BLOCK:
  1030. case DATA_FORMAT_BC4_SNORM_BLOCK:
  1031. return 8;
  1032. case DATA_FORMAT_BC5_UNORM_BLOCK:
  1033. case DATA_FORMAT_BC5_SNORM_BLOCK:
  1034. return 16;
  1035. case DATA_FORMAT_BC6H_UFLOAT_BLOCK:
  1036. case DATA_FORMAT_BC6H_SFLOAT_BLOCK:
  1037. return 16;
  1038. case DATA_FORMAT_BC7_UNORM_BLOCK:
  1039. case DATA_FORMAT_BC7_SRGB_BLOCK:
  1040. return 16;
  1041. case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK:
  1042. case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK:
  1043. return 8;
  1044. case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK:
  1045. case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK:
  1046. return 8;
  1047. case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK:
  1048. case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK:
  1049. return 16;
  1050. case DATA_FORMAT_EAC_R11_UNORM_BLOCK:
  1051. case DATA_FORMAT_EAC_R11_SNORM_BLOCK:
  1052. return 8;
  1053. case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK:
  1054. case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK:
  1055. return 16;
  1056. case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK: // Again, not sure about astc.
  1057. case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK:
  1058. case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK:
  1059. case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK:
  1060. case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK:
  1061. case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK:
  1062. case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK:
  1063. case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK:
  1064. case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK:
  1065. case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK:
  1066. case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK:
  1067. case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK:
  1068. case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK:
  1069. case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK:
  1070. case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK:
  1071. case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK:
  1072. case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK:
  1073. case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK:
  1074. case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK:
  1075. case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK:
  1076. case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK:
  1077. case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK:
  1078. case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK:
  1079. case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK:
  1080. case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK:
  1081. case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK:
  1082. case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK:
  1083. case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK:
  1084. return 16;
  1085. default: {
  1086. }
  1087. }
  1088. return 1;
  1089. }
  1090. uint32_t RenderingDeviceVulkan::get_compressed_image_format_pixel_rshift(DataFormat p_format) {
  1091. switch (p_format) {
  1092. case DATA_FORMAT_BC1_RGB_UNORM_BLOCK: // These formats are half byte size, so rshift is 1.
  1093. case DATA_FORMAT_BC1_RGB_SRGB_BLOCK:
  1094. case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK:
  1095. case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK:
  1096. case DATA_FORMAT_BC4_UNORM_BLOCK:
  1097. case DATA_FORMAT_BC4_SNORM_BLOCK:
  1098. case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK:
  1099. case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK:
  1100. case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK:
  1101. case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK:
  1102. case DATA_FORMAT_EAC_R11_UNORM_BLOCK:
  1103. case DATA_FORMAT_EAC_R11_SNORM_BLOCK:
  1104. return 1;
  1105. case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK:
  1106. case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK: {
  1107. return 2;
  1108. }
  1109. default: {
  1110. }
  1111. }
  1112. return 0;
  1113. }
  1114. bool RenderingDeviceVulkan::format_has_stencil(DataFormat p_format) {
  1115. switch (p_format) {
  1116. case DATA_FORMAT_S8_UINT:
  1117. case DATA_FORMAT_D16_UNORM_S8_UINT:
  1118. case DATA_FORMAT_D24_UNORM_S8_UINT:
  1119. case DATA_FORMAT_D32_SFLOAT_S8_UINT: {
  1120. return true;
  1121. }
  1122. default: {
  1123. }
  1124. }
  1125. return false;
  1126. }
  1127. uint32_t RenderingDeviceVulkan::get_image_format_required_size(DataFormat p_format, uint32_t p_width, uint32_t p_height, uint32_t p_depth, uint32_t p_mipmaps, uint32_t *r_blockw, uint32_t *r_blockh, uint32_t *r_depth) {
  1128. ERR_FAIL_COND_V(p_mipmaps == 0, 0);
  1129. uint32_t w = p_width;
  1130. uint32_t h = p_height;
  1131. uint32_t d = p_depth;
  1132. uint32_t size = 0;
  1133. uint32_t pixel_size = get_image_format_pixel_size(p_format);
  1134. uint32_t pixel_rshift = get_compressed_image_format_pixel_rshift(p_format);
  1135. uint32_t blockw, blockh;
  1136. get_compressed_image_format_block_dimensions(p_format, blockw, blockh);
  1137. for (uint32_t i = 0; i < p_mipmaps; i++) {
  1138. uint32_t bw = w % blockw != 0 ? w + (blockw - w % blockw) : w;
  1139. uint32_t bh = h % blockh != 0 ? h + (blockh - h % blockh) : h;
  1140. uint32_t s = bw * bh;
  1141. s *= pixel_size;
  1142. s >>= pixel_rshift;
  1143. size += s * d;
  1144. if (r_blockw) {
  1145. *r_blockw = bw;
  1146. }
  1147. if (r_blockh) {
  1148. *r_blockh = bh;
  1149. }
  1150. if (r_depth) {
  1151. *r_depth = d;
  1152. }
  1153. w = MAX(blockw, w >> 1);
  1154. h = MAX(blockh, h >> 1);
  1155. d = MAX(1u, d >> 1);
  1156. }
  1157. return size;
  1158. }
  1159. uint32_t RenderingDeviceVulkan::get_image_required_mipmaps(uint32_t p_width, uint32_t p_height, uint32_t p_depth) {
  1160. // Formats and block size don't really matter here since they can all go down to 1px (even if block is larger).
  1161. uint32_t w = p_width;
  1162. uint32_t h = p_height;
  1163. uint32_t d = p_depth;
  1164. uint32_t mipmaps = 1;
  1165. while (true) {
  1166. if (w == 1 && h == 1 && d == 1) {
  1167. break;
  1168. }
  1169. w = MAX(1u, w >> 1);
  1170. h = MAX(1u, h >> 1);
  1171. d = MAX(1u, d >> 1);
  1172. mipmaps++;
  1173. }
  1174. return mipmaps;
  1175. }
  1176. ///////////////////////
  1177. const VkCompareOp RenderingDeviceVulkan::compare_operators[RenderingDevice::COMPARE_OP_MAX] = {
  1178. VK_COMPARE_OP_NEVER,
  1179. VK_COMPARE_OP_LESS,
  1180. VK_COMPARE_OP_EQUAL,
  1181. VK_COMPARE_OP_LESS_OR_EQUAL,
  1182. VK_COMPARE_OP_GREATER,
  1183. VK_COMPARE_OP_NOT_EQUAL,
  1184. VK_COMPARE_OP_GREATER_OR_EQUAL,
  1185. VK_COMPARE_OP_ALWAYS
  1186. };
  1187. const VkStencilOp RenderingDeviceVulkan::stencil_operations[RenderingDevice::STENCIL_OP_MAX] = {
  1188. VK_STENCIL_OP_KEEP,
  1189. VK_STENCIL_OP_ZERO,
  1190. VK_STENCIL_OP_REPLACE,
  1191. VK_STENCIL_OP_INCREMENT_AND_CLAMP,
  1192. VK_STENCIL_OP_DECREMENT_AND_CLAMP,
  1193. VK_STENCIL_OP_INVERT,
  1194. VK_STENCIL_OP_INCREMENT_AND_WRAP,
  1195. VK_STENCIL_OP_DECREMENT_AND_WRAP
  1196. };
  1197. const VkSampleCountFlagBits RenderingDeviceVulkan::rasterization_sample_count[RenderingDevice::TEXTURE_SAMPLES_MAX] = {
  1198. VK_SAMPLE_COUNT_1_BIT,
  1199. VK_SAMPLE_COUNT_2_BIT,
  1200. VK_SAMPLE_COUNT_4_BIT,
  1201. VK_SAMPLE_COUNT_8_BIT,
  1202. VK_SAMPLE_COUNT_16_BIT,
  1203. VK_SAMPLE_COUNT_32_BIT,
  1204. VK_SAMPLE_COUNT_64_BIT,
  1205. };
  1206. const VkLogicOp RenderingDeviceVulkan::logic_operations[RenderingDevice::LOGIC_OP_MAX] = {
  1207. VK_LOGIC_OP_CLEAR,
  1208. VK_LOGIC_OP_AND,
  1209. VK_LOGIC_OP_AND_REVERSE,
  1210. VK_LOGIC_OP_COPY,
  1211. VK_LOGIC_OP_AND_INVERTED,
  1212. VK_LOGIC_OP_NO_OP,
  1213. VK_LOGIC_OP_XOR,
  1214. VK_LOGIC_OP_OR,
  1215. VK_LOGIC_OP_NOR,
  1216. VK_LOGIC_OP_EQUIVALENT,
  1217. VK_LOGIC_OP_INVERT,
  1218. VK_LOGIC_OP_OR_REVERSE,
  1219. VK_LOGIC_OP_COPY_INVERTED,
  1220. VK_LOGIC_OP_OR_INVERTED,
  1221. VK_LOGIC_OP_NAND,
  1222. VK_LOGIC_OP_SET
  1223. };
  1224. const VkBlendFactor RenderingDeviceVulkan::blend_factors[RenderingDevice::BLEND_FACTOR_MAX] = {
  1225. VK_BLEND_FACTOR_ZERO,
  1226. VK_BLEND_FACTOR_ONE,
  1227. VK_BLEND_FACTOR_SRC_COLOR,
  1228. VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR,
  1229. VK_BLEND_FACTOR_DST_COLOR,
  1230. VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR,
  1231. VK_BLEND_FACTOR_SRC_ALPHA,
  1232. VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
  1233. VK_BLEND_FACTOR_DST_ALPHA,
  1234. VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA,
  1235. VK_BLEND_FACTOR_CONSTANT_COLOR,
  1236. VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR,
  1237. VK_BLEND_FACTOR_CONSTANT_ALPHA,
  1238. VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA,
  1239. VK_BLEND_FACTOR_SRC_ALPHA_SATURATE,
  1240. VK_BLEND_FACTOR_SRC1_COLOR,
  1241. VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR,
  1242. VK_BLEND_FACTOR_SRC1_ALPHA,
  1243. VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA
  1244. };
  1245. const VkBlendOp RenderingDeviceVulkan::blend_operations[RenderingDevice::BLEND_OP_MAX] = {
  1246. VK_BLEND_OP_ADD,
  1247. VK_BLEND_OP_SUBTRACT,
  1248. VK_BLEND_OP_REVERSE_SUBTRACT,
  1249. VK_BLEND_OP_MIN,
  1250. VK_BLEND_OP_MAX
  1251. };
  1252. const VkSamplerAddressMode RenderingDeviceVulkan::address_modes[RenderingDevice::SAMPLER_REPEAT_MODE_MAX] = {
  1253. VK_SAMPLER_ADDRESS_MODE_REPEAT,
  1254. VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT,
  1255. VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
  1256. VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
  1257. VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE
  1258. };
  1259. const VkBorderColor RenderingDeviceVulkan::sampler_border_colors[RenderingDevice::SAMPLER_BORDER_COLOR_MAX] = {
  1260. VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK,
  1261. VK_BORDER_COLOR_INT_TRANSPARENT_BLACK,
  1262. VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK,
  1263. VK_BORDER_COLOR_INT_OPAQUE_BLACK,
  1264. VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
  1265. VK_BORDER_COLOR_INT_OPAQUE_WHITE
  1266. };
  1267. const VkImageType RenderingDeviceVulkan::vulkan_image_type[RenderingDevice::TEXTURE_TYPE_MAX] = {
  1268. VK_IMAGE_TYPE_1D,
  1269. VK_IMAGE_TYPE_2D,
  1270. VK_IMAGE_TYPE_3D,
  1271. VK_IMAGE_TYPE_2D,
  1272. VK_IMAGE_TYPE_1D,
  1273. VK_IMAGE_TYPE_2D,
  1274. VK_IMAGE_TYPE_2D
  1275. };
  1276. /***************************/
  1277. /**** BUFFER MANAGEMENT ****/
  1278. /***************************/
  1279. Error RenderingDeviceVulkan::_buffer_allocate(Buffer *p_buffer, uint32_t p_size, uint32_t p_usage, VmaMemoryUsage p_mem_usage, VmaAllocationCreateFlags p_mem_flags) {
  1280. VkBufferCreateInfo bufferInfo;
  1281. bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  1282. bufferInfo.pNext = nullptr;
  1283. bufferInfo.flags = 0;
  1284. bufferInfo.size = p_size;
  1285. bufferInfo.usage = p_usage;
  1286. bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1287. bufferInfo.queueFamilyIndexCount = 0;
  1288. bufferInfo.pQueueFamilyIndices = nullptr;
  1289. VmaAllocationCreateInfo allocInfo;
  1290. allocInfo.flags = p_mem_flags;
  1291. allocInfo.usage = p_mem_usage;
  1292. allocInfo.requiredFlags = 0;
  1293. allocInfo.preferredFlags = 0;
  1294. allocInfo.memoryTypeBits = 0;
  1295. allocInfo.pool = nullptr;
  1296. allocInfo.pUserData = nullptr;
  1297. if (p_size <= SMALL_ALLOCATION_MAX_SIZE) {
  1298. uint32_t mem_type_index = 0;
  1299. vmaFindMemoryTypeIndexForBufferInfo(allocator, &bufferInfo, &allocInfo, &mem_type_index);
  1300. allocInfo.pool = _find_or_create_small_allocs_pool(mem_type_index);
  1301. }
  1302. VkResult err = vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &p_buffer->buffer, &p_buffer->allocation, nullptr);
  1303. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "Can't create buffer of size: " + itos(p_size) + ", error " + itos(err) + ".");
  1304. p_buffer->size = p_size;
  1305. p_buffer->buffer_info.buffer = p_buffer->buffer;
  1306. p_buffer->buffer_info.offset = 0;
  1307. p_buffer->buffer_info.range = p_size;
  1308. p_buffer->usage = p_usage;
  1309. buffer_memory += p_size;
  1310. return OK;
  1311. }
  1312. Error RenderingDeviceVulkan::_buffer_free(Buffer *p_buffer) {
  1313. ERR_FAIL_COND_V(p_buffer->size == 0, ERR_INVALID_PARAMETER);
  1314. buffer_memory -= p_buffer->size;
  1315. vmaDestroyBuffer(allocator, p_buffer->buffer, p_buffer->allocation);
  1316. p_buffer->buffer = VK_NULL_HANDLE;
  1317. p_buffer->allocation = nullptr;
  1318. p_buffer->size = 0;
  1319. return OK;
  1320. }
  1321. Error RenderingDeviceVulkan::_insert_staging_block() {
  1322. VkBufferCreateInfo bufferInfo;
  1323. bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  1324. bufferInfo.pNext = nullptr;
  1325. bufferInfo.flags = 0;
  1326. bufferInfo.size = staging_buffer_block_size;
  1327. bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  1328. bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1329. bufferInfo.queueFamilyIndexCount = 0;
  1330. bufferInfo.pQueueFamilyIndices = nullptr;
  1331. VmaAllocationCreateInfo allocInfo;
  1332. allocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
  1333. allocInfo.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST;
  1334. allocInfo.requiredFlags = 0;
  1335. allocInfo.preferredFlags = 0;
  1336. allocInfo.memoryTypeBits = 0;
  1337. allocInfo.pool = nullptr;
  1338. allocInfo.pUserData = nullptr;
  1339. StagingBufferBlock block;
  1340. VkResult err = vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &block.buffer, &block.allocation, nullptr);
  1341. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vmaCreateBuffer failed with error " + itos(err) + ".");
  1342. block.frame_used = 0;
  1343. block.fill_amount = 0;
  1344. staging_buffer_blocks.insert(staging_buffer_current, block);
  1345. return OK;
  1346. }
  1347. Error RenderingDeviceVulkan::_staging_buffer_allocate(uint32_t p_amount, uint32_t p_required_align, uint32_t &r_alloc_offset, uint32_t &r_alloc_size, bool p_can_segment) {
  1348. // Determine a block to use.
  1349. r_alloc_size = p_amount;
  1350. while (true) {
  1351. r_alloc_offset = 0;
  1352. // See if we can use current block.
  1353. if (staging_buffer_blocks[staging_buffer_current].frame_used == frames_drawn) {
  1354. // We used this block this frame, let's see if there is still room.
  1355. uint32_t write_from = staging_buffer_blocks[staging_buffer_current].fill_amount;
  1356. {
  1357. uint32_t align_remainder = write_from % p_required_align;
  1358. if (align_remainder != 0) {
  1359. write_from += p_required_align - align_remainder;
  1360. }
  1361. }
  1362. int32_t available_bytes = int32_t(staging_buffer_block_size) - int32_t(write_from);
  1363. if ((int32_t)p_amount < available_bytes) {
  1364. // All is good, we should be ok, all will fit.
  1365. r_alloc_offset = write_from;
  1366. } else if (p_can_segment && available_bytes >= (int32_t)p_required_align) {
  1367. // Ok all won't fit but at least we can fit a chunkie.
  1368. // All is good, update what needs to be written to.
  1369. r_alloc_offset = write_from;
  1370. r_alloc_size = available_bytes - (available_bytes % p_required_align);
  1371. } else {
  1372. // Can't fit it into this buffer.
  1373. // Will need to try next buffer.
  1374. staging_buffer_current = (staging_buffer_current + 1) % staging_buffer_blocks.size();
  1375. // Before doing anything, though, let's check that we didn't manage to fill all blocks.
  1376. // Possible in a single frame.
  1377. if (staging_buffer_blocks[staging_buffer_current].frame_used == frames_drawn) {
  1378. // Guess we did.. ok, let's see if we can insert a new block.
  1379. if ((uint64_t)staging_buffer_blocks.size() * staging_buffer_block_size < staging_buffer_max_size) {
  1380. // We can, so we are safe.
  1381. Error err = _insert_staging_block();
  1382. if (err) {
  1383. return err;
  1384. }
  1385. // Claim for this frame.
  1386. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  1387. } else {
  1388. // Ok, worst case scenario, all the staging buffers belong to this frame
  1389. // and this frame is not even done.
  1390. // If this is the main thread, it means the user is likely loading a lot of resources at once,.
  1391. // Otherwise, the thread should just be blocked until the next frame (currently unimplemented).
  1392. if (false) { // Separate thread from render.
  1393. //block_until_next_frame()
  1394. continue;
  1395. } else {
  1396. // Flush EVERYTHING including setup commands. IF not immediate, also need to flush the draw commands.
  1397. _flush(true);
  1398. // Clear the whole staging buffer.
  1399. for (int i = 0; i < staging_buffer_blocks.size(); i++) {
  1400. staging_buffer_blocks.write[i].frame_used = 0;
  1401. staging_buffer_blocks.write[i].fill_amount = 0;
  1402. }
  1403. // Claim current.
  1404. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  1405. }
  1406. }
  1407. } else {
  1408. // Not from current frame, so continue and try again.
  1409. continue;
  1410. }
  1411. }
  1412. } else if (staging_buffer_blocks[staging_buffer_current].frame_used <= frames_drawn - frame_count) {
  1413. // This is an old block, which was already processed, let's reuse.
  1414. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  1415. staging_buffer_blocks.write[staging_buffer_current].fill_amount = 0;
  1416. } else {
  1417. // This block may still be in use, let's not touch it unless we have to, so.. can we create a new one?
  1418. if ((uint64_t)staging_buffer_blocks.size() * staging_buffer_block_size < staging_buffer_max_size) {
  1419. // We are still allowed to create a new block, so let's do that and insert it for current pos.
  1420. Error err = _insert_staging_block();
  1421. if (err) {
  1422. return err;
  1423. }
  1424. // Claim for this frame.
  1425. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  1426. } else {
  1427. // Oops, we are out of room and we can't create more.
  1428. // Let's flush older frames.
  1429. // The logic here is that if a game is loading a lot of data from the main thread, it will need to be stalled anyway.
  1430. // If loading from a separate thread, we can block that thread until next frame when more room is made (not currently implemented, though).
  1431. if (false) {
  1432. // Separate thread from render.
  1433. //block_until_next_frame()
  1434. continue; // And try again.
  1435. } else {
  1436. _flush(false);
  1437. for (int i = 0; i < staging_buffer_blocks.size(); i++) {
  1438. // Clear all blocks but the ones from this frame.
  1439. int block_idx = (i + staging_buffer_current) % staging_buffer_blocks.size();
  1440. if (staging_buffer_blocks[block_idx].frame_used == frames_drawn) {
  1441. break; // Ok, we reached something from this frame, abort.
  1442. }
  1443. staging_buffer_blocks.write[block_idx].frame_used = 0;
  1444. staging_buffer_blocks.write[block_idx].fill_amount = 0;
  1445. }
  1446. // Claim for current frame.
  1447. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  1448. }
  1449. }
  1450. }
  1451. // All was good, break.
  1452. break;
  1453. }
  1454. staging_buffer_used = true;
  1455. return OK;
  1456. }
  1457. Error RenderingDeviceVulkan::_buffer_update(Buffer *p_buffer, size_t p_offset, const uint8_t *p_data, size_t p_data_size, bool p_use_draw_command_buffer, uint32_t p_required_align) {
  1458. // Submitting may get chunked for various reasons, so convert this to a task.
  1459. size_t to_submit = p_data_size;
  1460. size_t submit_from = 0;
  1461. while (to_submit > 0) {
  1462. uint32_t block_write_offset;
  1463. uint32_t block_write_amount;
  1464. Error err = _staging_buffer_allocate(MIN(to_submit, staging_buffer_block_size), p_required_align, block_write_offset, block_write_amount);
  1465. if (err) {
  1466. return err;
  1467. }
  1468. // Map staging buffer (It's CPU and coherent).
  1469. void *data_ptr = nullptr;
  1470. {
  1471. VkResult vkerr = vmaMapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation, &data_ptr);
  1472. ERR_FAIL_COND_V_MSG(vkerr, ERR_CANT_CREATE, "vmaMapMemory failed with error " + itos(vkerr) + ".");
  1473. }
  1474. // Copy to staging buffer.
  1475. memcpy(((uint8_t *)data_ptr) + block_write_offset, p_data + submit_from, block_write_amount);
  1476. // Unmap.
  1477. vmaUnmapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation);
  1478. // Insert a command to copy this.
  1479. VkBufferCopy region;
  1480. region.srcOffset = block_write_offset;
  1481. region.dstOffset = submit_from + p_offset;
  1482. region.size = block_write_amount;
  1483. vkCmdCopyBuffer(p_use_draw_command_buffer ? frames[frame].draw_command_buffer : frames[frame].setup_command_buffer, staging_buffer_blocks[staging_buffer_current].buffer, p_buffer->buffer, 1, &region);
  1484. staging_buffer_blocks.write[staging_buffer_current].fill_amount = block_write_offset + block_write_amount;
  1485. to_submit -= block_write_amount;
  1486. submit_from += block_write_amount;
  1487. }
  1488. return OK;
  1489. }
  1490. void RenderingDeviceVulkan::_memory_barrier(VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_sccess, bool p_sync_with_draw) {
  1491. VkMemoryBarrier mem_barrier;
  1492. mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  1493. mem_barrier.pNext = nullptr;
  1494. mem_barrier.srcAccessMask = p_src_access;
  1495. mem_barrier.dstAccessMask = p_dst_sccess;
  1496. if (p_src_stage_mask == 0 || p_dst_stage_mask == 0) {
  1497. return; // No barrier, since this is invalid.
  1498. }
  1499. vkCmdPipelineBarrier(p_sync_with_draw ? frames[frame].draw_command_buffer : frames[frame].setup_command_buffer, p_src_stage_mask, p_dst_stage_mask, 0, 1, &mem_barrier, 0, nullptr, 0, nullptr);
  1500. }
  1501. void RenderingDeviceVulkan::_full_barrier(bool p_sync_with_draw) {
  1502. // Used for debug.
  1503. _memory_barrier(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
  1504. VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  1505. VK_ACCESS_INDEX_READ_BIT |
  1506. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  1507. VK_ACCESS_UNIFORM_READ_BIT |
  1508. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  1509. VK_ACCESS_SHADER_READ_BIT |
  1510. VK_ACCESS_SHADER_WRITE_BIT |
  1511. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  1512. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  1513. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  1514. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  1515. VK_ACCESS_TRANSFER_READ_BIT |
  1516. VK_ACCESS_TRANSFER_WRITE_BIT |
  1517. VK_ACCESS_HOST_READ_BIT |
  1518. VK_ACCESS_HOST_WRITE_BIT,
  1519. VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  1520. VK_ACCESS_INDEX_READ_BIT |
  1521. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  1522. VK_ACCESS_UNIFORM_READ_BIT |
  1523. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  1524. VK_ACCESS_SHADER_READ_BIT |
  1525. VK_ACCESS_SHADER_WRITE_BIT |
  1526. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  1527. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  1528. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  1529. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  1530. VK_ACCESS_TRANSFER_READ_BIT |
  1531. VK_ACCESS_TRANSFER_WRITE_BIT |
  1532. VK_ACCESS_HOST_READ_BIT |
  1533. VK_ACCESS_HOST_WRITE_BIT,
  1534. p_sync_with_draw);
  1535. }
  1536. void RenderingDeviceVulkan::_buffer_memory_barrier(VkBuffer buffer, uint64_t p_from, uint64_t p_size, VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_sccess, bool p_sync_with_draw) {
  1537. VkBufferMemoryBarrier buffer_mem_barrier;
  1538. buffer_mem_barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
  1539. buffer_mem_barrier.pNext = nullptr;
  1540. buffer_mem_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  1541. buffer_mem_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  1542. buffer_mem_barrier.srcAccessMask = p_src_access;
  1543. buffer_mem_barrier.dstAccessMask = p_dst_sccess;
  1544. buffer_mem_barrier.buffer = buffer;
  1545. buffer_mem_barrier.offset = p_from;
  1546. buffer_mem_barrier.size = p_size;
  1547. vkCmdPipelineBarrier(p_sync_with_draw ? frames[frame].draw_command_buffer : frames[frame].setup_command_buffer, p_src_stage_mask, p_dst_stage_mask, 0, 0, nullptr, 1, &buffer_mem_barrier, 0, nullptr);
  1548. }
  1549. /*****************/
  1550. /**** TEXTURE ****/
  1551. /*****************/
  1552. RID RenderingDeviceVulkan::texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector<Vector<uint8_t>> &p_data) {
  1553. _THREAD_SAFE_METHOD_
  1554. VkImageCreateInfo image_create_info;
  1555. image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  1556. image_create_info.pNext = nullptr;
  1557. image_create_info.flags = 0;
  1558. #ifndef _MSC_VER
  1559. #warning TODO check for support via RenderingDevice to enable on mobile when possible
  1560. #endif
  1561. #ifndef ANDROID_ENABLED
  1562. // vkCreateImage fails with format list on Android (VK_ERROR_OUT_OF_HOST_MEMORY)
  1563. VkImageFormatListCreateInfoKHR format_list_create_info; // Keep out of the if, needed for creation.
  1564. Vector<VkFormat> allowed_formats; // Keep out of the if, needed for creation.
  1565. #endif
  1566. if (p_format.shareable_formats.size()) {
  1567. image_create_info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
  1568. #ifndef ANDROID_ENABLED
  1569. for (int i = 0; i < p_format.shareable_formats.size(); i++) {
  1570. allowed_formats.push_back(vulkan_formats[p_format.shareable_formats[i]]);
  1571. }
  1572. format_list_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO_KHR;
  1573. format_list_create_info.pNext = nullptr;
  1574. format_list_create_info.viewFormatCount = allowed_formats.size();
  1575. format_list_create_info.pViewFormats = allowed_formats.ptr();
  1576. image_create_info.pNext = &format_list_create_info;
  1577. ERR_FAIL_COND_V_MSG(p_format.shareable_formats.find(p_format.format) == -1, RID(),
  1578. "If supplied a list of shareable formats, the current format must be present in the list");
  1579. ERR_FAIL_COND_V_MSG(p_view.format_override != DATA_FORMAT_MAX && p_format.shareable_formats.find(p_view.format_override) == -1, RID(),
  1580. "If supplied a list of shareable formats, the current view format override must be present in the list");
  1581. #endif
  1582. }
  1583. if (p_format.texture_type == TEXTURE_TYPE_CUBE || p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY) {
  1584. image_create_info.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
  1585. }
  1586. /*if (p_format.type == TEXTURE_TYPE_2D || p_format.type == TEXTURE_TYPE_2D_ARRAY) {
  1587. image_create_info.flags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT;
  1588. }*/
  1589. ERR_FAIL_INDEX_V(p_format.texture_type, TEXTURE_TYPE_MAX, RID());
  1590. image_create_info.imageType = vulkan_image_type[p_format.texture_type];
  1591. ERR_FAIL_COND_V_MSG(p_format.width < 1, RID(), "Width must be equal or greater than 1 for all textures");
  1592. image_create_info.format = vulkan_formats[p_format.format];
  1593. image_create_info.extent.width = p_format.width;
  1594. if (image_create_info.imageType == VK_IMAGE_TYPE_3D || image_create_info.imageType == VK_IMAGE_TYPE_2D) {
  1595. ERR_FAIL_COND_V_MSG(p_format.height < 1, RID(), "Height must be equal or greater than 1 for 2D and 3D textures");
  1596. image_create_info.extent.height = p_format.height;
  1597. } else {
  1598. image_create_info.extent.height = 1;
  1599. }
  1600. if (image_create_info.imageType == VK_IMAGE_TYPE_3D) {
  1601. ERR_FAIL_COND_V_MSG(p_format.depth < 1, RID(), "Depth must be equal or greater than 1 for 3D textures");
  1602. image_create_info.extent.depth = p_format.depth;
  1603. } else {
  1604. image_create_info.extent.depth = 1;
  1605. }
  1606. ERR_FAIL_COND_V(p_format.mipmaps < 1, RID());
  1607. image_create_info.mipLevels = p_format.mipmaps;
  1608. if (p_format.texture_type == TEXTURE_TYPE_1D_ARRAY || p_format.texture_type == TEXTURE_TYPE_2D_ARRAY || p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || p_format.texture_type == TEXTURE_TYPE_CUBE) {
  1609. ERR_FAIL_COND_V_MSG(p_format.array_layers < 1, RID(),
  1610. "Amount of layers must be equal or greater than 1 for arrays and cubemaps.");
  1611. ERR_FAIL_COND_V_MSG((p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || p_format.texture_type == TEXTURE_TYPE_CUBE) && (p_format.array_layers % 6) != 0, RID(),
  1612. "Cubemap and cubemap array textures must provide a layer number that is multiple of 6");
  1613. image_create_info.arrayLayers = p_format.array_layers;
  1614. } else {
  1615. image_create_info.arrayLayers = 1;
  1616. }
  1617. ERR_FAIL_INDEX_V(p_format.samples, TEXTURE_SAMPLES_MAX, RID());
  1618. image_create_info.samples = _ensure_supported_sample_count(p_format.samples);
  1619. image_create_info.tiling = (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) ? VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
  1620. // Usage.
  1621. image_create_info.usage = 0;
  1622. if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) {
  1623. image_create_info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
  1624. }
  1625. if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) {
  1626. image_create_info.usage |= VK_IMAGE_USAGE_STORAGE_BIT;
  1627. }
  1628. if (p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  1629. image_create_info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  1630. }
  1631. if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1632. image_create_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  1633. }
  1634. if (p_format.usage_bits & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT) {
  1635. image_create_info.usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
  1636. }
  1637. if (p_format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) {
  1638. image_create_info.usage |= VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR;
  1639. }
  1640. if (p_format.usage_bits & TEXTURE_USAGE_CAN_UPDATE_BIT) {
  1641. image_create_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1642. }
  1643. if (p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_FROM_BIT) {
  1644. image_create_info.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
  1645. }
  1646. if (p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_TO_BIT) {
  1647. image_create_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1648. }
  1649. image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1650. image_create_info.queueFamilyIndexCount = 0;
  1651. image_create_info.pQueueFamilyIndices = nullptr;
  1652. image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  1653. uint32_t required_mipmaps = get_image_required_mipmaps(image_create_info.extent.width, image_create_info.extent.height, image_create_info.extent.depth);
  1654. ERR_FAIL_COND_V_MSG(required_mipmaps < image_create_info.mipLevels, RID(),
  1655. "Too many mipmaps requested for texture format and dimensions (" + itos(image_create_info.mipLevels) + "), maximum allowed: (" + itos(required_mipmaps) + ").");
  1656. if (p_data.size()) {
  1657. ERR_FAIL_COND_V_MSG(!(p_format.usage_bits & TEXTURE_USAGE_CAN_UPDATE_BIT), RID(),
  1658. "Texture needs the TEXTURE_USAGE_CAN_UPDATE_BIT usage flag in order to be updated at initialization or later");
  1659. int expected_images = image_create_info.arrayLayers;
  1660. ERR_FAIL_COND_V_MSG(p_data.size() != expected_images, RID(),
  1661. "Default supplied data for image format is of invalid length (" + itos(p_data.size()) + "), should be (" + itos(expected_images) + ").");
  1662. for (uint32_t i = 0; i < image_create_info.arrayLayers; i++) {
  1663. uint32_t required_size = get_image_format_required_size(p_format.format, image_create_info.extent.width, image_create_info.extent.height, image_create_info.extent.depth, image_create_info.mipLevels);
  1664. ERR_FAIL_COND_V_MSG((uint32_t)p_data[i].size() != required_size, RID(),
  1665. "Data for slice index " + itos(i) + " (mapped to layer " + itos(i) + ") differs in size (supplied: " + itos(p_data[i].size()) + ") than what is required by the format (" + itos(required_size) + ").");
  1666. }
  1667. }
  1668. {
  1669. // Validate that this image is supported for the intended use.
  1670. VkFormatProperties properties;
  1671. vkGetPhysicalDeviceFormatProperties(context->get_physical_device(), image_create_info.format, &properties);
  1672. VkFormatFeatureFlags flags;
  1673. String format_text = "'" + String(named_formats[p_format.format]) + "'";
  1674. if (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) {
  1675. flags = properties.linearTilingFeatures;
  1676. format_text += " (with CPU read bit)";
  1677. } else {
  1678. flags = properties.optimalTilingFeatures;
  1679. }
  1680. if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT && !(flags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) {
  1681. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as sampling texture.");
  1682. }
  1683. if (p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) {
  1684. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as color attachment.");
  1685. }
  1686. if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  1687. printf("vkformat: %x\n", image_create_info.format);
  1688. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as depth-stencil attachment.");
  1689. }
  1690. if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) {
  1691. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as storage image.");
  1692. }
  1693. if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_ATOMIC_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT)) {
  1694. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as atomic storage image.");
  1695. }
  1696. // Validation via VK_FORMAT_FEATURE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR fails if VRS attachment is not supported.
  1697. if (p_format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT && p_format.format != DATA_FORMAT_R8_UINT) {
  1698. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as VRS attachment.");
  1699. }
  1700. }
  1701. // Some view validation.
  1702. if (p_view.format_override != DATA_FORMAT_MAX) {
  1703. ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());
  1704. }
  1705. ERR_FAIL_INDEX_V(p_view.swizzle_r, TEXTURE_SWIZZLE_MAX, RID());
  1706. ERR_FAIL_INDEX_V(p_view.swizzle_g, TEXTURE_SWIZZLE_MAX, RID());
  1707. ERR_FAIL_INDEX_V(p_view.swizzle_b, TEXTURE_SWIZZLE_MAX, RID());
  1708. ERR_FAIL_INDEX_V(p_view.swizzle_a, TEXTURE_SWIZZLE_MAX, RID());
  1709. // Allocate memory.
  1710. uint32_t width, height;
  1711. uint32_t image_size = get_image_format_required_size(p_format.format, p_format.width, p_format.height, p_format.depth, p_format.mipmaps, &width, &height);
  1712. VmaAllocationCreateInfo allocInfo;
  1713. allocInfo.flags = (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) ? VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT : 0;
  1714. allocInfo.pool = nullptr;
  1715. allocInfo.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE;
  1716. allocInfo.requiredFlags = 0;
  1717. allocInfo.preferredFlags = 0;
  1718. allocInfo.memoryTypeBits = 0;
  1719. allocInfo.pUserData = nullptr;
  1720. if (image_size <= SMALL_ALLOCATION_MAX_SIZE) {
  1721. uint32_t mem_type_index = 0;
  1722. vmaFindMemoryTypeIndexForImageInfo(allocator, &image_create_info, &allocInfo, &mem_type_index);
  1723. allocInfo.pool = _find_or_create_small_allocs_pool(mem_type_index);
  1724. }
  1725. Texture texture;
  1726. VkResult err = vmaCreateImage(allocator, &image_create_info, &allocInfo, &texture.image, &texture.allocation, &texture.allocation_info);
  1727. ERR_FAIL_COND_V_MSG(err, RID(), "vmaCreateImage failed with error " + itos(err) + ".");
  1728. image_memory += texture.allocation_info.size;
  1729. texture.type = p_format.texture_type;
  1730. texture.format = p_format.format;
  1731. texture.width = image_create_info.extent.width;
  1732. texture.height = image_create_info.extent.height;
  1733. texture.depth = image_create_info.extent.depth;
  1734. texture.layers = image_create_info.arrayLayers;
  1735. texture.mipmaps = image_create_info.mipLevels;
  1736. texture.base_mipmap = 0;
  1737. texture.base_layer = 0;
  1738. texture.is_resolve_buffer = p_format.is_resolve_buffer;
  1739. texture.usage_flags = p_format.usage_bits;
  1740. texture.samples = p_format.samples;
  1741. texture.allowed_shared_formats = p_format.shareable_formats;
  1742. // Set base layout based on usage priority.
  1743. if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) {
  1744. // First priority, readable.
  1745. texture.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  1746. } else if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) {
  1747. // Second priority, storage.
  1748. texture.layout = VK_IMAGE_LAYOUT_GENERAL;
  1749. } else if (p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  1750. // Third priority, color or depth.
  1751. texture.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1752. } else if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1753. texture.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  1754. } else {
  1755. texture.layout = VK_IMAGE_LAYOUT_GENERAL;
  1756. }
  1757. if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1758. texture.read_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1759. texture.barrier_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1760. if (format_has_stencil(p_format.format)) {
  1761. texture.barrier_aspect_mask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  1762. }
  1763. } else {
  1764. texture.read_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT;
  1765. texture.barrier_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT;
  1766. }
  1767. texture.bound = false;
  1768. // Create view.
  1769. VkImageViewCreateInfo image_view_create_info;
  1770. image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1771. image_view_create_info.pNext = nullptr;
  1772. image_view_create_info.flags = 0;
  1773. image_view_create_info.image = texture.image;
  1774. static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = {
  1775. VK_IMAGE_VIEW_TYPE_1D,
  1776. VK_IMAGE_VIEW_TYPE_2D,
  1777. VK_IMAGE_VIEW_TYPE_3D,
  1778. VK_IMAGE_VIEW_TYPE_CUBE,
  1779. VK_IMAGE_VIEW_TYPE_1D_ARRAY,
  1780. VK_IMAGE_VIEW_TYPE_2D_ARRAY,
  1781. VK_IMAGE_VIEW_TYPE_CUBE_ARRAY,
  1782. };
  1783. image_view_create_info.viewType = view_types[p_format.texture_type];
  1784. if (p_view.format_override == DATA_FORMAT_MAX) {
  1785. image_view_create_info.format = image_create_info.format;
  1786. } else {
  1787. image_view_create_info.format = vulkan_formats[p_view.format_override];
  1788. }
  1789. static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  1790. VK_COMPONENT_SWIZZLE_IDENTITY,
  1791. VK_COMPONENT_SWIZZLE_ZERO,
  1792. VK_COMPONENT_SWIZZLE_ONE,
  1793. VK_COMPONENT_SWIZZLE_R,
  1794. VK_COMPONENT_SWIZZLE_G,
  1795. VK_COMPONENT_SWIZZLE_B,
  1796. VK_COMPONENT_SWIZZLE_A
  1797. };
  1798. image_view_create_info.components.r = component_swizzles[p_view.swizzle_r];
  1799. image_view_create_info.components.g = component_swizzles[p_view.swizzle_g];
  1800. image_view_create_info.components.b = component_swizzles[p_view.swizzle_b];
  1801. image_view_create_info.components.a = component_swizzles[p_view.swizzle_a];
  1802. image_view_create_info.subresourceRange.baseMipLevel = 0;
  1803. image_view_create_info.subresourceRange.levelCount = image_create_info.mipLevels;
  1804. image_view_create_info.subresourceRange.baseArrayLayer = 0;
  1805. image_view_create_info.subresourceRange.layerCount = image_create_info.arrayLayers;
  1806. if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1807. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1808. } else {
  1809. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  1810. }
  1811. err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view);
  1812. if (err) {
  1813. vmaDestroyImage(allocator, texture.image, texture.allocation);
  1814. ERR_FAIL_V_MSG(RID(), "vkCreateImageView failed with error " + itos(err) + ".");
  1815. }
  1816. // Barrier to set layout.
  1817. {
  1818. VkImageMemoryBarrier image_memory_barrier;
  1819. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  1820. image_memory_barrier.pNext = nullptr;
  1821. image_memory_barrier.srcAccessMask = 0;
  1822. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  1823. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  1824. image_memory_barrier.newLayout = texture.layout;
  1825. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  1826. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  1827. image_memory_barrier.image = texture.image;
  1828. image_memory_barrier.subresourceRange.aspectMask = texture.barrier_aspect_mask;
  1829. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  1830. image_memory_barrier.subresourceRange.levelCount = image_create_info.mipLevels;
  1831. image_memory_barrier.subresourceRange.baseArrayLayer = 0;
  1832. image_memory_barrier.subresourceRange.layerCount = image_create_info.arrayLayers;
  1833. vkCmdPipelineBarrier(frames[frame].setup_command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  1834. }
  1835. RID id = texture_owner.make_rid(texture);
  1836. #ifdef DEV_ENABLED
  1837. set_resource_name(id, "RID:" + itos(id.get_id()));
  1838. #endif
  1839. if (p_data.size()) {
  1840. for (uint32_t i = 0; i < image_create_info.arrayLayers; i++) {
  1841. _texture_update(id, i, p_data[i], RD::BARRIER_MASK_ALL, true);
  1842. }
  1843. }
  1844. return id;
  1845. }
  1846. RID RenderingDeviceVulkan::texture_create_shared(const TextureView &p_view, RID p_with_texture) {
  1847. _THREAD_SAFE_METHOD_
  1848. Texture *src_texture = texture_owner.get_or_null(p_with_texture);
  1849. ERR_FAIL_COND_V(!src_texture, RID());
  1850. if (src_texture->owner.is_valid()) { // Ahh this is a share.
  1851. p_with_texture = src_texture->owner;
  1852. src_texture = texture_owner.get_or_null(src_texture->owner);
  1853. ERR_FAIL_COND_V(!src_texture, RID()); // This is a bug.
  1854. }
  1855. // Create view.
  1856. Texture texture = *src_texture;
  1857. VkImageViewCreateInfo image_view_create_info;
  1858. image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1859. image_view_create_info.pNext = nullptr;
  1860. image_view_create_info.flags = 0;
  1861. image_view_create_info.image = texture.image;
  1862. static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = {
  1863. VK_IMAGE_VIEW_TYPE_1D,
  1864. VK_IMAGE_VIEW_TYPE_2D,
  1865. VK_IMAGE_VIEW_TYPE_3D,
  1866. VK_IMAGE_VIEW_TYPE_CUBE,
  1867. VK_IMAGE_VIEW_TYPE_1D_ARRAY,
  1868. VK_IMAGE_VIEW_TYPE_2D_ARRAY,
  1869. VK_IMAGE_VIEW_TYPE_CUBE_ARRAY,
  1870. };
  1871. image_view_create_info.viewType = view_types[texture.type];
  1872. if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) {
  1873. image_view_create_info.format = vulkan_formats[texture.format];
  1874. } else {
  1875. ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());
  1876. ERR_FAIL_COND_V_MSG(texture.allowed_shared_formats.find(p_view.format_override) == -1, RID(),
  1877. "Format override is not in the list of allowed shareable formats for original texture.");
  1878. image_view_create_info.format = vulkan_formats[p_view.format_override];
  1879. }
  1880. static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  1881. VK_COMPONENT_SWIZZLE_IDENTITY,
  1882. VK_COMPONENT_SWIZZLE_ZERO,
  1883. VK_COMPONENT_SWIZZLE_ONE,
  1884. VK_COMPONENT_SWIZZLE_R,
  1885. VK_COMPONENT_SWIZZLE_G,
  1886. VK_COMPONENT_SWIZZLE_B,
  1887. VK_COMPONENT_SWIZZLE_A
  1888. };
  1889. image_view_create_info.components.r = component_swizzles[p_view.swizzle_r];
  1890. image_view_create_info.components.g = component_swizzles[p_view.swizzle_g];
  1891. image_view_create_info.components.b = component_swizzles[p_view.swizzle_b];
  1892. image_view_create_info.components.a = component_swizzles[p_view.swizzle_a];
  1893. image_view_create_info.subresourceRange.baseMipLevel = 0;
  1894. image_view_create_info.subresourceRange.levelCount = texture.mipmaps;
  1895. image_view_create_info.subresourceRange.layerCount = texture.layers;
  1896. image_view_create_info.subresourceRange.baseArrayLayer = 0;
  1897. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1898. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1899. } else {
  1900. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  1901. }
  1902. VkImageViewUsageCreateInfo usage_info;
  1903. usage_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO;
  1904. usage_info.pNext = nullptr;
  1905. if (p_view.format_override != DATA_FORMAT_MAX) {
  1906. // Need to validate usage with vulkan.
  1907. usage_info.usage = 0;
  1908. if (texture.usage_flags & TEXTURE_USAGE_SAMPLING_BIT) {
  1909. usage_info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
  1910. }
  1911. if (texture.usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  1912. if (texture_is_format_supported_for_usage(p_view.format_override, TEXTURE_USAGE_STORAGE_BIT)) {
  1913. usage_info.usage |= VK_IMAGE_USAGE_STORAGE_BIT;
  1914. }
  1915. }
  1916. if (texture.usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  1917. if (texture_is_format_supported_for_usage(p_view.format_override, TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) {
  1918. usage_info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  1919. }
  1920. }
  1921. if (texture.usage_flags & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT) {
  1922. usage_info.usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
  1923. }
  1924. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1925. usage_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  1926. }
  1927. if (texture.usage_flags & TEXTURE_USAGE_CAN_UPDATE_BIT) {
  1928. usage_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1929. }
  1930. if (texture.usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT) {
  1931. usage_info.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
  1932. }
  1933. if (texture.usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT) {
  1934. usage_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1935. }
  1936. image_view_create_info.pNext = &usage_info;
  1937. }
  1938. VkResult err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view);
  1939. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateImageView failed with error " + itos(err) + ".");
  1940. texture.owner = p_with_texture;
  1941. RID id = texture_owner.make_rid(texture);
  1942. #ifdef DEV_ENABLED
  1943. set_resource_name(id, "RID:" + itos(id.get_id()));
  1944. #endif
  1945. _add_dependency(id, p_with_texture);
  1946. return id;
  1947. }
  1948. RID RenderingDeviceVulkan::texture_create_from_extension(TextureType p_type, DataFormat p_format, TextureSamples p_samples, uint64_t p_flags, uint64_t p_image, uint64_t p_width, uint64_t p_height, uint64_t p_depth, uint64_t p_layers) {
  1949. _THREAD_SAFE_METHOD_
  1950. // This method creates a texture object using a VkImage created by an extension, module or other external source (OpenXR uses this).
  1951. VkImage image = (VkImage)p_image;
  1952. Texture texture;
  1953. texture.image = image;
  1954. // If we leave texture.allocation as a nullptr, would that be enough to detect we don't "own" the image?
  1955. // Also leave texture.allocation_info alone.
  1956. // We'll set texture.view later on.
  1957. texture.type = p_type;
  1958. texture.format = p_format;
  1959. texture.samples = p_samples;
  1960. texture.width = p_width;
  1961. texture.height = p_height;
  1962. texture.depth = p_depth;
  1963. texture.layers = p_layers;
  1964. texture.mipmaps = 0; // Maybe make this settable too?
  1965. texture.usage_flags = p_flags;
  1966. texture.base_mipmap = 0;
  1967. texture.base_layer = 0;
  1968. texture.allowed_shared_formats.push_back(RD::DATA_FORMAT_R8G8B8A8_UNORM);
  1969. texture.allowed_shared_formats.push_back(RD::DATA_FORMAT_R8G8B8A8_SRGB);
  1970. // Do we need to do something with texture.layout?
  1971. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1972. texture.read_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1973. texture.barrier_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1974. // if (format_has_stencil(p_format.format)) {
  1975. // texture.barrier_aspect_mask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  1976. // }
  1977. } else {
  1978. texture.read_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT;
  1979. texture.barrier_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT;
  1980. }
  1981. // Create a view for us to use.
  1982. VkImageViewCreateInfo image_view_create_info;
  1983. image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1984. image_view_create_info.pNext = nullptr;
  1985. image_view_create_info.flags = 0;
  1986. image_view_create_info.image = texture.image;
  1987. static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = {
  1988. VK_IMAGE_VIEW_TYPE_1D,
  1989. VK_IMAGE_VIEW_TYPE_2D,
  1990. VK_IMAGE_VIEW_TYPE_3D,
  1991. VK_IMAGE_VIEW_TYPE_CUBE,
  1992. VK_IMAGE_VIEW_TYPE_1D_ARRAY,
  1993. VK_IMAGE_VIEW_TYPE_2D_ARRAY,
  1994. VK_IMAGE_VIEW_TYPE_CUBE_ARRAY,
  1995. };
  1996. image_view_create_info.viewType = view_types[texture.type];
  1997. image_view_create_info.format = vulkan_formats[texture.format];
  1998. static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  1999. VK_COMPONENT_SWIZZLE_IDENTITY,
  2000. VK_COMPONENT_SWIZZLE_ZERO,
  2001. VK_COMPONENT_SWIZZLE_ONE,
  2002. VK_COMPONENT_SWIZZLE_R,
  2003. VK_COMPONENT_SWIZZLE_G,
  2004. VK_COMPONENT_SWIZZLE_B,
  2005. VK_COMPONENT_SWIZZLE_A
  2006. };
  2007. // Hardcode for now, maybe make this settable from outside.
  2008. image_view_create_info.components.r = component_swizzles[TEXTURE_SWIZZLE_R];
  2009. image_view_create_info.components.g = component_swizzles[TEXTURE_SWIZZLE_G];
  2010. image_view_create_info.components.b = component_swizzles[TEXTURE_SWIZZLE_B];
  2011. image_view_create_info.components.a = component_swizzles[TEXTURE_SWIZZLE_A];
  2012. image_view_create_info.subresourceRange.baseMipLevel = 0;
  2013. image_view_create_info.subresourceRange.levelCount = texture.mipmaps;
  2014. image_view_create_info.subresourceRange.baseArrayLayer = 0;
  2015. image_view_create_info.subresourceRange.layerCount = texture.layers;
  2016. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2017. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  2018. } else {
  2019. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2020. }
  2021. VkResult err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view);
  2022. if (err) {
  2023. // vmaDestroyImage(allocator, texture.image, texture.allocation);
  2024. ERR_FAIL_V_MSG(RID(), "vkCreateImageView failed with error " + itos(err) + ".");
  2025. }
  2026. // Barrier to set layout.
  2027. {
  2028. VkImageMemoryBarrier image_memory_barrier;
  2029. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2030. image_memory_barrier.pNext = nullptr;
  2031. image_memory_barrier.srcAccessMask = 0;
  2032. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2033. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2034. image_memory_barrier.newLayout = texture.layout;
  2035. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2036. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2037. image_memory_barrier.image = texture.image;
  2038. image_memory_barrier.subresourceRange.aspectMask = texture.barrier_aspect_mask;
  2039. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2040. image_memory_barrier.subresourceRange.levelCount = texture.mipmaps;
  2041. image_memory_barrier.subresourceRange.baseArrayLayer = 0;
  2042. image_memory_barrier.subresourceRange.layerCount = texture.layers;
  2043. vkCmdPipelineBarrier(frames[frame].setup_command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2044. }
  2045. RID id = texture_owner.make_rid(texture);
  2046. #ifdef DEV_ENABLED
  2047. set_resource_name(id, "RID:" + itos(id.get_id()));
  2048. #endif
  2049. return id;
  2050. }
  2051. RID RenderingDeviceVulkan::texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps, TextureSliceType p_slice_type) {
  2052. _THREAD_SAFE_METHOD_
  2053. Texture *src_texture = texture_owner.get_or_null(p_with_texture);
  2054. ERR_FAIL_COND_V(!src_texture, RID());
  2055. if (src_texture->owner.is_valid()) { // Ahh this is a share.
  2056. p_with_texture = src_texture->owner;
  2057. src_texture = texture_owner.get_or_null(src_texture->owner);
  2058. ERR_FAIL_COND_V(!src_texture, RID()); // This is a bug.
  2059. }
  2060. ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_CUBEMAP && (src_texture->type != TEXTURE_TYPE_CUBE && src_texture->type != TEXTURE_TYPE_CUBE_ARRAY), RID(),
  2061. "Can only create a cubemap slice from a cubemap or cubemap array mipmap");
  2062. ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_3D && src_texture->type != TEXTURE_TYPE_3D, RID(),
  2063. "Can only create a 3D slice from a 3D texture");
  2064. ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_2D_ARRAY && (src_texture->type != TEXTURE_TYPE_2D_ARRAY), RID(),
  2065. "Can only create an array slice from a 2D array mipmap");
  2066. // Create view.
  2067. ERR_FAIL_UNSIGNED_INDEX_V(p_mipmap, src_texture->mipmaps, RID());
  2068. ERR_FAIL_COND_V(p_mipmap + p_mipmaps > src_texture->mipmaps, RID());
  2069. ERR_FAIL_UNSIGNED_INDEX_V(p_layer, src_texture->layers, RID());
  2070. int slice_layers = 1;
  2071. if (p_slice_type == TEXTURE_SLICE_2D_ARRAY) {
  2072. ERR_FAIL_COND_V_MSG(p_layer != 0, RID(), "layer must be 0 when obtaining a 2D array mipmap slice");
  2073. slice_layers = src_texture->layers;
  2074. } else if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {
  2075. slice_layers = 6;
  2076. }
  2077. Texture texture = *src_texture;
  2078. get_image_format_required_size(texture.format, texture.width, texture.height, texture.depth, p_mipmap + 1, &texture.width, &texture.height);
  2079. texture.mipmaps = p_mipmaps;
  2080. texture.layers = slice_layers;
  2081. texture.base_mipmap = p_mipmap;
  2082. texture.base_layer = p_layer;
  2083. VkImageViewCreateInfo image_view_create_info;
  2084. image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  2085. image_view_create_info.pNext = nullptr;
  2086. image_view_create_info.flags = 0;
  2087. image_view_create_info.image = texture.image;
  2088. static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = {
  2089. VK_IMAGE_VIEW_TYPE_1D,
  2090. VK_IMAGE_VIEW_TYPE_2D,
  2091. VK_IMAGE_VIEW_TYPE_2D,
  2092. VK_IMAGE_VIEW_TYPE_2D,
  2093. VK_IMAGE_VIEW_TYPE_1D,
  2094. VK_IMAGE_VIEW_TYPE_2D,
  2095. VK_IMAGE_VIEW_TYPE_2D,
  2096. };
  2097. image_view_create_info.viewType = view_types[texture.type];
  2098. if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {
  2099. image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_CUBE;
  2100. } else if (p_slice_type == TEXTURE_SLICE_3D) {
  2101. image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_3D;
  2102. } else if (p_slice_type == TEXTURE_SLICE_2D_ARRAY) {
  2103. image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY;
  2104. }
  2105. if (p_slice_type == TEXTURE_SLICE_2D) {
  2106. texture.type = TEXTURE_TYPE_2D;
  2107. } else if (p_slice_type == TEXTURE_SLICE_3D) {
  2108. texture.type = TEXTURE_TYPE_3D;
  2109. }
  2110. if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) {
  2111. image_view_create_info.format = vulkan_formats[texture.format];
  2112. } else {
  2113. ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());
  2114. ERR_FAIL_COND_V_MSG(texture.allowed_shared_formats.find(p_view.format_override) == -1, RID(),
  2115. "Format override is not in the list of allowed shareable formats for original texture.");
  2116. image_view_create_info.format = vulkan_formats[p_view.format_override];
  2117. }
  2118. static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  2119. VK_COMPONENT_SWIZZLE_IDENTITY,
  2120. VK_COMPONENT_SWIZZLE_ZERO,
  2121. VK_COMPONENT_SWIZZLE_ONE,
  2122. VK_COMPONENT_SWIZZLE_R,
  2123. VK_COMPONENT_SWIZZLE_G,
  2124. VK_COMPONENT_SWIZZLE_B,
  2125. VK_COMPONENT_SWIZZLE_A
  2126. };
  2127. image_view_create_info.components.r = component_swizzles[p_view.swizzle_r];
  2128. image_view_create_info.components.g = component_swizzles[p_view.swizzle_g];
  2129. image_view_create_info.components.b = component_swizzles[p_view.swizzle_b];
  2130. image_view_create_info.components.a = component_swizzles[p_view.swizzle_a];
  2131. if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {
  2132. ERR_FAIL_COND_V_MSG(p_layer >= src_texture->layers, RID(),
  2133. "Specified layer is invalid for cubemap");
  2134. ERR_FAIL_COND_V_MSG((p_layer % 6) != 0, RID(),
  2135. "Specified layer must be a multiple of 6.");
  2136. }
  2137. image_view_create_info.subresourceRange.baseMipLevel = p_mipmap;
  2138. image_view_create_info.subresourceRange.levelCount = p_mipmaps;
  2139. image_view_create_info.subresourceRange.layerCount = slice_layers;
  2140. image_view_create_info.subresourceRange.baseArrayLayer = p_layer;
  2141. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2142. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  2143. } else {
  2144. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2145. }
  2146. VkResult err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view);
  2147. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateImageView failed with error " + itos(err) + ".");
  2148. texture.owner = p_with_texture;
  2149. RID id = texture_owner.make_rid(texture);
  2150. #ifdef DEV_ENABLED
  2151. set_resource_name(id, "RID:" + itos(id.get_id()));
  2152. #endif
  2153. _add_dependency(id, p_with_texture);
  2154. return id;
  2155. }
  2156. Error RenderingDeviceVulkan::texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, uint32_t p_post_barrier) {
  2157. return _texture_update(p_texture, p_layer, p_data, p_post_barrier, false);
  2158. }
  2159. static _ALWAYS_INLINE_ void _copy_region(uint8_t const *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_x, uint32_t p_src_y, uint32_t p_src_w, uint32_t p_src_h, uint32_t p_src_full_w, uint32_t p_unit_size) {
  2160. uint32_t src_offset = (p_src_y * p_src_full_w + p_src_x) * p_unit_size;
  2161. uint32_t dst_offset = 0;
  2162. for (uint32_t y = p_src_h; y > 0; y--) {
  2163. uint8_t const *__restrict src = p_src + src_offset;
  2164. uint8_t *__restrict dst = p_dst + dst_offset;
  2165. for (uint32_t x = p_src_w * p_unit_size; x > 0; x--) {
  2166. *dst = *src;
  2167. src++;
  2168. dst++;
  2169. }
  2170. src_offset += p_src_full_w * p_unit_size;
  2171. dst_offset += p_src_w * p_unit_size;
  2172. }
  2173. }
  2174. Error RenderingDeviceVulkan::_texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, uint32_t p_post_barrier, bool p_use_setup_queue) {
  2175. _THREAD_SAFE_METHOD_
  2176. ERR_FAIL_COND_V_MSG((draw_list || compute_list) && !p_use_setup_queue, ERR_INVALID_PARAMETER,
  2177. "Updating textures is forbidden during creation of a draw or compute list");
  2178. Texture *texture = texture_owner.get_or_null(p_texture);
  2179. ERR_FAIL_COND_V(!texture, ERR_INVALID_PARAMETER);
  2180. if (texture->owner != RID()) {
  2181. p_texture = texture->owner;
  2182. texture = texture_owner.get_or_null(texture->owner);
  2183. ERR_FAIL_COND_V(!texture, ERR_BUG); // This is a bug.
  2184. }
  2185. ERR_FAIL_COND_V_MSG(texture->bound, ERR_CANT_ACQUIRE_RESOURCE,
  2186. "Texture can't be updated while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2187. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_CAN_UPDATE_BIT), ERR_INVALID_PARAMETER,
  2188. "Texture requires the TEXTURE_USAGE_CAN_UPDATE_BIT in order to be updatable.");
  2189. uint32_t layer_count = texture->layers;
  2190. if (texture->type == TEXTURE_TYPE_CUBE || texture->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2191. layer_count *= 6;
  2192. }
  2193. ERR_FAIL_COND_V(p_layer >= layer_count, ERR_INVALID_PARAMETER);
  2194. uint32_t width, height;
  2195. uint32_t image_size = get_image_format_required_size(texture->format, texture->width, texture->height, texture->depth, texture->mipmaps, &width, &height);
  2196. uint32_t required_size = image_size;
  2197. uint32_t required_align = get_compressed_image_format_block_byte_size(texture->format);
  2198. if (required_align == 1) {
  2199. required_align = get_image_format_pixel_size(texture->format);
  2200. }
  2201. if ((required_align % 4) != 0) { // Alignment rules are really strange.
  2202. required_align *= 4;
  2203. }
  2204. ERR_FAIL_COND_V_MSG(required_size != (uint32_t)p_data.size(), ERR_INVALID_PARAMETER,
  2205. "Required size for texture update (" + itos(required_size) + ") does not match data supplied size (" + itos(p_data.size()) + ").");
  2206. uint32_t region_size = texture_upload_region_size_px;
  2207. const uint8_t *r = p_data.ptr();
  2208. VkCommandBuffer command_buffer = p_use_setup_queue ? frames[frame].setup_command_buffer : frames[frame].draw_command_buffer;
  2209. // Barrier to transfer.
  2210. {
  2211. VkImageMemoryBarrier image_memory_barrier;
  2212. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2213. image_memory_barrier.pNext = nullptr;
  2214. image_memory_barrier.srcAccessMask = 0;
  2215. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2216. image_memory_barrier.oldLayout = texture->layout;
  2217. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2218. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2219. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2220. image_memory_barrier.image = texture->image;
  2221. image_memory_barrier.subresourceRange.aspectMask = texture->barrier_aspect_mask;
  2222. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2223. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  2224. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2225. image_memory_barrier.subresourceRange.layerCount = 1;
  2226. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2227. }
  2228. uint32_t mipmap_offset = 0;
  2229. uint32_t logic_width = texture->width;
  2230. uint32_t logic_height = texture->height;
  2231. for (uint32_t mm_i = 0; mm_i < texture->mipmaps; mm_i++) {
  2232. uint32_t depth;
  2233. uint32_t image_total = get_image_format_required_size(texture->format, texture->width, texture->height, texture->depth, mm_i + 1, &width, &height, &depth);
  2234. const uint8_t *read_ptr_mipmap = r + mipmap_offset;
  2235. image_size = image_total - mipmap_offset;
  2236. for (uint32_t z = 0; z < depth; z++) { // For 3D textures, depth may be > 0.
  2237. const uint8_t *read_ptr = read_ptr_mipmap + image_size * z / depth;
  2238. for (uint32_t y = 0; y < height; y += region_size) {
  2239. for (uint32_t x = 0; x < width; x += region_size) {
  2240. uint32_t region_w = MIN(region_size, width - x);
  2241. uint32_t region_h = MIN(region_size, height - y);
  2242. uint32_t region_logic_w = MIN(region_size, logic_width - x);
  2243. uint32_t region_logic_h = MIN(region_size, logic_height - y);
  2244. uint32_t pixel_size = get_image_format_pixel_size(texture->format);
  2245. uint32_t to_allocate = region_w * region_h * pixel_size;
  2246. to_allocate >>= get_compressed_image_format_pixel_rshift(texture->format);
  2247. uint32_t alloc_offset, alloc_size;
  2248. Error err = _staging_buffer_allocate(to_allocate, required_align, alloc_offset, alloc_size, false);
  2249. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  2250. uint8_t *write_ptr;
  2251. { // Map.
  2252. void *data_ptr = nullptr;
  2253. VkResult vkerr = vmaMapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation, &data_ptr);
  2254. ERR_FAIL_COND_V_MSG(vkerr, ERR_CANT_CREATE, "vmaMapMemory failed with error " + itos(vkerr) + ".");
  2255. write_ptr = (uint8_t *)data_ptr;
  2256. write_ptr += alloc_offset;
  2257. }
  2258. uint32_t block_w, block_h;
  2259. get_compressed_image_format_block_dimensions(texture->format, block_w, block_h);
  2260. ERR_FAIL_COND_V(region_w % block_w, ERR_BUG);
  2261. ERR_FAIL_COND_V(region_h % block_h, ERR_BUG);
  2262. if (block_w != 1 || block_h != 1) {
  2263. // Compressed image (blocks).
  2264. // Must copy a block region.
  2265. uint32_t block_size = get_compressed_image_format_block_byte_size(texture->format);
  2266. // Re-create current variables in blocky format.
  2267. uint32_t xb = x / block_w;
  2268. uint32_t yb = y / block_h;
  2269. uint32_t wb = width / block_w;
  2270. //uint32_t hb = height / block_h;
  2271. uint32_t region_wb = region_w / block_w;
  2272. uint32_t region_hb = region_h / block_h;
  2273. _copy_region(read_ptr, write_ptr, xb, yb, region_wb, region_hb, wb, block_size);
  2274. } else {
  2275. // Regular image (pixels).
  2276. // Must copy a pixel region.
  2277. _copy_region(read_ptr, write_ptr, x, y, region_w, region_h, width, pixel_size);
  2278. }
  2279. { // Unmap.
  2280. vmaUnmapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation);
  2281. }
  2282. VkBufferImageCopy buffer_image_copy;
  2283. buffer_image_copy.bufferOffset = alloc_offset;
  2284. buffer_image_copy.bufferRowLength = 0; // Tightly packed.
  2285. buffer_image_copy.bufferImageHeight = 0; // Tightly packed.
  2286. buffer_image_copy.imageSubresource.aspectMask = texture->read_aspect_mask;
  2287. buffer_image_copy.imageSubresource.mipLevel = mm_i;
  2288. buffer_image_copy.imageSubresource.baseArrayLayer = p_layer;
  2289. buffer_image_copy.imageSubresource.layerCount = 1;
  2290. buffer_image_copy.imageOffset.x = x;
  2291. buffer_image_copy.imageOffset.y = y;
  2292. buffer_image_copy.imageOffset.z = z;
  2293. buffer_image_copy.imageExtent.width = region_logic_w;
  2294. buffer_image_copy.imageExtent.height = region_logic_h;
  2295. buffer_image_copy.imageExtent.depth = 1;
  2296. vkCmdCopyBufferToImage(command_buffer, staging_buffer_blocks[staging_buffer_current].buffer, texture->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buffer_image_copy);
  2297. staging_buffer_blocks.write[staging_buffer_current].fill_amount += alloc_size;
  2298. }
  2299. }
  2300. }
  2301. mipmap_offset = image_total;
  2302. logic_width = MAX(1u, logic_width >> 1);
  2303. logic_height = MAX(1u, logic_height >> 1);
  2304. }
  2305. // Barrier to restore layout.
  2306. {
  2307. uint32_t barrier_flags = 0;
  2308. uint32_t access_flags = 0;
  2309. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2310. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2311. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2312. }
  2313. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2314. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2315. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2316. }
  2317. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2318. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2319. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2320. }
  2321. if (barrier_flags == 0) {
  2322. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2323. }
  2324. VkImageMemoryBarrier image_memory_barrier;
  2325. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2326. image_memory_barrier.pNext = nullptr;
  2327. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2328. image_memory_barrier.dstAccessMask = access_flags;
  2329. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2330. image_memory_barrier.newLayout = texture->layout;
  2331. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2332. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2333. image_memory_barrier.image = texture->image;
  2334. image_memory_barrier.subresourceRange.aspectMask = texture->barrier_aspect_mask;
  2335. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2336. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  2337. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2338. image_memory_barrier.subresourceRange.layerCount = 1;
  2339. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2340. }
  2341. if (texture->used_in_frame != frames_drawn) {
  2342. texture->used_in_raster = false;
  2343. texture->used_in_compute = false;
  2344. texture->used_in_frame = frames_drawn;
  2345. }
  2346. texture->used_in_transfer = true;
  2347. return OK;
  2348. }
  2349. Vector<uint8_t> RenderingDeviceVulkan::_texture_get_data_from_image(Texture *tex, VkImage p_image, VmaAllocation p_allocation, uint32_t p_layer, bool p_2d) {
  2350. uint32_t width, height, depth;
  2351. uint32_t image_size = get_image_format_required_size(tex->format, tex->width, tex->height, p_2d ? 1 : tex->depth, tex->mipmaps, &width, &height, &depth);
  2352. Vector<uint8_t> image_data;
  2353. image_data.resize(image_size);
  2354. void *img_mem;
  2355. vmaMapMemory(allocator, p_allocation, &img_mem);
  2356. uint32_t blockw, blockh;
  2357. get_compressed_image_format_block_dimensions(tex->format, blockw, blockh);
  2358. uint32_t block_size = get_compressed_image_format_block_byte_size(tex->format);
  2359. uint32_t pixel_size = get_image_format_pixel_size(tex->format);
  2360. {
  2361. uint8_t *w = image_data.ptrw();
  2362. uint32_t mipmap_offset = 0;
  2363. for (uint32_t mm_i = 0; mm_i < tex->mipmaps; mm_i++) {
  2364. uint32_t image_total = get_image_format_required_size(tex->format, tex->width, tex->height, p_2d ? 1 : tex->depth, mm_i + 1, &width, &height, &depth);
  2365. uint8_t *write_ptr_mipmap = w + mipmap_offset;
  2366. image_size = image_total - mipmap_offset;
  2367. VkImageSubresource image_sub_resorce;
  2368. image_sub_resorce.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2369. image_sub_resorce.arrayLayer = p_layer;
  2370. image_sub_resorce.mipLevel = mm_i;
  2371. VkSubresourceLayout layout;
  2372. vkGetImageSubresourceLayout(device, p_image, &image_sub_resorce, &layout);
  2373. for (uint32_t z = 0; z < depth; z++) {
  2374. uint8_t *write_ptr = write_ptr_mipmap + z * image_size / depth;
  2375. const uint8_t *slice_read_ptr = ((uint8_t *)img_mem) + layout.offset + z * layout.depthPitch;
  2376. if (block_size > 1) {
  2377. // Compressed.
  2378. uint32_t line_width = (block_size * (width / blockw));
  2379. for (uint32_t y = 0; y < height / blockh; y++) {
  2380. const uint8_t *rptr = slice_read_ptr + y * layout.rowPitch;
  2381. uint8_t *wptr = write_ptr + y * line_width;
  2382. memcpy(wptr, rptr, line_width);
  2383. }
  2384. } else {
  2385. // Uncompressed.
  2386. for (uint32_t y = 0; y < height; y++) {
  2387. const uint8_t *rptr = slice_read_ptr + y * layout.rowPitch;
  2388. uint8_t *wptr = write_ptr + y * pixel_size * width;
  2389. memcpy(wptr, rptr, (uint64_t)pixel_size * width);
  2390. }
  2391. }
  2392. }
  2393. mipmap_offset = image_total;
  2394. }
  2395. }
  2396. vmaUnmapMemory(allocator, p_allocation);
  2397. return image_data;
  2398. }
  2399. Vector<uint8_t> RenderingDeviceVulkan::texture_get_data(RID p_texture, uint32_t p_layer) {
  2400. _THREAD_SAFE_METHOD_
  2401. Texture *tex = texture_owner.get_or_null(p_texture);
  2402. ERR_FAIL_COND_V(!tex, Vector<uint8_t>());
  2403. ERR_FAIL_COND_V_MSG(tex->bound, Vector<uint8_t>(),
  2404. "Texture can't be retrieved while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2405. ERR_FAIL_COND_V_MSG(!(tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), Vector<uint8_t>(),
  2406. "Texture requires the TEXTURE_USAGE_CAN_COPY_FROM_BIT in order to be retrieved.");
  2407. uint32_t layer_count = tex->layers;
  2408. if (tex->type == TEXTURE_TYPE_CUBE || tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2409. layer_count *= 6;
  2410. }
  2411. ERR_FAIL_COND_V(p_layer >= layer_count, Vector<uint8_t>());
  2412. if (tex->usage_flags & TEXTURE_USAGE_CPU_READ_BIT) {
  2413. // Does not need anything fancy, map and read.
  2414. return _texture_get_data_from_image(tex, tex->image, tex->allocation, p_layer);
  2415. } else {
  2416. // Compute total image size.
  2417. uint32_t width, height, depth;
  2418. uint32_t buffer_size = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, tex->mipmaps, &width, &height, &depth);
  2419. // Allocate buffer.
  2420. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer; // Makes more sense to retrieve.
  2421. Buffer tmp_buffer;
  2422. _buffer_allocate(&tmp_buffer, buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_HOST, VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT);
  2423. { // Source image barrier.
  2424. VkImageMemoryBarrier image_memory_barrier;
  2425. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2426. image_memory_barrier.pNext = nullptr;
  2427. image_memory_barrier.srcAccessMask = 0;
  2428. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2429. image_memory_barrier.oldLayout = tex->layout;
  2430. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2431. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2432. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2433. image_memory_barrier.image = tex->image;
  2434. image_memory_barrier.subresourceRange.aspectMask = tex->barrier_aspect_mask;
  2435. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2436. image_memory_barrier.subresourceRange.levelCount = tex->mipmaps;
  2437. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2438. image_memory_barrier.subresourceRange.layerCount = 1;
  2439. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2440. }
  2441. uint32_t computed_w = tex->width;
  2442. uint32_t computed_h = tex->height;
  2443. uint32_t computed_d = tex->depth;
  2444. uint32_t prev_size = 0;
  2445. uint32_t offset = 0;
  2446. for (uint32_t i = 0; i < tex->mipmaps; i++) {
  2447. VkBufferImageCopy buffer_image_copy;
  2448. uint32_t image_size = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, i + 1);
  2449. uint32_t size = image_size - prev_size;
  2450. prev_size = image_size;
  2451. buffer_image_copy.bufferOffset = offset;
  2452. buffer_image_copy.bufferImageHeight = 0;
  2453. buffer_image_copy.bufferRowLength = 0;
  2454. buffer_image_copy.imageSubresource.aspectMask = tex->read_aspect_mask;
  2455. buffer_image_copy.imageSubresource.baseArrayLayer = p_layer;
  2456. buffer_image_copy.imageSubresource.layerCount = 1;
  2457. buffer_image_copy.imageSubresource.mipLevel = i;
  2458. buffer_image_copy.imageOffset.x = 0;
  2459. buffer_image_copy.imageOffset.y = 0;
  2460. buffer_image_copy.imageOffset.z = 0;
  2461. buffer_image_copy.imageExtent.width = computed_w;
  2462. buffer_image_copy.imageExtent.height = computed_h;
  2463. buffer_image_copy.imageExtent.depth = computed_d;
  2464. vkCmdCopyImageToBuffer(command_buffer, tex->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, tmp_buffer.buffer, 1, &buffer_image_copy);
  2465. computed_w = MAX(1u, computed_w >> 1);
  2466. computed_h = MAX(1u, computed_h >> 1);
  2467. computed_d = MAX(1u, computed_d >> 1);
  2468. offset += size;
  2469. }
  2470. { // Restore src.
  2471. VkImageMemoryBarrier image_memory_barrier;
  2472. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2473. image_memory_barrier.pNext = nullptr;
  2474. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2475. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2476. if (tex->usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  2477. image_memory_barrier.dstAccessMask |= VK_ACCESS_SHADER_WRITE_BIT;
  2478. }
  2479. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2480. image_memory_barrier.newLayout = tex->layout;
  2481. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2482. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2483. image_memory_barrier.image = tex->image;
  2484. image_memory_barrier.subresourceRange.aspectMask = tex->barrier_aspect_mask;
  2485. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2486. image_memory_barrier.subresourceRange.levelCount = tex->mipmaps;
  2487. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2488. image_memory_barrier.subresourceRange.layerCount = 1;
  2489. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2490. }
  2491. _flush(true);
  2492. void *buffer_mem;
  2493. VkResult vkerr = vmaMapMemory(allocator, tmp_buffer.allocation, &buffer_mem);
  2494. ERR_FAIL_COND_V_MSG(vkerr, Vector<uint8_t>(), "vmaMapMemory failed with error " + itos(vkerr) + ".");
  2495. Vector<uint8_t> buffer_data;
  2496. {
  2497. buffer_data.resize(buffer_size);
  2498. uint8_t *w = buffer_data.ptrw();
  2499. memcpy(w, buffer_mem, buffer_size);
  2500. }
  2501. vmaUnmapMemory(allocator, tmp_buffer.allocation);
  2502. _buffer_free(&tmp_buffer);
  2503. return buffer_data;
  2504. }
  2505. }
  2506. bool RenderingDeviceVulkan::texture_is_shared(RID p_texture) {
  2507. _THREAD_SAFE_METHOD_
  2508. Texture *tex = texture_owner.get_or_null(p_texture);
  2509. ERR_FAIL_COND_V(!tex, false);
  2510. return tex->owner.is_valid();
  2511. }
  2512. bool RenderingDeviceVulkan::texture_is_valid(RID p_texture) {
  2513. return texture_owner.owns(p_texture);
  2514. }
  2515. Size2i RenderingDeviceVulkan::texture_size(RID p_texture) {
  2516. _THREAD_SAFE_METHOD_
  2517. Texture *tex = texture_owner.get_or_null(p_texture);
  2518. ERR_FAIL_COND_V(!tex, Size2i());
  2519. return Size2i(tex->width, tex->height);
  2520. }
  2521. Error RenderingDeviceVulkan::texture_copy(RID p_from_texture, RID p_to_texture, const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_size, uint32_t p_src_mipmap, uint32_t p_dst_mipmap, uint32_t p_src_layer, uint32_t p_dst_layer, uint32_t p_post_barrier) {
  2522. _THREAD_SAFE_METHOD_
  2523. Texture *src_tex = texture_owner.get_or_null(p_from_texture);
  2524. ERR_FAIL_COND_V(!src_tex, ERR_INVALID_PARAMETER);
  2525. ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,
  2526. "Source texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2527. ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), ERR_INVALID_PARAMETER,
  2528. "Source texture requires the TEXTURE_USAGE_CAN_COPY_FROM_BIT in order to be retrieved.");
  2529. uint32_t src_layer_count = src_tex->layers;
  2530. uint32_t src_width, src_height, src_depth;
  2531. get_image_format_required_size(src_tex->format, src_tex->width, src_tex->height, src_tex->depth, p_src_mipmap + 1, &src_width, &src_height, &src_depth);
  2532. if (src_tex->type == TEXTURE_TYPE_CUBE || src_tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2533. src_layer_count *= 6;
  2534. }
  2535. ERR_FAIL_COND_V(p_from.x < 0 || p_from.x + p_size.x > src_width, ERR_INVALID_PARAMETER);
  2536. ERR_FAIL_COND_V(p_from.y < 0 || p_from.y + p_size.y > src_height, ERR_INVALID_PARAMETER);
  2537. ERR_FAIL_COND_V(p_from.z < 0 || p_from.z + p_size.z > src_depth, ERR_INVALID_PARAMETER);
  2538. ERR_FAIL_COND_V(p_src_mipmap >= src_tex->mipmaps, ERR_INVALID_PARAMETER);
  2539. ERR_FAIL_COND_V(p_src_layer >= src_layer_count, ERR_INVALID_PARAMETER);
  2540. Texture *dst_tex = texture_owner.get_or_null(p_to_texture);
  2541. ERR_FAIL_COND_V(!dst_tex, ERR_INVALID_PARAMETER);
  2542. ERR_FAIL_COND_V_MSG(dst_tex->bound, ERR_INVALID_PARAMETER,
  2543. "Destination texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2544. ERR_FAIL_COND_V_MSG(!(dst_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,
  2545. "Destination texture requires the TEXTURE_USAGE_CAN_COPY_TO_BIT in order to be retrieved.");
  2546. uint32_t dst_layer_count = dst_tex->layers;
  2547. uint32_t dst_width, dst_height, dst_depth;
  2548. get_image_format_required_size(dst_tex->format, dst_tex->width, dst_tex->height, dst_tex->depth, p_dst_mipmap + 1, &dst_width, &dst_height, &dst_depth);
  2549. if (dst_tex->type == TEXTURE_TYPE_CUBE || dst_tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2550. dst_layer_count *= 6;
  2551. }
  2552. ERR_FAIL_COND_V(p_to.x < 0 || p_to.x + p_size.x > dst_width, ERR_INVALID_PARAMETER);
  2553. ERR_FAIL_COND_V(p_to.y < 0 || p_to.y + p_size.y > dst_height, ERR_INVALID_PARAMETER);
  2554. ERR_FAIL_COND_V(p_to.z < 0 || p_to.z + p_size.z > dst_depth, ERR_INVALID_PARAMETER);
  2555. ERR_FAIL_COND_V(p_dst_mipmap >= dst_tex->mipmaps, ERR_INVALID_PARAMETER);
  2556. ERR_FAIL_COND_V(p_dst_layer >= dst_layer_count, ERR_INVALID_PARAMETER);
  2557. ERR_FAIL_COND_V_MSG(src_tex->read_aspect_mask != dst_tex->read_aspect_mask, ERR_INVALID_PARAMETER,
  2558. "Source and destination texture must be of the same type (color or depth).");
  2559. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  2560. {
  2561. // PRE Copy the image.
  2562. { // Source.
  2563. VkImageMemoryBarrier image_memory_barrier;
  2564. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2565. image_memory_barrier.pNext = nullptr;
  2566. image_memory_barrier.srcAccessMask = 0;
  2567. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2568. image_memory_barrier.oldLayout = src_tex->layout;
  2569. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2570. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2571. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2572. image_memory_barrier.image = src_tex->image;
  2573. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2574. image_memory_barrier.subresourceRange.baseMipLevel = p_src_mipmap;
  2575. image_memory_barrier.subresourceRange.levelCount = 1;
  2576. image_memory_barrier.subresourceRange.baseArrayLayer = p_src_layer;
  2577. image_memory_barrier.subresourceRange.layerCount = 1;
  2578. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2579. }
  2580. { // Dest.
  2581. VkImageMemoryBarrier image_memory_barrier;
  2582. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2583. image_memory_barrier.pNext = nullptr;
  2584. image_memory_barrier.srcAccessMask = 0;
  2585. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2586. image_memory_barrier.oldLayout = dst_tex->layout;
  2587. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2588. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2589. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2590. image_memory_barrier.image = dst_tex->image;
  2591. image_memory_barrier.subresourceRange.aspectMask = dst_tex->read_aspect_mask;
  2592. image_memory_barrier.subresourceRange.baseMipLevel = p_dst_mipmap;
  2593. image_memory_barrier.subresourceRange.levelCount = 1;
  2594. image_memory_barrier.subresourceRange.baseArrayLayer = p_dst_layer;
  2595. image_memory_barrier.subresourceRange.layerCount = 1;
  2596. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2597. }
  2598. // COPY.
  2599. {
  2600. VkImageCopy image_copy_region;
  2601. image_copy_region.srcSubresource.aspectMask = src_tex->read_aspect_mask;
  2602. image_copy_region.srcSubresource.baseArrayLayer = p_src_layer;
  2603. image_copy_region.srcSubresource.layerCount = 1;
  2604. image_copy_region.srcSubresource.mipLevel = p_src_mipmap;
  2605. image_copy_region.srcOffset.x = p_from.x;
  2606. image_copy_region.srcOffset.y = p_from.y;
  2607. image_copy_region.srcOffset.z = p_from.z;
  2608. image_copy_region.dstSubresource.aspectMask = dst_tex->read_aspect_mask;
  2609. image_copy_region.dstSubresource.baseArrayLayer = p_dst_layer;
  2610. image_copy_region.dstSubresource.layerCount = 1;
  2611. image_copy_region.dstSubresource.mipLevel = p_dst_mipmap;
  2612. image_copy_region.dstOffset.x = p_to.x;
  2613. image_copy_region.dstOffset.y = p_to.y;
  2614. image_copy_region.dstOffset.z = p_to.z;
  2615. image_copy_region.extent.width = p_size.x;
  2616. image_copy_region.extent.height = p_size.y;
  2617. image_copy_region.extent.depth = p_size.z;
  2618. vkCmdCopyImage(command_buffer, src_tex->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst_tex->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy_region);
  2619. }
  2620. // RESTORE LAYOUT for SRC and DST.
  2621. uint32_t barrier_flags = 0;
  2622. uint32_t access_flags = 0;
  2623. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2624. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2625. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2626. }
  2627. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2628. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2629. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2630. }
  2631. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2632. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2633. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2634. }
  2635. if (barrier_flags == 0) {
  2636. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2637. }
  2638. { // Restore src.
  2639. VkImageMemoryBarrier image_memory_barrier;
  2640. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2641. image_memory_barrier.pNext = nullptr;
  2642. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2643. image_memory_barrier.dstAccessMask = access_flags;
  2644. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2645. image_memory_barrier.newLayout = src_tex->layout;
  2646. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2647. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2648. image_memory_barrier.image = src_tex->image;
  2649. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2650. image_memory_barrier.subresourceRange.baseMipLevel = p_src_mipmap;
  2651. image_memory_barrier.subresourceRange.levelCount = src_tex->mipmaps;
  2652. image_memory_barrier.subresourceRange.baseArrayLayer = p_src_layer;
  2653. image_memory_barrier.subresourceRange.layerCount = 1;
  2654. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2655. }
  2656. { // Make dst readable.
  2657. VkImageMemoryBarrier image_memory_barrier;
  2658. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2659. image_memory_barrier.pNext = nullptr;
  2660. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2661. image_memory_barrier.dstAccessMask = access_flags;
  2662. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2663. image_memory_barrier.newLayout = dst_tex->layout;
  2664. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2665. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2666. image_memory_barrier.image = dst_tex->image;
  2667. image_memory_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2668. image_memory_barrier.subresourceRange.baseMipLevel = p_src_mipmap;
  2669. image_memory_barrier.subresourceRange.levelCount = 1;
  2670. image_memory_barrier.subresourceRange.baseArrayLayer = p_src_layer;
  2671. image_memory_barrier.subresourceRange.layerCount = 1;
  2672. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2673. }
  2674. }
  2675. if (dst_tex->used_in_frame != frames_drawn) {
  2676. dst_tex->used_in_raster = false;
  2677. dst_tex->used_in_compute = false;
  2678. dst_tex->used_in_frame = frames_drawn;
  2679. }
  2680. dst_tex->used_in_transfer = true;
  2681. return OK;
  2682. }
  2683. Error RenderingDeviceVulkan::texture_resolve_multisample(RID p_from_texture, RID p_to_texture, uint32_t p_post_barrier) {
  2684. _THREAD_SAFE_METHOD_
  2685. Texture *src_tex = texture_owner.get_or_null(p_from_texture);
  2686. ERR_FAIL_COND_V(!src_tex, ERR_INVALID_PARAMETER);
  2687. ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,
  2688. "Source texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2689. ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), ERR_INVALID_PARAMETER,
  2690. "Source texture requires the TEXTURE_USAGE_CAN_COPY_FROM_BIT in order to be retrieved.");
  2691. ERR_FAIL_COND_V_MSG(src_tex->type != TEXTURE_TYPE_2D, ERR_INVALID_PARAMETER, "Source texture must be 2D (or a slice of a 3D/Cube texture)");
  2692. ERR_FAIL_COND_V_MSG(src_tex->samples == TEXTURE_SAMPLES_1, ERR_INVALID_PARAMETER, "Source texture must be multisampled.");
  2693. Texture *dst_tex = texture_owner.get_or_null(p_to_texture);
  2694. ERR_FAIL_COND_V(!dst_tex, ERR_INVALID_PARAMETER);
  2695. ERR_FAIL_COND_V_MSG(dst_tex->bound, ERR_INVALID_PARAMETER,
  2696. "Destination texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2697. ERR_FAIL_COND_V_MSG(!(dst_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,
  2698. "Destination texture requires the TEXTURE_USAGE_CAN_COPY_TO_BIT in order to be retrieved.");
  2699. ERR_FAIL_COND_V_MSG(dst_tex->type != TEXTURE_TYPE_2D, ERR_INVALID_PARAMETER, "Destination texture must be 2D (or a slice of a 3D/Cube texture).");
  2700. ERR_FAIL_COND_V_MSG(dst_tex->samples != TEXTURE_SAMPLES_1, ERR_INVALID_PARAMETER, "Destination texture must not be multisampled.");
  2701. ERR_FAIL_COND_V_MSG(src_tex->format != dst_tex->format, ERR_INVALID_PARAMETER, "Source and Destination textures must be the same format.");
  2702. ERR_FAIL_COND_V_MSG(src_tex->width != dst_tex->width && src_tex->height != dst_tex->height && src_tex->depth != dst_tex->depth, ERR_INVALID_PARAMETER, "Source and Destination textures must have the same dimensions.");
  2703. ERR_FAIL_COND_V_MSG(src_tex->read_aspect_mask != dst_tex->read_aspect_mask, ERR_INVALID_PARAMETER,
  2704. "Source and destination texture must be of the same type (color or depth).");
  2705. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  2706. {
  2707. // PRE Copy the image.
  2708. { // Source.
  2709. VkImageMemoryBarrier image_memory_barrier;
  2710. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2711. image_memory_barrier.pNext = nullptr;
  2712. image_memory_barrier.srcAccessMask = 0;
  2713. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2714. image_memory_barrier.oldLayout = src_tex->layout;
  2715. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2716. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2717. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2718. image_memory_barrier.image = src_tex->image;
  2719. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2720. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap;
  2721. image_memory_barrier.subresourceRange.levelCount = 1;
  2722. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer;
  2723. image_memory_barrier.subresourceRange.layerCount = 1;
  2724. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2725. }
  2726. { // Dest.
  2727. VkImageMemoryBarrier image_memory_barrier;
  2728. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2729. image_memory_barrier.pNext = nullptr;
  2730. image_memory_barrier.srcAccessMask = 0;
  2731. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2732. image_memory_barrier.oldLayout = dst_tex->layout;
  2733. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2734. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2735. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2736. image_memory_barrier.image = dst_tex->image;
  2737. image_memory_barrier.subresourceRange.aspectMask = dst_tex->read_aspect_mask;
  2738. image_memory_barrier.subresourceRange.baseMipLevel = dst_tex->base_mipmap;
  2739. image_memory_barrier.subresourceRange.levelCount = 1;
  2740. image_memory_barrier.subresourceRange.baseArrayLayer = dst_tex->base_layer;
  2741. image_memory_barrier.subresourceRange.layerCount = 1;
  2742. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2743. }
  2744. // COPY.
  2745. {
  2746. VkImageResolve image_copy_region;
  2747. image_copy_region.srcSubresource.aspectMask = src_tex->read_aspect_mask;
  2748. image_copy_region.srcSubresource.baseArrayLayer = src_tex->base_layer;
  2749. image_copy_region.srcSubresource.layerCount = 1;
  2750. image_copy_region.srcSubresource.mipLevel = src_tex->base_mipmap;
  2751. image_copy_region.srcOffset.x = 0;
  2752. image_copy_region.srcOffset.y = 0;
  2753. image_copy_region.srcOffset.z = 0;
  2754. image_copy_region.dstSubresource.aspectMask = dst_tex->read_aspect_mask;
  2755. image_copy_region.dstSubresource.baseArrayLayer = dst_tex->base_layer;
  2756. image_copy_region.dstSubresource.layerCount = 1;
  2757. image_copy_region.dstSubresource.mipLevel = dst_tex->base_mipmap;
  2758. image_copy_region.dstOffset.x = 0;
  2759. image_copy_region.dstOffset.y = 0;
  2760. image_copy_region.dstOffset.z = 0;
  2761. image_copy_region.extent.width = src_tex->width;
  2762. image_copy_region.extent.height = src_tex->height;
  2763. image_copy_region.extent.depth = src_tex->depth;
  2764. vkCmdResolveImage(command_buffer, src_tex->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst_tex->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy_region);
  2765. }
  2766. // RESTORE LAYOUT for SRC and DST.
  2767. uint32_t barrier_flags = 0;
  2768. uint32_t access_flags = 0;
  2769. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2770. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2771. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2772. }
  2773. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2774. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2775. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2776. }
  2777. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2778. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2779. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2780. }
  2781. if (barrier_flags == 0) {
  2782. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2783. }
  2784. { // Restore src.
  2785. VkImageMemoryBarrier image_memory_barrier;
  2786. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2787. image_memory_barrier.pNext = nullptr;
  2788. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2789. image_memory_barrier.dstAccessMask = access_flags;
  2790. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2791. image_memory_barrier.newLayout = src_tex->layout;
  2792. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2793. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2794. image_memory_barrier.image = src_tex->image;
  2795. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2796. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap;
  2797. image_memory_barrier.subresourceRange.levelCount = 1;
  2798. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer;
  2799. image_memory_barrier.subresourceRange.layerCount = 1;
  2800. vkCmdPipelineBarrier(command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2801. }
  2802. { // Make dst readable.
  2803. VkImageMemoryBarrier image_memory_barrier;
  2804. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2805. image_memory_barrier.pNext = nullptr;
  2806. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2807. image_memory_barrier.dstAccessMask = access_flags;
  2808. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2809. image_memory_barrier.newLayout = dst_tex->layout;
  2810. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2811. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2812. image_memory_barrier.image = dst_tex->image;
  2813. image_memory_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2814. image_memory_barrier.subresourceRange.baseMipLevel = dst_tex->base_mipmap;
  2815. image_memory_barrier.subresourceRange.levelCount = 1;
  2816. image_memory_barrier.subresourceRange.baseArrayLayer = dst_tex->base_layer;
  2817. image_memory_barrier.subresourceRange.layerCount = 1;
  2818. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2819. }
  2820. }
  2821. return OK;
  2822. }
  2823. Error RenderingDeviceVulkan::texture_clear(RID p_texture, const Color &p_color, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers, uint32_t p_post_barrier) {
  2824. _THREAD_SAFE_METHOD_
  2825. Texture *src_tex = texture_owner.get_or_null(p_texture);
  2826. ERR_FAIL_COND_V(!src_tex, ERR_INVALID_PARAMETER);
  2827. ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,
  2828. "Source texture can't be cleared while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2829. ERR_FAIL_COND_V(p_layers == 0, ERR_INVALID_PARAMETER);
  2830. ERR_FAIL_COND_V(p_mipmaps == 0, ERR_INVALID_PARAMETER);
  2831. ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,
  2832. "Source texture requires the TEXTURE_USAGE_CAN_COPY_TO_BIT in order to be cleared.");
  2833. uint32_t src_layer_count = src_tex->layers;
  2834. if (src_tex->type == TEXTURE_TYPE_CUBE || src_tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2835. src_layer_count *= 6;
  2836. }
  2837. ERR_FAIL_COND_V(p_base_mipmap + p_mipmaps > src_tex->mipmaps, ERR_INVALID_PARAMETER);
  2838. ERR_FAIL_COND_V(p_base_layer + p_layers > src_layer_count, ERR_INVALID_PARAMETER);
  2839. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  2840. VkImageLayout clear_layout = (src_tex->layout == VK_IMAGE_LAYOUT_GENERAL) ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2841. // NOTE: Perhaps the valid stages/accesses for a given owner should be a property of the owner. (Here and places like _get_buffer_from_owner.)
  2842. const VkPipelineStageFlags valid_texture_stages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2843. constexpr VkAccessFlags read_access = VK_ACCESS_SHADER_READ_BIT;
  2844. constexpr VkAccessFlags read_write_access = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2845. const VkAccessFlags valid_texture_access = (src_tex->usage_flags & TEXTURE_USAGE_STORAGE_BIT) ? read_write_access : read_access;
  2846. { // Barrier from previous access with optional layout change (see clear_layout logic above).
  2847. VkImageMemoryBarrier image_memory_barrier;
  2848. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2849. image_memory_barrier.pNext = nullptr;
  2850. image_memory_barrier.srcAccessMask = valid_texture_access;
  2851. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2852. image_memory_barrier.oldLayout = src_tex->layout;
  2853. image_memory_barrier.newLayout = clear_layout;
  2854. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2855. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2856. image_memory_barrier.image = src_tex->image;
  2857. image_memory_barrier.subresourceRange.aspectMask = src_tex->read_aspect_mask;
  2858. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap + p_base_mipmap;
  2859. image_memory_barrier.subresourceRange.levelCount = p_mipmaps;
  2860. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer + p_base_layer;
  2861. image_memory_barrier.subresourceRange.layerCount = p_layers;
  2862. vkCmdPipelineBarrier(command_buffer, valid_texture_stages, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2863. }
  2864. VkClearColorValue clear_color;
  2865. clear_color.float32[0] = p_color.r;
  2866. clear_color.float32[1] = p_color.g;
  2867. clear_color.float32[2] = p_color.b;
  2868. clear_color.float32[3] = p_color.a;
  2869. VkImageSubresourceRange range;
  2870. range.aspectMask = src_tex->read_aspect_mask;
  2871. range.baseArrayLayer = src_tex->base_layer + p_base_layer;
  2872. range.layerCount = p_layers;
  2873. range.baseMipLevel = src_tex->base_mipmap + p_base_mipmap;
  2874. range.levelCount = p_mipmaps;
  2875. vkCmdClearColorImage(command_buffer, src_tex->image, clear_layout, &clear_color, 1, &range);
  2876. { // Barrier to post clear accesses (changing back the layout if needed).
  2877. uint32_t barrier_flags = 0;
  2878. uint32_t access_flags = 0;
  2879. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2880. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2881. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2882. }
  2883. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2884. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2885. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2886. }
  2887. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2888. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2889. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2890. }
  2891. if (barrier_flags == 0) {
  2892. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2893. }
  2894. VkImageMemoryBarrier image_memory_barrier;
  2895. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2896. image_memory_barrier.pNext = nullptr;
  2897. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2898. image_memory_barrier.dstAccessMask = access_flags;
  2899. image_memory_barrier.oldLayout = clear_layout;
  2900. image_memory_barrier.newLayout = src_tex->layout;
  2901. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2902. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2903. image_memory_barrier.image = src_tex->image;
  2904. image_memory_barrier.subresourceRange.aspectMask = src_tex->read_aspect_mask;
  2905. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap + p_base_mipmap;
  2906. image_memory_barrier.subresourceRange.levelCount = p_mipmaps;
  2907. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer + p_base_layer;
  2908. image_memory_barrier.subresourceRange.layerCount = p_layers;
  2909. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2910. }
  2911. if (src_tex->used_in_frame != frames_drawn) {
  2912. src_tex->used_in_raster = false;
  2913. src_tex->used_in_compute = false;
  2914. src_tex->used_in_frame = frames_drawn;
  2915. }
  2916. src_tex->used_in_transfer = true;
  2917. return OK;
  2918. }
  2919. bool RenderingDeviceVulkan::texture_is_format_supported_for_usage(DataFormat p_format, uint32_t p_usage) const {
  2920. ERR_FAIL_INDEX_V(p_format, DATA_FORMAT_MAX, false);
  2921. _THREAD_SAFE_METHOD_
  2922. // Validate that this image is supported for the intended use.
  2923. VkFormatProperties properties;
  2924. vkGetPhysicalDeviceFormatProperties(context->get_physical_device(), vulkan_formats[p_format], &properties);
  2925. VkFormatFeatureFlags flags;
  2926. if (p_usage & TEXTURE_USAGE_CPU_READ_BIT) {
  2927. flags = properties.linearTilingFeatures;
  2928. } else {
  2929. flags = properties.optimalTilingFeatures;
  2930. }
  2931. if (p_usage & TEXTURE_USAGE_SAMPLING_BIT && !(flags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) {
  2932. return false;
  2933. }
  2934. if (p_usage & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) {
  2935. return false;
  2936. }
  2937. if (p_usage & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  2938. return false;
  2939. }
  2940. if (p_usage & TEXTURE_USAGE_STORAGE_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) {
  2941. return false;
  2942. }
  2943. if (p_usage & TEXTURE_USAGE_STORAGE_ATOMIC_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT)) {
  2944. return false;
  2945. }
  2946. // Validation via VK_FORMAT_FEATURE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR fails if VRS attachment is not supported.
  2947. if (p_usage & TEXTURE_USAGE_VRS_ATTACHMENT_BIT && p_format != DATA_FORMAT_R8_UINT) {
  2948. return false;
  2949. }
  2950. return true;
  2951. }
  2952. /********************/
  2953. /**** ATTACHMENT ****/
  2954. /********************/
  2955. VkRenderPass RenderingDeviceVulkan::_render_pass_create(const Vector<AttachmentFormat> &p_attachments, const Vector<FramebufferPass> &p_passes, InitialAction p_initial_action, FinalAction p_final_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, uint32_t p_view_count, Vector<TextureSamples> *r_samples) {
  2956. // Set up dependencies from/to external equivalent to the default (implicit) one, and then amend them.
  2957. const VkPipelineStageFlags default_access_mask = VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  2958. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  2959. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  2960. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  2961. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | // From Section 7.1 of Vulkan API Spec v1.1.148.
  2962. VK_ACCESS_FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT_KHR;
  2963. VkPipelineStageFlags reading_stages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT;
  2964. VkSubpassDependency2KHR dependencies[2] = {
  2965. { VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR, nullptr, VK_SUBPASS_EXTERNAL, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, default_access_mask, 0, 0 },
  2966. { VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR, nullptr, 0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, default_access_mask, 0, 0, 0 }
  2967. };
  2968. VkSubpassDependency2KHR &dependency_from_external = dependencies[0];
  2969. VkSubpassDependency2KHR &dependency_to_external = dependencies[1];
  2970. LocalVector<int32_t> attachment_last_pass;
  2971. attachment_last_pass.resize(p_attachments.size());
  2972. // These are only used if we use multiview but we need to define them in scope.
  2973. const uint32_t view_mask = (1 << p_view_count) - 1;
  2974. const uint32_t correlation_mask = (1 << p_view_count) - 1;
  2975. Vector<VkAttachmentDescription2KHR> attachments;
  2976. Vector<int> attachment_remap;
  2977. for (int i = 0; i < p_attachments.size(); i++) {
  2978. if (p_attachments[i].usage_flags == AttachmentFormat::UNUSED_ATTACHMENT) {
  2979. attachment_remap.push_back(VK_ATTACHMENT_UNUSED);
  2980. continue;
  2981. }
  2982. ERR_FAIL_INDEX_V(p_attachments[i].format, DATA_FORMAT_MAX, VK_NULL_HANDLE);
  2983. ERR_FAIL_INDEX_V(p_attachments[i].samples, TEXTURE_SAMPLES_MAX, VK_NULL_HANDLE);
  2984. ERR_FAIL_COND_V_MSG(!(p_attachments[i].usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT | TEXTURE_USAGE_VRS_ATTACHMENT_BIT)),
  2985. VK_NULL_HANDLE, "Texture format for index (" + itos(i) + ") requires an attachment (color, depth-stencil, input or VRS) bit set.");
  2986. VkAttachmentDescription2KHR description = {};
  2987. description.sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2_KHR;
  2988. description.pNext = nullptr;
  2989. description.flags = 0;
  2990. description.format = vulkan_formats[p_attachments[i].format];
  2991. description.samples = _ensure_supported_sample_count(p_attachments[i].samples);
  2992. bool is_sampled = p_attachments[i].usage_flags & TEXTURE_USAGE_SAMPLING_BIT;
  2993. bool is_storage = p_attachments[i].usage_flags & TEXTURE_USAGE_STORAGE_BIT;
  2994. bool is_depth = p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  2995. // We can setup a framebuffer where we write to our VRS texture to set it up.
  2996. // We make the assumption here that if our texture is actually used as our VRS attachment.
  2997. // It is used as such for each subpass. This is fairly certain seeing the restrictions on subpasses.
  2998. bool is_vrs = p_attachments[i].usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT && i == p_passes[0].vrs_attachment;
  2999. if (is_vrs) {
  3000. // For VRS we only read, there is no writing to this texture.
  3001. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3002. description.initialLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  3003. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3004. } else {
  3005. // For each UNDEFINED, assume the prior use was a *read*, as we'd be discarding the output of a write.
  3006. // Also, each UNDEFINED will do an immediate layout transition (write), s.t. we must ensure execution synchronization vs
  3007. // the read. If this is a performance issue, one could track the actual last accessor of each resource, adding only that
  3008. // stage.
  3009. switch (is_depth ? p_initial_depth_action : p_initial_action) {
  3010. case INITIAL_ACTION_CLEAR_REGION:
  3011. case INITIAL_ACTION_CLEAR: {
  3012. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3013. description.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  3014. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  3015. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3016. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3017. description.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  3018. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  3019. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  3020. dependency_from_external.srcStageMask |= reading_stages;
  3021. } else {
  3022. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3023. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3024. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // Don't care what is there.
  3025. dependency_from_external.srcStageMask |= reading_stages;
  3026. }
  3027. } break;
  3028. case INITIAL_ACTION_KEEP: {
  3029. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3030. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3031. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  3032. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3033. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3034. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3035. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  3036. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3037. dependency_from_external.srcStageMask |= reading_stages;
  3038. } else {
  3039. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3040. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3041. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // Don't care what is there.
  3042. dependency_from_external.srcStageMask |= reading_stages;
  3043. }
  3044. } break;
  3045. case INITIAL_ACTION_DROP: {
  3046. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3047. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3048. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  3049. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3050. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3051. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3052. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // Don't care what is there.
  3053. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3054. dependency_from_external.srcStageMask |= reading_stages;
  3055. } else {
  3056. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3057. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3058. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // Don't care what is there.
  3059. dependency_from_external.srcStageMask |= reading_stages;
  3060. }
  3061. } break;
  3062. case INITIAL_ACTION_CLEAR_REGION_CONTINUE:
  3063. case INITIAL_ACTION_CONTINUE: {
  3064. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3065. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3066. description.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  3067. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3068. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3069. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3070. description.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  3071. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3072. } else {
  3073. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3074. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3075. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // Don't care what is there.
  3076. dependency_from_external.srcStageMask |= reading_stages;
  3077. }
  3078. } break;
  3079. default: {
  3080. ERR_FAIL_V(VK_NULL_HANDLE); // Should never reach here.
  3081. }
  3082. }
  3083. }
  3084. bool used_last = false;
  3085. {
  3086. int last_pass = p_passes.size() - 1;
  3087. if (is_depth) {
  3088. // Likely missing depth resolve?
  3089. if (p_passes[last_pass].depth_attachment == i) {
  3090. used_last = true;
  3091. }
  3092. } else if (is_vrs) {
  3093. if (p_passes[last_pass].vrs_attachment == i) {
  3094. used_last = true;
  3095. }
  3096. } else {
  3097. if (p_passes[last_pass].resolve_attachments.size()) {
  3098. // If using resolve attachments, check resolve attachments.
  3099. for (int j = 0; j < p_passes[last_pass].resolve_attachments.size(); j++) {
  3100. if (p_passes[last_pass].resolve_attachments[j] == i) {
  3101. used_last = true;
  3102. break;
  3103. }
  3104. }
  3105. }
  3106. if (!used_last) {
  3107. for (int j = 0; j < p_passes[last_pass].color_attachments.size(); j++) {
  3108. if (p_passes[last_pass].color_attachments[j] == i) {
  3109. used_last = true;
  3110. break;
  3111. }
  3112. }
  3113. }
  3114. }
  3115. if (!used_last) {
  3116. for (int j = 0; j < p_passes[last_pass].preserve_attachments.size(); j++) {
  3117. if (p_passes[last_pass].preserve_attachments[j] == i) {
  3118. used_last = true;
  3119. break;
  3120. }
  3121. }
  3122. }
  3123. }
  3124. FinalAction final_action = p_final_action;
  3125. FinalAction final_depth_action = p_final_depth_action;
  3126. if (!used_last) {
  3127. if (is_depth) {
  3128. final_depth_action = FINAL_ACTION_DISCARD;
  3129. } else {
  3130. final_action = FINAL_ACTION_DISCARD;
  3131. }
  3132. }
  3133. if (is_vrs) {
  3134. // We don't change our VRS texture during this process.
  3135. description.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3136. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3137. description.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  3138. // TODO: Do we need to update our external dependency?
  3139. // update_external_dependency_for_store(dependency_to_external, is_sampled, is_storage, false);
  3140. } else {
  3141. switch (is_depth ? final_depth_action : final_action) {
  3142. case FINAL_ACTION_READ: {
  3143. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3144. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3145. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3146. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  3147. update_external_dependency_for_store(dependency_to_external, is_sampled, is_storage, false);
  3148. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3149. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3150. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
  3151. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  3152. update_external_dependency_for_store(dependency_to_external, is_sampled, is_storage, true);
  3153. } else {
  3154. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3155. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3156. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // Don't care what is there.
  3157. // TODO: What does this mean about the next usage (and thus appropriate dependency masks.
  3158. }
  3159. } break;
  3160. case FINAL_ACTION_DISCARD: {
  3161. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3162. description.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3163. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3164. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  3165. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3166. description.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3167. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3168. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  3169. } else {
  3170. description.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3171. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3172. description.finalLayout = VK_IMAGE_LAYOUT_UNDEFINED; // Don't care what is there.
  3173. }
  3174. } break;
  3175. case FINAL_ACTION_CONTINUE: {
  3176. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3177. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3178. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3179. description.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  3180. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3181. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3182. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
  3183. description.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  3184. } else {
  3185. description.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3186. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3187. description.finalLayout = VK_IMAGE_LAYOUT_UNDEFINED; // Don't care what is there.
  3188. }
  3189. } break;
  3190. default: {
  3191. ERR_FAIL_V(VK_NULL_HANDLE); // Should never reach here.
  3192. }
  3193. }
  3194. }
  3195. attachment_last_pass[i] = -1;
  3196. attachment_remap.push_back(attachments.size());
  3197. attachments.push_back(description);
  3198. }
  3199. LocalVector<VkSubpassDescription2KHR> subpasses;
  3200. LocalVector<LocalVector<VkAttachmentReference2KHR>> color_reference_array;
  3201. LocalVector<LocalVector<VkAttachmentReference2KHR>> input_reference_array;
  3202. LocalVector<LocalVector<VkAttachmentReference2KHR>> resolve_reference_array;
  3203. LocalVector<LocalVector<uint32_t>> preserve_reference_array;
  3204. LocalVector<VkAttachmentReference2KHR> depth_reference_array;
  3205. LocalVector<VkAttachmentReference2KHR> vrs_reference_array;
  3206. LocalVector<VkFragmentShadingRateAttachmentInfoKHR> vrs_attachment_info_array;
  3207. subpasses.resize(p_passes.size());
  3208. color_reference_array.resize(p_passes.size());
  3209. input_reference_array.resize(p_passes.size());
  3210. resolve_reference_array.resize(p_passes.size());
  3211. preserve_reference_array.resize(p_passes.size());
  3212. depth_reference_array.resize(p_passes.size());
  3213. vrs_reference_array.resize(p_passes.size());
  3214. vrs_attachment_info_array.resize(p_passes.size());
  3215. LocalVector<VkSubpassDependency2KHR> subpass_dependencies;
  3216. for (int i = 0; i < p_passes.size(); i++) {
  3217. const FramebufferPass *pass = &p_passes[i];
  3218. LocalVector<VkAttachmentReference2KHR> &color_references = color_reference_array[i];
  3219. TextureSamples texture_samples = TEXTURE_SAMPLES_1;
  3220. bool is_multisample_first = true;
  3221. void *subpass_nextptr = nullptr;
  3222. for (int j = 0; j < pass->color_attachments.size(); j++) {
  3223. int32_t attachment = pass->color_attachments[j];
  3224. VkAttachmentReference2KHR reference;
  3225. reference.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR;
  3226. reference.pNext = nullptr;
  3227. if (attachment == FramebufferPass::ATTACHMENT_UNUSED) {
  3228. reference.attachment = VK_ATTACHMENT_UNUSED;
  3229. reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3230. } else {
  3231. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), color attachment (" + itos(j) + ").");
  3232. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not usable as color attachment.");
  3233. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  3234. if (is_multisample_first) {
  3235. texture_samples = p_attachments[attachment].samples;
  3236. is_multisample_first = false;
  3237. } else {
  3238. ERR_FAIL_COND_V_MSG(texture_samples != p_attachments[attachment].samples, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), if an attachment is marked as multisample, all of them should be multisample and use the same number of samples.");
  3239. }
  3240. reference.attachment = attachment_remap[attachment];
  3241. reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  3242. attachment_last_pass[attachment] = i;
  3243. }
  3244. reference.aspectMask = 0;
  3245. color_references.push_back(reference);
  3246. }
  3247. LocalVector<VkAttachmentReference2KHR> &input_references = input_reference_array[i];
  3248. for (int j = 0; j < pass->input_attachments.size(); j++) {
  3249. int32_t attachment = pass->input_attachments[j];
  3250. VkAttachmentReference2KHR reference;
  3251. reference.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR;
  3252. reference.pNext = nullptr;
  3253. if (attachment == FramebufferPass::ATTACHMENT_UNUSED) {
  3254. reference.attachment = VK_ATTACHMENT_UNUSED;
  3255. reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3256. } else {
  3257. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), input attachment (" + itos(j) + ").");
  3258. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it isn't marked as an input texture.");
  3259. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  3260. reference.attachment = attachment_remap[attachment];
  3261. reference.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  3262. attachment_last_pass[attachment] = i;
  3263. }
  3264. reference.aspectMask = 0; // TODO: We need to set this here, possibly VK_IMAGE_ASPECT_COLOR_BIT?
  3265. input_references.push_back(reference);
  3266. }
  3267. LocalVector<VkAttachmentReference2KHR> &resolve_references = resolve_reference_array[i];
  3268. if (pass->resolve_attachments.size() > 0) {
  3269. ERR_FAIL_COND_V_MSG(pass->resolve_attachments.size() != pass->color_attachments.size(), VK_NULL_HANDLE, "The amount of resolve attachments (" + itos(pass->resolve_attachments.size()) + ") must match the number of color attachments (" + itos(pass->color_attachments.size()) + ").");
  3270. ERR_FAIL_COND_V_MSG(texture_samples == TEXTURE_SAMPLES_1, VK_NULL_HANDLE, "Resolve attachments specified, but color attachments are not multisample.");
  3271. }
  3272. for (int j = 0; j < pass->resolve_attachments.size(); j++) {
  3273. int32_t attachment = pass->resolve_attachments[j];
  3274. VkAttachmentReference2KHR reference;
  3275. reference.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR;
  3276. reference.pNext = nullptr;
  3277. if (attachment == FramebufferPass::ATTACHMENT_UNUSED) {
  3278. reference.attachment = VK_ATTACHMENT_UNUSED;
  3279. reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3280. } else {
  3281. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + ").");
  3282. ERR_FAIL_COND_V_MSG(pass->color_attachments[j] == FramebufferPass::ATTACHMENT_UNUSED, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + "), the respective color attachment is marked as unused.");
  3283. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment, it isn't marked as a color texture.");
  3284. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  3285. bool multisample = p_attachments[attachment].samples > TEXTURE_SAMPLES_1;
  3286. ERR_FAIL_COND_V_MSG(multisample, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachments can't be multisample.");
  3287. reference.attachment = attachment_remap[attachment];
  3288. reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
  3289. attachment_last_pass[attachment] = i;
  3290. }
  3291. reference.aspectMask = 0;
  3292. resolve_references.push_back(reference);
  3293. }
  3294. VkAttachmentReference2KHR &depth_stencil_reference = depth_reference_array[i];
  3295. depth_stencil_reference.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR;
  3296. depth_stencil_reference.pNext = nullptr;
  3297. if (pass->depth_attachment != FramebufferPass::ATTACHMENT_UNUSED) {
  3298. int32_t attachment = pass->depth_attachment;
  3299. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), depth attachment.");
  3300. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not a depth attachment.");
  3301. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  3302. depth_stencil_reference.attachment = attachment_remap[attachment];
  3303. depth_stencil_reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  3304. depth_stencil_reference.aspectMask = 0;
  3305. attachment_last_pass[attachment] = i;
  3306. if (is_multisample_first) {
  3307. texture_samples = p_attachments[attachment].samples;
  3308. is_multisample_first = false;
  3309. } else {
  3310. ERR_FAIL_COND_V_MSG(texture_samples != p_attachments[attachment].samples, VK_NULL_HANDLE, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), if an attachment is marked as multisample, all of them should be multisample and use the same number of samples including the depth.");
  3311. }
  3312. } else {
  3313. depth_stencil_reference.attachment = VK_ATTACHMENT_UNUSED;
  3314. depth_stencil_reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3315. }
  3316. if (context->get_vrs_capabilities().attachment_vrs_supported && pass->vrs_attachment != FramebufferPass::ATTACHMENT_UNUSED) {
  3317. int32_t attachment = pass->vrs_attachment;
  3318. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer VRS format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), VRS attachment.");
  3319. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer VRS format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as VRS, but it's not a VRS attachment.");
  3320. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer VRS attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  3321. VkAttachmentReference2KHR &vrs_reference = vrs_reference_array[i];
  3322. vrs_reference.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2_KHR;
  3323. vrs_reference.pNext = nullptr;
  3324. vrs_reference.attachment = attachment_remap[attachment];
  3325. vrs_reference.layout = VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR;
  3326. vrs_reference.aspectMask = 0;
  3327. Size2i texel_size = context->get_vrs_capabilities().max_texel_size;
  3328. VkFragmentShadingRateAttachmentInfoKHR &vrs_attachment_info = vrs_attachment_info_array[i];
  3329. vrs_attachment_info.sType = VK_STRUCTURE_TYPE_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR;
  3330. vrs_attachment_info.pNext = nullptr;
  3331. vrs_attachment_info.pFragmentShadingRateAttachment = &vrs_reference;
  3332. vrs_attachment_info.shadingRateAttachmentTexelSize = { uint32_t(texel_size.x), uint32_t(texel_size.y) };
  3333. attachment_last_pass[attachment] = i;
  3334. subpass_nextptr = &vrs_attachment_info;
  3335. }
  3336. LocalVector<uint32_t> &preserve_references = preserve_reference_array[i];
  3337. for (int j = 0; j < pass->preserve_attachments.size(); j++) {
  3338. int32_t attachment = pass->preserve_attachments[j];
  3339. ERR_FAIL_COND_V_MSG(attachment == FramebufferPass::ATTACHMENT_UNUSED, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + "). Preserve attachments can't be unused.");
  3340. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + ").");
  3341. if (attachment_last_pass[attachment] != i) {
  3342. // Preserve can still be used to keep depth or color from being discarded after use.
  3343. attachment_last_pass[attachment] = i;
  3344. preserve_references.push_back(attachment);
  3345. }
  3346. }
  3347. VkSubpassDescription2KHR &subpass = subpasses[i];
  3348. subpass.sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR;
  3349. subpass.pNext = subpass_nextptr;
  3350. subpass.flags = 0;
  3351. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  3352. if (p_view_count == 1) {
  3353. // VUID-VkSubpassDescription2-multiview-06558: If the multiview feature is not enabled, viewMask must be 0.
  3354. subpass.viewMask = 0;
  3355. } else {
  3356. subpass.viewMask = view_mask;
  3357. }
  3358. subpass.inputAttachmentCount = input_references.size();
  3359. if (input_references.size()) {
  3360. subpass.pInputAttachments = input_references.ptr();
  3361. } else {
  3362. subpass.pInputAttachments = nullptr;
  3363. }
  3364. subpass.colorAttachmentCount = color_references.size();
  3365. if (color_references.size()) {
  3366. subpass.pColorAttachments = color_references.ptr();
  3367. } else {
  3368. subpass.pColorAttachments = nullptr;
  3369. }
  3370. if (depth_stencil_reference.attachment != VK_ATTACHMENT_UNUSED) {
  3371. subpass.pDepthStencilAttachment = &depth_stencil_reference;
  3372. } else {
  3373. subpass.pDepthStencilAttachment = nullptr;
  3374. }
  3375. if (resolve_references.size()) {
  3376. subpass.pResolveAttachments = resolve_references.ptr();
  3377. } else {
  3378. subpass.pResolveAttachments = nullptr;
  3379. }
  3380. subpass.preserveAttachmentCount = preserve_references.size();
  3381. if (preserve_references.size()) {
  3382. subpass.pPreserveAttachments = preserve_references.ptr();
  3383. } else {
  3384. subpass.pPreserveAttachments = nullptr;
  3385. }
  3386. if (r_samples) {
  3387. r_samples->push_back(texture_samples);
  3388. }
  3389. if (i > 0) {
  3390. VkSubpassDependency2KHR dependency;
  3391. dependency.sType = VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2_KHR;
  3392. dependency.pNext = nullptr;
  3393. dependency.srcSubpass = i - 1;
  3394. dependency.dstSubpass = i;
  3395. dependency.srcStageMask = 0;
  3396. dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  3397. dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  3398. dependency.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  3399. dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
  3400. dependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
  3401. dependency.viewOffset = 0;
  3402. subpass_dependencies.push_back(dependency);
  3403. }
  3404. /*
  3405. // NOTE: Big Mallet Approach -- any layout transition causes a full barrier.
  3406. if (reference.layout != description.initialLayout) {
  3407. // NOTE: This should be smarter based on the texture's knowledge of its previous role.
  3408. dependency_from_external.srcStageMask |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
  3409. dependency_from_external.srcAccessMask |= VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
  3410. }
  3411. if (reference.layout != description.finalLayout) {
  3412. // NOTE: This should be smarter based on the texture's knowledge of its subsequent role.
  3413. dependency_to_external.dstStageMask |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
  3414. dependency_to_external.dstAccessMask |= VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
  3415. }
  3416. */
  3417. }
  3418. VkRenderPassCreateInfo2KHR render_pass_create_info;
  3419. render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2_KHR;
  3420. render_pass_create_info.pNext = nullptr;
  3421. render_pass_create_info.flags = 0;
  3422. render_pass_create_info.attachmentCount = attachments.size();
  3423. render_pass_create_info.pAttachments = attachments.ptr();
  3424. render_pass_create_info.subpassCount = subpasses.size();
  3425. render_pass_create_info.pSubpasses = subpasses.ptr();
  3426. // Commenting this because it seems it just avoids raster and compute to work at the same time.
  3427. // Other barriers seem to be protecting the render pass fine.
  3428. // render_pass_create_info.dependencyCount = 2;
  3429. // render_pass_create_info.pDependencies = dependencies;
  3430. render_pass_create_info.dependencyCount = subpass_dependencies.size();
  3431. if (subpass_dependencies.size()) {
  3432. render_pass_create_info.pDependencies = subpass_dependencies.ptr();
  3433. } else {
  3434. render_pass_create_info.pDependencies = nullptr;
  3435. }
  3436. if (p_view_count == 1) {
  3437. // VUID-VkRenderPassCreateInfo2-viewMask-03057: If the VkSubpassDescription2::viewMask member of all elements of pSubpasses is 0, correlatedViewMaskCount must be 0.
  3438. render_pass_create_info.correlatedViewMaskCount = 0;
  3439. render_pass_create_info.pCorrelatedViewMasks = nullptr;
  3440. } else {
  3441. render_pass_create_info.correlatedViewMaskCount = 1;
  3442. render_pass_create_info.pCorrelatedViewMasks = &correlation_mask;
  3443. }
  3444. Vector<uint32_t> view_masks;
  3445. VkRenderPassMultiviewCreateInfo render_pass_multiview_create_info;
  3446. if (p_view_count > 1) {
  3447. // This may no longer be needed with the new settings already including this.
  3448. const VulkanContext::MultiviewCapabilities capabilities = context->get_multiview_capabilities();
  3449. // For now this only works with multiview!
  3450. ERR_FAIL_COND_V_MSG(!capabilities.is_supported, VK_NULL_HANDLE, "Multiview not supported");
  3451. // Make sure we limit this to the number of views we support.
  3452. ERR_FAIL_COND_V_MSG(p_view_count > capabilities.max_view_count, VK_NULL_HANDLE, "Hardware does not support requested number of views for Multiview render pass");
  3453. // Set view masks for each subpass.
  3454. for (uint32_t i = 0; i < subpasses.size(); i++) {
  3455. view_masks.push_back(view_mask);
  3456. }
  3457. render_pass_multiview_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO;
  3458. render_pass_multiview_create_info.pNext = nullptr;
  3459. render_pass_multiview_create_info.subpassCount = subpasses.size();
  3460. render_pass_multiview_create_info.pViewMasks = view_masks.ptr();
  3461. render_pass_multiview_create_info.dependencyCount = 0;
  3462. render_pass_multiview_create_info.pViewOffsets = nullptr;
  3463. render_pass_multiview_create_info.correlationMaskCount = 1;
  3464. render_pass_multiview_create_info.pCorrelationMasks = &correlation_mask;
  3465. render_pass_create_info.pNext = &render_pass_multiview_create_info;
  3466. }
  3467. VkRenderPass render_pass;
  3468. VkResult res = context->vkCreateRenderPass2KHR(device, &render_pass_create_info, nullptr, &render_pass);
  3469. ERR_FAIL_COND_V_MSG(res, VK_NULL_HANDLE, "vkCreateRenderPass2KHR failed with error " + itos(res) + ".");
  3470. return render_pass;
  3471. }
  3472. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create(const Vector<AttachmentFormat> &p_format, uint32_t p_view_count) {
  3473. FramebufferPass pass;
  3474. for (int i = 0; i < p_format.size(); i++) {
  3475. if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3476. pass.depth_attachment = i;
  3477. } else {
  3478. pass.color_attachments.push_back(i);
  3479. }
  3480. }
  3481. Vector<FramebufferPass> passes;
  3482. passes.push_back(pass);
  3483. return framebuffer_format_create_multipass(p_format, passes, p_view_count);
  3484. }
  3485. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create_multipass(const Vector<AttachmentFormat> &p_attachments, const Vector<FramebufferPass> &p_passes, uint32_t p_view_count) {
  3486. _THREAD_SAFE_METHOD_
  3487. FramebufferFormatKey key;
  3488. key.attachments = p_attachments;
  3489. key.passes = p_passes;
  3490. key.view_count = p_view_count;
  3491. const RBMap<FramebufferFormatKey, FramebufferFormatID>::Element *E = framebuffer_format_cache.find(key);
  3492. if (E) {
  3493. // Exists, return.
  3494. return E->get();
  3495. }
  3496. Vector<TextureSamples> samples;
  3497. VkRenderPass render_pass = _render_pass_create(p_attachments, p_passes, INITIAL_ACTION_CLEAR, FINAL_ACTION_READ, INITIAL_ACTION_CLEAR, FINAL_ACTION_READ, p_view_count, &samples); // Actions don't matter for this use case.
  3498. if (render_pass == VK_NULL_HANDLE) { // Was likely invalid.
  3499. return INVALID_ID;
  3500. }
  3501. FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT));
  3502. E = framebuffer_format_cache.insert(key, id);
  3503. FramebufferFormat fb_format;
  3504. fb_format.E = E;
  3505. fb_format.render_pass = render_pass;
  3506. fb_format.pass_samples = samples;
  3507. fb_format.view_count = p_view_count;
  3508. framebuffer_formats[id] = fb_format;
  3509. return id;
  3510. }
  3511. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create_empty(TextureSamples p_samples) {
  3512. FramebufferFormatKey key;
  3513. key.passes.push_back(FramebufferPass());
  3514. const RBMap<FramebufferFormatKey, FramebufferFormatID>::Element *E = framebuffer_format_cache.find(key);
  3515. if (E) {
  3516. // Exists, return.
  3517. return E->get();
  3518. }
  3519. VkSubpassDescription2KHR subpass;
  3520. subpass.sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR;
  3521. subpass.pNext = nullptr;
  3522. subpass.flags = 0;
  3523. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  3524. subpass.viewMask = 0;
  3525. subpass.inputAttachmentCount = 0; // Unsupported for now.
  3526. subpass.pInputAttachments = nullptr;
  3527. subpass.colorAttachmentCount = 0;
  3528. subpass.pColorAttachments = nullptr;
  3529. subpass.pDepthStencilAttachment = nullptr;
  3530. subpass.pResolveAttachments = nullptr;
  3531. subpass.preserveAttachmentCount = 0;
  3532. subpass.pPreserveAttachments = nullptr;
  3533. VkRenderPassCreateInfo2KHR render_pass_create_info;
  3534. render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2_KHR;
  3535. render_pass_create_info.pNext = nullptr;
  3536. render_pass_create_info.flags = 0;
  3537. render_pass_create_info.attachmentCount = 0;
  3538. render_pass_create_info.pAttachments = nullptr;
  3539. render_pass_create_info.subpassCount = 1;
  3540. render_pass_create_info.pSubpasses = &subpass;
  3541. render_pass_create_info.dependencyCount = 0;
  3542. render_pass_create_info.pDependencies = nullptr;
  3543. render_pass_create_info.correlatedViewMaskCount = 0;
  3544. render_pass_create_info.pCorrelatedViewMasks = nullptr;
  3545. VkRenderPass render_pass;
  3546. VkResult res = context->vkCreateRenderPass2KHR(device, &render_pass_create_info, nullptr, &render_pass);
  3547. ERR_FAIL_COND_V_MSG(res, 0, "vkCreateRenderPass2KHR for empty fb failed with error " + itos(res) + ".");
  3548. if (render_pass == VK_NULL_HANDLE) { // Was likely invalid.
  3549. return INVALID_ID;
  3550. }
  3551. FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT));
  3552. E = framebuffer_format_cache.insert(key, id);
  3553. FramebufferFormat fb_format;
  3554. fb_format.E = E;
  3555. fb_format.render_pass = render_pass;
  3556. fb_format.pass_samples.push_back(p_samples);
  3557. framebuffer_formats[id] = fb_format;
  3558. return id;
  3559. }
  3560. RenderingDevice::TextureSamples RenderingDeviceVulkan::framebuffer_format_get_texture_samples(FramebufferFormatID p_format, uint32_t p_pass) {
  3561. HashMap<FramebufferFormatID, FramebufferFormat>::Iterator E = framebuffer_formats.find(p_format);
  3562. ERR_FAIL_COND_V(!E, TEXTURE_SAMPLES_1);
  3563. ERR_FAIL_COND_V(p_pass >= uint32_t(E->value.pass_samples.size()), TEXTURE_SAMPLES_1);
  3564. return E->value.pass_samples[p_pass];
  3565. }
  3566. /***********************/
  3567. /**** RENDER TARGET ****/
  3568. /***********************/
  3569. RID RenderingDeviceVulkan::framebuffer_create_empty(const Size2i &p_size, TextureSamples p_samples, FramebufferFormatID p_format_check) {
  3570. _THREAD_SAFE_METHOD_
  3571. Framebuffer framebuffer;
  3572. framebuffer.format_id = framebuffer_format_create_empty(p_samples);
  3573. ERR_FAIL_COND_V(p_format_check != INVALID_FORMAT_ID && framebuffer.format_id != p_format_check, RID());
  3574. framebuffer.size = p_size;
  3575. framebuffer.view_count = 1;
  3576. RID id = framebuffer_owner.make_rid(framebuffer);
  3577. #ifdef DEV_ENABLED
  3578. set_resource_name(id, "RID:" + itos(id.get_id()));
  3579. #endif
  3580. return id;
  3581. }
  3582. RID RenderingDeviceVulkan::framebuffer_create(const Vector<RID> &p_texture_attachments, FramebufferFormatID p_format_check, uint32_t p_view_count) {
  3583. _THREAD_SAFE_METHOD_
  3584. FramebufferPass pass;
  3585. for (int i = 0; i < p_texture_attachments.size(); i++) {
  3586. Texture *texture = texture_owner.get_or_null(p_texture_attachments[i]);
  3587. ERR_FAIL_COND_V_MSG(texture && texture->layers != p_view_count, RID(), "Layers of our texture doesn't match view count for this framebuffer");
  3588. if (texture && texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3589. pass.depth_attachment = i;
  3590. } else if (texture && texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) {
  3591. pass.vrs_attachment = i;
  3592. } else {
  3593. if (texture && texture->is_resolve_buffer) {
  3594. pass.resolve_attachments.push_back(i);
  3595. } else {
  3596. pass.color_attachments.push_back(texture ? i : FramebufferPass::ATTACHMENT_UNUSED);
  3597. }
  3598. }
  3599. }
  3600. Vector<FramebufferPass> passes;
  3601. passes.push_back(pass);
  3602. return framebuffer_create_multipass(p_texture_attachments, passes, p_format_check, p_view_count);
  3603. }
  3604. RID RenderingDeviceVulkan::framebuffer_create_multipass(const Vector<RID> &p_texture_attachments, const Vector<FramebufferPass> &p_passes, FramebufferFormatID p_format_check, uint32_t p_view_count) {
  3605. _THREAD_SAFE_METHOD_
  3606. Vector<AttachmentFormat> attachments;
  3607. attachments.resize(p_texture_attachments.size());
  3608. Size2i size;
  3609. bool size_set = false;
  3610. for (int i = 0; i < p_texture_attachments.size(); i++) {
  3611. AttachmentFormat af;
  3612. Texture *texture = texture_owner.get_or_null(p_texture_attachments[i]);
  3613. if (!texture) {
  3614. af.usage_flags = AttachmentFormat::UNUSED_ATTACHMENT;
  3615. } else {
  3616. ERR_FAIL_COND_V_MSG(texture->layers != p_view_count, RID(), "Layers of our texture doesn't match view count for this framebuffer");
  3617. if (!size_set) {
  3618. size.width = texture->width;
  3619. size.height = texture->height;
  3620. size_set = true;
  3621. } else if (texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) {
  3622. // If this is not the first attachement we assume this is used as the VRS attachment.
  3623. // In this case this texture will be 1/16th the size of the color attachement.
  3624. // So we skip the size check.
  3625. } else {
  3626. ERR_FAIL_COND_V_MSG((uint32_t)size.width != texture->width || (uint32_t)size.height != texture->height, RID(),
  3627. "All textures in a framebuffer should be the same size.");
  3628. }
  3629. af.format = texture->format;
  3630. af.samples = texture->samples;
  3631. af.usage_flags = texture->usage_flags;
  3632. }
  3633. attachments.write[i] = af;
  3634. }
  3635. ERR_FAIL_COND_V_MSG(!size_set, RID(), "All attachments unused.");
  3636. FramebufferFormatID format_id = framebuffer_format_create_multipass(attachments, p_passes, p_view_count);
  3637. if (format_id == INVALID_ID) {
  3638. return RID();
  3639. }
  3640. ERR_FAIL_COND_V_MSG(p_format_check != INVALID_ID && format_id != p_format_check, RID(),
  3641. "The format used to check this framebuffer differs from the intended framebuffer format.");
  3642. Framebuffer framebuffer;
  3643. framebuffer.format_id = format_id;
  3644. framebuffer.texture_ids = p_texture_attachments;
  3645. framebuffer.size = size;
  3646. framebuffer.view_count = p_view_count;
  3647. RID id = framebuffer_owner.make_rid(framebuffer);
  3648. #ifdef DEV_ENABLED
  3649. set_resource_name(id, "RID:" + itos(id.get_id()));
  3650. #endif
  3651. for (int i = 0; i < p_texture_attachments.size(); i++) {
  3652. if (p_texture_attachments[i].is_valid()) {
  3653. _add_dependency(id, p_texture_attachments[i]);
  3654. }
  3655. }
  3656. return id;
  3657. }
  3658. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_get_format(RID p_framebuffer) {
  3659. _THREAD_SAFE_METHOD_
  3660. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  3661. ERR_FAIL_COND_V(!framebuffer, INVALID_ID);
  3662. return framebuffer->format_id;
  3663. }
  3664. bool RenderingDeviceVulkan::framebuffer_is_valid(RID p_framebuffer) const {
  3665. _THREAD_SAFE_METHOD_
  3666. return framebuffer_owner.owns(p_framebuffer);
  3667. }
  3668. void RenderingDeviceVulkan::framebuffer_set_invalidation_callback(RID p_framebuffer, InvalidationCallback p_callback, void *p_userdata) {
  3669. _THREAD_SAFE_METHOD_
  3670. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  3671. ERR_FAIL_COND(!framebuffer);
  3672. framebuffer->invalidated_callback = p_callback;
  3673. framebuffer->invalidated_callback_userdata = p_userdata;
  3674. }
  3675. /*****************/
  3676. /**** SAMPLER ****/
  3677. /*****************/
  3678. RID RenderingDeviceVulkan::sampler_create(const SamplerState &p_state) {
  3679. _THREAD_SAFE_METHOD_
  3680. VkSamplerCreateInfo sampler_create_info;
  3681. sampler_create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  3682. sampler_create_info.pNext = nullptr;
  3683. sampler_create_info.flags = 0;
  3684. sampler_create_info.magFilter = p_state.mag_filter == SAMPLER_FILTER_LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
  3685. sampler_create_info.minFilter = p_state.min_filter == SAMPLER_FILTER_LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
  3686. sampler_create_info.mipmapMode = p_state.mip_filter == SAMPLER_FILTER_LINEAR ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST;
  3687. ERR_FAIL_INDEX_V(p_state.repeat_u, SAMPLER_REPEAT_MODE_MAX, RID());
  3688. sampler_create_info.addressModeU = address_modes[p_state.repeat_u];
  3689. ERR_FAIL_INDEX_V(p_state.repeat_v, SAMPLER_REPEAT_MODE_MAX, RID());
  3690. sampler_create_info.addressModeV = address_modes[p_state.repeat_v];
  3691. ERR_FAIL_INDEX_V(p_state.repeat_w, SAMPLER_REPEAT_MODE_MAX, RID());
  3692. sampler_create_info.addressModeW = address_modes[p_state.repeat_w];
  3693. sampler_create_info.mipLodBias = p_state.lod_bias;
  3694. sampler_create_info.anisotropyEnable = p_state.use_anisotropy;
  3695. sampler_create_info.maxAnisotropy = p_state.anisotropy_max;
  3696. sampler_create_info.compareEnable = p_state.enable_compare;
  3697. ERR_FAIL_INDEX_V(p_state.compare_op, COMPARE_OP_MAX, RID());
  3698. sampler_create_info.compareOp = compare_operators[p_state.compare_op];
  3699. sampler_create_info.minLod = p_state.min_lod;
  3700. sampler_create_info.maxLod = p_state.max_lod;
  3701. ERR_FAIL_INDEX_V(p_state.border_color, SAMPLER_BORDER_COLOR_MAX, RID());
  3702. sampler_create_info.borderColor = sampler_border_colors[p_state.border_color];
  3703. sampler_create_info.unnormalizedCoordinates = p_state.unnormalized_uvw;
  3704. VkSampler sampler;
  3705. VkResult res = vkCreateSampler(device, &sampler_create_info, nullptr, &sampler);
  3706. ERR_FAIL_COND_V_MSG(res, RID(), "vkCreateSampler failed with error " + itos(res) + ".");
  3707. RID id = sampler_owner.make_rid(sampler);
  3708. #ifdef DEV_ENABLED
  3709. set_resource_name(id, "RID:" + itos(id.get_id()));
  3710. #endif
  3711. return id;
  3712. }
  3713. /**********************/
  3714. /**** VERTEX ARRAY ****/
  3715. /**********************/
  3716. RID RenderingDeviceVulkan::vertex_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data, bool p_use_as_storage) {
  3717. _THREAD_SAFE_METHOD_
  3718. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  3719. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  3720. "Creating buffers with data is forbidden during creation of a draw list");
  3721. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  3722. "Creating buffers with data is forbidden during creation of a draw list");
  3723. uint32_t usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
  3724. if (p_use_as_storage) {
  3725. usage |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
  3726. }
  3727. Buffer buffer;
  3728. _buffer_allocate(&buffer, p_size_bytes, usage, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0);
  3729. if (p_data.size()) {
  3730. uint64_t data_size = p_data.size();
  3731. const uint8_t *r = p_data.ptr();
  3732. _buffer_update(&buffer, 0, r, data_size);
  3733. _buffer_memory_barrier(buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, false);
  3734. }
  3735. RID id = vertex_buffer_owner.make_rid(buffer);
  3736. #ifdef DEV_ENABLED
  3737. set_resource_name(id, "RID:" + itos(id.get_id()));
  3738. #endif
  3739. return id;
  3740. }
  3741. // Internally reference counted, this ID is warranted to be unique for the same description, but needs to be freed as many times as it was allocated.
  3742. RenderingDevice::VertexFormatID RenderingDeviceVulkan::vertex_format_create(const Vector<VertexAttribute> &p_vertex_formats) {
  3743. _THREAD_SAFE_METHOD_
  3744. VertexDescriptionKey key;
  3745. key.vertex_formats = p_vertex_formats;
  3746. VertexFormatID *idptr = vertex_format_cache.getptr(key);
  3747. if (idptr) {
  3748. return *idptr;
  3749. }
  3750. // Does not exist, create one and cache it.
  3751. VertexDescriptionCache vdcache;
  3752. vdcache.bindings = memnew_arr(VkVertexInputBindingDescription, p_vertex_formats.size());
  3753. vdcache.attributes = memnew_arr(VkVertexInputAttributeDescription, p_vertex_formats.size());
  3754. HashSet<int> used_locations;
  3755. for (int i = 0; i < p_vertex_formats.size(); i++) {
  3756. ERR_CONTINUE(p_vertex_formats[i].format >= DATA_FORMAT_MAX);
  3757. ERR_FAIL_COND_V(used_locations.has(p_vertex_formats[i].location), INVALID_ID);
  3758. ERR_FAIL_COND_V_MSG(get_format_vertex_size(p_vertex_formats[i].format) == 0, INVALID_ID,
  3759. "Data format for attachment (" + itos(i) + "), '" + named_formats[p_vertex_formats[i].format] + "', is not valid for a vertex array.");
  3760. vdcache.bindings[i].binding = i;
  3761. vdcache.bindings[i].stride = p_vertex_formats[i].stride;
  3762. vdcache.bindings[i].inputRate = p_vertex_formats[i].frequency == VERTEX_FREQUENCY_INSTANCE ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX;
  3763. vdcache.attributes[i].binding = i;
  3764. vdcache.attributes[i].location = p_vertex_formats[i].location;
  3765. vdcache.attributes[i].format = vulkan_formats[p_vertex_formats[i].format];
  3766. vdcache.attributes[i].offset = p_vertex_formats[i].offset;
  3767. used_locations.insert(p_vertex_formats[i].location);
  3768. }
  3769. vdcache.create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  3770. vdcache.create_info.pNext = nullptr;
  3771. vdcache.create_info.flags = 0;
  3772. vdcache.create_info.vertexAttributeDescriptionCount = p_vertex_formats.size();
  3773. vdcache.create_info.pVertexAttributeDescriptions = vdcache.attributes;
  3774. vdcache.create_info.vertexBindingDescriptionCount = p_vertex_formats.size();
  3775. vdcache.create_info.pVertexBindingDescriptions = vdcache.bindings;
  3776. vdcache.vertex_formats = p_vertex_formats;
  3777. VertexFormatID id = VertexFormatID(vertex_format_cache.size()) | (VertexFormatID(ID_TYPE_VERTEX_FORMAT) << ID_BASE_SHIFT);
  3778. vertex_format_cache[key] = id;
  3779. vertex_formats[id] = vdcache;
  3780. return id;
  3781. }
  3782. RID RenderingDeviceVulkan::vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector<RID> &p_src_buffers) {
  3783. _THREAD_SAFE_METHOD_
  3784. ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID());
  3785. const VertexDescriptionCache &vd = vertex_formats[p_vertex_format];
  3786. ERR_FAIL_COND_V(vd.vertex_formats.size() != p_src_buffers.size(), RID());
  3787. for (int i = 0; i < p_src_buffers.size(); i++) {
  3788. ERR_FAIL_COND_V(!vertex_buffer_owner.owns(p_src_buffers[i]), RID());
  3789. }
  3790. VertexArray vertex_array;
  3791. vertex_array.vertex_count = p_vertex_count;
  3792. vertex_array.description = p_vertex_format;
  3793. vertex_array.max_instances_allowed = 0xFFFFFFFF; // By default as many as you want.
  3794. for (int i = 0; i < p_src_buffers.size(); i++) {
  3795. Buffer *buffer = vertex_buffer_owner.get_or_null(p_src_buffers[i]);
  3796. // Validate with buffer.
  3797. {
  3798. const VertexAttribute &atf = vd.vertex_formats[i];
  3799. uint32_t element_size = get_format_vertex_size(atf.format);
  3800. ERR_FAIL_COND_V(element_size == 0, RID()); // Should never happens since this was prevalidated.
  3801. if (atf.frequency == VERTEX_FREQUENCY_VERTEX) {
  3802. // Validate size for regular drawing.
  3803. uint64_t total_size = uint64_t(atf.stride) * (p_vertex_count - 1) + atf.offset + element_size;
  3804. ERR_FAIL_COND_V_MSG(total_size > buffer->size, RID(),
  3805. "Attachment (" + itos(i) + ") will read past the end of the buffer.");
  3806. } else {
  3807. // Validate size for instances drawing.
  3808. uint64_t available = buffer->size - atf.offset;
  3809. ERR_FAIL_COND_V_MSG(available < element_size, RID(),
  3810. "Attachment (" + itos(i) + ") uses instancing, but it's just too small.");
  3811. uint32_t instances_allowed = available / atf.stride;
  3812. vertex_array.max_instances_allowed = MIN(instances_allowed, vertex_array.max_instances_allowed);
  3813. }
  3814. }
  3815. vertex_array.buffers.push_back(buffer->buffer);
  3816. vertex_array.offsets.push_back(0); // Offset unused, but passing anyway.
  3817. }
  3818. RID id = vertex_array_owner.make_rid(vertex_array);
  3819. for (int i = 0; i < p_src_buffers.size(); i++) {
  3820. _add_dependency(id, p_src_buffers[i]);
  3821. }
  3822. return id;
  3823. }
  3824. RID RenderingDeviceVulkan::index_buffer_create(uint32_t p_index_count, IndexBufferFormat p_format, const Vector<uint8_t> &p_data, bool p_use_restart_indices) {
  3825. _THREAD_SAFE_METHOD_
  3826. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  3827. "Creating buffers with data is forbidden during creation of a draw list");
  3828. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  3829. "Creating buffers with data is forbidden during creation of a draw list");
  3830. ERR_FAIL_COND_V(p_index_count == 0, RID());
  3831. IndexBuffer index_buffer;
  3832. index_buffer.index_type = (p_format == INDEX_BUFFER_FORMAT_UINT16) ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32;
  3833. index_buffer.supports_restart_indices = p_use_restart_indices;
  3834. index_buffer.index_count = p_index_count;
  3835. uint32_t size_bytes = p_index_count * ((p_format == INDEX_BUFFER_FORMAT_UINT16) ? 2 : 4);
  3836. #ifdef DEBUG_ENABLED
  3837. if (p_data.size()) {
  3838. index_buffer.max_index = 0;
  3839. ERR_FAIL_COND_V_MSG((uint32_t)p_data.size() != size_bytes, RID(),
  3840. "Default index buffer initializer array size (" + itos(p_data.size()) + ") does not match format required size (" + itos(size_bytes) + ").");
  3841. const uint8_t *r = p_data.ptr();
  3842. if (p_format == INDEX_BUFFER_FORMAT_UINT16) {
  3843. const uint16_t *index16 = (const uint16_t *)r;
  3844. for (uint32_t i = 0; i < p_index_count; i++) {
  3845. if (p_use_restart_indices && index16[i] == 0xFFFF) {
  3846. continue; // Restart index, ignore.
  3847. }
  3848. index_buffer.max_index = MAX(index16[i], index_buffer.max_index);
  3849. }
  3850. } else {
  3851. const uint32_t *index32 = (const uint32_t *)r;
  3852. for (uint32_t i = 0; i < p_index_count; i++) {
  3853. if (p_use_restart_indices && index32[i] == 0xFFFFFFFF) {
  3854. continue; // Restart index, ignore.
  3855. }
  3856. index_buffer.max_index = MAX(index32[i], index_buffer.max_index);
  3857. }
  3858. }
  3859. } else {
  3860. index_buffer.max_index = 0xFFFFFFFF;
  3861. }
  3862. #else
  3863. index_buffer.max_index = 0xFFFFFFFF;
  3864. #endif
  3865. _buffer_allocate(&index_buffer, size_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0);
  3866. if (p_data.size()) {
  3867. uint64_t data_size = p_data.size();
  3868. const uint8_t *r = p_data.ptr();
  3869. _buffer_update(&index_buffer, 0, r, data_size);
  3870. _buffer_memory_barrier(index_buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_INDEX_READ_BIT, false);
  3871. }
  3872. RID id = index_buffer_owner.make_rid(index_buffer);
  3873. #ifdef DEV_ENABLED
  3874. set_resource_name(id, "RID:" + itos(id.get_id()));
  3875. #endif
  3876. return id;
  3877. }
  3878. RID RenderingDeviceVulkan::index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count) {
  3879. _THREAD_SAFE_METHOD_
  3880. ERR_FAIL_COND_V(!index_buffer_owner.owns(p_index_buffer), RID());
  3881. IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_index_buffer);
  3882. ERR_FAIL_COND_V(p_index_count == 0, RID());
  3883. ERR_FAIL_COND_V(p_index_offset + p_index_count > index_buffer->index_count, RID());
  3884. IndexArray index_array;
  3885. index_array.max_index = index_buffer->max_index;
  3886. index_array.buffer = index_buffer->buffer;
  3887. index_array.offset = p_index_offset;
  3888. index_array.indices = p_index_count;
  3889. index_array.index_type = index_buffer->index_type;
  3890. index_array.supports_restart_indices = index_buffer->supports_restart_indices;
  3891. RID id = index_array_owner.make_rid(index_array);
  3892. _add_dependency(id, p_index_buffer);
  3893. return id;
  3894. }
  3895. /****************/
  3896. /**** SHADER ****/
  3897. /****************/
  3898. static const char *shader_stage_names[RenderingDevice::SHADER_STAGE_MAX] = {
  3899. "Vertex",
  3900. "Fragment",
  3901. "TesselationControl",
  3902. "TesselationEvaluation",
  3903. "Compute"
  3904. };
  3905. static const char *shader_uniform_names[RenderingDevice::UNIFORM_TYPE_MAX] = {
  3906. "Sampler", "CombinedSampler", "Texture", "Image", "TextureBuffer", "SamplerTextureBuffer", "ImageBuffer", "UniformBuffer", "StorageBuffer", "InputAttachment"
  3907. };
  3908. static VkShaderStageFlagBits shader_stage_masks[RenderingDevice::SHADER_STAGE_MAX] = {
  3909. VK_SHADER_STAGE_VERTEX_BIT,
  3910. VK_SHADER_STAGE_FRAGMENT_BIT,
  3911. VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT,
  3912. VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
  3913. VK_SHADER_STAGE_COMPUTE_BIT,
  3914. };
  3915. String RenderingDeviceVulkan::_shader_uniform_debug(RID p_shader, int p_set) {
  3916. String ret;
  3917. const Shader *shader = shader_owner.get_or_null(p_shader);
  3918. ERR_FAIL_COND_V(!shader, String());
  3919. for (int i = 0; i < shader->sets.size(); i++) {
  3920. if (p_set >= 0 && i != p_set) {
  3921. continue;
  3922. }
  3923. for (int j = 0; j < shader->sets[i].uniform_info.size(); j++) {
  3924. const UniformInfo &ui = shader->sets[i].uniform_info[j];
  3925. if (!ret.is_empty()) {
  3926. ret += "\n";
  3927. }
  3928. ret += "Set: " + itos(i) + " Binding: " + itos(ui.binding) + " Type: " + shader_uniform_names[ui.type] + " Writable: " + (ui.writable ? "Y" : "N") + " Length: " + itos(ui.length);
  3929. }
  3930. }
  3931. return ret;
  3932. }
  3933. #if 0
  3934. bool RenderingDeviceVulkan::_uniform_add_binding(Vector<Vector<VkDescriptorSetLayoutBinding> > &bindings, Vector<Vector<UniformInfo> > &uniform_infos, const glslang::TObjectReflection &reflection, RenderingDevice::ShaderStage p_stage, Shader::PushConstant &push_constant, String *r_error) {
  3935. VkDescriptorSetLayoutBinding layout_binding;
  3936. UniformInfo info;
  3937. switch (reflection.getType()->getBasicType()) {
  3938. case glslang::EbtSampler: {
  3939. //print_line("DEBUG: IsSampler");
  3940. if (reflection.getType()->getSampler().dim == glslang::EsdBuffer) {
  3941. // Texture buffers.
  3942. if (reflection.getType()->getSampler().isCombined()) {
  3943. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  3944. info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER;
  3945. //print_line("DEBUG: SAMPLER: texel combined");
  3946. } else if (reflection.getType()->getSampler().isTexture()) {
  3947. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  3948. info.type = UNIFORM_TYPE_TEXTURE_BUFFER;
  3949. //print_line("DEBUG: SAMPLER: texel alone");
  3950. } else if (reflection.getType()->getSampler().isImage()) {
  3951. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
  3952. info.type = UNIFORM_TYPE_IMAGE_BUFFER;
  3953. //print_line("DEBUG: SAMPLER: texel buffer");
  3954. } else {
  3955. if (r_error) {
  3956. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' is of unsupported buffer type.";
  3957. }
  3958. return false;
  3959. }
  3960. } else if (reflection.getType()->getSampler().isCombined()) {
  3961. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  3962. info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
  3963. //print_line("DEBUG: SAMPLER: combined");
  3964. } else if (reflection.getType()->getSampler().isPureSampler()) {
  3965. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
  3966. info.type = UNIFORM_TYPE_SAMPLER;
  3967. //print_line("DEBUG: SAMPLER: sampler");
  3968. } else if (reflection.getType()->getSampler().isTexture()) {
  3969. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  3970. info.type = UNIFORM_TYPE_TEXTURE;
  3971. //print_line("DEBUG: SAMPLER: image");
  3972. } else if (reflection.getType()->getSampler().isImage()) {
  3973. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  3974. info.type = UNIFORM_TYPE_IMAGE;
  3975. //print_line("DEBUG: SAMPLER: storage image");
  3976. } else {
  3977. //print_line("DEBUG: sampler unknown");
  3978. if (r_error) {
  3979. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' is of unsupported sampler type.";
  3980. }
  3981. return false;
  3982. }
  3983. if (reflection.getType()->isArray()) {
  3984. layout_binding.descriptorCount = reflection.getType()->getArraySizes()->getCumulativeSize();
  3985. //print_line("DEBUG: array of size: " + itos(layout_binding.descriptorCount));
  3986. } else {
  3987. layout_binding.descriptorCount = 1;
  3988. }
  3989. info.length = layout_binding.descriptorCount;
  3990. } break;
  3991. /*case glslang::EbtStruct: {
  3992. print_line("DEBUG: Struct");
  3993. } break;*/
  3994. case glslang::EbtBlock: {
  3995. //print_line("DEBUG: Block");
  3996. if (reflection.getType()->getQualifier().storage == glslang::EvqUniform) {
  3997. if (reflection.getType()->getQualifier().layoutPushConstant) {
  3998. uint32_t len = reflection.size;
  3999. if (push_constant.push_constant_size != 0 && push_constant.push_constant_size != len) {
  4000. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' push constants for different stages should all be the same size.";
  4001. return false;
  4002. }
  4003. push_constant.push_constant_size = len;
  4004. push_constant.push_constants_vk_stage |= shader_stage_masks[p_stage];
  4005. return true;
  4006. }
  4007. //print_line("DEBUG: Uniform buffer");
  4008. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  4009. info.type = UNIFORM_TYPE_UNIFORM_BUFFER;
  4010. } else if (reflection.getType()->getQualifier().storage == glslang::EvqBuffer) {
  4011. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  4012. info.type = UNIFORM_TYPE_STORAGE_BUFFER;
  4013. //print_line("DEBUG: Storage buffer");
  4014. } else {
  4015. if (r_error) {
  4016. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' is of unsupported block type: (" + itos(reflection.getType()->getQualifier().storage) + ").";
  4017. }
  4018. return false;
  4019. }
  4020. if (reflection.getType()->isArray()) {
  4021. layout_binding.descriptorCount = reflection.getType()->getArraySizes()->getCumulativeSize();
  4022. //print_line("DEBUG: array of size: " + itos(layout_binding.descriptorCount));
  4023. } else {
  4024. layout_binding.descriptorCount = 1;
  4025. }
  4026. info.length = reflection.size;
  4027. } break;
  4028. /*case glslang::EbtReference: {
  4029. } break;*/
  4030. /*case glslang::EbtAtomicUint: {
  4031. } break;*/
  4032. default: {
  4033. if (reflection.getType()->getQualifier().hasOffset() || reflection.name.find(".") != std::string::npos) {
  4034. // Member of uniform block?
  4035. return true;
  4036. }
  4037. if (r_error) {
  4038. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' unsupported uniform type.";
  4039. }
  4040. return false;
  4041. }
  4042. }
  4043. if (!reflection.getType()->getQualifier().hasBinding()) {
  4044. if (r_error) {
  4045. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' lacks a binding number.";
  4046. }
  4047. return false;
  4048. }
  4049. uint32_t set = reflection.getType()->getQualifier().hasSet() ? reflection.getType()->getQualifier().layoutSet : 0;
  4050. if (set >= MAX_UNIFORM_SETS) {
  4051. if (r_error) {
  4052. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' uses a set (" + itos(set) + ") index larger than what is supported (" + itos(MAX_UNIFORM_SETS) + ").";
  4053. }
  4054. return false;
  4055. }
  4056. if (set >= limits.maxBoundDescriptorSets) {
  4057. if (r_error) {
  4058. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' uses a set (" + itos(set) + ") index larger than what is supported by the hardware (" + itos(limits.maxBoundDescriptorSets) + ").";
  4059. }
  4060. return false;
  4061. }
  4062. uint32_t binding = reflection.getType()->getQualifier().layoutBinding;
  4063. if (set < (uint32_t)bindings.size()) {
  4064. // Check if this already exists.
  4065. for (int i = 0; i < bindings[set].size(); i++) {
  4066. if (bindings[set][i].binding == binding) {
  4067. // Already exists, verify that it's the same type.
  4068. if (bindings[set][i].descriptorType != layout_binding.descriptorType) {
  4069. if (r_error) {
  4070. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' trying to re-use location for set=" + itos(set) + ", binding=" + itos(binding) + " with different uniform type.";
  4071. }
  4072. return false;
  4073. }
  4074. // Also, verify that it's the same size.
  4075. if (bindings[set][i].descriptorCount != layout_binding.descriptorCount || uniform_infos[set][i].length != info.length) {
  4076. if (r_error) {
  4077. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' trying to re-use location for set=" + itos(set) + ", binding=" + itos(binding) + " with different uniform size.";
  4078. }
  4079. return false;
  4080. }
  4081. // Just append stage mask and return.
  4082. bindings.write[set].write[i].stageFlags |= shader_stage_masks[p_stage];
  4083. uniform_infos.write[set].write[i].stages |= 1 << p_stage;
  4084. return true;
  4085. }
  4086. }
  4087. }
  4088. layout_binding.binding = binding;
  4089. layout_binding.stageFlags = shader_stage_masks[p_stage];
  4090. layout_binding.pImmutableSamplers = nullptr; // No support for this yet.
  4091. info.stages = 1 << p_stage;
  4092. info.binding = binding;
  4093. if (set >= (uint32_t)bindings.size()) {
  4094. bindings.resize(set + 1);
  4095. uniform_infos.resize(set + 1);
  4096. }
  4097. #if 0
  4098. print_line("stage: " + String(shader_stage_names[p_stage]) + " set: " + itos(set) + " binding: " + itos(info.binding) + " type:" + shader_uniform_names[info.type] + " length: " + itos(info.length));
  4099. #endif
  4100. bindings.write[set].push_back(layout_binding);
  4101. uniform_infos.write[set].push_back(info);
  4102. return true;
  4103. }
  4104. #endif
  4105. // Version 1: initial.
  4106. // Version 2: Added shader name.
  4107. // Version 3: Added writable.
  4108. #define SHADER_BINARY_VERSION 3
  4109. String RenderingDeviceVulkan::shader_get_binary_cache_key() const {
  4110. return "Vulkan-SV" + itos(SHADER_BINARY_VERSION) + "-" + String(VERSION_NUMBER) + "-" + String(VERSION_HASH);
  4111. }
  4112. struct RenderingDeviceVulkanShaderBinaryDataBinding {
  4113. uint32_t type;
  4114. uint32_t binding;
  4115. uint32_t stages;
  4116. uint32_t length; // Size of arrays (in total elements), or ubos (in bytes * total elements).
  4117. uint32_t writable;
  4118. };
  4119. struct RenderingDeviceVulkanShaderBinarySpecializationConstant {
  4120. uint32_t type;
  4121. uint32_t constant_id;
  4122. union {
  4123. uint32_t int_value;
  4124. float float_value;
  4125. bool bool_value;
  4126. };
  4127. uint32_t stage_flags;
  4128. };
  4129. struct RenderingDeviceVulkanShaderBinaryData {
  4130. uint32_t vertex_input_mask;
  4131. uint32_t fragment_outputs;
  4132. uint32_t specialization_constant_count;
  4133. uint32_t is_compute;
  4134. uint32_t compute_local_size[3];
  4135. uint32_t set_count;
  4136. uint32_t push_constant_size;
  4137. uint32_t push_constants_vk_stage;
  4138. uint32_t stage_count;
  4139. uint32_t shader_name_len;
  4140. };
  4141. Vector<uint8_t> RenderingDeviceVulkan::shader_compile_binary_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv, const String &p_shader_name) {
  4142. RenderingDeviceVulkanShaderBinaryData binary_data;
  4143. binary_data.vertex_input_mask = 0;
  4144. binary_data.fragment_outputs = 0;
  4145. binary_data.specialization_constant_count = 0;
  4146. binary_data.is_compute = 0;
  4147. binary_data.compute_local_size[0] = 0;
  4148. binary_data.compute_local_size[1] = 0;
  4149. binary_data.compute_local_size[2] = 0;
  4150. binary_data.set_count = 0;
  4151. binary_data.push_constant_size = 0;
  4152. binary_data.push_constants_vk_stage = 0;
  4153. Vector<Vector<RenderingDeviceVulkanShaderBinaryDataBinding>> uniform_info; // Set bindings.
  4154. Vector<RenderingDeviceVulkanShaderBinarySpecializationConstant> specialization_constants;
  4155. uint32_t stages_processed = 0;
  4156. for (int i = 0; i < p_spirv.size(); i++) {
  4157. if (p_spirv[i].shader_stage == SHADER_STAGE_COMPUTE) {
  4158. binary_data.is_compute = true;
  4159. ERR_FAIL_COND_V_MSG(p_spirv.size() != 1, Vector<uint8_t>(),
  4160. "Compute shaders can only receive one stage, dedicated to compute.");
  4161. }
  4162. ERR_FAIL_COND_V_MSG(stages_processed & (1 << p_spirv[i].shader_stage), Vector<uint8_t>(),
  4163. "Stage " + String(shader_stage_names[p_spirv[i].shader_stage]) + " submitted more than once.");
  4164. {
  4165. SpvReflectShaderModule module;
  4166. const uint8_t *spirv = p_spirv[i].spir_v.ptr();
  4167. SpvReflectResult result = spvReflectCreateShaderModule(p_spirv[i].spir_v.size(), spirv, &module);
  4168. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4169. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed parsing shader.");
  4170. if (binary_data.is_compute) {
  4171. binary_data.compute_local_size[0] = module.entry_points->local_size.x;
  4172. binary_data.compute_local_size[1] = module.entry_points->local_size.y;
  4173. binary_data.compute_local_size[2] = module.entry_points->local_size.z;
  4174. }
  4175. uint32_t binding_count = 0;
  4176. result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, nullptr);
  4177. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4178. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating descriptor bindings.");
  4179. uint32_t stage = p_spirv[i].shader_stage;
  4180. if (binding_count > 0) {
  4181. // Parse bindings.
  4182. Vector<SpvReflectDescriptorBinding *> bindings;
  4183. bindings.resize(binding_count);
  4184. result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, bindings.ptrw());
  4185. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4186. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed getting descriptor bindings.");
  4187. for (uint32_t j = 0; j < binding_count; j++) {
  4188. const SpvReflectDescriptorBinding &binding = *bindings[j];
  4189. RenderingDeviceVulkanShaderBinaryDataBinding info;
  4190. bool need_array_dimensions = false;
  4191. bool need_block_size = false;
  4192. bool may_be_writable = false;
  4193. switch (binding.descriptor_type) {
  4194. case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLER: {
  4195. info.type = UNIFORM_TYPE_SAMPLER;
  4196. need_array_dimensions = true;
  4197. } break;
  4198. case SPV_REFLECT_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: {
  4199. info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
  4200. need_array_dimensions = true;
  4201. } break;
  4202. case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLED_IMAGE: {
  4203. info.type = UNIFORM_TYPE_TEXTURE;
  4204. need_array_dimensions = true;
  4205. } break;
  4206. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
  4207. info.type = UNIFORM_TYPE_IMAGE;
  4208. need_array_dimensions = true;
  4209. may_be_writable = true;
  4210. } break;
  4211. case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: {
  4212. info.type = UNIFORM_TYPE_TEXTURE_BUFFER;
  4213. need_array_dimensions = true;
  4214. } break;
  4215. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: {
  4216. info.type = UNIFORM_TYPE_IMAGE_BUFFER;
  4217. need_array_dimensions = true;
  4218. may_be_writable = true;
  4219. } break;
  4220. case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER: {
  4221. info.type = UNIFORM_TYPE_UNIFORM_BUFFER;
  4222. need_block_size = true;
  4223. } break;
  4224. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER: {
  4225. info.type = UNIFORM_TYPE_STORAGE_BUFFER;
  4226. need_block_size = true;
  4227. may_be_writable = true;
  4228. } break;
  4229. case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: {
  4230. ERR_PRINT("Dynamic uniform buffer not supported.");
  4231. continue;
  4232. } break;
  4233. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {
  4234. ERR_PRINT("Dynamic storage buffer not supported.");
  4235. continue;
  4236. } break;
  4237. case SPV_REFLECT_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: {
  4238. info.type = UNIFORM_TYPE_INPUT_ATTACHMENT;
  4239. need_array_dimensions = true;
  4240. } break;
  4241. case SPV_REFLECT_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR: {
  4242. ERR_PRINT("Acceleration structure not supported.");
  4243. continue;
  4244. } break;
  4245. }
  4246. if (need_array_dimensions) {
  4247. if (binding.array.dims_count == 0) {
  4248. info.length = 1;
  4249. } else {
  4250. for (uint32_t k = 0; k < binding.array.dims_count; k++) {
  4251. if (k == 0) {
  4252. info.length = binding.array.dims[0];
  4253. } else {
  4254. info.length *= binding.array.dims[k];
  4255. }
  4256. }
  4257. }
  4258. } else if (need_block_size) {
  4259. info.length = binding.block.size;
  4260. } else {
  4261. info.length = 0;
  4262. }
  4263. if (may_be_writable) {
  4264. info.writable = !(binding.type_description->decoration_flags & SPV_REFLECT_DECORATION_NON_WRITABLE) && !(binding.block.decoration_flags & SPV_REFLECT_DECORATION_NON_WRITABLE);
  4265. } else {
  4266. info.writable = false;
  4267. }
  4268. info.binding = binding.binding;
  4269. uint32_t set = binding.set;
  4270. ERR_FAIL_COND_V_MSG(set >= MAX_UNIFORM_SETS, Vector<uint8_t>(),
  4271. "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' uses a set (" + itos(set) + ") index larger than what is supported (" + itos(MAX_UNIFORM_SETS) + ").");
  4272. ERR_FAIL_COND_V_MSG(set >= limits.maxBoundDescriptorSets, Vector<uint8_t>(),
  4273. "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' uses a set (" + itos(set) + ") index larger than what is supported by the hardware (" + itos(limits.maxBoundDescriptorSets) + ").");
  4274. if (set < (uint32_t)uniform_info.size()) {
  4275. // Check if this already exists.
  4276. bool exists = false;
  4277. for (int k = 0; k < uniform_info[set].size(); k++) {
  4278. if (uniform_info[set][k].binding == (uint32_t)info.binding) {
  4279. // Already exists, verify that it's the same type.
  4280. ERR_FAIL_COND_V_MSG(uniform_info[set][k].type != info.type, Vector<uint8_t>(),
  4281. "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' trying to re-use location for set=" + itos(set) + ", binding=" + itos(info.binding) + " with different uniform type.");
  4282. // Also, verify that it's the same size.
  4283. ERR_FAIL_COND_V_MSG(uniform_info[set][k].length != info.length, Vector<uint8_t>(),
  4284. "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' trying to re-use location for set=" + itos(set) + ", binding=" + itos(info.binding) + " with different uniform size.");
  4285. // Also, verify that it has the same writability.
  4286. ERR_FAIL_COND_V_MSG(uniform_info[set][k].writable != info.writable, Vector<uint8_t>(),
  4287. "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' trying to re-use location for set=" + itos(set) + ", binding=" + itos(info.binding) + " with different writability.");
  4288. // Just append stage mask and return.
  4289. uniform_info.write[set].write[k].stages |= 1 << stage;
  4290. exists = true;
  4291. break;
  4292. }
  4293. }
  4294. if (exists) {
  4295. continue; // Merged.
  4296. }
  4297. }
  4298. info.stages = 1 << stage;
  4299. if (set >= (uint32_t)uniform_info.size()) {
  4300. uniform_info.resize(set + 1);
  4301. }
  4302. uniform_info.write[set].push_back(info);
  4303. }
  4304. }
  4305. {
  4306. // Specialization constants.
  4307. uint32_t sc_count = 0;
  4308. result = spvReflectEnumerateSpecializationConstants(&module, &sc_count, nullptr);
  4309. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4310. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating specialization constants.");
  4311. if (sc_count) {
  4312. Vector<SpvReflectSpecializationConstant *> spec_constants;
  4313. spec_constants.resize(sc_count);
  4314. result = spvReflectEnumerateSpecializationConstants(&module, &sc_count, spec_constants.ptrw());
  4315. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4316. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining specialization constants.");
  4317. for (uint32_t j = 0; j < sc_count; j++) {
  4318. int32_t existing = -1;
  4319. RenderingDeviceVulkanShaderBinarySpecializationConstant sconst;
  4320. SpvReflectSpecializationConstant *spc = spec_constants[j];
  4321. sconst.constant_id = spc->constant_id;
  4322. sconst.int_value = 0.0; // Clear previous value JIC.
  4323. switch (spc->constant_type) {
  4324. case SPV_REFLECT_SPECIALIZATION_CONSTANT_BOOL: {
  4325. sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL;
  4326. sconst.bool_value = spc->default_value.int_bool_value != 0;
  4327. } break;
  4328. case SPV_REFLECT_SPECIALIZATION_CONSTANT_INT: {
  4329. sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT;
  4330. sconst.int_value = spc->default_value.int_bool_value;
  4331. } break;
  4332. case SPV_REFLECT_SPECIALIZATION_CONSTANT_FLOAT: {
  4333. sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT;
  4334. sconst.float_value = spc->default_value.float_value;
  4335. } break;
  4336. }
  4337. sconst.stage_flags = 1 << p_spirv[i].shader_stage;
  4338. for (int k = 0; k < specialization_constants.size(); k++) {
  4339. if (specialization_constants[k].constant_id == sconst.constant_id) {
  4340. ERR_FAIL_COND_V_MSG(specialization_constants[k].type != sconst.type, Vector<uint8_t>(), "More than one specialization constant used for id (" + itos(sconst.constant_id) + "), but their types differ.");
  4341. ERR_FAIL_COND_V_MSG(specialization_constants[k].int_value != sconst.int_value, Vector<uint8_t>(), "More than one specialization constant used for id (" + itos(sconst.constant_id) + "), but their default values differ.");
  4342. existing = k;
  4343. break;
  4344. }
  4345. }
  4346. if (existing > 0) {
  4347. specialization_constants.write[existing].stage_flags |= sconst.stage_flags;
  4348. } else {
  4349. specialization_constants.push_back(sconst);
  4350. }
  4351. }
  4352. }
  4353. }
  4354. if (stage == SHADER_STAGE_VERTEX) {
  4355. uint32_t iv_count = 0;
  4356. result = spvReflectEnumerateInputVariables(&module, &iv_count, nullptr);
  4357. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4358. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating input variables.");
  4359. if (iv_count) {
  4360. Vector<SpvReflectInterfaceVariable *> input_vars;
  4361. input_vars.resize(iv_count);
  4362. result = spvReflectEnumerateInputVariables(&module, &iv_count, input_vars.ptrw());
  4363. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4364. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining input variables.");
  4365. for (uint32_t j = 0; j < iv_count; j++) {
  4366. if (input_vars[j] && input_vars[j]->decoration_flags == 0) { // Regular input.
  4367. binary_data.vertex_input_mask |= (1 << uint32_t(input_vars[j]->location));
  4368. }
  4369. }
  4370. }
  4371. }
  4372. if (stage == SHADER_STAGE_FRAGMENT) {
  4373. uint32_t ov_count = 0;
  4374. result = spvReflectEnumerateOutputVariables(&module, &ov_count, nullptr);
  4375. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4376. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating output variables.");
  4377. if (ov_count) {
  4378. Vector<SpvReflectInterfaceVariable *> output_vars;
  4379. output_vars.resize(ov_count);
  4380. result = spvReflectEnumerateOutputVariables(&module, &ov_count, output_vars.ptrw());
  4381. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4382. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining output variables.");
  4383. for (uint32_t j = 0; j < ov_count; j++) {
  4384. const SpvReflectInterfaceVariable *refvar = output_vars[j];
  4385. if (refvar != nullptr && refvar->built_in != SpvBuiltInFragDepth) {
  4386. binary_data.fragment_outputs |= 1 << refvar->location;
  4387. }
  4388. }
  4389. }
  4390. }
  4391. uint32_t pc_count = 0;
  4392. result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, nullptr);
  4393. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4394. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating push constants.");
  4395. if (pc_count) {
  4396. ERR_FAIL_COND_V_MSG(pc_count > 1, Vector<uint8_t>(),
  4397. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "': Only one push constant is supported, which should be the same across shader stages.");
  4398. Vector<SpvReflectBlockVariable *> pconstants;
  4399. pconstants.resize(pc_count);
  4400. result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, pconstants.ptrw());
  4401. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4402. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining push constants.");
  4403. #if 0
  4404. if (pconstants[0] == nullptr) {
  4405. Ref<FileAccess> f = FileAccess::open("res://popo.spv", FileAccess::WRITE);
  4406. f->store_buffer((const uint8_t *)&SpirV[0], SpirV.size() * sizeof(uint32_t));
  4407. }
  4408. #endif
  4409. ERR_FAIL_COND_V_MSG(binary_data.push_constant_size && binary_data.push_constant_size != pconstants[0]->size, Vector<uint8_t>(),
  4410. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "': Push constant block must be the same across shader stages.");
  4411. binary_data.push_constant_size = pconstants[0]->size;
  4412. binary_data.push_constants_vk_stage |= shader_stage_masks[stage];
  4413. //print_line("Stage: " + String(shader_stage_names[stage]) + " push constant of size=" + itos(push_constant.push_constant_size));
  4414. }
  4415. // Destroy the reflection data when no longer required.
  4416. spvReflectDestroyShaderModule(&module);
  4417. }
  4418. stages_processed |= (1 << p_spirv[i].shader_stage);
  4419. }
  4420. Vector<Vector<uint8_t>> compressed_stages;
  4421. Vector<uint32_t> smolv_size;
  4422. Vector<uint32_t> zstd_size; // If 0, zstd not used.
  4423. uint32_t stages_binary_size = 0;
  4424. bool strip_debug = false;
  4425. for (int i = 0; i < p_spirv.size(); i++) {
  4426. smolv::ByteArray smolv;
  4427. if (!smolv::Encode(p_spirv[i].spir_v.ptr(), p_spirv[i].spir_v.size(), smolv, strip_debug ? smolv::kEncodeFlagStripDebugInfo : 0)) {
  4428. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Error compressing shader stage :" + String(shader_stage_names[p_spirv[i].shader_stage]));
  4429. } else {
  4430. smolv_size.push_back(smolv.size());
  4431. { // zstd.
  4432. Vector<uint8_t> zstd;
  4433. zstd.resize(Compression::get_max_compressed_buffer_size(smolv.size(), Compression::MODE_ZSTD));
  4434. int dst_size = Compression::compress(zstd.ptrw(), &smolv[0], smolv.size(), Compression::MODE_ZSTD);
  4435. if (dst_size > 0 && (uint32_t)dst_size < smolv.size()) {
  4436. zstd_size.push_back(dst_size);
  4437. zstd.resize(dst_size);
  4438. compressed_stages.push_back(zstd);
  4439. } else {
  4440. Vector<uint8_t> smv;
  4441. smv.resize(smolv.size());
  4442. memcpy(smv.ptrw(), &smolv[0], smolv.size());
  4443. zstd_size.push_back(0); // Not using zstd.
  4444. compressed_stages.push_back(smv);
  4445. }
  4446. }
  4447. }
  4448. uint32_t s = compressed_stages[i].size();
  4449. if (s % 4 != 0) {
  4450. s += 4 - (s % 4);
  4451. }
  4452. stages_binary_size += s;
  4453. }
  4454. binary_data.specialization_constant_count = specialization_constants.size();
  4455. binary_data.set_count = uniform_info.size();
  4456. binary_data.stage_count = p_spirv.size();
  4457. CharString shader_name_utf = p_shader_name.utf8();
  4458. binary_data.shader_name_len = shader_name_utf.length();
  4459. uint32_t total_size = sizeof(uint32_t) * 3; // Header + version + main datasize;.
  4460. total_size += sizeof(RenderingDeviceVulkanShaderBinaryData);
  4461. total_size += binary_data.shader_name_len;
  4462. if ((binary_data.shader_name_len % 4) != 0) { // Alignment rules are really strange.
  4463. total_size += 4 - (binary_data.shader_name_len % 4);
  4464. }
  4465. for (int i = 0; i < uniform_info.size(); i++) {
  4466. total_size += sizeof(uint32_t);
  4467. total_size += uniform_info[i].size() * sizeof(RenderingDeviceVulkanShaderBinaryDataBinding);
  4468. }
  4469. total_size += sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) * specialization_constants.size();
  4470. total_size += compressed_stages.size() * sizeof(uint32_t) * 3; // Sizes.
  4471. total_size += stages_binary_size;
  4472. Vector<uint8_t> ret;
  4473. ret.resize(total_size);
  4474. {
  4475. uint32_t offset = 0;
  4476. uint8_t *binptr = ret.ptrw();
  4477. binptr[0] = 'G';
  4478. binptr[1] = 'V';
  4479. binptr[2] = 'B';
  4480. binptr[3] = 'D'; // Godot vulkan binary data.
  4481. offset += 4;
  4482. encode_uint32(SHADER_BINARY_VERSION, binptr + offset);
  4483. offset += sizeof(uint32_t);
  4484. encode_uint32(sizeof(RenderingDeviceVulkanShaderBinaryData), binptr + offset);
  4485. offset += sizeof(uint32_t);
  4486. memcpy(binptr + offset, &binary_data, sizeof(RenderingDeviceVulkanShaderBinaryData));
  4487. offset += sizeof(RenderingDeviceVulkanShaderBinaryData);
  4488. memcpy(binptr + offset, shader_name_utf.ptr(), binary_data.shader_name_len);
  4489. offset += binary_data.shader_name_len;
  4490. if ((binary_data.shader_name_len % 4) != 0) { // Alignment rules are really strange.
  4491. offset += 4 - (binary_data.shader_name_len % 4);
  4492. }
  4493. for (int i = 0; i < uniform_info.size(); i++) {
  4494. int count = uniform_info[i].size();
  4495. encode_uint32(count, binptr + offset);
  4496. offset += sizeof(uint32_t);
  4497. if (count > 0) {
  4498. memcpy(binptr + offset, uniform_info[i].ptr(), sizeof(RenderingDeviceVulkanShaderBinaryDataBinding) * count);
  4499. offset += sizeof(RenderingDeviceVulkanShaderBinaryDataBinding) * count;
  4500. }
  4501. }
  4502. if (specialization_constants.size()) {
  4503. memcpy(binptr + offset, specialization_constants.ptr(), sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) * specialization_constants.size());
  4504. offset += sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) * specialization_constants.size();
  4505. }
  4506. for (int i = 0; i < compressed_stages.size(); i++) {
  4507. encode_uint32(p_spirv[i].shader_stage, binptr + offset);
  4508. offset += sizeof(uint32_t);
  4509. encode_uint32(smolv_size[i], binptr + offset);
  4510. offset += sizeof(uint32_t);
  4511. encode_uint32(zstd_size[i], binptr + offset);
  4512. offset += sizeof(uint32_t);
  4513. memcpy(binptr + offset, compressed_stages[i].ptr(), compressed_stages[i].size());
  4514. uint32_t s = compressed_stages[i].size();
  4515. if (s % 4 != 0) {
  4516. s += 4 - (s % 4);
  4517. }
  4518. offset += s;
  4519. }
  4520. ERR_FAIL_COND_V(offset != (uint32_t)ret.size(), Vector<uint8_t>());
  4521. }
  4522. return ret;
  4523. }
  4524. RID RenderingDeviceVulkan::shader_create_from_bytecode(const Vector<uint8_t> &p_shader_binary) {
  4525. const uint8_t *binptr = p_shader_binary.ptr();
  4526. uint32_t binsize = p_shader_binary.size();
  4527. uint32_t read_offset = 0;
  4528. // Consistency check.
  4529. ERR_FAIL_COND_V(binsize < sizeof(uint32_t) * 3 + sizeof(RenderingDeviceVulkanShaderBinaryData), RID());
  4530. ERR_FAIL_COND_V(binptr[0] != 'G' || binptr[1] != 'V' || binptr[2] != 'B' || binptr[3] != 'D', RID());
  4531. uint32_t bin_version = decode_uint32(binptr + 4);
  4532. ERR_FAIL_COND_V(bin_version != SHADER_BINARY_VERSION, RID());
  4533. uint32_t bin_data_size = decode_uint32(binptr + 8);
  4534. const RenderingDeviceVulkanShaderBinaryData &binary_data = *(reinterpret_cast<const RenderingDeviceVulkanShaderBinaryData *>(binptr + 12));
  4535. Shader::PushConstant push_constant;
  4536. push_constant.push_constant_size = binary_data.push_constant_size;
  4537. push_constant.push_constants_vk_stage = binary_data.push_constants_vk_stage;
  4538. uint32_t vertex_input_mask = binary_data.vertex_input_mask;
  4539. uint32_t fragment_outputs = binary_data.fragment_outputs;
  4540. bool is_compute = binary_data.is_compute;
  4541. const uint32_t compute_local_size[3] = { binary_data.compute_local_size[0], binary_data.compute_local_size[1], binary_data.compute_local_size[2] };
  4542. read_offset += sizeof(uint32_t) * 3 + bin_data_size;
  4543. String name;
  4544. if (binary_data.shader_name_len) {
  4545. name.parse_utf8((const char *)(binptr + read_offset), binary_data.shader_name_len);
  4546. read_offset += binary_data.shader_name_len;
  4547. if ((binary_data.shader_name_len % 4) != 0) { // Alignment rules are really strange.
  4548. read_offset += 4 - (binary_data.shader_name_len % 4);
  4549. }
  4550. }
  4551. Vector<Vector<VkDescriptorSetLayoutBinding>> set_bindings;
  4552. Vector<Vector<UniformInfo>> uniform_info;
  4553. set_bindings.resize(binary_data.set_count);
  4554. uniform_info.resize(binary_data.set_count);
  4555. for (uint32_t i = 0; i < binary_data.set_count; i++) {
  4556. ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) >= binsize, RID());
  4557. uint32_t set_count = decode_uint32(binptr + read_offset);
  4558. read_offset += sizeof(uint32_t);
  4559. const RenderingDeviceVulkanShaderBinaryDataBinding *set_ptr = reinterpret_cast<const RenderingDeviceVulkanShaderBinaryDataBinding *>(binptr + read_offset);
  4560. uint32_t set_size = set_count * sizeof(RenderingDeviceVulkanShaderBinaryDataBinding);
  4561. ERR_FAIL_COND_V(read_offset + set_size >= binsize, RID());
  4562. for (uint32_t j = 0; j < set_count; j++) {
  4563. UniformInfo info;
  4564. info.type = UniformType(set_ptr[j].type);
  4565. info.writable = set_ptr[j].writable;
  4566. info.length = set_ptr[j].length;
  4567. info.binding = set_ptr[j].binding;
  4568. info.stages = set_ptr[j].stages;
  4569. VkDescriptorSetLayoutBinding layout_binding;
  4570. layout_binding.pImmutableSamplers = nullptr;
  4571. layout_binding.binding = set_ptr[j].binding;
  4572. layout_binding.descriptorCount = 1;
  4573. layout_binding.stageFlags = 0;
  4574. for (uint32_t k = 0; k < SHADER_STAGE_MAX; k++) {
  4575. if (set_ptr[j].stages & (1 << k)) {
  4576. layout_binding.stageFlags |= shader_stage_masks[k];
  4577. }
  4578. }
  4579. switch (info.type) {
  4580. case UNIFORM_TYPE_SAMPLER: {
  4581. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
  4582. layout_binding.descriptorCount = set_ptr[j].length;
  4583. } break;
  4584. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {
  4585. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  4586. layout_binding.descriptorCount = set_ptr[j].length;
  4587. } break;
  4588. case UNIFORM_TYPE_TEXTURE: {
  4589. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  4590. layout_binding.descriptorCount = set_ptr[j].length;
  4591. } break;
  4592. case UNIFORM_TYPE_IMAGE: {
  4593. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  4594. layout_binding.descriptorCount = set_ptr[j].length;
  4595. } break;
  4596. case UNIFORM_TYPE_TEXTURE_BUFFER: {
  4597. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  4598. layout_binding.descriptorCount = set_ptr[j].length;
  4599. } break;
  4600. case UNIFORM_TYPE_IMAGE_BUFFER: {
  4601. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
  4602. } break;
  4603. case UNIFORM_TYPE_UNIFORM_BUFFER: {
  4604. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  4605. } break;
  4606. case UNIFORM_TYPE_STORAGE_BUFFER: {
  4607. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  4608. } break;
  4609. case UNIFORM_TYPE_INPUT_ATTACHMENT: {
  4610. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
  4611. } break;
  4612. default: {
  4613. ERR_FAIL_V(RID());
  4614. }
  4615. }
  4616. set_bindings.write[i].push_back(layout_binding);
  4617. uniform_info.write[i].push_back(info);
  4618. }
  4619. read_offset += set_size;
  4620. }
  4621. ERR_FAIL_COND_V(read_offset + binary_data.specialization_constant_count * sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) >= binsize, RID());
  4622. Vector<Shader::SpecializationConstant> specialization_constants;
  4623. for (uint32_t i = 0; i < binary_data.specialization_constant_count; i++) {
  4624. const RenderingDeviceVulkanShaderBinarySpecializationConstant &src_sc = *(reinterpret_cast<const RenderingDeviceVulkanShaderBinarySpecializationConstant *>(binptr + read_offset));
  4625. Shader::SpecializationConstant sc;
  4626. sc.constant.int_value = src_sc.int_value;
  4627. sc.constant.type = PipelineSpecializationConstantType(src_sc.type);
  4628. sc.constant.constant_id = src_sc.constant_id;
  4629. sc.stage_flags = src_sc.stage_flags;
  4630. specialization_constants.push_back(sc);
  4631. read_offset += sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant);
  4632. }
  4633. Vector<Vector<uint8_t>> stage_spirv_data;
  4634. Vector<ShaderStage> stage_type;
  4635. for (uint32_t i = 0; i < binary_data.stage_count; i++) {
  4636. ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) * 3 >= binsize, RID());
  4637. uint32_t stage = decode_uint32(binptr + read_offset);
  4638. read_offset += sizeof(uint32_t);
  4639. uint32_t smolv_size = decode_uint32(binptr + read_offset);
  4640. read_offset += sizeof(uint32_t);
  4641. uint32_t zstd_size = decode_uint32(binptr + read_offset);
  4642. read_offset += sizeof(uint32_t);
  4643. uint32_t buf_size = (zstd_size > 0) ? zstd_size : smolv_size;
  4644. Vector<uint8_t> smolv;
  4645. const uint8_t *src_smolv = nullptr;
  4646. if (zstd_size > 0) {
  4647. // Decompress to smolv.
  4648. smolv.resize(smolv_size);
  4649. int dec_smolv_size = Compression::decompress(smolv.ptrw(), smolv.size(), binptr + read_offset, zstd_size, Compression::MODE_ZSTD);
  4650. ERR_FAIL_COND_V(dec_smolv_size != (int32_t)smolv_size, RID());
  4651. src_smolv = smolv.ptr();
  4652. } else {
  4653. src_smolv = binptr + read_offset;
  4654. }
  4655. Vector<uint8_t> spirv;
  4656. uint32_t spirv_size = smolv::GetDecodedBufferSize(src_smolv, smolv_size);
  4657. spirv.resize(spirv_size);
  4658. if (!smolv::Decode(src_smolv, smolv_size, spirv.ptrw(), spirv_size)) {
  4659. ERR_FAIL_V_MSG(RID(), "Malformed smolv input uncompressing shader stage:" + String(shader_stage_names[stage]));
  4660. }
  4661. stage_spirv_data.push_back(spirv);
  4662. stage_type.push_back(ShaderStage(stage));
  4663. if (buf_size % 4 != 0) {
  4664. buf_size += 4 - (buf_size % 4);
  4665. }
  4666. ERR_FAIL_COND_V(read_offset + buf_size > binsize, RID());
  4667. read_offset += buf_size;
  4668. }
  4669. ERR_FAIL_COND_V(read_offset != binsize, RID());
  4670. // All good, let's create modules.
  4671. _THREAD_SAFE_METHOD_
  4672. Shader shader;
  4673. shader.vertex_input_mask = vertex_input_mask;
  4674. shader.fragment_output_mask = fragment_outputs;
  4675. shader.push_constant = push_constant;
  4676. shader.is_compute = is_compute;
  4677. shader.compute_local_size[0] = compute_local_size[0];
  4678. shader.compute_local_size[1] = compute_local_size[1];
  4679. shader.compute_local_size[2] = compute_local_size[2];
  4680. shader.specialization_constants = specialization_constants;
  4681. shader.name = name;
  4682. String error_text;
  4683. bool success = true;
  4684. for (int i = 0; i < stage_spirv_data.size(); i++) {
  4685. VkShaderModuleCreateInfo shader_module_create_info;
  4686. shader_module_create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  4687. shader_module_create_info.pNext = nullptr;
  4688. shader_module_create_info.flags = 0;
  4689. shader_module_create_info.codeSize = stage_spirv_data[i].size();
  4690. const uint8_t *r = stage_spirv_data[i].ptr();
  4691. shader_module_create_info.pCode = (const uint32_t *)r;
  4692. VkShaderModule module;
  4693. VkResult res = vkCreateShaderModule(device, &shader_module_create_info, nullptr, &module);
  4694. if (res) {
  4695. success = false;
  4696. error_text = "Error (" + itos(res) + ") creating shader module for stage: " + String(shader_stage_names[stage_type[i]]);
  4697. break;
  4698. }
  4699. const VkShaderStageFlagBits shader_stage_bits[SHADER_STAGE_MAX] = {
  4700. VK_SHADER_STAGE_VERTEX_BIT,
  4701. VK_SHADER_STAGE_FRAGMENT_BIT,
  4702. VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT,
  4703. VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
  4704. VK_SHADER_STAGE_COMPUTE_BIT,
  4705. };
  4706. VkPipelineShaderStageCreateInfo shader_stage;
  4707. shader_stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  4708. shader_stage.pNext = nullptr;
  4709. shader_stage.flags = 0;
  4710. shader_stage.stage = shader_stage_bits[stage_type[i]];
  4711. shader_stage.module = module;
  4712. shader_stage.pName = "main";
  4713. shader_stage.pSpecializationInfo = nullptr;
  4714. shader.pipeline_stages.push_back(shader_stage);
  4715. }
  4716. // Proceed to create descriptor sets.
  4717. if (success) {
  4718. for (int i = 0; i < set_bindings.size(); i++) {
  4719. // Empty ones are fine if they were not used according to spec (binding count will be 0).
  4720. VkDescriptorSetLayoutCreateInfo layout_create_info;
  4721. layout_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
  4722. layout_create_info.pNext = nullptr;
  4723. layout_create_info.flags = 0;
  4724. layout_create_info.bindingCount = set_bindings[i].size();
  4725. layout_create_info.pBindings = set_bindings[i].ptr();
  4726. VkDescriptorSetLayout layout;
  4727. VkResult res = vkCreateDescriptorSetLayout(device, &layout_create_info, nullptr, &layout);
  4728. if (res) {
  4729. error_text = "Error (" + itos(res) + ") creating descriptor set layout for set " + itos(i);
  4730. success = false;
  4731. break;
  4732. }
  4733. Shader::Set set;
  4734. set.descriptor_set_layout = layout;
  4735. set.uniform_info = uniform_info[i];
  4736. // Sort and hash.
  4737. set.uniform_info.sort();
  4738. uint32_t format = 0; // No format, default.
  4739. if (set.uniform_info.size()) {
  4740. // Has data, needs an actual format.
  4741. UniformSetFormat usformat;
  4742. usformat.uniform_info = set.uniform_info;
  4743. RBMap<UniformSetFormat, uint32_t>::Element *E = uniform_set_format_cache.find(usformat);
  4744. if (E) {
  4745. format = E->get();
  4746. } else {
  4747. format = uniform_set_format_cache.size() + 1;
  4748. uniform_set_format_cache.insert(usformat, format);
  4749. }
  4750. }
  4751. shader.sets.push_back(set);
  4752. shader.set_formats.push_back(format);
  4753. }
  4754. }
  4755. if (success) {
  4756. // Create pipeline layout.
  4757. VkPipelineLayoutCreateInfo pipeline_layout_create_info;
  4758. pipeline_layout_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  4759. pipeline_layout_create_info.pNext = nullptr;
  4760. pipeline_layout_create_info.flags = 0;
  4761. pipeline_layout_create_info.setLayoutCount = shader.sets.size();
  4762. Vector<VkDescriptorSetLayout> layouts;
  4763. layouts.resize(shader.sets.size());
  4764. for (int i = 0; i < layouts.size(); i++) {
  4765. layouts.write[i] = shader.sets[i].descriptor_set_layout;
  4766. }
  4767. pipeline_layout_create_info.pSetLayouts = layouts.ptr();
  4768. // Needs to be declared in this outer scope, otherwise it may not outlive its assignment
  4769. // to pipeline_layout_create_info.
  4770. VkPushConstantRange push_constant_range;
  4771. if (push_constant.push_constant_size) {
  4772. push_constant_range.stageFlags = push_constant.push_constants_vk_stage;
  4773. push_constant_range.offset = 0;
  4774. push_constant_range.size = push_constant.push_constant_size;
  4775. pipeline_layout_create_info.pushConstantRangeCount = 1;
  4776. pipeline_layout_create_info.pPushConstantRanges = &push_constant_range;
  4777. } else {
  4778. pipeline_layout_create_info.pushConstantRangeCount = 0;
  4779. pipeline_layout_create_info.pPushConstantRanges = nullptr;
  4780. }
  4781. VkResult err = vkCreatePipelineLayout(device, &pipeline_layout_create_info, nullptr, &shader.pipeline_layout);
  4782. if (err) {
  4783. error_text = "Error (" + itos(err) + ") creating pipeline layout.";
  4784. success = false;
  4785. }
  4786. }
  4787. if (!success) {
  4788. // Clean up if failed.
  4789. for (int i = 0; i < shader.pipeline_stages.size(); i++) {
  4790. vkDestroyShaderModule(device, shader.pipeline_stages[i].module, nullptr);
  4791. }
  4792. for (int i = 0; i < shader.sets.size(); i++) {
  4793. vkDestroyDescriptorSetLayout(device, shader.sets[i].descriptor_set_layout, nullptr);
  4794. }
  4795. ERR_FAIL_V_MSG(RID(), error_text);
  4796. }
  4797. RID id = shader_owner.make_rid(shader);
  4798. #ifdef DEV_ENABLED
  4799. set_resource_name(id, "RID:" + itos(id.get_id()));
  4800. #endif
  4801. return id;
  4802. }
  4803. uint32_t RenderingDeviceVulkan::shader_get_vertex_input_attribute_mask(RID p_shader) {
  4804. _THREAD_SAFE_METHOD_
  4805. const Shader *shader = shader_owner.get_or_null(p_shader);
  4806. ERR_FAIL_COND_V(!shader, 0);
  4807. return shader->vertex_input_mask;
  4808. }
  4809. /******************/
  4810. /**** UNIFORMS ****/
  4811. /******************/
  4812. RID RenderingDeviceVulkan::uniform_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data) {
  4813. _THREAD_SAFE_METHOD_
  4814. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  4815. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  4816. "Creating buffers with data is forbidden during creation of a draw list");
  4817. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  4818. "Creating buffers with data is forbidden during creation of a draw list");
  4819. Buffer buffer;
  4820. Error err = _buffer_allocate(&buffer, p_size_bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0);
  4821. ERR_FAIL_COND_V(err != OK, RID());
  4822. if (p_data.size()) {
  4823. uint64_t data_size = p_data.size();
  4824. const uint8_t *r = p_data.ptr();
  4825. _buffer_update(&buffer, 0, r, data_size);
  4826. _buffer_memory_barrier(buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_UNIFORM_READ_BIT, false);
  4827. }
  4828. RID id = uniform_buffer_owner.make_rid(buffer);
  4829. #ifdef DEV_ENABLED
  4830. set_resource_name(id, "RID:" + itos(id.get_id()));
  4831. #endif
  4832. return id;
  4833. }
  4834. RID RenderingDeviceVulkan::storage_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data, uint32_t p_usage) {
  4835. _THREAD_SAFE_METHOD_
  4836. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  4837. "Creating buffers with data is forbidden during creation of a draw list");
  4838. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  4839. "Creating buffers with data is forbidden during creation of a draw list");
  4840. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  4841. Buffer buffer;
  4842. uint32_t flags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
  4843. if (p_usage & STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT) {
  4844. flags |= VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
  4845. }
  4846. Error err = _buffer_allocate(&buffer, p_size_bytes, flags, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0);
  4847. ERR_FAIL_COND_V(err != OK, RID());
  4848. if (p_data.size()) {
  4849. uint64_t data_size = p_data.size();
  4850. const uint8_t *r = p_data.ptr();
  4851. _buffer_update(&buffer, 0, r, data_size);
  4852. _buffer_memory_barrier(buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, false);
  4853. }
  4854. return storage_buffer_owner.make_rid(buffer);
  4855. }
  4856. RID RenderingDeviceVulkan::texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector<uint8_t> &p_data) {
  4857. _THREAD_SAFE_METHOD_
  4858. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  4859. "Creating buffers with data is forbidden during creation of a draw list");
  4860. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  4861. "Creating buffers with data is forbidden during creation of a draw list");
  4862. uint32_t element_size = get_format_vertex_size(p_format);
  4863. ERR_FAIL_COND_V_MSG(element_size == 0, RID(), "Format requested is not supported for texture buffers");
  4864. uint64_t size_bytes = uint64_t(element_size) * p_size_elements;
  4865. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != size_bytes, RID());
  4866. TextureBuffer texture_buffer;
  4867. Error err = _buffer_allocate(&texture_buffer.buffer, size_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0);
  4868. ERR_FAIL_COND_V(err != OK, RID());
  4869. if (p_data.size()) {
  4870. uint64_t data_size = p_data.size();
  4871. const uint8_t *r = p_data.ptr();
  4872. _buffer_update(&texture_buffer.buffer, 0, r, data_size);
  4873. _buffer_memory_barrier(texture_buffer.buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, false);
  4874. }
  4875. VkBufferViewCreateInfo view_create_info;
  4876. view_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;
  4877. view_create_info.pNext = nullptr;
  4878. view_create_info.flags = 0;
  4879. view_create_info.buffer = texture_buffer.buffer.buffer;
  4880. view_create_info.format = vulkan_formats[p_format];
  4881. view_create_info.offset = 0;
  4882. view_create_info.range = size_bytes;
  4883. texture_buffer.view = VK_NULL_HANDLE;
  4884. VkResult res = vkCreateBufferView(device, &view_create_info, nullptr, &texture_buffer.view);
  4885. if (res) {
  4886. _buffer_free(&texture_buffer.buffer);
  4887. ERR_FAIL_V_MSG(RID(), "Unable to create buffer view, error " + itos(res) + ".");
  4888. }
  4889. // Allocate the view.
  4890. RID id = texture_buffer_owner.make_rid(texture_buffer);
  4891. #ifdef DEV_ENABLED
  4892. set_resource_name(id, "RID:" + itos(id.get_id()));
  4893. #endif
  4894. return id;
  4895. }
  4896. RenderingDeviceVulkan::DescriptorPool *RenderingDeviceVulkan::_descriptor_pool_allocate(const DescriptorPoolKey &p_key) {
  4897. if (!descriptor_pools.has(p_key)) {
  4898. descriptor_pools[p_key] = HashSet<DescriptorPool *>();
  4899. }
  4900. DescriptorPool *pool = nullptr;
  4901. for (DescriptorPool *E : descriptor_pools[p_key]) {
  4902. if (E->usage < max_descriptors_per_pool) {
  4903. pool = E;
  4904. break;
  4905. }
  4906. }
  4907. if (!pool) {
  4908. // Create a new one.
  4909. pool = memnew(DescriptorPool);
  4910. pool->usage = 0;
  4911. VkDescriptorPoolCreateInfo descriptor_pool_create_info;
  4912. descriptor_pool_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
  4913. descriptor_pool_create_info.pNext = nullptr;
  4914. descriptor_pool_create_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; // Can't think how somebody may NOT need this flag.
  4915. descriptor_pool_create_info.maxSets = max_descriptors_per_pool;
  4916. Vector<VkDescriptorPoolSize> sizes;
  4917. // Here comes more vulkan API strangeness.
  4918. if (p_key.uniform_type[UNIFORM_TYPE_SAMPLER]) {
  4919. VkDescriptorPoolSize s;
  4920. s.type = VK_DESCRIPTOR_TYPE_SAMPLER;
  4921. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_SAMPLER] * max_descriptors_per_pool;
  4922. sizes.push_back(s);
  4923. }
  4924. if (p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE]) {
  4925. VkDescriptorPoolSize s;
  4926. s.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  4927. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE] * max_descriptors_per_pool;
  4928. sizes.push_back(s);
  4929. }
  4930. if (p_key.uniform_type[UNIFORM_TYPE_TEXTURE]) {
  4931. VkDescriptorPoolSize s;
  4932. s.type = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  4933. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_TEXTURE] * max_descriptors_per_pool;
  4934. sizes.push_back(s);
  4935. }
  4936. if (p_key.uniform_type[UNIFORM_TYPE_IMAGE]) {
  4937. VkDescriptorPoolSize s;
  4938. s.type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  4939. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_IMAGE] * max_descriptors_per_pool;
  4940. sizes.push_back(s);
  4941. }
  4942. if (p_key.uniform_type[UNIFORM_TYPE_TEXTURE_BUFFER] || p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER]) {
  4943. VkDescriptorPoolSize s;
  4944. s.type = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  4945. s.descriptorCount = (p_key.uniform_type[UNIFORM_TYPE_TEXTURE_BUFFER] + p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER]) * max_descriptors_per_pool;
  4946. sizes.push_back(s);
  4947. }
  4948. if (p_key.uniform_type[UNIFORM_TYPE_IMAGE_BUFFER]) {
  4949. VkDescriptorPoolSize s;
  4950. s.type = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
  4951. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_IMAGE_BUFFER] * max_descriptors_per_pool;
  4952. sizes.push_back(s);
  4953. }
  4954. if (p_key.uniform_type[UNIFORM_TYPE_UNIFORM_BUFFER]) {
  4955. VkDescriptorPoolSize s;
  4956. s.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  4957. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_UNIFORM_BUFFER] * max_descriptors_per_pool;
  4958. sizes.push_back(s);
  4959. }
  4960. if (p_key.uniform_type[UNIFORM_TYPE_STORAGE_BUFFER]) {
  4961. VkDescriptorPoolSize s;
  4962. s.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  4963. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_STORAGE_BUFFER] * max_descriptors_per_pool;
  4964. sizes.push_back(s);
  4965. }
  4966. if (p_key.uniform_type[UNIFORM_TYPE_INPUT_ATTACHMENT]) {
  4967. VkDescriptorPoolSize s;
  4968. s.type = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
  4969. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_INPUT_ATTACHMENT] * max_descriptors_per_pool;
  4970. sizes.push_back(s);
  4971. }
  4972. descriptor_pool_create_info.poolSizeCount = sizes.size();
  4973. descriptor_pool_create_info.pPoolSizes = sizes.ptr();
  4974. VkResult res = vkCreateDescriptorPool(device, &descriptor_pool_create_info, nullptr, &pool->pool);
  4975. if (res) {
  4976. memdelete(pool);
  4977. ERR_FAIL_COND_V_MSG(res, nullptr, "vkCreateDescriptorPool failed with error " + itos(res) + ".");
  4978. }
  4979. descriptor_pools[p_key].insert(pool);
  4980. }
  4981. pool->usage++;
  4982. return pool;
  4983. }
  4984. void RenderingDeviceVulkan::_descriptor_pool_free(const DescriptorPoolKey &p_key, DescriptorPool *p_pool) {
  4985. #ifdef DEBUG_ENABLED
  4986. ERR_FAIL_COND(!descriptor_pools[p_key].has(p_pool));
  4987. #endif
  4988. ERR_FAIL_COND(p_pool->usage == 0);
  4989. p_pool->usage--;
  4990. if (p_pool->usage == 0) {
  4991. vkDestroyDescriptorPool(device, p_pool->pool, nullptr);
  4992. descriptor_pools[p_key].erase(p_pool);
  4993. memdelete(p_pool);
  4994. if (descriptor_pools[p_key].is_empty()) {
  4995. descriptor_pools.erase(p_key);
  4996. }
  4997. }
  4998. }
  4999. RID RenderingDeviceVulkan::uniform_set_create(const Vector<Uniform> &p_uniforms, RID p_shader, uint32_t p_shader_set) {
  5000. _THREAD_SAFE_METHOD_
  5001. ERR_FAIL_COND_V(p_uniforms.size() == 0, RID());
  5002. Shader *shader = shader_owner.get_or_null(p_shader);
  5003. ERR_FAIL_COND_V(!shader, RID());
  5004. ERR_FAIL_COND_V_MSG(p_shader_set >= (uint32_t)shader->sets.size() || shader->sets[p_shader_set].uniform_info.size() == 0, RID(),
  5005. "Desired set (" + itos(p_shader_set) + ") not used by shader.");
  5006. // See that all sets in shader are satisfied.
  5007. const Shader::Set &set = shader->sets[p_shader_set];
  5008. uint32_t uniform_count = p_uniforms.size();
  5009. const Uniform *uniforms = p_uniforms.ptr();
  5010. uint32_t set_uniform_count = set.uniform_info.size();
  5011. const UniformInfo *set_uniforms = set.uniform_info.ptr();
  5012. Vector<VkWriteDescriptorSet> writes;
  5013. DescriptorPoolKey pool_key;
  5014. // To keep them alive until update call.
  5015. List<Vector<VkDescriptorBufferInfo>> buffer_infos;
  5016. List<Vector<VkBufferView>> buffer_views;
  5017. List<Vector<VkDescriptorImageInfo>> image_infos;
  5018. // Used for verification to make sure a uniform set does not use a framebuffer bound texture.
  5019. LocalVector<UniformSet::AttachableTexture> attachable_textures;
  5020. Vector<Texture *> mutable_sampled_textures;
  5021. Vector<Texture *> mutable_storage_textures;
  5022. for (uint32_t i = 0; i < set_uniform_count; i++) {
  5023. const UniformInfo &set_uniform = set_uniforms[i];
  5024. int uniform_idx = -1;
  5025. for (int j = 0; j < (int)uniform_count; j++) {
  5026. if (uniforms[j].binding == set_uniform.binding) {
  5027. uniform_idx = j;
  5028. }
  5029. }
  5030. ERR_FAIL_COND_V_MSG(uniform_idx == -1, RID(),
  5031. "All the shader bindings for the given set must be covered by the uniforms provided. Binding (" + itos(set_uniform.binding) + "), set (" + itos(p_shader_set) + ") was not provided.");
  5032. const Uniform &uniform = uniforms[uniform_idx];
  5033. ERR_FAIL_COND_V_MSG(uniform.uniform_type != set_uniform.type, RID(),
  5034. "Mismatch uniform type for binding (" + itos(set_uniform.binding) + "), set (" + itos(p_shader_set) + "). Expected '" + shader_uniform_names[set_uniform.type] + "', supplied: '" + shader_uniform_names[uniform.uniform_type] + "'.");
  5035. VkWriteDescriptorSet write; // Common header.
  5036. write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  5037. write.pNext = nullptr;
  5038. write.dstSet = VK_NULL_HANDLE; // Will assign afterwards when everything is valid.
  5039. write.dstBinding = set_uniform.binding;
  5040. write.dstArrayElement = 0;
  5041. write.descriptorCount = 0;
  5042. write.descriptorType = VK_DESCRIPTOR_TYPE_MAX_ENUM; // Invalid value.
  5043. write.pImageInfo = nullptr;
  5044. write.pBufferInfo = nullptr;
  5045. write.pTexelBufferView = nullptr;
  5046. uint32_t type_size = 1;
  5047. switch (uniform.uniform_type) {
  5048. case UNIFORM_TYPE_SAMPLER: {
  5049. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  5050. if (set_uniform.length > 1) {
  5051. ERR_FAIL_V_MSG(RID(), "Sampler (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") sampler elements, so it should be provided equal number of sampler IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5052. } else {
  5053. ERR_FAIL_V_MSG(RID(), "Sampler (binding: " + itos(uniform.binding) + ") should provide one ID referencing a sampler (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5054. }
  5055. }
  5056. Vector<VkDescriptorImageInfo> image_info;
  5057. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  5058. VkSampler *sampler = sampler_owner.get_or_null(uniform.get_id(j));
  5059. ERR_FAIL_COND_V_MSG(!sampler, RID(), "Sampler (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid sampler.");
  5060. VkDescriptorImageInfo img_info;
  5061. img_info.sampler = *sampler;
  5062. img_info.imageView = VK_NULL_HANDLE;
  5063. img_info.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  5064. image_info.push_back(img_info);
  5065. }
  5066. write.dstArrayElement = 0;
  5067. write.descriptorCount = uniform.get_id_count();
  5068. write.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
  5069. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  5070. write.pBufferInfo = nullptr;
  5071. write.pTexelBufferView = nullptr;
  5072. type_size = uniform.get_id_count();
  5073. } break;
  5074. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {
  5075. if (uniform.get_id_count() != (uint32_t)set_uniform.length * 2) {
  5076. if (set_uniform.length > 1) {
  5077. ERR_FAIL_V_MSG(RID(), "SamplerTexture (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") sampler&texture elements, so it should provided twice the amount of IDs (sampler,texture pairs) to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5078. } else {
  5079. ERR_FAIL_V_MSG(RID(), "SamplerTexture (binding: " + itos(uniform.binding) + ") should provide two IDs referencing a sampler and then a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5080. }
  5081. }
  5082. Vector<VkDescriptorImageInfo> image_info;
  5083. for (uint32_t j = 0; j < uniform.get_id_count(); j += 2) {
  5084. VkSampler *sampler = sampler_owner.get_or_null(uniform.get_id(j + 0));
  5085. ERR_FAIL_COND_V_MSG(!sampler, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler.");
  5086. Texture *texture = texture_owner.get_or_null(uniform.get_id(j + 1));
  5087. ERR_FAIL_COND_V_MSG(!texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  5088. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  5089. "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  5090. VkDescriptorImageInfo img_info;
  5091. img_info.sampler = *sampler;
  5092. img_info.imageView = texture->view;
  5093. if (texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT)) {
  5094. UniformSet::AttachableTexture attachable_texture;
  5095. attachable_texture.bind = set_uniform.binding;
  5096. attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.get_id(j + 1);
  5097. attachable_textures.push_back(attachable_texture);
  5098. }
  5099. if (texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  5100. // Can also be used as storage, add to mutable sampled.
  5101. mutable_sampled_textures.push_back(texture);
  5102. }
  5103. if (texture->owner.is_valid()) {
  5104. texture = texture_owner.get_or_null(texture->owner);
  5105. ERR_FAIL_COND_V(!texture, RID()); // Bug, should never happen.
  5106. }
  5107. img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  5108. image_info.push_back(img_info);
  5109. }
  5110. write.dstArrayElement = 0;
  5111. write.descriptorCount = uniform.get_id_count() / 2;
  5112. write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  5113. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  5114. write.pBufferInfo = nullptr;
  5115. write.pTexelBufferView = nullptr;
  5116. type_size = uniform.get_id_count() / 2;
  5117. } break;
  5118. case UNIFORM_TYPE_TEXTURE: {
  5119. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  5120. if (set_uniform.length > 1) {
  5121. ERR_FAIL_V_MSG(RID(), "Texture (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5122. } else {
  5123. ERR_FAIL_V_MSG(RID(), "Texture (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5124. }
  5125. }
  5126. Vector<VkDescriptorImageInfo> image_info;
  5127. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  5128. Texture *texture = texture_owner.get_or_null(uniform.get_id(j));
  5129. ERR_FAIL_COND_V_MSG(!texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  5130. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  5131. "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  5132. VkDescriptorImageInfo img_info;
  5133. img_info.sampler = VK_NULL_HANDLE;
  5134. img_info.imageView = texture->view;
  5135. if (texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT)) {
  5136. UniformSet::AttachableTexture attachable_texture;
  5137. attachable_texture.bind = set_uniform.binding;
  5138. attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.get_id(j);
  5139. attachable_textures.push_back(attachable_texture);
  5140. }
  5141. if (texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  5142. // Can also be used as storage, add to mutable sampled.
  5143. mutable_sampled_textures.push_back(texture);
  5144. }
  5145. if (texture->owner.is_valid()) {
  5146. texture = texture_owner.get_or_null(texture->owner);
  5147. ERR_FAIL_COND_V(!texture, RID()); // Bug, should never happen.
  5148. }
  5149. img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  5150. image_info.push_back(img_info);
  5151. }
  5152. write.dstArrayElement = 0;
  5153. write.descriptorCount = uniform.get_id_count();
  5154. write.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  5155. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  5156. write.pBufferInfo = nullptr;
  5157. write.pTexelBufferView = nullptr;
  5158. type_size = uniform.get_id_count();
  5159. } break;
  5160. case UNIFORM_TYPE_IMAGE: {
  5161. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  5162. if (set_uniform.length > 1) {
  5163. ERR_FAIL_V_MSG(RID(), "Image (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5164. } else {
  5165. ERR_FAIL_V_MSG(RID(), "Image (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5166. }
  5167. }
  5168. Vector<VkDescriptorImageInfo> image_info;
  5169. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  5170. Texture *texture = texture_owner.get_or_null(uniform.get_id(j));
  5171. ERR_FAIL_COND_V_MSG(!texture, RID(),
  5172. "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  5173. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT), RID(),
  5174. "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_STORAGE_BIT usage flag set in order to be used as uniform.");
  5175. VkDescriptorImageInfo img_info;
  5176. img_info.sampler = VK_NULL_HANDLE;
  5177. img_info.imageView = texture->view;
  5178. if (texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT) {
  5179. // Can also be used as storage, add to mutable sampled.
  5180. mutable_storage_textures.push_back(texture);
  5181. }
  5182. if (texture->owner.is_valid()) {
  5183. texture = texture_owner.get_or_null(texture->owner);
  5184. ERR_FAIL_COND_V(!texture, RID()); // Bug, should never happen.
  5185. }
  5186. img_info.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
  5187. image_info.push_back(img_info);
  5188. }
  5189. write.dstArrayElement = 0;
  5190. write.descriptorCount = uniform.get_id_count();
  5191. write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  5192. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  5193. write.pBufferInfo = nullptr;
  5194. write.pTexelBufferView = nullptr;
  5195. type_size = uniform.get_id_count();
  5196. } break;
  5197. case UNIFORM_TYPE_TEXTURE_BUFFER: {
  5198. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  5199. if (set_uniform.length > 1) {
  5200. ERR_FAIL_V_MSG(RID(), "Buffer (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") texture buffer elements, so it should be provided equal number of texture buffer IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5201. } else {
  5202. ERR_FAIL_V_MSG(RID(), "Buffer (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture buffer (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5203. }
  5204. }
  5205. Vector<VkDescriptorBufferInfo> buffer_info;
  5206. Vector<VkBufferView> buffer_view;
  5207. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  5208. TextureBuffer *buffer = texture_buffer_owner.get_or_null(uniform.get_id(j));
  5209. ERR_FAIL_COND_V_MSG(!buffer, RID(), "Texture Buffer (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture buffer.");
  5210. buffer_info.push_back(buffer->buffer.buffer_info);
  5211. buffer_view.push_back(buffer->view);
  5212. }
  5213. write.dstArrayElement = 0;
  5214. write.descriptorCount = uniform.get_id_count();
  5215. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  5216. write.pImageInfo = nullptr;
  5217. write.pBufferInfo = buffer_infos.push_back(buffer_info)->get().ptr();
  5218. write.pTexelBufferView = buffer_views.push_back(buffer_view)->get().ptr();
  5219. type_size = uniform.get_id_count();
  5220. } break;
  5221. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: {
  5222. if (uniform.get_id_count() != (uint32_t)set_uniform.length * 2) {
  5223. if (set_uniform.length > 1) {
  5224. ERR_FAIL_V_MSG(RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") sampler buffer elements, so it should provided twice the amount of IDs (sampler,buffer pairs) to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5225. } else {
  5226. ERR_FAIL_V_MSG(RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ") should provide two IDs referencing a sampler and then a texture buffer (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5227. }
  5228. }
  5229. Vector<VkDescriptorImageInfo> image_info;
  5230. Vector<VkDescriptorBufferInfo> buffer_info;
  5231. Vector<VkBufferView> buffer_view;
  5232. for (uint32_t j = 0; j < uniform.get_id_count(); j += 2) {
  5233. VkSampler *sampler = sampler_owner.get_or_null(uniform.get_id(j + 0));
  5234. ERR_FAIL_COND_V_MSG(!sampler, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler.");
  5235. TextureBuffer *buffer = texture_buffer_owner.get_or_null(uniform.get_id(j + 1));
  5236. VkDescriptorImageInfo img_info;
  5237. img_info.sampler = *sampler;
  5238. img_info.imageView = VK_NULL_HANDLE;
  5239. img_info.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  5240. image_info.push_back(img_info);
  5241. ERR_FAIL_COND_V_MSG(!buffer, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid texture buffer.");
  5242. buffer_info.push_back(buffer->buffer.buffer_info);
  5243. buffer_view.push_back(buffer->view);
  5244. }
  5245. write.dstArrayElement = 0;
  5246. write.descriptorCount = uniform.get_id_count() / 2;
  5247. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  5248. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  5249. write.pBufferInfo = buffer_infos.push_back(buffer_info)->get().ptr();
  5250. write.pTexelBufferView = buffer_views.push_back(buffer_view)->get().ptr();
  5251. type_size = uniform.get_id_count() / 2;
  5252. } break;
  5253. case UNIFORM_TYPE_IMAGE_BUFFER: {
  5254. // Todo.
  5255. } break;
  5256. case UNIFORM_TYPE_UNIFORM_BUFFER: {
  5257. ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(),
  5258. "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.get_id_count()) + " provided).");
  5259. Buffer *buffer = uniform_buffer_owner.get_or_null(uniform.get_id(0));
  5260. ERR_FAIL_COND_V_MSG(!buffer, RID(), "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") is invalid.");
  5261. ERR_FAIL_COND_V_MSG(buffer->size != (uint32_t)set_uniform.length, RID(),
  5262. "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " does not match size of shader uniform: (" + itos(set_uniform.length) + ").");
  5263. write.dstArrayElement = 0;
  5264. write.descriptorCount = 1;
  5265. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  5266. write.pImageInfo = nullptr;
  5267. write.pBufferInfo = &buffer->buffer_info;
  5268. write.pTexelBufferView = nullptr;
  5269. } break;
  5270. case UNIFORM_TYPE_STORAGE_BUFFER: {
  5271. ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(),
  5272. "Storage buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.get_id_count()) + " provided).");
  5273. Buffer *buffer = nullptr;
  5274. if (storage_buffer_owner.owns(uniform.get_id(0))) {
  5275. buffer = storage_buffer_owner.get_or_null(uniform.get_id(0));
  5276. } else if (vertex_buffer_owner.owns(uniform.get_id(0))) {
  5277. buffer = vertex_buffer_owner.get_or_null(uniform.get_id(0));
  5278. ERR_FAIL_COND_V_MSG(!(buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT), RID(), "Vertex buffer supplied (binding: " + itos(uniform.binding) + ") was not created with storage flag.");
  5279. }
  5280. ERR_FAIL_COND_V_MSG(!buffer, RID(), "Storage buffer supplied (binding: " + itos(uniform.binding) + ") is invalid.");
  5281. // If 0, then it's sized on link time.
  5282. ERR_FAIL_COND_V_MSG(set_uniform.length > 0 && buffer->size != (uint32_t)set_uniform.length, RID(),
  5283. "Storage buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " does not match size of shader uniform: (" + itos(set_uniform.length) + ").");
  5284. write.dstArrayElement = 0;
  5285. write.descriptorCount = 1;
  5286. write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  5287. write.pImageInfo = nullptr;
  5288. write.pBufferInfo = &buffer->buffer_info;
  5289. write.pTexelBufferView = nullptr;
  5290. } break;
  5291. case UNIFORM_TYPE_INPUT_ATTACHMENT: {
  5292. ERR_FAIL_COND_V_MSG(shader->is_compute, RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") supplied for compute shader (this is not allowed).");
  5293. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  5294. if (set_uniform.length > 1) {
  5295. ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5296. } else {
  5297. ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5298. }
  5299. }
  5300. Vector<VkDescriptorImageInfo> image_info;
  5301. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  5302. Texture *texture = texture_owner.get_or_null(uniform.get_id(j));
  5303. ERR_FAIL_COND_V_MSG(!texture, RID(),
  5304. "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  5305. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  5306. "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  5307. VkDescriptorImageInfo img_info;
  5308. img_info.sampler = VK_NULL_HANDLE;
  5309. img_info.imageView = texture->view;
  5310. if (texture->owner.is_valid()) {
  5311. texture = texture_owner.get_or_null(texture->owner);
  5312. ERR_FAIL_COND_V(!texture, RID()); // Bug, should never happen.
  5313. }
  5314. img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  5315. image_info.push_back(img_info);
  5316. }
  5317. write.dstArrayElement = 0;
  5318. write.descriptorCount = uniform.get_id_count();
  5319. write.descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
  5320. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  5321. write.pBufferInfo = nullptr;
  5322. write.pTexelBufferView = nullptr;
  5323. type_size = uniform.get_id_count();
  5324. } break;
  5325. default: {
  5326. }
  5327. }
  5328. writes.push_back(write);
  5329. ERR_FAIL_COND_V_MSG(pool_key.uniform_type[set_uniform.type] == MAX_DESCRIPTOR_POOL_ELEMENT, RID(),
  5330. "Uniform set reached the limit of bindings for the same type (" + itos(MAX_DESCRIPTOR_POOL_ELEMENT) + ").");
  5331. pool_key.uniform_type[set_uniform.type] += type_size;
  5332. }
  5333. // Need a descriptor pool.
  5334. DescriptorPool *pool = _descriptor_pool_allocate(pool_key);
  5335. ERR_FAIL_COND_V(!pool, RID());
  5336. VkDescriptorSetAllocateInfo descriptor_set_allocate_info;
  5337. descriptor_set_allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
  5338. descriptor_set_allocate_info.pNext = nullptr;
  5339. descriptor_set_allocate_info.descriptorPool = pool->pool;
  5340. descriptor_set_allocate_info.descriptorSetCount = 1;
  5341. descriptor_set_allocate_info.pSetLayouts = &shader->sets[p_shader_set].descriptor_set_layout;
  5342. VkDescriptorSet descriptor_set;
  5343. VkResult res = vkAllocateDescriptorSets(device, &descriptor_set_allocate_info, &descriptor_set);
  5344. if (res) {
  5345. _descriptor_pool_free(pool_key, pool); // Meh.
  5346. ERR_FAIL_V_MSG(RID(), "Cannot allocate descriptor sets, error " + itos(res) + ".");
  5347. }
  5348. UniformSet uniform_set;
  5349. uniform_set.pool = pool;
  5350. uniform_set.pool_key = pool_key;
  5351. uniform_set.descriptor_set = descriptor_set;
  5352. uniform_set.format = shader->set_formats[p_shader_set];
  5353. uniform_set.attachable_textures = attachable_textures;
  5354. uniform_set.mutable_sampled_textures = mutable_sampled_textures;
  5355. uniform_set.mutable_storage_textures = mutable_storage_textures;
  5356. uniform_set.shader_set = p_shader_set;
  5357. uniform_set.shader_id = p_shader;
  5358. RID id = uniform_set_owner.make_rid(uniform_set);
  5359. #ifdef DEV_ENABLED
  5360. set_resource_name(id, "RID:" + itos(id.get_id()));
  5361. #endif
  5362. // Add dependencies.
  5363. _add_dependency(id, p_shader);
  5364. for (uint32_t i = 0; i < uniform_count; i++) {
  5365. const Uniform &uniform = uniforms[i];
  5366. int id_count = uniform.get_id_count();
  5367. for (int j = 0; j < id_count; j++) {
  5368. _add_dependency(id, uniform.get_id(j));
  5369. }
  5370. }
  5371. // Write the contents.
  5372. if (writes.size()) {
  5373. for (int i = 0; i < writes.size(); i++) {
  5374. writes.write[i].dstSet = descriptor_set;
  5375. }
  5376. vkUpdateDescriptorSets(device, writes.size(), writes.ptr(), 0, nullptr);
  5377. }
  5378. return id;
  5379. }
  5380. bool RenderingDeviceVulkan::uniform_set_is_valid(RID p_uniform_set) {
  5381. return uniform_set_owner.owns(p_uniform_set);
  5382. }
  5383. void RenderingDeviceVulkan::uniform_set_set_invalidation_callback(RID p_uniform_set, InvalidationCallback p_callback, void *p_userdata) {
  5384. UniformSet *us = uniform_set_owner.get_or_null(p_uniform_set);
  5385. ERR_FAIL_COND(!us);
  5386. us->invalidated_callback = p_callback;
  5387. us->invalidated_callback_userdata = p_userdata;
  5388. }
  5389. Error RenderingDeviceVulkan::buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, uint32_t p_post_barrier) {
  5390. _THREAD_SAFE_METHOD_
  5391. ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER,
  5392. "Updating buffers is forbidden during creation of a draw list");
  5393. ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER,
  5394. "Updating buffers is forbidden during creation of a compute list");
  5395. VkPipelineStageFlags dst_stage_mask = 0;
  5396. VkAccessFlags dst_access = 0;
  5397. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  5398. // Protect subsequent updates.
  5399. dst_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT;
  5400. dst_access = VK_ACCESS_TRANSFER_WRITE_BIT;
  5401. }
  5402. Buffer *buffer = _get_buffer_from_owner(p_buffer, dst_stage_mask, dst_access, p_post_barrier);
  5403. if (!buffer) {
  5404. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type.");
  5405. }
  5406. ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER,
  5407. "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end.");
  5408. // No barrier should be needed here.
  5409. // _buffer_memory_barrier(buffer->buffer, p_offset, p_size, dst_stage_mask, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_access, VK_ACCESS_TRANSFER_WRITE_BIT, true);
  5410. Error err = _buffer_update(buffer, p_offset, (uint8_t *)p_data, p_size, p_post_barrier);
  5411. if (err) {
  5412. return err;
  5413. }
  5414. #ifdef FORCE_FULL_BARRIER
  5415. _full_barrier(true);
  5416. #else
  5417. if (dst_stage_mask == 0) {
  5418. dst_stage_mask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  5419. }
  5420. if (p_post_barrier != RD::BARRIER_MASK_NO_BARRIER) {
  5421. _buffer_memory_barrier(buffer->buffer, p_offset, p_size, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_stage_mask, VK_ACCESS_TRANSFER_WRITE_BIT, dst_access, true);
  5422. }
  5423. #endif
  5424. return err;
  5425. }
  5426. Error RenderingDeviceVulkan::buffer_clear(RID p_buffer, uint32_t p_offset, uint32_t p_size, uint32_t p_post_barrier) {
  5427. _THREAD_SAFE_METHOD_
  5428. ERR_FAIL_COND_V_MSG((p_size % 4) != 0, ERR_INVALID_PARAMETER,
  5429. "Size must be a multiple of four");
  5430. ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER,
  5431. "Updating buffers in is forbidden during creation of a draw list");
  5432. ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER,
  5433. "Updating buffers is forbidden during creation of a compute list");
  5434. VkPipelineStageFlags dst_stage_mask = 0;
  5435. VkAccessFlags dst_access = 0;
  5436. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  5437. // Protect subsequent updates.
  5438. dst_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT;
  5439. dst_access = VK_ACCESS_TRANSFER_WRITE_BIT;
  5440. }
  5441. Buffer *buffer = _get_buffer_from_owner(p_buffer, dst_stage_mask, dst_access, p_post_barrier);
  5442. if (!buffer) {
  5443. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type.");
  5444. }
  5445. ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER,
  5446. "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end.");
  5447. // Should not be needed.
  5448. // _buffer_memory_barrier(buffer->buffer, p_offset, p_size, dst_stage_mask, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_access, VK_ACCESS_TRANSFER_WRITE_BIT, p_post_barrier);
  5449. vkCmdFillBuffer(frames[frame].draw_command_buffer, buffer->buffer, p_offset, p_size, 0);
  5450. #ifdef FORCE_FULL_BARRIER
  5451. _full_barrier(true);
  5452. #else
  5453. if (dst_stage_mask == 0) {
  5454. dst_stage_mask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  5455. }
  5456. _buffer_memory_barrier(buffer->buffer, p_offset, p_size, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_stage_mask, VK_ACCESS_TRANSFER_WRITE_BIT, dst_access, dst_stage_mask);
  5457. #endif
  5458. return OK;
  5459. }
  5460. Vector<uint8_t> RenderingDeviceVulkan::buffer_get_data(RID p_buffer) {
  5461. _THREAD_SAFE_METHOD_
  5462. // It could be this buffer was just created.
  5463. VkPipelineShaderStageCreateFlags src_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT;
  5464. VkAccessFlags src_access_mask = VK_ACCESS_TRANSFER_WRITE_BIT;
  5465. // Get the vulkan buffer and the potential stage/access possible.
  5466. Buffer *buffer = _get_buffer_from_owner(p_buffer, src_stage_mask, src_access_mask, BARRIER_MASK_ALL);
  5467. if (!buffer) {
  5468. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Buffer is either invalid or this type of buffer can't be retrieved. Only Index and Vertex buffers allow retrieving.");
  5469. }
  5470. // Make sure no one is using the buffer -- the "false" gets us to the same command buffer as below.
  5471. _buffer_memory_barrier(buffer->buffer, 0, buffer->size, src_stage_mask, src_access_mask, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT, false);
  5472. VkCommandBuffer command_buffer = frames[frame].setup_command_buffer;
  5473. Buffer tmp_buffer;
  5474. _buffer_allocate(&tmp_buffer, buffer->size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_HOST, VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT);
  5475. VkBufferCopy region;
  5476. region.srcOffset = 0;
  5477. region.dstOffset = 0;
  5478. region.size = buffer->size;
  5479. vkCmdCopyBuffer(command_buffer, buffer->buffer, tmp_buffer.buffer, 1, &region); // Dst buffer is in CPU, but I wonder if src buffer needs a barrier for this.
  5480. // Flush everything so memory can be safely mapped.
  5481. _flush(true);
  5482. void *buffer_mem;
  5483. VkResult vkerr = vmaMapMemory(allocator, tmp_buffer.allocation, &buffer_mem);
  5484. ERR_FAIL_COND_V_MSG(vkerr, Vector<uint8_t>(), "vmaMapMemory failed with error " + itos(vkerr) + ".");
  5485. Vector<uint8_t> buffer_data;
  5486. {
  5487. buffer_data.resize(buffer->size);
  5488. uint8_t *w = buffer_data.ptrw();
  5489. memcpy(w, buffer_mem, buffer->size);
  5490. }
  5491. vmaUnmapMemory(allocator, tmp_buffer.allocation);
  5492. _buffer_free(&tmp_buffer);
  5493. return buffer_data;
  5494. }
  5495. /*************************/
  5496. /**** RENDER PIPELINE ****/
  5497. /*************************/
  5498. RID RenderingDeviceVulkan::render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const PipelineRasterizationState &p_rasterization_state, const PipelineMultisampleState &p_multisample_state, const PipelineDepthStencilState &p_depth_stencil_state, const PipelineColorBlendState &p_blend_state, int p_dynamic_state_flags, uint32_t p_for_render_pass, const Vector<PipelineSpecializationConstant> &p_specialization_constants) {
  5499. _THREAD_SAFE_METHOD_
  5500. // Needs a shader.
  5501. Shader *shader = shader_owner.get_or_null(p_shader);
  5502. ERR_FAIL_COND_V(!shader, RID());
  5503. ERR_FAIL_COND_V_MSG(shader->is_compute, RID(),
  5504. "Compute shaders can't be used in render pipelines");
  5505. if (p_framebuffer_format == INVALID_ID) {
  5506. // If nothing provided, use an empty one (no attachments).
  5507. p_framebuffer_format = framebuffer_format_create(Vector<AttachmentFormat>());
  5508. }
  5509. ERR_FAIL_COND_V(!framebuffer_formats.has(p_framebuffer_format), RID());
  5510. const FramebufferFormat &fb_format = framebuffer_formats[p_framebuffer_format];
  5511. { // Validate shader vs framebuffer.
  5512. ERR_FAIL_COND_V_MSG(p_for_render_pass >= uint32_t(fb_format.E->key().passes.size()), RID(), "Render pass requested for pipeline creation (" + itos(p_for_render_pass) + ") is out of bounds");
  5513. const FramebufferPass &pass = fb_format.E->key().passes[p_for_render_pass];
  5514. uint32_t output_mask = 0;
  5515. for (int i = 0; i < pass.color_attachments.size(); i++) {
  5516. if (pass.color_attachments[i] != FramebufferPass::ATTACHMENT_UNUSED) {
  5517. output_mask |= 1 << i;
  5518. }
  5519. }
  5520. ERR_FAIL_COND_V_MSG(shader->fragment_output_mask != output_mask, RID(),
  5521. "Mismatch fragment shader output mask (" + itos(shader->fragment_output_mask) + ") and framebuffer color output mask (" + itos(output_mask) + ") when binding both in render pipeline.");
  5522. }
  5523. // Vertex.
  5524. VkPipelineVertexInputStateCreateInfo pipeline_vertex_input_state_create_info;
  5525. if (p_vertex_format != INVALID_ID) {
  5526. // Uses vertices, else it does not.
  5527. ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID());
  5528. const VertexDescriptionCache &vd = vertex_formats[p_vertex_format];
  5529. pipeline_vertex_input_state_create_info = vd.create_info;
  5530. // Validate with inputs.
  5531. for (uint32_t i = 0; i < 32; i++) {
  5532. if (!(shader->vertex_input_mask & (1UL << i))) {
  5533. continue;
  5534. }
  5535. bool found = false;
  5536. for (int j = 0; j < vd.vertex_formats.size(); j++) {
  5537. if (vd.vertex_formats[j].location == i) {
  5538. found = true;
  5539. }
  5540. }
  5541. ERR_FAIL_COND_V_MSG(!found, RID(),
  5542. "Shader vertex input location (" + itos(i) + ") not provided in vertex input description for pipeline creation.");
  5543. }
  5544. } else {
  5545. // Does not use vertices.
  5546. pipeline_vertex_input_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  5547. pipeline_vertex_input_state_create_info.pNext = nullptr;
  5548. pipeline_vertex_input_state_create_info.flags = 0;
  5549. pipeline_vertex_input_state_create_info.vertexBindingDescriptionCount = 0;
  5550. pipeline_vertex_input_state_create_info.pVertexBindingDescriptions = nullptr;
  5551. pipeline_vertex_input_state_create_info.vertexAttributeDescriptionCount = 0;
  5552. pipeline_vertex_input_state_create_info.pVertexAttributeDescriptions = nullptr;
  5553. ERR_FAIL_COND_V_MSG(shader->vertex_input_mask != 0, RID(),
  5554. "Shader contains vertex inputs, but no vertex input description was provided for pipeline creation.");
  5555. }
  5556. // Input assembly.
  5557. ERR_FAIL_INDEX_V(p_render_primitive, RENDER_PRIMITIVE_MAX, RID());
  5558. VkPipelineInputAssemblyStateCreateInfo input_assembly_create_info;
  5559. input_assembly_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  5560. input_assembly_create_info.pNext = nullptr;
  5561. input_assembly_create_info.flags = 0;
  5562. static const VkPrimitiveTopology topology_list[RENDER_PRIMITIVE_MAX] = {
  5563. VK_PRIMITIVE_TOPOLOGY_POINT_LIST,
  5564. VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
  5565. VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY,
  5566. VK_PRIMITIVE_TOPOLOGY_LINE_STRIP,
  5567. VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY,
  5568. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
  5569. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY,
  5570. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
  5571. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY,
  5572. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
  5573. VK_PRIMITIVE_TOPOLOGY_PATCH_LIST
  5574. };
  5575. input_assembly_create_info.topology = topology_list[p_render_primitive];
  5576. input_assembly_create_info.primitiveRestartEnable = (p_render_primitive == RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX);
  5577. // Tessellation.
  5578. VkPipelineTessellationStateCreateInfo tessellation_create_info;
  5579. tessellation_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO;
  5580. tessellation_create_info.pNext = nullptr;
  5581. tessellation_create_info.flags = 0;
  5582. ERR_FAIL_COND_V(limits.maxTessellationPatchSize > 0 && (p_rasterization_state.patch_control_points < 1 || p_rasterization_state.patch_control_points > limits.maxTessellationPatchSize), RID());
  5583. tessellation_create_info.patchControlPoints = p_rasterization_state.patch_control_points;
  5584. VkPipelineViewportStateCreateInfo viewport_state_create_info;
  5585. viewport_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  5586. viewport_state_create_info.pNext = nullptr;
  5587. viewport_state_create_info.flags = 0;
  5588. viewport_state_create_info.viewportCount = 1; // If VR extensions are supported at some point, this will have to be customizable in the framebuffer format.
  5589. viewport_state_create_info.pViewports = nullptr;
  5590. viewport_state_create_info.scissorCount = 1;
  5591. viewport_state_create_info.pScissors = nullptr;
  5592. // Rasterization.
  5593. VkPipelineRasterizationStateCreateInfo rasterization_state_create_info;
  5594. rasterization_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  5595. rasterization_state_create_info.pNext = nullptr;
  5596. rasterization_state_create_info.flags = 0;
  5597. rasterization_state_create_info.depthClampEnable = p_rasterization_state.enable_depth_clamp;
  5598. rasterization_state_create_info.rasterizerDiscardEnable = p_rasterization_state.discard_primitives;
  5599. rasterization_state_create_info.polygonMode = (p_rasterization_state.wireframe ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL);
  5600. static const VkCullModeFlags cull_mode[3] = {
  5601. VK_CULL_MODE_NONE,
  5602. VK_CULL_MODE_FRONT_BIT,
  5603. VK_CULL_MODE_BACK_BIT
  5604. };
  5605. ERR_FAIL_INDEX_V(p_rasterization_state.cull_mode, 3, RID());
  5606. rasterization_state_create_info.cullMode = cull_mode[p_rasterization_state.cull_mode];
  5607. rasterization_state_create_info.frontFace = (p_rasterization_state.front_face == POLYGON_FRONT_FACE_CLOCKWISE ? VK_FRONT_FACE_CLOCKWISE : VK_FRONT_FACE_COUNTER_CLOCKWISE);
  5608. rasterization_state_create_info.depthBiasEnable = p_rasterization_state.depth_bias_enable;
  5609. rasterization_state_create_info.depthBiasConstantFactor = p_rasterization_state.depth_bias_constant_factor;
  5610. rasterization_state_create_info.depthBiasClamp = p_rasterization_state.depth_bias_clamp;
  5611. rasterization_state_create_info.depthBiasSlopeFactor = p_rasterization_state.depth_bias_slope_factor;
  5612. rasterization_state_create_info.lineWidth = p_rasterization_state.line_width;
  5613. // Multisample.
  5614. VkPipelineMultisampleStateCreateInfo multisample_state_create_info;
  5615. multisample_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  5616. multisample_state_create_info.pNext = nullptr;
  5617. multisample_state_create_info.flags = 0;
  5618. multisample_state_create_info.rasterizationSamples = _ensure_supported_sample_count(p_multisample_state.sample_count);
  5619. multisample_state_create_info.sampleShadingEnable = p_multisample_state.enable_sample_shading;
  5620. multisample_state_create_info.minSampleShading = p_multisample_state.min_sample_shading;
  5621. Vector<VkSampleMask> sample_mask;
  5622. if (p_multisample_state.sample_mask.size()) {
  5623. // Use sample mask.
  5624. const int rasterization_sample_mask_expected_size[TEXTURE_SAMPLES_MAX] = {
  5625. 1, 2, 4, 8, 16, 32, 64
  5626. };
  5627. ERR_FAIL_COND_V(rasterization_sample_mask_expected_size[p_multisample_state.sample_count] != p_multisample_state.sample_mask.size(), RID());
  5628. sample_mask.resize(p_multisample_state.sample_mask.size());
  5629. for (int i = 0; i < p_multisample_state.sample_mask.size(); i++) {
  5630. VkSampleMask mask = p_multisample_state.sample_mask[i];
  5631. sample_mask.push_back(mask);
  5632. }
  5633. multisample_state_create_info.pSampleMask = sample_mask.ptr();
  5634. } else {
  5635. multisample_state_create_info.pSampleMask = nullptr;
  5636. }
  5637. multisample_state_create_info.alphaToCoverageEnable = p_multisample_state.enable_alpha_to_coverage;
  5638. multisample_state_create_info.alphaToOneEnable = p_multisample_state.enable_alpha_to_one;
  5639. // Depth stencil.
  5640. VkPipelineDepthStencilStateCreateInfo depth_stencil_state_create_info;
  5641. depth_stencil_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
  5642. depth_stencil_state_create_info.pNext = nullptr;
  5643. depth_stencil_state_create_info.flags = 0;
  5644. depth_stencil_state_create_info.depthTestEnable = p_depth_stencil_state.enable_depth_test;
  5645. depth_stencil_state_create_info.depthWriteEnable = p_depth_stencil_state.enable_depth_write;
  5646. ERR_FAIL_INDEX_V(p_depth_stencil_state.depth_compare_operator, COMPARE_OP_MAX, RID());
  5647. depth_stencil_state_create_info.depthCompareOp = compare_operators[p_depth_stencil_state.depth_compare_operator];
  5648. depth_stencil_state_create_info.depthBoundsTestEnable = p_depth_stencil_state.enable_depth_range;
  5649. depth_stencil_state_create_info.stencilTestEnable = p_depth_stencil_state.enable_stencil;
  5650. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.fail, STENCIL_OP_MAX, RID());
  5651. depth_stencil_state_create_info.front.failOp = stencil_operations[p_depth_stencil_state.front_op.fail];
  5652. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.pass, STENCIL_OP_MAX, RID());
  5653. depth_stencil_state_create_info.front.passOp = stencil_operations[p_depth_stencil_state.front_op.pass];
  5654. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.depth_fail, STENCIL_OP_MAX, RID());
  5655. depth_stencil_state_create_info.front.depthFailOp = stencil_operations[p_depth_stencil_state.front_op.depth_fail];
  5656. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.compare, COMPARE_OP_MAX, RID());
  5657. depth_stencil_state_create_info.front.compareOp = compare_operators[p_depth_stencil_state.front_op.compare];
  5658. depth_stencil_state_create_info.front.compareMask = p_depth_stencil_state.front_op.compare_mask;
  5659. depth_stencil_state_create_info.front.writeMask = p_depth_stencil_state.front_op.write_mask;
  5660. depth_stencil_state_create_info.front.reference = p_depth_stencil_state.front_op.reference;
  5661. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.fail, STENCIL_OP_MAX, RID());
  5662. depth_stencil_state_create_info.back.failOp = stencil_operations[p_depth_stencil_state.back_op.fail];
  5663. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.pass, STENCIL_OP_MAX, RID());
  5664. depth_stencil_state_create_info.back.passOp = stencil_operations[p_depth_stencil_state.back_op.pass];
  5665. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.depth_fail, STENCIL_OP_MAX, RID());
  5666. depth_stencil_state_create_info.back.depthFailOp = stencil_operations[p_depth_stencil_state.back_op.depth_fail];
  5667. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.compare, COMPARE_OP_MAX, RID());
  5668. depth_stencil_state_create_info.back.compareOp = compare_operators[p_depth_stencil_state.back_op.compare];
  5669. depth_stencil_state_create_info.back.compareMask = p_depth_stencil_state.back_op.compare_mask;
  5670. depth_stencil_state_create_info.back.writeMask = p_depth_stencil_state.back_op.write_mask;
  5671. depth_stencil_state_create_info.back.reference = p_depth_stencil_state.back_op.reference;
  5672. depth_stencil_state_create_info.minDepthBounds = p_depth_stencil_state.depth_range_min;
  5673. depth_stencil_state_create_info.maxDepthBounds = p_depth_stencil_state.depth_range_max;
  5674. // Blend state.
  5675. VkPipelineColorBlendStateCreateInfo color_blend_state_create_info;
  5676. color_blend_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  5677. color_blend_state_create_info.pNext = nullptr;
  5678. color_blend_state_create_info.flags = 0;
  5679. color_blend_state_create_info.logicOpEnable = p_blend_state.enable_logic_op;
  5680. ERR_FAIL_INDEX_V(p_blend_state.logic_op, LOGIC_OP_MAX, RID());
  5681. color_blend_state_create_info.logicOp = logic_operations[p_blend_state.logic_op];
  5682. Vector<VkPipelineColorBlendAttachmentState> attachment_states;
  5683. {
  5684. const FramebufferPass &pass = fb_format.E->key().passes[p_for_render_pass];
  5685. attachment_states.resize(pass.color_attachments.size());
  5686. ERR_FAIL_COND_V(p_blend_state.attachments.size() < pass.color_attachments.size(), RID());
  5687. for (int i = 0; i < pass.color_attachments.size(); i++) {
  5688. VkPipelineColorBlendAttachmentState state;
  5689. if (pass.color_attachments[i] == FramebufferPass::ATTACHMENT_UNUSED) {
  5690. state.blendEnable = false;
  5691. state.srcColorBlendFactor = VK_BLEND_FACTOR_ZERO;
  5692. state.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO;
  5693. state.colorBlendOp = VK_BLEND_OP_ADD;
  5694. state.srcAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
  5695. state.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
  5696. state.alphaBlendOp = VK_BLEND_OP_ADD;
  5697. state.colorWriteMask = 0;
  5698. } else {
  5699. state.blendEnable = p_blend_state.attachments[i].enable_blend;
  5700. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_color_blend_factor, BLEND_FACTOR_MAX, RID());
  5701. state.srcColorBlendFactor = blend_factors[p_blend_state.attachments[i].src_color_blend_factor];
  5702. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_color_blend_factor, BLEND_FACTOR_MAX, RID());
  5703. state.dstColorBlendFactor = blend_factors[p_blend_state.attachments[i].dst_color_blend_factor];
  5704. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].color_blend_op, BLEND_OP_MAX, RID());
  5705. state.colorBlendOp = blend_operations[p_blend_state.attachments[i].color_blend_op];
  5706. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_alpha_blend_factor, BLEND_FACTOR_MAX, RID());
  5707. state.srcAlphaBlendFactor = blend_factors[p_blend_state.attachments[i].src_alpha_blend_factor];
  5708. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_alpha_blend_factor, BLEND_FACTOR_MAX, RID());
  5709. state.dstAlphaBlendFactor = blend_factors[p_blend_state.attachments[i].dst_alpha_blend_factor];
  5710. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].alpha_blend_op, BLEND_OP_MAX, RID());
  5711. state.alphaBlendOp = blend_operations[p_blend_state.attachments[i].alpha_blend_op];
  5712. state.colorWriteMask = 0;
  5713. if (p_blend_state.attachments[i].write_r) {
  5714. state.colorWriteMask |= VK_COLOR_COMPONENT_R_BIT;
  5715. }
  5716. if (p_blend_state.attachments[i].write_g) {
  5717. state.colorWriteMask |= VK_COLOR_COMPONENT_G_BIT;
  5718. }
  5719. if (p_blend_state.attachments[i].write_b) {
  5720. state.colorWriteMask |= VK_COLOR_COMPONENT_B_BIT;
  5721. }
  5722. if (p_blend_state.attachments[i].write_a) {
  5723. state.colorWriteMask |= VK_COLOR_COMPONENT_A_BIT;
  5724. }
  5725. }
  5726. attachment_states.write[i] = state;
  5727. }
  5728. }
  5729. color_blend_state_create_info.attachmentCount = attachment_states.size();
  5730. color_blend_state_create_info.pAttachments = attachment_states.ptr();
  5731. color_blend_state_create_info.blendConstants[0] = p_blend_state.blend_constant.r;
  5732. color_blend_state_create_info.blendConstants[1] = p_blend_state.blend_constant.g;
  5733. color_blend_state_create_info.blendConstants[2] = p_blend_state.blend_constant.b;
  5734. color_blend_state_create_info.blendConstants[3] = p_blend_state.blend_constant.a;
  5735. // Dynamic state.
  5736. VkPipelineDynamicStateCreateInfo dynamic_state_create_info;
  5737. dynamic_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
  5738. dynamic_state_create_info.pNext = nullptr;
  5739. dynamic_state_create_info.flags = 0;
  5740. Vector<VkDynamicState> dynamic_states; // Vulkan is weird.
  5741. dynamic_states.push_back(VK_DYNAMIC_STATE_VIEWPORT); // Viewport and scissor are always dynamic.
  5742. dynamic_states.push_back(VK_DYNAMIC_STATE_SCISSOR);
  5743. if (p_dynamic_state_flags & DYNAMIC_STATE_LINE_WIDTH) {
  5744. dynamic_states.push_back(VK_DYNAMIC_STATE_LINE_WIDTH);
  5745. }
  5746. if (p_dynamic_state_flags & DYNAMIC_STATE_DEPTH_BIAS) {
  5747. dynamic_states.push_back(VK_DYNAMIC_STATE_DEPTH_BIAS);
  5748. }
  5749. if (p_dynamic_state_flags & DYNAMIC_STATE_BLEND_CONSTANTS) {
  5750. dynamic_states.push_back(VK_DYNAMIC_STATE_BLEND_CONSTANTS);
  5751. }
  5752. if (p_dynamic_state_flags & DYNAMIC_STATE_DEPTH_BOUNDS) {
  5753. dynamic_states.push_back(VK_DYNAMIC_STATE_DEPTH_BOUNDS);
  5754. }
  5755. if (p_dynamic_state_flags & DYNAMIC_STATE_STENCIL_COMPARE_MASK) {
  5756. dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK);
  5757. }
  5758. if (p_dynamic_state_flags & DYNAMIC_STATE_STENCIL_WRITE_MASK) {
  5759. dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_WRITE_MASK);
  5760. }
  5761. if (p_dynamic_state_flags & DYNAMIC_STATE_STENCIL_REFERENCE) {
  5762. dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_REFERENCE);
  5763. }
  5764. dynamic_state_create_info.dynamicStateCount = dynamic_states.size();
  5765. dynamic_state_create_info.pDynamicStates = dynamic_states.ptr();
  5766. void *graphics_pipeline_nextptr = nullptr;
  5767. VkPipelineFragmentShadingRateStateCreateInfoKHR vrs_create_info;
  5768. if (context->get_vrs_capabilities().attachment_vrs_supported) {
  5769. // If VRS is used, this defines how the different VRS types are combined.
  5770. // combinerOps[0] decides how we use the output of pipeline and primitive (drawcall) VRS.
  5771. // combinerOps[1] decides how we use the output of combinerOps[0] and our attachment VRS.
  5772. vrs_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_FRAGMENT_SHADING_RATE_STATE_CREATE_INFO_KHR;
  5773. vrs_create_info.pNext = nullptr;
  5774. vrs_create_info.fragmentSize = { 4, 4 };
  5775. vrs_create_info.combinerOps[0] = VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR; // We don't use pipeline/primitive VRS so this really doesn't matter.
  5776. vrs_create_info.combinerOps[1] = VK_FRAGMENT_SHADING_RATE_COMBINER_OP_REPLACE_KHR; // Always use the outcome of attachment VRS if enabled.
  5777. graphics_pipeline_nextptr = &vrs_create_info;
  5778. }
  5779. // Finally, pipeline create info.
  5780. VkGraphicsPipelineCreateInfo graphics_pipeline_create_info;
  5781. graphics_pipeline_create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  5782. graphics_pipeline_create_info.pNext = graphics_pipeline_nextptr;
  5783. graphics_pipeline_create_info.flags = 0;
  5784. Vector<VkPipelineShaderStageCreateInfo> pipeline_stages = shader->pipeline_stages;
  5785. Vector<VkSpecializationInfo> specialization_info;
  5786. Vector<Vector<VkSpecializationMapEntry>> specialization_map_entries;
  5787. Vector<uint32_t> specialization_constant_data;
  5788. if (shader->specialization_constants.size()) {
  5789. specialization_constant_data.resize(shader->specialization_constants.size());
  5790. uint32_t *data_ptr = specialization_constant_data.ptrw();
  5791. specialization_info.resize(pipeline_stages.size());
  5792. specialization_map_entries.resize(pipeline_stages.size());
  5793. for (int i = 0; i < shader->specialization_constants.size(); i++) {
  5794. // See if overridden.
  5795. const Shader::SpecializationConstant &sc = shader->specialization_constants[i];
  5796. data_ptr[i] = sc.constant.int_value; // Just copy the 32 bits.
  5797. for (int j = 0; j < p_specialization_constants.size(); j++) {
  5798. const PipelineSpecializationConstant &psc = p_specialization_constants[j];
  5799. if (psc.constant_id == sc.constant.constant_id) {
  5800. ERR_FAIL_COND_V_MSG(psc.type != sc.constant.type, RID(), "Specialization constant provided for id (" + itos(sc.constant.constant_id) + ") is of the wrong type.");
  5801. data_ptr[i] = psc.int_value;
  5802. break;
  5803. }
  5804. }
  5805. VkSpecializationMapEntry entry;
  5806. entry.constantID = sc.constant.constant_id;
  5807. entry.offset = i * sizeof(uint32_t);
  5808. entry.size = sizeof(uint32_t);
  5809. for (int j = 0; j < SHADER_STAGE_MAX; j++) {
  5810. if (sc.stage_flags & (1 << j)) {
  5811. VkShaderStageFlagBits stage = shader_stage_masks[j];
  5812. for (int k = 0; k < pipeline_stages.size(); k++) {
  5813. if (pipeline_stages[k].stage == stage) {
  5814. specialization_map_entries.write[k].push_back(entry);
  5815. }
  5816. }
  5817. }
  5818. }
  5819. }
  5820. for (int i = 0; i < pipeline_stages.size(); i++) {
  5821. if (specialization_map_entries[i].size()) {
  5822. specialization_info.write[i].dataSize = specialization_constant_data.size() * sizeof(uint32_t);
  5823. specialization_info.write[i].pData = data_ptr;
  5824. specialization_info.write[i].mapEntryCount = specialization_map_entries[i].size();
  5825. specialization_info.write[i].pMapEntries = specialization_map_entries[i].ptr();
  5826. pipeline_stages.write[i].pSpecializationInfo = specialization_info.ptr() + i;
  5827. }
  5828. }
  5829. }
  5830. graphics_pipeline_create_info.stageCount = pipeline_stages.size();
  5831. graphics_pipeline_create_info.pStages = pipeline_stages.ptr();
  5832. graphics_pipeline_create_info.pVertexInputState = &pipeline_vertex_input_state_create_info;
  5833. graphics_pipeline_create_info.pInputAssemblyState = &input_assembly_create_info;
  5834. graphics_pipeline_create_info.pTessellationState = &tessellation_create_info;
  5835. graphics_pipeline_create_info.pViewportState = &viewport_state_create_info;
  5836. graphics_pipeline_create_info.pRasterizationState = &rasterization_state_create_info;
  5837. graphics_pipeline_create_info.pMultisampleState = &multisample_state_create_info;
  5838. graphics_pipeline_create_info.pDepthStencilState = &depth_stencil_state_create_info;
  5839. graphics_pipeline_create_info.pColorBlendState = &color_blend_state_create_info;
  5840. graphics_pipeline_create_info.pDynamicState = &dynamic_state_create_info;
  5841. graphics_pipeline_create_info.layout = shader->pipeline_layout;
  5842. graphics_pipeline_create_info.renderPass = fb_format.render_pass;
  5843. graphics_pipeline_create_info.subpass = p_for_render_pass;
  5844. graphics_pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE;
  5845. graphics_pipeline_create_info.basePipelineIndex = 0;
  5846. RenderPipeline pipeline;
  5847. VkResult err = vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &graphics_pipeline_create_info, nullptr, &pipeline.pipeline);
  5848. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateGraphicsPipelines failed with error " + itos(err) + " for shader '" + shader->name + "'.");
  5849. pipeline.set_formats = shader->set_formats;
  5850. pipeline.push_constant_stages = shader->push_constant.push_constants_vk_stage;
  5851. pipeline.pipeline_layout = shader->pipeline_layout;
  5852. pipeline.shader = p_shader;
  5853. pipeline.push_constant_size = shader->push_constant.push_constant_size;
  5854. #ifdef DEBUG_ENABLED
  5855. pipeline.validation.dynamic_state = p_dynamic_state_flags;
  5856. pipeline.validation.framebuffer_format = p_framebuffer_format;
  5857. pipeline.validation.render_pass = p_for_render_pass;
  5858. pipeline.validation.vertex_format = p_vertex_format;
  5859. pipeline.validation.uses_restart_indices = input_assembly_create_info.primitiveRestartEnable;
  5860. static const uint32_t primitive_divisor[RENDER_PRIMITIVE_MAX] = {
  5861. 1, 2, 1, 1, 1, 3, 1, 1, 1, 1, 1
  5862. };
  5863. pipeline.validation.primitive_divisor = primitive_divisor[p_render_primitive];
  5864. static const uint32_t primitive_minimum[RENDER_PRIMITIVE_MAX] = {
  5865. 1,
  5866. 2,
  5867. 2,
  5868. 2,
  5869. 2,
  5870. 3,
  5871. 3,
  5872. 3,
  5873. 3,
  5874. 3,
  5875. 1,
  5876. };
  5877. pipeline.validation.primitive_minimum = primitive_minimum[p_render_primitive];
  5878. #endif
  5879. // Create ID to associate with this pipeline.
  5880. RID id = render_pipeline_owner.make_rid(pipeline);
  5881. #ifdef DEV_ENABLED
  5882. set_resource_name(id, "RID:" + itos(id.get_id()));
  5883. #endif
  5884. // Now add all the dependencies.
  5885. _add_dependency(id, p_shader);
  5886. return id;
  5887. }
  5888. bool RenderingDeviceVulkan::render_pipeline_is_valid(RID p_pipeline) {
  5889. _THREAD_SAFE_METHOD_
  5890. return render_pipeline_owner.owns(p_pipeline);
  5891. }
  5892. /**************************/
  5893. /**** COMPUTE PIPELINE ****/
  5894. /**************************/
  5895. RID RenderingDeviceVulkan::compute_pipeline_create(RID p_shader, const Vector<PipelineSpecializationConstant> &p_specialization_constants) {
  5896. _THREAD_SAFE_METHOD_
  5897. // Needs a shader.
  5898. Shader *shader = shader_owner.get_or_null(p_shader);
  5899. ERR_FAIL_COND_V(!shader, RID());
  5900. ERR_FAIL_COND_V_MSG(!shader->is_compute, RID(),
  5901. "Non-compute shaders can't be used in compute pipelines");
  5902. // Finally, pipeline create info.
  5903. VkComputePipelineCreateInfo compute_pipeline_create_info;
  5904. compute_pipeline_create_info.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
  5905. compute_pipeline_create_info.pNext = nullptr;
  5906. compute_pipeline_create_info.flags = 0;
  5907. compute_pipeline_create_info.stage = shader->pipeline_stages[0];
  5908. compute_pipeline_create_info.layout = shader->pipeline_layout;
  5909. compute_pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE;
  5910. compute_pipeline_create_info.basePipelineIndex = 0;
  5911. VkSpecializationInfo specialization_info;
  5912. Vector<VkSpecializationMapEntry> specialization_map_entries;
  5913. Vector<uint32_t> specialization_constant_data;
  5914. if (shader->specialization_constants.size()) {
  5915. specialization_constant_data.resize(shader->specialization_constants.size());
  5916. uint32_t *data_ptr = specialization_constant_data.ptrw();
  5917. for (int i = 0; i < shader->specialization_constants.size(); i++) {
  5918. // See if overridden.
  5919. const Shader::SpecializationConstant &sc = shader->specialization_constants[i];
  5920. data_ptr[i] = sc.constant.int_value; // Just copy the 32 bits.
  5921. for (int j = 0; j < p_specialization_constants.size(); j++) {
  5922. const PipelineSpecializationConstant &psc = p_specialization_constants[j];
  5923. if (psc.constant_id == sc.constant.constant_id) {
  5924. ERR_FAIL_COND_V_MSG(psc.type != sc.constant.type, RID(), "Specialization constant provided for id (" + itos(sc.constant.constant_id) + ") is of the wrong type.");
  5925. data_ptr[i] = psc.int_value;
  5926. break;
  5927. }
  5928. }
  5929. VkSpecializationMapEntry entry;
  5930. entry.constantID = sc.constant.constant_id;
  5931. entry.offset = i * sizeof(uint32_t);
  5932. entry.size = sizeof(uint32_t);
  5933. specialization_map_entries.push_back(entry);
  5934. }
  5935. specialization_info.dataSize = specialization_constant_data.size() * sizeof(uint32_t);
  5936. specialization_info.pData = data_ptr;
  5937. specialization_info.mapEntryCount = specialization_map_entries.size();
  5938. specialization_info.pMapEntries = specialization_map_entries.ptr();
  5939. compute_pipeline_create_info.stage.pSpecializationInfo = &specialization_info;
  5940. }
  5941. ComputePipeline pipeline;
  5942. VkResult err = vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute_pipeline_create_info, nullptr, &pipeline.pipeline);
  5943. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateComputePipelines failed with error " + itos(err) + ".");
  5944. pipeline.set_formats = shader->set_formats;
  5945. pipeline.push_constant_stages = shader->push_constant.push_constants_vk_stage;
  5946. pipeline.pipeline_layout = shader->pipeline_layout;
  5947. pipeline.shader = p_shader;
  5948. pipeline.push_constant_size = shader->push_constant.push_constant_size;
  5949. pipeline.local_group_size[0] = shader->compute_local_size[0];
  5950. pipeline.local_group_size[1] = shader->compute_local_size[1];
  5951. pipeline.local_group_size[2] = shader->compute_local_size[2];
  5952. // Create ID to associate with this pipeline.
  5953. RID id = compute_pipeline_owner.make_rid(pipeline);
  5954. #ifdef DEV_ENABLED
  5955. set_resource_name(id, "RID:" + itos(id.get_id()));
  5956. #endif
  5957. // Now add all the dependencies.
  5958. _add_dependency(id, p_shader);
  5959. return id;
  5960. }
  5961. bool RenderingDeviceVulkan::compute_pipeline_is_valid(RID p_pipeline) {
  5962. return compute_pipeline_owner.owns(p_pipeline);
  5963. }
  5964. /****************/
  5965. /**** SCREEN ****/
  5966. /****************/
  5967. int RenderingDeviceVulkan::screen_get_width(DisplayServer::WindowID p_screen) const {
  5968. _THREAD_SAFE_METHOD_
  5969. ERR_FAIL_COND_V_MSG(local_device.is_valid(), -1, "Local devices have no screen");
  5970. return context->window_get_width(p_screen);
  5971. }
  5972. int RenderingDeviceVulkan::screen_get_height(DisplayServer::WindowID p_screen) const {
  5973. _THREAD_SAFE_METHOD_
  5974. ERR_FAIL_COND_V_MSG(local_device.is_valid(), -1, "Local devices have no screen");
  5975. return context->window_get_height(p_screen);
  5976. }
  5977. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::screen_get_framebuffer_format() const {
  5978. _THREAD_SAFE_METHOD_
  5979. ERR_FAIL_COND_V_MSG(local_device.is_valid(), INVALID_ID, "Local devices have no screen");
  5980. // Very hacky, but not used often per frame so I guess ok.
  5981. VkFormat vkformat = context->get_screen_format();
  5982. DataFormat format = DATA_FORMAT_MAX;
  5983. for (int i = 0; i < DATA_FORMAT_MAX; i++) {
  5984. if (vkformat == vulkan_formats[i]) {
  5985. format = DataFormat(i);
  5986. break;
  5987. }
  5988. }
  5989. ERR_FAIL_COND_V(format == DATA_FORMAT_MAX, INVALID_ID);
  5990. AttachmentFormat attachment;
  5991. attachment.format = format;
  5992. attachment.samples = TEXTURE_SAMPLES_1;
  5993. attachment.usage_flags = TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  5994. Vector<AttachmentFormat> screen_attachment;
  5995. screen_attachment.push_back(attachment);
  5996. return const_cast<RenderingDeviceVulkan *>(this)->framebuffer_format_create(screen_attachment);
  5997. }
  5998. /*******************/
  5999. /**** DRAW LIST ****/
  6000. /*******************/
  6001. RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_begin_for_screen(DisplayServer::WindowID p_screen, const Color &p_clear_color) {
  6002. _THREAD_SAFE_METHOD_
  6003. ERR_FAIL_COND_V_MSG(local_device.is_valid(), INVALID_ID, "Local devices have no screen");
  6004. ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  6005. ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  6006. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  6007. if (!context->window_is_valid_swapchain(p_screen)) {
  6008. return INVALID_ID;
  6009. }
  6010. Size2i size = Size2i(context->window_get_width(p_screen), context->window_get_height(p_screen));
  6011. _draw_list_allocate(Rect2i(Vector2i(), size), 0, 0);
  6012. #ifdef DEBUG_ENABLED
  6013. draw_list_framebuffer_format = screen_get_framebuffer_format();
  6014. #endif
  6015. draw_list_subpass_count = 1;
  6016. VkRenderPassBeginInfo render_pass_begin;
  6017. render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  6018. render_pass_begin.pNext = nullptr;
  6019. render_pass_begin.renderPass = context->window_get_render_pass(p_screen);
  6020. render_pass_begin.framebuffer = context->window_get_framebuffer(p_screen);
  6021. render_pass_begin.renderArea.extent.width = size.width;
  6022. render_pass_begin.renderArea.extent.height = size.height;
  6023. render_pass_begin.renderArea.offset.x = 0;
  6024. render_pass_begin.renderArea.offset.y = 0;
  6025. render_pass_begin.clearValueCount = 1;
  6026. VkClearValue clear_value;
  6027. clear_value.color.float32[0] = p_clear_color.r;
  6028. clear_value.color.float32[1] = p_clear_color.g;
  6029. clear_value.color.float32[2] = p_clear_color.b;
  6030. clear_value.color.float32[3] = p_clear_color.a;
  6031. render_pass_begin.pClearValues = &clear_value;
  6032. vkCmdBeginRenderPass(command_buffer, &render_pass_begin, VK_SUBPASS_CONTENTS_INLINE);
  6033. uint32_t size_x = screen_get_width(p_screen);
  6034. uint32_t size_y = screen_get_height(p_screen);
  6035. VkViewport viewport;
  6036. viewport.x = 0;
  6037. viewport.y = 0;
  6038. viewport.width = size_x;
  6039. viewport.height = size_y;
  6040. viewport.minDepth = 0;
  6041. viewport.maxDepth = 1.0;
  6042. vkCmdSetViewport(command_buffer, 0, 1, &viewport);
  6043. VkRect2D scissor;
  6044. scissor.offset.x = 0;
  6045. scissor.offset.y = 0;
  6046. scissor.extent.width = size_x;
  6047. scissor.extent.height = size_y;
  6048. vkCmdSetScissor(command_buffer, 0, 1, &scissor);
  6049. return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;
  6050. }
  6051. Error RenderingDeviceVulkan::_draw_list_setup_framebuffer(Framebuffer *p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, VkFramebuffer *r_framebuffer, VkRenderPass *r_render_pass, uint32_t *r_subpass_count) {
  6052. Framebuffer::VersionKey vk;
  6053. vk.initial_color_action = p_initial_color_action;
  6054. vk.final_color_action = p_final_color_action;
  6055. vk.initial_depth_action = p_initial_depth_action;
  6056. vk.final_depth_action = p_final_depth_action;
  6057. vk.view_count = p_framebuffer->view_count;
  6058. if (!p_framebuffer->framebuffers.has(vk)) {
  6059. // Need to create this version.
  6060. Framebuffer::Version version;
  6061. version.render_pass = _render_pass_create(framebuffer_formats[p_framebuffer->format_id].E->key().attachments, framebuffer_formats[p_framebuffer->format_id].E->key().passes, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_framebuffer->view_count);
  6062. VkFramebufferCreateInfo framebuffer_create_info;
  6063. framebuffer_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  6064. framebuffer_create_info.pNext = nullptr;
  6065. framebuffer_create_info.flags = 0;
  6066. framebuffer_create_info.renderPass = version.render_pass;
  6067. Vector<VkImageView> attachments;
  6068. for (int i = 0; i < p_framebuffer->texture_ids.size(); i++) {
  6069. Texture *texture = texture_owner.get_or_null(p_framebuffer->texture_ids[i]);
  6070. if (texture) {
  6071. attachments.push_back(texture->view);
  6072. if (!(texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT)) { // VRS attachment will be a different size.
  6073. ERR_FAIL_COND_V(texture->width != p_framebuffer->size.width, ERR_BUG);
  6074. ERR_FAIL_COND_V(texture->height != p_framebuffer->size.height, ERR_BUG);
  6075. }
  6076. }
  6077. }
  6078. framebuffer_create_info.attachmentCount = attachments.size();
  6079. framebuffer_create_info.pAttachments = attachments.ptr();
  6080. framebuffer_create_info.width = p_framebuffer->size.width;
  6081. framebuffer_create_info.height = p_framebuffer->size.height;
  6082. framebuffer_create_info.layers = 1;
  6083. VkResult err = vkCreateFramebuffer(device, &framebuffer_create_info, nullptr, &version.framebuffer);
  6084. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vkCreateFramebuffer failed with error " + itos(err) + ".");
  6085. version.subpass_count = framebuffer_formats[p_framebuffer->format_id].E->key().passes.size();
  6086. p_framebuffer->framebuffers.insert(vk, version);
  6087. }
  6088. const Framebuffer::Version &version = p_framebuffer->framebuffers[vk];
  6089. *r_framebuffer = version.framebuffer;
  6090. *r_render_pass = version.render_pass;
  6091. *r_subpass_count = version.subpass_count;
  6092. return OK;
  6093. }
  6094. Error RenderingDeviceVulkan::_draw_list_render_pass_begin(Framebuffer *framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_colors, float p_clear_depth, uint32_t p_clear_stencil, Point2i viewport_offset, Point2i viewport_size, VkFramebuffer vkframebuffer, VkRenderPass render_pass, VkCommandBuffer command_buffer, VkSubpassContents subpass_contents, const Vector<RID> &p_storage_textures) {
  6095. VkRenderPassBeginInfo render_pass_begin;
  6096. render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  6097. render_pass_begin.pNext = nullptr;
  6098. render_pass_begin.renderPass = render_pass;
  6099. render_pass_begin.framebuffer = vkframebuffer;
  6100. /*
  6101. * Given how API works, it makes sense to always fully operate on the whole framebuffer.
  6102. * This allows better continue operations for operations like shadowmapping.
  6103. render_pass_begin.renderArea.extent.width = viewport_size.width;
  6104. render_pass_begin.renderArea.extent.height = viewport_size.height;
  6105. render_pass_begin.renderArea.offset.x = viewport_offset.x;
  6106. render_pass_begin.renderArea.offset.y = viewport_offset.y;
  6107. */
  6108. render_pass_begin.renderArea.extent.width = framebuffer->size.width;
  6109. render_pass_begin.renderArea.extent.height = framebuffer->size.height;
  6110. render_pass_begin.renderArea.offset.x = 0;
  6111. render_pass_begin.renderArea.offset.y = 0;
  6112. Vector<VkClearValue> clear_values;
  6113. clear_values.resize(framebuffer->texture_ids.size());
  6114. int clear_values_count = 0;
  6115. {
  6116. int color_index = 0;
  6117. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  6118. VkClearValue clear_value;
  6119. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  6120. if (!texture) {
  6121. color_index++;
  6122. continue;
  6123. }
  6124. if (color_index < p_clear_colors.size() && texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  6125. ERR_FAIL_INDEX_V(color_index, p_clear_colors.size(), ERR_BUG); // A bug.
  6126. Color clear_color = p_clear_colors[color_index];
  6127. clear_value.color.float32[0] = clear_color.r;
  6128. clear_value.color.float32[1] = clear_color.g;
  6129. clear_value.color.float32[2] = clear_color.b;
  6130. clear_value.color.float32[3] = clear_color.a;
  6131. color_index++;
  6132. } else if (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  6133. clear_value.depthStencil.depth = p_clear_depth;
  6134. clear_value.depthStencil.stencil = p_clear_stencil;
  6135. } else {
  6136. clear_value.color.float32[0] = 0;
  6137. clear_value.color.float32[1] = 0;
  6138. clear_value.color.float32[2] = 0;
  6139. clear_value.color.float32[3] = 0;
  6140. }
  6141. clear_values.write[clear_values_count++] = clear_value;
  6142. }
  6143. }
  6144. render_pass_begin.clearValueCount = clear_values_count;
  6145. render_pass_begin.pClearValues = clear_values.ptr();
  6146. for (int i = 0; i < p_storage_textures.size(); i++) {
  6147. Texture *texture = texture_owner.get_or_null(p_storage_textures[i]);
  6148. if (!texture) {
  6149. continue;
  6150. }
  6151. ERR_CONTINUE_MSG(!(texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT), "Supplied storage texture " + itos(i) + " for draw list is not set to be used for storage.");
  6152. if (texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT) {
  6153. // Must change layout to general.
  6154. VkImageMemoryBarrier image_memory_barrier;
  6155. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  6156. image_memory_barrier.pNext = nullptr;
  6157. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6158. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6159. image_memory_barrier.oldLayout = texture->layout;
  6160. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  6161. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6162. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6163. image_memory_barrier.image = texture->image;
  6164. image_memory_barrier.subresourceRange.aspectMask = texture->read_aspect_mask;
  6165. image_memory_barrier.subresourceRange.baseMipLevel = texture->base_mipmap;
  6166. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  6167. image_memory_barrier.subresourceRange.baseArrayLayer = texture->base_layer;
  6168. image_memory_barrier.subresourceRange.layerCount = texture->layers;
  6169. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  6170. texture->layout = VK_IMAGE_LAYOUT_GENERAL;
  6171. draw_list_storage_textures.push_back(p_storage_textures[i]);
  6172. }
  6173. }
  6174. vkCmdBeginRenderPass(command_buffer, &render_pass_begin, subpass_contents);
  6175. // Mark textures as bound.
  6176. draw_list_bound_textures.clear();
  6177. draw_list_unbind_color_textures = p_final_color_action != FINAL_ACTION_CONTINUE;
  6178. draw_list_unbind_depth_textures = p_final_depth_action != FINAL_ACTION_CONTINUE;
  6179. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  6180. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  6181. if (!texture) {
  6182. continue;
  6183. }
  6184. texture->bound = true;
  6185. draw_list_bound_textures.push_back(framebuffer->texture_ids[i]);
  6186. }
  6187. return OK;
  6188. }
  6189. void RenderingDeviceVulkan::_draw_list_insert_clear_region(DrawList *draw_list, Framebuffer *framebuffer, Point2i viewport_offset, Point2i viewport_size, bool p_clear_color, const Vector<Color> &p_clear_colors, bool p_clear_depth, float p_depth, uint32_t p_stencil) {
  6190. Vector<VkClearAttachment> clear_attachments;
  6191. int color_index = 0;
  6192. int texture_index = 0;
  6193. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  6194. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  6195. if (!texture) {
  6196. texture_index++;
  6197. continue;
  6198. }
  6199. VkClearAttachment clear_at = {};
  6200. if (p_clear_color && texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  6201. Color clear_color = p_clear_colors[texture_index++];
  6202. clear_at.clearValue.color.float32[0] = clear_color.r;
  6203. clear_at.clearValue.color.float32[1] = clear_color.g;
  6204. clear_at.clearValue.color.float32[2] = clear_color.b;
  6205. clear_at.clearValue.color.float32[3] = clear_color.a;
  6206. clear_at.colorAttachment = color_index++;
  6207. clear_at.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  6208. } else if (p_clear_depth && texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  6209. clear_at.clearValue.depthStencil.depth = p_depth;
  6210. clear_at.clearValue.depthStencil.stencil = p_stencil;
  6211. clear_at.colorAttachment = 0;
  6212. clear_at.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  6213. if (format_has_stencil(texture->format)) {
  6214. clear_at.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  6215. }
  6216. } else {
  6217. ERR_CONTINUE(true);
  6218. }
  6219. clear_attachments.push_back(clear_at);
  6220. }
  6221. VkClearRect cr;
  6222. cr.baseArrayLayer = 0;
  6223. cr.layerCount = 1;
  6224. cr.rect.offset.x = viewport_offset.x;
  6225. cr.rect.offset.y = viewport_offset.y;
  6226. cr.rect.extent.width = viewport_size.width;
  6227. cr.rect.extent.height = viewport_size.height;
  6228. vkCmdClearAttachments(draw_list->command_buffer, clear_attachments.size(), clear_attachments.ptr(), 1, &cr);
  6229. }
  6230. RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const Vector<RID> &p_storage_textures) {
  6231. _THREAD_SAFE_METHOD_
  6232. ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  6233. ERR_FAIL_COND_V_MSG(compute_list != nullptr && !compute_list->state.allow_draw_overlap, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  6234. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  6235. ERR_FAIL_COND_V(!framebuffer, INVALID_ID);
  6236. Point2i viewport_offset;
  6237. Point2i viewport_size = framebuffer->size;
  6238. bool needs_clear_color = false;
  6239. bool needs_clear_depth = false;
  6240. if (p_region != Rect2() && p_region != Rect2(Vector2(), viewport_size)) { // Check custom region.
  6241. Rect2i viewport(viewport_offset, viewport_size);
  6242. Rect2i regioni = p_region;
  6243. if (!(regioni.position.x >= viewport.position.x) && (regioni.position.y >= viewport.position.y) &&
  6244. ((regioni.position.x + regioni.size.x) <= (viewport.position.x + viewport.size.x)) &&
  6245. ((regioni.position.y + regioni.size.y) <= (viewport.position.y + viewport.size.y))) {
  6246. ERR_FAIL_V_MSG(INVALID_ID, "When supplying a custom region, it must be contained within the framebuffer rectangle");
  6247. }
  6248. viewport_offset = regioni.position;
  6249. viewport_size = regioni.size;
  6250. if (p_initial_color_action == INITIAL_ACTION_CLEAR_REGION_CONTINUE) {
  6251. needs_clear_color = true;
  6252. p_initial_color_action = INITIAL_ACTION_CONTINUE;
  6253. }
  6254. if (p_initial_depth_action == INITIAL_ACTION_CLEAR_REGION_CONTINUE) {
  6255. needs_clear_depth = true;
  6256. p_initial_depth_action = INITIAL_ACTION_CONTINUE;
  6257. }
  6258. if (p_initial_color_action == INITIAL_ACTION_CLEAR_REGION) {
  6259. needs_clear_color = true;
  6260. p_initial_color_action = INITIAL_ACTION_KEEP;
  6261. }
  6262. if (p_initial_depth_action == INITIAL_ACTION_CLEAR_REGION) {
  6263. needs_clear_depth = true;
  6264. p_initial_depth_action = INITIAL_ACTION_KEEP;
  6265. }
  6266. }
  6267. if (p_initial_color_action == INITIAL_ACTION_CLEAR || needs_clear_color) { // Check clear values.
  6268. int color_count = 0;
  6269. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  6270. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  6271. // We only check for our VRS usage bit if this is not the first texture id.
  6272. // If it is the first we're likely populating our VRS texture.
  6273. // Bit dirty but...
  6274. if (!texture || (!(texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) && !(i != 0 && texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT))) {
  6275. if (!texture || !texture->is_resolve_buffer) {
  6276. color_count++;
  6277. }
  6278. }
  6279. }
  6280. ERR_FAIL_COND_V_MSG(p_clear_color_values.size() != color_count, INVALID_ID, "Clear color values supplied (" + itos(p_clear_color_values.size()) + ") differ from the amount required for framebuffer color attachments (" + itos(color_count) + ").");
  6281. }
  6282. VkFramebuffer vkframebuffer;
  6283. VkRenderPass render_pass;
  6284. Error err = _draw_list_setup_framebuffer(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, &vkframebuffer, &render_pass, &draw_list_subpass_count);
  6285. ERR_FAIL_COND_V(err != OK, INVALID_ID);
  6286. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  6287. err = _draw_list_render_pass_begin(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, viewport_offset, viewport_size, vkframebuffer, render_pass, command_buffer, VK_SUBPASS_CONTENTS_INLINE, p_storage_textures);
  6288. if (err != OK) {
  6289. return INVALID_ID;
  6290. }
  6291. draw_list_render_pass = render_pass;
  6292. draw_list_vkframebuffer = vkframebuffer;
  6293. _draw_list_allocate(Rect2i(viewport_offset, viewport_size), 0, 0);
  6294. #ifdef DEBUG_ENABLED
  6295. draw_list_framebuffer_format = framebuffer->format_id;
  6296. #endif
  6297. draw_list_current_subpass = 0;
  6298. if (needs_clear_color || needs_clear_depth) {
  6299. _draw_list_insert_clear_region(draw_list, framebuffer, viewport_offset, viewport_size, needs_clear_color, p_clear_color_values, needs_clear_depth, p_clear_depth, p_clear_stencil);
  6300. }
  6301. VkViewport viewport;
  6302. viewport.x = viewport_offset.x;
  6303. viewport.y = viewport_offset.y;
  6304. viewport.width = viewport_size.width;
  6305. viewport.height = viewport_size.height;
  6306. viewport.minDepth = 0;
  6307. viewport.maxDepth = 1.0;
  6308. vkCmdSetViewport(command_buffer, 0, 1, &viewport);
  6309. VkRect2D scissor;
  6310. scissor.offset.x = viewport_offset.x;
  6311. scissor.offset.y = viewport_offset.y;
  6312. scissor.extent.width = viewport_size.width;
  6313. scissor.extent.height = viewport_size.height;
  6314. vkCmdSetScissor(command_buffer, 0, 1, &scissor);
  6315. return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;
  6316. }
  6317. Error RenderingDeviceVulkan::draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, DrawListID *r_split_ids, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const Vector<RID> &p_storage_textures) {
  6318. _THREAD_SAFE_METHOD_
  6319. ERR_FAIL_COND_V_MSG(draw_list != nullptr, ERR_BUSY, "Only one draw list can be active at the same time.");
  6320. ERR_FAIL_COND_V_MSG(compute_list != nullptr && !compute_list->state.allow_draw_overlap, ERR_BUSY, "Only one draw/compute list can be active at the same time.");
  6321. ERR_FAIL_COND_V(p_splits < 1, ERR_INVALID_DECLARATION);
  6322. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  6323. ERR_FAIL_COND_V(!framebuffer, ERR_INVALID_DECLARATION);
  6324. Point2i viewport_offset;
  6325. Point2i viewport_size = framebuffer->size;
  6326. bool needs_clear_color = false;
  6327. bool needs_clear_depth = false;
  6328. if (p_region != Rect2() && p_region != Rect2(Vector2(), viewport_size)) { // Check custom region.
  6329. Rect2i viewport(viewport_offset, viewport_size);
  6330. Rect2i regioni = p_region;
  6331. if (!(regioni.position.x >= viewport.position.x) && (regioni.position.y >= viewport.position.y) &&
  6332. ((regioni.position.x + regioni.size.x) <= (viewport.position.x + viewport.size.x)) &&
  6333. ((regioni.position.y + regioni.size.y) <= (viewport.position.y + viewport.size.y))) {
  6334. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "When supplying a custom region, it must be contained within the framebuffer rectangle");
  6335. }
  6336. viewport_offset = regioni.position;
  6337. viewport_size = regioni.size;
  6338. if (p_initial_color_action == INITIAL_ACTION_CLEAR_REGION) {
  6339. needs_clear_color = true;
  6340. p_initial_color_action = INITIAL_ACTION_KEEP;
  6341. }
  6342. if (p_initial_depth_action == INITIAL_ACTION_CLEAR_REGION) {
  6343. needs_clear_depth = true;
  6344. p_initial_depth_action = INITIAL_ACTION_KEEP;
  6345. }
  6346. }
  6347. if (p_initial_color_action == INITIAL_ACTION_CLEAR || needs_clear_color) { // Check clear values.
  6348. int color_count = 0;
  6349. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  6350. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  6351. if (!texture || !(texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  6352. color_count++;
  6353. }
  6354. }
  6355. ERR_FAIL_COND_V_MSG(p_clear_color_values.size() != color_count, ERR_INVALID_PARAMETER,
  6356. "Clear color values supplied (" + itos(p_clear_color_values.size()) + ") differ from the amount required for framebuffer (" + itos(color_count) + ").");
  6357. }
  6358. VkFramebuffer vkframebuffer;
  6359. VkRenderPass render_pass;
  6360. Error err = _draw_list_setup_framebuffer(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, &vkframebuffer, &render_pass, &draw_list_subpass_count);
  6361. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  6362. VkCommandBuffer frame_command_buffer = frames[frame].draw_command_buffer;
  6363. err = _draw_list_render_pass_begin(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, viewport_offset, viewport_size, vkframebuffer, render_pass, frame_command_buffer, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS, p_storage_textures);
  6364. if (err != OK) {
  6365. return ERR_CANT_CREATE;
  6366. }
  6367. draw_list_current_subpass = 0;
  6368. #ifdef DEBUG_ENABLED
  6369. draw_list_framebuffer_format = framebuffer->format_id;
  6370. #endif
  6371. draw_list_render_pass = render_pass;
  6372. draw_list_vkframebuffer = vkframebuffer;
  6373. err = _draw_list_allocate(Rect2i(viewport_offset, viewport_size), p_splits, 0);
  6374. if (err != OK) {
  6375. return err;
  6376. }
  6377. if (needs_clear_color || needs_clear_depth) {
  6378. _draw_list_insert_clear_region(&draw_list[0], framebuffer, viewport_offset, viewport_size, needs_clear_color, p_clear_color_values, needs_clear_depth, p_clear_depth, p_clear_stencil);
  6379. }
  6380. for (uint32_t i = 0; i < p_splits; i++) {
  6381. VkViewport viewport;
  6382. viewport.x = viewport_offset.x;
  6383. viewport.y = viewport_offset.y;
  6384. viewport.width = viewport_size.width;
  6385. viewport.height = viewport_size.height;
  6386. viewport.minDepth = 0;
  6387. viewport.maxDepth = 1.0;
  6388. vkCmdSetViewport(draw_list[i].command_buffer, 0, 1, &viewport);
  6389. VkRect2D scissor;
  6390. scissor.offset.x = viewport_offset.x;
  6391. scissor.offset.y = viewport_offset.y;
  6392. scissor.extent.width = viewport_size.width;
  6393. scissor.extent.height = viewport_size.height;
  6394. vkCmdSetScissor(draw_list[i].command_buffer, 0, 1, &scissor);
  6395. r_split_ids[i] = (int64_t(ID_TYPE_SPLIT_DRAW_LIST) << ID_BASE_SHIFT) + i;
  6396. }
  6397. return OK;
  6398. }
  6399. RenderingDeviceVulkan::DrawList *RenderingDeviceVulkan::_get_draw_list_ptr(DrawListID p_id) {
  6400. if (p_id < 0) {
  6401. return nullptr;
  6402. }
  6403. if (!draw_list) {
  6404. return nullptr;
  6405. } else if (p_id == (int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT)) {
  6406. if (draw_list_split) {
  6407. return nullptr;
  6408. }
  6409. return draw_list;
  6410. } else if (p_id >> DrawListID(ID_BASE_SHIFT) == ID_TYPE_SPLIT_DRAW_LIST) {
  6411. if (!draw_list_split) {
  6412. return nullptr;
  6413. }
  6414. uint64_t index = p_id & ((DrawListID(1) << DrawListID(ID_BASE_SHIFT)) - 1); // Mask.
  6415. if (index >= draw_list_count) {
  6416. return nullptr;
  6417. }
  6418. return &draw_list[index];
  6419. } else {
  6420. return nullptr;
  6421. }
  6422. }
  6423. void RenderingDeviceVulkan::draw_list_set_blend_constants(DrawListID p_list, const Color &p_color) {
  6424. DrawList *dl = _get_draw_list_ptr(p_list);
  6425. ERR_FAIL_COND(!dl);
  6426. #ifdef DEBUG_ENABLED
  6427. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6428. #endif
  6429. vkCmdSetBlendConstants(dl->command_buffer, p_color.components);
  6430. }
  6431. void RenderingDeviceVulkan::draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline) {
  6432. DrawList *dl = _get_draw_list_ptr(p_list);
  6433. ERR_FAIL_COND(!dl);
  6434. #ifdef DEBUG_ENABLED
  6435. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6436. #endif
  6437. const RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_render_pipeline);
  6438. ERR_FAIL_COND(!pipeline);
  6439. #ifdef DEBUG_ENABLED
  6440. ERR_FAIL_COND(pipeline->validation.framebuffer_format != draw_list_framebuffer_format && pipeline->validation.render_pass != draw_list_current_subpass);
  6441. #endif
  6442. if (p_render_pipeline == dl->state.pipeline) {
  6443. return; // Redundant state, return.
  6444. }
  6445. dl->state.pipeline = p_render_pipeline;
  6446. dl->state.pipeline_layout = pipeline->pipeline_layout;
  6447. vkCmdBindPipeline(dl->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline);
  6448. if (dl->state.pipeline_shader != pipeline->shader) {
  6449. // Shader changed, so descriptor sets may become incompatible.
  6450. // Go through ALL sets, and unbind them (and all those above) if the format is different.
  6451. uint32_t pcount = pipeline->set_formats.size(); // Formats count in this pipeline.
  6452. dl->state.set_count = MAX(dl->state.set_count, pcount);
  6453. const uint32_t *pformats = pipeline->set_formats.ptr(); // Pipeline set formats.
  6454. bool sets_valid = true; // Once invalid, all above become invalid.
  6455. for (uint32_t i = 0; i < pcount; i++) {
  6456. // If a part of the format is different, invalidate it (and the rest).
  6457. if (!sets_valid || dl->state.sets[i].pipeline_expected_format != pformats[i]) {
  6458. dl->state.sets[i].bound = false;
  6459. dl->state.sets[i].pipeline_expected_format = pformats[i];
  6460. sets_valid = false;
  6461. }
  6462. }
  6463. for (uint32_t i = pcount; i < dl->state.set_count; i++) {
  6464. // Unbind the ones above (not used) if exist.
  6465. dl->state.sets[i].bound = false;
  6466. }
  6467. dl->state.set_count = pcount; // Update set count.
  6468. if (pipeline->push_constant_size) {
  6469. dl->state.pipeline_push_constant_stages = pipeline->push_constant_stages;
  6470. #ifdef DEBUG_ENABLED
  6471. dl->validation.pipeline_push_constant_supplied = false;
  6472. #endif
  6473. }
  6474. dl->state.pipeline_shader = pipeline->shader;
  6475. }
  6476. #ifdef DEBUG_ENABLED
  6477. // Update render pass pipeline info.
  6478. dl->validation.pipeline_active = true;
  6479. dl->validation.pipeline_dynamic_state = pipeline->validation.dynamic_state;
  6480. dl->validation.pipeline_vertex_format = pipeline->validation.vertex_format;
  6481. dl->validation.pipeline_uses_restart_indices = pipeline->validation.uses_restart_indices;
  6482. dl->validation.pipeline_primitive_divisor = pipeline->validation.primitive_divisor;
  6483. dl->validation.pipeline_primitive_minimum = pipeline->validation.primitive_minimum;
  6484. dl->validation.pipeline_push_constant_size = pipeline->push_constant_size;
  6485. #endif
  6486. }
  6487. void RenderingDeviceVulkan::draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index) {
  6488. #ifdef DEBUG_ENABLED
  6489. ERR_FAIL_COND_MSG(p_index >= limits.maxBoundDescriptorSets || p_index >= MAX_UNIFORM_SETS,
  6490. "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(limits.maxBoundDescriptorSets) + ").");
  6491. #endif
  6492. DrawList *dl = _get_draw_list_ptr(p_list);
  6493. ERR_FAIL_COND(!dl);
  6494. #ifdef DEBUG_ENABLED
  6495. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6496. #endif
  6497. const UniformSet *uniform_set = uniform_set_owner.get_or_null(p_uniform_set);
  6498. ERR_FAIL_COND(!uniform_set);
  6499. if (p_index > dl->state.set_count) {
  6500. dl->state.set_count = p_index;
  6501. }
  6502. dl->state.sets[p_index].descriptor_set = uniform_set->descriptor_set; // Update set pointer.
  6503. dl->state.sets[p_index].bound = false; // Needs rebind.
  6504. dl->state.sets[p_index].uniform_set_format = uniform_set->format;
  6505. dl->state.sets[p_index].uniform_set = p_uniform_set;
  6506. uint32_t mst_count = uniform_set->mutable_storage_textures.size();
  6507. if (mst_count) {
  6508. Texture **mst_textures = const_cast<UniformSet *>(uniform_set)->mutable_storage_textures.ptrw();
  6509. for (uint32_t i = 0; i < mst_count; i++) {
  6510. if (mst_textures[i]->used_in_frame != frames_drawn) {
  6511. mst_textures[i]->used_in_frame = frames_drawn;
  6512. mst_textures[i]->used_in_transfer = false;
  6513. mst_textures[i]->used_in_compute = false;
  6514. }
  6515. mst_textures[i]->used_in_raster = true;
  6516. }
  6517. }
  6518. #ifdef DEBUG_ENABLED
  6519. { // Validate that textures bound are not attached as framebuffer bindings.
  6520. uint32_t attachable_count = uniform_set->attachable_textures.size();
  6521. const UniformSet::AttachableTexture *attachable_ptr = uniform_set->attachable_textures.ptr();
  6522. uint32_t bound_count = draw_list_bound_textures.size();
  6523. const RID *bound_ptr = draw_list_bound_textures.ptr();
  6524. for (uint32_t i = 0; i < attachable_count; i++) {
  6525. for (uint32_t j = 0; j < bound_count; j++) {
  6526. ERR_FAIL_COND_MSG(attachable_ptr[i].texture == bound_ptr[j],
  6527. "Attempted to use the same texture in framebuffer attachment and a uniform (set: " + itos(p_index) + ", binding: " + itos(attachable_ptr[i].bind) + "), this is not allowed.");
  6528. }
  6529. }
  6530. }
  6531. #endif
  6532. }
  6533. void RenderingDeviceVulkan::draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array) {
  6534. DrawList *dl = _get_draw_list_ptr(p_list);
  6535. ERR_FAIL_COND(!dl);
  6536. #ifdef DEBUG_ENABLED
  6537. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6538. #endif
  6539. const VertexArray *vertex_array = vertex_array_owner.get_or_null(p_vertex_array);
  6540. ERR_FAIL_COND(!vertex_array);
  6541. if (dl->state.vertex_array == p_vertex_array) {
  6542. return; // Already set.
  6543. }
  6544. dl->state.vertex_array = p_vertex_array;
  6545. #ifdef DEBUG_ENABLED
  6546. dl->validation.vertex_format = vertex_array->description;
  6547. dl->validation.vertex_max_instances_allowed = vertex_array->max_instances_allowed;
  6548. #endif
  6549. dl->validation.vertex_array_size = vertex_array->vertex_count;
  6550. vkCmdBindVertexBuffers(dl->command_buffer, 0, vertex_array->buffers.size(), vertex_array->buffers.ptr(), vertex_array->offsets.ptr());
  6551. }
  6552. void RenderingDeviceVulkan::draw_list_bind_index_array(DrawListID p_list, RID p_index_array) {
  6553. DrawList *dl = _get_draw_list_ptr(p_list);
  6554. ERR_FAIL_COND(!dl);
  6555. #ifdef DEBUG_ENABLED
  6556. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6557. #endif
  6558. const IndexArray *index_array = index_array_owner.get_or_null(p_index_array);
  6559. ERR_FAIL_COND(!index_array);
  6560. if (dl->state.index_array == p_index_array) {
  6561. return; // Already set.
  6562. }
  6563. dl->state.index_array = p_index_array;
  6564. #ifdef DEBUG_ENABLED
  6565. dl->validation.index_array_max_index = index_array->max_index;
  6566. #endif
  6567. dl->validation.index_array_size = index_array->indices;
  6568. dl->validation.index_array_offset = index_array->offset;
  6569. vkCmdBindIndexBuffer(dl->command_buffer, index_array->buffer, index_array->offset, index_array->index_type);
  6570. }
  6571. void RenderingDeviceVulkan::draw_list_set_line_width(DrawListID p_list, float p_width) {
  6572. DrawList *dl = _get_draw_list_ptr(p_list);
  6573. ERR_FAIL_COND(!dl);
  6574. #ifdef DEBUG_ENABLED
  6575. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6576. #endif
  6577. vkCmdSetLineWidth(dl->command_buffer, p_width);
  6578. }
  6579. void RenderingDeviceVulkan::draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size) {
  6580. DrawList *dl = _get_draw_list_ptr(p_list);
  6581. ERR_FAIL_COND(!dl);
  6582. #ifdef DEBUG_ENABLED
  6583. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6584. #endif
  6585. #ifdef DEBUG_ENABLED
  6586. ERR_FAIL_COND_MSG(p_data_size != dl->validation.pipeline_push_constant_size,
  6587. "This render pipeline requires (" + itos(dl->validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")");
  6588. #endif
  6589. vkCmdPushConstants(dl->command_buffer, dl->state.pipeline_layout, dl->state.pipeline_push_constant_stages, 0, p_data_size, p_data);
  6590. #ifdef DEBUG_ENABLED
  6591. dl->validation.pipeline_push_constant_supplied = true;
  6592. #endif
  6593. }
  6594. void RenderingDeviceVulkan::draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances, uint32_t p_procedural_vertices) {
  6595. DrawList *dl = _get_draw_list_ptr(p_list);
  6596. ERR_FAIL_COND(!dl);
  6597. #ifdef DEBUG_ENABLED
  6598. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6599. #endif
  6600. #ifdef DEBUG_ENABLED
  6601. ERR_FAIL_COND_MSG(!dl->validation.pipeline_active,
  6602. "No render pipeline was set before attempting to draw.");
  6603. if (dl->validation.pipeline_vertex_format != INVALID_ID) {
  6604. // Pipeline uses vertices, validate format.
  6605. ERR_FAIL_COND_MSG(dl->validation.vertex_format == INVALID_ID,
  6606. "No vertex array was bound, and render pipeline expects vertices.");
  6607. // Make sure format is right.
  6608. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format != dl->validation.vertex_format,
  6609. "The vertex format used to create the pipeline does not match the vertex format bound.");
  6610. // Make sure number of instances is valid.
  6611. ERR_FAIL_COND_MSG(p_instances > dl->validation.vertex_max_instances_allowed,
  6612. "Number of instances requested (" + itos(p_instances) + " is larger than the maximum number supported by the bound vertex array (" + itos(dl->validation.vertex_max_instances_allowed) + ").");
  6613. }
  6614. if (dl->validation.pipeline_push_constant_size > 0) {
  6615. // Using push constants, check that they were supplied.
  6616. ERR_FAIL_COND_MSG(!dl->validation.pipeline_push_constant_supplied,
  6617. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  6618. }
  6619. #endif
  6620. // Bind descriptor sets.
  6621. for (uint32_t i = 0; i < dl->state.set_count; i++) {
  6622. if (dl->state.sets[i].pipeline_expected_format == 0) {
  6623. continue; // Nothing expected by this pipeline.
  6624. }
  6625. #ifdef DEBUG_ENABLED
  6626. if (dl->state.sets[i].pipeline_expected_format != dl->state.sets[i].uniform_set_format) {
  6627. if (dl->state.sets[i].uniform_set_format == 0) {
  6628. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline");
  6629. } else if (uniform_set_owner.owns(dl->state.sets[i].uniform_set)) {
  6630. UniformSet *us = uniform_set_owner.get_or_null(dl->state.sets[i].uniform_set);
  6631. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + "):\n" + _shader_uniform_debug(us->shader_id, us->shader_set) + "\nare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(dl->state.pipeline_shader));
  6632. } else {
  6633. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(dl->state.pipeline_shader));
  6634. }
  6635. }
  6636. #endif
  6637. if (!dl->state.sets[i].bound) {
  6638. // All good, see if this requires re-binding.
  6639. vkCmdBindDescriptorSets(dl->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, dl->state.pipeline_layout, i, 1, &dl->state.sets[i].descriptor_set, 0, nullptr);
  6640. dl->state.sets[i].bound = true;
  6641. }
  6642. }
  6643. if (p_use_indices) {
  6644. #ifdef DEBUG_ENABLED
  6645. ERR_FAIL_COND_MSG(p_procedural_vertices > 0,
  6646. "Procedural vertices can't be used together with indices.");
  6647. ERR_FAIL_COND_MSG(!dl->validation.index_array_size,
  6648. "Draw command requested indices, but no index buffer was set.");
  6649. ERR_FAIL_COND_MSG(dl->validation.pipeline_uses_restart_indices != dl->validation.index_buffer_uses_restart_indices,
  6650. "The usage of restart indices in index buffer does not match the render primitive in the pipeline.");
  6651. #endif
  6652. uint32_t to_draw = dl->validation.index_array_size;
  6653. #ifdef DEBUG_ENABLED
  6654. ERR_FAIL_COND_MSG(to_draw < dl->validation.pipeline_primitive_minimum,
  6655. "Too few indices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(dl->validation.pipeline_primitive_minimum) + ").");
  6656. ERR_FAIL_COND_MSG((to_draw % dl->validation.pipeline_primitive_divisor) != 0,
  6657. "Index amount (" + itos(to_draw) + ") must be a multiple of the amount of indices required by the render primitive (" + itos(dl->validation.pipeline_primitive_divisor) + ").");
  6658. #endif
  6659. vkCmdDrawIndexed(dl->command_buffer, to_draw, p_instances, dl->validation.index_array_offset, 0, 0);
  6660. } else {
  6661. uint32_t to_draw;
  6662. if (p_procedural_vertices > 0) {
  6663. #ifdef DEBUG_ENABLED
  6664. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format != INVALID_ID,
  6665. "Procedural vertices requested, but pipeline expects a vertex array.");
  6666. #endif
  6667. to_draw = p_procedural_vertices;
  6668. } else {
  6669. #ifdef DEBUG_ENABLED
  6670. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format == INVALID_ID,
  6671. "Draw command lacks indices, but pipeline format does not use vertices.");
  6672. #endif
  6673. to_draw = dl->validation.vertex_array_size;
  6674. }
  6675. #ifdef DEBUG_ENABLED
  6676. ERR_FAIL_COND_MSG(to_draw < dl->validation.pipeline_primitive_minimum,
  6677. "Too few vertices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(dl->validation.pipeline_primitive_minimum) + ").");
  6678. ERR_FAIL_COND_MSG((to_draw % dl->validation.pipeline_primitive_divisor) != 0,
  6679. "Vertex amount (" + itos(to_draw) + ") must be a multiple of the amount of vertices required by the render primitive (" + itos(dl->validation.pipeline_primitive_divisor) + ").");
  6680. #endif
  6681. vkCmdDraw(dl->command_buffer, to_draw, p_instances, 0, 0);
  6682. }
  6683. }
  6684. void RenderingDeviceVulkan::draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect) {
  6685. DrawList *dl = _get_draw_list_ptr(p_list);
  6686. ERR_FAIL_COND(!dl);
  6687. #ifdef DEBUG_ENABLED
  6688. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6689. #endif
  6690. Rect2i rect = p_rect;
  6691. rect.position += dl->viewport.position;
  6692. rect = dl->viewport.intersection(rect);
  6693. if (rect.get_area() == 0) {
  6694. return;
  6695. }
  6696. VkRect2D scissor;
  6697. scissor.offset.x = rect.position.x;
  6698. scissor.offset.y = rect.position.y;
  6699. scissor.extent.width = rect.size.width;
  6700. scissor.extent.height = rect.size.height;
  6701. vkCmdSetScissor(dl->command_buffer, 0, 1, &scissor);
  6702. }
  6703. void RenderingDeviceVulkan::draw_list_disable_scissor(DrawListID p_list) {
  6704. DrawList *dl = _get_draw_list_ptr(p_list);
  6705. ERR_FAIL_COND(!dl);
  6706. #ifdef DEBUG_ENABLED
  6707. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6708. #endif
  6709. VkRect2D scissor;
  6710. scissor.offset.x = dl->viewport.position.x;
  6711. scissor.offset.y = dl->viewport.position.y;
  6712. scissor.extent.width = dl->viewport.size.width;
  6713. scissor.extent.height = dl->viewport.size.height;
  6714. vkCmdSetScissor(dl->command_buffer, 0, 1, &scissor);
  6715. }
  6716. uint32_t RenderingDeviceVulkan::draw_list_get_current_pass() {
  6717. return draw_list_current_subpass;
  6718. }
  6719. RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_switch_to_next_pass() {
  6720. ERR_FAIL_COND_V(draw_list == nullptr, INVALID_ID);
  6721. ERR_FAIL_COND_V(draw_list_current_subpass >= draw_list_subpass_count - 1, INVALID_FORMAT_ID);
  6722. draw_list_current_subpass++;
  6723. Rect2i viewport;
  6724. _draw_list_free(&viewport);
  6725. vkCmdNextSubpass(frames[frame].draw_command_buffer, VK_SUBPASS_CONTENTS_INLINE);
  6726. _draw_list_allocate(viewport, 0, draw_list_current_subpass);
  6727. return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;
  6728. }
  6729. Error RenderingDeviceVulkan::draw_list_switch_to_next_pass_split(uint32_t p_splits, DrawListID *r_split_ids) {
  6730. ERR_FAIL_COND_V(draw_list == nullptr, ERR_INVALID_PARAMETER);
  6731. ERR_FAIL_COND_V(draw_list_current_subpass >= draw_list_subpass_count - 1, ERR_INVALID_PARAMETER);
  6732. draw_list_current_subpass++;
  6733. Rect2i viewport;
  6734. _draw_list_free(&viewport);
  6735. vkCmdNextSubpass(frames[frame].draw_command_buffer, VK_SUBPASS_CONTENTS_INLINE);
  6736. _draw_list_allocate(viewport, p_splits, draw_list_current_subpass);
  6737. for (uint32_t i = 0; i < p_splits; i++) {
  6738. r_split_ids[i] = (int64_t(ID_TYPE_SPLIT_DRAW_LIST) << ID_BASE_SHIFT) + i;
  6739. }
  6740. return OK;
  6741. }
  6742. Error RenderingDeviceVulkan::_draw_list_allocate(const Rect2i &p_viewport, uint32_t p_splits, uint32_t p_subpass) {
  6743. // Lock while draw_list is active.
  6744. _THREAD_SAFE_LOCK_
  6745. if (p_splits == 0) {
  6746. draw_list = memnew(DrawList);
  6747. draw_list->command_buffer = frames[frame].draw_command_buffer;
  6748. draw_list->viewport = p_viewport;
  6749. draw_list_count = 0;
  6750. draw_list_split = false;
  6751. } else {
  6752. if (p_splits > (uint32_t)split_draw_list_allocators.size()) {
  6753. uint32_t from = split_draw_list_allocators.size();
  6754. split_draw_list_allocators.resize(p_splits);
  6755. for (uint32_t i = from; i < p_splits; i++) {
  6756. VkCommandPoolCreateInfo cmd_pool_info;
  6757. cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  6758. cmd_pool_info.pNext = nullptr;
  6759. cmd_pool_info.queueFamilyIndex = context->get_graphics_queue_family_index();
  6760. cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  6761. VkResult res = vkCreateCommandPool(device, &cmd_pool_info, nullptr, &split_draw_list_allocators.write[i].command_pool);
  6762. ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "vkCreateCommandPool failed with error " + itos(res) + ".");
  6763. for (int j = 0; j < frame_count; j++) {
  6764. VkCommandBuffer command_buffer;
  6765. VkCommandBufferAllocateInfo cmdbuf;
  6766. // No command buffer exists, create it.
  6767. cmdbuf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  6768. cmdbuf.pNext = nullptr;
  6769. cmdbuf.commandPool = split_draw_list_allocators[i].command_pool;
  6770. cmdbuf.level = VK_COMMAND_BUFFER_LEVEL_SECONDARY;
  6771. cmdbuf.commandBufferCount = 1;
  6772. VkResult err = vkAllocateCommandBuffers(device, &cmdbuf, &command_buffer);
  6773. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vkAllocateCommandBuffers failed with error " + itos(err) + ".");
  6774. split_draw_list_allocators.write[i].command_buffers.push_back(command_buffer);
  6775. }
  6776. }
  6777. }
  6778. draw_list = memnew_arr(DrawList, p_splits);
  6779. draw_list_count = p_splits;
  6780. draw_list_split = true;
  6781. for (uint32_t i = 0; i < p_splits; i++) {
  6782. // Take a command buffer and initialize it.
  6783. VkCommandBuffer command_buffer = split_draw_list_allocators[i].command_buffers[frame];
  6784. VkCommandBufferInheritanceInfo inheritance_info;
  6785. inheritance_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO;
  6786. inheritance_info.pNext = nullptr;
  6787. inheritance_info.renderPass = draw_list_render_pass;
  6788. inheritance_info.subpass = p_subpass;
  6789. inheritance_info.framebuffer = draw_list_vkframebuffer;
  6790. inheritance_info.occlusionQueryEnable = false;
  6791. inheritance_info.queryFlags = 0; // ?
  6792. inheritance_info.pipelineStatistics = 0;
  6793. VkCommandBufferBeginInfo cmdbuf_begin;
  6794. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  6795. cmdbuf_begin.pNext = nullptr;
  6796. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT;
  6797. cmdbuf_begin.pInheritanceInfo = &inheritance_info;
  6798. VkResult res = vkResetCommandBuffer(command_buffer, 0);
  6799. if (res) {
  6800. memdelete_arr(draw_list);
  6801. draw_list = nullptr;
  6802. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "vkResetCommandBuffer failed with error " + itos(res) + ".");
  6803. }
  6804. res = vkBeginCommandBuffer(command_buffer, &cmdbuf_begin);
  6805. if (res) {
  6806. memdelete_arr(draw_list);
  6807. draw_list = nullptr;
  6808. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "vkBeginCommandBuffer failed with error " + itos(res) + ".");
  6809. }
  6810. draw_list[i].command_buffer = command_buffer;
  6811. draw_list[i].viewport = p_viewport;
  6812. }
  6813. }
  6814. return OK;
  6815. }
  6816. void RenderingDeviceVulkan::_draw_list_free(Rect2i *r_last_viewport) {
  6817. if (draw_list_split) {
  6818. // Send all command buffers.
  6819. VkCommandBuffer *command_buffers = (VkCommandBuffer *)alloca(sizeof(VkCommandBuffer) * draw_list_count);
  6820. for (uint32_t i = 0; i < draw_list_count; i++) {
  6821. vkEndCommandBuffer(draw_list[i].command_buffer);
  6822. command_buffers[i] = draw_list[i].command_buffer;
  6823. if (r_last_viewport) {
  6824. if (i == 0 || draw_list[i].viewport_set) {
  6825. *r_last_viewport = draw_list[i].viewport;
  6826. }
  6827. }
  6828. }
  6829. vkCmdExecuteCommands(frames[frame].draw_command_buffer, draw_list_count, command_buffers);
  6830. memdelete_arr(draw_list);
  6831. draw_list = nullptr;
  6832. } else {
  6833. if (r_last_viewport) {
  6834. *r_last_viewport = draw_list->viewport;
  6835. }
  6836. // Just end the list.
  6837. memdelete(draw_list);
  6838. draw_list = nullptr;
  6839. }
  6840. // Draw_list is no longer active.
  6841. _THREAD_SAFE_UNLOCK_
  6842. }
  6843. void RenderingDeviceVulkan::draw_list_end(uint32_t p_post_barrier) {
  6844. _THREAD_SAFE_METHOD_
  6845. ERR_FAIL_COND_MSG(!draw_list, "Immediate draw list is already inactive.");
  6846. _draw_list_free();
  6847. vkCmdEndRenderPass(frames[frame].draw_command_buffer);
  6848. for (int i = 0; i < draw_list_bound_textures.size(); i++) {
  6849. Texture *texture = texture_owner.get_or_null(draw_list_bound_textures[i]);
  6850. ERR_CONTINUE(!texture); // Wtf.
  6851. if (draw_list_unbind_color_textures && (texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) {
  6852. texture->bound = false;
  6853. }
  6854. if (draw_list_unbind_depth_textures && (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  6855. texture->bound = false;
  6856. }
  6857. }
  6858. uint32_t barrier_flags = 0;
  6859. uint32_t access_flags = 0;
  6860. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  6861. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  6862. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6863. }
  6864. if (p_post_barrier & BARRIER_MASK_RASTER) {
  6865. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT /*| VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT*/;
  6866. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT /*| VK_ACCESS_INDIRECT_COMMAND_READ_BIT*/;
  6867. }
  6868. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  6869. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  6870. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  6871. }
  6872. if (barrier_flags == 0) {
  6873. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  6874. }
  6875. draw_list_bound_textures.clear();
  6876. VkImageMemoryBarrier *image_barriers = nullptr;
  6877. uint32_t image_barrier_count = draw_list_storage_textures.size();
  6878. if (image_barrier_count) {
  6879. image_barriers = (VkImageMemoryBarrier *)alloca(sizeof(VkImageMemoryBarrier) * draw_list_storage_textures.size());
  6880. }
  6881. uint32_t src_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  6882. uint32_t src_access = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  6883. if (image_barrier_count) {
  6884. src_stage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  6885. src_access |= VK_ACCESS_SHADER_WRITE_BIT;
  6886. }
  6887. for (uint32_t i = 0; i < image_barrier_count; i++) {
  6888. Texture *texture = texture_owner.get_or_null(draw_list_storage_textures[i]);
  6889. VkImageMemoryBarrier &image_memory_barrier = image_barriers[i];
  6890. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  6891. image_memory_barrier.pNext = nullptr;
  6892. image_memory_barrier.srcAccessMask = src_access;
  6893. image_memory_barrier.dstAccessMask = access_flags;
  6894. image_memory_barrier.oldLayout = texture->layout;
  6895. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  6896. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6897. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6898. image_memory_barrier.image = texture->image;
  6899. image_memory_barrier.subresourceRange.aspectMask = texture->read_aspect_mask;
  6900. image_memory_barrier.subresourceRange.baseMipLevel = texture->base_mipmap;
  6901. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  6902. image_memory_barrier.subresourceRange.baseArrayLayer = texture->base_layer;
  6903. image_memory_barrier.subresourceRange.layerCount = texture->layers;
  6904. texture->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  6905. }
  6906. draw_list_storage_textures.clear();
  6907. // To ensure proper synchronization, we must make sure rendering is done before:
  6908. // * Some buffer is copied.
  6909. // * Another render pass happens (since we may be done).
  6910. VkMemoryBarrier mem_barrier;
  6911. mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  6912. mem_barrier.pNext = nullptr;
  6913. mem_barrier.srcAccessMask = src_access;
  6914. mem_barrier.dstAccessMask = access_flags;
  6915. if (image_barrier_count > 0 || p_post_barrier != BARRIER_MASK_NO_BARRIER) {
  6916. vkCmdPipelineBarrier(frames[frame].draw_command_buffer, src_stage, barrier_flags, 0, 1, &mem_barrier, 0, nullptr, image_barrier_count, image_barriers);
  6917. }
  6918. #ifdef FORCE_FULL_BARRIER
  6919. _full_barrier(true);
  6920. #endif
  6921. }
  6922. /***********************/
  6923. /**** COMPUTE LISTS ****/
  6924. /***********************/
  6925. RenderingDevice::ComputeListID RenderingDeviceVulkan::compute_list_begin(bool p_allow_draw_overlap) {
  6926. ERR_FAIL_COND_V_MSG(!p_allow_draw_overlap && draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  6927. ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  6928. // Lock while compute_list is active.
  6929. _THREAD_SAFE_LOCK_
  6930. compute_list = memnew(ComputeList);
  6931. compute_list->command_buffer = frames[frame].draw_command_buffer;
  6932. compute_list->state.allow_draw_overlap = p_allow_draw_overlap;
  6933. return ID_TYPE_COMPUTE_LIST;
  6934. }
  6935. void RenderingDeviceVulkan::compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline) {
  6936. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6937. ERR_FAIL_COND(!compute_list);
  6938. ComputeList *cl = compute_list;
  6939. const ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_compute_pipeline);
  6940. ERR_FAIL_COND(!pipeline);
  6941. if (p_compute_pipeline == cl->state.pipeline) {
  6942. return; // Redundant state, return.
  6943. }
  6944. cl->state.pipeline = p_compute_pipeline;
  6945. cl->state.pipeline_layout = pipeline->pipeline_layout;
  6946. vkCmdBindPipeline(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline->pipeline);
  6947. if (cl->state.pipeline_shader != pipeline->shader) {
  6948. // Shader changed, so descriptor sets may become incompatible.
  6949. // Go through ALL sets, and unbind them (and all those above) if the format is different.
  6950. uint32_t pcount = pipeline->set_formats.size(); // Formats count in this pipeline.
  6951. cl->state.set_count = MAX(cl->state.set_count, pcount);
  6952. const uint32_t *pformats = pipeline->set_formats.ptr(); // Pipeline set formats.
  6953. bool sets_valid = true; // Once invalid, all above become invalid.
  6954. for (uint32_t i = 0; i < pcount; i++) {
  6955. // If a part of the format is different, invalidate it (and the rest).
  6956. if (!sets_valid || cl->state.sets[i].pipeline_expected_format != pformats[i]) {
  6957. cl->state.sets[i].bound = false;
  6958. cl->state.sets[i].pipeline_expected_format = pformats[i];
  6959. sets_valid = false;
  6960. }
  6961. }
  6962. for (uint32_t i = pcount; i < cl->state.set_count; i++) {
  6963. // Unbind the ones above (not used) if exist.
  6964. cl->state.sets[i].bound = false;
  6965. }
  6966. cl->state.set_count = pcount; // Update set count.
  6967. if (pipeline->push_constant_size) {
  6968. cl->state.pipeline_push_constant_stages = pipeline->push_constant_stages;
  6969. #ifdef DEBUG_ENABLED
  6970. cl->validation.pipeline_push_constant_supplied = false;
  6971. #endif
  6972. }
  6973. cl->state.pipeline_shader = pipeline->shader;
  6974. cl->state.local_group_size[0] = pipeline->local_group_size[0];
  6975. cl->state.local_group_size[1] = pipeline->local_group_size[1];
  6976. cl->state.local_group_size[2] = pipeline->local_group_size[2];
  6977. }
  6978. #ifdef DEBUG_ENABLED
  6979. // Update compute pass pipeline info.
  6980. cl->validation.pipeline_active = true;
  6981. cl->validation.pipeline_push_constant_size = pipeline->push_constant_size;
  6982. #endif
  6983. }
  6984. void RenderingDeviceVulkan::compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index) {
  6985. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6986. ERR_FAIL_COND(!compute_list);
  6987. ComputeList *cl = compute_list;
  6988. #ifdef DEBUG_ENABLED
  6989. ERR_FAIL_COND_MSG(p_index >= limits.maxBoundDescriptorSets || p_index >= MAX_UNIFORM_SETS,
  6990. "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(limits.maxBoundDescriptorSets) + ").");
  6991. #endif
  6992. #ifdef DEBUG_ENABLED
  6993. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  6994. #endif
  6995. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_uniform_set);
  6996. ERR_FAIL_COND(!uniform_set);
  6997. if (p_index > cl->state.set_count) {
  6998. cl->state.set_count = p_index;
  6999. }
  7000. cl->state.sets[p_index].descriptor_set = uniform_set->descriptor_set; // Update set pointer.
  7001. cl->state.sets[p_index].bound = false; // Needs rebind.
  7002. cl->state.sets[p_index].uniform_set_format = uniform_set->format;
  7003. cl->state.sets[p_index].uniform_set = p_uniform_set;
  7004. uint32_t textures_to_sampled_count = uniform_set->mutable_sampled_textures.size();
  7005. uint32_t textures_to_storage_count = uniform_set->mutable_storage_textures.size();
  7006. Texture **textures_to_sampled = uniform_set->mutable_sampled_textures.ptrw();
  7007. VkImageMemoryBarrier *texture_barriers = nullptr;
  7008. if (textures_to_sampled_count + textures_to_storage_count) {
  7009. texture_barriers = (VkImageMemoryBarrier *)alloca(sizeof(VkImageMemoryBarrier) * (textures_to_sampled_count + textures_to_storage_count));
  7010. }
  7011. uint32_t texture_barrier_count = 0;
  7012. uint32_t src_stage_flags = 0;
  7013. for (uint32_t i = 0; i < textures_to_sampled_count; i++) {
  7014. if (textures_to_sampled[i]->layout != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
  7015. src_stage_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  7016. VkImageMemoryBarrier &image_memory_barrier = texture_barriers[texture_barrier_count++];
  7017. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  7018. image_memory_barrier.pNext = nullptr;
  7019. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7020. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7021. image_memory_barrier.oldLayout = textures_to_sampled[i]->layout;
  7022. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  7023. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  7024. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  7025. image_memory_barrier.image = textures_to_sampled[i]->image;
  7026. image_memory_barrier.subresourceRange.aspectMask = textures_to_sampled[i]->read_aspect_mask;
  7027. image_memory_barrier.subresourceRange.baseMipLevel = textures_to_sampled[i]->base_mipmap;
  7028. image_memory_barrier.subresourceRange.levelCount = textures_to_sampled[i]->mipmaps;
  7029. image_memory_barrier.subresourceRange.baseArrayLayer = textures_to_sampled[i]->base_layer;
  7030. image_memory_barrier.subresourceRange.layerCount = textures_to_sampled[i]->layers;
  7031. textures_to_sampled[i]->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  7032. cl->state.textures_to_sampled_layout.erase(textures_to_sampled[i]);
  7033. }
  7034. if (textures_to_sampled[i]->used_in_frame != frames_drawn) {
  7035. textures_to_sampled[i]->used_in_frame = frames_drawn;
  7036. textures_to_sampled[i]->used_in_transfer = false;
  7037. textures_to_sampled[i]->used_in_raster = false;
  7038. }
  7039. textures_to_sampled[i]->used_in_compute = true;
  7040. }
  7041. Texture **textures_to_storage = uniform_set->mutable_storage_textures.ptrw();
  7042. for (uint32_t i = 0; i < textures_to_storage_count; i++) {
  7043. if (textures_to_storage[i]->layout != VK_IMAGE_LAYOUT_GENERAL) {
  7044. uint32_t src_access_flags = 0;
  7045. if (textures_to_storage[i]->used_in_frame == frames_drawn) {
  7046. if (textures_to_storage[i]->used_in_compute) {
  7047. src_stage_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  7048. src_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7049. }
  7050. if (textures_to_storage[i]->used_in_raster) {
  7051. src_stage_flags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT;
  7052. src_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7053. }
  7054. if (textures_to_storage[i]->used_in_transfer) {
  7055. src_stage_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  7056. src_access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  7057. }
  7058. textures_to_storage[i]->used_in_compute = false;
  7059. textures_to_storage[i]->used_in_raster = false;
  7060. textures_to_storage[i]->used_in_transfer = false;
  7061. } else {
  7062. src_access_flags = 0;
  7063. textures_to_storage[i]->used_in_compute = false;
  7064. textures_to_storage[i]->used_in_raster = false;
  7065. textures_to_storage[i]->used_in_transfer = false;
  7066. textures_to_storage[i]->used_in_frame = frames_drawn;
  7067. }
  7068. VkImageMemoryBarrier &image_memory_barrier = texture_barriers[texture_barrier_count++];
  7069. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  7070. image_memory_barrier.pNext = nullptr;
  7071. image_memory_barrier.srcAccessMask = src_access_flags;
  7072. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7073. image_memory_barrier.oldLayout = textures_to_storage[i]->layout;
  7074. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  7075. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  7076. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  7077. image_memory_barrier.image = textures_to_storage[i]->image;
  7078. image_memory_barrier.subresourceRange.aspectMask = textures_to_storage[i]->read_aspect_mask;
  7079. image_memory_barrier.subresourceRange.baseMipLevel = textures_to_storage[i]->base_mipmap;
  7080. image_memory_barrier.subresourceRange.levelCount = textures_to_storage[i]->mipmaps;
  7081. image_memory_barrier.subresourceRange.baseArrayLayer = textures_to_storage[i]->base_layer;
  7082. image_memory_barrier.subresourceRange.layerCount = textures_to_storage[i]->layers;
  7083. textures_to_storage[i]->layout = VK_IMAGE_LAYOUT_GENERAL;
  7084. cl->state.textures_to_sampled_layout.insert(textures_to_storage[i]); // Needs to go back to sampled layout afterwards.
  7085. }
  7086. }
  7087. if (texture_barrier_count) {
  7088. if (src_stage_flags == 0) {
  7089. src_stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  7090. }
  7091. vkCmdPipelineBarrier(cl->command_buffer, src_stage_flags, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, texture_barrier_count, texture_barriers);
  7092. }
  7093. #if 0
  7094. { // Validate that textures bound are not attached as framebuffer bindings.
  7095. uint32_t attachable_count = uniform_set->attachable_textures.size();
  7096. const RID *attachable_ptr = uniform_set->attachable_textures.ptr();
  7097. uint32_t bound_count = draw_list_bound_textures.size();
  7098. const RID *bound_ptr = draw_list_bound_textures.ptr();
  7099. for (uint32_t i = 0; i < attachable_count; i++) {
  7100. for (uint32_t j = 0; j < bound_count; j++) {
  7101. ERR_FAIL_COND_MSG(attachable_ptr[i] == bound_ptr[j],
  7102. "Attempted to use the same texture in framebuffer attachment and a uniform set, this is not allowed.");
  7103. }
  7104. }
  7105. }
  7106. #endif
  7107. }
  7108. void RenderingDeviceVulkan::compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size) {
  7109. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  7110. ERR_FAIL_COND(!compute_list);
  7111. ComputeList *cl = compute_list;
  7112. #ifdef DEBUG_ENABLED
  7113. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  7114. #endif
  7115. #ifdef DEBUG_ENABLED
  7116. ERR_FAIL_COND_MSG(p_data_size != cl->validation.pipeline_push_constant_size,
  7117. "This compute pipeline requires (" + itos(cl->validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")");
  7118. #endif
  7119. vkCmdPushConstants(cl->command_buffer, cl->state.pipeline_layout, cl->state.pipeline_push_constant_stages, 0, p_data_size, p_data);
  7120. #ifdef DEBUG_ENABLED
  7121. cl->validation.pipeline_push_constant_supplied = true;
  7122. #endif
  7123. }
  7124. void RenderingDeviceVulkan::compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) {
  7125. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  7126. ERR_FAIL_COND(!compute_list);
  7127. ComputeList *cl = compute_list;
  7128. #ifdef DEBUG_ENABLED
  7129. ERR_FAIL_COND_MSG(p_x_groups == 0, "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is zero.");
  7130. ERR_FAIL_COND_MSG(p_z_groups == 0, "Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is zero.");
  7131. ERR_FAIL_COND_MSG(p_y_groups == 0, "Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is zero.");
  7132. ERR_FAIL_COND_MSG(p_x_groups > limits.maxComputeWorkGroupCount[0],
  7133. "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[0]) + ")");
  7134. ERR_FAIL_COND_MSG(p_y_groups > limits.maxComputeWorkGroupCount[1],
  7135. "Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[1]) + ")");
  7136. ERR_FAIL_COND_MSG(p_z_groups > limits.maxComputeWorkGroupCount[2],
  7137. "Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[2]) + ")");
  7138. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  7139. #endif
  7140. #ifdef DEBUG_ENABLED
  7141. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  7142. if (cl->validation.pipeline_push_constant_size > 0) {
  7143. // Using push constants, check that they were supplied.
  7144. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  7145. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  7146. }
  7147. #endif
  7148. // Bind descriptor sets.
  7149. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  7150. if (cl->state.sets[i].pipeline_expected_format == 0) {
  7151. continue; // Nothing expected by this pipeline.
  7152. }
  7153. #ifdef DEBUG_ENABLED
  7154. if (cl->state.sets[i].pipeline_expected_format != cl->state.sets[i].uniform_set_format) {
  7155. if (cl->state.sets[i].uniform_set_format == 0) {
  7156. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline");
  7157. } else if (uniform_set_owner.owns(cl->state.sets[i].uniform_set)) {
  7158. UniformSet *us = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set);
  7159. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + "):\n" + _shader_uniform_debug(us->shader_id, us->shader_set) + "\nare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader));
  7160. } else {
  7161. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader));
  7162. }
  7163. }
  7164. #endif
  7165. if (!cl->state.sets[i].bound) {
  7166. // All good, see if this requires re-binding.
  7167. vkCmdBindDescriptorSets(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, cl->state.pipeline_layout, i, 1, &cl->state.sets[i].descriptor_set, 0, nullptr);
  7168. cl->state.sets[i].bound = true;
  7169. }
  7170. }
  7171. vkCmdDispatch(cl->command_buffer, p_x_groups, p_y_groups, p_z_groups);
  7172. }
  7173. void RenderingDeviceVulkan::compute_list_dispatch_threads(ComputeListID p_list, uint32_t p_x_threads, uint32_t p_y_threads, uint32_t p_z_threads) {
  7174. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  7175. ERR_FAIL_COND(!compute_list);
  7176. #ifdef DEBUG_ENABLED
  7177. ERR_FAIL_COND_MSG(p_x_threads == 0, "Dispatch amount of X compute threads (" + itos(p_x_threads) + ") is zero.");
  7178. ERR_FAIL_COND_MSG(p_y_threads == 0, "Dispatch amount of Y compute threads (" + itos(p_y_threads) + ") is zero.");
  7179. ERR_FAIL_COND_MSG(p_z_threads == 0, "Dispatch amount of Z compute threads (" + itos(p_z_threads) + ") is zero.");
  7180. #endif
  7181. ComputeList *cl = compute_list;
  7182. #ifdef DEBUG_ENABLED
  7183. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  7184. if (cl->validation.pipeline_push_constant_size > 0) {
  7185. // Using push constants, check that they were supplied.
  7186. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  7187. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  7188. }
  7189. #endif
  7190. compute_list_dispatch(p_list, (p_x_threads - 1) / cl->state.local_group_size[0] + 1, (p_y_threads - 1) / cl->state.local_group_size[1] + 1, (p_z_threads - 1) / cl->state.local_group_size[2] + 1);
  7191. }
  7192. void RenderingDeviceVulkan::compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset) {
  7193. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  7194. ERR_FAIL_COND(!compute_list);
  7195. ComputeList *cl = compute_list;
  7196. Buffer *buffer = storage_buffer_owner.get_or_null(p_buffer);
  7197. ERR_FAIL_COND(!buffer);
  7198. ERR_FAIL_COND_MSG(!(buffer->usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT), "Buffer provided was not created to do indirect dispatch.");
  7199. ERR_FAIL_COND_MSG(p_offset + 12 > buffer->size, "Offset provided (+12) is past the end of buffer.");
  7200. #ifdef DEBUG_ENABLED
  7201. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  7202. #endif
  7203. #ifdef DEBUG_ENABLED
  7204. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  7205. if (cl->validation.pipeline_push_constant_size > 0) {
  7206. // Using push constants, check that they were supplied.
  7207. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  7208. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  7209. }
  7210. #endif
  7211. // Bind descriptor sets.
  7212. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  7213. if (cl->state.sets[i].pipeline_expected_format == 0) {
  7214. continue; // Nothing expected by this pipeline.
  7215. }
  7216. #ifdef DEBUG_ENABLED
  7217. if (cl->state.sets[i].pipeline_expected_format != cl->state.sets[i].uniform_set_format) {
  7218. if (cl->state.sets[i].uniform_set_format == 0) {
  7219. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline");
  7220. } else if (uniform_set_owner.owns(cl->state.sets[i].uniform_set)) {
  7221. UniformSet *us = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set);
  7222. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + "):\n" + _shader_uniform_debug(us->shader_id, us->shader_set) + "\nare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader));
  7223. } else {
  7224. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader));
  7225. }
  7226. }
  7227. #endif
  7228. if (!cl->state.sets[i].bound) {
  7229. // All good, see if this requires re-binding.
  7230. vkCmdBindDescriptorSets(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, cl->state.pipeline_layout, i, 1, &cl->state.sets[i].descriptor_set, 0, nullptr);
  7231. cl->state.sets[i].bound = true;
  7232. }
  7233. }
  7234. vkCmdDispatchIndirect(cl->command_buffer, buffer->buffer, p_offset);
  7235. }
  7236. void RenderingDeviceVulkan::compute_list_add_barrier(ComputeListID p_list) {
  7237. #ifdef FORCE_FULL_BARRIER
  7238. _full_barrier(true);
  7239. #else
  7240. _memory_barrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, true);
  7241. #endif
  7242. }
  7243. void RenderingDeviceVulkan::compute_list_end(uint32_t p_post_barrier) {
  7244. ERR_FAIL_COND(!compute_list);
  7245. uint32_t barrier_flags = 0;
  7246. uint32_t access_flags = 0;
  7247. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  7248. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  7249. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7250. }
  7251. if (p_post_barrier & BARRIER_MASK_RASTER) {
  7252. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
  7253. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
  7254. }
  7255. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  7256. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  7257. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  7258. }
  7259. if (barrier_flags == 0) {
  7260. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  7261. }
  7262. VkImageMemoryBarrier *image_barriers = nullptr;
  7263. uint32_t image_barrier_count = compute_list->state.textures_to_sampled_layout.size();
  7264. if (image_barrier_count) {
  7265. image_barriers = (VkImageMemoryBarrier *)alloca(sizeof(VkImageMemoryBarrier) * image_barrier_count);
  7266. }
  7267. uint32_t barrier_idx = 0;
  7268. for (Texture *E : compute_list->state.textures_to_sampled_layout) {
  7269. VkImageMemoryBarrier &image_memory_barrier = image_barriers[barrier_idx++];
  7270. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  7271. image_memory_barrier.pNext = nullptr;
  7272. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7273. image_memory_barrier.dstAccessMask = access_flags;
  7274. image_memory_barrier.oldLayout = E->layout;
  7275. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  7276. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  7277. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  7278. image_memory_barrier.image = E->image;
  7279. image_memory_barrier.subresourceRange.aspectMask = E->read_aspect_mask;
  7280. image_memory_barrier.subresourceRange.baseMipLevel = E->base_mipmap;
  7281. image_memory_barrier.subresourceRange.levelCount = E->mipmaps;
  7282. image_memory_barrier.subresourceRange.baseArrayLayer = E->base_layer;
  7283. image_memory_barrier.subresourceRange.layerCount = E->layers;
  7284. E->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  7285. if (E->used_in_frame != frames_drawn) {
  7286. E->used_in_transfer = false;
  7287. E->used_in_raster = false;
  7288. E->used_in_compute = false;
  7289. E->used_in_frame = frames_drawn;
  7290. }
  7291. }
  7292. VkMemoryBarrier mem_barrier;
  7293. mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  7294. mem_barrier.pNext = nullptr;
  7295. mem_barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
  7296. mem_barrier.dstAccessMask = access_flags;
  7297. if (image_barrier_count > 0 || p_post_barrier != BARRIER_MASK_NO_BARRIER) {
  7298. vkCmdPipelineBarrier(compute_list->command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, barrier_flags, 0, 1, &mem_barrier, 0, nullptr, image_barrier_count, image_barriers);
  7299. }
  7300. #ifdef FORCE_FULL_BARRIER
  7301. _full_barrier(true);
  7302. #endif
  7303. memdelete(compute_list);
  7304. compute_list = nullptr;
  7305. // Compute_list is no longer active.
  7306. _THREAD_SAFE_UNLOCK_
  7307. }
  7308. void RenderingDeviceVulkan::barrier(uint32_t p_from, uint32_t p_to) {
  7309. uint32_t src_barrier_flags = 0;
  7310. uint32_t src_access_flags = 0;
  7311. if (p_from & BARRIER_MASK_COMPUTE) {
  7312. src_barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  7313. src_access_flags |= VK_ACCESS_SHADER_WRITE_BIT;
  7314. }
  7315. if (p_from & BARRIER_MASK_RASTER) {
  7316. src_barrier_flags |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  7317. src_access_flags |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  7318. }
  7319. if (p_from & BARRIER_MASK_TRANSFER) {
  7320. src_barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  7321. src_access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  7322. }
  7323. if (p_from == 0) {
  7324. src_barrier_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  7325. }
  7326. uint32_t dst_barrier_flags = 0;
  7327. uint32_t dst_access_flags = 0;
  7328. if (p_to & BARRIER_MASK_COMPUTE) {
  7329. dst_barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  7330. dst_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7331. }
  7332. if (p_to & BARRIER_MASK_RASTER) {
  7333. dst_barrier_flags |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
  7334. dst_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
  7335. }
  7336. if (p_to & BARRIER_MASK_TRANSFER) {
  7337. dst_barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  7338. dst_access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  7339. }
  7340. if (p_to == 0) {
  7341. dst_barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  7342. }
  7343. _memory_barrier(src_barrier_flags, dst_barrier_flags, src_access_flags, dst_access_flags, true);
  7344. }
  7345. void RenderingDeviceVulkan::full_barrier() {
  7346. #ifndef DEBUG_ENABLED
  7347. ERR_PRINT("Full barrier is debug-only, should not be used in production");
  7348. #endif
  7349. _full_barrier(true);
  7350. }
  7351. #if 0
  7352. void RenderingDeviceVulkan::draw_list_render_secondary_to_framebuffer(ID p_framebuffer, ID *p_draw_lists, uint32_t p_draw_list_count, InitialAction p_initial_action, FinalAction p_final_action, const Vector<Variant> &p_clear_colors) {
  7353. VkCommandBuffer frame_cmdbuf = frames[frame].frame_buffer;
  7354. ERR_FAIL_COND(!frame_cmdbuf);
  7355. VkRenderPassBeginInfo render_pass_begin;
  7356. render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  7357. render_pass_begin.pNext = nullptr;
  7358. render_pass_begin.renderPass = context->get_render_pass();
  7359. render_pass_begin.framebuffer = context->get_frame_framebuffer(frame);
  7360. render_pass_begin.renderArea.extent.width = context->get_screen_width(p_screen);
  7361. render_pass_begin.renderArea.extent.height = context->get_screen_height(p_screen);
  7362. render_pass_begin.renderArea.offset.x = 0;
  7363. render_pass_begin.renderArea.offset.y = 0;
  7364. render_pass_begin.clearValueCount = 1;
  7365. VkClearValue clear_value;
  7366. clear_value.color.float32[0] = p_clear_color.r;
  7367. clear_value.color.float32[1] = p_clear_color.g;
  7368. clear_value.color.float32[2] = p_clear_color.b;
  7369. clear_value.color.float32[3] = p_clear_color.a;
  7370. render_pass_begin.pClearValues = &clear_value;
  7371. vkCmdBeginRenderPass(frame_cmdbuf, &render_pass_begin, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS);
  7372. ID screen_format = screen_get_framebuffer_format();
  7373. {
  7374. VkCommandBuffer *command_buffers = (VkCommandBuffer *)alloca(sizeof(VkCommandBuffer) * p_draw_list_count);
  7375. uint32_t command_buffer_count = 0;
  7376. for (uint32_t i = 0; i < p_draw_list_count; i++) {
  7377. DrawList *dl = _get_draw_list_ptr(p_draw_lists[i]);
  7378. ERR_CONTINUE_MSG(!dl, "Draw list index (" + itos(i) + ") is not a valid draw list ID.");
  7379. ERR_CONTINUE_MSG(dl->validation.framebuffer_format != p_format_check,
  7380. "Draw list index (" + itos(i) + ") is created with a framebuffer format incompatible with this render pass.");
  7381. if (dl->validation.active) {
  7382. // Needs to be closed, so close it.
  7383. vkEndCommandBuffer(dl->command_buffer);
  7384. dl->validation.active = false;
  7385. }
  7386. command_buffers[command_buffer_count++] = dl->command_buffer;
  7387. }
  7388. print_line("to draw: " + itos(command_buffer_count));
  7389. vkCmdExecuteCommands(p_primary, command_buffer_count, command_buffers);
  7390. }
  7391. vkCmdEndRenderPass(frame_cmdbuf);
  7392. }
  7393. #endif
  7394. void RenderingDeviceVulkan::_free_internal(RID p_id) {
  7395. #ifdef DEV_ENABLED
  7396. String resource_name;
  7397. if (resource_names.has(p_id)) {
  7398. resource_name = resource_names[p_id];
  7399. resource_names.erase(p_id);
  7400. }
  7401. #endif
  7402. // Push everything so it's disposed of next time this frame index is processed (means, it's safe to do it).
  7403. if (texture_owner.owns(p_id)) {
  7404. Texture *texture = texture_owner.get_or_null(p_id);
  7405. frames[frame].textures_to_dispose_of.push_back(*texture);
  7406. texture_owner.free(p_id);
  7407. } else if (framebuffer_owner.owns(p_id)) {
  7408. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_id);
  7409. frames[frame].framebuffers_to_dispose_of.push_back(*framebuffer);
  7410. if (framebuffer->invalidated_callback != nullptr) {
  7411. framebuffer->invalidated_callback(framebuffer->invalidated_callback_userdata);
  7412. }
  7413. framebuffer_owner.free(p_id);
  7414. } else if (sampler_owner.owns(p_id)) {
  7415. VkSampler *sampler = sampler_owner.get_or_null(p_id);
  7416. frames[frame].samplers_to_dispose_of.push_back(*sampler);
  7417. sampler_owner.free(p_id);
  7418. } else if (vertex_buffer_owner.owns(p_id)) {
  7419. Buffer *vertex_buffer = vertex_buffer_owner.get_or_null(p_id);
  7420. frames[frame].buffers_to_dispose_of.push_back(*vertex_buffer);
  7421. vertex_buffer_owner.free(p_id);
  7422. } else if (vertex_array_owner.owns(p_id)) {
  7423. vertex_array_owner.free(p_id);
  7424. } else if (index_buffer_owner.owns(p_id)) {
  7425. IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_id);
  7426. Buffer b;
  7427. b.allocation = index_buffer->allocation;
  7428. b.buffer = index_buffer->buffer;
  7429. b.size = index_buffer->size;
  7430. b.buffer_info = {};
  7431. frames[frame].buffers_to_dispose_of.push_back(b);
  7432. index_buffer_owner.free(p_id);
  7433. } else if (index_array_owner.owns(p_id)) {
  7434. index_array_owner.free(p_id);
  7435. } else if (shader_owner.owns(p_id)) {
  7436. Shader *shader = shader_owner.get_or_null(p_id);
  7437. frames[frame].shaders_to_dispose_of.push_back(*shader);
  7438. shader_owner.free(p_id);
  7439. } else if (uniform_buffer_owner.owns(p_id)) {
  7440. Buffer *uniform_buffer = uniform_buffer_owner.get_or_null(p_id);
  7441. frames[frame].buffers_to_dispose_of.push_back(*uniform_buffer);
  7442. uniform_buffer_owner.free(p_id);
  7443. } else if (texture_buffer_owner.owns(p_id)) {
  7444. TextureBuffer *texture_buffer = texture_buffer_owner.get_or_null(p_id);
  7445. frames[frame].buffers_to_dispose_of.push_back(texture_buffer->buffer);
  7446. frames[frame].buffer_views_to_dispose_of.push_back(texture_buffer->view);
  7447. texture_buffer_owner.free(p_id);
  7448. } else if (storage_buffer_owner.owns(p_id)) {
  7449. Buffer *storage_buffer = storage_buffer_owner.get_or_null(p_id);
  7450. frames[frame].buffers_to_dispose_of.push_back(*storage_buffer);
  7451. storage_buffer_owner.free(p_id);
  7452. } else if (uniform_set_owner.owns(p_id)) {
  7453. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id);
  7454. frames[frame].uniform_sets_to_dispose_of.push_back(*uniform_set);
  7455. uniform_set_owner.free(p_id);
  7456. if (uniform_set->invalidated_callback != nullptr) {
  7457. uniform_set->invalidated_callback(uniform_set->invalidated_callback_userdata);
  7458. }
  7459. } else if (render_pipeline_owner.owns(p_id)) {
  7460. RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_id);
  7461. frames[frame].render_pipelines_to_dispose_of.push_back(*pipeline);
  7462. render_pipeline_owner.free(p_id);
  7463. } else if (compute_pipeline_owner.owns(p_id)) {
  7464. ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_id);
  7465. frames[frame].compute_pipelines_to_dispose_of.push_back(*pipeline);
  7466. compute_pipeline_owner.free(p_id);
  7467. } else {
  7468. #ifdef DEV_ENABLED
  7469. ERR_PRINT("Attempted to free invalid ID: " + itos(p_id.get_id()) + " " + resource_name);
  7470. #else
  7471. ERR_PRINT("Attempted to free invalid ID: " + itos(p_id.get_id()));
  7472. #endif
  7473. }
  7474. }
  7475. void RenderingDeviceVulkan::free(RID p_id) {
  7476. _THREAD_SAFE_METHOD_
  7477. _free_dependencies(p_id); // Recursively erase dependencies first, to avoid potential API problems.
  7478. _free_internal(p_id);
  7479. }
  7480. // The full list of resources that can be named is in the VkObjectType enum.
  7481. // We just expose the resources that are owned and can be accessed easily.
  7482. void RenderingDeviceVulkan::set_resource_name(RID p_id, const String p_name) {
  7483. if (texture_owner.owns(p_id)) {
  7484. Texture *texture = texture_owner.get_or_null(p_id);
  7485. if (texture->owner.is_null()) {
  7486. // Don't set the source texture's name when calling on a texture view.
  7487. context->set_object_name(VK_OBJECT_TYPE_IMAGE, uint64_t(texture->image), p_name);
  7488. }
  7489. context->set_object_name(VK_OBJECT_TYPE_IMAGE_VIEW, uint64_t(texture->view), p_name + " View");
  7490. } else if (framebuffer_owner.owns(p_id)) {
  7491. //Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_id);
  7492. // Not implemented for now as the relationship between Framebuffer and RenderPass is very complex.
  7493. } else if (sampler_owner.owns(p_id)) {
  7494. VkSampler *sampler = sampler_owner.get_or_null(p_id);
  7495. context->set_object_name(VK_OBJECT_TYPE_SAMPLER, uint64_t(*sampler), p_name);
  7496. } else if (vertex_buffer_owner.owns(p_id)) {
  7497. Buffer *vertex_buffer = vertex_buffer_owner.get_or_null(p_id);
  7498. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(vertex_buffer->buffer), p_name);
  7499. } else if (index_buffer_owner.owns(p_id)) {
  7500. IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_id);
  7501. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(index_buffer->buffer), p_name);
  7502. } else if (shader_owner.owns(p_id)) {
  7503. Shader *shader = shader_owner.get_or_null(p_id);
  7504. context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, uint64_t(shader->pipeline_layout), p_name + " Pipeline Layout");
  7505. for (int i = 0; i < shader->sets.size(); i++) {
  7506. context->set_object_name(VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, uint64_t(shader->sets[i].descriptor_set_layout), p_name);
  7507. }
  7508. } else if (uniform_buffer_owner.owns(p_id)) {
  7509. Buffer *uniform_buffer = uniform_buffer_owner.get_or_null(p_id);
  7510. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(uniform_buffer->buffer), p_name);
  7511. } else if (texture_buffer_owner.owns(p_id)) {
  7512. TextureBuffer *texture_buffer = texture_buffer_owner.get_or_null(p_id);
  7513. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(texture_buffer->buffer.buffer), p_name);
  7514. context->set_object_name(VK_OBJECT_TYPE_BUFFER_VIEW, uint64_t(texture_buffer->view), p_name + " View");
  7515. } else if (storage_buffer_owner.owns(p_id)) {
  7516. Buffer *storage_buffer = storage_buffer_owner.get_or_null(p_id);
  7517. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(storage_buffer->buffer), p_name);
  7518. } else if (uniform_set_owner.owns(p_id)) {
  7519. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id);
  7520. context->set_object_name(VK_OBJECT_TYPE_DESCRIPTOR_SET, uint64_t(uniform_set->descriptor_set), p_name);
  7521. } else if (render_pipeline_owner.owns(p_id)) {
  7522. RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_id);
  7523. context->set_object_name(VK_OBJECT_TYPE_PIPELINE, uint64_t(pipeline->pipeline), p_name);
  7524. context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, uint64_t(pipeline->pipeline_layout), p_name + " Layout");
  7525. } else if (compute_pipeline_owner.owns(p_id)) {
  7526. ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_id);
  7527. context->set_object_name(VK_OBJECT_TYPE_PIPELINE, uint64_t(pipeline->pipeline), p_name);
  7528. context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, uint64_t(pipeline->pipeline_layout), p_name + " Layout");
  7529. } else {
  7530. ERR_PRINT("Attempted to name invalid ID: " + itos(p_id.get_id()));
  7531. return;
  7532. }
  7533. #ifdef DEV_ENABLED
  7534. resource_names[p_id] = p_name;
  7535. #endif
  7536. }
  7537. void RenderingDeviceVulkan::draw_command_begin_label(String p_label_name, const Color p_color) {
  7538. context->command_begin_label(frames[frame].draw_command_buffer, p_label_name, p_color);
  7539. }
  7540. void RenderingDeviceVulkan::draw_command_insert_label(String p_label_name, const Color p_color) {
  7541. context->command_insert_label(frames[frame].draw_command_buffer, p_label_name, p_color);
  7542. }
  7543. void RenderingDeviceVulkan::draw_command_end_label() {
  7544. context->command_end_label(frames[frame].draw_command_buffer);
  7545. }
  7546. String RenderingDeviceVulkan::get_device_vendor_name() const {
  7547. return context->get_device_vendor_name();
  7548. }
  7549. String RenderingDeviceVulkan::get_device_name() const {
  7550. return context->get_device_name();
  7551. }
  7552. RenderingDevice::DeviceType RenderingDeviceVulkan::get_device_type() const {
  7553. return context->get_device_type();
  7554. }
  7555. String RenderingDeviceVulkan::get_device_api_version() const {
  7556. return context->get_device_api_version();
  7557. }
  7558. String RenderingDeviceVulkan::get_device_pipeline_cache_uuid() const {
  7559. return context->get_device_pipeline_cache_uuid();
  7560. }
  7561. void RenderingDeviceVulkan::_finalize_command_bufers() {
  7562. if (draw_list) {
  7563. ERR_PRINT("Found open draw list at the end of the frame, this should never happen (further drawing will likely not work).");
  7564. }
  7565. if (compute_list) {
  7566. ERR_PRINT("Found open compute list at the end of the frame, this should never happen (further compute will likely not work).");
  7567. }
  7568. { // Complete the setup buffer (that needs to be processed before anything else).
  7569. vkEndCommandBuffer(frames[frame].setup_command_buffer);
  7570. vkEndCommandBuffer(frames[frame].draw_command_buffer);
  7571. }
  7572. }
  7573. void RenderingDeviceVulkan::_begin_frame() {
  7574. // Erase pending resources.
  7575. _free_pending_resources(frame);
  7576. // Create setup command buffer and set as the setup buffer.
  7577. {
  7578. VkCommandBufferBeginInfo cmdbuf_begin;
  7579. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7580. cmdbuf_begin.pNext = nullptr;
  7581. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7582. cmdbuf_begin.pInheritanceInfo = nullptr;
  7583. VkResult err = vkResetCommandBuffer(frames[frame].setup_command_buffer, 0);
  7584. ERR_FAIL_COND_MSG(err, "vkResetCommandBuffer failed with error " + itos(err) + ".");
  7585. err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin);
  7586. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7587. err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin);
  7588. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7589. if (local_device.is_null()) {
  7590. context->append_command_buffer(frames[frame].draw_command_buffer);
  7591. context->set_setup_buffer(frames[frame].setup_command_buffer); // Append now so it's added before everything else.
  7592. }
  7593. }
  7594. // Advance current frame.
  7595. frames_drawn++;
  7596. // Advance staging buffer if used.
  7597. if (staging_buffer_used) {
  7598. staging_buffer_current = (staging_buffer_current + 1) % staging_buffer_blocks.size();
  7599. staging_buffer_used = false;
  7600. }
  7601. if (frames[frame].timestamp_count) {
  7602. vkGetQueryPoolResults(device, frames[frame].timestamp_pool, 0, frames[frame].timestamp_count, sizeof(uint64_t) * max_timestamp_query_elements, frames[frame].timestamp_result_values.ptr(), sizeof(uint64_t), VK_QUERY_RESULT_64_BIT);
  7603. vkCmdResetQueryPool(frames[frame].setup_command_buffer, frames[frame].timestamp_pool, 0, frames[frame].timestamp_count);
  7604. SWAP(frames[frame].timestamp_names, frames[frame].timestamp_result_names);
  7605. SWAP(frames[frame].timestamp_cpu_values, frames[frame].timestamp_cpu_result_values);
  7606. }
  7607. frames[frame].timestamp_result_count = frames[frame].timestamp_count;
  7608. frames[frame].timestamp_count = 0;
  7609. frames[frame].index = Engine::get_singleton()->get_frames_drawn();
  7610. }
  7611. VkSampleCountFlagBits RenderingDeviceVulkan::_ensure_supported_sample_count(TextureSamples p_requested_sample_count) const {
  7612. VkSampleCountFlags sample_count_flags = limits.framebufferColorSampleCounts & limits.framebufferDepthSampleCounts;
  7613. if (sample_count_flags & rasterization_sample_count[p_requested_sample_count]) {
  7614. // The requested sample count is supported.
  7615. return rasterization_sample_count[p_requested_sample_count];
  7616. } else {
  7617. // Find the closest lower supported sample count.
  7618. VkSampleCountFlagBits sample_count = rasterization_sample_count[p_requested_sample_count];
  7619. while (sample_count > VK_SAMPLE_COUNT_1_BIT) {
  7620. if (sample_count_flags & rasterization_sample_count[sample_count]) {
  7621. return sample_count;
  7622. }
  7623. sample_count = (VkSampleCountFlagBits)(sample_count >> 1);
  7624. }
  7625. }
  7626. return VK_SAMPLE_COUNT_1_BIT;
  7627. }
  7628. void RenderingDeviceVulkan::swap_buffers() {
  7629. ERR_FAIL_COND_MSG(local_device.is_valid(), "Local devices can't swap buffers.");
  7630. _THREAD_SAFE_METHOD_
  7631. _finalize_command_bufers();
  7632. screen_prepared = false;
  7633. // Swap buffers.
  7634. context->swap_buffers();
  7635. frame = (frame + 1) % frame_count;
  7636. _begin_frame();
  7637. }
  7638. void RenderingDeviceVulkan::submit() {
  7639. ERR_FAIL_COND_MSG(local_device.is_null(), "Only local devices can submit and sync.");
  7640. ERR_FAIL_COND_MSG(local_device_processing, "device already submitted, call sync to wait until done.");
  7641. _finalize_command_bufers();
  7642. VkCommandBuffer command_buffers[2] = { frames[frame].setup_command_buffer, frames[frame].draw_command_buffer };
  7643. context->local_device_push_command_buffers(local_device, command_buffers, 2);
  7644. local_device_processing = true;
  7645. }
  7646. void RenderingDeviceVulkan::sync() {
  7647. ERR_FAIL_COND_MSG(local_device.is_null(), "Only local devices can submit and sync.");
  7648. ERR_FAIL_COND_MSG(!local_device_processing, "sync can only be called after a submit");
  7649. context->local_device_sync(local_device);
  7650. _begin_frame();
  7651. local_device_processing = false;
  7652. }
  7653. VmaPool RenderingDeviceVulkan::_find_or_create_small_allocs_pool(uint32_t p_mem_type_index) {
  7654. if (small_allocs_pools.has(p_mem_type_index)) {
  7655. return small_allocs_pools[p_mem_type_index];
  7656. }
  7657. print_verbose("Creating VMA small objects pool for memory type index " + itos(p_mem_type_index));
  7658. VmaPoolCreateInfo pci;
  7659. pci.memoryTypeIndex = p_mem_type_index;
  7660. pci.flags = 0;
  7661. pci.blockSize = 0;
  7662. pci.minBlockCount = 0;
  7663. pci.maxBlockCount = SIZE_MAX;
  7664. pci.priority = 0.5f;
  7665. pci.minAllocationAlignment = 0;
  7666. pci.pMemoryAllocateNext = nullptr;
  7667. VmaPool pool = VK_NULL_HANDLE;
  7668. VkResult res = vmaCreatePool(allocator, &pci, &pool);
  7669. small_allocs_pools[p_mem_type_index] = pool; // Don't try to create it again if failed the first time.
  7670. ERR_FAIL_COND_V_MSG(res, pool, "vmaCreatePool failed with error " + itos(res) + ".");
  7671. return pool;
  7672. }
  7673. void RenderingDeviceVulkan::_free_pending_resources(int p_frame) {
  7674. // Free in dependency usage order, so nothing weird happens.
  7675. // Pipelines.
  7676. while (frames[p_frame].render_pipelines_to_dispose_of.front()) {
  7677. RenderPipeline *pipeline = &frames[p_frame].render_pipelines_to_dispose_of.front()->get();
  7678. vkDestroyPipeline(device, pipeline->pipeline, nullptr);
  7679. frames[p_frame].render_pipelines_to_dispose_of.pop_front();
  7680. }
  7681. while (frames[p_frame].compute_pipelines_to_dispose_of.front()) {
  7682. ComputePipeline *pipeline = &frames[p_frame].compute_pipelines_to_dispose_of.front()->get();
  7683. vkDestroyPipeline(device, pipeline->pipeline, nullptr);
  7684. frames[p_frame].compute_pipelines_to_dispose_of.pop_front();
  7685. }
  7686. // Uniform sets.
  7687. while (frames[p_frame].uniform_sets_to_dispose_of.front()) {
  7688. UniformSet *uniform_set = &frames[p_frame].uniform_sets_to_dispose_of.front()->get();
  7689. vkFreeDescriptorSets(device, uniform_set->pool->pool, 1, &uniform_set->descriptor_set);
  7690. _descriptor_pool_free(uniform_set->pool_key, uniform_set->pool);
  7691. frames[p_frame].uniform_sets_to_dispose_of.pop_front();
  7692. }
  7693. // Buffer views.
  7694. while (frames[p_frame].buffer_views_to_dispose_of.front()) {
  7695. VkBufferView buffer_view = frames[p_frame].buffer_views_to_dispose_of.front()->get();
  7696. vkDestroyBufferView(device, buffer_view, nullptr);
  7697. frames[p_frame].buffer_views_to_dispose_of.pop_front();
  7698. }
  7699. // Shaders.
  7700. while (frames[p_frame].shaders_to_dispose_of.front()) {
  7701. Shader *shader = &frames[p_frame].shaders_to_dispose_of.front()->get();
  7702. // Descriptor set layout for each set.
  7703. for (int i = 0; i < shader->sets.size(); i++) {
  7704. vkDestroyDescriptorSetLayout(device, shader->sets[i].descriptor_set_layout, nullptr);
  7705. }
  7706. // Pipeline layout.
  7707. vkDestroyPipelineLayout(device, shader->pipeline_layout, nullptr);
  7708. // Shaders themselves.
  7709. for (int i = 0; i < shader->pipeline_stages.size(); i++) {
  7710. vkDestroyShaderModule(device, shader->pipeline_stages[i].module, nullptr);
  7711. }
  7712. frames[p_frame].shaders_to_dispose_of.pop_front();
  7713. }
  7714. // Samplers.
  7715. while (frames[p_frame].samplers_to_dispose_of.front()) {
  7716. VkSampler sampler = frames[p_frame].samplers_to_dispose_of.front()->get();
  7717. vkDestroySampler(device, sampler, nullptr);
  7718. frames[p_frame].samplers_to_dispose_of.pop_front();
  7719. }
  7720. // Framebuffers.
  7721. while (frames[p_frame].framebuffers_to_dispose_of.front()) {
  7722. Framebuffer *framebuffer = &frames[p_frame].framebuffers_to_dispose_of.front()->get();
  7723. for (const KeyValue<Framebuffer::VersionKey, Framebuffer::Version> &E : framebuffer->framebuffers) {
  7724. // First framebuffer, then render pass because it depends on it.
  7725. vkDestroyFramebuffer(device, E.value.framebuffer, nullptr);
  7726. vkDestroyRenderPass(device, E.value.render_pass, nullptr);
  7727. }
  7728. frames[p_frame].framebuffers_to_dispose_of.pop_front();
  7729. }
  7730. // Textures.
  7731. while (frames[p_frame].textures_to_dispose_of.front()) {
  7732. Texture *texture = &frames[p_frame].textures_to_dispose_of.front()->get();
  7733. if (texture->bound) {
  7734. WARN_PRINT("Deleted a texture while it was bound..");
  7735. }
  7736. vkDestroyImageView(device, texture->view, nullptr);
  7737. if (texture->owner.is_null()) {
  7738. // Actually owns the image and the allocation too.
  7739. image_memory -= texture->allocation_info.size;
  7740. vmaDestroyImage(allocator, texture->image, texture->allocation);
  7741. }
  7742. frames[p_frame].textures_to_dispose_of.pop_front();
  7743. }
  7744. // Buffers.
  7745. while (frames[p_frame].buffers_to_dispose_of.front()) {
  7746. _buffer_free(&frames[p_frame].buffers_to_dispose_of.front()->get());
  7747. frames[p_frame].buffers_to_dispose_of.pop_front();
  7748. }
  7749. }
  7750. void RenderingDeviceVulkan::prepare_screen_for_drawing() {
  7751. _THREAD_SAFE_METHOD_
  7752. context->prepare_buffers();
  7753. screen_prepared = true;
  7754. }
  7755. uint32_t RenderingDeviceVulkan::get_frame_delay() const {
  7756. return frame_count;
  7757. }
  7758. uint64_t RenderingDeviceVulkan::get_memory_usage(MemoryType p_type) const {
  7759. if (p_type == MEMORY_BUFFERS) {
  7760. return buffer_memory;
  7761. } else if (p_type == MEMORY_TEXTURES) {
  7762. return image_memory;
  7763. } else {
  7764. VmaTotalStatistics stats;
  7765. vmaCalculateStatistics(allocator, &stats);
  7766. return stats.total.statistics.allocationBytes;
  7767. }
  7768. }
  7769. void RenderingDeviceVulkan::_flush(bool p_current_frame) {
  7770. if (local_device.is_valid() && !p_current_frame) {
  7771. return; // Flushing previous frames has no effect with local device.
  7772. }
  7773. // Not doing this crashes RADV (undefined behavior).
  7774. if (p_current_frame) {
  7775. vkEndCommandBuffer(frames[frame].setup_command_buffer);
  7776. vkEndCommandBuffer(frames[frame].draw_command_buffer);
  7777. }
  7778. if (local_device.is_valid()) {
  7779. VkCommandBuffer command_buffers[2] = { frames[frame].setup_command_buffer, frames[frame].draw_command_buffer };
  7780. context->local_device_push_command_buffers(local_device, command_buffers, 2);
  7781. context->local_device_sync(local_device);
  7782. VkCommandBufferBeginInfo cmdbuf_begin;
  7783. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7784. cmdbuf_begin.pNext = nullptr;
  7785. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7786. cmdbuf_begin.pInheritanceInfo = nullptr;
  7787. VkResult err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin);
  7788. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7789. err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin);
  7790. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7791. } else {
  7792. context->flush(p_current_frame, p_current_frame);
  7793. // Re-create the setup command.
  7794. if (p_current_frame) {
  7795. VkCommandBufferBeginInfo cmdbuf_begin;
  7796. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7797. cmdbuf_begin.pNext = nullptr;
  7798. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7799. cmdbuf_begin.pInheritanceInfo = nullptr;
  7800. VkResult err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin);
  7801. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7802. context->set_setup_buffer(frames[frame].setup_command_buffer); // Append now so it's added before everything else.
  7803. }
  7804. if (p_current_frame) {
  7805. VkCommandBufferBeginInfo cmdbuf_begin;
  7806. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7807. cmdbuf_begin.pNext = nullptr;
  7808. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7809. cmdbuf_begin.pInheritanceInfo = nullptr;
  7810. VkResult err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin);
  7811. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7812. context->append_command_buffer(frames[frame].draw_command_buffer);
  7813. }
  7814. }
  7815. }
  7816. void RenderingDeviceVulkan::initialize(VulkanContext *p_context, bool p_local_device) {
  7817. // Get our device capabilities.
  7818. {
  7819. device_capabilities.version_major = p_context->get_vulkan_major();
  7820. device_capabilities.version_minor = p_context->get_vulkan_minor();
  7821. }
  7822. context = p_context;
  7823. device = p_context->get_device();
  7824. if (p_local_device) {
  7825. frame_count = 1;
  7826. local_device = p_context->local_device_create();
  7827. device = p_context->local_device_get_vk_device(local_device);
  7828. } else {
  7829. frame_count = p_context->get_swapchain_image_count() + 1; // Always need one extra to ensure it's unused at any time, without having to use a fence for this.
  7830. }
  7831. limits = p_context->get_device_limits();
  7832. max_timestamp_query_elements = 256;
  7833. { // Initialize allocator.
  7834. VmaAllocatorCreateInfo allocatorInfo;
  7835. memset(&allocatorInfo, 0, sizeof(VmaAllocatorCreateInfo));
  7836. allocatorInfo.physicalDevice = p_context->get_physical_device();
  7837. allocatorInfo.device = device;
  7838. allocatorInfo.instance = p_context->get_instance();
  7839. vmaCreateAllocator(&allocatorInfo, &allocator);
  7840. }
  7841. frames.resize(frame_count);
  7842. frame = 0;
  7843. // Create setup and frame buffers.
  7844. for (int i = 0; i < frame_count; i++) {
  7845. frames[i].index = 0;
  7846. { // Create command pool, one per frame is recommended.
  7847. VkCommandPoolCreateInfo cmd_pool_info;
  7848. cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  7849. cmd_pool_info.pNext = nullptr;
  7850. cmd_pool_info.queueFamilyIndex = p_context->get_graphics_queue_family_index();
  7851. cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  7852. VkResult res = vkCreateCommandPool(device, &cmd_pool_info, nullptr, &frames[i].command_pool);
  7853. ERR_FAIL_COND_MSG(res, "vkCreateCommandPool failed with error " + itos(res) + ".");
  7854. }
  7855. { // Create command buffers.
  7856. VkCommandBufferAllocateInfo cmdbuf;
  7857. // No command buffer exists, create it.
  7858. cmdbuf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  7859. cmdbuf.pNext = nullptr;
  7860. cmdbuf.commandPool = frames[i].command_pool;
  7861. cmdbuf.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  7862. cmdbuf.commandBufferCount = 1;
  7863. VkResult err = vkAllocateCommandBuffers(device, &cmdbuf, &frames[i].setup_command_buffer);
  7864. ERR_CONTINUE_MSG(err, "vkAllocateCommandBuffers failed with error " + itos(err) + ".");
  7865. err = vkAllocateCommandBuffers(device, &cmdbuf, &frames[i].draw_command_buffer);
  7866. ERR_CONTINUE_MSG(err, "vkAllocateCommandBuffers failed with error " + itos(err) + ".");
  7867. }
  7868. {
  7869. // Create query pool.
  7870. VkQueryPoolCreateInfo query_pool_create_info;
  7871. query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
  7872. query_pool_create_info.flags = 0;
  7873. query_pool_create_info.pNext = nullptr;
  7874. query_pool_create_info.queryType = VK_QUERY_TYPE_TIMESTAMP;
  7875. query_pool_create_info.queryCount = max_timestamp_query_elements;
  7876. query_pool_create_info.pipelineStatistics = 0;
  7877. vkCreateQueryPool(device, &query_pool_create_info, nullptr, &frames[i].timestamp_pool);
  7878. frames[i].timestamp_names.resize(max_timestamp_query_elements);
  7879. frames[i].timestamp_cpu_values.resize(max_timestamp_query_elements);
  7880. frames[i].timestamp_count = 0;
  7881. frames[i].timestamp_result_names.resize(max_timestamp_query_elements);
  7882. frames[i].timestamp_cpu_result_values.resize(max_timestamp_query_elements);
  7883. frames[i].timestamp_result_values.resize(max_timestamp_query_elements);
  7884. frames[i].timestamp_result_count = 0;
  7885. }
  7886. }
  7887. {
  7888. // Begin the first command buffer for the first frame, so
  7889. // setting up things can be done in the meantime until swap_buffers(), which is called before advance.
  7890. VkCommandBufferBeginInfo cmdbuf_begin;
  7891. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7892. cmdbuf_begin.pNext = nullptr;
  7893. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7894. cmdbuf_begin.pInheritanceInfo = nullptr;
  7895. VkResult err = vkBeginCommandBuffer(frames[0].setup_command_buffer, &cmdbuf_begin);
  7896. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7897. err = vkBeginCommandBuffer(frames[0].draw_command_buffer, &cmdbuf_begin);
  7898. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7899. if (local_device.is_null()) {
  7900. context->set_setup_buffer(frames[0].setup_command_buffer); // Append now so it's added before everything else.
  7901. context->append_command_buffer(frames[0].draw_command_buffer);
  7902. }
  7903. }
  7904. // NOTE: If adding new project settings here, also duplicate their definition in
  7905. // rendering_server.cpp for headless doctool.
  7906. staging_buffer_block_size = GLOBAL_DEF("rendering/vulkan/staging_buffer/block_size_kb", 256);
  7907. staging_buffer_block_size = MAX(4u, staging_buffer_block_size);
  7908. staging_buffer_block_size *= 1024; // Kb -> bytes.
  7909. staging_buffer_max_size = GLOBAL_DEF("rendering/vulkan/staging_buffer/max_size_mb", 128);
  7910. staging_buffer_max_size = MAX(1u, staging_buffer_max_size);
  7911. staging_buffer_max_size *= 1024 * 1024;
  7912. if (staging_buffer_max_size < staging_buffer_block_size * 4) {
  7913. // Validate enough blocks.
  7914. staging_buffer_max_size = staging_buffer_block_size * 4;
  7915. }
  7916. texture_upload_region_size_px = GLOBAL_DEF("rendering/vulkan/staging_buffer/texture_upload_region_size_px", 64);
  7917. texture_upload_region_size_px = nearest_power_of_2_templated(texture_upload_region_size_px);
  7918. frames_drawn = frame_count; // Start from frame count, so everything else is immediately old.
  7919. // Ensure current staging block is valid and at least one per frame exists.
  7920. staging_buffer_current = 0;
  7921. staging_buffer_used = false;
  7922. for (int i = 0; i < frame_count; i++) {
  7923. // Staging was never used, create a block.
  7924. Error err = _insert_staging_block();
  7925. ERR_CONTINUE(err != OK);
  7926. }
  7927. max_descriptors_per_pool = GLOBAL_DEF("rendering/vulkan/descriptor_pools/max_descriptors_per_pool", 64);
  7928. // Check to make sure DescriptorPoolKey is good.
  7929. static_assert(sizeof(uint64_t) * 3 >= UNIFORM_TYPE_MAX * sizeof(uint16_t));
  7930. draw_list = nullptr;
  7931. draw_list_count = 0;
  7932. draw_list_split = false;
  7933. compute_list = nullptr;
  7934. }
  7935. template <class T>
  7936. void RenderingDeviceVulkan::_free_rids(T &p_owner, const char *p_type) {
  7937. List<RID> owned;
  7938. p_owner.get_owned_list(&owned);
  7939. if (owned.size()) {
  7940. if (owned.size() == 1) {
  7941. WARN_PRINT(vformat("1 RID of type \"%s\" was leaked.", p_type));
  7942. } else {
  7943. WARN_PRINT(vformat("%d RIDs of type \"%s\" were leaked.", owned.size(), p_type));
  7944. }
  7945. for (const RID &E : owned) {
  7946. #ifdef DEV_ENABLED
  7947. if (resource_names.has(E)) {
  7948. print_line(String(" - ") + resource_names[E]);
  7949. }
  7950. #endif
  7951. free(E);
  7952. }
  7953. }
  7954. }
  7955. void RenderingDeviceVulkan::capture_timestamp(const String &p_name) {
  7956. ERR_FAIL_COND_MSG(draw_list != nullptr, "Capturing timestamps during draw list creation is not allowed. Offending timestamp was: " + p_name);
  7957. ERR_FAIL_COND(frames[frame].timestamp_count >= max_timestamp_query_elements);
  7958. // This should be optional for profiling, else it will slow things down.
  7959. {
  7960. VkMemoryBarrier memoryBarrier;
  7961. memoryBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  7962. memoryBarrier.pNext = nullptr;
  7963. memoryBarrier.srcAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  7964. VK_ACCESS_INDEX_READ_BIT |
  7965. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  7966. VK_ACCESS_UNIFORM_READ_BIT |
  7967. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  7968. VK_ACCESS_SHADER_READ_BIT |
  7969. VK_ACCESS_SHADER_WRITE_BIT |
  7970. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  7971. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  7972. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  7973. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  7974. VK_ACCESS_TRANSFER_READ_BIT |
  7975. VK_ACCESS_TRANSFER_WRITE_BIT |
  7976. VK_ACCESS_HOST_READ_BIT |
  7977. VK_ACCESS_HOST_WRITE_BIT;
  7978. memoryBarrier.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  7979. VK_ACCESS_INDEX_READ_BIT |
  7980. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  7981. VK_ACCESS_UNIFORM_READ_BIT |
  7982. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  7983. VK_ACCESS_SHADER_READ_BIT |
  7984. VK_ACCESS_SHADER_WRITE_BIT |
  7985. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  7986. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  7987. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  7988. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  7989. VK_ACCESS_TRANSFER_READ_BIT |
  7990. VK_ACCESS_TRANSFER_WRITE_BIT |
  7991. VK_ACCESS_HOST_READ_BIT |
  7992. VK_ACCESS_HOST_WRITE_BIT;
  7993. vkCmdPipelineBarrier(frames[frame].draw_command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &memoryBarrier, 0, nullptr, 0, nullptr);
  7994. }
  7995. vkCmdWriteTimestamp(frames[frame].draw_command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, frames[frame].timestamp_pool, frames[frame].timestamp_count);
  7996. frames[frame].timestamp_names[frames[frame].timestamp_count] = p_name;
  7997. frames[frame].timestamp_cpu_values[frames[frame].timestamp_count] = OS::get_singleton()->get_ticks_usec();
  7998. frames[frame].timestamp_count++;
  7999. }
  8000. uint64_t RenderingDeviceVulkan::get_driver_resource(DriverResource p_resource, RID p_rid, uint64_t p_index) {
  8001. _THREAD_SAFE_METHOD_
  8002. switch (p_resource) {
  8003. case DRIVER_RESOURCE_VULKAN_DEVICE: {
  8004. return (uint64_t)context->get_device();
  8005. } break;
  8006. case DRIVER_RESOURCE_VULKAN_PHYSICAL_DEVICE: {
  8007. return (uint64_t)context->get_physical_device();
  8008. } break;
  8009. case DRIVER_RESOURCE_VULKAN_INSTANCE: {
  8010. return (uint64_t)context->get_instance();
  8011. } break;
  8012. case DRIVER_RESOURCE_VULKAN_QUEUE: {
  8013. return (uint64_t)context->get_graphics_queue();
  8014. } break;
  8015. case DRIVER_RESOURCE_VULKAN_QUEUE_FAMILY_INDEX: {
  8016. return context->get_graphics_queue_family_index();
  8017. } break;
  8018. case DRIVER_RESOURCE_VULKAN_IMAGE: {
  8019. Texture *tex = texture_owner.get_or_null(p_rid);
  8020. ERR_FAIL_NULL_V(tex, 0);
  8021. return (uint64_t)tex->image;
  8022. } break;
  8023. case DRIVER_RESOURCE_VULKAN_IMAGE_VIEW: {
  8024. Texture *tex = texture_owner.get_or_null(p_rid);
  8025. ERR_FAIL_NULL_V(tex, 0);
  8026. return (uint64_t)tex->view;
  8027. } break;
  8028. case DRIVER_RESOURCE_VULKAN_IMAGE_NATIVE_TEXTURE_FORMAT: {
  8029. Texture *tex = texture_owner.get_or_null(p_rid);
  8030. ERR_FAIL_NULL_V(tex, 0);
  8031. return vulkan_formats[tex->format];
  8032. } break;
  8033. case DRIVER_RESOURCE_VULKAN_SAMPLER: {
  8034. VkSampler *sampler = sampler_owner.get_or_null(p_rid);
  8035. ERR_FAIL_NULL_V(sampler, 0);
  8036. return uint64_t(*sampler);
  8037. } break;
  8038. case DRIVER_RESOURCE_VULKAN_DESCRIPTOR_SET: {
  8039. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_rid);
  8040. ERR_FAIL_NULL_V(uniform_set, 0);
  8041. return uint64_t(uniform_set->descriptor_set);
  8042. } break;
  8043. case DRIVER_RESOURCE_VULKAN_BUFFER: {
  8044. Buffer *buffer = nullptr;
  8045. if (vertex_buffer_owner.owns(p_rid)) {
  8046. buffer = vertex_buffer_owner.get_or_null(p_rid);
  8047. } else if (index_buffer_owner.owns(p_rid)) {
  8048. buffer = index_buffer_owner.get_or_null(p_rid);
  8049. } else if (uniform_buffer_owner.owns(p_rid)) {
  8050. buffer = uniform_buffer_owner.get_or_null(p_rid);
  8051. } else if (texture_buffer_owner.owns(p_rid)) {
  8052. buffer = &texture_buffer_owner.get_or_null(p_rid)->buffer;
  8053. } else if (storage_buffer_owner.owns(p_rid)) {
  8054. buffer = storage_buffer_owner.get_or_null(p_rid);
  8055. }
  8056. ERR_FAIL_NULL_V(buffer, 0);
  8057. return uint64_t(buffer->buffer);
  8058. } break;
  8059. case DRIVER_RESOURCE_VULKAN_COMPUTE_PIPELINE: {
  8060. ComputePipeline *compute_pipeline = compute_pipeline_owner.get_or_null(p_rid);
  8061. ERR_FAIL_NULL_V(compute_pipeline, 0);
  8062. return uint64_t(compute_pipeline->pipeline);
  8063. } break;
  8064. case DRIVER_RESOURCE_VULKAN_RENDER_PIPELINE: {
  8065. RenderPipeline *render_pipeline = render_pipeline_owner.get_or_null(p_rid);
  8066. ERR_FAIL_NULL_V(render_pipeline, 0);
  8067. return uint64_t(render_pipeline->pipeline);
  8068. } break;
  8069. default: {
  8070. // Not supported for this driver.
  8071. return 0;
  8072. } break;
  8073. }
  8074. }
  8075. uint32_t RenderingDeviceVulkan::get_captured_timestamps_count() const {
  8076. return frames[frame].timestamp_result_count;
  8077. }
  8078. uint64_t RenderingDeviceVulkan::get_captured_timestamps_frame() const {
  8079. return frames[frame].index;
  8080. }
  8081. static void mult64to128(uint64_t u, uint64_t v, uint64_t &h, uint64_t &l) {
  8082. uint64_t u1 = (u & 0xffffffff);
  8083. uint64_t v1 = (v & 0xffffffff);
  8084. uint64_t t = (u1 * v1);
  8085. uint64_t w3 = (t & 0xffffffff);
  8086. uint64_t k = (t >> 32);
  8087. u >>= 32;
  8088. t = (u * v1) + k;
  8089. k = (t & 0xffffffff);
  8090. uint64_t w1 = (t >> 32);
  8091. v >>= 32;
  8092. t = (u1 * v) + k;
  8093. k = (t >> 32);
  8094. h = (u * v) + w1 + k;
  8095. l = (t << 32) + w3;
  8096. }
  8097. uint64_t RenderingDeviceVulkan::get_captured_timestamp_gpu_time(uint32_t p_index) const {
  8098. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0);
  8099. // This sucks because timestampPeriod multiplier is a float, while the timestamp is 64 bits nanosecs.
  8100. // So, in cases like nvidia which give you enormous numbers and 1 as multiplier, multiplying is next to impossible.
  8101. // Need to do 128 bits fixed point multiplication to get the right value.
  8102. uint64_t shift_bits = 16;
  8103. uint64_t h, l;
  8104. mult64to128(frames[frame].timestamp_result_values[p_index], uint64_t(double(limits.timestampPeriod) * double(1 << shift_bits)), h, l);
  8105. l >>= shift_bits;
  8106. l |= h << (64 - shift_bits);
  8107. return l;
  8108. }
  8109. uint64_t RenderingDeviceVulkan::get_captured_timestamp_cpu_time(uint32_t p_index) const {
  8110. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0);
  8111. return frames[frame].timestamp_cpu_result_values[p_index];
  8112. }
  8113. String RenderingDeviceVulkan::get_captured_timestamp_name(uint32_t p_index) const {
  8114. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, String());
  8115. return frames[frame].timestamp_result_names[p_index];
  8116. }
  8117. uint64_t RenderingDeviceVulkan::limit_get(Limit p_limit) const {
  8118. switch (p_limit) {
  8119. case LIMIT_MAX_BOUND_UNIFORM_SETS:
  8120. return limits.maxBoundDescriptorSets;
  8121. case LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS:
  8122. return limits.maxColorAttachments;
  8123. case LIMIT_MAX_TEXTURES_PER_UNIFORM_SET:
  8124. return limits.maxDescriptorSetSampledImages;
  8125. case LIMIT_MAX_SAMPLERS_PER_UNIFORM_SET:
  8126. return limits.maxDescriptorSetSamplers;
  8127. case LIMIT_MAX_STORAGE_BUFFERS_PER_UNIFORM_SET:
  8128. return limits.maxDescriptorSetStorageBuffers;
  8129. case LIMIT_MAX_STORAGE_IMAGES_PER_UNIFORM_SET:
  8130. return limits.maxDescriptorSetStorageImages;
  8131. case LIMIT_MAX_UNIFORM_BUFFERS_PER_UNIFORM_SET:
  8132. return limits.maxDescriptorSetUniformBuffers;
  8133. case LIMIT_MAX_DRAW_INDEXED_INDEX:
  8134. return limits.maxDrawIndexedIndexValue;
  8135. case LIMIT_MAX_FRAMEBUFFER_HEIGHT:
  8136. return limits.maxFramebufferHeight;
  8137. case LIMIT_MAX_FRAMEBUFFER_WIDTH:
  8138. return limits.maxFramebufferWidth;
  8139. case LIMIT_MAX_TEXTURE_ARRAY_LAYERS:
  8140. return limits.maxImageArrayLayers;
  8141. case LIMIT_MAX_TEXTURE_SIZE_1D:
  8142. return limits.maxImageDimension1D;
  8143. case LIMIT_MAX_TEXTURE_SIZE_2D:
  8144. return limits.maxImageDimension2D;
  8145. case LIMIT_MAX_TEXTURE_SIZE_3D:
  8146. return limits.maxImageDimension3D;
  8147. case LIMIT_MAX_TEXTURE_SIZE_CUBE:
  8148. return limits.maxImageDimensionCube;
  8149. case LIMIT_MAX_TEXTURES_PER_SHADER_STAGE:
  8150. return limits.maxPerStageDescriptorSampledImages;
  8151. case LIMIT_MAX_SAMPLERS_PER_SHADER_STAGE:
  8152. return limits.maxPerStageDescriptorSamplers;
  8153. case LIMIT_MAX_STORAGE_BUFFERS_PER_SHADER_STAGE:
  8154. return limits.maxPerStageDescriptorStorageBuffers;
  8155. case LIMIT_MAX_STORAGE_IMAGES_PER_SHADER_STAGE:
  8156. return limits.maxPerStageDescriptorStorageImages;
  8157. case LIMIT_MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE:
  8158. return limits.maxPerStageDescriptorUniformBuffers;
  8159. case LIMIT_MAX_PUSH_CONSTANT_SIZE:
  8160. return limits.maxPushConstantsSize;
  8161. case LIMIT_MAX_UNIFORM_BUFFER_SIZE:
  8162. return limits.maxUniformBufferRange;
  8163. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTE_OFFSET:
  8164. return limits.maxVertexInputAttributeOffset;
  8165. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTES:
  8166. return limits.maxVertexInputAttributes;
  8167. case LIMIT_MAX_VERTEX_INPUT_BINDINGS:
  8168. return limits.maxVertexInputBindings;
  8169. case LIMIT_MAX_VERTEX_INPUT_BINDING_STRIDE:
  8170. return limits.maxVertexInputBindingStride;
  8171. case LIMIT_MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
  8172. return limits.minUniformBufferOffsetAlignment;
  8173. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X:
  8174. return limits.maxComputeWorkGroupCount[0];
  8175. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y:
  8176. return limits.maxComputeWorkGroupCount[1];
  8177. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z:
  8178. return limits.maxComputeWorkGroupCount[2];
  8179. case LIMIT_MAX_COMPUTE_WORKGROUP_INVOCATIONS:
  8180. return limits.maxComputeWorkGroupInvocations;
  8181. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X:
  8182. return limits.maxComputeWorkGroupSize[0];
  8183. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y:
  8184. return limits.maxComputeWorkGroupSize[1];
  8185. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z:
  8186. return limits.maxComputeWorkGroupSize[2];
  8187. case LIMIT_SUBGROUP_SIZE: {
  8188. VulkanContext::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities();
  8189. return subgroup_capabilities.size;
  8190. }
  8191. case LIMIT_SUBGROUP_IN_SHADERS: {
  8192. VulkanContext::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities();
  8193. return subgroup_capabilities.supported_stages_flags_rd();
  8194. }
  8195. case LIMIT_SUBGROUP_OPERATIONS: {
  8196. VulkanContext::SubgroupCapabilities subgroup_capabilities = context->get_subgroup_capabilities();
  8197. return subgroup_capabilities.supported_operations_flags_rd();
  8198. }
  8199. default:
  8200. ERR_FAIL_V(0);
  8201. }
  8202. return 0;
  8203. }
  8204. void RenderingDeviceVulkan::finalize() {
  8205. // Free all resources.
  8206. _flush(false);
  8207. _free_rids(render_pipeline_owner, "Pipeline");
  8208. _free_rids(compute_pipeline_owner, "Compute");
  8209. _free_rids(uniform_set_owner, "UniformSet");
  8210. _free_rids(texture_buffer_owner, "TextureBuffer");
  8211. _free_rids(storage_buffer_owner, "StorageBuffer");
  8212. _free_rids(uniform_buffer_owner, "UniformBuffer");
  8213. _free_rids(shader_owner, "Shader");
  8214. _free_rids(index_array_owner, "IndexArray");
  8215. _free_rids(index_buffer_owner, "IndexBuffer");
  8216. _free_rids(vertex_array_owner, "VertexArray");
  8217. _free_rids(vertex_buffer_owner, "VertexBuffer");
  8218. _free_rids(framebuffer_owner, "Framebuffer");
  8219. _free_rids(sampler_owner, "Sampler");
  8220. {
  8221. // For textures it's a bit more difficult because they may be shared.
  8222. List<RID> owned;
  8223. texture_owner.get_owned_list(&owned);
  8224. if (owned.size()) {
  8225. if (owned.size() == 1) {
  8226. WARN_PRINT("1 RID of type \"Texture\" was leaked.");
  8227. } else {
  8228. WARN_PRINT(vformat("%d RIDs of type \"Texture\" were leaked.", owned.size()));
  8229. }
  8230. // Free shared first.
  8231. for (List<RID>::Element *E = owned.front(); E;) {
  8232. List<RID>::Element *N = E->next();
  8233. if (texture_is_shared(E->get())) {
  8234. #ifdef DEV_ENABLED
  8235. if (resource_names.has(E->get())) {
  8236. print_line(String(" - ") + resource_names[E->get()]);
  8237. }
  8238. #endif
  8239. free(E->get());
  8240. owned.erase(E);
  8241. }
  8242. E = N;
  8243. }
  8244. // Free non shared second, this will avoid an error trying to free unexisting textures due to dependencies.
  8245. for (const RID &E : owned) {
  8246. #ifdef DEV_ENABLED
  8247. if (resource_names.has(E)) {
  8248. print_line(String(" - ") + resource_names[E]);
  8249. }
  8250. #endif
  8251. free(E);
  8252. }
  8253. }
  8254. }
  8255. // Free everything pending.
  8256. for (int i = 0; i < frame_count; i++) {
  8257. int f = (frame + i) % frame_count;
  8258. _free_pending_resources(f);
  8259. vkDestroyCommandPool(device, frames[i].command_pool, nullptr);
  8260. vkDestroyQueryPool(device, frames[i].timestamp_pool, nullptr);
  8261. }
  8262. for (int i = 0; i < split_draw_list_allocators.size(); i++) {
  8263. vkDestroyCommandPool(device, split_draw_list_allocators[i].command_pool, nullptr);
  8264. }
  8265. frames.clear();
  8266. for (int i = 0; i < staging_buffer_blocks.size(); i++) {
  8267. vmaDestroyBuffer(allocator, staging_buffer_blocks[i].buffer, staging_buffer_blocks[i].allocation);
  8268. }
  8269. while (small_allocs_pools.size()) {
  8270. HashMap<uint32_t, VmaPool>::Iterator E = small_allocs_pools.begin();
  8271. vmaDestroyPool(allocator, E->value);
  8272. small_allocs_pools.remove(E);
  8273. }
  8274. vmaDestroyAllocator(allocator);
  8275. while (vertex_formats.size()) {
  8276. HashMap<VertexFormatID, VertexDescriptionCache>::Iterator temp = vertex_formats.begin();
  8277. memdelete_arr(temp->value.bindings);
  8278. memdelete_arr(temp->value.attributes);
  8279. vertex_formats.remove(temp);
  8280. }
  8281. for (KeyValue<FramebufferFormatID, FramebufferFormat> &E : framebuffer_formats) {
  8282. vkDestroyRenderPass(device, E.value.render_pass, nullptr);
  8283. }
  8284. framebuffer_formats.clear();
  8285. // All these should be clear at this point.
  8286. ERR_FAIL_COND(descriptor_pools.size());
  8287. ERR_FAIL_COND(dependency_map.size());
  8288. ERR_FAIL_COND(reverse_dependency_map.size());
  8289. }
  8290. RenderingDevice *RenderingDeviceVulkan::create_local_device() {
  8291. RenderingDeviceVulkan *rd = memnew(RenderingDeviceVulkan);
  8292. rd->initialize(context, true);
  8293. return rd;
  8294. }
  8295. bool RenderingDeviceVulkan::has_feature(const Features p_feature) const {
  8296. switch (p_feature) {
  8297. case SUPPORTS_MULTIVIEW: {
  8298. VulkanContext::MultiviewCapabilities multiview_capabilies = context->get_multiview_capabilities();
  8299. return multiview_capabilies.is_supported && multiview_capabilies.max_view_count > 1;
  8300. } break;
  8301. case SUPPORTS_FSR_HALF_FLOAT: {
  8302. return context->get_shader_capabilities().shader_float16_is_supported && context->get_storage_buffer_capabilities().storage_buffer_16_bit_access_is_supported;
  8303. } break;
  8304. case SUPPORTS_ATTACHMENT_VRS: {
  8305. VulkanContext::VRSCapabilities vrs_capabilities = context->get_vrs_capabilities();
  8306. return vrs_capabilities.attachment_vrs_supported;
  8307. } break;
  8308. default: {
  8309. return false;
  8310. }
  8311. }
  8312. }
  8313. RenderingDeviceVulkan::RenderingDeviceVulkan() {
  8314. device_capabilities.device_family = DEVICE_VULKAN;
  8315. }
  8316. RenderingDeviceVulkan::~RenderingDeviceVulkan() {
  8317. if (local_device.is_valid()) {
  8318. finalize();
  8319. context->local_device_free(local_device);
  8320. }
  8321. }