rendering_device_vulkan.cpp 304 KB

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