rendering_device_vulkan.cpp 334 KB

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