rendering_device_vulkan.cpp 312 KB

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