rendering_device_vulkan.cpp 371 KB

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